create-tigra 3.3.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 (203) hide show
  1. package/README.md +81 -12
  2. package/bin/create-tigra.js +495 -472
  3. package/lib/patchers/email-verification.patcher.js +72 -10
  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 +44 -13
  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 +35 -18
  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 +13 -2
  35. package/template/client/src/features/auth/components/RegisterForm.tsx +23 -7
  36. package/template/client/src/features/auth/hooks/useAuth.ts +11 -1
  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/lib/api/__tests__/axios.config.test.ts +183 -0
  41. package/template/client/src/lib/api/api.types.ts +14 -0
  42. package/template/client/src/lib/api/axios.config.ts +101 -15
  43. package/template/client/src/lib/api/hard-redirect.ts +8 -0
  44. package/template/client/src/lib/api/session-events.ts +29 -0
  45. package/template/client/src/lib/constants/routes.ts +12 -0
  46. package/template/client/src/lib/observability/sentry-scrub.ts +1 -1
  47. package/template/client/src/lib/utils/__tests__/error.test.ts +119 -0
  48. package/template/client/src/lib/utils/__tests__/form.test.ts +42 -0
  49. package/template/client/src/lib/utils/__tests__/paths.test.ts +43 -0
  50. package/template/client/src/lib/utils/__tests__/security.test.ts +40 -0
  51. package/template/client/src/lib/utils/__tests__/session-marker.test.ts +27 -0
  52. package/template/client/src/lib/utils/error.ts +81 -0
  53. package/template/client/src/lib/utils/form.ts +31 -0
  54. package/template/client/src/lib/utils/paths.ts +18 -0
  55. package/template/client/src/lib/utils/session-marker.ts +24 -0
  56. package/template/client/src/{middleware.ts → proxy.ts} +25 -11
  57. package/template/client/src/store/__tests__/store.test.ts +44 -0
  58. package/template/client/src/store/index.ts +26 -8
  59. package/template/client/vitest.config.mts +48 -0
  60. package/template/server/.env.example +280 -270
  61. package/template/server/.env.example.production +283 -242
  62. package/template/server/AGENTS.md +13 -4
  63. package/template/server/Dockerfile +176 -14
  64. package/template/server/docker-compose.yml +4 -2
  65. package/template/server/docs/deployment.md +63 -0
  66. package/template/server/docs/logging.md +52 -4
  67. package/template/server/docs/rate-limits.md +153 -0
  68. package/template/server/docs/testing.md +63 -0
  69. package/template/server/eslint.config.mjs +19 -0
  70. package/template/server/package-lock.json +8784 -8743
  71. package/template/server/package.json +79 -75
  72. package/template/server/prisma/migrations/0_init/migration.sql +82 -0
  73. package/template/server/prisma/migrations/migration_lock.toml +3 -0
  74. package/template/server/prisma/schema.prisma +0 -3
  75. package/template/server/scripts/check-heic.mjs +40 -0
  76. package/template/server/scripts/check-sharp.mjs +53 -0
  77. package/template/server/src/__tests__/routes.integration.test.ts +280 -0
  78. package/template/server/src/app.ts +248 -346
  79. package/template/server/src/config/__tests__/env.test.ts +219 -0
  80. package/template/server/src/config/__tests__/rate-limit.config.test.ts +158 -0
  81. package/template/server/src/config/env.ts +326 -182
  82. package/template/server/src/config/rate-limit.config.ts +157 -106
  83. package/template/server/src/jobs/__tests__/cleanup-deleted-accounts.job.test.ts +60 -8
  84. package/template/server/src/jobs/__tests__/cleanup-expired-auth.job.test.ts +44 -0
  85. package/template/server/src/jobs/__tests__/jobs.integration.test.ts +88 -0
  86. package/template/server/src/jobs/__tests__/schedule.test.ts +92 -0
  87. package/template/server/src/jobs/cleanup-deleted-accounts.job.ts +38 -36
  88. package/template/server/src/jobs/cleanup-expired-auth.job.ts +32 -24
  89. package/template/server/src/jobs/index.ts +12 -2
  90. package/template/server/src/jobs/refresh-cloudflare-ranges.job.ts +28 -0
  91. package/template/server/src/jobs/schedule.ts +50 -0
  92. package/template/server/src/libs/__tests__/auth.test.ts +98 -7
  93. package/template/server/src/libs/__tests__/client-ip.test.ts +257 -121
  94. package/template/server/src/libs/__tests__/cloudflare-ranges.test.ts +79 -0
  95. package/template/server/src/libs/__tests__/cookies.test.ts +53 -2
  96. package/template/server/src/libs/__tests__/email-quota.test.ts +81 -0
  97. package/template/server/src/libs/__tests__/email.test.ts +68 -0
  98. package/template/server/src/libs/__tests__/error-handler.test.ts +162 -0
  99. package/template/server/src/libs/__tests__/health-db-down.integration.test.ts +37 -0
  100. package/template/server/src/libs/__tests__/health-redis-down.integration.test.ts +45 -0
  101. package/template/server/src/libs/__tests__/health-routes.test.ts +83 -0
  102. package/template/server/src/libs/__tests__/health.integration.test.ts +118 -0
  103. package/template/server/src/libs/__tests__/http.test.ts +74 -2
  104. package/template/server/src/libs/__tests__/ip-block.test.ts +179 -62
  105. package/template/server/src/libs/__tests__/logger.test.ts +50 -0
  106. package/template/server/src/libs/__tests__/monitoring.test.ts +185 -0
  107. package/template/server/src/libs/__tests__/outbound.integration.test.ts +48 -0
  108. package/template/server/src/libs/__tests__/prisma-client.test.ts +28 -0
  109. package/template/server/src/libs/__tests__/query-counter.integration.test.ts +53 -0
  110. package/template/server/src/libs/__tests__/rate-limiting.test.ts +146 -0
  111. package/template/server/src/libs/__tests__/rate-limits.integration.test.ts +53 -0
  112. package/template/server/src/libs/__tests__/redis-required.test.ts +30 -0
  113. package/template/server/src/libs/__tests__/redis.test.ts +38 -2
  114. package/template/server/src/libs/__tests__/request-id.test.ts +25 -0
  115. package/template/server/src/libs/__tests__/requestLogger.test.ts +126 -0
  116. package/template/server/src/libs/__tests__/safe-http.test.ts +138 -0
  117. package/template/server/src/libs/__tests__/sentry-scrub.test.ts +82 -80
  118. package/template/server/src/libs/__tests__/shutdown.test.ts +89 -0
  119. package/template/server/src/libs/__tests__/url-safety.test.ts +130 -80
  120. package/template/server/src/libs/auth.ts +39 -10
  121. package/template/server/src/libs/client-ip.ts +158 -77
  122. package/template/server/src/libs/cloudflare-ranges.ts +132 -0
  123. package/template/server/src/libs/cookies.ts +53 -14
  124. package/template/server/src/libs/email-quota.ts +74 -0
  125. package/template/server/src/libs/email.ts +46 -9
  126. package/template/server/src/libs/error-handler.ts +111 -0
  127. package/template/server/src/libs/health-routes.ts +53 -0
  128. package/template/server/src/libs/http.ts +139 -47
  129. package/template/server/src/libs/ip-address.ts +37 -0
  130. package/template/server/src/libs/ip-block.ts +284 -221
  131. package/template/server/src/libs/logger.ts +41 -12
  132. package/template/server/src/libs/monitoring.ts +127 -41
  133. package/template/server/src/libs/observability/sentry.ts +1 -1
  134. package/template/server/src/libs/origin-check.ts +9 -7
  135. package/template/server/src/libs/prisma.ts +47 -4
  136. package/template/server/src/libs/query-counter.ts +71 -59
  137. package/template/server/src/libs/rate-limiting.ts +110 -0
  138. package/template/server/src/libs/redis-required.ts +28 -0
  139. package/template/server/src/libs/redis.ts +27 -1
  140. package/template/server/src/libs/request-id.ts +18 -0
  141. package/template/server/src/libs/requestLogger.ts +112 -17
  142. package/template/server/src/libs/safe-http.ts +101 -0
  143. package/template/server/src/libs/shutdown.ts +87 -0
  144. package/template/server/src/libs/storage/__tests__/fixtures/tiny-heic.ts +13 -0
  145. package/template/server/src/libs/storage/__tests__/image-optimizer.test.ts +59 -0
  146. package/template/server/src/libs/storage/__tests__/multipart-limits.test.ts +91 -0
  147. package/template/server/src/libs/storage/__tests__/upload-persistence.test.ts +52 -0
  148. package/template/server/src/libs/storage/file-storage.service.ts +94 -84
  149. package/template/server/src/libs/storage/file-validator.ts +48 -46
  150. package/template/server/src/libs/storage/image-optimizer.service.ts +16 -5
  151. package/template/server/src/libs/token-hash.ts +18 -0
  152. package/template/server/src/libs/url-safety.ts +127 -121
  153. package/template/server/src/libs/validation-errors.ts +86 -0
  154. package/template/server/src/modules/admin/__tests__/admin-actions.integration.test.ts +255 -0
  155. package/template/server/src/modules/admin/__tests__/admin.health.test.ts +82 -0
  156. package/template/server/src/modules/admin/__tests__/admin.repo.test.ts +55 -0
  157. package/template/server/src/modules/admin/__tests__/admin.schemas.test.ts +38 -0
  158. package/template/server/src/modules/admin/__tests__/admin.service.test.ts +162 -0
  159. package/template/server/src/modules/admin/admin.controller.ts +66 -49
  160. package/template/server/src/modules/admin/admin.repo.ts +49 -10
  161. package/template/server/src/modules/admin/admin.routes.ts +48 -2
  162. package/template/server/src/modules/admin/admin.schemas.ts +18 -6
  163. package/template/server/src/modules/admin/admin.service.ts +66 -4
  164. package/template/server/src/modules/auth/__tests__/auth.controller.test.ts +39 -0
  165. package/template/server/src/modules/auth/__tests__/auth.integration.test.ts +9 -3
  166. package/template/server/src/modules/auth/__tests__/auth.service.dummy-hash.test.ts +34 -0
  167. package/template/server/src/modules/auth/__tests__/auth.service.test.ts +197 -37
  168. package/template/server/src/modules/auth/__tests__/session-cleanup.test.ts +39 -0
  169. package/template/server/src/modules/auth/__tests__/sessions.integration.test.ts +246 -0
  170. package/template/server/src/modules/auth/__tests__/token-fingerprints.test.ts +119 -0
  171. package/template/server/src/modules/auth/auth.controller.ts +133 -128
  172. package/template/server/src/modules/auth/auth.repo.ts +44 -44
  173. package/template/server/src/modules/auth/auth.schemas.ts +4 -2
  174. package/template/server/src/modules/auth/auth.service.ts +167 -96
  175. package/template/server/src/modules/auth/session.repo.ts +12 -0
  176. package/template/server/src/modules/files/__tests__/files.integration.test.ts +5 -5
  177. package/template/server/src/modules/users/__tests__/avatar-upload.test.ts +120 -0
  178. package/template/server/src/modules/users/__tests__/name-rules.test.ts +46 -0
  179. package/template/server/src/modules/users/__tests__/users.integration.test.ts +295 -0
  180. package/template/server/src/modules/users/__tests__/users.repo.test.ts +37 -0
  181. package/template/server/src/modules/users/__tests__/users.service.test.ts +129 -0
  182. package/template/server/src/modules/users/users.controller.ts +9 -38
  183. package/template/server/src/modules/users/users.repo.ts +23 -7
  184. package/template/server/src/modules/users/users.routes.ts +3 -22
  185. package/template/server/src/modules/users/users.schemas.ts +15 -9
  186. package/template/server/src/modules/users/users.service.ts +105 -93
  187. package/template/server/src/scripts/make-admin.ts +48 -0
  188. package/template/server/src/server.ts +48 -26
  189. package/template/server/src/shared/errors/AppError.ts +27 -1
  190. package/template/server/src/shared/errors/errors.ts +42 -5
  191. package/template/server/src/shared/responses/successResponse.ts +22 -3
  192. package/template/server/src/shared/types/index.ts +7 -0
  193. package/template/server/src/test/__tests__/integration-services.test.ts +66 -0
  194. package/template/server/src/test/integration-helpers.ts +343 -0
  195. package/template/server/src/test/integration-services.ts +74 -0
  196. package/template/server/src/test/integration.global-setup.ts +144 -0
  197. package/template/server/src/test/integration.setup.ts +35 -158
  198. package/template/server/src/test/setup.ts +3 -10
  199. package/template/server/tsconfig.build.json +1 -1
  200. package/template/server/tsconfig.json +1 -0
  201. package/template/server/vitest.config.ts +17 -4
  202. package/template/server/vitest.integration.config.ts +18 -13
  203. package/template/server/src/libs/storage/filename-sanitizer.ts +0 -71
