initial commit
[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 return input
29 .replace(/=/g, '')
30 .replace(/\+/g, '-')
31 .replace(/\//g, '_');
32 };
33
34
35 /**
36 * Convert Base64URL to normal Base64.
37 * @param {String} input
38 * @returns {String}
39 */
40 const base64URLToBase64 = (input) => {
41 return base64RePad(input)
42 .replace(/-/g, '+')
43 .replace(/_/, '/');
44 };
45
46
47 /**
48 * Add any missing trailing padding which may have been removed from Base64URL encoding.
49 * @param {String} input
50 */
51 const base64RePad = (input) => {
52 const blockSize = 4;
53 const lastBlockSize = input.length % blockSize;
54 if (lastBlockSize) {
55 const missing = blockSize - lastBlockSize;
56 return input + '='.repeat(missing);
57 }
58 return input;
59 };
60
61
62 module.exports = {
63 base64ToBase64URL,
64 base64URLToBase64,
65 base64RePad,
66 fileScope,
67 randomBytesAsync,
68 };