-
Notifications
You must be signed in to change notification settings - Fork 96
/
Copy pathservice_worker.js
1313 lines (1141 loc) · 41.5 KB
/
service_worker.js
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
/**
* @license
* Copyright 2011 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @fileoverview Receives potential passwords from content_script.js and checks
* to see if they're the user's password. Populates chrome.storage.local with partial
* hashes of the user's password.
* @author [email protected] (Drew Hintz)
*/
'use strict';
goog.module('passwordalert.background');
const GoogCryptSha1 = goog.require('goog.crypt.Sha1');
const googCrypt = goog.require('goog.crypt');
const googString = goog.require('goog.string');
const keydown = goog.require('passwordalert.keydown');
let background = {};
goog.exportSymbol('background', background); // for tests only.
background.storageCache = {};
// With Chrome Manifest v3, localStorage was deprecated in favor of chrome.storage.local.
// Where previously, the use of localStorage would persist across browser sessions,
// we must now manually persist that data at a periodic interval. We accomplish this here
// by proxying the cache object and asynchronously writing it to storage on change.
background.storageCache = new Proxy(background.storageCache, {
set: function (target, key, value) {
let r = Reflect.set(target, key, value);
chrome.storage.local.set(
{'cacheData': background.storageCache}, function (result) {
console.log('persisted storageCache to chrome.local.storage on update');
background.refreshPasswordLengths_();
});
return r;
},
deleteProperty: function(target, prop) {
if (prop in target) {
let r = Reflect.deleteProperty(target, prop);
chrome.storage.local.set(
{'cacheData': background.storageCache}, function (result) {
console.log(
'persisted storageCache to chrome.local.storage on delete');
background.refreshPasswordLengths_();
});
return r;
}
},
get: function (target, prop, receiver) {
return Reflect.get(...arguments);
},
getOwnPropertyDescriptor: function (target, prop) {
return Reflect.getOwnPropertyDescriptor(...arguments);
}
});
/**
* Key for chrome.storage.local to store salt value.
* @private {string}
* @const
*/
background.SALT_KEY_ = 'salt';
/**
* Number of bits of the hash to use.
* @private {number}
* @const
*/
background.HASH_BITS_ = 37;
/**
* Where password use reports are sent.
* @private {string}
*/
background.report_url_;
/**
* Whether the user should be prompted to initialize their password.
* @private {boolean}
*/
background.shouldInitializePassword_;
/**
* Minimum length of passwords.
* @private {number}
* @const
*/
background.MINIMUM_PASSWORD_ = 8;
/**
* Maximum character typing rate to protect against abuse.
* Calculated for 60 wpm at 5 cpm for one hour.
* @private {number}
* @const
*/
background.MAX_RATE_PER_HOUR_ = 18000;
/**
* How many passwords have been checked in the past hour.
* @private {number}
*/
background.rateLimitCount_ = 0;
/**
* The time when the rateLimitCount_ will be reset.
* @private {?Date}
*/
background.rateLimitResetDate_;
/**
* Associative array of possible passwords. Keyed by tab id.
* @private {!Object.<number, !Object.<string, string|boolean>>}
*/
background.possiblePassword_ = {};
/**
* Associative array of state for Keydown events.
* @private {!background.State_}
*/
background.stateKeydown_ = {
'hash': '',
'otpCount': 0,
'otpMode': false,
'otpTime': null,
'typed': new keydown.Typed(),
'typedTime': null
};
/**
* Associative array of state for Keypress events.
* @private {!background.State_}
*/
background.stateKeypress_ = {
'hash': '',
'otpCount': 0,
'otpMode': false,
'otpTime': null,
'typed': '',
'typedTime': null
};
/**
* Password lengths for passwords that are being watched.
* If an array offset is true, then that password length is watched.
* @private {?Array.<boolean>}
*/
background.passwordLengths_;
/**
* If no key presses for this many seconds, flush buffer.
* @private {number}
* @const
*/
background.SECONDS_TO_CLEAR_ = 10;
/**
* OTP must be typed within this time since the password was typed.
* @private {number}
* @const
*/
background.SECONDS_TO_CLEAR_OTP_ = 60;
/**
* Number of digits in a valid OTP.
* @private {number}
*/
background.OTP_LENGTH_ = 6;
/**
* ASCII code for enter character.
* @private {number}
* @const
*/
background.ENTER_ASCII_CODE_ = 13;
/**
* Request from content_script. action is always defined. Other properties are
* only defined for certain actions.
* @typedef {{action: string, password: (string|undefined),
* url: (string), looksLikeGoogle: (string|undefined)}}
* @private
*/
background.Request_;
/**
* State of keypress or keydown events.
* @typedef {{hash: string, otpCount: number, otpMode: boolean,
* otpTime: ?Date, typed: (!keydown.Typed|string),
* typedTime: ?Date}}
* @private
*/
background.State_;
/**
* Namespace for chrome's managed storage.
* @private {string}
* @const
*/
background.MANAGED_STORAGE_NAMESPACE_ = 'managed';
/**
* Is password alert used in enterprise environment. If false, then it's
* used by individual consumer.
* @private {boolean}
*/
background.enterpriseMode_ = false;
/**
* The corp email domain, e.g. "@company.com".
* @private {string}
*/
background.corp_email_domain_;
/**
* Display the consumer mode alert even in enterprise mode.
* @private {boolean}
*/
background.displayUserAlert_ = false;
/**
* Domain-specific shared auth secret for enterprise when oauth token fails.
* @private {string}
*/
background.domain_auth_secret_ = '';
/**
* The id of the chrome notification that prompts the user to initialize
* their password.
* @private {string}
* @const
*/
background.NOTIFICATION_ID_ = 'initialize_password_notification';
/**
* Key for the allowed hosts object in chrome storage.
* @private {string}
* @const
*/
background.ALLOWED_HOSTS_KEY_ = 'allowed_hosts';
/**
* Key for the phishing warning allowlist object in chrome storage.
* @private {string}
* @const
*/
background.PHISHING_WARNING_ALLOWLIST_KEY_ = 'phishing_warning_allowlist';
/**
* The email of the user signed in to Chrome (which could be empty if there's
* no signed in user). Only updates when the background page first loads.
* @private {string}
*/
background.signed_in_email_ = '';
/**
* Whether the extension was newly installed.
* @private {boolean}
*/
background.isNewInstall_ = false;
/**
* Whether the background page is initialized (managed policy loaded).
* @private {boolean}
*/
background.isInitialized_ = false;
/**
* This sets the state of new install that can be used later.
* @param {!Object} details Details of the onInstall event.
* @private
*/
background.handleNewInstall_ = function (details) {
if (details['reason'] == 'install') {
console.log('New install detected.');
background.isNewInstall_ = true;
}
if (details['reason'] == 'install' || details['reason'] == 'update') {
// Only inject the content script into all tabs once upon new install.
// This prevents re-injection when the event page reloads.
//
// initializePassword_ should occur after injectContentScriptIntoAllTabs_.
// This way, the content script will be ready to receive
// post-password initialization messages.
background.injectContentScriptIntoAllTabs_(function () {
background.initializePasswordIfReady_(
5, 1000, background.initializePasswordIfNeeded_);
});
}
};
/**
* Set the managed policy values into the configurable variables.
* @param {function()} callback Executed after policy values have been set.
* @private
*/
background.setManagedPolicyValuesIntoConfigurableVariables_ = function (
callback) {
chrome.storage.managed.get(function (managedPolicy) {
if (Object.keys(managedPolicy).length == 0) {
console.log('No managed policy found. Consumer mode.');
} else {
console.log('Managed policy found. Enterprise mode.');
background.corp_email_domain_ =
managedPolicy['corp_email_domain'].replace(/@/g, '').toLowerCase();
background.displayUserAlert_ = managedPolicy['display_user_alert'];
background.enterpriseMode_ = true;
background.report_url_ = managedPolicy['report_url'];
background.shouldInitializePassword_ =
managedPolicy['should_initialize_password'];
background.domain_auth_secret_ = managedPolicy['domain_auth_secret'];
}
callback();
});
};
/**
* Handle managed policy changes by updating the configurable variables.
* @param {!Object} changedPolicies Object mapping each policy to its
* new values. Policies that have not changed will not be present.
* For example:
* {
* report_url: {
* newValue: "https://passwordalert222.example.com/report/"
* oldValue: "https://passwordalert111.example.com/report/"
* }
* }
* @param {string} storageNamespace The name of the storage area
* ("sync", "local" or "managed") the changes are for.
* @private
*/
background.handleManagedPolicyChanges_ = function (
changedPolicies, storageNamespace) {
if (storageNamespace == background.MANAGED_STORAGE_NAMESPACE_) {
console.log('Handling changed policies.');
let changedPolicy;
for (changedPolicy in changedPolicies) {
if (!background.enterpriseMode_) {
background.enterpriseMode_ = true;
console.log('Enterprise mode via updated managed policy.');
}
let newPolicyValue = '';
if (changedPolicies[changedPolicy].hasOwnProperty('newValue')) {
newPolicyValue = changedPolicies[changedPolicy]['newValue'];
}
switch (changedPolicy) {
case 'corp_email_domain':
background.corp_email_domain_ =
newPolicyValue.replace(/@/g, '').toLowerCase();
break;
case 'display_user_alert':
background.displayUserAlert_ = newPolicyValue;
break;
case 'report_url':
background.report_url_ = newPolicyValue;
break;
case 'should_initialize_password':
background.shouldInitializePassword_ = newPolicyValue;
break;
case 'domain_auth_secret':
background.domain_auth_secret_ = newPolicyValue;
break;
}
}
}
};
/**
* Programmatically inject the content script into all existing tabs that
* belongs to the user who has just installed the extension.
* https://developer.chrome.com/extensions/content_scripts#pi
*
* The programmatically injected script will be replaced by the
* normally injected script when a tab reloads or loads a new url.
*
* TODO: Think about how to handle orphaned content scripts after autoupdates.
*
* @param {function()} callback Executed after content scripts have been
* injected, e.g. user to initialize password.
* @private
*/
background.injectContentScriptIntoAllTabs_ = function (callback) {
console.log('Inject content scripts into all tabs.');
chrome.tabs.query({}, function (tabs) {
for (let i = 0; i < tabs.length; i++) {
// Skip chrome:// and chrome-devtools:// pages
if (tabs[i].url.lastIndexOf('chrome', 0) != 0) {
chrome.scripting.executeScript({
target: { 'tabId': tabs[i].id },
files: ['content_script_compiled.js']
});
}
}
callback();
});
};
/**
* Display the notification for user to initialize their password.
* If a notification has not been created, a new one is created and displayed.
* If a notification has already been created, it will be updated and displayed.
*
* A trick is used to make the notification display again --
* essentially updating it to a higher priority (> 0).
* http://stackoverflow.com/a/26358154/2830207
* @private
*/
background.displayInitializePasswordNotification_ = function () {
chrome.notifications.getAll(function (notifications) {
if (notifications[background.NOTIFICATION_ID_]) {
chrome.notifications.update(
background.NOTIFICATION_ID_, { priority: 2 }, function () { });
} else {
const options = {
type: 'basic',
priority: 1,
title: chrome.i18n.getMessage('extension_name'),
message: chrome.i18n.getMessage('initialization_message'),
iconUrl: chrome.runtime.getURL('logo_password_alert.png'),
buttons: [{ title: chrome.i18n.getMessage('sign_in') }]
};
chrome.notifications.create(
background.NOTIFICATION_ID_, options, function () { });
const openLoginPage_ = function (notificationId) {
if (notificationId === background.NOTIFICATION_ID_) {
chrome.tabs.create({
'url': 'https://accounts.google.com/ServiceLogin?' +
'continue=https://www.google.com'
});
}
};
// If a user clicks on the non-button area of the notification,
// they should still have the chance to go the login page to
// initialize their password.
chrome.notifications.onClicked.addListener(openLoginPage_);
chrome.notifications.onButtonClicked.addListener(openLoginPage_);
}
});
};
/**
* Prompts the user to initialize their password if needed.
* @private
*/
background.initializePasswordIfNeeded_ = function () {
if (background.enterpriseMode_ && !background.shouldInitializePassword_) {
return;
}
// For OS X, we add a delay that will give the user a chance to dismiss
// the webstore's post-install popup. Otherwise, there will be an overlap
// between this popup and the chrome.notification message.
// TODO(henryc): Find a more robust way to overcome this overlap issue.
if (navigator.userAgentData.platform.indexOf('macOS') != -1) {
setTimeout(
background.displayInitializePasswordNotification_,
5000); // 5 seconds
} else {
background.displayInitializePasswordNotification_();
}
setTimeout(function () {
if (!background.storageCache.hasOwnProperty(background.SALT_KEY_)) {
console.log(
'Password still has not been initialized. ' +
'Start the password initialization process again.');
background.initializePasswordIfReady_(
5, 1000, background.initializePasswordIfNeeded_);
}
}, 300000); // 5 minutes
};
/**
* Prompts the user to initialize their password if ready.
* Uses exponential backoff to make sure all page initialization and
* managed policies are completed first.
* @param {number} maxRetries Max number to retry.
* @param {number} delay Milliseconds to wait before retry.
* @param {function()} callback Executed if password is ready to be initialized.
* @private
*/
background.initializePasswordIfReady_ = function (maxRetries, delay, callback) {
if (background.isNewInstall_ && background.isInitialized_) {
callback();
return;
}
if (maxRetries > 0) {
setTimeout(function () {
background.initializePasswordIfReady_(
maxRetries - 1, delay * 2, callback);
}, delay);
} else {
console.log('Password is not ready to be initialized.');
}
};
/**
* Complete page initialization. This is executed after managed policy values
* have been set.
*
* @private
*/
background.completePageInitialization_ = async function () {
const response = await background.checkForCacheData_();
if(response) {
background.isInitialized_ = true;
background.refreshPasswordLengths_();
chrome.runtime.onMessage.addListener(background.handleRequest_);
}
// Get the username from a signed in Chrome profile, which might be used
// for reporting phishing sites (if the password store isn't initialized).
chrome.identity.getProfileUserInfo(function (userInfo) {
if (userInfo) {
background.signed_in_email_ = userInfo.email;
}
});
console.log('page init complete');
};
/**
* Check for existing cacheData object in chrome.storage.local
*
* @return {!Promise}
* @private
*/
background.checkForCacheData_ = async function() {
return new Promise((resolve, reject) => {
try {
chrome.storage.local.get('cacheData', function(value) {
if (typeof value['cacheData'] === "undefined") {
console.log('nothing in local storage to load into cache.');
resolve(true);
} else {
background.storageCache = value['cacheData'];
background.injectContentScriptIntoAllTabs_(
background.refreshPasswordLengths_); // let pages know we have
// passwords
console.log(
'local storage loaded into cache successfully. length: ',
Object.keys(background.storageCache).length);
resolve(true);
}
});
} catch (ex) {
reject(ex);
}
});
};
/**
* Called when the extension loads.
* @private
*/
background.initializePage_ = function () {
background.setManagedPolicyValuesIntoConfigurableVariables_(
background.completePageInitialization_);
};
/**
* Receives requests from content_script.js and calls the appropriate function.
* @param {!background.Request_} request Request message from the
* content_script.
* @param {{tab: {id: number}}} sender Who sent this message.
* @param {function(*)} sendResponse Callback with a response.
* @private
*/
background.handleRequest_ = function (request, sender, sendResponse) {
if (sender.tab === undefined) {
return;
}
console.log("Request from tab:", sender.tab.id, "action:", request.action, "context:", request.context, "url:", request.url);
switch (request.action) {
case 'handleKeypress':
background.handleKeypress_(sender.tab.id, request);
break;
case 'handleKeydown':
background.handleKeydown_(sender.tab.id, request);
break;
case 'checkString':
background.checkPassword_(
sender.tab.id, request, background.stateKeydown_);
break;
case 'statusRequest':
const state = {'passwordStored': (background.passwordLengths_.length > 0 ) };
sendResponse(JSON.stringify(state)); // Needed for pre-loaded pages.
break;
case 'looksLikeGoogle':
background.sendReportPage_(request);
background.displayPhishingWarningIfNeeded_(sender.tab.id, request);
break;
case 'setPossiblePassword':
background.setPossiblePassword_(sender.tab.id, request, true);
break;
case 'setPossiblePasswordWithoutEmail':
background.setPossiblePassword_(sender.tab.id, request, false);
break;
case 'savePossiblePassword':
background.savePossiblePassword_(sender.tab.id);
break;
default:
console.log(
'cannot handle request action: ' + request.action +
'. action is undefined.');
}
};
/**
* Clears OTP mode.
* @param {!background.State_} state State of keydown or keypress.
* @private
*/
background.clearOtpMode_ = function (state) {
state['otpMode'] = false;
state['otpCount'] = 0;
state['otpTime'] = null;
state['hash'] = '';
if (typeof state['typed'] == 'string') {
state['typed'] = '';
} else { // keydown.Typed object
state['typed'].clear();
}
};
/**
* Called on each key down. Checks the most recent possible characters.
* @param {number} tabId Id of the browser tab.
* @param {!background.Request_} request Request object from
* content_script. Contains url and referer.
* @param {!background.State_} state State of keypress or keydown.
* @private
*/
background.checkOtp_ = function (tabId, request, state) {
if (state['otpMode']) {
const now = new Date();
if (now - state['otpTime'] > background.SECONDS_TO_CLEAR_OTP_ * 1000) {
background.clearOtpMode_(state);
} else if (request.keyCode >= 0x30 && request.keyCode <= 0x39) {
// is a digit
state['otpCount']++;
} else if (
request.keyCode > 0x20 ||
// non-digit printable characters reset it
// Non-printable only allowed at start:
state['otpCount'] > 0) {
background.clearOtpMode_(state);
}
if (state['otpCount'] >= background.OTP_LENGTH_) {
const item = JSON.parse(background.storageCache[state.hash]);
console.log('OTP TYPED! ' + request.url);
background.sendReportPassword_(
request, item['email'], item['date'], true);
background.clearOtpMode_(state);
}
}
};
/**
* Called on each key down. Checks the most recent possible characters.
* @param {number} tabId Id of the browser tab.
* @param {!background.Request_} request Request object from
* content_script. Contains url and referer.
* @param {!background.State_} state State of keydown or keypress.
* @private
*/
background.checkAllPasswords_ = function (tabId, request, state) {
if (state['typed'].length >= background.MINIMUM_PASSWORD_) {
for (let i = 1; i < background.passwordLengths_.length; i++) {
// Perform a check on every length, even if we don't have enough
// typed characters, to avoid timing attacks.
if (background.passwordLengths_[i]) {
request.password = state['typed'].substr(-1 * i);
background.checkPassword_(tabId, request, state);
}
}
}
};
/**
* Called on each key down. Checks the most recent possible characters.
* @param {number} tabId Id of the browser tab.
* @param {!background.Request_} request Request object from
* content_script. Contains url and referer.
* @private
*/
background.handleKeydown_ = function (tabId, request) {
const state = background.stateKeydown_;
background.checkOtp_(tabId, request, state);
if (request.keyCode == background.ENTER_ASCII_CODE_) {
state['typed'].clear();
return;
}
const typedTime = new Date(request.typedTimeStamp);
if (typedTime - state['typedTime'] > background.SECONDS_TO_CLEAR_ * 1000) {
state['typed'].clear();
}
state['typed'].event(request.keyCode, request.shiftKey);
state['typedTime'] = typedTime;
state['typed'].trim(background.passwordLengths_.length);
background.checkAllPasswords_(tabId, request, state);
};
/**
* Called on each key press. Checks the most recent possible characters.
* @param {number} tabId Id of the browser tab.
* @param {!background.Request_} request Request object from
* content_script. Contains url and referer.
* @private
*/
background.handleKeypress_ = function (tabId, request) {
const state = background.stateKeypress_;
background.checkOtp_(tabId, request, state);
if (request.keyCode == background.ENTER_ASCII_CODE_) {
state['typed'] = '';
return;
}
const typedTime = new Date(request.typedTimeStamp);
if (typedTime - state['typedTime'] > background.SECONDS_TO_CLEAR_ * 1000) {
state['typed'] = '';
}
// We're treating keyCode and charCode the same here intentionally.
state['typed'] += String.fromCharCode(request.keyCode);
state['typedTime'] = typedTime;
// trim the buffer when it's too big
if (state['typed'].length > background.passwordLengths_.length) {
state['typed'] =
state['typed'].slice(-1 * background.passwordLengths_.length);
}
// Send keypress event to keydown state so the keydown library can attempt
// to guess the state of capslock.
background.stateKeydown_['typed'].keypress(request.keyCode);
// Do not check passwords if keydown is in OTP mode to avoid double-warning.
if (!background.stateKeydown_['otpMode']) {
background.checkAllPasswords_(tabId, request, state);
}
};
/**
* When password entered into a login page, temporarily save it here.
* We do not yet know if the password is correct.
* @param {number} tabId The tab that was used to log in.
* @param {!background.Request_} request Request object
* containing email address and password.
* @param {boolean} hasEmail Request object has an email value
* @private
*/
background.setPossiblePassword_ = function (tabId, request, hasEmail) {
if ((hasEmail && !request.email) || !request.password) {
return;
}
if (request.password.length < background.MINIMUM_PASSWORD_) {
console.log(
'password length is shorter than the minimum of ' +
background.MINIMUM_PASSWORD_);
return;
}
let email;
if (!hasEmail) {
email = background.possiblePassword_[sender.tab.id]['email'];
} else {
email = request.email;
}
console.log(
'Setting possible password for %s, password length of %s from tab %s (inferred: %s)', email,
request.password.length, tabId, !hasEmail);
background.possiblePassword_[tabId] = {
'email': email,
'password': background.hashPassword_(request.password),
'length': request.password.length,
'time': Math.floor(Date.now() / 1000)
};
};
/**
*
* @param {number} index Index in to the storageCache array.
* @return {*} The item.
* @private
*/
background.getStorageCacheItem_ = function (index) {
let item;
if (Object.keys(background.storageCache)[index] == background.SALT_KEY_) {
item = null;
} else {
item = JSON.parse(
background.storageCache[Object.keys(background.storageCache)[index]]);
}
return item;
};
/**
* The login was successful, so write the possible password to storageCache.
* @param {number} tabId The tab that was used to log in.
* @private
*/
background.savePossiblePassword_ = function (tabId) {
const possiblePassword_ = background.possiblePassword_[tabId];
if (!possiblePassword_) {
return;
}
if ((Math.floor(Date.now() / 1000) - possiblePassword_['time']) > 60) {
return; // If login took more than 60 seconds, ignore it.
}
const email = possiblePassword_['email'];
const password = possiblePassword_['password'];
const length = possiblePassword_['length'];
// Delete old email entries.
for (let i = 0; i < Object.keys(background.storageCache).length; i++) {
const item = background.getStorageCacheItem_(i);
if (item && item['email'] == email) {
delete item['email'];
delete item['date'];
background.storageCache[Object.keys(background.storageCache)[i]] =
JSON.stringify(item);
}
}
// Delete any entries that now have no emails.
const keysToDelete = [];
for (let i = 0; i < Object.keys(background.storageCache).length; i++) {
const item = background.getStorageCacheItem_(i);
if (item && !(item.hasOwnProperty('email'))) {
// Delete the item later.
// We avoid modifying storageCache while iterating over it.
keysToDelete.push(Object.keys(background.storageCache)[i]);
}
}
for (let i = 0; i < keysToDelete.length; i++) {
delete background.storageCache[keysToDelete[i]];
}
console.log('Saving password for: ' + email);
let item;
if (password in background.storageCache) {
item = JSON.parse(background.storageCache[password]);
} else {
item = { 'length': length };
}
item['email'] = email;
item['date'] = new Date();
if (background.isNewInstall_) {
if (background.enterpriseMode_ && !background.shouldInitializePassword_) {
// If enterprise policy says not to prompt, then don't prompt.
background.isNewInstall_ = false;
} else {
const options = {
type: 'basic',
title: chrome.i18n.getMessage('extension_name'),
message: chrome.i18n.getMessage('initialization_thank_you_message'),
iconUrl: chrome.runtime.getURL('logo_password_alert.png')
};
chrome.notifications.create(
'thank_you_notification', options, function () {
background.isNewInstall_ = false;
});
}
}
background.storageCache[password] = JSON.stringify(item);
delete background.possiblePassword_[tabId];
};
/**
* Updates the value of background.passwordLengths_ and pushes
* new value to all content_script tabs.
* @private
*/
background.refreshPasswordLengths_ = function () {
background.passwordLengths_ = [];
for (let i = 0; i < Object.keys(background.storageCache).length; i++) {
const item = background.getStorageCacheItem_(i);
if (item) {
background.passwordLengths_[item['length']] = true;
}
}
background.pushToAllTabs_();
};
/**
* If function is called too quickly, returns false.
* @return {boolean} Whether we are below the maximum rate.
* @private
*/
background.checkRateLimit_ = function () {
const now = new Date();
if (!background.rateLimitResetDate_ || // initialization case
now >= background.rateLimitResetDate_) {
now.setHours(now.getHours() + 1); // setHours() handles wrapping correctly.
background.rateLimitResetDate_ = now;
background.rateLimitCount_ = 0;
}
background.rateLimitCount_++;
// rate exceeded?
return background.rateLimitCount_ <= background.MAX_RATE_PER_HOUR_;
};
/**
* Determines if a password has been typed and if so creates alert. Also used
* for sending OTP alerts.
* @param {number} tabId The tab that sent this message.
* @param {!background.Request_} request Request object from
* content_script.
* @param {!background.State_} state State of keypress or keydown.
* @private
*/
background.checkPassword_ = function (tabId, request, state) {
if (!background.checkRateLimit_()) {
return; // This limits content_script brute-forcing the password.
}
if (state['otpMode']) {
return; // If password was recently typed, then no need to check again.
}
if (!request.password) {
return;
}
const hash = background.hashPassword_(request.password);