3 const crypto
= require('crypto');
4 const zlib
= require('zlib');
5 const { promisify
} = require('util');
6 const { base64ToBase64URL
, base64URLToBase64
} = require('@squeep/base64url');
7 const common
= require('./common');
8 const allVersions
= require('./version-parameters');
9 const { performance
} = require('perf_hooks');
11 const _fileScope
= common
.fileScope(__filename
);
13 const brotliCompressAsync
= promisify(zlib
.brotliCompress
);
14 const brotliDecompressAsync
= promisify(zlib
.brotliDecompress
);
15 const deflateRawAsync
= promisify(zlib
.deflateRaw
);
16 const inflateRawAsync
= promisify(zlib
.inflateRaw
);
17 const scryptAsync
= promisify(crypto
.scrypt
);
20 * Only you will know what's inside your...
22 * |\/ | | | __| __| _ \ __| | __ \ _ \ \ /
23 * | | | |\__ \ | __/ | | | | | ( |` <
24 * _| _|\__, |____/\__|\___|_| \__, |____/ \___/ _/\_\
27 * Our very own way of converting a buffer or serializable object
28 * to and from an opaque and web-safe representation, which we can
29 * let anyone see without disclosing the contents, nor allowing it
30 * to be modified without detection.
32 * The result is a Base64URL-encoded byte-array consisting of:
33 * - version, indicating format and encryption algorithm
34 * - flags, indicating state of the contents
35 * - iv/nonce, randomness for the algorithm
36 * - salt, applied to a secret to derive a key
37 * - tag, additional room for encryption to validate the previous fields
38 * - payload, encrypted version of possibly compressed and serialized object
43 const availableFlags
= {
44 Brotli: (1<<0), // Slightly better compression, but slow
45 Flate: (1<<1), // Slightly worse compression, but much faster especially with larger payloads. Prefer this.
46 FutureCompression: (1<<0)|(1<<1), // Something else, like zstd maybe.
54 BufferPayload: (1<<7), // Payload is a buffer, not an object
56 const compressionFlagsMask
= (availableFlags
.Flate
| availableFlags
.Brotli
);
57 const compressionFlagsShift
= 0;
58 const payloadFlagsMask
= (availableFlags
.BufferPayload
);
59 const payloadFlagsShift
= 7;
64 * @param {Console} logger
65 * @param {Object} options
66 * @param {String} options.encryptionSecret
67 * @param {Number=} options.defaultFlags
69 constructor(logger
, options
= {}) {
71 this.options
= options
;
73 this.secret
= options
.encryptionSecret
;
75 throw new Error('missing encryption secret');
77 // TODO: support secret rolling
79 // Filter any unavailable algorithms
80 const availableCiphers
= crypto
.getCiphers();
81 this.versionParameters
= Object
.entries(allVersions
).reduce((acc
, [v
, p
]) => {
82 if (availableCiphers
.includes(p
.algorithm
)) {
83 acc
[v
] = p
; // eslint-disable-line security/detect-object-injection
89 this.bestVersion
= Number(Object
.keys(this.versionParameters
).sort().pop());
90 if (Number
.isNaN(this.bestVersion
)) {
91 throw new Error('no supported versions available');
94 this.Flags
= availableFlags
;
95 this.defaultFlags
= 'defaultFlags' in options
? options
.defaultFlags : availableFlags
.Flate
;
96 if (this.defaultFlags
< 0 || this.defaultFlags
> 255) {
97 throw new RangeError('Invalid default flag value');
103 * Parse the bits out of the flags.
105 static _decodeFlags(flags
) {
107 compression: (flags
& compressionFlagsMask
) >> compressionFlagsShift
,
108 payloadIsBuffer: Boolean((flags
& payloadFlagsMask
) >> payloadFlagsShift
),
114 * Put contents into a mysterious box.
115 * @param {Object|Buffer} contents
118 async
pack(contents
, version
= this.bestVersion
, flags
= this.defaultFlags
) {
119 const _scope
= _fileScope('pack');
121 start: performance
.now(),
129 if (!(version
in this.versionParameters
)) {
130 throw new RangeError(`MysteryBox format version ${version} not supported`);
132 // eslint-disable-next-line security/detect-object-injection
133 const v
= this.versionParameters
[version
];
135 const { compression
} = MysteryBox
._decodeFlags(flags
);
137 if (Buffer
.isBuffer(contents
)) {
138 flags
|= this.Flags
.BufferPayload
;
140 contents
= JSON
.stringify(contents
);
143 const versionBuffer
= Buffer
.alloc(v
.versionBytes
);
144 versionBuffer
.writeUInt8(v
.version
, 0);
146 const [iv
, salt
] = await Promise
.all([
149 ].map((b
) => common
.randomBytesAsync(b
)));
151 timingsMs
.preCompress
= performance
.now();
152 let compressedContents
;
153 switch (compression
) {
154 case 0: // No compression requested
155 compressedContents
= contents
;
157 case this.Flags
.Brotli:
158 compressedContents
= await
brotliCompressAsync(contents
);
160 case this.Flags
.Flate:
161 compressedContents
= await
deflateRawAsync(contents
);
164 timingsMs
.postCompress
= timingsMs
.preCrypt
= performance
.now();
167 if (compressedContents
.length
>= contents
.length
) {
168 flags
= flags
& ~compressionFlagsMask
;
171 payload
= compressedContents
;
173 const flagsBuffer
= Buffer
.alloc(v
.flagsBytes
);
174 flagsBuffer
.writeUInt8(flags
, 0);
176 // Authenticate all this data
177 const aadBuffer
= Buffer
.concat([versionBuffer
, flagsBuffer
, iv
, salt
]);
179 const key
= await
scryptAsync(this.secret
, salt
, v
.keyBytes
);
180 const cipher
= crypto
.createCipheriv(v
.algorithm
, key
, iv
, v
.algOptions
);
181 cipher
.setAAD(aadBuffer
);
182 const encrypted
= cipher
.update(payload
);
183 const final
= cipher
.final();
184 const tag
= cipher
.getAuthTag();
186 const merged
= Buffer
.concat([versionBuffer
, flagsBuffer
, iv
, salt
, tag
, encrypted
, final
]).toString('base64');
187 const result
= base64ToBase64URL(merged
);
188 timingsMs
.end
= timingsMs
.postCrypt
= performance
.now();
190 this.logger
.debug(_scope
, 'statistics', { version
, flags: this._prettyFlags(flags
), serialized: contents
.length
, compressed: payload
.length
, encoded: result
.length
, ...MysteryBox
._timingsLog(timingsMs
) });
197 * Take contents out of a mysterious box.
198 * @param {String} box - Base64URL encoded payload
202 const _scope
= _fileScope('unpack');
204 start: performance
.now(),
213 throw new RangeError('nothing to unpack');
216 const raw
= Buffer
.from(base64URLToBase64(box
), 'base64');
219 const version
= raw
.slice(offset
, 1).readUInt8(0);
220 if (!(version
in this.versionParameters
)) {
221 throw new RangeError('unsupported version');
223 // eslint-disable-next-line security/detect-object-injection
224 const v
= this.versionParameters
[version
];
225 offset
+= v
.versionBytes
;
227 const minBytes
= v
.versionBytes
+ v
.flagsBytes
+ v
.ivBytes
+ v
.saltBytes
+ v
.tagBytes
;
228 if (raw
.length
< minBytes
) {
229 throw new RangeError('not enough to unpack');
232 const flags
= raw
.slice(offset
, offset
+ v
.flagsBytes
).readUInt8(0);
233 offset
+= v
.flagsBytes
;
235 const { compression
, payloadIsBuffer
} = MysteryBox
._decodeFlags(flags
);
237 const iv
= raw
.slice(offset
, offset
+ v
.ivBytes
);
240 const salt
= raw
.slice(offset
, offset
+ v
.saltBytes
);
241 offset
+= v
.saltBytes
;
243 const aad
= raw
.slice(0, offset
); // Everything up to here
245 const tag
= raw
.slice(offset
, offset
+ v
.tagBytes
);
246 offset
+= v
.tagBytes
;
248 const encrypted
= raw
.slice(offset
);
250 timingsMs
.preCrypt
= performance
.now();
251 const key
= await
scryptAsync(this.secret
, salt
, v
.keyBytes
);
252 const decipher
= crypto
.createDecipheriv(v
.algorithm
, key
, iv
, v
.algOptions
);
253 decipher
.setAAD(aad
);
254 decipher
.setAuthTag(tag
);
256 const decrypted
= Buffer
.concat([decipher
.update(encrypted
), decipher
.final()]);
259 timingsMs
.preCompress
= timingsMs
.postCrypt
= performance
.now();
260 switch (compression
) {
261 case 0: // No compression
264 case this.Flags
.Brotli:
265 payload
= await
brotliDecompressAsync(decrypted
);
267 case this.Flags
.Flate:
268 payload
= await
inflateRawAsync(decrypted
);
271 timingsMs
.end
= timingsMs
.postCompress
= performance
.now();
273 if (!payloadIsBuffer
) {
274 payload
= JSON
.parse(payload
.toString('utf8'));
277 this.logger
.debug(_scope
, 'statistics', { version
, flags: this._prettyFlags(flags
), ...MysteryBox
._timingsLog(timingsMs
) });
284 * Pretty-print flag values
285 * @param {Number} flags
288 _prettyFlags(flags
) {
289 const flagNames
= Object
.entries(this.Flags
).reduce((acc
, cur
) => {
290 const [flagName
, flagValue
] = cur
;
291 if ((flags
& flagValue
) === flagValue
) {
296 return `0x${flags.toString(16).padStart(2, '0')} [${flagNames.join(',')}]`;
301 * Everyone loves numbers.
302 * @param {Object} timingsMs
305 static _timingsLog({ start
, preCompress
, postCompress
, preCrypt
, postCrypt
, end
}) {
307 totalMs: end
- start
,
308 compressMs: postCompress
- preCompress
,
309 cryptMs: postCrypt
- preCrypt
,
315 // Expose for stubbing in tests
316 MysteryBox
._test
= { crypto
};
318 module
.exports
= MysteryBox
;