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
@@ -2,89 +2,105 @@
2
2
  * Cleanup Deleted Accounts Job
3
3
  *
4
4
  * Permanently purges soft-deleted user accounts after a 30-day retention period.
5
- * Deletes all user media from disk and hard-deletes the user record (cascades to
6
- * refresh tokens and sessions via onDelete: Cascade).
5
+ * Deletes all of the user's media from disk first (public AND private tier),
6
+ * then hard-deletes the user record (cascades to refresh tokens and sessions;
7
+ * IP blocks the user created as an admin are kept, with blockedBy set to NULL).
7
8
  *
8
- * Runs once daily.
9
+ * Files first, row last: while the row exists, the account is found again by
10
+ * the next run, so a failed file deletion is simply retried. The old order
11
+ * (row first) left files no run could ever find again, a public avatar
12
+ * included. (The public avatar is normally gone already: deleting the account
13
+ * removes it at once, see usersService.deleteAccount.)
14
+ *
15
+ * Runs about a minute after start, then once a day (jobs/schedule.ts): a
16
+ * deploy or restart never pushes the purge back by another day.
17
+ * `purgeDeletedAccounts()` is exported so it can also be run on demand (tests,
18
+ * an operator script) without waiting for the schedule.
9
19
  */
10
20
 
11
21
  import type { FastifyInstance } from 'fastify';
12
- import { prisma } from '@libs/prisma.js';
22
+ import { prisma, isPrismaNotFound } from '@libs/prisma.js';
13
23
  import { logger } from '@libs/logger.js';
14
24
  import { fileStorageService } from '@libs/storage/file-storage.service.js';
25
+ import { startRecurringJob } from './schedule.js';
15
26
 
16
27
  const INTERVAL_MS = 24 * 60 * 60 * 1000; // 24 hours
