create-tigra 3.2.0 → 4.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +81 -12
- package/bin/create-tigra.js +495 -472
- package/lib/patchers/email-verification.patcher.js +160 -44
- 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 +81 -21
- package/package.json +3 -2
- package/template/.github/dependabot.yml +47 -0
- package/template/.github/workflows/audit.yml +36 -0
- package/template/.github/workflows/ci.yml +79 -0
- package/template/AGENTS.md +18 -9
- package/template/client/.dockerignore +1 -0
- package/template/client/.env.example.production +13 -2
- package/template/client/AGENTS.md +13 -5
- package/template/client/Dockerfile +186 -14
- package/template/client/next.config.ts +1 -1
- package/template/client/package-lock.json +15983 -14181
- package/template/client/package.json +56 -48
- package/template/client/scripts/check-sharp.mjs +53 -0
- package/template/client/scripts/next-dev.cjs +5 -1
- package/template/client/src/__tests__/proxy.test.ts +92 -0
- package/template/client/src/app/healthz/route.ts +16 -0
- package/template/client/src/app/layout.tsx +9 -3
- package/template/client/src/app/page.tsx +2 -2
- package/template/client/src/app/providers.tsx +23 -4
- package/template/client/src/components/layout/Header.tsx +7 -3
- package/template/client/src/features/admin/hooks/useAdminSessions.ts +2 -1
- package/template/client/src/features/admin/hooks/useAdminUsers.ts +3 -1
- package/template/client/src/features/admin/types/admin.types.ts +2 -3
- package/template/client/src/features/auth/components/AuthInitializer.tsx +38 -19
- 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 +18 -4
- package/template/client/src/features/auth/components/RegisterForm.tsx +23 -7
- package/template/client/src/features/auth/hooks/useAuth.ts +27 -7
- 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/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/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 +71 -0
- 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 +86 -1
- 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/security.ts +37 -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 -269
- package/template/server/.env.example.production +283 -236
- package/template/server/AGENTS.md +13 -4
- package/template/server/Dockerfile +181 -14
- package/template/server/docker-compose.yml +4 -2
- package/template/server/docs/deployment.md +63 -0
- package/template/server/docs/logging.md +52 -4
- package/template/server/docs/rate-limits.md +153 -0
- package/template/server/docs/testing.md +63 -0
- package/template/server/eslint.config.mjs +19 -0
- package/template/server/package-lock.json +8784 -8743
- package/template/server/package.json +79 -75
- package/template/server/prisma/migrations/0_init/migration.sql +82 -0
- package/template/server/prisma/migrations/migration_lock.toml +3 -0
- package/template/server/prisma/schema.prisma +19 -6
- package/template/server/prisma/seed.ts +13 -5
- 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 -335
- 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 -171
- package/template/server/src/config/rate-limit.config.ts +157 -106
- package/template/server/src/jobs/__tests__/cleanup-deleted-accounts.job.test.ts +110 -0
- 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 +81 -65
- 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 +168 -0
- 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 +113 -0
- 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 +59 -0
- 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 -0
- 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/account-status.ts +52 -0
- package/template/server/src/libs/auth.ts +51 -12
- 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 +91 -24
- 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 -220
- package/template/server/src/libs/logger.ts +41 -12
- package/template/server/src/libs/monitoring.ts +131 -42
- package/template/server/src/libs/observability/sentry.ts +80 -0
- 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 +108 -18
- 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 +143 -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 +104 -83
- package/template/server/src/libs/storage/file-validator.ts +48 -46
- package/template/server/src/libs/storage/image-optimizer.service.ts +78 -72
- 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 +56 -13
- 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 +73 -7
- 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 +332 -49
- 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 +60 -42
- package/template/server/src/modules/auth/auth.schemas.ts +5 -2
- package/template/server/src/modules/auth/auth.service.ts +197 -109
- package/template/server/src/modules/auth/session.repo.ts +12 -12
- 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 +25 -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 +23 -8
- 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
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Admin service rules with the repositories mocked: a ban or a demotion ends
|
|
3
|
+
* the account's sessions at once, an admin can never ban themselves or change
|
|
4
|
+
* their own role (either could leave the project without an admin), and a
|
|
5
|
+
* force-expired session takes its refresh tokens with it.
|
|
6
|
+
*/
|
|
7
|
+
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
|
8
|
+
import { adminService } from '../admin.service.js';
|
|
9
|
+
import { adminRepository } from '../admin.repo.js';
|
|
10
|
+
import { sessionRepository } from '@modules/auth/session.repo.js';
|
|
11
|
+
import { deleteRefreshTokensByUserId } from '@modules/auth/auth.repo.js';
|
|
12
|
+
|
|
13
|
+
vi.mock('../admin.repo.js');
|
|
14
|
+
vi.mock('@modules/auth/session.repo.js');
|
|
15
|
+
vi.mock('@modules/auth/auth.repo.js');
|
|
16
|
+
vi.mock('@libs/logger.js', () => ({ logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() } }));
|
|
17
|
+
|
|
18
|
+
const ADMIN_ID = '11111111-1111-4111-8111-111111111111';
|
|
19
|
+
const USER_ID = '22222222-2222-4222-8222-222222222222';
|
|
20
|
+
|
|
21
|
+
function adminUser(overrides: Record<string, unknown> = {}): never {
|
|
22
|
+
return {
|
|
23
|
+
id: USER_ID, email: 'u@example.test', firstName: 'Us', lastName: 'Er', role: 'USER', avatarUrl: null,
|
|
24
|
+
isActive: true, emailVerifiedAt: new Date(), deletedAt: null, createdAt: new Date(), updatedAt: new Date(),
|
|
25
|
+
...overrides,
|
|
26
|
+
} as never;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
beforeEach(() => {
|
|
30
|
+
vi.clearAllMocks();
|
|
31
|
+
vi.mocked(adminRepository.findUserById).mockResolvedValue(adminUser());
|
|
32
|
+
vi.mocked(adminRepository.updateUserStatus).mockResolvedValue(adminUser());
|
|
33
|
+
vi.mocked(adminRepository.updateUserRole).mockResolvedValue(adminUser());
|
|
34
|
+
});
|
|
35
|
+
|
|
36
|
+
describe('ban and unban', () => {
|
|
37
|
+
it("banning another user ends that user's sessions and refresh tokens", async () => {
|
|
38
|
+
await adminService.toggleUserStatus(USER_ID, false, ADMIN_ID);
|
|
39
|
+
expect(adminRepository.updateUserStatus).toHaveBeenCalledWith(USER_ID, false, false);
|
|
40
|
+
expect(sessionRepository.deleteAllUserSessions).toHaveBeenCalledWith(USER_ID);
|
|
41
|
+
expect(deleteRefreshTokensByUserId).toHaveBeenCalledWith(USER_ID);
|
|
42
|
+
});
|
|
43
|
+
|
|
44
|
+
it('an admin cannot ban themselves (403 CANNOT_BAN_SELF), and nothing changes', async () => {
|
|
45
|
+
await expect(adminService.toggleUserStatus(ADMIN_ID, false, ADMIN_ID)).rejects.toMatchObject({
|
|
46
|
+
statusCode: 403,
|
|
47
|
+
code: 'CANNOT_BAN_SELF',
|
|
48
|
+
});
|
|
49
|
+
expect(adminRepository.updateUserStatus).not.toHaveBeenCalled();
|
|
50
|
+
expect(sessionRepository.deleteAllUserSessions).not.toHaveBeenCalled();
|
|
51
|
+
});
|
|
52
|
+
|
|
53
|
+
it('activating an unverified user also approves the email; no sessions are touched', async () => {
|
|
54
|
+
vi.mocked(adminRepository.findUserById).mockResolvedValue(adminUser({ emailVerifiedAt: null, isActive: false }));
|
|
55
|
+
await adminService.toggleUserStatus(USER_ID, true, ADMIN_ID);
|
|
56
|
+
expect(adminRepository.updateUserStatus).toHaveBeenCalledWith(USER_ID, true, true);
|
|
57
|
+
expect(sessionRepository.deleteAllUserSessions).not.toHaveBeenCalled();
|
|
58
|
+
});
|
|
59
|
+
|
|
60
|
+
it('banning an unknown or deleted user answers 404', async () => {
|
|
61
|
+
vi.mocked(adminRepository.findUserById).mockResolvedValue(null);
|
|
62
|
+
await expect(adminService.toggleUserStatus(USER_ID, false, ADMIN_ID)).rejects.toMatchObject({ statusCode: 404 });
|
|
63
|
+
});
|
|
64
|
+
});
|
|
65
|
+
|
|
66
|
+
describe('role changes', () => {
|
|
67
|
+
it('an admin cannot change their own role', async () => {
|
|
68
|
+
await expect(adminService.changeUserRole(ADMIN_ID, 'USER', ADMIN_ID)).rejects.toMatchObject({ statusCode: 403 });
|
|
69
|
+
expect(adminRepository.updateUserRole).not.toHaveBeenCalled();
|
|
70
|
+
});
|
|
71
|
+
|
|
72
|
+
it("demoting another admin ends that admin's sessions", async () => {
|
|
73
|
+
vi.mocked(adminRepository.findUserById).mockResolvedValue(adminUser({ id: USER_ID, role: 'ADMIN' }));
|
|
74
|
+
await adminService.changeUserRole(USER_ID, 'USER', ADMIN_ID);
|
|
75
|
+
expect(sessionRepository.deleteAllUserSessions).toHaveBeenCalledWith(USER_ID);
|
|
76
|
+
expect(deleteRefreshTokensByUserId).toHaveBeenCalledWith(USER_ID);
|
|
77
|
+
});
|
|
78
|
+
|
|
79
|
+
it('promoting a user keeps their sessions (the role is re-read on every request)', async () => {
|
|
80
|
+
await adminService.changeUserRole(USER_ID, 'ADMIN', ADMIN_ID);
|
|
81
|
+
expect(adminRepository.updateUserRole).toHaveBeenCalledWith(USER_ID, 'ADMIN');
|
|
82
|
+
expect(sessionRepository.deleteAllUserSessions).not.toHaveBeenCalled();
|
|
83
|
+
});
|
|
84
|
+
});
|
|
85
|
+
|
|
86
|
+
describe('force-expire a session', () => {
|
|
87
|
+
it('deletes its refresh tokens, then the session', async () => {
|
|
88
|
+
vi.mocked(adminRepository.getSessionById).mockResolvedValue({ id: 's1', userId: USER_ID } as never);
|
|
89
|
+
await adminService.forceExpireSession('s1');
|
|
90
|
+
const tokensAt = vi.mocked(adminRepository.deleteRefreshTokensBySessionId).mock.invocationCallOrder[0];
|
|
91
|
+
const sessionAt = vi.mocked(adminRepository.deleteSession).mock.invocationCallOrder[0];
|
|
92
|
+
expect(tokensAt).toBeLessThan(sessionAt);
|
|
93
|
+
});
|
|
94
|
+
|
|
95
|
+
it('answers 404 for an unknown session', async () => {
|
|
96
|
+
vi.mocked(adminRepository.getSessionById).mockResolvedValue(null);
|
|
97
|
+
await expect(adminService.forceExpireSession('missing')).rejects.toMatchObject({ statusCode: 404 });
|
|
98
|
+
expect(adminRepository.deleteSession).not.toHaveBeenCalled();
|
|
99
|
+
});
|
|
100
|
+
});
|
|
101
|
+
|
|
102
|
+
describe('deleted accounts and restore', () => {
|
|
103
|
+
it('lists deleted accounts with purgeAt = deletedAt + 30 days', async () => {
|
|
104
|
+
const deletedAt = new Date('2026-10-01T10:00:00Z');
|
|
105
|
+
vi.mocked(adminRepository.getUsers).mockResolvedValue({ items: [adminUser({ deletedAt })], totalItems: 1 });
|
|
106
|
+
const { items } = await adminService.getUsers({ page: 1, limit: 10, sortBy: 'createdAt', sortOrder: 'desc', deleted: true });
|
|
107
|
+
expect(items[0]?.purgeAt?.toISOString()).toBe('2026-10-31T10:00:00.000Z');
|
|
108
|
+
});
|
|
109
|
+
|
|
110
|
+
it('the normal list carries no purgeAt', async () => {
|
|
111
|
+
vi.mocked(adminRepository.getUsers).mockResolvedValue({ items: [adminUser()], totalItems: 1 });
|
|
112
|
+
const { items } = await adminService.getUsers({ page: 1, limit: 10, sortBy: 'createdAt', sortOrder: 'desc' });
|
|
113
|
+
expect(items[0]).not.toHaveProperty('purgeAt');
|
|
114
|
+
});
|
|
115
|
+
|
|
116
|
+
it('restores a deleted account and returns it', async () => {
|
|
117
|
+
vi.mocked(adminRepository.restoreUser).mockResolvedValue(true);
|
|
118
|
+
await expect(adminService.restoreUser(USER_ID)).resolves.toMatchObject({ id: USER_ID, isActive: true });
|
|
119
|
+
});
|
|
120
|
+
|
|
121
|
+
it('answers 409 USER_NOT_DELETED for an account that is not deleted', async () => {
|
|
122
|
+
vi.mocked(adminRepository.restoreUser).mockResolvedValue(false);
|
|
123
|
+
vi.mocked(adminRepository.userExists).mockResolvedValue(true);
|
|
124
|
+
await expect(adminService.restoreUser(USER_ID)).rejects.toMatchObject({ statusCode: 409, code: 'USER_NOT_DELETED' });
|
|
125
|
+
});
|
|
126
|
+
|
|
127
|
+
it('answers 404 USER_NOT_FOUND when there is no such account (or it was purged)', async () => {
|
|
128
|
+
vi.mocked(adminRepository.restoreUser).mockResolvedValue(false);
|
|
129
|
+
vi.mocked(adminRepository.userExists).mockResolvedValue(false);
|
|
130
|
+
await expect(adminService.restoreUser(USER_ID)).rejects.toMatchObject({ statusCode: 404, code: 'USER_NOT_FOUND' });
|
|
131
|
+
});
|
|
132
|
+
});
|
|
133
|
+
|
|
134
|
+
describe('promoteToAdmin (make-admin)', () => {
|
|
135
|
+
const state = (overrides: Record<string, unknown> = {}): never =>
|
|
136
|
+
({ id: USER_ID, role: 'USER', isActive: true, deletedAt: null, emailVerifiedAt: new Date('2026-01-01'), ...overrides }) as never;
|
|
137
|
+
|
|
138
|
+
it('promotes an existing account, looked up by its lower-cased email, and keeps its verification date', async () => {
|
|
139
|
+
vi.mocked(adminRepository.findAccountStateByEmail).mockResolvedValue(state());
|
|
140
|
+
await expect(adminService.promoteToAdmin(' Owner@Example.TEST ')).resolves.toBe('promoted');
|
|
141
|
+
expect(adminRepository.findAccountStateByEmail).toHaveBeenCalledWith('owner@example.test');
|
|
142
|
+
expect(adminRepository.promoteToAdmin).toHaveBeenCalledWith(USER_ID, new Date('2026-01-01'));
|
|
143
|
+
});
|
|
144
|
+
|
|
145
|
+
it('marks an unverified account verified when promoting it', async () => {
|
|
146
|
+
vi.mocked(adminRepository.findAccountStateByEmail).mockResolvedValue(state({ emailVerifiedAt: null }));
|
|
147
|
+
await adminService.promoteToAdmin('owner@example.test');
|
|
148
|
+
expect(vi.mocked(adminRepository.promoteToAdmin).mock.calls[0]?.[1]).toBeInstanceOf(Date);
|
|
149
|
+
});
|
|
150
|
+
|
|
151
|
+
it.each([
|
|
152
|
+
['no account', null, 'not-found'],
|
|
153
|
+
['a deleted account', state({ deletedAt: new Date() }), 'deleted'],
|
|
154
|
+
['a banned account', state({ isActive: false }), 'banned'],
|
|
155
|
+
['an admin already', state({ role: 'ADMIN' }), 'already-admin'],
|
|
156
|
+
])('changes nothing for %s', async (_label, account, outcome) => {
|
|
157
|
+
vi.mocked(adminRepository.findAccountStateByEmail).mockResolvedValue(account as never);
|
|
158
|
+
await expect(adminService.promoteToAdmin('owner@example.test')).resolves.toBe(outcome);
|
|
159
|
+
expect(adminRepository.promoteToAdmin).not.toHaveBeenCalled();
|
|
160
|
+
});
|
|
161
|
+
});
|
|
162
|
+
|
|
@@ -1,8 +1,10 @@
|
|
|
1
1
|
import type { FastifyRequest, FastifyReply } from 'fastify';
|
|
2
2
|
import { successResponse } from '@shared/responses/successResponse.js';
|
|
3
3
|
import { paginatedResponse } from '@shared/responses/paginatedResponse.js';
|
|
4
|
-
import {
|
|
4
|
+
import { parseInput } from '@libs/validation-errors.js';
|
|
5
5
|
import { blockIp, unblockIp, getBlockedIps } from '@libs/ip-block.js';
|
|
6
|
+
import { getClientIp, resolveClientIp } from '@libs/client-ip.js';
|
|
7
|
+
import { performHealthCheck } from '@libs/monitoring.js';
|
|
6
8
|
import { adminService } from './admin.service.js';
|
|
7
9
|
import {
|
|
8
10
|
blockIpSchema,
|
|
@@ -17,6 +19,10 @@ import {
|
|
|
17
19
|
import type { BlockIpInput, UnblockIpParams } from './admin.schemas.js';
|
|
18
20
|
import type { GetUsersQuery, UserIdParams, UpdateUserStatusInput, UpdateUserRoleInput, GetSessionsQuery, SessionIdParams } from './admin.schemas.js';
|
|
19
21
|
|
|
22
|
+
// The route schemas in admin.routes.ts reject wrong input first. parseInput
|
|
23
|
+
// here is the second line: it yields the typed values and, should a route ever
|
|
24
|
+
// lose its schema, still answers with the standard 422 VALIDATION_FAILED.
|
|
25
|
+
|
|
20
26
|
// ─── IP Blocking ────────────────────────────────────────────────────────────
|
|
21
27
|
|
|
22
28
|
export async function listBlockedIps(
|
|
@@ -27,15 +33,40 @@ export async function listBlockedIps(
|
|
|
27
33
|
reply.send(successResponse('Blocked IPs retrieved', { permanent, autoBlocked }));
|
|
28
34
|
}
|
|
29
35
|
|
|
36
|
+
/** The resolved visitor address for this request and its source (see libs/client-ip.ts). */
|
|
37
|
+
export async function getResolvedClientIp(
|
|
38
|
+
request: FastifyRequest,
|
|
39
|
+
reply: FastifyReply,
|
|
40
|
+
): Promise<void> {
|
|
41
|
+
const { ip, source } = resolveClientIp(request);
|
|
42
|
+
reply.send(successResponse('Client IP resolved', { ip, source }));
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
// ─── Health ─────────────────────────────────────────────────────────────────
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* The full health report (database, Redis, memory, uptime, version, commit).
|
|
49
|
+
* Always 200: it is a report for a person, not a probe (monitors use the public
|
|
50
|
+
* GET /api/v1/health, which answers 503 when unhealthy). While the database is
|
|
51
|
+
* down this route is unreachable anyway, because sign-in checks the session in
|
|
52
|
+
* the database; a Redis outage, the likelier case, shows here in full.
|
|
53
|
+
*/
|
|
54
|
+
export async function getHealthReport(
|
|
55
|
+
_request: FastifyRequest,
|
|
56
|
+
reply: FastifyReply,
|
|
57
|
+
): Promise<void> {
|
|
58
|
+
const report = await performHealthCheck();
|
|
59
|
+
reply.send(successResponse('Health report', report));
|
|
60
|
+
}
|
|
61
|
+
|
|
30
62
|
export async function blockIpHandler(
|
|
31
63
|
request: FastifyRequest<{ Body: BlockIpInput }>,
|
|
32
64
|
reply: FastifyReply,
|
|
33
65
|
): Promise<void> {
|
|
34
|
-
const parsed = blockIpSchema
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
const blocked = await blockIp(parsed.data.ip, request.user.userId, parsed.data.reason);
|
|
66
|
+
const parsed = parseInput(blockIpSchema, request.body);
|
|
67
|
+
// The admin's own address is passed so it can never be blocked (that would
|
|
68
|
+
// lock them out of every route, the unblock route included).
|
|
69
|
+
const blocked = await blockIp(parsed.ip, request.user.userId, parsed.reason, getClientIp(request));
|
|
39
70
|
reply.status(201).send(successResponse('IP blocked successfully', blocked));
|
|
40
71
|
}
|
|
41
72
|
|
|
@@ -64,13 +95,10 @@ export async function getUsers(
|
|
|
64
95
|
request: FastifyRequest<{ Querystring: GetUsersQuery }>,
|
|
65
96
|
reply: FastifyReply,
|
|
66
97
|
): Promise<void> {
|
|
67
|
-
const parsed = getUsersQuerySchema
|
|
68
|
-
if (!parsed.success) {
|
|
69
|
-
throw new ValidationError(parsed.error.issues[0]?.message ?? 'Invalid query parameters');
|
|
70
|
-
}
|
|
98
|
+
const parsed = parseInput(getUsersQuerySchema, request.query);
|
|
71
99
|
|
|
72
|
-
const { page, limit } = parsed
|
|
73
|
-
const { items, totalItems } = await adminService.getUsers(parsed
|
|
100
|
+
const { page, limit } = parsed;
|
|
101
|
+
const { items, totalItems } = await adminService.getUsers(parsed);
|
|
74
102
|
|
|
75
103
|
reply.send(paginatedResponse('Users retrieved', items, page, limit, totalItems));
|
|
76
104
|
}
|
|
@@ -79,12 +107,9 @@ export async function getUserDetail(
|
|
|
79
107
|
request: FastifyRequest<{ Params: UserIdParams }>,
|
|
80
108
|
reply: FastifyReply,
|
|
81
109
|
): Promise<void> {
|
|
82
|
-
const parsed = userIdParamsSchema
|
|
83
|
-
if (!parsed.success) {
|
|
84
|
-
throw new ValidationError(parsed.error.issues[0]?.message ?? 'Invalid user ID');
|
|
85
|
-
}
|
|
110
|
+
const parsed = parseInput(userIdParamsSchema, request.params);
|
|
86
111
|
|
|
87
|
-
const user = await adminService.getUserDetail(parsed.
|
|
112
|
+
const user = await adminService.getUserDetail(parsed.userId);
|
|
88
113
|
reply.send(successResponse('User details retrieved', user));
|
|
89
114
|
}
|
|
90
115
|
|
|
@@ -92,42 +117,40 @@ export async function updateUserStatus(
|
|
|
92
117
|
request: FastifyRequest<{ Params: UserIdParams; Body: UpdateUserStatusInput }>,
|
|
93
118
|
reply: FastifyReply,
|
|
94
119
|
): Promise<void> {
|
|
95
|
-
const paramsParsed = userIdParamsSchema
|
|
96
|
-
if (!paramsParsed.success) {
|
|
97
|
-
throw new ValidationError(paramsParsed.error.issues[0]?.message ?? 'Invalid user ID');
|
|
98
|
-
}
|
|
120
|
+
const paramsParsed = parseInput(userIdParamsSchema, request.params);
|
|
99
121
|
|
|
100
|
-
const bodyParsed = updateUserStatusSchema
|
|
101
|
-
if (!bodyParsed.success) {
|
|
102
|
-
throw new ValidationError(bodyParsed.error.issues[0]?.message ?? 'Invalid status');
|
|
103
|
-
}
|
|
122
|
+
const bodyParsed = parseInput(updateUserStatusSchema, request.body);
|
|
104
123
|
|
|
105
124
|
const user = await adminService.toggleUserStatus(
|
|
106
|
-
paramsParsed.
|
|
107
|
-
bodyParsed.
|
|
125
|
+
paramsParsed.userId,
|
|
126
|
+
bodyParsed.isActive,
|
|
127
|
+
request.user.userId,
|
|
108
128
|
);
|
|
109
129
|
|
|
110
|
-
const action = bodyParsed.
|
|
130
|
+
const action = bodyParsed.isActive ? 'activated' : 'deactivated';
|
|
111
131
|
reply.send(successResponse(`User ${action} successfully`, user));
|
|
112
132
|
}
|
|
113
133
|
|
|
134
|
+
export async function restoreUser(
|
|
135
|
+
request: FastifyRequest<{ Params: UserIdParams }>,
|
|
136
|
+
reply: FastifyReply,
|
|
137
|
+
): Promise<void> {
|
|
138
|
+
const parsed = parseInput(userIdParamsSchema, request.params);
|
|
139
|
+
const user = await adminService.restoreUser(parsed.userId);
|
|
140
|
+
reply.send(successResponse('User restored successfully', user));
|
|
141
|
+
}
|
|
142
|
+
|
|
114
143
|
export async function updateUserRole(
|
|
115
144
|
request: FastifyRequest<{ Params: UserIdParams; Body: UpdateUserRoleInput }>,
|
|
116
145
|
reply: FastifyReply,
|
|
117
146
|
): Promise<void> {
|
|
118
|
-
const paramsParsed = userIdParamsSchema
|
|
119
|
-
if (!paramsParsed.success) {
|
|
120
|
-
throw new ValidationError(paramsParsed.error.issues[0]?.message ?? 'Invalid user ID');
|
|
121
|
-
}
|
|
147
|
+
const paramsParsed = parseInput(userIdParamsSchema, request.params);
|
|
122
148
|
|
|
123
|
-
const bodyParsed = updateUserRoleSchema
|
|
124
|
-
if (!bodyParsed.success) {
|
|
125
|
-
throw new ValidationError(bodyParsed.error.issues[0]?.message ?? 'Invalid role');
|
|
126
|
-
}
|
|
149
|
+
const bodyParsed = parseInput(updateUserRoleSchema, request.body);
|
|
127
150
|
|
|
128
151
|
const user = await adminService.changeUserRole(
|
|
129
|
-
paramsParsed.
|
|
130
|
-
bodyParsed.
|
|
152
|
+
paramsParsed.userId,
|
|
153
|
+
bodyParsed.role,
|
|
131
154
|
request.user.userId,
|
|
132
155
|
);
|
|
133
156
|
|
|
@@ -140,13 +163,10 @@ export async function getAllSessions(
|
|
|
140
163
|
request: FastifyRequest<{ Querystring: GetSessionsQuery }>,
|
|
141
164
|
reply: FastifyReply,
|
|
142
165
|
): Promise<void> {
|
|
143
|
-
const parsed = getSessionsQuerySchema
|
|
144
|
-
if (!parsed.success) {
|
|
145
|
-
throw new ValidationError(parsed.error.issues[0]?.message ?? 'Invalid query parameters');
|
|
146
|
-
}
|
|
166
|
+
const parsed = parseInput(getSessionsQuerySchema, request.query);
|
|
147
167
|
|
|
148
|
-
const { page, limit } = parsed
|
|
149
|
-
const { items, totalItems } = await adminService.getAllSessions(parsed
|
|
168
|
+
const { page, limit } = parsed;
|
|
169
|
+
const { items, totalItems } = await adminService.getAllSessions(parsed);
|
|
150
170
|
|
|
151
171
|
reply.send(paginatedResponse('Sessions retrieved', items, page, limit, totalItems));
|
|
152
172
|
}
|
|
@@ -155,11 +175,8 @@ export async function forceExpireSession(
|
|
|
155
175
|
request: FastifyRequest<{ Params: SessionIdParams }>,
|
|
156
176
|
reply: FastifyReply,
|
|
157
177
|
): Promise<void> {
|
|
158
|
-
const parsed = sessionIdParamsSchema
|
|
159
|
-
if (!parsed.success) {
|
|
160
|
-
throw new ValidationError(parsed.error.issues[0]?.message ?? 'Invalid session ID');
|
|
161
|
-
}
|
|
178
|
+
const parsed = parseInput(sessionIdParamsSchema, request.params);
|
|
162
179
|
|
|
163
|
-
await adminService.forceExpireSession(parsed.
|
|
180
|
+
await adminService.forceExpireSession(parsed.sessionId);
|
|
164
181
|
reply.send(successResponse('Session expired successfully', null));
|
|
165
182
|
}
|
|
@@ -18,9 +18,8 @@ const adminUserSelect = {
|
|
|
18
18
|
role: true,
|
|
19
19
|
avatarUrl: true,
|
|
20
20
|
isActive: true,
|
|
21
|
+
emailVerifiedAt: true,
|
|
21
22
|
deletedAt: true,
|
|
22
|
-
failedLoginAttempts: true,
|
|
23
|
-
lockedUntil: true,
|
|
24
23
|
createdAt: true,
|
|
25
24
|
updatedAt: true,
|
|
26
25
|
} as const;
|
|
@@ -42,16 +41,20 @@ export type AdminUser = {
|
|
|
42
41
|
role: UserRole;
|
|
43
42
|
avatarUrl: string | null;
|
|
44
43
|
isActive: boolean;
|
|
44
|
+
emailVerifiedAt: Date | null;
|
|
45
45
|
deletedAt: Date | null;
|
|
46
|
-
failedLoginAttempts: number;
|
|
47
|
-
lockedUntil: Date | null;
|
|
48
46
|
createdAt: Date;
|
|
49
47
|
updatedAt: Date;
|
|
50
48
|
};
|
|
51
49
|
|
|
52
50
|
export type AdminUserDetail = AdminUser & {
|
|
53
51
|
sessionCount: number;
|
|
54
|
-
|
|
52
|
+
/**
|
|
53
|
+
* Most recent activity of a session that still exists (its lastActiveAt).
|
|
54
|
+
* Null once every session has ended or expired and been cleaned up: this is
|
|
55
|
+
* NOT a stored last-login time (it was called lastLogin, which misled).
|
|
56
|
+
*/
|
|
57
|
+
lastActiveAt: Date | null;
|
|
55
58
|
};
|
|
56
59
|
|
|
57
60
|
export type AdminSession = {
|
|
@@ -92,12 +95,14 @@ class AdminRepository {
|
|
|
92
95
|
isActive?: boolean;
|
|
93
96
|
sortBy: 'createdAt' | 'email' | 'firstName';
|
|
94
97
|
sortOrder: 'asc' | 'desc';
|
|
98
|
+
deleted?: boolean;
|
|
95
99
|
}): Promise<{ items: AdminUser[]; totalItems: number }> {
|
|
96
|
-
const { page, limit, search, role, isActive, sortBy, sortOrder } = params;
|
|
100
|
+
const { page, limit, search, role, isActive, sortBy, sortOrder, deleted = false } = params;
|
|
97
101
|
const offset = (page - 1) * limit;
|
|
98
102
|
|
|
103
|
+
// Live accounts by default; `deleted` lists only soft-deleted ones instead.
|
|
99
104
|
const where: Record<string, unknown> = {
|
|
100
|
-
deletedAt: null,
|
|
105
|
+
deletedAt: deleted ? { not: null } : null,
|
|
101
106
|
};
|
|
102
107
|
|
|
103
108
|
if (search) {
|
|
@@ -142,7 +147,7 @@ class AdminRepository {
|
|
|
142
147
|
}
|
|
143
148
|
|
|
144
149
|
/**
|
|
145
|
-
* Get detailed user info including session count and last
|
|
150
|
+
* Get detailed user info including session count and last activity
|
|
146
151
|
*/
|
|
147
152
|
async getUserDetail(userId: string): Promise<AdminUserDetail | null> {
|
|
148
153
|
const now = new Date();
|
|
@@ -163,7 +168,7 @@ class AdminRepository {
|
|
|
163
168
|
|
|
164
169
|
if (!user) return null;
|
|
165
170
|
|
|
166
|
-
//
|
|
171
|
+
// Last activity of the most recently used session that still exists
|
|
167
172
|
const latestSession = await prisma.session.findFirst({
|
|
168
173
|
where: { userId },
|
|
169
174
|
orderBy: { lastActiveAt: 'desc' },
|
|
@@ -175,21 +180,59 @@ class AdminRepository {
|
|
|
175
180
|
return {
|
|
176
181
|
...userData,
|
|
177
182
|
sessionCount: _count.sessions,
|
|
178
|
-
|
|
183
|
+
lastActiveAt: latestSession?.lastActiveAt ?? null,
|
|
179
184
|
};
|
|
180
185
|
}
|
|
181
186
|
|
|
182
187
|
/**
|
|
183
|
-
* Update
|
|
188
|
+
* Update the admin ban switch (isActive).
|
|
189
|
+
* `approveEmail` also marks the email verified — used when an admin activates
|
|
190
|
+
* a user who never verified, i.e. the admin vouches for them.
|
|
184
191
|
*/
|
|
185
|
-
async updateUserStatus(userId: string, isActive: boolean): Promise<AdminUser> {
|
|
192
|
+
async updateUserStatus(userId: string, isActive: boolean, approveEmail = false): Promise<AdminUser> {
|
|
186
193
|
return prisma.user.update({
|
|
187
194
|
where: { id: userId },
|
|
188
|
-
data: { isActive },
|
|
195
|
+
data: approveEmail ? { isActive, emailVerifiedAt: new Date() } : { isActive },
|
|
189
196
|
select: adminUserSelect,
|
|
190
197
|
});
|
|
191
198
|
}
|
|
192
199
|
|
|
200
|
+
/**
|
|
201
|
+
* Undo a soft delete: one conditional update, so only a deleted account
|
|
202
|
+
* changes. Returns false when there was nothing to restore (no such row, or
|
|
203
|
+
* the account is not deleted); the caller tells those two apart.
|
|
204
|
+
*/
|
|
205
|
+
async restoreUser(userId: string): Promise<boolean> {
|
|
206
|
+
const { count } = await prisma.user.updateMany({
|
|
207
|
+
where: { id: userId, deletedAt: { not: null } },
|
|
208
|
+
data: { deletedAt: null, isActive: true },
|
|
209
|
+
});
|
|
210
|
+
return count === 1;
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
/**
|
|
214
|
+
* The account state make-admin needs, by email, INCLUDING deleted accounts
|
|
215
|
+
* (so it can say "restore it first" instead of "no such account").
|
|
216
|
+
*/
|
|
217
|
+
async findAccountStateByEmail(
|
|
218
|
+
email: string,
|
|
219
|
+
): Promise<{ id: string; role: UserRole; isActive: boolean; deletedAt: Date | null; emailVerifiedAt: Date | null } | null> {
|
|
220
|
+
return prisma.user.findUnique({
|
|
221
|
+
where: { email },
|
|
222
|
+
select: { id: true, role: true, isActive: true, deletedAt: true, emailVerifiedAt: true },
|
|
223
|
+
});
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
/** Make an account ADMIN, marking its email verified if it was not (the operator vouches). */
|
|
227
|
+
async promoteToAdmin(userId: string, emailVerifiedAt: Date): Promise<void> {
|
|
228
|
+
await prisma.user.update({ where: { id: userId }, data: { role: 'ADMIN', emailVerifiedAt } });
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
/** Whether a user row exists at all, deleted or not (purged rows are gone). */
|
|
232
|
+
async userExists(userId: string): Promise<boolean> {
|
|
233
|
+
return (await prisma.user.count({ where: { id: userId } })) === 1;
|
|
234
|
+
}
|
|
235
|
+
|
|
193
236
|
/**
|
|
194
237
|
* Update user role
|
|
195
238
|
*/
|
|
@@ -32,6 +32,21 @@ export async function adminRoutes(fastify: FastifyInstance): Promise<void> {
|
|
|
32
32
|
handler: adminController.listBlockedIps,
|
|
33
33
|
});
|
|
34
34
|
|
|
35
|
+
/**
|
|
36
|
+
* Show the address the server resolves for THIS request, and where it came from.
|
|
37
|
+
* Used after a deploy or a proxy/CDN change to confirm rate limits and IP blocks see the real
|
|
38
|
+
* visitor (source "cloudflare" behind Cloudflare, "proxy" behind Traefik alone), never a
|
|
39
|
+
* Cloudflare, Docker or proxy address. Returns nothing else (no headers are echoed).
|
|
40
|
+
*
|
|
41
|
+
* GET /api/v1/admin/client-ip
|
|
42
|
+
* Auth: Required (ADMIN)
|
|
43
|
+
* Returns: { ip: string, source: 'cloudflare' | 'cloudflare-unverified' | 'proxy' | 'socket' }
|
|
44
|
+
*/
|
|
45
|
+
fastify.get('/admin/client-ip', {
|
|
46
|
+
config: { rateLimit: RATE_LIMITS.ADMIN_DEFAULT },
|
|
47
|
+
handler: adminController.getResolvedClientIp,
|
|
48
|
+
});
|
|
49
|
+
|
|
35
50
|
/**
|
|
36
51
|
* Block an IP address (permanent)
|
|
37
52
|
*
|
|
@@ -57,6 +72,23 @@ export async function adminRoutes(fastify: FastifyInstance): Promise<void> {
|
|
|
57
72
|
handler: adminController.unblockIpHandler,
|
|
58
73
|
});
|
|
59
74
|
|
|
75
|
+
// ─── Health ───────────────────────────────────────────────────────────
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* Full health report: per-check status and timings for the database and
|
|
79
|
+
* Redis (cached for 5 s, see libs/monitoring.ts), memory against the heap
|
|
80
|
+
* limit, uptime, checkedAt, version and deployed commit. The public
|
|
81
|
+
* GET /api/v1/health answers only { status }.
|
|
82
|
+
*
|
|
83
|
+
* GET /api/v1/admin/health
|
|
84
|
+
* Auth: Required (ADMIN)
|
|
85
|
+
* Returns: { status, checks: { database, redis, memory, uptime }, timestamp, checkedAt, version, commit, environment }
|
|
86
|
+
*/
|
|
87
|
+
fastify.get('/admin/health', {
|
|
88
|
+
config: { rateLimit: RATE_LIMITS.ADMIN_DEFAULT },
|
|
89
|
+
handler: adminController.getHealthReport,
|
|
90
|
+
});
|
|
91
|
+
|
|
60
92
|
// ─── Dashboard Stats ──────────────────────────────────────────────────
|
|
61
93
|
|
|
62
94
|
/**
|
|
@@ -78,7 +110,8 @@ export async function adminRoutes(fastify: FastifyInstance): Promise<void> {
|
|
|
78
110
|
*
|
|
79
111
|
* GET /api/v1/admin/users
|
|
80
112
|
* Auth: Required (ADMIN)
|
|
81
|
-
* Query: ?page=1&limit=10&search=&role=&isActive=&sortBy=createdAt&sortOrder=desc
|
|
113
|
+
* Query: ?page=1&limit=10&search=&role=&isActive=&sortBy=createdAt&sortOrder=desc&deleted=false
|
|
114
|
+
* deleted=true lists ONLY soft-deleted accounts, each with purgeAt (when the purge removes it)
|
|
82
115
|
*/
|
|
83
116
|
fastify.get('/admin/users', {
|
|
84
117
|
schema: { querystring: getUsersQuerySchema },
|
|
@@ -91,7 +124,7 @@ export async function adminRoutes(fastify: FastifyInstance): Promise<void> {
|
|
|
91
124
|
*
|
|
92
125
|
* GET /api/v1/admin/users/:userId
|
|
93
126
|
* Auth: Required (ADMIN)
|
|
94
|
-
* Returns: User with sessionCount and
|
|
127
|
+
* Returns: User with sessionCount and lastActiveAt (latest activity of a still-existing session)
|
|
95
128
|
*/
|
|
96
129
|
fastify.get('/admin/users/:userId', {
|
|
97
130
|
schema: { params: userIdParamsSchema },
|
|
@@ -113,6 +146,19 @@ export async function adminRoutes(fastify: FastifyInstance): Promise<void> {
|
|
|
113
146
|
handler: adminController.updateUserStatus,
|
|
114
147
|
});
|
|
115
148
|
|
|
149
|
+
/**
|
|
150
|
+
* Restore a soft-deleted account (until the 30-day purge removes it)
|
|
151
|
+
*
|
|
152
|
+
* POST /api/v1/admin/users/:userId/restore
|
|
153
|
+
* Auth: Required (ADMIN)
|
|
154
|
+
* 200 with the user; 404 USER_NOT_FOUND (none, or already purged); 409 USER_NOT_DELETED
|
|
155
|
+
*/
|
|
156
|
+
fastify.post('/admin/users/:userId/restore', {
|
|
157
|
+
schema: { params: userIdParamsSchema },
|
|
158
|
+
config: { rateLimit: RATE_LIMITS.ADMIN_DEFAULT },
|
|
159
|
+
handler: adminController.restoreUser,
|
|
160
|
+
});
|
|
161
|
+
|
|
116
162
|
/**
|
|
117
163
|
* Change user role
|
|
118
164
|
*
|
|
@@ -2,13 +2,17 @@ import { z } from 'zod';
|
|
|
2
2
|
|
|
3
3
|
// ─── IP Blocking ────────────────────────────────────────────────────────────
|
|
4
4
|
|
|
5
|
+
// Any spelling of an IPv4 or IPv6 address is accepted; libs/ip-block.ts stores
|
|
6
|
+
// and matches the canonical form (libs/ip-address.ts).
|
|
7
|
+
const ipAddress = z.union([z.ipv4(), z.ipv6()], { message: 'Invalid IP address' });
|
|
8
|
+
|
|
5
9
|
export const blockIpSchema = z.object({
|
|
6
|
-
ip:
|
|
10
|
+
ip: ipAddress,
|
|
7
11
|
reason: z.string().max(500).optional(),
|
|
8
12
|
});
|
|
9
13
|
|
|
10
14
|
export const unblockIpParamsSchema = z.object({
|
|
11
|
-
ip:
|
|
15
|
+
ip: ipAddress,
|
|
12
16
|
});
|
|
13
17
|
|
|
14
18
|
export type BlockIpInput = z.infer<typeof blockIpSchema>;
|
|
@@ -16,17 +20,25 @@ export type UnblockIpParams = z.infer<typeof unblockIpParamsSchema>;
|
|
|
16
20
|
|
|
17
21
|
// ─── User Management ────────────────────────────────────────────────────────
|
|
18
22
|
|
|
23
|
+
/**
|
|
24
|
+
* A true/false query parameter. It is parsed TWICE: the route schema turns
|
|
25
|
+
* "true"/"false" into a boolean, then the controller's parseInput parses that
|
|
26
|
+
* result again (admin.controller.ts). So it must also accept the boolean, or
|
|
27
|
+
* the second parse rejects every request (that broke ?isActive= and, with a
|
|
28
|
+
* default, the whole user list).
|
|
29
|
+
*/
|
|
30
|
+
const booleanQuery = z.union([z.boolean(), z.enum(['true', 'false']).transform((v) => v === 'true')]);
|
|
31
|
+
|
|
19
32
|
export const getUsersQuerySchema = z.object({
|
|
20
33
|
page: z.coerce.number().int().min(1).default(1),
|
|
21
34
|
limit: z.coerce.number().int().min(1).max(100).default(10),
|
|
22
35
|
search: z.string().max(100).optional(),
|
|
23
36
|
role: z.enum(['USER', 'ADMIN']).optional(),
|
|
24
|
-
isActive:
|
|
25
|
-
.enum(['true', 'false'])
|
|
26
|
-
.transform((v) => v === 'true')
|
|
27
|
-
.optional(),
|
|
37
|
+
isActive: booleanQuery.optional(),
|
|
28
38
|
sortBy: z.enum(['createdAt', 'email', 'firstName']).default('createdAt'),
|
|
29
39
|
sortOrder: z.enum(['asc', 'desc']).default('desc'),
|
|
40
|
+
// true: ONLY soft-deleted accounts (still restorable until the purge), with purgeAt.
|
|
41
|
+
deleted: booleanQuery.default(false),
|
|
30
42
|
});
|
|
31
43
|
|
|
32
44
|
export const userIdParamsSchema = z.object({
|