5dcf1b1fe4dbc8486c62de6e0cf3cbd3be96f2a6
3 const { EventEmitter
} = require('events');
4 const crypto
= require('crypto');
5 const zlib
= require('zlib');
6 const { promisify
} = require('util');
7 const common
= require('./common');
8 const allVersions
= require('./version-parameters');
9 const { performance
} = require('perf_hooks');
10 const { name: packageName
, version: packageVersion
} = require('../package.json');
17 const brotliCompressAsync
= promisify(zlib
.brotliCompress
);
18 const brotliDecompressAsync
= promisify(zlib
.brotliDecompress
);
19 const deflateRawAsync
= promisify(zlib
.deflateRaw
);
20 const inflateRawAsync
= promisify(zlib
.inflateRaw
);
21 const scryptAsync
= promisify(crypto
.scrypt
);
24 * Only you will know what's inside your...
26 * |\/ | | | __| __| _ \ __| | __ \ _ \ \ /
27 * | | | |\__ \ | __/ | | | | | ( |` <
28 * _| _|\__, |____/\__|\___|_| \__, |____/ \___/ _/\_\
31 * Our very own way of converting a buffer or serializable object
32 * to and from an opaque and web-safe representation, which we can
33 * let anyone see without disclosing the contents, nor allowing it
34 * to be modified without detection.
36 * The result is a Base64URL-encoded byte-array consisting of:
37 * - version, indicating format and encryption algorithm
38 * - flags, indicating state of the contents
39 * - iv/nonce, randomness for the algorithm
40 * - salt, applied to a secret to derive a key
41 * - tag, additional room for encryption to validate the previous fields
42 * - payload, encrypted version of possibly compressed and serialized object
47 const availableFlags
= {
48 Brotli: (1<<0), // Slightly better compression, but slow
49 Flate: (1<<1), // Slightly worse compression, but much faster especially with larger payloads. Prefer this.
50 FutureCompression: (1<<0)|(1<<1), // Something else, like zstd maybe.
58 BufferPayload: (1<<7), // Payload is a buffer, not an object
60 const compressionFlagsMask
= (availableFlags
.Flate
| availableFlags
.Brotli
);
61 const compressionFlagsShift
= 0;
62 const payloadFlagsMask
= (availableFlags
.BufferPayload
);
63 const payloadFlagsShift
= 7;
66 class MysteryBox
extends EventEmitter
{
68 * @param {Object} options
69 * @param {String|String[]} options.encryptionSecret - if an array, will always encrypt with first secret, will attempt to decrypt with all; useful for rolling secrets
70 * @param {Number=} options.defaultFlags
72 constructor(options
= {}, ...args
) {
74 this.secrets
= common
.ensureArray(options
.encryptionSecret
);
75 if (!this.secrets
.length
) {
76 throw new Error('missing encryption secret');
79 // Filter any unavailable algorithms
80 const availableCiphers
= crypto
.getCiphers();
81 const availableHashes
= crypto
.getHashes();
82 // Add legacy scrypt to available hashes for filtering key derivations
83 availableHashes
.push(allVersions
.KD
.SCRYPT
);
84 this.versionParameters
= Object
.entries(allVersions
).reduce((acc
, [v
, p
]) => {
85 const validCipher
= availableCiphers
.includes(p
.algorithm
);
86 const validKeyDeriver
= availableHashes
.includes(p
.keyDeriver
);
87 if (validCipher
&& validKeyDeriver
) {
88 acc
[v
] = p
; // eslint-disable-line security/detect-object-injection
94 this.bestVersion
= Number(Object
.keys(this.versionParameters
).sort().pop());
95 if (Number
.isNaN(this.bestVersion
)) {
96 throw new Error('no supported versions available');
99 this.Flags
= availableFlags
;
100 this.defaultFlags
= 'defaultFlags' in options
? options
.defaultFlags : availableFlags
.Flate
;
101 if (this.defaultFlags
< 0 || this.defaultFlags
> 255) {
102 throw new RangeError('Invalid default flag value');
108 * Parse the bits out of the flags.
110 static _decodeFlags(flags
) {
112 compression: (flags
& compressionFlagsMask
) >> compressionFlagsShift
,
113 payloadIsBuffer: Boolean((flags
& payloadFlagsMask
) >> payloadFlagsShift
),
121 static async
_keyFromSecret(deriver
, secret
, salt
, keyBytes
) {
123 case allVersions
.KD
.SHAKE256: {
124 const hash
= crypto
.createHash(allVersions
.KD
.SHAKE256
, { outputLength: keyBytes
});
127 return hash
.digest();
130 case allVersions
.KD
.BLAKE2B512: {
131 const hash
= crypto
.createHash(allVersions
.KD
.BLAKE2B512
);
134 const digest
= hash
.digest();
135 // should assert that keyBytes <= 64
136 // but not concerned about that for now
137 // until we have a new algorithm with bigger key size
138 return digest
.subarray(0, keyBytes
);
141 case allVersions
.KD
.SCRYPT:
142 return scryptAsync(secret
, salt
, keyBytes
);
145 throw new RangeError('unsupported key deriver');
151 * Return bits and bit mask for given number of encoded bytes.
152 * @param {Number} numBytes
155 static _versionHeaderBits(numBytes
) {
156 // Round up to 8 bits in result, just to be proper.
157 const resultBits
= (((numBytes
+ 7) >> 3) << 3) >>> 0;
159 headerValue: ((0xff << (resultBits
- numBytes
+ 1)) & 0xff) >>> 0,
160 headerMask: ((0xff << (resultBits
- numBytes
)) & 0xff) >>> 0,
166 * Parse a byte into the total number of bytes in the packed number,
167 * returning that and the new value for the first byte, to update in the
168 * buffer before parsing as an unsigned integer.
169 * Number of packed bytes is indicated by location of first leading 0 bit.
170 * Support for numbers larger than 127 is of dubious practicality, but here
172 * @param {Number} firstByte
175 static _versionHeaderDecode(firstByte
) {
176 for (let numBytes
= 1; numBytes
<= 8; numBytes
++) {
180 } = MysteryBox
._versionHeaderBits(numBytes
);
181 if (((firstByte
& headerMask
) >>> 0) === headerValue
) {
182 const restMask
= (~headerMask
& 0xff) >>> 0;
185 firstByte: (firstByte
& restMask
) >>> 0,
189 // Nine bytes would be an extravagence.
190 throw new RangeError(`unsupported version header (0x${firstByte.toString(16)})`);
195 * Decode leading bytes of buffer as version identifier.
196 * In the first byte, the position of the first unset bit indicates how
197 * many total bytes comprise the version, in big-endian encoding.
198 * Returns decoded version and number of bytes used to decode.
199 * Only supports up to 6-byte numbers, and of those, only up to 4398046511103.
200 * @param {Buffer} buf - N.B. will be mogrified
203 static _versionDecode(buf
) {
204 const headerByte
= buf
.readUInt8(0);
205 const { numBytes: versionBytes
, firstByte
} = MysteryBox
._versionHeaderDecode(headerByte
);
206 if (versionBytes
=== 1) {
213 if (versionBytes
> 6) {
214 throw new RangeError(`unsupported version (${versionBytes} bytes)`);
217 // Otherwise, update the masked first byte and parse the rest of the buffer.
220 version: buf
.readUIntBE(0, versionBytes
),
227 * Encode a version identifier into a buffer of a variable number of bytes.
228 * @param {Number} version
231 static _versionEncode(version
) {
232 let versionBytes
= 0;
234 if (version
<= 0x7f) { // 0-127
236 } else if (version
<= 0x3fff) { // 128-16383
238 } else if (version
<= 0x1fffff) { // 16384-2097151
240 } else if (version
<= 0x0fffffff) { // 2097152-268435455
242 } else if (version
<= 0x07ffffffff) { // 268435456-34359738367
244 } else if (version
<= 0x03ffffffffff) { // 34359738368-4398046511103
247 throw new RangeError('version too large to encode');
250 const buffer
= Buffer
.alloc(versionBytes
);
251 buffer
.writeUIntBE(version
, 0, versionBytes
);
252 const headerByte
= ((0xff << (8 - versionBytes
+ 1)) & 0xff) >>> 0;
253 buffer
[0] = (buffer
[0] | headerByte
) >>> 0;
263 * Stats tracked when packing/unpacking boxes.
266 static _newStats(method
) {
273 serializedBytes: undefined,
274 compressedBytes: undefined,
277 start: performance
.now(),
289 * Put contents into a mysterious box.
290 * @param {Object|Buffer} contents
291 * @param {Number=} version
292 * @param {Number=} flags
295 async
pack(contents
, version
= this.bestVersion
, flags
= this.defaultFlags
) {
296 const { stats
, timingsMs
} = MysteryBox
._newStats('pack');
298 if (!(version
in this.versionParameters
)) {
299 throw new RangeError(`MysteryBox format version ${version} not supported`);
301 // eslint-disable-next-line security/detect-object-injection
302 const v
= this.versionParameters
[version
];
303 stats
.version
= version
;
305 const { compression
, payloadIsBuffer
} = MysteryBox
._decodeFlags(flags
);
307 if (Buffer
.isBuffer(contents
)) {
308 // Ensure payloadIsBuffer flag is set when contents are indeed a Buffer
309 flags
|= this.Flags
.BufferPayload
;
311 if (payloadIsBuffer
) {
312 // Flag is set, but contents are not a Buffer? Try to coerce contents.
313 contents
= Buffer
.from(contents
);
315 // Otherwise attempt to serialize the object
316 contents
= JSON
.stringify(contents
);
319 stats
.serializedBytes
= Buffer
.byteLength(contents
);
321 const { buffer: versionBuffer
, versionBytes
} = MysteryBox
._versionEncode(v
.version
);
322 if (versionBytes
!== v
.versionBytes
) {
323 throw new Error('internal inconsistency, mismatched version byte length');
326 const [iv
, salt
] = await Promise
.all([
329 ].map((b
) => common
.randomBytesAsync(b
)));
331 timingsMs
.preCompress
= performance
.now();
332 let compressedContents
;
333 switch (compression
) {
334 case 0: // No compression requested
335 compressedContents
= contents
;
337 case this.Flags
.Brotli:
338 compressedContents
= await
brotliCompressAsync(contents
);
340 case this.Flags
.Flate:
341 compressedContents
= await
deflateRawAsync(contents
);
344 stats
.compressedBytes
= Buffer
.byteLength(compressedContents
);
345 // const compressionRatio = stats.compressedBytes / stats.serializedBytes;
346 timingsMs
.postCompress
= timingsMs
.preCrypt
= performance
.now();
349 if (stats
.compressedBytes
>= stats
.serializedBytes
) {
350 // If compression is not beneficial enough, or detrimental, do not use
351 flags
= flags
& ~compressionFlagsMask
;
353 stats
.compressedBytes
= undefined;
355 payload
= compressedContents
;
358 const flagsBuffer
= Buffer
.alloc(v
.flagsBytes
);
359 flagsBuffer
.writeUInt8(flags
, 0);
360 stats
.flagsRaw
= flags
;
361 stats
.flags
= this._prettyFlags(flags
);
363 // Authenticate all this data
364 const aadBuffer
= Buffer
.concat([versionBuffer
, flagsBuffer
, iv
, salt
]);
366 // Always encrypt with first secret
367 const secret
= this.secrets
[0];
368 const key
= await MysteryBox
._keyFromSecret(v
.keyDeriver
, secret
, salt
, v
.keyBytes
);
369 const cipher
= crypto
.createCipheriv(v
.algorithm
, key
, iv
, v
.algOptions
);
370 cipher
.setAAD(aadBuffer
);
371 const encrypted
= cipher
.update(payload
);
372 const final
= cipher
.final();
373 const tag
= cipher
.getAuthTag();
375 const result
= Buffer
.concat([versionBuffer
, flagsBuffer
, iv
, salt
, tag
, encrypted
, final
]).toString('base64url');
376 timingsMs
.end
= timingsMs
.postCrypt
= performance
.now();
378 this.emit('statistics', { ...stats
, ...MysteryBox
._timingsLog(timingsMs
), ...packageInfo
});
385 * Take contents out of a mysterious box.
386 * @param {String} box - Base64URL encoded payload
390 const { stats
, timingsMs
} = MysteryBox
._newStats('unpack');
393 throw new RangeError('nothing to unpack');
396 const raw
= Buffer
.from(box
, 'base64url');
399 const { version
, versionBytes
} = MysteryBox
._versionDecode(raw
);
400 if (!(version
in this.versionParameters
)) {
401 throw new RangeError('unsupported version');
403 // eslint-disable-next-line security/detect-object-injection
404 const v
= this.versionParameters
[version
];
406 if (v
.versionBytes
!== versionBytes
) {
407 throw new Error('internal inconsistency, mismatched version byte length');
409 offset
+= v
.versionBytes
;
410 stats
.version
= version
;
412 const minBytes
= v
.versionBytes
+ v
.flagsBytes
+ v
.ivBytes
+ v
.saltBytes
+ v
.tagBytes
;
413 if (raw
.length
< minBytes
) {
414 throw new RangeError('not enough to unpack');
417 const flags
= raw
.subarray(offset
, offset
+ v
.flagsBytes
).readUInt8(0);
418 offset
+= v
.flagsBytes
;
419 stats
.flagsRaw
= flags
;
421 const { compression
, payloadIsBuffer
} = MysteryBox
._decodeFlags(flags
);
423 const iv
= raw
.subarray(offset
, offset
+ v
.ivBytes
);
426 const salt
= raw
.subarray(offset
, offset
+ v
.saltBytes
);
427 offset
+= v
.saltBytes
;
429 const aad
= raw
.subarray(0, offset
); // Everything up to here
431 const tag
= raw
.subarray(offset
, offset
+ v
.tagBytes
);
432 offset
+= v
.tagBytes
;
434 const encrypted
= raw
.subarray(offset
);
436 timingsMs
.preCrypt
= performance
.now();
441 for await (const secret
of this.secrets
) {
442 const key
= await MysteryBox
._keyFromSecret(v
.keyDeriver
, secret
, salt
, v
.keyBytes
);
443 const decipher
= crypto
.createDecipheriv(v
.algorithm
, key
, iv
, v
.algOptions
);
444 decipher
.setAAD(aad
);
445 decipher
.setAuthTag(tag
);
448 decrypted
= Buffer
.concat([decipher
.update(encrypted
), decipher
.final()]);
461 timingsMs
.preCompress
= timingsMs
.postCrypt
= performance
.now();
462 switch (compression
) {
463 case 0: // No compression
466 case this.Flags
.Brotli:
467 payload
= await
brotliDecompressAsync(decrypted
);
469 case this.Flags
.Flate:
470 payload
= await
inflateRawAsync(decrypted
);
473 timingsMs
.end
= timingsMs
.postCompress
= performance
.now();
474 stats
.serializedBytes
= payload
.byteLength
;
476 stats
.compressedBytes
= decrypted
.byteLength
;
479 if (!payloadIsBuffer
) {
480 payload
= JSON
.parse(payload
.toString('utf8'));
483 stats
.flags
= this._prettyFlags(flags
);
484 this.emit('statistics', { ...stats
, ...MysteryBox
._timingsLog(timingsMs
), ...packageInfo
});
491 * Pretty-print flag values
492 * @param {Number} flags
495 _prettyFlags(flags
) {
496 const flagNames
= Object
.entries(this.Flags
).reduce((acc
, cur
) => {
497 const [flagName
, flagValue
] = cur
;
498 if ((flags
& flagValue
) === flagValue
) {
503 return `0x${flags.toString(16).padStart(2, '0')} [${flagNames.join(',')}]`;
508 * Everyone loves numbers.
509 * @param {Object} timingsMs
512 static _timingsLog({ start
, preCompress
, postCompress
, preCrypt
, postCrypt
, end
}) {
514 totalMs: end
- start
,
515 compressMs: postCompress
- preCompress
,
516 cryptMs: postCrypt
- preCrypt
,
522 module
.exports
= MysteryBox
;