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,43 @@
1
+ import { describe, expect, it } from 'vitest';
2
+
3
+ import { isAuthPath, isProtectedPath, isUnderPath } from '../paths';
4
+
5
+ describe('isUnderPath (whole path segments)', () => {
6
+ it.each([
7
+ ['/admin', '/admin', true],
8
+ ['/admin/users', '/admin', true],
9
+ ['/admin/users/1', '/admin', true],
10
+ ['/administrator', '/admin', false],
11
+ ['/admin-old', '/admin', false],
12
+ ['/', '/admin', false],
13
+ ['/anything', '/', true],
14
+ ])('%s under %s -> %s', (pathname, base, expected) => {
15
+ expect(isUnderPath(pathname, base)).toBe(expected);
16
+ });
17
+ });
18
+
19
+ describe('the shipped lists', () => {
20
+ it.each([
21
+ ['/dashboard', true],
22
+ ['/dashboard/settings', true],
23
+ ['/profile', true],
24
+ ['/admin/sessions', true],
25
+ ['/profile-public', false],
26
+ ['/dashboards', false],
27
+ ['/', false],
28
+ ['/login', false],
29
+ ])('protected %s -> %s', (pathname, expected) => {
30
+ expect(isProtectedPath(pathname)).toBe(expected);
31
+ });
32
+
33
+ it.each([
34
+ ['/login', true],
35
+ ['/register', true],
36
+ ['/reset-password', true],
37
+ ['/verify-account', true],
38
+ ['/login-help', false],
39
+ ['/dashboard', false],
40
+ ])('sign-in page %s -> %s', (pathname, expected) => {
41
+ expect(isAuthPath(pathname)).toBe(expected);
42
+ });
43
+ });
@@ -0,0 +1,40 @@
1
+ import { describe, expect, it } from 'vitest';
2
+
3
+ import { getSafeRedirectPath, isSafeUrl } from '../security';
4
+
5
+ describe('getSafeRedirectPath (the ?from= value after sign-in)', () => {
6
+ it.each([
7
+ ['/dashboard', '/dashboard'],
8
+ ['/admin/users?page=2#top', '/admin/users?page=2#top'],
9
+ ['/a/../b', '/b'],
10
+ ])('keeps a same-site path: %s', (input, expected) => {
11
+ expect(getSafeRedirectPath(input)).toBe(expected);
12
+ });
13
+
14
+ it.each([
15
+ ['nothing', undefined],
16
+ ['empty', ''],
17
+ ['no leading slash', 'dashboard'],
18
+ ['protocol-relative', '//evil.com'],
19
+ ['absolute URL', 'https://evil.com/x'],
20
+ ['backslash (browsers read it as a slash)', '/\\evil.com'],
21
+ // Caught only by the character rule: the URL parse alone would quietly turn it into /foo/bar.
22
+ ['backslash inside a path', '/foo\\bar'],
23
+ ['tab inside', '/\t/evil.com'],
24
+ ['newline inside', '/\n/evil.com'],
25
+ ['dot segments that resolve to //', '/..//evil.com'],
26
+ ['encoded dot segments', '/%2e%2e//evil.com'],
27
+ ])('refuses %s', (_name, input) => {
28
+ expect(getSafeRedirectPath(input as string | undefined)).toBeUndefined();
29
+ });
30
+ });
31
+
32
+ describe('isSafeUrl', () => {
33
+ it.each(['https://example.com', 'http://example.com/a', 'mailto:a@example.com'])('allows %s', (url) => {
34
+ expect(isSafeUrl(url)).toBe(true);
35
+ });
36
+
37
+ it.each(['javascript:alert(1)', 'data:text/html,<b>x</b>', 'not a url', 'vbscript:x'])('refuses %s', (url) => {
38
+ expect(isSafeUrl(url)).toBe(false);
39
+ });
40
+ });
@@ -0,0 +1,27 @@
1
+ // @vitest-environment jsdom
2
+ import { afterEach, describe, expect, it } from 'vitest';
3
+
4
+ import { hasSessionMarker } from '../session-marker';
5
+
6
+ describe('hasSessionMarker', () => {
7
+ afterEach(() => {
8
+ document.cookie = 'auth_session=; Max-Age=0; path=/';
9
+ });
10
+
11
+ it.each([
12
+ ['auth_session=1', true],
13
+ ['theme=dark; auth_session=1; other=x', true],
14
+ ['auth_session=', false],
15
+ ['xauth_session=1', false],
16
+ ['auth_session_old=1', false],
17
+ ['', false],
18
+ ])('%j -> %s', (cookies, expected) => {
19
+ expect(hasSessionMarker(cookies)).toBe(expected);
20
+ });
21
+
22
+ it("reads this browser's cookies by default", () => {
23
+ expect(hasSessionMarker()).toBe(false);
24
+ document.cookie = 'auth_session=1; path=/';
25
+ expect(hasSessionMarker()).toBe(true);
26
+ });
27
+ });
@@ -31,6 +31,91 @@ export const isErrorCode = (error: unknown, code: string): boolean => {
31
31
  return getErrorCode(error) === code;
32
32
  };
