create-tigra 3.3.0 → 4.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 +151 -0
- package/README.md +264 -56
- package/bin/create-tigra.js +497 -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 +5 -3
- 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/README.md +79 -0
- 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/README.md +92 -21
- 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/README.md +108 -0
- package/template/server/docker-compose.yml +4 -2
- package/template/server/docs/deployment.md +63 -0
- package/template/server/docs/logging.md +66 -4
- package/template/server/docs/rate-limits.md +153 -0
- package/template/server/docs/testing.md +81 -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
|
@@ -11,13 +11,48 @@ import {
|
|
|
11
11
|
UnauthorizedError,
|
|
12
12
|
NotFoundError,
|
|
13
13
|
BadRequestError,
|
|
14
|
+
TooManyRequestsError,
|
|
15
|
+
describeWait,
|
|
14
16
|
} from '@shared/errors/errors.js';
|
|
17
|
+
import { consumeEmailQuota } from '@libs/email-quota.js';
|
|
18
|
+
import { assertRedisReady } from '@libs/redis-required.js';
|
|
19
|
+
import { hashToken } from '@libs/token-hash.js';
|
|
15
20
|
import type { UserRole } from '@shared/types/index.js';
|
|
16
21
|
import * as authRepo from './auth.repo.js';
|
|
17
22
|
import { sessionRepository } from './session.repo.js';
|
|
18
23
|
import type { RegisterInput, LoginInput } from './auth.schemas.js';
|
|
19
24
|
|
|
25
|
+
/** A refresh that lost a race with a parallel one (see refresh()); its cookies must stay. */
|
|
26
|
+
export const REFRESH_TOKEN_ROTATED = 'REFRESH_TOKEN_ROTATED';
|
|
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
|
+
|
|
20
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.
|
|
21
56
|
const PASSWORD_RESET_PREFIX = 'pw-reset:';
|
|
22
57
|
const PASSWORD_RESET_USER_PREFIX = 'pw-reset-user:';
|
|
23
58
|
|
|
@@ -27,25 +62,26 @@ const PASSWORD_RESET_USER_PREFIX = 'pw-reset-user:';
|
|
|
27
62
|
// passwords at the victim's email (lockout DoS). Scoped to email+IP, an
|
|
28
63
|
// attacker only ever locks out their own address; distributed attempts are
|
|
29
64
|
// still throttled by the per-IP rate limit on the login route.
|
|
30
|
-
//
|
|
65
|
+
// Unknown emails are counted and locked exactly like real ones, so a locked
|
|
66
|
+
// answer (429 LOGIN_LOCKED with the wait time) never reveals that an account
|
|
67
|
+
// exists. Redis failures fail OPEN (no lockout) — consistent with ip-block.ts:
|
|
31
68
|
// availability over lockout, and rate limiting still applies.
|
|
32
69
|
const LOGIN_FAIL_PREFIX = 'login-fail:';
|
|
33
70
|
const LOGIN_LOCK_PREFIX = 'login-lock:';
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
}
|
|
71
|
+
// The failure count is forgotten an hour after the LAST failure (refreshed on each one).
|
|
72
|
+
const LOGIN_FAIL_WINDOW_SECONDS = 60 * 60;
|
|
73
|
+
|
|
74
|
+
// Lock ladder: the 15th failure locks for 15 minutes; the 30th (and every 15th
|
|
75
|
+
// after it) locks for 1 hour. Failures between those steps do not re-lock, so a
|
|
76
|
+
// user whose 15-minute lock ended gets another 14 tries before the long lock.
|
|
77
|
+
export const FIRST_LOCK_AT = 15;
|
|
78
|
+
const FIRST_LOCK_SECONDS = 15 * 60;
|
|
79
|
+
const LONG_LOCK_SECONDS = 60 * 60;
|
|
80
|
+
|
|
81
|
+
/** Lock length (seconds) that this failure count starts, or null for none. */
|
|
82
|
+
export function lockSecondsForFailure(failedAttempts: number): number | null {
|
|
83
|
+
if (failedAttempts === FIRST_LOCK_AT) return FIRST_LOCK_SECONDS;
|
|
84
|
+
if (failedAttempts >= FIRST_LOCK_AT * 2 && failedAttempts % FIRST_LOCK_AT === 0) return LONG_LOCK_SECONDS;
|
|
49
85
|
return null;
|
|
50
86
|
}
|
|
51
87
|
|
|
@@ -53,40 +89,59 @@ function lockoutKey(prefix: string, email: string, ipAddress?: string): string {
|
|
|
53
89
|
return `${prefix}${email.toLowerCase()}:${ipAddress ?? 'unknown'}`;
|
|
54
90
|
}
|
|
55
91
|
|
|
56
|
-
|
|
92
|
+
function loginLockedError(seconds: number): TooManyRequestsError {
|
|
93
|
+
return new TooManyRequestsError(
|
|
94
|
+
`Too many failed sign-in attempts. Try again in ${describeWait(seconds)}.`,
|
|
95
|
+
'LOGIN_LOCKED',
|
|
96
|
+
seconds,
|
|
97
|
+
);
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/** Seconds left on this email+IP lock, or 0 when not locked (also on Redis failure). */
|
|
101
|
+
async function loginLockSeconds(email: string, ipAddress?: string): Promise<number> {
|
|
57
102
|
try {
|
|
58
|
-
const
|
|
59
|
-
return
|
|
103
|
+
const ttl = await getRedis().ttl(lockoutKey(LOGIN_LOCK_PREFIX, email, ipAddress));
|
|
104
|
+
return ttl > 0 ? ttl : 0;
|
|
60
105
|
} catch {
|
|
61
|
-
return
|
|
106
|
+
return 0; // fail open — Redis down must not block all logins
|
|
62
107
|
}
|
|
63
108
|
}
|
|
64
109
|
|
|
65
|
-
|
|
110
|
+
/** Count one failure; returns the lock length (seconds) it started, or 0. */
|
|
111
|
+
async function recordFailedLogin(email: string, ipAddress?: string): Promise<number> {
|
|
66
112
|
try {
|
|
67
113
|
const redis = getRedis();
|
|
68
114
|
const failKey = lockoutKey(LOGIN_FAIL_PREFIX, email, ipAddress);
|
|
69
115
|
|
|
70
116
|
const attempts = await redis.incr(failKey);
|
|
71
|
-
|
|
72
|
-
await redis.expire(failKey, LOGIN_FAIL_WINDOW_SECONDS);
|
|
73
|
-
}
|
|
117
|
+
await redis.expire(failKey, LOGIN_FAIL_WINDOW_SECONDS);
|
|
74
118
|
|
|
75
|
-
const
|
|
76
|
-
if (
|
|
77
|
-
await redis.set(
|
|
78
|
-
|
|
79
|
-
'1',
|
|
80
|
-
'EX',
|
|
81
|
-
Math.ceil(lockDurationMs / 1000),
|
|
82
|
-
);
|
|
119
|
+
const lockSeconds = lockSecondsForFailure(attempts);
|
|
120
|
+
if (lockSeconds) {
|
|
121
|
+
await redis.set(lockoutKey(LOGIN_LOCK_PREFIX, email, ipAddress), '1', 'EX', lockSeconds);
|
|
122
|
+
return lockSeconds;
|
|
83
123
|
}
|
|
124
|
+
return 0;
|
|
84
125
|
} catch {
|
|
85
126
|
// Non-critical: don't break the login error path if tracking fails
|
|
86
127
|
logger.warn('[AUTH] Failed to record failed login attempt');
|
|
128
|
+
return 0;
|
|
87
129
|
}
|
|
88
130
|
}
|
|
89
131
|
|
|
132
|
+
// Hash checked for unknown emails, so they take as long as a wrong password on a real
|
|
133
|
+
// account (no timing hint about which emails are registered). Computed once, on first use.
|
|
134
|
+
// A failed computation is not cached: otherwise every later unknown-email login would
|
|
135
|
+
// answer 500 while real accounts answer 401, revealing which emails are registered.
|
|
136
|
+
let dummyPasswordHash: Promise<string> | undefined;
|
|
137
|
+
function getDummyPasswordHash(): Promise<string> {
|
|
138
|
+
dummyPasswordHash ??= hashPassword(crypto.randomBytes(32).toString('hex')).catch((error: unknown) => {
|
|
139
|
+
dummyPasswordHash = undefined;
|
|
140
|
+
throw error;
|
|
141
|
+
});
|
|
142
|
+
return dummyPasswordHash;
|
|
143
|
+
}
|
|
144
|
+
|
|
90
145
|
async function clearFailedLogins(email: string, ipAddress?: string): Promise<void> {
|
|
91
146
|
try {
|
|
92
147
|
await getRedis().del(
|
|
@@ -192,10 +247,7 @@ export async function register(
|
|
|
192
247
|
};
|
|
193
248
|
}
|
|
194
249
|
|
|
195
|
-
|
|
196
|
-
userId: user.id,
|
|
197
|
-
role: user.role,
|
|
198
|
-
});
|
|
250
|
+
// Session first: the access token carries its id (see authenticate()).
|
|
199
251
|
const refreshToken = generateRefreshToken();
|
|
200
252
|
const refreshTokenExpiresAt = getRefreshTokenExpiresAt();
|
|
201
253
|
|
|
@@ -206,6 +258,12 @@ export async function register(
|
|
|
206
258
|
expiresAt: refreshTokenExpiresAt,
|
|
207
259
|
});
|
|
208
260
|
|
|
261
|
+
const accessToken = signAccessToken({
|
|
262
|
+
userId: user.id,
|
|
263
|
+
role: user.role,
|
|
264
|
+
sessionId: session.id,
|
|
265
|
+
});
|
|
266
|
+
|
|
209
267
|
await authRepo.createRefreshToken({
|
|
210
268
|
token: refreshToken,
|
|
211
269
|
userId: user.id,
|
|
@@ -226,45 +284,38 @@ export async function login(
|
|
|
226
284
|
deviceInfo?: string,
|
|
227
285
|
ipAddress?: string,
|
|
228
286
|
): Promise<AuthResult> {
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
// cannot remotely lock the real user out (lockout DoS).
|
|
237
|
-
if (await isLoginLocked(input.email, ipAddress)) {
|
|
238
|
-
throw new UnauthorizedError('Invalid email or password', 'INVALID_CREDENTIALS');
|
|
287
|
+
// Check the lock FIRST, for any email (registered or not), so a locked
|
|
288
|
+
// answer looks the same whether or not the account exists. Scoped to this
|
|
289
|
+
// email+IP pair, so an attacker spamming bad passwords only locks out their
|
|
290
|
+
// OWN address and cannot remotely lock the real user out (lockout DoS).
|
|
291
|
+
const lockedFor = await loginLockSeconds(input.email, ipAddress);
|
|
292
|
+
if (lockedFor > 0) {
|
|
293
|
+
throw loginLockedError(lockedFor);
|
|
239
294
|
}
|
|
240
295
|
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
if (!valid) {
|
|
249
|
-
await recordFailedLogin(input.email, ipAddress);
|
|
296
|
+
const user = await authRepo.findUserByEmail(input.email);
|
|
297
|
+
// Unknown email: same password-check cost and same failure counting as a
|
|
298
|
+
// wrong password, so neither timing nor the lock reveals registered emails.
|
|
299
|
+
const valid = user
|
|
300
|
+
? await verifyPassword(input.password, user.password)
|
|
301
|
+
: (await verifyPassword(input.password, await getDummyPasswordHash()), false);
|
|
302
|
+
|
|
303
|
+
if (!user || !valid) {
|
|
304
|
+
const lockStarted = await recordFailedLogin(input.email, ipAddress);
|
|
305
|
+
if (lockStarted > 0) {
|
|
306
|
+
throw loginLockedError(lockStarted); // tell the user now, not on the next try
|
|
307
|
+
}
|
|
250
308
|
throw new UnauthorizedError('Invalid email or password', 'INVALID_CREDENTIALS');
|
|
251
309
|
}
|
|
252
310
|
|
|
253
|
-
// Successful login — clear the email+IP failure counter
|
|
254
|
-
// DB-level lockout state from before lockout moved to Redis.
|
|
311
|
+
// Successful login — clear the email+IP failure counter.
|
|
255
312
|
await clearFailedLogins(input.email, ipAddress);
|
|
256
|
-
if (user.failedLoginAttempts > 0 || user.lockedUntil) {
|
|
257
|
-
await authRepo.resetFailedAttempts(user.id);
|
|
258
|
-
}
|
|
259
313
|
|
|
260
314
|
// Reveal account state only now that the password is proven, so an anonymous
|
|
261
315
|
// caller cannot learn whether an email is banned or unverified.
|
|
262
316
|
assertAccountCanSignIn(user);
|
|
263
317
|
|
|
264
|
-
|
|
265
|
-
userId: user.id,
|
|
266
|
-
role: user.role,
|
|
267
|
-
});
|
|
318
|
+
// Session first: the access token carries its id (see authenticate()).
|
|
268
319
|
const refreshToken = generateRefreshToken();
|
|
269
320
|
const refreshTokenExpiresAt = getRefreshTokenExpiresAt();
|
|
270
321
|
|
|
@@ -275,6 +326,12 @@ export async function login(
|
|
|
275
326
|
expiresAt: refreshTokenExpiresAt,
|
|
276
327
|
});
|
|
277
328
|
|
|
329
|
+
const accessToken = signAccessToken({
|
|
330
|
+
userId: user.id,
|
|
331
|
+
role: user.role,
|
|
332
|
+
sessionId: session.id,
|
|
333
|
+
});
|
|
334
|
+
|
|
278
335
|
await authRepo.createRefreshToken({
|
|
279
336
|
token: refreshToken,
|
|
280
337
|
userId: user.id,
|
|
@@ -292,6 +349,10 @@ export async function login(
|
|
|
292
349
|
export async function refresh(refreshToken: string): Promise<{ accessToken: string; refreshToken: string }> {
|
|
293
350
|
const storedToken = await authRepo.findRefreshToken(refreshToken);
|
|
294
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
|
+
}
|
|
295
356
|
throw new UnauthorizedError('Invalid refresh token', 'INVALID_REFRESH_TOKEN');
|
|
296
357
|
}
|
|
297
358
|
|
|
@@ -322,11 +383,18 @@ export async function refresh(refreshToken: string): Promise<{ accessToken: stri
|
|
|
322
383
|
const newAccessToken = signAccessToken({
|
|
323
384
|
userId: user.id,
|
|
324
385
|
role: user.role,
|
|
386
|
+
sessionId: session.id,
|
|
325
387
|
});
|
|
326
388
|
const newRefreshToken = generateRefreshToken();
|
|
327
389
|
|
|
328
|
-
//
|
|
329
|
-
//
|
|
390
|
+
// Note the rotation BEFORE doing it, so a parallel refresh that finds the
|
|
391
|
+
// token already gone (it arrived just after this one won) is recognised as a
|
|
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.
|
|
330
398
|
const rotated = await authRepo.rotateRefreshToken(refreshToken, {
|
|
331
399
|
token: newRefreshToken,
|
|
332
400
|
userId: user.id,
|
|
@@ -335,26 +403,16 @@ export async function refresh(refreshToken: string): Promise<{ accessToken: stri
|
|
|
335
403
|
});
|
|
336
404
|
|
|
337
405
|
if (!rotated) {
|
|
338
|
-
//
|
|
339
|
-
//
|
|
340
|
-
//
|
|
341
|
-
//
|
|
342
|
-
//
|
|
343
|
-
//
|
|
344
|
-
//
|
|
345
|
-
//
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
// the initial not-found lookup above can only reject it. Full replay
|
|
349
|
-
// attribution would require tombstoning consumed tokens (e.g. a revokedAt
|
|
350
|
-
// column) instead of deleting them — a schema change out of scope here.
|
|
351
|
-
logger.warn(
|
|
352
|
-
{ userId: user.id },
|
|
353
|
-
'[AUTH] Refresh token reuse detected — revoking all sessions and refresh tokens for user',
|
|
354
|
-
);
|
|
355
|
-
await authRepo.deleteRefreshTokensByUserId(user.id);
|
|
356
|
-
await sessionRepository.deleteAllUserSessions(user.id);
|
|
357
|
-
throw new UnauthorizedError('Refresh token already used', 'INVALID_REFRESH_TOKEN');
|
|
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);
|
|
358
416
|
}
|
|
359
417
|
|
|
360
418
|
return {
|
|
@@ -412,6 +470,14 @@ export async function logoutAllSessions(userId: string): Promise<number> {
|
|
|
412
470
|
}
|
|
413
471
|
|
|
414
472
|
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
|
+
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
|
+
|
|
415
481
|
const user = await authRepo.findUserByEmail(email);
|
|
416
482
|
|
|
417
483
|
// Silent return if user not found — prevents email enumeration
|
|
@@ -419,18 +485,19 @@ export async function forgotPassword(email: string): Promise<void> {
|
|
|
419
485
|
|
|
420
486
|
const redis = getRedis();
|
|
421
487
|
|
|
422
|
-
// Invalidate any existing token for this user
|
|
423
|
-
const
|
|
424
|
-
if (
|
|
425
|
-
await redis.del(`${PASSWORD_RESET_PREFIX}${
|
|
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}`);
|
|
426
492
|
await redis.del(`${PASSWORD_RESET_USER_PREFIX}${user.id}`);
|
|
427
493
|
}
|
|
428
494
|
|
|
429
|
-
// Generate secure token
|
|
495
|
+
// Generate a secure token; only its fingerprint goes to Redis (1 hour TTL)
|
|
430
496
|
const token = crypto.randomBytes(32).toString('hex');
|
|
497
|
+
const tokenHash = hashToken(token);
|
|
431
498
|
|
|
432
|
-
await redis.set(`${PASSWORD_RESET_PREFIX}${
|
|
433
|
-
await redis.set(`${PASSWORD_RESET_USER_PREFIX}${user.id}`,
|
|
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);
|
|
434
501
|
|
|
435
502
|
// Build reset URL and send email
|
|
436
503
|
const resetUrl = `${env.CLIENT_URL}/reset-password?token=${token}`;
|
|
@@ -485,9 +552,14 @@ export async function forgotPassword(email: string): Promise<void> {
|
|
|
485
552
|
}
|
|
486
553
|
|
|
487
554
|
export async function resetPassword(token: string, newPassword: string): Promise<void> {
|
|
555
|
+
assertRedisReady('Password reset'); // the token is stored in Redis
|
|
488
556
|
const redis = getRedis();
|
|
489
557
|
|
|
490
|
-
|
|
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)}`);
|
|
491
563
|
if (!userId) {
|
|
492
564
|
throw new BadRequestError('Invalid or expired reset token', 'INVALID_RESET_TOKEN');
|
|
493
565
|
}
|
|
@@ -500,8 +572,7 @@ export async function resetPassword(token: string, newPassword: string): Promise
|
|
|
500
572
|
const hashedPassword = await hashPassword(newPassword);
|
|
501
573
|
await authRepo.updateUserPassword(userId, hashedPassword);
|
|
502
574
|
|
|
503
|
-
//
|
|
504
|
-
await redis.del(`${PASSWORD_RESET_PREFIX}${token}`);
|
|
575
|
+
// The per-user pointer to the (now consumed) token
|
|
505
576
|
await redis.del(`${PASSWORD_RESET_USER_PREFIX}${userId}`);
|
|
506
577
|
|
|
507
578
|
// Invalidate all sessions for security (force re-login with new password)
|
|
@@ -62,6 +62,18 @@ export class SessionRepository {
|
|
|
62
62
|
return result.count;
|
|
63
63
|
}
|
|
64
64
|
|
|
65
|
+
/**
|
|
66
|
+
* Delete every session of a user EXCEPT one (the device that asked). Used by
|
|
67
|
+
* an owner's password change: other devices are signed out, this one stays.
|
|
68
|
+
* Their refresh tokens go with them (onDelete: Cascade on RefreshToken.session).
|
|
69
|
+
*/
|
|
70
|
+
async deleteOtherUserSessions(userId: string, keepSessionId: string): Promise<number> {
|
|
71
|
+
const result = await prisma.session.deleteMany({
|
|
72
|
+
where: { userId, id: { not: keepSessionId } },
|
|
73
|
+
});
|
|
74
|
+
return result.count;
|
|
75
|
+
}
|
|
76
|
+
|
|
65
77
|
/**
|
|
66
78
|
* Delete expired sessions (for cleanup cron job)
|
|
67
79
|
*/
|
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
* Drives the REAL Fastify app via `app.inject()` against the MySQL 8 + Redis
|
|
6
6
|
* booted by `src/test/integration.setup.ts`. The setup file points
|
|
7
7
|
* UPLOAD_PUBLIC_DIR / UPLOAD_PRIVATE_DIR at isolated temp dirs (exported via
|
|
8
|
-
* `
|
|
8
|
+
* `integrationServices`) BEFORE env.ts is evaluated, so this test controls the files
|
|
9
9
|
* on disk and asserts exactly what is and isn't reachable.
|
|
10
10
|
*
|
|
11
11
|
* What this proves:
|
|
@@ -22,7 +22,7 @@ import { describe, it, expect, beforeAll, afterAll } from 'vitest';
|
|
|
22
22
|
import fs from 'node:fs/promises';
|
|
23
23
|
import path from 'node:path';
|
|
24
24
|
import type { FastifyInstance } from 'fastify';
|
|
25
|
-
import {
|
|
25
|
+
import { integrationServices } from '@/test/integration.setup.js';
|
|
26
26
|
|
|
27
27
|
let app: FastifyInstance;
|
|
28
28
|
|
|
@@ -75,18 +75,18 @@ beforeAll(async () => {
|
|
|
75
75
|
|
|
76
76
|
// --- Seed fixtures directly on disk, in the temp tiers the app reads. ---
|
|
77
77
|
// PUBLIC avatar (served statically, no auth).
|
|
78
|
-
const publicAvatarDir = path.join(
|
|
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
81
|
|
|
82
82
|
// PRIVATE file (auth-gated route only).
|
|
83
|
-
const privateUserDir = path.join(
|
|
83
|
+
const privateUserDir = path.join(integrationServices.uploadPrivateDir, 'users', userId);
|
|
84
84
|
await fs.mkdir(privateUserDir, { recursive: true });
|
|
85
85
|
await fs.writeFile(path.join(privateUserDir, 'doc.txt'), Buffer.from(PRIVATE_BODY));
|
|
86
86
|
|
|
87
87
|
// A SECRET file in the private tier, addressable only via traversal from the
|
|
88
88
|
// static root — used to prove the static mount cannot reach the private tier.
|
|
89
|
-
await fs.writeFile(path.join(
|
|
89
|
+
await fs.writeFile(path.join(integrationServices.uploadPrivateDir, 'secret.txt'), Buffer.from('TOP-SECRET'));
|
|
90
90
|
});
|
|
91
91
|
|
|
92
92
|
afterAll(async () => {
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Avatar upload (usersService.uploadAvatar) against an in-memory user row and
|
|
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';
|
|
11
|
+
import { fileStorageService } from '@libs/storage/file-storage.service.js';
|
|
12
|
+
import { testUsers } from '@/test/setup.js';
|
|
13
|
+
|
|
14
|
+
vi.mock('@modules/auth/auth.repo.js');
|
|
15
|
+
vi.mock('@modules/auth/session.repo.js');
|
|
16
|
+
vi.mock('@libs/password.js');
|
|
17
|
+
vi.mock('../users.repo.js');
|
|
18
|
+
vi.mock('@libs/storage/image-optimizer.service.js', () => ({
|
|
19
|
+
imageOptimizerService: { optimizeAvatar: vi.fn(async (b: Buffer) => b) },
|
|
20
|
+
}));
|
|
21
|
+
vi.mock('@libs/storage/file-storage.service.js', () => ({
|
|
22
|
+
fileStorageService: { saveAvatar: vi.fn(), removeAvatarFile: vi.fn() },
|
|
23
|
+
}));
|
|
24
|
+
|
|
25
|
+
const USER_ID = testUsers.validUser.id;
|
|
26
|
+
const urlOf = (file: string): string => `/uploads/users/${USER_ID}/avatar/${file}`;
|
|
27
|
+
|
|
28
|
+
/** The user row's avatarUrl and the files in the avatar folder. */
|
|
29
|
+
let row: { avatarUrl: string | null };
|
|
30
|
+
let folder: Set<string>;
|
|
31
|
+
let saved = 0;
|
|
32
|
+
/** When set, the Nth saveAvatar waits for this before returning (to force an interleaving). */
|
|
33
|
+
let holdSave: { call: number; until: Promise<unknown> } | null = null;
|
|
34
|
+
|
|
35
|
+
beforeEach(() => {
|
|
36
|
+
vi.clearAllMocks();
|
|
37
|
+
row = { avatarUrl: null };
|
|
38
|
+
folder = new Set();
|
|
39
|
+
saved = 0;
|
|
40
|
+
holdSave = null;
|
|
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
|
+
});
|
|
58
|
+
});
|
|
59
|
+
|
|
60
|
+
/** The invariant: the folder holds exactly the database's file. */
|
|
61
|
+
function expectFolderMatchesDatabase(): void {
|
|
62
|
+
expect(row.avatarUrl).not.toBeNull();
|
|
63
|
+
expect([...folder]).toEqual([row.avatarUrl!.split('/').pop()]);
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
const upload = (): Promise<{ avatarUrl: string }> => usersService.uploadAvatar(USER_ID, Buffer.from('img'), 'a.png');
|
|
67
|
+
|
|
68
|
+
describe('avatar upload', () => {
|
|
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
|
+
});
|
|
107
|
+
|
|
108
|
+
it('a database error removes the new file and passes the error on', async () => {
|
|
109
|
+
vi.mocked(usersRepository.swapAvatarUrl).mockRejectedValueOnce(new Error('db down'));
|
|
110
|
+
await expect(upload()).rejects.toThrow('db down');
|
|
111
|
+
expect(folder.size).toBe(0);
|
|
112
|
+
expect(row.avatarUrl).toBeNull();
|
|
113
|
+
});
|
|
114
|
+
|
|
115
|
+
it('an avatar that keeps changing answers 409 AVATAR_BUSY and leaves no new file', async () => {
|
|
116
|
+
vi.mocked(usersRepository.swapAvatarUrl).mockResolvedValue(false);
|
|
117
|
+
await expect(upload()).rejects.toMatchObject({ statusCode: 409, code: 'AVATAR_BUSY' });
|
|
118
|
+
expect(folder.size).toBe(0);
|
|
119
|
+
});
|
|
120
|
+
});
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Name rules at register and profile update: the name is trimmed BEFORE its
|
|
3
|
+
* length is checked, so blanks never become an empty name, and an update that
|
|
4
|
+
* sends nothing is wrong input (422 VALIDATION_FAILED naming both fields).
|
|
5
|
+
*/
|
|
6
|
+
import { describe, expect, it } from 'vitest';
|
|
7
|
+
import { registerSchema } from '@modules/auth/auth.schemas.js';
|
|
8
|
+
import { UpdateProfileSchema } from '../users.schemas.js';
|
|
9
|
+
|
|
10
|
+
const base = { email: 'qa@example.test', password: 'Passw0rd-123', lastName: 'Tester' };
|
|
11
|
+
|
|
12
|
+
describe('register name rules', () => {
|
|
13
|
+
it.each([' ', ' a ', '\t\n'])('refuses %j as a first name', (firstName) => {
|
|
14
|
+
const result = registerSchema.safeParse({ ...base, firstName });
|
|
15
|
+
expect(result.success).toBe(false);
|
|
16
|
+
expect(result.error?.issues.map((i) => i.path.join('.'))).toEqual(['firstName']);
|
|
17
|
+
});
|
|
18
|
+
|
|
19
|
+
it('stores the trimmed name', () => {
|
|
20
|
+
expect(registerSchema.parse({ ...base, firstName: ' Ann ' }).firstName).toBe('Ann');
|
|
21
|
+
});
|
|
22
|
+
|
|
23
|
+
it('judges the length after trimming (100 letters plus spaces is fine)', () => {
|
|
24
|
+
expect(registerSchema.parse({ ...base, firstName: `${'a'.repeat(100)} ` }).firstName).toHaveLength(100);
|
|
25
|
+
});
|
|
26
|
+
});
|
|
27
|
+
|
|
28
|
+
describe('profile update rules', () => {
|
|
29
|
+
it('refuses an update with nothing in it, naming both fields', () => {
|
|
30
|
+
const result = UpdateProfileSchema.safeParse({});
|
|
31
|
+
expect(result.success).toBe(false);
|
|
32
|
+
expect(result.error?.issues.map((i) => i.path.join('.')).sort()).toEqual(['firstName', 'lastName']);
|
|
33
|
+
});
|
|
34
|
+
|
|
35
|
+
it('refuses a blank name instead of silently ignoring it', () => {
|
|
36
|
+
expect(UpdateProfileSchema.safeParse({ firstName: ' ' }).success).toBe(false);
|
|
37
|
+
});
|
|
38
|
+
|
|
39
|
+
it('accepts and trims one field', () => {
|
|
40
|
+
expect(UpdateProfileSchema.parse({ firstName: ' Bo ' })).toEqual({ firstName: 'Bo' });
|
|
41
|
+
});
|
|
42
|
+
|
|
43
|
+
it('drops fields it does not know (role cannot be set here)', () => {
|
|
44
|
+
expect(UpdateProfileSchema.parse({ lastName: 'Lee', role: 'ADMIN' })).toEqual({ lastName: 'Lee' });
|
|
45
|
+
});
|
|
46
|
+
});
|