create-tigra 3.2.0 → 4.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +81 -12
- package/bin/create-tigra.js +495 -472
- package/lib/patchers/email-verification.patcher.js +160 -44
- package/modules/email-verification/client/hooks/useVerification.ts +4 -1
- package/modules/email-verification/server/__tests__/verification.integration.test.ts +115 -0
- package/modules/email-verification/server/verification.controller.ts +3 -1
- package/modules/email-verification/server/verification.service.ts +81 -21
- package/package.json +3 -2
- package/template/.github/dependabot.yml +47 -0
- package/template/.github/workflows/audit.yml +36 -0
- package/template/.github/workflows/ci.yml +79 -0
- package/template/AGENTS.md +18 -9
- package/template/client/.dockerignore +1 -0
- package/template/client/.env.example.production +13 -2
- package/template/client/AGENTS.md +13 -5
- package/template/client/Dockerfile +186 -14
- package/template/client/next.config.ts +1 -1
- package/template/client/package-lock.json +15983 -14181
- package/template/client/package.json +56 -48
- package/template/client/scripts/check-sharp.mjs +53 -0
- package/template/client/scripts/next-dev.cjs +5 -1
- package/template/client/src/__tests__/proxy.test.ts +92 -0
- package/template/client/src/app/healthz/route.ts +16 -0
- package/template/client/src/app/layout.tsx +9 -3
- package/template/client/src/app/page.tsx +2 -2
- package/template/client/src/app/providers.tsx +23 -4
- package/template/client/src/components/layout/Header.tsx +7 -3
- package/template/client/src/features/admin/hooks/useAdminSessions.ts +2 -1
- package/template/client/src/features/admin/hooks/useAdminUsers.ts +3 -1
- package/template/client/src/features/admin/types/admin.types.ts +2 -3
- package/template/client/src/features/auth/components/AuthInitializer.tsx +38 -19
- package/template/client/src/features/auth/components/ForgotPasswordForm.tsx +107 -0
- package/template/client/src/features/auth/components/LimitNotice.tsx +28 -0
- package/template/client/src/features/auth/components/LoginForm.tsx +18 -4
- package/template/client/src/features/auth/components/RegisterForm.tsx +23 -7
- package/template/client/src/features/auth/hooks/useAuth.ts +27 -7
- package/template/client/src/features/auth/hooks/usePasswordReset.ts +7 -1
- package/template/client/src/features/auth/services/auth.service.ts +8 -3
- package/template/client/src/features/auth/store/authSlice.ts +7 -2
- package/template/client/src/features/auth/types/auth.types.ts +3 -0
- package/template/client/src/instrumentation-client.ts +9 -1
- package/template/client/src/instrumentation.ts +6 -0
- package/template/client/src/lib/api/__tests__/axios.config.test.ts +183 -0
- package/template/client/src/lib/api/api.types.ts +14 -0
- package/template/client/src/lib/api/axios.config.ts +101 -15
- package/template/client/src/lib/api/hard-redirect.ts +8 -0
- package/template/client/src/lib/api/session-events.ts +29 -0
- package/template/client/src/lib/constants/routes.ts +12 -0
- package/template/client/src/lib/observability/sentry-scrub.ts +71 -0
- package/template/client/src/lib/utils/__tests__/error.test.ts +119 -0
- package/template/client/src/lib/utils/__tests__/form.test.ts +42 -0
- package/template/client/src/lib/utils/__tests__/paths.test.ts +43 -0
- package/template/client/src/lib/utils/__tests__/security.test.ts +40 -0
- package/template/client/src/lib/utils/__tests__/session-marker.test.ts +27 -0
- package/template/client/src/lib/utils/error.ts +86 -1
- package/template/client/src/lib/utils/form.ts +31 -0
- package/template/client/src/lib/utils/paths.ts +18 -0
- package/template/client/src/lib/utils/security.ts +37 -0
- package/template/client/src/lib/utils/session-marker.ts +24 -0
- package/template/client/src/{middleware.ts → proxy.ts} +25 -11
- package/template/client/src/store/__tests__/store.test.ts +44 -0
- package/template/client/src/store/index.ts +26 -8
- package/template/client/vitest.config.mts +48 -0
- package/template/server/.env.example +280 -269
- package/template/server/.env.example.production +283 -236
- package/template/server/AGENTS.md +13 -4
- package/template/server/Dockerfile +181 -14
- package/template/server/docker-compose.yml +4 -2
- package/template/server/docs/deployment.md +63 -0
- package/template/server/docs/logging.md +52 -4
- package/template/server/docs/rate-limits.md +153 -0
- package/template/server/docs/testing.md +63 -0
- package/template/server/eslint.config.mjs +19 -0
- package/template/server/package-lock.json +8784 -8743
- package/template/server/package.json +79 -75
- package/template/server/prisma/migrations/0_init/migration.sql +82 -0
- package/template/server/prisma/migrations/migration_lock.toml +3 -0
- package/template/server/prisma/schema.prisma +19 -6
- package/template/server/prisma/seed.ts +13 -5
- package/template/server/scripts/check-heic.mjs +40 -0
- package/template/server/scripts/check-sharp.mjs +53 -0
- package/template/server/src/__tests__/routes.integration.test.ts +280 -0
- package/template/server/src/app.ts +248 -335
- package/template/server/src/config/__tests__/env.test.ts +219 -0
- package/template/server/src/config/__tests__/rate-limit.config.test.ts +158 -0
- package/template/server/src/config/env.ts +326 -171
- package/template/server/src/config/rate-limit.config.ts +157 -106
- package/template/server/src/jobs/__tests__/cleanup-deleted-accounts.job.test.ts +110 -0
- package/template/server/src/jobs/__tests__/cleanup-expired-auth.job.test.ts +44 -0
- package/template/server/src/jobs/__tests__/jobs.integration.test.ts +88 -0
- package/template/server/src/jobs/__tests__/schedule.test.ts +92 -0
- package/template/server/src/jobs/cleanup-deleted-accounts.job.ts +81 -65
- package/template/server/src/jobs/cleanup-expired-auth.job.ts +32 -24
- package/template/server/src/jobs/index.ts +12 -2
- package/template/server/src/jobs/refresh-cloudflare-ranges.job.ts +28 -0
- package/template/server/src/jobs/schedule.ts +50 -0
- package/template/server/src/libs/__tests__/auth.test.ts +168 -0
- package/template/server/src/libs/__tests__/client-ip.test.ts +257 -121
- package/template/server/src/libs/__tests__/cloudflare-ranges.test.ts +79 -0
- package/template/server/src/libs/__tests__/cookies.test.ts +113 -0
- package/template/server/src/libs/__tests__/email-quota.test.ts +81 -0
- package/template/server/src/libs/__tests__/email.test.ts +68 -0
- package/template/server/src/libs/__tests__/error-handler.test.ts +162 -0
- package/template/server/src/libs/__tests__/health-db-down.integration.test.ts +37 -0
- package/template/server/src/libs/__tests__/health-redis-down.integration.test.ts +45 -0
- package/template/server/src/libs/__tests__/health-routes.test.ts +83 -0
- package/template/server/src/libs/__tests__/health.integration.test.ts +118 -0
- package/template/server/src/libs/__tests__/http.test.ts +74 -2
- package/template/server/src/libs/__tests__/ip-block.test.ts +179 -62
- package/template/server/src/libs/__tests__/logger.test.ts +50 -0
- package/template/server/src/libs/__tests__/monitoring.test.ts +185 -0
- package/template/server/src/libs/__tests__/outbound.integration.test.ts +48 -0
- package/template/server/src/libs/__tests__/prisma-client.test.ts +28 -0
- package/template/server/src/libs/__tests__/query-counter.integration.test.ts +53 -0
- package/template/server/src/libs/__tests__/rate-limiting.test.ts +146 -0
- package/template/server/src/libs/__tests__/rate-limits.integration.test.ts +53 -0
- package/template/server/src/libs/__tests__/redis-required.test.ts +30 -0
- package/template/server/src/libs/__tests__/redis.test.ts +59 -0
- package/template/server/src/libs/__tests__/request-id.test.ts +25 -0
- package/template/server/src/libs/__tests__/requestLogger.test.ts +126 -0
- package/template/server/src/libs/__tests__/safe-http.test.ts +138 -0
- package/template/server/src/libs/__tests__/sentry-scrub.test.ts +82 -0
- package/template/server/src/libs/__tests__/shutdown.test.ts +89 -0
- package/template/server/src/libs/__tests__/url-safety.test.ts +130 -80
- package/template/server/src/libs/account-status.ts +52 -0
- package/template/server/src/libs/auth.ts +51 -12
- package/template/server/src/libs/client-ip.ts +158 -77
- package/template/server/src/libs/cloudflare-ranges.ts +132 -0
- package/template/server/src/libs/cookies.ts +91 -24
- package/template/server/src/libs/email-quota.ts +74 -0
- package/template/server/src/libs/email.ts +46 -9
- package/template/server/src/libs/error-handler.ts +111 -0
- package/template/server/src/libs/health-routes.ts +53 -0
- package/template/server/src/libs/http.ts +139 -47
- package/template/server/src/libs/ip-address.ts +37 -0
- package/template/server/src/libs/ip-block.ts +284 -220
- package/template/server/src/libs/logger.ts +41 -12
- package/template/server/src/libs/monitoring.ts +131 -42
- package/template/server/src/libs/observability/sentry.ts +80 -0
- package/template/server/src/libs/origin-check.ts +9 -7
- package/template/server/src/libs/prisma.ts +47 -4
- package/template/server/src/libs/query-counter.ts +71 -59
- package/template/server/src/libs/rate-limiting.ts +110 -0
- package/template/server/src/libs/redis-required.ts +28 -0
- package/template/server/src/libs/redis.ts +108 -18
- package/template/server/src/libs/request-id.ts +18 -0
- package/template/server/src/libs/requestLogger.ts +112 -17
- package/template/server/src/libs/safe-http.ts +101 -0
- package/template/server/src/libs/shutdown.ts +87 -0
- package/template/server/src/libs/storage/__tests__/fixtures/tiny-heic.ts +13 -0
- package/template/server/src/libs/storage/__tests__/image-optimizer.test.ts +143 -0
- package/template/server/src/libs/storage/__tests__/multipart-limits.test.ts +91 -0
- package/template/server/src/libs/storage/__tests__/upload-persistence.test.ts +52 -0
- package/template/server/src/libs/storage/file-storage.service.ts +104 -83
- package/template/server/src/libs/storage/file-validator.ts +48 -46
- package/template/server/src/libs/storage/image-optimizer.service.ts +78 -72
- package/template/server/src/libs/token-hash.ts +18 -0
- package/template/server/src/libs/url-safety.ts +127 -121
- package/template/server/src/libs/validation-errors.ts +86 -0
- package/template/server/src/modules/admin/__tests__/admin-actions.integration.test.ts +255 -0
- package/template/server/src/modules/admin/__tests__/admin.health.test.ts +82 -0
- package/template/server/src/modules/admin/__tests__/admin.repo.test.ts +55 -0
- package/template/server/src/modules/admin/__tests__/admin.schemas.test.ts +38 -0
- package/template/server/src/modules/admin/__tests__/admin.service.test.ts +162 -0
- package/template/server/src/modules/admin/admin.controller.ts +66 -49
- package/template/server/src/modules/admin/admin.repo.ts +56 -13
- package/template/server/src/modules/admin/admin.routes.ts +48 -2
- package/template/server/src/modules/admin/admin.schemas.ts +18 -6
- package/template/server/src/modules/admin/admin.service.ts +73 -7
- package/template/server/src/modules/auth/__tests__/auth.controller.test.ts +39 -0
- package/template/server/src/modules/auth/__tests__/auth.integration.test.ts +9 -3
- package/template/server/src/modules/auth/__tests__/auth.service.dummy-hash.test.ts +34 -0
- package/template/server/src/modules/auth/__tests__/auth.service.test.ts +332 -49
- package/template/server/src/modules/auth/__tests__/session-cleanup.test.ts +39 -0
- package/template/server/src/modules/auth/__tests__/sessions.integration.test.ts +246 -0
- package/template/server/src/modules/auth/__tests__/token-fingerprints.test.ts +119 -0
- package/template/server/src/modules/auth/auth.controller.ts +133 -128
- package/template/server/src/modules/auth/auth.repo.ts +60 -42
- package/template/server/src/modules/auth/auth.schemas.ts +5 -2
- package/template/server/src/modules/auth/auth.service.ts +197 -109
- package/template/server/src/modules/auth/session.repo.ts +12 -12
- package/template/server/src/modules/files/__tests__/files.integration.test.ts +5 -5
- package/template/server/src/modules/users/__tests__/avatar-upload.test.ts +120 -0
- package/template/server/src/modules/users/__tests__/name-rules.test.ts +46 -0
- package/template/server/src/modules/users/__tests__/users.integration.test.ts +295 -0
- package/template/server/src/modules/users/__tests__/users.repo.test.ts +37 -0
- package/template/server/src/modules/users/__tests__/users.service.test.ts +129 -0
- package/template/server/src/modules/users/users.controller.ts +9 -38
- package/template/server/src/modules/users/users.repo.ts +25 -7
- package/template/server/src/modules/users/users.routes.ts +3 -22
- package/template/server/src/modules/users/users.schemas.ts +15 -9
- package/template/server/src/modules/users/users.service.ts +105 -93
- package/template/server/src/scripts/make-admin.ts +48 -0
- package/template/server/src/server.ts +48 -26
- package/template/server/src/shared/errors/AppError.ts +27 -1
- package/template/server/src/shared/errors/errors.ts +42 -5
- package/template/server/src/shared/responses/successResponse.ts +22 -3
- package/template/server/src/shared/types/index.ts +7 -0
- package/template/server/src/test/__tests__/integration-services.test.ts +66 -0
- package/template/server/src/test/integration-helpers.ts +343 -0
- package/template/server/src/test/integration-services.ts +74 -0
- package/template/server/src/test/integration.global-setup.ts +144 -0
- package/template/server/src/test/integration.setup.ts +35 -158
- package/template/server/src/test/setup.ts +23 -8
- package/template/server/tsconfig.build.json +1 -1
- package/template/server/tsconfig.json +1 -0
- package/template/server/vitest.config.ts +17 -4
- package/template/server/vitest.integration.config.ts +18 -13
- package/template/server/src/libs/storage/filename-sanitizer.ts +0 -71
|
@@ -5,19 +5,54 @@ import { getRedis } from '@libs/redis.js';
|
|
|
5
5
|
import { sendEmail } from '@libs/email.js';
|
|
6
6
|
import { logger } from '@libs/logger.js';
|
|
7
7
|
import { env } from '@config/env.js';
|
|
8
|
+
import { assertAccountCanSignIn } from '@libs/account-status.js';
|
|
8
9
|
import {
|
|
9
10
|
ConflictError,
|
|
10
11
|
UnauthorizedError,
|
|
11
|
-
ForbiddenError,
|
|
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(
|
|
@@ -106,6 +161,8 @@ interface SanitizedUser {
|
|
|
106
161
|
avatarUrl: string | null;
|
|
107
162
|
role: UserRole;
|
|
108
163
|
isActive: boolean;
|
|
164
|
+
/** ISO timestamp of email verification, or null while unverified. */
|
|
165
|
+
emailVerifiedAt: string | null;
|
|
109
166
|
createdAt: string;
|
|
110
167
|
updatedAt: string;
|
|
111
168
|
}
|
|
@@ -131,6 +188,7 @@ function sanitizeUser(user: {
|
|
|
131
188
|
avatarUrl?: string | null;
|
|
132
189
|
role: UserRole;
|
|
133
190
|
isActive: boolean;
|
|
191
|
+
emailVerifiedAt: Date | null;
|
|
134
192
|
createdAt: Date;
|
|
135
193
|
updatedAt: Date;
|
|
136
194
|
}): SanitizedUser {
|
|
@@ -142,6 +200,7 @@ function sanitizeUser(user: {
|
|
|
142
200
|
avatarUrl: user.avatarUrl ?? null,
|
|
143
201
|
role: user.role,
|
|
144
202
|
isActive: user.isActive,
|
|
203
|
+
emailVerifiedAt: user.emailVerifiedAt ? user.emailVerifiedAt.toISOString() : null,
|
|
145
204
|
createdAt: user.createdAt.toISOString(),
|
|
146
205
|
updatedAt: user.updatedAt.toISOString(),
|
|
147
206
|
};
|
|
@@ -167,28 +226,28 @@ export async function register(
|
|
|
167
226
|
}
|
|
168
227
|
|
|
169
228
|
const hashedPassword = await hashPassword(input.password);
|
|
170
|
-
|
|
229
|
+
// A new account is never banned (isActive stays at its default true). When
|
|
230
|
+
// verification is required it starts unverified and gets no session until it
|
|
231
|
+
// proves its email; otherwise it counts as verified from the start.
|
|
232
|
+
const requiresVerification = env.REQUIRE_USER_VERIFICATION;
|
|
171
233
|
|
|
172
234
|
const user = await authRepo.createUser({
|
|
173
235
|
email: input.email,
|
|
174
236
|
password: hashedPassword,
|
|
175
237
|
firstName: input.firstName,
|
|
176
238
|
lastName: input.lastName,
|
|
177
|
-
|
|
239
|
+
emailVerifiedAt: requiresVerification ? null : new Date(),
|
|
178
240
|
});
|
|
179
241
|
|
|
180
242
|
// If verification is required, don't issue tokens — user must verify first
|
|
181
|
-
if (
|
|
243
|
+
if (requiresVerification) {
|
|
182
244
|
return {
|
|
183
245
|
user: sanitizeUser(user),
|
|
184
246
|
requiresVerification: true,
|
|
185
247
|
};
|
|
186
248
|
}
|
|
187
249
|
|
|
188
|
-
|
|
189
|
-
userId: user.id,
|
|
190
|
-
role: user.role,
|
|
191
|
-
});
|
|
250
|
+
// Session first: the access token carries its id (see authenticate()).
|
|
192
251
|
const refreshToken = generateRefreshToken();
|
|
193
252
|
const refreshTokenExpiresAt = getRefreshTokenExpiresAt();
|
|
194
253
|
|
|
@@ -199,6 +258,12 @@ export async function register(
|
|
|
199
258
|
expiresAt: refreshTokenExpiresAt,
|
|
200
259
|
});
|
|
201
260
|
|
|
261
|
+
const accessToken = signAccessToken({
|
|
262
|
+
userId: user.id,
|
|
263
|
+
role: user.role,
|
|
264
|
+
sessionId: session.id,
|
|
265
|
+
});
|
|
266
|
+
|
|
202
267
|
await authRepo.createRefreshToken({
|
|
203
268
|
token: refreshToken,
|
|
204
269
|
userId: user.id,
|
|
@@ -219,46 +284,38 @@ export async function login(
|
|
|
219
284
|
deviceInfo?: string,
|
|
220
285
|
ipAddress?: string,
|
|
221
286
|
): Promise<AuthResult> {
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
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);
|
|
225
294
|
}
|
|
226
295
|
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
// DB-level lock (legacy data or manual admin lock) is still honored.
|
|
240
|
-
if (user.lockedUntil && user.lockedUntil > new Date()) {
|
|
241
|
-
throw new UnauthorizedError('Invalid email or password', 'INVALID_CREDENTIALS');
|
|
242
|
-
}
|
|
243
|
-
|
|
244
|
-
const valid = await verifyPassword(input.password, user.password);
|
|
245
|
-
|
|
246
|
-
if (!valid) {
|
|
247
|
-
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
|
+
}
|
|
248
308
|
throw new UnauthorizedError('Invalid email or password', 'INVALID_CREDENTIALS');
|
|
249
309
|
}
|
|
250
310
|
|
|
251
|
-
// Successful login — clear the email+IP failure counter
|
|
252
|
-
// DB-level lockout state from before lockout moved to Redis.
|
|
311
|
+
// Successful login — clear the email+IP failure counter.
|
|
253
312
|
await clearFailedLogins(input.email, ipAddress);
|
|
254
|
-
if (user.failedLoginAttempts > 0 || user.lockedUntil) {
|
|
255
|
-
await authRepo.resetFailedAttempts(user.id);
|
|
256
|
-
}
|
|
257
313
|
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
314
|
+
// Reveal account state only now that the password is proven, so an anonymous
|
|
315
|
+
// caller cannot learn whether an email is banned or unverified.
|
|
316
|
+
assertAccountCanSignIn(user);
|
|
317
|
+
|
|
318
|
+
// Session first: the access token carries its id (see authenticate()).
|
|
262
319
|
const refreshToken = generateRefreshToken();
|
|
263
320
|
const refreshTokenExpiresAt = getRefreshTokenExpiresAt();
|
|
264
321
|
|
|
@@ -269,6 +326,12 @@ export async function login(
|
|
|
269
326
|
expiresAt: refreshTokenExpiresAt,
|
|
270
327
|
});
|
|
271
328
|
|
|
329
|
+
const accessToken = signAccessToken({
|
|
330
|
+
userId: user.id,
|
|
331
|
+
role: user.role,
|
|
332
|
+
sessionId: session.id,
|
|
333
|
+
});
|
|
334
|
+
|
|
272
335
|
await authRepo.createRefreshToken({
|
|
273
336
|
token: refreshToken,
|
|
274
337
|
userId: user.id,
|
|
@@ -286,6 +349,10 @@ export async function login(
|
|
|
286
349
|
export async function refresh(refreshToken: string): Promise<{ accessToken: string; refreshToken: string }> {
|
|
287
350
|
const storedToken = await authRepo.findRefreshToken(refreshToken);
|
|
288
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
|
+
}
|
|
289
356
|
throw new UnauthorizedError('Invalid refresh token', 'INVALID_REFRESH_TOKEN');
|
|
290
357
|
}
|
|
291
358
|
|
|
@@ -294,50 +361,58 @@ export async function refresh(refreshToken: string): Promise<{ accessToken: stri
|
|
|
294
361
|
throw new UnauthorizedError('Refresh token expired', 'REFRESH_TOKEN_EXPIRED');
|
|
295
362
|
}
|
|
296
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
|
+
|
|
297
375
|
const user = await authRepo.findUserById(storedToken.userId);
|
|
298
376
|
if (!user) {
|
|
299
377
|
throw new UnauthorizedError('User not found or disabled', 'INVALID_REFRESH_TOKEN');
|
|
300
378
|
}
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
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);
|
|
304
382
|
|
|
305
383
|
const newAccessToken = signAccessToken({
|
|
306
384
|
userId: user.id,
|
|
307
385
|
role: user.role,
|
|
386
|
+
sessionId: session.id,
|
|
308
387
|
});
|
|
309
388
|
const newRefreshToken = generateRefreshToken();
|
|
310
389
|
|
|
311
|
-
//
|
|
312
|
-
//
|
|
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.
|
|
313
398
|
const rotated = await authRepo.rotateRefreshToken(refreshToken, {
|
|
314
399
|
token: newRefreshToken,
|
|
315
400
|
userId: user.id,
|
|
316
|
-
sessionId:
|
|
401
|
+
sessionId: session.id,
|
|
317
402
|
expiresAt: getRefreshTokenExpiresAt(),
|
|
318
403
|
});
|
|
319
404
|
|
|
320
405
|
if (!rotated) {
|
|
321
|
-
//
|
|
322
|
-
//
|
|
323
|
-
//
|
|
324
|
-
//
|
|
325
|
-
//
|
|
326
|
-
//
|
|
327
|
-
//
|
|
328
|
-
//
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
// the initial not-found lookup above can only reject it. Full replay
|
|
332
|
-
// attribution would require tombstoning consumed tokens (e.g. a revokedAt
|
|
333
|
-
// column) instead of deleting them — a schema change out of scope here.
|
|
334
|
-
logger.warn(
|
|
335
|
-
{ userId: user.id },
|
|
336
|
-
'[AUTH] Refresh token reuse detected — revoking all sessions and refresh tokens for user',
|
|
337
|
-
);
|
|
338
|
-
await authRepo.deleteRefreshTokensByUserId(user.id);
|
|
339
|
-
await sessionRepository.deleteAllUserSessions(user.id);
|
|
340
|
-
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);
|
|
341
416
|
}
|
|
342
417
|
|
|
343
418
|
return {
|
|
@@ -395,6 +470,14 @@ export async function logoutAllSessions(userId: string): Promise<number> {
|
|
|
395
470
|
}
|
|
396
471
|
|
|
397
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
|
+
|
|
398
481
|
const user = await authRepo.findUserByEmail(email);
|
|
399
482
|
|
|
400
483
|
// Silent return if user not found — prevents email enumeration
|
|
@@ -402,18 +485,19 @@ export async function forgotPassword(email: string): Promise<void> {
|
|
|
402
485
|
|
|
403
486
|
const redis = getRedis();
|
|
404
487
|
|
|
405
|
-
// Invalidate any existing token for this user
|
|
406
|
-
const
|
|
407
|
-
if (
|
|
408
|
-
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}`);
|
|
409
492
|
await redis.del(`${PASSWORD_RESET_USER_PREFIX}${user.id}`);
|
|
410
493
|
}
|
|
411
494
|
|
|
412
|
-
// Generate secure token
|
|
495
|
+
// Generate a secure token; only its fingerprint goes to Redis (1 hour TTL)
|
|
413
496
|
const token = crypto.randomBytes(32).toString('hex');
|
|
497
|
+
const tokenHash = hashToken(token);
|
|
414
498
|
|
|
415
|
-
await redis.set(`${PASSWORD_RESET_PREFIX}${
|
|
416
|
-
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);
|
|
417
501
|
|
|
418
502
|
// Build reset URL and send email
|
|
419
503
|
const resetUrl = `${env.CLIENT_URL}/reset-password?token=${token}`;
|
|
@@ -468,9 +552,14 @@ export async function forgotPassword(email: string): Promise<void> {
|
|
|
468
552
|
}
|
|
469
553
|
|
|
470
554
|
export async function resetPassword(token: string, newPassword: string): Promise<void> {
|
|
555
|
+
assertRedisReady('Password reset'); // the token is stored in Redis
|
|
471
556
|
const redis = getRedis();
|
|
472
557
|
|
|
473
|
-
|
|
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)}`);
|
|
474
563
|
if (!userId) {
|
|
475
564
|
throw new BadRequestError('Invalid or expired reset token', 'INVALID_RESET_TOKEN');
|
|
476
565
|
}
|
|
@@ -483,8 +572,7 @@ export async function resetPassword(token: string, newPassword: string): Promise
|
|
|
483
572
|
const hashedPassword = await hashPassword(newPassword);
|
|
484
573
|
await authRepo.updateUserPassword(userId, hashedPassword);
|
|
485
574
|
|
|
486
|
-
//
|
|
487
|
-
await redis.del(`${PASSWORD_RESET_PREFIX}${token}`);
|
|
575
|
+
// The per-user pointer to the (now consumed) token
|
|
488
576
|
await redis.del(`${PASSWORD_RESET_USER_PREFIX}${userId}`);
|
|
489
577
|
|
|
490
578
|
// Invalidate all sessions for security (force re-login with new password)
|
|
@@ -38,18 +38,6 @@ export class SessionRepository {
|
|
|
38
38
|
});
|
|
39
39
|
}
|
|
40
40
|
|
|
41
|
-
/**
|
|
42
|
-
* Update session last active timestamp
|
|
43
|
-
*/
|
|
44
|
-
async updateLastActive(sessionId: string): Promise<Session> {
|
|
45
|
-
return prisma.session.update({
|
|
46
|
-
where: { id: sessionId },
|
|
47
|
-
data: {
|
|
48
|
-
lastActiveAt: new Date(),
|
|
49
|
-
},
|
|
50
|
-
});
|
|
51
|
-
}
|
|
52
|
-
|
|
53
41
|
/**
|
|
54
42
|
* Delete a specific session (no-op if already deleted)
|
|
55
43
|
*/
|
|
@@ -74,6 +62,18 @@ export class SessionRepository {
|
|
|
74
62
|
return result.count;
|
|
75
63
|
}
|
|
76
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
|
+
|
|
77
77
|
/**
|
|
78
78
|
* Delete expired sessions (for cleanup cron job)
|
|
79
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 () => {
|