33
33
 
34
+ // Account-state codes from the server (src/libs/account-status.ts). They are
35
+ // separate on purpose: a deactivated (banned) account must never be steered to
36
+ // email verification, because verifying cannot lift a ban.
37
+ // RATE_LIMIT_EXCEEDED to IP_BLOCKED are the "wait and retry" answers (server
38
+ // docs/rate-limits.md). VALIDATION_FAILED is wrong input (see getFieldErrors).
39
+ // REFRESH_TOKEN_ROTATED: this tab lost a refresh race with another tab, which
40
+ // already set fresh cookies; not a dead session (lib/api/axios.config.ts).
41
+ // Keep this an object literal: the email-verification patcher appends to it.
34
42
  export const ERROR_CODES = {
35
- ACCOUNT_NOT_ACTIVE: 'ACCOUNT_NOT_ACTIVE',
43
+ ACCOUNT_DEACTIVATED: 'ACCOUNT_DEACTIVATED',
44
+ EMAIL_NOT_VERIFIED: 'EMAIL_NOT_VERIFIED',
45
+ REFRESH_TOKEN_ROTATED: 'REFRESH_TOKEN_ROTATED',
46
+ RATE_LIMIT_EXCEEDED: 'RATE_LIMIT_EXCEEDED',
47
+ LOGIN_LOCKED: 'LOGIN_LOCKED',
48
+ EMAIL_RATE_LIMITED: 'EMAIL_RATE_LIMITED',
49
+ IP_BLOCKED: 'IP_BLOCKED',
50
+ VALIDATION_FAILED: 'VALIDATION_FAILED',
36
51
  } as const;
