-
Notifications
You must be signed in to change notification settings - Fork 31.1k
/
Copy pathutil.js
405 lines (354 loc) Β· 9.43 KB
/
util.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
'use strict';
const {
ArrayPrototypeIncludes,
ArrayPrototypePush,
FunctionPrototypeBind,
Promise,
StringPrototypeToLowerCase,
StringPrototypeToUpperCase,
Symbol,
} = primordials;
const {
getCiphers: _getCiphers,
getCurves: _getCurves,
getHashes: _getHashes,
setEngine: _setEngine,
} = internalBinding('crypto');
const {
crypto: {
ENGINE_METHOD_ALL
}
} = internalBinding('constants');
const normalizeHashName = require('internal/crypto/hashnames');
const {
hideStackFrames,
codes: {
ERR_CRYPTO_ENGINE_UNKNOWN,
ERR_INVALID_ARG_TYPE,
ERR_INVALID_ARG_VALUE,
ERR_OUT_OF_RANGE,
}
} = require('internal/errors');
const {
validateArray,
validateString
} = require('internal/validators');
const { Buffer } = require('buffer');
const {
cachedResult,
filterDuplicateStrings,
} = require('internal/util');
const {
isArrayBufferView,
isAnyArrayBuffer,
} = require('internal/util/types');
const kHandle = Symbol('kHandle');
const kKeyObject = Symbol('kKeyObject');
const lazyRequireCache = {};
function lazyRequire(name) {
let ret = lazyRequireCache[name];
if (ret === undefined)
ret = lazyRequireCache[name] = require(name);
return ret;
}
let DOMException;
const lazyDOMException = hideStackFrames((message, name) => {
if (DOMException === undefined)
DOMException = internalBinding('messaging').DOMException;
return new DOMException(message, name);
});
var defaultEncoding = 'buffer';
function setDefaultEncoding(val) {
defaultEncoding = val;
}
function getDefaultEncoding() {
return defaultEncoding;
}
// This is here because many functions accepted binary strings without
// any explicit encoding in older versions of node, and we don't want
// to break them unnecessarily.
function toBuf(val, encoding) {
if (typeof val === 'string') {
if (encoding === 'buffer')
encoding = 'utf8';
return Buffer.from(val, encoding);
}
return val;
}
const getCiphers = cachedResult(() => filterDuplicateStrings(_getCiphers()));
const getHashes = cachedResult(() => filterDuplicateStrings(_getHashes()));
const getCurves = cachedResult(() => filterDuplicateStrings(_getCurves()));
function setEngine(id, flags) {
validateString(id, 'id');
if (flags && typeof flags !== 'number')
throw new ERR_INVALID_ARG_TYPE('flags', 'number', flags);
flags = flags >>> 0;
// Use provided engine for everything by default
if (flags === 0)
flags = ENGINE_METHOD_ALL;
if (!_setEngine(id, flags))
throw new ERR_CRYPTO_ENGINE_UNKNOWN(id);
}
const getArrayBufferOrView = hideStackFrames((buffer, name, encoding) => {
if (isAnyArrayBuffer(buffer))
return buffer;
if (typeof buffer === 'string') {
if (encoding === 'buffer')
encoding = 'utf8';
return Buffer.from(buffer, encoding);
}
if (!isArrayBufferView(buffer)) {
throw new ERR_INVALID_ARG_TYPE(
name,
[
'string',
'ArrayBuffer',
'Buffer',
'TypedArray',
'DataView'
],
buffer
);
}
return buffer;
});
// The maximum buffer size that we'll support in the WebCrypto impl
const kMaxBufferLength = (2 ** 31) - 1;
// The EC named curves that we currently support via the Web Crypto API.
const kNamedCurveAliases = {
'P-256': 'prime256v1',
'P-384': 'secp384r1',
'P-521': 'secp521r1',
};
const kAesKeyLengths = [128, 192, 256];
// These are the only algorithms we currently support
// via the Web Crypto API
const kAlgorithms = [
'rsassa-pkcs1-v1_5',
'rsa-pss',
'rsa-oaep',
'ecdsa',
'ecdh',
'aes-ctr',
'aes-cbc',
'aes-gcm',
'aes-kw',
'hmac',
'sha-1',
'sha-256',
'sha-384',
'sha-512',
'hkdf',
'pbkdf2',
// Following here are Node.js specific extensions. All
// should be prefixed with 'node-'
'node-dsa',
'node-dh',
'node-scrypt'
];
// These are the only export and import formats we currently
// support via the Web Crypto API
const kExportFormats = [
'raw',
'pkcs8',
'spki',
'jwk',
'node.keyObject'];
// These are the only hash algorithms we currently support via
// the Web Crypto API.
const kHashTypes = [
'SHA-1',
'SHA-256',
'SHA-384',
'SHA-512'
];
function validateMaxBufferLength(data, name) {
if (data.byteLength > kMaxBufferLength) {
throw lazyDOMException(
`${name} must be less than ${kMaxBufferLength + 1} bits`,
'OperationError');
}
}
function normalizeAlgorithm(algorithm, label = 'algorithm') {
if (algorithm != null) {
if (typeof algorithm === 'string')
algorithm = { name: algorithm };
if (typeof algorithm === 'object') {
const { name } = algorithm;
let hash;
if (typeof name !== 'string' ||
!ArrayPrototypeIncludes(
kAlgorithms,
StringPrototypeToLowerCase(name))) {
throw lazyDOMException('Unrecognized name.', 'NotSupportedError');
}
if (algorithm.hash !== undefined) {
hash = normalizeAlgorithm(algorithm.hash, 'algorithm.hash');
if (!ArrayPrototypeIncludes(kHashTypes, hash.name))
throw lazyDOMException('Unrecognized name.', 'NotSupportedError');
}
return { ...algorithm, name: StringPrototypeToUpperCase(name), hash };
}
}
throw lazyDOMException('Unrecognized name.', 'NotSupportedError');
}
function hasAnyNotIn(set, ...check) {
for (const s of set)
if (!ArrayPrototypeIncludes(check, s))
return true;
return false;
}
function validateBitLength(length, name, required = false) {
if (length !== undefined || required) {
if (typeof length !== 'number')
throw new ERR_INVALID_ARG_TYPE(name, 'number', length);
if (length < 0)
throw new ERR_OUT_OF_RANGE(name, '> 0');
if (length % 8) {
throw new ERR_INVALID_ARG_VALUE(
name,
length,
'must be a multiple of 8');
}
}
}
function validateByteLength(buf, name, target) {
if (buf.byteLength !== target) {
throw lazyDOMException(
`${name} must contain exactly ${target} bytes`,
'OperationError');
}
}
const validateByteSource = hideStackFrames((val, name) => {
val = toBuf(val);
if (isAnyArrayBuffer(val) || isArrayBufferView(val))
return;
throw new ERR_INVALID_ARG_TYPE(
name,
[
'string',
'ArrayBuffer',
'TypedArray',
'DataView',
'Buffer'
],
val);
});
function onDone(resolve, reject, err, result) {
if (err) return reject(err);
resolve(result);
}
function jobPromise(job) {
return new Promise((resolve, reject) => {
job.ondone = FunctionPrototypeBind(onDone, job, resolve, reject);
job.run();
});
}
// In WebCrypto, the publicExponent option in RSA is represented as a
// WebIDL "BigInteger"... that is, a Uint8Array that allows an arbitrary
// number of leading zero bits. Our conventional APIs for reading
// an unsigned int from a Buffer are not adequate. The implementation
// here is adapted from the chromium implementation here:
// https://github.com/chromium/chromium/blob/master/third_party/blink/public/platform/web_crypto_algorithm_params.h, but ported to JavaScript
// Returns undefined if the conversion was unsuccessful.
function bigIntArrayToUnsignedInt(input) {
let result = 0;
for (let n = 0; n < input.length; ++n) {
const n_reversed = input.length - n - 1;
if (n_reversed >= 4 && input[n])
return; // Too large
result |= input[n] << 8 * n_reversed;
}
return result;
}
function getStringOption(options, key) {
let value;
if (options && (value = options[key]) != null)
validateString(value, `options.${key}`);
return value;
}
function getUsagesUnion(usageSet, ...usages) {
const newset = [];
for (let n = 0; n < usages.length; n++) {
if (usageSet.has(usages[n]))
ArrayPrototypePush(newset, usages[n]);
}
return newset;
}
function getHashLength(name) {
switch (name) {
case 'SHA-1': return 160;
case 'SHA-256': return 256;
case 'SHA-384': return 384;
case 'SHA-512': return 512;
}
}
const kKeyOps = {
sign: 1,
verify: 2,
encrypt: 3,
decrypt: 4,
wrapKey: 5,
unwrapKey: 6,
deriveKey: 7,
deriveBits: 8,
};
function validateKeyOps(keyOps, usagesSet) {
if (keyOps === undefined) return;
validateArray(keyOps, 'keyData.key_ops');
let flags = 0;
for (let n = 0; n < keyOps.length; n++) {
const op = keyOps[n];
const op_flag = kKeyOps[op];
// Skipping unknown key ops
if (op_flag === undefined)
continue;
// Have we seen it already? if so, error
if (flags & (1 << op_flag))
throw lazyDOMException('Duplicate key operation', 'DataError');
flags |= (1 << op_flag);
// TODO(@jasnell): RFC7517 section 4.3 strong recommends validating
// key usage combinations. Specifically, it says that unrelated key
// ops SHOULD NOT be used together. We're not yet validating that here.
}
if (usagesSet !== undefined) {
for (const use of usagesSet) {
if (!ArrayPrototypeIncludes(keyOps, use)) {
throw lazyDOMException(
'Key operations and usage mismatch',
'DataError');
}
}
}
}
module.exports = {
getArrayBufferOrView,
getCiphers,
getCurves,
getDefaultEncoding,
getHashes,
kHandle,
kKeyObject,
setDefaultEncoding,
setEngine,
toBuf,
kHashTypes,
kNamedCurveAliases,
kAesKeyLengths,
kExportFormats,
normalizeAlgorithm,
normalizeHashName,
hasAnyNotIn,
lazyDOMException,
validateBitLength,
validateByteLength,
validateByteSource,
validateKeyOps,
jobPromise,
lazyRequire,
validateMaxBufferLength,
bigIntArrayToUnsignedInt,
getStringOption,
getUsagesUnion,
getHashLength,
};