@@ -1,121 +1,127 @@
1
- /**
2
- * URL/IP safety helpers shared across outbound-HTTP code paths.
3
- *
4
- * - `redactUrl` — strips secrets (Telegram bot tokens, query strings)
5
- * from a URL before it reaches any log sink.
6
- * - `isPrivateOrReservedIp`— SSRF building block: returns true for any loopback /
7
- * private / link-local / ULA / reserved address so the
8
- * image-fetch guard can reject internal targets.
9
- *
10
- * Pure, dependency-free, and side-effect-free so they are trivial to unit test.
11
- */
12
-
13
- /**
14
- * Redact a URL so it is safe to log.
15
- *
16
- * Telegram embeds the bot token directly in the request path:
17
- * https://api.telegram.org/bot<TOKEN>/getFile
18
- * https://api.telegram.org/file/bot<TOKEN>/photos/file_1.jpg
19
- * Both forms (`/bot<token>/` and `/file/bot<token>/`) are rewritten to
20
- * `/bot<redacted>/`. Any query string is dropped wholesale (it can also carry
21
- * media tokens / signatures). Non-Telegram URLs pass through unchanged apart
22
- * from query stripping. NEVER throws — an unparseable string is returned with
23
- * just the same path-level redaction applied.
24
- */
25
- export function redactUrl(url: string): string {
26
- if (typeof url !== 'string' || url.length === 0) {
27
- return url;
28
- }
29
-
30
- // Drop the query string (and fragment) — may hold signed tokens.
31
- const noQuery = url.split(/[?#]/, 1)[0];
32
-
33
- // Rewrite Telegram bot-token path segments. The token charset is [A-Za-z0-9_-]
34
- // plus the ':' separating bot-id from secret, e.g. 123456:AAH...
35
- return noQuery.replace(/\/bot[A-Za-z0-9:_-]+/g, '/bot<redacted>');
36
- }
37
-
38
- /**
39
- * True when `addr` is a loopback / private / link-local / ULA / unspecified /
40
- * reserved IP that an SSRF target could use to reach internal infrastructure.
41
- *
42
- * Covers:
43
- * IPv4: 0.0.0.0, 127/8, 10/8, 172.16/12, 192.168/16, 169.254/16, 100.64/10 (CGNAT)
44
- * IPv6: ::, ::1, fc00::/7 (ULA), fe80::/10 (link-local)
45
- * IPv4-mapped IPv6 (::ffff:a.b.c.d) — re-checked against the IPv4 rules.
46
- *
47
- * Unrecognised / unparseable input returns true (fail-closed) — the caller
48
- * uses this purely to BLOCK, so an address it cannot classify is treated as
49
- * unsafe rather than silently allowed.
50
- */
51
- export function isPrivateOrReservedIp(addr: string): boolean {
52
- if (typeof addr !== 'string' || addr.length === 0) {
53
- return true;
54
- }
55
-
56
- const ip = addr.trim().toLowerCase();
57
-
58
- // IPv4-mapped IPv6, e.g. ::ffff:10.0.0.5 or ::ffff:0a00:0005 — extract the v4 tail.
59
- const mapped = ip.match(/^::ffff:(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$/);
60
- if (mapped) {
61
- return isPrivateOrReservedIpv4(mapped[1]);
62
- }
63
-
64
- if (ip.includes(':')) {
65
- return isReservedIpv6(ip);
66
- }
67
-
68
- return isPrivateOrReservedIpv4(ip);
69
- }
70
-
71
- function isPrivateOrReservedIpv4(ip: string): boolean {
72
- const parts = ip.split('.');
73
- if (parts.length !== 4) {
74
- return true; // not a clean dotted-quad → block
75
- }
76
-
77
- const octets = parts.map((p) => Number(p));
78
- if (octets.some((o) => !Number.isInteger(o) || o < 0 || o > 255)) {
79
- return true; // malformed → block
80
- }
81
-
82
- const [a, b] = octets;
83
-
84
- if (a === 0) return true; // 0.0.0.0/8 (incl. unspecified)
85
- if (a === 127) return true; // 127.0.0.0/8 loopback
86
- if (a === 10) return true; // 10.0.0.0/8 private
87
- if (a === 172 && b >= 16 && b <= 31) return true; // 172.16.0.0/12 private
88
- if (a === 192 && b === 168) return true; // 192.168.0.0/16 private
89
- if (a === 169 && b === 254) return true; // 169.254.0.0/16 link-local
90
- if (a === 100 && b >= 64 && b <= 127) return true; // 100.64.0.0/10 CGNAT
91
-
92
- return false;
93
- }
94
-
95
- function isReservedIpv6(ip: string): boolean {
96
- // Normalise: drop zone id (fe80::1%eth0) and any brackets.
97
- const bare = ip.replace(/^\[|\]$/g, '').split('%')[0];
98
-
99
- if (bare === '::' || bare === '::0' || bare === '0:0:0:0:0:0:0:0') return true; // unspecified
100
- if (bare === '::1') return true; // loopback
101
-
102
- // First hextet determines ULA / link-local ranges.
103
- const firstHextet = bare.split(':')[0];
104
- if (firstHextet === '') {
105
- // Address starts with '::' (e.g. '::abcd') — already handled the special
106
- // cases above; remaining such addresses are not in fc00::/7 or fe80::/10.
107
- return false;
108
- }
109
-
110
- const value = parseInt(firstHextet, 16);
111
- if (Number.isNaN(value)) {
112
- return true; // unparseable hextet → block
113
- }
114
-
115
- // fc00::/7 → first 7 bits = 1111110 → first byte 0xfc or 0xfd
116
- if ((value & 0xfe00) === 0xfc00) return true;
117
- // fe80::/10 → first 10 bits = 1111111010 → 0xfe80..0xfebf
118
- if ((value & 0xffc0) === 0xfe80) return true;
119
-
120
- return false;
121
- }
1
+ /**
2
+ * URL/IP safety helpers for outbound HTTP and IP blocking.
3
+ *
4
+ * - `redactUrl` strips secrets (credentials in the URL, query
5
+ * strings, Telegram bot tokens) before a URL reaches
6
+ * any log sink.
7
+ * - `isPrivateOrReservedIp` internal infrastructure: loopback, private,
8
+ * link-local, CGNAT, unique-local, unspecified. Used
9
+ * by IP blocking (never block or auto-block these).
10
+ * - `isForbiddenOutboundIp` everything that is not a public unicast address
11
+ * (the above plus multicast, reserved, documentation,
12
+ * NAT64/6to4 and similar). Used ONLY by the guarded
13
+ * client for user-supplied URLs (libs/safe-http.ts).
14
+ *
15
+ * Two lists on purpose: documentation ranges such as 203.0.113.0/24 and
16
+ * 2001:db8::/32 are not internal (an admin may block them; tests use them as
17
+ * public visitors), yet an outbound request must never go there.
18
+ *
19
+ * Every address is first put into its canonical form (normalizeIp), so a hex
20
+ * IPv4-mapped spelling like ::ffff:7f00:1 is judged as the 127.0.0.1 it is.
21
+ * Pure and side-effect-free, so trivial to unit test.
22
+ */
23
+
24
+ import { BlockList } from 'node:net';
25
+ import { normalizeIp } from '@libs/ip-address.js';
26
+
27
+ /**
28
+ * Redact a URL so it is safe to log.
29
+ *
30
+ * Telegram embeds the bot token directly in the request path:
31
+ * https://api.telegram.org/bot<TOKEN>/getFile
32
+ * https://api.telegram.org/file/bot<TOKEN>/photos/file_1.jpg
33
+ * Both forms (`/bot<token>/` and `/file/bot<token>/`) are rewritten to
34
+ * `/bot<redacted>/`. Any query string is dropped wholesale (it can also carry
35
+ * media tokens / signatures). Non-Telegram URLs pass through unchanged apart
36
+ * from query stripping. NEVER throws — an unparseable string is returned with
37
+ * just the same path-level redaction applied.
38
+ */
39
+ export function redactUrl(url: string): string {
40
+ if (typeof url !== 'string' || url.length === 0) {
41
+ return url;
42
+ }
43
+
44
+ // Drop the query string (and fragment) — may hold API keys or signed tokens —
45
+ // and credentials in the authority (https://user:password@host/).
46
+ const noQuery = url.split(/[?#]/, 1)[0].replace(/^([a-z][a-z0-9+.-]*:\/\/)[^/@]*@/i, '$1');
47
+
48
+ // Rewrite Telegram bot-token path segments. The token charset is [A-Za-z0-9_-]
49
+ // plus the ':' separating bot-id from secret, e.g. 123456:AAH...
50
+ return noQuery.replace(/\/bot[A-Za-z0-9:_-]+/g, '/bot<redacted>');
51
+ }
52
+
53
+ /** Internal infrastructure ranges (isPrivateOrReservedIp). */
54
+ const INTERNAL = new BlockList();
55
+ for (const [net, prefix] of [
56
+ ['0.0.0.0', 8], // "this network", incl. unspecified
57
+ ['10.0.0.0', 8], // private
58
+ ['100.64.0.0', 10], // CGNAT
59
+ ['127.0.0.0', 8], // loopback
60
+ ['169.254.0.0', 16], // link-local (incl. cloud metadata 169.254.169.254)
61
+ ['172.16.0.0', 12], // private
62
+ ['192.168.0.0', 16], // private
63
+ ] as const) INTERNAL.addSubnet(net, prefix, 'ipv4');
64
+ for (const [net, prefix] of [
65
+ ['::', 128], // unspecified
66
+ ['::1', 128], // loopback
67
+ ['fc00::', 7], // unique local
68
+ ['fe80::', 10], // link-local
69
+ ] as const) INTERNAL.addSubnet(net, prefix, 'ipv6');
70
+
71
+ /** Not internal, but never a destination for an outbound request (isForbiddenOutboundIp). */
72
+ const NOT_PUBLIC = new BlockList();
73
+ for (const [net, prefix] of [
74
+ ['192.0.0.0', 24], // IETF protocol assignments
75
+ ['192.0.2.0', 24], // documentation (TEST-NET-1)
76
+ ['192.88.99.0', 24], // 6to4 relay anycast
77
+ ['198.18.0.0', 15], // benchmarking
78
+ ['198.51.100.0', 24], // documentation (TEST-NET-2)
79
+ ['203.0.113.0', 24], // documentation (TEST-NET-3)
80
+ ['224.0.0.0', 4], // multicast
81
+ ['240.0.0.0', 4], // reserved, incl. 255.255.255.255 broadcast
82
+ ] as const) NOT_PUBLIC.addSubnet(net, prefix, 'ipv4');
83
+ for (const [net, prefix] of [
84
+ ['64:ff9b::', 96], // NAT64: would reach any IPv4 address, internal ones too
85
+ ['64:ff9b:1::', 48], // local-use NAT64
86
+ ['100::', 64], // discard
87
+ ['2001::', 23], // IETF protocol assignments (incl. Teredo)
88
+ ['2001:db8::', 32], // documentation
89
+ ['2002::', 16], // 6to4: embeds an IPv4 address
90
+ ['fec0::', 10], // site-local (deprecated)
91
+ ['ff00::', 8], // multicast
92
+ ] as const) NOT_PUBLIC.addSubnet(net, prefix, 'ipv6');
93
+
94
+ /** Canonical address and its family, or undefined for anything that is not an IP literal. */
95
+ function parse(addr: unknown): { ip: string; family: 'ipv4' | 'ipv6' } | undefined {
96
+ if (typeof addr !== 'string') return undefined;
97
+ const ip = normalizeIp(addr.replace(/^\[|\]$/g, ''));
98
+ if (!ip) return undefined;
99
+ const family = ip.includes(':') ? 'ipv6' : 'ipv4';
100
+ // A zone id (fe80::1%eth0) is link-local by definition; BlockList cannot parse it.
101
+ return { ip: family === 'ipv6' ? ip.split('%')[0] : ip, family };
102
+ }
103
+
104
+ /**
105
+ * True when `addr` is internal infrastructure: loopback, private, link-local,
106
+ * CGNAT, unique-local or unspecified (ranges above). IPv4-mapped IPv6, dotted
107
+ * or hex, is judged as its IPv4 address.
108
+ *
109
+ * Unrecognised / unparseable input returns true (fail-closed): callers use this
110
+ * to protect, so an address it cannot classify is treated as internal.
111
+ */
112
+ export function isPrivateOrReservedIp(addr: string): boolean {
113
+ const parsed = parse(addr);
114
+ if (!parsed) return true;
115
+ return INTERNAL.check(parsed.ip, parsed.family);
116
+ }
117
+
118
+ /**
119
+ * True when an outbound request must not go to `addr`: anything internal
120
+ * (isPrivateOrReservedIp) and every other address that is not public unicast.
121
+ * Fail-closed like isPrivateOrReservedIp.
122
+ */
123
+ export function isForbiddenOutboundIp(addr: string): boolean {
124
+ const parsed = parse(addr);
125
+ if (!parsed) return true;
126
+ return INTERNAL.check(parsed.ip, parsed.family) || NOT_PUBLIC.check(parsed.ip, parsed.family);
127
+ }
@@ -0,0 +1,86 @@
1
+ /**
2
+ * One answer for wrong input, whichever layer catches it: a route schema
3
+ * (fastify-type-provider-zod), a `schema.parse()` inside a handler, or
4
+ * `parseInput()` below. Every case becomes
5
+ *
6
+ * 422 { success: false, error: { code: 'VALIDATION_FAILED',
7
+ * message: 'Please check these fields: email, password',
8
+ * fields: [{ field: 'email', message: 'Invalid email address' }, ...] } }
9
+ *
10
+ * Never the submitted values: messages come from Zod (or Ajv), which describe
11
+ * the rule ("Too small: expected string to have >=8 characters"), and Zod
12
+ * drops an issue's `input` unless `reportInput` is set, which nothing here
13
+ * does. Keep it that way: a value in a validation answer can leak a password
14
+ * into logs, screenshots or a support ticket.
15
+ *
16
+ * Malformed JSON is not "wrong input" but an unreadable request; it stays a
17
+ * 400 BAD_REQUEST in libs/error-handler.ts.
18
+ */
19
+ import type { z } from 'zod';
20
+ import type { FieldError } from '@shared/errors/AppError.js';
21
+ import { ValidationError } from '@shared/errors/errors.js';
22
+
23
+ export const VALIDATION_FAILED = 'VALIDATION_FAILED';
24
+
25
+ /** Enough to fix a form; caps the answer when a whole object is wrong. */
26
+ export const MAX_FIELD_ERRORS = 20;
27
+
28
+ interface IssueLike {
29
+ path: ReadonlyArray<PropertyKey>;
30
+ message: string;
31
+ }
32
+
33
+ /** Fastify's names for the request parts, shown when the whole part is wrong. */
34
+ const PART_NAMES: Record<string, string> = { body: 'body', querystring: 'query', params: 'params', headers: 'headers' };
35
+
36
+ function partName(context: string | undefined): string {
37
+ return (context && PART_NAMES[context]) ?? 'input';
38
+ }
39
+
40
+ /** Zod issues (from `.parse()` / `.safeParse()`) as field errors. */
41
+ export function fieldsFromZodIssues(issues: ReadonlyArray<IssueLike>, context?: string): FieldError[] {
42
+ return issues.slice(0, MAX_FIELD_ERRORS).map((issue) => ({
43
+ field: issue.path.length > 0 ? issue.path.map(String).join('.') : partName(context),
44
+ message: issue.message,
45
+ }));
46
+ }
47
+
48
+ /**
49
+ * Fastify schema-validation items as field errors. fastify-type-provider-zod
50
+ * and Fastify's own Ajv both report `instancePath` ("/address/city") and
51
+ * `message`; `context` is the request part that failed (Fastify validates
52
+ * params, body, querystring, headers in that order and stops at the first).
53
+ */
54
+ export function fieldsFromSchemaValidation(
55
+ validation: ReadonlyArray<{ instancePath?: string; message?: string }>,
56
+ context?: string,
57
+ ): FieldError[] {
58
+ return validation.slice(0, MAX_FIELD_ERRORS).map((item) => {
59
+ const path = (item.instancePath ?? '').split('/').filter(Boolean).join('.');
60
+ return { field: path || partName(context), message: item.message ?? 'Invalid value' };
61
+ });
62
+ }
63
+
64
+ /** The human summary: "Please check these fields: email, password". */
65
+ export function validationMessage(fields: ReadonlyArray<FieldError>): string {
66
+ const names = [...new Set(fields.map((f) => f.field))];
67
+ return names.length > 0 ? `Please check these fields: ${names.join(', ')}` : 'Validation failed';
68
+ }
69
+
70
+ /** The 422 error for these fields (thrown, or built by the global handler). */
71
+ export function validationError(fields: FieldError[]): ValidationError {
72
+ return new ValidationError(validationMessage(fields), VALIDATION_FAILED, fields);
73
+ }
74
+
75
+ /**
76
+ * Validate input inside a handler (when a route schema cannot express the
77
+ * rule, or for data that is not a request part). Returns the parsed value or
78
+ * throws the standard 422.
79
+ */
80
+ export function parseInput<S extends z.ZodType>(schema: S, data: unknown): z.output<S> {
81
+ const result = schema.safeParse(data);
82
+ if (!result.success) {
83
+ throw validationError(fieldsFromZodIssues(result.error.issues));
84
+ }
85
+ return result.data;
86
+ }
@@ -0,0 +1,255 @@
1
+ /**
2
+ * Administration against a real MySQL and Redis: what must stay true about
3
+ * admin powers (the layer 5 hardening).
4
+ * - The first admin is made with `make-admin <email>` (no password anywhere):
5
+ * it refuses unknown, deleted and banned accounts and verifies the email.
6
+ * - The last active admin cannot delete their own account; an admin cannot
7
+ * ban themselves or change their own role; demoting an admin ends their
8
+ * sessions.
9
+ * - An admin cannot block their own address or a private one; IP blocks use
10
+ * one canonical spelling (so a block matches however the address is
11
+ * written), a double block is 409, and the block is enforced.
12
+ * - Deleted accounts are listed with their purge date and can be restored
13
+ * within the 30 days; the purge removes the rest.
14
+ *
15
+ * The "last admin" tests run first and demote every other admin in this
16
+ * shared test database (files run one after another, earlier files are done
17
+ * with theirs).
18
+ */
19
+ import { spawnSync } from 'node:child_process';
20
+ import { createRequire } from 'node:module';
21
+ import path from 'node:path';
22
+ import { fileURLToPath } from 'node:url';
23
+ import { afterAll, beforeAll, describe, expect, it } from 'vitest';
24
+ import type { FastifyInstance } from 'fastify';
25
+ import {
26
+ PASSWORD,
27
+ buildTestApp,
28
+ call,
29
+ db,
30
+ image,
31
+ makeAdmin,
32
+ redis,
33
+ registerAdmin,
34
+ registerUser,
35
+ signIn,
36
+ uniqueEmail,
37
+ uploadAvatar,
38
+ type TestUser,
39
+ } from '@/test/integration-helpers.js';
40
+
41
+ const serverRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', '..', '..', '..');
42
+ const tsxCli = createRequire(import.meta.url).resolve('tsx/cli');
43
+
44
+ let app: FastifyInstance;
45
+ let admin: TestUser;
46
+
47
+ beforeAll(async () => {
48
+ app = await buildTestApp();
49
+ });
50
+
51
+ afterAll(async () => {
52
+ await app?.close();
53
+ });
54
+
55
+ const roleOf = async (id: string): Promise<{ role: string; verified: boolean } | null> => {
56
+ const row = await (await db()).user.findUnique({ where: { id }, select: { role: true, emailVerifiedAt: true } });
57
+ return row ? { role: row.role, verified: row.emailVerifiedAt !== null } : null;
58
+ };
59
+
60
+ describe('the last active admin', () => {
61
+ it('cannot delete their own account (409 LAST_ADMIN, after the password check); with a second admin they can', async () => {
62
+ const a = await registerAdmin(app, 'onlyadmin');
63
+ await (await db()).user.updateMany({ where: { role: 'ADMIN', id: { not: a.id } }, data: { role: 'USER' } });
64
+
65
+ const wrong = await call(app, 'DELETE', '/users/me', { jar: a.jar, payload: { password: 'Wrong-Passw0rd-1' } });
66
+ expect([wrong.status, wrong.code]).toEqual([422, 'INVALID_PASSWORD']);
67
+ const last = await call(app, 'DELETE', '/users/me', { jar: a.jar, payload: { password: PASSWORD } });
68
+ expect([last.status, last.code]).toEqual([409, 'LAST_ADMIN']);
69
+ expect((await (await db()).user.findUnique({ where: { id: a.id } }))?.deletedAt).toBeNull();
70
+
71
+ const b = await registerAdmin(app, 'secondadmin');
72
+ expect((await call(app, 'DELETE', '/users/me', { jar: a.jar, payload: { password: PASSWORD } })).status).toBe(200);
73
+ const c = await registerAdmin(app, 'thirdadmin');
74
+ expect((await call(app, 'DELETE', `/users/${c.id}`, { jar: b.jar })).status).toBe(200);
75
+ admin = b;
76
+ });
77
+ });
78
+
79
+ describe('make-admin', () => {
80
+ /** Runs the real script (src/scripts/make-admin.ts) against this test database. */
81
+ const makeAdminScript = (email: string): { code: number | null; out: string } => {
82
+ const r = spawnSync(process.execPath, [tsxCli, 'src/scripts/make-admin.ts', email], {
83
+ cwd: serverRoot,
84
+ env: process.env,
85
+ encoding: 'utf8',
86
+ timeout: 60_000,
87
+ });
88
+ return { code: r.status, out: `${r.stdout}${r.stderr}` };
89
+ };
90
+
91
+ it('promotes an existing account (email in any case), which works without signing in again; again → "already"', async () => {
92
+ const u = await registerUser(app, 'promote');
93
+ const r = makeAdminScript(u.email.toUpperCase());
94
+ expect(r.code).toBe(0);
95
+ expect(await roleOf(u.id)).toEqual({ role: 'ADMIN', verified: true });
96
+ expect((await call(app, 'GET', '/admin/stats', { jar: u.jar })).status).toBe(200);
97
+ const again = makeAdminScript(u.email);
98
+ expect(again.code).toBe(0);
99
+ expect(again.out).toMatch(/already an admin/);
100
+ });
101
+
102
+ it('refuses an unknown, a deleted and a banned account (exit 1, role unchanged); verifies an unverified one', async () => {
103
+ const outputs: string[] = [];
104
+ const unknown = makeAdminScript(uniqueEmail('nobody'));
105
+ outputs.push(unknown.out);
106
+ expect([unknown.code, /No account with that email/.test(unknown.out)]).toEqual([1, true]);
107
+
108
+ const del = await registerUser(app, 'mkdeleted');
109
+ await call(app, 'DELETE', '/users/me', { jar: del.jar, payload: { password: PASSWORD } });
110
+ const delR = makeAdminScript(del.email);
111
+ outputs.push(delR.out);
112
+ expect([delR.code, /deleted/.test(delR.out), (await roleOf(del.id))?.role]).toEqual([1, true, 'USER']);
113
+
114
+ const ban = await registerUser(app, 'mkbanned');
115
+ await call(app, 'PATCH', `/admin/users/${ban.id}/status`, { jar: admin.jar, payload: { isActive: false } });
116
+ const banR = makeAdminScript(ban.email);
117
+ outputs.push(banR.out);
118
+ expect([banR.code, /banned/.test(banR.out), (await roleOf(ban.id))?.role]).toEqual([1, true, 'USER']);
119
+
120
+ const unv = await registerUser(app, 'mkunverified');
121
+ await (await db()).user.update({ where: { id: unv.id }, data: { emailVerifiedAt: null } });
122
+ const unvR = makeAdminScript(unv.email);
123
+ outputs.push(unvR.out);
124
+ expect(unvR.code).toBe(0);
125
+ expect(await roleOf(unv.id)).toEqual({ role: 'ADMIN', verified: true });
126
+
127
+ // The output never carries the database URL or a password.
128
+ const all = outputs.join('\n');
129
+ expect(all).not.toMatch(/mysql:\/\//i);
130
+ expect(all).not.toContain(PASSWORD);
131
+ });
132
+ });
133
+
134
+ describe('admins cannot act on themselves', () => {
135
+ it('self-ban → 403 CANNOT_BAN_SELF and the admin still works; banning another user still works', async () => {
136
+ const self = await call(app, 'PATCH', `/admin/users/${admin.id}/status`, { jar: admin.jar, payload: { isActive: false } });
137
+ expect([self.status, self.code]).toEqual([403, 'CANNOT_BAN_SELF']);
138
+ expect((await call(app, 'GET', '/admin/stats', { jar: admin.jar })).status).toBe(200);
139
+ const v = await registerUser(app, 'banvictim');
140
+ expect((await call(app, 'PATCH', `/admin/users/${v.id}/status`, { jar: admin.jar, payload: { isActive: false } })).status).toBe(200);
141
+ const me = await call(app, 'GET', '/auth/me', { cookie: v.jar.header() });
142
+ expect([me.status, me.code]).toEqual([403, 'ACCOUNT_DEACTIVATED']);
143
+ });
144
+
145
+ it('self role change → 403; demoting another admin ends their sessions', async () => {
146
+ expect((await call(app, 'PATCH', `/admin/users/${admin.id}/role`, { jar: admin.jar, payload: { role: 'USER' } })).status).toBe(403);
147
+ const other = await registerAdmin(app, 'demoted');
148
+ const otherDevice = await signIn(app, other.email);
149
+ expect((await call(app, 'PATCH', `/admin/users/${other.id}/role`, { jar: admin.jar, payload: { role: 'USER' } })).status).toBe(200);
150
+ expect((await call(app, 'GET', '/auth/me', { cookie: otherDevice.header() })).status).toBe(401);
151
+ });
152
+ });
153
+
154
+ describe('IP blocks', () => {
155
+ const blocked = async (ip: string): Promise<boolean> => (await (await redis()).sismember('blocked_ips', ip)) === 1;
156
+
157
+ it('your own address → 422 CANNOT_BLOCK_OWN_IP; private and reserved addresses → 422 IP_NOT_BLOCKABLE', async () => {
158
+ const own = (await call(app, 'GET', '/admin/client-ip', { jar: admin.jar })).body?.data?.ip as string;
159
+ const self = await call(app, 'POST', '/admin/blocked-ips', { jar: admin.jar, payload: { ip: own } });
160
+ expect([self.status, self.code]).toEqual([422, 'CANNOT_BLOCK_OWN_IP']);
161
+ for (const ip of ['10.0.0.5', '192.168.1.1', '::1']) {
162
+ const r = await call(app, 'POST', '/admin/blocked-ips', { jar: admin.jar, payload: { ip } });
163
+ expect([ip, r.status, r.code]).toEqual([ip, 422, 'IP_NOT_BLOCKABLE']);
164
+ }
165
+ });
166
+
167
+ it('one canonical spelling: stored and in Redis as 2001:db8::1; another spelling → 409; mapped IPv4 → plain IPv4', async () => {
168
+ const r = await call(app, 'POST', '/admin/blocked-ips', { jar: admin.jar, payload: { ip: '2001:0DB8:0000::0001' } });
169
+ expect([r.status, r.body?.data?.ip]).toEqual([201, '2001:db8::1']);
170
+ expect((await (await db()).blockedIp.findMany({ where: { ip: { startsWith: '2001:' } } })).map((b) => b.ip)).toContain('2001:db8::1');
171
+ expect(await blocked('2001:db8::1')).toBe(true);
172
+ const dup = await call(app, 'POST', '/admin/blocked-ips', { jar: admin.jar, payload: { ip: '2001:db8::1' } });
173
+ expect([dup.status, dup.code]).toEqual([409, 'IP_ALREADY_BLOCKED']);
174
+ const mapped = await call(app, 'POST', '/admin/blocked-ips', { jar: admin.jar, payload: { ip: '::ffff:203.0.113.7' } });
175
+ expect([mapped.status, mapped.body?.data?.ip]).toEqual([201, '203.0.113.7']);
176
+
177
+ const un = await call(app, 'DELETE', `/admin/blocked-ips/${encodeURIComponent('2001:DB8::1')}`, { jar: admin.jar });
178
+ expect(un.status).toBe(200);
179
+ expect(await (await db()).blockedIp.count({ where: { ip: '2001:db8::1' } })).toBe(0);
180
+ expect(await blocked('2001:db8::1')).toBe(false);
181
+ expect((await call(app, 'DELETE', '/admin/blocked-ips/not-an-ip', { jar: admin.jar })).status).toBe(422);
182
+ await call(app, 'DELETE', '/admin/blocked-ips/203.0.113.7', { jar: admin.jar });
183
+ });
184
+
185
+ it('two identical blocks at once → one 201 and one 409, never 500', async () => {
186
+ const both = await Promise.all([0, 1].map(() => call(app, 'POST', '/admin/blocked-ips', { jar: admin.jar, payload: { ip: '203.0.113.50' } })));
187
+ expect(both.map((b) => b.status).sort()).toEqual([201, 409]);
188
+ await call(app, 'DELETE', '/admin/blocked-ips/203.0.113.50', { jar: admin.jar });
189
+ });
190
+
191
+ it('a block typed one way stops the same address written another way (403 IP_BLOCKED); a neighbour is not blocked', async () => {
192
+ await call(app, 'POST', '/admin/blocked-ips', { jar: admin.jar, payload: { ip: '2001:0db8::abcd' } });
193
+ // app.inject comes from 127.0.0.1, a trusted proxy hop, so X-Forwarded-For is believed.
194
+ const hit = await call(app, 'GET', '/auth/me', { headers: { 'x-forwarded-for': '2001:db8:0:0:0:0:0:abcd' } });
195
+ expect([hit.status, hit.code]).toEqual([403, 'IP_BLOCKED']);
196
+ const neighbour = await call(app, 'GET', '/auth/me', { headers: { 'x-forwarded-for': '2001:db8::abce' } });
197
+ expect(neighbour.status).toBe(401);
198
+ await call(app, 'DELETE', `/admin/blocked-ips/${encodeURIComponent('2001:db8::abcd')}`, { jar: admin.jar });
199
+ });
200
+ });
201
+
202
+ describe('deleted accounts: list, restore, purge', () => {
203
+ let x: TestUser;
204
+
205
+ it('?deleted=true lists a deleted account with purgeAt = deletedAt + 30 days; the default list does not', async () => {
206
+ x = await registerUser(app, 'restorable');
207
+ await uploadAvatar(app, x.jar, await image('png'));
208
+ await call(app, 'DELETE', '/users/me', { jar: x.jar, payload: { password: PASSWORD } });
209
+ const deleted = await call(app, 'GET', `/admin/users?deleted=true&search=${encodeURIComponent(x.email)}`, { jar: admin.jar });
210
+ const item = deleted.body?.data?.items?.[0];
211
+ expect(item?.id).toBe(x.id);
212
+ expect((new Date(item.purgeAt).getTime() - new Date(item.deletedAt).getTime()) / 86_400_000).toBe(30);
213
+ const live = await call(app, 'GET', `/admin/users?search=${encodeURIComponent(x.email)}`, { jar: admin.jar });
214
+ expect(live.body?.data?.items).toHaveLength(0);
215
+ });
216
+
217
+ it('restore → 200 (active, no avatar); the user signs in with the old password; again → 409, unknown → 404, non-admin → 403', async () => {
218
+ const restore = await call(app, 'POST', `/admin/users/${x.id}/restore`, { jar: admin.jar });
219
+ expect(restore.status).toBe(200);
220
+ expect(restore.body?.data).toMatchObject({ deletedAt: null, isActive: true, avatarUrl: null });
221
+ const userJar = await signIn(app, x.email);
222
+ const again = await call(app, 'POST', `/admin/users/${x.id}/restore`, { jar: admin.jar });
223
+ expect([again.status, again.code]).toEqual([409, 'USER_NOT_DELETED']);
224
+ const unknown = await call(app, 'POST', '/admin/users/00000000-0000-4000-8000-000000000000/restore', { jar: admin.jar });
225
+ expect([unknown.status, unknown.code]).toEqual([404, 'USER_NOT_FOUND']);
226
+ expect((await call(app, 'POST', `/admin/users/${x.id}/restore`, { jar: userJar })).status).toBe(403);
227
+ });
228
+
229
+ it('the purge removes an account deleted 31 days ago (restore then 404); the restored account stays', async () => {
230
+ const y = await registerUser(app, 'purged');
231
+ await call(app, 'DELETE', '/users/me', { jar: y.jar, payload: { password: PASSWORD } });
232
+ await (await db()).user.update({ where: { id: y.id }, data: { deletedAt: new Date(Date.now() - 31 * 86_400_000) } });
233
+ const { purgeDeletedAccounts } = await import('@jobs/cleanup-deleted-accounts.job.js');
234
+ await purgeDeletedAccounts();
235
+ expect(await (await db()).user.count({ where: { id: y.id } })).toBe(0);
236
+ expect((await call(app, 'POST', `/admin/users/${y.id}/restore`, { jar: admin.jar })).status).toBe(404);
237
+ expect((await (await db()).user.findUnique({ where: { id: x.id } }))?.deletedAt).toBeNull();
238
+ });
239
+
240
+ it('user detail has lastActiveAt and no lastLogin', async () => {
241
+ const d = await call(app, 'GET', `/admin/users/${x.id}`, { jar: admin.jar });
242
+ expect(d.status).toBe(200);
243
+ expect(d.body?.data).toHaveProperty('lastActiveAt');
244
+ expect(d.body?.data).not.toHaveProperty('lastLogin');
245
+ });
246
+ });
247
+
248
+ describe('makeAdmin helper sanity', () => {
249
+ it('a promoted account reaches the admin API at once (the role is read on every request)', async () => {
250
+ const u = await registerUser(app, 'helper');
251
+ expect((await call(app, 'GET', '/admin/stats', { jar: u.jar })).status).toBe(403);
252
+ await makeAdmin(u.id);
253
+ expect((await call(app, 'GET', '/admin/stats', { jar: u.jar })).status).toBe(200);
254
+ });
255
+ });