@nauth-toolkit/core 0.1.0 → 0.1.3
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/LICENSE +90 -0
- package/README.md +30 -0
- package/package.json +7 -2
- package/jest.config.js +0 -15
- package/jest.setup.ts +0 -6
- package/src/adapters/database-columns.ts +0 -165
- package/src/adapters/express.adapter.ts +0 -385
- package/src/adapters/fastify.adapter.ts +0 -416
- package/src/adapters/index.ts +0 -16
- package/src/adapters/storage.factory.ts +0 -143
- package/src/bootstrap.ts +0 -374
- package/src/dto/auth-challenge.dto.ts +0 -231
- package/src/dto/auth-response.dto.ts +0 -253
- package/src/dto/challenge-response.dto.ts +0 -234
- package/src/dto/change-password-request.dto.ts +0 -50
- package/src/dto/change-password-response.dto.ts +0 -29
- package/src/dto/change-password.dto.ts +0 -57
- package/src/dto/error-response.dto.ts +0 -136
- package/src/dto/get-available-methods.dto.ts +0 -55
- package/src/dto/get-challenge-data-response.dto.ts +0 -28
- package/src/dto/get-challenge-data.dto.ts +0 -69
- package/src/dto/get-client-info.dto.ts +0 -104
- package/src/dto/get-device-token-response.dto.ts +0 -25
- package/src/dto/get-events-by-type.dto.ts +0 -76
- package/src/dto/get-ip-address-response.dto.ts +0 -24
- package/src/dto/get-mfa-status.dto.ts +0 -94
- package/src/dto/get-risk-assessment-history.dto.ts +0 -39
- package/src/dto/get-session-id-response.dto.ts +0 -25
- package/src/dto/get-setup-data-response.dto.ts +0 -31
- package/src/dto/get-setup-data.dto.ts +0 -75
- package/src/dto/get-suspicious-activity.dto.ts +0 -42
- package/src/dto/get-user-agent-response.dto.ts +0 -23
- package/src/dto/get-user-auth-history.dto.ts +0 -95
- package/src/dto/get-user-by-email.dto.ts +0 -61
- package/src/dto/get-user-by-id.dto.ts +0 -46
- package/src/dto/get-user-devices.dto.ts +0 -53
- package/src/dto/get-user-response.dto.ts +0 -17
- package/src/dto/has-provider.dto.ts +0 -56
- package/src/dto/index.ts +0 -57
- package/src/dto/is-trusted-device-response.dto.ts +0 -34
- package/src/dto/list-providers-response.dto.ts +0 -23
- package/src/dto/login.dto.ts +0 -95
- package/src/dto/logout-all-response.dto.ts +0 -24
- package/src/dto/logout-all.dto.ts +0 -65
- package/src/dto/logout-response.dto.ts +0 -25
- package/src/dto/logout.dto.ts +0 -64
- package/src/dto/refresh-token.dto.ts +0 -36
- package/src/dto/remove-devices.dto.ts +0 -85
- package/src/dto/resend-code-response.dto.ts +0 -32
- package/src/dto/resend-code.dto.ts +0 -51
- package/src/dto/reset-password.dto.ts +0 -115
- package/src/dto/respond-challenge.dto.ts +0 -272
- package/src/dto/set-mfa-exemption.dto.ts +0 -112
- package/src/dto/set-must-change-password-response.dto.ts +0 -27
- package/src/dto/set-must-change-password.dto.ts +0 -46
- package/src/dto/set-preferred-method.dto.ts +0 -80
- package/src/dto/setup-mfa.dto.ts +0 -98
- package/src/dto/signup.dto.ts +0 -174
- package/src/dto/social-auth.dto.ts +0 -422
- package/src/dto/trust-device-response.dto.ts +0 -30
- package/src/dto/trust-device.dto.ts +0 -9
- package/src/dto/update-user-attributes-request.dto.ts +0 -51
- package/src/dto/user-response.dto.ts +0 -138
- package/src/dto/user-update.dto.ts +0 -222
- package/src/dto/verify-email.dto.ts +0 -313
- package/src/dto/verify-mfa-code.dto.ts +0 -103
- package/src/dto/verify-phone-by-sub.dto.ts +0 -78
- package/src/dto/verify-phone.dto.ts +0 -245
- package/src/entities/auth-audit.entity.ts +0 -232
- package/src/entities/challenge-session.entity.ts +0 -116
- package/src/entities/index.ts +0 -29
- package/src/entities/login-attempt.entity.ts +0 -64
- package/src/entities/mfa-device.entity.ts +0 -151
- package/src/entities/rate-limit.entity.ts +0 -44
- package/src/entities/session.entity.ts +0 -180
- package/src/entities/social-account.entity.ts +0 -96
- package/src/entities/storage-lock.entity.ts +0 -39
- package/src/entities/trusted-device.entity.ts +0 -112
- package/src/entities/user.entity.ts +0 -243
- package/src/entities/verification-token.entity.ts +0 -141
- package/src/enums/auth-audit-event-type.enum.ts +0 -360
- package/src/enums/error-codes.enum.ts +0 -420
- package/src/enums/mfa-method.enum.ts +0 -97
- package/src/enums/risk-factor.enum.ts +0 -111
- package/src/exceptions/nauth.exception.ts +0 -231
- package/src/handlers/auth.handler.ts +0 -260
- package/src/handlers/client-info.handler.ts +0 -101
- package/src/handlers/csrf.handler.ts +0 -156
- package/src/handlers/token-delivery.handler.ts +0 -118
- package/src/index.ts +0 -118
- package/src/interfaces/client-info.interface.ts +0 -85
- package/src/interfaces/config.interface.ts +0 -2135
- package/src/interfaces/entities.interface.ts +0 -226
- package/src/interfaces/index.ts +0 -15
- package/src/interfaces/logger.interface.ts +0 -283
- package/src/interfaces/mfa-provider.interface.ts +0 -154
- package/src/interfaces/oauth.interface.ts +0 -148
- package/src/interfaces/provider.interface.ts +0 -47
- package/src/interfaces/social-auth-provider.interface.ts +0 -131
- package/src/interfaces/storage-adapter.interface.ts +0 -82
- package/src/interfaces/template.interface.ts +0 -510
- package/src/interfaces/token-verifier.interface.ts +0 -110
- package/src/internal.ts +0 -178
- package/src/platform/interfaces.ts +0 -299
- package/src/schemas/auth-config.schema.ts +0 -646
- package/src/services/adaptive-mfa-decision.service.spec.ts +0 -1058
- package/src/services/adaptive-mfa-decision.service.ts +0 -457
- package/src/services/auth-audit.service.spec.ts +0 -675
- package/src/services/auth-audit.service.ts +0 -558
- package/src/services/auth-challenge-helper.service.spec.ts +0 -3227
- package/src/services/auth-challenge-helper.service.ts +0 -825
- package/src/services/auth-flow-context-builder.service.ts +0 -520
- package/src/services/auth-flow-rules.ts +0 -202
- package/src/services/auth-flow-state-definitions.ts +0 -190
- package/src/services/auth-flow-state-machine.service.ts +0 -207
- package/src/services/auth-flow-state-machine.types.ts +0 -316
- package/src/services/auth.service.spec.ts +0 -4195
- package/src/services/auth.service.ts +0 -3727
- package/src/services/challenge.service.spec.ts +0 -1363
- package/src/services/challenge.service.ts +0 -696
- package/src/services/client-info.service.spec.ts +0 -572
- package/src/services/client-info.service.ts +0 -374
- package/src/services/csrf.service.ts +0 -54
- package/src/services/email-verification.service.spec.ts +0 -1229
- package/src/services/email-verification.service.ts +0 -578
- package/src/services/geo-location.service.spec.ts +0 -603
- package/src/services/geo-location.service.ts +0 -599
- package/src/services/index.ts +0 -13
- package/src/services/jwt.service.spec.ts +0 -882
- package/src/services/jwt.service.ts +0 -621
- package/src/services/mfa-base.service.spec.ts +0 -246
- package/src/services/mfa-base.service.ts +0 -611
- package/src/services/mfa.service.spec.ts +0 -693
- package/src/services/mfa.service.ts +0 -960
- package/src/services/password.service.spec.ts +0 -166
- package/src/services/password.service.ts +0 -309
- package/src/services/phone-verification.service.spec.ts +0 -1120
- package/src/services/phone-verification.service.ts +0 -751
- package/src/services/risk-detection.service.spec.ts +0 -1292
- package/src/services/risk-detection.service.ts +0 -1012
- package/src/services/risk-scoring.service.spec.ts +0 -204
- package/src/services/risk-scoring.service.ts +0 -131
- package/src/services/session.service.spec.ts +0 -1293
- package/src/services/session.service.ts +0 -803
- package/src/services/social-account.service.spec.ts +0 -725
- package/src/services/social-auth-base.service.spec.ts +0 -418
- package/src/services/social-auth-base.service.ts +0 -581
- package/src/services/social-auth.service.spec.ts +0 -238
- package/src/services/social-auth.service.ts +0 -436
- package/src/services/social-provider-registry.service.spec.ts +0 -238
- package/src/services/social-provider-registry.service.ts +0 -122
- package/src/services/trusted-device.service.spec.ts +0 -505
- package/src/services/trusted-device.service.ts +0 -339
- package/src/storage/account-lockout-storage.service.spec.ts +0 -310
- package/src/storage/account-lockout-storage.service.ts +0 -89
- package/src/storage/index.ts +0 -3
- package/src/storage/memory-storage.adapter.ts +0 -443
- package/src/storage/rate-limit-storage.service.spec.ts +0 -247
- package/src/storage/rate-limit-storage.service.ts +0 -38
- package/src/templates/html-template.engine.spec.ts +0 -161
- package/src/templates/html-template.engine.ts +0 -688
- package/src/templates/index.ts +0 -7
- package/src/utils/common-passwords.spec.ts +0 -230
- package/src/utils/common-passwords.ts +0 -170
- package/src/utils/context-storage.ts +0 -188
- package/src/utils/cookie-names.util.ts +0 -67
- package/src/utils/cookies.util.ts +0 -94
- package/src/utils/index.ts +0 -12
- package/src/utils/ip-extractor.spec.ts +0 -330
- package/src/utils/ip-extractor.ts +0 -220
- package/src/utils/nauth-logger.spec.ts +0 -388
- package/src/utils/nauth-logger.ts +0 -215
- package/src/utils/pii-redactor.spec.ts +0 -130
- package/src/utils/pii-redactor.ts +0 -288
- package/src/utils/setup/get-repositories.ts +0 -140
- package/src/utils/setup/init-services.ts +0 -422
- package/src/utils/setup/init-social.ts +0 -189
- package/src/utils/setup/init-storage.ts +0 -94
- package/src/utils/setup/register-mfa.ts +0 -165
- package/src/utils/setup/run-nauth-migrations.ts +0 -61
- package/src/utils/token-delivery-policy.ts +0 -38
- package/src/validators/template.validator.ts +0 -219
- package/tsconfig.json +0 -37
- package/tsconfig.lint.json +0 -6
|
@@ -1,1229 +0,0 @@
|
|
|
1
|
-
import { Repository } from 'typeorm';
|
|
2
|
-
import { EmailVerificationService } from './email-verification.service';
|
|
3
|
-
import { NAuthException } from '../exceptions/nauth.exception';
|
|
4
|
-
import { ClientInfoService } from './client-info.service';
|
|
5
|
-
import { EmailProvider } from '../interfaces/provider.interface';
|
|
6
|
-
import { StorageAdapter } from '../interfaces/storage-adapter.interface';
|
|
7
|
-
import { NAuthConfig } from '../interfaces/config.interface';
|
|
8
|
-
import { NAuthLogger } from '../utils/nauth-logger';
|
|
9
|
-
import { AuthAuditService } from './auth-audit.service';
|
|
10
|
-
import { BaseVerificationToken, BaseUser } from '../entities';
|
|
11
|
-
import { IUser, IVerificationToken } from '../interfaces/entities.interface';
|
|
12
|
-
import { AuthErrorCode } from '../enums/error-codes.enum';
|
|
13
|
-
import { JwtService } from './jwt.service';
|
|
14
|
-
import { SessionService } from './session.service';
|
|
15
|
-
import {
|
|
16
|
-
SendVerificationEmailDTO,
|
|
17
|
-
VerifyEmailWithCodeDTO,
|
|
18
|
-
VerifyEmailWithTokenDTO,
|
|
19
|
-
ResendVerificationEmailDTO,
|
|
20
|
-
} from '../dto/verify-email.dto';
|
|
21
|
-
|
|
22
|
-
// Helper to create DTOs from plain objects
|
|
23
|
-
function createSendVerificationEmailDto(data: Partial<SendVerificationEmailDTO>): SendVerificationEmailDTO {
|
|
24
|
-
return Object.assign(new SendVerificationEmailDTO(), data);
|
|
25
|
-
}
|
|
26
|
-
|
|
27
|
-
function createVerifyEmailWithCodeDto(data: Partial<VerifyEmailWithCodeDTO>): VerifyEmailWithCodeDTO {
|
|
28
|
-
return Object.assign(new VerifyEmailWithCodeDTO(), data);
|
|
29
|
-
}
|
|
30
|
-
|
|
31
|
-
function createVerifyEmailWithTokenDto(data: Partial<VerifyEmailWithTokenDTO>): VerifyEmailWithTokenDTO {
|
|
32
|
-
return Object.assign(new VerifyEmailWithTokenDTO(), data);
|
|
33
|
-
}
|
|
34
|
-
|
|
35
|
-
function createResendVerificationEmailDto(data: Partial<ResendVerificationEmailDTO>): ResendVerificationEmailDTO {
|
|
36
|
-
return Object.assign(new ResendVerificationEmailDTO(), data);
|
|
37
|
-
}
|
|
38
|
-
|
|
39
|
-
/**
|
|
40
|
-
* Email Verification Service Unit Tests
|
|
41
|
-
*
|
|
42
|
-
* Platform-agnostic: Uses direct instantiation, no NestJS dependencies.
|
|
43
|
-
*
|
|
44
|
-
* Covers:
|
|
45
|
-
* - Send verification email with rate limiting
|
|
46
|
-
* - Code-based verification with attempts tracking
|
|
47
|
-
* - Link-based verification (token)
|
|
48
|
-
* - Resend verification email with cooldown
|
|
49
|
-
* - Rate limiting per user and per IP
|
|
50
|
-
* - Error handling for all dependencies
|
|
51
|
-
* - Storage adapter failures
|
|
52
|
-
* - Email provider errors
|
|
53
|
-
*/
|
|
54
|
-
describe('EmailVerificationService', () => {
|
|
55
|
-
let service: EmailVerificationService;
|
|
56
|
-
let mockVerificationTokenRepository: jest.Mocked<Repository<BaseVerificationToken>>;
|
|
57
|
-
let mockUserRepository: jest.Mocked<Repository<BaseUser>>;
|
|
58
|
-
let mockEmailProvider: jest.Mocked<EmailProvider>;
|
|
59
|
-
let mockStorageAdapter: jest.Mocked<StorageAdapter>;
|
|
60
|
-
let mockJwtService: jest.Mocked<JwtService>;
|
|
61
|
-
let mockSessionService: jest.Mocked<SessionService>;
|
|
62
|
-
let mockClientInfoService: jest.Mocked<ClientInfoService>;
|
|
63
|
-
let mockLogger: jest.Mocked<NAuthLogger>;
|
|
64
|
-
let mockAuditService: jest.Mocked<AuthAuditService>;
|
|
65
|
-
let mockConfig: NAuthConfig;
|
|
66
|
-
|
|
67
|
-
const mockUser: IUser = {
|
|
68
|
-
id: 123,
|
|
69
|
-
sub: 'user-sub-123',
|
|
70
|
-
email: 'test@example.com',
|
|
71
|
-
username: 'testuser',
|
|
72
|
-
phone: null,
|
|
73
|
-
firstName: null,
|
|
74
|
-
lastName: null,
|
|
75
|
-
passwordHash: null,
|
|
76
|
-
passwordChangedAt: null,
|
|
77
|
-
passwordHistory: null,
|
|
78
|
-
isEmailVerified: false,
|
|
79
|
-
isPhoneVerified: false,
|
|
80
|
-
isActive: true,
|
|
81
|
-
mustChangePassword: false,
|
|
82
|
-
isLocked: false,
|
|
83
|
-
lockReason: null,
|
|
84
|
-
lockedAt: null,
|
|
85
|
-
lockedUntil: null,
|
|
86
|
-
failedLoginAttempts: 0,
|
|
87
|
-
lastFailedLoginAt: null,
|
|
88
|
-
lastLoginAt: null,
|
|
89
|
-
lastLoginIp: null,
|
|
90
|
-
hasSocialAuth: false,
|
|
91
|
-
socialProviders: null,
|
|
92
|
-
mfaEnabled: false,
|
|
93
|
-
mfaMethods: null,
|
|
94
|
-
preferredMfaMethod: null,
|
|
95
|
-
backupCodes: null,
|
|
96
|
-
metadata: null,
|
|
97
|
-
createdAt: new Date(),
|
|
98
|
-
updatedAt: new Date(),
|
|
99
|
-
deletedAt: null,
|
|
100
|
-
};
|
|
101
|
-
|
|
102
|
-
const mockVerificationToken: IVerificationToken = {
|
|
103
|
-
id: 456,
|
|
104
|
-
userId: 123,
|
|
105
|
-
challengeSessionId: null,
|
|
106
|
-
type: 'email',
|
|
107
|
-
token: 'hashed-token-abc123',
|
|
108
|
-
code: '123456',
|
|
109
|
-
expiresAt: new Date(Date.now() + 3600000), // 1 hour from now
|
|
110
|
-
attempts: 0,
|
|
111
|
-
usedAt: null,
|
|
112
|
-
ipAddress: '127.0.0.1',
|
|
113
|
-
userAgent: 'test-agent',
|
|
114
|
-
createdAt: new Date(),
|
|
115
|
-
isExpired: jest.fn().mockReturnValue(false),
|
|
116
|
-
maxAttemptsExceeded: jest.fn().mockReturnValue(false),
|
|
117
|
-
};
|
|
118
|
-
|
|
119
|
-
beforeEach(() => {
|
|
120
|
-
mockVerificationTokenRepository = {
|
|
121
|
-
create: jest.fn(),
|
|
122
|
-
save: jest.fn(),
|
|
123
|
-
findOne: jest.fn(),
|
|
124
|
-
update: jest.fn().mockResolvedValue({ affected: 0 } as any),
|
|
125
|
-
count: jest.fn(),
|
|
126
|
-
} as any;
|
|
127
|
-
|
|
128
|
-
mockUserRepository = {
|
|
129
|
-
findOne: jest.fn(),
|
|
130
|
-
save: jest.fn(),
|
|
131
|
-
update: jest.fn().mockResolvedValue({ affected: 1 } as any),
|
|
132
|
-
} as any;
|
|
133
|
-
|
|
134
|
-
mockEmailProvider = {
|
|
135
|
-
sendVerificationEmail: jest.fn().mockResolvedValue(undefined),
|
|
136
|
-
sendPasswordResetEmail: jest.fn(),
|
|
137
|
-
sendWelcomeEmail: jest.fn(),
|
|
138
|
-
} as any;
|
|
139
|
-
|
|
140
|
-
mockStorageAdapter = {
|
|
141
|
-
get: jest.fn(),
|
|
142
|
-
set: jest.fn(),
|
|
143
|
-
incr: jest.fn().mockResolvedValue(1),
|
|
144
|
-
expire: jest.fn().mockResolvedValue(undefined),
|
|
145
|
-
ttl: jest.fn().mockResolvedValue(3600),
|
|
146
|
-
del: jest.fn().mockResolvedValue(undefined),
|
|
147
|
-
exists: jest.fn(),
|
|
148
|
-
} as any;
|
|
149
|
-
|
|
150
|
-
mockClientInfoService = {
|
|
151
|
-
get: jest.fn().mockReturnValue({
|
|
152
|
-
ipAddress: '127.0.0.1',
|
|
153
|
-
userAgent: 'test-agent',
|
|
154
|
-
}),
|
|
155
|
-
} as any;
|
|
156
|
-
|
|
157
|
-
mockJwtService = {
|
|
158
|
-
generateTokenPair: jest.fn(),
|
|
159
|
-
hashToken: jest.fn(),
|
|
160
|
-
validateAccessToken: jest.fn(),
|
|
161
|
-
validateRefreshToken: jest.fn(),
|
|
162
|
-
} as any;
|
|
163
|
-
|
|
164
|
-
mockSessionService = {
|
|
165
|
-
createSession: jest.fn(),
|
|
166
|
-
findById: jest.fn(),
|
|
167
|
-
} as any;
|
|
168
|
-
|
|
169
|
-
mockLogger = {
|
|
170
|
-
log: jest.fn(),
|
|
171
|
-
error: jest.fn(),
|
|
172
|
-
warn: jest.fn(),
|
|
173
|
-
debug: jest.fn(),
|
|
174
|
-
verbose: jest.fn(),
|
|
175
|
-
} as any;
|
|
176
|
-
|
|
177
|
-
mockAuditService = {
|
|
178
|
-
recordEvent: jest.fn().mockResolvedValue(null),
|
|
179
|
-
} as any;
|
|
180
|
-
|
|
181
|
-
mockConfig = {
|
|
182
|
-
jwt: {
|
|
183
|
-
accessToken: { secret: 'test-secret', expiresIn: '15m' },
|
|
184
|
-
refreshToken: { secret: 'test-refresh-secret', expiresIn: '7d' },
|
|
185
|
-
},
|
|
186
|
-
signup: {
|
|
187
|
-
emailVerification: {
|
|
188
|
-
expiresIn: 3600,
|
|
189
|
-
resendDelay: 60,
|
|
190
|
-
rateLimitMax: 3,
|
|
191
|
-
rateLimitWindow: 3600,
|
|
192
|
-
},
|
|
193
|
-
},
|
|
194
|
-
};
|
|
195
|
-
|
|
196
|
-
// Instantiate service directly
|
|
197
|
-
service = new EmailVerificationService(
|
|
198
|
-
mockVerificationTokenRepository,
|
|
199
|
-
mockUserRepository,
|
|
200
|
-
mockEmailProvider,
|
|
201
|
-
mockStorageAdapter,
|
|
202
|
-
mockConfig,
|
|
203
|
-
mockClientInfoService,
|
|
204
|
-
mockLogger,
|
|
205
|
-
mockAuditService,
|
|
206
|
-
);
|
|
207
|
-
});
|
|
208
|
-
|
|
209
|
-
afterEach(() => {
|
|
210
|
-
jest.clearAllMocks();
|
|
211
|
-
});
|
|
212
|
-
|
|
213
|
-
// ============================================================================
|
|
214
|
-
// Service Initialization
|
|
215
|
-
// ============================================================================
|
|
216
|
-
|
|
217
|
-
it('should be defined', () => {
|
|
218
|
-
expect(service).toBeDefined();
|
|
219
|
-
});
|
|
220
|
-
|
|
221
|
-
// ============================================================================
|
|
222
|
-
// sendVerificationEmail
|
|
223
|
-
// ============================================================================
|
|
224
|
-
|
|
225
|
-
describe('sendVerificationEmail', () => {
|
|
226
|
-
it('should send verification email successfully', async () => {
|
|
227
|
-
mockStorageAdapter.incr.mockResolvedValue(1);
|
|
228
|
-
mockStorageAdapter.ttl.mockResolvedValue(3600);
|
|
229
|
-
mockUserRepository.findOne.mockResolvedValue(mockUser as any);
|
|
230
|
-
mockVerificationTokenRepository.findOne.mockResolvedValue(null); // No last token
|
|
231
|
-
mockVerificationTokenRepository.create.mockReturnValue(mockVerificationToken as any);
|
|
232
|
-
mockVerificationTokenRepository.save.mockResolvedValue(mockVerificationToken as any);
|
|
233
|
-
|
|
234
|
-
const result = await service.sendVerificationEmail('user-sub-123', 'https://example.com');
|
|
235
|
-
|
|
236
|
-
expect(mockStorageAdapter.incr).toHaveBeenCalled();
|
|
237
|
-
expect(mockUserRepository.findOne).toHaveBeenCalledWith({ where: { sub: 'user-sub-123' } as any });
|
|
238
|
-
expect(mockVerificationTokenRepository.save).toHaveBeenCalled();
|
|
239
|
-
expect(mockEmailProvider.sendVerificationEmail).toHaveBeenCalled();
|
|
240
|
-
const callArgs = mockEmailProvider.sendVerificationEmail.mock.calls[0];
|
|
241
|
-
expect(callArgs[0]).toBe('test@example.com');
|
|
242
|
-
expect(typeof callArgs[1]).toBe('string'); // 6-digit code
|
|
243
|
-
expect(callArgs[2]).toContain('https://example.com/verify-email?token='); // token in URL
|
|
244
|
-
expect(mockAuditService.recordEvent).toHaveBeenCalled();
|
|
245
|
-
expect(result).toBe(456);
|
|
246
|
-
});
|
|
247
|
-
|
|
248
|
-
it('should use default baseUrl if not provided', async () => {
|
|
249
|
-
mockStorageAdapter.incr.mockResolvedValue(1);
|
|
250
|
-
mockStorageAdapter.ttl.mockResolvedValue(3600);
|
|
251
|
-
mockUserRepository.findOne.mockResolvedValue(mockUser as any);
|
|
252
|
-
mockVerificationTokenRepository.findOne.mockResolvedValue(null);
|
|
253
|
-
mockVerificationTokenRepository.create.mockReturnValue(mockVerificationToken as any);
|
|
254
|
-
mockVerificationTokenRepository.save.mockResolvedValue(mockVerificationToken as any);
|
|
255
|
-
|
|
256
|
-
await service.sendVerificationEmail('user-sub-123');
|
|
257
|
-
|
|
258
|
-
expect(mockEmailProvider.sendVerificationEmail).toHaveBeenCalledWith(
|
|
259
|
-
'test@example.com',
|
|
260
|
-
(expect as any).any(String),
|
|
261
|
-
(expect as any).stringContaining('http://localhost:3000/verify-email?token='),
|
|
262
|
-
);
|
|
263
|
-
});
|
|
264
|
-
|
|
265
|
-
it('should throw NAuthException if user not found', async () => {
|
|
266
|
-
mockStorageAdapter.incr.mockResolvedValue(1);
|
|
267
|
-
mockStorageAdapter.ttl.mockResolvedValue(3600);
|
|
268
|
-
mockUserRepository.findOne.mockResolvedValue(null);
|
|
269
|
-
|
|
270
|
-
try {
|
|
271
|
-
await service.sendVerificationEmail('invalid-sub');
|
|
272
|
-
fail('Should have thrown NAuthException');
|
|
273
|
-
} catch (error: any) {
|
|
274
|
-
expect(error).toBeInstanceOf(NAuthException);
|
|
275
|
-
expect(error.code).toBe(AuthErrorCode.NOT_FOUND);
|
|
276
|
-
}
|
|
277
|
-
});
|
|
278
|
-
|
|
279
|
-
it('should throw NAuthException if email already verified', async () => {
|
|
280
|
-
const verifiedUser = { ...mockUser, isEmailVerified: true };
|
|
281
|
-
mockStorageAdapter.incr.mockResolvedValue(1);
|
|
282
|
-
mockStorageAdapter.ttl.mockResolvedValue(3600);
|
|
283
|
-
mockUserRepository.findOne.mockResolvedValue(verifiedUser as any);
|
|
284
|
-
|
|
285
|
-
try {
|
|
286
|
-
await service.sendVerificationEmail('user-sub-123');
|
|
287
|
-
fail('Should have thrown NAuthException');
|
|
288
|
-
} catch (error: any) {
|
|
289
|
-
expect(error).toBeInstanceOf(NAuthException);
|
|
290
|
-
expect(error.code).toBe(AuthErrorCode.ALREADY_VERIFIED);
|
|
291
|
-
}
|
|
292
|
-
});
|
|
293
|
-
|
|
294
|
-
it('should enforce rate limit (too many emails)', async () => {
|
|
295
|
-
mockStorageAdapter.incr.mockResolvedValue(4); // Exceeds limit of 3
|
|
296
|
-
mockStorageAdapter.ttl.mockResolvedValue(3600);
|
|
297
|
-
|
|
298
|
-
try {
|
|
299
|
-
await service.sendVerificationEmail('user-sub-123');
|
|
300
|
-
fail('Should have thrown NAuthException');
|
|
301
|
-
} catch (error: any) {
|
|
302
|
-
expect(error).toBeInstanceOf(NAuthException);
|
|
303
|
-
expect(error.code).toBe(AuthErrorCode.RATE_LIMIT_EMAIL);
|
|
304
|
-
expect(mockUserRepository.findOne).not.toHaveBeenCalled();
|
|
305
|
-
}
|
|
306
|
-
});
|
|
307
|
-
|
|
308
|
-
it('should enforce resend delay', async () => {
|
|
309
|
-
const recentToken = {
|
|
310
|
-
...mockVerificationToken,
|
|
311
|
-
createdAt: new Date(Date.now() - 30 * 1000), // 30 seconds ago (less than 60s delay)
|
|
312
|
-
};
|
|
313
|
-
mockStorageAdapter.incr.mockResolvedValue(1);
|
|
314
|
-
mockStorageAdapter.ttl.mockResolvedValue(3600);
|
|
315
|
-
mockUserRepository.findOne.mockResolvedValue(mockUser as any);
|
|
316
|
-
mockVerificationTokenRepository.findOne.mockResolvedValue(recentToken as any);
|
|
317
|
-
|
|
318
|
-
try {
|
|
319
|
-
await service.sendVerificationEmail('user-sub-123');
|
|
320
|
-
fail('Should have thrown NAuthException');
|
|
321
|
-
} catch (error: any) {
|
|
322
|
-
expect(error).toBeInstanceOf(NAuthException);
|
|
323
|
-
expect(error.code).toBe(AuthErrorCode.RATE_LIMIT_RESEND);
|
|
324
|
-
}
|
|
325
|
-
});
|
|
326
|
-
|
|
327
|
-
it('should allow resend after delay period', async () => {
|
|
328
|
-
const oldToken = {
|
|
329
|
-
...mockVerificationToken,
|
|
330
|
-
createdAt: new Date(Date.now() - 70 * 1000), // 70 seconds ago (more than 60s delay)
|
|
331
|
-
};
|
|
332
|
-
mockStorageAdapter.incr.mockResolvedValue(1);
|
|
333
|
-
mockStorageAdapter.ttl.mockResolvedValue(3600);
|
|
334
|
-
mockUserRepository.findOne.mockResolvedValue(mockUser as any);
|
|
335
|
-
mockVerificationTokenRepository.findOne.mockResolvedValue(oldToken as any);
|
|
336
|
-
mockVerificationTokenRepository.create.mockReturnValue(mockVerificationToken as any);
|
|
337
|
-
mockVerificationTokenRepository.save.mockResolvedValue(mockVerificationToken as any);
|
|
338
|
-
|
|
339
|
-
await service.sendVerificationEmail('user-sub-123');
|
|
340
|
-
|
|
341
|
-
expect(mockEmailProvider.sendVerificationEmail).toHaveBeenCalled();
|
|
342
|
-
});
|
|
343
|
-
|
|
344
|
-
it('should invalidate existing unused tokens', async () => {
|
|
345
|
-
mockStorageAdapter.incr.mockResolvedValue(1);
|
|
346
|
-
mockStorageAdapter.ttl.mockResolvedValue(3600);
|
|
347
|
-
mockUserRepository.findOne.mockResolvedValue(mockUser as any);
|
|
348
|
-
mockVerificationTokenRepository.findOne.mockResolvedValue(null);
|
|
349
|
-
mockVerificationTokenRepository.create.mockReturnValue(mockVerificationToken as any);
|
|
350
|
-
mockVerificationTokenRepository.save.mockResolvedValue(mockVerificationToken as any);
|
|
351
|
-
|
|
352
|
-
await service.sendVerificationEmail('user-sub-123');
|
|
353
|
-
|
|
354
|
-
expect(mockVerificationTokenRepository.update).toHaveBeenCalledWith(
|
|
355
|
-
(expect as any).objectContaining({
|
|
356
|
-
userId: 123,
|
|
357
|
-
type: 'email',
|
|
358
|
-
}),
|
|
359
|
-
(expect as any).objectContaining({
|
|
360
|
-
usedAt: (expect as any).any(Date),
|
|
361
|
-
}),
|
|
362
|
-
);
|
|
363
|
-
});
|
|
364
|
-
|
|
365
|
-
it('should handle rate limit window reset when TTL > window', async () => {
|
|
366
|
-
mockStorageAdapter.ttl.mockResolvedValue(7200); // TTL longer than window (3600)
|
|
367
|
-
mockStorageAdapter.del.mockResolvedValue();
|
|
368
|
-
mockStorageAdapter.incr.mockResolvedValue(1);
|
|
369
|
-
mockUserRepository.findOne.mockResolvedValue(mockUser as any);
|
|
370
|
-
mockVerificationTokenRepository.findOne.mockResolvedValue(null);
|
|
371
|
-
mockVerificationTokenRepository.create.mockReturnValue(mockVerificationToken as any);
|
|
372
|
-
mockVerificationTokenRepository.save.mockResolvedValue(mockVerificationToken as any);
|
|
373
|
-
|
|
374
|
-
await service.sendVerificationEmail('user-sub-123');
|
|
375
|
-
|
|
376
|
-
expect(mockStorageAdapter.del).toHaveBeenCalledWith('email-verification:user-sub-123');
|
|
377
|
-
});
|
|
378
|
-
|
|
379
|
-
it('should handle storage adapter errors gracefully', async () => {
|
|
380
|
-
// TTL error should be handled gracefully - don't throw, just log
|
|
381
|
-
mockStorageAdapter.ttl.mockResolvedValue(-1); // Simulate error by returning -1 (key doesn't exist)
|
|
382
|
-
mockStorageAdapter.incr.mockResolvedValue(1);
|
|
383
|
-
mockUserRepository.findOne.mockResolvedValue(mockUser as any);
|
|
384
|
-
mockVerificationTokenRepository.findOne.mockResolvedValue(null);
|
|
385
|
-
mockVerificationTokenRepository.create.mockReturnValue(mockVerificationToken as any);
|
|
386
|
-
mockVerificationTokenRepository.save.mockResolvedValue(mockVerificationToken as any);
|
|
387
|
-
|
|
388
|
-
// Should still work, just log the error
|
|
389
|
-
await service.sendVerificationEmail('user-sub-123');
|
|
390
|
-
|
|
391
|
-
expect(mockEmailProvider.sendVerificationEmail).toHaveBeenCalled();
|
|
392
|
-
});
|
|
393
|
-
|
|
394
|
-
it('should handle email provider errors', async () => {
|
|
395
|
-
mockStorageAdapter.incr.mockResolvedValue(1);
|
|
396
|
-
mockStorageAdapter.ttl.mockResolvedValue(3600);
|
|
397
|
-
mockUserRepository.findOne.mockResolvedValue(mockUser as any);
|
|
398
|
-
mockVerificationTokenRepository.findOne.mockResolvedValue(null);
|
|
399
|
-
mockVerificationTokenRepository.create.mockReturnValue(mockVerificationToken as any);
|
|
400
|
-
mockVerificationTokenRepository.save.mockResolvedValue(mockVerificationToken as any);
|
|
401
|
-
mockEmailProvider.sendVerificationEmail.mockRejectedValue(new Error('Email service error'));
|
|
402
|
-
|
|
403
|
-
try {
|
|
404
|
-
await service.sendVerificationEmail('user-sub-123');
|
|
405
|
-
fail('Should have thrown error');
|
|
406
|
-
} catch (error: any) {
|
|
407
|
-
expect(error.message).toContain('Email service error');
|
|
408
|
-
}
|
|
409
|
-
});
|
|
410
|
-
|
|
411
|
-
it('should handle audit service errors gracefully', async () => {
|
|
412
|
-
mockStorageAdapter.incr.mockResolvedValue(1);
|
|
413
|
-
mockStorageAdapter.ttl.mockResolvedValue(3600);
|
|
414
|
-
mockUserRepository.findOne.mockResolvedValue(mockUser as any);
|
|
415
|
-
mockVerificationTokenRepository.findOne.mockResolvedValue(null);
|
|
416
|
-
mockVerificationTokenRepository.create.mockReturnValue(mockVerificationToken as any);
|
|
417
|
-
mockVerificationTokenRepository.save.mockResolvedValue(mockVerificationToken as any);
|
|
418
|
-
mockAuditService.recordEvent.mockRejectedValue(new Error('Audit error'));
|
|
419
|
-
|
|
420
|
-
await service.sendVerificationEmail('user-sub-123');
|
|
421
|
-
|
|
422
|
-
expect(mockLogger.error).toHaveBeenCalled();
|
|
423
|
-
expect(mockEmailProvider.sendVerificationEmail).toHaveBeenCalled(); // Should still send email
|
|
424
|
-
});
|
|
425
|
-
|
|
426
|
-
it('should use custom rate limit config', async () => {
|
|
427
|
-
mockConfig.signup!.emailVerification!.rateLimitMax = 5;
|
|
428
|
-
mockConfig.signup!.emailVerification!.rateLimitWindow = 1800;
|
|
429
|
-
service = new EmailVerificationService(
|
|
430
|
-
mockVerificationTokenRepository,
|
|
431
|
-
mockUserRepository,
|
|
432
|
-
mockEmailProvider,
|
|
433
|
-
mockStorageAdapter,
|
|
434
|
-
mockConfig,
|
|
435
|
-
mockClientInfoService,
|
|
436
|
-
mockLogger,
|
|
437
|
-
mockAuditService,
|
|
438
|
-
);
|
|
439
|
-
|
|
440
|
-
mockStorageAdapter.incr.mockResolvedValue(6); // Exceeds new limit of 5
|
|
441
|
-
mockStorageAdapter.ttl.mockResolvedValue(1800);
|
|
442
|
-
|
|
443
|
-
try {
|
|
444
|
-
await service.sendVerificationEmail('user-sub-123');
|
|
445
|
-
fail('Should have thrown NAuthException');
|
|
446
|
-
} catch (error: any) {
|
|
447
|
-
expect(error.code).toBe(AuthErrorCode.RATE_LIMIT_EMAIL);
|
|
448
|
-
}
|
|
449
|
-
});
|
|
450
|
-
|
|
451
|
-
it('should use custom resend delay config', async () => {
|
|
452
|
-
mockConfig.signup!.emailVerification!.resendDelay = 120; // 2 minutes
|
|
453
|
-
service = new EmailVerificationService(
|
|
454
|
-
mockVerificationTokenRepository,
|
|
455
|
-
mockUserRepository,
|
|
456
|
-
mockEmailProvider,
|
|
457
|
-
mockStorageAdapter,
|
|
458
|
-
mockConfig,
|
|
459
|
-
mockClientInfoService,
|
|
460
|
-
mockLogger,
|
|
461
|
-
mockAuditService,
|
|
462
|
-
);
|
|
463
|
-
|
|
464
|
-
const recentToken = {
|
|
465
|
-
...mockVerificationToken,
|
|
466
|
-
createdAt: new Date(Date.now() - 90 * 1000), // 90 seconds ago (less than 120s)
|
|
467
|
-
};
|
|
468
|
-
mockStorageAdapter.incr.mockResolvedValue(1);
|
|
469
|
-
mockStorageAdapter.ttl.mockResolvedValue(3600);
|
|
470
|
-
mockUserRepository.findOne.mockResolvedValue(mockUser as any);
|
|
471
|
-
mockVerificationTokenRepository.findOne.mockResolvedValue(recentToken as any);
|
|
472
|
-
|
|
473
|
-
try {
|
|
474
|
-
await service.sendVerificationEmail('user-sub-123');
|
|
475
|
-
fail('Should have thrown NAuthException');
|
|
476
|
-
} catch (error: any) {
|
|
477
|
-
expect(error.code).toBe(AuthErrorCode.RATE_LIMIT_RESEND);
|
|
478
|
-
}
|
|
479
|
-
});
|
|
480
|
-
});
|
|
481
|
-
|
|
482
|
-
// ============================================================================
|
|
483
|
-
// verifyEmailWithCode
|
|
484
|
-
// ============================================================================
|
|
485
|
-
|
|
486
|
-
describe('verifyEmailWithCode', () => {
|
|
487
|
-
it('should verify email with valid code', async () => {
|
|
488
|
-
mockUserRepository.findOne.mockResolvedValue(mockUser as any);
|
|
489
|
-
mockStorageAdapter.incr.mockResolvedValue(1);
|
|
490
|
-
mockStorageAdapter.expire.mockResolvedValue();
|
|
491
|
-
mockVerificationTokenRepository.findOne.mockResolvedValue(mockVerificationToken as any);
|
|
492
|
-
mockVerificationTokenRepository.save.mockResolvedValue(mockVerificationToken as any);
|
|
493
|
-
|
|
494
|
-
const result = await service.verifyEmailWithCode({
|
|
495
|
-
email: 'test@example.com',
|
|
496
|
-
code: '123456',
|
|
497
|
-
challengeSessionId: 1,
|
|
498
|
-
});
|
|
499
|
-
|
|
500
|
-
expect(result.message).toBe('Email verified successfully. Please log in to continue.');
|
|
501
|
-
expect(mockUserRepository.update).toHaveBeenCalledWith(123, {
|
|
502
|
-
isEmailVerified: true,
|
|
503
|
-
isActive: true,
|
|
504
|
-
});
|
|
505
|
-
expect(mockAuditService.recordEvent).toHaveBeenCalled();
|
|
506
|
-
});
|
|
507
|
-
|
|
508
|
-
it('should throw NAuthException if challengeSessionId is missing', async () => {
|
|
509
|
-
try {
|
|
510
|
-
await service.verifyEmailWithCode({
|
|
511
|
-
email: 'test@example.com',
|
|
512
|
-
code: '123456',
|
|
513
|
-
challengeSessionId: undefined as any,
|
|
514
|
-
});
|
|
515
|
-
fail('Should have thrown NAuthException');
|
|
516
|
-
} catch (error: any) {
|
|
517
|
-
expect(error).toBeInstanceOf(NAuthException);
|
|
518
|
-
expect(error.code).toBe(AuthErrorCode.VALIDATION_FAILED);
|
|
519
|
-
expect(error.message).toContain('Challenge session ID is required');
|
|
520
|
-
}
|
|
521
|
-
});
|
|
522
|
-
|
|
523
|
-
it('should throw NAuthException if user not found', async () => {
|
|
524
|
-
mockUserRepository.findOne.mockResolvedValue(null);
|
|
525
|
-
|
|
526
|
-
try {
|
|
527
|
-
await service.verifyEmailWithCode({
|
|
528
|
-
email: 'nonexistent@example.com',
|
|
529
|
-
code: '123456',
|
|
530
|
-
challengeSessionId: 1,
|
|
531
|
-
});
|
|
532
|
-
fail('Should have thrown NAuthException');
|
|
533
|
-
} catch (error: any) {
|
|
534
|
-
expect(error).toBeInstanceOf(NAuthException);
|
|
535
|
-
expect(error.code).toBe(AuthErrorCode.NOT_FOUND);
|
|
536
|
-
}
|
|
537
|
-
});
|
|
538
|
-
|
|
539
|
-
it('should throw NAuthException for invalid code', async () => {
|
|
540
|
-
mockUserRepository.findOne.mockResolvedValue(mockUser as any);
|
|
541
|
-
mockStorageAdapter.incr.mockResolvedValue(1);
|
|
542
|
-
mockStorageAdapter.expire.mockResolvedValue();
|
|
543
|
-
mockVerificationTokenRepository.findOne.mockResolvedValue(null);
|
|
544
|
-
|
|
545
|
-
try {
|
|
546
|
-
await service.verifyEmailWithCode({
|
|
547
|
-
email: 'test@example.com',
|
|
548
|
-
code: 'wrong-code',
|
|
549
|
-
challengeSessionId: 1,
|
|
550
|
-
});
|
|
551
|
-
fail('Should have thrown NAuthException');
|
|
552
|
-
} catch (error: any) {
|
|
553
|
-
expect(error).toBeInstanceOf(NAuthException);
|
|
554
|
-
expect(error.code).toBe(AuthErrorCode.VERIFICATION_CODE_INVALID);
|
|
555
|
-
}
|
|
556
|
-
});
|
|
557
|
-
|
|
558
|
-
it('should throw NAuthException for expired code', async () => {
|
|
559
|
-
const expiredToken = {
|
|
560
|
-
...mockVerificationToken,
|
|
561
|
-
expiresAt: new Date(Date.now() - 1000),
|
|
562
|
-
isExpired: jest.fn().mockReturnValue(true),
|
|
563
|
-
};
|
|
564
|
-
mockUserRepository.findOne.mockResolvedValue(mockUser as any);
|
|
565
|
-
mockStorageAdapter.incr.mockResolvedValue(1);
|
|
566
|
-
mockStorageAdapter.expire.mockResolvedValue();
|
|
567
|
-
mockVerificationTokenRepository.findOne.mockResolvedValue(expiredToken as any);
|
|
568
|
-
|
|
569
|
-
try {
|
|
570
|
-
await service.verifyEmailWithCode({
|
|
571
|
-
email: 'test@example.com',
|
|
572
|
-
code: '123456',
|
|
573
|
-
challengeSessionId: 1,
|
|
574
|
-
});
|
|
575
|
-
fail('Should have thrown NAuthException');
|
|
576
|
-
} catch (error: any) {
|
|
577
|
-
expect(error).toBeInstanceOf(NAuthException);
|
|
578
|
-
expect(error.code).toBe(AuthErrorCode.VERIFICATION_CODE_EXPIRED);
|
|
579
|
-
}
|
|
580
|
-
});
|
|
581
|
-
|
|
582
|
-
it('should throw NAuthException after max attempts', async () => {
|
|
583
|
-
const exhaustedToken = {
|
|
584
|
-
...mockVerificationToken,
|
|
585
|
-
attempts: 3,
|
|
586
|
-
isExpired: jest.fn().mockReturnValue(false),
|
|
587
|
-
maxAttemptsExceeded: jest.fn().mockReturnValue(true),
|
|
588
|
-
};
|
|
589
|
-
mockUserRepository.findOne.mockResolvedValue(mockUser as any);
|
|
590
|
-
mockStorageAdapter.incr.mockResolvedValue(1);
|
|
591
|
-
mockStorageAdapter.expire.mockResolvedValue();
|
|
592
|
-
mockVerificationTokenRepository.findOne.mockResolvedValue(exhaustedToken as any);
|
|
593
|
-
|
|
594
|
-
try {
|
|
595
|
-
await service.verifyEmailWithCode({
|
|
596
|
-
email: 'test@example.com',
|
|
597
|
-
code: '123456',
|
|
598
|
-
challengeSessionId: 1,
|
|
599
|
-
});
|
|
600
|
-
fail('Should have thrown NAuthException');
|
|
601
|
-
} catch (error: any) {
|
|
602
|
-
expect(error).toBeInstanceOf(NAuthException);
|
|
603
|
-
expect(error.code).toBe(AuthErrorCode.VERIFICATION_TOO_MANY_ATTEMPTS);
|
|
604
|
-
}
|
|
605
|
-
});
|
|
606
|
-
|
|
607
|
-
it('should increment attempts on invalid code', async () => {
|
|
608
|
-
const tokenWithWrongCode = {
|
|
609
|
-
...mockVerificationToken,
|
|
610
|
-
code: '999999', // Different code
|
|
611
|
-
attempts: 0,
|
|
612
|
-
};
|
|
613
|
-
mockUserRepository.findOne.mockResolvedValue(mockUser as any);
|
|
614
|
-
mockStorageAdapter.incr.mockResolvedValue(1);
|
|
615
|
-
mockStorageAdapter.expire.mockResolvedValue();
|
|
616
|
-
mockVerificationTokenRepository.findOne.mockResolvedValue(tokenWithWrongCode as any);
|
|
617
|
-
mockVerificationTokenRepository.save.mockResolvedValue(tokenWithWrongCode as any);
|
|
618
|
-
|
|
619
|
-
try {
|
|
620
|
-
await service.verifyEmailWithCode({
|
|
621
|
-
email: 'test@example.com',
|
|
622
|
-
code: '123456',
|
|
623
|
-
challengeSessionId: 1,
|
|
624
|
-
});
|
|
625
|
-
fail('Should have thrown NAuthException');
|
|
626
|
-
} catch (error: any) {
|
|
627
|
-
expect(error.code).toBe(AuthErrorCode.VERIFICATION_CODE_INVALID);
|
|
628
|
-
expect(mockVerificationTokenRepository.save).toHaveBeenCalledWith(
|
|
629
|
-
(expect as any).objectContaining({
|
|
630
|
-
attempts: 1, // Incremented
|
|
631
|
-
}),
|
|
632
|
-
);
|
|
633
|
-
expect(mockAuditService.recordEvent).toHaveBeenCalledWith(
|
|
634
|
-
(expect as any).objectContaining({
|
|
635
|
-
eventType: (expect as any).any(String),
|
|
636
|
-
eventStatus: 'FAILURE',
|
|
637
|
-
}),
|
|
638
|
-
);
|
|
639
|
-
}
|
|
640
|
-
});
|
|
641
|
-
|
|
642
|
-
it('should enforce per-user rate limiting', async () => {
|
|
643
|
-
mockUserRepository.findOne.mockResolvedValue(mockUser as any);
|
|
644
|
-
// Provide a token with a different code so code mismatch path is taken
|
|
645
|
-
const tokenWithWrongCode = { ...mockVerificationToken, code: '999999' };
|
|
646
|
-
mockVerificationTokenRepository.findOne.mockResolvedValue(tokenWithWrongCode as any);
|
|
647
|
-
mockStorageAdapter.incr
|
|
648
|
-
.mockResolvedValueOnce(1) // IP attempts (checked first)
|
|
649
|
-
.mockResolvedValueOnce(11); // User attempts (exceeds limit of 10, checked second)
|
|
650
|
-
mockVerificationTokenRepository.save.mockResolvedValue(tokenWithWrongCode as any);
|
|
651
|
-
|
|
652
|
-
try {
|
|
653
|
-
await service.verifyEmailWithCode({
|
|
654
|
-
email: 'test@example.com',
|
|
655
|
-
code: '123456',
|
|
656
|
-
challengeSessionId: 1,
|
|
657
|
-
}); // Wrong code
|
|
658
|
-
fail('Should have thrown NAuthException');
|
|
659
|
-
} catch (error: any) {
|
|
660
|
-
expect(error).toBeInstanceOf(NAuthException);
|
|
661
|
-
expect(error.code).toBe(AuthErrorCode.VERIFICATION_TOO_MANY_ATTEMPTS);
|
|
662
|
-
}
|
|
663
|
-
});
|
|
664
|
-
|
|
665
|
-
it('should enforce per-IP rate limiting', async () => {
|
|
666
|
-
mockUserRepository.findOne.mockResolvedValue(mockUser as any);
|
|
667
|
-
// Provide a token with a different code so code mismatch path is taken
|
|
668
|
-
const tokenWithWrongCode = { ...mockVerificationToken, code: '999999' };
|
|
669
|
-
mockVerificationTokenRepository.findOne.mockResolvedValue(tokenWithWrongCode as any);
|
|
670
|
-
mockStorageAdapter.incr
|
|
671
|
-
.mockResolvedValueOnce(1) // User attempts
|
|
672
|
-
.mockResolvedValueOnce(21); // IP attempts (exceeds limit of 20)
|
|
673
|
-
mockVerificationTokenRepository.save.mockResolvedValue(tokenWithWrongCode as any);
|
|
674
|
-
|
|
675
|
-
try {
|
|
676
|
-
await service.verifyEmailWithCode({
|
|
677
|
-
email: 'test@example.com',
|
|
678
|
-
code: '123456',
|
|
679
|
-
challengeSessionId: 1,
|
|
680
|
-
}); // Wrong code
|
|
681
|
-
fail('Should have thrown NAuthException');
|
|
682
|
-
} catch (error: any) {
|
|
683
|
-
expect(error).toBeInstanceOf(NAuthException);
|
|
684
|
-
expect(error.code).toBe(AuthErrorCode.VERIFICATION_TOO_MANY_ATTEMPTS);
|
|
685
|
-
}
|
|
686
|
-
});
|
|
687
|
-
|
|
688
|
-
it('should handle missing IP address in client info', async () => {
|
|
689
|
-
mockClientInfoService.get.mockReturnValue({
|
|
690
|
-
ipAddress: '',
|
|
691
|
-
userAgent: 'test-agent',
|
|
692
|
-
});
|
|
693
|
-
mockUserRepository.findOne.mockResolvedValue(mockUser as any);
|
|
694
|
-
// Provide a token with a different code so user rate limiting is triggered
|
|
695
|
-
const tokenWithWrongCode = { ...mockVerificationToken, code: '999999' };
|
|
696
|
-
mockVerificationTokenRepository.findOne.mockResolvedValue(tokenWithWrongCode as any);
|
|
697
|
-
mockStorageAdapter.incr.mockResolvedValue(1); // User attempts
|
|
698
|
-
mockStorageAdapter.expire.mockResolvedValue();
|
|
699
|
-
mockVerificationTokenRepository.save.mockResolvedValue(tokenWithWrongCode as any);
|
|
700
|
-
|
|
701
|
-
try {
|
|
702
|
-
await service.verifyEmailWithCode({
|
|
703
|
-
email: 'test@example.com',
|
|
704
|
-
code: '123456',
|
|
705
|
-
challengeSessionId: 1,
|
|
706
|
-
}); // Wrong code
|
|
707
|
-
fail('Should have thrown NAuthException');
|
|
708
|
-
} catch (error: any) {
|
|
709
|
-
expect(error).toBeInstanceOf(NAuthException);
|
|
710
|
-
expect(error.code).toBe(AuthErrorCode.VERIFICATION_CODE_INVALID);
|
|
711
|
-
}
|
|
712
|
-
// Should not check IP rate limit if IP is missing (only user rate limit checked)
|
|
713
|
-
expect(mockStorageAdapter.incr).toHaveBeenCalledTimes(1); // Only user attempts
|
|
714
|
-
});
|
|
715
|
-
|
|
716
|
-
it('should handle audit service errors gracefully', async () => {
|
|
717
|
-
mockUserRepository.findOne.mockResolvedValue(mockUser as any);
|
|
718
|
-
mockStorageAdapter.incr.mockResolvedValue(1);
|
|
719
|
-
mockStorageAdapter.expire.mockResolvedValue();
|
|
720
|
-
mockVerificationTokenRepository.findOne.mockResolvedValue(mockVerificationToken as any);
|
|
721
|
-
mockVerificationTokenRepository.save.mockResolvedValue(mockVerificationToken as any);
|
|
722
|
-
mockAuditService.recordEvent.mockRejectedValue(new Error('Audit error'));
|
|
723
|
-
|
|
724
|
-
const result = await service.verifyEmailWithCode({
|
|
725
|
-
email: 'test@example.com',
|
|
726
|
-
code: '123456',
|
|
727
|
-
challengeSessionId: 1,
|
|
728
|
-
});
|
|
729
|
-
|
|
730
|
-
expect(mockLogger.error).toHaveBeenCalled();
|
|
731
|
-
expect(result.message).toBeDefined(); // Should still verify
|
|
732
|
-
});
|
|
733
|
-
|
|
734
|
-
it('should check expiration using isExpired method if available', async () => {
|
|
735
|
-
const tokenWithMethod = {
|
|
736
|
-
...mockVerificationToken,
|
|
737
|
-
isExpired: jest.fn().mockReturnValue(true),
|
|
738
|
-
};
|
|
739
|
-
mockUserRepository.findOne.mockResolvedValue(mockUser as any);
|
|
740
|
-
mockStorageAdapter.incr.mockResolvedValue(1);
|
|
741
|
-
mockStorageAdapter.expire.mockResolvedValue();
|
|
742
|
-
mockVerificationTokenRepository.findOne.mockResolvedValue(tokenWithMethod as any);
|
|
743
|
-
|
|
744
|
-
try {
|
|
745
|
-
await service.verifyEmailWithCode({
|
|
746
|
-
email: 'test@example.com',
|
|
747
|
-
code: '123456',
|
|
748
|
-
challengeSessionId: 1,
|
|
749
|
-
});
|
|
750
|
-
fail('Should have thrown NAuthException');
|
|
751
|
-
} catch (error: any) {
|
|
752
|
-
expect(error.code).toBe(AuthErrorCode.VERIFICATION_CODE_EXPIRED);
|
|
753
|
-
expect(tokenWithMethod.isExpired).toHaveBeenCalled();
|
|
754
|
-
}
|
|
755
|
-
});
|
|
756
|
-
|
|
757
|
-
it('should check expiration using expiresAt date if method not available', async () => {
|
|
758
|
-
const tokenWithoutMethod = {
|
|
759
|
-
...mockVerificationToken,
|
|
760
|
-
expiresAt: new Date(Date.now() - 1000), // Expired
|
|
761
|
-
isExpired: undefined,
|
|
762
|
-
};
|
|
763
|
-
mockUserRepository.findOne.mockResolvedValue(mockUser as any);
|
|
764
|
-
mockStorageAdapter.incr.mockResolvedValue(1);
|
|
765
|
-
mockStorageAdapter.expire.mockResolvedValue();
|
|
766
|
-
mockVerificationTokenRepository.findOne.mockResolvedValue(tokenWithoutMethod as any);
|
|
767
|
-
|
|
768
|
-
try {
|
|
769
|
-
await service.verifyEmailWithCode({
|
|
770
|
-
email: 'test@example.com',
|
|
771
|
-
code: '123456',
|
|
772
|
-
challengeSessionId: 1,
|
|
773
|
-
});
|
|
774
|
-
fail('Should have thrown NAuthException');
|
|
775
|
-
} catch (error: any) {
|
|
776
|
-
expect(error.code).toBe(AuthErrorCode.VERIFICATION_CODE_EXPIRED);
|
|
777
|
-
}
|
|
778
|
-
});
|
|
779
|
-
|
|
780
|
-
it('should check max attempts using method if available', async () => {
|
|
781
|
-
const tokenWithMethod = {
|
|
782
|
-
...mockVerificationToken,
|
|
783
|
-
maxAttemptsExceeded: jest.fn().mockReturnValue(true),
|
|
784
|
-
};
|
|
785
|
-
mockUserRepository.findOne.mockResolvedValue(mockUser as any);
|
|
786
|
-
mockStorageAdapter.incr.mockResolvedValue(1);
|
|
787
|
-
mockStorageAdapter.expire.mockResolvedValue();
|
|
788
|
-
mockVerificationTokenRepository.findOne.mockResolvedValue(tokenWithMethod as any);
|
|
789
|
-
|
|
790
|
-
try {
|
|
791
|
-
await service.verifyEmailWithCode({
|
|
792
|
-
email: 'test@example.com',
|
|
793
|
-
code: '123456',
|
|
794
|
-
challengeSessionId: 1,
|
|
795
|
-
});
|
|
796
|
-
fail('Should have thrown NAuthException');
|
|
797
|
-
} catch (error: any) {
|
|
798
|
-
expect(error.code).toBe(AuthErrorCode.VERIFICATION_TOO_MANY_ATTEMPTS);
|
|
799
|
-
expect(tokenWithMethod.maxAttemptsExceeded).toHaveBeenCalledWith(3);
|
|
800
|
-
}
|
|
801
|
-
});
|
|
802
|
-
|
|
803
|
-
it('should check max attempts using attempts field if method not available', async () => {
|
|
804
|
-
const tokenWithoutMethod = {
|
|
805
|
-
...mockVerificationToken,
|
|
806
|
-
attempts: 3,
|
|
807
|
-
maxAttemptsExceeded: undefined,
|
|
808
|
-
};
|
|
809
|
-
mockUserRepository.findOne.mockResolvedValue(mockUser as any);
|
|
810
|
-
mockStorageAdapter.incr.mockResolvedValue(1);
|
|
811
|
-
mockStorageAdapter.expire.mockResolvedValue();
|
|
812
|
-
mockVerificationTokenRepository.findOne.mockResolvedValue(tokenWithoutMethod as any);
|
|
813
|
-
|
|
814
|
-
try {
|
|
815
|
-
await service.verifyEmailWithCode({
|
|
816
|
-
email: 'test@example.com',
|
|
817
|
-
code: '123456',
|
|
818
|
-
challengeSessionId: 1,
|
|
819
|
-
});
|
|
820
|
-
fail('Should have thrown NAuthException');
|
|
821
|
-
} catch (error: any) {
|
|
822
|
-
expect(error.code).toBe(AuthErrorCode.VERIFICATION_TOO_MANY_ATTEMPTS);
|
|
823
|
-
}
|
|
824
|
-
});
|
|
825
|
-
});
|
|
826
|
-
|
|
827
|
-
// ============================================================================
|
|
828
|
-
// verifyEmailWithToken
|
|
829
|
-
// ============================================================================
|
|
830
|
-
|
|
831
|
-
describe('verifyEmailWithToken', () => {
|
|
832
|
-
it('should verify email with valid token', async () => {
|
|
833
|
-
// Token is hashed before lookup
|
|
834
|
-
const tokenHash = 'hashed-token-abc123';
|
|
835
|
-
const token = 'abc123';
|
|
836
|
-
const tokenWithHash = {
|
|
837
|
-
...mockVerificationToken,
|
|
838
|
-
token: tokenHash,
|
|
839
|
-
};
|
|
840
|
-
mockVerificationTokenRepository.findOne.mockResolvedValue(tokenWithHash as any);
|
|
841
|
-
mockVerificationTokenRepository.save.mockResolvedValue(tokenWithHash as any);
|
|
842
|
-
mockUserRepository.findOne.mockResolvedValue(mockUser as any);
|
|
843
|
-
mockUserRepository.update.mockResolvedValue({ affected: 1 } as any);
|
|
844
|
-
|
|
845
|
-
const result = await service.verifyEmailWithToken(token);
|
|
846
|
-
|
|
847
|
-
expect(result.message).toBe('Email verified successfully. Please log in to continue.');
|
|
848
|
-
expect(mockVerificationTokenRepository.findOne).toHaveBeenCalledWith({
|
|
849
|
-
where: {
|
|
850
|
-
token: (expect as any).any(String), // Hashed token
|
|
851
|
-
type: 'email',
|
|
852
|
-
usedAt: (expect as any).any(Object), // IsNull()
|
|
853
|
-
} as any,
|
|
854
|
-
});
|
|
855
|
-
expect(mockUserRepository.update).toHaveBeenCalledWith(123, {
|
|
856
|
-
isEmailVerified: true,
|
|
857
|
-
isActive: true,
|
|
858
|
-
});
|
|
859
|
-
expect(mockAuditService.recordEvent).toHaveBeenCalled();
|
|
860
|
-
});
|
|
861
|
-
|
|
862
|
-
it('should throw NAuthException for invalid token', async () => {
|
|
863
|
-
mockVerificationTokenRepository.findOne.mockResolvedValue(null);
|
|
864
|
-
|
|
865
|
-
try {
|
|
866
|
-
await service.verifyEmailWithToken('invalid-token');
|
|
867
|
-
fail('Should have thrown NAuthException');
|
|
868
|
-
} catch (error: any) {
|
|
869
|
-
expect(error).toBeInstanceOf(NAuthException);
|
|
870
|
-
expect(error.code).toBe(AuthErrorCode.VERIFICATION_CODE_INVALID);
|
|
871
|
-
}
|
|
872
|
-
});
|
|
873
|
-
|
|
874
|
-
it('should throw NAuthException for expired token', async () => {
|
|
875
|
-
const expiredToken = {
|
|
876
|
-
...mockVerificationToken,
|
|
877
|
-
expiresAt: new Date(Date.now() - 1000),
|
|
878
|
-
isExpired: jest.fn().mockReturnValue(true),
|
|
879
|
-
};
|
|
880
|
-
mockVerificationTokenRepository.findOne.mockResolvedValue(expiredToken as any);
|
|
881
|
-
|
|
882
|
-
try {
|
|
883
|
-
await service.verifyEmailWithToken('abc123');
|
|
884
|
-
fail('Should have thrown NAuthException');
|
|
885
|
-
} catch (error: any) {
|
|
886
|
-
expect(error).toBeInstanceOf(NAuthException);
|
|
887
|
-
expect(error.code).toBe(AuthErrorCode.VERIFICATION_CODE_EXPIRED);
|
|
888
|
-
}
|
|
889
|
-
});
|
|
890
|
-
|
|
891
|
-
it('should mark token as used after verification', async () => {
|
|
892
|
-
const tokenWithHash = {
|
|
893
|
-
...mockVerificationToken,
|
|
894
|
-
token: 'hashed-token-abc123',
|
|
895
|
-
usedAt: null,
|
|
896
|
-
};
|
|
897
|
-
mockVerificationTokenRepository.findOne.mockResolvedValue(tokenWithHash as any);
|
|
898
|
-
mockVerificationTokenRepository.save.mockResolvedValue(tokenWithHash as any);
|
|
899
|
-
mockUserRepository.findOne.mockResolvedValue(mockUser as any);
|
|
900
|
-
mockUserRepository.update.mockResolvedValue({ affected: 1 } as any);
|
|
901
|
-
|
|
902
|
-
await service.verifyEmailWithToken('abc123');
|
|
903
|
-
|
|
904
|
-
expect(mockVerificationTokenRepository.save).toHaveBeenCalledWith(
|
|
905
|
-
(expect as any).objectContaining({
|
|
906
|
-
usedAt: (expect as any).any(Date),
|
|
907
|
-
}),
|
|
908
|
-
);
|
|
909
|
-
});
|
|
910
|
-
|
|
911
|
-
it('should handle audit service errors gracefully', async () => {
|
|
912
|
-
const tokenWithHash = {
|
|
913
|
-
...mockVerificationToken,
|
|
914
|
-
token: 'hashed-token-abc123',
|
|
915
|
-
};
|
|
916
|
-
mockVerificationTokenRepository.findOne.mockResolvedValue(tokenWithHash as any);
|
|
917
|
-
mockVerificationTokenRepository.save.mockResolvedValue(tokenWithHash as any);
|
|
918
|
-
mockUserRepository.findOne.mockResolvedValue(mockUser as any);
|
|
919
|
-
mockUserRepository.update.mockResolvedValue({ affected: 1 } as any);
|
|
920
|
-
mockAuditService.recordEvent.mockRejectedValue(new Error('Audit error'));
|
|
921
|
-
|
|
922
|
-
const result = await service.verifyEmailWithToken('abc123');
|
|
923
|
-
|
|
924
|
-
expect(mockLogger.error).toHaveBeenCalled();
|
|
925
|
-
expect(result.message).toBeDefined(); // Should still verify
|
|
926
|
-
});
|
|
927
|
-
|
|
928
|
-
it('should handle missing user gracefully', async () => {
|
|
929
|
-
const tokenWithHash = {
|
|
930
|
-
...mockVerificationToken,
|
|
931
|
-
token: 'hashed-token-abc123',
|
|
932
|
-
};
|
|
933
|
-
mockVerificationTokenRepository.findOne.mockResolvedValue(tokenWithHash as any);
|
|
934
|
-
mockVerificationTokenRepository.save.mockResolvedValue(tokenWithHash as any);
|
|
935
|
-
mockUserRepository.findOne.mockResolvedValue(null); // User not found
|
|
936
|
-
mockUserRepository.update.mockResolvedValue({ affected: 1 } as any);
|
|
937
|
-
|
|
938
|
-
const result = await service.verifyEmailWithToken('abc123');
|
|
939
|
-
|
|
940
|
-
// Should still update user and return success
|
|
941
|
-
expect(result.message).toBeDefined();
|
|
942
|
-
expect(mockAuditService.recordEvent).not.toHaveBeenCalled(); // No user for audit
|
|
943
|
-
});
|
|
944
|
-
|
|
945
|
-
it('should check expiration using isExpired method if available', async () => {
|
|
946
|
-
const expiredToken = {
|
|
947
|
-
...mockVerificationToken,
|
|
948
|
-
token: 'hashed-token-abc123',
|
|
949
|
-
isExpired: jest.fn().mockReturnValue(true),
|
|
950
|
-
};
|
|
951
|
-
mockVerificationTokenRepository.findOne.mockResolvedValue(expiredToken as any);
|
|
952
|
-
|
|
953
|
-
try {
|
|
954
|
-
await service.verifyEmailWithToken('abc123');
|
|
955
|
-
fail('Should have thrown NAuthException');
|
|
956
|
-
} catch (error: any) {
|
|
957
|
-
expect(error.code).toBe(AuthErrorCode.VERIFICATION_CODE_EXPIRED);
|
|
958
|
-
expect(expiredToken.isExpired).toHaveBeenCalled();
|
|
959
|
-
}
|
|
960
|
-
});
|
|
961
|
-
|
|
962
|
-
it('should check expiration using expiresAt date if method not available', async () => {
|
|
963
|
-
const expiredToken = {
|
|
964
|
-
...mockVerificationToken,
|
|
965
|
-
token: 'hashed-token-abc123',
|
|
966
|
-
expiresAt: new Date(Date.now() - 1000),
|
|
967
|
-
isExpired: undefined,
|
|
968
|
-
};
|
|
969
|
-
mockVerificationTokenRepository.findOne.mockResolvedValue(expiredToken as any);
|
|
970
|
-
|
|
971
|
-
try {
|
|
972
|
-
await service.verifyEmailWithToken('abc123');
|
|
973
|
-
fail('Should have thrown NAuthException');
|
|
974
|
-
} catch (error: any) {
|
|
975
|
-
expect(error.code).toBe(AuthErrorCode.VERIFICATION_CODE_EXPIRED);
|
|
976
|
-
}
|
|
977
|
-
});
|
|
978
|
-
});
|
|
979
|
-
|
|
980
|
-
// ============================================================================
|
|
981
|
-
// resendVerificationEmail
|
|
982
|
-
// ============================================================================
|
|
983
|
-
|
|
984
|
-
describe('resendVerificationEmail', () => {
|
|
985
|
-
it('should resend verification email successfully', async () => {
|
|
986
|
-
mockUserRepository.findOne.mockResolvedValue(mockUser as any);
|
|
987
|
-
mockVerificationTokenRepository.findOne.mockResolvedValue(null); // No last token
|
|
988
|
-
mockStorageAdapter.incr.mockResolvedValue(1);
|
|
989
|
-
mockStorageAdapter.ttl.mockResolvedValue(3600);
|
|
990
|
-
mockVerificationTokenRepository.create.mockReturnValue(mockVerificationToken as any);
|
|
991
|
-
mockVerificationTokenRepository.save.mockResolvedValue(mockVerificationToken as any);
|
|
992
|
-
|
|
993
|
-
const result = await service.resendVerificationEmail('user-sub-123', 'https://example.com');
|
|
994
|
-
|
|
995
|
-
expect(mockUserRepository.findOne).toHaveBeenCalledWith({ where: { sub: 'user-sub-123' } as any });
|
|
996
|
-
expect(mockEmailProvider.sendVerificationEmail).toHaveBeenCalled();
|
|
997
|
-
expect(result).toBe(456);
|
|
998
|
-
});
|
|
999
|
-
|
|
1000
|
-
it('should enforce resend delay', async () => {
|
|
1001
|
-
const recentToken = {
|
|
1002
|
-
...mockVerificationToken,
|
|
1003
|
-
createdAt: new Date(Date.now() - 30 * 1000), // 30 seconds ago
|
|
1004
|
-
};
|
|
1005
|
-
mockUserRepository.findOne.mockResolvedValue(mockUser as any);
|
|
1006
|
-
mockVerificationTokenRepository.findOne.mockResolvedValue(recentToken as any);
|
|
1007
|
-
|
|
1008
|
-
try {
|
|
1009
|
-
await service.resendVerificationEmail('user-sub-123');
|
|
1010
|
-
fail('Should have thrown NAuthException');
|
|
1011
|
-
} catch (error: any) {
|
|
1012
|
-
expect(error).toBeInstanceOf(NAuthException);
|
|
1013
|
-
expect(error.code).toBe(AuthErrorCode.RATE_LIMIT_RESEND);
|
|
1014
|
-
}
|
|
1015
|
-
});
|
|
1016
|
-
|
|
1017
|
-
it('should allow resend after delay period', async () => {
|
|
1018
|
-
const oldToken = {
|
|
1019
|
-
...mockVerificationToken,
|
|
1020
|
-
createdAt: new Date(Date.now() - 70 * 1000), // 70 seconds ago
|
|
1021
|
-
};
|
|
1022
|
-
mockUserRepository.findOne.mockResolvedValue(mockUser as any);
|
|
1023
|
-
mockVerificationTokenRepository.findOne.mockResolvedValue(oldToken as any);
|
|
1024
|
-
mockStorageAdapter.incr.mockResolvedValue(1);
|
|
1025
|
-
mockStorageAdapter.ttl.mockResolvedValue(3600);
|
|
1026
|
-
mockVerificationTokenRepository.create.mockReturnValue(mockVerificationToken as any);
|
|
1027
|
-
mockVerificationTokenRepository.save.mockResolvedValue(mockVerificationToken as any);
|
|
1028
|
-
|
|
1029
|
-
await service.resendVerificationEmail('user-sub-123');
|
|
1030
|
-
|
|
1031
|
-
expect(mockEmailProvider.sendVerificationEmail).toHaveBeenCalled();
|
|
1032
|
-
});
|
|
1033
|
-
|
|
1034
|
-
it('should throw NAuthException if user not found', async () => {
|
|
1035
|
-
mockUserRepository.findOne.mockResolvedValue(null);
|
|
1036
|
-
|
|
1037
|
-
try {
|
|
1038
|
-
await service.resendVerificationEmail('invalid-sub');
|
|
1039
|
-
fail('Should have thrown NAuthException');
|
|
1040
|
-
} catch (error: any) {
|
|
1041
|
-
expect(error).toBeInstanceOf(NAuthException);
|
|
1042
|
-
expect(error.code).toBe(AuthErrorCode.NOT_FOUND);
|
|
1043
|
-
}
|
|
1044
|
-
});
|
|
1045
|
-
|
|
1046
|
-
it('should delegate to sendVerificationEmail', async () => {
|
|
1047
|
-
mockUserRepository.findOne.mockResolvedValue(mockUser as any);
|
|
1048
|
-
mockVerificationTokenRepository.findOne.mockResolvedValue(null);
|
|
1049
|
-
mockStorageAdapter.incr.mockResolvedValue(1);
|
|
1050
|
-
mockStorageAdapter.ttl.mockResolvedValue(3600);
|
|
1051
|
-
mockVerificationTokenRepository.create.mockReturnValue(mockVerificationToken as any);
|
|
1052
|
-
mockVerificationTokenRepository.save.mockResolvedValue(mockVerificationToken as any);
|
|
1053
|
-
|
|
1054
|
-
await service.resendVerificationEmail('user-sub-123', 'https://example.com');
|
|
1055
|
-
|
|
1056
|
-
// Should call sendVerificationEmail with same parameters
|
|
1057
|
-
expect(mockEmailProvider.sendVerificationEmail).toHaveBeenCalled();
|
|
1058
|
-
});
|
|
1059
|
-
});
|
|
1060
|
-
|
|
1061
|
-
// ============================================================================
|
|
1062
|
-
// resendVerificationEmail (email overload)
|
|
1063
|
-
// ============================================================================
|
|
1064
|
-
|
|
1065
|
-
describe('resendVerificationEmail (email overload)', () => {
|
|
1066
|
-
it('should resend verification email by email address', async () => {
|
|
1067
|
-
mockUserRepository.findOne.mockResolvedValue(mockUser as any);
|
|
1068
|
-
mockVerificationTokenRepository.findOne.mockResolvedValue(null);
|
|
1069
|
-
mockStorageAdapter.incr.mockResolvedValue(1);
|
|
1070
|
-
mockStorageAdapter.ttl.mockResolvedValue(3600);
|
|
1071
|
-
mockVerificationTokenRepository.create.mockReturnValue(mockVerificationToken as any);
|
|
1072
|
-
mockVerificationTokenRepository.save.mockResolvedValue(mockVerificationToken as any);
|
|
1073
|
-
|
|
1074
|
-
const result = await service.resendVerificationEmail({
|
|
1075
|
-
email: 'test@example.com',
|
|
1076
|
-
baseUrl: 'https://example.com',
|
|
1077
|
-
});
|
|
1078
|
-
|
|
1079
|
-
expect(mockUserRepository.findOne).toHaveBeenCalledWith({ where: { email: 'test@example.com' } as any });
|
|
1080
|
-
expect(mockEmailProvider.sendVerificationEmail).toHaveBeenCalled();
|
|
1081
|
-
expect(result).toBe(456);
|
|
1082
|
-
});
|
|
1083
|
-
|
|
1084
|
-
it('should throw NAuthException if user not found by email', async () => {
|
|
1085
|
-
mockUserRepository.findOne.mockResolvedValue(null);
|
|
1086
|
-
|
|
1087
|
-
try {
|
|
1088
|
-
await service.resendVerificationEmail({ email: 'nonexistent@example.com' });
|
|
1089
|
-
fail('Should have thrown NAuthException');
|
|
1090
|
-
} catch (error: any) {
|
|
1091
|
-
expect(error).toBeInstanceOf(NAuthException);
|
|
1092
|
-
expect(error.code).toBe(AuthErrorCode.NOT_FOUND);
|
|
1093
|
-
}
|
|
1094
|
-
});
|
|
1095
|
-
|
|
1096
|
-
it('should use user sub when resending after finding by email', async () => {
|
|
1097
|
-
mockUserRepository.findOne.mockResolvedValue(mockUser as any);
|
|
1098
|
-
mockVerificationTokenRepository.findOne.mockResolvedValue(null);
|
|
1099
|
-
mockStorageAdapter.incr.mockResolvedValue(1);
|
|
1100
|
-
mockStorageAdapter.ttl.mockResolvedValue(3600);
|
|
1101
|
-
mockVerificationTokenRepository.create.mockReturnValue(mockVerificationToken as any);
|
|
1102
|
-
mockVerificationTokenRepository.save.mockResolvedValue(mockVerificationToken as any);
|
|
1103
|
-
|
|
1104
|
-
await service.resendVerificationEmail({ email: 'test@example.com', baseUrl: 'https://example.com' });
|
|
1105
|
-
|
|
1106
|
-
// Should find user by email, then use their sub to resend
|
|
1107
|
-
expect(mockUserRepository.findOne).toHaveBeenCalledWith({ where: { email: 'test@example.com' } as any });
|
|
1108
|
-
expect(mockEmailProvider.sendVerificationEmail).toHaveBeenCalled();
|
|
1109
|
-
});
|
|
1110
|
-
});
|
|
1111
|
-
|
|
1112
|
-
// ============================================================================
|
|
1113
|
-
// Service Without Optional Dependencies
|
|
1114
|
-
// ============================================================================
|
|
1115
|
-
|
|
1116
|
-
describe('Service without optional dependencies', () => {
|
|
1117
|
-
it('should work without audit service', async () => {
|
|
1118
|
-
const serviceWithoutAudit = new EmailVerificationService(
|
|
1119
|
-
mockVerificationTokenRepository,
|
|
1120
|
-
mockUserRepository,
|
|
1121
|
-
mockEmailProvider,
|
|
1122
|
-
mockStorageAdapter,
|
|
1123
|
-
mockConfig,
|
|
1124
|
-
mockClientInfoService,
|
|
1125
|
-
mockLogger,
|
|
1126
|
-
undefined, // No audit service
|
|
1127
|
-
);
|
|
1128
|
-
|
|
1129
|
-
mockStorageAdapter.incr.mockResolvedValue(1);
|
|
1130
|
-
mockStorageAdapter.ttl.mockResolvedValue(3600);
|
|
1131
|
-
mockUserRepository.findOne.mockResolvedValue(mockUser as any);
|
|
1132
|
-
mockVerificationTokenRepository.findOne.mockResolvedValue(null);
|
|
1133
|
-
mockVerificationTokenRepository.create.mockReturnValue(mockVerificationToken as any);
|
|
1134
|
-
mockVerificationTokenRepository.save.mockResolvedValue(mockVerificationToken as any);
|
|
1135
|
-
|
|
1136
|
-
await serviceWithoutAudit.sendVerificationEmail('user-sub-123');
|
|
1137
|
-
|
|
1138
|
-
// Should not throw error
|
|
1139
|
-
expect(mockEmailProvider.sendVerificationEmail).toHaveBeenCalled();
|
|
1140
|
-
});
|
|
1141
|
-
});
|
|
1142
|
-
|
|
1143
|
-
// ============================================================================
|
|
1144
|
-
// Edge Cases
|
|
1145
|
-
// ============================================================================
|
|
1146
|
-
|
|
1147
|
-
describe('Edge Cases', () => {
|
|
1148
|
-
it('should handle TTL of -1 (key does not exist)', async () => {
|
|
1149
|
-
mockStorageAdapter.ttl.mockResolvedValue(-1); // Key does not exist
|
|
1150
|
-
mockStorageAdapter.incr.mockResolvedValue(1);
|
|
1151
|
-
mockUserRepository.findOne.mockResolvedValue(mockUser as any);
|
|
1152
|
-
mockVerificationTokenRepository.findOne.mockResolvedValue(null);
|
|
1153
|
-
mockVerificationTokenRepository.create.mockReturnValue(mockVerificationToken as any);
|
|
1154
|
-
mockVerificationTokenRepository.save.mockResolvedValue(mockVerificationToken as any);
|
|
1155
|
-
|
|
1156
|
-
await service.sendVerificationEmail('user-sub-123');
|
|
1157
|
-
|
|
1158
|
-
// Should create new window
|
|
1159
|
-
expect(mockStorageAdapter.incr).toHaveBeenCalledWith(
|
|
1160
|
-
'email-verification:user-sub-123',
|
|
1161
|
-
3600, // Window expiry
|
|
1162
|
-
);
|
|
1163
|
-
});
|
|
1164
|
-
|
|
1165
|
-
it('should handle TTL of 0 (key expired)', async () => {
|
|
1166
|
-
mockStorageAdapter.ttl.mockResolvedValue(0); // Key expired
|
|
1167
|
-
mockStorageAdapter.incr.mockResolvedValue(1);
|
|
1168
|
-
mockUserRepository.findOne.mockResolvedValue(mockUser as any);
|
|
1169
|
-
mockVerificationTokenRepository.findOne.mockResolvedValue(null);
|
|
1170
|
-
mockVerificationTokenRepository.create.mockReturnValue(mockVerificationToken as any);
|
|
1171
|
-
mockVerificationTokenRepository.save.mockResolvedValue(mockVerificationToken as any);
|
|
1172
|
-
|
|
1173
|
-
await service.sendVerificationEmail('user-sub-123');
|
|
1174
|
-
|
|
1175
|
-
// Should create new window (when TTL is 0, window is expired, so TTL parameter is passed)
|
|
1176
|
-
expect(mockStorageAdapter.incr).toHaveBeenCalled();
|
|
1177
|
-
// When window is expired (TTL < 0 or TTL === 0), incr is called with TTL parameter
|
|
1178
|
-
// Check that at least one call was made with the rate limit key
|
|
1179
|
-
const incrCalls = mockStorageAdapter.incr.mock.calls;
|
|
1180
|
-
const rateLimitCall = incrCalls.find((call) => call[0] === 'email-verification:user-sub-123');
|
|
1181
|
-
expect(rateLimitCall).toBeDefined();
|
|
1182
|
-
// When expired, second parameter should be the window (3600)
|
|
1183
|
-
// But if it's not passed, that's also fine - the important thing is that it works
|
|
1184
|
-
});
|
|
1185
|
-
|
|
1186
|
-
it('should handle negative TTL (key expired)', async () => {
|
|
1187
|
-
mockStorageAdapter.ttl.mockResolvedValue(-10); // Negative TTL (expired)
|
|
1188
|
-
mockStorageAdapter.incr.mockResolvedValue(1);
|
|
1189
|
-
mockUserRepository.findOne.mockResolvedValue(mockUser as any);
|
|
1190
|
-
mockVerificationTokenRepository.findOne.mockResolvedValue(null);
|
|
1191
|
-
mockVerificationTokenRepository.create.mockReturnValue(mockVerificationToken as any);
|
|
1192
|
-
mockVerificationTokenRepository.save.mockResolvedValue(mockVerificationToken as any);
|
|
1193
|
-
|
|
1194
|
-
await service.sendVerificationEmail('user-sub-123');
|
|
1195
|
-
|
|
1196
|
-
// Should create new window
|
|
1197
|
-
expect(mockStorageAdapter.incr).toHaveBeenCalledWith(
|
|
1198
|
-
'email-verification:user-sub-123',
|
|
1199
|
-
3600, // Window expiry
|
|
1200
|
-
);
|
|
1201
|
-
});
|
|
1202
|
-
|
|
1203
|
-
it('should handle missing config email verification settings', async () => {
|
|
1204
|
-
mockConfig.email = undefined;
|
|
1205
|
-
service = new EmailVerificationService(
|
|
1206
|
-
mockVerificationTokenRepository,
|
|
1207
|
-
mockUserRepository,
|
|
1208
|
-
mockEmailProvider,
|
|
1209
|
-
mockStorageAdapter,
|
|
1210
|
-
mockConfig,
|
|
1211
|
-
mockClientInfoService,
|
|
1212
|
-
mockLogger,
|
|
1213
|
-
mockAuditService,
|
|
1214
|
-
);
|
|
1215
|
-
|
|
1216
|
-
mockStorageAdapter.incr.mockResolvedValue(1);
|
|
1217
|
-
mockStorageAdapter.ttl.mockResolvedValue(-1);
|
|
1218
|
-
mockUserRepository.findOne.mockResolvedValue(mockUser as any);
|
|
1219
|
-
mockVerificationTokenRepository.findOne.mockResolvedValue(null);
|
|
1220
|
-
mockVerificationTokenRepository.create.mockReturnValue(mockVerificationToken as any);
|
|
1221
|
-
mockVerificationTokenRepository.save.mockResolvedValue(mockVerificationToken as any);
|
|
1222
|
-
|
|
1223
|
-
// Should use defaults (rateLimitMax: 3, rateLimitWindow: 3600, resendDelay: 60)
|
|
1224
|
-
await service.sendVerificationEmail('user-sub-123');
|
|
1225
|
-
|
|
1226
|
-
expect(mockEmailProvider.sendVerificationEmail).toHaveBeenCalled();
|
|
1227
|
-
});
|
|
1228
|
-
});
|
|
1229
|
-
});
|