create-tigra 3.2.0 → 4.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +81 -12
- package/bin/create-tigra.js +495 -472
- package/lib/patchers/email-verification.patcher.js +160 -44
- package/modules/email-verification/client/hooks/useVerification.ts +4 -1
- package/modules/email-verification/server/__tests__/verification.integration.test.ts +115 -0
- package/modules/email-verification/server/verification.controller.ts +3 -1
- package/modules/email-verification/server/verification.service.ts +81 -21
- package/package.json +3 -2
- package/template/.github/dependabot.yml +47 -0
- package/template/.github/workflows/audit.yml +36 -0
- package/template/.github/workflows/ci.yml +79 -0
- package/template/AGENTS.md +18 -9
- package/template/client/.dockerignore +1 -0
- package/template/client/.env.example.production +13 -2
- package/template/client/AGENTS.md +13 -5
- package/template/client/Dockerfile +186 -14
- package/template/client/next.config.ts +1 -1
- package/template/client/package-lock.json +15983 -14181
- package/template/client/package.json +56 -48
- package/template/client/scripts/check-sharp.mjs +53 -0
- package/template/client/scripts/next-dev.cjs +5 -1
- package/template/client/src/__tests__/proxy.test.ts +92 -0
- package/template/client/src/app/healthz/route.ts +16 -0
- package/template/client/src/app/layout.tsx +9 -3
- package/template/client/src/app/page.tsx +2 -2
- package/template/client/src/app/providers.tsx +23 -4
- package/template/client/src/components/layout/Header.tsx +7 -3
- package/template/client/src/features/admin/hooks/useAdminSessions.ts +2 -1
- package/template/client/src/features/admin/hooks/useAdminUsers.ts +3 -1
- package/template/client/src/features/admin/types/admin.types.ts +2 -3
- package/template/client/src/features/auth/components/AuthInitializer.tsx +38 -19
- package/template/client/src/features/auth/components/ForgotPasswordForm.tsx +107 -0
- package/template/client/src/features/auth/components/LimitNotice.tsx +28 -0
- package/template/client/src/features/auth/components/LoginForm.tsx +18 -4
- package/template/client/src/features/auth/components/RegisterForm.tsx +23 -7
- package/template/client/src/features/auth/hooks/useAuth.ts +27 -7
- package/template/client/src/features/auth/hooks/usePasswordReset.ts +7 -1
- package/template/client/src/features/auth/services/auth.service.ts +8 -3
- package/template/client/src/features/auth/store/authSlice.ts +7 -2
- package/template/client/src/features/auth/types/auth.types.ts +3 -0
- package/template/client/src/instrumentation-client.ts +9 -1
- package/template/client/src/instrumentation.ts +6 -0
- package/template/client/src/lib/api/__tests__/axios.config.test.ts +183 -0
- package/template/client/src/lib/api/api.types.ts +14 -0
- package/template/client/src/lib/api/axios.config.ts +101 -15
- package/template/client/src/lib/api/hard-redirect.ts +8 -0
- package/template/client/src/lib/api/session-events.ts +29 -0
- package/template/client/src/lib/constants/routes.ts +12 -0
- package/template/client/src/lib/observability/sentry-scrub.ts +71 -0
- package/template/client/src/lib/utils/__tests__/error.test.ts +119 -0
- package/template/client/src/lib/utils/__tests__/form.test.ts +42 -0
- package/template/client/src/lib/utils/__tests__/paths.test.ts +43 -0
- package/template/client/src/lib/utils/__tests__/security.test.ts +40 -0
- package/template/client/src/lib/utils/__tests__/session-marker.test.ts +27 -0
- package/template/client/src/lib/utils/error.ts +86 -1
- package/template/client/src/lib/utils/form.ts +31 -0
- package/template/client/src/lib/utils/paths.ts +18 -0
- package/template/client/src/lib/utils/security.ts +37 -0
- package/template/client/src/lib/utils/session-marker.ts +24 -0
- package/template/client/src/{middleware.ts → proxy.ts} +25 -11
- package/template/client/src/store/__tests__/store.test.ts +44 -0
- package/template/client/src/store/index.ts +26 -8
- package/template/client/vitest.config.mts +48 -0
- package/template/server/.env.example +280 -269
- package/template/server/.env.example.production +283 -236
- package/template/server/AGENTS.md +13 -4
- package/template/server/Dockerfile +181 -14
- package/template/server/docker-compose.yml +4 -2
- package/template/server/docs/deployment.md +63 -0
- package/template/server/docs/logging.md +52 -4
- package/template/server/docs/rate-limits.md +153 -0
- package/template/server/docs/testing.md +63 -0
- package/template/server/eslint.config.mjs +19 -0
- package/template/server/package-lock.json +8784 -8743
- package/template/server/package.json +79 -75
- package/template/server/prisma/migrations/0_init/migration.sql +82 -0
- package/template/server/prisma/migrations/migration_lock.toml +3 -0
- package/template/server/prisma/schema.prisma +19 -6
- package/template/server/prisma/seed.ts +13 -5
- package/template/server/scripts/check-heic.mjs +40 -0
- package/template/server/scripts/check-sharp.mjs +53 -0
- package/template/server/src/__tests__/routes.integration.test.ts +280 -0
- package/template/server/src/app.ts +248 -335
- package/template/server/src/config/__tests__/env.test.ts +219 -0
- package/template/server/src/config/__tests__/rate-limit.config.test.ts +158 -0
- package/template/server/src/config/env.ts +326 -171
- package/template/server/src/config/rate-limit.config.ts +157 -106
- package/template/server/src/jobs/__tests__/cleanup-deleted-accounts.job.test.ts +110 -0
- package/template/server/src/jobs/__tests__/cleanup-expired-auth.job.test.ts +44 -0
- package/template/server/src/jobs/__tests__/jobs.integration.test.ts +88 -0
- package/template/server/src/jobs/__tests__/schedule.test.ts +92 -0
- package/template/server/src/jobs/cleanup-deleted-accounts.job.ts +81 -65
- package/template/server/src/jobs/cleanup-expired-auth.job.ts +32 -24
- package/template/server/src/jobs/index.ts +12 -2
- package/template/server/src/jobs/refresh-cloudflare-ranges.job.ts +28 -0
- package/template/server/src/jobs/schedule.ts +50 -0
- package/template/server/src/libs/__tests__/auth.test.ts +168 -0
- package/template/server/src/libs/__tests__/client-ip.test.ts +257 -121
- package/template/server/src/libs/__tests__/cloudflare-ranges.test.ts +79 -0
- package/template/server/src/libs/__tests__/cookies.test.ts +113 -0
- package/template/server/src/libs/__tests__/email-quota.test.ts +81 -0
- package/template/server/src/libs/__tests__/email.test.ts +68 -0
- package/template/server/src/libs/__tests__/error-handler.test.ts +162 -0
- package/template/server/src/libs/__tests__/health-db-down.integration.test.ts +37 -0
- package/template/server/src/libs/__tests__/health-redis-down.integration.test.ts +45 -0
- package/template/server/src/libs/__tests__/health-routes.test.ts +83 -0
- package/template/server/src/libs/__tests__/health.integration.test.ts +118 -0
- package/template/server/src/libs/__tests__/http.test.ts +74 -2
- package/template/server/src/libs/__tests__/ip-block.test.ts +179 -62
- package/template/server/src/libs/__tests__/logger.test.ts +50 -0
- package/template/server/src/libs/__tests__/monitoring.test.ts +185 -0
- package/template/server/src/libs/__tests__/outbound.integration.test.ts +48 -0
- package/template/server/src/libs/__tests__/prisma-client.test.ts +28 -0
- package/template/server/src/libs/__tests__/query-counter.integration.test.ts +53 -0
- package/template/server/src/libs/__tests__/rate-limiting.test.ts +146 -0
- package/template/server/src/libs/__tests__/rate-limits.integration.test.ts +53 -0
- package/template/server/src/libs/__tests__/redis-required.test.ts +30 -0
- package/template/server/src/libs/__tests__/redis.test.ts +59 -0
- package/template/server/src/libs/__tests__/request-id.test.ts +25 -0
- package/template/server/src/libs/__tests__/requestLogger.test.ts +126 -0
- package/template/server/src/libs/__tests__/safe-http.test.ts +138 -0
- package/template/server/src/libs/__tests__/sentry-scrub.test.ts +82 -0
- package/template/server/src/libs/__tests__/shutdown.test.ts +89 -0
- package/template/server/src/libs/__tests__/url-safety.test.ts +130 -80
- package/template/server/src/libs/account-status.ts +52 -0
- package/template/server/src/libs/auth.ts +51 -12
- package/template/server/src/libs/client-ip.ts +158 -77
- package/template/server/src/libs/cloudflare-ranges.ts +132 -0
- package/template/server/src/libs/cookies.ts +91 -24
- package/template/server/src/libs/email-quota.ts +74 -0
- package/template/server/src/libs/email.ts +46 -9
- package/template/server/src/libs/error-handler.ts +111 -0
- package/template/server/src/libs/health-routes.ts +53 -0
- package/template/server/src/libs/http.ts +139 -47
- package/template/server/src/libs/ip-address.ts +37 -0
- package/template/server/src/libs/ip-block.ts +284 -220
- package/template/server/src/libs/logger.ts +41 -12
- package/template/server/src/libs/monitoring.ts +131 -42
- package/template/server/src/libs/observability/sentry.ts +80 -0
- package/template/server/src/libs/origin-check.ts +9 -7
- package/template/server/src/libs/prisma.ts +47 -4
- package/template/server/src/libs/query-counter.ts +71 -59
- package/template/server/src/libs/rate-limiting.ts +110 -0
- package/template/server/src/libs/redis-required.ts +28 -0
- package/template/server/src/libs/redis.ts +108 -18
- package/template/server/src/libs/request-id.ts +18 -0
- package/template/server/src/libs/requestLogger.ts +112 -17
- package/template/server/src/libs/safe-http.ts +101 -0
- package/template/server/src/libs/shutdown.ts +87 -0
- package/template/server/src/libs/storage/__tests__/fixtures/tiny-heic.ts +13 -0
- package/template/server/src/libs/storage/__tests__/image-optimizer.test.ts +143 -0
- package/template/server/src/libs/storage/__tests__/multipart-limits.test.ts +91 -0
- package/template/server/src/libs/storage/__tests__/upload-persistence.test.ts +52 -0
- package/template/server/src/libs/storage/file-storage.service.ts +104 -83
- package/template/server/src/libs/storage/file-validator.ts +48 -46
- package/template/server/src/libs/storage/image-optimizer.service.ts +78 -72
- package/template/server/src/libs/token-hash.ts +18 -0
- package/template/server/src/libs/url-safety.ts +127 -121
- package/template/server/src/libs/validation-errors.ts +86 -0
- package/template/server/src/modules/admin/__tests__/admin-actions.integration.test.ts +255 -0
- package/template/server/src/modules/admin/__tests__/admin.health.test.ts +82 -0
- package/template/server/src/modules/admin/__tests__/admin.repo.test.ts +55 -0
- package/template/server/src/modules/admin/__tests__/admin.schemas.test.ts +38 -0
- package/template/server/src/modules/admin/__tests__/admin.service.test.ts +162 -0
- package/template/server/src/modules/admin/admin.controller.ts +66 -49
- package/template/server/src/modules/admin/admin.repo.ts +56 -13
- package/template/server/src/modules/admin/admin.routes.ts +48 -2
- package/template/server/src/modules/admin/admin.schemas.ts +18 -6
- package/template/server/src/modules/admin/admin.service.ts +73 -7
- package/template/server/src/modules/auth/__tests__/auth.controller.test.ts +39 -0
- package/template/server/src/modules/auth/__tests__/auth.integration.test.ts +9 -3
- package/template/server/src/modules/auth/__tests__/auth.service.dummy-hash.test.ts +34 -0
- package/template/server/src/modules/auth/__tests__/auth.service.test.ts +332 -49
- package/template/server/src/modules/auth/__tests__/session-cleanup.test.ts +39 -0
- package/template/server/src/modules/auth/__tests__/sessions.integration.test.ts +246 -0
- package/template/server/src/modules/auth/__tests__/token-fingerprints.test.ts +119 -0
- package/template/server/src/modules/auth/auth.controller.ts +133 -128
- package/template/server/src/modules/auth/auth.repo.ts +60 -42
- package/template/server/src/modules/auth/auth.schemas.ts +5 -2
- package/template/server/src/modules/auth/auth.service.ts +197 -109
- package/template/server/src/modules/auth/session.repo.ts +12 -12
- package/template/server/src/modules/files/__tests__/files.integration.test.ts +5 -5
- package/template/server/src/modules/users/__tests__/avatar-upload.test.ts +120 -0
- package/template/server/src/modules/users/__tests__/name-rules.test.ts +46 -0
- package/template/server/src/modules/users/__tests__/users.integration.test.ts +295 -0
- package/template/server/src/modules/users/__tests__/users.repo.test.ts +37 -0
- package/template/server/src/modules/users/__tests__/users.service.test.ts +129 -0
- package/template/server/src/modules/users/users.controller.ts +9 -38
- package/template/server/src/modules/users/users.repo.ts +25 -7
- package/template/server/src/modules/users/users.routes.ts +3 -22
- package/template/server/src/modules/users/users.schemas.ts +15 -9
- package/template/server/src/modules/users/users.service.ts +105 -93
- package/template/server/src/scripts/make-admin.ts +48 -0
- package/template/server/src/server.ts +48 -26
- package/template/server/src/shared/errors/AppError.ts +27 -1
- package/template/server/src/shared/errors/errors.ts +42 -5
- package/template/server/src/shared/responses/successResponse.ts +22 -3
- package/template/server/src/shared/types/index.ts +7 -0
- package/template/server/src/test/__tests__/integration-services.test.ts +66 -0
- package/template/server/src/test/integration-helpers.ts +343 -0
- package/template/server/src/test/integration-services.ts +74 -0
- package/template/server/src/test/integration.global-setup.ts +144 -0
- package/template/server/src/test/integration.setup.ts +35 -158
- package/template/server/src/test/setup.ts +23 -8
- package/template/server/tsconfig.build.json +1 -1
- package/template/server/tsconfig.json +1 -0
- package/template/server/vitest.config.ts +17 -4
- package/template/server/vitest.integration.config.ts +18 -13
- package/template/server/src/libs/storage/filename-sanitizer.ts +0 -71
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* One answer for wrong input, whichever layer catches it: a route schema
|
|
3
|
+
* (fastify-type-provider-zod), a `schema.parse()` inside a handler, or
|
|
4
|
+
* `parseInput()` below. Every case becomes
|
|
5
|
+
*
|
|
6
|
+
* 422 { success: false, error: { code: 'VALIDATION_FAILED',
|
|
7
|
+
* message: 'Please check these fields: email, password',
|
|
8
|
+
* fields: [{ field: 'email', message: 'Invalid email address' }, ...] } }
|
|
9
|
+
*
|
|
10
|
+
* Never the submitted values: messages come from Zod (or Ajv), which describe
|
|
11
|
+
* the rule ("Too small: expected string to have >=8 characters"), and Zod
|
|
12
|
+
* drops an issue's `input` unless `reportInput` is set, which nothing here
|
|
13
|
+
* does. Keep it that way: a value in a validation answer can leak a password
|
|
14
|
+
* into logs, screenshots or a support ticket.
|
|
15
|
+
*
|
|
16
|
+
* Malformed JSON is not "wrong input" but an unreadable request; it stays a
|
|
17
|
+
* 400 BAD_REQUEST in libs/error-handler.ts.
|
|
18
|
+
*/
|
|
19
|
+
import type { z } from 'zod';
|
|
20
|
+
import type { FieldError } from '@shared/errors/AppError.js';
|
|
21
|
+
import { ValidationError } from '@shared/errors/errors.js';
|
|
22
|
+
|
|
23
|
+
export const VALIDATION_FAILED = 'VALIDATION_FAILED';
|
|
24
|
+
|
|
25
|
+
/** Enough to fix a form; caps the answer when a whole object is wrong. */
|
|
26
|
+
export const MAX_FIELD_ERRORS = 20;
|
|
27
|
+
|
|
28
|
+
interface IssueLike {
|
|
29
|
+
path: ReadonlyArray<PropertyKey>;
|
|
30
|
+
message: string;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** Fastify's names for the request parts, shown when the whole part is wrong. */
|
|
34
|
+
const PART_NAMES: Record<string, string> = { body: 'body', querystring: 'query', params: 'params', headers: 'headers' };
|
|
35
|
+
|
|
36
|
+
function partName(context: string | undefined): string {
|
|
37
|
+
return (context && PART_NAMES[context]) ?? 'input';
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** Zod issues (from `.parse()` / `.safeParse()`) as field errors. */
|
|
41
|
+
export function fieldsFromZodIssues(issues: ReadonlyArray<IssueLike>, context?: string): FieldError[] {
|
|
42
|
+
return issues.slice(0, MAX_FIELD_ERRORS).map((issue) => ({
|
|
43
|
+
field: issue.path.length > 0 ? issue.path.map(String).join('.') : partName(context),
|
|
44
|
+
message: issue.message,
|
|
45
|
+
}));
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* Fastify schema-validation items as field errors. fastify-type-provider-zod
|
|
50
|
+
* and Fastify's own Ajv both report `instancePath` ("/address/city") and
|
|
51
|
+
* `message`; `context` is the request part that failed (Fastify validates
|
|
52
|
+
* params, body, querystring, headers in that order and stops at the first).
|
|
53
|
+
*/
|
|
54
|
+
export function fieldsFromSchemaValidation(
|
|
55
|
+
validation: ReadonlyArray<{ instancePath?: string; message?: string }>,
|
|
56
|
+
context?: string,
|
|
57
|
+
): FieldError[] {
|
|
58
|
+
return validation.slice(0, MAX_FIELD_ERRORS).map((item) => {
|
|
59
|
+
const path = (item.instancePath ?? '').split('/').filter(Boolean).join('.');
|
|
60
|
+
return { field: path || partName(context), message: item.message ?? 'Invalid value' };
|
|
61
|
+
});
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** The human summary: "Please check these fields: email, password". */
|
|
65
|
+
export function validationMessage(fields: ReadonlyArray<FieldError>): string {
|
|
66
|
+
const names = [...new Set(fields.map((f) => f.field))];
|
|
67
|
+
return names.length > 0 ? `Please check these fields: ${names.join(', ')}` : 'Validation failed';
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** The 422 error for these fields (thrown, or built by the global handler). */
|
|
71
|
+
export function validationError(fields: FieldError[]): ValidationError {
|
|
72
|
+
return new ValidationError(validationMessage(fields), VALIDATION_FAILED, fields);
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* Validate input inside a handler (when a route schema cannot express the
|
|
77
|
+
* rule, or for data that is not a request part). Returns the parsed value or
|
|
78
|
+
* throws the standard 422.
|
|
79
|
+
*/
|
|
80
|
+
export function parseInput<S extends z.ZodType>(schema: S, data: unknown): z.output<S> {
|
|
81
|
+
const result = schema.safeParse(data);
|
|
82
|
+
if (!result.success) {
|
|
83
|
+
throw validationError(fieldsFromZodIssues(result.error.issues));
|
|
84
|
+
}
|
|
85
|
+
return result.data;
|
|
86
|
+
}
|
|
@@ -0,0 +1,255 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Administration against a real MySQL and Redis: what must stay true about
|
|
3
|
+
* admin powers (the layer 5 hardening).
|
|
4
|
+
* - The first admin is made with `make-admin <email>` (no password anywhere):
|
|
5
|
+
* it refuses unknown, deleted and banned accounts and verifies the email.
|
|
6
|
+
* - The last active admin cannot delete their own account; an admin cannot
|
|
7
|
+
* ban themselves or change their own role; demoting an admin ends their
|
|
8
|
+
* sessions.
|
|
9
|
+
* - An admin cannot block their own address or a private one; IP blocks use
|
|
10
|
+
* one canonical spelling (so a block matches however the address is
|
|
11
|
+
* written), a double block is 409, and the block is enforced.
|
|
12
|
+
* - Deleted accounts are listed with their purge date and can be restored
|
|
13
|
+
* within the 30 days; the purge removes the rest.
|
|
14
|
+
*
|
|
15
|
+
* The "last admin" tests run first and demote every other admin in this
|
|
16
|
+
* shared test database (files run one after another, earlier files are done
|
|
17
|
+
* with theirs).
|
|
18
|
+
*/
|
|
19
|
+
import { spawnSync } from 'node:child_process';
|
|
20
|
+
import { createRequire } from 'node:module';
|
|
21
|
+
import path from 'node:path';
|
|
22
|
+
import { fileURLToPath } from 'node:url';
|
|
23
|
+
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
|
|
24
|
+
import type { FastifyInstance } from 'fastify';
|
|
25
|
+
import {
|
|
26
|
+
PASSWORD,
|
|
27
|
+
buildTestApp,
|
|
28
|
+
call,
|
|
29
|
+
db,
|
|
30
|
+
image,
|
|
31
|
+
makeAdmin,
|
|
32
|
+
redis,
|
|
33
|
+
registerAdmin,
|
|
34
|
+
registerUser,
|
|
35
|
+
signIn,
|
|
36
|
+
uniqueEmail,
|
|
37
|
+
uploadAvatar,
|
|
38
|
+
type TestUser,
|
|
39
|
+
} from '@/test/integration-helpers.js';
|
|
40
|
+
|
|
41
|
+
const serverRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', '..', '..', '..');
|
|
42
|
+
const tsxCli = createRequire(import.meta.url).resolve('tsx/cli');
|
|
43
|
+
|
|
44
|
+
let app: FastifyInstance;
|
|
45
|
+
let admin: TestUser;
|
|
46
|
+
|
|
47
|
+
beforeAll(async () => {
|
|
48
|
+
app = await buildTestApp();
|
|
49
|
+
});
|
|
50
|
+
|
|
51
|
+
afterAll(async () => {
|
|
52
|
+
await app?.close();
|
|
53
|
+
});
|
|
54
|
+
|
|
55
|
+
const roleOf = async (id: string): Promise<{ role: string; verified: boolean } | null> => {
|
|
56
|
+
const row = await (await db()).user.findUnique({ where: { id }, select: { role: true, emailVerifiedAt: true } });
|
|
57
|
+
return row ? { role: row.role, verified: row.emailVerifiedAt !== null } : null;
|
|
58
|
+
};
|
|
59
|
+
|
|
60
|
+
describe('the last active admin', () => {
|
|
61
|
+
it('cannot delete their own account (409 LAST_ADMIN, after the password check); with a second admin they can', async () => {
|
|
62
|
+
const a = await registerAdmin(app, 'onlyadmin');
|
|
63
|
+
await (await db()).user.updateMany({ where: { role: 'ADMIN', id: { not: a.id } }, data: { role: 'USER' } });
|
|
64
|
+
|
|
65
|
+
const wrong = await call(app, 'DELETE', '/users/me', { jar: a.jar, payload: { password: 'Wrong-Passw0rd-1' } });
|
|
66
|
+
expect([wrong.status, wrong.code]).toEqual([422, 'INVALID_PASSWORD']);
|
|
67
|
+
const last = await call(app, 'DELETE', '/users/me', { jar: a.jar, payload: { password: PASSWORD } });
|
|
68
|
+
expect([last.status, last.code]).toEqual([409, 'LAST_ADMIN']);
|
|
69
|
+
expect((await (await db()).user.findUnique({ where: { id: a.id } }))?.deletedAt).toBeNull();
|
|
70
|
+
|
|
71
|
+
const b = await registerAdmin(app, 'secondadmin');
|
|
72
|
+
expect((await call(app, 'DELETE', '/users/me', { jar: a.jar, payload: { password: PASSWORD } })).status).toBe(200);
|
|
73
|
+
const c = await registerAdmin(app, 'thirdadmin');
|
|
74
|
+
expect((await call(app, 'DELETE', `/users/${c.id}`, { jar: b.jar })).status).toBe(200);
|
|
75
|
+
admin = b;
|
|
76
|
+
});
|
|
77
|
+
});
|
|
78
|
+
|
|
79
|
+
describe('make-admin', () => {
|
|
80
|
+
/** Runs the real script (src/scripts/make-admin.ts) against this test database. */
|
|
81
|
+
const makeAdminScript = (email: string): { code: number | null; out: string } => {
|
|
82
|
+
const r = spawnSync(process.execPath, [tsxCli, 'src/scripts/make-admin.ts', email], {
|
|
83
|
+
cwd: serverRoot,
|
|
84
|
+
env: process.env,
|
|
85
|
+
encoding: 'utf8',
|
|
86
|
+
timeout: 60_000,
|
|
87
|
+
});
|
|
88
|
+
return { code: r.status, out: `${r.stdout}${r.stderr}` };
|
|
89
|
+
};
|
|
90
|
+
|
|
91
|
+
it('promotes an existing account (email in any case), which works without signing in again; again → "already"', async () => {
|
|
92
|
+
const u = await registerUser(app, 'promote');
|
|
93
|
+
const r = makeAdminScript(u.email.toUpperCase());
|
|
94
|
+
expect(r.code).toBe(0);
|
|
95
|
+
expect(await roleOf(u.id)).toEqual({ role: 'ADMIN', verified: true });
|
|
96
|
+
expect((await call(app, 'GET', '/admin/stats', { jar: u.jar })).status).toBe(200);
|
|
97
|
+
const again = makeAdminScript(u.email);
|
|
98
|
+
expect(again.code).toBe(0);
|
|
99
|
+
expect(again.out).toMatch(/already an admin/);
|
|
100
|
+
});
|
|
101
|
+
|
|
102
|
+
it('refuses an unknown, a deleted and a banned account (exit 1, role unchanged); verifies an unverified one', async () => {
|
|
103
|
+
const outputs: string[] = [];
|
|
104
|
+
const unknown = makeAdminScript(uniqueEmail('nobody'));
|
|
105
|
+
outputs.push(unknown.out);
|
|
106
|
+
expect([unknown.code, /No account with that email/.test(unknown.out)]).toEqual([1, true]);
|
|
107
|
+
|
|
108
|
+
const del = await registerUser(app, 'mkdeleted');
|
|
109
|
+
await call(app, 'DELETE', '/users/me', { jar: del.jar, payload: { password: PASSWORD } });
|
|
110
|
+
const delR = makeAdminScript(del.email);
|
|
111
|
+
outputs.push(delR.out);
|
|
112
|
+
expect([delR.code, /deleted/.test(delR.out), (await roleOf(del.id))?.role]).toEqual([1, true, 'USER']);
|
|
113
|
+
|
|
114
|
+
const ban = await registerUser(app, 'mkbanned');
|
|
115
|
+
await call(app, 'PATCH', `/admin/users/${ban.id}/status`, { jar: admin.jar, payload: { isActive: false } });
|
|
116
|
+
const banR = makeAdminScript(ban.email);
|
|
117
|
+
outputs.push(banR.out);
|
|
118
|
+
expect([banR.code, /banned/.test(banR.out), (await roleOf(ban.id))?.role]).toEqual([1, true, 'USER']);
|
|
119
|
+
|
|
120
|
+
const unv = await registerUser(app, 'mkunverified');
|
|
121
|
+
await (await db()).user.update({ where: { id: unv.id }, data: { emailVerifiedAt: null } });
|
|
122
|
+
const unvR = makeAdminScript(unv.email);
|
|
123
|
+
outputs.push(unvR.out);
|
|
124
|
+
expect(unvR.code).toBe(0);
|
|
125
|
+
expect(await roleOf(unv.id)).toEqual({ role: 'ADMIN', verified: true });
|
|
126
|
+
|
|
127
|
+
// The output never carries the database URL or a password.
|
|
128
|
+
const all = outputs.join('\n');
|
|
129
|
+
expect(all).not.toMatch(/mysql:\/\//i);
|
|
130
|
+
expect(all).not.toContain(PASSWORD);
|
|
131
|
+
});
|
|
132
|
+
});
|
|
133
|
+
|
|
134
|
+
describe('admins cannot act on themselves', () => {
|
|
135
|
+
it('self-ban → 403 CANNOT_BAN_SELF and the admin still works; banning another user still works', async () => {
|
|
136
|
+
const self = await call(app, 'PATCH', `/admin/users/${admin.id}/status`, { jar: admin.jar, payload: { isActive: false } });
|
|
137
|
+
expect([self.status, self.code]).toEqual([403, 'CANNOT_BAN_SELF']);
|
|
138
|
+
expect((await call(app, 'GET', '/admin/stats', { jar: admin.jar })).status).toBe(200);
|
|
139
|
+
const v = await registerUser(app, 'banvictim');
|
|
140
|
+
expect((await call(app, 'PATCH', `/admin/users/${v.id}/status`, { jar: admin.jar, payload: { isActive: false } })).status).toBe(200);
|
|
141
|
+
const me = await call(app, 'GET', '/auth/me', { cookie: v.jar.header() });
|
|
142
|
+
expect([me.status, me.code]).toEqual([403, 'ACCOUNT_DEACTIVATED']);
|
|
143
|
+
});
|
|
144
|
+
|
|
145
|
+
it('self role change → 403; demoting another admin ends their sessions', async () => {
|
|
146
|
+
expect((await call(app, 'PATCH', `/admin/users/${admin.id}/role`, { jar: admin.jar, payload: { role: 'USER' } })).status).toBe(403);
|
|
147
|
+
const other = await registerAdmin(app, 'demoted');
|
|
148
|
+
const otherDevice = await signIn(app, other.email);
|
|
149
|
+
expect((await call(app, 'PATCH', `/admin/users/${other.id}/role`, { jar: admin.jar, payload: { role: 'USER' } })).status).toBe(200);
|
|
150
|
+
expect((await call(app, 'GET', '/auth/me', { cookie: otherDevice.header() })).status).toBe(401);
|
|
151
|
+
});
|
|
152
|
+
});
|
|
153
|
+
|
|
154
|
+
describe('IP blocks', () => {
|
|
155
|
+
const blocked = async (ip: string): Promise<boolean> => (await (await redis()).sismember('blocked_ips', ip)) === 1;
|
|
156
|
+
|
|
157
|
+
it('your own address → 422 CANNOT_BLOCK_OWN_IP; private and reserved addresses → 422 IP_NOT_BLOCKABLE', async () => {
|
|
158
|
+
const own = (await call(app, 'GET', '/admin/client-ip', { jar: admin.jar })).body?.data?.ip as string;
|
|
159
|
+
const self = await call(app, 'POST', '/admin/blocked-ips', { jar: admin.jar, payload: { ip: own } });
|
|
160
|
+
expect([self.status, self.code]).toEqual([422, 'CANNOT_BLOCK_OWN_IP']);
|
|
161
|
+
for (const ip of ['10.0.0.5', '192.168.1.1', '::1']) {
|
|
162
|
+
const r = await call(app, 'POST', '/admin/blocked-ips', { jar: admin.jar, payload: { ip } });
|
|
163
|
+
expect([ip, r.status, r.code]).toEqual([ip, 422, 'IP_NOT_BLOCKABLE']);
|
|
164
|
+
}
|
|
165
|
+
});
|
|
166
|
+
|
|
167
|
+
it('one canonical spelling: stored and in Redis as 2001:db8::1; another spelling → 409; mapped IPv4 → plain IPv4', async () => {
|
|
168
|
+
const r = await call(app, 'POST', '/admin/blocked-ips', { jar: admin.jar, payload: { ip: '2001:0DB8:0000::0001' } });
|
|
169
|
+
expect([r.status, r.body?.data?.ip]).toEqual([201, '2001:db8::1']);
|
|
170
|
+
expect((await (await db()).blockedIp.findMany({ where: { ip: { startsWith: '2001:' } } })).map((b) => b.ip)).toContain('2001:db8::1');
|
|
171
|
+
expect(await blocked('2001:db8::1')).toBe(true);
|
|
172
|
+
const dup = await call(app, 'POST', '/admin/blocked-ips', { jar: admin.jar, payload: { ip: '2001:db8::1' } });
|
|
173
|
+
expect([dup.status, dup.code]).toEqual([409, 'IP_ALREADY_BLOCKED']);
|
|
174
|
+
const mapped = await call(app, 'POST', '/admin/blocked-ips', { jar: admin.jar, payload: { ip: '::ffff:203.0.113.7' } });
|
|
175
|
+
expect([mapped.status, mapped.body?.data?.ip]).toEqual([201, '203.0.113.7']);
|
|
176
|
+
|
|
177
|
+
const un = await call(app, 'DELETE', `/admin/blocked-ips/${encodeURIComponent('2001:DB8::1')}`, { jar: admin.jar });
|
|
178
|
+
expect(un.status).toBe(200);
|
|
179
|
+
expect(await (await db()).blockedIp.count({ where: { ip: '2001:db8::1' } })).toBe(0);
|
|
180
|
+
expect(await blocked('2001:db8::1')).toBe(false);
|
|
181
|
+
expect((await call(app, 'DELETE', '/admin/blocked-ips/not-an-ip', { jar: admin.jar })).status).toBe(422);
|
|
182
|
+
await call(app, 'DELETE', '/admin/blocked-ips/203.0.113.7', { jar: admin.jar });
|
|
183
|
+
});
|
|
184
|
+
|
|
185
|
+
it('two identical blocks at once → one 201 and one 409, never 500', async () => {
|
|
186
|
+
const both = await Promise.all([0, 1].map(() => call(app, 'POST', '/admin/blocked-ips', { jar: admin.jar, payload: { ip: '203.0.113.50' } })));
|
|
187
|
+
expect(both.map((b) => b.status).sort()).toEqual([201, 409]);
|
|
188
|
+
await call(app, 'DELETE', '/admin/blocked-ips/203.0.113.50', { jar: admin.jar });
|
|
189
|
+
});
|
|
190
|
+
|
|
191
|
+
it('a block typed one way stops the same address written another way (403 IP_BLOCKED); a neighbour is not blocked', async () => {
|
|
192
|
+
await call(app, 'POST', '/admin/blocked-ips', { jar: admin.jar, payload: { ip: '2001:0db8::abcd' } });
|
|
193
|
+
// app.inject comes from 127.0.0.1, a trusted proxy hop, so X-Forwarded-For is believed.
|
|
194
|
+
const hit = await call(app, 'GET', '/auth/me', { headers: { 'x-forwarded-for': '2001:db8:0:0:0:0:0:abcd' } });
|
|
195
|
+
expect([hit.status, hit.code]).toEqual([403, 'IP_BLOCKED']);
|
|
196
|
+
const neighbour = await call(app, 'GET', '/auth/me', { headers: { 'x-forwarded-for': '2001:db8::abce' } });
|
|
197
|
+
expect(neighbour.status).toBe(401);
|
|
198
|
+
await call(app, 'DELETE', `/admin/blocked-ips/${encodeURIComponent('2001:db8::abcd')}`, { jar: admin.jar });
|
|
199
|
+
});
|
|
200
|
+
});
|
|
201
|
+
|
|
202
|
+
describe('deleted accounts: list, restore, purge', () => {
|
|
203
|
+
let x: TestUser;
|
|
204
|
+
|
|
205
|
+
it('?deleted=true lists a deleted account with purgeAt = deletedAt + 30 days; the default list does not', async () => {
|
|
206
|
+
x = await registerUser(app, 'restorable');
|
|
207
|
+
await uploadAvatar(app, x.jar, await image('png'));
|
|
208
|
+
await call(app, 'DELETE', '/users/me', { jar: x.jar, payload: { password: PASSWORD } });
|
|
209
|
+
const deleted = await call(app, 'GET', `/admin/users?deleted=true&search=${encodeURIComponent(x.email)}`, { jar: admin.jar });
|
|
210
|
+
const item = deleted.body?.data?.items?.[0];
|
|
211
|
+
expect(item?.id).toBe(x.id);
|
|
212
|
+
expect((new Date(item.purgeAt).getTime() - new Date(item.deletedAt).getTime()) / 86_400_000).toBe(30);
|
|
213
|
+
const live = await call(app, 'GET', `/admin/users?search=${encodeURIComponent(x.email)}`, { jar: admin.jar });
|
|
214
|
+
expect(live.body?.data?.items).toHaveLength(0);
|
|
215
|
+
});
|
|
216
|
+
|
|
217
|
+
it('restore → 200 (active, no avatar); the user signs in with the old password; again → 409, unknown → 404, non-admin → 403', async () => {
|
|
218
|
+
const restore = await call(app, 'POST', `/admin/users/${x.id}/restore`, { jar: admin.jar });
|
|
219
|
+
expect(restore.status).toBe(200);
|
|
220
|
+
expect(restore.body?.data).toMatchObject({ deletedAt: null, isActive: true, avatarUrl: null });
|
|
221
|
+
const userJar = await signIn(app, x.email);
|
|
222
|
+
const again = await call(app, 'POST', `/admin/users/${x.id}/restore`, { jar: admin.jar });
|
|
223
|
+
expect([again.status, again.code]).toEqual([409, 'USER_NOT_DELETED']);
|
|
224
|
+
const unknown = await call(app, 'POST', '/admin/users/00000000-0000-4000-8000-000000000000/restore', { jar: admin.jar });
|
|
225
|
+
expect([unknown.status, unknown.code]).toEqual([404, 'USER_NOT_FOUND']);
|
|
226
|
+
expect((await call(app, 'POST', `/admin/users/${x.id}/restore`, { jar: userJar })).status).toBe(403);
|
|
227
|
+
});
|
|
228
|
+
|
|
229
|
+
it('the purge removes an account deleted 31 days ago (restore then 404); the restored account stays', async () => {
|
|
230
|
+
const y = await registerUser(app, 'purged');
|
|
231
|
+
await call(app, 'DELETE', '/users/me', { jar: y.jar, payload: { password: PASSWORD } });
|
|
232
|
+
await (await db()).user.update({ where: { id: y.id }, data: { deletedAt: new Date(Date.now() - 31 * 86_400_000) } });
|
|
233
|
+
const { purgeDeletedAccounts } = await import('@jobs/cleanup-deleted-accounts.job.js');
|
|
234
|
+
await purgeDeletedAccounts();
|
|
235
|
+
expect(await (await db()).user.count({ where: { id: y.id } })).toBe(0);
|
|
236
|
+
expect((await call(app, 'POST', `/admin/users/${y.id}/restore`, { jar: admin.jar })).status).toBe(404);
|
|
237
|
+
expect((await (await db()).user.findUnique({ where: { id: x.id } }))?.deletedAt).toBeNull();
|
|
238
|
+
});
|
|
239
|
+
|
|
240
|
+
it('user detail has lastActiveAt and no lastLogin', async () => {
|
|
241
|
+
const d = await call(app, 'GET', `/admin/users/${x.id}`, { jar: admin.jar });
|
|
242
|
+
expect(d.status).toBe(200);
|
|
243
|
+
expect(d.body?.data).toHaveProperty('lastActiveAt');
|
|
244
|
+
expect(d.body?.data).not.toHaveProperty('lastLogin');
|
|
245
|
+
});
|
|
246
|
+
});
|
|
247
|
+
|
|
248
|
+
describe('makeAdmin helper sanity', () => {
|
|
249
|
+
it('a promoted account reaches the admin API at once (the role is read on every request)', async () => {
|
|
250
|
+
const u = await registerUser(app, 'helper');
|
|
251
|
+
expect((await call(app, 'GET', '/admin/stats', { jar: u.jar })).status).toBe(403);
|
|
252
|
+
await makeAdmin(u.id);
|
|
253
|
+
expect((await call(app, 'GET', '/admin/stats', { jar: u.jar })).status).toBe(200);
|
|
254
|
+
});
|
|
255
|
+
});
|
|
@@ -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
|
+
});
|