crypto: deduplicate and canonicalize CryptoKey usages · nodejs/node@8752b60
@@ -3,6 +3,7 @@
33const {
44 ArrayBufferIsView,
55 ArrayBufferPrototypeGetByteLength,
6+ ArrayFrom,
67 ArrayPrototypeIncludes,
78 ArrayPrototypePush,
89 BigInt,
@@ -16,6 +17,7 @@ const {
1617 ObjectKeys,
1718 ObjectPrototypeHasOwnProperty,
1819 PromiseWithResolvers,
20+ SafeSet,
1921 StringPrototypeToUpperCase,
2022 Symbol,
2123 TypedArrayPrototypeGetBuffer,
@@ -706,14 +708,40 @@ function getStringOption(options, key) {
706708}
707709708710function getUsagesUnion(usageSet, ...usages) {
709-const newset = [];
711+const newset = new SafeSet();
710712for (let n = 0; n < usages.length; n++) {
711713if (usageSet.has(usages[n]))
712-ArrayPrototypePush(newset, usages[n]);
714+newset.add(usages[n]);
713715}
714716return newset;
715717}
716718719+const kCanonicalUsageOrder = new SafeSet([
720+'encrypt', 'decrypt',
721+'sign', 'verify',
722+'deriveKey', 'deriveBits',
723+'wrapKey', 'unwrapKey',
724+'encapsulateKey', 'encapsulateBits',
725+'decapsulateKey', 'decapsulateBits',
726+]);
727+728+/**
729+ * Returns the usages from `usageSet` as an array in the canonical order
730+ * defined by {@link kCanonicalUsageOrder}.
731+ * @param {SafeSet<string>} usageSet
732+ * @returns {string[]}
733+ */
734+function getSortedUsages(usageSet) {
735+if (usageSet.size <= 1) {
736+return ArrayFrom(usageSet);
737+}
738+const result = [];
739+for (const usage of kCanonicalUsageOrder) {
740+if (usageSet.has(usage)) ArrayPrototypePush(result, usage);
741+}
742+return result;
743+}
744+717745function getBlockSize(name) {
718746switch (name) {
719747case 'SHA-1':
@@ -830,6 +858,7 @@ module.exports = {
830858 getDigestSizeInBytes,
831859 getStringOption,
832860 getUsagesUnion,
861+ getSortedUsages,
833862 secureHeapUsed,
834863 getCachedHashId,
835864 getHashCache,