forked from Dmitry1987/vault-chrome-extension
-
Notifications
You must be signed in to change notification settings - Fork 41
Expand file tree
/
Copy pathbackground.js
More file actions
347 lines (293 loc) · 9.18 KB
/
Copy pathbackground.js
File metadata and controls
347 lines (293 loc) · 9.18 KB
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
/* global URL, importScripts */
importScripts('compat.js');
const idealTokenTTL = '24h';
const tokenCheckAlarm = 'tokenCheck';
const tokenRenewAlarm = 'tokenRenew';
setupTokenAutoRenew(1800);
refreshTokenTimer();
setupIdleListener();
const storage = {
storageGetterProvider: (storageType) => {
return function (key, defaultValue) {
return new Promise(function (resolve, reject) {
try {
browser.storage[storageType]
.get([key])
.then(function (result) {
const value = result[key] || defaultValue || null;
resolve(value);
})
.catch((error) => {
reject(error);
});
} catch (error) {
reject(error);
}
});
};
},
local: {
get: (key, defaultValue) =>
storage.storageGetterProvider('local')(key, defaultValue),
},
sync: {
get: (key, defaultValue) =>
storage.storageGetterProvider('sync')(key, defaultValue),
},
};
class Vault {
constructor(token, address) {
this.token = token;
this.address = address;
this.base = `${this.address}/v1`;
}
async request(method, endpoint, content = null) {
const res = await fetch(this.base + endpoint, {
method: method.toUpperCase(),
headers: {
'X-Vault-Token': this.token,
'Content-Type': 'application/json',
},
body: content != null ? JSON.stringify(content) : null,
});
if (!res.ok)
throw new Error(
`Error calling: ${method.toUpperCase()} ${
this.base
}${endpoint} -> HTTP ${res.status} - ${res.statusText}`
);
return await res.json();
}
list(endpoint) {
return this.request('LIST', endpoint);
}
get(endpoint) {
return this.request('GET', endpoint);
}
post(endpoint, content) {
return this.request('POST', endpoint, content);
}
}
function storePathComponents(storePath) {
let path = 'secret/vaultPass';
if (storePath && storePath.length > 0) {
path = storePath;
}
const pathComponents = path.split('/');
const storeRoot = pathComponents[0];
const storeSubPath =
pathComponents.length > 0 ? pathComponents.slice(1).join('/') : '';
return {
root: storeRoot,
subPath: storeSubPath,
};
}
function clearHostname(hostname) {
const match = hostname.match(/^(www\.)?(.*)$/);
return match[2] ? match[2] : match[1];
}
async function autoFillSecrets(message, sender) {
const vaultToken = await storage.local.get('vaultToken');
const vaultAddress = await storage.sync.get('vaultAddress');
const secretList = await storage.sync.get('secrets', []);
const storePath = await storage.sync.get('storePath');
const storeComponents = storePathComponents(storePath);
if (!vaultToken || !vaultAddress) return;
const url = new URL(sender.tab.url);
const hostname = clearHostname(url.hostname);
const vault = new Vault(vaultToken, vaultAddress);
let loginCount = 0;
const matches = [];
for (const secret of secretList) {
const secretKeys = await vault.list(
`/${storeComponents.root}/metadata/${storeComponents.subPath}/${secret}`
);
for (const key of secretKeys.data.keys) {
const pattern = new RegExp(key);
const patternMatches = pattern.test(hostname);
// Add entries to array if the hostname is a match
if (hostname === clearHostname(key)) {
const credentials = await vault.get(
`/${storeComponents.root}/data/${storeComponents.subPath}/${secret}${key}`
);
matches.push({
organization: secret,
secret: key,
username: credentials.data.data.username,
password: credentials.data.data.password,
comment: credentials.data.data.comment,
});
}
if (patternMatches) {
loginCount++;
}
}
}
if (loginCount > 0) {
browser.action.setBadgeText({ text: '*', tabId: sender.tab.id });
}
// If there is only one match, fill the credentials, otherwise prompt the user
if (matches.length === 1) {
const m = matches[0];
browser.tabs.sendMessage(sender.tab.id, {
message: 'fill_creds',
username: m.username,
password: m.password,
});
} else if (matches.length > 1) {
promptUserForChoice(matches, sender.tab.id);
}
}
function promptUserForChoice(matches, tabId) {
browser.tabs.sendMessage(tabId, {
type: 'show_matches_popup_iframe',
matches: matches,
});
}
async function renewToken(force = false) {
const vaultToken = await storage.local.get('vaultToken');
const vaultAddress = await storage.sync.get('vaultAddress');
if (vaultToken) {
try {
const vault = new Vault(vaultToken, vaultAddress);
const token = await vault.get('/auth/token/lookup-self');
console.log(
`${new Date().toLocaleString()} Token will expire in ${
token.data.ttl / 60
} minutes`
);
if (token.data.ttl > 3600) {
refreshTokenTimer(1800);
} else {
refreshTokenTimer(token.data.ttl / 2);
}
if (force || token.data.ttl <= 600) {
console.log(`${new Date().toLocaleString()} Renewing Token...`);
const newToken = await vault.post('/auth/token/renew-self', {
increment: idealTokenTTL,
});
console.log(
`${new Date().toLocaleString()} Token renewed. It will expire in ${
newToken.auth.lease_duration / 60
} minutes`
);
}
await browser.action.setBadgeBackgroundColor({ color: '#1c98ed' });
} catch (e) {
console.log(e);
await browser.action.setBadgeBackgroundColor({ color: '#FF0000' });
await browser.action.setBadgeText({ text: '!' });
refreshTokenTimer();
}
}
}
function setupTokenAutoRenew(interval = 1800) {
browser.alarms.get(tokenRenewAlarm).then((alarm) => {
if (alarm) {
browser.alarms.clear(tokenRenewAlarm);
}
browser.alarms.create(tokenRenewAlarm, {
periodInMinutes: interval / 60,
});
});
}
function refreshTokenTimer(delay = 45) {
browser.alarms.get(tokenCheckAlarm).then((alarm) => {
if (alarm) {
browser.alarms.clear(tokenCheckAlarm);
}
browser.alarms.create(tokenCheckAlarm, {
delayInMinutes: delay / 60,
});
});
}
function setupIdleListener() {
if (!browser.idle.onStateChanged.hasListener(newStateHandler)) {
browser.idle.onStateChanged.addListener(newStateHandler);
}
}
async function newStateHandler(newState) {
console.log(`${new Date().toLocaleString()} ${newState}`);
if (newState === 'active') {
await renewToken(false);
}
if (newState === 'locked') {
await renewToken(true);
}
}
browser.alarms.onAlarm.addListener(async function (alarm) {
if (alarm.name === tokenCheckAlarm) {
await renewToken();
}
if (alarm.name === tokenRenewAlarm) {
await renewToken(true);
}
});
browser.runtime.onMessage.addListener(function (message, sender) {
if (message.type === 'auto_fill_secrets') {
setupIdleListener();
autoFillSecrets(message, sender).catch(console.error);
}
if (message.type === 'auto_renew_token') {
refreshTokenTimer();
}
});
// Listener to catch the fill_creds message and then forward it to the active tab
browser.runtime.onMessage.addListener((request) => {
if (request.message === 'fill_creds') {
browser.tabs.query({ active: true, currentWindow: true }).then((tabs) => {
if (tabs.length) {
browser.tabs.sendMessage(tabs[0].id, request);
}
});
}
if (request.type === 'start_web_login_flow') {
startWebLoginFlow(request.vaultServer);
}
});
async function startWebLoginFlow(vaultServer) {
const loginUrl = `${vaultServer}/ui/vault/auth`;
const tab = await browser.tabs.create({ url: loginUrl });
const pollInterval = 2000; // 2 seconds
const maxPolls = 150; // 5 minutes total
let pollCount = 0;
const poller = setInterval(async () => {
pollCount++;
if (pollCount > maxPolls) {
clearInterval(poller);
// notify user somehow? (cannot notify popup if closed)
return;
}
try {
// Check if tab is still open
const currentTab = await browser.tabs.get(tab.id);
if (!currentTab) {
clearInterval(poller);
return;
}
// Try to fetch token
await browser.tabs.sendMessage(tab.id, { message: 'fetch_token' });
} catch {
// Ignore errors while polling
}
}, pollInterval);
// Listener to stop polling when token is found
const tokenListener = async (message) => {
if (message.type === 'fetch_token') {
clearInterval(poller);
browser.runtime.onMessage.removeListener(tokenListener);
// Token found! Process it just like options.js would have
await browser.storage.local.set({ vaultToken: message.token });
await browser.storage.sync.set({ vaultAddress: message.address });
// Start auto-renew
browser.alarms.create(tokenCheckAlarm, {
delayInMinutes: 45 / 60,
});
await renewToken();
// We need to notify options page if it's open, but mostly just saving it is enough
// The user will see they are logged in next time they open popup/options
console.log('login successful via background script');
}
};
browser.runtime.onMessage.addListener(tokenListener);
}