-
-
Notifications
You must be signed in to change notification settings - Fork 35.4k
Expand file tree
/
Copy pathutil.js
More file actions
854 lines (783 loc) Β· 22.6 KB
/
util.js
File metadata and controls
854 lines (783 loc) Β· 22.6 KB
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
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
'use strict';
const {
ArrayBufferIsView,
ArrayBufferPrototypeGetByteLength,
ArrayPrototypeIncludes,
ArrayPrototypePush,
BigInt,
DataViewPrototypeGetBuffer,
DataViewPrototypeGetByteLength,
DataViewPrototypeGetByteOffset,
FunctionPrototypeBind,
Number,
ObjectDefineProperty,
ObjectEntries,
ObjectKeys,
ObjectPrototypeHasOwnProperty,
PromiseWithResolvers,
SafeMap,
StringPrototypeToUpperCase,
Symbol,
TypedArrayPrototypeGetBuffer,
TypedArrayPrototypeGetByteLength,
TypedArrayPrototypeGetByteOffset,
TypedArrayPrototypeSlice,
Uint8Array,
} = primordials;
const {
getCiphers: _getCiphers,
getCurves: _getCurves,
getHashes: _getHashes,
setEngine: _setEngine,
secureHeapUsed: _secureHeapUsed,
getCachedAliases,
getOpenSSLSecLevelCrypto: getOpenSSLSecLevel,
EVP_PKEY_ML_DSA_44,
EVP_PKEY_ML_DSA_65,
EVP_PKEY_ML_DSA_87,
EVP_PKEY_ML_KEM_512,
EVP_PKEY_ML_KEM_768,
EVP_PKEY_ML_KEM_1024,
kKeyVariantAES_OCB_128: hasAesOcbMode,
Argon2Job,
KmacJob,
} = internalBinding('crypto');
const { getOptionValue } = require('internal/options');
const {
crypto: {
ENGINE_METHOD_ALL,
},
} = internalBinding('constants');
const normalizeHashName = require('internal/crypto/hashnames');
const {
codes: {
ERR_CRYPTO_CUSTOM_ENGINE_NOT_SUPPORTED,
ERR_CRYPTO_ENGINE_UNKNOWN,
ERR_INVALID_ARG_TYPE,
},
hideStackFrames,
} = require('internal/errors');
const {
validateArray,
validateNumber,
validateString,
} = require('internal/validators');
const { Buffer } = require('buffer');
const {
cachedResult,
emitExperimentalWarning,
filterDuplicateStrings,
lazyDOMException,
} = require('internal/util');
const {
namespace: {
isBuildingSnapshot,
addSerializeCallback,
},
} = require('internal/v8/startup_snapshot');
const {
isDataView,
isArrayBufferView,
isAnyArrayBuffer,
} = require('internal/util/types');
const kHandle = Symbol('kHandle');
const kKeyObject = Symbol('kKeyObject');
// 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;
}
let _hashCache;
function getHashCache() {
if (_hashCache === undefined) {
_hashCache = getCachedAliases();
if (isBuildingSnapshot()) {
// For dynamic linking, clear the map.
addSerializeCallback(() => { _hashCache = undefined; });
}
}
return _hashCache;
}
function getCachedHashId(algorithm) {
const result = getHashCache()[algorithm];
return result === undefined ? -1 : result;
}
const getCiphers = cachedResult(() => filterDuplicateStrings(_getCiphers()));
const getHashes = cachedResult(() => filterDuplicateStrings(_getHashes()));
const getCurves = cachedResult(() => filterDuplicateStrings(_getCurves()));
function setEngine(id, flags) {
validateString(id, 'id');
if (flags)
validateNumber(flags, 'flags');
flags = flags >>> 0;
// Use provided engine for everything by default
if (flags === 0)
flags = ENGINE_METHOD_ALL;
if (typeof _setEngine !== 'function')
throw new ERR_CRYPTO_CUSTOM_ENGINE_NOT_SUPPORTED();
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.HideStackFramesError(
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',
};
// Algorithm definitions organized by algorithm name
const kAlgorithmDefinitions = {
'AES-CBC': {
'generateKey': 'AesKeyGenParams',
'exportKey': null,
'importKey': null,
'encrypt': 'AesCbcParams',
'decrypt': 'AesCbcParams',
'get key length': 'AesDerivedKeyParams',
},
'AES-CTR': {
'generateKey': 'AesKeyGenParams',
'exportKey': null,
'importKey': null,
'encrypt': 'AesCtrParams',
'decrypt': 'AesCtrParams',
'get key length': 'AesDerivedKeyParams',
},
'AES-GCM': {
'generateKey': 'AesKeyGenParams',
'exportKey': null,
'importKey': null,
'encrypt': 'AeadParams',
'decrypt': 'AeadParams',
'get key length': 'AesDerivedKeyParams',
},
'AES-KW': {
'generateKey': 'AesKeyGenParams',
'exportKey': null,
'importKey': null,
'get key length': 'AesDerivedKeyParams',
'wrapKey': null,
'unwrapKey': null,
},
'AES-OCB': {
'generateKey': 'AesKeyGenParams',
'exportKey': null,
'importKey': null,
'encrypt': 'AeadParams',
'decrypt': 'AeadParams',
'get key length': 'AesDerivedKeyParams',
},
'Argon2d': {
'deriveBits': 'Argon2Params',
'get key length': null,
'importKey': null,
},
'Argon2i': {
'deriveBits': 'Argon2Params',
'get key length': null,
'importKey': null,
},
'Argon2id': {
'deriveBits': 'Argon2Params',
'get key length': null,
'importKey': null,
},
'ChaCha20-Poly1305': {
'generateKey': null,
'exportKey': null,
'importKey': null,
'encrypt': 'AeadParams',
'decrypt': 'AeadParams',
'get key length': null,
},
'cSHAKE128': { 'digest': 'CShakeParams' },
'cSHAKE256': { 'digest': 'CShakeParams' },
'KT128': { 'digest': 'KangarooTwelveParams' },
'KT256': { 'digest': 'KangarooTwelveParams' },
'TurboSHAKE128': { 'digest': 'TurboShakeParams' },
'TurboSHAKE256': { 'digest': 'TurboShakeParams' },
'ECDH': {
'generateKey': 'EcKeyGenParams',
'exportKey': null,
'importKey': 'EcKeyImportParams',
'deriveBits': 'EcdhKeyDeriveParams',
},
'ECDSA': {
'generateKey': 'EcKeyGenParams',
'exportKey': null,
'importKey': 'EcKeyImportParams',
'sign': 'EcdsaParams',
'verify': 'EcdsaParams',
},
'Ed25519': {
'generateKey': null,
'exportKey': null,
'importKey': null,
'sign': null,
'verify': null,
},
'Ed448': {
'generateKey': null,
'exportKey': null,
'importKey': null,
'sign': 'ContextParams',
'verify': 'ContextParams',
},
'HKDF': {
'importKey': null,
'deriveBits': 'HkdfParams',
'get key length': null,
},
'HMAC': {
'generateKey': 'HmacKeyGenParams',
'exportKey': null,
'importKey': 'HmacImportParams',
'sign': null,
'verify': null,
'get key length': 'HmacImportParams',
},
'KMAC128': {
'generateKey': 'KmacKeyGenParams',
'exportKey': null,
'importKey': 'KmacImportParams',
'sign': 'KmacParams',
'verify': 'KmacParams',
'get key length': 'KmacImportParams',
},
'KMAC256': {
'generateKey': 'KmacKeyGenParams',
'exportKey': null,
'importKey': 'KmacImportParams',
'sign': 'KmacParams',
'verify': 'KmacParams',
'get key length': 'KmacImportParams',
},
'ML-DSA-44': {
'generateKey': null,
'exportKey': null,
'importKey': null,
'sign': 'ContextParams',
'verify': 'ContextParams',
},
'ML-DSA-65': {
'generateKey': null,
'exportKey': null,
'importKey': null,
'sign': 'ContextParams',
'verify': 'ContextParams',
},
'ML-DSA-87': {
'generateKey': null,
'exportKey': null,
'importKey': null,
'sign': 'ContextParams',
'verify': 'ContextParams',
},
'ML-KEM-512': {
'generateKey': null,
'exportKey': null,
'importKey': null,
'encapsulate': null,
'decapsulate': null,
},
'ML-KEM-768': {
'generateKey': null,
'exportKey': null,
'importKey': null,
'encapsulate': null,
'decapsulate': null,
},
'ML-KEM-1024': {
'generateKey': null,
'exportKey': null,
'importKey': null,
'encapsulate': null,
'decapsulate': null,
},
'PBKDF2': {
'importKey': null,
'deriveBits': 'Pbkdf2Params',
'get key length': null,
},
'RSA-OAEP': {
'generateKey': 'RsaHashedKeyGenParams',
'exportKey': null,
'importKey': 'RsaHashedImportParams',
'encrypt': 'RsaOaepParams',
'decrypt': 'RsaOaepParams',
},
'RSA-PSS': {
'generateKey': 'RsaHashedKeyGenParams',
'exportKey': null,
'importKey': 'RsaHashedImportParams',
'sign': 'RsaPssParams',
'verify': 'RsaPssParams',
},
'RSASSA-PKCS1-v1_5': {
'generateKey': 'RsaHashedKeyGenParams',
'exportKey': null,
'importKey': 'RsaHashedImportParams',
'sign': null,
'verify': null,
},
'SHA-1': { 'digest': null },
'SHA-256': { 'digest': null },
'SHA-384': { 'digest': null },
'SHA-512': { 'digest': null },
'SHA3-256': { 'digest': null },
'SHA3-384': { 'digest': null },
'SHA3-512': { 'digest': null },
'X25519': {
'generateKey': null,
'exportKey': null,
'importKey': null,
'deriveBits': 'EcdhKeyDeriveParams',
},
'X448': {
'generateKey': null,
'exportKey': null,
'importKey': null,
'deriveBits': 'EcdhKeyDeriveParams',
},
};
// Conditionally supported algorithms
const conditionalAlgorithms = {
'AES-KW': !process.features.openssl_is_boringssl,
'AES-OCB': !!hasAesOcbMode,
'Argon2d': !!Argon2Job,
'Argon2i': !!Argon2Job,
'Argon2id': !!Argon2Job,
'ChaCha20-Poly1305': !process.features.openssl_is_boringssl ||
ArrayPrototypeIncludes(getCiphers(), 'chacha20-poly1305'),
'cSHAKE128': !process.features.openssl_is_boringssl ||
ArrayPrototypeIncludes(getHashes(), 'shake128'),
'cSHAKE256': !process.features.openssl_is_boringssl ||
ArrayPrototypeIncludes(getHashes(), 'shake256'),
'Ed448': !process.features.openssl_is_boringssl,
'KMAC128': !!KmacJob,
'KMAC256': !!KmacJob,
'ML-DSA-44': !!EVP_PKEY_ML_DSA_44,
'ML-DSA-65': !!EVP_PKEY_ML_DSA_65,
'ML-DSA-87': !!EVP_PKEY_ML_DSA_87,
'ML-KEM-512': !!EVP_PKEY_ML_KEM_512,
'ML-KEM-768': !!EVP_PKEY_ML_KEM_768,
'ML-KEM-1024': !!EVP_PKEY_ML_KEM_1024,
'SHA3-256': !process.features.openssl_is_boringssl ||
ArrayPrototypeIncludes(getHashes(), 'sha3-256'),
'SHA3-384': !process.features.openssl_is_boringssl ||
ArrayPrototypeIncludes(getHashes(), 'sha3-384'),
'SHA3-512': !process.features.openssl_is_boringssl ||
ArrayPrototypeIncludes(getHashes(), 'sha3-512'),
'X448': !process.features.openssl_is_boringssl,
};
// Experimental algorithms
const experimentalAlgorithms = [
'AES-OCB',
'Argon2d',
'Argon2i',
'Argon2id',
'ChaCha20-Poly1305',
'cSHAKE128',
'cSHAKE256',
'Ed448',
'KMAC128',
'KMAC256',
'ML-DSA-44',
'ML-DSA-65',
'ML-DSA-87',
'ML-KEM-512',
'ML-KEM-768',
'ML-KEM-1024',
'SHA3-256',
'SHA3-384',
'SHA3-512',
'TurboSHAKE128',
'TurboSHAKE256',
'KT128',
'KT256',
'X448',
];
// Transform the algorithm definitions into the operation-keyed structure
// Also builds a parallel Map<UPPERCASED_NAME, canonicalName> per operation
// for O(1) case-insensitive algorithm name lookup in normalizeAlgorithm.
function createSupportedAlgorithms(algorithmDefs) {
const result = {};
const nameMap = {};
for (const { 0: algorithmName, 1: operations } of ObjectEntries(algorithmDefs)) {
// Skip algorithms that are conditionally not supported
if (ObjectPrototypeHasOwnProperty(conditionalAlgorithms, algorithmName) &&
!conditionalAlgorithms[algorithmName]) {
continue;
}
for (const { 0: operation, 1: dict } of ObjectEntries(operations)) {
result[operation] ||= {};
nameMap[operation] ||= new SafeMap();
nameMap[operation].set(StringPrototypeToUpperCase(algorithmName), algorithmName);
// Add experimental warnings for experimental algorithms
if (ArrayPrototypeIncludes(experimentalAlgorithms, algorithmName)) {
ObjectDefineProperty(result[operation], algorithmName, {
get() {
emitExperimentalWarning(`The ${algorithmName} Web Crypto API algorithm`);
return dict;
},
__proto__: null,
enumerable: true,
});
} else {
result[operation][algorithmName] = dict;
}
}
}
return { algorithms: result, nameMap };
}
const { algorithms: kSupportedAlgorithms, nameMap: kAlgorithmNameMap } =
createSupportedAlgorithms(kAlgorithmDefinitions);
const simpleAlgorithmDictionaries = {
__proto__: null,
AesCbcParams: { iv: 'BufferSource' },
AesCtrParams: { counter: 'BufferSource' },
AeadParams: { iv: 'BufferSource', additionalData: 'BufferSource' },
// publicExponent is not strictly a BufferSource but it is a Uint8Array that we normalize
// this way
RsaHashedKeyGenParams: { hash: 'HashAlgorithmIdentifier', publicExponent: 'BufferSource' },
EcKeyGenParams: {},
HmacKeyGenParams: { hash: 'HashAlgorithmIdentifier' },
RsaPssParams: {},
EcdsaParams: { hash: 'HashAlgorithmIdentifier' },
HmacImportParams: { hash: 'HashAlgorithmIdentifier' },
HkdfParams: {
hash: 'HashAlgorithmIdentifier',
salt: 'BufferSource',
info: 'BufferSource',
},
ContextParams: { context: 'BufferSource' },
Pbkdf2Params: { hash: 'HashAlgorithmIdentifier', salt: 'BufferSource' },
RsaOaepParams: { label: 'BufferSource' },
RsaHashedImportParams: { hash: 'HashAlgorithmIdentifier' },
EcKeyImportParams: {},
CShakeParams: {
functionName: 'BufferSource',
customization: 'BufferSource',
},
Argon2Params: {
associatedData: 'BufferSource',
nonce: 'BufferSource',
secretValue: 'BufferSource',
},
KmacParams: {
customization: 'BufferSource',
},
KangarooTwelveParams: {
customization: 'BufferSource',
},
TurboShakeParams: {},
};
// Pre-compute ObjectKeys() for each dictionary entry at module init
// to avoid allocating a new keys array on every normalizeAlgorithm call.
for (const { 0: name, 1: types } of ObjectEntries(simpleAlgorithmDictionaries)) {
simpleAlgorithmDictionaries[name] = { keys: ObjectKeys(types), types };
}
function validateMaxBufferLength(data, name) {
if (data.byteLength > kMaxBufferLength) {
throw lazyDOMException(
`${name} must be less than ${kMaxBufferLength + 1} bits`,
'OperationError');
}
}
let webidl;
const kNormalizeAlgorithmOpts = {
prefix: 'Failed to normalize algorithm',
context: 'passed algorithm',
};
// https://w3c.github.io/webcrypto/#algorithm-normalization-normalize-an-algorithm
// adapted for Node.js from Deno's implementation
// https://github.com/denoland/deno/blob/v1.29.1/ext/crypto/00_crypto.js#L195
function normalizeAlgorithm(algorithm, op) {
if (typeof algorithm === 'string')
return normalizeAlgorithm({ name: algorithm }, op);
webidl ??= require('internal/crypto/webidl');
// 1.
const registeredAlgorithms = kSupportedAlgorithms[op];
// 2. 3.
const initialAlg = webidl.converters.Algorithm(algorithm,
kNormalizeAlgorithmOpts);
// 4.
let algName = initialAlg.name;
// 5. Case-insensitive lookup via pre-built Map (O(1) instead of O(n)).
const canonicalName = kAlgorithmNameMap[op]?.get(
StringPrototypeToUpperCase(algName));
if (canonicalName === undefined)
throw lazyDOMException('Unrecognized algorithm name', 'NotSupportedError');
algName = canonicalName;
const desiredType = registeredAlgorithms[algName];
// Fast path everything below if the registered dictionary is null
if (desiredType === null)
return { name: algName };
// 6.
const normalizedAlgorithm = webidl.converters[desiredType](
{ __proto__: algorithm, name: algName },
kNormalizeAlgorithmOpts,
);
// 7.
normalizedAlgorithm.name = algName;
// 9. 10. Pre-computed keys and types from simpleAlgorithmDictionaries.
const dictMeta = simpleAlgorithmDictionaries[desiredType];
if (dictMeta) {
const { keys: dictKeys, types: dictTypes } = dictMeta;
for (let i = 0; i < dictKeys.length; i++) {
const member = dictKeys[i];
const idlType = dictTypes[member];
const idlValue = normalizedAlgorithm[member];
// 3.
if (idlType === 'BufferSource' && idlValue) {
const isView = ArrayBufferIsView(idlValue);
normalizedAlgorithm[member] = TypedArrayPrototypeSlice(
new Uint8Array(
isView ? getDataViewOrTypedArrayBuffer(idlValue) : idlValue,
isView ? getDataViewOrTypedArrayByteOffset(idlValue) : 0,
isView ? getDataViewOrTypedArrayByteLength(idlValue) : ArrayBufferPrototypeGetByteLength(idlValue),
),
);
} else if (idlType === 'HashAlgorithmIdentifier') {
normalizedAlgorithm[member] = normalizeAlgorithm(idlValue, 'digest');
} else if (idlType === 'AlgorithmIdentifier') {
// This extension point is not used by any supported algorithm (yet?)
throw lazyDOMException('Not implemented.', 'NotSupportedError');
}
}
}
return normalizedAlgorithm;
}
function getDataViewOrTypedArrayBuffer(V) {
return isDataView(V) ?
DataViewPrototypeGetBuffer(V) : TypedArrayPrototypeGetBuffer(V);
}
function getDataViewOrTypedArrayByteOffset(V) {
return isDataView(V) ?
DataViewPrototypeGetByteOffset(V) : TypedArrayPrototypeGetByteOffset(V);
}
function getDataViewOrTypedArrayByteLength(V) {
return isDataView(V) ?
DataViewPrototypeGetByteLength(V) : TypedArrayPrototypeGetByteLength(V);
}
function hasAnyNotIn(set, checks) {
for (const s of set)
if (!ArrayPrototypeIncludes(checks, s))
return true;
return false;
}
const validateByteSource = hideStackFrames((val, name) => {
val = toBuf(val);
if (isAnyArrayBuffer(val) || isArrayBufferView(val))
return val;
throw new ERR_INVALID_ARG_TYPE.HideStackFramesError(
name,
[
'string',
'ArrayBuffer',
'TypedArray',
'DataView',
'Buffer',
],
val);
});
function onDone(resolve, reject, err, result) {
if (err) {
return reject(lazyDOMException(
'The operation failed for an operation-specific reason',
{ name: 'OperationError', cause: err }));
}
resolve(result);
}
function jobPromise(getJob) {
const { promise, resolve, reject } = PromiseWithResolvers();
try {
const job = getJob();
job.ondone = FunctionPrototypeBind(onDone, job, resolve, reject);
job.run();
} catch (err) {
onDone(resolve, reject, err);
}
return promise;
}
// 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/HEAD/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 bigIntArrayToUnsignedBigInt(input) {
let result = 0n;
for (let n = 0; n < input.length; ++n) {
const n_reversed = input.length - n - 1;
result |= BigInt(input[n]) << 8n * BigInt(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 getBlockSize(name) {
switch (name) {
case 'SHA-1':
// Fall through
case 'SHA-256':
return 512;
case 'SHA-384':
// Fall through
case 'SHA-512':
return 1024;
case 'SHA3-256':
// Fall through
case 'SHA3-384':
// Fall through
case 'SHA3-512':
// This interaction is not defined for now.
// https://github.com/WICG/webcrypto-modern-algos/issues/23
throw lazyDOMException('Explicit algorithm length member is required', 'NotSupportedError');
}
}
function getDigestSizeInBytes(name) {
switch (name) {
case 'SHA-1':
return 20;
case 'SHA-256': // Fall through
case 'SHA3-256':
return 32;
case 'SHA-384': // Fall through
case 'SHA3-384':
return 48;
case 'SHA-512': // Fall through
case 'SHA3-512':
return 64;
}
}
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');
}
}
}
}
function secureHeapUsed() {
const val = _secureHeapUsed();
if (val === undefined)
return { total: 0, used: 0, utilization: 0, min: 0 };
const used = Number(_secureHeapUsed());
const total = Number(getOptionValue('--secure-heap'));
const min = Number(getOptionValue('--secure-heap-min'));
const utilization = used / total;
return { total, used, utilization, min };
}
module.exports = {
getArrayBufferOrView,
getCiphers,
getCurves,
getDataViewOrTypedArrayBuffer,
getHashes,
kHandle,
kKeyObject,
setEngine,
toBuf,
kNamedCurveAliases,
normalizeAlgorithm,
normalizeHashName,
hasAnyNotIn,
validateByteSource,
validateKeyOps,
jobPromise,
validateMaxBufferLength,
bigIntArrayToUnsignedBigInt,
bigIntArrayToUnsignedInt,
getBlockSize,
getDigestSizeInBytes,
getStringOption,
getUsagesUnion,
secureHeapUsed,
getCachedHashId,
getHashCache,
getOpenSSLSecLevel,
};