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,82 @@
1
+ import { describe, it, expect } from 'vitest';
2
+ import type { Event } from '@sentry/node';
3
+ import { scrubSentryEvent } from '../observability/sentry.js';
4
+
5
+ // Error events must never carry passwords, tokens or cookies to Sentry.
6
+
7
+ describe('scrubSentryEvent', () => {
8
+ it('removes request body, cookies, auth headers and query strings', () => {
9
+ const event: Event = {
10
+ request: {
11
+ url: 'https://api.example.test/api/v1/auth/reset-password?token=secret-reset-token',
12
+ method: 'POST',
13
+ data: '{"email":"a@example.test","password":"Plaintext-Passw0rd"}',
14
+ cookies: { access_token: 'jwt-value', refresh_token: 'refresh-value' },
15
+ query_string: 'token=secret-reset-token',
16
+ headers: {
17
+ Cookie: 'access_token=jwt-value; refresh_token=refresh-value',
18
+ authorization: 'Bearer jwt-value',
19
+ 'X-Origin-Verify': 'origin-secret-value',
20
+ 'user-agent': 'vitest',
21
+ },
22
+ },
23
+ breadcrumbs: [
24
+ { category: 'http', data: { url: 'https://x.test/verify-account?token=abc', 'http.query': 'token=abc' } },
25
+ ],
26
+ };
27
+
28
+ const scrubbed = scrubSentryEvent(event);
29
+ const serialized = JSON.stringify(scrubbed);
30
+
31
+ expect(serialized).not.toContain('Plaintext-Passw0rd');
32
+ expect(serialized).not.toContain('jwt-value');
33
+ expect(serialized).not.toContain('refresh-value');
34
+ expect(serialized).not.toContain('origin-secret-value');
35
+ expect(serialized).not.toContain('secret-reset-token');
36
+ expect(serialized).not.toContain('token=abc');
37
+ // Useful, non-secret context survives
38
+ expect(scrubbed.request?.method).toBe('POST');
39
+ expect(scrubbed.request?.url).toBe('https://api.example.test/api/v1/auth/reset-password');
40
+ expect(scrubbed.request?.headers?.['user-agent']).toBe('vitest');
41
+ });
42
+
43
+ it('strips tokens from the Referer header, trace data, span attributes and the transaction name', () => {
44
+ // The browser SDK copies the page URL and the Referer into request headers
45
+ // and span/trace attributes; reset/verify pages carry ?token=… there.
46
+ const event: Event = {
47
+ transaction: '/verify-account?token=txn-secret',
48
+ request: { headers: { Referer: 'https://app.example.test/reset-password?token=referer-secret' } },
49
+ contexts: {
50
+ trace: {
51
+ trace_id: 't',
52
+ span_id: 's',
53
+ data: {
54
+ 'url.full': 'https://app.example.test/reset-password?token=trace-secret',
55
+ 'http.request.header.referer': 'https://app.example.test/verify-account?token=trace-ref-secret',
56
+ 'http.query': 'token=trace-query-secret',
57
+ },
58
+ },
59
+ },
60
+ spans: [
61
+ {
62
+ span_id: 'x',
63
+ trace_id: 't',
64
+ start_timestamp: 0,
65
+ data: { 'http.request.header.referer': 'https://app.example.test/x?token=span-secret' },
66
+ },
67
+ ],
68
+ };
69
+
70
+ const serialized = JSON.stringify(scrubSentryEvent(event));
71
+
72
+ for (const secret of ['txn-secret', 'referer-secret', 'trace-secret', 'trace-ref-secret', 'trace-query-secret', 'span-secret']) {
73
+ expect(serialized).not.toContain(secret);
74
+ }
75
+ expect(serialized).toContain('https://app.example.test/reset-password');
76
+ });
77
+
78
+ it('leaves an event without request data untouched', () => {
79
+ const event: Event = { message: 'boom' };
80
+ expect(scrubSentryEvent(event)).toEqual({ message: 'boom' });
81
+ });
82
+ });
@@ -0,0 +1,89 @@
1
+ /**
2
+ * createShutdown (../shutdown.ts): exit 0 only after a signal and a clean
3
+ * close, 1 after a crash, a failed start or a failed close, one close no matter
4
+ * how often it is called, and the 8 s deadline.
5
+ */
6
+ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
7
+ import { createShutdown, SHUTDOWN_DEADLINE_MS, type ShutdownReason } from '../shutdown.js';
8
+
9
+ const logger = { info: vi.fn(), error: vi.fn(), fatal: vi.fn() };
10
+ const exit = vi.fn();
11
+
12
+ beforeEach(() => {
13
+ vi.clearAllMocks();
14
+ vi.useFakeTimers();
15
+ });
16
+ afterEach(() => vi.useRealTimers());
17
+
18
+ describe('exit codes', () => {
19
+ it.each(['SIGTERM', 'SIGINT'] as const)('%s with a clean close exits 0', async (reason) => {
20
+ const close = vi.fn().mockResolvedValue(undefined);
21
+ await createShutdown({ close, exit, logger })(reason);
22
+ expect(close).toHaveBeenCalledTimes(1);
23
+ expect(exit).toHaveBeenCalledExactlyOnceWith(0);
24
+ expect(logger.info).toHaveBeenCalledWith(`[SERVER] Received ${reason} - shutting down gracefully`);
25
+ expect(logger.info).toHaveBeenCalledWith('[SERVER] Shutdown complete');
26
+ });
27
+
28
+ it.each(['uncaughtException', 'unhandledRejection', 'startup-error'] as const)(
29
+ '%s exits 1 even though the close went fine',
30
+ async (reason) => {
31
+ const close = vi.fn().mockResolvedValue(undefined);
32
+ await createShutdown({ close, exit, logger })(reason);
33
+ expect(close).toHaveBeenCalledTimes(1);
34
+ expect(exit).toHaveBeenCalledExactlyOnceWith(1);
35
+ },
36
+ );
37
+
38
+ it('a close that throws exits 1 and logs the error under err', async () => {
39
+ const failure = new Error('redis quit failed');
40
+ await createShutdown({ close: vi.fn().mockRejectedValue(failure), exit, logger })('SIGTERM');
41
+ expect(exit).toHaveBeenCalledExactlyOnceWith(1);
42
+ expect(logger.error).toHaveBeenCalledWith({ err: failure }, '[SERVER] Error during shutdown');
43
+ });
44
+ });
45
+
46
+ describe('only one shutdown', () => {
47
+ it('a second signal starts no second close and no second exit', async () => {
48
+ const close = vi.fn().mockResolvedValue(undefined);
49
+ const shutdown = createShutdown({ close, exit, logger });
50
+ await Promise.all([shutdown('SIGTERM'), shutdown('SIGINT'), shutdown('SIGTERM')]);
51
+ expect(close).toHaveBeenCalledTimes(1);
52
+ expect(exit).toHaveBeenCalledExactlyOnceWith(0);
53
+ });
54
+
55
+ it('a crash while a signal shutdown is closing still makes the exit code 1', async () => {
56
+ let finishClose!: () => void;
57
+ const close = vi.fn(() => new Promise<void>((resolve) => (finishClose = resolve)));
58
+ const shutdown = createShutdown({ close, exit, logger });
59
+ const closing = shutdown('SIGTERM');
60
+ await shutdown('uncaughtException' satisfies ShutdownReason);
61
+ finishClose();
62
+ await closing;
63
+ expect(close).toHaveBeenCalledTimes(1);
64
+ expect(exit).toHaveBeenCalledExactlyOnceWith(1);
65
+ });
66
+ });
67
+
68
+ describe('deadline', () => {
69
+ it('a close that hangs is cut off at 8 s with a fatal line and exit 1', async () => {
70
+ const close = vi.fn(() => new Promise<void>(() => {}));
71
+ void createShutdown({ close, exit, logger })('SIGTERM');
72
+ vi.advanceTimersByTime(SHUTDOWN_DEADLINE_MS - 1);
73
+ expect(exit).not.toHaveBeenCalled();
74
+ vi.advanceTimersByTime(1);
75
+ expect(logger.fatal).toHaveBeenCalledWith('[SERVER] Shutdown did not finish within 8s; exiting');
76
+ expect(exit).toHaveBeenCalledExactlyOnceWith(1);
77
+ });
78
+
79
+ it('8 s fits inside Docker’s default 10 s stop timeout', () => {
80
+ expect(SHUTDOWN_DEADLINE_MS).toBe(8_000);
81
+ });
82
+
83
+ it('a close that finishes in time cancels the deadline', async () => {
84
+ await createShutdown({ close: vi.fn().mockResolvedValue(undefined), exit, logger, deadlineMs: 50 })('SIGTERM');
85
+ vi.advanceTimersByTime(1_000);
86
+ expect(logger.fatal).not.toHaveBeenCalled();
87
+ expect(exit).toHaveBeenCalledExactlyOnceWith(0);
88
+ });
89
+ });
@@ -1,80 +1,130 @@
1
- import { describe, it, expect } from 'vitest';
2
- import { redactUrl, isPrivateOrReservedIp } from '../url-safety.js';
3
-
4
- describe('redactUrl', () => {
5
- it('redacts a Telegram bot token in the API path', () => {
6
- expect(redactUrl('https://api.telegram.org/bot123456:AAHsecret/getFile')).toBe(
7
- 'https://api.telegram.org/bot<redacted>/getFile',
8
- );
9
- });
10
-
11
- it('redacts a Telegram bot token in the file-download path', () => {
12
- expect(redactUrl('https://api.telegram.org/file/bot123456:AAHsecret/photos/file_1.jpg')).toBe(
13
- 'https://api.telegram.org/file/bot<redacted>/photos/file_1.jpg',
14
- );
15
- });
16
-
17
- it('strips the query string (may carry signed media tokens)', () => {
18
- expect(redactUrl('https://lookaside.fbsbx.com/media?asset_id=1&token=SECRET')).toBe(
19
- 'https://lookaside.fbsbx.com/media',
20
- );
21
- });
22
-
23
- it('strips a fragment as well', () => {
24
- expect(redactUrl('https://cdn.example.com/x.jpg#frag')).toBe('https://cdn.example.com/x.jpg');
25
- });
26
-
27
- it('leaves a normal URL unchanged', () => {
28
- expect(redactUrl('https://scontent.xx.fbcdn.net/v/photo.jpg')).toBe(
29
- 'https://scontent.xx.fbcdn.net/v/photo.jpg',
30
- );
31
- });
32
-
33
- it('returns empty / non-string input as-is without throwing', () => {
34
- expect(redactUrl('')).toBe('');
35
- });
36
- });
37
-
38
- describe('isPrivateOrReservedIp', () => {
39
- it.each([
40
- '0.0.0.0',
41
- '127.0.0.1',
42
- '10.0.0.5',
43
- '172.16.0.1',
44
- '172.31.255.254',
45
- '192.168.1.1',
46
- '169.254.169.254',
47
- '100.64.0.1',
48
- '100.127.255.255',
49
- '::1',
50
- '::',
51
- 'fc00::1',
52
- 'fd12:3456:789a::1',
53
- 'fe80::abcd',
54
- '::ffff:10.0.0.5',
55
- '::ffff:127.0.0.1',
56
- ])('blocks internal/reserved address %s', (addr) => {
57
- expect(isPrivateOrReservedIp(addr)).toBe(true);
58
- });
59
-
60
- it.each([
61
- '93.184.216.34',
62
- '8.8.8.8',
63
- '1.1.1.1',
64
- '172.32.0.1', // just outside 172.16/12
65
- '172.15.0.1', // just below 172.16/12
66
- '192.169.0.1', // not 192.168
67
- '100.63.255.255', // just below CGNAT
68
- '100.128.0.0', // just above CGNAT
69
- '2606:4700:4700::1111', // Cloudflare public IPv6
70
- '::ffff:93.184.216.34', // IPv4-mapped public
71
- ])('allows public address %s', (addr) => {
72
- expect(isPrivateOrReservedIp(addr)).toBe(false);
73
- });
74
-
75
- it('fails closed (blocks) on malformed input', () => {
76
- expect(isPrivateOrReservedIp('not-an-ip')).toBe(true);
77
- expect(isPrivateOrReservedIp('999.999.999.999')).toBe(true);
78
- expect(isPrivateOrReservedIp('')).toBe(true);
79
- });
80
- });
1
+ import { describe, it, expect } from 'vitest';
2
+ import { redactUrl, isPrivateOrReservedIp, isForbiddenOutboundIp } from '../url-safety.js';
3
+
4
+ describe('redactUrl', () => {
5
+ it('redacts a Telegram bot token in the API path', () => {
6
+ expect(redactUrl('https://api.telegram.org/bot123456:AAHsecret/getFile')).toBe(
7
+ 'https://api.telegram.org/bot<redacted>/getFile',
8
+ );
9
+ });
10
+
11
+ it('redacts a Telegram bot token in the file-download path', () => {
12
+ expect(redactUrl('https://api.telegram.org/file/bot123456:AAHsecret/photos/file_1.jpg')).toBe(
13
+ 'https://api.telegram.org/file/bot<redacted>/photos/file_1.jpg',
14
+ );
15
+ });
16
+
17
+ it('strips the query string (may carry signed media tokens)', () => {
18
+ expect(redactUrl('https://lookaside.fbsbx.com/media?asset_id=1&token=SECRET')).toBe(
19
+ 'https://lookaside.fbsbx.com/media',
20
+ );
21
+ });
22
+
23
+ it('strips a fragment as well', () => {
24
+ expect(redactUrl('https://cdn.example.com/x.jpg#frag')).toBe('https://cdn.example.com/x.jpg');
25
+ });
26
+
27
+ it('strips credentials from the authority', () => {
28
+ expect(redactUrl('https://user:pa55@api.example.com/v1/x')).toBe('https://api.example.com/v1/x');
29
+ expect(redactUrl('http://token@example.com/')).toBe('http://example.com/');
30
+ });
31
+
32
+ it('leaves a normal URL unchanged', () => {
33
+ expect(redactUrl('https://scontent.xx.fbcdn.net/v/photo.jpg')).toBe(
34
+ 'https://scontent.xx.fbcdn.net/v/photo.jpg',
35
+ );
36
+ });
37
+
38
+ it('returns empty / non-string input as-is without throwing', () => {
39
+ expect(redactUrl('')).toBe('');
40
+ });
41
+ });
42
+
43
+ describe('isPrivateOrReservedIp', () => {
44
+ it.each([
45
+ '0.0.0.0',
46
+ '127.0.0.1',
47
+ '10.0.0.5',
48
+ '172.16.0.1',
49
+ '172.31.255.254',
50
+ '192.168.1.1',
51
+ '169.254.169.254',
52
+ '100.64.0.1',
53
+ '100.127.255.255',
54
+ '::1',
55
+ '::',
56
+ 'fc00::1',
57
+ 'fd12:3456:789a::1',
58
+ 'fe80::abcd',
59
+ '::ffff:10.0.0.5',
60
+ '::ffff:127.0.0.1',
61
+ ])('blocks internal/reserved address %s', (addr) => {
62
+ expect(isPrivateOrReservedIp(addr)).toBe(true);
63
+ });
64
+
65
+ it.each([
66
+ '93.184.216.34',
67
+ '8.8.8.8',
68
+ '1.1.1.1',
69
+ '172.32.0.1', // just outside 172.16/12
70
+ '172.15.0.1', // just below 172.16/12
71
+ '192.169.0.1', // not 192.168
72
+ '100.63.255.255', // just below CGNAT
73
+ '100.128.0.0', // just above CGNAT
74
+ '2606:4700:4700::1111', // Cloudflare public IPv6
75
+ '::ffff:93.184.216.34', // IPv4-mapped public
76
+ ])('allows public address %s', (addr) => {
77
+ expect(isPrivateOrReservedIp(addr)).toBe(false);
78
+ });
79
+
80
+ it('fails closed (blocks) on malformed input', () => {
81
+ expect(isPrivateOrReservedIp('not-an-ip')).toBe(true);
82
+ expect(isPrivateOrReservedIp('999.999.999.999')).toBe(true);
83
+ expect(isPrivateOrReservedIp('')).toBe(true);
84
+ });
85
+ });
86
+
87
+ describe('isPrivateOrReservedIp — every spelling of an internal address', () => {
88
+ it.each([
89
+ ['::ffff:7f00:1', '127.0.0.1 as hex IPv4-mapped'],
90
+ ['::ffff:a00:5', '10.0.0.5 as hex IPv4-mapped'],
91
+ ['[::1]', 'bracketed IPv6 (URL form)'],
92
+ ['FE80::1%ETH0', 'link-local with a zone id'],
93
+ ])('blocks %s (%s)', (addr) => {
94
+ expect(isPrivateOrReservedIp(addr)).toBe(true);
95
+ });
96
+
97
+ it.each(['203.0.113.7', '198.51.100.9', '2001:db8::1', '224.0.0.1'])(
98
+ 'does not call the documentation/multicast address %s internal (IP blocks may target it)',
99
+ (addr) => {
100
+ expect(isPrivateOrReservedIp(addr)).toBe(false);
101
+ },
102
+ );
103
+ });
104
+
105
+ describe('isForbiddenOutboundIp — only public unicast is a valid destination', () => {
106
+ it.each([
107
+ '127.0.0.1', '10.0.0.5', '169.254.169.254', '::1', '::ffff:7f00:1', '::ffff:a00:5',
108
+ '64:ff9b::a00:5', // NAT64 to 10.0.0.5
109
+ '2002:a00:5::1', // 6to4 embedding 10.0.0.5
110
+ '224.0.0.1', '240.0.0.1', '255.255.255.255', '198.18.0.1', '192.0.0.1',
111
+ '192.0.2.1', '198.51.100.1', '203.0.113.1', '2001:db8::1',
112
+ 'ff02::1', 'fec0::1', '100::1', '2001::1',
113
+ ])('forbids %s', (addr) => {
114
+ expect(isForbiddenOutboundIp(addr)).toBe(true);
115
+ });
116
+
117
+ it.each(['93.184.216.34', '8.8.8.8', '1.1.1.1', '2606:4700:4700::1111', '::ffff:93.184.216.34'])(
118
+ 'allows the public address %s',
119
+ (addr) => {
120
+ expect(isForbiddenOutboundIp(addr)).toBe(false);
121
+ },
122
+ );
123
+
124
+ it('fails closed on anything that is not an IP', () => {
125
+ for (const addr of ['', 'not-an-ip', '999.999.999.999', 'example.com']) {
126
+ expect(isForbiddenOutboundIp(addr)).toBe(true);
127
+ }
128
+ });
129
+ });
130
+
@@ -0,0 +1,52 @@
1
+ /**
2
+ * Account status rules: one place that decides whether an existing, non-deleted
3
+ * account may hold a session.
4
+ *
5
+ * Two independent states, deliberately kept apart:
6
+ * - `isActive` — the admin ban switch. false = deactivated by an admin.
7
+ * - `emailVerifiedAt` — proof of email ownership. Required only while
8
+ * REQUIRE_USER_VERIFICATION is on.
9
+ *
10
+ * They used to share one flag (`isActive=false` meant "banned" OR "not
11
+ * verified yet"), which let a banned user re-activate themselves through the
12
+ * email-verification link. Every place that issues or honours a session
13
+ * (login, refresh, authenticate, verify-account) calls this helper so the rule
14
+ * cannot drift between them.
15
+ *
16
+ * Callers must run it only AFTER the user has proven who they are (password,
17
+ * valid token or refresh token): the distinct error codes would otherwise tell
18
+ * an anonymous caller whether an email is banned or unverified.
19
+ */
20
+
21
+ import { env } from '@config/env.js';
22
+ import { ForbiddenError } from '@shared/errors/errors.js';
23
+
24
+ export const ACCOUNT_DEACTIVATED = 'ACCOUNT_DEACTIVATED';
25
+ export const EMAIL_NOT_VERIFIED = 'EMAIL_NOT_VERIFIED';
26
+
27
+ export interface AccountStatus {
28
+ isActive: boolean;
29
+ emailVerifiedAt: Date | null;
30
+ }
31
+
32
+ /** True when the account still needs to verify its email before signing in. */
33
+ export function needsEmailVerification(user: Pick<AccountStatus, 'emailVerifiedAt'>): boolean {
34
+ return env.REQUIRE_USER_VERIFICATION && !user.emailVerifiedAt;
35
+ }
36
+
37
+ /**
38
+ * Throw a 403 when the account may not hold a session.
39
+ * The ban check runs first: a banned account must never be told to "verify",
40
+ * because verifying cannot (and must not) lift a ban.
41
+ */
42
+ export function assertAccountCanSignIn(user: AccountStatus): void {
43
+ if (!user.isActive) {
44
+ throw new ForbiddenError(
45
+ 'This account has been deactivated. Contact support if you think this is a mistake.',
46
+ ACCOUNT_DEACTIVATED,
47
+ );
48
+ }
49
+ if (needsEmailVerification(user)) {
50
+ throw new ForbiddenError('Please verify your email address before signing in.', EMAIL_NOT_VERIFIED);
51
+ }
52
+ }
@@ -4,6 +4,7 @@ import { env } from '@config/env.js';
4
4
  import { prisma } from '@libs/prisma.js';
