create-tigra 3.3.0 → 4.0.1
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/CHANGELOG.md +151 -0
- package/README.md +264 -56
- package/bin/create-tigra.js +497 -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 +5 -3
- 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/README.md +79 -0
- 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/README.md +92 -21
- 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/README.md +108 -0
- package/template/server/docker-compose.yml +4 -2
- package/template/server/docs/deployment.md +63 -0
- package/template/server/docs/logging.md +66 -4
- package/template/server/docs/rate-limits.md +153 -0
- package/template/server/docs/testing.md +81 -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
|
@@ -2,21 +2,32 @@
|
|
|
2
2
|
* Cleanup Deleted Accounts Job
|
|
3
3
|
*
|
|
4
4
|
* Permanently purges soft-deleted user accounts after a 30-day retention period.
|
|
5
|
-
*
|
|
6
|
-
*
|
|
7
|
-
*
|
|
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).
|
|
8
8
|
*
|
|
9
|
-
*
|
|
10
|
-
*
|
|
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.
|
|
11
19
|
*/
|
|
12
20
|
|
|
13
21
|
import type { FastifyInstance } from 'fastify';
|
|
14
|
-
import { prisma } from '@libs/prisma.js';
|
|
22
|
+
import { prisma, isPrismaNotFound } from '@libs/prisma.js';
|
|
15
23
|
import { logger } from '@libs/logger.js';
|
|
16
24
|
import { fileStorageService } from '@libs/storage/file-storage.service.js';
|
|
25
|
+
import { startRecurringJob } from './schedule.js';
|
|
17
26
|
|
|
18
27
|
const INTERVAL_MS = 24 * 60 * 60 * 1000; // 24 hours
|
|
19
|
-
const
|
|
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;
|
|
20
31
|
|
|
21
32
|
export interface PurgeResult {
|
|
22
33
|
found: number;
|
|
@@ -49,30 +60,24 @@ export async function purgeDeletedAccounts(now: Date = new Date()): Promise<Purg
|
|
|
49
60
|
});
|
|
50
61
|
|
|
51
62
|
const result: PurgeResult = { found: usersToDelete.length, purged: 0, failed: 0 };
|
|
52
|
-
if (usersToDelete.length === 0) {
|
|
53
|
-
return result;
|
|
54
|
-
}
|
|
55
|
-
|
|
56
|
-
logger.info({ count: usersToDelete.length }, 'Starting purge of soft-deleted accounts');
|
|
57
63
|
|
|
58
64
|
for (const user of usersToDelete) {
|
|
59
65
|
try {
|
|
60
|
-
//
|
|
61
|
-
//
|
|
62
|
-
|
|
63
|
-
// The reverse (files deleted, DB intact) would leave a dangling user record.
|
|
64
|
-
await prisma.user.delete({
|
|
65
|
-
where: { id: user.id },
|
|
66
|
-
});
|
|
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);
|
|
67
69
|
|
|
68
|
-
//
|
|
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.
|
|
69
72
|
try {
|
|
70
|
-
await
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
)
|
|
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
83
|
result.purged++;
|
|
@@ -82,6 +87,8 @@ export async function purgeDeletedAccounts(now: Date = new Date()): Promise<Purg
|
|
|
82
87
|
}
|
|
83
88
|
}
|
|
84
89
|
|
|
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).
|
|
85
92
|
logger.info(
|
|
86
93
|
{ purgedCount: result.purged, failedCount: result.failed, totalFound: result.found },
|
|
87
94
|
'Deleted accounts purge complete',
|
|
@@ -90,15 +97,10 @@ export async function purgeDeletedAccounts(now: Date = new Date()): Promise<Purg
|
|
|
90
97
|
}
|
|
91
98
|
|
|
92
99
|
export function startCleanupDeletedAccountsJob(app: FastifyInstance): void {
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
}
|
|
99
|
-
}, INTERVAL_MS);
|
|
100
|
-
|
|
101
|
-
app.addHook('onClose', async () => {
|
|
102
|
-
clearInterval(intervalId);
|
|
100
|
+
startRecurringJob(app, {
|
|
101
|
+
name: 'purge-deleted-accounts',
|
|
102
|
+
intervalMs: INTERVAL_MS,
|
|
103
|
+
firstRunDelayMs: FIRST_RUN_DELAY_MS,
|
|
104
|
+
run: () => purgeDeletedAccounts(),
|
|
103
105
|
});
|
|
104
106
|
}
|
|
@@ -1,41 +1,49 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Cleanup Expired Auth Records Job
|
|
3
3
|
*
|
|
4
|
-
*
|
|
5
|
-
* Runs
|
|
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
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
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
|
-
|
|
20
|
-
|
|
21
|
-
|
|
26
|
+
const deletedSessions = await prisma.session.deleteMany({
|
|
27
|
+
where: { expiresAt: { lt: now } },
|
|
28
|
+
});
|
|
22
29
|
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
});
|
|
30
|
+
// Redis, separate from the database: never fails the pass (fail-open).
|
|
31
|
+
const autoBlocks = await pruneExpiredAutoBlocks(now.getTime() / 1000);
|
|
26
32
|
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
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
|
-
|
|
39
|
-
|
|
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
|
-
*
|
|
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
|
+
}
|
|
@@ -2,13 +2,14 @@ import { describe, it, expect, vi, beforeEach } from 'vitest';
|
|
|
2
2
|
import type { FastifyReply, FastifyRequest } from 'fastify';
|
|
3
3
|
import { prisma } from '@libs/prisma.js';
|
|
4
4
|
import { clearAuthCookies } from '@libs/cookies.js';
|
|
5
|
-
import { authenticate, authorize } from '../auth.js';
|
|
5
|
+
import { authenticate, authorize, resolveMe, resolveTargetUser } from '../auth.js';
|
|
6
6
|
|
|
7
|
-
// authenticate() is the single per-request gate:
|
|
8
|
-
// the database (not the token)
|
|
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.
|
|
9
10
|
|
|
10
11
|
vi.mock('@libs/prisma.js', () => ({
|
|
11
|
-
prisma: { user: { findUnique: vi.fn() } },
|
|
12
|
+
prisma: { session: { findFirst: vi.fn() }, user: { findUnique: vi.fn() } },
|
|
12
13
|
}));
|
|
13
14
|
vi.mock('@libs/cookies.js', () => ({ clearAuthCookies: vi.fn() }));
|
|
14
15
|
|
|
@@ -19,9 +20,10 @@ type DbUser = {
|
|
|
19
20
|
role: 'USER' | 'ADMIN';
|
|
20
21
|
};
|
|
21
22
|
|
|
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 {
|
|
23
25
|
const request = {
|
|
24
|
-
user: { userId: 'user-1', role: tokenRole },
|
|
26
|
+
user: { userId: 'user-1', role: tokenRole, ...(sessionId === null ? {} : { sessionId }) },
|
|
25
27
|
jwtVerify: vi.fn().mockResolvedValue(undefined),
|
|
26
28
|
};
|
|
27
29
|
return request as unknown as FastifyRequest;
|
|
@@ -29,8 +31,9 @@ function makeRequest(tokenRole: 'USER' | 'ADMIN'): FastifyRequest {
|
|
|
29
31
|
|
|
30
32
|
const reply = {} as FastifyReply;
|
|
31
33
|
|
|
34
|
+
/** The live session found for the token, carrying its user's current state. */
|
|
32
35
|
function mockDbUser(user: DbUser | null): void {
|
|
33
|
-
vi.mocked(prisma.
|
|
36
|
+
vi.mocked(prisma.session.findFirst).mockResolvedValue({ user } as never);
|
|
34
37
|
}
|
|
35
38
|
|
|
36
39
|
describe('authenticate', () => {
|
|
@@ -74,4 +77,92 @@ describe('authenticate', () => {
|
|
|
74
77
|
await expect(authenticate(makeRequest('USER'), reply)).rejects.toMatchObject({ statusCode: 401 });
|
|
75
78
|
expect(clearAuthCookies).toHaveBeenCalledWith(reply);
|
|
76
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
|
+
});
|
|
77
168
|
});
|