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,183 @@
1
+ // @vitest-environment jsdom
2
+ /**
3
+ * The API client's session rules, against a fake transport (an axios adapter):
4
+ * one refresh for parallel 401s, a lost refresh race between tabs, a dead
5
+ * session, a network failure, limits, the start-up probe and a ban mid-session.
6
+ * Each test loads a fresh copy of the module, because the refresh state and the
7
+ * circuit breaker live at module level.
8
+ */
9
+ import { AxiosError, type AxiosAdapter, type AxiosResponse, type InternalAxiosRequestConfig } from 'axios';
10
+ import { beforeEach, describe, expect, it, vi } from 'vitest';
11
+
12
+ vi.mock('sonner', () => ({ toast: { error: vi.fn(), success: vi.fn() } }));
13
+ vi.mock('@/lib/api/hard-redirect', () => ({ hardRedirect: vi.fn() }));
14
+
15
+ type Handler = (config: InternalAxiosRequestConfig) => { status: number; body?: unknown } | 'network';
16
+
17
+ /** The server's answer for one request: 2xx resolves, anything else rejects like axios' own adapters. */
18
+ function respond(config: InternalAxiosRequestConfig, status: number, body?: unknown): Promise<AxiosResponse> {
19
+ const response: AxiosResponse = { data: body, status, statusText: '', headers: {}, config };
20
+ if (status >= 200 && status < 300) return Promise.resolve(response);
21
+ return Promise.reject(new AxiosError(`Request failed with status code ${status}`, 'ERR_BAD_REQUEST', config, undefined, response));
22
+ }
23
+
24
+ const fail = (code: string, extra: Record<string, unknown> = {}): unknown => ({ success: false, error: { code, message: code, ...extra } });
25
+
26
+ async function load(handler: Handler) {
27
+ vi.resetModules();
28
+ const { apiClient } = await import('../axios.config');
29
+ const events = await import('../session-events');
30
+ const { hardRedirect } = await import('@/lib/api/hard-redirect');
31
+ const { toast } = await import('sonner');
32
+ const calls: string[] = [];
33
+ const adapter: AxiosAdapter = async (config) => {
34
+ calls.push(`${config.method?.toUpperCase()} ${config.url}`);
35
+ await new Promise((r) => setTimeout(r, 5)); // let parallel requests overlap
36
+ const answer = handler(config);
37
+ if (answer === 'network') throw new AxiosError('Network Error', 'ERR_NETWORK', config);
38
+ return respond(config, answer.status, answer.body);
39
+ };
40
+ apiClient.defaults.adapter = adapter;
41
+ const ended: string[] = [];
42
+ events.onSessionEnded((reason) => ended.push(reason));
43
+ return { apiClient, calls, ended, hardRedirect: vi.mocked(hardRedirect), toastError: vi.mocked(toast.error) };
44
+ }
45
+
46
+ const count = (calls: string[], call: string): number => calls.filter((c) => c === call).length;
47
+
48
+ beforeEach(() => {
49
+ // Module mocks survive vi.resetModules(): forget the previous test's calls.
50
+ vi.clearAllMocks();
51
+ document.cookie = 'auth_session=1; path=/';
52
+ });
53
+
54
+ describe('expired access token', () => {
55
+ it('parallel 401s share ONE refresh, then every request is replayed', async () => {
56
+ let refreshed = false;
57
+ const t = await load((c) => {
58
+ if (c.url === '/auth/refresh') { refreshed = true; return { status: 200 }; }
59
+ return refreshed ? { status: 200, body: { ok: c.url } } : { status: 401, body: fail('UNAUTHORIZED') };
60
+ });
61
+ const [a, b] = await Promise.all([t.apiClient.get('/a'), t.apiClient.get('/b')]);
62
+ expect([a.data, b.data]).toEqual([{ ok: '/a' }, { ok: '/b' }]);
63
+ expect(count(t.calls, 'POST /auth/refresh')).toBe(1);
64
+ expect(t.ended).toEqual([]);
65
+ });
66
+
67
+ it('a lost refresh race (another tab won) replays the request and keeps the session', async () => {
68
+ let refreshAttempted = false;
69
+ const t = await load((c) => {
70
+ if (c.url === '/auth/refresh') { refreshAttempted = true; return { status: 401, body: fail('REFRESH_TOKEN_ROTATED') }; }
71
+ // The winner's fresh cookies are already in the browser: the replay works.
72
+ return refreshAttempted ? { status: 200, body: 'fresh' } : { status: 401, body: fail('UNAUTHORIZED') };
73
+ });
74
+ const r = await t.apiClient.get('/sessions');
75
+ expect(r.data).toBe('fresh');
76
+ expect(t.ended).toEqual([]);
77
+ expect(t.hardRedirect).not.toHaveBeenCalled();
78
+ expect(document.cookie).toContain('auth_session=1');
79
+ });
80
+
81
+ it('a lost race also releases the requests queued behind it', async () => {
82
+ let refreshAttempted = false;
83
+ const t = await load((c) => {
84
+ if (c.url === '/auth/refresh') { refreshAttempted = true; return { status: 401, body: fail('REFRESH_TOKEN_ROTATED') }; }
85
+ return refreshAttempted ? { status: 200, body: c.url } : { status: 401, body: fail('UNAUTHORIZED') };
86
+ });
87
+ const results = await Promise.all([t.apiClient.get('/a'), t.apiClient.get('/b')]);
88
+ expect(results.map((r) => r.data)).toEqual(['/a', '/b']);
89
+ expect(count(t.calls, 'POST /auth/refresh')).toBe(1);
90
+ });
91
+
92
+ it('a replay that still gets 401 after a lost race is rejected, not looped', async () => {
93
+ const t = await load((c) =>
94
+ c.url === '/auth/refresh' ? { status: 401, body: fail('REFRESH_TOKEN_ROTATED') } : { status: 401, body: fail('UNAUTHORIZED') },
95
+ );
96
+ await expect(t.apiClient.get('/a')).rejects.toMatchObject({ response: { status: 401 } });
97
+ expect(count(t.calls, 'POST /auth/refresh')).toBe(1);
98
+ expect(count(t.calls, 'GET /a')).toBe(2);
99
+ });
100
+ });
101
+
102
+ describe('a dead session', () => {
103
+ it('a refused refresh signs out, clears the marker and goes to sign-in', async () => {
104
+ const t = await load((c) =>
105
+ c.url === '/auth/refresh' ? { status: 401, body: fail('INVALID_REFRESH_TOKEN') } : { status: 401, body: fail('UNAUTHORIZED') },
106
+ );
107
+ await expect(t.apiClient.get('/sessions')).rejects.toBeTruthy();
108
+ expect(t.ended).toEqual(['expired']);
109
+ expect(t.hardRedirect).toHaveBeenCalledWith('/login');
110
+ expect(document.cookie).not.toContain('auth_session=1');
111
+ });
112
+
113
+ it('after that, further 401s are rejected without another refresh (circuit breaker)', async () => {
114
+ const t = await load((c) =>
115
+ c.url === '/auth/refresh' ? { status: 401, body: fail('INVALID_REFRESH_TOKEN') } : { status: 401, body: fail('UNAUTHORIZED') },
116
+ );
117
+ await expect(t.apiClient.get('/a')).rejects.toBeTruthy();
118
+ await expect(t.apiClient.get('/b')).rejects.toBeTruthy();
119
+ expect(count(t.calls, 'POST /auth/refresh')).toBe(1);
120
+ });
121
+
122
+ it('a refresh that never reached the server keeps the session', async () => {
123
+ const t = await load((c) => (c.url === '/auth/refresh' ? 'network' : { status: 401, body: fail('UNAUTHORIZED') }));
124
+ await expect(t.apiClient.get('/a')).rejects.toMatchObject({ code: 'ERR_NETWORK' });
125
+ expect(t.ended).toEqual([]);
126
+ expect(t.hardRedirect).not.toHaveBeenCalled();
127
+ });
128
+
129
+ it('the start-up probe finding no session signs out quietly, without leaving the page', async () => {
130
+ const t = await load((c) =>
131
+ c.url === '/auth/refresh' ? { status: 401, body: fail('MISSING_REFRESH_TOKEN') } : { status: 401, body: fail('UNAUTHORIZED') },
132
+ );
133
+ await expect(t.apiClient.get('/auth/me')).rejects.toBeTruthy();
134
+ expect(t.ended).toEqual(['signed-out']);
135
+ expect(t.hardRedirect).not.toHaveBeenCalled();
136
+ });
137
+ });
138
+
139
+ describe('slow down answers', () => {
140
+ it('a 429 shows one toast with the wait and never starts a refresh', async () => {
141
+ const t = await load(() => ({ status: 429, body: fail('RATE_LIMIT_EXCEEDED', { retryAfterSeconds: 60 }) }));
142
+ await expect(t.apiClient.get('/a')).rejects.toBeTruthy();
143
+ expect(t.toastError).toHaveBeenCalledWith('Too many requests. Try again in 1 minute.', { id: 'rate-limit' });
144
+ expect(count(t.calls, 'POST /auth/refresh')).toBe(0);
145
+ });
146
+
147
+ it('skipLimitToast leaves the message to the caller', async () => {
148
+ const t = await load(() => ({ status: 429, body: fail('LOGIN_LOCKED', { retryAfterSeconds: 60 }) }));
149
+ await expect(t.apiClient.post('/auth/login', {}, { skipLimitToast: true })).rejects.toBeTruthy();
150
+ expect(t.toastError).not.toHaveBeenCalled();
151
+ });
152
+ });
153
+
154
+ describe('banned while signed in (403 ACCOUNT_DEACTIVATED)', () => {
155
+ it('ends the session through the logout route ONCE for a burst of calls, then reports it', async () => {
156
+ const t = await load((c) => (c.url === '/auth/logout' ? { status: 200 } : { status: 403, body: fail('ACCOUNT_DEACTIVATED') }));
157
+ const results = await Promise.allSettled([t.apiClient.get('/a'), t.apiClient.get('/b')]);
158
+ expect(results.map((r) => r.status)).toEqual(['rejected', 'rejected']);
159
+ expect(count(t.calls, 'POST /auth/logout')).toBe(1);
160
+ expect(t.ended).toEqual(['deactivated']);
161
+ expect(t.hardRedirect).not.toHaveBeenCalled();
162
+ });
163
+
164
+ it('still signs out locally when the logout call itself fails', async () => {
165
+ const t = await load((c) => (c.url === '/auth/logout' ? 'network' : { status: 403, body: fail('ACCOUNT_DEACTIVATED') }));
166
+ await expect(t.apiClient.get('/a')).rejects.toBeTruthy();
167
+ expect(t.ended).toEqual(['deactivated']);
168
+ });
169
+
170
+ it('a banned account trying to sign in is left to the form (no logout call, no event)', async () => {
171
+ const t = await load(() => ({ status: 403, body: fail('ACCOUNT_DEACTIVATED') }));
172
+ await expect(t.apiClient.post('/auth/login', {})).rejects.toBeTruthy();
173
+ expect(count(t.calls, 'POST /auth/logout')).toBe(0);
174
+ expect(t.ended).toEqual([]);
175
+ });
176
+
177
+ it('another 403 (a missing role) does not end the session', async () => {
178
+ const t = await load(() => ({ status: 403, body: fail('FORBIDDEN') }));
179
+ await expect(t.apiClient.get('/admin/stats')).rejects.toBeTruthy();
180
+ expect(t.ended).toEqual([]);
181
+ expect(count(t.calls, 'POST /auth/logout')).toBe(0);
182
+ });
183
+ });
@@ -20,11 +20,25 @@ export interface PaginatedApiResponse<T> {
20
20
  };
