create-tigra 3.3.0 → 4.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +151 -0
- package/README.md +264 -56
- package/bin/create-tigra.js +497 -472
- package/lib/patchers/email-verification.patcher.js +72 -10
- package/modules/email-verification/client/hooks/useVerification.ts +4 -1
- package/modules/email-verification/server/__tests__/verification.integration.test.ts +115 -0
- package/modules/email-verification/server/verification.controller.ts +3 -1
- package/modules/email-verification/server/verification.service.ts +44 -13
- package/package.json +5 -3
- package/template/.github/dependabot.yml +47 -0
- package/template/.github/workflows/audit.yml +36 -0
- package/template/.github/workflows/ci.yml +79 -0
- package/template/AGENTS.md +18 -9
- package/template/README.md +79 -0
- package/template/client/.dockerignore +1 -0
- package/template/client/.env.example.production +13 -2
- package/template/client/AGENTS.md +13 -5
- package/template/client/Dockerfile +186 -14
- package/template/client/README.md +92 -21
- package/template/client/next.config.ts +1 -1
- package/template/client/package-lock.json +15983 -14181
- package/template/client/package.json +56 -48
- package/template/client/scripts/check-sharp.mjs +53 -0
- package/template/client/scripts/next-dev.cjs +5 -1
- package/template/client/src/__tests__/proxy.test.ts +92 -0
- package/template/client/src/app/healthz/route.ts +16 -0
- package/template/client/src/app/layout.tsx +9 -3
- package/template/client/src/app/page.tsx +2 -2
- package/template/client/src/app/providers.tsx +23 -4
- package/template/client/src/components/layout/Header.tsx +7 -3
- package/template/client/src/features/admin/hooks/useAdminSessions.ts +2 -1
- package/template/client/src/features/admin/hooks/useAdminUsers.ts +3 -1
- package/template/client/src/features/admin/types/admin.types.ts +2 -3
- package/template/client/src/features/auth/components/AuthInitializer.tsx +35 -18
- package/template/client/src/features/auth/components/ForgotPasswordForm.tsx +107 -0
- package/template/client/src/features/auth/components/LimitNotice.tsx +28 -0
- package/template/client/src/features/auth/components/LoginForm.tsx +13 -2
- package/template/client/src/features/auth/components/RegisterForm.tsx +23 -7
- package/template/client/src/features/auth/hooks/useAuth.ts +11 -1
- package/template/client/src/features/auth/hooks/usePasswordReset.ts +7 -1
- package/template/client/src/features/auth/services/auth.service.ts +8 -3
- package/template/client/src/features/auth/store/authSlice.ts +7 -2
- package/template/client/src/lib/api/__tests__/axios.config.test.ts +183 -0
- package/template/client/src/lib/api/api.types.ts +14 -0
- package/template/client/src/lib/api/axios.config.ts +101 -15
- package/template/client/src/lib/api/hard-redirect.ts +8 -0
- package/template/client/src/lib/api/session-events.ts +29 -0
- package/template/client/src/lib/constants/routes.ts +12 -0
- package/template/client/src/lib/observability/sentry-scrub.ts +1 -1
- package/template/client/src/lib/utils/__tests__/error.test.ts +119 -0
- package/template/client/src/lib/utils/__tests__/form.test.ts +42 -0
- package/template/client/src/lib/utils/__tests__/paths.test.ts +43 -0
- package/template/client/src/lib/utils/__tests__/security.test.ts +40 -0
- package/template/client/src/lib/utils/__tests__/session-marker.test.ts +27 -0
- package/template/client/src/lib/utils/error.ts +81 -0
- package/template/client/src/lib/utils/form.ts +31 -0
- package/template/client/src/lib/utils/paths.ts +18 -0
- package/template/client/src/lib/utils/session-marker.ts +24 -0
- package/template/client/src/{middleware.ts → proxy.ts} +25 -11
- package/template/client/src/store/__tests__/store.test.ts +44 -0
- package/template/client/src/store/index.ts +26 -8
- package/template/client/vitest.config.mts +48 -0
- package/template/server/.env.example +280 -270
- package/template/server/.env.example.production +283 -242
- package/template/server/AGENTS.md +13 -4
- package/template/server/Dockerfile +176 -14
- package/template/server/README.md +108 -0
- package/template/server/docker-compose.yml +4 -2
- package/template/server/docs/deployment.md +63 -0
- package/template/server/docs/logging.md +66 -4
- package/template/server/docs/rate-limits.md +153 -0
- package/template/server/docs/testing.md +81 -0
- package/template/server/eslint.config.mjs +19 -0
- package/template/server/package-lock.json +8784 -8743
- package/template/server/package.json +79 -75
- package/template/server/prisma/migrations/0_init/migration.sql +82 -0
- package/template/server/prisma/migrations/migration_lock.toml +3 -0
- package/template/server/prisma/schema.prisma +0 -3
- package/template/server/scripts/check-heic.mjs +40 -0
- package/template/server/scripts/check-sharp.mjs +53 -0
- package/template/server/src/__tests__/routes.integration.test.ts +280 -0
- package/template/server/src/app.ts +248 -346
- package/template/server/src/config/__tests__/env.test.ts +219 -0
- package/template/server/src/config/__tests__/rate-limit.config.test.ts +158 -0
- package/template/server/src/config/env.ts +326 -182
- package/template/server/src/config/rate-limit.config.ts +157 -106
- package/template/server/src/jobs/__tests__/cleanup-deleted-accounts.job.test.ts +60 -8
- package/template/server/src/jobs/__tests__/cleanup-expired-auth.job.test.ts +44 -0
- package/template/server/src/jobs/__tests__/jobs.integration.test.ts +88 -0
- package/template/server/src/jobs/__tests__/schedule.test.ts +92 -0
- package/template/server/src/jobs/cleanup-deleted-accounts.job.ts +38 -36
- package/template/server/src/jobs/cleanup-expired-auth.job.ts +32 -24
- package/template/server/src/jobs/index.ts +12 -2
- package/template/server/src/jobs/refresh-cloudflare-ranges.job.ts +28 -0
- package/template/server/src/jobs/schedule.ts +50 -0
- package/template/server/src/libs/__tests__/auth.test.ts +98 -7
- package/template/server/src/libs/__tests__/client-ip.test.ts +257 -121
- package/template/server/src/libs/__tests__/cloudflare-ranges.test.ts +79 -0
- package/template/server/src/libs/__tests__/cookies.test.ts +53 -2
- package/template/server/src/libs/__tests__/email-quota.test.ts +81 -0
- package/template/server/src/libs/__tests__/email.test.ts +68 -0
- package/template/server/src/libs/__tests__/error-handler.test.ts +162 -0
- package/template/server/src/libs/__tests__/health-db-down.integration.test.ts +37 -0
- package/template/server/src/libs/__tests__/health-redis-down.integration.test.ts +45 -0
- package/template/server/src/libs/__tests__/health-routes.test.ts +83 -0
- package/template/server/src/libs/__tests__/health.integration.test.ts +118 -0
- package/template/server/src/libs/__tests__/http.test.ts +74 -2
- package/template/server/src/libs/__tests__/ip-block.test.ts +179 -62
- package/template/server/src/libs/__tests__/logger.test.ts +50 -0
- package/template/server/src/libs/__tests__/monitoring.test.ts +185 -0
- package/template/server/src/libs/__tests__/outbound.integration.test.ts +48 -0
- package/template/server/src/libs/__tests__/prisma-client.test.ts +28 -0
- package/template/server/src/libs/__tests__/query-counter.integration.test.ts +53 -0
- package/template/server/src/libs/__tests__/rate-limiting.test.ts +146 -0
- package/template/server/src/libs/__tests__/rate-limits.integration.test.ts +53 -0
- package/template/server/src/libs/__tests__/redis-required.test.ts +30 -0
- package/template/server/src/libs/__tests__/redis.test.ts +38 -2
- package/template/server/src/libs/__tests__/request-id.test.ts +25 -0
- package/template/server/src/libs/__tests__/requestLogger.test.ts +126 -0
- package/template/server/src/libs/__tests__/safe-http.test.ts +138 -0
- package/template/server/src/libs/__tests__/sentry-scrub.test.ts +82 -80
- package/template/server/src/libs/__tests__/shutdown.test.ts +89 -0
- package/template/server/src/libs/__tests__/url-safety.test.ts +130 -80
- package/template/server/src/libs/auth.ts +39 -10
- package/template/server/src/libs/client-ip.ts +158 -77
- package/template/server/src/libs/cloudflare-ranges.ts +132 -0
- package/template/server/src/libs/cookies.ts +53 -14
- package/template/server/src/libs/email-quota.ts +74 -0
- package/template/server/src/libs/email.ts +46 -9
- package/template/server/src/libs/error-handler.ts +111 -0
- package/template/server/src/libs/health-routes.ts +53 -0
- package/template/server/src/libs/http.ts +139 -47
- package/template/server/src/libs/ip-address.ts +37 -0
- package/template/server/src/libs/ip-block.ts +284 -221
- package/template/server/src/libs/logger.ts +41 -12
- package/template/server/src/libs/monitoring.ts +127 -41
- package/template/server/src/libs/observability/sentry.ts +1 -1
- package/template/server/src/libs/origin-check.ts +9 -7
- package/template/server/src/libs/prisma.ts +47 -4
- package/template/server/src/libs/query-counter.ts +71 -59
- package/template/server/src/libs/rate-limiting.ts +110 -0
- package/template/server/src/libs/redis-required.ts +28 -0
- package/template/server/src/libs/redis.ts +27 -1
- package/template/server/src/libs/request-id.ts +18 -0
- package/template/server/src/libs/requestLogger.ts +112 -17
- package/template/server/src/libs/safe-http.ts +101 -0
- package/template/server/src/libs/shutdown.ts +87 -0
- package/template/server/src/libs/storage/__tests__/fixtures/tiny-heic.ts +13 -0
- package/template/server/src/libs/storage/__tests__/image-optimizer.test.ts +59 -0
- package/template/server/src/libs/storage/__tests__/multipart-limits.test.ts +91 -0
- package/template/server/src/libs/storage/__tests__/upload-persistence.test.ts +52 -0
- package/template/server/src/libs/storage/file-storage.service.ts +94 -84
- package/template/server/src/libs/storage/file-validator.ts +48 -46
- package/template/server/src/libs/storage/image-optimizer.service.ts +16 -5
- package/template/server/src/libs/token-hash.ts +18 -0
- package/template/server/src/libs/url-safety.ts +127 -121
- package/template/server/src/libs/validation-errors.ts +86 -0
- package/template/server/src/modules/admin/__tests__/admin-actions.integration.test.ts +255 -0
- package/template/server/src/modules/admin/__tests__/admin.health.test.ts +82 -0
- package/template/server/src/modules/admin/__tests__/admin.repo.test.ts +55 -0
- package/template/server/src/modules/admin/__tests__/admin.schemas.test.ts +38 -0
- package/template/server/src/modules/admin/__tests__/admin.service.test.ts +162 -0
- package/template/server/src/modules/admin/admin.controller.ts +66 -49
- package/template/server/src/modules/admin/admin.repo.ts +49 -10
- package/template/server/src/modules/admin/admin.routes.ts +48 -2
- package/template/server/src/modules/admin/admin.schemas.ts +18 -6
- package/template/server/src/modules/admin/admin.service.ts +66 -4
- package/template/server/src/modules/auth/__tests__/auth.controller.test.ts +39 -0
- package/template/server/src/modules/auth/__tests__/auth.integration.test.ts +9 -3
- package/template/server/src/modules/auth/__tests__/auth.service.dummy-hash.test.ts +34 -0
- package/template/server/src/modules/auth/__tests__/auth.service.test.ts +197 -37
- package/template/server/src/modules/auth/__tests__/session-cleanup.test.ts +39 -0
- package/template/server/src/modules/auth/__tests__/sessions.integration.test.ts +246 -0
- package/template/server/src/modules/auth/__tests__/token-fingerprints.test.ts +119 -0
- package/template/server/src/modules/auth/auth.controller.ts +133 -128
- package/template/server/src/modules/auth/auth.repo.ts +44 -44
- package/template/server/src/modules/auth/auth.schemas.ts +4 -2
- package/template/server/src/modules/auth/auth.service.ts +167 -96
- package/template/server/src/modules/auth/session.repo.ts +12 -0
- package/template/server/src/modules/files/__tests__/files.integration.test.ts +5 -5
- package/template/server/src/modules/users/__tests__/avatar-upload.test.ts +120 -0
- package/template/server/src/modules/users/__tests__/name-rules.test.ts +46 -0
- package/template/server/src/modules/users/__tests__/users.integration.test.ts +295 -0
- package/template/server/src/modules/users/__tests__/users.repo.test.ts +37 -0
- package/template/server/src/modules/users/__tests__/users.service.test.ts +129 -0
- package/template/server/src/modules/users/users.controller.ts +9 -38
- package/template/server/src/modules/users/users.repo.ts +23 -7
- package/template/server/src/modules/users/users.routes.ts +3 -22
- package/template/server/src/modules/users/users.schemas.ts +15 -9
- package/template/server/src/modules/users/users.service.ts +105 -93
- package/template/server/src/scripts/make-admin.ts +48 -0
- package/template/server/src/server.ts +48 -26
- package/template/server/src/shared/errors/AppError.ts +27 -1
- package/template/server/src/shared/errors/errors.ts +42 -5
- package/template/server/src/shared/responses/successResponse.ts +22 -3
- package/template/server/src/shared/types/index.ts +7 -0
- package/template/server/src/test/__tests__/integration-services.test.ts +66 -0
- package/template/server/src/test/integration-helpers.ts +343 -0
- package/template/server/src/test/integration-services.ts +74 -0
- package/template/server/src/test/integration.global-setup.ts +144 -0
- package/template/server/src/test/integration.setup.ts +35 -158
- package/template/server/src/test/setup.ts +3 -10
- package/template/server/tsconfig.build.json +1 -1
- package/template/server/tsconfig.json +1 -0
- package/template/server/vitest.config.ts +17 -4
- package/template/server/vitest.integration.config.ts +18 -13
- package/template/server/src/libs/storage/filename-sanitizer.ts +0 -71
|
@@ -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({
|
|
@@ -5,7 +5,8 @@
|
|
|
5
5
|
*/
|
|
6
6
|
|
|
7
7
|
import { logger } from '@libs/logger.js';
|
|
8
|
-
import { NotFoundError, ForbiddenError } from '@shared/errors/errors.js';
|
|
8
|
+
import { NotFoundError, ForbiddenError, ConflictError } from '@shared/errors/errors.js';
|
|
9
|
+
import { RETENTION_DAYS } from '@/jobs/cleanup-deleted-accounts.job.js';
|
|
9
10
|
import { adminRepository } from './admin.repo.js';
|
|
10
11
|
import { sessionRepository } from '@modules/auth/session.repo.js';
|
|
11
12
|
import { deleteRefreshTokensByUserId } from '@modules/auth/auth.repo.js';
|
|
@@ -25,8 +26,43 @@ class AdminService {
|
|
|
25
26
|
isActive?: boolean;
|
|
26
27
|
sortBy: 'createdAt' | 'email' | 'firstName';
|
|
27
28
|
sortOrder: 'asc' | 'desc';
|
|
28
|
-
|
|
29
|
-
|
|
29
|
+
deleted?: boolean;
|
|
30
|
+
}): Promise<{ items: (AdminUser & { purgeAt?: Date })[]; totalItems: number }> {
|
|
31
|
+
const result = await adminRepository.getUsers(params);
|
|
32
|
+
if (!params.deleted) return result;
|
|
33
|
+
// Deleted accounts say when the nightly purge removes them for good.
|
|
34
|
+
return {
|
|
35
|
+
...result,
|
|
36
|
+
items: result.items.map((user) => ({
|
|
37
|
+
...user,
|
|
38
|
+
purgeAt: new Date(user.deletedAt!.getTime() + RETENTION_DAYS * 24 * 60 * 60 * 1000),
|
|
39
|
+
})),
|
|
40
|
+
};
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* Restore a soft-deleted account (before the purge removes it). It can sign
|
|
45
|
+
* in again with its old password: isActive is set back to true, since the
|
|
46
|
+
* deletion overwrote it (a ban from before the deletion is not kept; ban
|
|
47
|
+
* again if needed). No sessions come back, and no avatar (removed at
|
|
48
|
+
* deletion). The email was reserved while deleted, so it never conflicts.
|
|
49
|
+
*
|
|
50
|
+
* @throws NotFoundError 404 USER_NOT_FOUND if the account does not exist (or was purged)
|
|
51
|
+
* @throws ConflictError 409 USER_NOT_DELETED if the account is not deleted
|
|
52
|
+
*/
|
|
53
|
+
async restoreUser(userId: string): Promise<AdminUser> {
|
|
54
|
+
if (!(await adminRepository.restoreUser(userId))) {
|
|
55
|
+
if (!(await adminRepository.userExists(userId))) {
|
|
56
|
+
throw new NotFoundError('User not found', 'USER_NOT_FOUND');
|
|
57
|
+
}
|
|
58
|
+
throw new ConflictError('This account is not deleted', 'USER_NOT_DELETED');
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
const user = await adminRepository.findUserById(userId);
|
|
62
|
+
if (!user) throw new NotFoundError('User not found', 'USER_NOT_FOUND');
|
|
63
|
+
|
|
64
|
+
logger.info({ msg: 'Deleted account restored', userId });
|
|
65
|
+
return user;
|
|
30
66
|
}
|
|
31
67
|
|
|
32
68
|
/**
|
|
@@ -48,8 +84,14 @@ class AdminService {
|
|
|
48
84
|
* lifted here: email verification no longer touches isActive.
|
|
49
85
|
* Activating a user who never verified their email also approves the email,
|
|
50
86
|
* so admins keep the ability to let a user in manually.
|
|
87
|
+
* An admin can never ban themselves (like changing their own role): it would
|
|
88
|
+
* end their own sessions and could leave the project with no admin at all.
|
|
51
89
|
*/
|
|
52
|
-
async toggleUserStatus(userId: string, isActive: boolean): Promise<AdminUser> {
|
|
90
|
+
async toggleUserStatus(userId: string, isActive: boolean, adminUserId: string): Promise<AdminUser> {
|
|
91
|
+
if (!isActive && userId === adminUserId) {
|
|
92
|
+
throw new ForbiddenError('You cannot ban your own account', 'CANNOT_BAN_SELF');
|
|
93
|
+
}
|
|
94
|
+
|
|
53
95
|
const user = await adminRepository.findUserById(userId);
|
|
54
96
|
|
|
55
97
|
if (!user) {
|
|
@@ -114,6 +156,26 @@ class AdminService {
|
|
|
114
156
|
return updatedUser;
|
|
115
157
|
}
|
|
116
158
|
|
|
159
|
+
/**
|
|
160
|
+
* Promote an EXISTING account to ADMIN by email (src/scripts/make-admin.ts).
|
|
161
|
+
* The way to get the first admin in production, and to recover when no admin
|
|
162
|
+
* is left. It never creates an account and never touches a password: the
|
|
163
|
+
* person signs up in the app with their own password first.
|
|
164
|
+
* Refuses a deleted account (restore it first) and a banned one (unban it
|
|
165
|
+
* first). Marks the email verified if it was not. Sessions are kept: the role
|
|
166
|
+
* is re-read on every request, so the new rights apply at once.
|
|
167
|
+
*/
|
|
168
|
+
async promoteToAdmin(rawEmail: string): Promise<'promoted' | 'already-admin' | 'not-found' | 'deleted' | 'banned'> {
|
|
169
|
+
const email = rawEmail.trim().toLowerCase(); // register stores emails lower-cased
|
|
170
|
+
const account = await adminRepository.findAccountStateByEmail(email);
|
|
171
|
+
if (!account) return 'not-found';
|
|
172
|
+
if (account.deletedAt) return 'deleted';
|
|
173
|
+
if (!account.isActive) return 'banned';
|
|
174
|
+
if (account.role === 'ADMIN') return 'already-admin';
|
|
175
|
+
await adminRepository.promoteToAdmin(account.id, account.emailVerifiedAt ?? new Date());
|
|
176
|
+
return 'promoted';
|
|
177
|
+
}
|
|
178
|
+
|
|
117
179
|
/**
|
|
118
180
|
* Get dashboard statistics
|
|
119
181
|
*/
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The refresh controller clears the auth cookies when a session is dead,
|
|
3
|
+
* EXCEPT when the refresh lost a race with a parallel one (two tabs): that
|
|
4
|
+
* browser already holds the winner's fresh cookies (auth.service.ts refresh()).
|
|
5
|
+
*/
|
|
6
|
+
import { describe, expect, it, vi, beforeEach } from 'vitest';
|
|
7
|
+
import type { FastifyReply, FastifyRequest } from 'fastify';
|
|
8
|
+
import { UnauthorizedError } from '@shared/errors/errors.js';
|
|
9
|
+
import { clearAuthCookies, setAuthCookies } from '@libs/cookies.js';
|
|
10
|
+
import * as authService from '../auth.service.js';
|
|
11
|
+
import { refresh } from '../auth.controller.js';
|
|
12
|
+
|
|
13
|
+
vi.mock('@libs/cookies.js', () => ({ clearAuthCookies: vi.fn(), setAuthCookies: vi.fn() }));
|
|
14
|
+
vi.mock('../auth.service.js', () => ({ refresh: vi.fn(), REFRESH_TOKEN_ROTATED: 'REFRESH_TOKEN_ROTATED' }));
|
|
15
|
+
|
|
16
|
+
const request = { cookies: { refresh_token: 'rt' } } as unknown as FastifyRequest;
|
|
17
|
+
const reply = { send: vi.fn() } as unknown as FastifyReply;
|
|
18
|
+
|
|
19
|
+
describe('auth.controller refresh', () => {
|
|
20
|
+
beforeEach(() => vi.clearAllMocks());
|
|
21
|
+
|
|
22
|
+
it('keeps the cookies when the refresh lost a race with a parallel one', async () => {
|
|
23
|
+
vi.mocked(authService.refresh).mockRejectedValue(new UnauthorizedError('lost race', 'REFRESH_TOKEN_ROTATED'));
|
|
24
|
+
await expect(refresh(request, reply)).rejects.toMatchObject({ code: 'REFRESH_TOKEN_ROTATED' });
|
|
25
|
+
expect(clearAuthCookies).not.toHaveBeenCalled();
|
|
26
|
+
});
|
|
27
|
+
|
|
28
|
+
it('still clears the cookies when the session is dead', async () => {
|
|
29
|
+
vi.mocked(authService.refresh).mockRejectedValue(new UnauthorizedError('gone', 'INVALID_REFRESH_TOKEN'));
|
|
30
|
+
await expect(refresh(request, reply)).rejects.toMatchObject({ code: 'INVALID_REFRESH_TOKEN' });
|
|
31
|
+
expect(clearAuthCookies).toHaveBeenCalledWith(reply);
|
|
32
|
+
});
|
|
33
|
+
|
|
34
|
+
it('sets the new cookies on success', async () => {
|
|
35
|
+
vi.mocked(authService.refresh).mockResolvedValue({ accessToken: 'a', refreshToken: 'r' });
|
|
36
|
+
await refresh(request, reply);
|
|
37
|
+
expect(setAuthCookies).toHaveBeenCalledWith(reply, 'a', 'r');
|
|
38
|
+
});
|
|
39
|
+
});
|
|
@@ -70,7 +70,7 @@ describe('auth money-path (real containers)', () => {
|
|
|
70
70
|
expect(body.data.user.password).toBeUndefined();
|
|
71
71
|
});
|
|
72
72
|
|
|
73
|
-
it('POST /api/v1/auth/register with an INVALID body is rejected (
|
|
73
|
+
it('POST /api/v1/auth/register with an INVALID body is rejected (422 VALIDATION_FAILED + fields)', async () => {
|
|
74
74
|
const res = await app.inject({
|
|
75
75
|
method: 'POST',
|
|
76
76
|
url: '/api/v1/auth/register',
|
|
@@ -78,8 +78,14 @@ describe('auth money-path (real containers)', () => {
|
|
|
78
78
|
});
|
|
79
79
|
|
|
80
80
|
// fastify-type-provider-zod surfaces body validation as a Fastify
|
|
81
|
-
// validation error →
|
|
82
|
-
expect(res.statusCode).toBe(
|
|
81
|
+
// validation error → libs/error-handler.ts answers 422 with the field list.
|
|
82
|
+
expect(res.statusCode).toBe(422);
|
|
83
|
+
const body = res.json();
|
|
84
|
+
expect(body.error.code).toBe('VALIDATION_FAILED');
|
|
85
|
+
expect(body.error.fields.map((f: { field: string }) => f.field)).toEqual(
|
|
86
|
+
expect.arrayContaining(['email', 'password']),
|
|
87
|
+
);
|
|
88
|
+
expect(res.body).not.toContain('not-an-email');
|
|
83
89
|
});
|
|
84
90
|
|
|
85
91
|
it('POST /api/v1/auth/login with valid credentials succeeds and sets an access_token cookie', async () => {
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { describe, it, expect, vi } from 'vitest';
|
|
2
|
+
import * as authRepo from '../auth.repo.js';
|
|
3
|
+
import { hashPassword, verifyPassword } from '@libs/password.js';
|
|
4
|
+
import { login } from '../auth.service.js';
|
|
5
|
+
|
|
6
|
+
// Own file: the dummy hash is cached at module level, and this test needs that cache empty.
|
|
7
|
+
vi.mock('../auth.repo.js');
|
|
8
|
+
vi.mock('@libs/auth.js');
|
|
9
|
+
vi.mock('@libs/password.js');
|
|
10
|
+
vi.mock('../session.repo.js');
|
|
11
|
+
|
|
12
|
+
const mockRedis = vi.hoisted(() => ({
|
|
13
|
+
ttl: vi.fn().mockResolvedValue(-2),
|
|
14
|
+
incr: vi.fn().mockResolvedValue(1),
|
|
15
|
+
expire: vi.fn().mockResolvedValue(1),
|
|
16
|
+
set: vi.fn(),
|
|
17
|
+
del: vi.fn(),
|
|
18
|
+
}));
|
|
19
|
+
vi.mock('@libs/redis.js', () => ({ getRedis: (): typeof mockRedis => mockRedis }));
|
|
20
|
+
|
|
21
|
+
describe('login — dummy hash for unknown emails', () => {
|
|
22
|
+
it('does not cache a failed dummy hash (a lasting 500 would reveal which emails are unknown)', async () => {
|
|
23
|
+
vi.mocked(authRepo.findUserByEmail).mockResolvedValue(null);
|
|
24
|
+
vi.mocked(verifyPassword).mockResolvedValue(false);
|
|
25
|
+
vi.mocked(hashPassword).mockRejectedValueOnce(new Error('argon2 unavailable')).mockResolvedValue('dummy-hash');
|
|
26
|
+
const input = { email: 'nobody@example.com', password: 'Wrong-Passw0rd!' };
|
|
27
|
+
|
|
28
|
+
await expect(login(input)).rejects.toThrow('argon2 unavailable');
|
|
29
|
+
// The next attempt computes the hash again and answers like any wrong password.
|
|
30
|
+
await expect(login(input)).rejects.toMatchObject({ code: 'INVALID_CREDENTIALS' });
|
|
31
|
+
expect(hashPassword).toHaveBeenCalledTimes(2);
|
|
32
|
+
expect(verifyPassword).toHaveBeenCalledWith(input.password, 'dummy-hash');
|
|
33
|
+
});
|
|
34
|
+
});
|