diff --git a/lib/internal/crypto/cfrg.js b/lib/internal/crypto/cfrg.js index 2e4bf9a82755..c797c4335585 100644 --- a/lib/internal/crypto/cfrg.js +++ b/lib/internal/crypto/cfrg.js @@ -10,7 +10,6 @@ const { kCryptoJobWebCrypto, kKeyFormatDER, kKeyFormatRawPublic, - kKeyTypePublic, kSignJobModeSign, kSignJobModeVerify, kWebCryptoKeyFormatPKCS8, @@ -39,7 +38,7 @@ const { const { createKeyUsages, getKeyPairUsages, - importDerKey, + importAsymmetricKeyHandle, importJwkKey, importRawKey, validateJwk, @@ -117,24 +116,11 @@ function cfrgImportKey( const usagesSet = toUsagesSet(usages); switch (format) { case 'KeyObjectHandle': - verifyAcceptableKeyUse( - name, - usagesSet, - keyData.getKeyType() === kKeyTypePublic ? - allowedUsages.public : - allowedUsages.private); - handle = keyData; - break; - case 'spki': { - verifyAcceptableKeyUse(name, usagesSet, allowedUsages.public); - handle = importDerKey(keyData, true); - break; - } - case 'pkcs8': { - verifyAcceptableKeyUse(name, usagesSet, allowedUsages.private); - handle = importDerKey(keyData, false); + case 'spki': + case 'pkcs8': + handle = importAsymmetricKeyHandle( + format, keyData, name, usagesSet, allowedUsages); break; - } case 'jwk': { const isPublic = keyData.d === undefined; verifyAcceptableKeyUse( diff --git a/lib/internal/crypto/ec.js b/lib/internal/crypto/ec.js index bb857be74c84..7aedff11559a 100644 --- a/lib/internal/crypto/ec.js +++ b/lib/internal/crypto/ec.js @@ -50,7 +50,7 @@ const { const { createKeyUsages, getKeyPairUsages, - importDerKey, + importAsymmetricKeyHandle, importJwkKey, importRawKey, validateJwk, @@ -148,24 +148,11 @@ function ecImportKey( const usagesSet = toUsagesSet(usages); switch (format) { case 'KeyObjectHandle': - verifyAcceptableKeyUse( - name, - usagesSet, - keyData.getKeyType() === kKeyTypePublic ? - allowedUsages.public : - allowedUsages.private); - handle = keyData; - break; - case 'spki': { - verifyAcceptableKeyUse(name, usagesSet, allowedUsages.public); - handle = importDerKey(keyData, true); - break; - } - case 'pkcs8': { - verifyAcceptableKeyUse(name, usagesSet, allowedUsages.private); - handle = importDerKey(keyData, false); + case 'spki': + case 'pkcs8': + handle = importAsymmetricKeyHandle( + format, keyData, name, usagesSet, allowedUsages); break; - } case 'jwk': { const isPublic = keyData.d === undefined; verifyAcceptableKeyUse( diff --git a/lib/internal/crypto/ml_dsa.js b/lib/internal/crypto/ml_dsa.js index 581e9beb5d0f..38850d4a21e7 100644 --- a/lib/internal/crypto/ml_dsa.js +++ b/lib/internal/crypto/ml_dsa.js @@ -12,7 +12,6 @@ const { kKeyFormatDER, kKeyFormatRawPublic, kKeyFormatRawSeed, - kKeyTypePublic, kSignJobModeSign, kSignJobModeVerify, kWebCryptoKeyFormatRaw, @@ -42,7 +41,7 @@ const { const { createKeyUsages, getKeyPairUsages, - importDerKey, + importAsymmetricKeyHandle, importJwkKey, importRawKey, validateJwk, @@ -105,6 +104,21 @@ function mlDsaExportKey(key, format) { } } +const kPrivOnlyPkcs8Lengths = { + '__proto__': null, + 'ML-DSA-44': 2588, + 'ML-DSA-65': 4060, + 'ML-DSA-87': 4924, +}; + +function rejectPkcs8WithoutSeed(keyData, name) { + if (getBufferSourceByteLength(keyData) === kPrivOnlyPkcs8Lengths[name]) { + throw lazyDOMException( + 'Importing an ML-DSA PKCS#8 key without a seed is not supported', + 'NotSupportedError'); + } +} + function mlDsaImportKey( format, keyData, @@ -117,37 +131,12 @@ function mlDsaImportKey( const usagesSet = toUsagesSet(usages); switch (format) { case 'KeyObjectHandle': - verifyAcceptableKeyUse( - name, - usagesSet, - keyData.getKeyType() === kKeyTypePublic ? - kUsages.public : - kUsages.private); - handle = keyData; - break; - case 'spki': { - verifyAcceptableKeyUse(name, usagesSet, kUsages.public); - handle = importDerKey(keyData, true); - break; - } - case 'pkcs8': { - verifyAcceptableKeyUse(name, usagesSet, kUsages.private); - - const privOnlyLengths = { - '__proto__': null, - 'ML-DSA-44': 2588, - 'ML-DSA-65': 4060, - 'ML-DSA-87': 4924, - }; - if (getBufferSourceByteLength(keyData) === privOnlyLengths[name]) { - throw lazyDOMException( - 'Importing an ML-DSA PKCS#8 key without a seed is not supported', - 'NotSupportedError'); - } - - handle = importDerKey(keyData, false); + case 'spki': + case 'pkcs8': + handle = importAsymmetricKeyHandle( + format, keyData, name, usagesSet, kUsages, + (data) => rejectPkcs8WithoutSeed(data, name)); break; - } case 'jwk': { const isPublic = keyData.priv === undefined; verifyAcceptableKeyUse( diff --git a/lib/internal/crypto/ml_kem.js b/lib/internal/crypto/ml_kem.js index 025790829f04..e0987b60f51b 100644 --- a/lib/internal/crypto/ml_kem.js +++ b/lib/internal/crypto/ml_kem.js @@ -13,7 +13,6 @@ const { kKeyFormatDER, kKeyFormatRawPublic, kKeyFormatRawSeed, - kKeyTypePublic, kWebCryptoKeyFormatPKCS8, kWebCryptoKeyFormatRaw, kWebCryptoKeyFormatSPKI, @@ -40,7 +39,7 @@ const { const { createKeyUsages, getKeyPairUsages, - importDerKey, + importAsymmetricKeyHandle, importJwkKey, importRawKey, validateJwk, @@ -105,6 +104,21 @@ function mlKemExportKey(key, format) { } } +const kPrivOnlyPkcs8Lengths = { + '__proto__': null, + 'ML-KEM-512': 1660, + 'ML-KEM-768': 2428, + 'ML-KEM-1024': 3196, +}; + +function rejectPkcs8WithoutSeed(keyData, name) { + if (getBufferSourceByteLength(keyData) === kPrivOnlyPkcs8Lengths[name]) { + throw lazyDOMException( + 'Importing an ML-KEM PKCS#8 key without a seed is not supported', + 'NotSupportedError'); + } +} + function mlKemImportKey( format, keyData, @@ -117,37 +131,12 @@ function mlKemImportKey( const usagesSet = toUsagesSet(usages); switch (format) { case 'KeyObjectHandle': - verifyAcceptableKeyUse( - name, - usagesSet, - keyData.getKeyType() === kKeyTypePublic ? - kUsages.public : - kUsages.private); - handle = keyData; - break; - case 'spki': { - verifyAcceptableKeyUse(name, usagesSet, kUsages.public); - handle = importDerKey(keyData, true); - break; - } - case 'pkcs8': { - verifyAcceptableKeyUse(name, usagesSet, kUsages.private); - - const privOnlyLengths = { - '__proto__': null, - 'ML-KEM-512': 1660, - 'ML-KEM-768': 2428, - 'ML-KEM-1024': 3196, - }; - if (getBufferSourceByteLength(keyData) === privOnlyLengths[name]) { - throw lazyDOMException( - 'Importing an ML-KEM PKCS#8 key without a seed is not supported', - 'NotSupportedError'); - } - - handle = importDerKey(keyData, false); + case 'spki': + case 'pkcs8': + handle = importAsymmetricKeyHandle( + format, keyData, name, usagesSet, kUsages, + (data) => rejectPkcs8WithoutSeed(data, name)); break; - } case 'raw-public': case 'raw-seed': { const isPublic = format === 'raw-public'; diff --git a/lib/internal/crypto/rsa.js b/lib/internal/crypto/rsa.js index 8fa3ecdff1b8..9dd90803a056 100644 --- a/lib/internal/crypto/rsa.js +++ b/lib/internal/crypto/rsa.js @@ -12,7 +12,6 @@ const { SignJob, kCryptoJobWebCrypto, kKeyFormatDER, - kKeyTypePublic, kSignJobModeSign, kSignJobModeVerify, kKeyVariantRSA_OAEP, @@ -53,7 +52,7 @@ const { const { createKeyUsages, getKeyPairUsages, - importDerKey, + importAsymmetricKeyHandle, importJwkKey, validateJwk, validateKeyUsages, @@ -182,26 +181,11 @@ function rsaImportKey( let handle; switch (format) { case 'KeyObjectHandle': - verifyAcceptableKeyUse( - algorithm.name, - usagesSet, - keyData.getKeyType() === kKeyTypePublic ? - allowedUsages.public : - allowedUsages.private); - handle = keyData; - break; - case 'spki': { - verifyAcceptableKeyUse( - algorithm.name, usagesSet, allowedUsages.public); - handle = importDerKey(keyData, true); + case 'spki': + case 'pkcs8': + handle = importAsymmetricKeyHandle( + format, keyData, algorithm.name, usagesSet, allowedUsages); break; - } - case 'pkcs8': { - verifyAcceptableKeyUse( - algorithm.name, usagesSet, allowedUsages.private); - handle = importDerKey(keyData, false); - break; - } case 'jwk': { const isPublic = keyData.d === undefined; verifyAcceptableKeyUse( diff --git a/lib/internal/crypto/webcrypto.js b/lib/internal/crypto/webcrypto.js index 7ca945cb4f21..3ecb96f0dfc3 100644 --- a/lib/internal/crypto/webcrypto.js +++ b/lib/internal/crypto/webcrypto.js @@ -499,21 +499,20 @@ function deriveKeyImpl( )); } -function exportKeySpki(key) { - let exporter; - switch (getCryptoKeyAlgorithm(key).name) { +// Returns the SPKI/PKCS#8 export function for an asymmetric algorithm, or +// undefined if the algorithm does not support those formats. +function getAsymmetricKeyExporter(name) { + switch (name) { case 'RSASSA-PKCS1-v1_5': // Fall through case 'RSA-PSS': // Fall through case 'RSA-OAEP': - exporter = require('internal/crypto/rsa').rsaExportKey; - break; + return require('internal/crypto/rsa').rsaExportKey; case 'ECDSA': // Fall through case 'ECDH': - exporter = require('internal/crypto/ec').ecExportKey; - break; + return require('internal/crypto/ec').ecExportKey; case 'Ed25519': // Fall through case 'Ed448': @@ -521,25 +520,28 @@ function exportKeySpki(key) { case 'X25519': // Fall through case 'X448': - exporter = require('internal/crypto/cfrg').cfrgExportKey; - break; + return require('internal/crypto/cfrg').cfrgExportKey; case 'ML-DSA-44': // Fall through case 'ML-DSA-65': // Fall through case 'ML-DSA-87': - exporter = require('internal/crypto/ml_dsa').mlDsaExportKey; - break; + return require('internal/crypto/ml_dsa').mlDsaExportKey; case 'ML-KEM-512': // Fall through case 'ML-KEM-768': // Fall through case 'ML-KEM-1024': - exporter = require('internal/crypto/ml_kem').mlKemExportKey; - break; + return require('internal/crypto/ml_kem').mlKemExportKey; default: return undefined; } +} + +function exportKeySpki(key) { + const exporter = getAsymmetricKeyExporter(getCryptoKeyAlgorithm(key).name); + if (exporter === undefined) + return undefined; if (getCryptoKeyType(key) !== 'public') throw lazyDOMException('Key must be a public key', 'InvalidAccessError'); @@ -548,46 +550,9 @@ function exportKeySpki(key) { } function exportKeyPkcs8(key) { - let exporter; - switch (getCryptoKeyAlgorithm(key).name) { - case 'RSASSA-PKCS1-v1_5': - // Fall through - case 'RSA-PSS': - // Fall through - case 'RSA-OAEP': - exporter = require('internal/crypto/rsa').rsaExportKey; - break; - case 'ECDSA': - // Fall through - case 'ECDH': - exporter = require('internal/crypto/ec').ecExportKey; - break; - case 'Ed25519': - // Fall through - case 'Ed448': - // Fall through - case 'X25519': - // Fall through - case 'X448': - exporter = require('internal/crypto/cfrg').cfrgExportKey; - break; - case 'ML-DSA-44': - // Fall through - case 'ML-DSA-65': - // Fall through - case 'ML-DSA-87': - exporter = require('internal/crypto/ml_dsa').mlDsaExportKey; - break; - case 'ML-KEM-512': - // Fall through - case 'ML-KEM-768': - // Fall through - case 'ML-KEM-1024': - exporter = require('internal/crypto/ml_kem').mlKemExportKey; - break; - default: - return undefined; - } + const exporter = getAsymmetricKeyExporter(getCryptoKeyAlgorithm(key).name); + if (exporter === undefined) + return undefined; if (getCryptoKeyType(key) !== 'private') throw lazyDOMException('Key must be a private key', 'InvalidAccessError'); diff --git a/lib/internal/crypto/webcrypto_util.js b/lib/internal/crypto/webcrypto_util.js index 065520c59cb3..2b21d455cc57 100644 --- a/lib/internal/crypto/webcrypto_util.js +++ b/lib/internal/crypto/webcrypto_util.js @@ -139,6 +139,39 @@ function importDerKey(keyData, isPublic) { return handle; } +/** + * Imports a key in one of the formats shared by the asymmetric WebCrypto + * algorithms: 'KeyObjectHandle', 'spki', or 'pkcs8'. + * @param {string} format + * @param {any} keyData + * @param {string} name The algorithm name. + * @param {Set} usagesSet + * @param {{ public: string[], private: string[] }} allowedUsages + * @param {(keyData: any) => void} [validatePkcs8] Additional validation run + * for 'pkcs8' key data after the key usages have been verified. + * @returns {KeyObjectHandle} + */ +function importAsymmetricKeyHandle( + format, keyData, name, usagesSet, allowedUsages, validatePkcs8) { + switch (format) { + case 'KeyObjectHandle': + verifyAcceptableKeyUse( + name, + usagesSet, + keyData.getKeyType() === kKeyTypePublic ? + allowedUsages.public : + allowedUsages.private); + return keyData; + case 'spki': + verifyAcceptableKeyUse(name, usagesSet, allowedUsages.public); + return importDerKey(keyData, true); + case 'pkcs8': + verifyAcceptableKeyUse(name, usagesSet, allowedUsages.private); + validatePkcs8?.(keyData); + return importDerKey(keyData, false); + } +} + function validateJwk(keyData, kty, extractable, usagesSet, expectedUse) { if (typeof keyData.kty !== 'string') throw lazyDOMException('Invalid keyData', 'DataError'); @@ -246,6 +279,7 @@ function importJwkSecretKey(keyData) { module.exports = { createKeyUsages, getKeyPairUsages, + importAsymmetricKeyHandle, importDerKey, importJwkKey, importJwkSecretKey, diff --git a/lib/internal/http.js b/lib/internal/http.js index 68d4a75a253e..1fa8bf24d828 100644 --- a/lib/internal/http.js +++ b/lib/internal/http.js @@ -20,7 +20,11 @@ const { const { URL } = require('internal/url'); const { Buffer } = require('buffer'); const { isIPv4 } = require('internal/net'); -const { ERR_PROXY_INVALID_CONFIG } = require('internal/errors').codes; +const { + ERR_INVALID_ARG_VALUE, + ERR_PROXY_INVALID_CONFIG, +} = require('internal/errors').codes; +const { validateBoolean, validateOneOf } = require('internal/validators'); let utcCache; let utcHeaderCache; @@ -301,6 +305,33 @@ function getGlobalAgent(proxyEnv, Agent) { }); } +/** + * Validates the `insecureHTTPParser` and `httpValidation` options shared by + * HTTP clients and servers, and sets them on `target`. + * @param {object} target + * @param {{ insecureHTTPParser?: boolean, httpValidation?: string }} options + */ +function setHttpParserOptions(target, options) { + const insecureHTTPParser = options.insecureHTTPParser; + if (insecureHTTPParser !== undefined) + validateBoolean(insecureHTTPParser, 'options.insecureHTTPParser'); + target.insecureHTTPParser = insecureHTTPParser; + + const httpValidation = options.httpValidation; + if (httpValidation !== undefined) { + validateOneOf(httpValidation, 'options.httpValidation', + ['strict', 'relaxed', 'insecure']); + if (insecureHTTPParser !== undefined) { + throw new ERR_INVALID_ARG_VALUE( + 'options.httpValidation', + httpValidation, + 'cannot be used together with options.insecureHTTPParser', + ); + } + } + target.httpValidation = httpValidation; +} + module.exports = { kOutHeaders: Symbol('kOutHeaders'), kNeedDrain: Symbol('kNeedDrain'), @@ -318,4 +349,5 @@ module.exports = { getGlobalAgent, parseProxyUrl, redactProxyUrl, + setHttpParserOptions, }; diff --git a/lib/internal/http/client.js b/lib/internal/http/client.js index ecc872553113..880e0ee52408 100644 --- a/lib/internal/http/client.js +++ b/lib/internal/http/client.js @@ -72,6 +72,7 @@ const { getNextTraceEventId, kProxyConfig, checkShouldUseProxy, + setHttpParserOptions, } = require('internal/http'); const { ConnResetException, @@ -87,7 +88,6 @@ const { const { validateInteger, validateBoolean, - validateOneOf, validatePort, validateString, } = require('internal/validators'); @@ -456,27 +456,7 @@ function ClientRequest(input, options, cb) { validateInteger(maxHeaderSize, 'maxHeaderSize', 0); this.maxHeaderSize = maxHeaderSize; - const insecureHTTPParser = options.insecureHTTPParser; - if (insecureHTTPParser !== undefined) { - validateBoolean(insecureHTTPParser, 'options.insecureHTTPParser'); - } - - this.insecureHTTPParser = insecureHTTPParser; - - const httpValidation = options.httpValidation; - if (httpValidation !== undefined) { - validateOneOf(httpValidation, 'options.httpValidation', - ['strict', 'relaxed', 'insecure']); - if (insecureHTTPParser !== undefined) { - throw new ERR_INVALID_ARG_VALUE( - 'options.httpValidation', - httpValidation, - 'cannot be used together with options.insecureHTTPParser', - ); - } - } - - this.httpValidation = httpValidation; + setHttpParserOptions(this, options); if (options.joinDuplicateHeaders !== undefined) { validateBoolean(options.joinDuplicateHeaders, 'options.joinDuplicateHeaders'); diff --git a/lib/internal/http/server.js b/lib/internal/http/server.js index 9e13aeba63a6..fe870c471440 100644 --- a/lib/internal/http/server.js +++ b/lib/internal/http/server.js @@ -65,6 +65,7 @@ const { traceBegin, traceEnd, getNextTraceEventId, + setHttpParserOptions, } = require('internal/http'); const { defaultTriggerAsyncIdScope, @@ -99,7 +100,6 @@ const { const { validateInteger, validateBoolean, - validateOneOf, validateLinkHeaderValue, validateObject, validateFunction, @@ -538,24 +538,7 @@ function storeHTTPOptions(options) { validateBoolean(optimizeEmptyRequests, 'options.optimizeEmptyRequests'); this[kOptimizeEmptyRequests] = optimizeEmptyRequests || false; - const insecureHTTPParser = options.insecureHTTPParser; - if (insecureHTTPParser !== undefined) - validateBoolean(insecureHTTPParser, 'options.insecureHTTPParser'); - this.insecureHTTPParser = insecureHTTPParser; - - const httpValidation = options.httpValidation; - if (httpValidation !== undefined) { - validateOneOf(httpValidation, 'options.httpValidation', - ['strict', 'relaxed', 'insecure']); - if (insecureHTTPParser !== undefined) { - throw new ERR_INVALID_ARG_VALUE( - 'options.httpValidation', - httpValidation, - 'cannot be used together with options.insecureHTTPParser', - ); - } - } - this.httpValidation = httpValidation; + setHttpParserOptions(this, options); const requestTimeout = options.requestTimeout; if (requestTimeout !== undefined) { diff --git a/lib/internal/util/debounce.js b/lib/internal/util/debounce.js index 3038dfeb83fe..91b6ae847ace 100644 --- a/lib/internal/util/debounce.js +++ b/lib/internal/util/debounce.js @@ -2,7 +2,6 @@ const { ArrayPrototypePush, - ObjectDefineProperties, PromiseReject, PromiseWithResolvers, ReflectApply, @@ -19,6 +18,10 @@ const { validateObject, } = require('internal/validators'); const { addAbortListener } = require('internal/events/abort_listener'); +const { + createAbortError, + defineWrapperProperties, +} = require('internal/util/wrapped_function'); const { kEmptyObject } = require('internal/util'); const { TIMEOUT_MAX } = require('internal/timers'); const { clearTimeout, setTimeout } = require('timers'); @@ -82,17 +85,12 @@ function debounce(fn, wait, options = kEmptyObject) { function cancel(reason) { if (timeout === undefined) return; - const error = reason === undefined ? - new AbortError() : - new AbortError(undefined, { __proto__: null, cause: reason }); - cancelWithError(error); + cancelWithError(createAbortError(reason)); } function abort() { if (abortError === undefined) { - abortError = signal.reason === undefined ? - new AbortError() : - new AbortError(undefined, { __proto__: null, cause: signal.reason }); + abortError = createAbortError(signal.reason); } cancelWithError(abortError); } @@ -187,44 +185,18 @@ function debounce(fn, wait, options = kEmptyObject) { return call.promise; } - function createFn(value) { - return { - __proto__: null, - configurable: true, - enumerable: true, - writable: true, - value, - }; - } - - ObjectDefineProperties(debounced, { + defineWrapperProperties(debounced, fn, { __proto__: null, - cancel: createFn(cancel), - flush: createFn(flush), - ref: createFn(ref), - unref: createFn(unref), - pending: { - __proto__: null, - enumerable: false, - get() { - return pendingCalls.length === 0 ? null : pendingCalls[pendingCalls.length - 1].promise; - }, - }, - pendingCount: { - __proto__: null, - enumerable: false, - get() { return pendingCalls.length; }, - }, - length: { - __proto__: null, - configurable: true, - value: fn.length, - }, - name: { - __proto__: null, - configurable: true, - value: fn.name, + cancel, + flush, + ref, + unref, + }, { + __proto__: null, + pending() { + return pendingCalls.length === 0 ? null : pendingCalls[pendingCalls.length - 1].promise; }, + pendingCount() { return pendingCalls.length; }, }); if (signal !== undefined) { diff --git a/lib/internal/util/throttle.js b/lib/internal/util/throttle.js index bc1b4f01bdea..6083745bfc44 100644 --- a/lib/internal/util/throttle.js +++ b/lib/internal/util/throttle.js @@ -3,7 +3,6 @@ const { ArrayPrototypePush, ArrayPrototypeSlice, - ObjectDefineProperties, PromisePrototypeThen, PromiseReject, PromiseResolve, @@ -26,6 +25,10 @@ const { validateOneOf, } = require('internal/validators'); const { addAbortListener } = require('internal/events/abort_listener'); +const { + createAbortError, + defineWrapperProperties, +} = require('internal/util/wrapped_function'); const { kEmptyObject } = require('internal/util'); const { TIMEOUT_MAX } = require('internal/timers'); const { clearTimeout, setTimeout } = require('timers'); @@ -135,17 +138,12 @@ function throttle(fn, limit, interval, options = kEmptyObject) { } function cancel(reason) { - const error = reason === undefined ? - new AbortError() : - new AbortError(undefined, { __proto__: null, cause: reason }); - cancelWithError(error); + cancelWithError(createAbortError(reason)); } function abort() { if (abortError === undefined) { - abortError = signal.reason === undefined ? - new AbortError() : - new AbortError(undefined, { __proto__: null, cause: signal.reason }); + abortError = createAbortError(signal.reason); } cancelWithError(abortError); } @@ -312,51 +310,21 @@ function throttle(fn, limit, interval, options = kEmptyObject) { return call.promise; } - function createFn(value) { - return { - __proto__: null, - configurable: true, - enumerable: true, - writable: true, - value, - }; - } - - ObjectDefineProperties(throttled, { + defineWrapperProperties(throttled, fn, { __proto__: null, - cancel: createFn(cancel), - hasImmediateCapacity: createFn(hasImmediateCapacity), - ref: createFn(ref), - unref: createFn(unref), - pending: { - __proto__: null, - enumerable: false, - get() { - return pendingCount() === 0 ? null : - pendingCalls[pendingCalls.length - 1].promise; - }, - }, - pendingCount: { - __proto__: null, - enumerable: false, - get: pendingCount, - }, - activeCount: { - __proto__: null, - enumerable: false, - get() { - return activeCount; - }, - }, - length: { - __proto__: null, - configurable: true, - value: fn.length, + cancel, + hasImmediateCapacity, + ref, + unref, + }, { + __proto__: null, + pending() { + return pendingCount() === 0 ? null : + pendingCalls[pendingCalls.length - 1].promise; }, - name: { - __proto__: null, - configurable: true, - value: fn.name, + pendingCount, + activeCount() { + return activeCount; }, }); diff --git a/lib/internal/util/wrapped_function.js b/lib/internal/util/wrapped_function.js new file mode 100644 index 000000000000..27b3c796edea --- /dev/null +++ b/lib/internal/util/wrapped_function.js @@ -0,0 +1,69 @@ +'use strict'; + +// Helpers shared by util.debounce() and util.throttle(). + +const { + ObjectDefineProperties, +} = primordials; + +const { + AbortError, +} = require('internal/errors'); + +/** + * Creates the AbortError used to reject calls that were cancelled or aborted. + * @param {any} reason + * @returns {AbortError} + */ +function createAbortError(reason) { + return reason === undefined ? + new AbortError() : + new AbortError(undefined, { __proto__: null, cause: reason }); +} + +/** + * Defines the control methods, state getters, `length`, and `name` on a + * function returned by util.debounce() or util.throttle(). + * @param {Function} wrapper The function returned to the user. + * @param {Function} fn The wrapped user function. + * @param {{ [name: string]: Function }} methods Enumerable, writable methods. + * @param {{ [name: string]: Function }} getters Non-enumerable getters. + * @returns {Function} `wrapper`. + */ +function defineWrapperProperties(wrapper, fn, methods, getters) { + const descriptors = { + __proto__: null, + length: { + __proto__: null, + configurable: true, + value: fn.length, + }, + name: { + __proto__: null, + configurable: true, + value: fn.name, + }, + }; + for (const name in methods) { + descriptors[name] = { + __proto__: null, + configurable: true, + enumerable: true, + writable: true, + value: methods[name], + }; + } + for (const name in getters) { + descriptors[name] = { + __proto__: null, + enumerable: false, + get: getters[name], + }; + } + return ObjectDefineProperties(wrapper, descriptors); +} + +module.exports = { + createAbortError, + defineWrapperProperties, +}; diff --git a/lib/internal/webstreams/adapters.js b/lib/internal/webstreams/adapters.js index fc5ada12be3c..443bea0386c8 100644 --- a/lib/internal/webstreams/adapters.js +++ b/lib/internal/webstreams/adapters.js @@ -167,6 +167,24 @@ const noop = () => {}; // `failed`/`failure` latch a write that could not proceed. The callback // runs in the async context of the Node.js write that set it, as the // reaction to writer.write() did (see settle()). +/** + * Encodes a string chunk written to a Node.js Writable as a Uint8Array for a + * WritableStream. + * @param {string} chunk + * @param {string} encoding + * @returns {Uint8Array} + */ +function encodeStringChunk(chunk, encoding) { + if (normalizeEncoding(encoding) === 'utf8') + return encoder.encode(chunk); + const buffer = Buffer.from(chunk, encoding); + return new Uint8Array( + TypedArrayPrototypeGetBuffer(buffer), + TypedArrayPrototypeGetByteOffset(buffer), + TypedArrayPrototypeGetByteLength(buffer), + ); +} + function createWriteTracker(getDestination) { return { promise: null, @@ -493,20 +511,8 @@ function newStreamWritableFromWritableStream(writableStream, options = kEmptyObj }, write(chunk, encoding, callback) { - if (typeof chunk === 'string' && decodeStrings && !objectMode) { - const enc = normalizeEncoding(encoding); - - if (enc === 'utf8') { - chunk = encoder.encode(chunk); - } else { - chunk = Buffer.from(chunk, encoding); - chunk = new Uint8Array( - TypedArrayPrototypeGetBuffer(chunk), - TypedArrayPrototypeGetByteOffset(chunk), - TypedArrayPrototypeGetByteLength(chunk), - ); - } - } + if (typeof chunk === 'string' && decodeStrings && !objectMode) + chunk = encodeStringChunk(chunk, encoding); writeTracker.callback = callback; dispatchWrite(writer, chunk, writeTracker); @@ -948,20 +954,8 @@ function newStreamDuplexFromReadableWritablePair(pair = kEmptyObject, options = }, write(chunk, encoding, callback) { - if (typeof chunk === 'string' && decodeStrings && !objectMode) { - const enc = normalizeEncoding(encoding); - - if (enc === 'utf8') { - chunk = encoder.encode(chunk); - } else { - chunk = Buffer.from(chunk, encoding); - chunk = new Uint8Array( - TypedArrayPrototypeGetBuffer(chunk), - TypedArrayPrototypeGetByteOffset(chunk), - TypedArrayPrototypeGetByteLength(chunk), - ); - } - } + if (typeof chunk === 'string' && decodeStrings && !objectMode) + chunk = encodeStringChunk(chunk, encoding); writeTracker.callback = callback; dispatchWrite(writer, chunk, writeTracker); diff --git a/src/crypto/crypto_context.cc b/src/crypto/crypto_context.cc index 21decb34e111..bd6f9c596898 100644 --- a/src/crypto/crypto_context.cc +++ b/src/crypto/crypto_context.cc @@ -2516,13 +2516,7 @@ int SecureContext::TicketKeyCallback(SSL* ssl, unsigned char* name, unsigned char* iv, EVP_CIPHER_CTX* ectx, -#if NCRYPTO_USE_OPENSSL_PROVIDER - EVP_MAC_CTX* hctx, -#elif NCRYPTO_USE_BORINGSSL - HMAC_CTX* hctx, -#else -#error "Unsupported crypto backend" -#endif + TicketHmacCtx* hctx, int enc) { static const int kTicketPartSize = 16; @@ -2615,13 +2609,7 @@ int SecureContext::TicketCompatibilityCallback(SSL* ssl, unsigned char* name, unsigned char* iv, EVP_CIPHER_CTX* ectx, -#if NCRYPTO_USE_OPENSSL_PROVIDER - EVP_MAC_CTX* hctx, -#elif NCRYPTO_USE_BORINGSSL - HMAC_CTX* hctx, -#else -#error "Unsupported crypto backend" -#endif + TicketHmacCtx* hctx, int enc) { SecureContext* sc = static_cast( SSL_CTX_get_app_data(SSL_get_SSL_CTX(ssl))); diff --git a/src/crypto/crypto_context.h b/src/crypto/crypto_context.h index 5073897251a8..8b6f0fe18817 100644 --- a/src/crypto/crypto_context.h +++ b/src/crypto/crypto_context.h @@ -35,6 +35,15 @@ void InstallCertVerifyCallback(SSL_CTX* ctx); ncrypto::BIOPointer LoadBIO(Environment* env, v8::Local v); +// The HMAC context type passed to TLS session ticket key callbacks. +#if NCRYPTO_USE_OPENSSL_PROVIDER +using TicketHmacCtx = EVP_MAC_CTX; +#elif NCRYPTO_USE_BORINGSSL +using TicketHmacCtx = HMAC_CTX; +#else +#error "Unsupported crypto backend" +#endif + class SecureContext final : public BaseObject { public: using GetSessionCb = SSL_SESSION* (*)(SSL*, const unsigned char*, int, int*); @@ -161,26 +170,14 @@ class SecureContext final : public BaseObject { unsigned char* name, unsigned char* iv, EVP_CIPHER_CTX* ectx, -#if NCRYPTO_USE_OPENSSL_PROVIDER - EVP_MAC_CTX* hctx, -#elif NCRYPTO_USE_BORINGSSL - HMAC_CTX* hctx, -#else -#error "Unsupported crypto backend" -#endif + TicketHmacCtx* hctx, int enc); static int TicketCompatibilityCallback(SSL* ssl, unsigned char* name, unsigned char* iv, EVP_CIPHER_CTX* ectx, -#if NCRYPTO_USE_OPENSSL_PROVIDER - EVP_MAC_CTX* hctx, -#elif NCRYPTO_USE_BORINGSSL - HMAC_CTX* hctx, -#else -#error "Unsupported crypto backend" -#endif + TicketHmacCtx* hctx, int enc); SecureContext(Environment* env, v8::Local wrap); diff --git a/src/crypto/crypto_hash.cc b/src/crypto/crypto_hash.cc index b0ea75e88b27..77b7e7d41693 100644 --- a/src/crypto/crypto_hash.cc +++ b/src/crypto/crypto_hash.cc @@ -709,13 +709,8 @@ void Hash::New(const FunctionCallbackInfo& args) { } } -bool Hash::HashInit(const EVP_MD* digest, Maybe xof_md_len) { - mdctx_ = EVPMDCtxPointer::New(); - if (!mdctx_.digestInit(digest)) [[unlikely]] { - mdctx_.reset(); - return false; - } - +bool Hash::FinishHashInit(const EVP_MD* digest, + Maybe xof_md_len) { md_len_ = mdctx_.getDigestSize(); if (mdctx_.hasXofFlag() && !xof_md_len.IsJust() && ShouldRejectMissingXofLength(digest, md_len_)) { @@ -738,35 +733,26 @@ bool Hash::HashInit(const EVP_MD* digest, Maybe xof_md_len) { return true; } -bool Hash::HashInit(const EVP_MD* digest, - const CShakeOptions& options, - Maybe xof_md_len) { +bool Hash::HashInit(const EVP_MD* digest, Maybe xof_md_len) { mdctx_ = EVPMDCtxPointer::New(); - if (!options.Initialize(&mdctx_, digest)) [[unlikely]] { + if (!mdctx_.digestInit(digest)) [[unlikely]] { mdctx_.reset(); return false; } - md_len_ = mdctx_.getDigestSize(); - if (mdctx_.hasXofFlag() && !xof_md_len.IsJust() && - ShouldRejectMissingXofLength(digest, md_len_)) { - MarkInvalidXofLength(); + return FinishHashInit(digest, xof_md_len); +} + +bool Hash::HashInit(const EVP_MD* digest, + const CShakeOptions& options, + Maybe xof_md_len) { + mdctx_ = EVPMDCtxPointer::New(); + if (!options.Initialize(&mdctx_, digest)) [[unlikely]] { mdctx_.reset(); return false; } - if (xof_md_len.IsJust() && xof_md_len.FromJust() != md_len_) { - // This is a little hack to cause createHash to fail when an incorrect - // hashSize option was passed for a non-XOF hash function. - if (!mdctx_.hasXofFlag()) [[unlikely]] { - MarkInvalidXofLength(); - mdctx_.reset(); - return false; - } - md_len_ = xof_md_len.FromJust(); - } - - return true; + return FinishHashInit(digest, xof_md_len); } bool Hash::HashUpdate(const char* data, size_t len) { diff --git a/src/crypto/crypto_hash.h b/src/crypto/crypto_hash.h index 322ff83da695..558c67822f4c 100644 --- a/src/crypto/crypto_hash.h +++ b/src/crypto/crypto_hash.h @@ -57,6 +57,11 @@ class Hash final : public BaseObject { Hash(Environment* env, v8::Local wrap); private: + // Determines the digest length after mdctx_ has been initialized, applying + // and validating the requested XOF output length. Resets mdctx_ and returns + // false on failure. + bool FinishHashInit(const EVP_MD* digest, v8::Maybe xof_md_len); + ncrypto::EVPMDCtxPointer mdctx_{}; unsigned int md_len_ = 0; ByteSource digest_; diff --git a/src/node_buffer.cc b/src/node_buffer.cc index 448ef5b6049e..e7accbbe8d3f 100644 --- a/src/node_buffer.cc +++ b/src/node_buffer.cc @@ -1013,33 +1013,23 @@ int64_t IndexOfOffset(size_t length, } } -void IndexOfString(const FunctionCallbackInfo& args) { - Environment* env = Environment::GetCurrent(args); - Isolate* isolate = env->isolate(); - - CHECK(args[1]->IsString()); - CHECK(args[2]->IsNumber()); - CHECK(args[3]->IsInt32()); - CHECK(args[4]->IsBoolean()); - CHECK(args[5]->IsNumber()); - - enum encoding enc = static_cast(args[3].As()->Value()); - - THROW_AND_RETURN_UNLESS_BUFFER(env, args[0]); - ArrayBufferViewContents buffer(args[0]); - - Local needle = args[1].As(); - int64_t offset_i64 = args[2].As()->Value(); - bool is_forward = args[4]->IsTrue(); - int64_t end_i64 = args[5].As()->Value(); - - const char* haystack = buffer.data(); - // Round down to the nearest multiple of 2 in case of UCS2. - const size_t haystack_length = (enc == UCS2) ? - buffer.length() &~ 1 : buffer.length(); // NOLINT(whitespace/operators) - - size_t needle_length; - if (!StringBytes::Size(isolate, needle, enc).To(&needle_length)) return; +// Resolves the range searched by IndexOfString() and IndexOfBuffer(). Returns +// false if the result is known without searching, in which case +// `*early_result` holds the value to return. Otherwise, sets `*offset` to the +// position to start searching from and `*search_end` to the exclusive upper +// bound of the search range. If `align_ucs2_offset` is true, forward UCS-2 +// searches start at an even byte offset. +bool GetIndexOfSearchRange(size_t haystack_length, + size_t needle_length, + int64_t offset_i64, + int64_t end_i64, + bool is_forward, + enum encoding enc, + bool align_ucs2_offset, + size_t* offset_out, + size_t* search_end_out, + double* early_result) { + *early_result = -1; // search_end is the exclusive upper bound of the search range. size_t search_end = static_cast(std::min( @@ -1055,33 +1045,79 @@ void IndexOfString(const FunctionCallbackInfo& args) { // Match String#indexOf() and String#lastIndexOf() behavior, // but clamp to search_end. int64_t clamped = std::min(opt_offset, static_cast(search_end)); - args.GetReturnValue().Set(static_cast(clamped)); - return; - } - - if (haystack_length == 0) { - return args.GetReturnValue().Set(-1); + *early_result = static_cast(clamped); + return false; } - if (opt_offset <= -1) { - return args.GetReturnValue().Set(-1); + if (haystack_length == 0 || opt_offset <= -1) { + return false; } size_t offset = static_cast(opt_offset); // For backward search, clamp start to within the search range. if (!is_forward && offset >= search_end) { - if (search_end == 0) return args.GetReturnValue().Set(-1); + if (search_end == 0) return false; offset = search_end - 1; } else if (is_forward && offset >= search_end) { - return args.GetReturnValue().Set(-1); + return false; } - if (enc == UCS2 && is_forward) { + if (align_ucs2_offset && enc == UCS2 && is_forward) { offset += offset % sizeof(uint16_t); - if (offset >= search_end) return args.GetReturnValue().Set(-1); + if (offset >= search_end) return false; } CHECK_LT(offset, haystack_length); if ((is_forward && needle_length + offset > search_end) || needle_length > search_end) { - return args.GetReturnValue().Set(-1); + return false; + } + + *offset_out = offset; + *search_end_out = search_end; + return true; +} + +void IndexOfString(const FunctionCallbackInfo& args) { + Environment* env = Environment::GetCurrent(args); + Isolate* isolate = env->isolate(); + + CHECK(args[1]->IsString()); + CHECK(args[2]->IsNumber()); + CHECK(args[3]->IsInt32()); + CHECK(args[4]->IsBoolean()); + CHECK(args[5]->IsNumber()); + + enum encoding enc = static_cast(args[3].As()->Value()); + + THROW_AND_RETURN_UNLESS_BUFFER(env, args[0]); + ArrayBufferViewContents buffer(args[0]); + + Local needle = args[1].As(); + int64_t offset_i64 = args[2].As()->Value(); + bool is_forward = args[4]->IsTrue(); + int64_t end_i64 = args[5].As()->Value(); + + const char* haystack = buffer.data(); + // Round down to the nearest multiple of 2 in case of UCS2. + const size_t haystack_length = + (enc == UCS2) ? buffer.length() & ~1 + : buffer.length(); // NOLINT(whitespace/operators) + + size_t needle_length; + if (!StringBytes::Size(isolate, needle, enc).To(&needle_length)) return; + + size_t offset; + size_t search_end; + double early_result; + if (!GetIndexOfSearchRange(haystack_length, + needle_length, + offset_i64, + end_i64, + is_forward, + enc, + true, + &offset, + &search_end, + &early_result)) { + return args.GetReturnValue().Set(early_result); } size_t result = search_end; @@ -1172,43 +1208,20 @@ void IndexOfBuffer(const FunctionCallbackInfo& args) { const char* needle = needle_contents.data(); const size_t needle_length = needle_contents.length(); - // search_end is the exclusive upper bound of the search range. - size_t search_end = static_cast(std::min( - std::max(end_i64, int64_t{0}), static_cast(haystack_length))); - if (enc == UCS2) search_end &= ~static_cast(1); - - int64_t opt_offset = IndexOfOffset(haystack_length, - offset_i64, - needle_length, - is_forward); - - if (needle_length == 0) { - // Match String#indexOf() and String#lastIndexOf() behavior, - // but clamp to search_end. - int64_t clamped = std::min(opt_offset, static_cast(search_end)); - args.GetReturnValue().Set(static_cast(clamped)); - return; - } - - if (haystack_length == 0) { - return args.GetReturnValue().Set(-1); - } - - if (opt_offset <= -1) { - return args.GetReturnValue().Set(-1); - } - size_t offset = static_cast(opt_offset); - // For backward search, clamp start to within the search range. - if (!is_forward && offset >= search_end) { - if (search_end == 0) return args.GetReturnValue().Set(-1); - offset = search_end - 1; - } else if (is_forward && offset >= search_end) { - return args.GetReturnValue().Set(-1); - } - CHECK_LT(offset, haystack_length); - if ((is_forward && needle_length + offset > search_end) || - needle_length > search_end) { - return args.GetReturnValue().Set(-1); + size_t offset; + size_t search_end; + double early_result; + if (!GetIndexOfSearchRange(haystack_length, + needle_length, + offset_i64, + end_i64, + is_forward, + enc, + false, + &offset, + &search_end, + &early_result)) { + return args.GetReturnValue().Set(early_result); } size_t result = search_end; diff --git a/src/node_sqlite.cc b/src/node_sqlite.cc index 8341b27a4fa0..444367abdbbc 100644 --- a/src/node_sqlite.cc +++ b/src/node_sqlite.cc @@ -4375,7 +4375,8 @@ bool SQLTagStore::ResetAndBindStatement( return true; } -void SQLTagStore::Run(const FunctionCallbackInfo& args) { +void SQLTagStore::PrepareForExecution(const FunctionCallbackInfo& args, + BaseObjectPtr* out) { SQLTagStore* session; ASSIGN_OR_RETURN_UNWRAP(&session, args.This()); Environment* env = Environment::GetCurrent(args); @@ -4396,6 +4397,17 @@ void SQLTagStore::Run(const FunctionCallbackInfo& args) { return; } + *out = std::move(stmt); +} + +void SQLTagStore::Run(const FunctionCallbackInfo& args) { + BaseObjectPtr stmt; + PrepareForExecution(args, &stmt); + if (!stmt) { + return; + } + Environment* env = Environment::GetCurrent(args); + Local result; if (StatementExecutionHelper::Run(env, stmt.get()).ToLocal(&result)) { args.GetReturnValue().Set(result); @@ -4403,25 +4415,12 @@ void SQLTagStore::Run(const FunctionCallbackInfo& args) { } void SQLTagStore::Iterate(const FunctionCallbackInfo& args) { - SQLTagStore* session; - ASSIGN_OR_RETURN_UNWRAP(&session, args.This()); - Environment* env = Environment::GetCurrent(args); - - THROW_AND_RETURN_ON_BAD_STATE( - env, !session->database_->IsOpen(), "database is not open"); - THROW_AND_RETURN_IF_IN_AUTHORIZER(env, session->database_.get()); - - BaseObjectPtr stmt = PrepareStatement(args); - + BaseObjectPtr stmt; + PrepareForExecution(args, &stmt); if (!stmt) { return; } - - THROW_AND_RETURN_IF_STEPPING(env, stmt.get()); - - if (!ResetAndBindStatement(env, stmt.get(), args)) { - return; - } + Environment* env = Environment::GetCurrent(args); BaseObjectPtr iter = StatementExecutionHelper::Iterate(env, BaseObjectPtr(stmt)); @@ -4434,25 +4433,12 @@ void SQLTagStore::Iterate(const FunctionCallbackInfo& args) { } void SQLTagStore::Get(const FunctionCallbackInfo& args) { - SQLTagStore* session; - ASSIGN_OR_RETURN_UNWRAP(&session, args.This()); - Environment* env = Environment::GetCurrent(args); - - THROW_AND_RETURN_ON_BAD_STATE( - env, !session->database_->IsOpen(), "database is not open"); - THROW_AND_RETURN_IF_IN_AUTHORIZER(env, session->database_.get()); - - BaseObjectPtr stmt = PrepareStatement(args); - + BaseObjectPtr stmt; + PrepareForExecution(args, &stmt); if (!stmt) { return; } - - THROW_AND_RETURN_IF_STEPPING(env, stmt.get()); - - if (!ResetAndBindStatement(env, stmt.get(), args)) { - return; - } + Environment* env = Environment::GetCurrent(args); Local result; if (StatementExecutionHelper::Get(env, stmt.get()).ToLocal(&result)) { @@ -4461,25 +4447,12 @@ void SQLTagStore::Get(const FunctionCallbackInfo& args) { } void SQLTagStore::All(const FunctionCallbackInfo& args) { - SQLTagStore* session; - ASSIGN_OR_RETURN_UNWRAP(&session, args.This()); - Environment* env = Environment::GetCurrent(args); - - THROW_AND_RETURN_ON_BAD_STATE( - env, !session->database_->IsOpen(), "database is not open"); - THROW_AND_RETURN_IF_IN_AUTHORIZER(env, session->database_.get()); - - BaseObjectPtr stmt = PrepareStatement(args); - + BaseObjectPtr stmt; + PrepareForExecution(args, &stmt); if (!stmt) { return; } - - THROW_AND_RETURN_IF_STEPPING(env, stmt.get()); - - if (!ResetAndBindStatement(env, stmt.get(), args)) { - return; - } + Environment* env = Environment::GetCurrent(args); Isolate* isolate = env->isolate(); bool needs_reset = true; diff --git a/src/node_sqlite.h b/src/node_sqlite.h index 2bba70c3bbae..c14a7c3cdead 100644 --- a/src/node_sqlite.h +++ b/src/node_sqlite.h @@ -534,6 +534,13 @@ class SQLTagStore : public BaseObject { Environment* env, Statement* stmt, const v8::FunctionCallbackInfo& args); + // Performs the state checks, statement preparation, and parameter binding + // shared by Run(), Iterate(), Get(), and All(). On success, `*out` is set to + // the prepared statement. On failure, a JavaScript exception is pending and + // `*out` is left empty. + static void PrepareForExecution( + const v8::FunctionCallbackInfo& args, + BaseObjectPtr* out); BaseObjectWeakPtr database_; LRUCache> sql_tags_; friend class StatementExecutionHelper; diff --git a/src/node_url_pattern.cc b/src/node_url_pattern.cc index 63f01d58170f..eac1d62f34d4 100644 --- a/src/node_url_pattern.cc +++ b/src/node_url_pattern.cc @@ -560,46 +560,72 @@ bool URLPattern::Test(Environment* env, // V8 Methods -void URLPattern::Exec(const FunctionCallbackInfo& args) { - URLPattern* url_pattern; - ASSIGN_OR_RETURN_UNWRAP(&url_pattern, args.This()); - auto env = Environment::GetCurrent(args); +namespace { +// The arguments of URLPattern.prototype.exec() and test(). When the input is +// a string, `input` refers to `input_storage`, so instances must not be copied +// or moved. +struct URLPatternMatchArgs { + URLPatternMatchArgs() = default; + URLPatternMatchArgs(const URLPatternMatchArgs&) = delete; + URLPatternMatchArgs& operator=(const URLPatternMatchArgs&) = delete; + + std::optional base_url_view() const { + return base_url ? std::optional(*base_url) : std::nullopt; + } ada::url_pattern_input input; - std::optional baseURL{}; - std::string input_base; + std::string input_storage; + std::optional base_url; +}; + +// Parses the `input` and `baseURL` arguments of exec() and test(). Returns +// false if a JavaScript exception is pending. +bool ParseURLPatternMatchArgs(Environment* env, + const FunctionCallbackInfo& args, + URLPatternMatchArgs* out) { if (args.Length() == 0 || args[0]->IsNullOrUndefined()) { - input = ada::url_pattern_init{}; + out->input = ada::url_pattern_init{}; } else if (args[0]->IsString()) { Utf8Value input_value(env->isolate(), args[0].As()); - input_base = input_value.ToString(); - input = std::string_view(input_base); + out->input_storage = input_value.ToString(); + out->input = std::string_view(out->input_storage); } else if (args[0]->IsObject()) { - auto maybeInput = URLPatternInit::FromJsObject(env, args[0].As()); - if (!maybeInput.has_value()) return; - input = std::move(*maybeInput); + auto maybeInput = + URLPattern::URLPatternInit::FromJsObject(env, args[0].As()); + if (!maybeInput.has_value()) return false; + out->input = std::move(*maybeInput); } else { THROW_ERR_INVALID_ARG_TYPE( env, "URLPattern input needs to be a string or an object"); - return; + return false; } if (args.Length() > 1 && !args[1]->IsUndefined()) { if (args[1]->IsNull()) { - baseURL = std::string("null"); + out->base_url = std::string("null"); } else if (args[1]->IsString()) { Utf8Value base_url_value(env->isolate(), args[1].As()); - baseURL = base_url_value.ToStringView(); + out->base_url = base_url_value.ToStringView(); } else { THROW_ERR_INVALID_ARG_TYPE(env, "baseURL must be a string"); - return; + return false; } } + return true; +} +} // namespace +void URLPattern::Exec(const FunctionCallbackInfo& args) { + URLPattern* url_pattern; + ASSIGN_OR_RETURN_UNWRAP(&url_pattern, args.This()); + auto env = Environment::GetCurrent(args); + + URLPatternMatchArgs match_args; + if (!ParseURLPatternMatchArgs(env, args, &match_args)) return; + + std::optional base_url = match_args.base_url_view(); Local result; - std::optional baseURL_opt = - baseURL ? std::optional(*baseURL) : std::nullopt; - if (!url_pattern->Exec(env, input, baseURL_opt).ToLocal(&result)) { + if (!url_pattern->Exec(env, match_args.input, base_url).ToLocal(&result)) { THROW_ERR_OPERATION_FAILED(env, "Failed to exec URLPattern"); return; } @@ -611,40 +637,11 @@ void URLPattern::Test(const FunctionCallbackInfo& args) { ASSIGN_OR_RETURN_UNWRAP(&url_pattern, args.This()); auto env = Environment::GetCurrent(args); - ada::url_pattern_input input; - std::optional baseURL{}; - std::string input_base; - if (args.Length() == 0 || args[0]->IsNullOrUndefined()) { - input = ada::url_pattern_init{}; - } else if (args[0]->IsString()) { - Utf8Value input_value(env->isolate(), args[0].As()); - input_base = input_value.ToString(); - input = std::string_view(input_base); - } else if (args[0]->IsObject()) { - auto maybeInput = URLPatternInit::FromJsObject(env, args[0].As()); - if (!maybeInput.has_value()) return; - input = std::move(*maybeInput); - } else { - THROW_ERR_INVALID_ARG_TYPE( - env, "URLPattern input needs to be a string or an object"); - return; - } - - if (args.Length() > 1 && !args[1]->IsUndefined()) { - if (args[1]->IsNull()) { - baseURL = std::string("null"); - } else if (args[1]->IsString()) { - Utf8Value base_url_value(env->isolate(), args[1].As()); - baseURL = base_url_value.ToStringView(); - } else { - THROW_ERR_INVALID_ARG_TYPE(env, "baseURL must be a string"); - return; - } - } + URLPatternMatchArgs match_args; + if (!ParseURLPatternMatchArgs(env, args, &match_args)) return; - std::optional baseURL_opt = - baseURL ? std::optional(*baseURL) : std::nullopt; - args.GetReturnValue().Set(url_pattern->Test(env, input, baseURL_opt)); + std::optional base_url = match_args.base_url_view(); + args.GetReturnValue().Set(url_pattern->Test(env, match_args.input, base_url)); } #define URL_PATTERN_COMPONENT_GETTERS(uppercase_name, lowercase_name) \