create-tigra 3.3.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 +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 +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 +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/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 +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
|
@@ -28,11 +28,14 @@ vi.mock('../session.repo.js');
|
|
|
28
28
|
// In-memory Redis stub — account lockout (email+IP) uses Redis. Tests must
|
|
29
29
|
// never require a live Redis instance.
|
|
30
30
|
const mockRedis = vi.hoisted(() => ({
|
|
31
|
+
status: 'ready',
|
|
31
32
|
exists: vi.fn(),
|
|
33
|
+
ttl: vi.fn(),
|
|
32
34
|
incr: vi.fn(),
|
|
33
35
|
expire: vi.fn(),
|
|
34
36
|
set: vi.fn(),
|
|
35
37
|
get: vi.fn(),
|
|
38
|
+
getdel: vi.fn(),
|
|
36
39
|
del: vi.fn(),
|
|
37
40
|
}));
|
|
38
41
|
|
|
@@ -44,8 +47,12 @@ describe('Auth Service', () => {
|
|
|
44
47
|
beforeEach(() => {
|
|
45
48
|
resetMocks();
|
|
46
49
|
vi.clearAllMocks();
|
|
47
|
-
// Default Redis behavior: nothing locked, first failure
|
|
50
|
+
// Default Redis behavior: connected, nothing locked (TTL -2 = no key), first failure
|
|
51
|
+
mockRedis.status = 'ready';
|
|
48
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');
|
|
49
56
|
mockRedis.incr.mockResolvedValue(1);
|
|
50
57
|
mockRedis.expire.mockResolvedValue(1);
|
|
51
58
|
mockRedis.set.mockResolvedValue('OK');
|
|
@@ -101,6 +108,7 @@ describe('Auth Service', () => {
|
|
|
101
108
|
expect(authLib.signAccessToken).toHaveBeenCalledWith({
|
|
102
109
|
userId: createdUser.id,
|
|
103
110
|
role: createdUser.role,
|
|
111
|
+
sessionId: testSession.id, // the access token is bound to the new session
|
|
104
112
|
});
|
|
105
113
|
expect(authLib.generateRefreshToken).toHaveBeenCalled();
|
|
106
114
|
expect(sessionRepository.createSession).toHaveBeenCalledWith({
|
|
@@ -233,15 +241,19 @@ describe('Auth Service', () => {
|
|
|
233
241
|
expect(result.user).not.toHaveProperty('password');
|
|
234
242
|
});
|
|
235
243
|
|
|
236
|
-
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 () => {
|
|
237
245
|
// Arrange
|
|
238
246
|
vi.mocked(authRepo.findUserByEmail).mockResolvedValue(null);
|
|
247
|
+
vi.mocked(verifyPassword).mockResolvedValue(false);
|
|
239
248
|
|
|
240
249
|
// Act & Assert
|
|
241
250
|
await expect(authService.login(validLoginInput)).rejects.toThrow(UnauthorizedError);
|
|
242
251
|
await expect(authService.login(validLoginInput)).rejects.toThrow('Invalid email or password');
|
|
243
252
|
expect(authRepo.findDeletedUserByEmail).not.toHaveBeenCalled();
|
|
244
|
-
|
|
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`);
|
|
245
257
|
});
|
|
246
258
|
|
|
247
259
|
it('should not restore or authenticate a soft-deleted account with correct credentials', async () => {
|
|
@@ -258,7 +270,8 @@ describe('Auth Service', () => {
|
|
|
258
270
|
await expect(authService.login(validLoginInput)).rejects.toThrow(UnauthorizedError);
|
|
259
271
|
await expect(authService.login(validLoginInput)).rejects.toThrow('Invalid email or password');
|
|
260
272
|
expect(authRepo.findDeletedUserByEmail).not.toHaveBeenCalled();
|
|
261
|
-
|
|
273
|
+
// Only the dummy hash is checked, never the deleted account's own password
|
|
274
|
+
expect(verifyPassword).not.toHaveBeenCalledWith(validLoginInput.password, testUsers.validUser.password);
|
|
262
275
|
expect(authLib.signAccessToken).not.toHaveBeenCalled();
|
|
263
276
|
expect(authLib.generateRefreshToken).not.toHaveBeenCalled();
|
|
264
277
|
expect(sessionRepository.createSession).not.toHaveBeenCalled();
|
|
@@ -328,17 +341,36 @@ describe('Auth Service', () => {
|
|
|
328
341
|
const loginInput = { email: 'test@example.com', password: 'WrongPassword!' };
|
|
329
342
|
const attackerIp = '203.0.113.7';
|
|
330
343
|
|
|
331
|
-
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 () => {
|
|
332
345
|
// Arrange
|
|
333
346
|
vi.mocked(authRepo.findUserByEmail).mockResolvedValue(testUsers.validUser);
|
|
334
|
-
mockRedis.
|
|
347
|
+
mockRedis.ttl.mockResolvedValue(600); // lock key present for this pair, 10 min left
|
|
335
348
|
|
|
336
|
-
// Act & Assert
|
|
349
|
+
// Act & Assert — even the right password gets the locked answer
|
|
337
350
|
await expect(
|
|
338
|
-
authService.login(loginInput, 'test-agent', attackerIp),
|
|
339
|
-
).rejects.
|
|
340
|
-
|
|
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}`);
|
|
341
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);
|
|
342
374
|
});
|
|
343
375
|
|
|
344
376
|
it('should NOT lock out the same email from a different IP (no remote lockout DoS)', async () => {
|
|
@@ -348,7 +380,7 @@ describe('Auth Service', () => {
|
|
|
348
380
|
const expiresAt = new Date(Date.now() + 7 * 24 * 60 * 60 * 1000);
|
|
349
381
|
|
|
350
382
|
vi.mocked(authRepo.findUserByEmail).mockResolvedValue(testUsers.validUser);
|
|
351
|
-
mockRedis.
|
|
383
|
+
mockRedis.ttl.mockResolvedValue(-2);
|
|
352
384
|
vi.mocked(verifyPassword).mockResolvedValue(true);
|
|
353
385
|
vi.mocked(authLib.signAccessToken).mockReturnValue('access');
|
|
354
386
|
vi.mocked(authLib.generateRefreshToken).mockReturnValue('refresh');
|
|
@@ -364,7 +396,7 @@ describe('Auth Service', () => {
|
|
|
364
396
|
);
|
|
365
397
|
|
|
366
398
|
// Assert — lock was checked for the VICTIM's pair only, and login succeeded
|
|
367
|
-
expect(mockRedis.
|
|
399
|
+
expect(mockRedis.ttl).toHaveBeenCalledWith(`login-lock:test@example.com:${victimIp}`);
|
|
368
400
|
expect(result.accessToken).toBe('access');
|
|
369
401
|
});
|
|
370
402
|
|
|
@@ -372,26 +404,31 @@ describe('Auth Service', () => {
|
|
|
372
404
|
// Arrange
|
|
373
405
|
vi.mocked(authRepo.findUserByEmail).mockResolvedValue(testUsers.validUser);
|
|
374
406
|
vi.mocked(verifyPassword).mockResolvedValue(false);
|
|
375
|
-
mockRedis.incr.mockResolvedValue(
|
|
407
|
+
mockRedis.incr.mockResolvedValue(14); // one below the first lock
|
|
376
408
|
|
|
377
409
|
// Act & Assert
|
|
378
|
-
await expect(authService.login(loginInput, 'test-agent', attackerIp)).rejects.
|
|
379
|
-
|
|
380
|
-
);
|
|
410
|
+
await expect(authService.login(loginInput, 'test-agent', attackerIp)).rejects.toMatchObject({
|
|
411
|
+
code: 'INVALID_CREDENTIALS',
|
|
412
|
+
});
|
|
381
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);
|
|
382
416
|
expect(mockRedis.set).not.toHaveBeenCalled(); // no lock yet
|
|
383
417
|
});
|
|
384
418
|
|
|
385
|
-
it('should
|
|
419
|
+
it('should lock for 15 minutes on the 15th failure and say so on that same attempt', async () => {
|
|
386
420
|
// Arrange
|
|
387
421
|
vi.mocked(authRepo.findUserByEmail).mockResolvedValue(testUsers.validUser);
|
|
388
422
|
vi.mocked(verifyPassword).mockResolvedValue(false);
|
|
389
|
-
mockRedis.incr.mockResolvedValue(
|
|
423
|
+
mockRedis.incr.mockResolvedValue(15); // hits the first threshold
|
|
390
424
|
|
|
391
425
|
// Act & Assert
|
|
392
|
-
await expect(authService.login(loginInput, 'test-agent', attackerIp)).rejects.
|
|
393
|
-
|
|
394
|
-
|
|
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
|
+
});
|
|
395
432
|
expect(mockRedis.set).toHaveBeenCalledWith(
|
|
396
433
|
`login-lock:test@example.com:${attackerIp}`,
|
|
397
434
|
'1',
|
|
@@ -400,11 +437,38 @@ describe('Auth Service', () => {
|
|
|
400
437
|
);
|
|
401
438
|
});
|
|
402
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
|
+
|
|
403
467
|
it('should fail open and allow login when Redis is unavailable', async () => {
|
|
404
468
|
// Arrange — Redis down: lockout checks must not block all logins
|
|
405
469
|
const expiresAt = new Date(Date.now() + 7 * 24 * 60 * 60 * 1000);
|
|
406
470
|
vi.mocked(authRepo.findUserByEmail).mockResolvedValue(testUsers.validUser);
|
|
407
|
-
mockRedis.
|
|
471
|
+
mockRedis.ttl.mockRejectedValue(new Error('Redis down'));
|
|
408
472
|
mockRedis.del.mockRejectedValue(new Error('Redis down'));
|
|
409
473
|
vi.mocked(verifyPassword).mockResolvedValue(true);
|
|
410
474
|
vi.mocked(authLib.signAccessToken).mockReturnValue('access');
|
|
@@ -496,6 +560,7 @@ describe('Auth Service', () => {
|
|
|
496
560
|
expect(authLib.signAccessToken).toHaveBeenCalledWith({
|
|
497
561
|
userId: testUsers.validUser.id,
|
|
498
562
|
role: testUsers.validUser.role,
|
|
563
|
+
sessionId: testSession.id,
|
|
499
564
|
});
|
|
500
565
|
expect(authRepo.rotateRefreshToken).toHaveBeenCalledWith(validRefreshToken, {
|
|
501
566
|
token: newRefreshToken,
|
|
@@ -567,12 +632,46 @@ describe('Auth Service', () => {
|
|
|
567
632
|
expect(authLib.signAccessToken).not.toHaveBeenCalled();
|
|
568
633
|
});
|
|
569
634
|
|
|
570
|
-
it('
|
|
571
|
-
|
|
572
|
-
// the
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
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,
|
|
667
|
+
);
|
|
668
|
+
});
|
|
669
|
+
|
|
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.
|
|
576
675
|
const storedToken = {
|
|
577
676
|
...testRefreshToken,
|
|
578
677
|
sessionId: testSession.id,
|
|
@@ -583,19 +682,18 @@ describe('Auth Service', () => {
|
|
|
583
682
|
vi.mocked(authLib.signAccessToken).mockReturnValue('access');
|
|
584
683
|
vi.mocked(authLib.generateRefreshToken).mockReturnValue('refresh');
|
|
585
684
|
vi.mocked(authLib.getRefreshTokenExpiresAt).mockReturnValue(new Date());
|
|
586
|
-
vi.mocked(authRepo.rotateRefreshToken).mockResolvedValue(false); //
|
|
587
|
-
vi.mocked(authRepo.deleteRefreshTokensByUserId).mockResolvedValue(undefined);
|
|
588
|
-
vi.mocked(sessionRepository.deleteAllUserSessions).mockResolvedValue(1);
|
|
685
|
+
vi.mocked(authRepo.rotateRefreshToken).mockResolvedValue(false); // the parallel request rotated it first
|
|
589
686
|
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
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();
|
|
594
693
|
});
|
|
595
694
|
|
|
596
695
|
it('should NOT revoke the token family on a successful rotation', async () => {
|
|
597
|
-
// Companion to the
|
|
598
|
-
// the happy path.
|
|
696
|
+
// Companion to the race test: nothing is revoked on a normal rotation either.
|
|
599
697
|
const storedToken = {
|
|
600
698
|
...testRefreshToken,
|
|
601
699
|
sessionId: testSession.id,
|
|
@@ -668,6 +766,68 @@ describe('Auth Service', () => {
|
|
|
668
766
|
});
|
|
669
767
|
});
|
|
670
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
|
+
|
|
671
831
|
describe('getCurrentUser', () => {
|
|
672
832
|
it('should return sanitized user data', async () => {
|
|
673
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
|
+
});
|
|
@@ -0,0 +1,246 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Identity and sessions against a real MySQL and Redis: what must stay true
|
|
3
|
+
* about tokens and sessions (the layer 3 hardening).
|
|
4
|
+
* - Refresh and reset tokens are stored as fingerprints, never as issued.
|
|
5
|
+
* - Two refreshes with the same cookie at once: exactly one wins; the other
|
|
6
|
+
* gets 401 REFRESH_TOKEN_ROTATED and keeps its cookies.
|
|
7
|
+
* - An access token dies with its session (logout, logout-all, password
|
|
8
|
+
* reset, admin revoke), and a token without a session id is refused.
|
|
9
|
+
* - A reset link works once, even when used twice at the same moment.
|
|
10
|
+
* - Wrong passwords on change/delete answer 422, a ban stops refresh at once,
|
|
11
|
+
* 15 wrong sign-ins lock the email for this address, hostile cookies never
|
|
12
|
+
* cause a 500.
|
|
13
|
+
* Emails go to an in-process Resend stub; nothing is sent.
|
|
14
|
+
*/
|
|
15
|
+
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
|
|
16
|
+
import type { FastifyInstance } from 'fastify';
|
|
17
|
+
import {
|
|
18
|
+
PASSWORD,
|
|
19
|
+
call,
|
|
20
|
+
clearsCookies,
|
|
21
|
+
db,
|
|
22
|
+
redis,
|
|
23
|
+
registerAdmin,
|
|
24
|
+
registerUser,
|
|
25
|
+
signIn,
|
|
26
|
+
startEmailStub,
|
|
27
|
+
tokenOf,
|
|
28
|
+
uniqueEmail,
|
|
29
|
+
type CookieJar,
|
|
30
|
+
type EmailStub,
|
|
31
|
+
} from '@/test/integration-helpers.js';
|
|
32
|
+
|
|
33
|
+
let app: FastifyInstance;
|
|
34
|
+
let mail: EmailStub;
|
|
35
|
+
|
|
36
|
+
beforeAll(async () => {
|
|
37
|
+
mail = await startEmailStub();
|
|
38
|
+
const { buildTestApp } = await import('@/test/integration-helpers.js');
|
|
39
|
+
app = await buildTestApp();
|
|
40
|
+
});
|
|
41
|
+
|
|
42
|
+
afterAll(async () => {
|
|
43
|
+
await app?.close();
|
|
44
|
+
await mail?.close();
|
|
45
|
+
});
|
|
46
|
+
|
|
47
|
+
/** Only the access token of a jar, as a Cookie header (so a refresh cannot rescue it). */
|
|
48
|
+
const accessOnly = (jar: CookieJar): string => `access_token=${jar.get('access_token')}`;
|
|
49
|
+
|
|
50
|
+
/** Requests a reset link for the address and returns its raw token. */
|
|
51
|
+
async function resetTokenFor(email: string): Promise<string> {
|
|
52
|
+
const r = await call(app, 'POST', '/auth/forgot-password', { payload: { email } });
|
|
53
|
+
expect(r.status).toBe(200);
|
|
54
|
+
return tokenOf(mail.to(email).filter((e) => /reset-password/.test(e.link ?? '')).at(-1)?.link ?? null);
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
describe('tokens are stored as fingerprints', () => {
|
|
58
|
+
it('refresh tokens in the database are 64-hex SHA-256 fingerprints, never the cookie value', async () => {
|
|
59
|
+
const u = await registerUser(app, 'fp');
|
|
60
|
+
const rows = await (await db()).refreshToken.findMany({ where: { userId: u.id }, select: { token: true } });
|
|
61
|
+
const cookieValue = decodeURIComponent(u.jar.get('refresh_token') ?? '');
|
|
62
|
+
expect(rows.length).toBeGreaterThan(0);
|
|
63
|
+
expect(rows.every((r) => /^[0-9a-f]{64}$/.test(r.token))).toBe(true);
|
|
64
|
+
expect(cookieValue.length).toBeGreaterThan(0);
|
|
65
|
+
expect(rows.map((r) => r.token)).not.toContain(cookieValue);
|
|
66
|
+
});
|
|
67
|
+
|
|
68
|
+
it('no reset key or pointer in Redis holds the raw reset token', async () => {
|
|
69
|
+
const u = await registerUser(app, 'resetkey');
|
|
70
|
+
const raw = await resetTokenFor(u.email);
|
|
71
|
+
const keys = await (await redis()).keys('pw-reset*');
|
|
72
|
+
expect(keys.length).toBeGreaterThan(0);
|
|
73
|
+
expect(keys.join('\n')).not.toContain(raw);
|
|
74
|
+
for (const key of keys) {
|
|
75
|
+
const type = await (await redis()).type(key);
|
|
76
|
+
const value = type === 'string' ? await (await redis()).get(key) : JSON.stringify(await (await redis()).hgetall(key));
|
|
77
|
+
expect(value ?? '').not.toContain(raw);
|
|
78
|
+
}
|
|
79
|
+
});
|
|
80
|
+
});
|
|
81
|
+
|
|
82
|
+
describe('parallel refresh', () => {
|
|
83
|
+
it('two refreshes with the same cookie: one 200, one 401 REFRESH_TOKEN_ROTATED that keeps its cookies', async () => {
|
|
84
|
+
const u = await registerUser(app, 'race');
|
|
85
|
+
const otherDevice = await signIn(app, u.email);
|
|
86
|
+
let raced: { winner: Awaited<ReturnType<typeof call>>; loser: Awaited<ReturnType<typeof call>> } | null = null;
|
|
87
|
+
// A real race: on a fast machine both can still land one after the other; try a few times.
|
|
88
|
+
for (let attempt = 0; attempt < 8 && !raced; attempt++) {
|
|
89
|
+
const device = await signIn(app, u.email);
|
|
90
|
+
const sameCookie = device.header();
|
|
91
|
+
const pair = await Promise.all([
|
|
92
|
+
call(app, 'POST', '/auth/refresh', { cookie: sameCookie }),
|
|
93
|
+
call(app, 'POST', '/auth/refresh', { cookie: sameCookie }),
|
|
94
|
+
]);
|
|
95
|
+
const winner = pair.find((r) => r.status === 200);
|
|
96
|
+
const loser = pair.find((r) => r.code === 'REFRESH_TOKEN_ROTATED');
|
|
97
|
+
if (winner && loser) raced = { winner, loser };
|
|
98
|
+
for (const r of pair) expect(r.status).not.toBe(500);
|
|
99
|
+
}
|
|
100
|
+
expect(raced, 'no attempt produced a real race').not.toBeNull();
|
|
101
|
+
expect(raced!.loser.status).toBe(401);
|
|
102
|
+
expect(clearsCookies(raced!.loser.res)).toBe(false);
|
|
103
|
+
|
|
104
|
+
// The winner's new refresh token works afterwards; another device was not touched.
|
|
105
|
+
const { CookieJar } = await import('@/test/integration-helpers.js');
|
|
106
|
+
const winnerJar = new CookieJar().absorb(raced!.winner.res);
|
|
107
|
+
expect((await call(app, 'POST', '/auth/refresh', { jar: winnerJar })).status).toBe(200);
|
|
108
|
+
expect((await call(app, 'GET', '/auth/me', { jar: otherDevice })).status).toBe(200);
|
|
109
|
+
});
|
|
110
|
+
});
|
|
111
|
+
|
|
112
|
+
describe('an access token ends with its session', () => {
|
|
113
|
+
it('logout: the old access token is refused at once (401 SESSION_EXPIRED, cookies cleared); another device stays in', async () => {
|
|
114
|
+
const u = await registerUser(app, 'logout');
|
|
115
|
+
const otherDevice = await signIn(app, u.email);
|
|
116
|
+
const token = accessOnly(u.jar);
|
|
117
|
+
expect((await call(app, 'GET', '/auth/me', { cookie: token })).status).toBe(200);
|
|
118
|
+
await call(app, 'POST', '/auth/logout', { jar: u.jar });
|
|
119
|
+
const after = await call(app, 'GET', '/auth/me', { cookie: token });
|
|
120
|
+
expect(after.status).toBe(401);
|
|
121
|
+
expect(after.code).toBe('SESSION_EXPIRED');
|
|
122
|
+
expect(clearsCookies(after.res)).toBe(true);
|
|
123
|
+
// The token is bound to ITS session, not to "some live session of this user".
|
|
124
|
+
expect((await call(app, 'GET', '/auth/me', { cookie: accessOnly(otherDevice) })).status).toBe(200);
|
|
125
|
+
});
|
|
126
|
+
|
|
127
|
+
it("logout-all: another device's access token is refused at once", async () => {
|
|
128
|
+
const u = await registerUser(app, 'logoutall');
|
|
129
|
+
const other = await signIn(app, u.email);
|
|
130
|
+
await call(app, 'POST', '/auth/logout-all', { jar: u.jar });
|
|
131
|
+
const r = await call(app, 'GET', '/auth/me', { cookie: accessOnly(other) });
|
|
132
|
+
expect([r.status, r.code]).toEqual([401, 'SESSION_EXPIRED']);
|
|
133
|
+
});
|
|
134
|
+
|
|
135
|
+
it('password reset: every earlier access token is refused at once', async () => {
|
|
136
|
+
const u = await registerUser(app, 'resetends');
|
|
137
|
+
const other = await signIn(app, u.email);
|
|
138
|
+
const token = await resetTokenFor(u.email);
|
|
139
|
+
expect((await call(app, 'POST', '/auth/reset-password', { payload: { token, newPassword: 'New-Passw0rd-456!' } })).status).toBe(200);
|
|
140
|
+
for (const jar of [u.jar, other]) {
|
|
141
|
+
const r = await call(app, 'GET', '/auth/me', { cookie: accessOnly(jar) });
|
|
142
|
+
expect([r.status, r.code]).toEqual([401, 'SESSION_EXPIRED']);
|
|
143
|
+
}
|
|
144
|
+
});
|
|
145
|
+
|
|
146
|
+
it("admin revoke: that session's access token is refused at once", async () => {
|
|
147
|
+
const admin = await registerAdmin(app, 'revoker');
|
|
148
|
+
const victim = await registerUser(app, 'revoked');
|
|
149
|
+
const sessions = await call(app, 'GET', '/auth/sessions', { jar: victim.jar });
|
|
150
|
+
const newest = [...(sessions.body?.data ?? [])].sort((a, b) => b.createdAt.localeCompare(a.createdAt))[0];
|
|
151
|
+
const del = await call(app, 'DELETE', `/admin/sessions/${newest.id}`, { jar: admin.jar });
|
|
152
|
+
expect(del.status).toBe(200);
|
|
153
|
+
const r = await call(app, 'GET', '/auth/me', { cookie: accessOnly(victim.jar) });
|
|
154
|
+
expect([r.status, r.code]).toEqual([401, 'SESSION_EXPIRED']);
|
|
155
|
+
});
|
|
156
|
+
|
|
157
|
+
it('a validly signed token without a session id is refused (401 SESSION_EXPIRED, cookies cleared)', async () => {
|
|
158
|
+
const u = await registerUser(app, 'legacy');
|
|
159
|
+
const legacy = app.jwt.sign({ userId: u.id, role: 'USER' } as never, { expiresIn: '15m' });
|
|
160
|
+
const r = await call(app, 'GET', '/auth/me', { cookie: `access_token=${legacy}` });
|
|
161
|
+
expect([r.status, r.code]).toEqual([401, 'SESSION_EXPIRED']);
|
|
162
|
+
expect(clearsCookies(r.res)).toBe(true);
|
|
163
|
+
});
|
|
164
|
+
});
|
|
165
|
+
|
|
166
|
+
describe('reset links', () => {
|
|
167
|
+
it('the same link twice at once: exactly one 200, the other 400 INVALID_RESET_TOKEN', async () => {
|
|
168
|
+
const u = await registerUser(app, 'resettwice');
|
|
169
|
+
const token = await resetTokenFor(u.email);
|
|
170
|
+
const answers = await Promise.all([
|
|
171
|
+
call(app, 'POST', '/auth/reset-password', { payload: { token, newPassword: 'New-Passw0rd-456!' } }),
|
|
172
|
+
call(app, 'POST', '/auth/reset-password', { payload: { token, newPassword: 'New-Passw0rd-789!' } }),
|
|
173
|
+
]);
|
|
174
|
+
expect(answers.map((a) => `${a.status}${a.code ? ` ${a.code}` : ''}`).sort()).toEqual(['200', '400 INVALID_RESET_TOKEN']);
|
|
175
|
+
});
|
|
176
|
+
});
|
|
177
|
+
|
|
178
|
+
describe('passwords and sign-in answers', () => {
|
|
179
|
+
it('wrong current password on change → 422 INVALID_CURRENT_PASSWORD; on delete → 422 INVALID_PASSWORD', async () => {
|
|
180
|
+
const u = await registerUser(app, 'wrongpw');
|
|
181
|
+
const change = await call(app, 'PATCH', '/users/me/password', {
|
|
182
|
+
jar: u.jar,
|
|
183
|
+
payload: { currentPassword: 'Wrong-Passw0rd-1', newPassword: 'New-Passw0rd-456!' },
|
|
184
|
+
});
|
|
185
|
+
expect([change.status, change.code]).toEqual([422, 'INVALID_CURRENT_PASSWORD']);
|
|
186
|
+
const del = await call(app, 'DELETE', '/users/me', { jar: u.jar, payload: { password: 'Wrong-Passw0rd-1' } });
|
|
187
|
+
expect([del.status, del.code]).toEqual([422, 'INVALID_PASSWORD']);
|
|
188
|
+
});
|
|
189
|
+
|
|
190
|
+
it('the right current password changes it and keeps this device signed in', async () => {
|
|
191
|
+
const u = await registerUser(app, 'rightpw');
|
|
192
|
+
const change = await call(app, 'PATCH', '/users/me/password', {
|
|
193
|
+
jar: u.jar,
|
|
194
|
+
payload: { currentPassword: PASSWORD, newPassword: 'New-Passw0rd-456!' },
|
|
195
|
+
});
|
|
196
|
+
expect(change.status).toBe(200);
|
|
197
|
+
expect((await call(app, 'GET', '/auth/me', { jar: u.jar })).status).toBe(200);
|
|
198
|
+
});
|
|
199
|
+
|
|
200
|
+
it('login → me → refresh → me works; a wrong password is 401 INVALID_CREDENTIALS; bad input is 422 with fields', async () => {
|
|
201
|
+
const u = await registerUser(app, 'flow');
|
|
202
|
+
const jar = await signIn(app, u.email);
|
|
203
|
+
expect((await call(app, 'GET', '/auth/me', { jar })).status).toBe(200);
|
|
204
|
+
expect((await call(app, 'POST', '/auth/refresh', { jar })).status).toBe(200);
|
|
205
|
+
expect((await call(app, 'GET', '/auth/me', { jar })).status).toBe(200);
|
|
206
|
+
const wrong = await call(app, 'POST', '/auth/login', { payload: { email: u.email, password: 'Wrong-Passw0rd-1' } });
|
|
207
|
+
expect([wrong.status, wrong.code]).toEqual([401, 'INVALID_CREDENTIALS']);
|
|
208
|
+
const bad = await call(app, 'POST', '/auth/register', { payload: { email: 'not-an-email', password: 'x', firstName: '', lastName: '' } });
|
|
209
|
+
expect([bad.status, bad.code]).toEqual([422, 'VALIDATION_FAILED']);
|
|
210
|
+
expect(Array.isArray(bad.body?.error?.fields)).toBe(true);
|
|
211
|
+
});
|
|
212
|
+
|
|
213
|
+
it("a ban stops the user's refresh and says ACCOUNT_DEACTIVATED on their access token at once", async () => {
|
|
214
|
+
const admin = await registerAdmin(app, 'banner');
|
|
215
|
+
const victim = await registerUser(app, 'banned');
|
|
216
|
+
expect((await call(app, 'GET', '/auth/me', { jar: victim.jar.copy() })).status).toBe(200);
|
|
217
|
+
const ban = await call(app, 'PATCH', `/admin/users/${victim.id}/status`, { jar: admin.jar, payload: { isActive: false } });
|
|
218
|
+
expect(ban.status).toBe(200);
|
|
219
|
+
const refresh = await call(app, 'POST', '/auth/refresh', { cookie: victim.jar.header() });
|
|
220
|
+
expect([refresh.status, refresh.code]).toEqual([401, 'INVALID_REFRESH_TOKEN']);
|
|
221
|
+
const me = await call(app, 'GET', '/auth/me', { cookie: victim.jar.header() });
|
|
222
|
+
expect([me.status, me.code]).toEqual([403, 'ACCOUNT_DEACTIVATED']);
|
|
223
|
+
expect(clearsCookies(me.res)).toBe(true);
|
|
224
|
+
});
|
|
225
|
+
|
|
226
|
+
it('15 wrong sign-ins for one email from one address lock it (429 LOGIN_LOCKED)', async () => {
|
|
227
|
+
const email = uniqueEmail('lock');
|
|
228
|
+
const codes: (string | undefined)[] = [];
|
|
229
|
+
for (let i = 0; i < 15; i++) {
|
|
230
|
+
codes.push((await call(app, 'POST', '/auth/login', { payload: { email, password: 'Wrong-Passw0rd-1' } })).code);
|
|
231
|
+
}
|
|
232
|
+
expect(codes.slice(0, 14).every((c) => c === 'INVALID_CREDENTIALS')).toBe(true);
|
|
233
|
+
expect(codes[14]).toBe('LOGIN_LOCKED');
|
|
234
|
+
});
|
|
235
|
+
});
|
|
236
|
+
|
|
237
|
+
describe('hostile refresh cookies', () => {
|
|
238
|
+
it.each([
|
|
239
|
+
['empty', ''],
|
|
240
|
+
['8 KB', 'x'.repeat(8192)],
|
|
241
|
+
['garbage', '%%%;;notatoken'],
|
|
242
|
+
])('a %s refresh cookie → 401, never 500', async (_label, value) => {
|
|
243
|
+
const r = await call(app, 'POST', '/auth/refresh', { cookie: `refresh_token=${encodeURIComponent(value)}` });
|
|
244
|
+
expect(r.status).toBe(401);
|
|
245
|
+
});
|
|
246
|
+
});
|