forked from Dmitry1987/vault-chrome-extension
-
Notifications
You must be signed in to change notification settings - Fork 38
/
background.js
253 lines (212 loc) · 6.47 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
/* eslint-disable no-console */
/* global chrome */
const idealTokenTTL = '24h';
const tokenCheckAlarm = 'tokenCheck';
const tokenRenewAlarm = 'tokenRenew';
if (!chrome.browserAction) {
chrome.browserAction = chrome.action;
}
setupTokenAutoRenew(1800);
refreshTokenTimer();
setupIdleListener();
const storage = {
storageGetterProvider: (storageType) => {
return function (key, defaultValue) {
return new Promise(function (resolve, reject) {
try {
chrome.storage[storageType].get([key], function (result) {
const value = result[key] || defaultValue || null;
resolve(value);
});
} 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;
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);
// If the key is an exact match to the current hostname --> autofill
if (hostname === clearHostname(key)) {
const credentials = await vault.get(
`/${storeComponents.root}/data/${storeComponents.subPath}/${secret}${key}`
);
chrome.tabs.sendMessage(sender.tab.id, {
message: 'fill_creds',
username: credentials.data.data.username,
password: credentials.data.data.password,
});
}
if (patternMatches) {
loginCount++;
}
}
}
if (loginCount > 0) {
chrome.browserAction.setBadgeText({ text: '*', tabId: sender.tab.id });
}
}
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 chrome.browserAction.setBadgeBackgroundColor({ color: '#1c98ed' });
} catch (e) {
console.log(e);
await chrome.browserAction.setBadgeBackgroundColor({ color: '#FF0000' });
await chrome.browserAction.setBadgeText({ text: '!' });
refreshTokenTimer();
}
}
}
function setupTokenAutoRenew(interval = 1800) {
chrome.alarms.get(tokenRenewAlarm, function(exists) {
if (exists) {
chrome.alarms.clear(tokenRenewAlarm);
}
chrome.alarms.create(tokenRenewAlarm, {
periodInMinutes: interval / 60
});
});
}
function refreshTokenTimer(delay = 45) {
chrome.alarms.get(tokenCheckAlarm, function(exists) {
if (exists) {
chrome.alarms.clear(tokenCheckAlarm);
}
chrome.alarms.create(tokenCheckAlarm, {
delayInMinutes: delay / 60
});
});
}
function setupIdleListener() {
if (!chrome.idle.onStateChanged.hasListener(newStateHandler)) {
chrome.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);
}
}
chrome.alarms.onAlarm.addListener(async function (alarm) {
if (alarm.name === tokenCheckAlarm) {
await renewToken();
}
if (alarm.name === tokenRenewAlarm) {
await renewToken(true);
}
})
chrome.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();
}
});