Debian Codegraph @

browserpass-extension/src/helpers.js

raw
1 //------------------------------------- Initialisation --------------------------------------//
2 "use strict";
3
4 const FuzzySort = require("fuzzysort");
5 const sha1 = require("sha1");
6 const ignore = require("ignore");
7 const hash = require("hash.js");
8 const Authenticator = require("otplib").authenticator.Authenticator;
9 const BrowserpassURL = require("@browserpass/url");
10
11 module.exports = {
12 prepareLogins,
13 filterSortLogins,
14 ignoreFiles,
15 makeTOTP,
16 };
17
18 //----------------------------------- Function definitions ----------------------------------//
19
20 /**
21 * Get the deepest available domain component of a path
22 *
23 * @since 3.2.3
24 *
25 * @param string path Path to parse
26 * @param object currentHost Current host info for the active tab
27 * @return object|null Extracted domain info
28 */
29 function pathToInfo(path, currentHost) {
30 var parts = path.split(/\//).reverse();
31 for (var key in parts) {
32 if (parts[key].indexOf("@") >= 0) {
33 continue;
34 }
35 var info = BrowserpassURL.parseHost(parts[key]);
36
37 // Part is considered to be a domain component in one of the following cases:
38 // - it is a valid domain with well-known TLD (github.com, login.github.com)
39 // - it is or isn't a valid domain with any TLD but the current host matches it EXACTLY (localhost, pi.hole)
40 // - it is or isn't a valid domain with any TLD but the current host is its subdomain (login.pi.hole)
41 if (
42 info.validDomain ||
43 currentHost.hostname === info.hostname ||
44 currentHost.hostname.endsWith(`.${info.hostname}`)
45 ) {
46 return info;
47 }
48 }
49
50 return null;
51 }
52
53 /**
54 * Prepare list of logins based on provided files
55 *
56 * @since 3.1.0
57 *
58 * @param string array List of password files
59 * @param string object Settings object
60 * @return array List of logins
61 */
62 function prepareLogins(files, settings) {
63 const logins = [];
64 let index = 0;
65 let origin = new BrowserpassURL(settings.origin);
66
67 for (let storeId in files) {
68 for (let key in files[storeId]) {
69 // set login fields
70 const login = {
71 index: index++,
72 store: settings.stores[storeId],
73 login: files[storeId][key].replace(/\.gpg$/i, ""),
74 allowFill: true,
75 };
76
77 // extract url info from path
78 let pathInfo = pathToInfo(storeId + "/" + login.login, origin);
79 if (pathInfo) {
80 // set assumed host
81 login.host = pathInfo.port
82 ? `${pathInfo.hostname}:${pathInfo.port}`
83 : pathInfo.hostname;
84
85 // check whether extracted path info matches the current origin
86 login.inCurrentHost = origin.hostname === pathInfo.hostname;
87
88 // check whether the current origin is subordinate to extracted path info, meaning:
89 // - that the path info is not a single level domain (e.g. com, net, local)
90 // - and that the current origin is a subdomain of that path info
91 if (
92 pathInfo.hostname.includes(".") &&
93 origin.hostname.endsWith(`.${pathInfo.hostname}`)
94 ) {
95 login.inCurrentHost = true;
96 }
97
98 // filter out entries with a non-matching port
99 if (pathInfo.port && pathInfo.port !== origin.port) {
100 login.inCurrentHost = false;
101 }
102 } else {
103 login.host = null;
104 login.inCurrentHost = false;
105 }
106
107 // update recent counter
108 login.recent =
109 settings.recent[sha1(settings.origin + sha1(login.store.id + sha1(login.login)))];
110 if (!login.recent) {
111 login.recent = {
112 when: 0,
113 count: 0,
114 };
115 }
116
117 logins.push(login);
118 }
119 }
120
121 return logins;
122 }
123
124 /**
125 * Filter and sort logins
126 *
127 * @since 3.1.0
128 *
129 * @param string array List of logins
130 * @param string object Settings object
131 * @return array Filtered and sorted list of logins
132 */
133 function filterSortLogins(logins, searchQuery, currentDomainOnly) {
134 var fuzzyFirstWord = searchQuery.substr(0, 1) !== " ";
135 searchQuery = searchQuery.trim();
136
137 // get candidate list
138 var candidates = logins.map((candidate) => {
139 let lastSlashIndex = candidate.login.lastIndexOf("/") + 1;
140 return Object.assign(candidate, {
141 path: candidate.login.substr(0, lastSlashIndex),
142 display: candidate.login.substr(lastSlashIndex),
143 });
144 });
145
146 var mostRecent = null;
147 if (currentDomainOnly) {
148 var recent = candidates.filter(function (login) {
149 if (login.recent.count > 0) {
150 // find most recently used login
151 if (!mostRecent || login.recent.when > mostRecent.recent.when) {
152 mostRecent = login;
153 }
154 return true;
155 }
156 return false;
157 });
158 var remainingInCurrentDomain = candidates.filter(
159 (login) => login.inCurrentHost && !login.recent.count
160 );
161 candidates = recent.concat(remainingInCurrentDomain);
162 }
163
164 candidates.sort((a, b) => {
165 // show most recent first
166 if (a === mostRecent) {
167 return -1;
168 }
169 if (b === mostRecent) {
170 return 1;
171 }
172
173 // sort by frequency
174 var countDiff = b.recent.count - a.recent.count;
175 if (countDiff) {
176 return countDiff;
177 }
178
179 // sort by specificity, only if filtering for one domain
180 if (currentDomainOnly) {
181 var domainLevelsDiff =
182 (b.login.match(/\./g) || []).length - (a.login.match(/\./g) || []).length;
183 if (domainLevelsDiff) {
184 return domainLevelsDiff;
185 }
186 }
187
188 // sort alphabetically
189 return a.login.localeCompare(b.login);
190 });
191
192 if (searchQuery.length) {
193 let filter = searchQuery.split(/\s+/);
194 let fuzzyFilter = fuzzyFirstWord ? filter[0] : "";
195 let substringFilters = filter.slice(fuzzyFirstWord ? 1 : 0).map((w) => w.toLowerCase());
196
197 // First reduce the list by running the substring search
198 substringFilters.forEach(function (word) {
199 candidates = candidates.filter((c) => c.login.toLowerCase().indexOf(word) >= 0);
200 });
201
202 // Then run the fuzzy filter
203 let fuzzyResults = {};
204 if (fuzzyFilter) {
205 candidates = FuzzySort.go(fuzzyFilter, candidates, {
206 keys: ["login", "store.name"],
207 allowTypo: false,
208 }).map((result) => {
209 fuzzyResults[result.obj.login] = result;
210 return result.obj;
211 });
212 }
213
214 // Finally highlight all matches
215 candidates = candidates.map((c) => highlightMatches(c, fuzzyResults, substringFilters));
216 }
217
218 // Prefix root entries with slash to let them have some visible path
219 candidates.forEach((c) => {
220 c.path = c.path || "/";
221 });
222
223 return candidates;
224 }
225
226 /**
227 * Generate TOTP token
228 *
229 * @since 3.6.0
230 *
231 * @param object params OTP generation params
232 * @return string Generated OTP code
233 */
234 function makeTOTP(params) {
235 switch (params.algorithm) {
236 case "sha1":
237 case "sha256":
238 case "sha512":
239 break;
240 default:
241 throw new Error(`Unsupported TOTP algorithm: ${params.algorithm}`);
242 }
243
244 var generator = new Authenticator();
245 generator.options = {
246 crypto: {
247 createHmac: (a, k) => hash.hmac(hash[a], k),
248 },
249 algorithm: params.algorithm,
250 digits: params.digits,
251 step: params.period,
252 };
253
254 return generator.generate(params.secret);
255 }
256
257 //----------------------------------- Private functions ----------------------------------//
258
259 /**
260 * Highlight filter matches
261 *
262 * @since 3.0.0
263 *
264 * @param object entry password entry
265 * @param object fuzzyResults positions of fuzzy filter matches
266 * @param array substringFilters list of substring filters applied
267 * @return object entry with highlighted matches
268 */
269 function highlightMatches(entry, fuzzyResults, substringFilters) {
270 // Add all positions of the fuzzy search to the array
271 let matches = (fuzzyResults[entry.login] && fuzzyResults[entry.login][0]
272 ? fuzzyResults[entry.login][0].indexes
273 : []
274 ).slice();
275
276 // Add all positions of substring searches to the array
277 let login = entry.login.toLowerCase();
278 for (let word of substringFilters) {
279 let startIndex = login.indexOf(word);
280 for (let i = 0; i < word.length; i++) {
281 matches.push(startIndex + i);
282 }
283 }
284
285 // Prepare the final array of matches before
286 matches = sortUnique(matches, (a, b) => a - b);
287
288 const OPEN = "<em>";
289 const CLOSE = "</em>";
290 let highlighted = "";
291 var matchesIndex = 0;
292 var opened = false;
293 for (var i = 0; i < entry.login.length; ++i) {
294 var char = entry.login[i];
295
296 if (i == entry.path.length) {
297 if (opened) {
298 highlighted += CLOSE;
299 }
300 var path = highlighted;
301 highlighted = "";
302 if (opened) {
303 highlighted += OPEN;
304 }
305 }
306
307 if (matches[matchesIndex] === i) {
308 matchesIndex++;
309 if (!opened) {
310 opened = true;
311 highlighted += OPEN;
312 }
313 } else {
314 if (opened) {
315 opened = false;
316 highlighted += CLOSE;
317 }
318 }
319 highlighted += char;
320 }
321 if (opened) {
322 opened = false;
323 highlighted += CLOSE;
324 }
325 let display = highlighted;
326
327 return Object.assign(entry, {
328 path: path,
329 display: display,
330 });
331 }
332
333 /**
334 * Filter out ignored files according to .browserpass.json rules
335 *
336 * @since 3.2.0
337 *
338 * @param object files Arrays of files, grouped by store
339 * @param object settings Settings object
340 * @return object Filtered arrays of files, grouped by store
341 */
342 function ignoreFiles(files, settings) {
343 let filteredFiles = {};
344 for (let store in files) {
345 let storeSettings = settings.stores[store].settings;
346 if (storeSettings.hasOwnProperty("ignore")) {
347 if (typeof storeSettings.ignore === "string") {
348 storeSettings.ignore = [storeSettings.ignore];
349 }
350 filteredFiles[store] = ignore().add(storeSettings.ignore).filter(files[store]);
351 } else {
352 filteredFiles[store] = files[store];
353 }
354 }
355 return filteredFiles;
356 }
357
358 /**
359 * Sort and remove duplicates
360 *
361 * @since 3.0.0
362 *
363 * @param array array items to sort
364 * @param function comparator sort comparator
365 * @return array sorted items without duplicates
366 */
367 function sortUnique(array, comparator) {
368 return array
369 .sort(comparator)
370 .filter((elem, index, arr) => index == !arr.length || arr[index - 1] != elem);
371 }