create-tigra 4.1.0 → 5.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +20 -0
- package/README.md +4 -1
- package/bin/create-tigra.js +68 -73
- package/lib/installer-transaction.js +275 -0
- package/lib/patchers/diagnostics.patcher.js +33 -59
- package/lib/patchers/email-verification.patcher.js +86 -92
- package/lib/patchers/metrics.patcher.js +18 -18
- package/lib/project-files.js +99 -0
- package/modules/diagnostics/diagnostics.md +10 -0
- package/modules/diagnostics/prisma/diagnostic-hourly-view.sql +24 -0
- package/modules/diagnostics/prisma/migration.sql +1 -24
- package/modules/diagnostics/server/__tests__/diagnostics.integration.test.ts +18 -2
- package/modules/diagnostics/server/diagnostics.repo.ts +12 -2
- package/modules/diagnostics/server/diagnostics.routes.ts +1 -2
- package/modules/email-verification/client/hooks/useVerification.ts +4 -7
- package/modules/email-verification/server/__tests__/verification.integration.test.ts +17 -0
- package/modules/email-verification/server/__tests__/verification.service.test.ts +71 -0
- package/modules/email-verification/server/verification.service.ts +102 -157
- package/modules/metrics/client/WebVitalsReporter.tsx +2 -0
- package/modules/metrics/client/__tests__/WebVitalsReporter.test.ts +1 -0
- package/modules/metrics/performance.md +2 -2
- package/modules/metrics/server/__tests__/metrics.collector.test.ts +22 -0
- package/modules/metrics/server/metrics.collector.ts +6 -3
- package/modules/metrics/server/metrics.routes.ts +1 -2
- package/modules/metrics/server/metrics.service.ts +6 -2
- package/package.json +1 -1
- package/template/AGENTS.md +4 -3
- package/template/client/.dockerignore +2 -5
- package/template/client/gitignore +43 -0
- package/template/client/package-lock.json +51 -51
- package/template/client/package.json +2 -2
- package/template/client/src/features/auth/components/AuthInitializer.tsx +45 -7
- package/template/client/src/features/auth/hooks/useAuth.ts +10 -33
- package/template/client/src/features/auth/hooks/useCurrentUser.ts +3 -3
- package/template/client/src/features/auth/hooks/useSessionTransition.ts +51 -0
- package/template/client/src/features/auth/services/auth.service.ts +3 -2
- package/template/client/src/features/auth/store/authSlice.ts +11 -8
- package/template/client/src/features/auth/types/auth.types.ts +1 -0
- package/template/client/src/lib/api/__tests__/axios.config.test.ts +17 -0
- package/template/client/src/lib/api/__tests__/session-events.test.ts +23 -0
- package/template/client/src/lib/api/axios.config.ts +24 -6
- package/template/client/src/lib/api/session-events.ts +54 -0
- package/template/client/src/lib/observability/sentry-scrub.ts +63 -46
- package/template/client/src/store/__tests__/store.test.ts +1 -0
- package/template/gitignore +3 -2
- package/template/server/.dockerignore +2 -5
- package/template/server/.env.example +1 -0
- package/template/server/.env.example.production +1 -0
- package/template/server/README.md +7 -2
- package/template/server/docs/deployment.md +66 -0
- package/template/server/docs/logging.md +9 -8
- package/template/server/docs/rate-limits.md +6 -4
- package/template/server/gitignore +33 -0
- package/template/server/prisma/migrations/0_init/migration.sql +25 -0
- package/template/server/prisma/retrofits/20261116000000_retired_refresh_tokens/migration.sql +13 -0
- package/template/server/prisma/retrofits/20261116000100_avatar_cleanup/migration.sql +9 -0
- package/template/server/prisma/retrofits/20261117000000_account_purge/migration.sql +1 -0
- package/template/server/prisma/schema.prisma +25 -1
- package/template/server/src/__tests__/routes.integration.test.ts +5 -2
- package/template/server/src/app.ts +14 -5
- package/template/server/src/config/env.ts +8 -0
- package/template/server/src/config/rate-limit.config.ts +1 -1
- package/template/server/src/jobs/__tests__/cleanup-deleted-accounts.job.test.ts +26 -9
- package/template/server/src/jobs/__tests__/cleanup-expired-auth.job.test.ts +2 -1
- package/template/server/src/jobs/__tests__/jobs.integration.test.ts +51 -5
- package/template/server/src/jobs/cleanup-deleted-accounts.job.ts +30 -34
- package/template/server/src/jobs/cleanup-expired-auth.job.ts +2 -0
- package/template/server/src/jobs/index.ts +8 -2
- package/template/server/src/libs/__tests__/auth.test.ts +1 -1
- package/template/server/src/libs/__tests__/cookies.test.ts +16 -0
- package/template/server/src/libs/__tests__/error-handler.test.ts +20 -1
- package/template/server/src/libs/__tests__/http.test.ts +10 -10
- package/template/server/src/libs/__tests__/ip-block.test.ts +39 -7
- package/template/server/src/libs/__tests__/logger.test.ts +10 -1
- package/template/server/src/libs/__tests__/monitoring.test.ts +19 -0
- package/template/server/src/libs/__tests__/outbound.integration.test.ts +7 -10
- package/template/server/src/libs/__tests__/rate-limits.integration.test.ts +32 -3
- package/template/server/src/libs/__tests__/requestLogger.test.ts +9 -1
- package/template/server/src/libs/__tests__/safe-http.test.ts +65 -3
- package/template/server/src/libs/__tests__/sentry-scrub.test.ts +22 -6
- package/template/server/src/libs/__tests__/url-safety.test.ts +3 -1
- package/template/server/src/libs/account-mutation.ts +77 -0
- package/template/server/src/libs/auth.ts +37 -3
- package/template/server/src/libs/cookies.ts +25 -13
- package/template/server/src/libs/email-quota.ts +11 -7
- package/template/server/src/libs/email.ts +11 -8
- package/template/server/src/libs/error-handler.ts +16 -12
- package/template/server/src/libs/http.ts +37 -13
- package/template/server/src/libs/ip-block.ts +56 -34
- package/template/server/src/libs/logger.ts +23 -8
- package/template/server/src/libs/monitoring.ts +57 -31
- package/template/server/src/libs/observability/sentry.ts +65 -49
- package/template/server/src/libs/prisma.ts +1 -1
- package/template/server/src/libs/private-cache.ts +6 -0
- package/template/server/src/libs/rate-limiting.ts +4 -0
- package/template/server/src/libs/requestLogger.ts +3 -3
- package/template/server/src/libs/safe-http.ts +58 -18
- package/template/server/src/libs/storage/__tests__/upload-persistence.test.ts +15 -2
- package/template/server/src/libs/storage/file-storage.service.ts +59 -109
- package/template/server/src/libs/storage/file-validator.ts +2 -1
- package/template/server/src/libs/url-safety.ts +10 -2
- package/template/server/src/libs/validation-errors.ts +11 -8
- package/template/server/src/modules/admin/__tests__/admin.repo.test.ts +21 -4
- package/template/server/src/modules/admin/__tests__/admin.schemas.test.ts +11 -0
- package/template/server/src/modules/admin/__tests__/admin.service.test.ts +83 -40
- package/template/server/src/modules/admin/admin.controller.ts +4 -4
- package/template/server/src/modules/admin/admin.repo.ts +37 -54
- package/template/server/src/modules/admin/admin.routes.ts +3 -5
- package/template/server/src/modules/admin/admin.schemas.ts +3 -6
- package/template/server/src/modules/admin/admin.service.ts +61 -62
- package/template/server/src/modules/auth/__tests__/auth.schemas.test.ts +12 -0
- package/template/server/src/modules/auth/__tests__/auth.service.test.ts +58 -295
- package/template/server/src/modules/auth/__tests__/recovery.integration.test.ts +177 -0
- package/template/server/src/modules/auth/__tests__/recovery.queue.test.ts +159 -0
- package/template/server/src/modules/auth/__tests__/session-cleanup.test.ts +5 -10
- package/template/server/src/modules/auth/__tests__/sessions.integration.test.ts +1 -1
- package/template/server/src/modules/auth/__tests__/token-fingerprints.test.ts +115 -44
- package/template/server/src/modules/auth/auth-link-store.ts +64 -0
- package/template/server/src/modules/auth/auth-mail-queue.ts +124 -0
- package/template/server/src/modules/auth/auth.controller.ts +16 -5
- package/template/server/src/modules/auth/auth.repo.ts +152 -61
- package/template/server/src/modules/auth/auth.routes.ts +4 -0
- package/template/server/src/modules/auth/auth.schemas.ts +7 -3
- package/template/server/src/modules/auth/auth.service.ts +33 -237
- package/template/server/src/modules/auth/recovery.queue.ts +44 -0
- package/template/server/src/modules/auth/recovery.store.ts +7 -0
- package/template/server/src/modules/auth/session.repo.ts +5 -4
- package/template/server/src/modules/files/__tests__/files.integration.test.ts +29 -1
- package/template/server/src/modules/files/files.controller.ts +2 -2
- package/template/server/src/modules/users/__tests__/avatar-cleanup.test.ts +49 -0
- package/template/server/src/modules/users/__tests__/avatar-controller.test.ts +50 -0
- package/template/server/src/modules/users/__tests__/avatar-upload.test.ts +56 -105
- package/template/server/src/modules/users/__tests__/users.integration.test.ts +2 -2
- package/template/server/src/modules/users/__tests__/users.repo.test.ts +8 -11
- package/template/server/src/modules/users/__tests__/users.service.test.ts +116 -44
- package/template/server/src/modules/users/avatar-cleanup.ts +70 -0
- package/template/server/src/modules/users/users.controller.ts +28 -25
- package/template/server/src/modules/users/users.repo.ts +12 -51
- package/template/server/src/modules/users/users.service.ts +109 -234
- package/template/server/src/shared/responses/paginatedResponse.ts +4 -1
- package/template/server/src/shared/schemas/pagination.schema.ts +5 -1
- package/template/server/src/test/setup.ts +4 -0
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import { createHmac } from 'node:crypto';
|
|
2
|
+
import type { FastifyInstance } from 'fastify';
|
|
3
|
+
import { env } from '@config/env.js';
|
|
4
|
+
import { sendEmail } from '@libs/email.js';
|
|
5
|
+
import { enqueueAuthMail, startAuthMailWorker } from './auth-mail-queue.js';
|
|
6
|
+
import { findUserByEmail } from './auth.repo.js';
|
|
7
|
+
import { issueRecoveryToken } from './recovery.store.js';
|
|
8
|
+
|
|
9
|
+
const stream = 'pw-recovery:jobs';
|
|
10
|
+
const group = 'password-recovery';
|
|
11
|
+
|
|
12
|
+
export function enqueueRecovery(email: string): Promise<void> {
|
|
13
|
+
return enqueueAuthMail(stream, email, 'public', 1_000, 'Password reset');
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
async function deliver(id: string, email: string): Promise<void> {
|
|
17
|
+
const user = await findUserByEmail(email);
|
|
18
|
+
if (!user) return;
|
|
19
|
+
|
|
20
|
+
// The job ID and account pin the same link across retries. The scoped HMAC
|
|
21
|
+
// keeps the link unpredictable to anyone who can only read Redis.
|
|
22
|
+
const token = createHmac('sha256', env.JWT_SECRET)
|
|
23
|
+
.update(`tigra/password-recovery/v1/${id}/${user.id}`)
|
|
24
|
+
.digest('hex');
|
|
25
|
+
if (!await issueRecoveryToken(user.id, token, id)) return;
|
|
26
|
+
|
|
27
|
+
const link = `${env.CLIENT_URL}/reset-password?token=${token}`;
|
|
28
|
+
// Redis IDs can overlap across deployments that share one Resend account.
|
|
29
|
+
const deliveryKey = createHmac('sha256', env.JWT_SECRET)
|
|
30
|
+
.update(`tigra/password-recovery-delivery/v1/${env.CLIENT_URL}/${id}`)
|
|
31
|
+
.digest('hex');
|
|
32
|
+
await sendEmail({
|
|
33
|
+
to: user.email,
|
|
34
|
+
subject: 'Reset your password',
|
|
35
|
+
html: `<p>We received a request to reset your password.</p>
|
|
36
|
+
<p><a href="${link}">Reset password</a></p>
|
|
37
|
+
<p>The link expires in one hour. If you did not request a reset, you can ignore this email.</p>`,
|
|
38
|
+
idempotencyKey: `password-recovery/${deliveryKey}`,
|
|
39
|
+
});
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export function startPasswordRecoveryJob(app: FastifyInstance): void {
|
|
43
|
+
startAuthMailWorker(app, stream, group, deliver);
|
|
44
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { authLinkStore } from './auth-link-store.js';
|
|
2
|
+
|
|
3
|
+
const recoveryLinks = authLinkStore('pw-reset:', 'pw-reset-user:', 'pw-reset-order:');
|
|
4
|
+
|
|
5
|
+
export const issueRecoveryToken = recoveryLinks.issue;
|
|
6
|
+
export const findRecoveryOwner = recoveryLinks.findOwner;
|
|
7
|
+
export const consumeRecoveryToken = recoveryLinks.consume;
|
|
@@ -1,17 +1,18 @@
|
|
|
1
1
|
import { prisma, isPrismaNotFound } from '@libs/prisma.js';
|
|
2
|
-
import type { Session } from '@prisma/client';
|
|
2
|
+
import type { Prisma, Session } from '@prisma/client';
|
|
3
3
|
|
|
4
4
|
export class SessionRepository {
|
|
5
5
|
/**
|
|
6
|
-
* Create a
|
|
6
|
+
* Create a session in the caller's transaction when issuing credentials
|
|
7
|
+
* as part of an account state change.
|
|
7
8
|
*/
|
|
8
9
|
async createSession(data: {
|
|
9
10
|
userId: string;
|
|
10
11
|
deviceInfo?: string;
|
|
11
12
|
ipAddress?: string;
|
|
12
13
|
expiresAt: Date;
|
|
13
|
-
}): Promise<Session> {
|
|
14
|
-
return
|
|
14
|
+
}, db: Prisma.TransactionClient = prisma): Promise<Session> {
|
|
15
|
+
return db.session.create({
|
|
15
16
|
data: {
|
|
16
17
|
userId: data.userId,
|
|
17
18
|
deviceInfo: data.deviceInfo,
|
|
@@ -78,6 +78,7 @@ beforeAll(async () => {
|
|
|
78
78
|
const publicAvatarDir = path.join(integrationServices.uploadPublicDir, 'users', userId, 'avatar');
|
|
79
79
|
await fs.mkdir(publicAvatarDir, { recursive: true });
|
|
80
80
|
await fs.writeFile(path.join(publicAvatarDir, 'x.webp'), Buffer.from('PUBLIC-AVATAR-BYTES'));
|
|
81
|
+
await fs.writeFile(path.join(integrationServices.uploadPublicDir, 'public-note.txt'), 'public fixture');
|
|
81
82
|
|
|
82
83
|
// PRIVATE file (auth-gated route only).
|
|
83
84
|
const privateUserDir = path.join(integrationServices.uploadPrivateDir, 'users', userId);
|
|
@@ -98,6 +99,21 @@ describe('files two-tier uploads (real containers)', () => {
|
|
|
98
99
|
const res = await app.inject({ method: 'GET', url: `/uploads/users/${userId}/avatar/x.webp` });
|
|
99
100
|
expect(res.statusCode).toBe(200);
|
|
100
101
|
expect(res.body).toContain('PUBLIC-AVATAR-BYTES');
|
|
102
|
+
expect(res.headers['cache-control']).toBe('no-store');
|
|
103
|
+
});
|
|
104
|
+
|
|
105
|
+
it('uses no-store on avatar HEAD and range responses', async () => {
|
|
106
|
+
const url = `/uploads/users/${userId}/avatar/x.webp`;
|
|
107
|
+
const head = await app.inject({ method: 'HEAD', url });
|
|
108
|
+
const range = await app.inject({ method: 'GET', url, headers: { range: 'bytes=0-3' } });
|
|
109
|
+
expect([head.statusCode, range.statusCode]).toEqual([200, 206]);
|
|
110
|
+
expect([head.headers['cache-control'], range.headers['cache-control']]).toEqual(['no-store', 'no-store']);
|
|
111
|
+
});
|
|
112
|
+
|
|
113
|
+
it('keeps immutable caching for other public files', async () => {
|
|
114
|
+
const res = await app.inject({ method: 'GET', url: '/uploads/public-note.txt' });
|
|
115
|
+
expect(res.statusCode).toBe(200);
|
|
116
|
+
expect(res.headers['cache-control']).toBe('public, max-age=31536000, immutable');
|
|
101
117
|
});
|
|
102
118
|
|
|
103
119
|
it('EXPOSURE CLOSED: a PRIVATE-tier file is NOT reachable via /uploads/... (404)', async () => {
|
|
@@ -129,7 +145,7 @@ describe('files two-tier uploads (real containers)', () => {
|
|
|
129
145
|
expect(res.statusCode).toBe(200);
|
|
130
146
|
expect(res.body).toBe(PRIVATE_BODY);
|
|
131
147
|
expect(res.headers['accept-ranges']).toBe('bytes');
|
|
132
|
-
expect(res.headers['cache-control']).toBe('private');
|
|
148
|
+
expect(res.headers['cache-control']).toBe('private, no-store');
|
|
133
149
|
expect(res.headers['content-type']).toContain('text/plain');
|
|
134
150
|
});
|
|
135
151
|
|
|
@@ -141,11 +157,23 @@ describe('files two-tier uploads (real containers)', () => {
|
|
|
141
157
|
headers: { range: 'bytes=0-3' },
|
|
142
158
|
});
|
|
143
159
|
expect(res.statusCode).toBe(206);
|
|
160
|
+
expect(res.headers['cache-control']).toBe('private, no-store');
|
|
144
161
|
expect(res.headers['content-range']).toBe(`bytes 0-3/${PRIVATE_BODY.length}`);
|
|
145
162
|
expect(res.headers['content-length']).toBe('4');
|
|
146
163
|
expect(res.body).toBe(PRIVATE_BODY.slice(0, 4));
|
|
147
164
|
});
|
|
148
165
|
|
|
166
|
+
it('returns FILE_NOT_FOUND when a missing filename cannot be normalized', async () => {
|
|
167
|
+
const res = await app.inject({
|
|
168
|
+
method: 'GET',
|
|
169
|
+
url: `/api/v1/files/${encodeURIComponent('未命名')}`,
|
|
170
|
+
cookies: { access_token: accessCookie },
|
|
171
|
+
});
|
|
172
|
+
expect(res.statusCode).toBe(404);
|
|
173
|
+
expect(res.json().error.code).toBe('FILE_NOT_FOUND');
|
|
174
|
+
expect(res.headers['content-range']).toBeUndefined();
|
|
175
|
+
});
|
|
176
|
+
|
|
149
177
|
it('PRIVATE route traversal attempt → 404 (no existence leak, not 403)', async () => {
|
|
150
178
|
const res = await app.inject({
|
|
151
179
|
method: 'GET',
|
|
@@ -121,6 +121,7 @@ class FilesController {
|
|
|
121
121
|
|
|
122
122
|
// Guard 1: owner-scoped path, derived from the authenticated user id only.
|
|
123
123
|
const filePath = fileStorageService.getPrivateFilePath(userId, filename);
|
|
124
|
+
if (!filePath) throw new NotFoundError('File not found', 'FILE_NOT_FOUND');
|
|
124
125
|
|
|
125
126
|
// Guard 3: path containment. The resolved absolute path must remain inside
|
|
126
127
|
// the user's resolved private directory.
|
|
@@ -151,8 +152,7 @@ class FilesController {
|
|
|
151
152
|
|
|
152
153
|
reply.header('Accept-Ranges', 'bytes');
|
|
153
154
|
reply.header('Content-Type', contentType);
|
|
154
|
-
//
|
|
155
|
-
reply.header('Cache-Control', 'private');
|
|
155
|
+
// The authentication hook applies no-store to full and partial responses.
|
|
156
156
|
|
|
157
157
|
const range = parseRange(request.headers.range, size);
|
|
158
158
|
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import { beforeEach, expect, it, vi } from 'vitest';
|
|
2
|
+
import { fileStorageService } from '@libs/storage/file-storage.service.js';
|
|
3
|
+
import { cleanupDueAvatars, tryAvatarCleanup } from '../avatar-cleanup.js';
|
|
4
|
+
|
|
5
|
+
const db = vi.hoisted(() => ({
|
|
6
|
+
$queryRaw: vi.fn(),
|
|
7
|
+
user: { findUnique: vi.fn() },
|
|
8
|
+
avatarCleanup: { findMany: vi.fn(), delete: vi.fn(), updateMany: vi.fn() },
|
|
9
|
+
}));
|
|
10
|
+
vi.mock('@libs/prisma.js', () => ({ prisma: db }));
|
|
11
|
+
vi.mock('@libs/account-mutation.js', () => ({
|
|
12
|
+
runAccountMutation: async (write: (transaction: typeof db) => Promise<unknown>): Promise<unknown> => write(db),
|
|
13
|
+
}));
|
|
14
|
+
vi.mock('@modules/auth/auth.repo.js', () => ({ lockUser: vi.fn() }));
|
|
15
|
+
vi.mock('@libs/storage/file-storage.service.js', async importOriginal => ({
|
|
16
|
+
...await importOriginal<typeof import('@libs/storage/file-storage.service.js')>(),
|
|
17
|
+
fileStorageService: { removeAvatarFile: vi.fn() },
|
|
18
|
+
}));
|
|
19
|
+
|
|
20
|
+
const file = { userId: 'user-test', filename: 'old.webp' };
|
|
21
|
+
beforeEach(() => {
|
|
22
|
+
vi.resetAllMocks();
|
|
23
|
+
db.$queryRaw.mockResolvedValue([{ dueAt: new Date(0) }]);
|
|
24
|
+
db.user.findUnique.mockResolvedValue(null);
|
|
25
|
+
db.avatarCleanup.updateMany.mockResolvedValue({ count: 1 });
|
|
26
|
+
});
|
|
27
|
+
|
|
28
|
+
it('leaves a cleanup record when unlink fails and schedules a retry', async () => {
|
|
29
|
+
vi.mocked(fileStorageService.removeAvatarFile).mockRejectedValueOnce(new Error('disk'));
|
|
30
|
+
await tryAvatarCleanup(file);
|
|
31
|
+
expect(db.avatarCleanup.delete).not.toHaveBeenCalled();
|
|
32
|
+
expect(db.avatarCleanup.updateMany).toHaveBeenCalledWith({
|
|
33
|
+
where: file, data: { dueAt: expect.any(Date) },
|
|
34
|
+
});
|
|
35
|
+
});
|
|
36
|
+
|
|
37
|
+
it('drops stale cleanup work for the file still selected in the database', async () => {
|
|
38
|
+
db.user.findUnique.mockResolvedValue({ avatarUrl: '/uploads/users/user-test/avatar/old.webp' });
|
|
39
|
+
await tryAvatarCleanup(file);
|
|
40
|
+
expect(fileStorageService.removeAvatarFile).not.toHaveBeenCalled();
|
|
41
|
+
expect(db.avatarCleanup.delete).toHaveBeenCalledOnce();
|
|
42
|
+
});
|
|
43
|
+
|
|
44
|
+
it('processes a bounded batch of eligible cleanup records', async () => {
|
|
45
|
+
db.avatarCleanup.findMany.mockResolvedValue([file]);
|
|
46
|
+
await cleanupDueAvatars();
|
|
47
|
+
expect(db.avatarCleanup.findMany).toHaveBeenCalledWith(expect.objectContaining({ take: 50 }));
|
|
48
|
+
expect(fileStorageService.removeAvatarFile).toHaveBeenCalledExactlyOnceWith(file);
|
|
49
|
+
});
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import { beforeEach, expect, it, vi } from 'vitest';
|
|
2
|
+
import type { FastifyReply } from 'fastify';
|
|
3
|
+
import type { Multipart } from '@fastify/multipart';
|
|
4
|
+
import type { AuthenticatedRequest } from '@shared/types/index.js';
|
|
5
|
+
import { usersController } from '../users.controller.js';
|
|
6
|
+
import { usersService } from '../users.service.js';
|
|
7
|
+
|
|
8
|
+
vi.mock('../users.service.js', () => ({ usersService: { uploadAvatar: vi.fn() } }));
|
|
9
|
+
|
|
10
|
+
const image = Buffer.from('fixture image buffer');
|
|
11
|
+
const first = {
|
|
12
|
+
type: 'file', filename: 'fixture.png', mimetype: 'image/png',
|
|
13
|
+
file: { truncated: false },
|
|
14
|
+
toBuffer: async (): Promise<Buffer> => image,
|
|
15
|
+
} as Multipart;
|
|
16
|
+
|
|
17
|
+
function fixture(parts: () => AsyncGenerator<Multipart>): AuthenticatedRequest {
|
|
18
|
+
return {
|
|
19
|
+
targetUserId: 'fixture-user',
|
|
20
|
+
user: { userId: 'fixture-user' },
|
|
21
|
+
file: async (): Promise<Multipart> => first,
|
|
22
|
+
parts,
|
|
23
|
+
} as unknown as AuthenticatedRequest;
|
|
24
|
+
}
|
|
25
|
+
const reply = { send: vi.fn() } as unknown as FastifyReply;
|
|
26
|
+
|
|
27
|
+
beforeEach(() => {
|
|
28
|
+
vi.clearAllMocks();
|
|
29
|
+
vi.mocked(usersService.uploadAvatar).mockResolvedValue({ avatarUrl: '/uploads/fixture.webp' });
|
|
30
|
+
});
|
|
31
|
+
|
|
32
|
+
it.each(['FST_FIELDS_LIMIT', 'FST_FILES_LIMIT'])('waits for a late %s before publishing', async code => {
|
|
33
|
+
const request = fixture(async function* () {
|
|
34
|
+
yield first;
|
|
35
|
+
throw Object.assign(new Error('Multipart limit fixture'), { code, statusCode: 413 });
|
|
36
|
+
});
|
|
37
|
+
await expect(usersController.uploadAvatar(request, reply)).rejects.toMatchObject({ code, statusCode: 413 });
|
|
38
|
+
expect(usersService.uploadAvatar).not.toHaveBeenCalled();
|
|
39
|
+
});
|
|
40
|
+
|
|
41
|
+
it('rejects a field that the parser truncated after the first file', async () => {
|
|
42
|
+
const request = fixture(async function* () {
|
|
43
|
+
yield first;
|
|
44
|
+
yield { type: 'field', fieldnameTruncated: false, valueTruncated: true } as Multipart;
|
|
45
|
+
});
|
|
46
|
+
await expect(usersController.uploadAvatar(request, reply)).rejects.toMatchObject({
|
|
47
|
+
code: 'MULTIPART_LIMIT', statusCode: 413,
|
|
48
|
+
});
|
|
49
|
+
expect(usersService.uploadAvatar).not.toHaveBeenCalled();
|
|
50
|
+
});
|
|
@@ -1,120 +1,71 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
* avatar folder: every upload gets a new file, the database is pointed at it
|
|
4
|
-
* with a compare-and-swap, and only the file that swap replaced is deleted.
|
|
5
|
-
* The invariant checked throughout: afterwards the folder holds exactly the
|
|
6
|
-
* file the database names, including when two uploads race.
|
|
7
|
-
*/
|
|
8
|
-
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
|
9
|
-
import { usersService } from '../users.service.js';
|
|
10
|
-
import { usersRepository } from '../users.repo.js';
|
|
1
|
+
import { beforeEach, expect, it, vi } from 'vitest';
|
|
2
|
+
import { assertMutationActor } from '@libs/account-mutation.js';
|
|
11
3
|
import { fileStorageService } from '@libs/storage/file-storage.service.js';
|
|
12
4
|
import { testUsers } from '@/test/setup.js';
|
|
5
|
+
import { usersService } from '../users.service.js';
|
|
6
|
+
import { usersRepository } from '../users.repo.js';
|
|
7
|
+
import { protectPendingAvatar, queueReplacedAvatar, tryAvatarCleanup } from '../avatar-cleanup.js';
|
|
13
8
|
|
|
9
|
+
const tx = vi.hoisted(() => ({ avatarCleanup: { findUnique: vi.fn(), delete: vi.fn() } }));
|
|
10
|
+
vi.mock('@libs/account-mutation.js', () => ({
|
|
11
|
+
assertMutationActor: vi.fn(),
|
|
12
|
+
runAccountMutation: async (write: (transaction: typeof tx) => Promise<unknown>): Promise<unknown> => write(tx),
|
|
13
|
+
}));
|
|
14
14
|
vi.mock('@modules/auth/auth.repo.js');
|
|
15
|
-
vi.mock('@modules/auth/session.repo.js');
|
|
16
|
-
vi.mock('@libs/password.js');
|
|
17
15
|
vi.mock('../users.repo.js');
|
|
16
|
+
vi.mock('../avatar-cleanup.js');
|
|
18
17
|
vi.mock('@libs/storage/image-optimizer.service.js', () => ({
|
|
19
|
-
imageOptimizerService: { optimizeAvatar: vi.fn(async (
|
|
18
|
+
imageOptimizerService: { optimizeAvatar: vi.fn(async (bytes: Buffer) => bytes) },
|
|
20
19
|
}));
|
|
21
|
-
vi.mock('@libs/storage/file-storage.service.js',
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
const USER_ID = testUsers.validUser.id;
|
|
26
|
-
const urlOf = (file: string): string => `/uploads/users/${USER_ID}/avatar/${file}`;
|
|
20
|
+
vi.mock('@libs/storage/file-storage.service.js', async importOriginal => {
|
|
21
|
+
const actual = await importOriginal<typeof import('@libs/storage/file-storage.service.js')>();
|
|
22
|
+
return { ...actual, fileStorageService: { allocateAvatar: vi.fn(), publishAvatar: vi.fn() } };
|
|
23
|
+
});
|
|
27
24
|
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
25
|
+
const user = testUsers.validUser;
|
|
26
|
+
const actor = { userId: user.id, sessionId: 'fixture-session' };
|
|
27
|
+
const next = { userId: user.id, filename: 'avatar-1234567890abcdef.webp' };
|
|
28
|
+
const previous = { userId: user.id, filename: 'old.webp' };
|
|
29
|
+
const oldUrl = `/uploads/users/${user.id}/avatar/${previous.filename}`;
|
|
30
|
+
const newUrl = `/uploads/users/${user.id}/avatar/${next.filename}`;
|
|
31
|
+
const upload = (): Promise<{ avatarUrl: string }> =>
|
|
32
|
+
usersService.uploadAvatar(user.id, Buffer.from('image fixture'), 'avatar.png', actor);
|
|
34
33
|
|
|
35
34
|
beforeEach(() => {
|
|
36
|
-
vi.
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
vi.mocked(usersRepository.getUserById).mockImplementation(async () => ({ ...testUsers.validUser, avatarUrl: row.avatarUrl }) as never);
|
|
43
|
-
vi.mocked(usersRepository.swapAvatarUrl).mockImplementation(async (_id, expected, next) => {
|
|
44
|
-
if (row.avatarUrl !== expected) return false;
|
|
45
|
-
row.avatarUrl = next;
|
|
46
|
-
return true;
|
|
47
|
-
});
|
|
48
|
-
vi.mocked(fileStorageService.saveAvatar).mockImplementation(async () => {
|
|
49
|
-
const n = ++saved;
|
|
50
|
-
const filename = `avatar-${String(n).padStart(16, '0')}.webp`;
|
|
51
|
-
folder.add(filename);
|
|
52
|
-
if (holdSave?.call === n) await holdSave.until;
|
|
53
|
-
return { filename, url: urlOf(filename) };
|
|
54
|
-
});
|
|
55
|
-
vi.mocked(fileStorageService.removeAvatarFile).mockImplementation(async (_id, filename) => {
|
|
56
|
-
folder.delete(filename);
|
|
57
|
-
});
|
|
35
|
+
vi.resetAllMocks();
|
|
36
|
+
tx.avatarCleanup.findUnique.mockResolvedValue({ dueAt: new Date(Date.now() + 60_000) });
|
|
37
|
+
vi.mocked(fileStorageService.allocateAvatar).mockReturnValue(next);
|
|
38
|
+
vi.mocked(usersRepository.getUserById).mockResolvedValue({ ...user, avatarUrl: oldUrl });
|
|
39
|
+
vi.mocked(queueReplacedAvatar).mockResolvedValue(previous);
|
|
58
40
|
});
|
|
59
41
|
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
expect(
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
it('a first upload stores the file and points the database at it', async () => {
|
|
70
|
-
const { avatarUrl } = await upload();
|
|
71
|
-
expect(avatarUrl).toMatch(/\/avatar\/avatar-\d{16}\.webp$/);
|
|
72
|
-
expect(row.avatarUrl).toBe(avatarUrl);
|
|
73
|
-
expect(fileStorageService.removeAvatarFile).not.toHaveBeenCalled();
|
|
74
|
-
expectFolderMatchesDatabase();
|
|
75
|
-
});
|
|
76
|
-
|
|
77
|
-
it('a re-upload gets a NEW url and deletes the file it replaced', async () => {
|
|
78
|
-
const first = await upload();
|
|
79
|
-
const second = await upload();
|
|
80
|
-
expect(second.avatarUrl).not.toBe(first.avatarUrl);
|
|
81
|
-
expect(fileStorageService.removeAvatarFile).toHaveBeenCalledWith(USER_ID, first.avatarUrl.split('/').pop());
|
|
82
|
-
expectFolderMatchesDatabase();
|
|
83
|
-
});
|
|
84
|
-
|
|
85
|
-
it('two uploads at once end with exactly the database file', async () => {
|
|
86
|
-
await upload();
|
|
87
|
-
await Promise.all([upload(), upload()]);
|
|
88
|
-
expectFolderMatchesDatabase();
|
|
89
|
-
});
|
|
90
|
-
|
|
91
|
-
it('an upload that finishes while another is between writing and swapping does not delete its file', async () => {
|
|
92
|
-
await upload(); // an existing avatar both uploads will try to replace
|
|
93
|
-
let releaseSecond!: () => void;
|
|
94
|
-
holdSave = { call: 3, until: new Promise<void>((r) => { releaseSecond = r; }) };
|
|
95
|
-
|
|
96
|
-
const second = upload(); // reads the old avatar, writes, then waits before swapping
|
|
97
|
-
await vi.waitFor(() => expect(saved).toBe(2));
|
|
98
|
-
const third = upload(); // its save is held: written to disk, not yet in the database
|
|
99
|
-
await vi.waitFor(() => expect(saved).toBe(3));
|
|
100
|
-
await second; // swaps old -> second, deletes old; must leave the third file alone
|
|
101
|
-
releaseSecond();
|
|
102
|
-
await third; // swap fails (database moved on), retries, replaces second, deletes it
|
|
103
|
-
|
|
104
|
-
expectFolderMatchesDatabase();
|
|
105
|
-
expect(row.avatarUrl).toBe((await third).avatarUrl);
|
|
106
|
-
});
|
|
42
|
+
it('protects the new file before publishing and cleans only the detached file after success', async () => {
|
|
43
|
+
await expect(upload()).resolves.toEqual({ avatarUrl: newUrl });
|
|
44
|
+
expect(vi.mocked(protectPendingAvatar).mock.invocationCallOrder[0]).toBeLessThan(
|
|
45
|
+
vi.mocked(fileStorageService.publishAvatar).mock.invocationCallOrder[0]!,
|
|
46
|
+
);
|
|
47
|
+
expect(usersRepository.setAvatarUrl).toHaveBeenCalledWith(tx, user.id, newUrl);
|
|
48
|
+
expect(queueReplacedAvatar).toHaveBeenCalledWith(tx, user.id, oldUrl);
|
|
49
|
+
expect(tryAvatarCleanup).toHaveBeenCalledExactlyOnceWith(previous);
|
|
50
|
+
});
|
|
107
51
|
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
52
|
+
it('rejects a revoked actor before publishing and cleans up the unpublished file', async () => {
|
|
53
|
+
vi.mocked(assertMutationActor).mockRejectedValueOnce(Object.assign(new Error('Ended'), { statusCode: 401 }));
|
|
54
|
+
await expect(upload()).rejects.toMatchObject({ statusCode: 401 });
|
|
55
|
+
expect(fileStorageService.publishAvatar).not.toHaveBeenCalled();
|
|
56
|
+
expect(usersRepository.setAvatarUrl).not.toHaveBeenCalled();
|
|
57
|
+
expect(tryAvatarCleanup).toHaveBeenCalledExactlyOnceWith(next);
|
|
58
|
+
});
|
|
114
59
|
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
60
|
+
it('preserves the old avatar when publishing fails', async () => {
|
|
61
|
+
vi.mocked(fileStorageService.publishAvatar).mockRejectedValueOnce(new Error('disk'));
|
|
62
|
+
await expect(upload()).rejects.toThrow('disk');
|
|
63
|
+
expect(usersRepository.setAvatarUrl).not.toHaveBeenCalled();
|
|
64
|
+
expect(tryAvatarCleanup).toHaveBeenCalledExactlyOnceWith(next);
|
|
120
65
|
});
|
|
66
|
+
|
|
67
|
+
it('refuses a pending upload whose cleanup deadline has arrived', async () => {
|
|
68
|
+
tx.avatarCleanup.findUnique.mockResolvedValueOnce({ dueAt: new Date(0) });
|
|
69
|
+
await expect(upload()).rejects.toMatchObject({ statusCode: 503, code: 'AVATAR_UPLOAD_EXPIRED' });
|
|
70
|
+
expect(fileStorageService.publishAvatar).not.toHaveBeenCalled();
|
|
71
|
+
});
|
|
@@ -113,7 +113,7 @@ describe('avatar formats are judged by the bytes', () => {
|
|
|
113
113
|
});
|
|
114
114
|
|
|
115
115
|
describe('avatar files', () => {
|
|
116
|
-
it('a re-upload gets a new random name with
|
|
116
|
+
it('a re-upload gets a new random name served with no-store; the old URL is 404 at once; 1 file on disk', async () => {
|
|
117
117
|
const u = await registerUser(app, 'files');
|
|
118
118
|
const a = await uploadAvatar(app, u.jar, await image('jpeg'));
|
|
119
119
|
const b = await uploadAvatar(app, u.jar, await image('png'));
|
|
@@ -123,7 +123,7 @@ describe('avatar files', () => {
|
|
|
123
123
|
expect((await call(app, 'GET', urlA)).status).toBe(404);
|
|
124
124
|
const fresh = await call(app, 'GET', urlB);
|
|
125
125
|
expect(fresh.status).toBe(200);
|
|
126
|
-
expect(fresh.res.headers['cache-control']).toBe('
|
|
126
|
+
expect(fresh.res.headers['cache-control']).toBe('no-store');
|
|
127
127
|
expect(urlB).toMatch(/\/avatar\/avatar-[0-9a-f]{16}\.webp$/);
|
|
128
128
|
expect(await avatarUrlOf(u.id)).toBe(urlB);
|
|
129
129
|
expect(filesIn(avatarDir(u.id))).toEqual([path.basename(urlB)]);
|
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* The two avatar-related queries in users.repo: soft delete clears the avatar
|
|
3
|
-
* URL, and the avatar
|
|
4
|
-
* deleted account.
|
|
3
|
+
* URL, and the avatar/profile writes keep the deleted-account predicate.
|
|
5
4
|
*/
|
|
6
5
|
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
|
7
6
|
import { prisma } from '@libs/prisma.js';
|
|
@@ -17,21 +16,19 @@ beforeEach(() => {
|
|
|
17
16
|
|
|
18
17
|
describe('usersRepository', () => {
|
|
19
18
|
it('softDeleteUser clears the avatar URL with the deletion', async () => {
|
|
20
|
-
await usersRepository.softDeleteUser('u1');
|
|
19
|
+
await usersRepository.softDeleteUser(prisma, 'u1');
|
|
21
20
|
expect(prisma.user.update).toHaveBeenCalledWith({
|
|
22
21
|
where: { id: 'u1' },
|
|
23
22
|
data: { deletedAt: expect.any(Date), isActive: false, avatarUrl: null },
|
|
24
23
|
});
|
|
25
24
|
});
|
|
26
25
|
|
|
27
|
-
it('
|
|
28
|
-
|
|
29
|
-
await
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
where: { id: 'u1', deletedAt: null, avatarUrl: '/old.webp' },
|
|
33
|
-
data: { avatarUrl: '/new.webp' },
|
|
26
|
+
it('updates the avatar and profile only for a live target in the transaction', async () => {
|
|
27
|
+
await usersRepository.setAvatarUrl(prisma, 'u1', null);
|
|
28
|
+
await usersRepository.updateUserProfile(prisma, 'u1', { firstName: 'New' });
|
|
29
|
+
expect(prisma.user.update).toHaveBeenNthCalledWith(1, {
|
|
30
|
+
where: { id: 'u1', deletedAt: null }, data: { avatarUrl: null },
|
|
34
31
|
});
|
|
35
|
-
expect(vi.mocked(prisma.user.
|
|
32
|
+
expect(vi.mocked(prisma.user.update).mock.calls[1]?.[0].where).toEqual({ id: 'u1', deletedAt: null });
|
|
36
33
|
});
|
|
37
34
|
});
|