create-tigra 3.3.0 → 4.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +81 -12
- package/bin/create-tigra.js +495 -472
- package/lib/patchers/email-verification.patcher.js +72 -10
- package/modules/email-verification/client/hooks/useVerification.ts +4 -1
- package/modules/email-verification/server/__tests__/verification.integration.test.ts +115 -0
- package/modules/email-verification/server/verification.controller.ts +3 -1
- package/modules/email-verification/server/verification.service.ts +44 -13
- package/package.json +3 -2
- package/template/.github/dependabot.yml +47 -0
- package/template/.github/workflows/audit.yml +36 -0
- package/template/.github/workflows/ci.yml +79 -0
- package/template/AGENTS.md +18 -9
- package/template/client/.dockerignore +1 -0
- package/template/client/.env.example.production +13 -2
- package/template/client/AGENTS.md +13 -5
- package/template/client/Dockerfile +186 -14
- package/template/client/next.config.ts +1 -1
- package/template/client/package-lock.json +15983 -14181
- package/template/client/package.json +56 -48
- package/template/client/scripts/check-sharp.mjs +53 -0
- package/template/client/scripts/next-dev.cjs +5 -1
- package/template/client/src/__tests__/proxy.test.ts +92 -0
- package/template/client/src/app/healthz/route.ts +16 -0
- package/template/client/src/app/layout.tsx +9 -3
- package/template/client/src/app/page.tsx +2 -2
- package/template/client/src/app/providers.tsx +23 -4
- package/template/client/src/components/layout/Header.tsx +7 -3
- package/template/client/src/features/admin/hooks/useAdminSessions.ts +2 -1
- package/template/client/src/features/admin/hooks/useAdminUsers.ts +3 -1
- package/template/client/src/features/admin/types/admin.types.ts +2 -3
- package/template/client/src/features/auth/components/AuthInitializer.tsx +35 -18
- package/template/client/src/features/auth/components/ForgotPasswordForm.tsx +107 -0
- package/template/client/src/features/auth/components/LimitNotice.tsx +28 -0
- package/template/client/src/features/auth/components/LoginForm.tsx +13 -2
- package/template/client/src/features/auth/components/RegisterForm.tsx +23 -7
- package/template/client/src/features/auth/hooks/useAuth.ts +11 -1
- package/template/client/src/features/auth/hooks/usePasswordReset.ts +7 -1
- package/template/client/src/features/auth/services/auth.service.ts +8 -3
- package/template/client/src/features/auth/store/authSlice.ts +7 -2
- package/template/client/src/lib/api/__tests__/axios.config.test.ts +183 -0
- package/template/client/src/lib/api/api.types.ts +14 -0
- package/template/client/src/lib/api/axios.config.ts +101 -15
- package/template/client/src/lib/api/hard-redirect.ts +8 -0
- package/template/client/src/lib/api/session-events.ts +29 -0
- package/template/client/src/lib/constants/routes.ts +12 -0
- package/template/client/src/lib/observability/sentry-scrub.ts +1 -1
- package/template/client/src/lib/utils/__tests__/error.test.ts +119 -0
- package/template/client/src/lib/utils/__tests__/form.test.ts +42 -0
- package/template/client/src/lib/utils/__tests__/paths.test.ts +43 -0
- package/template/client/src/lib/utils/__tests__/security.test.ts +40 -0
- package/template/client/src/lib/utils/__tests__/session-marker.test.ts +27 -0
- package/template/client/src/lib/utils/error.ts +81 -0
- package/template/client/src/lib/utils/form.ts +31 -0
- package/template/client/src/lib/utils/paths.ts +18 -0
- package/template/client/src/lib/utils/session-marker.ts +24 -0
- package/template/client/src/{middleware.ts → proxy.ts} +25 -11
- package/template/client/src/store/__tests__/store.test.ts +44 -0
- package/template/client/src/store/index.ts +26 -8
- package/template/client/vitest.config.mts +48 -0
- package/template/server/.env.example +280 -270
- package/template/server/.env.example.production +283 -242
- package/template/server/AGENTS.md +13 -4
- package/template/server/Dockerfile +176 -14
- package/template/server/docker-compose.yml +4 -2
- package/template/server/docs/deployment.md +63 -0
- package/template/server/docs/logging.md +52 -4
- package/template/server/docs/rate-limits.md +153 -0
- package/template/server/docs/testing.md +63 -0
- package/template/server/eslint.config.mjs +19 -0
- package/template/server/package-lock.json +8784 -8743
- package/template/server/package.json +79 -75
- package/template/server/prisma/migrations/0_init/migration.sql +82 -0
- package/template/server/prisma/migrations/migration_lock.toml +3 -0
- package/template/server/prisma/schema.prisma +0 -3
- package/template/server/scripts/check-heic.mjs +40 -0
- package/template/server/scripts/check-sharp.mjs +53 -0
- package/template/server/src/__tests__/routes.integration.test.ts +280 -0
- package/template/server/src/app.ts +248 -346
- package/template/server/src/config/__tests__/env.test.ts +219 -0
- package/template/server/src/config/__tests__/rate-limit.config.test.ts +158 -0
- package/template/server/src/config/env.ts +326 -182
- package/template/server/src/config/rate-limit.config.ts +157 -106
- package/template/server/src/jobs/__tests__/cleanup-deleted-accounts.job.test.ts +60 -8
- package/template/server/src/jobs/__tests__/cleanup-expired-auth.job.test.ts +44 -0
- package/template/server/src/jobs/__tests__/jobs.integration.test.ts +88 -0
- package/template/server/src/jobs/__tests__/schedule.test.ts +92 -0
- package/template/server/src/jobs/cleanup-deleted-accounts.job.ts +38 -36
- package/template/server/src/jobs/cleanup-expired-auth.job.ts +32 -24
- package/template/server/src/jobs/index.ts +12 -2
- package/template/server/src/jobs/refresh-cloudflare-ranges.job.ts +28 -0
- package/template/server/src/jobs/schedule.ts +50 -0
- package/template/server/src/libs/__tests__/auth.test.ts +98 -7
- package/template/server/src/libs/__tests__/client-ip.test.ts +257 -121
- package/template/server/src/libs/__tests__/cloudflare-ranges.test.ts +79 -0
- package/template/server/src/libs/__tests__/cookies.test.ts +53 -2
- package/template/server/src/libs/__tests__/email-quota.test.ts +81 -0
- package/template/server/src/libs/__tests__/email.test.ts +68 -0
- package/template/server/src/libs/__tests__/error-handler.test.ts +162 -0
- package/template/server/src/libs/__tests__/health-db-down.integration.test.ts +37 -0
- package/template/server/src/libs/__tests__/health-redis-down.integration.test.ts +45 -0
- package/template/server/src/libs/__tests__/health-routes.test.ts +83 -0
- package/template/server/src/libs/__tests__/health.integration.test.ts +118 -0
- package/template/server/src/libs/__tests__/http.test.ts +74 -2
- package/template/server/src/libs/__tests__/ip-block.test.ts +179 -62
- package/template/server/src/libs/__tests__/logger.test.ts +50 -0
- package/template/server/src/libs/__tests__/monitoring.test.ts +185 -0
- package/template/server/src/libs/__tests__/outbound.integration.test.ts +48 -0
- package/template/server/src/libs/__tests__/prisma-client.test.ts +28 -0
- package/template/server/src/libs/__tests__/query-counter.integration.test.ts +53 -0
- package/template/server/src/libs/__tests__/rate-limiting.test.ts +146 -0
- package/template/server/src/libs/__tests__/rate-limits.integration.test.ts +53 -0
- package/template/server/src/libs/__tests__/redis-required.test.ts +30 -0
- package/template/server/src/libs/__tests__/redis.test.ts +38 -2
- package/template/server/src/libs/__tests__/request-id.test.ts +25 -0
- package/template/server/src/libs/__tests__/requestLogger.test.ts +126 -0
- package/template/server/src/libs/__tests__/safe-http.test.ts +138 -0
- package/template/server/src/libs/__tests__/sentry-scrub.test.ts +82 -80
- package/template/server/src/libs/__tests__/shutdown.test.ts +89 -0
- package/template/server/src/libs/__tests__/url-safety.test.ts +130 -80
- package/template/server/src/libs/auth.ts +39 -10
- package/template/server/src/libs/client-ip.ts +158 -77
- package/template/server/src/libs/cloudflare-ranges.ts +132 -0
- package/template/server/src/libs/cookies.ts +53 -14
- package/template/server/src/libs/email-quota.ts +74 -0
- package/template/server/src/libs/email.ts +46 -9
- package/template/server/src/libs/error-handler.ts +111 -0
- package/template/server/src/libs/health-routes.ts +53 -0
- package/template/server/src/libs/http.ts +139 -47
- package/template/server/src/libs/ip-address.ts +37 -0
- package/template/server/src/libs/ip-block.ts +284 -221
- package/template/server/src/libs/logger.ts +41 -12
- package/template/server/src/libs/monitoring.ts +127 -41
- package/template/server/src/libs/observability/sentry.ts +1 -1
- package/template/server/src/libs/origin-check.ts +9 -7
- package/template/server/src/libs/prisma.ts +47 -4
- package/template/server/src/libs/query-counter.ts +71 -59
- package/template/server/src/libs/rate-limiting.ts +110 -0
- package/template/server/src/libs/redis-required.ts +28 -0
- package/template/server/src/libs/redis.ts +27 -1
- package/template/server/src/libs/request-id.ts +18 -0
- package/template/server/src/libs/requestLogger.ts +112 -17
- package/template/server/src/libs/safe-http.ts +101 -0
- package/template/server/src/libs/shutdown.ts +87 -0
- package/template/server/src/libs/storage/__tests__/fixtures/tiny-heic.ts +13 -0
- package/template/server/src/libs/storage/__tests__/image-optimizer.test.ts +59 -0
- package/template/server/src/libs/storage/__tests__/multipart-limits.test.ts +91 -0
- package/template/server/src/libs/storage/__tests__/upload-persistence.test.ts +52 -0
- package/template/server/src/libs/storage/file-storage.service.ts +94 -84
- package/template/server/src/libs/storage/file-validator.ts +48 -46
- package/template/server/src/libs/storage/image-optimizer.service.ts +16 -5
- package/template/server/src/libs/token-hash.ts +18 -0
- package/template/server/src/libs/url-safety.ts +127 -121
- package/template/server/src/libs/validation-errors.ts +86 -0
- package/template/server/src/modules/admin/__tests__/admin-actions.integration.test.ts +255 -0
- package/template/server/src/modules/admin/__tests__/admin.health.test.ts +82 -0
- package/template/server/src/modules/admin/__tests__/admin.repo.test.ts +55 -0
- package/template/server/src/modules/admin/__tests__/admin.schemas.test.ts +38 -0
- package/template/server/src/modules/admin/__tests__/admin.service.test.ts +162 -0
- package/template/server/src/modules/admin/admin.controller.ts +66 -49
- package/template/server/src/modules/admin/admin.repo.ts +49 -10
- package/template/server/src/modules/admin/admin.routes.ts +48 -2
- package/template/server/src/modules/admin/admin.schemas.ts +18 -6
- package/template/server/src/modules/admin/admin.service.ts +66 -4
- package/template/server/src/modules/auth/__tests__/auth.controller.test.ts +39 -0
- package/template/server/src/modules/auth/__tests__/auth.integration.test.ts +9 -3
- package/template/server/src/modules/auth/__tests__/auth.service.dummy-hash.test.ts +34 -0
- package/template/server/src/modules/auth/__tests__/auth.service.test.ts +197 -37
- package/template/server/src/modules/auth/__tests__/session-cleanup.test.ts +39 -0
- package/template/server/src/modules/auth/__tests__/sessions.integration.test.ts +246 -0
- package/template/server/src/modules/auth/__tests__/token-fingerprints.test.ts +119 -0
- package/template/server/src/modules/auth/auth.controller.ts +133 -128
- package/template/server/src/modules/auth/auth.repo.ts +44 -44
- package/template/server/src/modules/auth/auth.schemas.ts +4 -2
- package/template/server/src/modules/auth/auth.service.ts +167 -96
- package/template/server/src/modules/auth/session.repo.ts +12 -0
- package/template/server/src/modules/files/__tests__/files.integration.test.ts +5 -5
- package/template/server/src/modules/users/__tests__/avatar-upload.test.ts +120 -0
- package/template/server/src/modules/users/__tests__/name-rules.test.ts +46 -0
- package/template/server/src/modules/users/__tests__/users.integration.test.ts +295 -0
- package/template/server/src/modules/users/__tests__/users.repo.test.ts +37 -0
- package/template/server/src/modules/users/__tests__/users.service.test.ts +129 -0
- package/template/server/src/modules/users/users.controller.ts +9 -38
- package/template/server/src/modules/users/users.repo.ts +23 -7
- package/template/server/src/modules/users/users.routes.ts +3 -22
- package/template/server/src/modules/users/users.schemas.ts +15 -9
- package/template/server/src/modules/users/users.service.ts +105 -93
- package/template/server/src/scripts/make-admin.ts +48 -0
- package/template/server/src/server.ts +48 -26
- package/template/server/src/shared/errors/AppError.ts +27 -1
- package/template/server/src/shared/errors/errors.ts +42 -5
- package/template/server/src/shared/responses/successResponse.ts +22 -3
- package/template/server/src/shared/types/index.ts +7 -0
- package/template/server/src/test/__tests__/integration-services.test.ts +66 -0
- package/template/server/src/test/integration-helpers.ts +343 -0
- package/template/server/src/test/integration-services.ts +74 -0
- package/template/server/src/test/integration.global-setup.ts +144 -0
- package/template/server/src/test/integration.setup.ts +35 -158
- package/template/server/src/test/setup.ts +3 -10
- package/template/server/tsconfig.build.json +1 -1
- package/template/server/tsconfig.json +1 -0
- package/template/server/vitest.config.ts +17 -4
- package/template/server/vitest.integration.config.ts +18 -13
- package/template/server/src/libs/storage/filename-sanitizer.ts +0 -71
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* GET /api/v1/admin/health behind the REAL admin gate (authenticate +
|
|
3
|
+
* authorize('ADMIN') from libs/auth.ts, @fastify/jwt): 401 without a token,
|
|
4
|
+
* 403 for a USER, 200 with the full report for an ADMIN. Only the session
|
|
5
|
+
* lookup and the checks are mocked.
|
|
6
|
+
*/
|
|
7
|
+
import Fastify, { type FastifyInstance } from 'fastify';
|
|
8
|
+
import jwt from '@fastify/jwt';
|
|
9
|
+
import { serializerCompiler, validatorCompiler } from 'fastify-type-provider-zod';
|
|
10
|
+
import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest';
|
|
11
|
+
import { prisma } from '@libs/prisma.js';
|
|
12
|
+
import { performHealthCheck } from '@libs/monitoring.js';
|
|
13
|
+
import { initAuth } from '@libs/auth.js';
|
|
14
|
+
import { registerErrorHandler } from '@libs/error-handler.js';
|
|
15
|
+
import { adminRoutes } from '../admin.routes.js';
|
|
16
|
+
|
|
17
|
+
vi.mock('@libs/prisma.js', () => ({
|
|
18
|
+
prisma: { session: { findFirst: vi.fn() }, user: { findUnique: vi.fn() } },
|
|
19
|
+
}));
|
|
20
|
+
vi.mock('@libs/monitoring.js', () => ({ performHealthCheck: vi.fn() }));
|
|
21
|
+
|
|
22
|
+
const fullReport = {
|
|
23
|
+
status: 'degraded' as const,
|
|
24
|
+
checks: {
|
|
25
|
+
database: { status: 'up' as const, responseTime: 3 },
|
|
26
|
+
redis: { status: 'down' as const, message: 'Redis connection failed (non-fatal)' },
|
|
27
|
+
memory: { status: 'up' as const, details: { heapUsedMB: 50, heapLimitMB: 4096 } },
|
|
28
|
+
uptime: { status: 'up' as const, details: { uptimeSeconds: 99 } },
|
|
29
|
+
},
|
|
30
|
+
timestamp: '2026-10-20T00:00:00.000Z',
|
|
31
|
+
checkedAt: '2026-10-20T00:00:00.000Z',
|
|
32
|
+
version: '1.2.3',
|
|
33
|
+
commit: 'abc1234def56',
|
|
34
|
+
environment: 'test',
|
|
35
|
+
};
|
|
36
|
+
|
|
37
|
+
let app: FastifyInstance;
|
|
38
|
+
|
|
39
|
+
/** A signed access token whose session lookup answers with `role`. */
|
|
40
|
+
function tokenFor(role: 'USER' | 'ADMIN'): string {
|
|
41
|
+
vi.mocked(prisma.session.findFirst).mockResolvedValue({
|
|
42
|
+
user: { isActive: true, emailVerifiedAt: new Date(), deletedAt: null, role },
|
|
43
|
+
} as never);
|
|
44
|
+
return app.jwt.sign({ userId: `${role}-1`, role, sessionId: `${role}-session` });
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
beforeAll(async () => {
|
|
48
|
+
app = Fastify({ logger: false });
|
|
49
|
+
app.setValidatorCompiler(validatorCompiler);
|
|
50
|
+
app.setSerializerCompiler(serializerCompiler);
|
|
51
|
+
await app.register(jwt, { secret: 'test-jwt-secret-must-be-at-least-32-characters-long' });
|
|
52
|
+
initAuth(app);
|
|
53
|
+
registerErrorHandler(app);
|
|
54
|
+
await app.register(adminRoutes, { prefix: '/api/v1' });
|
|
55
|
+
await app.ready();
|
|
56
|
+
vi.mocked(performHealthCheck).mockResolvedValue(fullReport);
|
|
57
|
+
});
|
|
58
|
+
afterAll(() => app.close());
|
|
59
|
+
|
|
60
|
+
describe('GET /api/v1/admin/health', () => {
|
|
61
|
+
it('401 without a token, and runs no check', async () => {
|
|
62
|
+
const res = await app.inject({ method: 'GET', url: '/api/v1/admin/health' });
|
|
63
|
+
expect(res.statusCode).toBe(401);
|
|
64
|
+
expect(performHealthCheck).not.toHaveBeenCalled();
|
|
65
|
+
});
|
|
66
|
+
|
|
67
|
+
it('403 for a signed-in USER', async () => {
|
|
68
|
+
const res = await app.inject({
|
|
69
|
+
method: 'GET', url: '/api/v1/admin/health', headers: { authorization: `Bearer ${tokenFor('USER')}` },
|
|
70
|
+
});
|
|
71
|
+
expect(res.statusCode).toBe(403);
|
|
72
|
+
expect(performHealthCheck).not.toHaveBeenCalled();
|
|
73
|
+
});
|
|
74
|
+
|
|
75
|
+
it('200 with the full report for an ADMIN, even when degraded', async () => {
|
|
76
|
+
const res = await app.inject({
|
|
77
|
+
method: 'GET', url: '/api/v1/admin/health', headers: { authorization: `Bearer ${tokenFor('ADMIN')}` },
|
|
78
|
+
});
|
|
79
|
+
expect(res.statusCode).toBe(200);
|
|
80
|
+
expect(res.json()).toEqual({ success: true, message: 'Health report', data: fullReport });
|
|
81
|
+
});
|
|
82
|
+
});
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The admin repository queries behind the deleted-accounts list and restore:
|
|
3
|
+
* the list shows live OR deleted accounts (never both), and restore changes
|
|
4
|
+
* only a deleted row.
|
|
5
|
+
*/
|
|
6
|
+
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
|
7
|
+
import { prisma } from '@libs/prisma.js';
|
|
8
|
+
import { adminRepository } from '../admin.repo.js';
|
|
9
|
+
|
|
10
|
+
vi.mock('@libs/prisma.js', () => ({
|
|
11
|
+
prisma: {
|
|
12
|
+
user: { findMany: vi.fn(), findUnique: vi.fn(), count: vi.fn(), updateMany: vi.fn() },
|
|
13
|
+
session: { findFirst: vi.fn() },
|
|
14
|
+
},
|
|
15
|
+
isPrismaNotFound: (): boolean => false,
|
|
16
|
+
}));
|
|
17
|
+
|
|
18
|
+
const list = { page: 1, limit: 10, sortBy: 'createdAt', sortOrder: 'desc' } as const;
|
|
19
|
+
|
|
20
|
+
beforeEach(() => {
|
|
21
|
+
vi.clearAllMocks();
|
|
22
|
+
vi.mocked(prisma.user.findMany).mockResolvedValue([]);
|
|
23
|
+
vi.mocked(prisma.user.count).mockResolvedValue(0);
|
|
24
|
+
});
|
|
25
|
+
|
|
26
|
+
describe('adminRepository', () => {
|
|
27
|
+
it('lists only live accounts by default', async () => {
|
|
28
|
+
await adminRepository.getUsers(list);
|
|
29
|
+
expect(vi.mocked(prisma.user.findMany).mock.calls[0]?.[0]?.where).toMatchObject({ deletedAt: null });
|
|
30
|
+
});
|
|
31
|
+
|
|
32
|
+
it('lists only soft-deleted accounts with deleted: true', async () => {
|
|
33
|
+
await adminRepository.getUsers({ ...list, deleted: true });
|
|
34
|
+
expect(vi.mocked(prisma.user.findMany).mock.calls[0]?.[0]?.where).toMatchObject({ deletedAt: { not: null } });
|
|
35
|
+
});
|
|
36
|
+
|
|
37
|
+
it('restore is one conditional update that touches only a deleted row', async () => {
|
|
38
|
+
vi.mocked(prisma.user.updateMany).mockResolvedValueOnce({ count: 1 }).mockResolvedValueOnce({ count: 0 });
|
|
39
|
+
await expect(adminRepository.restoreUser('u1')).resolves.toBe(true);
|
|
40
|
+
await expect(adminRepository.restoreUser('u1')).resolves.toBe(false);
|
|
41
|
+
expect(prisma.user.updateMany).toHaveBeenCalledWith({
|
|
42
|
+
where: { id: 'u1', deletedAt: { not: null } },
|
|
43
|
+
data: { deletedAt: null, isActive: true },
|
|
44
|
+
});
|
|
45
|
+
});
|
|
46
|
+
|
|
47
|
+
it('user detail reports lastActiveAt (the latest still-existing session), not lastLogin', async () => {
|
|
48
|
+
const seen = new Date('2026-10-19T08:00:00Z');
|
|
49
|
+
vi.mocked(prisma.user.findUnique).mockResolvedValue({ id: 'u1', _count: { sessions: 2 } } as never);
|
|
50
|
+
vi.mocked(prisma.session.findFirst).mockResolvedValue({ lastActiveAt: seen } as never);
|
|
51
|
+
const detail = await adminRepository.getUserDetail('u1');
|
|
52
|
+
expect(detail).toMatchObject({ sessionCount: 2, lastActiveAt: seen });
|
|
53
|
+
expect(detail).not.toHaveProperty('lastLogin');
|
|
54
|
+
});
|
|
55
|
+
});
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Admin query schemas are parsed twice: by the route schema, then again by the
|
|
3
|
+
* controller's parseInput on the already-parsed values. Parsing a result again
|
|
4
|
+
* must give the same result, or every request answers 422 (it did: a boolean
|
|
5
|
+
* from the first parse failed the "true"/"false" check of the second).
|
|
6
|
+
*/
|
|
7
|
+
import { describe, expect, it } from 'vitest';
|
|
8
|
+
import { getSessionsQuerySchema, getUsersQuerySchema } from '../admin.schemas.js';
|
|
9
|
+
|
|
10
|
+
const twice = <T>(schema: { parse: (v: unknown) => T }, input: unknown): { once: T; again: T } => {
|
|
11
|
+
const once = schema.parse(input);
|
|
12
|
+
return { once, again: schema.parse(once) };
|
|
13
|
+
};
|
|
14
|
+
|
|
15
|
+
describe('admin query schemas survive the second parse', () => {
|
|
16
|
+
it.each([
|
|
17
|
+
[{}],
|
|
18
|
+
[{ isActive: 'true' }],
|
|
19
|
+
[{ isActive: 'false', deleted: 'true', page: '2', limit: '50', role: 'ADMIN', search: 'ann' }],
|
|
20
|
+
])('users query %j', (input) => {
|
|
21
|
+
const { once, again } = twice(getUsersQuerySchema, input);
|
|
22
|
+
expect(again).toEqual(once);
|
|
23
|
+
});
|
|
24
|
+
|
|
25
|
+
it('users query turns the strings into booleans and defaults deleted to false', () => {
|
|
26
|
+
expect(getUsersQuerySchema.parse({ isActive: 'true' })).toMatchObject({ isActive: true, deleted: false });
|
|
27
|
+
expect(getUsersQuerySchema.parse({ deleted: 'true' })).toMatchObject({ deleted: true });
|
|
28
|
+
});
|
|
29
|
+
|
|
30
|
+
it('still refuses a value that is not true/false', () => {
|
|
31
|
+
expect(getUsersQuerySchema.safeParse({ isActive: 'yes' }).success).toBe(false);
|
|
32
|
+
});
|
|
33
|
+
|
|
34
|
+
it('sessions query', () => {
|
|
35
|
+
const { once, again } = twice(getSessionsQuerySchema, { page: '3', userId: '22222222-2222-4222-8222-222222222222' });
|
|
36
|
+
expect(again).toEqual(once);
|
|
37
|
+
});
|
|
38
|
+
});
|
|
@@ -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
|
}
|
|
@@ -20,8 +20,6 @@ const adminUserSelect = {
|
|
|
20
20
|
isActive: true,
|
|
21
21
|
emailVerifiedAt: true,
|
|
22
22
|
deletedAt: true,
|
|
23
|
-
failedLoginAttempts: true,
|
|
24
|
-
lockedUntil: true,
|
|
25
23
|
createdAt: true,
|
|
26
24
|
updatedAt: true,
|
|
27
25
|
} as const;
|
|
@@ -45,15 +43,18 @@ export type AdminUser = {
|
|
|
45
43
|
isActive: boolean;
|
|
46
44
|
emailVerifiedAt: Date | null;
|
|
47
45
|
deletedAt: Date | null;
|
|
48
|
-
failedLoginAttempts: number;
|
|
49
|
-
lockedUntil: Date | null;
|
|
50
46
|
createdAt: Date;
|
|
51
47
|
updatedAt: Date;
|
|
52
48
|
};
|
|
53
49
|
|
|
54
50
|
export type AdminUserDetail = AdminUser & {
|
|
55
51
|
sessionCount: number;
|
|
56
|
-
|
|
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;
|
|
57
58
|
};
|
|
58
59
|
|
|
59
60
|
export type AdminSession = {
|
|
@@ -94,12 +95,14 @@ class AdminRepository {
|
|
|
94
95
|
isActive?: boolean;
|
|
95
96
|
sortBy: 'createdAt' | 'email' | 'firstName';
|
|
96
97
|
sortOrder: 'asc' | 'desc';
|
|
98
|
+
deleted?: boolean;
|
|
97
99
|
}): Promise<{ items: AdminUser[]; totalItems: number }> {
|
|
98
|
-
const { page, limit, search, role, isActive, sortBy, sortOrder } = params;
|
|
100
|
+
const { page, limit, search, role, isActive, sortBy, sortOrder, deleted = false } = params;
|
|
99
101
|
const offset = (page - 1) * limit;
|
|
100
102
|
|
|
103
|
+
// Live accounts by default; `deleted` lists only soft-deleted ones instead.
|
|
101
104
|
const where: Record<string, unknown> = {
|
|
102
|
-
deletedAt: null,
|
|
105
|
+
deletedAt: deleted ? { not: null } : null,
|
|
103
106
|
};
|
|
104
107
|
|
|
105
108
|
if (search) {
|
|
@@ -144,7 +147,7 @@ class AdminRepository {
|
|
|
144
147
|
}
|
|
145
148
|
|
|
146
149
|
/**
|
|
147
|
-
* Get detailed user info including session count and last
|
|
150
|
+
* Get detailed user info including session count and last activity
|
|
148
151
|
*/
|
|
149
152
|
async getUserDetail(userId: string): Promise<AdminUserDetail | null> {
|
|
150
153
|
const now = new Date();
|
|
@@ -165,7 +168,7 @@ class AdminRepository {
|
|
|
165
168
|
|
|
166
169
|
if (!user) return null;
|
|
167
170
|
|
|
168
|
-
//
|
|
171
|
+
// Last activity of the most recently used session that still exists
|
|
169
172
|
const latestSession = await prisma.session.findFirst({
|
|
170
173
|
where: { userId },
|
|
171
174
|
orderBy: { lastActiveAt: 'desc' },
|
|
@@ -177,7 +180,7 @@ class AdminRepository {
|
|
|
177
180
|
return {
|
|
178
181
|
...userData,
|
|
179
182
|
sessionCount: _count.sessions,
|
|
180
|
-
|
|
183
|
+
lastActiveAt: latestSession?.lastActiveAt ?? null,
|
|
181
184
|
};
|
|
182
185
|
}
|
|
183
186
|
|
|
@@ -194,6 +197,42 @@ class AdminRepository {
|
|
|
194
197
|
});
|
|
195
198
|
}
|
|
196
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
|
+
|
|
197
236
|
/**
|
|
198
237
|
* Update user role
|
|
199
238
|
*/
|