create-tigra 3.1.1 → 3.3.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 +1 -1
- package/bin/create-tigra.js +6 -5
- package/lib/patchers/email-verification.patcher.js +93 -39
- package/modules/email-verification/server/verification.service.ts +38 -9
- package/package.json +1 -1
- package/template/.claude/skills/security-audit/SKILL.md +10 -0
- package/template/AGENTS.md +18 -2
- package/template/CLAUDE.md +1 -0
- package/template/client/CLAUDE.md +1 -0
- package/template/client/src/features/auth/components/AuthInitializer.tsx +4 -2
- package/template/client/src/features/auth/components/LoginForm.tsx +5 -2
- package/template/client/src/features/auth/hooks/useAuth.ts +16 -6
- package/template/client/src/features/auth/types/auth.types.ts +3 -0
- package/template/client/src/instrumentation-client.ts +9 -1
- package/template/client/src/instrumentation.ts +6 -0
- package/template/client/src/lib/observability/sentry-scrub.ts +71 -0
- package/template/client/src/lib/utils/error.ts +5 -1
- package/template/client/src/lib/utils/security.ts +37 -0
- package/template/server/.env.example +5 -4
- package/template/server/.env.example.production +14 -8
- package/template/server/CLAUDE.md +1 -0
- package/template/server/Dockerfile +5 -0
- package/template/server/prisma/schema.prisma +19 -3
- package/template/server/prisma/seed.ts +13 -5
- package/template/server/src/app.ts +11 -0
- package/template/server/src/config/env.ts +17 -6
- package/template/server/src/jobs/__tests__/cleanup-deleted-accounts.job.test.ts +58 -0
- package/template/server/src/jobs/cleanup-deleted-accounts.job.ts +72 -58
- package/template/server/src/libs/__tests__/auth.test.ts +77 -0
- package/template/server/src/libs/__tests__/cookies.test.ts +62 -0
- package/template/server/src/libs/__tests__/redis.test.ts +23 -0
- package/template/server/src/libs/__tests__/sentry-scrub.test.ts +80 -0
- package/template/server/src/libs/account-status.ts +52 -0
- package/template/server/src/libs/auth.ts +15 -5
- package/template/server/src/libs/cookies.ts +40 -12
- package/template/server/src/libs/ip-block.ts +3 -2
- package/template/server/src/libs/monitoring.ts +4 -1
- package/template/server/src/libs/observability/sentry.ts +80 -0
- package/template/server/src/libs/redis.ts +82 -18
- package/template/server/src/libs/storage/__tests__/image-optimizer.test.ts +84 -0
- package/template/server/src/libs/storage/file-storage.service.ts +21 -10
- package/template/server/src/libs/storage/image-optimizer.service.ts +67 -72
- package/template/server/src/modules/admin/admin.repo.ts +7 -3
- package/template/server/src/modules/admin/admin.service.ts +7 -3
- package/template/server/src/modules/auth/__tests__/auth.service.test.ts +136 -13
- package/template/server/src/modules/auth/auth.controller.ts +1 -1
- package/template/server/src/modules/auth/auth.repo.ts +20 -2
- package/template/server/src/modules/auth/auth.schemas.ts +1 -0
- package/template/server/src/modules/auth/auth.service.ts +30 -13
- package/template/server/src/modules/auth/session.repo.ts +0 -12
- package/template/server/src/modules/users/users.repo.ts +2 -0
- package/template/server/src/test/setup.ts +22 -0
|
@@ -7,6 +7,43 @@ export const isSafeUrl = (url: string): boolean => {
|
|
|
7
7
|
}
|
|
8
8
|
};
|
|
9
9
|
|
|
10
|
+
// Placeholder origin used only to parse relative paths. It never appears in
|
|
11
|
+
// output and `.invalid` can never resolve, so nothing here can point at it.
|
|
12
|
+
const REDIRECT_PARSE_BASE = 'https://redirect-check.invalid';
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* Turn an untrusted "where to go next" value (e.g. `?from=` on /login) into a
|
|
16
|
+
* same-site path, or undefined when it isn't one.
|
|
17
|
+
*
|
|
18
|
+
* A prefix check like `startsWith('/') && !startsWith('//')` is NOT enough:
|
|
19
|
+
* browsers treat `\` like `/` and silently drop tabs and newlines, so
|
|
20
|
+
* `/\evil.com` and `/<TAB>/evil.com` both become `//evil.com` — another site.
|
|
21
|
+
* The value is therefore parsed exactly like the browser will, and accepted
|
|
22
|
+
* only if it stays on our origin; we then return just path + query + hash.
|
|
23
|
+
*/
|
|
24
|
+
export const getSafeRedirectPath = (value: string | null | undefined): string | undefined => {
|
|
25
|
+
if (!value || !value.startsWith('/') || value.startsWith('//')) return undefined;
|
|
26
|
+
// Backslashes, control characters and whitespace have no place in an
|
|
27
|
+
// internal path and are exactly what the bypasses rely on.
|
|
28
|
+
if (/[\\\s\u0000-\u001f\u007f]/.test(value)) return undefined;
|
|
29
|
+
|
|
30
|
+
try {
|
|
31
|
+
const url = new URL(value, REDIRECT_PARSE_BASE);
|
|
32
|
+
if (url.origin !== REDIRECT_PARSE_BASE) return undefined;
|
|
33
|
+
const path = `${url.pathname}${url.search}${url.hash}`;
|
|
34
|
+
// Check the RESULT, not only the input: dot segments normalize away, so
|
|
35
|
+
// '/..//evil.com' or '/%2e%2e//evil.com' come out as '//evil.com', which
|
|
36
|
+
// the router would treat as another site. The path we return must itself
|
|
37
|
+
// resolve back to our origin.
|
|
38
|
+
if (path.startsWith('//') || new URL(path, REDIRECT_PARSE_BASE).origin !== REDIRECT_PARSE_BASE) {
|
|
39
|
+
return undefined;
|
|
40
|
+
}
|
|
41
|
+
return path;
|
|
42
|
+
} catch {
|
|
43
|
+
return undefined;
|
|
44
|
+
}
|
|
45
|
+
};
|
|
46
|
+
|
|
10
47
|
export const sanitizeString = (input: string): string => {
|
|
11
48
|
return input
|
|
12
49
|
.trim()
|
|
@@ -184,17 +184,18 @@ JWT_REFRESH_EXPIRY="7d"
|
|
|
184
184
|
|
|
185
185
|
# Cookie signing secret (separate from JWT for defense-in-depth)
|
|
186
186
|
# Optional: defaults to JWT_SECRET if not set
|
|
187
|
-
# For production: generate a separate secret: openssl rand -
|
|
187
|
+
# For production: generate a separate secret: openssl rand -hex 48
|
|
188
188
|
# COOLIFY: Runtime only. Do NOT check "Available at Buildtime" — this is a secret!
|
|
189
|
-
# COOKIE_SECRET="
|
|
189
|
+
# COOKIE_SECRET="CHANGE_ME_generate_with_openssl_rand_hex_48"
|
|
190
190
|
|
|
191
191
|
# Cookie domain for cross-origin deployments
|
|
192
192
|
# REQUIRED when client and API are on different subdomains:
|
|
193
193
|
# Client: https://app.example.com | API: https://api.example.com
|
|
194
194
|
# → Set COOKIE_DOMAIN=".example.com" (note the leading dot)
|
|
195
195
|
# NOT needed when client and API share the same hostname (local dev, same-origin prod)
|
|
196
|
-
#
|
|
197
|
-
#
|
|
196
|
+
# It scopes ONLY the non-secret auth_session indicator, so the client's Next.js
|
|
197
|
+
# middleware can see that a session exists. The access/refresh token cookies stay
|
|
198
|
+
# host-only on the API (never shared with other subdomains).
|
|
198
199
|
# COOKIE_DOMAIN=".example.com"
|
|
199
200
|
|
|
200
201
|
# ===================================================================
|
|
@@ -142,18 +142,21 @@ MAX_FILE_SIZE_MB=10
|
|
|
142
142
|
# JWT AUTHENTICATION
|
|
143
143
|
# ===================================================================
|
|
144
144
|
|
|
145
|
-
# CRITICAL: Generate a cryptographically secure secret
|
|
146
|
-
#
|
|
145
|
+
# CRITICAL: Generate a cryptographically secure secret: openssl rand -hex 48
|
|
146
|
+
# The value below is EXAMPLE TEXT, not a real secret. Every committed example
|
|
147
|
+
# secret starts with CHANGE_ME, and the server refuses to boot with it
|
|
148
|
+
# (src/config/env.ts), so a forgotten placeholder fails loudly.
|
|
147
149
|
# COOLIFY: Runtime only. Do NOT check "Available at Buildtime" — this is a secret!
|
|
148
|
-
JWT_SECRET="
|
|
150
|
+
JWT_SECRET="CHANGE_ME_generate_with_openssl_rand_hex_48"
|
|
149
151
|
|
|
150
152
|
# Production token expiry (tighter security)
|
|
151
153
|
JWT_ACCESS_EXPIRY="15m"
|
|
152
154
|
JWT_REFRESH_EXPIRY="7d"
|
|
153
155
|
|
|
154
|
-
# Cookie signing secret (separate from JWT for defense-in-depth)
|
|
156
|
+
# Cookie signing secret (separate from JWT for defense-in-depth).
|
|
157
|
+
# EXAMPLE TEXT: generate a different value with openssl rand -hex 48.
|
|
155
158
|
# COOLIFY: Runtime only. Do NOT check "Available at Buildtime" — this is a secret!
|
|
156
|
-
COOKIE_SECRET="
|
|
159
|
+
COOKIE_SECRET="CHANGE_ME_generate_with_openssl_rand_hex_48"
|
|
157
160
|
|
|
158
161
|
# ===================================================================
|
|
159
162
|
# CORS
|
|
@@ -167,8 +170,10 @@ CORS_ORIGIN="https://yourdomain.com,https://app.yourdomain.com"
|
|
|
167
170
|
# REQUIRED when client and API are on different subdomains:
|
|
168
171
|
# Client: https://app.example.com | API: https://api.example.com
|
|
169
172
|
# → Set COOKIE_DOMAIN=".example.com" (leading dot = all subdomains)
|
|
170
|
-
#
|
|
171
|
-
#
|
|
173
|
+
# Only the non-secret auth_session indicator uses this domain, so the client's
|
|
174
|
+
# middleware can see a session exists. The access/refresh token cookies stay
|
|
175
|
+
# host-only on the API and are never sent to other subdomains.
|
|
176
|
+
# Without it, the client keeps redirecting signed-in users to /login.
|
|
172
177
|
COOKIE_DOMAIN=".yourdomain.com"
|
|
173
178
|
|
|
174
179
|
# ===================================================================
|
|
@@ -222,7 +227,8 @@ SENTRY_ENVIRONMENT=production
|
|
|
222
227
|
# PRODUCTION CHECKLIST
|
|
223
228
|
# ===================================================================
|
|
224
229
|
# [ ] DATABASE_URL uses secure credentials and SSL
|
|
225
|
-
# [ ] JWT_SECRET is a strong random string (48
|
|
230
|
+
# [ ] JWT_SECRET is a strong random string (openssl rand -hex 48), not the CHANGE_ME example
|
|
231
|
+
# [ ] COOKIE_SECRET is a different strong random string, not the CHANGE_ME example
|
|
226
232
|
# [ ] CORS_ORIGIN is set to your exact frontend URL(s)
|
|
227
233
|
# [ ] COOKIE_DOMAIN is set if client and API are on different subdomains
|
|
228
234
|
# [ ] REDIS_URL uses authentication if Redis is exposed
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
@AGENTS.md
|
|
@@ -87,6 +87,11 @@ RUN addgroup -g 1001 -S nodejs && \
|
|
|
87
87
|
|
|
88
88
|
WORKDIR /app
|
|
89
89
|
|
|
90
|
+
# Pin production mode in the runtime image. src/config/env.ts already defaults
|
|
91
|
+
# an unset NODE_ENV to production; this keeps the image fail-closed even if that
|
|
92
|
+
# default ever changes. A runtime NODE_ENV from Coolify still overrides it.
|
|
93
|
+
ENV NODE_ENV=production
|
|
94
|
+
|
|
90
95
|
# Copy production dependencies from dependencies stage.
|
|
91
96
|
# Includes the Prisma CLI (+ its engines) installed in stage 1, which the
|
|
92
97
|
# CMD below needs for `npx prisma migrate deploy`.
|
|
@@ -20,7 +20,14 @@ model User {
|
|
|
20
20
|
lastName String
|
|
21
21
|
avatarUrl String? // SEO-friendly path: /uploads/users/{userId}/avatar/{firstName-lastName}-avatar.webp
|
|
22
22
|
role UserRole @default(USER)
|
|
23
|
+
// Admin ban switch ONLY: false = deactivated by an admin (or soft-deleted).
|
|
24
|
+
// Never use it to mean "email not verified" — that is emailVerifiedAt. Mixing
|
|
25
|
+
// the two let a banned user re-activate themselves through the verify link.
|
|
23
26
|
isActive Boolean @default(true)
|
|
27
|
+
// Set when the user proves ownership of their email (or an admin approves
|
|
28
|
+
// them). Null = not verified; login requires it only while
|
|
29
|
+
// REQUIRE_USER_VERIFICATION is on.
|
|
30
|
+
emailVerifiedAt DateTime?
|
|
24
31
|
deletedAt DateTime?
|
|
25
32
|
|
|
26
33
|
// Account lockout
|
|
@@ -51,6 +58,10 @@ model RefreshToken {
|
|
|
51
58
|
createdAt DateTime @default(now())
|
|
52
59
|
|
|
53
60
|
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
|
|
61
|
+
// A refresh token lives only as long as its session: deleting the session
|
|
62
|
+
// (logout, admin force-expire, the expiry cleanup job) deletes its tokens, so
|
|
63
|
+
// a login can never outlive the session record users and admins see.
|
|
64
|
+
session Session? @relation(fields: [sessionId], references: [id], onDelete: Cascade)
|
|
54
65
|
|
|
55
66
|
// Performance indexes for token operations and cleanup
|
|
56
67
|
@@index([userId])
|
|
@@ -70,7 +81,8 @@ model Session {
|
|
|
70
81
|
expiresAt DateTime
|
|
71
82
|
createdAt DateTime @default(now())
|
|
72
83
|
|
|
73
|
-
user
|
|
84
|
+
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
|
|
85
|
+
refreshTokens RefreshToken[]
|
|
74
86
|
|
|
75
87
|
// Performance indexes for session queries
|
|
76
88
|
@@index([userId])
|
|
@@ -83,12 +95,16 @@ model BlockedIp {
|
|
|
83
95
|
id String @id @default(uuid())
|
|
84
96
|
ip String @unique @db.VarChar(45)
|
|
85
97
|
reason String? @db.VarChar(500)
|
|
86
|
-
|
|
98
|
+
// Admin who created the block. Nullable + SetNull: deleting that admin (the
|
|
99
|
+
// 30-day account purge) must neither fail nor remove the block — the block
|
|
100
|
+
// stays in force, only "who blocked it" is lost. With a required relation the
|
|
101
|
+
// database refused the delete and the purge got stuck on that admin forever.
|
|
102
|
+
blockedBy String?
|
|
87
103
|
|
|
88
104
|
createdAt DateTime @default(now())
|
|
89
105
|
updatedAt DateTime @updatedAt
|
|
90
106
|
|
|
91
|
-
user User @relation(fields: [blockedBy], references: [id])
|
|
107
|
+
user User? @relation(fields: [blockedBy], references: [id], onDelete: SetNull)
|
|
92
108
|
|
|
93
109
|
@@map("blocked_ips")
|
|
94
110
|
}
|
|
@@ -4,18 +4,23 @@ import argon2 from 'argon2';
|
|
|
4
4
|
const prisma = new PrismaClient();
|
|
5
5
|
|
|
6
6
|
// Well-known dev-only fallbacks. NEVER used in production — the guard in
|
|
7
|
-
// main()
|
|
8
|
-
// you can override via SEED_ADMIN_PASSWORD / SEED_USER_PASSWORD.
|
|
7
|
+
// main() seeds only when NODE_ENV is explicitly development or test, and even
|
|
8
|
+
// then you can override via SEED_ADMIN_PASSWORD / SEED_USER_PASSWORD.
|
|
9
9
|
const DEV_ADMIN_PASSWORD = 'Admin123!';
|
|
10
10
|
const DEV_USER_PASSWORD = 'User123!';
|
|
11
11
|
|
|
12
|
+
// Environments where demo accounts are acceptable. Anything else, including an
|
|
13
|
+
// unset NODE_ENV, is treated as production (matching src/config/env.ts).
|
|
14
|
+
const SEEDABLE_ENVS = new Set(['development', 'test']);
|
|
15
|
+
|
|
12
16
|
async function main(): Promise<void> {
|
|
13
17
|
// Refuse to seed production: this script creates a well-known admin account
|
|
14
18
|
// (admin@example.com). On a production database that is a backdoor, not a
|
|
15
|
-
// convenience. Seed data belongs to dev/test environments only
|
|
16
|
-
|
|
19
|
+
// convenience. Seed data belongs to dev/test environments only, so the guard
|
|
20
|
+
// is an allowlist: a missing NODE_ENV must not slip through.
|
|
21
|
+
if (!SEEDABLE_ENVS.has(process.env.NODE_ENV ?? '')) {
|
|
17
22
|
console.error(
|
|
18
|
-
|
|
23
|
+
`Refusing to seed: NODE_ENV is "${process.env.NODE_ENV ?? '(unset)'}" (seeding needs development or test).\n` +
|
|
19
24
|
'The seed script creates well-known demo accounts (admin@example.com) and must never run against a production database.\n' +
|
|
20
25
|
'If you really need initial data in production, create it manually or write a dedicated, audited provisioning script.',
|
|
21
26
|
);
|
|
@@ -34,6 +39,8 @@ async function main(): Promise<void> {
|
|
|
34
39
|
firstName: 'Admin',
|
|
35
40
|
lastName: 'User',
|
|
36
41
|
role: 'ADMIN',
|
|
42
|
+
// Demo accounts are pre-verified so they can log in with email verification on.
|
|
43
|
+
emailVerifiedAt: new Date(),
|
|
37
44
|
},
|
|
38
45
|
});
|
|
39
46
|
|
|
@@ -46,6 +53,7 @@ async function main(): Promise<void> {
|
|
|
46
53
|
firstName: 'Test',
|
|
47
54
|
lastName: 'User',
|
|
48
55
|
role: 'USER',
|
|
56
|
+
emailVerifiedAt: new Date(),
|
|
49
57
|
},
|
|
50
58
|
});
|
|
51
59
|
|
|
@@ -23,6 +23,7 @@ import { fileStorageService } from '@libs/storage/file-storage.service.js';
|
|
|
23
23
|
import { registerJobs } from '@jobs/index.js';
|
|
24
24
|
import { RATE_LIMIT_ENABLED, getRateLimitRedisStore } from '@config/rate-limit.config.js';
|
|
25
25
|
import { isIpBlocked, recordRateLimitViolation, syncBlockedIpsToRedis } from '@libs/ip-block.js';
|
|
26
|
+
import { onRedisReady } from '@libs/redis.js';
|
|
26
27
|
import { getClientIp } from '@libs/client-ip.js';
|
|
27
28
|
import { isAuthPath } from '@libs/auth-path.js';
|
|
28
29
|
import { isOriginAllowed } from '@libs/origin-check.js';
|
|
@@ -157,6 +158,16 @@ export async function buildApp(): Promise<FastifyInstance> {
|
|
|
157
158
|
|
|
158
159
|
// --- Sync permanent IP blocks from DB to Redis ---
|
|
159
160
|
await syncBlockedIpsToRedis();
|
|
161
|
+
// Permanent blocks live in MySQL and are only *enforced* through Redis. A
|
|
162
|
+
// restarted Redis (or one that was down at boot) comes back without them, so
|
|
163
|
+
// re-sync on every reconnect instead of waiting for a server restart.
|
|
164
|
+
// syncBlockedIpsToRedis never throws (it logs and returns on failure).
|
|
165
|
+
const stopResyncOnReconnect = onRedisReady(() => {
|
|
166
|
+
void syncBlockedIpsToRedis();
|
|
167
|
+
});
|
|
168
|
+
app.addHook('onClose', async () => {
|
|
169
|
+
stopResyncOnReconnect();
|
|
170
|
+
});
|
|
160
171
|
|
|
161
172
|
// Monitoring endpoints exempt from IP blocking and request logging.
|
|
162
173
|
// Health probes (Coolify/Docker/K8s/load balancers) come from infrastructure
|
|
@@ -20,7 +20,11 @@ const optionalEnv = <T extends z.ZodTypeAny>(schema: T): z.ZodPreprocess<T> =>
|
|
|
20
20
|
|
|
21
21
|
const envSchema = z.object({
|
|
22
22
|
// --- Application ---
|
|
23
|
-
|
|
23
|
+
// Fail-closed default: an unset NODE_ENV means production. Development mode
|
|
24
|
+
// deliberately relaxes CORS, the Origin check and Secure cookies, so a
|
|
25
|
+
// deployment that forgets NODE_ENV must not silently land there. Local dev
|
|
26
|
+
// gets NODE_ENV=development from the generated .env; tests set 'test'.
|
|
27
|
+
NODE_ENV: optionalEnv(z.enum(['development', 'production', 'test']).default('production')),
|
|
24
28
|
PORT: optionalEnv(z.coerce.number().int().min(1).max(65535).default(8000)),
|
|
25
29
|
HOST: optionalEnv(z.string().default('0.0.0.0')),
|
|
26
30
|
|
|
@@ -39,6 +43,8 @@ const envSchema = z.object({
|
|
|
39
43
|
|
|
40
44
|
// --- Redis ---
|
|
41
45
|
REDIS_URL: optionalEnv(z.string().default('redis://localhost:6379')),
|
|
46
|
+
// Retries for a single Redis command. The connection itself reconnects
|
|
47
|
+
// forever with capped backoff (see src/libs/redis.ts).
|
|
42
48
|
REDIS_MAX_RETRIES: optionalEnv(z.coerce.number().int().min(0).default(3)),
|
|
43
49
|
REDIS_CONNECT_TIMEOUT: optionalEnv(z.coerce.number().int().min(1000).default(10000)), // ms
|
|
44
50
|
|
|
@@ -82,8 +88,10 @@ const envSchema = z.object({
|
|
|
82
88
|
JWT_SECRET: z
|
|
83
89
|
.string()
|
|
84
90
|
.min(32, 'JWT_SECRET must be at least 32 characters')
|
|
85
|
-
//
|
|
86
|
-
//
|
|
91
|
+
// Every secret committed in the template's .env.example files is example
|
|
92
|
+
// text starting with CHANGE_ME (43 chars, so it would pass min(32)). This
|
|
93
|
+
// guard is what stops an app from booting with that publicly-known signing
|
|
94
|
+
// key. Keep any new example secret on the CHANGE_ME prefix; CI asserts it.
|
|
87
95
|
.refine(
|
|
88
96
|
(s) => !s.startsWith('CHANGE_ME'),
|
|
89
97
|
'JWT_SECRET is still the placeholder — generate one: openssl rand -hex 48',
|
|
@@ -107,12 +115,15 @@ const envSchema = z.object({
|
|
|
107
115
|
// Cookie domain for cross-origin deployments (client ≠ server hostname)
|
|
108
116
|
// Required when client and API are on different subdomains (e.g., app.example.com + api.example.com)
|
|
109
117
|
// Set to the shared parent domain with a leading dot: ".example.com"
|
|
110
|
-
// Leave empty for same-origin deployments or local development
|
|
118
|
+
// Leave empty for same-origin deployments or local development.
|
|
119
|
+
// Applies only to the non-secret auth_session cookie; the token cookies are
|
|
120
|
+
// always host-only on the API (see src/libs/cookies.ts).
|
|
111
121
|
COOKIE_DOMAIN: optionalEnv(z.string().optional()),
|
|
112
122
|
|
|
113
123
|
// --- Account Activation ---
|
|
114
|
-
// When true (default), new users
|
|
115
|
-
//
|
|
124
|
+
// When true (default), new users start with emailVerifiedAt = null and cannot
|
|
125
|
+
// sign in until they verify their email. When false, they count as verified
|
|
126
|
+
// immediately. This never touches isActive, which is only the admin ban switch.
|
|
116
127
|
REQUIRE_USER_VERIFICATION: optionalEnv(z.string().default('true').transform((val) => val === 'true')),
|
|
117
128
|
|
|
118
129
|
// --- CORS ---
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
|
2
|
+
import { prisma } from '@libs/prisma.js';
|
|
3
|
+
import { fileStorageService } from '@libs/storage/file-storage.service.js';
|
|
4
|
+
import { purgeDeletedAccounts } from '../cleanup-deleted-accounts.job.js';
|
|
5
|
+
|
|
6
|
+
// The purge must complete for every account past retention: one failing
|
|
7
|
+
// account is logged and skipped, never blocks the rest, and files are only
|
|
8
|
+
// removed after the database row is really gone.
|
|
9
|
+
|
|
10
|
+
vi.mock('@libs/prisma.js', () => ({
|
|
11
|
+
prisma: { user: { findMany: vi.fn(), delete: vi.fn() } },
|
|
12
|
+
}));
|
|
13
|
+
vi.mock('@libs/storage/file-storage.service.js', () => ({
|
|
14
|
+
fileStorageService: { deleteUserMedia: vi.fn() },
|
|
15
|
+
}));
|
|
16
|
+
vi.mock('@libs/logger.js', () => ({
|
|
17
|
+
logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() },
|
|
18
|
+
}));
|
|
19
|
+
|
|
20
|
+
describe('purgeDeletedAccounts', () => {
|
|
21
|
+
beforeEach(() => {
|
|
22
|
+
vi.clearAllMocks();
|
|
23
|
+
});
|
|
24
|
+
|
|
25
|
+
it('only selects accounts soft-deleted more than 30 days ago', async () => {
|
|
26
|
+
vi.mocked(prisma.user.findMany).mockResolvedValue([]);
|
|
27
|
+
const now = new Date('2026-03-31T12:00:00Z');
|
|
28
|
+
|
|
29
|
+
const result = await purgeDeletedAccounts(now);
|
|
30
|
+
|
|
31
|
+
const where = vi.mocked(prisma.user.findMany).mock.calls[0][0]?.where as {
|
|
32
|
+
deletedAt: { not: null; lt: Date };
|
|
33
|
+
};
|
|
34
|
+
expect(where.deletedAt.lt.toISOString()).toBe('2026-03-01T12:00:00.000Z');
|
|
35
|
+
expect(result).toEqual({ found: 0, purged: 0, failed: 0 });
|
|
36
|
+
});
|
|
37
|
+
|
|
38
|
+
it('keeps going when one account fails and reports the counts', async () => {
|
|
39
|
+
vi.mocked(prisma.user.findMany).mockResolvedValue([{ id: 'a' }, { id: 'b' }, { id: 'c' }] as never);
|
|
40
|
+
vi.mocked(prisma.user.delete).mockImplementation((({ where }: { where: { id: string } }) =>
|
|
41
|
+
where.id === 'b' ? Promise.reject(new Error('fk constraint')) : Promise.resolve({})) as never);
|
|
42
|
+
|
|
43
|
+
const result = await purgeDeletedAccounts();
|
|
44
|
+
|
|
45
|
+
expect(result).toEqual({ found: 3, purged: 2, failed: 1 });
|
|
46
|
+
// Media is removed only for accounts whose row was really deleted
|
|
47
|
+
expect(fileStorageService.deleteUserMedia).toHaveBeenCalledTimes(2);
|
|
48
|
+
expect(fileStorageService.deleteUserMedia).not.toHaveBeenCalledWith('b');
|
|
49
|
+
});
|
|
50
|
+
|
|
51
|
+
it('counts an account as purged even if its file cleanup fails', async () => {
|
|
52
|
+
vi.mocked(prisma.user.findMany).mockResolvedValue([{ id: 'a' }] as never);
|
|
53
|
+
vi.mocked(prisma.user.delete).mockResolvedValue({} as never);
|
|
54
|
+
vi.mocked(fileStorageService.deleteUserMedia).mockRejectedValue(new Error('disk'));
|
|
55
|
+
|
|
56
|
+
await expect(purgeDeletedAccounts()).resolves.toEqual({ found: 1, purged: 1, failed: 0 });
|
|
57
|
+
});
|
|
58
|
+
});
|
|
@@ -2,10 +2,12 @@
|
|
|
2
2
|
* Cleanup Deleted Accounts Job
|
|
3
3
|
*
|
|
4
4
|
* Permanently purges soft-deleted user accounts after a 30-day retention period.
|
|
5
|
-
*
|
|
6
|
-
*
|
|
5
|
+
* Hard-deletes the user record (cascades to refresh tokens and sessions; IP
|
|
6
|
+
* blocks the user created as an admin are kept, with blockedBy set to NULL),
|
|
7
|
+
* then deletes all of the user's media from disk (public AND private tier).
|
|
7
8
|
*
|
|
8
|
-
* Runs once daily.
|
|
9
|
+
* Runs once daily. `purgeDeletedAccounts()` is exported so it can also be run
|
|
10
|
+
* on demand (tests, an operator script) without waiting for the interval.
|
|
9
11
|
*/
|
|
10
12
|
|
|
11
13
|
import type { FastifyInstance } from 'fastify';
|
|
@@ -16,69 +18,81 @@ import { fileStorageService } from '@libs/storage/file-storage.service.js';
|
|
|
16
18
|
const INTERVAL_MS = 24 * 60 * 60 * 1000; // 24 hours
|
|
17
19
|
const RETENTION_DAYS = 30;
|
|
18
20
|
|
|
19
|
-
export
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
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
|
-
});
|
|
21
|
+
export interface PurgeResult {
|
|
22
|
+
found: number;
|
|
23
|
+
purged: number;
|
|
24
|
+
failed: number;
|
|
25
|
+
}
|
|
37
26
|
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
27
|
+
/**
|
|
28
|
+
* Purge every account soft-deleted more than RETENTION_DAYS ago.
|
|
29
|
+
*
|
|
30
|
+
* One failing account is logged and skipped; it never stops the others. A
|
|
31
|
+
* failure here is a real problem (data kept past its promised deletion), so it
|
|
32
|
+
* is logged at error level with the user id.
|
|
33
|
+
*/
|
|
34
|
+
export async function purgeDeletedAccounts(now: Date = new Date()): Promise<PurgeResult> {
|
|
35
|
+
const cutoffDate = new Date(now);
|
|
36
|
+
cutoffDate.setDate(cutoffDate.getDate() - RETENTION_DAYS);
|
|
41
37
|
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
38
|
+
// Find users soft-deleted more than 30 days ago
|
|
39
|
+
const usersToDelete = await prisma.user.findMany({
|
|
40
|
+
where: {
|
|
41
|
+
deletedAt: {
|
|
42
|
+
not: null,
|
|
43
|
+
lt: cutoffDate,
|
|
44
|
+
},
|
|
45
|
+
},
|
|
46
|
+
select: {
|
|
47
|
+
id: true,
|
|
48
|
+
},
|
|
49
|
+
});
|
|
46
50
|
|
|
47
|
-
|
|
51
|
+
const result: PurgeResult = { found: usersToDelete.length, purged: 0, failed: 0 };
|
|
52
|
+
if (usersToDelete.length === 0) {
|
|
53
|
+
return result;
|
|
54
|
+
}
|
|
48
55
|
|
|
49
|
-
|
|
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
|
-
});
|
|
56
|
+
logger.info({ count: usersToDelete.length }, 'Starting purge of soft-deleted accounts');
|
|
58
57
|
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
58
|
+
for (const user of usersToDelete) {
|
|
59
|
+
try {
|
|
60
|
+
// Hard delete user record first (cascades to RefreshToken + Session).
|
|
61
|
+
// DB deletion is the critical operation — if it succeeds but file cleanup
|
|
62
|
+
// fails, we only have orphaned files (harmless, cleanable later).
|
|
63
|
+
// The reverse (files deleted, DB intact) would leave a dangling user record.
|
|
64
|
+
await prisma.user.delete({
|
|
65
|
+
where: { id: user.id },
|
|
66
|
+
});
|
|
68
67
|
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
68
|
+
// Delete all user media from disk (no-op if dirs don't exist)
|
|
69
|
+
try {
|
|
70
|
+
await fileStorageService.deleteUserMedia(user.id);
|
|
71
|
+
} catch (fileError) {
|
|
72
|
+
logger.warn(
|
|
73
|
+
{ err: fileError, userId: user.id },
|
|
74
|
+
'User record purged but file cleanup failed — orphaned files may remain',
|
|
75
|
+
);
|
|
76
76
|
}
|
|
77
77
|
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
);
|
|
78
|
+
result.purged++;
|
|
79
|
+
} catch (error) {
|
|
80
|
+
result.failed++;
|
|
81
|
+
logger.error({ err: error, userId: user.id }, 'Failed to purge deleted account');
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
logger.info(
|
|
86
|
+
{ purgedCount: result.purged, failedCount: result.failed, totalFound: result.found },
|
|
87
|
+
'Deleted accounts purge complete',
|
|
88
|
+
);
|
|
89
|
+
return result;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
export function startCleanupDeletedAccountsJob(app: FastifyInstance): void {
|
|
93
|
+
const intervalId = setInterval(async () => {
|
|
94
|
+
try {
|
|
95
|
+
await purgeDeletedAccounts();
|
|
82
96
|
} catch (error) {
|
|
83
97
|
logger.error({ err: error }, 'Failed to run deleted accounts cleanup');
|
|
84
98
|
}
|
|
@@ -0,0 +1,77 @@
|
|
|
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 } from '../auth.js';
|
|
6
|
+
|
|
7
|
+
// authenticate() is the single per-request gate: it must take the role from
|
|
8
|
+
// the database (not the token) and refuse banned accounts.
|
|
9
|
+
|
|
10
|
+
vi.mock('@libs/prisma.js', () => ({
|
|
11
|
+
prisma: { user: { findUnique: vi.fn() } },
|
|
12
|
+
}));
|
|
13
|
+
vi.mock('@libs/cookies.js', () => ({ clearAuthCookies: vi.fn() }));
|
|
14
|
+
|
|
15
|
+
type DbUser = {
|
|
16
|
+
isActive: boolean;
|
|
17
|
+
emailVerifiedAt: Date | null;
|
|
18
|
+
deletedAt: Date | null;
|
|
19
|
+
role: 'USER' | 'ADMIN';
|
|
20
|
+
};
|
|
21
|
+
|
|
22
|
+
function makeRequest(tokenRole: 'USER' | 'ADMIN'): FastifyRequest {
|
|
23
|
+
const request = {
|
|
24
|
+
user: { userId: 'user-1', role: tokenRole },
|
|
25
|
+
jwtVerify: vi.fn().mockResolvedValue(undefined),
|
|
26
|
+
};
|
|
27
|
+
return request as unknown as FastifyRequest;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
const reply = {} as FastifyReply;
|
|
31
|
+
|
|
32
|
+
function mockDbUser(user: DbUser | null): void {
|
|
33
|
+
vi.mocked(prisma.user.findUnique).mockResolvedValue(user as never);
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
describe('authenticate', () => {
|
|
37
|
+
beforeEach(() => {
|
|
38
|
+
vi.clearAllMocks();
|
|
39
|
+
});
|
|
40
|
+
|
|
41
|
+
it('replaces a stale ADMIN role from the token with the current database role', async () => {
|
|
42
|
+
// The admin was demoted after this token was signed.
|
|
43
|
+
mockDbUser({ isActive: true, emailVerifiedAt: new Date(), deletedAt: null, role: 'USER' });
|
|
44
|
+
const request = makeRequest('ADMIN');
|
|
45
|
+
|
|
46
|
+
await authenticate(request, reply);
|
|
47
|
+
|
|
48
|
+
expect(request.user.role).toBe('USER');
|
|
49
|
+
await expect(authorize('ADMIN')(request, reply)).rejects.toMatchObject({ statusCode: 403 });
|
|
50
|
+
});
|
|
51
|
+
|
|
52
|
+
it('keeps admin access for a current admin', async () => {
|
|
53
|
+
mockDbUser({ isActive: true, emailVerifiedAt: new Date(), deletedAt: null, role: 'ADMIN' });
|
|
54
|
+
const request = makeRequest('ADMIN');
|
|
55
|
+
|
|
56
|
+
await authenticate(request, reply);
|
|
57
|
+
|
|
58
|
+
await expect(authorize('ADMIN')(request, reply)).resolves.toBeUndefined();
|
|
59
|
+
});
|
|
60
|
+
|
|
61
|
+
it('rejects a banned account with ACCOUNT_DEACTIVATED and clears its cookies', async () => {
|
|
62
|
+
mockDbUser({ isActive: false, emailVerifiedAt: new Date(), deletedAt: null, role: 'USER' });
|
|
63
|
+
|
|
64
|
+
await expect(authenticate(makeRequest('USER'), reply)).rejects.toMatchObject({
|
|
65
|
+
statusCode: 403,
|
|
66
|
+
code: 'ACCOUNT_DEACTIVATED',
|
|
67
|
+
});
|
|
68
|
+
expect(clearAuthCookies).toHaveBeenCalledWith(reply);
|
|
69
|
+
});
|
|
70
|
+
|
|
71
|
+
it('rejects a deleted account with 401', async () => {
|
|
72
|
+
mockDbUser({ isActive: false, emailVerifiedAt: null, deletedAt: new Date(), role: 'USER' });
|
|
73
|
+
|
|
74
|
+
await expect(authenticate(makeRequest('USER'), reply)).rejects.toMatchObject({ statusCode: 401 });
|
|
75
|
+
expect(clearAuthCookies).toHaveBeenCalledWith(reply);
|
|
76
|
+
});
|
|
77
|
+
});
|