a47226f6e76fe355416380f3a77db24450481783
[squeep-mystery-box] / lib / common.js
1 'use strict';
2
3 const path = require('path');
4 const { randomBytes } = require('crypto');
5 const { promisify } = require('util');
6 const randomBytesAsync = promisify(randomBytes);
7
8
9 /**
10 * Return a function which combines a part of the filename with a scope, for use in logging.
11 * @param {string} filename
12 */
13 const fileScope = (filename) => {
14 let fScope = path.basename(filename, '.js');
15 if (fScope === 'index') {
16 fScope = path.basename(path.dirname(filename));
17 }
18 return (scope) => `${fScope}:${scope}`;
19 }
20
21
22 /**
23 * Convert Base64 to Base64URL.
24 * @param {String} input
25 * @returns {String}
26 */
27 const base64ToBase64URL = (input) => {
28 if (!input) {
29 return input;
30 }
31 return input
32 .replace(/=/g, '')
33 .replace(/\+/g, '-')
34 .replace(/\//g, '_');
35 };
36
37
38 /**
39 * Convert Base64URL to normal Base64.
40 * @param {String} input
41 * @returns {String}
42 */
43 const base64URLToBase64 = (input) => {
44 if (!input) {
45 return input;
46 }
47 return base64RePad(input)
48 .replace(/-/g, '+')
49 .replace(/_/, '/');
50 };
51
52
53 /**
54 * Add any missing trailing padding which may have been removed from Base64URL encoding.
55 * @param {String} input
56 */
57 const base64RePad = (input) => {
58 const blockSize = 4;
59 const lastBlockSize = input.length % blockSize;
60 if (lastBlockSize) {
61 const missing = blockSize - lastBlockSize;
62 return input + '='.repeat(missing);
63 }
64 return input;
65 };
66
67
68 module.exports = {
69 base64ToBase64URL,
70 base64URLToBase64,
71 base64RePad,
72 fileScope,
73 randomBytesAsync,
74 };