-
Notifications
You must be signed in to change notification settings - Fork 0
/
User.ts
731 lines (623 loc) · 24.6 KB
/
User.ts
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
import { Tokens } from "./Tokens";
import * as srp from "secure-remote-password/client";
import { bufferToBase64, hex2base64, base642hex, base64toByteArray, hexStringToByteArray, bufferToHex, utf8encode } from "./Utils";
import { JWT } from "./JWT";
import { RemoteService, isResponse } from "./RemoteService";
import { KeeError } from "./KeeError";
import { Claim } from "./Claim";
import { Response } from "superagent";
import { Pbkdf2HmacSha256 } from "./asmcrypto/entry-export_all";
let remoteService: RemoteService;
let tokenChangeHandler: (tokens: Tokens) => void;
export type Feature = string;
export class Features {
enabled: Feature[];
validUntil: number;
source: string;
subscriptionId?: string;
}
export class User {
private email: string;
private _emailHashed: string;
public get emailHashed (): string {
return this._emailHashed;
}
private _userId: string;
public get userId (): string {
return this._userId;
}
private salt: string;
private passKey: string;
private features: Features;
private _tokens: Tokens;
public get tokens (): Tokens {
return this._tokens;
}
private loginParameters?: { clientEphemeral: srp.Ephemeral, B: string, authId: string, nonce: string };
private _verificationStatus: AccountVerificationStatus = AccountVerificationStatus.Never;
public get verificationStatus (): AccountVerificationStatus {
return this._verificationStatus;
}
// hashedMasterKey may come from a combination of password and keyfile in future but for now, we require a text password
static async fromEmailAndKey (email: string, hashedMasterKey: ArrayBuffer) {
const user = new User();
user.email = email;
user.passKey = await user.derivePassKey(email, hashedMasterKey);
user._emailHashed = await hashString(email, EMAIL_ID_SALT);
return user;
}
static async fromEmail (email: string) {
const user = new User();
user.email = email;
user._emailHashed = await hashString(email, EMAIL_ID_SALT);
return user;
}
static async fromResetProcess (email: string, unverifiedJWTString: string, hashedMasterKey: ArrayBuffer,
sendResetConfirmation: (obj: object) => Promise<KeeError|Response>) {
if (!remoteService) {
return false;
}
if (!unverifiedJWTString) {
return false;
}
if (!email) {
console.error("Email missing. Can't complete reset procedure.");
return false;
}
const unverifiedJWT = JWT.parse(unverifiedJWTString);
if (!unverifiedJWT || !unverifiedJWT.sub) {
return false;
}
const user = new User();
user.email = email;
user.passKey = await user.derivePassKey(email, hashedMasterKey);
user._emailHashed = await hashString(email, EMAIL_ID_SALT);
// Mostly just a sanity check to ensure truncated links can't result in an invalid
// verifier being associated with the user's account
if (unverifiedJWT.sub !== user._emailHashed) {
console.error("Email mismatch. Can't complete reset procedure.");
return false;
}
const hexSalt = srp.generateSalt();
const salt = hex2base64(hexSalt);
user.salt = salt;
const privateKey = srp.derivePrivateKey(hexSalt, unverifiedJWT.sub, user.passKey);
const verifier = hex2base64(srp.deriveVerifier(privateKey));
try {
const response = await sendResetConfirmation({
verifier,
salt
});
if (!isResponse(response)) {
return false;
}
await user.parseJWTs(response.body.JWTs);
return user;
} catch (e) {
console.error(e);
return false;
}
}
public currentFeatures () {
return this.features ? this.features.enabled : [];
}
public setUserId (userId: string) {
this._userId = userId;
}
public async derivePassKey (email: string, hashedMasterKey: ArrayBuffer) {
const emailHash = await hashString(email, EMAIL_AUTH_SALT);
const passHash = await hashByteArray(new Uint8Array(hashedMasterKey), hexStringToByteArray(PASS_AUTH_SALT));
const b1 = base64toByteArray(emailHash);
const b2 = base64toByteArray(passHash);
const byteArray = new Uint8Array(b1.byteLength+b2.byteLength);
byteArray.set(b1);
byteArray.set(b2, b1.length);
return stretchByteArray(byteArray, STRETCH_SALT);
}
public async register (introEmailStatus: number, marketingEmailStatus: number, isMobile: boolean, code: string) {
if (!remoteService) {
return KeeError.InvalidState;
}
const hexSalt = srp.generateSalt();
const salt = hex2base64(hexSalt);
this.salt = salt;
const privateKey = srp.derivePrivateKey(hexSalt, this.emailHashed, this.passKey);
const verifier = hex2base64(srp.deriveVerifier(privateKey));
try {
const response = await remoteService.postUnauthenticatedRequest("register", {
emailHashed: this.emailHashed,
verifier,
salt,
email: this.email,
introEmailStatus,
marketingEmailStatus,
mob: isMobile ? 1 : 0,
code
});
if (isResponse(response)) {
if (response.status !== 201) {
console.error("Unexpected status code");
return KeeError.Unexpected;
}
await this.parseJWTs(response.body.JWTs);
return true;
}
if (response === KeeError.ServerConflict) {
return KeeError.AlreadyRegistered; // .......... similar.......
}
return response;
} catch (e) {
console.error(e);
return KeeError.Unexpected;
}
}
public async loginStart () {
if (!remoteService) {
return KeeError.InvalidState;
}
try {
const request1 = remoteService.postUnauthenticatedRequest("loginStart", {
emailHashed: this.emailHashed
});
const clientEphemeral = srp.generateEphemeral();
const response1 = await request1;
if (isResponse(response1)) {
const srp1 = response1.body as SRP1;
this.salt = srp1.salt;
const nonce = srp1.costFactor > 0 ? await calculateCostNonce(srp1.costFactor, srp1.costTarget!) : "";
this.loginParameters = { clientEphemeral, B: srp1.B, authId: srp1.authId, nonce };
return { kms: srp1.kms };
}
// We can't handle any errors. The server is either working with a 200 response or failed in some unexpected way
return response1;
} catch (e) {
console.error(e);
return KeeError.Unexpected;
}
}
async loginFinish (hashedMasterKey?: ArrayBuffer) {
if (!remoteService) {
return KeeError.InvalidState;
}
if (hashedMasterKey) {
if (!this.email) {
console.error("Email missing. Can't complete login procedure.");
return KeeError.InvalidState;
}
this.passKey = await this.derivePassKey(this.email, hashedMasterKey);
}
if (!this.loginParameters) {
return KeeError.MaybeOffline;
}
if (!this.emailHashed) {
console.error("Hashed email missing. Can't complete login procedure.");
return KeeError.InvalidState;
}
if (!this.salt) {
console.error("salt missing. Can't complete login procedure.");
return KeeError.InvalidState;
}
if (!this.passKey) {
console.error("passKey missing. Can't complete login procedure.");
return KeeError.InvalidState;
}
if (!this.loginParameters.clientEphemeral) {
console.error("clientEphemeral missing. Can't complete login procedure.");
return KeeError.InvalidState;
}
if (!this.loginParameters.B) {
console.error("B missing. Can't complete login procedure.");
return KeeError.InvalidState;
}
if (!this.loginParameters.authId) {
console.error("authId missing. Can't complete login procedure.");
return KeeError.InvalidState;
}
const privateKey = srp.derivePrivateKey(base642hex(this.salt), this.emailHashed, this.passKey);
const clientSession = srp.deriveSession(
this.loginParameters.clientEphemeral.secret,
base642hex(this.loginParameters.B),
base642hex(this.salt),
this.emailHashed,
privateKey);
try {
const response2 = await remoteService.postUnauthenticatedRequest("loginFinish", {
emailHashed: this.emailHashed,
clientSessionEphemeral: hex2base64(this.loginParameters.clientEphemeral.public),
authId: this.loginParameters.authId,
costNonce: this.loginParameters.nonce,
clientSessionProof: hex2base64(clientSession.proof)
});
if (isResponse(response2)) {
const srp2 = response2.body as SRP2;
try {
srp.verifySession(this.loginParameters.clientEphemeral.public, clientSession, base642hex(srp2.proof));
} catch (e) {
return KeeError.LoginFailedMITM;
}
await this.parseJWTs(srp2.JWTs);
this._verificationStatus = srp2.verificationStatus;
return true;
}
// If we are told we need to login after attempting to do so, clearly there
// were invalid authentication credentials supplied
if (response2 === KeeError.LoginRequired) {
return KeeError.LoginFailed;
}
// We can't handle any other errors
return response2;
} catch (e) {
console.error(e);
return KeeError.Unexpected;
}
}
async applyCouponToSubscription (code: string) {
if (!remoteService) {
return KeeError.InvalidState;
}
if (!this.email) {
console.error("Email missing. Can't apply coupon.");
return KeeError.InvalidState;
}
if (!this.emailHashed) {
console.error("Hashed email missing. Can't apply coupon.");
return KeeError.InvalidState;
}
if (!code) {
console.error("Code missing. Can't apply coupon.");
return KeeError.InvalidState;
}
try {
const response = await remoteService.getRequest(`applyCoupon/${code}`,
this.tokens ? this.tokens.identity : undefined, () => this.refresh());
if (!isResponse(response)) {
if (response === KeeError.LoginRequired) {
return KeeError.LoginFailed;
}
// We can't handle any other errors
return response;
}
return response.ok;
} catch (e) {
console.error(e);
return KeeError.Unexpected;
}
}
async refresh () {
if (!remoteService) {
return KeeError.InvalidState;
}
try {
let response: KeeError|Response = KeeError.LoginRequired;
if (this.tokens && this.tokens.identity) {
response = await remoteService.postRequest("refresh", {}, this.tokens.identity);
if (isResponse(response)) {
if (response.status !== 200) {
console.error("Unexpected status code");
return KeeError.Unexpected;
}
await this.parseJWTs(response.body.JWTs);
return this.tokens;
}
}
if (response === KeeError.LoginRequired) {
// We need to reauthenticate. If we have a cached User object with
// a hashedPassword and emailHashed, we can trigger the login process automatically...
// but if not, or it it fails, we need to force the user's session to logout and ask them
// to login again. Initially this will involve logging out of the vault DBs too but perhaps could relax that one day.
try {
if (this.emailHashed && this.passKey) {
await this.loginStart();
const loginResult = await this.loginFinish();
return loginResult === true ? this.tokens : loginResult;
} else {
return KeeError.LoginRequired;
}
} catch (error) {
return KeeError.LoginRequired;
}
}
// We can't handle any other errors
return response;
} catch (e) {
console.error(e);
return KeeError.Unexpected;
}
}
async resendVerificationEmail () {
if (!remoteService) {
return KeeError.InvalidState;
}
if (!this.tokens || !this.tokens.identity) {
return KeeError.InvalidState;
}
try {
const response = await remoteService.postRequest("resendVerificationEmail", {}, this.tokens.identity);
if (isResponse(response)) {
if (response.status !== 200) {
console.error("Unexpected status code");
return KeeError.Unexpected;
}
return true;
}
if (response === KeeError.LoginRequired) {
// We need to reauthenticate. If we have a cached User object with
// a hashedPassword and emailHashed, we can trigger the login process automatically...
try {
if (this.emailHashed && this.passKey) {
await this.loginStart();
const success = await this.loginFinish();
return success;
} else {
return KeeError.LoginRequired;
}
} catch (error) {
return KeeError.LoginRequired;
}
}
// We can't handle any other errors
return response;
} catch (e) {
console.error(e);
return KeeError.Unexpected;
}
}
async restartTrial () {
if (!remoteService) {
return KeeError.InvalidState;
}
if (!this.emailHashed) {
console.error("Hashed email missing. Can't complete trial restart procedure.");
return KeeError.InvalidState;
}
try {
const response1 = await remoteService.getRequest("restartTrial/", this.tokens ? this.tokens.identity : undefined, () => this.refresh());
if (!isResponse(response1)) {
if (response1 === KeeError.LoginRequired) {
return KeeError.LoginFailed;
}
// We can't handle any other errors
return response1;
}
return true;
} catch (e) {
console.error(e);
return KeeError.Unexpected;
}
}
async changePassword (hashedMasterKey: ArrayBuffer, onChangeStarted: () => Promise<boolean>) {
if (!remoteService) {
return KeeError.InvalidState;
}
if (!this.email) {
console.error("Email missing. Can't complete change password procedure.");
return KeeError.InvalidState;
}
const newPassKey = await this.derivePassKey(this.email, hashedMasterKey);
if (!this.emailHashed) {
console.error("Hashed email missing. Can't complete change password procedure.");
return KeeError.InvalidState;
}
if (!this.salt) {
console.error("salt missing. Can't complete change password procedure.");
return KeeError.InvalidState;
}
if (!newPassKey) {
console.error("passKey missing. Can't complete change password procedure.");
return KeeError.InvalidState;
}
const privateKey = srp.derivePrivateKey(base642hex(this.salt), this.emailHashed, newPassKey);
const verifier = hex2base64(srp.deriveVerifier(privateKey));
try {
const response1 = await remoteService.postRequest("changePasswordStart", {
verifier
}, this.tokens ? this.tokens.identity : undefined, () => this.refresh());
if (!isResponse(response1)) {
if (response1 === KeeError.LoginRequired) {
return KeeError.LoginFailed;
}
// We can't handle any other errors
return response1;
}
const success = await onChangeStarted();
if (!success) {
throw new Error("Password change aborted.");
}
const response2 = await remoteService.postRequest("changePasswordFinish", {},
this.tokens ? this.tokens.identity : undefined, () => this.refresh());
if (isResponse(response2)) {
this.passKey = newPassKey;
await this.parseJWTs(response2.body.JWTs);
return true;
} else {
if (response2 === KeeError.LoginRequired) {
return KeeError.LoginFailed;
}
// We can't handle any other errors
return response2;
}
} catch (e) {
console.error(e);
return KeeError.Unexpected;
}
}
async resetStart () {
if (!remoteService) {
return false;
}
if (!this.email) {
console.error("Email missing. Can't reset.");
return false;
}
if (!this.emailHashed) {
console.error("Hashed email missing. Can't reset.");
return false;
}
try {
const response1 = await remoteService.postUnauthenticatedRequest("resetPasswordRequest", {
emailHashed: this.emailHashed
});
if (!isResponse(response1)) {
// We can't handle any errors
return false;
}
const unverifiedJWTString = response1.body.jwt;
if (!unverifiedJWTString) {
return false;
}
const unverifiedJWT = JWT.parse(unverifiedJWTString);
if (!unverifiedJWT || !unverifiedJWT.costTarget || !unverifiedJWT.costFactor) {
return false;
}
const nonce = await calculateCostNonce(unverifiedJWT.costFactor, unverifiedJWT.costTarget);
const response2 = await remoteService.postUnauthenticatedRequest("resetPasswordStart", {
authToken: unverifiedJWTString,
costNonce: nonce
});
if (isResponse(response2)) {
return response2.ok;
}
} catch (e) {
console.error(e);
}
return false;
}
private async parseJWTs (JWTs: string[]) {
this._tokens = {};
// Extract features from the client claim supplied by the server and cache
// the other claims for later forwarding back to the server
for (const jwt of JWTs) {
try {
const { audience, claim } = await JWT.verify(jwt, remoteService.stage);
switch (audience) {
case "client": {
if (claim !== undefined) {
// Don't do anything in the unlikely event that the JWT has already expired
if (claim.exp > Date.now()) {
this.features = {
enabled: claim.features,
source: "unknown",
validUntil: claim.featureExpiry,
subscriptionId: claim.subscriptionId
};
this._userId = claim.sub;
this._tokens.client = jwt;
}
}
} break;
case "storage": this._tokens.storage = jwt; break;
case "forms": this._tokens.forms = jwt; break;
case "identity": this._tokens.identity = jwt; break;
case "sso": this._tokens.sso = jwt; break;
}
} catch (e) {
console.log("Token error: " + e);
}
}
if (tokenChangeHandler) tokenChangeHandler(this._tokens);
}
}
export class UserManager {
public static init (stage: "dev"|"beta"|"prod", tokenChangeHandlerParam: (tokens: Tokens) => void) {
remoteService = new RemoteService(stage, "identity");
tokenChangeHandler = tokenChangeHandlerParam;
}
public static verifyJWT (jwt: string): Promise<{audience: string, claim?: Claim | undefined}> {
return JWT.verify(jwt, remoteService.stage);
}
}
export async function hashString (text: string, salt?: string) {
const message = (salt ? salt : "") + text;
const msgBuffer = utf8encode(message);
const hash = await crypto.subtle.digest("SHA-256", msgBuffer);
return bufferToBase64(hash);
}
export async function hashStringToHex (text: string, salt?: string) {
const message = (salt ? salt : "") + text;
const msgBuffer = utf8encode(message);
const hash = await crypto.subtle.digest("SHA-256", msgBuffer);
return bufferToHex(hash);
}
export async function hashByteArray (text: Uint8Array, salt: Uint8Array) {
const msgBuffer = new Uint8Array(salt.byteLength+text.byteLength);
msgBuffer.set(salt);
msgBuffer.set(text, salt.byteLength);
const hash = await crypto.subtle.digest("SHA-256", msgBuffer);
return bufferToBase64(hash);
}
export async function stretchByteArray (byteArray: Uint8Array, salt: string) {
const saltArray = base64toByteArray(salt);
try {
const key = await crypto.subtle.importKey(
"raw",
byteArray,
{
name: "PBKDF2"
},
false,
["deriveKey"]
);
const derivedKey = await crypto.subtle.deriveKey(
{
name: "PBKDF2",
salt: saltArray,
iterations: 500,
hash: { name: "SHA-256" }
},
key,
{
name: "AES-CTR",
length: 256
},
true,
["encrypt", "decrypt"]
);
const hashBuffer = await crypto.subtle.exportKey("raw", derivedKey);
return bufferToBase64(hashBuffer);
} catch (e) {
// Exception expected in Edge until it switches to Chromium
// backend, maybe in other rare browsers too.
return bufferToBase64(Pbkdf2HmacSha256(byteArray, saltArray, 500, 32));
}
}
export const EMAIL_ID_SALT = "a7d60f672fc7836e94dabbd7000f7ef4e5e72bfbc66ba4372add41d7d46a1c24";
export const EMAIL_AUTH_SALT = "4e1cc573ed8cd48a19beb6ec6729be6c7a19c91a40c6483be3c9d671b5fbae9a";
export const PASS_AUTH_SALT = "a90b6364315150a39a60d324bfafe6f4444deb15bee194a6d34726c31493dacc";
export const STRETCH_SALT = "509d04a4c27ea9947335e7aa45aabe4fcc2222c87daf0f0520712cefb000124a";
export enum AccountVerificationStatus {
Never,
Reverify,
Sent,
Success
}
class SRP1 {
costFactor: number;
costTarget?: string;
B: string;
authId: string;
salt: string;
kms: string[];
}
class SRP2 {
proof: string;
authId: string;
JWTs: string[];
verificationStatus: AccountVerificationStatus;
}
//TODO: Might want to do this differently - not sure how much overhead this many async awaits will add
async function calculateCostNonce (costFactor: number, costTarget: string) {
let nonce = 0;
let h = await hashStringToHex(costTarget + nonce);
while (!checkNonce(h, costFactor)) {
nonce++;
h = await hashStringToHex(costTarget + nonce);
}
return nonce.toString();
}
function checkNonce (proposedSolution: string, costFactor: number) {
let i;
for (i = 0; i < proposedSolution.length; i++) {
if (proposedSolution[i] !== "0") break;
}
return i >= costFactor;
}