5
5
  import { UnauthorizedError, ForbiddenError, BadRequestError } from '@shared/errors/errors.js';
6
6
  import { clearAuthCookies } from '@libs/cookies.js';
7
+ import { assertAccountCanSignIn } from '@libs/account-status.js';
7
8
  import { parseDurationMs } from '@libs/duration.js';
8
9
  import type { JwtPayload, UserRole } from '@shared/types/index.js';
9
10
 
@@ -27,7 +28,7 @@ function getApp(): FastifyInstance {
27
28
 
28
29
  export function signAccessToken(payload: JwtPayload): string {
29
30
  return getApp().jwt.sign(
30
- { userId: payload.userId, role: payload.role },
31
+ { userId: payload.userId, role: payload.role, sessionId: payload.sessionId },
31
32
  { expiresIn: env.JWT_ACCESS_EXPIRY },
32
33
  );
33
34
  }
@@ -51,26 +52,64 @@ export async function authenticate(
51
52
  throw new UnauthorizedError('Invalid or expired token');
52
53
  }
53
54
 
54
- // Verify user still exists, is active, and not soft-deleted.
55
- // When the session is definitively dead (user gone/deleted/inactive), clear auth
56
- // cookies on the response so the browser stops replaying stale credentials.
57
- // Without this, middleware keeps seeing the (still-unexpired) JWT cookie and
58
- // bounces /login → /dashboard → 401 → /login in an infinite loop.
59
- const user = await prisma.user.findUnique({
60
- where: { id: request.user.userId },
61
- select: { isActive: true, deletedAt: true },
62
- });
55
+ // The token is only as alive as its login session: one query fetches the
56
+ // session (must exist, belong to this user and be unexpired) together with
57
+ // the account state. A session ended by logout, logout-all, a password
58
+ // change or reset, or an admin revoke therefore stops this token at once,
59
+ // not when its 15 minutes run out. A token without a session id (signed
60
+ // before tokens carried one) is refused the same way; the client refreshes.
61
+ //
62
+ // When the session or account is definitively dead, clear auth cookies on
63
+ // the response so the browser stops replaying stale credentials. Without
64
+ // this, middleware keeps seeing the (still-unexpired) JWT cookie and bounces
65
+ // /login → /dashboard → 401 → /login in an infinite loop.
66
+ const { userId, sessionId } = request.user;
67
+ const session =
68
+ typeof sessionId === 'string' && sessionId
69
+ ? await prisma.session.findFirst({
70
+ where: { id: sessionId, userId, expiresAt: { gt: new Date() } },
71
+ select: { user: { select: { isActive: true, emailVerifiedAt: true, deletedAt: true, role: true } } },
72
+ })
73
+ : null;
74
+ if (!session) {
75
+ clearAuthCookies(reply);
76
+ // A ban deletes every session of the account (admin.service toggleUserStatus),
77
+ // so a banned user's still-unexpired token lands here. Say so, as before
78
+ // tokens were bound to sessions: 403 ACCOUNT_DEACTIVATED lets the app explain
79
+ // why, instead of a bare "session ended". One extra query, on this path only.
80
+ const account = await prisma.user.findUnique({
81
+ where: { id: userId },
82
+ select: { isActive: true, emailVerifiedAt: true, deletedAt: true },
83
+ });
84
+ if (account && !account.deletedAt) assertAccountCanSignIn(account);
85
+ throw new UnauthorizedError('Session ended', 'SESSION_EXPIRED');
86
+ }
87
+ const { user } = session;
63
88
 
64
89
  if (!user || user.deletedAt) {
65
90
  clearAuthCookies(reply);
66
91
  throw new UnauthorizedError('Account is deactivated or deleted');
67
92
  }
68
- if (!user.isActive) {
93
+ try {
94
+ assertAccountCanSignIn(user);
95
+ } catch (error) {
69
96
  clearAuthCookies(reply);
70
- throw new ForbiddenError('Account is not activated. Please verify your account.', 'ACCOUNT_NOT_ACTIVE');
97
+ throw error;
71
98
  }
99
+
100
+ // The role decides authorization, so take it from the database, not from the
101
+ // token. A JWT keeps the role it was signed with until it expires (15 min by
102
+ // default); trusting it let a demoted admin keep admin rights for that window.
103
+ // Same query as above, so this costs nothing extra. authorize() and
104
+ // resolveTargetUser() read request.user.role after this runs.
105
+ request.user.role = user.role;
72
106
  }
73
107
 
108
+ /**
109
+ * Verifies the token's signature ONLY: no session, ban or deletion check. Use
110
+ * it to personalise public responses, never to authorize anything (use
111
+ * authenticate for that).
112
+ */
74
113
  export async function optionalAuth(
75
114
  request: FastifyRequest,
76
115
  _reply: FastifyReply,