-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathAuthService.ts
More file actions
1179 lines (1042 loc) · 41.1 KB
/
Copy pathAuthService.ts
File metadata and controls
1179 lines (1042 loc) · 41.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Main Authentication Service
* Orchestrates all auth operations including login, registration, and OAuth
*/
import * as schema from '../schema';
import { eq, and, sql, or, lt, isNull } from 'drizzle-orm';
import { JWTUtils } from '../../utils/jwtUtils';
import { generateSecureToken } from '../../utils/cryptoUtils';
import { SessionService } from './SessionService';
import { ApiKeyService } from './ApiKeyService';
import { PasswordService } from '../../utils/passwordService';
import { GoogleOAuthProvider } from '../../services/oauth/google';
import { GitHubOAuthProvider } from '../../services/oauth/github';
import { CloudflareConnectOAuthProvider } from '../../services/oauth/cloudflare-connect';
import { BaseOAuthProvider } from '../../services/oauth/base';
import { readOAuthNonceCookie } from '../../utils/oauthCookie';
import {
SecurityError,
SecurityErrorType
} from 'shared/types/errors';
import { AuthResult, AuthUserSession, OAuthUserInfo } from '../../types/auth-types';
import { generateId } from '../../utils/idGenerator';
import {
AuthUser,
OAuthProvider
} from '../../types/auth-types';
import { mapUserResponse, validateRedirectUrl, enforceAllowedEmail } from '../../utils/authUtils';
import { createLogger } from '../../logger';
import { validateEmail, validatePassword } from '../../utils/validationUtils';
import { extractRequestMetadata } from '../../utils/authUtils';
import { BaseService } from './BaseService';
const logger = createLogger('AuthService');
/**
* Login credentials
*/
export interface LoginCredentials {
email: string;
password: string;
}
/**
* Registration data
*/
export interface RegistrationData {
email: string;
password: string;
name?: string;
}
/**
* Main Authentication Service
*/
export class AuthService extends BaseService {
private readonly sessionService: SessionService;
private readonly apiKeyService: ApiKeyService;
private readonly passwordService: PasswordService;
constructor(
env: Env,
) {
super(env);
this.sessionService = new SessionService(env);
this.apiKeyService = new ApiKeyService(env);
this.passwordService = new PasswordService();
}
/**
* Register a new user
*/
async register(data: RegistrationData, request: Request): Promise<AuthResult> {
try {
// Deployment-level admission gate (ALLOWED_EMAIL)
enforceAllowedEmail(this.env, data.email, 'register');
// Validate email format using centralized utility
const emailValidation = validateEmail(data.email);
if (!emailValidation.valid) {
throw new SecurityError(
SecurityErrorType.INVALID_INPUT,
emailValidation.error || 'Invalid email format',
400
);
}
// Validate password using centralized utility
const passwordValidation = validatePassword(data.password, undefined, {
email: data.email,
name: data.name
});
if (!passwordValidation.valid) {
throw new SecurityError(
SecurityErrorType.INVALID_INPUT,
passwordValidation.errors!.join(', '),
400
);
}
// Check if user already exists
const existingUser = await this.database
.select()
.from(schema.users)
.where(eq(schema.users.email, data.email.toLowerCase()))
.get();
if (existingUser) {
throw new SecurityError(
SecurityErrorType.INVALID_INPUT,
'Email already registered',
400
);
}
// Hash password
const passwordHash = await this.passwordService.hash(data.password);
// Create user
const userId = generateId();
const now = new Date();
// Store user as verified immediately (no OTP verification required)
await this.database.insert(schema.users).values({
id: userId,
email: data.email.toLowerCase(),
passwordHash,
displayName: data.name || data.email.split('@')[0],
emailVerified: true, // Set as verified immediately
provider: 'email',
providerId: userId,
createdAt: now,
updatedAt: now
});
// Get the created user
const newUser = await this.database
.select()
.from(schema.users)
.where(eq(schema.users.id, userId))
.get();
if (!newUser) {
throw new SecurityError(
SecurityErrorType.INVALID_INPUT,
'Failed to retrieve created user',
500
);
}
// Log successful registration
await this.logAuthAttempt(data.email, 'register', true, request);
logger.info('User registered and logged in directly', { userId, email: data.email });
// Create session and tokens immediately (log user in after registration)
const { accessToken, session } = await this.sessionService.createSession(
userId,
request
);
return {
user: mapUserResponse(newUser),
sessionId: session.sessionId,
expiresAt: session.expiresAt,
accessToken,
};
} catch (error) {
await this.logAuthAttempt(data.email, 'register', false, request);
if (error instanceof SecurityError) {
throw error;
}
logger.error('Registration error', error);
throw new SecurityError(
SecurityErrorType.INVALID_INPUT,
'Registration failed',
500
);
}
}
/**
* Login with email and password
*/
async login(credentials: LoginCredentials, request: Request): Promise<AuthResult> {
try {
// Deployment-level admission gate (ALLOWED_EMAIL)
enforceAllowedEmail(this.env, credentials.email, 'login');
// Find user
const user = await this.database
.select()
.from(schema.users)
.where(
and(
eq(schema.users.email, credentials.email.toLowerCase()),
sql`${schema.users.deletedAt} IS NULL`
)
)
.get();
if (!user || !user.passwordHash) {
await this.logAuthAttempt(credentials.email, 'login', false, request);
throw new SecurityError(
SecurityErrorType.UNAUTHORIZED,
'Invalid email or password',
401
);
}
// Verify password
const passwordValid = await this.passwordService.verify(
credentials.password,
user.passwordHash
);
if (!passwordValid) {
await this.logAuthAttempt(credentials.email, 'login', false, request);
throw new SecurityError(
SecurityErrorType.UNAUTHORIZED,
'Invalid email or password',
401
);
}
// Create session
const { accessToken, session } = await this.sessionService.createSession(
user.id,
request
);
// Log successful attempt
await this.logAuthAttempt(credentials.email, 'login', true, request);
logger.info('User logged in', { userId: user.id, email: user.email });
return {
user: mapUserResponse(user),
accessToken,
sessionId: session.sessionId,
expiresAt: session.expiresAt,
};
} catch (error) {
if (error instanceof SecurityError) {
throw error;
}
logger.error('Login error', error);
throw new SecurityError(
SecurityErrorType.UNAUTHORIZED,
'Login failed',
500
);
}
}
/**
* Logout
*/
async logout(sessionId: string): Promise<void> {
try {
await this.sessionService.revokeSessionId(sessionId);
logger.info('User logged out', { sessionId });
} catch (error) {
logger.error('Logout error', error);
throw new SecurityError(
SecurityErrorType.UNAUTHORIZED,
'Logout failed',
500
);
}
}
async getOauthProvider(provider: OAuthProvider, request: Request): Promise<BaseOAuthProvider> {
const url = new URL(request.url).origin;
switch (provider) {
case 'google':
return GoogleOAuthProvider.create(this.env, url);
case 'github':
return GitHubOAuthProvider.create(this.env, url);
case 'cloudflare':
return CloudflareConnectOAuthProvider.createForLogin(this.env, url);
default:
throw new SecurityError(
SecurityErrorType.INVALID_INPUT,
`OAuth provider ${provider} not configured`,
400
);
}
}
/**
* Get OAuth authorization URL
*/
async getOAuthAuthorizationUrl(
provider: OAuthProvider,
request: Request,
intendedRedirectUrl?: string,
linkUserId?: string
): Promise<{ authUrl: string; nonce: string }> {
const oauthProvider = await this.getOauthProvider(provider, request);
if (!oauthProvider) {
throw new SecurityError(
SecurityErrorType.INVALID_INPUT,
`OAuth provider ${provider} not configured`,
400
);
}
// Clean up expired OAuth states first
await this.cleanupExpiredOAuthStates();
// Validate and sanitize intended redirect URL
let validatedRedirectUrl: string | null = null;
if (intendedRedirectUrl) {
validatedRedirectUrl = validateRedirectUrl(intendedRedirectUrl, request);
}
// Generate state for CSRF protection
const state = generateSecureToken();
// Generate PKCE code verifier
const codeVerifier = BaseOAuthProvider.generateCodeVerifier();
// Generate a nonce that binds this state to the initiating browser. It is
// stored here and also set as an HttpOnly cookie by the controller; the
// callback rejects any request whose cookie nonce does not match. This is
// the core defense against login CSRF / session fixation.
const nonce = generateSecureToken();
// Store OAuth state with intended redirect URL
await this.database.insert(schema.oauthStates).values({
id: generateId(),
state,
provider,
codeVerifier,
redirectUri: validatedRedirectUrl || oauthProvider['redirectUri'],
createdAt: new Date(),
expiresAt: new Date(Date.now() + 600000), // 10 minutes
isUsed: false,
scopes: [],
userId: linkUserId ?? null,
nonce
});
// Get authorization URL
const authUrl = await oauthProvider.getAuthorizationUrl(state, codeVerifier);
logger.info('OAuth authorization initiated', { provider });
return { authUrl, nonce };
}
/**
* Clean up expired OAuth states
*/
private async cleanupExpiredOAuthStates(): Promise<void> {
try {
const now = new Date();
await this.database
.delete(schema.oauthStates)
.where(
or(
lt(schema.oauthStates.expiresAt, now),
eq(schema.oauthStates.isUsed, true)
)
);
logger.debug('Cleaned up expired OAuth states');
} catch (error) {
logger.error('Error cleaning up OAuth states', error);
}
}
/**
* Validate an OAuth state row (existence, expiry, browser nonce) and mark it as
* used. Shared by the login callback and the account-link callback.
*/
private async validateAndConsumeOAuthState(
provider: OAuthProvider,
state: string,
request: Request
): Promise<schema.OAuthState> {
const now = new Date();
const oauthState = await this.database
.select()
.from(schema.oauthStates)
.where(
and(
eq(schema.oauthStates.state, state),
eq(schema.oauthStates.provider, provider),
eq(schema.oauthStates.isUsed, false)
)
)
.get();
if (!oauthState || new Date(oauthState.expiresAt) < now) {
throw new SecurityError(
SecurityErrorType.CSRF_VIOLATION,
'Invalid or expired OAuth state',
400
);
}
// Bind the state to the initiating browser via the nonce cookie. A callback
// replayed in a different browser (login CSRF / session fixation) will not
// carry the matching nonce and is rejected here.
const cookieNonce = readOAuthNonceCookie(request, this.env);
if (!oauthState.nonce || !cookieNonce || cookieNonce !== oauthState.nonce) {
logger.warn('OAuth callback nonce mismatch - possible login CSRF', {
provider,
hasStoredNonce: !!oauthState.nonce,
hasCookieNonce: !!cookieNonce,
});
throw new SecurityError(
SecurityErrorType.CSRF_VIOLATION,
'Invalid or expired OAuth state',
400
);
}
// Mark state as used
await this.database
.update(schema.oauthStates)
.set({ isUsed: true })
.where(eq(schema.oauthStates.id, oauthState.id));
return oauthState;
}
/**
* Look up whether a still-valid, unused OAuth state is bound to a user (i.e. an
* account-link flow). Returns the bound userId or null. Does not consume state.
*/
async getPendingLinkUserId(
provider: OAuthProvider,
state: string
): Promise<string | null> {
const row = await this.database
.select({ userId: schema.oauthStates.userId })
.from(schema.oauthStates)
.where(
and(
eq(schema.oauthStates.state, state),
eq(schema.oauthStates.provider, provider),
eq(schema.oauthStates.isUsed, false)
)
)
.get();
return row?.userId ?? null;
}
/**
* Handle OAuth callback
*/
async handleOAuthCallback(
provider: OAuthProvider,
code: string,
state: string,
request: Request
): Promise<AuthResult> {
try {
const oauthProvider = await this.getOauthProvider(provider, request);
if (!oauthProvider) {
throw new SecurityError(
SecurityErrorType.INVALID_INPUT,
`OAuth provider ${provider} not configured`,
400
);
}
// Validate the state (existence, expiry, browser nonce) and mark it used.
const oauthState = await this.validateAndConsumeOAuthState(provider, state, request);
// A state bound to a user is an account-link flow and must go through
// completeOAuthLink (which re-checks the session), never the login path.
if (oauthState.userId) {
throw new SecurityError(
SecurityErrorType.CSRF_VIOLATION,
'Invalid OAuth state for login',
400
);
}
// Exchange code for tokens
const tokens = await oauthProvider.exchangeCodeForTokens(
code,
oauthState.codeVerifier || undefined
);
// Get user info
const oauthUserInfo = await oauthProvider.getUserInfo(tokens.accessToken);
// Deployment-level admission gate (ALLOWED_EMAIL). Enforced BEFORE any
// user row or session is created so a rejected email never gets admitted.
enforceAllowedEmail(this.env, oauthUserInfo.email, 'oauth');
// Find or create user
const user = await this.findOrCreateOAuthUser(provider, oauthUserInfo);
// Create session
const { accessToken: sessionAccessToken, session } = await this.sessionService.createSession(
user.id,
request
);
// Log auth attempt
await this.logAuthAttempt(user.email, `oauth_${provider}`, true, request);
logger.info('OAuth login successful', { userId: user.id, provider });
return {
user: mapUserResponse(user),
accessToken: sessionAccessToken,
sessionId: session.sessionId,
expiresAt: session.expiresAt,
redirectUrl: oauthState.redirectUri || undefined,
// Surface raw provider tokens only for Cloudflare so the controller can
// best-effort auto-connect the AI Gateway in the same round-trip.
oauthTokens: provider === 'cloudflare' ? tokens : undefined,
};
} catch (error) {
await this.logAuthAttempt('', `oauth_${provider}`, false, request);
if (error instanceof SecurityError) {
throw error;
}
logger.error('OAuth callback error', error);
throw new SecurityError(
SecurityErrorType.UNAUTHORIZED,
'OAuth authentication failed',
500
);
}
}
/**
* Resolve the user for an OAuth login.
*
* An OAuth login is a request to authenticate as a (provider, providerId)
* identity, NOT as an email address. Lookup therefore happens against the
* user_oauth_identities table. Binding an OAuth identity to an existing
* account only happens through the authenticated link flow (linkOAuthIdentity),
* never implicitly by email match — that implicit bind was the account-takeover
* vector this method previously had.
*/
private async findOrCreateOAuthUser(
provider: OAuthProvider,
oauthUserInfo: OAuthUserInfo
): Promise<schema.User> {
// Fail closed unless the provider asserts the email is verified.
if (oauthUserInfo.emailVerified !== true) {
throw new SecurityError(
SecurityErrorType.UNAUTHORIZED,
'OAuth provider did not verify the email address',
401
);
}
const email = oauthUserInfo.email.toLowerCase();
// 1. Identity-first lookup: match by (provider, providerId).
const identity = await this.database
.select()
.from(schema.userOauthIdentities)
.where(
and(
eq(schema.userOauthIdentities.provider, provider),
eq(schema.userOauthIdentities.providerId, oauthUserInfo.id)
)
)
.get();
if (identity) {
const now = new Date();
// Refresh the identity's cached email/verification.
await this.database
.update(schema.userOauthIdentities)
.set({ email, emailVerified: true, updatedAt: now })
.where(eq(schema.userOauthIdentities.id, identity.id));
// Refresh profile fields on the user, but never the primary
// provider/providerId binding.
await this.database
.update(schema.users)
.set({
displayName: oauthUserInfo.name || undefined,
avatarUrl: oauthUserInfo.picture || undefined,
updatedAt: now
})
.where(eq(schema.users.id, identity.userId));
const user = await this.database
.select()
.from(schema.users)
.where(eq(schema.users.id, identity.userId))
.get();
if (!user) {
throw new SecurityError(
SecurityErrorType.UNAUTHORIZED,
'OAuth authentication failed',
500
);
}
return user;
}
// 2. No identity match. If a user already exists with this email (local
// signup or a different provider), refuse to silently take it over.
const emailRow = await this.database
.select()
.from(schema.users)
.where(eq(schema.users.email, email))
.get();
if (emailRow) {
throw new SecurityError(
SecurityErrorType.CONFLICT,
'An account with this email already exists. Sign in with your existing method, then link this provider from settings.',
409
);
}
// 3. Brand-new identity: create the user and its first identity row.
return this.createOAuthUser(provider, oauthUserInfo);
}
/**
* Create a new user from a verified OAuth identity, writing both the users
* row (primary identity, for display/back-compat) and its user_oauth_identities row.
*/
private async createOAuthUser(
provider: OAuthProvider,
oauthUserInfo: OAuthUserInfo
): Promise<schema.User> {
const userId = generateId();
const now = new Date();
const email = oauthUserInfo.email.toLowerCase();
await this.database.insert(schema.users).values({
id: userId,
email,
displayName: oauthUserInfo.name || email.split('@')[0],
avatarUrl: oauthUserInfo.picture,
emailVerified: true,
provider,
providerId: oauthUserInfo.id,
createdAt: now,
updatedAt: now
});
await this.database.insert(schema.userOauthIdentities).values({
id: generateId(),
userId,
provider,
providerId: oauthUserInfo.id,
email,
emailVerified: true,
createdAt: now,
updatedAt: now
});
const user = await this.database
.select()
.from(schema.users)
.where(eq(schema.users.id, userId))
.get();
return user!;
}
/**
* Complete an authenticated account-link callback: validate the state, verify
* it is bound to the acting user, and attach the (provider, providerId) identity.
*/
async completeOAuthLink(
provider: OAuthProvider,
code: string,
state: string,
request: Request,
sessionUserId: string
): Promise<{ userId: string; provider: OAuthProvider; redirectUrl?: string }> {
const oauthProvider = await this.getOauthProvider(provider, request);
if (!oauthProvider) {
throw new SecurityError(
SecurityErrorType.INVALID_INPUT,
`OAuth provider ${provider} not configured`,
400
);
}
const oauthState = await this.validateAndConsumeOAuthState(provider, state, request);
// The state must have been created by (and for) the acting session's user.
if (!oauthState.userId || oauthState.userId !== sessionUserId) {
throw new SecurityError(
SecurityErrorType.CSRF_VIOLATION,
'Invalid account-link state',
403
);
}
const tokens = await oauthProvider.exchangeCodeForTokens(
code,
oauthState.codeVerifier || undefined
);
const oauthUserInfo = await oauthProvider.getUserInfo(tokens.accessToken);
await this.linkOAuthIdentity(oauthState.userId, provider, oauthUserInfo);
return {
userId: oauthState.userId,
provider,
redirectUrl: oauthState.redirectUri || undefined
};
}
/**
* Attach a verified OAuth identity to an existing user. Rejects if the identity
* is already bound to a different user.
*/
async linkOAuthIdentity(
userId: string,
provider: OAuthProvider,
oauthUserInfo: OAuthUserInfo
): Promise<void> {
if (oauthUserInfo.emailVerified !== true) {
throw new SecurityError(
SecurityErrorType.UNAUTHORIZED,
'OAuth provider did not verify the email address',
401
);
}
const email = oauthUserInfo.email.toLowerCase();
const now = new Date();
const existing = await this.database
.select()
.from(schema.userOauthIdentities)
.where(
and(
eq(schema.userOauthIdentities.provider, provider),
eq(schema.userOauthIdentities.providerId, oauthUserInfo.id)
)
)
.get();
if (existing) {
if (existing.userId !== userId) {
throw new SecurityError(
SecurityErrorType.CONFLICT,
'This provider account is already linked to another user.',
409
);
}
// Already linked to this user; just refresh the cached email.
await this.database
.update(schema.userOauthIdentities)
.set({ email, emailVerified: true, updatedAt: now })
.where(eq(schema.userOauthIdentities.id, existing.id));
return;
}
await this.database.insert(schema.userOauthIdentities).values({
id: generateId(),
userId,
provider,
providerId: oauthUserInfo.id,
email,
emailVerified: true,
createdAt: now,
updatedAt: now
});
logger.info('OAuth identity linked', { userId, provider });
}
/**
* List the OAuth identities linked to a user.
*/
async getUserIdentities(userId: string): Promise<schema.UserOauthIdentity[]> {
return this.database
.select()
.from(schema.userOauthIdentities)
.where(eq(schema.userOauthIdentities.userId, userId))
.all();
}
/**
* Remove a linked OAuth identity. Refuses to remove the user's only remaining
* login method (must keep at least one identity or a password).
*/
async unlinkOAuthIdentity(userId: string, provider: OAuthProvider): Promise<void> {
const identities = await this.getUserIdentities(userId);
const target = identities.find((i) => i.provider === provider);
if (!target) {
throw new SecurityError(
SecurityErrorType.INVALID_INPUT,
'No linked identity found for this provider.',
404
);
}
const user = await this.database
.select()
.from(schema.users)
.where(eq(schema.users.id, userId))
.get();
const hasPassword = !!user?.passwordHash;
const remainingIdentities = identities.length - 1;
if (remainingIdentities < 1 && !hasPassword) {
throw new SecurityError(
SecurityErrorType.INVALID_INPUT,
'Cannot remove your only login method.',
400
);
}
await this.database
.delete(schema.userOauthIdentities)
.where(eq(schema.userOauthIdentities.id, target.id));
// If the removed identity was the primary one on the users row, repoint the
// primary to another remaining identity so display/back-compat stays coherent.
if (user && user.provider === provider) {
const next = identities.find((i) => i.provider !== provider);
if (next) {
await this.database
.update(schema.users)
.set({ provider: next.provider, providerId: next.providerId, updatedAt: new Date() })
.where(eq(schema.users.id, userId));
}
}
logger.info('OAuth identity unlinked', { userId, provider });
}
/**
* Log authentication attempt
*/
private async logAuthAttempt(
identifier: string,
attemptType: string,
success: boolean,
request: Request
): Promise<void> {
try {
const requestMetadata = extractRequestMetadata(request);
await this.database.insert(schema.authAttempts).values({
identifier: identifier.toLowerCase(),
attemptType: attemptType as 'login' | 'register' | 'oauth_google' | 'oauth_github' | 'oauth_cloudflare' | 'refresh' | 'reset_password',
success: success,
ipAddress: requestMetadata.ipAddress
});
} catch (error) {
logger.error('Failed to log auth attempt', error);
}
}
/**
* Generate and store verification OTP for email
*/
private async generateAndStoreVerificationOtp(email: string): Promise<void> {
const otp = Math.floor(100000 + Math.random() * 900000).toString(); // 6-digit OTP
const expiresAt = new Date(Date.now() + 15 * 60 * 1000); // 15 minutes expiry
// Store OTP in database (you may need to create a verification_otps table)
await this.database.insert(schema.verificationOtps).values({
id: generateId(),
email: email.toLowerCase(),
otp: await this.passwordService.hash(otp), // Hash the OTP for security
expiresAt,
createdAt: new Date()
});
// TODO: Send email with OTP (integrate with email service)
logger.info('Verification OTP generated', { email, otp: otp.slice(0, 2) + '****' });
}
/**
* Verify email with OTP
*/
async verifyEmailWithOtp(email: string, otp: string, request: Request): Promise<AuthResult> {
try {
// Deployment-level admission gate (ALLOWED_EMAIL)
enforceAllowedEmail(this.env, email, 'login');
// Find valid OTP
const storedOtp = await this.database
.select()
.from(schema.verificationOtps)
.where(
and(
eq(schema.verificationOtps.email, email.toLowerCase()),
eq(schema.verificationOtps.used, false),
sql`${schema.verificationOtps.expiresAt} > ${new Date()}`
)
)
.orderBy(sql`${schema.verificationOtps.createdAt} DESC`)
.get();
if (!storedOtp) {
throw new SecurityError(
SecurityErrorType.INVALID_INPUT,
'Invalid or expired verification code',
400
);
}
// Verify OTP
const otpValid = await this.passwordService.verify(otp, storedOtp.otp);
if (!otpValid) {
throw new SecurityError(
SecurityErrorType.INVALID_INPUT,
'Invalid verification code',
400
);
}
// Mark OTP as used
await this.database
.update(schema.verificationOtps)
.set({ used: true, usedAt: new Date() })
.where(eq(schema.verificationOtps.id, storedOtp.id));
// Find and verify the user
const user = await this.database
.select()
.from(schema.users)
.where(eq(schema.users.email, email.toLowerCase()))
.get();
if (!user) {
throw new SecurityError(
SecurityErrorType.INVALID_INPUT,
'User not found',
404
);
}
// Update user as verified
await this.database
.update(schema.users)
.set({ emailVerified: true, updatedAt: new Date() })
.where(eq(schema.users.id, user.id));
// Create session for verified user
const { accessToken, session } = await this.sessionService.createSession(
user.id,
request
);
// Log successful verification
await this.logAuthAttempt(email, 'email_verification', true, request);
logger.info('Email verified successfully', { email, userId: user.id });
return {
user: mapUserResponse({ ...user, emailVerified: true }),
accessToken,
sessionId: session.sessionId,
expiresAt: session.expiresAt,
};
} catch (error) {
await this.logAuthAttempt(email, 'email_verification', false, request);
if (error instanceof SecurityError) {
throw error;
}
logger.error('Email verification error', error);
throw new SecurityError(
SecurityErrorType.INVALID_INPUT,
'Email verification failed',
500
);
}
}
/**
* Get user for authentication (for middleware)
*/
async getUserForAuth(userId: string): Promise<AuthUser | null> {
try {
const user = await this.database
.select({
id: schema.users.id,
email: schema.users.email,
displayName: schema.users.displayName,
username: schema.users.username,
avatarUrl: schema.users.avatarUrl,
bio: schema.users.bio,