3 const crypto
= require('crypto');
4 const zlib
= require('zlib');
5 const { promisify
} = require('util');
6 const common
= require('./common');
7 const allVersions
= require('./version-parameters');
8 const { performance
} = require('perf_hooks');
10 const _fileScope
= common
.fileScope(__filename
);
12 const brotliCompressAsync
= promisify(zlib
.brotliCompress
);
13 const brotliDecompressAsync
= promisify(zlib
.brotliDecompress
);
14 const deflateRawAsync
= promisify(zlib
.deflateRaw
);
15 const inflateRawAsync
= promisify(zlib
.inflateRaw
);
16 const scryptAsync
= promisify(crypto
.scrypt
);
19 * Only you will know what's inside your...
21 * |\/ | | | __| __| _ \ __| | __ \ _ \ \ /
22 * | | | |\__ \ | __/ | | | | | ( |` <
23 * _| _|\__, |____/\__|\___|_| \__, |____/ \___/ _/\_\
26 * Our very own way of converting a buffer or serializable object
27 * to and from an opaque and web-safe representation, which we can
28 * let anyone see without disclosing the contents, nor allowing it
29 * to be modified without detection.
31 * The result is a Base64URL-encoded byte-array consisting of:
32 * - version, indicating format and encryption algorithm
33 * - flags, indicating state of the contents
34 * - iv/nonce, randomness for the algorithm
35 * - salt, applied to a secret to derive a key
36 * - tag, additional room for encryption to validate the previous fields
37 * - payload, encrypted version of possibly compressed and serialized object
42 const availableFlags
= {
43 Brotli: (1<<0), // Slightly better compression, but slow
44 Flate: (1<<1), // Slightly worse compression, but much faster especially with larger payloads. Prefer this.
45 FutureCompression: (1<<0)|(1<<1), // Something else, like zstd maybe.
53 BufferPayload: (1<<7), // Payload is a buffer, not an object
55 const compressionFlagsMask
= (availableFlags
.Flate
| availableFlags
.Brotli
);
56 const compressionFlagsShift
= 0;
57 const payloadFlagsMask
= (availableFlags
.BufferPayload
);
58 const payloadFlagsShift
= 7;
63 * @param {Console} logger
64 * @param {Object} options
65 * @param {String} options.encryptionSecret
66 * @param {Number=} options.defaultFlags
68 constructor(logger
, options
= {}) {
70 this.options
= options
;
72 this.secret
= options
.encryptionSecret
;
74 throw new Error('missing encryption secret');
76 // TODO: support secret rolling
78 // Filter any unavailable algorithms
79 const availableCiphers
= crypto
.getCiphers();
80 this.versionParameters
= Object
.entries(allVersions
).reduce((acc
, [v
, p
]) => {
81 if (availableCiphers
.includes(p
.algorithm
)) {
82 acc
[v
] = p
; // eslint-disable-line security/detect-object-injection
88 this.bestVersion
= Number(Object
.keys(this.versionParameters
).sort().pop());
89 if (Number
.isNaN(this.bestVersion
)) {
90 throw new Error('no supported versions available');
93 this.Flags
= availableFlags
;
94 this.defaultFlags
= 'defaultFlags' in options
? options
.defaultFlags : availableFlags
.Flate
;
95 if (this.defaultFlags
< 0 || this.defaultFlags
> 255) {
96 throw new RangeError('Invalid default flag value');
102 * Parse the bits out of the flags.
104 static _decodeFlags(flags
) {
106 compression: (flags
& compressionFlagsMask
) >> compressionFlagsShift
,
107 payloadIsBuffer: Boolean((flags
& payloadFlagsMask
) >> payloadFlagsShift
),
113 * Put contents into a mysterious box.
114 * @param {Object|Buffer} contents
117 async
pack(contents
, version
= this.bestVersion
, flags
= this.defaultFlags
) {
118 const _scope
= _fileScope('pack');
120 start: performance
.now(),
128 if (!(version
in this.versionParameters
)) {
129 throw new RangeError(`MysteryBox format version ${version} not supported`);
131 // eslint-disable-next-line security/detect-object-injection
132 const v
= this.versionParameters
[version
];
134 const { compression
} = MysteryBox
._decodeFlags(flags
);
136 if (Buffer
.isBuffer(contents
)) {
137 flags
|= this.Flags
.BufferPayload
;
139 contents
= JSON
.stringify(contents
);
142 const versionBuffer
= Buffer
.alloc(v
.versionBytes
);
143 versionBuffer
.writeUInt8(v
.version
, 0);
145 const [iv
, salt
] = await Promise
.all([
148 ].map((b
) => common
.randomBytesAsync(b
)));
150 timingsMs
.preCompress
= performance
.now();
151 let compressedContents
;
152 switch (compression
) {
153 case 0: // No compression requested
154 compressedContents
= contents
;
156 case this.Flags
.Brotli:
157 compressedContents
= await
brotliCompressAsync(contents
);
159 case this.Flags
.Flate:
160 compressedContents
= await
deflateRawAsync(contents
);
163 timingsMs
.postCompress
= timingsMs
.preCrypt
= performance
.now();
166 if (compressedContents
.length
>= contents
.length
) {
167 flags
= flags
& ~compressionFlagsMask
;
170 payload
= compressedContents
;
172 const flagsBuffer
= Buffer
.alloc(v
.flagsBytes
);
173 flagsBuffer
.writeUInt8(flags
, 0);
175 // Authenticate all this data
176 const aadBuffer
= Buffer
.concat([versionBuffer
, flagsBuffer
, iv
, salt
]);
178 const key
= await
scryptAsync(this.secret
, salt
, v
.keyBytes
);
179 const cipher
= crypto
.createCipheriv(v
.algorithm
, key
, iv
, v
.algOptions
);
180 cipher
.setAAD(aadBuffer
);
181 const encrypted
= cipher
.update(payload
);
182 const final
= cipher
.final();
183 const tag
= cipher
.getAuthTag();
185 const merged
= Buffer
.concat([versionBuffer
, flagsBuffer
, iv
, salt
, tag
, encrypted
, final
]).toString('base64');
186 const result
= common
.base64ToBase64URL(merged
);
187 timingsMs
.end
= timingsMs
.postCrypt
= performance
.now();
189 this.logger
.debug(_scope
, 'statistics', { version
, flags: this._prettyFlags(flags
), serialized: contents
.length
, compressed: payload
.length
, encoded: result
.length
, ...MysteryBox
._timingsLog(timingsMs
) });
196 * Take contents out of a mysterious box.
197 * @param {String} box - Base64URL encoded payload
201 const _scope
= _fileScope('unpack');
203 start: performance
.now(),
211 const raw
= Buffer
.from(common
.base64URLToBase64(box
), 'base64');
214 const version
= raw
.slice(offset
, 1).readUInt8(0);
215 if (!(version
in this.versionParameters
)) {
216 throw new RangeError('unsupported version');
218 // eslint-disable-next-line security/detect-object-injection
219 const v
= this.versionParameters
[version
];
220 offset
+= v
.versionBytes
;
222 const flags
= raw
.slice(offset
, offset
+ v
.flagsBytes
).readUInt8(0);
223 offset
+= v
.flagsBytes
;
225 const { compression
, payloadIsBuffer
} = MysteryBox
._decodeFlags(flags
);
227 const iv
= raw
.slice(offset
, offset
+ v
.ivBytes
);
230 const salt
= raw
.slice(offset
, offset
+ v
.saltBytes
);
231 offset
+= v
.saltBytes
;
233 const aad
= raw
.slice(0, offset
); // Everything up to here
235 const tag
= raw
.slice(offset
, offset
+ v
.tagBytes
);
236 offset
+= v
.tagBytes
;
238 const encrypted
= raw
.slice(offset
);
240 timingsMs
.preCrypt
= performance
.now();
241 const key
= await
scryptAsync(this.secret
, salt
, v
.keyBytes
);
242 const decipher
= crypto
.createDecipheriv(v
.algorithm
, key
, iv
, v
.algOptions
);
243 decipher
.setAAD(aad
);
244 decipher
.setAuthTag(tag
);
246 const decrypted
= Buffer
.concat([decipher
.update(encrypted
), decipher
.final()]);
249 timingsMs
.preCompress
= timingsMs
.postCrypt
= performance
.now();
250 switch (compression
) {
251 case 0: // No compression
254 case this.Flags
.Brotli:
255 payload
= await
brotliDecompressAsync(decrypted
);
257 case this.Flags
.Flate:
258 payload
= await
inflateRawAsync(decrypted
);
261 timingsMs
.end
= timingsMs
.postCompress
= performance
.now();
263 if (!payloadIsBuffer
) {
264 payload
= JSON
.parse(payload
.toString('utf8'));
267 this.logger
.debug(_scope
, 'statistics', { version
, flags: this._prettyFlags(flags
), ...MysteryBox
._timingsLog(timingsMs
) });
274 * Pretty-print flag values
275 * @param {Number} flags
278 _prettyFlags(flags
) {
279 const flagNames
= Object
.entries(this.Flags
).reduce((acc
, cur
) => {
280 const [flagName
, flagValue
] = cur
;
281 if ((flags
& flagValue
) === flagValue
) {
286 return `0x${flags.toString(16).padStart(2, '0')} [${flagNames.join(',')}]`;
291 * Everyone loves numbers.
292 * @param {Object} timingsMs
295 static _timingsLog({ start
, preCompress
, postCompress
, preCrypt
, postCrypt
, end
}) {
297 totalMs: end
- start
,
298 compressMs: postCompress
- preCompress
,
299 cryptMs: postCrypt
- preCrypt
,
305 // Expose for stubbing in tests
306 MysteryBox
._test
= { crypto
};
308 module
.exports
= MysteryBox
;