bitwarden-estensione-browser/src/background.js

737 lines
23 KiB
JavaScript
Raw Normal View History

var isBackground = true;
2017-06-27 05:55:51 +02:00
var bg_loginsToAdd = [];
var bg_i18nService = new i18nService();
var bg_constantsService = new ConstantsService(bg_i18nService);
2017-06-27 05:55:51 +02:00
var bg_utilsService = new UtilsService();
var bg_cryptoService = new CryptoService(bg_constantsService);
var bg_tokenService = new TokenService();
var bg_appIdService = new AppIdService();
2017-08-22 18:00:59 +02:00
var bg_apiService = new ApiService(bg_tokenService, bg_appIdService, bg_utilsService, bg_constantsService, logout);
2017-06-27 05:55:51 +02:00
var bg_userService = new UserService(bg_tokenService, bg_apiService, bg_cryptoService);
var bg_settingsService = new SettingsService(bg_userService);
var bg_loginService = new LoginService(bg_cryptoService, bg_userService, bg_apiService, bg_settingsService);
2017-07-11 19:05:56 +02:00
var bg_folderService = new FolderService(bg_cryptoService, bg_userService, bg_apiService, bg_i18nService);
2017-06-27 05:55:51 +02:00
var bg_lockService = new LockService(bg_constantsService, bg_cryptoService, bg_folderService, bg_loginService, setIcon,
refreshBadgeAndMenu);
var bg_syncService = new SyncService(bg_loginService, bg_folderService, bg_userService, bg_apiService, bg_settingsService,
bg_cryptoService, logout);
var bg_autofillService = new AutofillService();
var bg_passwordGenerationService = new PasswordGenerationService();
var bg_totpService = new TotpService(bg_constantsService);
2017-06-05 20:27:24 +02:00
if (chrome.commands) {
chrome.commands.onCommand.addListener(function (command) {
if (command === 'generate_password') {
ga('send', {
hitType: 'event',
eventAction: 'Generated Password From Command'
});
2017-06-27 05:55:51 +02:00
bg_passwordGenerationService.getOptions().then(function (options) {
var password = bg_passwordGenerationService.generatePassword(options);
bg_utilsService.copyToClipboard(password);
2017-06-05 20:27:24 +02:00
});
}
});
}
var loginToAutoFill = null,
pageDetailsToAutoFill = [],
2017-01-21 05:20:09 +01:00
autofillTimeout = null,
menuOptionsLoaded = [];
chrome.runtime.onMessage.addListener(function (msg, sender, sendResponse) {
if (msg.command === 'loggedIn' || msg.command === 'unlocked' || msg.command === 'locked') {
setIcon();
refreshBadgeAndMenu();
}
else if (msg.command === 'logout') {
logout(msg.expired, function () { });
}
else if (msg.command === 'syncCompleted' && msg.successfully) {
setTimeout(refreshBadgeAndMenu, 2000);
}
2016-09-29 06:14:15 +02:00
else if (msg.command === 'bgOpenOverlayPopup') {
messageCurrentTab('openOverlayPopup', msg.data);
}
else if (msg.command === 'bgCloseOverlayPopup') {
messageCurrentTab('closeOverlayPopup');
}
2016-12-30 00:35:41 +01:00
else if (msg.command === 'bgOpenNotificationBar') {
messageTab(sender.tab.id, 'openNotificationBar', msg.data);
2016-12-30 00:35:41 +01:00
}
else if (msg.command === 'bgCloseNotificationBar') {
messageTab(sender.tab.id, 'closeNotificationBar');
2016-12-30 00:35:41 +01:00
}
else if (msg.command === 'bgCollectPageDetails') {
collectPageDetailsForContentScript(sender.tab);
}
else if (msg.command === 'bgAddLogin') {
addLogin(msg.login, sender.tab);
}
else if (msg.command === 'bgAddClose') {
removeAddLogin(sender.tab);
}
else if (msg.command === 'bgAddSave') {
saveAddLogin(sender.tab);
}
else if (msg.command === 'bgNeverSave') {
saveNever(sender.tab);
}
else if (msg.command === 'collectPageDetailsResponse') {
if (msg.contentScript) {
2017-06-27 05:55:51 +02:00
var forms = bg_autofillService.getFormsWithPasswordFields(msg.details);
messageTab(msg.tabId, 'pageDetails', { details: msg.details, forms: forms });
}
else {
clearTimeout(autofillTimeout);
pageDetailsToAutoFill.push({ frameId: sender.frameId, tabId: msg.tabId, details: msg.details });
autofillTimeout = setTimeout(autofillPage, 300);
}
} else if (msg.command === 'bgUpdateContextMenu') {
refreshBadgeAndMenu();
}
2016-09-28 05:36:55 +02:00
});
setIcon();
function setIcon() {
2017-06-27 05:55:51 +02:00
bg_userService.isAuthenticated(function (isAuthenticated) {
bg_cryptoService.getKey().then(function (key) {
var suffix = '';
if (!isAuthenticated) {
suffix = '_gray';
}
else if (!key) {
suffix = '_locked';
}
chrome.browserAction.setIcon({
path: {
'19': 'images/icon19' + suffix + '.png',
'38': 'images/icon38' + suffix + '.png',
}
});
});
});
}
if (chrome.runtime.onInstalled) {
chrome.runtime.onInstalled.addListener(function (details) {
ga('send', {
hitType: 'event',
eventAction: 'onInstalled ' + details.reason
});
if (details.reason === 'install') {
chrome.tabs.create({ url: 'https://bitwarden.com/browser-start/' }, function (tab) { });
}
});
}
2017-01-21 04:32:21 +01:00
var buildingContextMenu = false;
function buildContextMenu(callback) {
2017-01-21 04:32:21 +01:00
if (buildingContextMenu) {
return;
}
buildingContextMenu = true;
chrome.contextMenus.removeAll(function () {
chrome.contextMenus.create({
type: 'normal',
id: 'root',
contexts: ['all'],
title: 'bitwarden'
}, function () {
chrome.contextMenus.create({
type: 'normal',
id: 'autofill',
parentId: 'root',
contexts: ['all'],
2017-06-27 05:55:51 +02:00
title: bg_i18nService.autoFill
}, function () {
2017-06-27 05:55:51 +02:00
if (bg_utilsService.isFirefox()) {
2017-01-21 05:20:09 +01:00
// Firefox does not support writing to the clipboard from background
buildingContextMenu = false;
if (callback) {
callback();
}
return;
}
chrome.contextMenus.create({
type: 'normal',
id: 'copy-username',
parentId: 'root',
contexts: ['all'],
2017-06-27 05:55:51 +02:00
title: bg_i18nService.copyUsername
}, function () {
chrome.contextMenus.create({
type: 'normal',
id: 'copy-password',
parentId: 'root',
contexts: ['all'],
2017-06-27 05:55:51 +02:00
title: bg_i18nService.copyPassword
}, function () {
chrome.contextMenus.create({
type: 'separator',
parentId: 'root'
});
chrome.contextMenus.create({
type: 'normal',
id: 'generate-password',
parentId: 'root',
contexts: ['all'],
2017-06-27 05:55:51 +02:00
title: bg_i18nService.generatePasswordCopied
}, function () {
2017-01-21 04:32:21 +01:00
buildingContextMenu = false;
if (callback) {
callback();
}
});
});
});
});
});
});
}
chrome.tabs.onActivated.addListener(function (activeInfo) {
refreshBadgeAndMenu();
});
var onReplacedRan = false;
chrome.tabs.onReplaced.addListener(function (addedTabId, removedTabId) {
if (onReplacedRan) {
return;
}
onReplacedRan = true;
2017-06-27 05:55:51 +02:00
checkbg_loginsToAdd();
refreshBadgeAndMenu();
});
var onUpdatedRan = false;
chrome.tabs.onUpdated.addListener(function (tabId, changeInfo, tab) {
if (onUpdatedRan) {
return;
}
onUpdatedRan = true;
2017-06-27 05:55:51 +02:00
checkbg_loginsToAdd();
refreshBadgeAndMenu();
});
2017-01-21 04:32:21 +01:00
chrome.windows.onFocusChanged.addListener(function (windowId) {
2017-01-21 05:20:09 +01:00
if (windowId === null || windowId < 0) {
2017-01-21 04:32:21 +01:00
return;
}
refreshBadgeAndMenu();
});
function refreshBadgeAndMenu() {
2017-01-21 04:32:21 +01:00
chrome.tabs.query({ active: true, windowId: chrome.windows.WINDOW_ID_CURRENT }, function (tabs) {
var tab = null;
if (tabs.length > 0) {
tab = tabs[0];
}
if (!tab) {
return;
}
2017-06-27 05:55:51 +02:00
chrome.storage.local.get(bg_constantsService.disableContextMenuItemKey, function (obj) {
if (!obj[bg_constantsService.disableContextMenuItemKey]) {
buildContextMenu(function () {
contextMenuReady(tab, true);
});
}
else {
chrome.contextMenus.removeAll();
contextMenuReady(tab, false);
}
});
});
}
function contextMenuReady(tab, contextMenuEnabled) {
loadMenuAndUpdateBadge(tab.url, tab.id, contextMenuEnabled);
onUpdatedRan = onReplacedRan = false;
}
function loadMenuAndUpdateBadge(url, tabId, contextMenuEnabled) {
if (!url) {
return;
}
2017-06-27 05:55:51 +02:00
var tabDomain = bg_utilsService.getDomain(url);
if (!tabDomain) {
return;
}
chrome.browserAction.setBadgeBackgroundColor({ color: '#294e5f' });
2017-01-21 05:20:09 +01:00
menuOptionsLoaded = [];
2017-06-27 05:55:51 +02:00
bg_loginService.getAllDecryptedForDomain(tabDomain).then(function (logins) {
sortLogins(logins);
2017-01-21 05:20:09 +01:00
if (contextMenuEnabled) {
2017-01-21 05:20:09 +01:00
for (var i = 0; i < logins.length; i++) {
loadLoginContextMenuOptions(logins[i]);
}
}
if (logins.length > 0 && logins.length < 9) {
chrome.browserAction.setBadgeText({
text: logins.length.toString(),
tabId: tabId
});
}
else if (logins.length > 0) {
chrome.browserAction.setBadgeText({
text: '9+',
tabId: tabId
});
}
else {
if (contextMenuEnabled) {
2017-06-27 05:55:51 +02:00
loadNoLoginsContextMenuOptions(bg_i18nService.noMatchingLogins);
}
chrome.browserAction.setBadgeText({
text: '',
tabId: tabId
});
}
}, function () {
if (contextMenuEnabled) {
2017-06-27 05:55:51 +02:00
loadNoLoginsContextMenuOptions(bg_i18nService.vaultLocked);
}
chrome.browserAction.setBadgeText({
text: '',
tabId: tabId
});
});
}
chrome.contextMenus.onClicked.addListener(function (info, tab) {
if (info.menuItemId === 'generate-password') {
ga('send', {
hitType: 'event',
eventAction: 'Generated Password From Context Menu'
});
2017-06-27 05:55:51 +02:00
bg_passwordGenerationService.getOptions().then(function (options) {
var password = bg_passwordGenerationService.generatePassword(options);
bg_utilsService.copyToClipboard(password);
});
}
else if (info.parentMenuItemId === 'autofill' || info.parentMenuItemId === 'copy-username' ||
info.parentMenuItemId === 'copy-password') {
var id = info.menuItemId.split('_')[1];
if (id === 'noop') {
return;
}
2017-06-27 05:55:51 +02:00
bg_loginService.getAllDecrypted().then(function (logins) {
for (var i = 0; i < logins.length; i++) {
if (logins[i].id === id) {
if (info.parentMenuItemId === 'autofill') {
2016-09-28 05:19:33 +02:00
ga('send', {
hitType: 'event',
eventAction: 'Autofilled From Context Menu'
});
startAutofillPage(logins[i]);
}
else if (info.parentMenuItemId === 'copy-username') {
2016-09-28 05:19:33 +02:00
ga('send', {
hitType: 'event',
eventAction: 'Copied Username From Context Menu'
});
bg_utilsService.copyToClipboard(logins[i].username);
}
else if (info.parentMenuItemId === 'copy-password') {
2016-09-28 05:19:33 +02:00
ga('send', {
hitType: 'event',
eventAction: 'Copied Password From Context Menu'
});
bg_utilsService.copyToClipboard(logins[i].password);
}
return;
}
}
}, function () {
});
}
});
2016-09-22 05:41:53 +02:00
function messageCurrentTab(command, data) {
chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
var tabId = null;
if (tabs.length > 0) {
tabId = tabs[0].id;
}
else {
return;
}
messageTab(tabId, command, data);
});
}
2017-01-27 05:12:09 +01:00
function messageTab(tabId, command, data, callback) {
if (!tabId) {
return;
}
var obj = {
command: command
};
if (data) {
2017-07-14 21:34:05 +02:00
obj.data = data;
}
2017-01-27 05:12:09 +01:00
chrome.tabs.sendMessage(tabId, obj, function () {
if (callback) {
callback();
}
});
}
function collectPageDetailsForContentScript(tab) {
2017-01-27 05:12:09 +01:00
chrome.tabs.sendMessage(tab.id, { command: 'collectPageDetails', tabId: tab.id, contentScript: true }, function () {
});
}
function addLogin(login, tab) {
2017-06-27 05:55:51 +02:00
var loginDomain = bg_utilsService.getDomain(login.url);
if (!loginDomain) {
return;
}
2017-06-27 05:55:51 +02:00
bg_loginService.getAllDecryptedForDomain(loginDomain).then(function (logins) {
var match = false;
for (var i = 0; i < logins.length; i++) {
if (logins[i].username === login.username) {
match = true;
break;
}
}
if (!match) {
// remove any old logins for this tab
removeAddLogin(tab);
2017-06-27 05:55:51 +02:00
bg_loginsToAdd.push({
username: login.username,
password: login.password,
name: loginDomain,
2017-01-27 05:12:09 +01:00
domain: loginDomain,
uri: login.url,
tabId: tab.id,
expires: new Date((new Date()).getTime() + 30 * 60000) // 30 minutes
});
2017-06-27 05:55:51 +02:00
checkbg_loginsToAdd(tab);
}
});
}
2017-06-27 05:55:51 +02:00
cleanupbg_loginsToAdd();
function cleanupbg_loginsToAdd() {
for (var i = bg_loginsToAdd.length - 1; i >= 0; i--) {
if (bg_loginsToAdd[i].expires < new Date()) {
2017-06-27 05:55:51 +02:00
bg_loginsToAdd.splice(i, 1);
}
}
setTimeout(cleanupbg_loginsToAdd, 2 * 60 * 1000); // check every 2 minutes
}
function removeAddLogin(tab) {
2017-06-27 05:55:51 +02:00
for (var i = bg_loginsToAdd.length - 1; i >= 0; i--) {
if (bg_loginsToAdd[i].tabId === tab.id) {
bg_loginsToAdd.splice(i, 1);
}
}
}
function saveAddLogin(tab) {
2017-06-27 05:55:51 +02:00
for (var i = bg_loginsToAdd.length - 1; i >= 0; i--) {
if (bg_loginsToAdd[i].tabId === tab.id) {
var loginToAdd = bg_loginsToAdd[i];
2017-01-27 05:12:09 +01:00
2017-06-27 05:55:51 +02:00
var tabDomain = bg_utilsService.getDomain(tab.url);
2017-01-27 05:12:09 +01:00
if (tabDomain && tabDomain === loginToAdd.domain) {
2017-06-27 05:55:51 +02:00
bg_loginsToAdd.splice(i, 1);
bg_loginService.encrypt({
2017-01-27 05:12:09 +01:00
id: null,
folderId: null,
favorite: false,
name: loginToAdd.name,
uri: loginToAdd.uri,
username: loginToAdd.username,
password: loginToAdd.password,
notes: null
}).then(function (loginModel) {
var login = new Login(loginModel, true);
2017-06-27 05:55:51 +02:00
bg_loginService.saveWithServer(login).then(function (login) {
2017-01-27 05:12:09 +01:00
ga('send', {
hitType: 'event',
eventAction: 'Added Login from Notification Bar'
});
});
});
2017-01-27 05:12:09 +01:00
messageTab(tab.id, 'closeNotificationBar');
}
}
}
}
function saveNever(tab) {
2017-06-27 05:55:51 +02:00
for (var i = bg_loginsToAdd.length - 1; i >= 0; i--) {
if (bg_loginsToAdd[i].tabId === tab.id) {
var loginToAdd = bg_loginsToAdd[i];
2017-06-27 05:55:51 +02:00
var tabDomain = bg_utilsService.getDomain(tab.url);
if (tabDomain && tabDomain === loginToAdd.domain) {
2017-06-27 05:55:51 +02:00
bg_loginsToAdd.splice(i, 1);
var hostname = bg_utilsService.getHostname(tab.url);
bg_loginService.saveNeverDomain(hostname);
messageTab(tab.id, 'closeNotificationBar');
}
}
}
}
2017-06-27 05:55:51 +02:00
function checkbg_loginsToAdd(tab, callback) {
if (!bg_loginsToAdd.length) {
2017-01-27 05:12:09 +01:00
if (callback) {
callback();
}
return;
}
2016-12-30 20:50:16 +01:00
if (tab) {
check();
return;
}
chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
if (tabs.length > 0) {
2016-12-30 20:50:16 +01:00
tab = tabs[0];
check();
2016-09-22 05:41:53 +02:00
}
2016-12-30 20:50:16 +01:00
});
2016-09-22 05:41:53 +02:00
2016-12-30 20:50:16 +01:00
function check() {
if (!tab) {
2017-01-27 05:12:09 +01:00
if (callback) {
callback();
}
return;
}
2016-09-22 05:41:53 +02:00
2017-06-27 05:55:51 +02:00
var tabDomain = bg_utilsService.getDomain(tab.url);
if (!tabDomain) {
2017-01-27 05:12:09 +01:00
if (callback) {
callback();
}
return;
2016-09-22 05:41:53 +02:00
}
2017-06-27 05:55:51 +02:00
for (var i = 0; i < bg_loginsToAdd.length; i++) {
if (bg_loginsToAdd[i].tabId === tab.id && bg_loginsToAdd[i].domain === tabDomain) {
2017-01-27 05:12:09 +01:00
messageTab(tab.id, 'openNotificationBar', {
type: 'add'
}, function () {
if (callback) {
callback();
}
});
break;
}
}
2016-12-30 20:50:16 +01:00
}
2016-09-22 05:41:53 +02:00
}
function startAutofillPage(login) {
loginToAutoFill = login;
chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
var tabId = null;
if (tabs.length > 0) {
tabId = tabs[0].id;
}
else {
return;
}
if (!tabId) {
return;
}
2017-01-27 05:12:09 +01:00
chrome.tabs.sendMessage(tabId, { command: 'collectPageDetails', tabId: tabId }, function () {
});
});
}
function autofillPage() {
chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
var tabId = null;
if (tabs.length > 0) {
tabId = tabs[0].id;
}
else {
return;
}
if (!tabId) {
return;
}
if (loginToAutoFill && pageDetailsToAutoFill && pageDetailsToAutoFill.length) {
for (var i = 0; i < pageDetailsToAutoFill.length; i++) {
// make sure we're still on correct tab
2016-11-26 05:53:46 +01:00
if (pageDetailsToAutoFill[i].tabId !== tabId) {
continue;
}
2017-06-27 05:55:51 +02:00
var fillScript = bg_autofillService.generateFillScript(pageDetailsToAutoFill[i].details,
loginToAutoFill.username, loginToAutoFill.password);
if (tabId && fillScript && fillScript.script && fillScript.script.length) {
chrome.tabs.sendMessage(tabId, {
command: 'fillForm',
fillScript: fillScript
}, { frameId: pageDetailsToAutoFill[i].frameId });
if (!bg_utilsService.isFirefox() && loginToAutoFill.totp && bg_tokenService.getPremium()) {
var totpKey = loginToAutoFill.totp;
bg_totpService.isAutoCopyEnabled().then(function (enabled) {
if (enabled) {
return bg_totpService.getCode(totpKey);
}
return null;
}).then(function (code) {
if (code) {
bg_utilsService.copyToClipboard(code);
}
});
}
}
}
}
// reset
loginToAutoFill = null;
pageDetailsToAutoFill = [];
});
}
function sortLogins(logins) {
logins.sort(function (a, b) {
var nameA = (a.name + '_' + a.username).toUpperCase();
var nameB = (b.name + '_' + b.username).toUpperCase();
if (nameA < nameB) {
return -1;
}
if (nameA > nameB) {
return 1;
}
return 0;
});
}
function loadLoginContextMenuOptions(login) {
var title = login.name + (login.username && login.username !== '' ? ' (' + login.username + ')' : '');
loadContextMenuOptions(title, login.id, login);
}
function loadNoLoginsContextMenuOptions(noLoginsMessage) {
loadContextMenuOptions(noLoginsMessage, 'noop', null);
}
function loadContextMenuOptions(title, idSuffix, login) {
2017-01-21 05:20:09 +01:00
if (menuOptionsLoaded.indexOf(idSuffix) > -1) {
2017-01-21 04:32:21 +01:00
return;
}
2017-01-21 05:20:09 +01:00
menuOptionsLoaded.push(idSuffix);
2017-01-21 04:32:21 +01:00
if (!login || (login.password && login.password !== '')) {
chrome.contextMenus.create({
type: 'normal',
id: 'autofill_' + idSuffix,
parentId: 'autofill',
contexts: ['all'],
title: title
});
}
2017-06-27 05:55:51 +02:00
if (bg_utilsService.isFirefox()) {
2017-01-21 05:20:09 +01:00
// Firefox does not support writing to the clipboard from background
return;
}
if (!login || (login.username && login.username !== '')) {
chrome.contextMenus.create({
type: 'normal',
id: 'copy-username_' + idSuffix,
parentId: 'copy-username',
contexts: ['all'],
title: title
});
}
if (!login || (login.password && login.password !== '')) {
chrome.contextMenus.create({
type: 'normal',
id: 'copy-password_' + idSuffix,
parentId: 'copy-password',
contexts: ['all'],
title: title
});
}
}
// TODO: Fix callback hell by moving to promises
function logout(expired, callback) {
2017-06-27 05:55:51 +02:00
bg_userService.getUserId(function (userId) {
bg_syncService.setLastSync(new Date(0), function () {
bg_settingsService.clear(function () {
bg_tokenService.clearToken(function () {
bg_cryptoService.clearKeys(function () {
bg_userService.clear(function () {
bg_loginService.clear(userId, function () {
bg_folderService.clear(userId, function () {
chrome.runtime.sendMessage({
command: 'doneLoggingOut', expired: expired
});
setIcon();
refreshBadgeAndMenu();
callback();
});
});
});
});
});
});
});
});
}
2016-09-22 02:13:52 +02:00
// Sync polling
2016-09-22 02:13:52 +02:00
fullSync(true);
function fullSync(override) {
override = override || false;
2017-06-27 05:55:51 +02:00
bg_syncService.getLastSync(function (lastSync) {
var syncInternal = 6 * 60 * 60 * 1000; // 6 hours
var lastSyncAgo = new Date() - lastSync;
if (override || !lastSync || lastSyncAgo >= syncInternal) {
2017-06-27 05:55:51 +02:00
bg_syncService.fullSync(override || false, function () {
// done
2017-01-27 05:12:09 +01:00
});
2016-09-22 02:13:52 +02:00
}
});
setTimeout(fullSync, 5 * 60 * 1000); // check every 5 minutes
}