/
autofill.service.ts
2073 lines (1858 loc) · 67.7 KB
/
autofill.service.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
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 { firstValueFrom } from "rxjs";
import { EventCollectionService } from "@bitwarden/common/abstractions/event/event-collection.service";
import { UserVerificationService } from "@bitwarden/common/auth/abstractions/user-verification/user-verification.service.abstraction";
import { AutofillSettingsServiceAbstraction } from "@bitwarden/common/autofill/services/autofill-settings.service";
import { DomainSettingsService } from "@bitwarden/common/autofill/services/domain-settings.service";
import { InlineMenuVisibilitySetting } from "@bitwarden/common/autofill/types";
import { BillingAccountProfileStateService } from "@bitwarden/common/billing/abstractions/account/billing-account-profile-state.service";
import { EventType } from "@bitwarden/common/enums";
import {
UriMatchStrategySetting,
UriMatchStrategy,
} from "@bitwarden/common/models/domain/domain-service";
import { LogService } from "@bitwarden/common/platform/abstractions/log.service";
import { CipherService } from "@bitwarden/common/vault/abstractions/cipher.service";
import { TotpService } from "@bitwarden/common/vault/abstractions/totp.service";
import { FieldType, CipherType } from "@bitwarden/common/vault/enums";
import { CipherRepromptType } from "@bitwarden/common/vault/enums/cipher-reprompt-type";
import { CipherView } from "@bitwarden/common/vault/models/view/cipher.view";
import { FieldView } from "@bitwarden/common/vault/models/view/field.view";
import { BrowserApi } from "../../platform/browser/browser-api";
import { openVaultItemPasswordRepromptPopout } from "../../vault/popup/utils/vault-popout-window";
import { AutofillPort } from "../enums/autofill-port.enums";
import AutofillField from "../models/autofill-field";
import AutofillPageDetails from "../models/autofill-page-details";
import AutofillScript from "../models/autofill-script";
import {
AutoFillOptions,
AutofillService as AutofillServiceInterface,
FormData,
GenerateFillScriptOptions,
PageDetail,
} from "./abstractions/autofill.service";
import {
AutoFillConstants,
CreditCardAutoFillConstants,
IdentityAutoFillConstants,
} from "./autofill-constants";
export default class AutofillService implements AutofillServiceInterface {
private openVaultItemPasswordRepromptPopout = openVaultItemPasswordRepromptPopout;
private openPasswordRepromptPopoutDebounce: number | NodeJS.Timeout;
private currentlyOpeningPasswordRepromptPopout = false;
private autofillScriptPortsSet = new Set<chrome.runtime.Port>();
static searchFieldNamesSet = new Set(AutoFillConstants.SearchFieldNames);
constructor(
private cipherService: CipherService,
private autofillSettingsService: AutofillSettingsServiceAbstraction,
private totpService: TotpService,
private eventCollectionService: EventCollectionService,
private logService: LogService,
private domainSettingsService: DomainSettingsService,
private userVerificationService: UserVerificationService,
private billingAccountProfileStateService: BillingAccountProfileStateService,
) {}
/**
* Triggers on installation of the extension Handles injecting
* content scripts into all tabs that are currently open, and
* sets up a listener to ensure content scripts can identify
* if the extension context has been disconnected.
*/
async loadAutofillScriptsOnInstall() {
BrowserApi.addListener(chrome.runtime.onConnect, this.handleInjectedScriptPortConnection);
// FIXME: Verify that this floating promise is intentional. If it is, add an explanatory comment and ensure there is proper error handling.
// eslint-disable-next-line @typescript-eslint/no-floating-promises
this.injectAutofillScriptsInAllTabs();
}
/**
* Triggers a complete reload of all autofill scripts on tabs open within
* the user's browsing session. This is done by first disconnecting all
* existing autofill content script ports, which cleans up existing object
* instances, and then re-injecting the autofill scripts into all tabs.
*/
async reloadAutofillScripts() {
this.autofillScriptPortsSet.forEach((port) => {
port.disconnect();
this.autofillScriptPortsSet.delete(port);
});
// FIXME: Verify that this floating promise is intentional. If it is, add an explanatory comment and ensure there is proper error handling.
// eslint-disable-next-line @typescript-eslint/no-floating-promises
this.injectAutofillScriptsInAllTabs();
}
/**
* Injects the autofill scripts into the current tab and all frames
* found within the tab. Temporarily, will conditionally inject
* the refactor of the core autofill script if the feature flag
* is enabled.
* @param {chrome.tabs.Tab} tab
* @param {number} frameId
* @param {boolean} triggeringOnPageLoad
*/
async injectAutofillScripts(
tab: chrome.tabs.Tab,
frameId = 0,
triggeringOnPageLoad = true,
): Promise<void> {
const mainAutofillScript = (await this.getOverlayVisibility())
? "bootstrap-autofill-overlay.js"
: "bootstrap-autofill.js";
const injectedScripts = [mainAutofillScript];
const autoFillOnPageLoadIsEnabled = await this.getAutofillOnPageLoad();
if (triggeringOnPageLoad && autoFillOnPageLoadIsEnabled) {
injectedScripts.push("autofiller.js");
} else {
await BrowserApi.executeScriptInTab(tab.id, {
file: "content/content-message-handler.js",
runAt: "document_start",
});
}
injectedScripts.push("notificationBar.js", "contextMenuHandler.js");
for (const injectedScript of injectedScripts) {
await BrowserApi.executeScriptInTab(tab.id, {
file: `content/${injectedScript}`,
frameId,
runAt: "document_start",
});
}
}
/**
* Gets all forms with password fields and formats the data
* for both forms and password input elements.
* @param {AutofillPageDetails} pageDetails
* @returns {FormData[]}
*/
getFormsWithPasswordFields(pageDetails: AutofillPageDetails): FormData[] {
const formData: FormData[] = [];
const passwordFields = AutofillService.loadPasswordFields(pageDetails, true, true, false, true);
// TODO: this logic prevents multi-step account creation forms (that just start with email)
// from being passed on to the notification bar content script - even if autofill-init.js found the form and email field.
// ex: https://signup.live.com/
if (passwordFields.length === 0) {
return formData;
}
// Back up check for cases where there are several password fields detected,
// but they are not all part of the form b/c of bad HTML
// gather password fields that don't have an enclosing form
const passwordFieldsWithoutForm = passwordFields.filter((pf) => pf.form === undefined);
const formKeys = Object.keys(pageDetails.forms);
const formCount = formKeys.length;
// if we have 3 password fields and only 1 form, and there are password fields that are not within a form
// but there is at least one password field within the form, then most likely this is a poorly built password change form
if (passwordFields.length === 3 && formCount == 1 && passwordFieldsWithoutForm.length > 0) {
// Only one form so get the singular form key
const soloFormKey = formKeys[0];
const atLeastOnePasswordFieldWithinSoloForm =
passwordFields.filter((pf) => pf.form !== null && pf.form === soloFormKey).length > 0;
if (atLeastOnePasswordFieldWithinSoloForm) {
// We have a form with at least one password field,
// so let's make an assumption that the password fields without a form are actually part of this form
passwordFieldsWithoutForm.forEach((pf) => {
pf.form = soloFormKey;
});
}
}
for (const formKey in pageDetails.forms) {
// eslint-disable-next-line
if (!pageDetails.forms.hasOwnProperty(formKey)) {
continue;
}
const formPasswordFields = passwordFields.filter((pf) => formKey === pf.form);
if (formPasswordFields.length > 0) {
let uf = this.findUsernameField(pageDetails, formPasswordFields[0], false, false, false);
if (uf == null) {
// not able to find any viewable username fields. maybe there are some "hidden" ones?
uf = this.findUsernameField(pageDetails, formPasswordFields[0], true, true, false);
}
formData.push({
form: pageDetails.forms[formKey],
password: formPasswordFields[0],
username: uf,
passwords: formPasswordFields,
});
}
}
return formData;
}
/**
* Gets the overlay's visibility setting from the autofill settings service.
*/
async getOverlayVisibility(): Promise<InlineMenuVisibilitySetting> {
return await firstValueFrom(this.autofillSettingsService.inlineMenuVisibility$);
}
/**
* Gets the setting for automatically copying TOTP upon autofill from the autofill settings service.
*/
async getShouldAutoCopyTotp(): Promise<boolean> {
return await firstValueFrom(this.autofillSettingsService.autoCopyTotp$);
}
/**
* Gets the autofill on page load setting from the autofill settings service.
*/
async getAutofillOnPageLoad(): Promise<boolean> {
return await firstValueFrom(this.autofillSettingsService.autofillOnPageLoad$);
}
/**
* Gets the default URI match strategy setting from the domain settings service.
*/
async getDefaultUriMatchStrategy(): Promise<UriMatchStrategySetting> {
return await firstValueFrom(this.domainSettingsService.defaultUriMatchStrategy$);
}
/**
* Autofill a given tab with a given login item
* @param {AutoFillOptions} options Instructions about the autofill operation, including tab and login item
* @returns {Promise<string | null>} The TOTP code of the successfully autofilled login, if any
*/
async doAutoFill(options: AutoFillOptions): Promise<string | null> {
const tab = options.tab;
if (!tab || !options.cipher || !options.pageDetails || !options.pageDetails.length) {
throw new Error("Nothing to auto-fill.");
}
let totp: string | null = null;
const canAccessPremium = await firstValueFrom(
this.billingAccountProfileStateService.hasPremiumFromAnySource$,
);
const defaultUriMatch = await this.getDefaultUriMatchStrategy();
if (!canAccessPremium) {
options.cipher.login.totp = null;
}
let didAutofill = false;
await Promise.all(
options.pageDetails.map(async (pd) => {
// make sure we're still on correct tab
if (pd.tab.id !== tab.id || pd.tab.url !== tab.url) {
return;
}
const fillScript = await this.generateFillScript(pd.details, {
skipUsernameOnlyFill: options.skipUsernameOnlyFill || false,
onlyEmptyFields: options.onlyEmptyFields || false,
onlyVisibleFields: options.onlyVisibleFields || false,
fillNewPassword: options.fillNewPassword || false,
allowTotpAutofill: options.allowTotpAutofill || false,
cipher: options.cipher,
tabUrl: tab.url,
defaultUriMatch: defaultUriMatch,
});
if (!fillScript || !fillScript.script || !fillScript.script.length) {
return;
}
if (
fillScript.untrustedIframe &&
options.allowUntrustedIframe != undefined &&
!options.allowUntrustedIframe
) {
this.logService.info("Auto-fill on page load was blocked due to an untrusted iframe.");
return;
}
// Add a small delay between operations
fillScript.properties.delay_between_operations = 20;
didAutofill = true;
if (!options.skipLastUsed) {
// FIXME: Verify that this floating promise is intentional. If it is, add an explanatory comment and ensure there is proper error handling.
// eslint-disable-next-line @typescript-eslint/no-floating-promises
this.cipherService.updateLastUsedDate(options.cipher.id);
}
// FIXME: Verify that this floating promise is intentional. If it is, add an explanatory comment and ensure there is proper error handling.
// eslint-disable-next-line @typescript-eslint/no-floating-promises
BrowserApi.tabSendMessage(
tab,
{
command: "fillForm",
fillScript: fillScript,
url: tab.url,
pageDetailsUrl: pd.details.url,
},
{ frameId: pd.frameId },
);
// Skip getting the TOTP code for clipboard in these cases
if (
options.cipher.type !== CipherType.Login ||
totp !== null ||
!options.cipher.login.totp ||
(!canAccessPremium && !options.cipher.organizationUseTotp)
) {
return;
}
const shouldAutoCopyTotp = await this.getShouldAutoCopyTotp();
totp = shouldAutoCopyTotp
? await this.totpService.getCode(options.cipher.login.totp)
: null;
}),
);
if (didAutofill) {
// FIXME: Verify that this floating promise is intentional. If it is, add an explanatory comment and ensure there is proper error handling.
// eslint-disable-next-line @typescript-eslint/no-floating-promises
this.eventCollectionService.collect(EventType.Cipher_ClientAutofilled, options.cipher.id);
if (totp !== null) {
return totp;
} else {
return null;
}
} else {
throw new Error("Did not auto-fill.");
}
}
/**
* Autofill the specified tab with the next login item from the cache
* @param {PageDetail[]} pageDetails The data scraped from the page
* @param {chrome.tabs.Tab} tab The tab to be autofilled
* @param {boolean} fromCommand Whether the autofill is triggered by a keyboard shortcut (`true`) or autofill on page load (`false`)
* @returns {Promise<string | null>} The TOTP code of the successfully autofilled login, if any
*/
async doAutoFillOnTab(
pageDetails: PageDetail[],
tab: chrome.tabs.Tab,
fromCommand: boolean,
): Promise<string | null> {
let cipher: CipherView;
if (fromCommand) {
cipher = await this.cipherService.getNextCipherForUrl(tab.url);
} else {
const lastLaunchedCipher = await this.cipherService.getLastLaunchedForUrl(tab.url, true);
if (
lastLaunchedCipher &&
Date.now().valueOf() - lastLaunchedCipher.localData?.lastLaunched?.valueOf() < 30000
) {
cipher = lastLaunchedCipher;
} else {
cipher = await this.cipherService.getLastUsedForUrl(tab.url, true);
}
}
if (cipher == null || (cipher.reprompt === CipherRepromptType.Password && !fromCommand)) {
return null;
}
if (await this.isPasswordRepromptRequired(cipher, tab)) {
if (fromCommand) {
this.cipherService.updateLastUsedIndexForUrl(tab.url);
}
return null;
}
const totpCode = await this.doAutoFill({
tab: tab,
cipher: cipher,
pageDetails: pageDetails,
skipLastUsed: !fromCommand,
skipUsernameOnlyFill: !fromCommand,
onlyEmptyFields: !fromCommand,
onlyVisibleFields: !fromCommand,
fillNewPassword: fromCommand,
allowUntrustedIframe: fromCommand,
allowTotpAutofill: fromCommand,
});
// Update last used index as autofill has succeeded
if (fromCommand) {
this.cipherService.updateLastUsedIndexForUrl(tab.url);
}
return totpCode;
}
async isPasswordRepromptRequired(cipher: CipherView, tab: chrome.tabs.Tab): Promise<boolean> {
const userHasMasterPasswordAndKeyHash =
await this.userVerificationService.hasMasterPasswordAndMasterKeyHash();
if (cipher.reprompt === CipherRepromptType.Password && userHasMasterPasswordAndKeyHash) {
if (!this.isDebouncingPasswordRepromptPopout()) {
await this.openVaultItemPasswordRepromptPopout(tab, {
cipherId: cipher.id,
action: "autofill",
});
}
return true;
}
return false;
}
/**
* Autofill the active tab with the next cipher from the cache
* @param {PageDetail[]} pageDetails The data scraped from the page
* @param {boolean} fromCommand Whether the autofill is triggered by a keyboard shortcut (`true`) or autofill on page load (`false`)
* @returns {Promise<string | null>} The TOTP code of the successfully autofilled login, if any
*/
async doAutoFillActiveTab(
pageDetails: PageDetail[],
fromCommand: boolean,
cipherType?: CipherType,
): Promise<string | null> {
if (!pageDetails[0]?.details?.fields?.length) {
return null;
}
const tab = await this.getActiveTab();
if (!tab || !tab.url) {
return null;
}
if (!cipherType || cipherType === CipherType.Login) {
return await this.doAutoFillOnTab(pageDetails, tab, fromCommand);
}
// Cipher is a non-login type
const cipher: CipherView = (
(await this.cipherService.getAllDecryptedForUrl(tab.url, [cipherType])) || []
).find(({ type }) => type === cipherType);
if (!cipher || cipher.reprompt !== CipherRepromptType.None) {
return null;
}
return await this.doAutoFill({
tab: tab,
cipher: cipher,
pageDetails: pageDetails,
skipLastUsed: !fromCommand,
skipUsernameOnlyFill: !fromCommand,
onlyEmptyFields: !fromCommand,
onlyVisibleFields: !fromCommand,
fillNewPassword: false,
allowUntrustedIframe: fromCommand,
allowTotpAutofill: false,
});
}
/**
* Gets the active tab from the current window.
* Throws an error if no tab is found.
* @returns {Promise<chrome.tabs.Tab>}
* @private
*/
private async getActiveTab(): Promise<chrome.tabs.Tab> {
const tab = await BrowserApi.getTabFromCurrentWindow();
if (!tab) {
throw new Error("No tab found.");
}
return tab;
}
/**
* Generates the autofill script for the specified page details and cipher.
* @param {AutofillPageDetails} pageDetails
* @param {GenerateFillScriptOptions} options
* @returns {Promise<AutofillScript | null>}
* @private
*/
private async generateFillScript(
pageDetails: AutofillPageDetails,
options: GenerateFillScriptOptions,
): Promise<AutofillScript | null> {
if (!pageDetails || !options.cipher) {
return null;
}
let fillScript = new AutofillScript();
const filledFields: { [id: string]: AutofillField } = {};
const fields = options.cipher.fields;
if (fields && fields.length) {
const fieldNames: string[] = [];
fields.forEach((f) => {
if (AutofillService.hasValue(f.name)) {
fieldNames.push(f.name.toLowerCase());
}
});
pageDetails.fields.forEach((field) => {
// eslint-disable-next-line
if (filledFields.hasOwnProperty(field.opid)) {
return;
}
if (!field.viewable && field.tagName !== "span") {
return;
}
// Check if the input is an untyped/mistyped search input
if (AutofillService.isSearchField(field)) {
return;
}
const matchingIndex = this.findMatchingFieldIndex(field, fieldNames);
if (matchingIndex > -1) {
const matchingField: FieldView = fields[matchingIndex];
let val: string;
if (matchingField.type === FieldType.Linked) {
// Assumption: Linked Field is not being used to autofill a boolean value
val = options.cipher.linkedFieldValue(matchingField.linkedId) as string;
} else {
val = matchingField.value;
if (val == null && matchingField.type === FieldType.Boolean) {
val = "false";
}
}
filledFields[field.opid] = field;
AutofillService.fillByOpid(fillScript, field, val);
}
});
}
switch (options.cipher.type) {
case CipherType.Login:
fillScript = await this.generateLoginFillScript(
fillScript,
pageDetails,
filledFields,
options,
);
break;
case CipherType.Card:
fillScript = this.generateCardFillScript(fillScript, pageDetails, filledFields, options);
break;
case CipherType.Identity:
fillScript = this.generateIdentityFillScript(
fillScript,
pageDetails,
filledFields,
options,
);
break;
default:
return null;
}
return fillScript;
}
/**
* Generates the autofill script for the specified page details and login cipher item.
* @param {AutofillScript} fillScript
* @param {AutofillPageDetails} pageDetails
* @param {{[p: string]: AutofillField}} filledFields
* @param {GenerateFillScriptOptions} options
* @returns {Promise<AutofillScript | null>}
* @private
*/
private async generateLoginFillScript(
fillScript: AutofillScript,
pageDetails: AutofillPageDetails,
filledFields: { [id: string]: AutofillField },
options: GenerateFillScriptOptions,
): Promise<AutofillScript | null> {
if (!options.cipher.login) {
return null;
}
const passwords: AutofillField[] = [];
const usernames: AutofillField[] = [];
const totps: AutofillField[] = [];
let pf: AutofillField = null;
let username: AutofillField = null;
let totp: AutofillField = null;
const login = options.cipher.login;
fillScript.savedUrls =
login?.uris?.filter((u) => u.match != UriMatchStrategy.Never).map((u) => u.uri) ?? [];
fillScript.untrustedIframe = await this.inUntrustedIframe(pageDetails.url, options);
let passwordFields = AutofillService.loadPasswordFields(
pageDetails,
false,
false,
options.onlyEmptyFields,
options.fillNewPassword,
);
if (!passwordFields.length && !options.onlyVisibleFields) {
// not able to find any viewable password fields. maybe there are some "hidden" ones?
passwordFields = AutofillService.loadPasswordFields(
pageDetails,
true,
true,
options.onlyEmptyFields,
options.fillNewPassword,
);
}
for (const formKey in pageDetails.forms) {
// eslint-disable-next-line
if (!pageDetails.forms.hasOwnProperty(formKey)) {
continue;
}
passwordFields.forEach((passField) => {
pf = passField;
passwords.push(pf);
if (login.username) {
username = this.findUsernameField(pageDetails, pf, false, false, false);
if (!username && !options.onlyVisibleFields) {
// not able to find any viewable username fields. maybe there are some "hidden" ones?
username = this.findUsernameField(pageDetails, pf, true, true, false);
}
if (username) {
usernames.push(username);
}
}
if (options.allowTotpAutofill && login.totp) {
totp = this.findTotpField(pageDetails, pf, false, false, false);
if (!totp && !options.onlyVisibleFields) {
// not able to find any viewable totp fields. maybe there are some "hidden" ones?
totp = this.findTotpField(pageDetails, pf, true, true, false);
}
if (totp) {
totps.push(totp);
}
}
});
}
if (passwordFields.length && !passwords.length) {
// The page does not have any forms with password fields. Use the first password field on the page and the
// input field just before it as the username.
pf = passwordFields[0];
passwords.push(pf);
if (login.username && pf.elementNumber > 0) {
username = this.findUsernameField(pageDetails, pf, false, false, true);
if (!username && !options.onlyVisibleFields) {
// not able to find any viewable username fields. maybe there are some "hidden" ones?
username = this.findUsernameField(pageDetails, pf, true, true, true);
}
if (username) {
usernames.push(username);
}
}
if (options.allowTotpAutofill && login.totp && pf.elementNumber > 0) {
totp = this.findTotpField(pageDetails, pf, false, false, true);
if (!totp && !options.onlyVisibleFields) {
// not able to find any viewable username fields. maybe there are some "hidden" ones?
totp = this.findTotpField(pageDetails, pf, true, true, true);
}
if (totp) {
totps.push(totp);
}
}
}
if (!passwordFields.length) {
// No password fields on this page. Let's try to just fuzzy fill the username.
pageDetails.fields.forEach((f) => {
if (
!options.skipUsernameOnlyFill &&
f.viewable &&
(f.type === "text" || f.type === "email" || f.type === "tel") &&
AutofillService.fieldIsFuzzyMatch(f, AutoFillConstants.UsernameFieldNames)
) {
usernames.push(f);
}
if (
options.allowTotpAutofill &&
f.viewable &&
(f.type === "text" || f.type === "number") &&
(AutofillService.fieldIsFuzzyMatch(f, AutoFillConstants.TotpFieldNames) ||
f.autoCompleteType === "one-time-code")
) {
totps.push(f);
}
});
}
usernames.forEach((u) => {
// eslint-disable-next-line
if (filledFields.hasOwnProperty(u.opid)) {
return;
}
filledFields[u.opid] = u;
AutofillService.fillByOpid(fillScript, u, login.username);
});
passwords.forEach((p) => {
// eslint-disable-next-line
if (filledFields.hasOwnProperty(p.opid)) {
return;
}
filledFields[p.opid] = p;
AutofillService.fillByOpid(fillScript, p, login.password);
});
if (options.allowTotpAutofill) {
await Promise.all(
totps.map(async (t) => {
if (Object.prototype.hasOwnProperty.call(filledFields, t.opid)) {
return;
}
filledFields[t.opid] = t;
const totpValue = await this.totpService.getCode(login.totp);
AutofillService.fillByOpid(fillScript, t, totpValue);
}),
);
}
fillScript = AutofillService.setFillScriptForFocus(filledFields, fillScript);
return fillScript;
}
/**
* Generates the autofill script for the specified page details and credit card cipher item.
* @param {AutofillScript} fillScript
* @param {AutofillPageDetails} pageDetails
* @param {{[p: string]: AutofillField}} filledFields
* @param {GenerateFillScriptOptions} options
* @returns {AutofillScript|null}
* @private
*/
private generateCardFillScript(
fillScript: AutofillScript,
pageDetails: AutofillPageDetails,
filledFields: { [id: string]: AutofillField },
options: GenerateFillScriptOptions,
): AutofillScript | null {
if (!options.cipher.card) {
return null;
}
const fillFields: { [id: string]: AutofillField } = {};
pageDetails.fields.forEach((f) => {
if (AutofillService.isExcludedFieldType(f, AutoFillConstants.ExcludedAutofillTypes)) {
return;
}
for (let i = 0; i < CreditCardAutoFillConstants.CardAttributes.length; i++) {
const attr = CreditCardAutoFillConstants.CardAttributes[i];
// eslint-disable-next-line
if (!f.hasOwnProperty(attr) || !f[attr] || !f.viewable) {
continue;
}
// ref https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#autofill
// ref https://developers.google.com/web/fundamentals/design-and-ux/input/forms/
if (
!fillFields.cardholderName &&
AutofillService.isFieldMatch(
f[attr],
CreditCardAutoFillConstants.CardHolderFieldNames,
CreditCardAutoFillConstants.CardHolderFieldNameValues,
)
) {
fillFields.cardholderName = f;
break;
} else if (
!fillFields.number &&
AutofillService.isFieldMatch(
f[attr],
CreditCardAutoFillConstants.CardNumberFieldNames,
CreditCardAutoFillConstants.CardNumberFieldNameValues,
)
) {
fillFields.number = f;
break;
} else if (
!fillFields.exp &&
AutofillService.isFieldMatch(
f[attr],
CreditCardAutoFillConstants.CardExpiryFieldNames,
CreditCardAutoFillConstants.CardExpiryFieldNameValues,
)
) {
fillFields.exp = f;
break;
} else if (
!fillFields.expMonth &&
AutofillService.isFieldMatch(f[attr], CreditCardAutoFillConstants.ExpiryMonthFieldNames)
) {
fillFields.expMonth = f;
break;
} else if (
!fillFields.expYear &&
AutofillService.isFieldMatch(f[attr], CreditCardAutoFillConstants.ExpiryYearFieldNames)
) {
fillFields.expYear = f;
break;
} else if (
!fillFields.code &&
AutofillService.isFieldMatch(f[attr], CreditCardAutoFillConstants.CVVFieldNames)
) {
fillFields.code = f;
break;
} else if (
!fillFields.brand &&
AutofillService.isFieldMatch(f[attr], CreditCardAutoFillConstants.CardBrandFieldNames)
) {
fillFields.brand = f;
break;
}
}
});
const card = options.cipher.card;
this.makeScriptAction(fillScript, card, fillFields, filledFields, "cardholderName");
this.makeScriptAction(fillScript, card, fillFields, filledFields, "number");
this.makeScriptAction(fillScript, card, fillFields, filledFields, "code");
this.makeScriptAction(fillScript, card, fillFields, filledFields, "brand");
if (fillFields.expMonth && AutofillService.hasValue(card.expMonth)) {
let expMonth: string = card.expMonth;
if (fillFields.expMonth.selectInfo && fillFields.expMonth.selectInfo.options) {
let index: number = null;
const siOptions = fillFields.expMonth.selectInfo.options;
if (siOptions.length === 12) {
index = parseInt(card.expMonth, null) - 1;
} else if (siOptions.length === 13) {
if (
siOptions[0][0] != null &&
siOptions[0][0] !== "" &&
(siOptions[12][0] == null || siOptions[12][0] === "")
) {
index = parseInt(card.expMonth, null) - 1;
} else {
index = parseInt(card.expMonth, null);
}
}
if (index != null) {
const option = siOptions[index];
if (option.length > 1) {
expMonth = option[1];
}
}
} else if (
(this.fieldAttrsContain(fillFields.expMonth, "mm") ||
fillFields.expMonth.maxLength === 2) &&
expMonth.length === 1
) {
expMonth = "0" + expMonth;
}
filledFields[fillFields.expMonth.opid] = fillFields.expMonth;
AutofillService.fillByOpid(fillScript, fillFields.expMonth, expMonth);
}
if (fillFields.expYear && AutofillService.hasValue(card.expYear)) {
let expYear: string = card.expYear;
if (fillFields.expYear.selectInfo && fillFields.expYear.selectInfo.options) {
for (let i = 0; i < fillFields.expYear.selectInfo.options.length; i++) {
const o: [string, string] = fillFields.expYear.selectInfo.options[i];
if (o[0] === card.expYear || o[1] === card.expYear) {
expYear = o[1];
break;
}
if (
o[1].length === 2 &&
card.expYear.length === 4 &&
o[1] === card.expYear.substring(2)
) {
expYear = o[1];
break;
}
const colonIndex = o[1].indexOf(":");
if (colonIndex > -1 && o[1].length > colonIndex + 1) {
const val = o[1].substring(colonIndex + 2);
if (val != null && val.trim() !== "" && val === card.expYear) {
expYear = o[1];
break;
}
}
}
} else if (
this.fieldAttrsContain(fillFields.expYear, "yyyy") ||
fillFields.expYear.maxLength === 4
) {
if (expYear.length === 2) {
expYear = "20" + expYear;
}
} else if (
this.fieldAttrsContain(fillFields.expYear, "yy") ||
fillFields.expYear.maxLength === 2
) {
if (expYear.length === 4) {
expYear = expYear.substr(2);
}
}
filledFields[fillFields.expYear.opid] = fillFields.expYear;
AutofillService.fillByOpid(fillScript, fillFields.expYear, expYear);
}
if (
fillFields.exp &&
AutofillService.hasValue(card.expMonth) &&
AutofillService.hasValue(card.expYear)
) {
const fullMonth = ("0" + card.expMonth).slice(-2);
let fullYear: string = card.expYear;
let partYear: string = null;
if (fullYear.length === 2) {
partYear = fullYear;
fullYear = "20" + fullYear;
} else if (fullYear.length === 4) {
partYear = fullYear.substr(2, 2);
}
let exp: string = null;
for (let i = 0; i < CreditCardAutoFillConstants.MonthAbbr.length; i++) {
if (
this.fieldAttrsContain(
fillFields.exp,
CreditCardAutoFillConstants.MonthAbbr[i] +
"/" +
CreditCardAutoFillConstants.YearAbbrLong[i],
)
) {
exp = fullMonth + "/" + fullYear;
} else if (
this.fieldAttrsContain(
fillFields.exp,
CreditCardAutoFillConstants.MonthAbbr[i] +
"/" +
CreditCardAutoFillConstants.YearAbbrShort[i],
) &&
partYear != null
) {
exp = fullMonth + "/" + partYear;
} else if (
this.fieldAttrsContain(
fillFields.exp,
CreditCardAutoFillConstants.YearAbbrLong[i] +
"/" +
CreditCardAutoFillConstants.MonthAbbr[i],
)
) {
exp = fullYear + "/" + fullMonth;
} else if (
this.fieldAttrsContain(
fillFields.exp,
CreditCardAutoFillConstants.YearAbbrShort[i] +
"/" +
CreditCardAutoFillConstants.MonthAbbr[i],
) &&
partYear != null
) {
exp = partYear + "/" + fullMonth;
} else if (
this.fieldAttrsContain(
fillFields.exp,
CreditCardAutoFillConstants.MonthAbbr[i] +
"-" +
CreditCardAutoFillConstants.YearAbbrLong[i],
)
) {
exp = fullMonth + "-" + fullYear;
} else if (