-
Notifications
You must be signed in to change notification settings - Fork 55
/
Copy pathbackground.js
1207 lines (1098 loc) · 38.5 KB
/
background.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
//-------------------------------- Background initialisation --------------------------------//
"use strict";
require("chrome-extension-async");
const sha1 = require("sha1");
const idb = require("idb");
const BrowserpassURL = require("@browserpass/url");
const helpers = require("./helpers");
// native application id
var appID = "com.github.browserpass.native";
// default settings
var defaultSettings = {
autoSubmit: false,
gpgPath: null,
stores: {},
foreignFills: {},
username: null,
theme: "auto",
enableOTP: false,
caps: {
save: false,
delete: false,
tree: false,
},
};
var authListeners = {};
var badgeCache = {
files: null,
settings: null,
expires: Date.now(),
isRefreshing: false,
};
// the last text copied to the clipboard is stored here in order to be cleared after 60 seconds
let lastCopiedText = null;
chrome.browserAction.setBadgeBackgroundColor({
color: "#666",
});
// watch for tab updates
chrome.tabs.onUpdated.addListener((tabId, info) => {
// unregister any auth listeners for this tab
if (info.status === "complete") {
if (authListeners[tabId]) {
chrome.webRequest.onAuthRequired.removeListener(authListeners[tabId]);
delete authListeners[tabId];
}
}
// redraw badge counter
updateMatchingPasswordsCount(tabId);
});
// handle incoming messages
chrome.runtime.onMessage.addListener(function (message, sender, sendResponse) {
receiveMessage(message, sender, sendResponse);
// allow async responses after this function returns
return true;
});
// handle keyboard shortcuts
chrome.commands.onCommand.addListener(async (command) => {
switch (command) {
case "fillBest":
try {
const settings = await getFullSettings();
if (settings.tab.url.match(/^(chrome|about):/)) {
// only fill on real domains
return;
}
handleMessage(settings, { action: "listFiles" }, (listResults) => {
const logins = helpers.prepareLogins(listResults.files, settings);
const bestLogin = helpers.filterSortLogins(logins, "", true)[0];
if (bestLogin) {
handleMessage(settings, { action: "fill", login: bestLogin }, () => {});
}
});
} catch (e) {
console.log(e);
}
break;
}
});
// handle fired alarms
chrome.alarms.onAlarm.addListener((alarm) => {
if (alarm.name === "clearClipboard") {
if (readFromClipboard() === lastCopiedText) {
copyToClipboard("", false);
}
lastCopiedText = null;
}
});
chrome.runtime.onInstalled.addListener(onExtensionInstalled);
//----------------------------------- Function definitions ----------------------------------//
/**
* Set badge text with the number of matching password entries
*
* @since 3.0.0
*
* @param int tabId Tab id
* @param bool forceRefresh force invalidate cache
* @return void
*/
async function updateMatchingPasswordsCount(tabId, forceRefresh = false) {
if (badgeCache.isRefreshing) {
return;
}
try {
if (forceRefresh || Date.now() > badgeCache.expires) {
badgeCache.isRefreshing = true;
let settings = await getFullSettings();
let response = await hostAction(settings, "list");
if (response.status != "ok") {
throw new Error(JSON.stringify(response));
}
const CACHE_TTL_MS = 60 * 1000;
badgeCache = {
files: response.data.files,
settings: settings,
expires: Date.now() + CACHE_TTL_MS,
isRefreshing: false,
};
}
try {
const tab = await chrome.tabs.get(tabId);
badgeCache.settings.origin = new BrowserpassURL(tab.url).origin;
} catch (e) {
throw new Error(`Unable to determine domain of the tab with id ${tabId}`);
}
// Compute badge counter
const files = helpers.ignoreFiles(badgeCache.files, badgeCache.settings);
const logins = helpers.prepareLogins(files, badgeCache.settings);
const matchedPasswordsCount = logins.reduce(
(acc, login) => acc + (login.recent.count || login.inCurrentHost ? 1 : 0),
0
);
// Set badge for the current tab
chrome.browserAction.setBadgeText({
text: "" + (matchedPasswordsCount || ""),
tabId: tabId,
});
} catch (e) {
console.log(e);
}
}
/**
* Copy text to clipboard and optionally clear it from the clipboard after one minute
*
* @since 3.2.0
*
* @param string text Text to copy
* @param boolean clear Whether to clear the clipboard after one minute
* @return void
*/
function copyToClipboard(text, clear = true) {
document.addEventListener(
"copy",
function (e) {
e.clipboardData.setData("text/plain", text);
e.preventDefault();
},
{ once: true }
);
document.execCommand("copy");
if (clear) {
lastCopiedText = text;
chrome.alarms.create("clearClipboard", { delayInMinutes: 1 });
}
}
/**
* Read plain text from clipboard
*
* @since 3.2.0
*
* @return string The current plaintext content of the clipboard
*/
function readFromClipboard() {
const ta = document.createElement("textarea");
// these lines are carefully crafted to make paste work in both Chrome and Firefox
ta.contentEditable = true;
ta.textContent = "";
document.body.appendChild(ta);
ta.select();
document.execCommand("paste");
const content = ta.value;
document.body.removeChild(ta);
return content;
}
/**
* Save login to recent list for current domain
*
* @since 3.0.0
*
* @param object settings Settings object
* @param string host Hostname
* @param object login Login object
* @param bool remove Remove this item from recent history
* @return void
*/
async function saveRecent(settings, login, remove = false) {
var ignoreInterval = 60000; // 60 seconds - don't increment counter twice within this window
// save store timestamp
localStorage.setItem("recent:" + login.store.id, JSON.stringify(Date.now()));
// update login usage count & timestamp
if (Date.now() > login.recent.when + ignoreInterval) {
login.recent.count++;
}
login.recent.when = Date.now();
settings.recent[sha1(settings.origin + sha1(login.store.id + sha1(login.login)))] =
login.recent;
// save to local storage
localStorage.setItem("recent", JSON.stringify(settings.recent));
// a new entry was added to the popup matching list, need to refresh the count
if (!login.inCurrentHost && login.recent.count === 1) {
updateMatchingPasswordsCount(settings.tab.id, true);
}
// save to usage log
try {
const DB_VERSION = 1;
const db = await idb.openDB("browserpass", DB_VERSION, {
upgrade(db) {
db.createObjectStore("log", { keyPath: "time" });
},
});
await db.add("log", { time: Date.now(), host: settings.origin, login: login.login });
} catch {
// ignore any errors and proceed without saving a log entry to Indexed DB
}
}
/**
* Call injected code to fill the form
*
* @param object settings Settings object
* @param object request Request details
* @param boolean allFrames Dispatch to all frames
* @param boolean allowForeign Allow foreign-origin iframes
* @param boolean allowNoSecret Allow forms that don't contain a password field
* @return array list of filled fields
*/
async function dispatchFill(settings, request, allFrames, allowForeign, allowNoSecret) {
request = Object.assign(helpers.deepCopy(request), {
allowForeign: allowForeign,
allowNoSecret: allowNoSecret,
foreignFills: settings.foreignFills[settings.origin] || {},
});
let perFrameResults = await chrome.tabs.executeScript(settings.tab.id, {
allFrames: allFrames,
code: `window.browserpass.fillLogin(${JSON.stringify(request)});`,
});
// merge filled fields into a single array
let filledFields = perFrameResults
.reduce((merged, frameResult) => merged.concat(frameResult.filledFields), [])
.filter((val, i, merged) => merged.indexOf(val) === i);
// if user answered a foreign-origin confirmation,
// store the answers in the settings
let foreignFillsChanged = false;
for (let frame of perFrameResults) {
if (typeof frame.foreignFill !== "undefined") {
if (typeof settings.foreignFills[settings.origin] === "undefined") {
settings.foreignFills[settings.origin] = {};
}
settings.foreignFills[settings.origin][frame.foreignOrigin] = frame.foreignFill;
foreignFillsChanged = true;
}
}
if (foreignFillsChanged) {
await saveSettings(settings);
}
return filledFields;
}
/**
* Call injected code to focus or submit the form
*
* @param object settings Settings object
* @param object request Request details
* @param boolean allFrames Dispatch to all frames
* @param boolean allowForeign Allow foreign-origin iframes
* @return void
*/
async function dispatchFocusOrSubmit(settings, request, allFrames, allowForeign) {
request = Object.assign(helpers.deepCopy(request), {
allowForeign: allowForeign,
foreignFills: settings.foreignFills[settings.origin] || {},
});
await chrome.tabs.executeScript(settings.tab.id, {
allFrames: allFrames,
code: `window.browserpass.focusOrSubmit(${JSON.stringify(request)});`,
});
}
/**
* Inject script
*
* @param object settings Settings object
* @param boolean allFrames Inject in all frames
* @return object Cancellable promise
*/
async function injectScript(settings, allFrames) {
const MAX_WAIT = 1000;
return new Promise(async (resolve, reject) => {
const waitTimeout = setTimeout(reject, MAX_WAIT);
await chrome.tabs.executeScript(settings.tab.id, {
allFrames: allFrames,
file: "js/inject.dist.js",
});
clearTimeout(waitTimeout);
resolve(true);
});
}
/**
* Fill form fields
*
* @param object settings Settings object
* @param object login Login object
* @param array fields List of fields to fill
* @return array List of filled fields
*/
async function fillFields(settings, login, fields) {
// inject script
try {
await injectScript(settings, false);
} catch {
throw new Error("Unable to inject script in the top frame");
}
let injectedAllFrames = false;
try {
await injectScript(settings, true);
injectedAllFrames = true;
} catch {
// we'll proceed with trying to fill only the top frame
}
// build fill request
var fillRequest = {
origin: new BrowserpassURL(settings.tab.url).origin,
login: login,
fields: fields,
};
let allFrames = false;
let allowForeign = false;
let allowNoSecret = !fields.includes("secret");
let filledFields = [];
let importantFieldToFill = fields.includes("openid") ? "openid" : "secret";
// fill form via injected script
filledFields = filledFields.concat(
await dispatchFill(settings, fillRequest, allFrames, allowForeign, allowNoSecret)
);
if (injectedAllFrames) {
// try again using same-origin frames if we couldn't fill an "important" field
if (!filledFields.includes(importantFieldToFill)) {
allFrames = true;
filledFields = filledFields.concat(
await dispatchFill(settings, fillRequest, allFrames, allowForeign, allowNoSecret)
);
}
// try again using all available frames if we couldn't fill an "important" field
if (
!filledFields.includes(importantFieldToFill) &&
settings.foreignFills[settings.origin] !== false
) {
allowForeign = true;
filledFields = filledFields.concat(
await dispatchFill(settings, fillRequest, allFrames, allowForeign, allowNoSecret)
);
}
}
// try again, but don't require a password field (if it was required until now)
if (!allowNoSecret) {
allowNoSecret = true;
// try again using only the top frame
if (!filledFields.length) {
allFrames = false;
allowForeign = false;
filledFields = filledFields.concat(
await dispatchFill(settings, fillRequest, allFrames, allowForeign, allowNoSecret)
);
}
if (injectedAllFrames) {
// try again using same-origin frames
if (!filledFields.length) {
allFrames = true;
filledFields = filledFields.concat(
await dispatchFill(
settings,
fillRequest,
allFrames,
allowForeign,
allowNoSecret
)
);
}
// try again using all available frames
if (!filledFields.length && settings.foreignFills[settings.origin] !== false) {
allowForeign = true;
filledFields = filledFields.concat(
await dispatchFill(
settings,
fillRequest,
allFrames,
allowForeign,
allowNoSecret
)
);
}
}
}
if (!filledFields.length) {
throw new Error(`No fillable forms available for fields: ${fields.join(", ")}`);
}
// build focus or submit request
let focusOrSubmitRequest = {
origin: new BrowserpassURL(settings.tab.url).origin,
autoSubmit: helpers.getSetting("autoSubmit", login, settings),
filledFields: filledFields,
};
// try to focus or submit form with the settings that were used to fill it
await dispatchFocusOrSubmit(settings, focusOrSubmitRequest, allFrames, allowForeign);
return filledFields;
}
/**
* Get Local settings from the extension
*
* @since 3.0.0
*
* @return object Local settings from the extension
*/
function getLocalSettings() {
var settings = helpers.deepCopy(defaultSettings);
for (var key in settings) {
var value = localStorage.getItem(key);
if (value !== null) {
settings[key] = JSON.parse(value);
}
}
return settings;
}
/**
* Get full settings from the extension and host application
*
* @since 3.0.0
*
* @return object Full settings object
*/
async function getFullSettings() {
var settings = getLocalSettings();
var configureSettings = Object.assign(helpers.deepCopy(settings), {
defaultStore: {},
});
var response = await hostAction(configureSettings, "configure");
if (response.status != "ok") {
settings.hostError = response;
}
settings.version = response.version;
const EDIT_VERSION = 3 * 1000000 + 1 * 1000 + 0;
// host capabilities
settings.caps.save = settings.version >= EDIT_VERSION;
settings.caps.delete = settings.version >= EDIT_VERSION;
settings.caps.tree = settings.version >= EDIT_VERSION;
// Fill store settings, only makes sense if 'configure' succeeded
if (response.status === "ok") {
if (Object.keys(settings.stores).length > 0) {
// there are user-configured stores present
for (var storeId in settings.stores) {
if (response.data.storeSettings.hasOwnProperty(storeId)) {
var fileSettings = JSON.parse(response.data.storeSettings[storeId]);
if (typeof settings.stores[storeId].settings !== "object") {
settings.stores[storeId].settings = {};
}
var storeSettings = settings.stores[storeId].settings;
for (var settingKey in fileSettings) {
if (!storeSettings.hasOwnProperty(settingKey)) {
storeSettings[settingKey] = fileSettings[settingKey];
}
}
}
}
} else {
// no user-configured stores, so use the default store
settings.stores.default = {
id: "default",
name: "pass",
path: response.data.defaultStore.path,
};
var fileSettings = JSON.parse(response.data.defaultStore.settings);
if (typeof settings.stores.default.settings !== "object") {
settings.stores.default.settings = {};
}
var storeSettings = settings.stores.default.settings;
for (var settingKey in fileSettings) {
if (!storeSettings.hasOwnProperty(settingKey)) {
storeSettings[settingKey] = fileSettings[settingKey];
}
}
}
}
// Fill recent data
for (var storeId in settings.stores) {
var when = localStorage.getItem("recent:" + storeId);
if (when) {
settings.stores[storeId].when = JSON.parse(when);
} else {
settings.stores[storeId].when = 0;
}
}
settings.recent = localStorage.getItem("recent");
if (settings.recent) {
settings.recent = JSON.parse(settings.recent);
} else {
settings.recent = {};
}
// Fill current tab info
try {
settings.tab = (await chrome.tabs.query({ active: true, currentWindow: true }))[0];
let originInfo = new BrowserpassURL(settings.tab.url);
settings.origin = originInfo.origin;
} catch (e) {}
return settings;
}
/**
* Get most relevant setting value
*
* @param string key Setting key
* @param object login Login object
* @param object settings Settings object
* @return object Setting value
*/
function getSetting(key, login, settings) {
if (typeof login.settings[key] !== "undefined") {
return login.settings[key];
}
if (typeof settings.stores[login.store.id].settings[key] !== "undefined") {
return settings.stores[login.store.id].settings[key];
}
return settings[key];
}
/**
* Handle modal authentication requests (e.g. HTTP basic)
*
* @since 3.0.0
*
* @param object requestDetails Auth request details
* @return object Authentication credentials or {}
*/
function handleModalAuth(requestDetails) {
var launchHost = requestDetails.url.match(/:\/\/([^\/]+)/)[1];
// don't attempt authentication against the same login more than once
if (!this.login.allowFill) {
return {};
}
this.login.allowFill = false;
// don't attempt authentication outside the main frame
if (requestDetails.type !== "main_frame") {
return {};
}
// ensure the auth domain is the same, or ask the user for permissions to continue
if (launchHost !== requestDetails.challenger.host) {
var message =
"You are about to send login credentials to a domain that is different than " +
"the one you launched from the browserpass extension. Do you wish to proceed?\n\n" +
"Realm: " +
requestDetails.realm +
"\n" +
"Launched URL: " +
this.url +
"\n" +
"Authentication URL: " +
requestDetails.url;
if (!confirm(message)) {
return {};
}
}
// ask the user before sending credentials over an insecure connection
if (!requestDetails.url.match(/^https:/i)) {
var message =
"You are about to send login credentials via an insecure connection!\n\n" +
"Are you sure you want to do this? If there is an attacker watching your " +
"network traffic, they may be able to see your username and password.\n\n" +
"URL: " +
requestDetails.url;
if (!confirm(message)) {
return {};
}
}
// supply credentials
return {
authCredentials: {
username: this.login.fields.login,
password: this.login.fields.secret,
},
};
}
/**
* Handle a message from elsewhere within the extension
*
* @since 3.0.0
*
* @param object settings Settings object
* @param mixed message Incoming message
* @param function(mixed) sendResponse Callback to send response
* @return void
*/
async function handleMessage(settings, message, sendResponse) {
// check that action is present
if (typeof message !== "object" || !message.hasOwnProperty("action")) {
sendResponse({ status: "error", message: "Action is missing" });
return;
}
// fetch file & parse fields if a login entry is present
try {
// do not fetch file for new login entries
if (typeof message.login !== "undefined" && message.action != "add") {
await parseFields(settings, message.login);
}
} catch (e) {
sendResponse({
status: "error",
message: "Unable to fetch and parse login fields: " + e.toString(),
});
return;
}
// route action
switch (message.action) {
case "getSettings":
sendResponse({
status: "ok",
settings: settings,
});
break;
case "saveSettings":
try {
await saveSettings(message.settings);
sendResponse({ status: "ok" });
} catch (e) {
sendResponse({
status: "error",
message: e.message,
});
}
break;
case "listFiles":
try {
var response = await hostAction(settings, "list");
if (response.status != "ok") {
throw new Error(JSON.stringify(response)); // TODO handle host error
}
let files = helpers.ignoreFiles(response.data.files, settings);
sendResponse({ status: "ok", files });
} catch (e) {
sendResponse({
status: "error",
message: "Unable to enumerate password files. " + e.toString(),
});
}
break;
case "listDirs":
try {
var response = await hostAction(settings, "tree");
if (response.status != "ok") {
throw new Error(JSON.stringify(response));
}
let dirs = response.data.directories;
sendResponse({ status: "ok", dirs });
} catch (e) {
sendResponse({
status: "error",
message: "Unable to enumerate directory trees. " + e.toString(),
});
}
break;
case "add":
case "save":
try {
var response = await hostAction(settings, "save", {
storeId: message.login.store.id,
file: `${message.login.login}.gpg`,
contents: message.params.rawContents,
});
if (response.status != "ok") {
alert(`Save failed: ${response.params.message}`);
throw new Error(JSON.stringify(response)); // TODO handle host error
}
sendResponse({ status: "ok" });
} catch (e) {
sendResponse({
status: "error",
message: "Unable to save password file" + e.toString(),
});
}
break;
case "delete":
try {
var response = await hostAction(settings, "delete", {
storeId: message.login.store.id,
file: `${message.login.login}.gpg`,
});
if (response.status != "ok") {
alert(`Delete failed: ${response.params.message}`);
throw new Error(JSON.stringify(response));
}
sendResponse({ status: "ok" });
} catch (e) {
sendResponse({
status: "error",
message: "Unable to delete password file" + e.toString(),
});
}
break;
case "copyPassword":
try {
copyToClipboard(message.login.fields.secret);
await saveRecent(settings, message.login);
sendResponse({ status: "ok" });
} catch (e) {
sendResponse({
status: "error",
message: "Unable to copy password",
});
}
break;
case "copyUsername":
try {
copyToClipboard(message.login.fields.login);
await saveRecent(settings, message.login);
sendResponse({ status: "ok" });
} catch (e) {
sendResponse({
status: "error",
message: "Unable to copy username",
});
}
break;
case "copyOTP":
if (helpers.getSetting("enableOTP", message.login, settings)) {
try {
if (!message.login.fields.otp) {
throw new Exception("No OTP seed available");
}
copyToClipboard(helpers.makeTOTP(message.login.fields.otp.params));
sendResponse({ status: "ok" });
} catch (e) {
sendResponse({
status: "error",
message: "Unable to copy OTP token",
});
}
} else {
sendResponse({ status: "error", message: "OTP support is disabled" });
}
break;
case "getDetails":
sendResponse({ status: "ok", login: message.login });
break;
case "launch":
case "launchInNewTab":
try {
var url = message.login.fields.url || message.login.host;
if (!url) {
throw new Error("No URL is defined for this entry");
}
if (!url.match(/:\/\//)) {
url = "http://" + url;
}
const tab =
message.action === "launch"
? await chrome.tabs.update(settings.tab.id, { url: url })
: await chrome.tabs.create({ url: url });
if (authListeners[tab.id]) {
chrome.tabs.onUpdated.removeListener(authListeners[tab.id]);
delete authListeners[tab.id];
}
authListeners[tab.id] = handleModalAuth.bind({
url: url,
login: message.login,
});
chrome.webRequest.onAuthRequired.addListener(
authListeners[tab.id],
{ urls: ["*://*/*"], tabId: tab.id },
["blocking"]
);
sendResponse({ status: "ok" });
} catch (e) {
sendResponse({
status: "error",
message: "Unable to launch URL: " + e.toString(),
});
}
break;
case "fill":
try {
let fields = message.login.fields.openid ? ["openid"] : ["login", "secret"];
// dispatch initial fill request
var filledFields = await fillFields(settings, message.login, fields);
await saveRecent(settings, message.login);
// no need to check filledFields, because fillFields() already throws an error if empty
sendResponse({ status: "ok", filledFields: filledFields });
// copy OTP token after fill
if (
typeof message.login !== "undefined" &&
helpers.getSetting("enableOTP", message.login, settings) &&
message.login.fields.hasOwnProperty("otp")
) {
copyToClipboard(helpers.makeTOTP(message.login.fields.otp.params));
}
} catch (e) {
try {
sendResponse({
status: "error",
message: e.toString(),
});
} catch (e) {
// TODO An error here is typically a closed message port, due to a popup taking focus
// away from the extension menu and the menu closing as a result. Need to investigate
// whether triggering the extension menu from the background script is possible.
console.log(e);
}
}
break;
case "clearUsageData":
try {
await clearUsageData();
sendResponse({ status: "ok" });
} catch (e) {
sendResponse({
status: "error",
message: e.message,
});
}
break;
default:
sendResponse({
status: "error",
message: "Unknown action: " + message.action,
});
break;
}
}
/**
* Send a request to the host app
*
* @since 3.0.0
*
* @param object settings Live settings object
* @param string action Action to run
* @param params object Additional params to pass to the host app
* @return Promise
*/
function hostAction(settings, action, params = {}) {
var request = {
settings: settings,
action: action,
};
for (var key in params) {
request[key] = params[key];
}
return chrome.runtime.sendNativeMessage(appID, request);
}
/**
* Fetch file & parse fields
*
* @since 3.0.0
*
* @param object settings Settings object
* @param object login Login object
* @return void
*/
async function parseFields(settings, login) {
var response = await hostAction(settings, "fetch", {
storeId: login.store.id,
file: login.loginPath,
});
if (response.status != "ok") {
throw new Error(JSON.stringify(response)); // TODO handle host error
}
var allowEmpty = ["login"];
// save raw data inside login
login.raw = response.data.contents;
// parse lines
login.fields = helpers.deepCopy(helpers.fieldsPrefix);
login.settings = {
autoSubmit: { name: "autosubmit", type: "bool" },
};
var lines = login.raw.split(/[\r\n]+/).filter((line) => line.trim().length > 0);
lines.forEach(function (line) {
// check for uri-encoded otp without line prefix
if (line.match(/^otpauth:\/\/.+/i)) {
line = `otp: ${line}`;
}
// split key / value & ignore non-k/v lines
var parts = line.match(/^(.+?):(.*)$/);
if (parts === null) {
return;
}
parts = parts
.slice(1)
.map((value) => value.trim())
.filter((value) => value.length);
if (!parts.length) {
return;
}
// assign to fields
for (var key in login.fields) {
if (
Array.isArray(login.fields[key]) &&
login.fields[key].includes(parts[0].toLowerCase())
) {
if (parts.length < 2 && !allowEmpty.includes(key)) {
return;
}
login.fields[key] = parts[1];
break;
}
}
// assign to settings
for (var key in login.settings) {
if (
typeof login.settings[key].type !== "undefined" &&