create-tigra 4.0.1 → 5.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +43 -0
- package/README.md +21 -3
- package/bin/create-tigra.js +131 -65
- package/lib/installer-transaction.js +275 -0
- package/lib/patchers/diagnostics.patcher.js +123 -0
- package/lib/patchers/email-verification.patcher.js +86 -92
- package/lib/patchers/metrics.patcher.js +145 -0
- package/lib/project-files.js +99 -0
- package/modules/diagnostics/diagnostics.md +75 -0
- package/modules/diagnostics/prisma/diagnostic-bucket.prisma +22 -0
- package/modules/diagnostics/prisma/diagnostic-hourly-view.sql +24 -0
- package/modules/diagnostics/prisma/migration.sql +20 -0
- package/modules/diagnostics/server/__tests__/diagnostics.collector.test.ts +72 -0
- package/modules/diagnostics/server/__tests__/diagnostics.context.test.ts +51 -0
- package/modules/diagnostics/server/__tests__/diagnostics.integration.test.ts +123 -0
- package/modules/diagnostics/server/__tests__/diagnostics.service.test.ts +31 -0
- package/modules/diagnostics/server/diagnostics.collector.ts +95 -0
- package/modules/diagnostics/server/diagnostics.context.ts +73 -0
- package/modules/diagnostics/server/diagnostics.repo.ts +79 -0
- package/modules/diagnostics/server/diagnostics.routes.ts +16 -0
- package/modules/diagnostics/server/diagnostics.sample.ts +92 -0
- package/modules/diagnostics/server/diagnostics.schemas.ts +33 -0
- package/modules/diagnostics/server/diagnostics.service.ts +44 -0
- package/modules/email-verification/client/hooks/useVerification.ts +4 -7
- package/modules/email-verification/server/__tests__/verification.integration.test.ts +17 -0
- package/modules/email-verification/server/__tests__/verification.service.test.ts +71 -0
- package/modules/email-verification/server/verification.service.ts +102 -157
- package/modules/metrics/client/WebVitalsReporter.tsx +37 -0
- package/modules/metrics/client/__tests__/WebVitalsReporter.test.ts +66 -0
- package/modules/metrics/client/metrics.pages.ts +5 -0
- package/modules/metrics/performance.md +56 -0
- package/modules/metrics/prisma/metric-bucket.prisma +18 -0
- package/modules/metrics/prisma/migration.sql +17 -0
- package/modules/metrics/server/__tests__/metrics.collector.test.ts +97 -0
- package/modules/metrics/server/__tests__/metrics.integration.test.ts +88 -0
- package/modules/metrics/server/__tests__/metrics.schemas.test.ts +36 -0
- package/modules/metrics/server/__tests__/metrics.service.test.ts +84 -0
- package/modules/metrics/server/metrics.collector.ts +133 -0
- package/modules/metrics/server/metrics.pages.ts +3 -0
- package/modules/metrics/server/metrics.repo.ts +45 -0
- package/modules/metrics/server/metrics.routes.ts +45 -0
- package/modules/metrics/server/metrics.schemas.ts +57 -0
- package/modules/metrics/server/metrics.service.ts +104 -0
- package/package.json +1 -1
- package/template/AGENTS.md +18 -10
- package/template/client/.dockerignore +2 -5
- package/template/client/gitignore +43 -0
- package/template/client/src/app/focus-rings.policy.test.ts +88 -0
- package/template/client/src/app/globals.css +46 -0
- package/template/client/src/app/layout.tsx +5 -0
- package/template/client/src/app/page.tsx +2 -2
- package/template/client/src/components/common/InputModalityTracker.tsx +12 -0
- package/template/client/src/components/ui/input.tsx +3 -2
- package/template/client/src/features/auth/components/AuthInitializer.tsx +45 -7
- package/template/client/src/features/auth/hooks/useAuth.ts +10 -33
- package/template/client/src/features/auth/hooks/useCurrentUser.ts +3 -3
- package/template/client/src/features/auth/hooks/useSessionTransition.ts +51 -0
- package/template/client/src/features/auth/services/auth.service.ts +3 -2
- package/template/client/src/features/auth/store/authSlice.ts +11 -8
- package/template/client/src/features/auth/types/auth.types.ts +1 -0
- package/template/client/src/lib/api/__tests__/axios.config.test.ts +17 -0
- package/template/client/src/lib/api/__tests__/session-events.test.ts +23 -0
- package/template/client/src/lib/api/axios.config.ts +24 -6
- package/template/client/src/lib/api/session-events.ts +54 -0
- package/template/client/src/lib/input-modality.test.ts +79 -0
- package/template/client/src/lib/input-modality.ts +52 -0
- package/template/client/src/lib/observability/sentry-scrub.ts +63 -46
- package/template/client/src/store/__tests__/store.test.ts +1 -0
- package/template/gitignore +3 -2
- package/template/server/.dockerignore +2 -5
- package/template/server/.env.example +1 -0
- package/template/server/.env.example.production +1 -0
- package/template/server/README.md +7 -2
- package/template/server/docs/deployment.md +66 -0
- package/template/server/docs/logging.md +9 -8
- package/template/server/docs/rate-limits.md +6 -4
- package/template/server/gitignore +33 -0
- package/template/server/prisma/migrations/0_init/migration.sql +25 -0
- package/template/server/prisma/retrofits/20261116000000_retired_refresh_tokens/migration.sql +13 -0
- package/template/server/prisma/retrofits/20261116000100_avatar_cleanup/migration.sql +9 -0
- package/template/server/prisma/retrofits/20261117000000_account_purge/migration.sql +1 -0
- package/template/server/prisma/schema.prisma +25 -1
- package/template/server/src/__tests__/routes.integration.test.ts +5 -2
- package/template/server/src/app.ts +14 -5
- package/template/server/src/config/env.ts +8 -0
- package/template/server/src/config/rate-limit.config.ts +1 -1
- package/template/server/src/jobs/__tests__/cleanup-deleted-accounts.job.test.ts +26 -9
- package/template/server/src/jobs/__tests__/cleanup-expired-auth.job.test.ts +2 -1
- package/template/server/src/jobs/__tests__/jobs.integration.test.ts +51 -5
- package/template/server/src/jobs/cleanup-deleted-accounts.job.ts +30 -34
- package/template/server/src/jobs/cleanup-expired-auth.job.ts +2 -0
- package/template/server/src/jobs/index.ts +8 -2
- package/template/server/src/libs/__tests__/auth.test.ts +1 -1
- package/template/server/src/libs/__tests__/cookies.test.ts +16 -0
- package/template/server/src/libs/__tests__/error-handler.test.ts +20 -1
- package/template/server/src/libs/__tests__/http.test.ts +10 -10
- package/template/server/src/libs/__tests__/ip-block.test.ts +39 -7
- package/template/server/src/libs/__tests__/logger.test.ts +10 -1
- package/template/server/src/libs/__tests__/monitoring.test.ts +19 -0
- package/template/server/src/libs/__tests__/outbound.integration.test.ts +7 -10
- package/template/server/src/libs/__tests__/rate-limits.integration.test.ts +32 -3
- package/template/server/src/libs/__tests__/requestLogger.test.ts +9 -1
- package/template/server/src/libs/__tests__/safe-http.test.ts +65 -3
- package/template/server/src/libs/__tests__/sentry-scrub.test.ts +22 -6
- package/template/server/src/libs/__tests__/url-safety.test.ts +3 -1
- package/template/server/src/libs/account-mutation.ts +77 -0
- package/template/server/src/libs/auth.ts +37 -3
- package/template/server/src/libs/cookies.ts +25 -13
- package/template/server/src/libs/email-quota.ts +11 -7
- package/template/server/src/libs/email.ts +11 -8
- package/template/server/src/libs/error-handler.ts +16 -12
- package/template/server/src/libs/http.ts +37 -13
- package/template/server/src/libs/ip-block.ts +56 -34
- package/template/server/src/libs/logger.ts +23 -8
- package/template/server/src/libs/monitoring.ts +57 -31
- package/template/server/src/libs/observability/sentry.ts +65 -49
- package/template/server/src/libs/prisma.ts +1 -1
- package/template/server/src/libs/private-cache.ts +6 -0
- package/template/server/src/libs/rate-limiting.ts +4 -0
- package/template/server/src/libs/requestLogger.ts +3 -3
- package/template/server/src/libs/safe-http.ts +58 -18
- package/template/server/src/libs/storage/__tests__/upload-persistence.test.ts +15 -2
- package/template/server/src/libs/storage/file-storage.service.ts +59 -109
- package/template/server/src/libs/storage/file-validator.ts +2 -1
- package/template/server/src/libs/url-safety.ts +10 -2
- package/template/server/src/libs/validation-errors.ts +11 -8
- package/template/server/src/modules/admin/__tests__/admin.repo.test.ts +21 -4
- package/template/server/src/modules/admin/__tests__/admin.schemas.test.ts +11 -0
- package/template/server/src/modules/admin/__tests__/admin.service.test.ts +83 -40
- package/template/server/src/modules/admin/admin.controller.ts +4 -4
- package/template/server/src/modules/admin/admin.repo.ts +37 -54
- package/template/server/src/modules/admin/admin.routes.ts +3 -5
- package/template/server/src/modules/admin/admin.schemas.ts +3 -6
- package/template/server/src/modules/admin/admin.service.ts +61 -62
- package/template/server/src/modules/auth/__tests__/auth.schemas.test.ts +12 -0
- package/template/server/src/modules/auth/__tests__/auth.service.test.ts +58 -295
- package/template/server/src/modules/auth/__tests__/recovery.integration.test.ts +177 -0
- package/template/server/src/modules/auth/__tests__/recovery.queue.test.ts +159 -0
- package/template/server/src/modules/auth/__tests__/session-cleanup.test.ts +5 -10
- package/template/server/src/modules/auth/__tests__/sessions.integration.test.ts +1 -1
- package/template/server/src/modules/auth/__tests__/token-fingerprints.test.ts +115 -44
- package/template/server/src/modules/auth/auth-link-store.ts +64 -0
- package/template/server/src/modules/auth/auth-mail-queue.ts +124 -0
- package/template/server/src/modules/auth/auth.controller.ts +16 -5
- package/template/server/src/modules/auth/auth.repo.ts +152 -61
- package/template/server/src/modules/auth/auth.routes.ts +4 -0
- package/template/server/src/modules/auth/auth.schemas.ts +7 -3
- package/template/server/src/modules/auth/auth.service.ts +33 -237
- package/template/server/src/modules/auth/recovery.queue.ts +44 -0
- package/template/server/src/modules/auth/recovery.store.ts +7 -0
- package/template/server/src/modules/auth/session.repo.ts +5 -4
- package/template/server/src/modules/files/__tests__/files.integration.test.ts +29 -1
- package/template/server/src/modules/files/files.controller.ts +2 -2
- package/template/server/src/modules/users/__tests__/avatar-cleanup.test.ts +49 -0
- package/template/server/src/modules/users/__tests__/avatar-controller.test.ts +50 -0
- package/template/server/src/modules/users/__tests__/avatar-upload.test.ts +56 -105
- package/template/server/src/modules/users/__tests__/users.integration.test.ts +2 -2
- package/template/server/src/modules/users/__tests__/users.repo.test.ts +8 -11
- package/template/server/src/modules/users/__tests__/users.service.test.ts +116 -44
- package/template/server/src/modules/users/avatar-cleanup.ts +70 -0
- package/template/server/src/modules/users/users.controller.ts +28 -25
- package/template/server/src/modules/users/users.repo.ts +12 -51
- package/template/server/src/modules/users/users.service.ts +109 -234
- package/template/server/src/shared/responses/paginatedResponse.ts +4 -1
- package/template/server/src/shared/schemas/pagination.schema.ts +5 -1
- package/template/server/src/test/setup.ts +4 -0
|
@@ -6,10 +6,12 @@
|
|
|
6
6
|
|
|
7
7
|
import { logger } from '@libs/logger.js';
|
|
8
8
|
import { NotFoundError, ForbiddenError, ConflictError } from '@shared/errors/errors.js';
|
|
9
|
-
import {
|
|
9
|
+
import { RETENTION_MS } from '@/jobs/cleanup-deleted-accounts.job.js';
|
|
10
10
|
import { adminRepository } from './admin.repo.js';
|
|
11
|
-
import {
|
|
12
|
-
|
|
11
|
+
import {
|
|
12
|
+
assertAnotherSignInAdmin, assertMutationActor, revokeAccountCredentials, runAccountMutation,
|
|
13
|
+
type MutationActor,
|
|
14
|
+
} from '@libs/account-mutation.js';
|
|
13
15
|
|
|
14
16
|
import type { UserRole } from '@shared/types/index.js';
|
|
15
17
|
import type { AdminUser, AdminUserDetail, AdminSession, DashboardStats } from './admin.repo.js';
|
|
@@ -35,7 +37,7 @@ class AdminService {
|
|
|
35
37
|
...result,
|
|
36
38
|
items: result.items.map((user) => ({
|
|
37
39
|
...user,
|
|
38
|
-
purgeAt: new Date(user.deletedAt!.getTime() +
|
|
40
|
+
purgeAt: new Date(user.deletedAt!.getTime() + RETENTION_MS),
|
|
39
41
|
})),
|
|
40
42
|
};
|
|
41
43
|
}
|
|
@@ -49,17 +51,25 @@ class AdminService {
|
|
|
49
51
|
*
|
|
50
52
|
* @throws NotFoundError 404 USER_NOT_FOUND if the account does not exist (or was purged)
|
|
51
53
|
* @throws ConflictError 409 USER_NOT_DELETED if the account is not deleted
|
|
54
|
+
* @throws ConflictError 409 USER_PURGE_IN_PROGRESS once a purge has claimed the account
|
|
52
55
|
*/
|
|
53
|
-
async restoreUser(userId: string): Promise<AdminUser> {
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
56
|
+
async restoreUser(userId: string, actor: MutationActor): Promise<AdminUser> {
|
|
57
|
+
const user = await runAccountMutation(async tx => {
|
|
58
|
+
await assertMutationActor(tx, actor, 'ADMIN');
|
|
59
|
+
if (!(await adminRepository.restoreUser(tx, userId))) {
|
|
60
|
+
const state = await adminRepository.getPurgeState(tx, userId);
|
|
61
|
+
if (!state) {
|
|
62
|
+
throw new NotFoundError('User not found', 'USER_NOT_FOUND');
|
|
63
|
+
}
|
|
64
|
+
if (state.purgeStartedAt) {
|
|
65
|
+
throw new ConflictError('Permanent deletion has already started for this account.', 'USER_PURGE_IN_PROGRESS');
|
|
66
|
+
}
|
|
67
|
+
throw new ConflictError('This account is not deleted', 'USER_NOT_DELETED');
|
|
57
68
|
}
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
if (!user) throw new NotFoundError('User not found', 'USER_NOT_FOUND');
|
|
69
|
+
const restored = await adminRepository.findUserById(tx, userId);
|
|
70
|
+
if (!restored) throw new NotFoundError('User not found', 'USER_NOT_FOUND');
|
|
71
|
+
return restored;
|
|
72
|
+
});
|
|
63
73
|
|
|
64
74
|
logger.info({ msg: 'Deleted account restored', userId });
|
|
65
75
|
return user;
|
|
@@ -87,25 +97,22 @@ class AdminService {
|
|
|
87
97
|
* An admin can never ban themselves (like changing their own role): it would
|
|
88
98
|
* end their own sessions and could leave the project with no admin at all.
|
|
89
99
|
*/
|
|
90
|
-
async toggleUserStatus(userId: string, isActive: boolean,
|
|
91
|
-
if (!isActive && userId ===
|
|
100
|
+
async toggleUserStatus(userId: string, isActive: boolean, actor: MutationActor): Promise<AdminUser> {
|
|
101
|
+
if (!isActive && userId === actor.userId) {
|
|
92
102
|
throw new ForbiddenError('You cannot ban your own account', 'CANNOT_BAN_SELF');
|
|
93
103
|
}
|
|
94
104
|
|
|
95
|
-
const
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
throw new NotFoundError('User not found');
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
105
|
+
const { updatedUser, deletedSessions } = await runAccountMutation(async tx => {
|
|
106
|
+
await assertMutationActor(tx, actor, 'ADMIN');
|
|
107
|
+
const user = await adminRepository.findUserById(tx, userId);
|
|
108
|
+
if (!user) throw new NotFoundError('User not found');
|
|
109
|
+
if (!isActive) await assertAnotherSignInAdmin(tx, user);
|
|
110
|
+
const updatedUser = await adminRepository.updateUserStatus(tx, userId, isActive, isActive && !user.emailVerifiedAt);
|
|
111
|
+
const deletedSessions = isActive ? 0 : await revokeAccountCredentials(tx, userId);
|
|
112
|
+
return { updatedUser, deletedSessions };
|
|
113
|
+
});
|
|
103
114
|
|
|
104
115
|
if (!isActive) {
|
|
105
|
-
// Force-logout: invalidate all sessions and refresh tokens
|
|
106
|
-
const deletedSessions = await sessionRepository.deleteAllUserSessions(userId);
|
|
107
|
-
await deleteRefreshTokensByUserId(userId);
|
|
108
|
-
|
|
109
116
|
logger.info({
|
|
110
117
|
msg: 'User deactivated and sessions invalidated',
|
|
111
118
|
userId,
|
|
@@ -125,25 +132,25 @@ class AdminService {
|
|
|
125
132
|
async changeUserRole(
|
|
126
133
|
userId: string,
|
|
127
134
|
role: UserRole,
|
|
128
|
-
|
|
135
|
+
actor: MutationActor,
|
|
129
136
|
): Promise<AdminUser> {
|
|
130
|
-
if (userId ===
|
|
137
|
+
if (userId === actor.userId) {
|
|
131
138
|
throw new ForbiddenError('Cannot change your own role');
|
|
132
139
|
}
|
|
133
140
|
|
|
134
|
-
const
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
throw new NotFoundError('User not found');
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
+
const { updatedUser, deletedSessions } = await runAccountMutation(async tx => {
|
|
142
|
+
await assertMutationActor(tx, actor, 'ADMIN');
|
|
143
|
+
const user = await adminRepository.findUserById(tx, userId);
|
|
144
|
+
if (!user) throw new NotFoundError('User not found');
|
|
145
|
+
const demotion = user.role === 'ADMIN' && role === 'USER';
|
|
146
|
+
if (demotion) await assertAnotherSignInAdmin(tx, user);
|
|
147
|
+
const updatedUser = await adminRepository.updateUserRole(tx, userId, role);
|
|
148
|
+
const deletedSessions = demotion ? await revokeAccountCredentials(tx, userId) : undefined;
|
|
149
|
+
return { updatedUser, deletedSessions };
|
|
150
|
+
});
|
|
141
151
|
|
|
142
152
|
// If demoting from ADMIN to USER, invalidate sessions so new role takes effect
|
|
143
|
-
if (
|
|
144
|
-
const deletedSessions = await sessionRepository.deleteAllUserSessions(userId);
|
|
145
|
-
await deleteRefreshTokensByUserId(userId);
|
|
146
|
-
|
|
153
|
+
if (deletedSessions !== undefined) {
|
|
147
154
|
logger.info({
|
|
148
155
|
msg: 'User demoted from ADMIN and sessions invalidated',
|
|
149
156
|
userId,
|
|
@@ -167,13 +174,15 @@ class AdminService {
|
|
|
167
174
|
*/
|
|
168
175
|
async promoteToAdmin(rawEmail: string): Promise<'promoted' | 'already-admin' | 'not-found' | 'deleted' | 'banned'> {
|
|
169
176
|
const email = rawEmail.trim().toLowerCase(); // register stores emails lower-cased
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
+
return runAccountMutation(async tx => {
|
|
178
|
+
const account = await adminRepository.findAccountStateByEmail(tx, email);
|
|
179
|
+
if (!account) return 'not-found';
|
|
180
|
+
if (account.deletedAt) return 'deleted';
|
|
181
|
+
if (!account.isActive) return 'banned';
|
|
182
|
+
if (account.role === 'ADMIN') return 'already-admin';
|
|
183
|
+
await adminRepository.promoteToAdmin(tx, account.id, account.emailVerifiedAt ?? new Date());
|
|
184
|
+
return 'promoted';
|
|
185
|
+
});
|
|
177
186
|
}
|
|
178
187
|
|
|
179
188
|
/**
|
|
@@ -198,22 +207,12 @@ class AdminService {
|
|
|
198
207
|
* Force-expire a specific session.
|
|
199
208
|
* Deletes the session and any associated refresh tokens.
|
|
200
209
|
*/
|
|
201
|
-
async forceExpireSession(sessionId: string): Promise<void> {
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
throw new NotFoundError('Session not found');
|
|
206
|
-
}
|
|
207
|
-
|
|
208
|
-
// Delete refresh tokens linked to this session first
|
|
209
|
-
await adminRepository.deleteRefreshTokensBySessionId(sessionId);
|
|
210
|
-
await adminRepository.deleteSession(sessionId);
|
|
211
|
-
|
|
212
|
-
logger.info({
|
|
213
|
-
msg: 'Session force-expired by admin',
|
|
214
|
-
sessionId,
|
|
215
|
-
userId: session.userId,
|
|
210
|
+
async forceExpireSession(sessionId: string, actor: MutationActor): Promise<void> {
|
|
211
|
+
await runAccountMutation(async tx => {
|
|
212
|
+
await assertMutationActor(tx, actor, 'ADMIN');
|
|
213
|
+
if (!await adminRepository.deleteLiveSession(tx, sessionId)) throw new NotFoundError('Session not found');
|
|
216
214
|
});
|
|
215
|
+
logger.info({ msg: 'Session force-expired by admin', sessionId, adminUserId: actor.userId });
|
|
217
216
|
}
|
|
218
217
|
}
|
|
219
218
|
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { describe, expect, it } from 'vitest';
|
|
2
|
+
import { loginSchema, registerSchema } from '../auth.schemas.js';
|
|
3
|
+
|
|
4
|
+
describe('account email validation', () => {
|
|
5
|
+
const credentials = { password: 'FixturePassword1', firstName: 'Test', lastName: 'User' };
|
|
6
|
+
const email = (lastLabelLength: number): string => `${'a'.repeat(60)}@${'b'.repeat(63)}.${'c'.repeat(lastLabelLength)}.test`;
|
|
7
|
+
|
|
8
|
+
it.each([registerSchema, loginSchema])('enforces the database length before lookup or persistence', (schema) => {
|
|
9
|
+
expect(schema.safeParse({ ...credentials, email: email(61) }).success).toBe(true);
|
|
10
|
+
expect(schema.safeParse({ ...credentials, email: email(62) }).success).toBe(false);
|
|
11
|
+
});
|
|
12
|
+
});
|
|
@@ -35,7 +35,7 @@ const mockRedis = vi.hoisted(() => ({
|
|
|
35
35
|
expire: vi.fn(),
|
|
36
36
|
set: vi.fn(),
|
|
37
37
|
get: vi.fn(),
|
|
38
|
-
|
|
38
|
+
eval: vi.fn(),
|
|
39
39
|
del: vi.fn(),
|
|
40
40
|
}));
|
|
41
41
|
|
|
@@ -55,6 +55,7 @@ describe('Auth Service', () => {
|
|
|
55
55
|
vi.mocked(hashPassword).mockResolvedValue('dummy-hash');
|
|
56
56
|
mockRedis.incr.mockResolvedValue(1);
|
|
57
57
|
mockRedis.expire.mockResolvedValue(1);
|
|
58
|
+
mockRedis.eval.mockResolvedValue(0);
|
|
58
59
|
mockRedis.set.mockResolvedValue('OK');
|
|
59
60
|
mockRedis.del.mockResolvedValue(1);
|
|
60
61
|
// refresh() requires the token's session to exist and be unexpired
|
|
@@ -192,6 +193,14 @@ describe('Auth Service', () => {
|
|
|
192
193
|
});
|
|
193
194
|
});
|
|
194
195
|
|
|
196
|
+
it('accepts a recovery request without looking up the account in the HTTP path', async () => {
|
|
197
|
+
vi.mocked(authRepo.findUserByEmail).mockResolvedValue(null);
|
|
198
|
+
|
|
199
|
+
await authService.forgotPassword('recovery@example.test');
|
|
200
|
+
|
|
201
|
+
expect(authRepo.findUserByEmail).not.toHaveBeenCalled();
|
|
202
|
+
});
|
|
203
|
+
|
|
195
204
|
describe('login', () => {
|
|
196
205
|
const validLoginInput = {
|
|
197
206
|
email: 'test@example.com',
|
|
@@ -209,7 +218,7 @@ describe('Auth Service', () => {
|
|
|
209
218
|
vi.mocked(authLib.signAccessToken).mockReturnValue(accessToken);
|
|
210
219
|
vi.mocked(authLib.generateRefreshToken).mockReturnValue(refreshToken);
|
|
211
220
|
vi.mocked(authLib.getRefreshTokenExpiresAt).mockReturnValue(expiresAt);
|
|
212
|
-
vi.mocked(
|
|
221
|
+
vi.mocked(authRepo.createLoginSession).mockResolvedValue(testSession);
|
|
213
222
|
vi.mocked(authRepo.createRefreshToken).mockResolvedValue(testRefreshToken);
|
|
214
223
|
|
|
215
224
|
// Act
|
|
@@ -218,18 +227,14 @@ describe('Auth Service', () => {
|
|
|
218
227
|
// Assert
|
|
219
228
|
expect(authRepo.findUserByEmail).toHaveBeenCalledWith(validLoginInput.email);
|
|
220
229
|
expect(verifyPassword).toHaveBeenCalledWith(validLoginInput.password, testUsers.validUser.password);
|
|
221
|
-
expect(
|
|
230
|
+
expect(authRepo.createLoginSession).toHaveBeenCalledWith({
|
|
222
231
|
userId: testUsers.validUser.id,
|
|
232
|
+
verifiedPasswordHash: testUsers.validUser.password,
|
|
233
|
+
refreshToken,
|
|
223
234
|
deviceInfo: undefined,
|
|
224
235
|
ipAddress: undefined,
|
|
225
236
|
expiresAt,
|
|
226
237
|
});
|
|
227
|
-
expect(authRepo.createRefreshToken).toHaveBeenCalledWith({
|
|
228
|
-
token: refreshToken,
|
|
229
|
-
userId: testUsers.validUser.id,
|
|
230
|
-
sessionId: testSession.id,
|
|
231
|
-
expiresAt,
|
|
232
|
-
});
|
|
233
238
|
expect(result).toEqual({
|
|
234
239
|
user: expect.objectContaining({
|
|
235
240
|
id: testUsers.validUser.id,
|
|
@@ -385,7 +390,7 @@ describe('Auth Service', () => {
|
|
|
385
390
|
vi.mocked(authLib.signAccessToken).mockReturnValue('access');
|
|
386
391
|
vi.mocked(authLib.generateRefreshToken).mockReturnValue('refresh');
|
|
387
392
|
vi.mocked(authLib.getRefreshTokenExpiresAt).mockReturnValue(expiresAt);
|
|
388
|
-
vi.mocked(
|
|
393
|
+
vi.mocked(authRepo.createLoginSession).mockResolvedValue(testSession);
|
|
389
394
|
vi.mocked(authRepo.createRefreshToken).mockResolvedValue(testRefreshToken);
|
|
390
395
|
|
|
391
396
|
// Act
|
|
@@ -474,7 +479,7 @@ describe('Auth Service', () => {
|
|
|
474
479
|
vi.mocked(authLib.signAccessToken).mockReturnValue('access');
|
|
475
480
|
vi.mocked(authLib.generateRefreshToken).mockReturnValue('refresh');
|
|
476
481
|
vi.mocked(authLib.getRefreshTokenExpiresAt).mockReturnValue(expiresAt);
|
|
477
|
-
vi.mocked(
|
|
482
|
+
vi.mocked(authRepo.createLoginSession).mockResolvedValue(testSession);
|
|
478
483
|
vi.mocked(authRepo.createRefreshToken).mockResolvedValue(testRefreshToken);
|
|
479
484
|
|
|
480
485
|
// Act
|
|
@@ -490,279 +495,43 @@ describe('Auth Service', () => {
|
|
|
490
495
|
});
|
|
491
496
|
|
|
492
497
|
describe('refresh', () => {
|
|
493
|
-
const
|
|
494
|
-
|
|
495
|
-
it(
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
});
|
|
502
|
-
|
|
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
|
-
|
|
535
|
-
it('should successfully refresh tokens with valid refresh token', async () => {
|
|
536
|
-
// Arrange
|
|
537
|
-
const newAccessToken = 'new-access-token';
|
|
538
|
-
const newRefreshToken = 'new-refresh-token';
|
|
539
|
-
const expiresAt = new Date(Date.now() + 7 * 24 * 60 * 60 * 1000);
|
|
540
|
-
const storedToken = {
|
|
541
|
-
...testRefreshToken,
|
|
542
|
-
sessionId: testSession.id,
|
|
543
|
-
token: validRefreshToken,
|
|
544
|
-
expiresAt: new Date(Date.now() + 24 * 60 * 60 * 1000), // expires in 1 day
|
|
545
|
-
};
|
|
546
|
-
|
|
547
|
-
vi.mocked(authRepo.findRefreshToken).mockResolvedValue(storedToken);
|
|
548
|
-
vi.mocked(authRepo.findUserById).mockResolvedValue(testUsers.validUser);
|
|
549
|
-
vi.mocked(authLib.signAccessToken).mockReturnValue(newAccessToken);
|
|
550
|
-
vi.mocked(authLib.generateRefreshToken).mockReturnValue(newRefreshToken);
|
|
551
|
-
vi.mocked(authLib.getRefreshTokenExpiresAt).mockReturnValue(expiresAt);
|
|
552
|
-
vi.mocked(authRepo.rotateRefreshToken).mockResolvedValue(true);
|
|
553
|
-
|
|
554
|
-
// Act
|
|
555
|
-
const result = await authService.refresh(validRefreshToken);
|
|
556
|
-
|
|
557
|
-
// Assert
|
|
558
|
-
expect(authRepo.findRefreshToken).toHaveBeenCalledWith(validRefreshToken);
|
|
559
|
-
expect(authRepo.findUserById).toHaveBeenCalledWith(storedToken.userId);
|
|
560
|
-
expect(authLib.signAccessToken).toHaveBeenCalledWith({
|
|
561
|
-
userId: testUsers.validUser.id,
|
|
562
|
-
role: testUsers.validUser.role,
|
|
563
|
-
sessionId: testSession.id,
|
|
564
|
-
});
|
|
565
|
-
expect(authRepo.rotateRefreshToken).toHaveBeenCalledWith(validRefreshToken, {
|
|
566
|
-
token: newRefreshToken,
|
|
567
|
-
userId: testUsers.validUser.id,
|
|
568
|
-
sessionId: testSession.id,
|
|
569
|
-
expiresAt,
|
|
570
|
-
});
|
|
571
|
-
expect(result).toEqual({
|
|
572
|
-
accessToken: newAccessToken,
|
|
573
|
-
refreshToken: newRefreshToken,
|
|
574
|
-
});
|
|
575
|
-
});
|
|
576
|
-
|
|
577
|
-
it('should throw UnauthorizedError if refresh token not found', async () => {
|
|
578
|
-
// Arrange
|
|
579
|
-
vi.mocked(authRepo.findRefreshToken).mockResolvedValue(null);
|
|
580
|
-
|
|
581
|
-
// Act & Assert
|
|
582
|
-
await expect(authService.refresh(validRefreshToken)).rejects.toThrow(UnauthorizedError);
|
|
583
|
-
await expect(authService.refresh(validRefreshToken)).rejects.toThrow('Invalid refresh token');
|
|
584
|
-
});
|
|
585
|
-
|
|
586
|
-
it('should throw UnauthorizedError if refresh token expired', async () => {
|
|
587
|
-
// Arrange
|
|
588
|
-
const expiredToken = {
|
|
589
|
-
...testRefreshToken,
|
|
590
|
-
sessionId: testSession.id,
|
|
591
|
-
expiresAt: new Date(Date.now() - 1000), // expired 1 second ago
|
|
592
|
-
};
|
|
593
|
-
vi.mocked(authRepo.findRefreshToken).mockResolvedValue(expiredToken);
|
|
594
|
-
vi.mocked(authRepo.deleteRefreshToken).mockResolvedValue(undefined);
|
|
595
|
-
|
|
596
|
-
// Act & Assert
|
|
597
|
-
await expect(authService.refresh(validRefreshToken)).rejects.toThrow(UnauthorizedError);
|
|
598
|
-
await expect(authService.refresh(validRefreshToken)).rejects.toThrow('Refresh token expired');
|
|
599
|
-
expect(authRepo.deleteRefreshToken).toHaveBeenCalledWith(validRefreshToken);
|
|
600
|
-
});
|
|
601
|
-
|
|
602
|
-
it('should throw UnauthorizedError if user not found', async () => {
|
|
603
|
-
// Arrange
|
|
604
|
-
const storedToken = {
|
|
605
|
-
...testRefreshToken,
|
|
606
|
-
sessionId: testSession.id,
|
|
607
|
-
expiresAt: new Date(Date.now() + 24 * 60 * 60 * 1000),
|
|
608
|
-
};
|
|
609
|
-
vi.mocked(authRepo.findRefreshToken).mockResolvedValue(storedToken);
|
|
610
|
-
vi.mocked(authRepo.findUserById).mockResolvedValue(null);
|
|
611
|
-
|
|
612
|
-
// Act & Assert
|
|
613
|
-
await expect(authService.refresh(validRefreshToken)).rejects.toThrow(UnauthorizedError);
|
|
614
|
-
await expect(authService.refresh(validRefreshToken)).rejects.toThrow('User not found or disabled');
|
|
615
|
-
});
|
|
616
|
-
|
|
617
|
-
it('should refuse to refresh a banned account', async () => {
|
|
618
|
-
// Arrange
|
|
619
|
-
const storedToken = {
|
|
620
|
-
...testRefreshToken,
|
|
621
|
-
sessionId: testSession.id,
|
|
622
|
-
expiresAt: new Date(Date.now() + 24 * 60 * 60 * 1000),
|
|
623
|
-
};
|
|
624
|
-
vi.mocked(authRepo.findRefreshToken).mockResolvedValue(storedToken);
|
|
625
|
-
vi.mocked(authRepo.findUserById).mockResolvedValue(testUsers.inactiveUser);
|
|
626
|
-
|
|
627
|
-
// Act & Assert
|
|
628
|
-
await expect(authService.refresh(validRefreshToken)).rejects.toThrow(ForbiddenError);
|
|
629
|
-
await expect(authService.refresh(validRefreshToken)).rejects.toMatchObject({
|
|
630
|
-
code: 'ACCOUNT_DEACTIVATED',
|
|
631
|
-
});
|
|
498
|
+
const token = 'valid-refresh-token';
|
|
499
|
+
|
|
500
|
+
it.each([
|
|
501
|
+
['invalid', 'INVALID_REFRESH_TOKEN'],
|
|
502
|
+
['expired-token', 'REFRESH_TOKEN_EXPIRED'],
|
|
503
|
+
['expired-session', 'SESSION_EXPIRED'],
|
|
504
|
+
['rotated', 'REFRESH_TOKEN_ROTATED'],
|
|
505
|
+
] as const)('rejects a %s transaction outcome without issuing credentials', async (kind, code) => {
|
|
506
|
+
vi.mocked(authRepo.rotateRefreshToken).mockResolvedValue({ kind });
|
|
507
|
+
await expect(authService.refresh(token)).rejects.toMatchObject({ statusCode: 401, code });
|
|
632
508
|
expect(authLib.signAccessToken).not.toHaveBeenCalled();
|
|
633
509
|
});
|
|
634
510
|
|
|
635
|
-
it('
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
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
|
-
});
|
|
511
|
+
it('signs the access token from the committed session and role', async () => {
|
|
512
|
+
const claims = { userId: 'user', sessionId: 'session', role: 'USER' as const };
|
|
513
|
+
vi.mocked(authRepo.rotateRefreshToken).mockResolvedValue({ kind: 'issued', claims });
|
|
514
|
+
vi.mocked(authLib.generateRefreshToken).mockReturnValue('new-refresh');
|
|
515
|
+
vi.mocked(authLib.signAccessToken).mockReturnValue('new-access');
|
|
669
516
|
|
|
670
|
-
|
|
671
|
-
|
|
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.
|
|
675
|
-
const storedToken = {
|
|
676
|
-
...testRefreshToken,
|
|
677
|
-
sessionId: testSession.id,
|
|
678
|
-
expiresAt: new Date(Date.now() + 24 * 60 * 60 * 1000),
|
|
679
|
-
};
|
|
680
|
-
vi.mocked(authRepo.findRefreshToken).mockResolvedValue(storedToken);
|
|
681
|
-
vi.mocked(authRepo.findUserById).mockResolvedValue(testUsers.validUser);
|
|
682
|
-
vi.mocked(authLib.signAccessToken).mockReturnValue('access');
|
|
683
|
-
vi.mocked(authLib.generateRefreshToken).mockReturnValue('refresh');
|
|
684
|
-
vi.mocked(authLib.getRefreshTokenExpiresAt).mockReturnValue(new Date());
|
|
685
|
-
vi.mocked(authRepo.rotateRefreshToken).mockResolvedValue(false); // the parallel request rotated it first
|
|
686
|
-
|
|
687
|
-
await expect(authService.refresh(validRefreshToken)).rejects.toMatchObject({
|
|
688
|
-
statusCode: 401,
|
|
689
|
-
code: 'REFRESH_TOKEN_ROTATED',
|
|
517
|
+
await expect(authService.refresh(token)).resolves.toEqual({
|
|
518
|
+
accessToken: 'new-access', refreshToken: 'new-refresh',
|
|
690
519
|
});
|
|
691
|
-
expect(
|
|
692
|
-
expect(
|
|
693
|
-
});
|
|
694
|
-
|
|
695
|
-
it('should NOT revoke the token family on a successful rotation', async () => {
|
|
696
|
-
// Companion to the race test: nothing is revoked on a normal rotation either.
|
|
697
|
-
const storedToken = {
|
|
698
|
-
...testRefreshToken,
|
|
699
|
-
sessionId: testSession.id,
|
|
700
|
-
expiresAt: new Date(Date.now() + 24 * 60 * 60 * 1000),
|
|
701
|
-
};
|
|
702
|
-
vi.mocked(authRepo.findRefreshToken).mockResolvedValue(storedToken);
|
|
703
|
-
vi.mocked(authRepo.findUserById).mockResolvedValue(testUsers.validUser);
|
|
704
|
-
vi.mocked(authLib.signAccessToken).mockReturnValue('access');
|
|
705
|
-
vi.mocked(authLib.generateRefreshToken).mockReturnValue('refresh');
|
|
706
|
-
vi.mocked(authLib.getRefreshTokenExpiresAt).mockReturnValue(new Date());
|
|
707
|
-
vi.mocked(authRepo.rotateRefreshToken).mockResolvedValue(true);
|
|
708
|
-
|
|
709
|
-
// Act
|
|
710
|
-
await authService.refresh(validRefreshToken);
|
|
711
|
-
|
|
712
|
-
// Assert
|
|
713
|
-
expect(authRepo.deleteRefreshTokensByUserId).not.toHaveBeenCalled();
|
|
714
|
-
expect(sessionRepository.deleteAllUserSessions).not.toHaveBeenCalled();
|
|
520
|
+
expect(authLib.signAccessToken).toHaveBeenCalledWith(claims);
|
|
521
|
+
expect(mockRedis.set).not.toHaveBeenCalled();
|
|
715
522
|
});
|
|
716
523
|
});
|
|
717
524
|
|
|
718
525
|
describe('logout', () => {
|
|
719
|
-
it('
|
|
720
|
-
|
|
721
|
-
|
|
722
|
-
|
|
723
|
-
...testRefreshToken,
|
|
724
|
-
token: refreshToken,
|
|
725
|
-
sessionId: 'session-1',
|
|
726
|
-
};
|
|
727
|
-
|
|
728
|
-
vi.mocked(authRepo.findRefreshToken).mockResolvedValue(storedToken);
|
|
729
|
-
vi.mocked(authRepo.deleteRefreshToken).mockResolvedValue(undefined);
|
|
730
|
-
vi.mocked(sessionRepository.deleteSession).mockResolvedValue(undefined as never);
|
|
731
|
-
|
|
732
|
-
// Act
|
|
733
|
-
await authService.logout(refreshToken);
|
|
734
|
-
|
|
735
|
-
// Assert
|
|
736
|
-
expect(authRepo.findRefreshToken).toHaveBeenCalledWith(refreshToken);
|
|
737
|
-
expect(authRepo.deleteRefreshToken).toHaveBeenCalledWith(refreshToken);
|
|
738
|
-
expect(sessionRepository.deleteSession).toHaveBeenCalledWith('session-1');
|
|
526
|
+
it('passes a verified access session and lets the repository revoke it atomically', async () => {
|
|
527
|
+
const session = { userId: 'user', sessionId: 'session' };
|
|
528
|
+
await authService.logout('refresh', session);
|
|
529
|
+
expect(authRepo.revokeSession).toHaveBeenCalledWith('refresh', session);
|
|
739
530
|
});
|
|
740
531
|
|
|
741
|
-
it('
|
|
742
|
-
|
|
743
|
-
|
|
744
|
-
vi.mocked(authRepo.findRefreshToken).mockResolvedValue({
|
|
745
|
-
...testRefreshToken,
|
|
746
|
-
token: refreshToken,
|
|
747
|
-
});
|
|
748
|
-
vi.mocked(authRepo.deleteRefreshToken).mockResolvedValue(undefined);
|
|
749
|
-
|
|
750
|
-
// Act
|
|
751
|
-
await authService.logout(refreshToken);
|
|
752
|
-
|
|
753
|
-
// Assert
|
|
754
|
-
expect(authRepo.deleteRefreshToken).toHaveBeenCalledWith(refreshToken);
|
|
755
|
-
expect(sessionRepository.deleteSession).not.toHaveBeenCalled();
|
|
756
|
-
});
|
|
757
|
-
|
|
758
|
-
it('should propagate unexpected repository errors', async () => {
|
|
759
|
-
// "Token already deleted" is handled gracefully inside the repo (P2025);
|
|
760
|
-
// anything else is a real failure and must reach the global error handler.
|
|
761
|
-
const refreshToken = 'valid-refresh-token';
|
|
762
|
-
vi.mocked(authRepo.findRefreshToken).mockRejectedValue(new Error('DB error'));
|
|
763
|
-
|
|
764
|
-
// Act & Assert
|
|
765
|
-
await expect(authService.logout(refreshToken)).rejects.toThrow('DB error');
|
|
532
|
+
it('propagates database failures so a failed logout cannot report success', async () => {
|
|
533
|
+
vi.mocked(authRepo.revokeSession).mockRejectedValueOnce(new Error('DB error'));
|
|
534
|
+
await expect(authService.logout('refresh')).rejects.toThrow('DB error');
|
|
766
535
|
});
|
|
767
536
|
});
|
|
768
537
|
|
|
@@ -785,7 +554,7 @@ describe('Auth Service', () => {
|
|
|
785
554
|
statusCode: 503,
|
|
786
555
|
code: 'SERVICE_UNAVAILABLE',
|
|
787
556
|
});
|
|
788
|
-
expect(mockRedis.
|
|
557
|
+
expect(mockRedis.get).not.toHaveBeenCalled();
|
|
789
558
|
});
|
|
790
559
|
|
|
791
560
|
it('forgotPassword still answers normally while Redis is connected (unknown email: no error)', async () => {
|
|
@@ -795,36 +564,30 @@ describe('Auth Service', () => {
|
|
|
795
564
|
});
|
|
796
565
|
|
|
797
566
|
describe('resetPassword', () => {
|
|
798
|
-
it('
|
|
799
|
-
mockRedis.
|
|
567
|
+
it('commits recovery against the password observed before token consumption', async () => {
|
|
568
|
+
mockRedis.get.mockResolvedValue(testUsers.validUser.id);
|
|
569
|
+
mockRedis.eval.mockResolvedValue(1);
|
|
800
570
|
vi.mocked(authRepo.findUserById).mockResolvedValue(testUsers.validUser);
|
|
801
571
|
vi.mocked(hashPassword).mockResolvedValue('new-hash');
|
|
572
|
+
vi.mocked(authRepo.commitPasswordRecovery).mockResolvedValue(true);
|
|
802
573
|
|
|
803
574
|
await authService.resetPassword('reset-token', 'New-Passw0rd-123!');
|
|
804
575
|
|
|
805
|
-
expect(
|
|
806
|
-
|
|
807
|
-
|
|
808
|
-
expect(mockRedis.del).
|
|
809
|
-
expect(sessionRepository.deleteAllUserSessions).toHaveBeenCalledWith(testUsers.validUser.id);
|
|
810
|
-
expect(authRepo.deleteRefreshTokensByUserId).toHaveBeenCalledWith(testUsers.validUser.id);
|
|
576
|
+
expect(authRepo.commitPasswordRecovery).toHaveBeenCalledWith(
|
|
577
|
+
testUsers.validUser.id, testUsers.validUser.password, 'new-hash',
|
|
578
|
+
);
|
|
579
|
+
expect(mockRedis.del).not.toHaveBeenCalled();
|
|
811
580
|
});
|
|
812
581
|
|
|
813
|
-
it('the
|
|
814
|
-
|
|
815
|
-
mockRedis.
|
|
582
|
+
it('keeps the password unchanged when the token store refuses consumption', async () => {
|
|
583
|
+
mockRedis.get.mockResolvedValue(testUsers.validUser.id);
|
|
584
|
+
mockRedis.eval.mockResolvedValue(0);
|
|
816
585
|
vi.mocked(authRepo.findUserById).mockResolvedValue(testUsers.validUser);
|
|
817
|
-
vi.mocked(hashPassword).mockResolvedValue('new-hash');
|
|
818
586
|
|
|
819
|
-
|
|
820
|
-
|
|
821
|
-
|
|
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);
|
|
587
|
+
await expect(authService.resetPassword('reset-token', 'New-Passw0rd-123!')).rejects.toMatchObject({
|
|
588
|
+
statusCode: 400, code: 'INVALID_RESET_TOKEN',
|
|
589
|
+
});
|
|
590
|
+
expect(authRepo.commitPasswordRecovery).not.toHaveBeenCalled();
|
|
828
591
|
});
|
|
829
592
|
});
|
|
830
593
|
|