create-tigra 4.1.0 → 5.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 +20 -0
- package/README.md +4 -1
- package/bin/create-tigra.js +68 -73
- package/lib/installer-transaction.js +275 -0
- package/lib/patchers/diagnostics.patcher.js +33 -59
- package/lib/patchers/email-verification.patcher.js +86 -92
- package/lib/patchers/metrics.patcher.js +18 -18
- package/lib/project-files.js +99 -0
- package/modules/diagnostics/diagnostics.md +10 -0
- package/modules/diagnostics/prisma/diagnostic-hourly-view.sql +24 -0
- package/modules/diagnostics/prisma/migration.sql +1 -24
- package/modules/diagnostics/server/__tests__/diagnostics.integration.test.ts +18 -2
- package/modules/diagnostics/server/diagnostics.repo.ts +12 -2
- package/modules/diagnostics/server/diagnostics.routes.ts +1 -2
- package/modules/email-verification/client/hooks/useVerification.ts +4 -7
- package/modules/email-verification/server/__tests__/verification.integration.test.ts +17 -0
- package/modules/email-verification/server/__tests__/verification.service.test.ts +71 -0
- package/modules/email-verification/server/verification.service.ts +102 -157
- package/modules/metrics/client/WebVitalsReporter.tsx +2 -0
- package/modules/metrics/client/__tests__/WebVitalsReporter.test.ts +1 -0
- package/modules/metrics/performance.md +2 -2
- package/modules/metrics/server/__tests__/metrics.collector.test.ts +22 -0
- package/modules/metrics/server/metrics.collector.ts +6 -3
- package/modules/metrics/server/metrics.routes.ts +1 -2
- package/modules/metrics/server/metrics.service.ts +6 -2
- package/package.json +1 -1
- package/template/AGENTS.md +4 -3
- package/template/client/.dockerignore +2 -5
- package/template/client/gitignore +43 -0
- package/template/client/package-lock.json +51 -51
- package/template/client/package.json +2 -2
- package/template/client/src/features/auth/components/AuthInitializer.tsx +45 -7
- package/template/client/src/features/auth/hooks/useAuth.ts +10 -33
- package/template/client/src/features/auth/hooks/useCurrentUser.ts +3 -3
- package/template/client/src/features/auth/hooks/useSessionTransition.ts +51 -0
- package/template/client/src/features/auth/services/auth.service.ts +3 -2
- package/template/client/src/features/auth/store/authSlice.ts +11 -8
- package/template/client/src/features/auth/types/auth.types.ts +1 -0
- package/template/client/src/lib/api/__tests__/axios.config.test.ts +17 -0
- package/template/client/src/lib/api/__tests__/session-events.test.ts +23 -0
- package/template/client/src/lib/api/axios.config.ts +24 -6
- package/template/client/src/lib/api/session-events.ts +54 -0
- package/template/client/src/lib/observability/sentry-scrub.ts +63 -46
- package/template/client/src/store/__tests__/store.test.ts +1 -0
- package/template/gitignore +3 -2
- package/template/server/.dockerignore +2 -5
- package/template/server/.env.example +1 -0
- package/template/server/.env.example.production +1 -0
- package/template/server/README.md +7 -2
- package/template/server/docs/deployment.md +66 -0
- package/template/server/docs/logging.md +9 -8
- package/template/server/docs/rate-limits.md +6 -4
- package/template/server/gitignore +33 -0
- package/template/server/prisma/migrations/0_init/migration.sql +25 -0
- package/template/server/prisma/retrofits/20261116000000_retired_refresh_tokens/migration.sql +13 -0
- package/template/server/prisma/retrofits/20261116000100_avatar_cleanup/migration.sql +9 -0
- package/template/server/prisma/retrofits/20261117000000_account_purge/migration.sql +1 -0
- package/template/server/prisma/schema.prisma +25 -1
- package/template/server/src/__tests__/routes.integration.test.ts +5 -2
- package/template/server/src/app.ts +14 -5
- package/template/server/src/config/env.ts +8 -0
- package/template/server/src/config/rate-limit.config.ts +1 -1
- package/template/server/src/jobs/__tests__/cleanup-deleted-accounts.job.test.ts +26 -9
- package/template/server/src/jobs/__tests__/cleanup-expired-auth.job.test.ts +2 -1
- package/template/server/src/jobs/__tests__/jobs.integration.test.ts +51 -5
- package/template/server/src/jobs/cleanup-deleted-accounts.job.ts +30 -34
- package/template/server/src/jobs/cleanup-expired-auth.job.ts +2 -0
- package/template/server/src/jobs/index.ts +8 -2
- package/template/server/src/libs/__tests__/auth.test.ts +1 -1
- package/template/server/src/libs/__tests__/cookies.test.ts +16 -0
- package/template/server/src/libs/__tests__/error-handler.test.ts +20 -1
- package/template/server/src/libs/__tests__/http.test.ts +10 -10
- package/template/server/src/libs/__tests__/ip-block.test.ts +39 -7
- package/template/server/src/libs/__tests__/logger.test.ts +10 -1
- package/template/server/src/libs/__tests__/monitoring.test.ts +19 -0
- package/template/server/src/libs/__tests__/outbound.integration.test.ts +7 -10
- package/template/server/src/libs/__tests__/rate-limits.integration.test.ts +32 -3
- package/template/server/src/libs/__tests__/requestLogger.test.ts +9 -1
- package/template/server/src/libs/__tests__/safe-http.test.ts +65 -3
- package/template/server/src/libs/__tests__/sentry-scrub.test.ts +22 -6
- package/template/server/src/libs/__tests__/url-safety.test.ts +3 -1
- package/template/server/src/libs/account-mutation.ts +77 -0
- package/template/server/src/libs/auth.ts +37 -3
- package/template/server/src/libs/cookies.ts +25 -13
- package/template/server/src/libs/email-quota.ts +11 -7
- package/template/server/src/libs/email.ts +11 -8
- package/template/server/src/libs/error-handler.ts +16 -12
- package/template/server/src/libs/http.ts +37 -13
- package/template/server/src/libs/ip-block.ts +56 -34
- package/template/server/src/libs/logger.ts +23 -8
- package/template/server/src/libs/monitoring.ts +57 -31
- package/template/server/src/libs/observability/sentry.ts +65 -49
- package/template/server/src/libs/prisma.ts +1 -1
- package/template/server/src/libs/private-cache.ts +6 -0
- package/template/server/src/libs/rate-limiting.ts +4 -0
- package/template/server/src/libs/requestLogger.ts +3 -3
- package/template/server/src/libs/safe-http.ts +58 -18
- package/template/server/src/libs/storage/__tests__/upload-persistence.test.ts +15 -2
- package/template/server/src/libs/storage/file-storage.service.ts +59 -109
- package/template/server/src/libs/storage/file-validator.ts +2 -1
- package/template/server/src/libs/url-safety.ts +10 -2
- package/template/server/src/libs/validation-errors.ts +11 -8
- package/template/server/src/modules/admin/__tests__/admin.repo.test.ts +21 -4
- package/template/server/src/modules/admin/__tests__/admin.schemas.test.ts +11 -0
- package/template/server/src/modules/admin/__tests__/admin.service.test.ts +83 -40
- package/template/server/src/modules/admin/admin.controller.ts +4 -4
- package/template/server/src/modules/admin/admin.repo.ts +37 -54
- package/template/server/src/modules/admin/admin.routes.ts +3 -5
- package/template/server/src/modules/admin/admin.schemas.ts +3 -6
- package/template/server/src/modules/admin/admin.service.ts +61 -62
- package/template/server/src/modules/auth/__tests__/auth.schemas.test.ts +12 -0
- package/template/server/src/modules/auth/__tests__/auth.service.test.ts +58 -295
- package/template/server/src/modules/auth/__tests__/recovery.integration.test.ts +177 -0
- package/template/server/src/modules/auth/__tests__/recovery.queue.test.ts +159 -0
- package/template/server/src/modules/auth/__tests__/session-cleanup.test.ts +5 -10
- package/template/server/src/modules/auth/__tests__/sessions.integration.test.ts +1 -1
- package/template/server/src/modules/auth/__tests__/token-fingerprints.test.ts +115 -44
- package/template/server/src/modules/auth/auth-link-store.ts +64 -0
- package/template/server/src/modules/auth/auth-mail-queue.ts +124 -0
- package/template/server/src/modules/auth/auth.controller.ts +16 -5
- package/template/server/src/modules/auth/auth.repo.ts +152 -61
- package/template/server/src/modules/auth/auth.routes.ts +4 -0
- package/template/server/src/modules/auth/auth.schemas.ts +7 -3
- package/template/server/src/modules/auth/auth.service.ts +33 -237
- package/template/server/src/modules/auth/recovery.queue.ts +44 -0
- package/template/server/src/modules/auth/recovery.store.ts +7 -0
- package/template/server/src/modules/auth/session.repo.ts +5 -4
- package/template/server/src/modules/files/__tests__/files.integration.test.ts +29 -1
- package/template/server/src/modules/files/files.controller.ts +2 -2
- package/template/server/src/modules/users/__tests__/avatar-cleanup.test.ts +49 -0
- package/template/server/src/modules/users/__tests__/avatar-controller.test.ts +50 -0
- package/template/server/src/modules/users/__tests__/avatar-upload.test.ts +56 -105
- package/template/server/src/modules/users/__tests__/users.integration.test.ts +2 -2
- package/template/server/src/modules/users/__tests__/users.repo.test.ts +8 -11
- package/template/server/src/modules/users/__tests__/users.service.test.ts +116 -44
- package/template/server/src/modules/users/avatar-cleanup.ts +70 -0
- package/template/server/src/modules/users/users.controller.ts +28 -25
- package/template/server/src/modules/users/users.repo.ts +12 -51
- package/template/server/src/modules/users/users.service.ts +109 -234
- package/template/server/src/shared/responses/paginatedResponse.ts +4 -1
- package/template/server/src/shared/schemas/pagination.schema.ts +5 -1
- package/template/server/src/test/setup.ts +4 -0
|
@@ -124,7 +124,7 @@ export async function updateUserStatus(
|
|
|
124
124
|
const user = await adminService.toggleUserStatus(
|
|
125
125
|
paramsParsed.userId,
|
|
126
126
|
bodyParsed.isActive,
|
|
127
|
-
request.user
|
|
127
|
+
request.user,
|
|
128
128
|
);
|
|
129
129
|
|
|
130
130
|
const action = bodyParsed.isActive ? 'activated' : 'deactivated';
|
|
@@ -136,7 +136,7 @@ export async function restoreUser(
|
|
|
136
136
|
reply: FastifyReply,
|
|
137
137
|
): Promise<void> {
|
|
138
138
|
const parsed = parseInput(userIdParamsSchema, request.params);
|
|
139
|
-
const user = await adminService.restoreUser(parsed.userId);
|
|
139
|
+
const user = await adminService.restoreUser(parsed.userId, request.user);
|
|
140
140
|
reply.send(successResponse('User restored successfully', user));
|
|
141
141
|
}
|
|
142
142
|
|
|
@@ -151,7 +151,7 @@ export async function updateUserRole(
|
|
|
151
151
|
const user = await adminService.changeUserRole(
|
|
152
152
|
paramsParsed.userId,
|
|
153
153
|
bodyParsed.role,
|
|
154
|
-
request.user
|
|
154
|
+
request.user,
|
|
155
155
|
);
|
|
156
156
|
|
|
157
157
|
reply.send(successResponse('User role updated successfully', user));
|
|
@@ -177,6 +177,6 @@ export async function forceExpireSession(
|
|
|
177
177
|
): Promise<void> {
|
|
178
178
|
const parsed = parseInput(sessionIdParamsSchema, request.params);
|
|
179
179
|
|
|
180
|
-
await adminService.forceExpireSession(parsed.sessionId);
|
|
180
|
+
await adminService.forceExpireSession(parsed.sessionId, request.user);
|
|
181
181
|
reply.send(successResponse('Session expired successfully', null));
|
|
182
182
|
}
|
|
@@ -4,8 +4,10 @@
|
|
|
4
4
|
* Data access layer for admin-specific queries.
|
|
5
5
|
*/
|
|
6
6
|
|
|
7
|
-
import { prisma
|
|
7
|
+
import { prisma } from '@libs/prisma.js';
|
|
8
|
+
import type { Prisma } from '@prisma/client';
|
|
8
9
|
|
|
10
|
+
import { calculateOffset } from '@shared/schemas/pagination.schema.js';
|
|
9
11
|
import type { UserRole } from '@shared/types/index.js';
|
|
10
12
|
|
|
11
13
|
// ─── Select Shapes ──────────────────────────────────────────────────────────
|
|
@@ -98,18 +100,21 @@ class AdminRepository {
|
|
|
98
100
|
deleted?: boolean;
|
|
99
101
|
}): Promise<{ items: AdminUser[]; totalItems: number }> {
|
|
100
102
|
const { page, limit, search, role, isActive, sortBy, sortOrder, deleted = false } = params;
|
|
101
|
-
const offset = (page
|
|
103
|
+
const offset = calculateOffset(page, limit);
|
|
102
104
|
|
|
103
105
|
// Live accounts by default; `deleted` lists only soft-deleted ones instead.
|
|
104
|
-
const where:
|
|
106
|
+
const where: Prisma.UserWhereInput = {
|
|
105
107
|
deletedAt: deleted ? { not: null } : null,
|
|
106
108
|
};
|
|
107
109
|
|
|
108
110
|
if (search) {
|
|
111
|
+
// Prisma binds this as a value, but MySQL still interprets LIKE wildcards.
|
|
112
|
+
// Escape them so the search box always finds literal text.
|
|
113
|
+
const contains = search.replace(/[\\%_]/g, '\\$&');
|
|
109
114
|
where.OR = [
|
|
110
|
-
{ email: { contains
|
|
111
|
-
{ firstName: { contains
|
|
112
|
-
{ lastName: { contains
|
|
115
|
+
{ email: { contains } },
|
|
116
|
+
{ firstName: { contains } },
|
|
117
|
+
{ lastName: { contains } },
|
|
113
118
|
];
|
|
114
119
|
}
|
|
115
120
|
|
|
@@ -125,7 +130,7 @@ class AdminRepository {
|
|
|
125
130
|
prisma.user.findMany({
|
|
126
131
|
where,
|
|
127
132
|
select: adminUserSelect,
|
|
128
|
-
orderBy: { [sortBy]: sortOrder },
|
|
133
|
+
orderBy: [{ [sortBy]: sortOrder }, { id: 'asc' }],
|
|
129
134
|
skip: offset,
|
|
130
135
|
take: limit,
|
|
131
136
|
}),
|
|
@@ -139,8 +144,8 @@ class AdminRepository {
|
|
|
139
144
|
* Lightweight user lookup for write operations (existence + role check).
|
|
140
145
|
* Use getUserDetail() when you need session count and last login.
|
|
141
146
|
*/
|
|
142
|
-
async findUserById(userId: string): Promise<AdminUser | null> {
|
|
143
|
-
return
|
|
147
|
+
async findUserById(tx: Prisma.TransactionClient, userId: string): Promise<AdminUser | null> {
|
|
148
|
+
return tx.user.findUnique({
|
|
144
149
|
where: { id: userId, deletedAt: null },
|
|
145
150
|
select: adminUserSelect,
|
|
146
151
|
});
|
|
@@ -189,8 +194,8 @@ class AdminRepository {
|
|
|
189
194
|
* `approveEmail` also marks the email verified — used when an admin activates
|
|
190
195
|
* a user who never verified, i.e. the admin vouches for them.
|
|
191
196
|
*/
|
|
192
|
-
async updateUserStatus(userId: string, isActive: boolean, approveEmail = false): Promise<AdminUser> {
|
|
193
|
-
return
|
|
197
|
+
async updateUserStatus(tx: Prisma.TransactionClient, userId: string, isActive: boolean, approveEmail = false): Promise<AdminUser> {
|
|
198
|
+
return tx.user.update({
|
|
194
199
|
where: { id: userId },
|
|
195
200
|
data: approveEmail ? { isActive, emailVerifiedAt: new Date() } : { isActive },
|
|
196
201
|
select: adminUserSelect,
|
|
@@ -199,12 +204,12 @@ class AdminRepository {
|
|
|
199
204
|
|
|
200
205
|
/**
|
|
201
206
|
* Undo a soft delete: one conditional update, so only a deleted account
|
|
202
|
-
* changes.
|
|
203
|
-
* the
|
|
207
|
+
* changes. A committed purge claim makes restoration ineligible before
|
|
208
|
+
* the worker touches any retained files.
|
|
204
209
|
*/
|
|
205
|
-
async restoreUser(userId: string): Promise<boolean> {
|
|
206
|
-
const { count } = await
|
|
207
|
-
where: { id: userId, deletedAt: { not: null } },
|
|
210
|
+
async restoreUser(tx: Prisma.TransactionClient, userId: string): Promise<boolean> {
|
|
211
|
+
const { count } = await tx.user.updateMany({
|
|
212
|
+
where: { id: userId, deletedAt: { not: null }, purgeStartedAt: null },
|
|
208
213
|
data: { deletedAt: null, isActive: true },
|
|
209
214
|
});
|
|
210
215
|
return count === 1;
|
|
@@ -215,29 +220,30 @@ class AdminRepository {
|
|
|
215
220
|
* (so it can say "restore it first" instead of "no such account").
|
|
216
221
|
*/
|
|
217
222
|
async findAccountStateByEmail(
|
|
223
|
+
tx: Prisma.TransactionClient,
|
|
218
224
|
email: string,
|
|
219
225
|
): Promise<{ id: string; role: UserRole; isActive: boolean; deletedAt: Date | null; emailVerifiedAt: Date | null } | null> {
|
|
220
|
-
return
|
|
226
|
+
return tx.user.findUnique({
|
|
221
227
|
where: { email },
|
|
222
228
|
select: { id: true, role: true, isActive: true, deletedAt: true, emailVerifiedAt: true },
|
|
223
229
|
});
|
|
224
230
|
}
|
|
225
231
|
|
|
226
232
|
/** 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
|
|
233
|
+
async promoteToAdmin(tx: Prisma.TransactionClient, userId: string, emailVerifiedAt: Date): Promise<void> {
|
|
234
|
+
await tx.user.update({ where: { id: userId }, data: { role: 'ADMIN', emailVerifiedAt } });
|
|
229
235
|
}
|
|
230
236
|
|
|
231
|
-
/**
|
|
232
|
-
async
|
|
233
|
-
return
|
|
237
|
+
/** Distinguish an absent user from a claim that still has media to remove. */
|
|
238
|
+
async getPurgeState(tx: Prisma.TransactionClient, userId: string): Promise<{ purgeStartedAt: Date | null } | null> {
|
|
239
|
+
return tx.user.findUnique({ where: { id: userId }, select: { purgeStartedAt: true } });
|
|
234
240
|
}
|
|
235
241
|
|
|
236
242
|
/**
|
|
237
243
|
* Update user role
|
|
238
244
|
*/
|
|
239
|
-
async updateUserRole(userId: string, role: UserRole): Promise<AdminUser> {
|
|
240
|
-
return
|
|
245
|
+
async updateUserRole(tx: Prisma.TransactionClient, userId: string, role: UserRole): Promise<AdminUser> {
|
|
246
|
+
return tx.user.update({
|
|
241
247
|
where: { id: userId },
|
|
242
248
|
data: { role },
|
|
243
249
|
select: adminUserSelect,
|
|
@@ -274,10 +280,10 @@ class AdminRepository {
|
|
|
274
280
|
userId?: string;
|
|
275
281
|
}): Promise<{ items: AdminSession[]; totalItems: number }> {
|
|
276
282
|
const { page, limit, userId } = params;
|
|
277
|
-
const offset = (page
|
|
283
|
+
const offset = calculateOffset(page, limit);
|
|
278
284
|
const now = new Date();
|
|
279
285
|
|
|
280
|
-
const where:
|
|
286
|
+
const where: Prisma.SessionWhereInput = {
|
|
281
287
|
expiresAt: { gt: now },
|
|
282
288
|
};
|
|
283
289
|
|
|
@@ -289,7 +295,7 @@ class AdminRepository {
|
|
|
289
295
|
prisma.session.findMany({
|
|
290
296
|
where,
|
|
291
297
|
include: { user: { select: sessionUserSelect } },
|
|
292
|
-
orderBy: { lastActiveAt: 'desc' },
|
|
298
|
+
orderBy: [{ lastActiveAt: 'desc' }, { id: 'asc' }],
|
|
293
299
|
skip: offset,
|
|
294
300
|
take: limit,
|
|
295
301
|
}),
|
|
@@ -299,33 +305,10 @@ class AdminRepository {
|
|
|
299
305
|
return { items, totalItems };
|
|
300
306
|
}
|
|
301
307
|
|
|
302
|
-
/**
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
return prisma.session.findUnique({
|
|
307
|
-
where: { id: sessionId },
|
|
308
|
-
include: { user: { select: sessionUserSelect } },
|
|
309
|
-
});
|
|
310
|
-
}
|
|
311
|
-
|
|
312
|
-
/**
|
|
313
|
-
* Delete a session (no-op if already deleted)
|
|
314
|
-
*/
|
|
315
|
-
async deleteSession(sessionId: string): Promise<void> {
|
|
316
|
-
try {
|
|
317
|
-
await prisma.session.delete({ where: { id: sessionId } });
|
|
318
|
-
} catch (error) {
|
|
319
|
-
if (isPrismaNotFound(error)) return;
|
|
320
|
-
throw error;
|
|
321
|
-
}
|
|
322
|
-
}
|
|
323
|
-
|
|
324
|
-
/**
|
|
325
|
-
* Delete refresh tokens linked to a specific session
|
|
326
|
-
*/
|
|
327
|
-
async deleteRefreshTokensBySessionId(sessionId: string): Promise<void> {
|
|
328
|
-
await prisma.refreshToken.deleteMany({ where: { sessionId } });
|
|
308
|
+
/** The row count decides success, and the foreign key revokes its refresh tokens. */
|
|
309
|
+
async deleteLiveSession(tx: Prisma.TransactionClient, sessionId: string): Promise<boolean> {
|
|
310
|
+
const { count } = await tx.session.deleteMany({ where: { id: sessionId, expiresAt: { gt: new Date() } } });
|
|
311
|
+
return count === 1;
|
|
329
312
|
}
|
|
330
313
|
}
|
|
331
314
|
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { FastifyInstance } from 'fastify';
|
|
2
|
-
import {
|
|
2
|
+
import { registerAdminAuthorization } from '@libs/auth.js';
|
|
3
3
|
import { RATE_LIMITS } from '@config/rate-limit.config.js';
|
|
4
4
|
import * as adminController from './admin.controller.js';
|
|
5
5
|
import {
|
|
@@ -14,9 +14,7 @@ import {
|
|
|
14
14
|
} from './admin.schemas.js';
|
|
15
15
|
|
|
16
16
|
export async function adminRoutes(fastify: FastifyInstance): Promise<void> {
|
|
17
|
-
|
|
18
|
-
fastify.addHook('preValidation', authenticate);
|
|
19
|
-
fastify.addHook('preValidation', authorize('ADMIN'));
|
|
17
|
+
registerAdminAuthorization(fastify);
|
|
20
18
|
|
|
21
19
|
// ─── IP Blocking ────────────────────────────────────────────────────────
|
|
22
20
|
|
|
@@ -151,7 +149,7 @@ export async function adminRoutes(fastify: FastifyInstance): Promise<void> {
|
|
|
151
149
|
*
|
|
152
150
|
* POST /api/v1/admin/users/:userId/restore
|
|
153
151
|
* Auth: Required (ADMIN)
|
|
154
|
-
* 200 with the user
|
|
152
|
+
* 200 with the user, 404 if gone, or 409 if already restored or claimed for purge.
|
|
155
153
|
*/
|
|
156
154
|
fastify.post('/admin/users/:userId/restore', {
|
|
157
155
|
schema: { params: userIdParamsSchema },
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { z } from 'zod';
|
|
2
|
+
import { PaginationSchema } from '@shared/schemas/pagination.schema.js';
|
|
2
3
|
|
|
3
4
|
// ─── IP Blocking ────────────────────────────────────────────────────────────
|
|
4
5
|
|
|
@@ -29,9 +30,7 @@ export type UnblockIpParams = z.infer<typeof unblockIpParamsSchema>;
|
|
|
29
30
|
*/
|
|
30
31
|
const booleanQuery = z.union([z.boolean(), z.enum(['true', 'false']).transform((v) => v === 'true')]);
|
|
31
32
|
|
|
32
|
-
export const getUsersQuerySchema =
|
|
33
|
-
page: z.coerce.number().int().min(1).default(1),
|
|
34
|
-
limit: z.coerce.number().int().min(1).max(100).default(10),
|
|
33
|
+
export const getUsersQuerySchema = PaginationSchema.extend({
|
|
35
34
|
search: z.string().max(100).optional(),
|
|
36
35
|
role: z.enum(['USER', 'ADMIN']).optional(),
|
|
37
36
|
isActive: booleanQuery.optional(),
|
|
@@ -60,9 +59,7 @@ export type UpdateUserRoleInput = z.infer<typeof updateUserRoleSchema>;
|
|
|
60
59
|
|
|
61
60
|
// ─── Session Management ─────────────────────────────────────────────────────
|
|
62
61
|
|
|
63
|
-
export const getSessionsQuerySchema =
|
|
64
|
-
page: z.coerce.number().int().min(1).default(1),
|
|
65
|
-
limit: z.coerce.number().int().min(1).max(100).default(10),
|
|
62
|
+
export const getSessionsQuerySchema = PaginationSchema.extend({
|
|
66
63
|
userId: z.string().uuid('Invalid user ID').optional(),
|
|
67
64
|
});
|
|
68
65
|
|
|
@@ -6,10 +6,12 @@
|
|
|
6
6
|
|
|
7
7
|
import { logger } from '@libs/logger.js';
|
|
8
8
|
import { NotFoundError, ForbiddenError, ConflictError } from '@shared/errors/errors.js';
|
|
9
|
-
import {
|
|
9
|
+
import { RETENTION_MS } from '@/jobs/cleanup-deleted-accounts.job.js';
|
|
10
10
|
import { adminRepository } from './admin.repo.js';
|
|
11
|
-
import {
|
|
12
|
-
|
|
11
|
+
import {
|
|
12
|
+
assertAnotherSignInAdmin, assertMutationActor, revokeAccountCredentials, runAccountMutation,
|
|
13
|
+
type MutationActor,
|
|
14
|
+
} from '@libs/account-mutation.js';
|
|
13
15
|
|
|
14
16
|
import type { UserRole } from '@shared/types/index.js';
|
|
15
17
|
import type { AdminUser, AdminUserDetail, AdminSession, DashboardStats } from './admin.repo.js';
|
|
@@ -35,7 +37,7 @@ class AdminService {
|
|
|
35
37
|
...result,
|
|
36
38
|
items: result.items.map((user) => ({
|
|
37
39
|
...user,
|
|
38
|
-
purgeAt: new Date(user.deletedAt!.getTime() +
|
|
40
|
+
purgeAt: new Date(user.deletedAt!.getTime() + RETENTION_MS),
|
|
39
41
|
})),
|
|
40
42
|
};
|
|
41
43
|
}
|
|
@@ -49,17 +51,25 @@ class AdminService {
|
|
|
49
51
|
*
|
|
50
52
|
* @throws NotFoundError 404 USER_NOT_FOUND if the account does not exist (or was purged)
|
|
51
53
|
* @throws ConflictError 409 USER_NOT_DELETED if the account is not deleted
|
|
54
|
+
* @throws ConflictError 409 USER_PURGE_IN_PROGRESS once a purge has claimed the account
|
|
52
55
|
*/
|
|
53
|
-
async restoreUser(userId: string): Promise<AdminUser> {
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
56
|
+
async restoreUser(userId: string, actor: MutationActor): Promise<AdminUser> {
|
|
57
|
+
const user = await runAccountMutation(async tx => {
|
|
58
|
+
await assertMutationActor(tx, actor, 'ADMIN');
|
|
59
|
+
if (!(await adminRepository.restoreUser(tx, userId))) {
|
|
60
|
+
const state = await adminRepository.getPurgeState(tx, userId);
|
|
61
|
+
if (!state) {
|
|
62
|
+
throw new NotFoundError('User not found', 'USER_NOT_FOUND');
|
|
63
|
+
}
|
|
64
|
+
if (state.purgeStartedAt) {
|
|
65
|
+
throw new ConflictError('Permanent deletion has already started for this account.', 'USER_PURGE_IN_PROGRESS');
|
|
66
|
+
}
|
|
67
|
+
throw new ConflictError('This account is not deleted', 'USER_NOT_DELETED');
|
|
57
68
|
}
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
if (!user) throw new NotFoundError('User not found', 'USER_NOT_FOUND');
|
|
69
|
+
const restored = await adminRepository.findUserById(tx, userId);
|
|
70
|
+
if (!restored) throw new NotFoundError('User not found', 'USER_NOT_FOUND');
|
|
71
|
+
return restored;
|
|
72
|
+
});
|
|
63
73
|
|
|
64
74
|
logger.info({ msg: 'Deleted account restored', userId });
|
|
65
75
|
return user;
|
|
@@ -87,25 +97,22 @@ class AdminService {
|
|
|
87
97
|
* An admin can never ban themselves (like changing their own role): it would
|
|
88
98
|
* end their own sessions and could leave the project with no admin at all.
|
|
89
99
|
*/
|
|
90
|
-
async toggleUserStatus(userId: string, isActive: boolean,
|
|
91
|
-
if (!isActive && userId ===
|
|
100
|
+
async toggleUserStatus(userId: string, isActive: boolean, actor: MutationActor): Promise<AdminUser> {
|
|
101
|
+
if (!isActive && userId === actor.userId) {
|
|
92
102
|
throw new ForbiddenError('You cannot ban your own account', 'CANNOT_BAN_SELF');
|
|
93
103
|
}
|
|
94
104
|
|
|
95
|
-
const
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
throw new NotFoundError('User not found');
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
105
|
+
const { updatedUser, deletedSessions } = await runAccountMutation(async tx => {
|
|
106
|
+
await assertMutationActor(tx, actor, 'ADMIN');
|
|
107
|
+
const user = await adminRepository.findUserById(tx, userId);
|
|
108
|
+
if (!user) throw new NotFoundError('User not found');
|
|
109
|
+
if (!isActive) await assertAnotherSignInAdmin(tx, user);
|
|
110
|
+
const updatedUser = await adminRepository.updateUserStatus(tx, userId, isActive, isActive && !user.emailVerifiedAt);
|
|
111
|
+
const deletedSessions = isActive ? 0 : await revokeAccountCredentials(tx, userId);
|
|
112
|
+
return { updatedUser, deletedSessions };
|
|
113
|
+
});
|
|
103
114
|
|
|
104
115
|
if (!isActive) {
|
|
105
|
-
// Force-logout: invalidate all sessions and refresh tokens
|
|
106
|
-
const deletedSessions = await sessionRepository.deleteAllUserSessions(userId);
|
|
107
|
-
await deleteRefreshTokensByUserId(userId);
|
|
108
|
-
|
|
109
116
|
logger.info({
|
|
110
117
|
msg: 'User deactivated and sessions invalidated',
|
|
111
118
|
userId,
|
|
@@ -125,25 +132,25 @@ class AdminService {
|
|
|
125
132
|
async changeUserRole(
|
|
126
133
|
userId: string,
|
|
127
134
|
role: UserRole,
|
|
128
|
-
|
|
135
|
+
actor: MutationActor,
|
|
129
136
|
): Promise<AdminUser> {
|
|
130
|
-
if (userId ===
|
|
137
|
+
if (userId === actor.userId) {
|
|
131
138
|
throw new ForbiddenError('Cannot change your own role');
|
|
132
139
|
}
|
|
133
140
|
|
|
134
|
-
const
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
throw new NotFoundError('User not found');
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
+
const { updatedUser, deletedSessions } = await runAccountMutation(async tx => {
|
|
142
|
+
await assertMutationActor(tx, actor, 'ADMIN');
|
|
143
|
+
const user = await adminRepository.findUserById(tx, userId);
|
|
144
|
+
if (!user) throw new NotFoundError('User not found');
|
|
145
|
+
const demotion = user.role === 'ADMIN' && role === 'USER';
|
|
146
|
+
if (demotion) await assertAnotherSignInAdmin(tx, user);
|
|
147
|
+
const updatedUser = await adminRepository.updateUserRole(tx, userId, role);
|
|
148
|
+
const deletedSessions = demotion ? await revokeAccountCredentials(tx, userId) : undefined;
|
|
149
|
+
return { updatedUser, deletedSessions };
|
|
150
|
+
});
|
|
141
151
|
|
|
142
152
|
// If demoting from ADMIN to USER, invalidate sessions so new role takes effect
|
|
143
|
-
if (
|
|
144
|
-
const deletedSessions = await sessionRepository.deleteAllUserSessions(userId);
|
|
145
|
-
await deleteRefreshTokensByUserId(userId);
|
|
146
|
-
|
|
153
|
+
if (deletedSessions !== undefined) {
|
|
147
154
|
logger.info({
|
|
148
155
|
msg: 'User demoted from ADMIN and sessions invalidated',
|
|
149
156
|
userId,
|
|
@@ -167,13 +174,15 @@ class AdminService {
|
|
|
167
174
|
*/
|
|
168
175
|
async promoteToAdmin(rawEmail: string): Promise<'promoted' | 'already-admin' | 'not-found' | 'deleted' | 'banned'> {
|
|
169
176
|
const email = rawEmail.trim().toLowerCase(); // register stores emails lower-cased
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
+
return runAccountMutation(async tx => {
|
|
178
|
+
const account = await adminRepository.findAccountStateByEmail(tx, email);
|
|
179
|
+
if (!account) return 'not-found';
|
|
180
|
+
if (account.deletedAt) return 'deleted';
|
|
181
|
+
if (!account.isActive) return 'banned';
|
|
182
|
+
if (account.role === 'ADMIN') return 'already-admin';
|
|
183
|
+
await adminRepository.promoteToAdmin(tx, account.id, account.emailVerifiedAt ?? new Date());
|
|
184
|
+
return 'promoted';
|
|
185
|
+
});
|
|
177
186
|
}
|
|
178
187
|
|
|
179
188
|
/**
|
|
@@ -198,22 +207,12 @@ class AdminService {
|
|
|
198
207
|
* Force-expire a specific session.
|
|
199
208
|
* Deletes the session and any associated refresh tokens.
|
|
200
209
|
*/
|
|
201
|
-
async forceExpireSession(sessionId: string): Promise<void> {
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
throw new NotFoundError('Session not found');
|
|
206
|
-
}
|
|
207
|
-
|
|
208
|
-
// Delete refresh tokens linked to this session first
|
|
209
|
-
await adminRepository.deleteRefreshTokensBySessionId(sessionId);
|
|
210
|
-
await adminRepository.deleteSession(sessionId);
|
|
211
|
-
|
|
212
|
-
logger.info({
|
|
213
|
-
msg: 'Session force-expired by admin',
|
|
214
|
-
sessionId,
|
|
215
|
-
userId: session.userId,
|
|
210
|
+
async forceExpireSession(sessionId: string, actor: MutationActor): Promise<void> {
|
|
211
|
+
await runAccountMutation(async tx => {
|
|
212
|
+
await assertMutationActor(tx, actor, 'ADMIN');
|
|
213
|
+
if (!await adminRepository.deleteLiveSession(tx, sessionId)) throw new NotFoundError('Session not found');
|
|
216
214
|
});
|
|
215
|
+
logger.info({ msg: 'Session force-expired by admin', sessionId, adminUserId: actor.userId });
|
|
217
216
|
}
|
|
218
217
|
}
|
|
219
218
|
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { describe, expect, it } from 'vitest';
|
|
2
|
+
import { loginSchema, registerSchema } from '../auth.schemas.js';
|
|
3
|
+
|
|
4
|
+
describe('account email validation', () => {
|
|
5
|
+
const credentials = { password: 'FixturePassword1', firstName: 'Test', lastName: 'User' };
|
|
6
|
+
const email = (lastLabelLength: number): string => `${'a'.repeat(60)}@${'b'.repeat(63)}.${'c'.repeat(lastLabelLength)}.test`;
|
|
7
|
+
|
|
8
|
+
it.each([registerSchema, loginSchema])('enforces the database length before lookup or persistence', (schema) => {
|
|
9
|
+
expect(schema.safeParse({ ...credentials, email: email(61) }).success).toBe(true);
|
|
10
|
+
expect(schema.safeParse({ ...credentials, email: email(62) }).success).toBe(false);
|
|
11
|
+
});
|
|
12
|
+
});
|