forked from Dmitry1987/vault-chrome-extension
-
Notifications
You must be signed in to change notification settings - Fork 38
/
popup.js
277 lines (243 loc) · 8.38 KB
/
popup.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
/* eslint-disable no-console */
/* eslint-disable no-prototype-builtins */
/* global browser Notify storePathComponents */
const notify = new Notify(document.querySelector('#notify'));
const resultList = document.getElementById('resultList');
const searchInput = document.getElementById('vault-search');
var currentUrl, currentTabId;
var vaultServerAddress, vaultToken, storePath, secretList;
async function mainLoaded() {
const tabs = await browser.tabs.query({ active: true, currentWindow: true });
for (let tabIndex = 0; tabIndex < tabs.length; tabIndex++) {
const tab = tabs[tabIndex];
if (tab.url) {
currentTabId = tab.id;
currentUrl = tab.url;
break;
}
}
if (searchInput.value.length !== 0) {
currentUrl = searchInput.value;
}
vaultToken = (await browser.storage.local.get('vaultToken')).vaultToken;
if (!vaultToken || vaultToken.length === 0) {
return notify.clear().info(
`No Vault-Token information available.<br>
Please use the <a href="/options.html" class="link">options page</a> to login.`,
{ removeOption: false }
);
}
vaultServerAddress = (await browser.storage.sync.get('vaultAddress'))
.vaultAddress;
storePath = (await browser.storage.sync.get('storePath')).storePath;
secretList = (await browser.storage.sync.get('secrets')).secrets;
if (!secretList) {
secretList = [];
}
await querySecrets(currentUrl, searchInput.value.length !== 0);
}
async function querySecrets(searchString, manualSearch) {
if (searchString.length === 0) {
searchString = currentUrl;
}
resultList.textContent = '';
const promises = [];
notify.clear();
const storeComponents = storePathComponents(storePath);
let matches = 0;
for (const secret of secretList) {
promises.push(
(async function () {
const secretsInPath = await fetch(
`${vaultServerAddress}/v1/${storeComponents.root}/metadata/${storeComponents.subPath}/${secret}`,
{
method: 'LIST',
headers: {
'X-Vault-Token': vaultToken,
'Content-Type': 'application/json',
},
}
);
if (!secretsInPath.ok) {
if (secretsInPath.status !== 404) {
notify.error(`Unable to read ${secret}... Try re-login`, {
removeOption: true,
});
}
return;
}
for (const element of (await secretsInPath.json()).data.keys) {
const pattern = new RegExp(element);
const patternMatches =
pattern.test(searchString) || element.includes(searchString);
if (patternMatches) {
const urlPath = `${vaultServerAddress}/v1/${storeComponents.root}/data/${storeComponents.subPath}/${secret}${element}`;
const credentials = await getCredentials(urlPath);
const credentialsSets = extractCredentialsSets(
credentials.data.data
);
for (const item of credentialsSets) {
addCredentialsToList(item, element, resultList);
matches++;
}
notify.clear();
}
}
})()
);
}
try {
await Promise.all(promises);
if (matches > 0) {
browser.browserAction.setBadgeText({
text: `${matches}`,
tabId: currentTabId,
});
} else {
browser.browserAction.setBadgeText({ text: '', tabId: currentTabId });
if (!manualSearch) {
notify.info('No matching key found for this page.', {
removeOption: false,
});
} else {
notify.info('No matching key found for the search', {
removeOption: false,
});
}
}
} catch (err) {
browser.browserAction.setBadgeText({ text: '', tabId: currentTabId });
notify.clear().error(err.message);
}
}
const searchHandler = function (e) {
if (e.key === 'Enter') {
mainLoaded();
}
};
searchInput.addEventListener('keyup', searchHandler);
function extractCredentialsSets(data) {
const keys = Object.keys(data);
const credentials = [];
for (const key of keys) {
if (key.startsWith('username')) {
const passwordField = 'password' + key.substring(8);
if (data[passwordField]) {
credentials.push({
username: data[key],
password: data['password' + key.substring(8)],
title: data.hasOwnProperty('title' + key.substring(8))
? data['title' + key.substring(8)]
: data.hasOwnProperty('title')
? data['title']
: '',
comment: data.hasOwnProperty('comment' + key.substring(8))
? data['comment' + key.substring(8)]
: data.hasOwnProperty('comment')
? data['comment']
: '',
});
}
}
}
return credentials;
}
function addCredentialsToList(credentials, credentialName, list) {
const item = document.createElement('li');
item.classList.add('list__item', 'list__item--three-line');
const primaryContent = document.createElement('button');
primaryContent.title = 'insert credentials';
primaryContent.classList.add(
'list__item-primary-content',
'list__item-button',
'nobutton',
'js-button',
'js-ripple-effect'
);
primaryContent.addEventListener('click', function () {
fillCredentialsInBrowser(credentials.username, credentials.password);
});
item.appendChild(primaryContent);
const titleContent = document.createElement('span');
titleContent.classList.add('list__item-text-title', 'link');
titleContent.textContent = credentials.title || credentialName;
if (credentials.comment && credentials.comment.length > 0) {
titleContent.title = credentials.comment;
}
primaryContent.appendChild(titleContent);
const detailContent = document.createElement('span');
detailContent.classList.add('list__item-text-body');
detailContent.textContent = `User: ${credentials.username}`;
primaryContent.appendChild(detailContent);
const actions = document.createElement('div');
actions.classList.add('list__item-actions');
item.appendChild(actions);
const copyUsernameButton = document.createElement('button');
copyUsernameButton.classList.add('button');
copyUsernameButton.title = 'copy username to clipboard';
copyUsernameButton.innerHTML = `
<svg xmlns="http://www.w3.org/2000/svg" class="icon icon--inline">
<use href="icons/copy-user.svg#copy-user"/>
</svg>
`;
copyUsernameButton.addEventListener('click', function () {
copyStringToClipboard(credentials.username);
});
actions.appendChild(copyUsernameButton);
const copyPasswordButton = document.createElement('button');
copyPasswordButton.classList.add('button');
copyPasswordButton.title = 'copy password to clipboard';
copyPasswordButton.innerHTML = `
<svg xmlns="http://www.w3.org/2000/svg" class="icon icon--inline">
<use href="icons/copy-key.svg#copy-key"/>
</svg>
`;
copyPasswordButton.addEventListener('click', function () {
copyStringToClipboard(credentials.password);
});
actions.appendChild(copyPasswordButton);
list.appendChild(item);
}
async function getCredentials(urlPath) {
const vaultToken = (await browser.storage.local.get('vaultToken')).vaultToken;
const result = await fetch(urlPath, {
headers: {
'X-Vault-Token': vaultToken,
'Content-Type': 'application/json',
},
});
if (!result.ok) {
throw new Error(`getCredentials: ${await result.text}`);
}
return await result.json();
}
async function fillCredentialsInBrowser(username, password) {
const tabs = await browser.tabs.query({ active: true, currentWindow: true });
for (let tabIndex = 0; tabIndex < tabs.length; tabIndex++) {
const tab = tabs[tabIndex];
if (tab.url) {
// tabs.sendMessage(integer tabId, any message, optional object options, optional function responseCallback)
browser.tabs.sendMessage(tab.id, {
message: 'fill_creds',
username: username,
password: password,
isUserTriggered: true,
});
break;
}
}
}
async function copyStringToClipboard(string) {
const tabs = await browser.tabs.query({ active: true, currentWindow: true });
for (let tabIndex = 0; tabIndex < tabs.length; tabIndex++) {
const tab = tabs[tabIndex];
if (tab.url) {
browser.tabs.sendMessage(tab.id, {
message: 'copy_to_clipboard',
string: string,
});
break;
}
}
}
document.addEventListener('DOMContentLoaded', mainLoaded, false);