17
- const RETENTION_DAYS = 30;
18
-
19
- export function startCleanupDeletedAccountsJob(app: FastifyInstance): void {
20
- const intervalId = setInterval(async () => {
21
- try {
22
- const cutoffDate = new Date();
23
- cutoffDate.setDate(cutoffDate.getDate() - RETENTION_DAYS);
28
+ const FIRST_RUN_DELAY_MS = 60 * 1000;
29
+ /** Days a soft-deleted account is kept (restorable by an admin) before the purge. */
30
+ export const RETENTION_DAYS = 30;
24
31
 
25
- // Find users soft-deleted more than 30 days ago
26
- const usersToDelete = await prisma.user.findMany({
27
- where: {
28
- deletedAt: {
29
- not: null,
30
- lt: cutoffDate,
31
- },
32
- },
33
- select: {
34
- id: true,
35
- },
36
- });
37
-
38
- if (usersToDelete.length === 0) {
39
- return;
40
- }
32
+ export interface PurgeResult {
33
+ found: number;
34
+ purged: number;
35
+ failed: number;
36
+ }
41
37
 
42
- logger.info(
43
- { count: usersToDelete.length },
44
- 'Starting purge of soft-deleted accounts',
45
- );
38
+ /**
39
+ * Purge every account soft-deleted more than RETENTION_DAYS ago.
40
+ *
41
+ * One failing account is logged and skipped; it never stops the others. A
42
+ * failure here is a real problem (data kept past its promised deletion), so it
43
+ * is logged at error level with the user id.
44
+ */
45
+ export async function purgeDeletedAccounts(now: Date = new Date()): Promise<PurgeResult> {
46
+ const cutoffDate = new Date(now);
47
+ cutoffDate.setDate(cutoffDate.getDate() - RETENTION_DAYS);
46
48
 
47
- let purgedCount = 0;
49
+ // Find users soft-deleted more than 30 days ago
50
+ const usersToDelete = await prisma.user.findMany({
51
+ where: {
52
+ deletedAt: {
53
+ not: null,
54
+ lt: cutoffDate,
55
+ },
56
+ },
57
+ select: {
58
+ id: true,
59
+ },
60
+ });
48
61
 
49
- for (const user of usersToDelete) {
50
- try {
51
- // Hard delete user record first (cascades to RefreshToken + Session).
52
- // DB deletion is the critical operation — if it succeeds but file cleanup
53
- // fails, we only have orphaned files (harmless, cleanable later).
54
- // The reverse (files deleted, DB intact) would leave a dangling user record.
55
- await prisma.user.delete({
56
- where: { id: user.id },
57
- });
62
+ const result: PurgeResult = { found: usersToDelete.length, purged: 0, failed: 0 };
58
63
 
59
- // Delete all user media from disk (no-op if dir doesn't exist)
60
- try {
61
- await fileStorageService.deleteUserMedia(user.id);
62
- } catch (fileError) {
63
- logger.warn(
64
- { err: fileError, userId: user.id },
65
- 'User record purged but file cleanup failed — orphaned files may remain',
66
- );
67
- }
64
+ for (const user of usersToDelete) {
65
+ try {
66
+ // Media first (no-op if the folders don't exist). If it throws, the row
67
+ // stays and the next run retries this account.
68
+ await fileStorageService.deleteUserMedia(user.id);
68
69
 
69
- purgedCount++;
70
- } catch (error) {
71
- logger.error(
72
- { err: error, userId: user.id },
73
- 'Failed to purge deleted account',
74
- );
75
- }
70
+ // Then the row (cascades to RefreshToken + Session). If only this fails,
71
+ // the next run finds the account again; its media is already gone.
72
+ try {
73
+ await prisma.user.delete({
74
+ where: { id: user.id },
75
+ });
76
+ } catch (error) {
77
+ // Another server process (a replica, or the old container during a
78
+ // deploy) purged it a moment ago: the account is gone, which is the
79
+ // goal. Not a failure, so no error log.
80
+ if (!isPrismaNotFound(error)) throw error;
76
81
  }
77
82
 
78
- logger.info(
79
- { purgedCount, totalFound: usersToDelete.length },
80
- 'Deleted accounts purge complete',
81
- );
83
+ result.purged++;
82
84
  } catch (error) {
83
- logger.error({ err: error }, 'Failed to run deleted accounts cleanup');
85
+ result.failed++;
86
+ logger.error({ err: error, userId: user.id }, 'Failed to purge deleted account');
84
87
  }
85
- }, INTERVAL_MS);
88
+ }
86
89
 
87
- app.addHook('onClose', async () => {
88
- clearInterval(intervalId);
90
+ // One line per run, also when nothing was due: the log then shows the purge
91
+ // really runs (it used to say nothing unless it found an account).
92
+ logger.info(
93
+ { purgedCount: result.purged, failedCount: result.failed, totalFound: result.found },
94
+ 'Deleted accounts purge complete',
95
+ );
96
+ return result;
97
+ }
98
+
99
+ export function startCleanupDeletedAccountsJob(app: FastifyInstance): void {
100
+ startRecurringJob(app, {
101
+ name: 'purge-deleted-accounts',
102
+ intervalMs: INTERVAL_MS,
103
+ firstRunDelayMs: FIRST_RUN_DELAY_MS,
104
+ run: () => purgeDeletedAccounts(),
89
105
  });
90
106
  }
@@ -1,41 +1,49 @@
1
1
  /**
2
2
  * Cleanup Expired Auth Records Job
3
3
  *
4
- * Periodically removes expired refresh tokens and sessions from the database.
5
- * Runs every hour.
4
+ * Removes expired refresh tokens and sessions from the database, and expired
5
+ * automatic IP blocks from Redis (libs/ip-block.ts). Runs about a minute after
6
+ * start, then every hour (jobs/schedule.ts).
6
7
  */
7
8
 
8
9
  import type { FastifyInstance } from 'fastify';
9
10
  import { prisma } from '@libs/prisma.js';
10
11
  import { logger } from '@libs/logger.js';
12
+ import { pruneExpiredAutoBlocks } from '@libs/ip-block.js';
13
+ import { startRecurringJob } from './schedule.js';
11
14
 
12
15
  const INTERVAL_MS = 60 * 60 * 1000; // 1 hour
16
+ const FIRST_RUN_DELAY_MS = 60 * 1000;
13
17
 
14
- export function startCleanupExpiredAuthJob(app: FastifyInstance): void {
15
- const intervalId = setInterval(async () => {
16
- try {
17
- const now = new Date();
18
+ /** One cleanup pass; exported so tests (and an operator script) can run it directly. */
19
+ export async function cleanupExpiredAuth(
20
+ now: Date = new Date(),
21
+ ): Promise<{ tokens: number; sessions: number; autoBlocks: number }> {
22
+ const deletedTokens = await prisma.refreshToken.deleteMany({
23
+ where: { expiresAt: { lt: now } },
24
+ });
18
25
 
19
- const deletedTokens = await prisma.refreshToken.deleteMany({
20
- where: { expiresAt: { lt: now } },
21
- });
26
+ const deletedSessions = await prisma.session.deleteMany({
27
+ where: { expiresAt: { lt: now } },
28
+ });
22
29
 
23
- const deletedSessions = await prisma.session.deleteMany({
24
- where: { expiresAt: { lt: now } },
25
- });
30
+ // Redis, separate from the database: never fails the pass (fail-open).
31
+ const autoBlocks = await pruneExpiredAutoBlocks(now.getTime() / 1000);
26
32
 
27
- if (deletedTokens.count > 0 || deletedSessions.count > 0) {
28
- logger.info(
29
- { deletedTokens: deletedTokens.count, deletedSessions: deletedSessions.count },
30
- 'Expired auth records cleaned up',
31
- );
32
- }
33
- } catch (error) {
34
- logger.error({ err: error }, 'Failed to clean up expired auth records');
35
- }
36
- }, INTERVAL_MS);
33
+ if (deletedTokens.count > 0 || deletedSessions.count > 0 || autoBlocks > 0) {
34
+ logger.info(
35
+ { deletedTokens: deletedTokens.count, deletedSessions: deletedSessions.count, prunedAutoBlocks: autoBlocks },
36
+ 'Expired auth records cleaned up',
37
+ );
38
+ }
39
+ return { tokens: deletedTokens.count, sessions: deletedSessions.count, autoBlocks };
40
+ }
37
41
 
38
- app.addHook('onClose', async () => {
39
- clearInterval(intervalId);
42
+ export function startCleanupExpiredAuthJob(app: FastifyInstance): void {
43
+ startRecurringJob(app, {
44
+ name: 'cleanup-expired-auth',
45
+ intervalMs: INTERVAL_MS,
46
+ firstRunDelayMs: FIRST_RUN_DELAY_MS,
47
+ run: () => cleanupExpiredAuth(),
40
48
  });
41
49
  }
@@ -1,13 +1,22 @@
1
1
  /**
2
2
  * Jobs Registry
3
3
  *
4
- * Registers all background jobs with the Fastify instance.
5
- * Each job manages its own interval and cleanup via onClose hook.
4
+ * Registers all background jobs with the Fastify instance. They run inside the
5
+ * server process, each once shortly after start and then on its interval
6
+ * (jobs/schedule.ts), so a deploy never postpones them. With several server
7
+ * processes (replicas) each runs them too; that is safe, the jobs are
8
+ * idempotent (the purge treats an account another process removed as done).
9
+ *
10
+ * - cleanup-expired-auth: hourly, expired refresh tokens and sessions, and
11
+ * expired automatic IP blocks in Redis
12
+ * - purge-deleted-accounts: daily, accounts deleted more than 30 days ago
13
+ * - refresh-cloudflare-ranges: daily, Cloudflare's edge IP ranges (not in tests)
6
14
  */
7
15
 
8
16
  import type { FastifyInstance } from 'fastify';
9
17
  import { startCleanupExpiredAuthJob } from './cleanup-expired-auth.job.js';
10
18
  import { startCleanupDeletedAccountsJob } from './cleanup-deleted-accounts.job.js';
19
+ import { startRefreshCloudflareRangesJob } from './refresh-cloudflare-ranges.job.js';
11
20
 
12
21
  /**
13
22
  * Registers all background jobs
@@ -17,4 +26,5 @@ import { startCleanupDeletedAccountsJob } from './cleanup-deleted-accounts.job.j
17
26
  export function registerJobs(app: FastifyInstance): void {
18
27
  startCleanupExpiredAuthJob(app);
19
28
  startCleanupDeletedAccountsJob(app);
29
+ startRefreshCloudflareRangesJob(app);
20
30
  }
@@ -0,0 +1,28 @@
1
+ /**
2
+ * Refresh Cloudflare IP Ranges Job
3
+ *
4
+ * Keeps libs/cloudflare-ranges.ts in step with Cloudflare's published edge ranges: once shortly
5
+ * after start, then every 24 hours (jobs/schedule.ts). The bundled list keeps working when a
6
+ * refresh fails, so this job is a freshness optimisation, not a dependency (see that module for
7
+ * why it matters). Skipped under NODE_ENV=test so test runs never make outbound calls.
8
+ */
9
+
10
+ import type { FastifyInstance } from 'fastify';
11
+ import { env } from '@config/env.js';
12
+ import { refreshCloudflareRanges } from '@libs/cloudflare-ranges.js';
13
+ import { startRecurringJob } from './schedule.js';
14
+
15
+ const INTERVAL_MS = 24 * 60 * 60 * 1000; // 24 hours
16
+ const FIRST_RUN_DELAY_MS = 30 * 1000; // off the startup path
17
+
18
+ export function startRefreshCloudflareRangesJob(app: FastifyInstance): void {
19
+ if (env.NODE_ENV === 'test') return;
20
+
21
+ // refreshCloudflareRanges never throws; it logs and keeps the current list on failure.
22
+ startRecurringJob(app, {
23
+ name: 'refresh-cloudflare-ranges',
24
+ intervalMs: INTERVAL_MS,
25
+ firstRunDelayMs: FIRST_RUN_DELAY_MS,
26
+ run: () => refreshCloudflareRanges(),
27
+ });
28
+ }
@@ -0,0 +1,50 @@
1
+ /**
2
+ * The one way background jobs are scheduled (see jobs/index.ts).
3
+ *
4
+ * A job runs once shortly after start, then every interval. Running only on
5
+ * setInterval (as the jobs used to) waits a FULL interval from boot, and every
6
+ * deploy or restart starts that wait again: a project deployed at least once a
7
+ * day never ran its daily purge at all.
8
+ *
9
+ * - The first run is delayed (firstRunDelayMs) so it stays off the startup path.
10
+ * - Timers are unref'd: they never keep the process alive on their own, and
11
+ * app.close() (graceful shutdown) clears them.
12
+ * - A failing run is logged and the schedule goes on; one bad run never stops
13
+ * the job. Runs never overlap: a run that is still busy skips the next tick.
14
+ */
15
+ import type { FastifyInstance } from 'fastify';
16
+ import { logger } from '@libs/logger.js';
17
+
18
+ export interface RecurringJob {
19
+ /** Short name for the logs, e.g. 'purge-deleted-accounts'. */
20
+ name: string;
21
+ intervalMs: number;
22
+ firstRunDelayMs: number;
23
+ run: () => Promise<unknown>;
24
+ }
25
+
26
+ export function startRecurringJob(app: FastifyInstance, job: RecurringJob): void {
27
+ let running = false;
28
+
29
+ const tick = async (): Promise<void> => {
30
+ if (running) return; // the previous run is still busy
31
+ running = true;
32
+ try {
33
+ await job.run();
34
+ } catch (error) {
35
+ logger.error({ err: error, job: job.name }, `[JOB] ${job.name} failed`);
36
+ } finally {
37
+ running = false;
38
+ }
39
+ };
40
+
41
+ const firstRun = setTimeout(() => void tick(), job.firstRunDelayMs);
42
+ const interval = setInterval(() => void tick(), job.intervalMs);
43
+ firstRun.unref();
44
+ interval.unref();
45
+
46
+ app.addHook('onClose', async () => {
47
+ clearTimeout(firstRun);
48
+ clearInterval(interval);
49
+ });
50
+ }
@@ -0,0 +1,168 @@
1
+ import { describe, it, expect, vi, beforeEach } from 'vitest';
2
+ import type { FastifyReply, FastifyRequest } from 'fastify';
3
+ import { prisma } from '@libs/prisma.js';
4
+ import { clearAuthCookies } from '@libs/cookies.js';
5
+ import { authenticate, authorize, resolveMe, resolveTargetUser } from '../auth.js';
6
+
7
+ // authenticate() is the single per-request gate: the token must belong to a
8
+ // live session of this user, the role comes from the database (not the token),
9
+ // and banned or deleted accounts are refused.
10
+
11
+ vi.mock('@libs/prisma.js', () => ({
12
+ prisma: { session: { findFirst: vi.fn() }, user: { findUnique: vi.fn() } },
13
+ }));
14
+ vi.mock('@libs/cookies.js', () => ({ clearAuthCookies: vi.fn() }));
15
+
16
+ type DbUser = {
17
+ isActive: boolean;
18
+ emailVerifiedAt: Date | null;
19
+ deletedAt: Date | null;
20
+ role: 'USER' | 'ADMIN';
21
+ };
22
+
23
+ /** `sessionId: null` builds a token without one (signed before tokens carried it). */
24
+ function makeRequest(tokenRole: 'USER' | 'ADMIN', sessionId: string | null = 'session-1'): FastifyRequest {
25
+ const request = {
26
+ user: { userId: 'user-1', role: tokenRole, ...(sessionId === null ? {} : { sessionId }) },
27
+ jwtVerify: vi.fn().mockResolvedValue(undefined),
28
+ };
29
+ return request as unknown as FastifyRequest;
30
+ }
31
+
32
+ const reply = {} as FastifyReply;
33
+
34
+ /** The live session found for the token, carrying its user's current state. */
35
+ function mockDbUser(user: DbUser | null): void {
36
+ vi.mocked(prisma.session.findFirst).mockResolvedValue({ user } as never);
37
+ }
38
+
39
+ describe('authenticate', () => {
40
+ beforeEach(() => {
41
+ vi.clearAllMocks();
42
+ });
43
+
44
+ it('replaces a stale ADMIN role from the token with the current database role', async () => {
45
+ // The admin was demoted after this token was signed.
46
+ mockDbUser({ isActive: true, emailVerifiedAt: new Date(), deletedAt: null, role: 'USER' });
47
+ const request = makeRequest('ADMIN');
48
+
49
+ await authenticate(request, reply);
50
+
51
+ expect(request.user.role).toBe('USER');
52
+ await expect(authorize('ADMIN')(request, reply)).rejects.toMatchObject({ statusCode: 403 });
53
+ });
54
+
55
+ it('keeps admin access for a current admin', async () => {
56
+ mockDbUser({ isActive: true, emailVerifiedAt: new Date(), deletedAt: null, role: 'ADMIN' });
57
+ const request = makeRequest('ADMIN');
58
+
59
+ await authenticate(request, reply);
60
+
61
+ await expect(authorize('ADMIN')(request, reply)).resolves.toBeUndefined();
62
+ });
63
+
64
+ it('rejects a banned account with ACCOUNT_DEACTIVATED and clears its cookies', async () => {
65
+ mockDbUser({ isActive: false, emailVerifiedAt: new Date(), deletedAt: null, role: 'USER' });
66
+
67
+ await expect(authenticate(makeRequest('USER'), reply)).rejects.toMatchObject({
68
+ statusCode: 403,
69
+ code: 'ACCOUNT_DEACTIVATED',
70
+ });
71
+ expect(clearAuthCookies).toHaveBeenCalledWith(reply);
72
+ });
73
+
74
+ it('rejects a deleted account with 401', async () => {
75
+ mockDbUser({ isActive: false, emailVerifiedAt: null, deletedAt: new Date(), role: 'USER' });
76
+
77
+ await expect(authenticate(makeRequest('USER'), reply)).rejects.toMatchObject({ statusCode: 401 });
78
+ expect(clearAuthCookies).toHaveBeenCalledWith(reply);
79
+ });
80
+
81
+ it('looks the session up by id, user and expiry in one query', async () => {
82
+ mockDbUser({ isActive: true, emailVerifiedAt: new Date(), deletedAt: null, role: 'USER' });
83
+ await authenticate(makeRequest('USER'), reply);
84
+ expect(prisma.session.findFirst).toHaveBeenCalledTimes(1);
85
+ expect(vi.mocked(prisma.session.findFirst).mock.calls[0]?.[0]).toMatchObject({
86
+ where: { id: 'session-1', userId: 'user-1', expiresAt: { gt: expect.any(Date) } },
87
+ });
88
+ });
89
+
90
+ it('refuses a token whose session ended (logout, revoke, password reset) and clears its cookies', async () => {
91
+ vi.mocked(prisma.session.findFirst).mockResolvedValue(null);
92
+ vi.mocked(prisma.user.findUnique).mockResolvedValue({ isActive: true, emailVerifiedAt: new Date(), deletedAt: null } as never);
93
+ await expect(authenticate(makeRequest('USER'), reply)).rejects.toMatchObject({
94
+ statusCode: 401,
95
+ code: 'SESSION_EXPIRED',
96
+ });
97
+ expect(clearAuthCookies).toHaveBeenCalledWith(reply);
98
+ });
99
+
100
+ it('refuses a token without a session id (signed before tokens carried one) without querying', async () => {
101
+ await expect(authenticate(makeRequest('USER', null), reply)).rejects.toMatchObject({
102
+ statusCode: 401,
103
+ code: 'SESSION_EXPIRED',
104
+ });
105
+ expect(prisma.session.findFirst).not.toHaveBeenCalled();
106
+ expect(clearAuthCookies).toHaveBeenCalledWith(reply);
107
+ });
108
+
109
+ it("a banned user's token (the ban deleted its sessions) still says ACCOUNT_DEACTIVATED", async () => {
110
+ vi.mocked(prisma.session.findFirst).mockResolvedValue(null);
111
+ vi.mocked(prisma.user.findUnique).mockResolvedValue({ isActive: false, emailVerifiedAt: new Date(), deletedAt: null } as never);
112
+ await expect(authenticate(makeRequest('USER'), reply)).rejects.toMatchObject({
113
+ statusCode: 403,
114
+ code: 'ACCOUNT_DEACTIVATED',
115
+ });
116
+ expect(clearAuthCookies).toHaveBeenCalledWith(reply);
117
+ });
118
+ });
119
+
120
+ // resolveMe / resolveTargetUser decide WHOSE account a /users route acts on.
121
+ // They are the whole ownership check for the /users/:userId routes (profile,
122
+ // password, account deletion, avatar): an owner acts on themselves, an admin on
123
+ // anyone, everyone else is refused before the handler runs.
124
+ describe('resolveMe and resolveTargetUser', () => {
125
+ function guardRequest(userId: string, role: 'USER' | 'ADMIN', params: Record<string, string> = {}): FastifyRequest {
126
+ return { user: { userId, role, sessionId: 'session-1' }, params } as unknown as FastifyRequest;
127
+ }
128
+
129
+ it('resolveMe targets the signed-in user, never as an admin action', async () => {
130
+ const request = guardRequest('user-1', 'ADMIN');
131
+ await resolveMe(request, reply);
132
+ expect(request.targetUserId).toBe('user-1');
133
+ expect(request.isAdminAction).toBe(false);
134
+ });
135
+
136
+ it('an owner acts on their own account', async () => {
137
+ const request = guardRequest('user-1', 'USER', { userId: 'user-1' });
138
+ await resolveTargetUser(request, reply);
139
+ expect(request.targetUserId).toBe('user-1');
140
+ expect(request.isAdminAction).toBe(false);
141
+ });
142
+
143
+ it("refuses a user acting on someone else's account with 403", async () => {
144
+ const request = guardRequest('user-2', 'USER', { userId: 'user-1' });
145
+ await expect(resolveTargetUser(request, reply)).rejects.toMatchObject({ statusCode: 403 });
146
+ expect(request.targetUserId).toBeUndefined();
147
+ });
148
+
149
+ it("lets an admin act on another user's account, marked as an admin action", async () => {
150
+ const request = guardRequest('admin-1', 'ADMIN', { userId: 'user-1' });
151
+ await resolveTargetUser(request, reply);
152
+ expect(request.targetUserId).toBe('user-1');
153
+ expect(request.isAdminAction).toBe(true);
154
+ });
155
+
156
+ it('an admin on their own account takes the owner path (still needs their own password)', async () => {
157
+ const request = guardRequest('admin-1', 'ADMIN', { userId: 'admin-1' });
158
+ await resolveTargetUser(request, reply);
159
+ expect(request.isAdminAction).toBe(false);
160
+ });
161
+
162
+ it('refuses a request without :userId with 400 MISSING_USER_ID', async () => {
163
+ await expect(resolveTargetUser(guardRequest('user-1', 'USER'), reply)).rejects.toMatchObject({
164
+ statusCode: 400,
165
+ code: 'MISSING_USER_ID',
166
+ });
167
+ });
168
+ });