21
21
  }
22
22
 
23
+ /** One wrong input field in a 422 VALIDATION_FAILED answer (never the submitted value). */
24
+ export interface ApiFieldError {
25
+ /** Dot path inside the request part ("email", "address.city"), or the part itself ("body"). */
26
+ field: string;
27
+ message: string;
28
+ }
29
+
23
30
  export interface ApiError {
24
31
  success: false;
25
32
  error: {
26
33
  code: string;
27
34
  message: string;
35
+ /**
36
+ * Whole seconds until a retry can work. Sent on rate limits (429) and an
37
+ * automatic IP block (403 IP_BLOCKED); see getLimitInfo in lib/utils/error.ts.
38
+ */
39
+ retryAfterSeconds?: number;
40
+ /** Sent on 422 VALIDATION_FAILED: every wrong field and why; see getFieldErrors. */
41
+ fields?: ApiFieldError[];
28
42
  };
29
43
  }
30
44
 
@@ -1,10 +1,27 @@
1
1
  import axios from 'axios';
2
+ import { toast } from 'sonner';
2
3
 
3
4
  import type { InternalAxiosRequestConfig } from 'axios';
4
5
 
6
+ import { hardRedirect } from '@/lib/api/hard-redirect';
7
+ import { emitSessionEnded } from '@/lib/api/session-events';
5
8
  import { API_ENDPOINTS } from '@/lib/constants/api-endpoints';
