create-tigra 3.3.0 → 4.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +81 -12
- package/bin/create-tigra.js +495 -472
- package/lib/patchers/email-verification.patcher.js +72 -10
- package/modules/email-verification/client/hooks/useVerification.ts +4 -1
- package/modules/email-verification/server/__tests__/verification.integration.test.ts +115 -0
- package/modules/email-verification/server/verification.controller.ts +3 -1
- package/modules/email-verification/server/verification.service.ts +44 -13
- package/package.json +3 -2
- package/template/.github/dependabot.yml +47 -0
- package/template/.github/workflows/audit.yml +36 -0
- package/template/.github/workflows/ci.yml +79 -0
- package/template/AGENTS.md +18 -9
- package/template/client/.dockerignore +1 -0
- package/template/client/.env.example.production +13 -2
- package/template/client/AGENTS.md +13 -5
- package/template/client/Dockerfile +186 -14
- package/template/client/next.config.ts +1 -1
- package/template/client/package-lock.json +15983 -14181
- package/template/client/package.json +56 -48
- package/template/client/scripts/check-sharp.mjs +53 -0
- package/template/client/scripts/next-dev.cjs +5 -1
- package/template/client/src/__tests__/proxy.test.ts +92 -0
- package/template/client/src/app/healthz/route.ts +16 -0
- package/template/client/src/app/layout.tsx +9 -3
- package/template/client/src/app/page.tsx +2 -2
- package/template/client/src/app/providers.tsx +23 -4
- package/template/client/src/components/layout/Header.tsx +7 -3
- package/template/client/src/features/admin/hooks/useAdminSessions.ts +2 -1
- package/template/client/src/features/admin/hooks/useAdminUsers.ts +3 -1
- package/template/client/src/features/admin/types/admin.types.ts +2 -3
- package/template/client/src/features/auth/components/AuthInitializer.tsx +35 -18
- package/template/client/src/features/auth/components/ForgotPasswordForm.tsx +107 -0
- package/template/client/src/features/auth/components/LimitNotice.tsx +28 -0
- package/template/client/src/features/auth/components/LoginForm.tsx +13 -2
- package/template/client/src/features/auth/components/RegisterForm.tsx +23 -7
- package/template/client/src/features/auth/hooks/useAuth.ts +11 -1
- package/template/client/src/features/auth/hooks/usePasswordReset.ts +7 -1
- package/template/client/src/features/auth/services/auth.service.ts +8 -3
- package/template/client/src/features/auth/store/authSlice.ts +7 -2
- package/template/client/src/lib/api/__tests__/axios.config.test.ts +183 -0
- package/template/client/src/lib/api/api.types.ts +14 -0
- package/template/client/src/lib/api/axios.config.ts +101 -15
- package/template/client/src/lib/api/hard-redirect.ts +8 -0
- package/template/client/src/lib/api/session-events.ts +29 -0
- package/template/client/src/lib/constants/routes.ts +12 -0
- package/template/client/src/lib/observability/sentry-scrub.ts +1 -1
- package/template/client/src/lib/utils/__tests__/error.test.ts +119 -0
- package/template/client/src/lib/utils/__tests__/form.test.ts +42 -0
- package/template/client/src/lib/utils/__tests__/paths.test.ts +43 -0
- package/template/client/src/lib/utils/__tests__/security.test.ts +40 -0
- package/template/client/src/lib/utils/__tests__/session-marker.test.ts +27 -0
- package/template/client/src/lib/utils/error.ts +81 -0
- package/template/client/src/lib/utils/form.ts +31 -0
- package/template/client/src/lib/utils/paths.ts +18 -0
- package/template/client/src/lib/utils/session-marker.ts +24 -0
- package/template/client/src/{middleware.ts → proxy.ts} +25 -11
- package/template/client/src/store/__tests__/store.test.ts +44 -0
- package/template/client/src/store/index.ts +26 -8
- package/template/client/vitest.config.mts +48 -0
- package/template/server/.env.example +280 -270
- package/template/server/.env.example.production +283 -242
- package/template/server/AGENTS.md +13 -4
- package/template/server/Dockerfile +176 -14
- package/template/server/docker-compose.yml +4 -2
- package/template/server/docs/deployment.md +63 -0
- package/template/server/docs/logging.md +52 -4
- package/template/server/docs/rate-limits.md +153 -0
- package/template/server/docs/testing.md +63 -0
- package/template/server/eslint.config.mjs +19 -0
- package/template/server/package-lock.json +8784 -8743
- package/template/server/package.json +79 -75
- package/template/server/prisma/migrations/0_init/migration.sql +82 -0
- package/template/server/prisma/migrations/migration_lock.toml +3 -0
- package/template/server/prisma/schema.prisma +0 -3
- package/template/server/scripts/check-heic.mjs +40 -0
- package/template/server/scripts/check-sharp.mjs +53 -0
- package/template/server/src/__tests__/routes.integration.test.ts +280 -0
- package/template/server/src/app.ts +248 -346
- package/template/server/src/config/__tests__/env.test.ts +219 -0
- package/template/server/src/config/__tests__/rate-limit.config.test.ts +158 -0
- package/template/server/src/config/env.ts +326 -182
- package/template/server/src/config/rate-limit.config.ts +157 -106
- package/template/server/src/jobs/__tests__/cleanup-deleted-accounts.job.test.ts +60 -8
- package/template/server/src/jobs/__tests__/cleanup-expired-auth.job.test.ts +44 -0
- package/template/server/src/jobs/__tests__/jobs.integration.test.ts +88 -0
- package/template/server/src/jobs/__tests__/schedule.test.ts +92 -0
- package/template/server/src/jobs/cleanup-deleted-accounts.job.ts +38 -36
- package/template/server/src/jobs/cleanup-expired-auth.job.ts +32 -24
- package/template/server/src/jobs/index.ts +12 -2
- package/template/server/src/jobs/refresh-cloudflare-ranges.job.ts +28 -0
- package/template/server/src/jobs/schedule.ts +50 -0
- package/template/server/src/libs/__tests__/auth.test.ts +98 -7
- package/template/server/src/libs/__tests__/client-ip.test.ts +257 -121
- package/template/server/src/libs/__tests__/cloudflare-ranges.test.ts +79 -0
- package/template/server/src/libs/__tests__/cookies.test.ts +53 -2
- package/template/server/src/libs/__tests__/email-quota.test.ts +81 -0
- package/template/server/src/libs/__tests__/email.test.ts +68 -0
- package/template/server/src/libs/__tests__/error-handler.test.ts +162 -0
- package/template/server/src/libs/__tests__/health-db-down.integration.test.ts +37 -0
- package/template/server/src/libs/__tests__/health-redis-down.integration.test.ts +45 -0
- package/template/server/src/libs/__tests__/health-routes.test.ts +83 -0
- package/template/server/src/libs/__tests__/health.integration.test.ts +118 -0
- package/template/server/src/libs/__tests__/http.test.ts +74 -2
- package/template/server/src/libs/__tests__/ip-block.test.ts +179 -62
- package/template/server/src/libs/__tests__/logger.test.ts +50 -0
- package/template/server/src/libs/__tests__/monitoring.test.ts +185 -0
- package/template/server/src/libs/__tests__/outbound.integration.test.ts +48 -0
- package/template/server/src/libs/__tests__/prisma-client.test.ts +28 -0
- package/template/server/src/libs/__tests__/query-counter.integration.test.ts +53 -0
- package/template/server/src/libs/__tests__/rate-limiting.test.ts +146 -0
- package/template/server/src/libs/__tests__/rate-limits.integration.test.ts +53 -0
- package/template/server/src/libs/__tests__/redis-required.test.ts +30 -0
- package/template/server/src/libs/__tests__/redis.test.ts +38 -2
- package/template/server/src/libs/__tests__/request-id.test.ts +25 -0
- package/template/server/src/libs/__tests__/requestLogger.test.ts +126 -0
- package/template/server/src/libs/__tests__/safe-http.test.ts +138 -0
- package/template/server/src/libs/__tests__/sentry-scrub.test.ts +82 -80
- package/template/server/src/libs/__tests__/shutdown.test.ts +89 -0
- package/template/server/src/libs/__tests__/url-safety.test.ts +130 -80
- package/template/server/src/libs/auth.ts +39 -10
- package/template/server/src/libs/client-ip.ts +158 -77
- package/template/server/src/libs/cloudflare-ranges.ts +132 -0
- package/template/server/src/libs/cookies.ts +53 -14
- package/template/server/src/libs/email-quota.ts +74 -0
- package/template/server/src/libs/email.ts +46 -9
- package/template/server/src/libs/error-handler.ts +111 -0
- package/template/server/src/libs/health-routes.ts +53 -0
- package/template/server/src/libs/http.ts +139 -47
- package/template/server/src/libs/ip-address.ts +37 -0
- package/template/server/src/libs/ip-block.ts +284 -221
- package/template/server/src/libs/logger.ts +41 -12
- package/template/server/src/libs/monitoring.ts +127 -41
- package/template/server/src/libs/observability/sentry.ts +1 -1
- package/template/server/src/libs/origin-check.ts +9 -7
- package/template/server/src/libs/prisma.ts +47 -4
- package/template/server/src/libs/query-counter.ts +71 -59
- package/template/server/src/libs/rate-limiting.ts +110 -0
- package/template/server/src/libs/redis-required.ts +28 -0
- package/template/server/src/libs/redis.ts +27 -1
- package/template/server/src/libs/request-id.ts +18 -0
- package/template/server/src/libs/requestLogger.ts +112 -17
- package/template/server/src/libs/safe-http.ts +101 -0
- package/template/server/src/libs/shutdown.ts +87 -0
- package/template/server/src/libs/storage/__tests__/fixtures/tiny-heic.ts +13 -0
- package/template/server/src/libs/storage/__tests__/image-optimizer.test.ts +59 -0
- package/template/server/src/libs/storage/__tests__/multipart-limits.test.ts +91 -0
- package/template/server/src/libs/storage/__tests__/upload-persistence.test.ts +52 -0
- package/template/server/src/libs/storage/file-storage.service.ts +94 -84
- package/template/server/src/libs/storage/file-validator.ts +48 -46
- package/template/server/src/libs/storage/image-optimizer.service.ts +16 -5
- package/template/server/src/libs/token-hash.ts +18 -0
- package/template/server/src/libs/url-safety.ts +127 -121
- package/template/server/src/libs/validation-errors.ts +86 -0
- package/template/server/src/modules/admin/__tests__/admin-actions.integration.test.ts +255 -0
- package/template/server/src/modules/admin/__tests__/admin.health.test.ts +82 -0
- package/template/server/src/modules/admin/__tests__/admin.repo.test.ts +55 -0
- package/template/server/src/modules/admin/__tests__/admin.schemas.test.ts +38 -0
- package/template/server/src/modules/admin/__tests__/admin.service.test.ts +162 -0
- package/template/server/src/modules/admin/admin.controller.ts +66 -49
- package/template/server/src/modules/admin/admin.repo.ts +49 -10
- package/template/server/src/modules/admin/admin.routes.ts +48 -2
- package/template/server/src/modules/admin/admin.schemas.ts +18 -6
- package/template/server/src/modules/admin/admin.service.ts +66 -4
- package/template/server/src/modules/auth/__tests__/auth.controller.test.ts +39 -0
- package/template/server/src/modules/auth/__tests__/auth.integration.test.ts +9 -3
- package/template/server/src/modules/auth/__tests__/auth.service.dummy-hash.test.ts +34 -0
- package/template/server/src/modules/auth/__tests__/auth.service.test.ts +197 -37
- package/template/server/src/modules/auth/__tests__/session-cleanup.test.ts +39 -0
- package/template/server/src/modules/auth/__tests__/sessions.integration.test.ts +246 -0
- package/template/server/src/modules/auth/__tests__/token-fingerprints.test.ts +119 -0
- package/template/server/src/modules/auth/auth.controller.ts +133 -128
- package/template/server/src/modules/auth/auth.repo.ts +44 -44
- package/template/server/src/modules/auth/auth.schemas.ts +4 -2
- package/template/server/src/modules/auth/auth.service.ts +167 -96
- package/template/server/src/modules/auth/session.repo.ts +12 -0
- package/template/server/src/modules/files/__tests__/files.integration.test.ts +5 -5
- package/template/server/src/modules/users/__tests__/avatar-upload.test.ts +120 -0
- package/template/server/src/modules/users/__tests__/name-rules.test.ts +46 -0
- package/template/server/src/modules/users/__tests__/users.integration.test.ts +295 -0
- package/template/server/src/modules/users/__tests__/users.repo.test.ts +37 -0
- package/template/server/src/modules/users/__tests__/users.service.test.ts +129 -0
- package/template/server/src/modules/users/users.controller.ts +9 -38
- package/template/server/src/modules/users/users.repo.ts +23 -7
- package/template/server/src/modules/users/users.routes.ts +3 -22
- package/template/server/src/modules/users/users.schemas.ts +15 -9
- package/template/server/src/modules/users/users.service.ts +105 -93
- package/template/server/src/scripts/make-admin.ts +48 -0
- package/template/server/src/server.ts +48 -26
- package/template/server/src/shared/errors/AppError.ts +27 -1
- package/template/server/src/shared/errors/errors.ts +42 -5
- package/template/server/src/shared/responses/successResponse.ts +22 -3
- package/template/server/src/shared/types/index.ts +7 -0
- package/template/server/src/test/__tests__/integration-services.test.ts +66 -0
- package/template/server/src/test/integration-helpers.ts +343 -0
- package/template/server/src/test/integration-services.ts +74 -0
- package/template/server/src/test/integration.global-setup.ts +144 -0
- package/template/server/src/test/integration.setup.ts +35 -158
- package/template/server/src/test/setup.ts +3 -10
- package/template/server/tsconfig.build.json +1 -1
- package/template/server/tsconfig.json +1 -0
- package/template/server/vitest.config.ts +17 -4
- package/template/server/vitest.integration.config.ts +18 -13
- package/template/server/src/libs/storage/filename-sanitizer.ts +0 -71
|
@@ -0,0 +1,295 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Users and files against a real MySQL, Redis and upload folders: what must
|
|
3
|
+
* stay true about profiles, avatars and account deletion (the layer 4
|
|
4
|
+
* hardening).
|
|
5
|
+
* - Names are trimmed before their length check.
|
|
6
|
+
* - An avatar's format is judged by its bytes (the browser's type and name
|
|
7
|
+
* are ignored); every upload gets a new random name with a one-year cache,
|
|
8
|
+
* the old file is gone at once, two uploads at once leave exactly one file,
|
|
9
|
+
* and the served file carries no EXIF.
|
|
10
|
+
* - Too many pixels → 422, too many bytes → 413, never a 500.
|
|
11
|
+
* - A deleted account's photo stops being public at once; the purge removes
|
|
12
|
+
* both upload tiers, then the row.
|
|
13
|
+
* - Changing your own password keeps this device signed in and ends the
|
|
14
|
+
* others; an admin's forced change ends them all.
|
|
15
|
+
* - Only the owner or an admin may change a user; private files are the
|
|
16
|
+
* owner's only.
|
|
17
|
+
*/
|
|
18
|
+
import fs from 'node:fs';
|
|
19
|
+
import path from 'node:path';
|
|
20
|
+
import { crc32, deflateSync } from 'node:zlib';
|
|
21
|
+
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
|
|
22
|
+
import type { FastifyInstance } from 'fastify';
|
|
23
|
+
import { integrationServices } from '@/test/integration.setup.js';
|
|
24
|
+
import { TINY_HEIC_BASE64 } from '@/libs/storage/__tests__/fixtures/tiny-heic.js';
|
|
25
|
+
import {
|
|
26
|
+
PASSWORD,
|
|
27
|
+
buildTestApp,
|
|
28
|
+
call,
|
|
29
|
+
db,
|
|
30
|
+
image,
|
|
31
|
+
registerAdmin,
|
|
32
|
+
registerUser,
|
|
33
|
+
signIn,
|
|
34
|
+
uniqueEmail,
|
|
35
|
+
uploadAvatar,
|
|
36
|
+
type TestUser,
|
|
37
|
+
} from '@/test/integration-helpers.js';
|
|
38
|
+
|
|
39
|
+
let app: FastifyInstance;
|
|
40
|
+
let admin: TestUser;
|
|
41
|
+
|
|
42
|
+
beforeAll(async () => {
|
|
43
|
+
app = await buildTestApp();
|
|
44
|
+
admin = await registerAdmin(app, 'users-admin');
|
|
45
|
+
});
|
|
46
|
+
|
|
47
|
+
afterAll(async () => {
|
|
48
|
+
await app?.close();
|
|
49
|
+
});
|
|
50
|
+
|
|
51
|
+
const avatarDir = (userId: string): string => path.join(integrationServices.uploadPublicDir, 'users', userId, 'avatar');
|
|
52
|
+
const filesIn = (dir: string): string[] => (fs.existsSync(dir) ? fs.readdirSync(dir).sort() : []);
|
|
53
|
+
const avatarUrlOf = async (userId: string): Promise<string | null> =>
|
|
54
|
+
(await (await db()).user.findUnique({ where: { id: userId }, select: { avatarUrl: true } }))?.avatarUrl ?? null;
|
|
55
|
+
const isWebp = (bytes: Buffer): boolean => bytes.subarray(0, 4).toString() === 'RIFF' && bytes.subarray(8, 12).toString() === 'WEBP';
|
|
56
|
+
|
|
57
|
+
describe('names', () => {
|
|
58
|
+
const base = { password: PASSWORD, lastName: 'Tester' };
|
|
59
|
+
|
|
60
|
+
it('register with a blank or 1-letter first name (after trimming) → 422 naming firstName', async () => {
|
|
61
|
+
const blank = await call(app, 'POST', '/auth/register', { payload: { ...base, email: uniqueEmail('blank'), firstName: ' ' } });
|
|
62
|
+
expect([blank.status, blank.code]).toEqual([422, 'VALIDATION_FAILED']);
|
|
63
|
+
expect(blank.body?.error?.fields?.map((f) => f.field)).toContain('firstName');
|
|
64
|
+
const one = await call(app, 'POST', '/auth/register', { payload: { ...base, email: uniqueEmail('one'), firstName: ' a ' } });
|
|
65
|
+
expect(one.status).toBe(422);
|
|
66
|
+
});
|
|
67
|
+
|
|
68
|
+
it('register " Ann " → 201 and stored trimmed', async () => {
|
|
69
|
+
const email = uniqueEmail('ann');
|
|
70
|
+
const r = await call(app, 'POST', '/auth/register', { payload: { ...base, email, firstName: ' Ann ' } });
|
|
71
|
+
expect(r.status).toBe(201);
|
|
72
|
+
expect((await (await db()).user.findUnique({ where: { email } }))?.firstName).toBe('Ann');
|
|
73
|
+
});
|
|
74
|
+
|
|
75
|
+
it('PATCH /users/me with nothing → 422 naming both fields; " Bo " → saved "Bo"', async () => {
|
|
76
|
+
const u = await registerUser(app, 'names');
|
|
77
|
+
const empty = await call(app, 'PATCH', '/users/me', { jar: u.jar, payload: {} });
|
|
78
|
+
expect([empty.status, empty.code]).toEqual([422, 'VALIDATION_FAILED']);
|
|
79
|
+
expect(empty.body?.error?.fields?.map((f) => f.field).sort()).toEqual(['firstName', 'lastName']);
|
|
80
|
+
const bo = await call(app, 'PATCH', '/users/me', { jar: u.jar, payload: { firstName: ' Bo ' } });
|
|
81
|
+
expect([bo.status, bo.body?.data?.firstName]).toEqual([200, 'Bo']);
|
|
82
|
+
});
|
|
83
|
+
});
|
|
84
|
+
|
|
85
|
+
describe('avatar formats are judged by the bytes', () => {
|
|
86
|
+
let u: TestUser;
|
|
87
|
+
beforeAll(async () => {
|
|
88
|
+
u = await registerUser(app, 'formats');
|
|
89
|
+
});
|
|
90
|
+
|
|
91
|
+
it.each(['jpeg', 'png', 'webp', 'avif'] as const)('%s sent as application/octet-stream named "blob" → 200', async (format) => {
|
|
92
|
+
const r = await uploadAvatar(app, u.jar, await image(format));
|
|
93
|
+
expect(r.status).toBe(200);
|
|
94
|
+
});
|
|
95
|
+
|
|
96
|
+
it('PNG bytes named photo.exe → 200, and the served file is WebP', async () => {
|
|
97
|
+
const r = await uploadAvatar(app, u.jar, await image('png'), { filename: 'photo.exe', type: 'application/x-msdownload' });
|
|
98
|
+
expect(r.status).toBe(200);
|
|
99
|
+
const served = await call(app, 'GET', r.body?.data?.avatarUrl);
|
|
100
|
+
expect(isWebp(served.res.rawPayload)).toBe(true);
|
|
101
|
+
});
|
|
102
|
+
|
|
103
|
+
it('text bytes named photo.jpg (image/jpeg) → 422', async () => {
|
|
104
|
+
const r = await uploadAvatar(app, u.jar, Buffer.from('this is not an image at all'), { filename: 'photo.jpg', type: 'image/jpeg' });
|
|
105
|
+
expect(r.status).toBe(422);
|
|
106
|
+
});
|
|
107
|
+
|
|
108
|
+
it('HEIC → 200 where this sharp can decode HEVC, otherwise 422 UNSUPPORTED_IMAGE_FORMAT; never a 500', async () => {
|
|
109
|
+
const r = await uploadAvatar(app, u.jar, Buffer.from(TINY_HEIC_BASE64, 'base64'), { filename: 'IMG_0001.HEIC' });
|
|
110
|
+
if (r.status === 422) expect(r.code).toBe('UNSUPPORTED_IMAGE_FORMAT');
|
|
111
|
+
else expect(r.status).toBe(200);
|
|
112
|
+
});
|
|
113
|
+
});
|
|
114
|
+
|
|
115
|
+
describe('avatar files', () => {
|
|
116
|
+
it('a re-upload gets a new random name with a one-year cache; the old URL is 404 at once; 1 file on disk', async () => {
|
|
117
|
+
const u = await registerUser(app, 'files');
|
|
118
|
+
const a = await uploadAvatar(app, u.jar, await image('jpeg'));
|
|
119
|
+
const b = await uploadAvatar(app, u.jar, await image('png'));
|
|
120
|
+
const urlA = a.body?.data?.avatarUrl as string;
|
|
121
|
+
const urlB = b.body?.data?.avatarUrl as string;
|
|
122
|
+
expect(urlA).not.toBe(urlB);
|
|
123
|
+
expect((await call(app, 'GET', urlA)).status).toBe(404);
|
|
124
|
+
const fresh = await call(app, 'GET', urlB);
|
|
125
|
+
expect(fresh.status).toBe(200);
|
|
126
|
+
expect(fresh.res.headers['cache-control']).toBe('public, max-age=31536000, immutable');
|
|
127
|
+
expect(urlB).toMatch(/\/avatar\/avatar-[0-9a-f]{16}\.webp$/);
|
|
128
|
+
expect(await avatarUrlOf(u.id)).toBe(urlB);
|
|
129
|
+
expect(filesIn(avatarDir(u.id))).toEqual([path.basename(urlB)]);
|
|
130
|
+
});
|
|
131
|
+
|
|
132
|
+
it('two uploads at the same instant (6 rounds) → exactly 1 file, the one the database points at, served 200', async () => {
|
|
133
|
+
const u = await registerUser(app, 'race');
|
|
134
|
+
for (let round = 0; round < 6; round++) {
|
|
135
|
+
const [r1, r2] = await Promise.all([
|
|
136
|
+
uploadAvatar(app, u.jar, await image('jpeg', 60 + round)),
|
|
137
|
+
uploadAvatar(app, u.jar, await image('png', 70 + round)),
|
|
138
|
+
]);
|
|
139
|
+
expect([r1.status, r2.status]).toEqual([200, 200]);
|
|
140
|
+
const current = (await avatarUrlOf(u.id)) as string;
|
|
141
|
+
expect(filesIn(avatarDir(u.id))).toEqual([path.basename(current)]);
|
|
142
|
+
expect((await call(app, 'GET', current)).status).toBe(200);
|
|
143
|
+
}
|
|
144
|
+
});
|
|
145
|
+
|
|
146
|
+
it('the served file carries no EXIF (a JPEG with GPS comes back as WebP without it)', async () => {
|
|
147
|
+
const u = await registerUser(app, 'gps');
|
|
148
|
+
const sharp = (await import('sharp')).default;
|
|
149
|
+
const gps = await sharp({ create: { width: 64, height: 32, channels: 3, background: '#808080' } })
|
|
150
|
+
.jpeg()
|
|
151
|
+
.withExif({ IFD0: { Make: 'DummyCam' }, IFD3: { GPSLatitudeRef: 'N', GPSLatitude: '1/1 2/1 3/1', GPSLongitudeRef: 'E', GPSLongitude: '4/1 5/1 6/1' } })
|
|
152
|
+
.toBuffer();
|
|
153
|
+
const up = await uploadAvatar(app, u.jar, gps, { filename: 'gps.jpg', type: 'image/jpeg' });
|
|
154
|
+
const meta = await sharp((await call(app, 'GET', up.body?.data?.avatarUrl)).res.rawPayload).metadata();
|
|
155
|
+
expect([meta.format, meta.exif]).toEqual(['webp', undefined]);
|
|
156
|
+
});
|
|
157
|
+
|
|
158
|
+
it('the old GET /api/v1/users/:id/avatar route is gone → 404', async () => {
|
|
159
|
+
const u = await registerUser(app, 'oldroute');
|
|
160
|
+
expect((await call(app, 'GET', `/users/${u.id}/avatar`)).status).toBe(404);
|
|
161
|
+
});
|
|
162
|
+
|
|
163
|
+
it('avatar delete → folder gone, URL 404, avatarUrl NULL', async () => {
|
|
164
|
+
const u = await registerUser(app, 'avdel');
|
|
165
|
+
const url = (await uploadAvatar(app, u.jar, await image('png'))).body?.data?.avatarUrl as string;
|
|
166
|
+
expect((await call(app, 'DELETE', '/users/avatar', { jar: u.jar })).status).toBe(200);
|
|
167
|
+
expect(fs.existsSync(avatarDir(u.id))).toBe(false);
|
|
168
|
+
expect((await call(app, 'GET', url)).status).toBe(404);
|
|
169
|
+
expect(await avatarUrlOf(u.id)).toBeNull();
|
|
170
|
+
});
|
|
171
|
+
});
|
|
172
|
+
|
|
173
|
+
describe('upload limits', () => {
|
|
174
|
+
it('a 60 MP PNG → 422 IMAGE_TOO_LARGE (refused from its header, never decoded)', async () => {
|
|
175
|
+
const u = await registerUser(app, 'pixels');
|
|
176
|
+
const chunk = (type: string, data: Buffer): Buffer => {
|
|
177
|
+
const len = Buffer.alloc(4);
|
|
178
|
+
len.writeUInt32BE(data.length);
|
|
179
|
+
const body = Buffer.concat([Buffer.from(type), data]);
|
|
180
|
+
const crc = Buffer.alloc(4);
|
|
181
|
+
crc.writeUInt32BE(crc32(body) >>> 0);
|
|
182
|
+
return Buffer.concat([len, body, crc]);
|
|
183
|
+
};
|
|
184
|
+
const ihdr = Buffer.alloc(13);
|
|
185
|
+
ihdr.writeUInt32BE(8000, 0);
|
|
186
|
+
ihdr.writeUInt32BE(7500, 4);
|
|
187
|
+
ihdr[8] = 8;
|
|
188
|
+
ihdr[9] = 2;
|
|
189
|
+
const huge = Buffer.concat([
|
|
190
|
+
Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]),
|
|
191
|
+
chunk('IHDR', ihdr),
|
|
192
|
+
chunk('IDAT', deflateSync(Buffer.alloc(64))),
|
|
193
|
+
chunk('IEND', Buffer.alloc(0)),
|
|
194
|
+
]);
|
|
195
|
+
const r = await uploadAvatar(app, u.jar, huge, { filename: 'huge.png', type: 'image/png' });
|
|
196
|
+
expect([r.status, r.code]).toEqual([422, 'IMAGE_TOO_LARGE']);
|
|
197
|
+
});
|
|
198
|
+
|
|
199
|
+
it('an 11 MB file → 413 FILE_TOO_LARGE', async () => {
|
|
200
|
+
const u = await registerUser(app, 'bytes');
|
|
201
|
+
const r = await uploadAvatar(app, u.jar, Buffer.alloc(11 * 1024 * 1024, 7), { filename: 'big.jpg', type: 'image/jpeg' });
|
|
202
|
+
expect([r.status, r.code]).toEqual([413, 'FILE_TOO_LARGE']);
|
|
203
|
+
});
|
|
204
|
+
});
|
|
205
|
+
|
|
206
|
+
describe('account deletion', () => {
|
|
207
|
+
it('self-delete → the avatar URL is 404 at once, avatarUrl NULL, deletedAt set', async () => {
|
|
208
|
+
const x = await registerUser(app, 'selfdel');
|
|
209
|
+
const url = (await uploadAvatar(app, x.jar, await image('jpeg'))).body?.data?.avatarUrl as string;
|
|
210
|
+
expect((await call(app, 'GET', url)).status).toBe(200);
|
|
211
|
+
expect((await call(app, 'DELETE', '/users/me', { jar: x.jar, payload: { password: PASSWORD } })).status).toBe(200);
|
|
212
|
+
expect((await call(app, 'GET', url)).status).toBe(404);
|
|
213
|
+
const row = await (await db()).user.findUnique({ where: { id: x.id }, select: { avatarUrl: true, deletedAt: true } });
|
|
214
|
+
expect(row?.avatarUrl).toBeNull();
|
|
215
|
+
expect(row?.deletedAt).not.toBeNull();
|
|
216
|
+
});
|
|
217
|
+
|
|
218
|
+
it("an admin's delete → that avatar URL is 404 at once, avatarUrl NULL", async () => {
|
|
219
|
+
const y = await registerUser(app, 'admindel');
|
|
220
|
+
const url = (await uploadAvatar(app, y.jar, await image('png'))).body?.data?.avatarUrl as string;
|
|
221
|
+
expect((await call(app, 'DELETE', `/users/${y.id}`, { jar: admin.jar })).status).toBe(200);
|
|
222
|
+
expect((await call(app, 'GET', url)).status).toBe(404);
|
|
223
|
+
expect(await avatarUrlOf(y.id)).toBeNull();
|
|
224
|
+
});
|
|
225
|
+
|
|
226
|
+
it('the purge (31 days later) removes both upload tiers, then the row', async () => {
|
|
227
|
+
const x = await registerUser(app, 'purge');
|
|
228
|
+
await call(app, 'DELETE', '/users/me', { jar: x.jar, payload: { password: PASSWORD } });
|
|
229
|
+
const privateDir = path.join(integrationServices.uploadPrivateDir, 'users', x.id);
|
|
230
|
+
fs.mkdirSync(privateDir, { recursive: true });
|
|
231
|
+
fs.writeFileSync(path.join(privateDir, 'doc.txt'), 'private');
|
|
232
|
+
fs.mkdirSync(avatarDir(x.id), { recursive: true });
|
|
233
|
+
fs.writeFileSync(path.join(avatarDir(x.id), 'leftover.webp'), 'x'); // a stray public file the purge must also remove
|
|
234
|
+
await (await db()).user.update({ where: { id: x.id }, data: { deletedAt: new Date(Date.now() - 31 * 86_400_000) } });
|
|
235
|
+
|
|
236
|
+
const { purgeDeletedAccounts } = await import('@jobs/cleanup-deleted-accounts.job.js');
|
|
237
|
+
const result = await purgeDeletedAccounts();
|
|
238
|
+
expect(result.failed).toBe(0);
|
|
239
|
+
expect(await (await db()).user.count({ where: { id: x.id } })).toBe(0);
|
|
240
|
+
expect(fs.existsSync(privateDir)).toBe(false);
|
|
241
|
+
expect(fs.existsSync(path.join(integrationServices.uploadPublicDir, 'users', x.id))).toBe(false);
|
|
242
|
+
});
|
|
243
|
+
});
|
|
244
|
+
|
|
245
|
+
describe('password changes', () => {
|
|
246
|
+
it('your own change keeps this device (me and refresh 200) and ends the other one; 1 session left', async () => {
|
|
247
|
+
const z = await registerUser(app, 'ownpw');
|
|
248
|
+
const deviceB = await signIn(app, z.email);
|
|
249
|
+
const change = await call(app, 'PATCH', '/users/me/password', {
|
|
250
|
+
jar: z.jar,
|
|
251
|
+
payload: { currentPassword: PASSWORD, newPassword: 'New-Passw0rd-456!' },
|
|
252
|
+
});
|
|
253
|
+
expect(change.status).toBe(200);
|
|
254
|
+
expect((await call(app, 'GET', '/auth/me', { jar: z.jar })).status).toBe(200);
|
|
255
|
+
expect((await call(app, 'POST', '/auth/refresh', { jar: z.jar })).status).toBe(200);
|
|
256
|
+
const bMe = await call(app, 'GET', '/auth/me', { cookie: deviceB.header() });
|
|
257
|
+
expect([bMe.status, bMe.code]).toEqual([401, 'SESSION_EXPIRED']);
|
|
258
|
+
expect((await call(app, 'POST', '/auth/refresh', { cookie: deviceB.header() })).status).toBe(401);
|
|
259
|
+
expect(await (await db()).session.count({ where: { userId: z.id } })).toBe(1);
|
|
260
|
+
});
|
|
261
|
+
|
|
262
|
+
it("an admin's forced change ends both of that user's devices", async () => {
|
|
263
|
+
const w = await registerUser(app, 'forcedpw');
|
|
264
|
+
const wB = await signIn(app, w.email);
|
|
265
|
+
const forced = await call(app, 'PATCH', `/users/${w.id}/password`, { jar: admin.jar, payload: { newPassword: 'Forced-Passw0rd-789!' } });
|
|
266
|
+
expect(forced.status).toBe(200);
|
|
267
|
+
expect((await call(app, 'GET', '/auth/me', { cookie: w.jar.header() })).status).toBe(401);
|
|
268
|
+
expect((await call(app, 'GET', '/auth/me', { cookie: wB.header() })).status).toBe(401);
|
|
269
|
+
});
|
|
270
|
+
});
|
|
271
|
+
|
|
272
|
+
describe('who may change a user', () => {
|
|
273
|
+
it('another user → 403 (profile and avatar); an admin → 200; anonymous → 401', async () => {
|
|
274
|
+
const a = await registerUser(app, 'owner');
|
|
275
|
+
const b = await registerUser(app, 'stranger');
|
|
276
|
+
expect((await call(app, 'PATCH', `/users/${a.id}`, { jar: b.jar, payload: { firstName: 'Hacker' } })).status).toBe(403);
|
|
277
|
+
const byAdmin = await call(app, 'PATCH', `/users/${a.id}`, { jar: admin.jar, payload: { firstName: 'Fixed' } });
|
|
278
|
+
expect([byAdmin.status, byAdmin.body?.data?.firstName]).toEqual([200, 'Fixed']);
|
|
279
|
+
expect((await uploadAvatar(app, b.jar, await image('png'), { url: `/users/${a.id}/avatar` })).status).toBe(403);
|
|
280
|
+
expect((await call(app, 'PATCH', `/users/${a.id}`, { payload: { firstName: 'Anon' } })).status).toBe(401);
|
|
281
|
+
});
|
|
282
|
+
|
|
283
|
+
it("a private file: the owner 200 with its bytes, anonymous 401, another user 404, a traversal 404", async () => {
|
|
284
|
+
const owner = await registerUser(app, 'privowner');
|
|
285
|
+
const other = await registerUser(app, 'privother');
|
|
286
|
+
const dir = path.join(integrationServices.uploadPrivateDir, 'users', owner.id);
|
|
287
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
288
|
+
fs.writeFileSync(path.join(dir, 'note.txt'), 'owner only');
|
|
289
|
+
const own = await call(app, 'GET', '/files/note.txt', { jar: owner.jar });
|
|
290
|
+
expect([own.status, own.res.body]).toEqual([200, 'owner only']);
|
|
291
|
+
expect((await call(app, 'GET', '/files/note.txt')).status).toBe(401);
|
|
292
|
+
expect((await call(app, 'GET', '/files/note.txt', { jar: other.jar })).status).toBe(404);
|
|
293
|
+
expect((await call(app, 'GET', '/files/..%2F..%2Fpublic%2Fx', { jar: owner.jar })).status).toBe(404);
|
|
294
|
+
});
|
|
295
|
+
});
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The two avatar-related queries in users.repo: soft delete clears the avatar
|
|
3
|
+
* URL, and the avatar swap is a counted compare-and-swap that never touches a
|
|
4
|
+
* deleted account.
|
|
5
|
+
*/
|
|
6
|
+
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
|
7
|
+
import { prisma } from '@libs/prisma.js';
|
|
8
|
+
import { usersRepository } from '../users.repo.js';
|
|
9
|
+
|
|
10
|
+
vi.mock('@libs/prisma.js', () => ({
|
|
11
|
+
prisma: { user: { update: vi.fn(), updateMany: vi.fn() } },
|
|
12
|
+
}));
|
|
13
|
+
|
|
14
|
+
beforeEach(() => {
|
|
15
|
+
vi.clearAllMocks();
|
|
16
|
+
});
|
|
17
|
+
|
|
18
|
+
describe('usersRepository', () => {
|
|
19
|
+
it('softDeleteUser clears the avatar URL with the deletion', async () => {
|
|
20
|
+
await usersRepository.softDeleteUser('u1');
|
|
21
|
+
expect(prisma.user.update).toHaveBeenCalledWith({
|
|
22
|
+
where: { id: 'u1' },
|
|
23
|
+
data: { deletedAt: expect.any(Date), isActive: false, avatarUrl: null },
|
|
24
|
+
});
|
|
25
|
+
});
|
|
26
|
+
|
|
27
|
+
it('swapAvatarUrl changes the URL only if it is still the expected one, and says whether it did', async () => {
|
|
28
|
+
vi.mocked(prisma.user.updateMany).mockResolvedValueOnce({ count: 1 }).mockResolvedValueOnce({ count: 0 });
|
|
29
|
+
await expect(usersRepository.swapAvatarUrl('u1', '/old.webp', '/new.webp')).resolves.toBe(true);
|
|
30
|
+
await expect(usersRepository.swapAvatarUrl('u1', null, '/new.webp')).resolves.toBe(false);
|
|
31
|
+
expect(prisma.user.updateMany).toHaveBeenNthCalledWith(1, {
|
|
32
|
+
where: { id: 'u1', deletedAt: null, avatarUrl: '/old.webp' },
|
|
33
|
+
data: { avatarUrl: '/new.webp' },
|
|
34
|
+
});
|
|
35
|
+
expect(vi.mocked(prisma.user.updateMany).mock.calls[1]?.[0]?.where).toMatchObject({ avatarUrl: null });
|
|
36
|
+
});
|
|
37
|
+
});
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Password confirmation in users.service: a wrong password is wrong INPUT
|
|
3
|
+
* (422 with its own code), never 401. A 401 tells the client "your session
|
|
4
|
+
* expired", which made it run a pointless token refresh.
|
|
5
|
+
*/
|
|
6
|
+
import { describe, expect, it, vi, beforeEach } from 'vitest';
|
|
7
|
+
import { usersService } from '../users.service.js';
|
|
8
|
+
import * as authRepo from '@modules/auth/auth.repo.js';
|
|
9
|
+
import { sessionRepository } from '@modules/auth/session.repo.js';
|
|
10
|
+
import { usersRepository } from '../users.repo.js';
|
|
11
|
+
import { hashPassword, verifyPassword } from '@libs/password.js';
|
|
12
|
+
import { fileStorageService } from '@libs/storage/file-storage.service.js';
|
|
13
|
+
import { testUsers } from '@/test/setup.js';
|
|
14
|
+
|
|
15
|
+
vi.mock('@modules/auth/auth.repo.js');
|
|
16
|
+
vi.mock('@modules/auth/session.repo.js');
|
|
17
|
+
vi.mock('../users.repo.js');
|
|
18
|
+
vi.mock('@libs/password.js');
|
|
19
|
+
vi.mock('@libs/storage/file-storage.service.js', () => ({ fileStorageService: { deleteAvatar: vi.fn() } }));
|
|
20
|
+
vi.mock('@libs/storage/image-optimizer.service.js', () => ({ imageOptimizerService: {} }));
|
|
21
|
+
|
|
22
|
+
const user = testUsers.validUser;
|
|
23
|
+
|
|
24
|
+
describe('users.service password confirmation', () => {
|
|
25
|
+
beforeEach(() => {
|
|
26
|
+
vi.clearAllMocks();
|
|
27
|
+
vi.mocked(authRepo.findUserById).mockResolvedValue(user);
|
|
28
|
+
vi.mocked(hashPassword).mockResolvedValue('new-hash');
|
|
29
|
+
});
|
|
30
|
+
|
|
31
|
+
it('changePassword with a wrong current password answers 422 INVALID_CURRENT_PASSWORD and changes nothing', async () => {
|
|
32
|
+
vi.mocked(verifyPassword).mockResolvedValue(false);
|
|
33
|
+
await expect(
|
|
34
|
+
usersService.changePassword(user.id, { currentPassword: 'wrong', newPassword: 'New-Passw0rd-123!' }),
|
|
35
|
+
).rejects.toMatchObject({ statusCode: 422, code: 'INVALID_CURRENT_PASSWORD', message: 'Current password is incorrect' });
|
|
36
|
+
expect(authRepo.updateUserPassword).not.toHaveBeenCalled();
|
|
37
|
+
expect(sessionRepository.deleteAllUserSessions).not.toHaveBeenCalled();
|
|
38
|
+
});
|
|
39
|
+
|
|
40
|
+
it('changePassword with the right current password still changes it and ends all sessions', async () => {
|
|
41
|
+
// First call: current password matches; second: the new one differs from it.
|
|
42
|
+
vi.mocked(verifyPassword).mockResolvedValueOnce(true).mockResolvedValueOnce(false);
|
|
43
|
+
await usersService.changePassword(user.id, { currentPassword: 'right', newPassword: 'New-Passw0rd-123!' });
|
|
44
|
+
expect(authRepo.updateUserPassword).toHaveBeenCalledWith(user.id, 'new-hash');
|
|
45
|
+
expect(sessionRepository.deleteAllUserSessions).toHaveBeenCalledWith(user.id);
|
|
46
|
+
});
|
|
47
|
+
|
|
48
|
+
it('deleteAccount with a wrong password answers 422 INVALID_PASSWORD and deletes nothing', async () => {
|
|
49
|
+
vi.mocked(verifyPassword).mockResolvedValue(false);
|
|
50
|
+
await expect(usersService.deleteAccount(user.id, 'wrong')).rejects.toMatchObject({
|
|
51
|
+
statusCode: 422,
|
|
52
|
+
code: 'INVALID_PASSWORD',
|
|
53
|
+
message: 'Incorrect password',
|
|
54
|
+
});
|
|
55
|
+
expect(usersRepository.softDeleteUser).not.toHaveBeenCalled();
|
|
56
|
+
});
|
|
57
|
+
|
|
58
|
+
it('deleteAccount with the right password still soft-deletes and ends all sessions', async () => {
|
|
59
|
+
vi.mocked(verifyPassword).mockResolvedValue(true);
|
|
60
|
+
await usersService.deleteAccount(user.id, 'right');
|
|
61
|
+
expect(usersRepository.softDeleteUser).toHaveBeenCalledWith(user.id);
|
|
62
|
+
expect(sessionRepository.deleteAllUserSessions).toHaveBeenCalledWith(user.id);
|
|
63
|
+
});
|
|
64
|
+
|
|
65
|
+
it('deleteAccount removes the public avatar at once, after the soft delete', async () => {
|
|
66
|
+
vi.mocked(verifyPassword).mockResolvedValue(true);
|
|
67
|
+
await usersService.deleteAccount(user.id, 'right');
|
|
68
|
+
expect(fileStorageService.deleteAvatar).toHaveBeenCalledWith(user.id);
|
|
69
|
+
const softDeletedAt = vi.mocked(usersRepository.softDeleteUser).mock.invocationCallOrder[0];
|
|
70
|
+
expect(vi.mocked(fileStorageService.deleteAvatar).mock.invocationCallOrder[0]).toBeGreaterThan(softDeletedAt);
|
|
71
|
+
});
|
|
72
|
+
|
|
73
|
+
it('an admin deleting an account removes its public avatar too', async () => {
|
|
74
|
+
await usersService.deleteAccount(user.id, '', true);
|
|
75
|
+
expect(fileStorageService.deleteAvatar).toHaveBeenCalledWith(user.id);
|
|
76
|
+
});
|
|
77
|
+
|
|
78
|
+
it('deleteAccount still succeeds when the avatar file cannot be removed (the purge retries)', async () => {
|
|
79
|
+
vi.mocked(verifyPassword).mockResolvedValue(true);
|
|
80
|
+
vi.mocked(fileStorageService.deleteAvatar).mockRejectedValueOnce(new Error('disk'));
|
|
81
|
+
await expect(usersService.deleteAccount(user.id, 'right')).resolves.toBeUndefined();
|
|
82
|
+
expect(usersRepository.softDeleteUser).toHaveBeenCalledWith(user.id);
|
|
83
|
+
});
|
|
84
|
+
|
|
85
|
+
it("an owner's password change keeps the asking device signed in and ends every other session", async () => {
|
|
86
|
+
vi.mocked(verifyPassword).mockResolvedValueOnce(true).mockResolvedValueOnce(false);
|
|
87
|
+
await usersService.changePassword(user.id, { currentPassword: 'right', newPassword: 'New-Passw0rd-123!' }, false, 'session-here');
|
|
88
|
+
expect(sessionRepository.deleteOtherUserSessions).toHaveBeenCalledWith(user.id, 'session-here');
|
|
89
|
+
expect(authRepo.deleteRefreshTokensByUserId).toHaveBeenCalledWith(user.id, { exceptSessionId: 'session-here' });
|
|
90
|
+
expect(sessionRepository.deleteAllUserSessions).not.toHaveBeenCalled();
|
|
91
|
+
});
|
|
92
|
+
|
|
93
|
+
it('an admin-forced password change still ends every session of that user', async () => {
|
|
94
|
+
vi.mocked(verifyPassword).mockResolvedValue(false); // only the "same as current" check runs
|
|
95
|
+
await usersService.changePassword(user.id, { newPassword: 'New-Passw0rd-123!' }, true, 'admins-own-session');
|
|
96
|
+
expect(sessionRepository.deleteAllUserSessions).toHaveBeenCalledWith(user.id);
|
|
97
|
+
expect(authRepo.deleteRefreshTokensByUserId).toHaveBeenCalledWith(user.id);
|
|
98
|
+
expect(sessionRepository.deleteOtherUserSessions).not.toHaveBeenCalled();
|
|
99
|
+
});
|
|
100
|
+
|
|
101
|
+
it('the last active admin cannot delete their own account (409 LAST_ADMIN), and nothing is deleted', async () => {
|
|
102
|
+
vi.mocked(authRepo.findUserById).mockResolvedValue({ ...user, role: 'ADMIN' });
|
|
103
|
+
vi.mocked(verifyPassword).mockResolvedValue(true);
|
|
104
|
+
vi.mocked(usersRepository.countOtherActiveAdmins).mockResolvedValue(0);
|
|
105
|
+
await expect(usersService.deleteAccount(user.id, 'right')).rejects.toMatchObject({ statusCode: 409, code: 'LAST_ADMIN' });
|
|
106
|
+
expect(usersRepository.softDeleteUser).not.toHaveBeenCalled();
|
|
107
|
+
});
|
|
108
|
+
|
|
109
|
+
it('an admin can delete their own account when another active admin exists', async () => {
|
|
110
|
+
vi.mocked(authRepo.findUserById).mockResolvedValue({ ...user, role: 'ADMIN' });
|
|
111
|
+
vi.mocked(verifyPassword).mockResolvedValue(true);
|
|
112
|
+
vi.mocked(usersRepository.countOtherActiveAdmins).mockResolvedValue(1);
|
|
113
|
+
await usersService.deleteAccount(user.id, 'right');
|
|
114
|
+
expect(usersRepository.softDeleteUser).toHaveBeenCalledWith(user.id);
|
|
115
|
+
});
|
|
116
|
+
|
|
117
|
+
it('a wrong password still answers 422 first, even for the last admin', async () => {
|
|
118
|
+
vi.mocked(authRepo.findUserById).mockResolvedValue({ ...user, role: 'ADMIN' });
|
|
119
|
+
vi.mocked(verifyPassword).mockResolvedValue(false);
|
|
120
|
+
await expect(usersService.deleteAccount(user.id, 'wrong')).rejects.toMatchObject({ code: 'INVALID_PASSWORD' });
|
|
121
|
+
expect(usersRepository.countOtherActiveAdmins).not.toHaveBeenCalled();
|
|
122
|
+
});
|
|
123
|
+
|
|
124
|
+
it('a normal user never triggers the admin check', async () => {
|
|
125
|
+
vi.mocked(verifyPassword).mockResolvedValue(true);
|
|
126
|
+
await usersService.deleteAccount(user.id, 'right');
|
|
127
|
+
expect(usersRepository.countOtherActiveAdmins).not.toHaveBeenCalled();
|
|
128
|
+
});
|
|
129
|
+
});
|
|
@@ -5,13 +5,12 @@
|
|
|
5
5
|
*/
|
|
6
6
|
|
|
7
7
|
import type { FastifyRequest, FastifyReply } from 'fastify';
|
|
8
|
-
import path from 'path';
|
|
9
8
|
import { usersService } from './users.service.js';
|
|
10
9
|
import { validateImageFile, validateFileSize } from '@libs/storage/file-validator.js';
|
|
11
10
|
import { successResponse } from '@shared/responses/successResponse.js';
|
|
12
11
|
import { clearAuthCookies } from '@libs/cookies.js';
|
|
13
12
|
import { ChangePasswordSchema, AdminChangePasswordSchema, DeleteAccountSchema } from './users.schemas.js';
|
|
14
|
-
import type {
|
|
13
|
+
import type { UpdateProfileInput } from './users.schemas.js';
|
|
15
14
|
import type { AuthenticatedRequest } from '@shared/types/index.js';
|
|
16
15
|
import { logger } from '@libs/logger.js';
|
|
17
16
|
import { BadRequestError } from '@shared/errors/errors.js';
|
|
@@ -40,14 +39,15 @@ class UsersController {
|
|
|
40
39
|
throw new BadRequestError('No file uploaded', 'NO_FILE');
|
|
41
40
|
}
|
|
42
41
|
|
|
43
|
-
//
|
|
42
|
+
// A file must be present. Its format is judged from the bytes later
|
|
43
|
+
// (imageOptimizerService); the browser-sent type and name are not trusted.
|
|
44
44
|
validateImageFile(data);
|
|
45
45
|
|
|
46
46
|
// Read file buffer
|
|
47
47
|
const buffer = await data.toBuffer();
|
|
48
48
|
|
|
49
|
-
// Validate file size
|
|
50
|
-
validateFileSize(buffer);
|
|
49
|
+
// Validate file size, including a file the parser silently cut at the limit
|
|
50
|
+
validateFileSize(buffer, data.file.truncated);
|
|
51
51
|
|
|
52
52
|
// Get target user ID (set by resolveMe or resolveTargetUser middleware)
|
|
53
53
|
const userId = request.targetUserId!;
|
|
@@ -61,13 +61,9 @@ class UsersController {
|
|
|
61
61
|
});
|
|
62
62
|
|
|
63
63
|
// Call service to process and save avatar
|
|
64
|
-
const
|
|
64
|
+
const { avatarUrl } = await usersService.uploadAvatar(userId, buffer, data.filename);
|
|
65
65
|
|
|
66
|
-
return reply.send(
|
|
67
|
-
successResponse('Avatar uploaded successfully', {
|
|
68
|
-
avatarUrl: updatedUser.avatarUrl,
|
|
69
|
-
})
|
|
70
|
-
);
|
|
66
|
+
return reply.send(successResponse('Avatar uploaded successfully', { avatarUrl }));
|
|
71
67
|
}
|
|
72
68
|
|
|
73
69
|
/**
|
|
@@ -91,32 +87,6 @@ class UsersController {
|
|
|
91
87
|
return reply.send(successResponse('Avatar deleted successfully', null));
|
|
92
88
|
}
|
|
93
89
|
|
|
94
|
-
/**
|
|
95
|
-
* Get avatar handler
|
|
96
|
-
*
|
|
97
|
-
* GET /api/v1/users/:userId/avatar
|
|
98
|
-
* Auth: Not required (public endpoint)
|
|
99
|
-
*
|
|
100
|
-
* Returns the avatar file directly or 404 if not found.
|
|
101
|
-
*
|
|
102
|
-
* @param request - Fastify request
|
|
103
|
-
* @param reply - Fastify reply
|
|
104
|
-
*/
|
|
105
|
-
async getAvatar(
|
|
106
|
-
request: FastifyRequest<{ Params: GetUserAvatarParams }>,
|
|
107
|
-
reply: FastifyReply
|
|
108
|
-
): Promise<void> {
|
|
109
|
-
const { userId } = request.params;
|
|
110
|
-
|
|
111
|
-
logger.info({ msg: 'Avatar fetch request', userId });
|
|
112
|
-
|
|
113
|
-
// Get avatar file path
|
|
114
|
-
const { path: filePath } = await usersService.getAvatar(userId);
|
|
115
|
-
|
|
116
|
-
// Send file directly
|
|
117
|
-
return reply.sendFile(path.basename(filePath), path.dirname(filePath));
|
|
118
|
-
}
|
|
119
|
-
|
|
120
90
|
/**
|
|
121
91
|
* Update profile handler
|
|
122
92
|
*
|
|
@@ -163,7 +133,8 @@ class UsersController {
|
|
|
163
133
|
} else {
|
|
164
134
|
const parsed = ChangePasswordSchema.parse(request.body);
|
|
165
135
|
logger.info({ msg: 'Change password request', userId });
|
|
166
|
-
|
|
136
|
+
// Keep the device that asked signed in; every other session ends.
|
|
137
|
+
await usersService.changePassword(userId, parsed, false, request.user.sessionId);
|
|
167
138
|
}
|
|
168
139
|
|
|
169
140
|
return reply.send(successResponse('Password changed successfully', null));
|
|
@@ -53,14 +53,18 @@ class UsersRepository {
|
|
|
53
53
|
}
|
|
54
54
|
|
|
55
55
|
/**
|
|
56
|
-
*
|
|
56
|
+
* Compare-and-swap of the avatar URL: sets `next` only if the stored URL is
|
|
57
|
+
* still `expected` (null matches "no avatar"). Returns whether THIS call made
|
|
58
|
+
* the change. One counted UPDATE, so of two parallel uploads exactly one
|
|
59
|
+
* replaces any given URL, and only that one deletes the replaced file (see
|
|
60
|
+
* usersService.uploadAvatar). Deleted accounts never match.
|
|
57
61
|
*/
|
|
58
|
-
async
|
|
59
|
-
|
|
60
|
-
where: { id: userId },
|
|
61
|
-
data: { avatarUrl },
|
|
62
|
-
select: userSelect,
|
|
62
|
+
async swapAvatarUrl(userId: string, expected: string | null, next: string): Promise<boolean> {
|
|
63
|
+
const { count } = await prisma.user.updateMany({
|
|
64
|
+
where: { id: userId, deletedAt: null, avatarUrl: expected },
|
|
65
|
+
data: { avatarUrl: next },
|
|
63
66
|
});
|
|
67
|
+
return count === 1;
|
|
64
68
|
}
|
|
65
69
|
|
|
66
70
|
/**
|
|
@@ -89,7 +93,18 @@ class UsersRepository {
|
|
|
89
93
|
}
|
|
90
94
|
|
|
91
95
|
/**
|
|
92
|
-
*
|
|
96
|
+
* How many OTHER admins could still manage the project: role ADMIN, not
|
|
97
|
+
* banned, not deleted. Zero means `userId` is the last one.
|
|
98
|
+
*/
|
|
99
|
+
async countOtherActiveAdmins(userId: string): Promise<number> {
|
|
100
|
+
return prisma.user.count({
|
|
101
|
+
where: { role: 'ADMIN', isActive: true, deletedAt: null, id: { not: userId } },
|
|
102
|
+
});
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/**
|
|
106
|
+
* Soft deletes a user: deletedAt set, isActive = false, and the avatar URL
|
|
107
|
+
* cleared (its file is removed right after, see usersService.deleteAccount).
|
|
93
108
|
*/
|
|
94
109
|
async softDeleteUser(userId: string): Promise<void> {
|
|
95
110
|
await prisma.user.update({
|
|
@@ -97,6 +112,7 @@ class UsersRepository {
|
|
|
97
112
|
data: {
|
|
98
113
|
deletedAt: new Date(),
|
|
99
114
|
isActive: false,
|
|
115
|
+
avatarUrl: null,
|
|
100
116
|
},
|
|
101
117
|
});
|
|
102
118
|
}
|
|
@@ -7,7 +7,6 @@
|
|
|
7
7
|
import type { FastifyInstance } from 'fastify';
|
|
8
8
|
import { usersController } from './users.controller.js';
|
|
9
9
|
import {
|
|
10
|
-
GetUserAvatarSchema,
|
|
11
10
|
UserIdParamSchema,
|
|
12
11
|
UpdateProfileSchema,
|
|
13
12
|
ChangePasswordSchema,
|
|
@@ -25,13 +24,15 @@ import { RATE_LIMITS } from '@config/rate-limit.config.js';
|
|
|
25
24
|
* - DELETE /users/me - Delete account (authenticated)
|
|
26
25
|
* - POST /users/avatar - Upload avatar (authenticated)
|
|
27
26
|
* - DELETE /users/avatar - Delete avatar (authenticated)
|
|
28
|
-
* - GET /users/:userId/avatar - Get avatar (public)
|
|
29
27
|
* - PATCH /users/:userId - Update profile (owner or admin)
|
|
30
28
|
* - PATCH /users/:userId/password - Change password (owner or admin)
|
|
31
29
|
* - DELETE /users/:userId - Delete account (owner or admin)
|
|
32
30
|
* - POST /users/:userId/avatar - Upload avatar (owner or admin)
|
|
33
31
|
* - DELETE /users/:userId/avatar - Delete avatar (owner or admin)
|
|
34
32
|
*
|
|
33
|
+
* Avatars are read from their public URL (/uploads/users/{id}/avatar/...,
|
|
34
|
+
* served statically by app.ts), never through a /users route.
|
|
35
|
+
*
|
|
35
36
|
* @param fastify - Fastify instance
|
|
36
37
|
*/
|
|
37
38
|
export async function usersRoutes(fastify: FastifyInstance): Promise<void> {
|
|
@@ -143,26 +144,6 @@ export async function usersRoutes(fastify: FastifyInstance): Promise<void> {
|
|
|
143
144
|
usersController.deleteAvatar.bind(usersController)
|
|
144
145
|
);
|
|
145
146
|
|
|
146
|
-
/**
|
|
147
|
-
* Get user avatar
|
|
148
|
-
*
|
|
149
|
-
* GET /api/v1/users/:userId/avatar
|
|
150
|
-
* Auth: Not required (public)
|
|
151
|
-
* Rate limit: 100 requests per minute per IP
|
|
152
|
-
*/
|
|
153
|
-
fastify.get<{ Params: { userId: string } }>(
|
|
154
|
-
'/users/:userId/avatar',
|
|
155
|
-
{
|
|
156
|
-
schema: {
|
|
157
|
-
params: GetUserAvatarSchema,
|
|
158
|
-
},
|
|
159
|
-
config: {
|
|
160
|
-
rateLimit: RATE_LIMITS.USERS_GET_AVATAR,
|
|
161
|
-
},
|
|
162
|
-
},
|
|
163
|
-
usersController.getAvatar.bind(usersController)
|
|
164
|
-
);
|
|
165
|
-
|
|
166
147
|
// --- /users/:userId variants (owner or admin) ---
|
|
167
148
|
|
|
168
149
|
/**
|