create-tigra 3.2.0 → 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/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/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/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
|
@@ -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
|
+
});
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import { describe, it, expect, vi } from 'vitest';
|
|
2
|
+
import type { FastifyReply } from 'fastify';
|
|
3
|
+
import { setAuthCookies, clearAuthCookies } from '../cookies.js';
|
|
4
|
+
|
|
5
|
+
// Production cross-subdomain setup: only the non-secret auth_session indicator
|
|
6
|
+
// may use COOKIE_DOMAIN; the bearer token cookies must stay host-only.
|
|
7
|
+
|
|
8
|
+
vi.mock('@config/env.js', () => ({
|
|
9
|
+
env: {
|
|
10
|
+
NODE_ENV: 'production',
|
|
11
|
+
COOKIE_DOMAIN: '.example.test',
|
|
12
|
+
JWT_ACCESS_EXPIRY: '15m',
|
|
13
|
+
JWT_REFRESH_EXPIRY: '7d',
|
|
14
|
+
},
|
|
15
|
+
}));
|
|
16
|
+
|
|
17
|
+
type CookieOpts = { domain?: string; path?: string; httpOnly?: boolean; secure?: boolean };
|
|
18
|
+
|
|
19
|
+
function fakeReply(): { reply: FastifyReply; set: Map<string, CookieOpts>; cleared: Array<[string, CookieOpts]> } {
|
|
20
|
+
const set = new Map<string, CookieOpts>();
|
|
21
|
+
const cleared: Array<[string, CookieOpts]> = [];
|
|
22
|
+
const reply = {
|
|
23
|
+
setCookie: vi.fn((name: string, _value: string, opts: CookieOpts) => set.set(name, opts)),
|
|
24
|
+
clearCookie: vi.fn((name: string, opts: CookieOpts) => cleared.push([name, opts])),
|
|
25
|
+
} as unknown as FastifyReply;
|
|
26
|
+
return { reply, set, cleared };
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
describe('setAuthCookies', () => {
|
|
30
|
+
it('keeps access and refresh tokens host-only and shares only auth_session', () => {
|
|
31
|
+
const { reply, set } = fakeReply();
|
|
32
|
+
setAuthCookies(reply, 'access', 'refresh');
|
|
33
|
+
|
|
34
|
+
expect(set.get('access_token')?.domain).toBeUndefined();
|
|
35
|
+
expect(set.get('refresh_token')?.domain).toBeUndefined();
|
|
36
|
+
expect(set.get('access_token')?.httpOnly).toBe(true);
|
|
37
|
+
expect(set.get('access_token')?.secure).toBe(true);
|
|
38
|
+
expect(set.get('auth_session')?.domain).toBe('.example.test');
|
|
39
|
+
});
|
|
40
|
+
|
|
41
|
+
it('expires legacy domain-wide token cookies from older versions', () => {
|
|
42
|
+
const { reply, cleared } = fakeReply();
|
|
43
|
+
setAuthCookies(reply, 'access', 'refresh');
|
|
44
|
+
|
|
45
|
+
expect(cleared).toContainEqual(['access_token', expect.objectContaining({ domain: '.example.test', path: '/' })]);
|
|
46
|
+
expect(cleared).toContainEqual([
|
|
47
|
+
'refresh_token',
|
|
48
|
+
expect.objectContaining({ domain: '.example.test', path: '/api/v1/auth' }),
|
|
49
|
+
]);
|
|
50
|
+
});
|
|
51
|
+
});
|
|
52
|
+
|
|
53
|
+
describe('clearAuthCookies', () => {
|
|
54
|
+
it('clears both the host-only tokens and any legacy domain-wide copies', () => {
|
|
55
|
+
const { reply, cleared } = fakeReply();
|
|
56
|
+
clearAuthCookies(reply);
|
|
57
|
+
|
|
58
|
+
const tokenClears = cleared.filter(([name]) => name === 'access_token');
|
|
59
|
+
expect(tokenClears.map(([, o]) => o.domain).sort()).toEqual(['.example.test', undefined].sort());
|
|
60
|
+
expect(cleared).toContainEqual(['auth_session', expect.objectContaining({ domain: '.example.test' })]);
|
|
61
|
+
});
|
|
62
|
+
});
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { describe, it, expect } from 'vitest';
|
|
2
|
+
import { redisRetryDelay } from '../redis.js';
|
|
3
|
+
|
|
4
|
+
// The Redis client must never stop reconnecting: ioredis gives up for good
|
|
5
|
+
// when the retry strategy returns null, which used to leave a process without
|
|
6
|
+
// rate limits, IP blocks and login lockout until it was restarted.
|
|
7
|
+
|
|
8
|
+
describe('redisRetryDelay', () => {
|
|
9
|
+
it('always returns a delay, even after many attempts (never gives up)', () => {
|
|
10
|
+
for (const attempt of [1, 3, 5, 50, 1000, 100000]) {
|
|
11
|
+
const delay = redisRetryDelay(attempt);
|
|
12
|
+
expect(typeof delay).toBe('number');
|
|
13
|
+
expect(delay).toBeGreaterThan(0);
|
|
14
|
+
}
|
|
15
|
+
});
|
|
16
|
+
|
|
17
|
+
it('backs off and caps the wait at 5 seconds', () => {
|
|
18
|
+
expect(redisRetryDelay(1)).toBe(200);
|
|
19
|
+
expect(redisRetryDelay(2)).toBe(400);
|
|
20
|
+
expect(redisRetryDelay(25)).toBe(5000);
|
|
21
|
+
expect(redisRetryDelay(10000)).toBe(5000);
|
|
22
|
+
});
|
|
23
|
+
});
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
import { describe, it, expect } from 'vitest';
|
|
2
|
+
import type { Event } from '@sentry/node';
|
|
3
|
+
import { scrubSentryEvent } from '../observability/sentry.js';
|
|
4
|
+
|
|
5
|
+
// Error events must never carry passwords, tokens or cookies to Sentry.
|
|
6
|
+
|
|
7
|
+
describe('scrubSentryEvent', () => {
|
|
8
|
+
it('removes request body, cookies, auth headers and query strings', () => {
|
|
9
|
+
const event: Event = {
|
|
10
|
+
request: {
|
|
11
|
+
url: 'https://api.example.test/api/v1/auth/reset-password?token=secret-reset-token',
|
|
12
|
+
method: 'POST',
|
|
13
|
+
data: '{"email":"a@example.test","password":"Plaintext-Passw0rd"}',
|
|
14
|
+
cookies: { access_token: 'jwt-value', refresh_token: 'refresh-value' },
|
|
15
|
+
query_string: 'token=secret-reset-token',
|
|
16
|
+
headers: {
|
|
17
|
+
Cookie: 'access_token=jwt-value; refresh_token=refresh-value',
|
|
18
|
+
authorization: 'Bearer jwt-value',
|
|
19
|
+
'user-agent': 'vitest',
|
|
20
|
+
},
|
|
21
|
+
},
|
|
22
|
+
breadcrumbs: [
|
|
23
|
+
{ category: 'http', data: { url: 'https://x.test/verify-account?token=abc', 'http.query': 'token=abc' } },
|
|
24
|
+
],
|
|
25
|
+
};
|
|
26
|
+
|
|
27
|
+
const scrubbed = scrubSentryEvent(event);
|
|
28
|
+
const serialized = JSON.stringify(scrubbed);
|
|
29
|
+
|
|
30
|
+
expect(serialized).not.toContain('Plaintext-Passw0rd');
|
|
31
|
+
expect(serialized).not.toContain('jwt-value');
|
|
32
|
+
expect(serialized).not.toContain('refresh-value');
|
|
33
|
+
expect(serialized).not.toContain('secret-reset-token');
|
|
34
|
+
expect(serialized).not.toContain('token=abc');
|
|
35
|
+
// Useful, non-secret context survives
|
|
36
|
+
expect(scrubbed.request?.method).toBe('POST');
|
|
37
|
+
expect(scrubbed.request?.url).toBe('https://api.example.test/api/v1/auth/reset-password');
|
|
38
|
+
expect(scrubbed.request?.headers?.['user-agent']).toBe('vitest');
|
|
39
|
+
});
|
|
40
|
+
|
|
41
|
+
it('strips tokens from the Referer header, trace data, span attributes and the transaction name', () => {
|
|
42
|
+
// The browser SDK copies the page URL and the Referer into request headers
|
|
43
|
+
// and span/trace attributes; reset/verify pages carry ?token=… there.
|
|
44
|
+
const event: Event = {
|
|
45
|
+
transaction: '/verify-account?token=txn-secret',
|
|
46
|
+
request: { headers: { Referer: 'https://app.example.test/reset-password?token=referer-secret' } },
|
|
47
|
+
contexts: {
|
|
48
|
+
trace: {
|
|
49
|
+
trace_id: 't',
|
|
50
|
+
span_id: 's',
|
|
51
|
+
data: {
|
|
52
|
+
'url.full': 'https://app.example.test/reset-password?token=trace-secret',
|
|
53
|
+
'http.request.header.referer': 'https://app.example.test/verify-account?token=trace-ref-secret',
|
|
54
|
+
'http.query': 'token=trace-query-secret',
|
|
55
|
+
},
|
|
56
|
+
},
|
|
57
|
+
},
|
|
58
|
+
spans: [
|
|
59
|
+
{
|
|
60
|
+
span_id: 'x',
|
|
61
|
+
trace_id: 't',
|
|
62
|
+
start_timestamp: 0,
|
|
63
|
+
data: { 'http.request.header.referer': 'https://app.example.test/x?token=span-secret' },
|
|
64
|
+
},
|
|
65
|
+
],
|
|
66
|
+
};
|
|
67
|
+
|
|
68
|
+
const serialized = JSON.stringify(scrubSentryEvent(event));
|
|
69
|
+
|
|
70
|
+
for (const secret of ['txn-secret', 'referer-secret', 'trace-secret', 'trace-ref-secret', 'trace-query-secret', 'span-secret']) {
|
|
71
|
+
expect(serialized).not.toContain(secret);
|
|
72
|
+
}
|
|
73
|
+
expect(serialized).toContain('https://app.example.test/reset-password');
|
|
74
|
+
});
|
|
75
|
+
|
|
76
|
+
it('leaves an event without request data untouched', () => {
|
|
77
|
+
const event: Event = { message: 'boom' };
|
|
78
|
+
expect(scrubSentryEvent(event)).toEqual({ message: 'boom' });
|
|
79
|
+
});
|
|
80
|
+
});
|