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
|
@@ -6,6 +6,18 @@ import { hashPassword, verifyPassword } from '@libs/password.js';
|
|
|
6
6
|
import { ConflictError, UnauthorizedError, ForbiddenError, NotFoundError } from '@shared/errors/errors.js';
|
|
7
7
|
import { testUsers, testRefreshToken, testSession, resetMocks } from '@/test/setup.js';
|
|
8
8
|
import { sessionRepository } from '../session.repo.js';
|
|
9
|
+
import { env } from '@config/env.js';
|
|
10
|
+
|
|
11
|
+
/** Run `fn` with REQUIRE_USER_VERIFICATION switched on, then restore it. */
|
|
12
|
+
async function withVerificationRequired<T>(fn: () => Promise<T>): Promise<T> {
|
|
13
|
+
const previous = env.REQUIRE_USER_VERIFICATION;
|
|
14
|
+
env.REQUIRE_USER_VERIFICATION = true;
|
|
15
|
+
try {
|
|
16
|
+
return await fn();
|
|
17
|
+
} finally {
|
|
18
|
+
env.REQUIRE_USER_VERIFICATION = previous;
|
|
19
|
+
}
|
|
20
|
+
}
|
|
9
21
|
|
|
10
22
|
// Mock dependencies
|
|
11
23
|
vi.mock('../auth.repo.js');
|
|
@@ -16,11 +28,14 @@ vi.mock('../session.repo.js');
|
|
|
16
28
|
// In-memory Redis stub — account lockout (email+IP) uses Redis. Tests must
|
|
17
29
|
// never require a live Redis instance.
|
|
18
30
|
const mockRedis = vi.hoisted(() => ({
|
|
31
|
+
status: 'ready',
|
|
19
32
|
exists: vi.fn(),
|
|
33
|
+
ttl: vi.fn(),
|
|
20
34
|
incr: vi.fn(),
|
|
21
35
|
expire: vi.fn(),
|
|
22
36
|
set: vi.fn(),
|
|
23
37
|
get: vi.fn(),
|
|
38
|
+
getdel: vi.fn(),
|
|
24
39
|
del: vi.fn(),
|
|
25
40
|
}));
|
|
26
41
|
|
|
@@ -32,12 +47,18 @@ describe('Auth Service', () => {
|
|
|
32
47
|
beforeEach(() => {
|
|
33
48
|
resetMocks();
|
|
34
49
|
vi.clearAllMocks();
|
|
35
|
-
// Default Redis behavior: nothing locked, first failure
|
|
50
|
+
// Default Redis behavior: connected, nothing locked (TTL -2 = no key), first failure
|
|
51
|
+
mockRedis.status = 'ready';
|
|
36
52
|
mockRedis.exists.mockResolvedValue(0);
|
|
53
|
+
mockRedis.ttl.mockResolvedValue(-2);
|
|
54
|
+
// Unknown emails are checked against a dummy hash (equal timing)
|
|
55
|
+
vi.mocked(hashPassword).mockResolvedValue('dummy-hash');
|
|
37
56
|
mockRedis.incr.mockResolvedValue(1);
|
|
38
57
|
mockRedis.expire.mockResolvedValue(1);
|
|
39
58
|
mockRedis.set.mockResolvedValue('OK');
|
|
40
59
|
mockRedis.del.mockResolvedValue(1);
|
|
60
|
+
// refresh() requires the token's session to exist and be unexpired
|
|
61
|
+
vi.mocked(sessionRepository.getSessionById).mockResolvedValue(testSession);
|
|
41
62
|
});
|
|
42
63
|
|
|
43
64
|
describe('register', () => {
|
|
@@ -82,11 +103,12 @@ describe('Auth Service', () => {
|
|
|
82
103
|
password: hashedPassword,
|
|
83
104
|
firstName: validRegisterInput.firstName,
|
|
84
105
|
lastName: validRegisterInput.lastName,
|
|
85
|
-
|
|
106
|
+
emailVerifiedAt: expect.any(Date),
|
|
86
107
|
});
|
|
87
108
|
expect(authLib.signAccessToken).toHaveBeenCalledWith({
|
|
88
109
|
userId: createdUser.id,
|
|
89
110
|
role: createdUser.role,
|
|
111
|
+
sessionId: testSession.id, // the access token is bound to the new session
|
|
90
112
|
});
|
|
91
113
|
expect(authLib.generateRefreshToken).toHaveBeenCalled();
|
|
92
114
|
expect(sessionRepository.createSession).toHaveBeenCalledWith({
|
|
@@ -116,6 +138,32 @@ describe('Auth Service', () => {
|
|
|
116
138
|
expect(result.user).not.toHaveProperty('password');
|
|
117
139
|
});
|
|
118
140
|
|
|
141
|
+
it('should create an unverified (but never banned) user and issue no session when verification is required', async () => {
|
|
142
|
+
vi.mocked(authRepo.findUserByEmail).mockResolvedValue(null);
|
|
143
|
+
vi.mocked(authRepo.findDeletedUserByEmail).mockResolvedValue(null);
|
|
144
|
+
vi.mocked(hashPassword).mockResolvedValue('$2a$12$hashedpassword');
|
|
145
|
+
vi.mocked(authRepo.createUser).mockResolvedValue({
|
|
146
|
+
...testUsers.unverifiedUser,
|
|
147
|
+
email: validRegisterInput.email,
|
|
148
|
+
});
|
|
149
|
+
|
|
150
|
+
const result = await withVerificationRequired(() => authService.register(validRegisterInput));
|
|
151
|
+
|
|
152
|
+
// isActive is not passed at all: the ban switch keeps its default (true).
|
|
153
|
+
expect(authRepo.createUser).toHaveBeenCalledWith({
|
|
154
|
+
email: validRegisterInput.email,
|
|
155
|
+
password: '$2a$12$hashedpassword',
|
|
156
|
+
firstName: validRegisterInput.firstName,
|
|
157
|
+
lastName: validRegisterInput.lastName,
|
|
158
|
+
emailVerifiedAt: null,
|
|
159
|
+
});
|
|
160
|
+
expect(result.requiresVerification).toBe(true);
|
|
161
|
+
expect(result.accessToken).toBeUndefined();
|
|
162
|
+
expect(result.user.emailVerifiedAt).toBeNull();
|
|
163
|
+
expect(authLib.signAccessToken).not.toHaveBeenCalled();
|
|
164
|
+
expect(sessionRepository.createSession).not.toHaveBeenCalled();
|
|
165
|
+
});
|
|
166
|
+
|
|
119
167
|
it('should throw ConflictError if email already exists', async () => {
|
|
120
168
|
// Arrange
|
|
121
169
|
vi.mocked(authRepo.findUserByEmail).mockResolvedValue(testUsers.validUser);
|
|
@@ -193,15 +241,19 @@ describe('Auth Service', () => {
|
|
|
193
241
|
expect(result.user).not.toHaveProperty('password');
|
|
194
242
|
});
|
|
195
243
|
|
|
196
|
-
it('should throw UnauthorizedError if user not found', async () => {
|
|
244
|
+
it('should throw UnauthorizedError if user not found, after the same password check and failure count', async () => {
|
|
197
245
|
// Arrange
|
|
198
246
|
vi.mocked(authRepo.findUserByEmail).mockResolvedValue(null);
|
|
247
|
+
vi.mocked(verifyPassword).mockResolvedValue(false);
|
|
199
248
|
|
|
200
249
|
// Act & Assert
|
|
201
250
|
await expect(authService.login(validLoginInput)).rejects.toThrow(UnauthorizedError);
|
|
202
251
|
await expect(authService.login(validLoginInput)).rejects.toThrow('Invalid email or password');
|
|
203
252
|
expect(authRepo.findDeletedUserByEmail).not.toHaveBeenCalled();
|
|
204
|
-
|
|
253
|
+
// Same cost as a wrong password on a real account: no timing hint about registered emails
|
|
254
|
+
expect(verifyPassword).toHaveBeenCalledWith(validLoginInput.password, 'dummy-hash');
|
|
255
|
+
// Counted like a real failure, so the lock cannot reveal which emails exist
|
|
256
|
+
expect(mockRedis.incr).toHaveBeenCalledWith(`login-fail:${validLoginInput.email}:unknown`);
|
|
205
257
|
});
|
|
206
258
|
|
|
207
259
|
it('should not restore or authenticate a soft-deleted account with correct credentials', async () => {
|
|
@@ -218,23 +270,60 @@ describe('Auth Service', () => {
|
|
|
218
270
|
await expect(authService.login(validLoginInput)).rejects.toThrow(UnauthorizedError);
|
|
219
271
|
await expect(authService.login(validLoginInput)).rejects.toThrow('Invalid email or password');
|
|
220
272
|
expect(authRepo.findDeletedUserByEmail).not.toHaveBeenCalled();
|
|
221
|
-
|
|
273
|
+
// Only the dummy hash is checked, never the deleted account's own password
|
|
274
|
+
expect(verifyPassword).not.toHaveBeenCalledWith(validLoginInput.password, testUsers.validUser.password);
|
|
222
275
|
expect(authLib.signAccessToken).not.toHaveBeenCalled();
|
|
223
276
|
expect(authLib.generateRefreshToken).not.toHaveBeenCalled();
|
|
224
277
|
expect(sessionRepository.createSession).not.toHaveBeenCalled();
|
|
225
278
|
expect(authRepo.createRefreshToken).not.toHaveBeenCalled();
|
|
226
279
|
});
|
|
227
280
|
|
|
228
|
-
it('should
|
|
229
|
-
//
|
|
281
|
+
it('should not reveal that an account is banned when the password is wrong', async () => {
|
|
282
|
+
// Account state is checked only after the password, so a caller without
|
|
283
|
+
// the password gets the same answer as for any wrong password.
|
|
230
284
|
vi.mocked(authRepo.findUserByEmail).mockResolvedValue(testUsers.inactiveUser);
|
|
285
|
+
vi.mocked(verifyPassword).mockResolvedValue(false);
|
|
286
|
+
|
|
287
|
+
await expect(authService.login(validLoginInput)).rejects.toMatchObject({
|
|
288
|
+
code: 'INVALID_CREDENTIALS',
|
|
289
|
+
});
|
|
290
|
+
expect(verifyPassword).toHaveBeenCalled();
|
|
291
|
+
});
|
|
292
|
+
|
|
293
|
+
it('should reject a banned account with ACCOUNT_DEACTIVATED and issue no session', async () => {
|
|
294
|
+
vi.mocked(authRepo.findUserByEmail).mockResolvedValue(testUsers.inactiveUser);
|
|
295
|
+
vi.mocked(verifyPassword).mockResolvedValue(true);
|
|
231
296
|
|
|
232
|
-
// Act & Assert
|
|
233
297
|
await expect(authService.login(validLoginInput)).rejects.toThrow(ForbiddenError);
|
|
234
|
-
await expect(authService.login(validLoginInput)).rejects.
|
|
235
|
-
|
|
236
|
-
);
|
|
237
|
-
expect(
|
|
298
|
+
await expect(authService.login(validLoginInput)).rejects.toMatchObject({
|
|
299
|
+
code: 'ACCOUNT_DEACTIVATED',
|
|
300
|
+
});
|
|
301
|
+
expect(authLib.signAccessToken).not.toHaveBeenCalled();
|
|
302
|
+
expect(sessionRepository.createSession).not.toHaveBeenCalled();
|
|
303
|
+
});
|
|
304
|
+
|
|
305
|
+
it('should reject an unverified account with EMAIL_NOT_VERIFIED while verification is required', async () => {
|
|
306
|
+
vi.mocked(authRepo.findUserByEmail).mockResolvedValue(testUsers.unverifiedUser);
|
|
307
|
+
vi.mocked(verifyPassword).mockResolvedValue(true);
|
|
308
|
+
|
|
309
|
+
await expect(
|
|
310
|
+
withVerificationRequired(() => authService.login(validLoginInput)),
|
|
311
|
+
).rejects.toMatchObject({ code: 'EMAIL_NOT_VERIFIED' });
|
|
312
|
+
expect(authLib.signAccessToken).not.toHaveBeenCalled();
|
|
313
|
+
expect(sessionRepository.createSession).not.toHaveBeenCalled();
|
|
314
|
+
});
|
|
315
|
+
|
|
316
|
+
it('should report a ban (not "verify your email") for a banned account that is also unverified', async () => {
|
|
317
|
+
// Verifying an email can never lift a ban, so the ban must win.
|
|
318
|
+
vi.mocked(authRepo.findUserByEmail).mockResolvedValue({
|
|
319
|
+
...testUsers.unverifiedUser,
|
|
320
|
+
isActive: false,
|
|
321
|
+
});
|
|
322
|
+
vi.mocked(verifyPassword).mockResolvedValue(true);
|
|
323
|
+
|
|
324
|
+
await expect(
|
|
325
|
+
withVerificationRequired(() => authService.login(validLoginInput)),
|
|
326
|
+
).rejects.toMatchObject({ code: 'ACCOUNT_DEACTIVATED' });
|
|
238
327
|
});
|
|
239
328
|
|
|
240
329
|
it('should throw UnauthorizedError if password is invalid', async () => {
|
|
@@ -252,17 +341,36 @@ describe('Auth Service', () => {
|
|
|
252
341
|
const loginInput = { email: 'test@example.com', password: 'WrongPassword!' };
|
|
253
342
|
const attackerIp = '203.0.113.7';
|
|
254
343
|
|
|
255
|
-
it('should
|
|
344
|
+
it('should answer 429 LOGIN_LOCKED with the wait time while the email+IP pair is locked, without checking the password', async () => {
|
|
256
345
|
// Arrange
|
|
257
346
|
vi.mocked(authRepo.findUserByEmail).mockResolvedValue(testUsers.validUser);
|
|
258
|
-
mockRedis.
|
|
347
|
+
mockRedis.ttl.mockResolvedValue(600); // lock key present for this pair, 10 min left
|
|
259
348
|
|
|
260
|
-
// Act & Assert
|
|
349
|
+
// Act & Assert — even the right password gets the locked answer
|
|
261
350
|
await expect(
|
|
262
|
-
authService.login(loginInput, 'test-agent', attackerIp),
|
|
263
|
-
).rejects.
|
|
264
|
-
|
|
351
|
+
authService.login({ ...loginInput, password: 'Password123!' }, 'test-agent', attackerIp),
|
|
352
|
+
).rejects.toMatchObject({
|
|
353
|
+
statusCode: 429,
|
|
354
|
+
code: 'LOGIN_LOCKED',
|
|
355
|
+
retryAfterSeconds: 600,
|
|
356
|
+
message: 'Too many failed sign-in attempts. Try again in 10 minutes.',
|
|
357
|
+
});
|
|
358
|
+
expect(mockRedis.ttl).toHaveBeenCalledWith(`login-lock:test@example.com:${attackerIp}`);
|
|
265
359
|
expect(verifyPassword).not.toHaveBeenCalled();
|
|
360
|
+
expect(authRepo.findUserByEmail).not.toHaveBeenCalled(); // checked before the lookup
|
|
361
|
+
});
|
|
362
|
+
|
|
363
|
+
it('should lock an unknown email exactly like a real one (no account enumeration)', async () => {
|
|
364
|
+
vi.mocked(authRepo.findUserByEmail).mockResolvedValue(null);
|
|
365
|
+
vi.mocked(verifyPassword).mockResolvedValue(false);
|
|
366
|
+
mockRedis.incr.mockResolvedValue(15);
|
|
367
|
+
|
|
368
|
+
await expect(authService.login(loginInput, 'test-agent', attackerIp)).rejects.toMatchObject({
|
|
369
|
+
statusCode: 429,
|
|
370
|
+
code: 'LOGIN_LOCKED',
|
|
371
|
+
retryAfterSeconds: 15 * 60,
|
|
372
|
+
});
|
|
373
|
+
expect(mockRedis.set).toHaveBeenCalledWith(`login-lock:test@example.com:${attackerIp}`, '1', 'EX', 15 * 60);
|
|
266
374
|
});
|
|
267
375
|
|
|
268
376
|
it('should NOT lock out the same email from a different IP (no remote lockout DoS)', async () => {
|
|
@@ -272,7 +380,7 @@ describe('Auth Service', () => {
|
|
|
272
380
|
const expiresAt = new Date(Date.now() + 7 * 24 * 60 * 60 * 1000);
|
|
273
381
|
|
|
274
382
|
vi.mocked(authRepo.findUserByEmail).mockResolvedValue(testUsers.validUser);
|
|
275
|
-
mockRedis.
|
|
383
|
+
mockRedis.ttl.mockResolvedValue(-2);
|
|
276
384
|
vi.mocked(verifyPassword).mockResolvedValue(true);
|
|
277
385
|
vi.mocked(authLib.signAccessToken).mockReturnValue('access');
|
|
278
386
|
vi.mocked(authLib.generateRefreshToken).mockReturnValue('refresh');
|
|
@@ -288,7 +396,7 @@ describe('Auth Service', () => {
|
|
|
288
396
|
);
|
|
289
397
|
|
|
290
398
|
// Assert — lock was checked for the VICTIM's pair only, and login succeeded
|
|
291
|
-
expect(mockRedis.
|
|
399
|
+
expect(mockRedis.ttl).toHaveBeenCalledWith(`login-lock:test@example.com:${victimIp}`);
|
|
292
400
|
expect(result.accessToken).toBe('access');
|
|
293
401
|
});
|
|
294
402
|
|
|
@@ -296,26 +404,31 @@ describe('Auth Service', () => {
|
|
|
296
404
|
// Arrange
|
|
297
405
|
vi.mocked(authRepo.findUserByEmail).mockResolvedValue(testUsers.validUser);
|
|
298
406
|
vi.mocked(verifyPassword).mockResolvedValue(false);
|
|
299
|
-
mockRedis.incr.mockResolvedValue(
|
|
407
|
+
mockRedis.incr.mockResolvedValue(14); // one below the first lock
|
|
300
408
|
|
|
301
409
|
// Act & Assert
|
|
302
|
-
await expect(authService.login(loginInput, 'test-agent', attackerIp)).rejects.
|
|
303
|
-
|
|
304
|
-
);
|
|
410
|
+
await expect(authService.login(loginInput, 'test-agent', attackerIp)).rejects.toMatchObject({
|
|
411
|
+
code: 'INVALID_CREDENTIALS',
|
|
412
|
+
});
|
|
305
413
|
expect(mockRedis.incr).toHaveBeenCalledWith(`login-fail:test@example.com:${attackerIp}`);
|
|
414
|
+
// The count is forgotten an hour after the last failure
|
|
415
|
+
expect(mockRedis.expire).toHaveBeenCalledWith(`login-fail:test@example.com:${attackerIp}`, 3600);
|
|
306
416
|
expect(mockRedis.set).not.toHaveBeenCalled(); // no lock yet
|
|
307
417
|
});
|
|
308
418
|
|
|
309
|
-
it('should
|
|
419
|
+
it('should lock for 15 minutes on the 15th failure and say so on that same attempt', async () => {
|
|
310
420
|
// Arrange
|
|
311
421
|
vi.mocked(authRepo.findUserByEmail).mockResolvedValue(testUsers.validUser);
|
|
312
422
|
vi.mocked(verifyPassword).mockResolvedValue(false);
|
|
313
|
-
mockRedis.incr.mockResolvedValue(
|
|
423
|
+
mockRedis.incr.mockResolvedValue(15); // hits the first threshold
|
|
314
424
|
|
|
315
425
|
// Act & Assert
|
|
316
|
-
await expect(authService.login(loginInput, 'test-agent', attackerIp)).rejects.
|
|
317
|
-
|
|
318
|
-
|
|
426
|
+
await expect(authService.login(loginInput, 'test-agent', attackerIp)).rejects.toMatchObject({
|
|
427
|
+
statusCode: 429,
|
|
428
|
+
code: 'LOGIN_LOCKED',
|
|
429
|
+
retryAfterSeconds: 15 * 60,
|
|
430
|
+
message: 'Too many failed sign-in attempts. Try again in 15 minutes.',
|
|
431
|
+
});
|
|
319
432
|
expect(mockRedis.set).toHaveBeenCalledWith(
|
|
320
433
|
`login-lock:test@example.com:${attackerIp}`,
|
|
321
434
|
'1',
|
|
@@ -324,11 +437,38 @@ describe('Auth Service', () => {
|
|
|
324
437
|
);
|
|
325
438
|
});
|
|
326
439
|
|
|
440
|
+
it('should not re-lock between the steps, and lock for 1 hour on the 30th failure', async () => {
|
|
441
|
+
vi.mocked(authRepo.findUserByEmail).mockResolvedValue(testUsers.validUser);
|
|
442
|
+
vi.mocked(verifyPassword).mockResolvedValue(false);
|
|
443
|
+
|
|
444
|
+
mockRedis.incr.mockResolvedValue(16);
|
|
445
|
+
await expect(authService.login(loginInput, 'test-agent', attackerIp)).rejects.toMatchObject({
|
|
446
|
+
code: 'INVALID_CREDENTIALS',
|
|
447
|
+
});
|
|
448
|
+
expect(mockRedis.set).not.toHaveBeenCalled();
|
|
449
|
+
|
|
450
|
+
mockRedis.incr.mockResolvedValue(30);
|
|
451
|
+
await expect(authService.login(loginInput, 'test-agent', attackerIp)).rejects.toMatchObject({
|
|
452
|
+
code: 'LOGIN_LOCKED',
|
|
453
|
+
retryAfterSeconds: 3600,
|
|
454
|
+
});
|
|
455
|
+
expect(mockRedis.set).toHaveBeenCalledWith(`login-lock:test@example.com:${attackerIp}`, '1', 'EX', 3600);
|
|
456
|
+
});
|
|
457
|
+
|
|
458
|
+
it('lockSecondsForFailure: 15 → 15 min, 30 and every 15th after → 1 h, others → none', () => {
|
|
459
|
+
expect(authService.lockSecondsForFailure(14)).toBeNull();
|
|
460
|
+
expect(authService.lockSecondsForFailure(15)).toBe(900);
|
|
461
|
+
expect(authService.lockSecondsForFailure(16)).toBeNull();
|
|
462
|
+
expect(authService.lockSecondsForFailure(29)).toBeNull();
|
|
463
|
+
expect(authService.lockSecondsForFailure(30)).toBe(3600);
|
|
464
|
+
expect(authService.lockSecondsForFailure(45)).toBe(3600);
|
|
465
|
+
});
|
|
466
|
+
|
|
327
467
|
it('should fail open and allow login when Redis is unavailable', async () => {
|
|
328
468
|
// Arrange — Redis down: lockout checks must not block all logins
|
|
329
469
|
const expiresAt = new Date(Date.now() + 7 * 24 * 60 * 60 * 1000);
|
|
330
470
|
vi.mocked(authRepo.findUserByEmail).mockResolvedValue(testUsers.validUser);
|
|
331
|
-
mockRedis.
|
|
471
|
+
mockRedis.ttl.mockRejectedValue(new Error('Redis down'));
|
|
332
472
|
mockRedis.del.mockRejectedValue(new Error('Redis down'));
|
|
333
473
|
vi.mocked(verifyPassword).mockResolvedValue(true);
|
|
334
474
|
vi.mocked(authLib.signAccessToken).mockReturnValue('access');
|
|
@@ -352,6 +492,46 @@ describe('Auth Service', () => {
|
|
|
352
492
|
describe('refresh', () => {
|
|
353
493
|
const validRefreshToken = 'valid-refresh-token';
|
|
354
494
|
|
|
495
|
+
it('should reject and delete a token whose session no longer exists', async () => {
|
|
496
|
+
// e.g. the session was force-expired by an admin or removed by the cleanup job
|
|
497
|
+
vi.mocked(authRepo.findRefreshToken).mockResolvedValue({
|
|
498
|
+
...testRefreshToken,
|
|
499
|
+
sessionId: testSession.id,
|
|
500
|
+
expiresAt: new Date(Date.now() + 24 * 60 * 60 * 1000),
|
|
501
|
+
});
|
|
502
|
+
vi.mocked(sessionRepository.getSessionById).mockResolvedValue(null);
|
|
503
|
+
|
|
504
|
+
await expect(authService.refresh(validRefreshToken)).rejects.toMatchObject({ code: 'SESSION_EXPIRED' });
|
|
505
|
+
expect(authRepo.deleteRefreshToken).toHaveBeenCalledWith(validRefreshToken);
|
|
506
|
+
expect(authRepo.rotateRefreshToken).not.toHaveBeenCalled();
|
|
507
|
+
expect(authLib.signAccessToken).not.toHaveBeenCalled();
|
|
508
|
+
});
|
|
509
|
+
|
|
510
|
+
it('should reject a token whose session has expired', async () => {
|
|
511
|
+
vi.mocked(authRepo.findRefreshToken).mockResolvedValue({
|
|
512
|
+
...testRefreshToken,
|
|
513
|
+
sessionId: testSession.id,
|
|
514
|
+
expiresAt: new Date(Date.now() + 24 * 60 * 60 * 1000),
|
|
515
|
+
});
|
|
516
|
+
vi.mocked(sessionRepository.getSessionById).mockResolvedValue({
|
|
517
|
+
...testSession,
|
|
518
|
+
expiresAt: new Date(Date.now() - 1000),
|
|
519
|
+
});
|
|
520
|
+
|
|
521
|
+
await expect(authService.refresh(validRefreshToken)).rejects.toMatchObject({ code: 'SESSION_EXPIRED' });
|
|
522
|
+
expect(authRepo.rotateRefreshToken).not.toHaveBeenCalled();
|
|
523
|
+
});
|
|
524
|
+
|
|
525
|
+
it('should reject a legacy token that has no session at all', async () => {
|
|
526
|
+
vi.mocked(authRepo.findRefreshToken).mockResolvedValue({
|
|
527
|
+
...testRefreshToken,
|
|
528
|
+
sessionId: null,
|
|
529
|
+
expiresAt: new Date(Date.now() + 24 * 60 * 60 * 1000),
|
|
530
|
+
});
|
|
531
|
+
|
|
532
|
+
await expect(authService.refresh(validRefreshToken)).rejects.toMatchObject({ code: 'SESSION_EXPIRED' });
|
|
533
|
+
});
|
|
534
|
+
|
|
355
535
|
it('should successfully refresh tokens with valid refresh token', async () => {
|
|
356
536
|
// Arrange
|
|
357
537
|
const newAccessToken = 'new-access-token';
|
|
@@ -359,6 +539,7 @@ describe('Auth Service', () => {
|
|
|
359
539
|
const expiresAt = new Date(Date.now() + 7 * 24 * 60 * 60 * 1000);
|
|
360
540
|
const storedToken = {
|
|
361
541
|
...testRefreshToken,
|
|
542
|
+
sessionId: testSession.id,
|
|
362
543
|
token: validRefreshToken,
|
|
363
544
|
expiresAt: new Date(Date.now() + 24 * 60 * 60 * 1000), // expires in 1 day
|
|
364
545
|
};
|
|
@@ -379,11 +560,12 @@ describe('Auth Service', () => {
|
|
|
379
560
|
expect(authLib.signAccessToken).toHaveBeenCalledWith({
|
|
380
561
|
userId: testUsers.validUser.id,
|
|
381
562
|
role: testUsers.validUser.role,
|
|
563
|
+
sessionId: testSession.id,
|
|
382
564
|
});
|
|
383
565
|
expect(authRepo.rotateRefreshToken).toHaveBeenCalledWith(validRefreshToken, {
|
|
384
566
|
token: newRefreshToken,
|
|
385
567
|
userId: testUsers.validUser.id,
|
|
386
|
-
sessionId:
|
|
568
|
+
sessionId: testSession.id,
|
|
387
569
|
expiresAt,
|
|
388
570
|
});
|
|
389
571
|
expect(result).toEqual({
|
|
@@ -405,6 +587,7 @@ describe('Auth Service', () => {
|
|
|
405
587
|
// Arrange
|
|
406
588
|
const expiredToken = {
|
|
407
589
|
...testRefreshToken,
|
|
590
|
+
sessionId: testSession.id,
|
|
408
591
|
expiresAt: new Date(Date.now() - 1000), // expired 1 second ago
|
|
409
592
|
};
|
|
410
593
|
vi.mocked(authRepo.findRefreshToken).mockResolvedValue(expiredToken);
|
|
@@ -420,6 +603,7 @@ describe('Auth Service', () => {
|
|
|
420
603
|
// Arrange
|
|
421
604
|
const storedToken = {
|
|
422
605
|
...testRefreshToken,
|
|
606
|
+
sessionId: testSession.id,
|
|
423
607
|
expiresAt: new Date(Date.now() + 24 * 60 * 60 * 1000),
|
|
424
608
|
};
|
|
425
609
|
vi.mocked(authRepo.findRefreshToken).mockResolvedValue(storedToken);
|
|
@@ -430,10 +614,11 @@ describe('Auth Service', () => {
|
|
|
430
614
|
await expect(authService.refresh(validRefreshToken)).rejects.toThrow('User not found or disabled');
|
|
431
615
|
});
|
|
432
616
|
|
|
433
|
-
it('should
|
|
617
|
+
it('should refuse to refresh a banned account', async () => {
|
|
434
618
|
// Arrange
|
|
435
619
|
const storedToken = {
|
|
436
620
|
...testRefreshToken,
|
|
621
|
+
sessionId: testSession.id,
|
|
437
622
|
expiresAt: new Date(Date.now() + 24 * 60 * 60 * 1000),
|
|
438
623
|
};
|
|
439
624
|
vi.mocked(authRepo.findRefreshToken).mockResolvedValue(storedToken);
|
|
@@ -441,19 +626,55 @@ describe('Auth Service', () => {
|
|
|
441
626
|
|
|
442
627
|
// Act & Assert
|
|
443
628
|
await expect(authService.refresh(validRefreshToken)).rejects.toThrow(ForbiddenError);
|
|
444
|
-
await expect(authService.refresh(validRefreshToken)).rejects.
|
|
445
|
-
|
|
629
|
+
await expect(authService.refresh(validRefreshToken)).rejects.toMatchObject({
|
|
630
|
+
code: 'ACCOUNT_DEACTIVATED',
|
|
631
|
+
});
|
|
632
|
+
expect(authLib.signAccessToken).not.toHaveBeenCalled();
|
|
633
|
+
});
|
|
634
|
+
|
|
635
|
+
it('a refresh whose token was rotated a moment ago by a parallel one is a lost race (cookies kept)', async () => {
|
|
636
|
+
vi.mocked(authRepo.findRefreshToken).mockResolvedValue(null);
|
|
637
|
+
mockRedis.exists.mockResolvedValue(1); // the winner's "just rotated" note
|
|
638
|
+
await expect(authService.refresh(validRefreshToken)).rejects.toMatchObject({
|
|
639
|
+
statusCode: 401,
|
|
640
|
+
code: 'REFRESH_TOKEN_ROTATED',
|
|
641
|
+
});
|
|
642
|
+
expect(mockRedis.exists).toHaveBeenCalledWith(expect.stringMatching(/^rt-rotated:[0-9a-f]{64}$/));
|
|
643
|
+
});
|
|
644
|
+
|
|
645
|
+
it('an unknown refresh token without that note is still INVALID_REFRESH_TOKEN', async () => {
|
|
646
|
+
vi.mocked(authRepo.findRefreshToken).mockResolvedValue(null);
|
|
647
|
+
mockRedis.exists.mockResolvedValue(0);
|
|
648
|
+
await expect(authService.refresh(validRefreshToken)).rejects.toMatchObject({ code: 'INVALID_REFRESH_TOKEN' });
|
|
649
|
+
});
|
|
650
|
+
|
|
651
|
+
it('notes the rotation (fingerprint key, 60 s) before rotating', async () => {
|
|
652
|
+
const storedToken = { ...testRefreshToken, sessionId: testSession.id, expiresAt: new Date(Date.now() + 86_400_000) };
|
|
653
|
+
vi.mocked(authRepo.findRefreshToken).mockResolvedValue(storedToken);
|
|
654
|
+
vi.mocked(authRepo.findUserById).mockResolvedValue(testUsers.validUser);
|
|
655
|
+
vi.mocked(authLib.signAccessToken).mockReturnValue('access');
|
|
656
|
+
vi.mocked(authLib.generateRefreshToken).mockReturnValue('refresh');
|
|
657
|
+
vi.mocked(authLib.getRefreshTokenExpiresAt).mockReturnValue(new Date());
|
|
658
|
+
vi.mocked(authRepo.rotateRefreshToken).mockResolvedValue(true);
|
|
659
|
+
|
|
660
|
+
await authService.refresh(validRefreshToken);
|
|
661
|
+
|
|
662
|
+
const note = mockRedis.set.mock.calls.find(([key]) => String(key).startsWith('rt-rotated:'));
|
|
663
|
+
expect(note).toEqual([expect.stringMatching(/^rt-rotated:[0-9a-f]{64}$/), '1', 'EX', 60]);
|
|
664
|
+
expect(String(note?.[0])).not.toContain(validRefreshToken);
|
|
665
|
+
expect(mockRedis.set.mock.invocationCallOrder[mockRedis.set.mock.calls.indexOf(note as never)]).toBeLessThan(
|
|
666
|
+
vi.mocked(authRepo.rotateRefreshToken).mock.invocationCallOrder[0] as number,
|
|
446
667
|
);
|
|
447
668
|
});
|
|
448
669
|
|
|
449
|
-
it('
|
|
450
|
-
//
|
|
451
|
-
//
|
|
452
|
-
//
|
|
453
|
-
//
|
|
454
|
-
// party redeemed it first (possibly an attacker) holds a valid token.
|
|
670
|
+
it('a refresh that loses a race with a parallel one is refused alone: nothing is revoked', async () => {
|
|
671
|
+
// Two tabs share the cookie and refresh at the same moment; the atomic
|
|
672
|
+
// rotation lets one win. The loser must get its own code (so the
|
|
673
|
+
// controller keeps the winner's cookies) and must NOT wipe the user's
|
|
674
|
+
// sessions: that used to sign the user out on every device.
|
|
455
675
|
const storedToken = {
|
|
456
676
|
...testRefreshToken,
|
|
677
|
+
sessionId: testSession.id,
|
|
457
678
|
expiresAt: new Date(Date.now() + 24 * 60 * 60 * 1000),
|
|
458
679
|
};
|
|
459
680
|
vi.mocked(authRepo.findRefreshToken).mockResolvedValue(storedToken);
|
|
@@ -461,21 +682,21 @@ describe('Auth Service', () => {
|
|
|
461
682
|
vi.mocked(authLib.signAccessToken).mockReturnValue('access');
|
|
462
683
|
vi.mocked(authLib.generateRefreshToken).mockReturnValue('refresh');
|
|
463
684
|
vi.mocked(authLib.getRefreshTokenExpiresAt).mockReturnValue(new Date());
|
|
464
|
-
vi.mocked(authRepo.rotateRefreshToken).mockResolvedValue(false); //
|
|
465
|
-
vi.mocked(authRepo.deleteRefreshTokensByUserId).mockResolvedValue(undefined);
|
|
466
|
-
vi.mocked(sessionRepository.deleteAllUserSessions).mockResolvedValue(1);
|
|
685
|
+
vi.mocked(authRepo.rotateRefreshToken).mockResolvedValue(false); // the parallel request rotated it first
|
|
467
686
|
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
687
|
+
await expect(authService.refresh(validRefreshToken)).rejects.toMatchObject({
|
|
688
|
+
statusCode: 401,
|
|
689
|
+
code: 'REFRESH_TOKEN_ROTATED',
|
|
690
|
+
});
|
|
691
|
+
expect(authRepo.deleteRefreshTokensByUserId).not.toHaveBeenCalled();
|
|
692
|
+
expect(sessionRepository.deleteAllUserSessions).not.toHaveBeenCalled();
|
|
472
693
|
});
|
|
473
694
|
|
|
474
695
|
it('should NOT revoke the token family on a successful rotation', async () => {
|
|
475
|
-
// Companion to the
|
|
476
|
-
// the happy path.
|
|
696
|
+
// Companion to the race test: nothing is revoked on a normal rotation either.
|
|
477
697
|
const storedToken = {
|
|
478
698
|
...testRefreshToken,
|
|
699
|
+
sessionId: testSession.id,
|
|
479
700
|
expiresAt: new Date(Date.now() + 24 * 60 * 60 * 1000),
|
|
480
701
|
};
|
|
481
702
|
vi.mocked(authRepo.findRefreshToken).mockResolvedValue(storedToken);
|
|
@@ -545,6 +766,68 @@ describe('Auth Service', () => {
|
|
|
545
766
|
});
|
|
546
767
|
});
|
|
547
768
|
|
|
769
|
+
describe('password reset while Redis is down', () => {
|
|
770
|
+
// Reset tokens live in Redis: the answer must be a clear 503 for every
|
|
771
|
+
// address, decided before any lookup (so it reveals nothing).
|
|
772
|
+
it('forgotPassword answers 503 SERVICE_UNAVAILABLE before looking the user up', async () => {
|
|
773
|
+
mockRedis.status = 'reconnecting';
|
|
774
|
+
await expect(authService.forgotPassword('anyone@example.com')).rejects.toMatchObject({
|
|
775
|
+
statusCode: 503,
|
|
776
|
+
code: 'SERVICE_UNAVAILABLE',
|
|
777
|
+
message: 'Password reset is temporarily unavailable. Please try again in a few minutes.',
|
|
778
|
+
});
|
|
779
|
+
expect(authRepo.findUserByEmail).not.toHaveBeenCalled();
|
|
780
|
+
});
|
|
781
|
+
|
|
782
|
+
it('resetPassword answers 503 SERVICE_UNAVAILABLE instead of failing on the token lookup', async () => {
|
|
783
|
+
mockRedis.status = 'reconnecting';
|
|
784
|
+
await expect(authService.resetPassword('some-token', 'New-Passw0rd-123!')).rejects.toMatchObject({
|
|
785
|
+
statusCode: 503,
|
|
786
|
+
code: 'SERVICE_UNAVAILABLE',
|
|
787
|
+
});
|
|
788
|
+
expect(mockRedis.getdel).not.toHaveBeenCalled();
|
|
789
|
+
});
|
|
790
|
+
|
|
791
|
+
it('forgotPassword still answers normally while Redis is connected (unknown email: no error)', async () => {
|
|
792
|
+
vi.mocked(authRepo.findUserByEmail).mockResolvedValue(null);
|
|
793
|
+
await expect(authService.forgotPassword('nobody@example.com')).resolves.toBeUndefined();
|
|
794
|
+
});
|
|
795
|
+
});
|
|
796
|
+
|
|
797
|
+
describe('resetPassword', () => {
|
|
798
|
+
it('consumes the token in one step (GETDEL), changes the password and ends all sessions', async () => {
|
|
799
|
+
mockRedis.getdel.mockResolvedValue(testUsers.validUser.id);
|
|
800
|
+
vi.mocked(authRepo.findUserById).mockResolvedValue(testUsers.validUser);
|
|
801
|
+
vi.mocked(hashPassword).mockResolvedValue('new-hash');
|
|
802
|
+
|
|
803
|
+
await authService.resetPassword('reset-token', 'New-Passw0rd-123!');
|
|
804
|
+
|
|
805
|
+
expect(mockRedis.getdel).toHaveBeenCalledTimes(1);
|
|
806
|
+
expect(mockRedis.get).not.toHaveBeenCalled();
|
|
807
|
+
expect(authRepo.updateUserPassword).toHaveBeenCalledWith(testUsers.validUser.id, 'new-hash');
|
|
808
|
+
expect(mockRedis.del).toHaveBeenCalledWith(`pw-reset-user:${testUsers.validUser.id}`);
|
|
809
|
+
expect(sessionRepository.deleteAllUserSessions).toHaveBeenCalledWith(testUsers.validUser.id);
|
|
810
|
+
expect(authRepo.deleteRefreshTokensByUserId).toHaveBeenCalledWith(testUsers.validUser.id);
|
|
811
|
+
});
|
|
812
|
+
|
|
813
|
+
it('the same link used twice at once changes the password only once', async () => {
|
|
814
|
+
// Redis hands the token to the first GETDEL only.
|
|
815
|
+
mockRedis.getdel.mockResolvedValueOnce(testUsers.validUser.id).mockResolvedValueOnce(null);
|
|
816
|
+
vi.mocked(authRepo.findUserById).mockResolvedValue(testUsers.validUser);
|
|
817
|
+
vi.mocked(hashPassword).mockResolvedValue('new-hash');
|
|
818
|
+
|
|
819
|
+
const results = await Promise.allSettled([
|
|
820
|
+
authService.resetPassword('reset-token', 'New-Passw0rd-123!'),
|
|
821
|
+
authService.resetPassword('reset-token', 'New-Passw0rd-123!'),
|
|
822
|
+
]);
|
|
823
|
+
|
|
824
|
+
expect(results.map((r) => r.status).sort()).toEqual(['fulfilled', 'rejected']);
|
|
825
|
+
const rejected = results.find((r) => r.status === 'rejected') as PromiseRejectedResult;
|
|
826
|
+
expect(rejected.reason).toMatchObject({ statusCode: 400, code: 'INVALID_RESET_TOKEN' });
|
|
827
|
+
expect(authRepo.updateUserPassword).toHaveBeenCalledTimes(1);
|
|
828
|
+
});
|
|
829
|
+
});
|
|
830
|
+
|
|
548
831
|
describe('getCurrentUser', () => {
|
|
549
832
|
it('should return sanitized user data', async () => {
|
|
550
833
|
// Arrange
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* "Sign out everywhere except here" (an owner's password change): the session
|
|
3
|
+
* and refresh-token deletes keep exactly the asking session. Tokens without a
|
|
4
|
+
* session always go: SQL `sessionId <> x` alone would skip NULL rows.
|
|
5
|
+
*/
|
|
6
|
+
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
|
7
|
+
import { prisma } from '@libs/prisma.js';
|
|
8
|
+
import { sessionRepository } from '../session.repo.js';
|
|
9
|
+
import { deleteRefreshTokensByUserId } from '../auth.repo.js';
|
|
10
|
+
|
|
11
|
+
vi.mock('@libs/prisma.js', () => ({
|
|
12
|
+
prisma: { session: { deleteMany: vi.fn() }, refreshToken: { deleteMany: vi.fn() } },
|
|
13
|
+
isPrismaNotFound: (): boolean => false,
|
|
14
|
+
isPrismaWriteConflict: (): boolean => false,
|
|
15
|
+
}));
|
|
16
|
+
|
|
17
|
+
beforeEach(() => {
|
|
18
|
+
vi.clearAllMocks();
|
|
19
|
+
vi.mocked(prisma.session.deleteMany).mockResolvedValue({ count: 2 });
|
|
20
|
+
});
|
|
21
|
+
|
|
22
|
+
describe('keeping one session', () => {
|
|
23
|
+
it('deleteOtherUserSessions deletes every session of the user but the kept one', async () => {
|
|
24
|
+
await expect(sessionRepository.deleteOtherUserSessions('u1', 's-keep')).resolves.toBe(2);
|
|
25
|
+
expect(prisma.session.deleteMany).toHaveBeenCalledWith({ where: { userId: 'u1', id: { not: 's-keep' } } });
|
|
26
|
+
});
|
|
27
|
+
|
|
28
|
+
it("deleteRefreshTokensByUserId with exceptSessionId keeps that session's tokens and deletes session-less ones", async () => {
|
|
29
|
+
await deleteRefreshTokensByUserId('u1', { exceptSessionId: 's-keep' });
|
|
30
|
+
expect(prisma.refreshToken.deleteMany).toHaveBeenCalledWith({
|
|
31
|
+
where: { userId: 'u1', OR: [{ sessionId: null }, { sessionId: { not: 's-keep' } }] },
|
|
32
|
+
});
|
|
33
|
+
});
|
|
34
|
+
|
|
35
|
+
it('deleteRefreshTokensByUserId without options still deletes all of them', async () => {
|
|
36
|
+
await deleteRefreshTokensByUserId('u1');
|
|
37
|
+
expect(prisma.refreshToken.deleteMany).toHaveBeenCalledWith({ where: { userId: 'u1' } });
|
|
38
|
+
});
|
|
39
|
+
});
|