create-tigra 4.0.1 → 5.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/CHANGELOG.md +43 -0
- package/README.md +21 -3
- package/bin/create-tigra.js +131 -65
- package/lib/installer-transaction.js +275 -0
- package/lib/patchers/diagnostics.patcher.js +123 -0
- package/lib/patchers/email-verification.patcher.js +86 -92
- package/lib/patchers/metrics.patcher.js +145 -0
- package/lib/project-files.js +99 -0
- package/modules/diagnostics/diagnostics.md +75 -0
- package/modules/diagnostics/prisma/diagnostic-bucket.prisma +22 -0
- package/modules/diagnostics/prisma/diagnostic-hourly-view.sql +24 -0
- package/modules/diagnostics/prisma/migration.sql +20 -0
- package/modules/diagnostics/server/__tests__/diagnostics.collector.test.ts +72 -0
- package/modules/diagnostics/server/__tests__/diagnostics.context.test.ts +51 -0
- package/modules/diagnostics/server/__tests__/diagnostics.integration.test.ts +123 -0
- package/modules/diagnostics/server/__tests__/diagnostics.service.test.ts +31 -0
- package/modules/diagnostics/server/diagnostics.collector.ts +95 -0
- package/modules/diagnostics/server/diagnostics.context.ts +73 -0
- package/modules/diagnostics/server/diagnostics.repo.ts +79 -0
- package/modules/diagnostics/server/diagnostics.routes.ts +16 -0
- package/modules/diagnostics/server/diagnostics.sample.ts +92 -0
- package/modules/diagnostics/server/diagnostics.schemas.ts +33 -0
- package/modules/diagnostics/server/diagnostics.service.ts +44 -0
- 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 +37 -0
- package/modules/metrics/client/__tests__/WebVitalsReporter.test.ts +66 -0
- package/modules/metrics/client/metrics.pages.ts +5 -0
- package/modules/metrics/performance.md +56 -0
- package/modules/metrics/prisma/metric-bucket.prisma +18 -0
- package/modules/metrics/prisma/migration.sql +17 -0
- package/modules/metrics/server/__tests__/metrics.collector.test.ts +97 -0
- package/modules/metrics/server/__tests__/metrics.integration.test.ts +88 -0
- package/modules/metrics/server/__tests__/metrics.schemas.test.ts +36 -0
- package/modules/metrics/server/__tests__/metrics.service.test.ts +84 -0
- package/modules/metrics/server/metrics.collector.ts +133 -0
- package/modules/metrics/server/metrics.pages.ts +3 -0
- package/modules/metrics/server/metrics.repo.ts +45 -0
- package/modules/metrics/server/metrics.routes.ts +45 -0
- package/modules/metrics/server/metrics.schemas.ts +57 -0
- package/modules/metrics/server/metrics.service.ts +104 -0
- package/package.json +1 -1
- package/template/AGENTS.md +18 -10
- package/template/client/.dockerignore +2 -5
- package/template/client/gitignore +43 -0
- package/template/client/src/app/focus-rings.policy.test.ts +88 -0
- package/template/client/src/app/globals.css +46 -0
- package/template/client/src/app/layout.tsx +5 -0
- package/template/client/src/app/page.tsx +2 -2
- package/template/client/src/components/common/InputModalityTracker.tsx +12 -0
- package/template/client/src/components/ui/input.tsx +3 -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/input-modality.test.ts +79 -0
- package/template/client/src/lib/input-modality.ts +52 -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
|
@@ -2,7 +2,7 @@ import crypto from 'node:crypto';
|
|
|
2
2
|
import { signAccessToken, generateRefreshToken, getRefreshTokenExpiresAt } from '@libs/auth.js';
|
|
3
3
|
import { hashPassword, verifyPassword } from '@libs/password.js';
|
|
4
4
|
import { getRedis } from '@libs/redis.js';
|
|
5
|
-
import {
|
|
5
|
+
import { enqueueRecovery } from './recovery.queue.js';
|
|
6
6
|
import { logger } from '@libs/logger.js';
|
|
7
7
|
import { env } from '@config/env.js';
|
|
8
8
|
import { assertAccountCanSignIn } from '@libs/account-status.js';
|
|
@@ -14,10 +14,10 @@ import {
|
|
|
14
14
|
TooManyRequestsError,
|
|
15
15
|
describeWait,
|
|
16
16
|
} from '@shared/errors/errors.js';
|
|
17
|
-
import {
|
|
17
|
+
import { consumeRecoveryToken, findRecoveryOwner } from './recovery.store.js';
|
|
18
18
|
import { assertRedisReady } from '@libs/redis-required.js';
|
|
19
|
-
import { hashToken } from '@libs/token-hash.js';
|
|
20
19
|
import type { UserRole } from '@shared/types/index.js';
|
|
20
|
+
import type { MutationActor } from '@libs/account-mutation.js';
|
|
21
21
|
import * as authRepo from './auth.repo.js';
|
|
22
22
|
import { sessionRepository } from './session.repo.js';
|
|
23
23
|
import type { RegisterInput, LoginInput } from './auth.schemas.js';
|
|
@@ -25,37 +25,6 @@ import type { RegisterInput, LoginInput } from './auth.schemas.js';
|
|
|
25
25
|
/** A refresh that lost a race with a parallel one (see refresh()); its cookies must stay. */
|
|
26
26
|
export const REFRESH_TOKEN_ROTATED = 'REFRESH_TOKEN_ROTATED';
|
|
27
27
|
|
|
28
|
-
// "Just rotated" notes: `rt-rotated:<sha256 of the old refresh token>`, kept
|
|
29
|
-
// for a minute. A parallel refresh that arrives a few ms after the winner
|
|
30
|
-
// finds its token already gone; the note tells it apart from a stale or
|
|
31
|
-
// stolen token, so it gets REFRESH_TOKEN_ROTATED (cookies kept) instead of
|
|
32
|
-
// INVALID_REFRESH_TOKEN (cookies cleared, signing that browser out).
|
|
33
|
-
const ROTATED_NOTE_PREFIX = 'rt-rotated:';
|
|
34
|
-
const ROTATED_NOTE_SECONDS = 60;
|
|
35
|
-
|
|
36
|
-
async function noteRotation(refreshToken: string): Promise<void> {
|
|
37
|
-
try {
|
|
38
|
-
await getRedis().set(`${ROTATED_NOTE_PREFIX}${hashToken(refreshToken)}`, '1', 'EX', ROTATED_NOTE_SECONDS);
|
|
39
|
-
} catch {
|
|
40
|
-
// Redis down: a late parallel refresh then falls back to INVALID_REFRESH_TOKEN
|
|
41
|
-
}
|
|
42
|
-
}
|
|
43
|
-
|
|
44
|
-
async function wasJustRotated(refreshToken: string): Promise<boolean> {
|
|
45
|
-
try {
|
|
46
|
-
return (await getRedis().exists(`${ROTATED_NOTE_PREFIX}${hashToken(refreshToken)}`)) === 1;
|
|
47
|
-
} catch {
|
|
48
|
-
return false;
|
|
49
|
-
}
|
|
50
|
-
}
|
|
51
|
-
|
|
52
|
-
const PASSWORD_RESET_TTL = 3600; // 1 hour in seconds
|
|
53
|
-
// Reset tokens in Redis are stored by fingerprint only (libs/token-hash.ts):
|
|
54
|
-
// `pw-reset:<sha256>` -> userId, and `pw-reset-user:<userId>` -> that sha256
|
|
55
|
-
// (to invalidate a user's previous link). The raw token exists only in the email.
|
|
56
|
-
const PASSWORD_RESET_PREFIX = 'pw-reset:';
|
|
57
|
-
const PASSWORD_RESET_USER_PREFIX = 'pw-reset-user:';
|
|
58
|
-
|
|
59
28
|
// --- Account lockout (scoped to email + IP) ---
|
|
60
29
|
// Failed-login attempts are tracked in Redis keyed by the (email, IP) PAIR.
|
|
61
30
|
// Keying by email alone let anyone lock a victim out remotely by spamming bad
|
|
@@ -315,29 +284,18 @@ export async function login(
|
|
|
315
284
|
// caller cannot learn whether an email is banned or unverified.
|
|
316
285
|
assertAccountCanSignIn(user);
|
|
317
286
|
|
|
318
|
-
//
|
|
287
|
+
// Login rechecks the verified hash under the same lock used by recovery.
|
|
319
288
|
const refreshToken = generateRefreshToken();
|
|
320
|
-
const
|
|
321
|
-
|
|
322
|
-
const session = await sessionRepository.createSession({
|
|
289
|
+
const session = await authRepo.createLoginSession({
|
|
323
290
|
userId: user.id,
|
|
291
|
+
verifiedPasswordHash: user.password,
|
|
292
|
+
refreshToken,
|
|
324
293
|
deviceInfo,
|
|
325
294
|
ipAddress,
|
|
326
|
-
expiresAt:
|
|
327
|
-
});
|
|
328
|
-
|
|
329
|
-
const accessToken = signAccessToken({
|
|
330
|
-
userId: user.id,
|
|
331
|
-
role: user.role,
|
|
332
|
-
sessionId: session.id,
|
|
333
|
-
});
|
|
334
|
-
|
|
335
|
-
await authRepo.createRefreshToken({
|
|
336
|
-
token: refreshToken,
|
|
337
|
-
userId: user.id,
|
|
338
|
-
sessionId: session.id,
|
|
339
|
-
expiresAt: refreshTokenExpiresAt,
|
|
295
|
+
expiresAt: getRefreshTokenExpiresAt(),
|
|
340
296
|
});
|
|
297
|
+
if (!session) throw new UnauthorizedError('Invalid email or password', 'INVALID_CREDENTIALS');
|
|
298
|
+
const accessToken = signAccessToken({ userId: user.id, role: user.role, sessionId: session.id });
|
|
341
299
|
|
|
342
300
|
return {
|
|
343
301
|
user: sanitizeUser(user),
|
|
@@ -347,90 +305,22 @@ export async function login(
|
|
|
347
305
|
}
|
|
348
306
|
|
|
349
307
|
export async function refresh(refreshToken: string): Promise<{ accessToken: string; refreshToken: string }> {
|
|
350
|
-
const storedToken = await authRepo.findRefreshToken(refreshToken);
|
|
351
|
-
if (!storedToken) {
|
|
352
|
-
// Gone a moment ago because a parallel refresh rotated it: lost race, not a bad token.
|
|
353
|
-
if (await wasJustRotated(refreshToken)) {
|
|
354
|
-
throw new UnauthorizedError('Refresh token already used by a parallel request', REFRESH_TOKEN_ROTATED);
|
|
355
|
-
}
|
|
356
|
-
throw new UnauthorizedError('Invalid refresh token', 'INVALID_REFRESH_TOKEN');
|
|
357
|
-
}
|
|
358
|
-
|
|
359
|
-
if (new Date() > storedToken.expiresAt) {
|
|
360
|
-
await authRepo.deleteRefreshToken(refreshToken);
|
|
361
|
-
throw new UnauthorizedError('Refresh token expired', 'REFRESH_TOKEN_EXPIRED');
|
|
362
|
-
}
|
|
363
|
-
|
|
364
|
-
// A token is only as alive as its session. If the session row is gone
|
|
365
|
-
// (logout elsewhere, admin force-expire, cleanup job) or past its expiry, the
|
|
366
|
-
// login is over: drop the token instead of minting new ones.
|
|
367
|
-
const session = storedToken.sessionId
|
|
368
|
-
? await sessionRepository.getSessionById(storedToken.sessionId)
|
|
369
|
-
: null;
|
|
370
|
-
if (!session || session.expiresAt <= new Date()) {
|
|
371
|
-
await authRepo.deleteRefreshToken(refreshToken);
|
|
372
|
-
throw new UnauthorizedError('Session expired', 'SESSION_EXPIRED');
|
|
373
|
-
}
|
|
374
|
-
|
|
375
|
-
const user = await authRepo.findUserById(storedToken.userId);
|
|
376
|
-
if (!user) {
|
|
377
|
-
throw new UnauthorizedError('User not found or disabled', 'INVALID_REFRESH_TOKEN');
|
|
378
|
-
}
|
|
379
|
-
// A ban (or a pending verification) also stops refresh, so a banned user's
|
|
380
|
-
// leftover refresh token cannot mint new access tokens.
|
|
381
|
-
assertAccountCanSignIn(user);
|
|
382
|
-
|
|
383
|
-
const newAccessToken = signAccessToken({
|
|
384
|
-
userId: user.id,
|
|
385
|
-
role: user.role,
|
|
386
|
-
sessionId: session.id,
|
|
387
|
-
});
|
|
388
308
|
const newRefreshToken = generateRefreshToken();
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
// lost race. Harmless if this rotation then fails: the note only matters to
|
|
393
|
-
// requests whose token no longer exists.
|
|
394
|
-
await noteRotation(refreshToken);
|
|
395
|
-
|
|
396
|
-
// Single-winner rotation (see rotateRefreshToken): false when a parallel
|
|
397
|
-
// request rotated this token first.
|
|
398
|
-
const rotated = await authRepo.rotateRefreshToken(refreshToken, {
|
|
399
|
-
token: newRefreshToken,
|
|
400
|
-
userId: user.id,
|
|
401
|
-
sessionId: session.id,
|
|
402
|
-
expiresAt: getRefreshTokenExpiresAt(),
|
|
403
|
-
});
|
|
404
|
-
|
|
405
|
-
if (!rotated) {
|
|
406
|
-
// A parallel request rotated this token first. That is normally two tabs
|
|
407
|
-
// of the same browser refreshing at once (they share the cookie and the
|
|
408
|
-
// 15-minute access token, so both refresh when it expires). The winner's
|
|
409
|
-
// response has already set the new cookies, so refuse ONLY this request,
|
|
410
|
-
// with a code the controller recognises so it does NOT clear those cookies.
|
|
411
|
-
// Nothing is revoked: wiping every session here used to sign the user out
|
|
412
|
-
// on all devices for a harmless race, while a real replay of a stolen old
|
|
413
|
-
// token arrives later and is rejected above as not found.
|
|
414
|
-
logger.info({ userId: user.id }, '[AUTH] Parallel refresh lost the race; refusing only this request');
|
|
415
|
-
throw new UnauthorizedError('Refresh token already used by a parallel request', REFRESH_TOKEN_ROTATED);
|
|
309
|
+
const result = await authRepo.rotateRefreshToken(refreshToken, newRefreshToken, getRefreshTokenExpiresAt);
|
|
310
|
+
if (result.kind === 'issued') {
|
|
311
|
+
return { accessToken: signAccessToken(result.claims), refreshToken: newRefreshToken };
|
|
416
312
|
}
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
313
|
+
const [message, code] = {
|
|
314
|
+
rotated: ['Refresh token already used by a parallel request', REFRESH_TOKEN_ROTATED],
|
|
315
|
+
invalid: ['Invalid refresh token', 'INVALID_REFRESH_TOKEN'],
|
|
316
|
+
'expired-token': ['Refresh token expired', 'REFRESH_TOKEN_EXPIRED'],
|
|
317
|
+
'expired-session': ['Session expired', 'SESSION_EXPIRED'],
|
|
318
|
+
}[result.kind];
|
|
319
|
+
throw new UnauthorizedError(message, code);
|
|
422
320
|
}
|
|
423
321
|
|
|
424
|
-
export
|
|
425
|
-
|
|
426
|
-
// Both deleteRefreshToken and deleteSession handle "already deleted" (P2025)
|
|
427
|
-
// gracefully, so no catch needed for concurrent request / cleanup job races.
|
|
428
|
-
const storedToken = await authRepo.findRefreshToken(refreshToken);
|
|
429
|
-
await authRepo.deleteRefreshToken(refreshToken);
|
|
430
|
-
|
|
431
|
-
if (storedToken?.sessionId) {
|
|
432
|
-
await sessionRepository.deleteSession(storedToken.sessionId);
|
|
433
|
-
}
|
|
322
|
+
export function logout(refreshToken?: string, accessSession?: MutationActor): Promise<void> {
|
|
323
|
+
return authRepo.revokeSession(refreshToken, accessSession);
|
|
434
324
|
}
|
|
435
325
|
|
|
436
326
|
export async function getCurrentUser(userId: string): Promise<SanitizedUser> {
|
|
@@ -463,121 +353,27 @@ export async function getUserSessions(userId: string): Promise<SessionInfo[]> {
|
|
|
463
353
|
}));
|
|
464
354
|
}
|
|
465
355
|
|
|
466
|
-
export
|
|
467
|
-
|
|
468
|
-
await authRepo.deleteRefreshTokensByUserId(userId);
|
|
469
|
-
return sessionCount;
|
|
356
|
+
export function logoutAllSessions(actor: MutationActor): Promise<number> {
|
|
357
|
+
return authRepo.revokeAllSessions(actor);
|
|
470
358
|
}
|
|
471
359
|
|
|
472
360
|
export async function forgotPassword(email: string): Promise<void> {
|
|
473
|
-
// Reset tokens live in Redis: without it, answer a clear 503 for every
|
|
474
|
-
// address (checked before the lookup, so it reveals nothing).
|
|
475
361
|
assertRedisReady('Password reset');
|
|
476
|
-
|
|
477
|
-
// Per-address email cap, counted BEFORE the lookup so unknown addresses are
|
|
478
|
-
// counted too (the 429 reveals nothing about the account). See libs/email-quota.ts.
|
|
479
|
-
await consumeEmailQuota(email);
|
|
480
|
-
|
|
481
|
-
const user = await authRepo.findUserByEmail(email);
|
|
482
|
-
|
|
483
|
-
// Silent return if user not found — prevents email enumeration
|
|
484
|
-
if (!user) return;
|
|
485
|
-
|
|
486
|
-
const redis = getRedis();
|
|
487
|
-
|
|
488
|
-
// Invalidate any existing token for this user (the pointer holds its fingerprint)
|
|
489
|
-
const existingTokenHash = await redis.get(`${PASSWORD_RESET_USER_PREFIX}${user.id}`);
|
|
490
|
-
if (existingTokenHash) {
|
|
491
|
-
await redis.del(`${PASSWORD_RESET_PREFIX}${existingTokenHash}`);
|
|
492
|
-
await redis.del(`${PASSWORD_RESET_USER_PREFIX}${user.id}`);
|
|
493
|
-
}
|
|
494
|
-
|
|
495
|
-
// Generate a secure token; only its fingerprint goes to Redis (1 hour TTL)
|
|
496
|
-
const token = crypto.randomBytes(32).toString('hex');
|
|
497
|
-
const tokenHash = hashToken(token);
|
|
498
|
-
|
|
499
|
-
await redis.set(`${PASSWORD_RESET_PREFIX}${tokenHash}`, user.id, 'EX', PASSWORD_RESET_TTL);
|
|
500
|
-
await redis.set(`${PASSWORD_RESET_USER_PREFIX}${user.id}`, tokenHash, 'EX', PASSWORD_RESET_TTL);
|
|
501
|
-
|
|
502
|
-
// Build reset URL and send email
|
|
503
|
-
const resetUrl = `${env.CLIENT_URL}/reset-password?token=${token}`;
|
|
504
|
-
const safeName = user.firstName.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
|
|
505
|
-
|
|
506
|
-
try {
|
|
507
|
-
await sendEmail({
|
|
508
|
-
to: user.email,
|
|
509
|
-
subject: 'Reset your password',
|
|
510
|
-
html: `
|
|
511
|
-
<table width="100%" cellpadding="0" cellspacing="0" style="background-color: #f4f3ee; padding: 40px 20px; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;">
|
|
512
|
-
<tr>
|
|
513
|
-
<td align="center">
|
|
514
|
-
<table width="100%" cellpadding="0" cellspacing="0" style="max-width: 480px; background-color: #ffffff; border-radius: 16px; overflow: hidden; box-shadow: 0 1px 3px rgba(0,0,0,0.06); border-left: 4px solid #c15f3c;">
|
|
515
|
-
<tr>
|
|
516
|
-
<td style="padding: 40px;">
|
|
517
|
-
<p style="margin: 0 0 20px; font-size: 12px; font-weight: 600; color: #c15f3c; text-transform: uppercase; letter-spacing: 1.5px;">Password Reset</p>
|
|
518
|
-
<h1 style="margin: 0 0 8px; font-size: 22px; font-weight: 600; color: #1a170f;">Choose a new password</h1>
|
|
519
|
-
<p style="margin: 0 0 28px; font-size: 15px; color: #6b6560; line-height: 1.6;">
|
|
520
|
-
Hi ${safeName}, we received a request to reset your password. Click the button below to continue.
|
|
521
|
-
</p>
|
|
522
|
-
<a href="${resetUrl}" style="display: inline-block; background-color: #1a170f; color: #ffffff; padding: 14px 32px; border-radius: 10px; text-decoration: none; font-size: 15px; font-weight: 600;">
|
|
523
|
-
Reset password →
|
|
524
|
-
</a>
|
|
525
|
-
<p style="margin: 28px 0 0; font-size: 13px; color: #9b958e; line-height: 1.6;">
|
|
526
|
-
This link expires in 1 hour. If you didn't request this, you can safely ignore this email.
|
|
527
|
-
</p>
|
|
528
|
-
</td>
|
|
529
|
-
</tr>
|
|
530
|
-
<tr>
|
|
531
|
-
<td style="padding: 0 40px 32px;">
|
|
532
|
-
<div style="border-top: 1px solid #e8e6e1; padding-top: 20px;">
|
|
533
|
-
<p style="margin: 0; font-size: 12px; color: #b5b0a8; line-height: 1.5;">
|
|
534
|
-
If the button doesn't work, copy this link:<br/>
|
|
535
|
-
<a href="${resetUrl}" style="color: #c15f3c; text-decoration: underline; word-break: break-all;">${resetUrl}</a>
|
|
536
|
-
</p>
|
|
537
|
-
</div>
|
|
538
|
-
</td>
|
|
539
|
-
</tr>
|
|
540
|
-
</table>
|
|
541
|
-
</td>
|
|
542
|
-
</tr>
|
|
543
|
-
</table>
|
|
544
|
-
`,
|
|
545
|
-
});
|
|
546
|
-
|
|
547
|
-
logger.info({ userId: user.id }, '[AUTH] Password reset email sent');
|
|
548
|
-
} catch (error) {
|
|
549
|
-
// Log but don't throw — prevents leaking email existence via 500 vs 200
|
|
550
|
-
logger.error({ userId: user.id, err: error }, '[AUTH] Failed to send password reset email');
|
|
551
|
-
}
|
|
362
|
+
await enqueueRecovery(email);
|
|
552
363
|
}
|
|
553
364
|
|
|
554
365
|
export async function resetPassword(token: string, newPassword: string): Promise<void> {
|
|
555
|
-
assertRedisReady('Password reset');
|
|
556
|
-
const
|
|
557
|
-
|
|
558
|
-
// GETDEL reads and removes the token in one step, so a link used twice at
|
|
559
|
-
// the same instant changes the password only once: the second request finds
|
|
560
|
-
// nothing. (A separate GET then DEL let both requests through.) Consumed
|
|
561
|
-
// before the work below, so a failure after this point means a new link.
|
|
562
|
-
const userId = await redis.getdel(`${PASSWORD_RESET_PREFIX}${hashToken(token)}`);
|
|
563
|
-
if (!userId) {
|
|
564
|
-
throw new BadRequestError('Invalid or expired reset token', 'INVALID_RESET_TOKEN');
|
|
565
|
-
}
|
|
366
|
+
assertRedisReady('Password reset');
|
|
367
|
+
const invalid = (): BadRequestError => new BadRequestError('Invalid or expired reset token', 'INVALID_RESET_TOKEN');
|
|
566
368
|
|
|
369
|
+
// Read the password before consumption. The SQL transaction checks this
|
|
370
|
+
// same version under lock before changing it and revoking its sessions.
|
|
371
|
+
const userId = await findRecoveryOwner(token);
|
|
372
|
+
if (!userId) throw invalid();
|
|
567
373
|
const user = await authRepo.findUserById(userId);
|
|
568
|
-
if (!user)
|
|
569
|
-
throw new NotFoundError('User not found', 'USER_NOT_FOUND');
|
|
570
|
-
}
|
|
374
|
+
if (!user || !await consumeRecoveryToken(userId, token)) throw invalid();
|
|
571
375
|
|
|
572
376
|
const hashedPassword = await hashPassword(newPassword);
|
|
573
|
-
await authRepo.
|
|
574
|
-
|
|
575
|
-
// The per-user pointer to the (now consumed) token
|
|
576
|
-
await redis.del(`${PASSWORD_RESET_USER_PREFIX}${userId}`);
|
|
577
|
-
|
|
578
|
-
// Invalidate all sessions for security (force re-login with new password)
|
|
579
|
-
await sessionRepository.deleteAllUserSessions(userId);
|
|
580
|
-
await authRepo.deleteRefreshTokensByUserId(userId);
|
|
581
|
-
|
|
377
|
+
if (!await authRepo.commitPasswordRecovery(userId, user.password, hashedPassword)) throw invalid();
|
|
582
378
|
logger.info({ userId }, '[AUTH] Password reset completed');
|
|
583
379
|
}
|
|
@@ -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
|
+
});
|