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.
- package/README.md +81 -12
- package/bin/create-tigra.js +495 -472
- package/lib/patchers/email-verification.patcher.js +72 -10
- package/modules/email-verification/client/hooks/useVerification.ts +4 -1
- package/modules/email-verification/server/__tests__/verification.integration.test.ts +115 -0
- package/modules/email-verification/server/verification.controller.ts +3 -1
- package/modules/email-verification/server/verification.service.ts +44 -13
- package/package.json +3 -2
- package/template/.github/dependabot.yml +47 -0
- package/template/.github/workflows/audit.yml +36 -0
- package/template/.github/workflows/ci.yml +79 -0
- package/template/AGENTS.md +18 -9
- package/template/client/.dockerignore +1 -0
- package/template/client/.env.example.production +13 -2
- package/template/client/AGENTS.md +13 -5
- package/template/client/Dockerfile +186 -14
- package/template/client/next.config.ts +1 -1
- package/template/client/package-lock.json +15983 -14181
- package/template/client/package.json +56 -48
- package/template/client/scripts/check-sharp.mjs +53 -0
- package/template/client/scripts/next-dev.cjs +5 -1
- package/template/client/src/__tests__/proxy.test.ts +92 -0
- package/template/client/src/app/healthz/route.ts +16 -0
- package/template/client/src/app/layout.tsx +9 -3
- package/template/client/src/app/page.tsx +2 -2
- package/template/client/src/app/providers.tsx +23 -4
- package/template/client/src/components/layout/Header.tsx +7 -3
- package/template/client/src/features/admin/hooks/useAdminSessions.ts +2 -1
- package/template/client/src/features/admin/hooks/useAdminUsers.ts +3 -1
- package/template/client/src/features/admin/types/admin.types.ts +2 -3
- package/template/client/src/features/auth/components/AuthInitializer.tsx +35 -18
- package/template/client/src/features/auth/components/ForgotPasswordForm.tsx +107 -0
- package/template/client/src/features/auth/components/LimitNotice.tsx +28 -0
- package/template/client/src/features/auth/components/LoginForm.tsx +13 -2
- package/template/client/src/features/auth/components/RegisterForm.tsx +23 -7
- package/template/client/src/features/auth/hooks/useAuth.ts +11 -1
- package/template/client/src/features/auth/hooks/usePasswordReset.ts +7 -1
- package/template/client/src/features/auth/services/auth.service.ts +8 -3
- package/template/client/src/features/auth/store/authSlice.ts +7 -2
- package/template/client/src/lib/api/__tests__/axios.config.test.ts +183 -0
- package/template/client/src/lib/api/api.types.ts +14 -0
- package/template/client/src/lib/api/axios.config.ts +101 -15
- package/template/client/src/lib/api/hard-redirect.ts +8 -0
- package/template/client/src/lib/api/session-events.ts +29 -0
- package/template/client/src/lib/constants/routes.ts +12 -0
- package/template/client/src/lib/observability/sentry-scrub.ts +1 -1
- package/template/client/src/lib/utils/__tests__/error.test.ts +119 -0
- package/template/client/src/lib/utils/__tests__/form.test.ts +42 -0
- package/template/client/src/lib/utils/__tests__/paths.test.ts +43 -0
- package/template/client/src/lib/utils/__tests__/security.test.ts +40 -0
- package/template/client/src/lib/utils/__tests__/session-marker.test.ts +27 -0
- package/template/client/src/lib/utils/error.ts +81 -0
- package/template/client/src/lib/utils/form.ts +31 -0
- package/template/client/src/lib/utils/paths.ts +18 -0
- package/template/client/src/lib/utils/session-marker.ts +24 -0
- package/template/client/src/{middleware.ts → proxy.ts} +25 -11
- package/template/client/src/store/__tests__/store.test.ts +44 -0
- package/template/client/src/store/index.ts +26 -8
- package/template/client/vitest.config.mts +48 -0
- package/template/server/.env.example +280 -270
- package/template/server/.env.example.production +283 -242
- package/template/server/AGENTS.md +13 -4
- package/template/server/Dockerfile +176 -14
- package/template/server/docker-compose.yml +4 -2
- package/template/server/docs/deployment.md +63 -0
- package/template/server/docs/logging.md +52 -4
- package/template/server/docs/rate-limits.md +153 -0
- package/template/server/docs/testing.md +63 -0
- package/template/server/eslint.config.mjs +19 -0
- package/template/server/package-lock.json +8784 -8743
- package/template/server/package.json +79 -75
- package/template/server/prisma/migrations/0_init/migration.sql +82 -0
- package/template/server/prisma/migrations/migration_lock.toml +3 -0
- package/template/server/prisma/schema.prisma +0 -3
- package/template/server/scripts/check-heic.mjs +40 -0
- package/template/server/scripts/check-sharp.mjs +53 -0
- package/template/server/src/__tests__/routes.integration.test.ts +280 -0
- package/template/server/src/app.ts +248 -346
- package/template/server/src/config/__tests__/env.test.ts +219 -0
- package/template/server/src/config/__tests__/rate-limit.config.test.ts +158 -0
- package/template/server/src/config/env.ts +326 -182
- package/template/server/src/config/rate-limit.config.ts +157 -106
- package/template/server/src/jobs/__tests__/cleanup-deleted-accounts.job.test.ts +60 -8
- package/template/server/src/jobs/__tests__/cleanup-expired-auth.job.test.ts +44 -0
- package/template/server/src/jobs/__tests__/jobs.integration.test.ts +88 -0
- package/template/server/src/jobs/__tests__/schedule.test.ts +92 -0
- package/template/server/src/jobs/cleanup-deleted-accounts.job.ts +38 -36
- package/template/server/src/jobs/cleanup-expired-auth.job.ts +32 -24
- package/template/server/src/jobs/index.ts +12 -2
- package/template/server/src/jobs/refresh-cloudflare-ranges.job.ts +28 -0
- package/template/server/src/jobs/schedule.ts +50 -0
- package/template/server/src/libs/__tests__/auth.test.ts +98 -7
- package/template/server/src/libs/__tests__/client-ip.test.ts +257 -121
- package/template/server/src/libs/__tests__/cloudflare-ranges.test.ts +79 -0
- package/template/server/src/libs/__tests__/cookies.test.ts +53 -2
- package/template/server/src/libs/__tests__/email-quota.test.ts +81 -0
- package/template/server/src/libs/__tests__/email.test.ts +68 -0
- package/template/server/src/libs/__tests__/error-handler.test.ts +162 -0
- package/template/server/src/libs/__tests__/health-db-down.integration.test.ts +37 -0
- package/template/server/src/libs/__tests__/health-redis-down.integration.test.ts +45 -0
- package/template/server/src/libs/__tests__/health-routes.test.ts +83 -0
- package/template/server/src/libs/__tests__/health.integration.test.ts +118 -0
- package/template/server/src/libs/__tests__/http.test.ts +74 -2
- package/template/server/src/libs/__tests__/ip-block.test.ts +179 -62
- package/template/server/src/libs/__tests__/logger.test.ts +50 -0
- package/template/server/src/libs/__tests__/monitoring.test.ts +185 -0
- package/template/server/src/libs/__tests__/outbound.integration.test.ts +48 -0
- package/template/server/src/libs/__tests__/prisma-client.test.ts +28 -0
- package/template/server/src/libs/__tests__/query-counter.integration.test.ts +53 -0
- package/template/server/src/libs/__tests__/rate-limiting.test.ts +146 -0
- package/template/server/src/libs/__tests__/rate-limits.integration.test.ts +53 -0
- package/template/server/src/libs/__tests__/redis-required.test.ts +30 -0
- package/template/server/src/libs/__tests__/redis.test.ts +38 -2
- package/template/server/src/libs/__tests__/request-id.test.ts +25 -0
- package/template/server/src/libs/__tests__/requestLogger.test.ts +126 -0
- package/template/server/src/libs/__tests__/safe-http.test.ts +138 -0
- package/template/server/src/libs/__tests__/sentry-scrub.test.ts +82 -80
- package/template/server/src/libs/__tests__/shutdown.test.ts +89 -0
- package/template/server/src/libs/__tests__/url-safety.test.ts +130 -80
- package/template/server/src/libs/auth.ts +39 -10
- package/template/server/src/libs/client-ip.ts +158 -77
- package/template/server/src/libs/cloudflare-ranges.ts +132 -0
- package/template/server/src/libs/cookies.ts +53 -14
- package/template/server/src/libs/email-quota.ts +74 -0
- package/template/server/src/libs/email.ts +46 -9
- package/template/server/src/libs/error-handler.ts +111 -0
- package/template/server/src/libs/health-routes.ts +53 -0
- package/template/server/src/libs/http.ts +139 -47
- package/template/server/src/libs/ip-address.ts +37 -0
- package/template/server/src/libs/ip-block.ts +284 -221
- package/template/server/src/libs/logger.ts +41 -12
- package/template/server/src/libs/monitoring.ts +127 -41
- package/template/server/src/libs/observability/sentry.ts +1 -1
- package/template/server/src/libs/origin-check.ts +9 -7
- package/template/server/src/libs/prisma.ts +47 -4
- package/template/server/src/libs/query-counter.ts +71 -59
- package/template/server/src/libs/rate-limiting.ts +110 -0
- package/template/server/src/libs/redis-required.ts +28 -0
- package/template/server/src/libs/redis.ts +27 -1
- package/template/server/src/libs/request-id.ts +18 -0
- package/template/server/src/libs/requestLogger.ts +112 -17
- package/template/server/src/libs/safe-http.ts +101 -0
- package/template/server/src/libs/shutdown.ts +87 -0
- package/template/server/src/libs/storage/__tests__/fixtures/tiny-heic.ts +13 -0
- package/template/server/src/libs/storage/__tests__/image-optimizer.test.ts +59 -0
- package/template/server/src/libs/storage/__tests__/multipart-limits.test.ts +91 -0
- package/template/server/src/libs/storage/__tests__/upload-persistence.test.ts +52 -0
- package/template/server/src/libs/storage/file-storage.service.ts +94 -84
- package/template/server/src/libs/storage/file-validator.ts +48 -46
- package/template/server/src/libs/storage/image-optimizer.service.ts +16 -5
- package/template/server/src/libs/token-hash.ts +18 -0
- package/template/server/src/libs/url-safety.ts +127 -121
- package/template/server/src/libs/validation-errors.ts +86 -0
- package/template/server/src/modules/admin/__tests__/admin-actions.integration.test.ts +255 -0
- package/template/server/src/modules/admin/__tests__/admin.health.test.ts +82 -0
- package/template/server/src/modules/admin/__tests__/admin.repo.test.ts +55 -0
- package/template/server/src/modules/admin/__tests__/admin.schemas.test.ts +38 -0
- package/template/server/src/modules/admin/__tests__/admin.service.test.ts +162 -0
- package/template/server/src/modules/admin/admin.controller.ts +66 -49
- package/template/server/src/modules/admin/admin.repo.ts +49 -10
- package/template/server/src/modules/admin/admin.routes.ts +48 -2
- package/template/server/src/modules/admin/admin.schemas.ts +18 -6
- package/template/server/src/modules/admin/admin.service.ts +66 -4
- package/template/server/src/modules/auth/__tests__/auth.controller.test.ts +39 -0
- package/template/server/src/modules/auth/__tests__/auth.integration.test.ts +9 -3
- package/template/server/src/modules/auth/__tests__/auth.service.dummy-hash.test.ts +34 -0
- package/template/server/src/modules/auth/__tests__/auth.service.test.ts +197 -37
- package/template/server/src/modules/auth/__tests__/session-cleanup.test.ts +39 -0
- package/template/server/src/modules/auth/__tests__/sessions.integration.test.ts +246 -0
- package/template/server/src/modules/auth/__tests__/token-fingerprints.test.ts +119 -0
- package/template/server/src/modules/auth/auth.controller.ts +133 -128
- package/template/server/src/modules/auth/auth.repo.ts +44 -44
- package/template/server/src/modules/auth/auth.schemas.ts +4 -2
- package/template/server/src/modules/auth/auth.service.ts +167 -96
- package/template/server/src/modules/auth/session.repo.ts +12 -0
- package/template/server/src/modules/files/__tests__/files.integration.test.ts +5 -5
- package/template/server/src/modules/users/__tests__/avatar-upload.test.ts +120 -0
- package/template/server/src/modules/users/__tests__/name-rules.test.ts +46 -0
- package/template/server/src/modules/users/__tests__/users.integration.test.ts +295 -0
- package/template/server/src/modules/users/__tests__/users.repo.test.ts +37 -0
- package/template/server/src/modules/users/__tests__/users.service.test.ts +129 -0
- package/template/server/src/modules/users/users.controller.ts +9 -38
- package/template/server/src/modules/users/users.repo.ts +23 -7
- package/template/server/src/modules/users/users.routes.ts +3 -22
- package/template/server/src/modules/users/users.schemas.ts +15 -9
- package/template/server/src/modules/users/users.service.ts +105 -93
- package/template/server/src/scripts/make-admin.ts +48 -0
- package/template/server/src/server.ts +48 -26
- package/template/server/src/shared/errors/AppError.ts +27 -1
- package/template/server/src/shared/errors/errors.ts +42 -5
- package/template/server/src/shared/responses/successResponse.ts +22 -3
- package/template/server/src/shared/types/index.ts +7 -0
- package/template/server/src/test/__tests__/integration-services.test.ts +66 -0
- package/template/server/src/test/integration-helpers.ts +343 -0
- package/template/server/src/test/integration-services.ts +74 -0
- package/template/server/src/test/integration.global-setup.ts +144 -0
- package/template/server/src/test/integration.setup.ts +35 -158
- package/template/server/src/test/setup.ts +3 -10
- package/template/server/tsconfig.build.json +1 -1
- package/template/server/tsconfig.json +1 -0
- package/template/server/vitest.config.ts +17 -4
- package/template/server/vitest.integration.config.ts +18 -13
- package/template/server/src/libs/storage/filename-sanitizer.ts +0 -71
|
@@ -1,36 +1,42 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Rate
|
|
2
|
+
* Rate limiting configuration: the single source of every limit.
|
|
3
3
|
*
|
|
4
|
-
*
|
|
5
|
-
*
|
|
4
|
+
* What is counted (see docs/rate-limits.md for the full picture):
|
|
5
|
+
* - Every entry below is per visitor IP (getClientIp) and per route: each route
|
|
6
|
+
* keeps its own counter, even when two routes share an entry.
|
|
7
|
+
* - A route with no entry gets DEFAULT_LIMIT (its own counter per route) through
|
|
8
|
+
* the onRoute hook in app.ts. Unknown URLs (404s) share one DEFAULT counter.
|
|
9
|
+
* - Never limited: /api/v1/health, /api/v1/ready, /api/v1/live, static /uploads/*
|
|
10
|
+
* and CORS preflights.
|
|
11
|
+
* - EMAIL_PER_ADDRESS caps emails to one address, per counter (public flows such as
|
|
12
|
+
* forgot-password, and the sign-in re-send separately; see src/libs/email-quota.ts).
|
|
13
|
+
* Login lockout lives in modules/auth/auth.service.ts.
|
|
6
14
|
*
|
|
7
15
|
* ENV controls:
|
|
8
|
-
* - RATE_LIMIT_ENABLED: master switch (default
|
|
9
|
-
* - RATE_LIMIT_MULTIPLIER:
|
|
10
|
-
* -
|
|
11
|
-
*
|
|
16
|
+
* - RATE_LIMIT_ENABLED: master switch (default true). Off = every max is 1,000,000.
|
|
17
|
+
* - RATE_LIMIT_MULTIPLIER: scales every max (default 1; e.g. 10 for local development).
|
|
18
|
+
* - RATE_LIMIT_OVERRIDES: "NAME=MAX/WINDOW,..." with WINDOW like 30s, 15m or 1h, and
|
|
19
|
+
* NAME any key of RATE_LIMITS, DEFAULT or EMAIL_PER_ADDRESS. An override replaces
|
|
20
|
+
* that limit's max and window; the multiplier still applies. A bad entry stops the
|
|
21
|
+
* server at boot with the list of valid names.
|
|
12
22
|
*
|
|
13
23
|
* ── Self-ban interaction with IP auto-block (read before tightening limits) ──
|
|
14
|
-
* Every
|
|
15
|
-
* (app.ts `onExceeded` → recordRateLimitViolation).
|
|
16
|
-
*
|
|
17
|
-
*
|
|
18
|
-
*
|
|
24
|
+
* Every request over a limit on a NON-auth route records one strike against the IP
|
|
25
|
+
* (app.ts `onExceeded` → recordRateLimitViolation). IP_AUTO_BLOCK_THRESHOLD strikes
|
|
26
|
+
* (default 20) within IP_AUTO_BLOCK_WINDOW_SECONDS (default 300 s) block the IP for
|
|
27
|
+
* IP_AUTO_BLOCK_DURATION_SECONDS (default 1 h) on EVERY route. /api/v1/auth/* adds
|
|
28
|
+
* no strikes: a mistyped password must never ban a whole network.
|
|
19
29
|
*
|
|
20
|
-
*
|
|
21
|
-
*
|
|
22
|
-
*
|
|
23
|
-
*
|
|
24
|
-
*
|
|
25
|
-
*
|
|
26
|
-
* per 5-minute window — safely below 20. A hypothetical 5/10s limit could
|
|
27
|
-
* produce 30 violations in 5 minutes and trip the auto-block on its own.
|
|
30
|
+
* Counting happens before validation, and offices or mobile carriers put many people
|
|
31
|
+
* behind one IP. So the strike budget is about 20 requests ABOVE a limit in five
|
|
32
|
+
* minutes. A client that keeps hammering a short-window route after its 429 (the
|
|
33
|
+
* client does not auto-retry 429s, but a script might) bans itself within minutes:
|
|
34
|
+
* e.g. avatar upload at 10/min retried once a second earns ~50 strikes a minute.
|
|
35
|
+
* Keep short windows only on routes a person cannot reasonably hammer.
|
|
28
36
|
*/
|
|
29
37
|
|
|
30
38
|
import { env } from '@config/env.js';
|
|
31
|
-
import { getRedis } from '@libs/redis.js';
|
|
32
39
|
import { logger } from '@libs/logger.js';
|
|
33
|
-
import type { Redis } from 'ioredis';
|
|
34
40
|
|
|
35
41
|
// ─── Global settings ───────────────────────────────────────────
|
|
36
42
|
|
|
@@ -38,6 +44,75 @@ export const RATE_LIMIT_ENABLED = env.RATE_LIMIT_ENABLED;
|
|
|
38
44
|
|
|
39
45
|
const MULTIPLIER = env.RATE_LIMIT_MULTIPLIER;
|
|
40
46
|
|
|
47
|
+
/** A limit as @fastify/rate-limit takes it: `timeWindow` in milliseconds. */
|
|
48
|
+
export interface RouteLimit {
|
|
49
|
+
max: number;
|
|
50
|
+
timeWindow: number;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** Thrown for a malformed RATE_LIMIT_OVERRIDES entry or window; becomes a boot failure. */
|
|
54
|
+
export class RateLimitConfigError extends Error {}
|
|
55
|
+
|
|
56
|
+
const UNIT_MS = { s: 1_000, m: 60_000, h: 3_600_000 } as const;
|
|
57
|
+
|
|
58
|
+
/** "15m" → 900000. A whole number of at least 1 with an s, m or h suffix. */
|
|
59
|
+
export function parseWindow(text: string): number {
|
|
60
|
+
const match = /^(\d+)([smh])$/.exec(text.trim());
|
|
61
|
+
if (!match || Number(match[1]) < 1) {
|
|
62
|
+
throw new RateLimitConfigError(`invalid window "${text}" (use e.g. 30s, 15m or 1h)`);
|
|
63
|
+
}
|
|
64
|
+
return Number(match[1]) * UNIT_MS[match[2] as keyof typeof UNIT_MS];
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* Parse RATE_LIMIT_OVERRIDES ("NAME=MAX/WINDOW,..."). Checks the format only;
|
|
69
|
+
* names are checked once every limit exists (see the end of this file).
|
|
70
|
+
*/
|
|
71
|
+
export function parseOverrides(raw: string | undefined): Map<string, RouteLimit> {
|
|
72
|
+
const overrides = new Map<string, RouteLimit>();
|
|
73
|
+
if (!raw?.trim()) return overrides;
|
|
74
|
+
for (const part of raw.split(',')) {
|
|
75
|
+
const entry = part.trim();
|
|
76
|
+
if (!entry) continue;
|
|
77
|
+
const match = /^([A-Z][A-Z0-9_]*)=(\d+)\/(\S+)$/.exec(entry);
|
|
78
|
+
if (!match) {
|
|
79
|
+
throw new RateLimitConfigError(`invalid entry "${entry}" (expected NAME=MAX/WINDOW, e.g. AUTH_LOGIN=100/15m)`);
|
|
80
|
+
}
|
|
81
|
+
const [, name, maxText, windowText] = match;
|
|
82
|
+
const max = Number(maxText);
|
|
83
|
+
if (!Number.isSafeInteger(max) || max < 1) {
|
|
84
|
+
throw new RateLimitConfigError(`invalid max in "${entry}" (a whole number of at least 1)`);
|
|
85
|
+
}
|
|
86
|
+
if (overrides.has(name)) {
|
|
87
|
+
throw new RateLimitConfigError(`${name} is set more than once`);
|
|
88
|
+
}
|
|
89
|
+
overrides.set(name, { max, timeWindow: parseWindow(windowText) });
|
|
90
|
+
}
|
|
91
|
+
return overrides;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** Override names that match no limit (a typo would otherwise be silently ignored). */
|
|
95
|
+
export function unknownOverrideNames(overrides: Map<string, RouteLimit>, known: Iterable<string>): string[] {
|
|
96
|
+
const knownNames = new Set(known);
|
|
97
|
+
return [...overrides.keys()].filter((name) => !knownNames.has(name));
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/** Configuration mistakes stop the server before it serves anything (same style as env.ts). */
|
|
101
|
+
function failBoot(message: string): never {
|
|
102
|
+
console.error(`\nInvalid RATE_LIMIT_OVERRIDES: ${message}\n`);
|
|
103
|
+
process.exit(1);
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
function loadOverrides(): Map<string, RouteLimit> {
|
|
107
|
+
try {
|
|
108
|
+
return parseOverrides(env.RATE_LIMIT_OVERRIDES);
|
|
109
|
+
} catch (error) {
|
|
110
|
+
return failBoot(error instanceof Error ? error.message : String(error));
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
const OVERRIDES = loadOverrides();
|
|
115
|
+
|
|
41
116
|
/**
|
|
42
117
|
* Apply the global multiplier to a max value.
|
|
43
118
|
* Ensures minimum of 1 if rate limiting is enabled.
|
|
@@ -47,99 +122,75 @@ function applyMultiplier(max: number): number {
|
|
|
47
122
|
return Math.max(1, Math.round(max * MULTIPLIER));
|
|
48
123
|
}
|
|
49
124
|
|
|
125
|
+
/**
|
|
126
|
+
* One limit. An override for `name` replaces the default max and window, then
|
|
127
|
+
* the multiplier scales the max. `name` must equal the RATE_LIMITS key (the
|
|
128
|
+
* overrides use it). The email-verification patcher adds its two entries with
|
|
129
|
+
* this helper, so keep the name and signature.
|
|
130
|
+
*/
|
|
131
|
+
function routeLimit(name: string, max: number, window: string): RouteLimit {
|
|
132
|
+
const override = OVERRIDES.get(name);
|
|
133
|
+
return {
|
|
134
|
+
max: applyMultiplier(override?.max ?? max),
|
|
135
|
+
timeWindow: override?.timeWindow ?? parseWindow(window),
|
|
136
|
+
};
|
|
137
|
+
}
|
|
138
|
+
|
|
50
139
|
// ─── Per-route configs ─────────────────────────────────────────
|
|
140
|
+
// Keep this an object literal: the email-verification patcher appends to it.
|
|
51
141
|
|
|
52
142
|
export const RATE_LIMITS = {
|
|
53
|
-
// Auth routes
|
|
54
|
-
AUTH_REGISTER:
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
AUTH_SESSIONS: {
|
|
75
|
-
max: applyMultiplier(30),
|
|
76
|
-
timeWindow: '1 minute',
|
|
77
|
-
},
|
|
78
|
-
AUTH_LOGOUT_ALL: {
|
|
79
|
-
max: applyMultiplier(10),
|
|
80
|
-
timeWindow: '15 minutes',
|
|
81
|
-
},
|
|
82
|
-
AUTH_FORGOT_PASSWORD: {
|
|
83
|
-
max: applyMultiplier(5),
|
|
84
|
-
timeWindow: '15 minutes',
|
|
85
|
-
},
|
|
86
|
-
AUTH_RESET_PASSWORD: {
|
|
87
|
-
max: applyMultiplier(10),
|
|
88
|
-
timeWindow: '15 minutes',
|
|
89
|
-
},
|
|
90
|
-
|
|
91
|
-
// Users — profile management
|
|
92
|
-
USERS_UPDATE_PROFILE: {
|
|
93
|
-
max: applyMultiplier(10),
|
|
94
|
-
timeWindow: '1 minute',
|
|
95
|
-
},
|
|
96
|
-
USERS_CHANGE_PASSWORD: {
|
|
97
|
-
max: applyMultiplier(5),
|
|
98
|
-
timeWindow: '1 minute',
|
|
99
|
-
},
|
|
100
|
-
USERS_DELETE_ACCOUNT: {
|
|
101
|
-
max: applyMultiplier(3),
|
|
102
|
-
timeWindow: '1 minute',
|
|
103
|
-
},
|
|
104
|
-
|
|
105
|
-
// Users — avatar management
|
|
106
|
-
USERS_UPLOAD_AVATAR: {
|
|
107
|
-
max: applyMultiplier(5),
|
|
108
|
-
timeWindow: '1 minute',
|
|
109
|
-
},
|
|
110
|
-
USERS_DELETE_AVATAR: {
|
|
111
|
-
max: applyMultiplier(10),
|
|
112
|
-
timeWindow: '1 minute',
|
|
113
|
-
},
|
|
114
|
-
USERS_GET_AVATAR: {
|
|
115
|
-
max: applyMultiplier(100),
|
|
116
|
-
timeWindow: '1 minute',
|
|
117
|
-
},
|
|
143
|
+
// Auth routes (no auto-block strikes; login also has the email + IP lockout)
|
|
144
|
+
AUTH_REGISTER: routeLimit('AUTH_REGISTER', 40, '1h'),
|
|
145
|
+
AUTH_LOGIN: routeLimit('AUTH_LOGIN', 100, '15m'),
|
|
146
|
+
AUTH_LOGOUT: routeLimit('AUTH_LOGOUT', 200, '15m'),
|
|
147
|
+
AUTH_REFRESH: routeLimit('AUTH_REFRESH', 200, '15m'),
|
|
148
|
+
AUTH_ME: routeLimit('AUTH_ME', 200, '1m'),
|
|
149
|
+
AUTH_SESSIONS: routeLimit('AUTH_SESSIONS', 30, '1m'),
|
|
150
|
+
AUTH_LOGOUT_ALL: routeLimit('AUTH_LOGOUT_ALL', 10, '15m'),
|
|
151
|
+
// Sends an email: also capped per address by EMAIL_PER_ADDRESS.
|
|
152
|
+
AUTH_FORGOT_PASSWORD: routeLimit('AUTH_FORGOT_PASSWORD', 20, '15m'),
|
|
153
|
+
AUTH_RESET_PASSWORD: routeLimit('AUTH_RESET_PASSWORD', 100, '15m'),
|
|
154
|
+
|
|
155
|
+
// Users — profile management (the admin /users/:userId/... routes share these)
|
|
156
|
+
USERS_UPDATE_PROFILE: routeLimit('USERS_UPDATE_PROFILE', 30, '1m'),
|
|
157
|
+
// Checks the current password: kept low so a stolen session cannot guess it.
|
|
158
|
+
USERS_CHANGE_PASSWORD: routeLimit('USERS_CHANGE_PASSWORD', 10, '15m'),
|
|
159
|
+
USERS_DELETE_ACCOUNT: routeLimit('USERS_DELETE_ACCOUNT', 10, '1m'),
|
|
160
|
+
|
|
161
|
+
// Users — avatar management (an upload decodes up to 50 MP: real CPU work)
|
|
162
|
+
USERS_UPLOAD_AVATAR: routeLimit('USERS_UPLOAD_AVATAR', 10, '1m'),
|
|
163
|
+
USERS_DELETE_AVATAR: routeLimit('USERS_DELETE_AVATAR', 30, '1m'),
|
|
118
164
|
|
|
119
165
|
// Files — auth-gated private file streaming
|
|
120
|
-
FILES_GET:
|
|
121
|
-
max: applyMultiplier(100),
|
|
122
|
-
timeWindow: '1 minute',
|
|
123
|
-
},
|
|
166
|
+
FILES_GET: routeLimit('FILES_GET', 100, '1m'),
|
|
124
167
|
|
|
125
168
|
// Admin routes
|
|
126
|
-
ADMIN_DEFAULT:
|
|
127
|
-
max: applyMultiplier(30),
|
|
128
|
-
timeWindow: '1 minute',
|
|
129
|
-
},
|
|
169
|
+
ADMIN_DEFAULT: routeLimit('ADMIN_DEFAULT', 30, '1m'),
|
|
130
170
|
} as const;
|
|
131
171
|
|
|
132
|
-
|
|
172
|
+
/** Any route without its own entry (own counter per route), and unknown URLs. */
|
|
173
|
+
export const DEFAULT_LIMIT: RouteLimit = routeLimit('DEFAULT', 200, '1m');
|
|
133
174
|
|
|
134
|
-
/**
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
175
|
+
/** Emails to one address per window, applied to each email counter (src/libs/email-quota.ts). */
|
|
176
|
+
export const EMAIL_PER_ADDRESS: RouteLimit = routeLimit('EMAIL_PER_ADDRESS', 3, '1h');
|
|
177
|
+
|
|
178
|
+
// ─── Boot checks ───────────────────────────────────────────────
|
|
179
|
+
|
|
180
|
+
// Checked only now, so entries appended to RATE_LIMITS (email-verification module)
|
|
181
|
+
// count as known names.
|
|
182
|
+
const VALID_OVERRIDE_NAMES = [...Object.keys(RATE_LIMITS), 'DEFAULT', 'EMAIL_PER_ADDRESS'];
|
|
183
|
+
const unknownNames = unknownOverrideNames(OVERRIDES, VALID_OVERRIDE_NAMES);
|
|
184
|
+
if (unknownNames.length > 0) {
|
|
185
|
+
failBoot(`unknown name(s): ${unknownNames.join(', ')}. Valid names: ${VALID_OVERRIDE_NAMES.join(', ')}`);
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
// Removed variables: say so instead of silently changing a deployment's limits.
|
|
189
|
+
for (const removed of ['RATE_LIMIT_AUTH_LOGIN_MAX', 'RATE_LIMIT_AUTH_REGISTER_MAX']) {
|
|
190
|
+
if (process.env[removed]) {
|
|
191
|
+
logger.warn(
|
|
192
|
+
`[RATE-LIMIT] ${removed} is no longer read and its value is ignored. ` +
|
|
193
|
+
'Use RATE_LIMIT_OVERRIDES instead, e.g. RATE_LIMIT_OVERRIDES=AUTH_LOGIN=100/15m',
|
|
194
|
+
);
|
|
144
195
|
}
|
|
145
196
|
}
|
|
@@ -1,14 +1,18 @@
|
|
|
1
1
|
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
|
2
2
|
import { prisma } from '@libs/prisma.js';
|
|
3
3
|
import { fileStorageService } from '@libs/storage/file-storage.service.js';
|
|
4
|
-
import {
|
|
4
|
+
import type { FastifyInstance } from 'fastify';
|
|
5
|
+
import { logger } from '@libs/logger.js';
|
|
6
|
+
import { purgeDeletedAccounts, startCleanupDeletedAccountsJob } from '../cleanup-deleted-accounts.job.js';
|
|
5
7
|
|
|
6
8
|
// The purge must complete for every account past retention: one failing
|
|
7
|
-
// account is logged and skipped, never blocks the rest
|
|
8
|
-
//
|
|
9
|
+
// account is logged and skipped, never blocks the rest. Files go first and the
|
|
10
|
+
// row last, so an account whose files could not be removed stays in the
|
|
11
|
+
// database and is retried by the next run.
|
|
9
12
|
|
|
10
13
|
vi.mock('@libs/prisma.js', () => ({
|
|
11
14
|
prisma: { user: { findMany: vi.fn(), delete: vi.fn() } },
|
|
15
|
+
isPrismaNotFound: (e: unknown): boolean => (e as { code?: string })?.code === 'P2025',
|
|
12
16
|
}));
|
|
13
17
|
vi.mock('@libs/storage/file-storage.service.js', () => ({
|
|
14
18
|
fileStorageService: { deleteUserMedia: vi.fn() },
|
|
@@ -43,16 +47,64 @@ describe('purgeDeletedAccounts', () => {
|
|
|
43
47
|
const result = await purgeDeletedAccounts();
|
|
44
48
|
|
|
45
49
|
expect(result).toEqual({ found: 3, purged: 2, failed: 1 });
|
|
46
|
-
|
|
47
|
-
expect(fileStorageService.deleteUserMedia).toHaveBeenCalledTimes(2);
|
|
48
|
-
expect(fileStorageService.deleteUserMedia).not.toHaveBeenCalledWith('b');
|
|
50
|
+
expect(prisma.user.delete).toHaveBeenCalledTimes(3);
|
|
49
51
|
});
|
|
50
52
|
|
|
51
|
-
it('
|
|
53
|
+
it('removes the files before the row', async () => {
|
|
52
54
|
vi.mocked(prisma.user.findMany).mockResolvedValue([{ id: 'a' }] as never);
|
|
53
55
|
vi.mocked(prisma.user.delete).mockResolvedValue({} as never);
|
|
54
|
-
|
|
56
|
+
|
|
57
|
+
await purgeDeletedAccounts();
|
|
58
|
+
|
|
59
|
+
const filesAt = vi.mocked(fileStorageService.deleteUserMedia).mock.invocationCallOrder[0];
|
|
60
|
+
const rowAt = vi.mocked(prisma.user.delete).mock.invocationCallOrder[0];
|
|
61
|
+
expect(filesAt).toBeLessThan(rowAt);
|
|
62
|
+
});
|
|
63
|
+
|
|
64
|
+
it('keeps the row when its files cannot be removed, so the next run retries', async () => {
|
|
65
|
+
vi.mocked(prisma.user.findMany).mockResolvedValue([{ id: 'a' }, { id: 'b' }] as never);
|
|
66
|
+
vi.mocked(prisma.user.delete).mockResolvedValue({} as never);
|
|
67
|
+
vi.mocked(fileStorageService.deleteUserMedia).mockImplementation(async (id: string) => {
|
|
68
|
+
if (id === 'a') throw new Error('disk');
|
|
69
|
+
});
|
|
70
|
+
|
|
71
|
+
await expect(purgeDeletedAccounts()).resolves.toEqual({ found: 2, purged: 1, failed: 1 });
|
|
72
|
+
expect(prisma.user.delete).toHaveBeenCalledTimes(1);
|
|
73
|
+
expect(prisma.user.delete).not.toHaveBeenCalledWith({ where: { id: 'a' } });
|
|
74
|
+
});
|
|
75
|
+
|
|
76
|
+
it('an account another process purged a moment ago counts as purged, without an error log', async () => {
|
|
77
|
+
vi.mocked(prisma.user.findMany).mockResolvedValue([{ id: 'z' }] as never);
|
|
78
|
+
vi.mocked(fileStorageService.deleteUserMedia).mockResolvedValue(undefined);
|
|
79
|
+
vi.mocked(prisma.user.delete).mockRejectedValue(Object.assign(new Error('not found'), { code: 'P2025' }));
|
|
55
80
|
|
|
56
81
|
await expect(purgeDeletedAccounts()).resolves.toEqual({ found: 1, purged: 1, failed: 0 });
|
|
82
|
+
expect(logger.error).not.toHaveBeenCalled();
|
|
83
|
+
});
|
|
84
|
+
|
|
85
|
+
it('logs one line per run even when nothing was due (so the log shows it runs)', async () => {
|
|
86
|
+
vi.mocked(prisma.user.findMany).mockResolvedValue([]);
|
|
87
|
+
await purgeDeletedAccounts();
|
|
88
|
+
expect(logger.info).toHaveBeenCalledWith(
|
|
89
|
+
{ purgedCount: 0, failedCount: 0, totalFound: 0 },
|
|
90
|
+
'Deleted accounts purge complete',
|
|
91
|
+
);
|
|
57
92
|
});
|
|
58
93
|
});
|
|
94
|
+
|
|
95
|
+
describe('startCleanupDeletedAccountsJob', () => {
|
|
96
|
+
it('runs about a minute after start, not a day later (a daily deploy used to postpone it forever)', async () => {
|
|
97
|
+
vi.useFakeTimers();
|
|
98
|
+
vi.clearAllMocks(); // this describe has no beforeEach of its own
|
|
99
|
+
try {
|
|
100
|
+
vi.mocked(prisma.user.findMany).mockResolvedValue([]);
|
|
101
|
+
const app = { addHook: vi.fn() } as unknown as FastifyInstance;
|
|
102
|
+
startCleanupDeletedAccountsJob(app);
|
|
103
|
+
await vi.advanceTimersByTimeAsync(60_000);
|
|
104
|
+
expect(prisma.user.findMany).toHaveBeenCalledTimes(1);
|
|
105
|
+
} finally {
|
|
106
|
+
vi.useRealTimers();
|
|
107
|
+
}
|
|
108
|
+
});
|
|
109
|
+
});
|
|
110
|
+
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The hourly auth cleanup: expired refresh tokens and sessions go from the
|
|
3
|
+
* database, expired automatic IP blocks from Redis, and it first runs about a
|
|
4
|
+
* minute after start.
|
|
5
|
+
*/
|
|
6
|
+
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
|
7
|
+
import type { FastifyInstance } from 'fastify';
|
|
8
|
+
import { prisma } from '@libs/prisma.js';
|
|
9
|
+
import { pruneExpiredAutoBlocks } from '@libs/ip-block.js';
|
|
10
|
+
import { cleanupExpiredAuth, startCleanupExpiredAuthJob } from '../cleanup-expired-auth.job.js';
|
|
11
|
+
|
|
12
|
+
vi.mock('@libs/prisma.js', () => ({
|
|
13
|
+
prisma: { refreshToken: { deleteMany: vi.fn() }, session: { deleteMany: vi.fn() } },
|
|
14
|
+
}));
|
|
15
|
+
vi.mock('@libs/ip-block.js', () => ({ pruneExpiredAutoBlocks: vi.fn() }));
|
|
16
|
+
vi.mock('@libs/logger.js', () => ({ logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() } }));
|
|
17
|
+
|
|
18
|
+
beforeEach(() => {
|
|
19
|
+
vi.clearAllMocks();
|
|
20
|
+
vi.mocked(prisma.refreshToken.deleteMany).mockResolvedValue({ count: 3 });
|
|
21
|
+
vi.mocked(prisma.session.deleteMany).mockResolvedValue({ count: 2 });
|
|
22
|
+
vi.mocked(pruneExpiredAutoBlocks).mockResolvedValue(4);
|
|
23
|
+
});
|
|
24
|
+
|
|
25
|
+
describe('cleanupExpiredAuth', () => {
|
|
26
|
+
it('removes expired tokens and sessions, and prunes expired automatic IP blocks', async () => {
|
|
27
|
+
const now = new Date('2026-10-19T12:00:00Z');
|
|
28
|
+
await expect(cleanupExpiredAuth(now)).resolves.toEqual({ tokens: 3, sessions: 2, autoBlocks: 4 });
|
|
29
|
+
expect(prisma.refreshToken.deleteMany).toHaveBeenCalledWith({ where: { expiresAt: { lt: now } } });
|
|
30
|
+
expect(prisma.session.deleteMany).toHaveBeenCalledWith({ where: { expiresAt: { lt: now } } });
|
|
31
|
+
expect(pruneExpiredAutoBlocks).toHaveBeenCalledWith(now.getTime() / 1000);
|
|
32
|
+
});
|
|
33
|
+
|
|
34
|
+
it('first runs about a minute after start', async () => {
|
|
35
|
+
vi.useFakeTimers();
|
|
36
|
+
try {
|
|
37
|
+
startCleanupExpiredAuthJob({ addHook: vi.fn() } as unknown as FastifyInstance);
|
|
38
|
+
await vi.advanceTimersByTimeAsync(60_000);
|
|
39
|
+
expect(prisma.session.deleteMany).toHaveBeenCalledTimes(1);
|
|
40
|
+
} finally {
|
|
41
|
+
vi.useRealTimers();
|
|
42
|
+
}
|
|
43
|
+
});
|
|
44
|
+
});
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The background jobs' work against a real MySQL and Redis (the layer 6
|
|
3
|
+
* guarantees). Their timing (first run about a minute after every start,
|
|
4
|
+
* then on the interval) is covered by schedule.test.ts; here each job runs
|
|
5
|
+
* once, directly, on data made for it.
|
|
6
|
+
* - The purge removes accounts deleted more than 30 days ago and keeps the
|
|
7
|
+
* recent ones; two purges at once (two server processes) both succeed.
|
|
8
|
+
* - The auth cleanup removes expired sessions and refresh tokens, keeps live
|
|
9
|
+
* ones, and prunes expired automatic IP blocks while keeping running ones.
|
|
10
|
+
*/
|
|
11
|
+
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
|
|
12
|
+
import type { FastifyInstance } from 'fastify';
|
|
13
|
+
import { PASSWORD, buildTestApp, call, db, redis, registerUser, signIn } from '@/test/integration-helpers.js';
|
|
14
|
+
|
|
15
|
+
let app: FastifyInstance;
|
|
16
|
+
|
|
17
|
+
beforeAll(async () => {
|
|
18
|
+
app = await buildTestApp();
|
|
19
|
+
});
|
|
20
|
+
|
|
21
|
+
afterAll(async () => {
|
|
22
|
+
await app?.close();
|
|
23
|
+
});
|
|
24
|
+
|
|
25
|
+
const DAY_MS = 86_400_000;
|
|
26
|
+
|
|
27
|
+
/** A registered, then self-deleted account, its deletion moved `daysAgo` back. */
|
|
28
|
+
async function deletedAccount(tag: string, daysAgo: number): Promise<string> {
|
|
29
|
+
const u = await registerUser(app, tag);
|
|
30
|
+
expect((await call(app, 'DELETE', '/users/me', { jar: u.jar, payload: { password: PASSWORD } })).status).toBe(200);
|
|
31
|
+
await (await db()).user.update({ where: { id: u.id }, data: { deletedAt: new Date(Date.now() - daysAgo * DAY_MS) } });
|
|
32
|
+
return u.id;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
describe('purge of deleted accounts', () => {
|
|
36
|
+
it('removes the account deleted 31 days ago and keeps the one deleted just now', async () => {
|
|
37
|
+
const old = await deletedAccount('purge-old', 31);
|
|
38
|
+
const recent = await deletedAccount('purge-recent', 0);
|
|
39
|
+
const { purgeDeletedAccounts } = await import('@jobs/cleanup-deleted-accounts.job.js');
|
|
40
|
+
const result = await purgeDeletedAccounts();
|
|
41
|
+
expect(result.failed).toBe(0);
|
|
42
|
+
expect(await (await db()).user.count({ where: { id: old } })).toBe(0);
|
|
43
|
+
const kept = await (await db()).user.findUnique({ where: { id: recent }, select: { deletedAt: true } });
|
|
44
|
+
expect(kept).not.toBeNull();
|
|
45
|
+
expect(kept?.deletedAt).not.toBeNull();
|
|
46
|
+
});
|
|
47
|
+
|
|
48
|
+
it('two purges at once (two server processes) both finish without a failure; every account is gone', async () => {
|
|
49
|
+
// Several accounts, so the two runs work on the same rows at the same time.
|
|
50
|
+
// Here both usually read a row before either deletes it, and the second
|
|
51
|
+
// DELETE simply removes nothing. The other order (the row is gone before
|
|
52
|
+
// the read, Prisma P2025) is pinned by cleanup-deleted-accounts.job.test.ts.
|
|
53
|
+
const ids = await Promise.all([0, 1, 2, 3, 4, 5].map((i) => deletedAccount(`purge-race-${i}`, 40)));
|
|
54
|
+
const { purgeDeletedAccounts } = await import('@jobs/cleanup-deleted-accounts.job.js');
|
|
55
|
+
const results = await Promise.all([purgeDeletedAccounts(), purgeDeletedAccounts()]);
|
|
56
|
+
expect(results.map((r) => r.failed)).toEqual([0, 0]);
|
|
57
|
+
expect(await (await db()).user.count({ where: { id: { in: ids } } })).toBe(0);
|
|
58
|
+
});
|
|
59
|
+
});
|
|
60
|
+
|
|
61
|
+
describe('cleanup of expired auth records', () => {
|
|
62
|
+
it('removes an expired session and its refresh token; the live session stays', async () => {
|
|
63
|
+
const u = await registerUser(app, 'cleanup');
|
|
64
|
+
await signIn(app, u.email); // a second session
|
|
65
|
+
const prisma = await db();
|
|
66
|
+
const [expired] = await prisma.session.findMany({ where: { userId: u.id }, orderBy: { createdAt: 'asc' }, take: 1 });
|
|
67
|
+
const past = new Date(Date.now() - 3_600_000);
|
|
68
|
+
await prisma.session.update({ where: { id: expired.id }, data: { expiresAt: past } });
|
|
69
|
+
await prisma.refreshToken.updateMany({ where: { sessionId: expired.id }, data: { expiresAt: past } });
|
|
70
|
+
|
|
71
|
+
const { cleanupExpiredAuth } = await import('@jobs/cleanup-expired-auth.job.js');
|
|
72
|
+
await cleanupExpiredAuth();
|
|
73
|
+
expect(await prisma.session.count({ where: { id: expired.id } })).toBe(0);
|
|
74
|
+
expect(await prisma.refreshToken.count({ where: { sessionId: expired.id } })).toBe(0);
|
|
75
|
+
expect(await prisma.session.count({ where: { userId: u.id } })).toBe(1);
|
|
76
|
+
});
|
|
77
|
+
|
|
78
|
+
it('prunes an automatic IP block that ended and keeps one still running', async () => {
|
|
79
|
+
const now = Math.floor(Date.now() / 1000);
|
|
80
|
+
await (await redis()).zadd('auto_blocked_ips', now - 100, '203.0.113.201', now + 3600, '203.0.113.202');
|
|
81
|
+
const { cleanupExpiredAuth } = await import('@jobs/cleanup-expired-auth.job.js');
|
|
82
|
+
const result = await cleanupExpiredAuth();
|
|
83
|
+
expect(result.autoBlocks).toBeGreaterThanOrEqual(1);
|
|
84
|
+
expect(await (await redis()).zscore('auto_blocked_ips', '203.0.113.201')).toBeNull();
|
|
85
|
+
expect(await (await redis()).zscore('auto_blocked_ips', '203.0.113.202')).not.toBeNull();
|
|
86
|
+
await (await redis()).zrem('auto_blocked_ips', '203.0.113.202');
|
|
87
|
+
});
|
|
88
|
+
});
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* startRecurringJob (jobs/schedule.ts) with fake timers: a job runs once
|
|
3
|
+
* shortly after start, then on its interval; a failing run is logged and the
|
|
4
|
+
* schedule goes on; runs never overlap; app close stops it.
|
|
5
|
+
*/
|
|
6
|
+
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
|
7
|
+
import type { FastifyInstance } from 'fastify';
|
|
8
|
+
import { logger } from '@libs/logger.js';
|
|
9
|
+
import { startRecurringJob } from '../schedule.js';
|
|
10
|
+
|
|
11
|
+
vi.mock('@libs/logger.js', () => ({ logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() } }));
|
|
12
|
+
|
|
13
|
+
const MINUTE = 60_000;
|
|
14
|
+
const HOUR = 60 * MINUTE;
|
|
15
|
+
|
|
16
|
+
/** A stand-in app that records onClose hooks so the test can "close" it. */
|
|
17
|
+
function fakeApp(): { app: FastifyInstance; close: () => Promise<void> } {
|
|
18
|
+
const hooks: Array<() => Promise<void>> = [];
|
|
19
|
+
const app = {
|
|
20
|
+
addHook: (name: string, fn: () => Promise<void>): void => {
|
|
21
|
+
if (name === 'onClose') hooks.push(fn);
|
|
22
|
+
},
|
|
23
|
+
};
|
|
24
|
+
const close = async (): Promise<void> => {
|
|
25
|
+
for (const h of hooks) await h();
|
|
26
|
+
};
|
|
27
|
+
return { app: app as unknown as FastifyInstance, close };
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
beforeEach(() => {
|
|
31
|
+
vi.useFakeTimers();
|
|
32
|
+
vi.clearAllMocks();
|
|
33
|
+
});
|
|
34
|
+
afterEach(() => {
|
|
35
|
+
vi.useRealTimers();
|
|
36
|
+
});
|
|
37
|
+
|
|
38
|
+
describe('startRecurringJob', () => {
|
|
39
|
+
it('runs once shortly after start, then every interval (a restart never postpones it a full interval)', async () => {
|
|
40
|
+
const run = vi.fn(async () => undefined);
|
|
41
|
+
startRecurringJob(fakeApp().app, { name: 't', intervalMs: HOUR, firstRunDelayMs: MINUTE, run });
|
|
42
|
+
|
|
43
|
+
await vi.advanceTimersByTimeAsync(MINUTE - 1);
|
|
44
|
+
expect(run).not.toHaveBeenCalled();
|
|
45
|
+
await vi.advanceTimersByTimeAsync(1);
|
|
46
|
+
expect(run).toHaveBeenCalledTimes(1); // one minute after start, not one hour
|
|
47
|
+
await vi.advanceTimersByTimeAsync(HOUR);
|
|
48
|
+
expect(run).toHaveBeenCalledTimes(2);
|
|
49
|
+
});
|
|
50
|
+
|
|
51
|
+
it('logs a failing run and keeps the schedule going', async () => {
|
|
52
|
+
const run = vi.fn().mockRejectedValueOnce(new Error('db down')).mockResolvedValue(undefined);
|
|
53
|
+
startRecurringJob(fakeApp().app, { name: 'purge', intervalMs: HOUR, firstRunDelayMs: MINUTE, run });
|
|
54
|
+
|
|
55
|
+
await vi.advanceTimersByTimeAsync(MINUTE);
|
|
56
|
+
expect(logger.error).toHaveBeenCalledWith(expect.objectContaining({ job: 'purge' }), '[JOB] purge failed');
|
|
57
|
+
await vi.advanceTimersByTimeAsync(HOUR);
|
|
58
|
+
expect(run).toHaveBeenCalledTimes(2);
|
|
59
|
+
});
|
|
60
|
+
|
|
61
|
+
it('skips a tick while the previous run is still busy (runs never overlap)', async () => {
|
|
62
|
+
let finish!: () => void;
|
|
63
|
+
const run = vi.fn(() => new Promise<void>((resolve) => { finish = resolve; }));
|
|
64
|
+
startRecurringJob(fakeApp().app, { name: 'slow', intervalMs: MINUTE, firstRunDelayMs: MINUTE, run });
|
|
65
|
+
|
|
66
|
+
await vi.advanceTimersByTimeAsync(MINUTE); // first run starts and hangs
|
|
67
|
+
await vi.advanceTimersByTimeAsync(MINUTE); // interval tick while busy: skipped
|
|
68
|
+
expect(run).toHaveBeenCalledTimes(1);
|
|
69
|
+
finish();
|
|
70
|
+
await vi.advanceTimersByTimeAsync(MINUTE);
|
|
71
|
+
expect(run).toHaveBeenCalledTimes(2);
|
|
72
|
+
});
|
|
73
|
+
|
|
74
|
+
it('stops when the app closes', async () => {
|
|
75
|
+
const run = vi.fn(async () => undefined);
|
|
76
|
+
const { app, close } = fakeApp();
|
|
77
|
+
startRecurringJob(app, { name: 't', intervalMs: HOUR, firstRunDelayMs: MINUTE, run });
|
|
78
|
+
await close();
|
|
79
|
+
await vi.advanceTimersByTimeAsync(2 * HOUR);
|
|
80
|
+
expect(run).not.toHaveBeenCalled();
|
|
81
|
+
});
|
|
82
|
+
|
|
83
|
+
it('does not keep the process alive on its own (timers are unref-ed)', () => {
|
|
84
|
+
const unref = vi.fn();
|
|
85
|
+
const spyTimeout = vi.spyOn(globalThis, 'setTimeout').mockReturnValue({ unref } as never);
|
|
86
|
+
const spyInterval = vi.spyOn(globalThis, 'setInterval').mockReturnValue({ unref } as never);
|
|
87
|
+
startRecurringJob(fakeApp().app, { name: 't', intervalMs: HOUR, firstRunDelayMs: MINUTE, run: async () => undefined });
|
|
88
|
+
expect(unref).toHaveBeenCalledTimes(2);
|
|
89
|
+
spyTimeout.mockRestore();
|
|
90
|
+
spyInterval.mockRestore();
|
|
91
|
+
});
|
|
92
|
+
});
|