-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathauth.ts
More file actions
1323 lines (1206 loc) · 56 KB
/
Copy pathauth.ts
File metadata and controls
1323 lines (1206 loc) · 56 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
import {
ClientConfiguration,
ClientConfigurationInternal,
DeviceApprovalChannel,
DeviceVerificationMethods,
KeeperError,
LoginError,
TwoFactorChannelData
} from './configuration'
import {KeeperEndpoint, KeeperEnvironment} from "./endpoint";
import {KeyWrapper, platform} from "./platform";
import {
generateEncryptionKey,
generateUidBytes,
normal64,
normal64Bytes,
resolvablePromise,
webSafe64FromBytes,
wrapPassword
} from "./utils";
import {
accountSummaryMessage,
getEnterprisePublicKeyMessage,
logoutV3Message,
NN,
requestCreateUserMessage,
requestDeviceAdminApprovalMessage,
requestDeviceVerificationMessage,
RestActionMessage,
RestInMessage,
RestMessage,
RestOutMessage,
ssoServiceProviderRequestMessage,
startLoginMessage,
startLoginMessageFromSessionToken,
twoFactorSend2FAPushMessage,
twoFactorValidateMessage,
twoFASendDuoMessage,
validateAuthHashMessage,
validateDeviceVerificationCodeMessage
} from './restMessages'
import {AccountSummary, Authentication} from './proto';
import {RestCommand} from './commands'
import {CloseReason, createAsyncSocket, SocketListener} from './socket';
import IStartLoginRequest = Authentication.IStartLoginRequest;
import ITwoFactorSendPushRequest = Authentication.ITwoFactorSendPushRequest;
import TwoFactorExpiration = Authentication.TwoFactorExpiration;
import TwoFactorPushType = Authentication.TwoFactorPushType;
import TwoFactorChannelType = Authentication.TwoFactorChannelType;
import ISsoServiceProviderRequest = Authentication.ISsoServiceProviderRequest;
import LoginType = Authentication.LoginType;
import LoginMethod = Authentication.LoginMethod;
import IAccountSummaryElements = AccountSummary.IAccountSummaryElements;
function unifyLoginError(e: any): LoginError {
if (e instanceof Error) {
try {
return JSON.parse(e.message);
} catch (jsonError) {
return {
error: "unknown",
message: e.message
}
}
} else {
return {
error: e.result_code,
message: e.result_code
}
}
}
export type LoginPayload = {
username: string,
password?: string | KeyWrapper,
loginToken?: Uint8Array
loginType: Authentication.LoginType | null
loginMethod?: Authentication.LoginMethod,
v2TwoFactorToken?: string
resumeSessionOnly?: boolean
givenSessionToken?: string
ecOnly?: boolean
fromSessionToken?: Uint8Array | null
}
export enum UserType {
normal = "normal",
onsiteSso = "onsite_sso",
cloudSso = "cloud_sso"
}
export type SessionParams = {
accountUid: Uint8Array
username: string
sessionToken: string
sessionTokenType: Authentication.SessionTokenType
dataKey: Uint8Array
privateKey: Uint8Array
eccPrivateKey?: Uint8Array
eccPublicKey?: Uint8Array
enterprisePublicKey?: Uint8Array
enterpriseEccPublicKey?: Uint8Array
clientKey: Uint8Array
userType: UserType
ssoLogoutUrl: string
ssoSessionId: string
messageSessionUid: Uint8Array
}
export type EncryptionKeys = {
dataKey: Uint8Array;
privateKey?: Uint8Array;
eccPrivateKey: Uint8Array;
}
export class Auth {
ssoLogoutUrl: string = ''
userType: UserType = UserType.normal
ssoSessionId: string = ''
dataKey?: Uint8Array;
privateKey?: Uint8Array;
eccPrivateKey?: Uint8Array;
eccPublicKey?: Uint8Array;
enterprisePublicKey?: Uint8Array;
enterpriseEccPublicKey?: Uint8Array;
private _accountUid?: Uint8Array;
private _sessionToken: string = '';
private _sessionTokenType?: Authentication.SessionTokenType;
private _username: string = '';
private endpoint: KeeperEndpoint;
private managedCompanyId?: number;
private messageSessionUid: Uint8Array;
options: ClientConfigurationInternal;
private socket?: SocketListener;
public clientKey?: Uint8Array;
private _accountSummary?: IAccountSummaryElements;
private _accountSummaryVersion: number = 1
constructor(options: ClientConfiguration) {
if (options.deviceConfig && options.deviceToken) {
throw new Error('Both loginV2 and loginV3 token strategies supplied')
}
this.options = options as ClientConfigurationInternal
if (!this.options.deviceConfig) {
this.options.deviceConfig = { }
}
if (!this.options.sessionStorage) {
this.options.sessionStorage = {
lastUsername: undefined,
getCloneCode: () => Promise.resolve(null),
saveCloneCode: () => new Promise((res, rej) => {}),
getSessionParameters: () => Promise.resolve(null),
saveSessionParameters: () => Promise.resolve()
}
}
this.endpoint = new KeeperEndpoint(this.options);
this.endpoint.clientVersion = this.options.clientVersion || "c14.0.0";
this.messageSessionUid = generateUidBytes()
}
get _endpoint(): KeeperEndpoint {
return this.endpoint;
}
get accountUid(): Uint8Array | undefined {
return this._accountUid;
}
get clientVersion(): string {
return this.endpoint.clientVersion;
}
get sessionToken(): string {
return this._sessionToken;
}
get sessionTokenType(): Authentication.SessionTokenType | undefined {
return this._sessionTokenType
}
get username(): string {
return this._username;
}
getMessageSessionUid(): Uint8Array {
return this.messageSessionUid;
}
get accountSummary(): IAccountSummaryElements | null {
return this._accountSummary || null
}
async idpLogout() {
if (!this.options.authUI3?.idpLogout) {
throw Error('authUI3 is not configured')
}
if (this.userType == UserType.cloudSso) {
const payload = await this.endpoint.prepareSsoPayload(this.messageSessionUid, this.username, this.ssoSessionId)
const params = new URLSearchParams({
'payload': payload,
})
const url = `${this.ssoLogoutUrl}?${String(params)}`
try {
await this.options.authUI3.idpLogout(url);
} catch (e) {
console.log('Logout errored out: ' + e)
}
} else if (this.userType == UserType.onsiteSso) {
const params = new URLSearchParams({
'embedded': 'true',
'username': this.username,
'session_id': this.ssoSessionId,
'dest': 'vault'
})
const url = `${this.ssoLogoutUrl}?${String(params)}`
try {
await this.options.authUI3.idpLogout(url);
} catch (e) {
console.log('Logout errored out: ' + e)
}
}
}
async logout() {
platform.unloadKeys()
await this.executeRestAction(logoutV3Message())
await this.idpLogout()
this._sessionToken = ''
}
async connect() {
// When connecting to govcloud, remove the govcloud subdomain. There is no list of urls that do/don't require the govcloud subdomain, so for now do this.
const url = `wss://push.services.${this.options.host.replace('govcloud.', '')}/wss_open_connection`
const getConnectionRequest = (messageSessionUid) => this.endpoint.getPushConnectionRequest(messageSessionUid)
this.socket = await createAsyncSocket(url, this.messageSessionUid, getConnectionRequest)
console.log("Socket connected")
this.onCloseMessage((closeReason: CloseReason) => {
if (this.options.onCommandFailure) {
this.options.onCommandFailure({
result_code: closeReason.code.toString(),
message: closeReason.reason.close_reason
})
}
})
}
disconnect() {
if (this.socket) {
this.socket.disconnect()
delete this.socket
}
}
/**
* useAlternate is to pass to the next function to use an alternate method, for testing a different path.
*/
async loginV3(
{
username = '',
password = undefined,
loginToken = undefined,
loginType = Authentication.LoginType.NORMAL,
loginMethod = Authentication.LoginMethod.EXISTING_ACCOUNT,
v2TwoFactorToken = undefined,
resumeSessionOnly = false,
givenSessionToken = undefined,
ecOnly = false,
fromSessionToken = undefined
}: Partial<LoginPayload>
) {
this._username = username || this.options.sessionStorage?.lastUsername || ''
let wrappedPassword: KeyWrapper | undefined;
if (password) {
if (typeof password === 'string') {
wrappedPassword = wrapPassword(password)
}
else
wrappedPassword = password
}
let needUserName = false
const handleError = (resultCode: string, loginResponse: NN<Authentication.ILoginResponse>, error: KeeperError) => {
const errorMessage = chooseErrorMessage(loginResponse.loginState)
if (this.options.onCommandFailure) {
this.options.onCommandFailure({
result_code: resultCode,
message: errorMessage,
error: error.message,
})
} else {
throw error;
}
};
while (true) {
if (!this.options.deviceConfig.deviceToken) {
await this.endpoint.registerDevice()
}
if (!this.socket || !this.socket.getIsConnected()) {
await this.connect()
}
const startLoginRequest = new Authentication.StartLoginRequest({
clientVersion: this.endpoint.clientVersion,
encryptedDeviceToken: this.options.deviceConfig.deviceToken ?? null,
messageSessionUid: this.messageSessionUid,
loginMethod: loginMethod,
cloneCode: await this.options.sessionStorage?.getCloneCode(this.options.host as KeeperEnvironment, this._username),
v2TwoFactorToken: v2TwoFactorToken,
fromSessionToken,
})
if (loginType !== LoginType.NORMAL && !!loginType) {
startLoginRequest.loginType = loginType
}
if (loginToken) {
startLoginRequest.encryptedLoginToken = loginToken
}
if (needUserName || !this.options.useSessionResumption || loginType === LoginType.ALTERNATE || username) {
startLoginRequest.username = this._username
needUserName = false
}
console.log(startLoginRequest)
var loginResponse: NN<Authentication.ILoginResponse>;
if (givenSessionToken){
this._sessionToken = givenSessionToken
try{
loginResponse = await this.executeRest(startLoginMessageFromSessionToken(startLoginRequest))
} catch(e: any){
console.error('Fails session token login. failed_login_from_existing_session_token')
throw(e)
}
} else {
loginResponse = await this.executeRest(startLoginMessage(startLoginRequest))
}
if (loginResponse.cloneCode && loginResponse.cloneCode.length > 0) {
this.options.sessionStorage?.saveCloneCode(this.options.host as KeeperEnvironment, this._username, loginResponse.cloneCode)
}
if (resumeSessionOnly && loginResponse && (loginResponse.loginState != Authentication.LoginState.LOGGED_IN)) {
return {
result: 'notLoggedin'
}
}
console.log(loginResponse)
console.log("login state =", loginResponse.loginState);
switch (loginResponse.loginState) {
case Authentication.LoginState.ACCOUNT_LOCKED:
case Authentication.LoginState.INVALID_LOGINSTATE:
case Authentication.LoginState.LOGGED_OUT:
case Authentication.LoginState.AFTER_CLOUD_SSO_LOGIN:
case Authentication.LoginState.LOGIN_TOKEN_EXPIRED:
case Authentication.LoginState.DEVICE_ACCOUNT_LOCKED:
case Authentication.LoginState.DEVICE_LOCKED:
handleError('generic_error', loginResponse, new Error(`Unable to login, login state = ${loginResponse.loginState}`))
return
case Authentication.LoginState.REQUIRES_ACCOUNT_CREATION:
if (this.userType === UserType.cloudSso) {
await this.createSsoUser(loginResponse.encryptedLoginToken)
} else {
if (!wrappedPassword) {
throw Error('Password must be assigned before user creation')
}
await this.createUser(this._username, wrappedPassword, ecOnly)
}
break;
case Authentication.LoginState.UPGRADE:
handleError('generic_error', loginResponse, new Error(`Unable to login, login state = ${loginResponse.loginState}`))
return;
case Authentication.LoginState.REQUIRES_USERNAME:
if (!this._username) {
handleError('generic_error', loginResponse, new Error(`No username supplied, login state = ${loginResponse.loginState}`));
return
}
needUserName = true
break;
case Authentication.LoginState.DEVICE_APPROVAL_REQUIRED:
case Authentication.LoginState.REQUIRES_DEVICE_ENCRYPTED_DATA_KEY:
if (givenSessionToken) return { result: 'notLoggedin' }
try {
loginToken = await this.verifyDevice(username, loginResponse.encryptedLoginToken, loginResponse.loginState == Authentication.LoginState.REQUIRES_DEVICE_ENCRYPTED_DATA_KEY)
} catch (e: any) {
handleError('auth_failed', loginResponse, e)
return
}
break;
case Authentication.LoginState.LICENSE_EXPIRED:
handleError('license_expired', loginResponse, new Error(loginResponse.message))
return;
case Authentication.LoginState.REGION_REDIRECT:
// TODO: put region_redirect in its own loop since
// its unique to the other states.
this.options.host = loginResponse.stateSpecificValue
loginToken = undefined
if (this.options.onRegionChanged) {
await this.options.onRegionChanged(loginResponse.stateSpecificValue)
}
// Current socket no longer pointing to the right region
this.disconnect()
break;
case Authentication.LoginState.REDIRECT_CLOUD_SSO:
console.log("Cloud SSO Connect login");
this.ssoLogoutUrl = loginResponse.url.replace('login', 'logout')
this.userType = UserType.cloudSso
let payload = await this._endpoint.prepareSsoPayload(this.messageSessionUid)
let cloudSsoLoginUrl = loginResponse.url + "?payload=" + payload;
if (this.options.authUI3?.redirectCallback) {
await this.options.authUI3.redirectCallback(cloudSsoLoginUrl)
return
} else if (this.options.authUI3?.ssoLogin) {
const token = await this.options.authUI3.ssoLogin(cloudSsoLoginUrl)
const cloudResp = await this.endpoint.decryptCloudSsoResponse(token)
console.log(cloudResp)
this._username = cloudResp.email
loginToken = cloudResp.encryptedLoginToken
loginMethod = LoginMethod.AFTER_SSO
}
break;
case Authentication.LoginState.REDIRECT_ONSITE_SSO:
console.log("SSO Connect login");
this.ssoLogoutUrl = loginResponse.url.replace('login', 'logout')
this.userType = UserType.onsiteSso
let onsitePublicKey = await this._endpoint.getOnsitePublicKey(ecOnly)
let onsiteSsoLoginUrl = loginResponse.url + '?embedded&key=' + onsitePublicKey
if (this.options.authUI3?.redirectCallback) {
await this.options.authUI3.redirectCallback(onsiteSsoLoginUrl)
return
} else if (this.options.authUI3?.ssoLogin) {
const onsiteResp = await this.options.authUI3.ssoLogin(onsiteSsoLoginUrl)
console.log(onsiteResp)
this._username = onsiteResp.email
wrappedPassword = wrapPassword(onsiteResp.password)
loginType = LoginType.SSO
loginMethod = LoginMethod.AFTER_SSO
}
break;
case Authentication.LoginState.REQUIRES_2FA:
try{
loginToken = await this.handleTwoFactor(loginResponse)
} catch(e: any){
if (e?.message && e.message == 'push_declined'){
handleError(e.message, loginResponse, e)
}
}
break
case Authentication.LoginState.REQUIRES_AUTH_HASH:
// TODO: loop in authHashLogin until successful or get into
// some other state other than Authentication.LoginState.REQUIRES_AUTH_HASH
if (!wrappedPassword && this.options.authUI3?.getPassword) {
password = await this.options.authUI3.getPassword(loginType === LoginType.ALTERNATE)
if (password) {
if (typeof password === 'string') {
wrappedPassword = wrapPassword(password)
}
else
wrappedPassword = password
}
}
if (!wrappedPassword) {
throw new Error('User password required and not provided')
}
try {
await this.authHashLogin(loginResponse, username, wrappedPassword, loginType === LoginType.ALTERNATE)
return;
} catch (e: any) {
wrappedPassword = undefined
handleError('auth_failed', loginResponse, e)
const error = e as Error
if (error.cause?.message === 'No alternate master password found') {
return;
}
break;
}
case Authentication.LoginState.LOGGED_IN:
try {
await this.loginSuccess(loginResponse, undefined)
console.log("Exiting on loginState = LOGGED_IN");
return;
} catch (e) {
console.log('Error in Authentication.LoginState.LOGGED_IN: ', e)
return;
}
default:
handleError('generic_error', loginResponse, new Error(`Unknown login state ${loginResponse.loginState}`))
return
}
}
}
/**
* The MV3 browser extension runs in a service worker that shuts down every 5 minutes.
* This rehydrates the Auth class and re-opens our socket with the session parameters.
*/
async continueSession() {
if (!this.options.sessionStorage) {
throw new Error('Missing configuration option to get session parameters')
}
const sessionParams = await this.options.sessionStorage.getSessionParameters()
if (!sessionParams) {
throw new Error('No session to resume')
}
this.messageSessionUid = sessionParams.messageSessionUid
this._username = sessionParams.username
this.dataKey = sessionParams.dataKey
this.clientKey = sessionParams.clientKey
this.privateKey = sessionParams.privateKey
this.eccPrivateKey = sessionParams.eccPrivateKey
this.eccPublicKey = sessionParams.eccPublicKey
this.enterprisePublicKey = sessionParams.enterprisePublicKey
this.enterpriseEccPublicKey = sessionParams.enterpriseEccPublicKey
this.ssoLogoutUrl = sessionParams.ssoLogoutUrl
this.ssoSessionId = sessionParams.ssoSessionId
this.userType = sessionParams.userType
if (!this.socket || !this.socket.getIsConnected()) {
await this.connect()
}
this.setLoginParameters(sessionParams.sessionToken, sessionParams.sessionTokenType, sessionParams.accountUid)
}
private getSessionParameters(): Partial<SessionParams> {
return {
accountUid: this._accountUid,
username: this._username,
sessionToken: this._sessionToken,
sessionTokenType: this._sessionTokenType,
dataKey: this.dataKey,
privateKey: this.privateKey,
eccPrivateKey: this.eccPrivateKey,
eccPublicKey: this.eccPublicKey,
enterprisePublicKey: this.enterprisePublicKey,
enterpriseEccPublicKey: this.enterpriseEccPublicKey,
clientKey: this.clientKey,
userType: this.userType,
ssoLogoutUrl: this.ssoLogoutUrl,
ssoSessionId: this.ssoSessionId,
messageSessionUid: this.messageSessionUid
}
}
async getSsoProvider(ssoDomain: string, locale?: string, ecOnly = false) {
let domainRequest: ISsoServiceProviderRequest = {
name: ssoDomain.trim(),
locale: locale,
clientVersion: this.endpoint.clientVersion,
}
const domainResponse = await this.executeRest(ssoServiceProviderRequestMessage(domainRequest))
const params = domainResponse.isCloud
? '?payload=' + await this._endpoint.prepareSsoPayload(this.messageSessionUid)
: '?embedded&key=' + await this._endpoint.getOnsitePublicKey(ecOnly)
this.userType = domainResponse.isCloud ? UserType.cloudSso : UserType.onsiteSso
this.ssoLogoutUrl = domainResponse.spUrl.replace('login', 'logout')
return {
url: domainResponse.spUrl + params,
name: domainResponse.name,
}
}
verifyDevice(username: string, loginToken: Uint8Array, isCloud: boolean = false): Promise<Uint8Array> {
return new Promise<Uint8Array>((resolve, reject) => {
if (!this.options.authUI3) {
reject(new Error('No authUI3 provided. authUI3 required to verify devices'))
return
}
let emailSent = false
let tfaExpiration = TwoFactorExpiration.TWO_FA_EXP_IMMEDIATELY
const deviceConfig = this.options.deviceConfig
let channels: DeviceApprovalChannel[]
if (!isCloud) {
channels = [
{
channel: DeviceVerificationMethods.Email,
sendApprovalRequest: async () => {
await this.executeRestAction(requestDeviceVerificationMessage({
username: username,
verificationChannel: emailSent ? 'email_resend' : 'email',
encryptedDeviceToken: deviceConfig.deviceToken,
clientVersion: this.endpoint.clientVersion,
messageSessionUid: this.messageSessionUid
}))
emailSent = true
},
validateCode: async (code) => {
await this.executeRestAction(validateDeviceVerificationCodeMessage({
verificationCode: code,
username: username,
}))
resumeWithToken(loginToken)
}
},
{
channel: DeviceVerificationMethods.KeeperPush,
sendApprovalRequest: async () => {
await this.executeRestAction(twoFactorSend2FAPushMessage({
encryptedLoginToken: loginToken,
pushType: TwoFactorPushType.TWO_FA_PUSH_KEEPER
}))
}
},
{
channel: DeviceVerificationMethods.TFA,
sendApprovalRequest: async () => {
await this.executeRestAction(twoFactorSend2FAPushMessage({
encryptedLoginToken: loginToken,
}))
},
validateCode: async (code) => {
const twoFactorValidateMsg = twoFactorValidateMessage({
encryptedLoginToken: loginToken,
value: code,
expireIn: tfaExpiration
})
const twoFactorValidateResp = await this.executeRest(twoFactorValidateMsg)
if (twoFactorValidateResp.encryptedLoginToken) {
const wssRs: Record<string, any> = {
event: 'received_totp',
encryptedLoginToken: platform.bytesToBase64(twoFactorValidateResp.encryptedLoginToken)
}
processPushNotification(wssRs)
}
},
setExpiration: expiration => {
tfaExpiration = expiration
}
}
];
} else {
channels = [
{
channel: DeviceVerificationMethods.KeeperPush,
sendApprovalRequest: async () => {
await this.executeRestAction(twoFactorSend2FAPushMessage({
encryptedLoginToken: loginToken,
pushType: TwoFactorPushType.TWO_FA_PUSH_KEEPER
}))
}
},
{
channel: DeviceVerificationMethods.AdminApproval,
sendApprovalRequest: async () => {
await this.executeRestAction(requestDeviceAdminApprovalMessage({
username: username,
verificationChannel: emailSent ? 'email_resend' : 'email',
encryptedDeviceToken: deviceConfig.deviceToken,
clientVersion: this.endpoint.clientVersion,
messageSessionUid: this.messageSessionUid
}))
}
}
]
}
let done = false
const resumeWithToken = (token: Uint8Array) => {
done = true
resolve(token)
}
const rejectWithError = (error: Error) => {
done = true
reject(error)
}
const processPushNotification = (wssRs: Record<string, any>) => {
if (wssRs.event === 'received_totp') {
// Duo
if (wssRs.encryptedLoginToken) {
const token = normal64Bytes(wssRs.encryptedLoginToken)
resumeWithToken(token)
}
// DNA
else if (wssRs.passcode) {
const tfaChannel = channels.find(x => x.channel === DeviceVerificationMethods.TFA)
if (tfaChannel && tfaChannel.validateCode) {
tfaChannel.validateCode(wssRs.passcode)
}
} else {
// do nothing, we don't leak rejection during device approvals
}
} else if (wssRs.message === 'device_approved') {
if (wssRs.approved) {
resumeWithToken(loginToken)
} else {
rejectWithError(new Error('Rejected'))
}
} else if (wssRs.command === 'device_verified') {
if (this.options.onDeviceVerified) {
this.options.onDeviceVerified(true)
}
resumeWithToken(loginToken)
}
}
// response from the client true - try again, false - cancel
this.options.authUI3.waitForDeviceApproval(channels, isCloud)
.then((ok) => {
if (ok) {
resumeWithToken(loginToken)
} else {
rejectWithError(new Error('Canceled'))
}
})
.catch(reason => rejectWithError(reason))
// receive push notification
;(async () => {
if (!this.socket) {
return
}
while (!done) {
const pushMessage = await this.socket.getPushMessage()
const wssClientResponse = await this.endpoint.decryptPushMessage(pushMessage)
if (!done) {
const wssRs = JSON.parse(wssClientResponse.message)
console.log(wssRs)
processPushNotification(wssRs)
}
}
})();
})
}
private handleTwoFactor(loginResponse: Authentication.ILoginResponse): Promise<Uint8Array> {
return new Promise<Uint8Array>((resolve, reject) => {
const responseChannels = loginResponse.channels
if (!responseChannels) {
reject(new Error('Channels not provided by API'))
return
}
const loginToken = loginResponse.encryptedLoginToken
if (!loginToken) {
reject(new Error('Login token not provided by API'))
return
}
let done = false
let twoFactorWaitCancel = resolvablePromise();
const resumeWithToken = (token: Uint8Array) => {
done = true
twoFactorWaitCancel.resolve()
resolve(token)
}
const rejectWithError = (error: Error) => {
done = true
twoFactorWaitCancel.resolve()
reject(error)
}
let tfaExpiration = TwoFactorExpiration.TWO_FA_EXP_IMMEDIATELY
const submitCode = async (channel: Authentication.TwoFactorChannelType, code: string) => {
const channelInfo = responseChannels.find(x => x.channelType === channel)
let valueType: Authentication.TwoFactorValueType | undefined
switch (channelInfo?.channelType) {
case Authentication.TwoFactorChannelType.TWO_FA_CT_DNA:
valueType = Authentication.TwoFactorValueType.TWO_FA_CODE_DNA
break
case Authentication.TwoFactorChannelType.TWO_FA_CT_DUO:
valueType = Authentication.TwoFactorValueType.TWO_FA_CODE_DUO
break
case Authentication.TwoFactorChannelType.TWO_FA_CT_SMS:
valueType = Authentication.TwoFactorValueType.TWO_FA_CODE_SMS
break
case Authentication.TwoFactorChannelType.TWO_FA_CT_TOTP:
valueType = Authentication.TwoFactorValueType.TWO_FA_CODE_TOTP
break
case Authentication.TwoFactorChannelType.TWO_FA_CT_RSA:
valueType = Authentication.TwoFactorValueType.TWO_FA_CODE_RSA
break
case Authentication.TwoFactorChannelType.TWO_FA_CT_U2F:
valueType = Authentication.TwoFactorValueType.TWO_FA_RESP_U2F
break
case Authentication.TwoFactorChannelType.TWO_FA_CT_WEBAUTHN:
valueType = Authentication.TwoFactorValueType.TWO_FA_RESP_WEBAUTHN
break
default:
valueType = undefined
break
}
const twoFactorValidateMsg = twoFactorValidateMessage({
channelUid: channelInfo ? channelInfo.channelUid : undefined,
encryptedLoginToken: loginToken,
value: code,
expireIn: tfaExpiration,
valueType: valueType,
})
const twoFactorValidateResp = await this.executeRest(twoFactorValidateMsg)
if (twoFactorValidateResp.encryptedLoginToken) {
resumeWithToken(twoFactorValidateResp.encryptedLoginToken)
}
}
let lastPushChannel = TwoFactorChannelType.TWO_FA_CT_NONE
const submitPush = async (channel: TwoFactorChannelType, pushType: TwoFactorPushType) => {
const sendPushRequest: ITwoFactorSendPushRequest = {
encryptedLoginToken: loginResponse.encryptedLoginToken,
pushType: pushType,
expireIn: tfaExpiration
}
if(channel === TwoFactorChannelType.TWO_FA_CT_DUO && [TwoFactorPushType.TWO_FA_PUSH_DUO_PUSH, TwoFactorPushType.TWO_FA_PUSH_DUO_CALL].includes(pushType)) {
const tfaValidateResponse = await this.executeRest(twoFASendDuoMessage(sendPushRequest))
resumeWithToken(tfaValidateResponse.encryptedLoginToken)
} else {
await this.executeRestAction(twoFactorSend2FAPushMessage(sendPushRequest))
}
lastPushChannel = channel
}
const channels: TwoFactorChannelData[] = responseChannels
.map((ch) => {
const tfachannelData: TwoFactorChannelData = {
channel: ch,
setExpiration: (exp) => {
tfaExpiration = exp
},
sendCode: async (code) => {
await submitCode(ch.channelType!, code)
}
}
switch (ch.channelType) {
case TwoFactorChannelType.TWO_FA_CT_U2F:
case TwoFactorChannelType.TWO_FA_CT_WEBAUTHN:
// add support for security key as push
break;
case TwoFactorChannelType.TWO_FA_CT_TOTP:
case TwoFactorChannelType.TWO_FA_CT_RSA:
break
case TwoFactorChannelType.TWO_FA_CT_SMS:
tfachannelData.availablePushes = [TwoFactorPushType.TWO_FA_PUSH_SMS]
break
case TwoFactorChannelType.TWO_FA_CT_DNA:
tfachannelData.availablePushes = [TwoFactorPushType.TWO_FA_PUSH_DNA]
break
case TwoFactorChannelType.TWO_FA_CT_KEEPER:
case TwoFactorChannelType.TWO_FA_CT_DUO:
if (ch.capabilities) {
tfachannelData.availablePushes = ch.capabilities
.map(cap => {
switch (cap) {
case 'push':
return TwoFactorPushType.TWO_FA_PUSH_DUO_PUSH
case 'sms':
return TwoFactorPushType.TWO_FA_PUSH_DUO_TEXT
case 'phone':
return TwoFactorPushType.TWO_FA_PUSH_DUO_CALL
default:
return undefined
}
}).filter(cap => !!cap).map(cap => cap!)
}
break
}
if (tfachannelData.availablePushes) {
tfachannelData.sendPush = async (pushType: TwoFactorPushType) => {
submitPush(ch.channelType!, pushType)
}
}
return tfachannelData
}).filter((chd: TwoFactorChannelData | undefined) => !!chd).map(chd => chd!)
const processPushNotification = (wssRs: Record<string, any>) => {
if (wssRs.event === 'received_totp') {
// Duo
if (wssRs.encryptedLoginToken) {
const token = normal64Bytes(wssRs.encryptedLoginToken)
resumeWithToken(token)
}
// DNA
else if (wssRs.passcode) {
(async () => {
await submitCode(lastPushChannel, wssRs.passcode)
})()
} else {
rejectWithError(new Error('push_declined'))
}
}
}
this.options.authUI3?.waitForTwoFactorCode(channels, twoFactorWaitCancel.promise)
.then(ok => {
if (ok) {
resumeWithToken(loginToken)
} else {
rejectWithError(new Error('Canceled'))
}
})
.catch(reason => rejectWithError(reason))
// receive push notification
;(async () => {
if (!this.socket) {
return
}
while (!done) {
const pushMessage = await this.socket.getPushMessage()
const wssClientResponse = await this.endpoint.decryptPushMessage(pushMessage)
if (!done) {
const wssRs = JSON.parse(wssClientResponse.message)
console.log(wssRs)
processPushNotification(wssRs)
}
}
})();
})
}
async authHashLogin(loginResponse: NN<Authentication.ILoginResponse>, username: string, password: KeyWrapper, useAlternate: boolean = false) {
// TODO test for account transfer and account recovery
const salt = useAlternate ? loginResponse.salt.find(s => s.name === 'alternate') : loginResponse.salt[0]
if (!salt?.salt || !salt?.iterations) {
const error = new Error('Salt missing from API response')
if (useAlternate && !salt) {
error.cause = Error('No alternate master password found')
}
throw error
}
this.options.salt = salt.salt
this.options.iterations = salt.iterations
const authHashKey = await platform.deriveKey(password, salt.salt, salt.iterations);
let authHash = await platform.calcAuthVerifier(authHashKey);
const loginMsg = validateAuthHashMessage({
authResponse: authHash,
encryptedLoginToken: loginResponse.encryptedLoginToken
})
const loginResp = await this.executeRest(loginMsg)
console.log(loginResp)
if (loginResp.cloneCode && loginResp.cloneCode.length > 0) {
await this.options.sessionStorage?.saveCloneCode(this.options.host as KeeperEnvironment, this._username, loginResp.cloneCode)
}
await this.loginSuccess(loginResp, password, salt)
}
async loginSuccess(loginResponse: NN<Authentication.ILoginResponse>, password?: KeyWrapper, salt: Authentication.ISalt | undefined = undefined) {
this._username = loginResponse.primaryUsername || this._username
this.setLoginParameters(webSafe64FromBytes(loginResponse.encryptedSessionToken), loginResponse.sessionTokenType ?? undefined, loginResponse.accountUid)
switch (loginResponse.encryptedDataKeyType) {
case Authentication.EncryptedDataKeyType.BY_DEVICE_PUBLIC_KEY:
if (!this.options.deviceConfig.privateKey) {
throw Error('Private key is missing from the device config')
}
this.dataKey = await platform.privateDecryptEC(loginResponse.encryptedDataKey, this.options.deviceConfig.privateKey, this.options.deviceConfig.publicKey)
break;
case Authentication.EncryptedDataKeyType.BY_PASSWORD:
if (!password) {
throw Error('Password is missing, unable to continue')
}
this.dataKey = await decryptEncryptionParams(password, loginResponse.encryptedDataKey);
break;
case Authentication.EncryptedDataKeyType.BY_ALTERNATE:
if (!password || !salt) {
throw Error('Password or salt is missing, unable to continue')
}
if (salt) {
const encKey = await platform.deriveKeyV2('data_key', password, salt.salt!, salt.iterations!)
this.dataKey = await platform.aesGcmDecrypt(loginResponse.encryptedDataKey, encKey)
}
break;
case Authentication.EncryptedDataKeyType.NO_KEY:
case Authentication.EncryptedDataKeyType.BY_BIO:
throw new Error(`Data Key type ${loginResponse.encryptedDataKeyType} decryption not implemented`)
}
await this.loadAccountSummary()
let encryptedPrivateKey: Uint8Array | undefined
let encryptedEccPrivateKey: Uint8Array | undefined
if (this.options.kvs) {
const encryptedPrivateKeyString = this.options.kvs.getValue(`${this._username}/private_key`)
if (encryptedPrivateKeyString) {
encryptedPrivateKey = platform.base64ToBytes(encryptedPrivateKeyString)