-
Notifications
You must be signed in to change notification settings - Fork 5
/
main.js
551 lines (521 loc) · 14.8 KB
/
main.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
/* globals keepass, keepassClient, onDisconnected */
"use strict";
const page = {
tabs: [],
clearCredentials: () => {},
clearAllLogins: () => {},
settings: {
autoReconnect: true,
checkUpdateKeePassXC: 0
}
};
const browserAction = {
show: () => {},
showDefault: () => {}
};
const log = function(){
function f(d, n){
const s = d.toString();
return "0".repeat(n - s.length) + s;
}
return function log(...args){
const now = new Date();
console.log(
`${f(now.getFullYear(), 4)}-${f(now.getMonth() + 1, 2)}-${f(now.getDate(), 2)} `+
`${f(now.getHours(), 2)}:${f(now.getMinutes(), 2)}:` +
`${f(now.getSeconds(), 2)}.${f(now.getMilliseconds(), 3)}:`,
...args
);
};
}();
keepassClient.nativeHostName = "de.kkapsner.keepassxc_mail";
async function connect(forceOptionSearch){
const savedNativeHostName = forceOptionSearch?
false:
(await browser.storage.local.get({nativeHostName: false})).nativeHostName;
if (savedNativeHostName){
keepassClient.nativeHostName = savedNativeHostName;
log("Use saved native application", keepassClient.nativeHostName);
if (await keepass.reconnect(null, 10000)){ // 10 second timeout for the first connect
return true;
}
}
else {
const options = [
"de.kkapsner.keepassxc_mail",
"org.keepassxc.keepassxc_mail",
"org.keepassxc.keepassxc_browser",
];
for (let index = 0; index < options.length; index += 1){
keepassClient.nativeHostName = options[index];
log("Try native application", keepassClient.nativeHostName);
if (await keepass.reconnect(null, 10000)){ // 10 second timeout for the first connect
browser.storage.local.set({nativeHostName: keepassClient.nativeHostName});
return true;
}
}
}
throw "Unable to connect to native messaging";
}
async function disconnect(){
if (keepassClient.nativePort){
await keepassClient.nativePort.disconnect();
onDisconnected();
}
}
async function wait(ms, returnValue){
return new Promise(function(resolve){
window.setTimeout(function(){
resolve(returnValue);
}, ms);
});
}
async function loadKeyRing(){
let loadCount = 0;
let lastLoadError = null;
while (!keepass.keyRing){
await wait(50);
loadCount += 1;
try {
const item = await browser.storage.local.get({
latestKeePassXC: {
version: "",
lastChecked: null
},
keyRing: {}
});
keepass.latestKeePassXC = item.latestKeePassXC;
keepass.keyRing = item.keyRing || {};
}
catch (error){
lastLoadError = error;
}
}
if (lastLoadError){
log("Loaded key ring", loadCount, "times", lastLoadError);
}
}
async function checkKeyRingStorage(){
function objectsEqual(obj1, obj2){
const keys1 = Object.keys(obj1);
const keys2 = Object.keys(obj2);
if (keys1.length !== keys2.length){
return false;
}
return keys1.every(function(key){
const value1 = obj1[key];
const value2 = obj2[key];
if ((typeof value1) !== (typeof value2)){
return false;
}
if ((typeof value1) === "object"){
return objectsEqual(value1, value2);
}
return value1 === value2;
});
}
// check if the key ring actually saved in the storage
const databaseHashes = Object.keys(keepass.keyRing);
if (databaseHashes.length){
let storedKeyRing = (await browser.storage.local.get({keyRing: {}})).keyRing;
while (!objectsEqual(keepass.keyRing, storedKeyRing)){
await wait(500);
log("Store key ring");
try {
await browser.storage.local.set({keyRing: keepass.keyRing});
storedKeyRing = (await browser.storage.local.get({keyRing: {}})).keyRing;
}
catch (e){
log("storing key ring failed:", e);
}
}
}
}
// enable access to keepass object in option page
window.keepass = keepass;
const isKeepassReady = (() => {
async function initialize(){
// load key ring - initially done in keepass.js but it fails sometimes...
await loadKeyRing();
await keepass.migrateKeyRing();
await connect();
await keepass.enableAutomaticReconnect();
await keepass.associate();
// check key ring storage - initially done in keepass.js but it fails sometimes...
checkKeyRingStorage();
}
let keepassReady = initialize();
keepassReady.catch((error) => log("Initialization failed:", error));
return async function(){
try {
await keepassReady;
}
catch (error){
keepassReady = initialize();
keepassReady.catch((error) => log("Initialization failed:", error));
await keepassReady;
}
};
})();
const waitForPort = (function(){
const ports = new Map();
const queue = new Map();
function addQueue(tabId, callback){
const queueEntry = (queue.get(tabId) || []);
queueEntry.push(callback);
queue.set(tabId, queueEntry);
}
function removeQueue(tabId, callback){
const remaining = (queue.get(tabId) || []).filter(c => c !== callback);
if (remaining.length){
queue.set(tabId, remaining);
}
else {
queue.delete(tabId);
}
}
browser.runtime.onConnect.addListener(function(port){
const tabId = port.sender.tab.id;
ports.set(tabId, port);
if(queue.has(tabId)){
queue.get(tabId).forEach(function(callback){
callback(port);
});
queue.delete(tabId);
}
port.onDisconnect.addListener(function(){
ports.delete(tabId);
});
});
return async function waitForPort(tabId, timeout = 1500){
return new Promise(function(resolve, reject){
if (ports.has(tabId)){
resolve(ports.get(tabId));
return;
}
addQueue(tabId, resolve);
const timeoutId = window.setTimeout(function(){
removeQueue(tabId, resolve);
removeQueue(tabId, cancelTimeout);
reject("Timeout");
}, timeout);
function cancelTimeout(){
window.clearTimeout(timeoutId);
}
addQueue(tabId, cancelTimeout);
});
};
}());
async function openModal({path, message, defaultReturnValue}){
function getPortResponse(port){
return new Promise(function(resolve){
function resolveDefault(){
resolve(defaultReturnValue);
}
port.onDisconnect.addListener(resolveDefault);
port.onMessage.addListener(function(data){
if (data.type === "response"){
resolve(data.value);
port.onDisconnect.removeListener(resolveDefault);
}
});
port.postMessage({
type: "start",
message
});
});
}
const window = await browser.windows.create({
url: browser.runtime.getURL(path),
allowScriptsToClose: true,
height: 100,
width: 600,
type: "detached_panel"
});
try {
const port = await waitForPort(window.tabs[0].id);
return getPortResponse(port);
}
catch (error){
return defaultReturnValue;
}
}
async function messageModal(title, text){
return await openModal({
path: "modal/message/index.html",
message: {
title,
text
},
defaultReturnValue: undefined
});
}
const selectedEntries = new Map();
const storeAtEntries = new Map();
async function clearSelectedEntries(){
selectedEntries.clear();
storeAtEntries.clear();
await browser.storage.local.set({selectedEntries: [], storeAtEntries: []});
}
browser.storage.local.get({selectedEntries: [], storeAtEntries: []}).then(function({
selectedEntries: selectedEntriesStorage,
storeAtEntries: storeAtEntriesStorage
}){
selectedEntriesStorage.forEach(function(selectedEntry){
selectedEntries.set(selectedEntry.host, {doNotAskAgain: true, uuid: selectedEntry.uuid});
});
storeAtEntriesStorage.forEach(function(storeAtEntry){
storeAtEntries.set(storeAtEntry.host, {doNotAskAgain: true, save: storeAtEntry.save, uuid: storeAtEntry.uuid});
});
return undefined;
}).catch(()=>{});
async function choiceModal(host, login, entries){
const cachedId = login? `${login}@${host}`: host;
if (selectedEntries.has(cachedId)){
const cached = selectedEntries.get(cachedId);
if (
(
cached.doNotAskAgain ||
Date.now() - cached.timestamp <= 60000
) &&
(
cached.uuid === false ||
entries.some(e => e.uuid === cached.uuid)
)
){
log("Use last selected entry for", cachedId);
return cached.uuid;
}
}
const {selectedUuid, doNotAskAgain} = (entries.length === 1 && entries[0].autoSubmit)?
{selectedUuid: entries[0].uuid, doNotAskAgain: false}:
await openModal({
path: "modal/choice/index.html",
message: {
host,
login,
entries
},
defaultReturnValue: {selectedUuid: undefined, doNotAskAgain: false}
});
if (selectedUuid !== undefined){
selectedEntries.set(cachedId, {uuid: selectedUuid, doNotAskAgain, timestamp: Date.now()});
if (doNotAskAgain){
browser.storage.local.get({selectedEntries: []}).then(async function({selectedEntries}){
let found = false;
for (let i = 0; i < selectedEntries.length; i += 1){
if (selectedEntries[i].host === cachedId){
selectedEntries[i].uuid = selectedUuid;
found = true;
}
}
if (!found){
selectedEntries.push({host: cachedId, uuid: selectedUuid});
}
await browser.storage.local.set({selectedEntries});
return undefined;
}).catch(error => console.error(error));
}
}
return selectedUuid;
}
const lastRequest = {};
browser.credentials.onCredentialRequested.addListener(async function(credentialInfo){
log("got credential request:", credentialInfo);
await isKeepassReady();
const presentIds = new Map();
let credentialsForHost = (await keepass.retrieveCredentials(false, [credentialInfo.host, credentialInfo.host]))
.filter(function(credentials){
const alreadyPresent = presentIds.has(credentials.uuid);
if (alreadyPresent){
return false;
}
presentIds.set(credentials.uuid, true);
return true;
})
.filter(function(credential){
return (credentialInfo.login || !credentialInfo.loginChangeable)?
(
credentialInfo.login === true ||
credential.login.toLowerCase?.() === credentialInfo.login.toLowerCase?.()
):
credential.login;
}).map(function(credential){
credential.skipAutoSubmit = credential.skipAutoSubmit === "true";
return credential;
});
log("keepassXC provided", credentialsForHost.length, "logins");
let autoSubmit = (await browser.storage.local.get({autoSubmit: false})).autoSubmit;
if (autoSubmit){
const requestId = credentialInfo.login + "|" + credentialInfo.host;
const now = Date.now();
if (now - lastRequest[requestId] < 1000){
autoSubmit = false;
}
lastRequest[requestId] = now;
}
if (
credentialInfo.openChoiceDialog &&
credentialsForHost.length
){
const selectedUuid = await choiceModal(
credentialInfo.host,
credentialInfo.login,
credentialsForHost.map(function (data){
return {
name: data.name,
login: data.login,
uuid: data.uuid,
autoSubmit: autoSubmit && !data.skipAutoSubmit
};
})
);
const filteredCredentialsForHost = credentialsForHost.filter(e => e.uuid === selectedUuid);
if (!selectedUuid || filteredCredentialsForHost.length){
credentialsForHost = filteredCredentialsForHost;
}
}
return {
autoSubmit,
credentials: credentialsForHost
};
});
async function savingPasswordModal(host, login, entries){
const storeId = login? `${login}@${host}`: host;
if (storeAtEntries.has(storeId)){
const stored = storeAtEntries.get(storeId);
if (
!stored.save ||
entries.some(e => e.uuid === stored.uuid)
){
log("Use last store at entry for", storeId);
return stored;
}
}
const {save, uuid, doNotAskAgain} = await openModal({
path: "modal/savingPassword/index.html",
message: {
host,
login,
entries,
},
defaultReturnValue: {save: false, uuid: undefined, doNotAskAgain: false}
});
if (doNotAskAgain){
storeAtEntries.set(storeId, {save, uuid, doNotAskAgain});
browser.storage.local.get({storeAtEntries: []}).then(async function({storeAtEntries}){
let found = false;
for (let i = 0; i < storeAtEntries.length; i += 1){
if (storeAtEntries[i].host === storeId){
storeAtEntries[i].save = save;
storeAtEntries[i].uuid = uuid;
found = true;
}
}
if (!found){
storeAtEntries.push({host: storeId, uuid, save});
}
await browser.storage.local.set({storeAtEntries});
return undefined;
}).catch(error => console.error(error));
}
return {save, uuid, doNotAskAgain};
}
browser.runtime.onMessage.addListener(function(message, tab){
if (message.action === "resize"){
browser.windows.update(tab.tab.windowId, {
width: message.width,
height: message.height
});
}
});
const timeoutSymbol = Symbol("timeout");
async function storeCredentials(credentialInfo, uuid){
log("Get or create password group");
const group = await Promise.any([
keepass.createNewGroup(null, ["KeePassXC-Mail Passwords"]),
wait(1 * 60 * 1000, timeoutSymbol)
]);
if (group === timeoutSymbol){
log("Timeout while creating password group: using default password manager");
messageModal(
browser.i18n.getMessage("createPasswordGroup.timeout.title"),
browser.i18n.getMessage("createPasswordGroup.timeout.message")
.replace("{account}", credentialInfo.login)
);
return false;
}
log("Saving password to database for", credentialInfo.login, "at", credentialInfo.host);
log("Using uuid:", uuid);
const result = await Promise.any([
keepass.updateCredentials(null, [
uuid,
credentialInfo.login, credentialInfo.password, credentialInfo.host,
group.name, group.uuid
]),
wait(2 * 60 * 1000, timeoutSymbol)
]);
if (result === timeoutSymbol){
log("Timeout while saving: using default password manager");
messageModal(
browser.i18n.getMessage("savePassword.timeout.title"),
browser.i18n.getMessage("savePassword.timeout.message")
.replace("{account}", credentialInfo.login)
);
return false;
}
else {
log("Saving done");
return true;
}
}
browser.credentials.onNewCredential.addListener(async function(credentialInfo){
log("Got new password for", credentialInfo.login, "at", credentialInfo.host);
const {saveNewCredentials, autoSaveNewCredentials} = (await browser.storage.local.get({
saveNewCredentials: true,
autoSaveNewCredentials: false
}));
if (!saveNewCredentials){
log("password saving is disabled in the settings");
return false;
}
await isKeepassReady();
const existingCredentials = (await keepass.retrieveCredentials(
false,
[credentialInfo.host, credentialInfo.host]
)).filter(function (credential){
return (
true === credentialInfo.login ||
credential.login.toLowerCase?.() === credentialInfo.login.toLowerCase?.()
);
});
if (existingCredentials.some(function(credential){
return credential.password === credentialInfo.password;
})){
log("the password is already stored");
return true;
}
const cachedId = credentialInfo.login?
`${credentialInfo.login}@${credentialInfo.host}`:
credentialInfo.host;
const cached = selectedEntries.get(cachedId) || null;
const {save, uuid} = autoSaveNewCredentials?
{save: true, uuid: cached?.uuid || null}:
await savingPasswordModal(
credentialInfo.host,
credentialInfo.login,
existingCredentials.map(function (data){
return {
name: data.name,
login: data.login,
uuid: data.uuid,
preselected: data.uuid === cached?.uuid
};
})
);
if (!save){
log("the user decided to not store the password");
return true;
}
return await storeCredentials(credentialInfo, uuid);
});