6
9
  import { ROUTES } from '@/lib/constants/routes';
7
10
  import { env } from '@/lib/env';
11
+ import { ERROR_CODES, getLimitInfo, isErrorCode, isLimitError } from '@/lib/utils/error';
12
+
13
+ declare module 'axios' {
14
+ interface AxiosRequestConfig {
15
+ /**
16
+ * Skip the global "too many requests" toast for this request because the
17
+ * caller shows the message itself (the auth forms show it inline).
18
+ */
19
+ skipLimitToast?: boolean;
20
+ }
21
+ }
22
+
23
+ // One fixed toast id: a burst of limited requests updates one toast instead of stacking many.
24
+ const LIMIT_TOAST_ID = 'rate-limit';
8
25
 
9
26
  const apiClient = axios.create({
10
27
  baseURL: env.NEXT_PUBLIC_API_BASE_URL,
@@ -43,11 +60,71 @@ const resetRefreshState = (): void => {
43
60
  refreshTimestamp = 0;
44
61
  };
45
62
 
63
+ // Calls that do not carry a session, so their 401 or 403 says nothing about one:
64
+ // a 401 there is wrong credentials or a bad token, and sign-in answers a banned
65
+ // account with 403 ACCOUNT_DEACTIVATED (the forms show that). Logout is here so
66
+ // ending a session never re-enters the session rules below.
67
+ const SESSIONLESS_ENDPOINTS: string[] = [
68
+ API_ENDPOINTS.AUTH.LOGIN,
69
+ API_ENDPOINTS.AUTH.REGISTER,
70
+ API_ENDPOINTS.AUTH.REFRESH,
71
+ API_ENDPOINTS.AUTH.RESET_PASSWORD,
72
+ API_ENDPOINTS.AUTH.LOGOUT,
73
+ ];
74
+
75
+ // One logout for a burst of calls that all found the account banned.
76
+ let endingDeactivatedSession: Promise<void> | null = null;
77
+
78
+ /**
79
+ * The account was banned while signed in: every authenticated call now answers
80
+ * 403 ACCOUNT_DEACTIVATED, and so would a refresh. End the session the way a
81
+ * logout does (the server clears the cookies, auth_session with its cookie
82
+ * domain included), then tell the app, which clears the user and says why.
83
+ * Best effort: the user is signed out locally even if the logout call fails.
84
+ */
85
+ const endDeactivatedSession = (): Promise<void> => {
86
+ endingDeactivatedSession ??= apiClient
87
+ .post(API_ENDPOINTS.AUTH.LOGOUT)
88
+ .then(
89
+ () => undefined,
90
+ () => undefined
91
+ )
92
+ .then(() => {
93
+ emitSessionEnded('deactivated');
94
+ })
95
+ .finally(() => {
96
+ endingDeactivatedSession = null;
97
+ });
98
+ return endingDeactivatedSession;
99
+ };
100
+
46
101
  apiClient.interceptors.response.use(
47
102
  (response) => response,
48
103
  async (error) => {
49
104
  const originalRequest = error.config as InternalAxiosRequestConfig & { _retry?: boolean };
50
105
 
106
+ // "Slow down" answers (429 rate limit / login lock / email cap, 403 IP_BLOCKED):
107
+ // tell the person once, with the wait time, and never treat them as an auth
108
+ // failure. They are rejected as-is; React Query does not retry them (providers.tsx).
109
+ const limit = getLimitInfo(error);
110
+ if (limit) {
111
+ if (!originalRequest?.skipLimitToast && typeof window !== 'undefined') {
112
+ toast.error(limit.message, { id: LIMIT_TOAST_ID });
113
+ }
114
+ return Promise.reject(error);
115
+ }
116
+
117
+ const isSessionless = SESSIONLESS_ENDPOINTS.includes(originalRequest?.url ?? '');
118
+
119
+ if (
120
+ error.response?.status === 403 &&
121
+ isErrorCode(error, ERROR_CODES.ACCOUNT_DEACTIVATED) &&
122
+ !isSessionless
123
+ ) {
124
+ await endDeactivatedSession();
125
+ return Promise.reject(error);
126
+ }
127
+
51
128
  if (error.response?.status !== 401 || originalRequest._retry) {
52
129
  return Promise.reject(error);
53
130
  }
@@ -60,13 +137,7 @@ apiClient.interceptors.response.use(
60
137
 
61
138
  // Don't retry auth endpoints that don't use tokens —
62
139
  // a 401 here means wrong credentials, not an expired token.
63
- const noRetryEndpoints: string[] = [
64
- API_ENDPOINTS.AUTH.LOGIN,
65
- API_ENDPOINTS.AUTH.REGISTER,
66
- API_ENDPOINTS.AUTH.REFRESH,
67
- API_ENDPOINTS.AUTH.RESET_PASSWORD,
68
- ];
69
- if (noRetryEndpoints.includes(originalRequest.url ?? '')) {
140
+ if (isSessionless) {
70
141
  return Promise.reject(error);
71
142
  }
72
143
 
@@ -97,15 +168,29 @@ apiClient.interceptors.response.use(
97
168
  // Retry original request — new cookie is set automatically
98
169
  return apiClient(originalRequest);
99
170
  } catch (refreshError) {
171
+ // Lost a race with another tab: both refreshed at once with the same
172
+ // token, the other one won, and the server kept the cookies, so this
173
+ // browser already holds the winner's fresh ones (401
174
+ // REFRESH_TOKEN_ROTATED, server auth.controller.ts). Not a dead session:
175
+ // release the queue and replay the request once with the new cookies.
176
+ // `_retry` is already set, so a second 401 is rejected, never looped.
177
+ if (isErrorCode(refreshError, ERROR_CODES.REFRESH_TOKEN_ROTATED)) {
178
+ processQueue(null);
179
+ return apiClient(originalRequest);
180
+ }
181
+
100
182
  processQueue(refreshError);
101
183
 
102
184
  // Only logout on definitive auth failures (server responded with 4xx).
103
- // Network errors (server unreachable, timeout) should NOT destroy the session.
185
+ // Network errors (server unreachable, timeout) should NOT destroy the session,
186
+ // and neither should a rate-limited or blocked refresh: the session is still
187
+ // valid, the caller just has to wait (the toast says how long).
104
188
  const isAuthFailure =
105
189
  axios.isAxiosError(refreshError) &&
106
190
  refreshError.response != null &&
107
191
  refreshError.response.status >= 400 &&
108
- refreshError.response.status < 500;
192
+ refreshError.response.status < 500 &&
193
+ !isLimitError(refreshError);
109
194
 
110
195
  if (isAuthFailure) {
111
196
  // The bootstrap probe (AuthInitializer's getMe) runs on EVERY page,
@@ -127,15 +212,16 @@ apiClient.interceptors.response.use(
127
212
  isSessionDead = true;
128
213
  }
129
214
 
130
- const { logout } = await import('@/features/auth/store/authSlice');
131
- const { store } = await import('@/store');
132
- store.dispatch(logout());
215
+ // AuthInitializer clears the signed-in user on this event.
216
+ emitSessionEnded(isBootstrapProbe ? 'signed-out' : 'expired');
133
217
 
134
218
  if (!isBootstrapProbe && typeof window !== 'undefined') {
135
- // Clear session indicator so middleware won't let user through
136
- // to protected pages — prevents redirect loops
219
+ // Clear the session marker so the proxy won't let the user through to
220
+ // protected pages (prevents redirect loops). The server already
221
+ // cleared it, with its cookie domain, when it refused the refresh;
222
+ // this covers a host-only marker too.
137
223
  document.cookie = 'auth_session=; Max-Age=0; path=/; SameSite=Strict';
138
- window.location.href = ROUTES.LOGIN;
224
+ hardRedirect(ROUTES.LOGIN);
139
225
  }
140
226
  }
141
227
 
@@ -0,0 +1,8 @@
1
+ /**
2
+ * A full page load to `path`, used when the session is dead: it drops every
3
+ * in-memory state (React Query cache, the API client's refresh state) at once.
4
+ * Its own module so tests can replace it (jsdom cannot navigate).
5
+ */
6
+ export function hardRedirect(path: string): void {
7
+ window.location.href = path;
8
+ }
@@ -0,0 +1,29 @@
1
+ /**
2
+ * How the API client tells the app that the session ended. The client never
3
+ * imports the Redux store (each visitor gets their own store, see
4
+ * store/index.ts); AuthInitializer listens here and clears the signed-in user.
5
+ *
6
+ * Reasons:
7
+ * - 'expired': a real call found the session dead (the refresh was refused).
8
+ * The API client also sends the browser to the sign-in page.
9
+ * - 'signed-out': the start-up "who am I" check found no live session.
10
+ * - 'deactivated': the account was banned while signed in (403
11
+ * ACCOUNT_DEACTIVATED); the cookies were cleared through the logout route.
12
+ */
13
+ export type SessionEndReason = 'expired' | 'signed-out' | 'deactivated';
14
+
15
+ type Listener = (reason: SessionEndReason) => void;
16
+
17
+ const listeners = new Set<Listener>();
18
+
19
+ /** Subscribe; returns the unsubscribe function (fits a useEffect cleanup). */
20
+ export function onSessionEnded(listener: Listener): () => void {
21
+ listeners.add(listener);
22
+ return () => {
23
+ listeners.delete(listener);
24
+ };
25
+ }
26
+
27
+ export function emitSessionEnded(reason: SessionEndReason): void {
28
+ for (const listener of [...listeners]) listener(reason);
29
+ }
@@ -13,3 +13,15 @@ export const ROUTES = {
13
13
  SESSIONS: '/admin/sessions',
14
14
  },
15
15
  } as const;
16
+
17
+ /**
18
+ * Pages only a signed-in visitor may open, each with everything under it
19
+ * (/admin also covers /admin/users, never /administrator; lib/utils/paths.ts).
20
+ * The proxy sends a visitor with no session marker to sign-in, and
21
+ * AuthInitializer does the same when the session turns out to be dead. The
22
+ * template ships no pages: add your own protected areas here.
23
+ */
24
+ export const PROTECTED_PATHS: readonly string[] = [ROUTES.DASHBOARD, ROUTES.PROFILE, ROUTES.ADMIN.DASHBOARD];
25
+
26
+ /** The sign-in pages, where the start-up "who am I" check never runs (no session to read there yet). */
27
+ export const AUTH_PATHS: readonly string[] = [ROUTES.LOGIN, ROUTES.REGISTER, ROUTES.RESET_PASSWORD, ROUTES.VERIFY_ACCOUNT];
@@ -0,0 +1,71 @@
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.
15
+ */
16
+ import type { Event } from '@sentry/nextjs';
17
+
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);
25
+ }
26
+
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
+ */
31
+ function scrubData(data: Record<string, unknown> | undefined): void {
32
+ if (!data) return;
33
+ for (const key of Object.keys(data)) {
34
+ const lower = key.toLowerCase();
35
+ if (lower.includes('query') || lower.includes('cookie') || lower.includes('authorization')) {
36
+ 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
+ }
46
+ }
47
+ }
48
+
49
+ export function scrubSentryEvent<T extends Event>(event: T): T {
50
+ const request = event.request;
51
+ if (request) {
52
+ delete request.data;
53
+ delete request.cookies;
54
+ delete request.query_string;
55
+ if (request.url) request.url = withoutQuery(request.url);
56
+ 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]);
61
+ }
62
+ }
63
+ }
64
+
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
+
70
+ return event;
71
+ }
@@ -0,0 +1,119 @@
1
+ import { AxiosError, AxiosHeaders } from 'axios';
2
+ import { describe, expect, it } from 'vitest';
3
+
4
+ import {
5
+ formatWait,
6
+ getErrorCode,
7
+ getErrorMessage,
8
+ getFieldErrors,
9
+ getLimitInfo,
10
+ isLimitError,
11
+ } from '../error';
12
+
13
+ /** An axios error carrying the server's answer, as the API client sees it. */
14
+ function apiError(status: number, error?: Record<string, unknown>): AxiosError {
15
+ const config = { headers: new AxiosHeaders() };
16
+ return new AxiosError('Request failed', 'ERR_BAD_REQUEST', config, undefined, {
17
+ status,
18
+ statusText: '',
19
+ headers: {},
20
+ config,
21
+ data: error ? { success: false, error } : undefined,
22
+ });
23
+ }
24
+
25
+ describe('getLimitInfo ("slow down" answers)', () => {
26
+ it('a bare 429 is a rate limit with a generic wait', () => {
27
+ expect(getLimitInfo(apiError(429))).toEqual({
28
+ code: 'RATE_LIMIT_EXCEEDED',
29
+ retryAfterSeconds: undefined,
30
+ message: 'Too many requests. Please wait a moment and try again.',
31
+ });
32
+ });
33
+
34
+ it('uses the server wait, rounded up to whole minutes', () => {
35
+ const info = getLimitInfo(apiError(429, { code: 'RATE_LIMIT_EXCEEDED', message: 'x', retryAfterSeconds: 90 }));
36
+ expect(info?.message).toBe('Too many requests. Try again in 2 minutes.');
37
+ });
38
+
39
+ it('a login lock and the email cap have their own wording', () => {
40
+ expect(getLimitInfo(apiError(429, { code: 'LOGIN_LOCKED', message: 'x', retryAfterSeconds: 900 }))?.message).toBe(
41
+ 'Too many failed sign-in attempts. Try again in 15 minutes.',
42
+ );
43
+ expect(getLimitInfo(apiError(429, { code: 'EMAIL_RATE_LIMITED', message: 'x', retryAfterSeconds: 30 }))?.message).toBe(
44
+ 'Too many emails were sent to this address. Try again in 30 seconds.',
45
+ );
46
+ });
47
+
48
+ it('an IP block says how long when it is automatic, and that it is blocked otherwise', () => {
49
+ expect(getLimitInfo(apiError(403, { code: 'IP_BLOCKED', message: 'x', retryAfterSeconds: 120 }))?.message).toBe(
50
+ 'Too many requests from your network. Try again in 2 minutes.',
51
+ );
52
+ expect(getLimitInfo(apiError(403, { code: 'IP_BLOCKED', message: 'x' }))?.message).toBe(
53
+ 'Access from your network is blocked.',
54
+ );
55
+ });
56
+
57
+ it('anything else is not a limit', () => {
58
+ expect(getLimitInfo(apiError(401, { code: 'UNAUTHORIZED', message: 'x' }))).toBeNull();
59
+ expect(getLimitInfo(apiError(403, { code: 'ACCOUNT_DEACTIVATED', message: 'x' }))).toBeNull();
60
+ expect(getLimitInfo(new Error('boom'))).toBeNull();
61
+ expect(isLimitError(apiError(500))).toBe(false);
62
+ expect(isLimitError(apiError(429))).toBe(true);
63
+ });
64
+ });
65
+
66
+ describe('formatWait', () => {
67
+ it.each([
68
+ [0, '1 second'],
69
+ [1, '1 second'],
70
+ [45, '45 seconds'],
71
+ [59.2, '1 minute'],
72
+ [60, '1 minute'],
73
+ [61, '2 minutes'],
74
+ ])('%s s -> %s', (seconds, text) => {
75
+ expect(formatWait(seconds)).toBe(text);
76
+ });
77
+ });
78
+
79
+ describe('getFieldErrors (422 VALIDATION_FAILED)', () => {
80
+ it('maps each field to its first message', () => {
81
+ const error = apiError(422, {
82
+ code: 'VALIDATION_FAILED',
83
+ message: 'Please check these fields: firstName, email',
84
+ fields: [
85
+ { field: 'firstName', message: 'First name must be at least 2 characters' },
86
+ { field: 'firstName', message: 'second message is ignored' },
87
+ { field: 'email', message: 'Invalid email address' },
88
+ ],
89
+ });
90
+ expect(getFieldErrors(error)).toEqual({
91
+ firstName: 'First name must be at least 2 characters',
92
+ email: 'Invalid email address',
93
+ });
94
+ });
95
+
96
+ it('is empty for any other error', () => {
97
+ expect(getFieldErrors(apiError(400, { code: 'BAD_REQUEST', message: 'x', fields: [{ field: 'a', message: 'b' }] }))).toEqual({});
98
+ expect(getFieldErrors(new Error('x'))).toEqual({});
99
+ });
100
+
101
+ it('field names become plain own keys, never prototype setters', () => {
102
+ const out = getFieldErrors(
103
+ apiError(422, { code: 'VALIDATION_FAILED', message: 'x', fields: [{ field: '__proto__', message: 'm' }] }),
104
+ );
105
+ expect(Object.prototype.hasOwnProperty.call(out, '__proto__')).toBe(true);
106
+ expect(({} as Record<string, unknown>).m).toBeUndefined();
107
+ });
108
+ });
109
+
110
+ describe('getErrorMessage and getErrorCode', () => {
111
+ it('prefers the server message, then a network hint, then the error message', () => {
112
+ expect(getErrorMessage(apiError(400, { code: 'X', message: 'Server says no' }))).toBe('Server says no');
113
+ expect(getErrorMessage(new AxiosError('Network Error', 'ERR_NETWORK'))).toBe('Network error. Check your connection.');
114
+ expect(getErrorMessage(new Error('plain'))).toBe('plain');
115
+ expect(getErrorMessage('?')).toBe('An unexpected error occurred');
116
+ expect(getErrorCode(apiError(403, { code: 'ACCOUNT_DEACTIVATED', message: 'x' }))).toBe('ACCOUNT_DEACTIVATED');
117
+ expect(getErrorCode(new Error('x'))).toBeUndefined();
118
+ });
119
+ });
@@ -0,0 +1,42 @@
1
+ import { AxiosError, AxiosHeaders } from 'axios';
2
+ import { describe, expect, it, vi } from 'vitest';
3
+
4
+ import { applyFieldErrors } from '../form';
5
+
6
+ function validationFailed(fields: { field: string; message: string }[]): AxiosError {
7
+ const config = { headers: new AxiosHeaders() };
8
+ return new AxiosError('Request failed', 'ERR_BAD_REQUEST', config, undefined, {
9
+ status: 422,
10
+ statusText: '',
11
+ headers: {},
12
+ config,
13
+ data: { success: false, error: { code: 'VALIDATION_FAILED', message: 'Please check these fields', fields } },
14
+ });
15
+ }
16
+
17
+ type Form = { firstName: string; email: string };
18
+
19
+ describe('applyFieldErrors', () => {
20
+ it("puts each server message on the form's own field", () => {
21
+ const setError = vi.fn();
22
+ const applied = applyFieldErrors<Form>(
23
+ validationFailed([
24
+ { field: 'firstName', message: 'First name must be at least 2 characters' },
25
+ { field: 'body', message: 'not a form field' },
26
+ ]),
27
+ setError,
28
+ ['firstName', 'email'],
29
+ );
30
+ expect(applied).toBe(true);
31
+ expect(setError).toHaveBeenCalledTimes(1);
32
+ expect(setError).toHaveBeenCalledWith('firstName', { type: 'server', message: 'First name must be at least 2 characters' });
33
+ });
34
+
35
+ it('sets nothing for fields the form does not have, or for any other error', () => {
36
+ const setError = vi.fn();
37
+ expect(applyFieldErrors<Form>(validationFailed([{ field: 'body', message: 'x' }]), setError, ['firstName'])).toBe(false);
38
+ expect(applyFieldErrors<Form>(new Error('boom'), setError, ['firstName'])).toBe(false);
39
+ expect(applyFieldErrors<Form>(null, setError, ['firstName'])).toBe(false);
40
+ expect(setError).not.toHaveBeenCalled();
41
+ });
42
+ });