52
+
53
+ /**
54
+ * The server's verdict per field on a 422 VALIDATION_FAILED answer, as
55
+ * { email: 'Invalid email address', ... } (first message per field). Empty for
56
+ * any other error. Forms can pass these to react-hook-form's setError; the
57
+ * error's message already names the fields for a toast.
58
+ */
59
+ export const getFieldErrors = (error: unknown): Record<string, string> => {
60
+ if (!axios.isAxiosError(error)) return {};
61
+ const data = error.response?.data as ApiError | undefined;
62
+ if (data?.error?.code !== ERROR_CODES.VALIDATION_FAILED) return {};
63
+ // A Map, then fromEntries: field names become own keys only, whatever they are.
64
+ const firsts = new Map<string, string>();
65
+ for (const { field, message } of data.error.fields ?? []) {
66
+ if (!firsts.has(field)) firsts.set(field, message);
67
+ }
68
+ return Object.fromEntries(firsts);
69
+ };
70
+
71
+ /** "45 seconds", "1 minute", "15 minutes": minutes round up, so nobody retries too early. */
72
+ export const formatWait = (seconds: number): string => {
73
+ const s = Math.max(1, Math.ceil(seconds));
74
+ if (s < 60) return `${s} ${s === 1 ? 'second' : 'seconds'}`;
75
+ const m = Math.ceil(s / 60);
76
+ return `${m} ${m === 1 ? 'minute' : 'minutes'}`;
77
+ };
78
+
79
+ export interface LimitInfo {
80
+ code: string;
81
+ retryAfterSeconds?: number;
82
+ /** Plain message for the person, with the wait time when the server sent one. */
83
+ message: string;
84
+ }
85
+
86
+ /**
87
+ * Recognise a "slow down" answer: a route rate limit, a login lock, the
88
+ * per-address email cap or a blocked network. Returns null for any other
89
+ * error. Wording lives here (not in the server's message) so every screen
90
+ * says the same thing.
91
+ */
92
+ export const getLimitInfo = (error: unknown): LimitInfo | null => {
93
+ if (!axios.isAxiosError(error)) return null;
94
+ const status = error.response?.status;
95
+ const data = error.response?.data as ApiError | undefined;
96
+ const code = data?.error?.code ?? (status === 429 ? ERROR_CODES.RATE_LIMIT_EXCEEDED : undefined);
97
+ const seconds = data?.error?.retryAfterSeconds;
98
+ const wait = seconds ? ` Try again in ${formatWait(seconds)}.` : ' Please wait a moment and try again.';
99
+
100
+ switch (code) {
101
+ case ERROR_CODES.RATE_LIMIT_EXCEEDED:
102
+ return { code, retryAfterSeconds: seconds, message: `Too many requests.${wait}` };
103
+ case ERROR_CODES.LOGIN_LOCKED:
104
+ return { code, retryAfterSeconds: seconds, message: `Too many failed sign-in attempts.${wait}` };
105
+ case ERROR_CODES.EMAIL_RATE_LIMITED:
106
+ return { code, retryAfterSeconds: seconds, message: `Too many emails were sent to this address.${wait}` };
107
+ case ERROR_CODES.IP_BLOCKED:
108
+ return {
109
+ code,
110
+ retryAfterSeconds: seconds,
111
+ message: seconds
112
+ ? `Too many requests from your network. Try again in ${formatWait(seconds)}.`
113
+ : 'Access from your network is blocked.',
114
+ };
115
+ default:
116
+ return null;
117
+ }
118
+ };
119
+
120
+ /** True for the answers getLimitInfo recognises. Such requests must not be retried. */
121
+ export const isLimitError = (error: unknown): boolean => getLimitInfo(error) !== null;
@@ -0,0 +1,31 @@
1
+ import type { FieldValues, Path, UseFormSetError } from 'react-hook-form';
2
+
3
+ import { getFieldErrors } from '@/lib/utils/error';
4
+
5
+ /**
6
+ * Put the server's verdict on wrong input (422 VALIDATION_FAILED, one message
7
+ * per field) onto the form's own fields, so it shows where the client rules
8
+ * show theirs. The client rules mirror the server's, but the server is the one
9
+ * that decides: whatever slips through (a rule changed on one side only) still
10
+ * lands under the right field instead of only in a toast.
11
+ *
12
+ * Only the form's own `fields` are set; anything else (a field the form does
13
+ * not have) stays in the toast the auth hooks show. Returns whether any field
14
+ * got a message. Call it from an effect on the request's error.
15
+ */
16
+ export function applyFieldErrors<T extends FieldValues>(
17
+ error: unknown,
18
+ setError: UseFormSetError<T>,
19
+ fields: readonly Path<T>[]
20
+ ): boolean {
21
+ const byField = getFieldErrors(error);
22
+ let applied = false;
23
+ for (const field of fields) {
24
+ const message = byField[field];
25
+ if (message) {
26
+ setError(field, { type: 'server', message });
27
+ applied = true;
28
+ }
29
+ }
30
+ return applied;
31
+ }
@@ -0,0 +1,18 @@
1
+ import { AUTH_PATHS, PROTECTED_PATHS } from '@/lib/constants/routes';
2
+
3
+ /**
4
+ * Whether `pathname` is `base` itself or a page under it, by whole path
5
+ * segments: '/admin' covers '/admin' and '/admin/users', never '/administrator'
6
+ * (a plain startsWith would treat that unrelated page as protected).
7
+ */
8
+ export function isUnderPath(pathname: string, base: string): boolean {
9
+ if (pathname === base) return true;
10
+ return pathname.startsWith(base.endsWith('/') ? base : `${base}/`);
11
+ }
12
+
13
+ /** A page that needs a signed-in visitor (PROTECTED_PATHS). */
14
+ export const isProtectedPath = (pathname: string): boolean =>
15
+ PROTECTED_PATHS.some((base) => isUnderPath(pathname, base));
16
+
17
+ /** A sign-in page (AUTH_PATHS). */
18
+ export const isAuthPath = (pathname: string): boolean => AUTH_PATHS.some((base) => isUnderPath(pathname, base));
@@ -7,6 +7,43 @@ export const isSafeUrl = (url: string): boolean => {
7
7
  }
8
8
  };
9
9
 
10
+ // Placeholder origin used only to parse relative paths. It never appears in
11
+ // output and `.invalid` can never resolve, so nothing here can point at it.
12
+ const REDIRECT_PARSE_BASE = 'https://redirect-check.invalid';
13
+
14
+ /**
15
+ * Turn an untrusted "where to go next" value (e.g. `?from=` on /login) into a
16
+ * same-site path, or undefined when it isn't one.
17
+ *
18
+ * A prefix check like `startsWith('/') && !startsWith('//')` is NOT enough:
19
+ * browsers treat `\` like `/` and silently drop tabs and newlines, so
20
+ * `/\evil.com` and `/<TAB>/evil.com` both become `//evil.com` — another site.
21
+ * The value is therefore parsed exactly like the browser will, and accepted
22
+ * only if it stays on our origin; we then return just path + query + hash.
23
+ */
24
+ export const getSafeRedirectPath = (value: string | null | undefined): string | undefined => {
25
+ if (!value || !value.startsWith('/') || value.startsWith('//')) return undefined;
26
+ // Backslashes, control characters and whitespace have no place in an
27
+ // internal path and are exactly what the bypasses rely on.
28
+ if (/[\\\s\u0000-\u001f\u007f]/.test(value)) return undefined;
29
+
30
+ try {
31
+ const url = new URL(value, REDIRECT_PARSE_BASE);
32
+ if (url.origin !== REDIRECT_PARSE_BASE) return undefined;
33
+ const path = `${url.pathname}${url.search}${url.hash}`;
34
+ // Check the RESULT, not only the input: dot segments normalize away, so
35
+ // '/..//evil.com' or '/%2e%2e//evil.com' come out as '//evil.com', which
36
+ // the router would treat as another site. The path we return must itself
37
+ // resolve back to our origin.
38
+ if (path.startsWith('//') || new URL(path, REDIRECT_PARSE_BASE).origin !== REDIRECT_PARSE_BASE) {
39
+ return undefined;
40
+ }
41
+ return path;
42
+ } catch {
43
+ return undefined;
44
+ }
45
+ };
46
+
10
47
  export const sanitizeString = (input: string): string => {
11
48
  return input
12
49
  .trim()
@@ -0,0 +1,24 @@
1
+ /**
2
+ * The server's "signed in" marker: the auth_session cookie (value "1", not a
3
+ * secret, readable by JavaScript; server src/libs/cookies.ts). It lives as long
4
+ * as the refresh token, and in a split deployment (app. + api. subdomains) it
5
+ * reaches the client only through COOKIE_DOMAIN, like everything that depends
6
+ * on it, the proxy's protected-page check included.
7
+ */
8
+ export const SESSION_MARKER_COOKIE = 'auth_session';
9
+
10
+ /**
11
+ * Whether a cookie string holds the marker. Without it there is no session to
12
+ * ask about, so the start-up "who am I" call is skipped and an anonymous
13
+ * visitor makes no API calls at all. Defaults to this browser's cookies, and is
14
+ * false during server rendering (no document).
15
+ */
16
+ export function hasSessionMarker(
17
+ cookies: string | undefined = typeof document === 'undefined' ? undefined : document.cookie
18
+ ): boolean {
19
+ if (!cookies) return false;
20
+ return cookies.split(';').some((part) => {
21
+ const [name, ...value] = part.trim().split('=');
22
+ return name === SESSION_MARKER_COOKIE && value.join('=') !== '';
23
+ });
24
+ }
@@ -1,8 +1,16 @@
1
+ /**
2
+ * Next.js proxy (the file convention formerly called middleware; renamed in
3
+ * Next 16, which runs it on the Node.js runtime). It runs before every page
4
+ * request except static assets and /healthz (see `config` below): it mints the
5
+ * per-request CSP nonce, sets the security headers, and sends visitors without
6
+ * a session marker away from protected pages.
7
+ */
1
8
  import { NextResponse } from 'next/server';
2
9
 
3
10
  import type { NextRequest } from 'next/server';
4
11
 
5
- const protectedPaths = ['/dashboard', '/profile', '/admin'];
12
+ import { isProtectedPath } from '@/lib/utils/paths';
13
+ import { SESSION_MARKER_COOKIE } from '@/lib/utils/session-marker';
6
14
 
7
15
  function isTokenExpired(token: string): boolean {
8
16
  try {
@@ -35,7 +43,7 @@ const sentryOrigin = toOrigin(process.env.NEXT_PUBLIC_SENTRY_DSN);
35
43
 
36
44
  /**
37
45
  * Build the per-request Content-Security-Policy. A fresh nonce is minted for
38
- * every request and threaded onto Next's own scripts (see middleware below), so
46
+ * every request and threaded onto Next's own scripts (see proxy below), so
39
47
  * 'strict-dynamic' can trust them while refusing any attacker-injected inline
40
48
  * script that lacks the nonce.
41
49
  *
@@ -84,7 +92,7 @@ function applySecurityHeaders(response: NextResponse): NextResponse {
84
92
  return response;
85
93
  }
86
94
 
87
- export function middleware(request: NextRequest): NextResponse {
95
+ export function proxy(request: NextRequest): NextResponse {
88
96
  const { pathname } = request.nextUrl;
89
97
 
90
98
  const isProd = process.env.NODE_ENV === 'production';
@@ -102,18 +110,22 @@ export function middleware(request: NextRequest): NextResponse {
102
110
  requestHeaders.set('x-nonce', nonce);
103
111
  requestHeaders.set('content-security-policy', cspHeader);
104
112
 
105
- // NOTE: This middleware only checks COOKIE PRESENCE (and a best-effort,
113
+ // NOTE: This proxy only checks COOKIE PRESENCE (and a best-effort,
106
114
  // unverified exp claim) for UX-level routing — redirecting users who are
107
115
  // obviously logged out away from protected pages. It does NOT verify the
108
116
  // JWT signature and is NOT a security boundary. Real authorization happens
109
- // server-side on every API call; a forged cookie gets past this middleware
117
+ // server-side on every API call; a forged cookie gets past this proxy
110
118
  // but every API request it makes will be rejected with 401/403.
119
+ // access_token is host-only on the API host, so in a split deployment only
120
+ // the session marker (shared through COOKIE_DOMAIN) is visible here.
111
121
  const accessToken = request.cookies.get('access_token')?.value;
112
- const authSession = request.cookies.get('auth_session')?.value;
122
+ const authSession = request.cookies.get(SESSION_MARKER_COOKIE)?.value;
113
123
 
114
- const isProtectedPath = protectedPaths.some((path) => pathname.startsWith(path));
124
+ // Whole path segments (lib/utils/paths.ts): /admin/users is protected,
125
+ // /administrator is not.
126
+ const isProtected = isProtectedPath(pathname);
115
127
 
116
- if (isProtectedPath) {
128
+ if (isProtected) {
117
129
  // No access_token AND no auth_session — truly unauthenticated.
118
130
  if (!accessToken && !authSession) {
119
131
  const loginUrl = new URL('/login', request.url);
@@ -130,7 +142,7 @@ export function middleware(request: NextRequest): NextResponse {
130
142
  response.headers.set('content-security-policy', cspHeader);
131
143
  applySecurityHeaders(response);
132
144
 
133
- if (isProtectedPath) {
145
+ if (isProtected) {
134
146
  // No access_token BUT auth_session exists — session is alive, let through
135
147
  // so client-side can do getMe() → 401 → refresh → retry.
136
148
  // (response already passes through; nothing extra needed here.)
@@ -146,6 +158,8 @@ export function middleware(request: NextRequest): NextResponse {
146
158
 
147
159
  export const config = {
148
160
  // Apply security headers site-wide, but skip Next's static assets and the
149
- // favicon (no CSP needed on immutable static files / images).
150
- matcher: ['/((?!_next/static|_next/image|favicon.ico).*)'],
161
+ // favicon (no CSP needed on immutable static files / images), and the
162
+ // container health check /healthz (src/app/healthz/route.ts), which must
163
+ // answer 200 whatever this proxy decides for pages.
164
+ matcher: ['/((?!_next/static|_next/image|favicon.ico|healthz).*)'],
151
165
  };
@@ -0,0 +1,44 @@
1
+ import { describe, expect, it } from 'vitest';
2
+
3
+ import { setUser } from '@/features/auth/store/authSlice';
4
+ import type { IUser } from '@/features/auth/types/auth.types';
5
+
6
+ import { makeStore } from '../index';
7
+
8
+ const user: IUser = {
9
+ id: 'u1',
10
+ email: 'a@example.test',
11
+ firstName: 'Ana',
12
+ lastName: 'Test',
13
+ role: 'USER',
14
+ isActive: true,
15
+ emailVerifiedAt: null,
16
+ avatarUrl: null,
17
+ createdAt: '2026-01-01T00:00:00.000Z',
18
+ updatedAt: '2026-01-01T00:00:00.000Z',
19
+ };
20
+
21
+ describe('makeStore', () => {
22
+ it('without a session marker the visitor is signed out from the first render', () => {
23
+ expect(makeStore().getState().auth).toEqual({
24
+ user: null,
25
+ isAuthenticated: false,
26
+ isInitializing: false,
27
+ isLoggingOut: false,
28
+ });
29
+ });
30
+
31
+ it('with a session marker the user is unknown until the "who am I" check answers', () => {
32
+ const auth = makeStore({ hasSession: true }).getState().auth;
33
+ expect(auth.isInitializing).toBe(true);
34
+ expect(auth.isAuthenticated).toBe(false);
35
+ });
36
+
37
+ it('every store is its own: one visitor signing in never shows in another', () => {
38
+ const a = makeStore({ hasSession: true });
39
+ const b = makeStore({ hasSession: true });
40
+ a.dispatch(setUser(user));
41
+ expect(a.getState().auth.user?.firstName).toBe('Ana');
42
+ expect(b.getState().auth.user).toBeNull();
43
+ });
44
+ });
@@ -1,12 +1,30 @@
1
1
  import { configureStore } from '@reduxjs/toolkit';
2
2
 
3
- import authReducer from '@/features/auth/store/authSlice';
3
+ import authReducer, { initialAuthState } from '@/features/auth/store/authSlice';
4
4
 
5
- export const store = configureStore({
6
- reducer: {
7
- auth: authReducer,
8
- },
9
- });
5
+ /**
6
+ * A new store per visitor: Providers makes one per page load in the browser and
7
+ * one per request during server rendering, so no visitor's state can ever leak
8
+ * into another's (Redux's guidance for the Next.js App Router: a module-level
9
+ * store would be shared by every request the server renders).
10
+ *
11
+ * `hasSession`: the request carries the server's session marker (the root
12
+ * layout reads it). Then who the visitor is stays unknown until the "who am I"
13
+ * check answers (isInitializing). Without it the visitor is plainly signed out
14
+ * from the first render, so the server already renders the signed-out header
15
+ * instead of one that flips after loading.
16
+ */
17
+ export function makeStore({ hasSession = false }: { hasSession?: boolean } = {}) {
18
+ return configureStore({
19
+ reducer: {
20
+ auth: authReducer,
21
+ },
22
+ preloadedState: {
23
+ auth: { ...initialAuthState, isInitializing: hasSession },
24
+ },
25
+ });
26
+ }
10
27
 
11
- export type RootState = ReturnType<typeof store.getState>;
12
- export type AppDispatch = typeof store.dispatch;
28
+ export type AppStore = ReturnType<typeof makeStore>;
29
+ export type RootState = ReturnType<AppStore['getState']>;
30
+ export type AppDispatch = AppStore['dispatch'];
@@ -0,0 +1,48 @@
1
+ import { fileURLToPath } from 'node:url';
2
+
3
+ import { defineConfig } from 'vitest/config';
4
+
5
+ /**
6
+ * Unit tests for the client's logic: the API client's session rules, the
7
+ * proxy's CSP and redirects, redirect safety, error parsing and the store.
8
+ * They run in Node; a file that needs `document` or `window` starts with
9
+ * `// @vitest-environment jsdom`. Screens are not unit-tested here: the
10
+ * template ships no pages, and the components are thin over these functions.
11
+ *
12
+ * Test files and this config are kept out of the production image
13
+ * (.dockerignore), so the image's `next build` never type-checks them. The
14
+ * .mts extension: this package is not `"type": "module"`, and Vite warns about
15
+ * ESM syntax in a config it would load as CommonJS.
16
+ */
17
+ export default defineConfig({
18
+ test: {
19
+ environment: 'node',
20
+ include: ['src/**/*.test.ts'],
21
+ restoreMocks: true,
22
+ coverage: {
23
+ provider: 'v8',
24
+ reporter: ['text', 'json', 'html', 'lcov'],
25
+ // Every source file counts, also the ones no test loads, so the number
26
+ // is honest. Type-only files and the tests themselves are left out.
27
+ include: ['src/**/*.{ts,tsx}'],
28
+ exclude: ['**/__tests__/**', '**/*.test.ts', '**/*.d.ts', 'src/types/**'],
29
+ // A ratchet, not a target: the real numbers when they were set
30
+ // (2026-10-20), rounded down, from a project made with the
31
+ // email-verification module (its client code has no unit tests, so it
32
+ // sits about one point below a plain project). `npm run test:coverage`
33
+ // (and CI) fails below them; raise them when tests are added. Components
34
+ // and pages count but are thin: the logic they call is what is tested.
35
+ thresholds: {
36
+ lines: 23,
37
+ statements: 23,
38
+ branches: 27,
39
+ functions: 13,
40
+ },
41
+ },
42
+ },
43
+ resolve: {
44
+ alias: {
45
+ '@': fileURLToPath(new URL('./src', import.meta.url)),
46
+ },
47
+ },
48
+ });