diff --git a/lib/internal/crypto/keys.js b/lib/internal/crypto/keys.js index fdf97dc549d..e82e48ad653 100644 --- a/lib/internal/crypto/keys.js +++ b/lib/internal/crypto/keys.js @@ -117,12 +117,13 @@ for (const m of [[kKeyEncodingPKCS1, 'pkcs1'], [kKeyEncodingPKCS8, 'pkcs8'], [kKeyEncodingSPKI, 'spki'], [kKeyEncodingSEC1, 'sec1']]) encodingNames[m[0]] = m[1]; -// KeyObject state lives on the native NativeKeyObject base class. JS reads -// the native type enum and a KeyObjectHandle in one call and caches that -// slot tuple in a private field so no forgeable own Symbols are exposed on -// public KeyObject instances. +// KeyObject state lives on the native NativeKeyObject base class. JS caches +// the constructor-known type enum in a private field, then replaces it with +// the native type and KeyObjectHandle tuple when the handle is first needed. +// No forgeable own Symbols are exposed on public KeyObject instances. let getKeyObjectSlots; // Populated by the createNativeKeyObjectClass callback. let isKeyObject; +let getKeyObjectTypeValue; const kKeyObjectSlotType = 0; const kKeyObjectSlotHandle = 1; @@ -162,12 +163,18 @@ const { #slots; constructor(type, handle) { - if (type !== 'secret' && type !== 'public' && type !== 'private') - throw new ERR_INVALID_ARG_VALUE('type', type); + let keyType; + switch (type) { + case 'secret': keyType = kKeyTypeSecret; break; + case 'public': keyType = kKeyTypePublic; break; + case 'private': keyType = kKeyTypePrivate; break; + default: throw new ERR_INVALID_ARG_VALUE('type', type); + } if (typeof handle !== 'object' || !(handle instanceof KeyObjectHandle)) throw new ERR_INVALID_ARG_TYPE('handle', 'object', handle); super(handle); + this.#slots = keyType; } get type() { @@ -232,12 +239,23 @@ const { if (key == null || typeof key !== 'object') return false; return #slots in key || isNativeKeyObject(key); }; + getKeyObjectTypeValue = (key) => { + if (!key || typeof key !== 'object') + throw new ERR_INVALID_THIS('KeyObject'); + if (#slots in key) { + const cached = key.#slots; + if (typeof cached === 'number') return cached; + if (cached !== undefined) return cached[kKeyObjectSlotType]; + } + return getKeyObjectSlots(key)[kKeyObjectSlotType]; + }; + getKeyObjectSlots = (key) => { if (!key || typeof key !== 'object') throw new ERR_INVALID_THIS('KeyObject'); if (#slots in key) { const cached = key.#slots; - if (cached !== undefined) return cached; + if (cached !== undefined && typeof cached !== 'number') return cached; } const slots = nativeGetKeyObjectSlots(key); key.#slots = slots; @@ -961,7 +979,7 @@ function keyObjectTypeToString(type) { * @returns {'secret' | 'public' | 'private'} */ function getKeyObjectType(key) { - return keyObjectTypeToString(getKeyObjectSlots(key)[kKeyObjectSlotType]); + return keyObjectTypeToString(getKeyObjectTypeValue(key)); } /** @@ -1062,11 +1080,11 @@ function getKeyObjectAsymmetricKeyDetails(key) { // -> CryptoKey.prototype // -> Object.prototype // -// All five internal slots are read from C++ in a single call via -// `getCryptoKeySlots`. The resulting array is cached in a private -// class field on `InternalCryptoKey` so that it is invisible to -// reflection (`Object.getOwnPropertySymbols` etc.) and leaves each -// CryptoKey's hidden class pristine. The `getCryptoKey{Type, +// Normal construction caches all five internal slots in a private class +// field on `InternalCryptoKey`. Partially initialized transferred keys read +// them from C++ in a single `getCryptoKeySlots` call on first access. The +// cache is invisible to reflection (`Object.getOwnPropertySymbols` etc.) and +// leaves each CryptoKey's hidden class pristine. The `getCryptoKey{Type, // Extractable,Algorithm,Usages,Handle}` helpers index into that // array and convert native enums/masks back to Web Crypto strings. // The internal algorithm object is stored as a null-prototype clone @@ -1175,6 +1193,15 @@ const { if (algorithm !== undefined) algorithm = cloneInternalAlgorithm(algorithm); super(handle, algorithm, usagesMask, extractable); + if (algorithm !== undefined) { + this.#slots = [ + handle.getKeyType(), + extractable, + algorithm, + usagesMask, + handle, + ]; + } } static { @@ -1215,12 +1242,10 @@ const { return [CryptoKey, InternalCryptoKey]; }); -// The helpers below return a CryptoKey's internal slot value, -// populating the per-instance cache on first access via a single -// native call. The public `type` getter converts the native enum to -// the Web Crypto string. The `usages` helper converts the native usage -// mask to Web Crypto strings. The public `algorithm` / `usages` getters -// on `CryptoKey.prototype` cache their returned objects. +// The helpers below return a CryptoKey's internal slot value. The public +// `type` getter converts the native enum to the Web Crypto string. The +// `usages` helper converts the native usage mask to Web Crypto strings. The +// public `algorithm` / `usages` getters cache their returned objects. /** * Returns the value of a CryptoKey's `[[type]]` internal slot. diff --git a/src/crypto/README.md b/src/crypto/README.md index 7f3d2de8e77..9f6139d8a4c 100644 --- a/src/crypto/README.md +++ b/src/crypto/README.md @@ -171,11 +171,12 @@ JavaScript needs access to those operations and is kept out of user-visible A `KeyObject` is the public Node.js-specific API for keys. It extends a native `NativeKeyObject`, which stores `KeyObjectData` for structured -cloning. The JavaScript API surface reads its key type and a -`KeyObjectHandle` through a hidden native-backed slot tuple, caching that -tuple in a private field outside user-visible own properties. Derived -metadata, such as symmetric key size and asymmetric key details, is read -from the cached handle and appended lazily to the same private-field cache. +cloning. The JavaScript constructor caches the known key type in a private +field outside user-visible own properties. When a `KeyObjectHandle` is first +needed, JavaScript replaces that value with a hidden native-backed slot tuple. +Derived metadata, such as symmetric key size and asymmetric key details, is +read from the cached handle and appended lazily to the same private-field +cache. #### `CryptoKey` @@ -183,7 +184,10 @@ A `CryptoKey` is the Web Crypto API key type. In the Node.js implementation, public `CryptoKey` instances are backed by a native `NativeCryptoKey`, not by a `KeyObject`. `NativeCryptoKey` stores the same `KeyObjectData` representation as `KeyObject`, plus the Web Crypto internal slots -(`[[extractable]]`, `[[algorithm]]`, and `[[usages]]`). +(`[[extractable]]`, `[[algorithm]]`, and `[[usages]]`). Normal construction +primes a private JavaScript slot cache from the constructor arguments. +Partially initialized transferred keys populate that cache from the native +slots on first access. ### `CryptoJob` diff --git a/test/parallel/test-crypto-keyobject-clone-transfer.js b/test/parallel/test-crypto-keyobject-clone-transfer.js index 1d68e4b9911..61cfcdc497f 100644 --- a/test/parallel/test-crypto-keyobject-clone-transfer.js +++ b/test/parallel/test-crypto-keyobject-clone-transfer.js @@ -52,23 +52,25 @@ async function roundTripViaMessageChannel(key) { return received; } -async function roundTripViaWorker(key) { - const worker = new Worker(` - 'use strict'; - const { parentPort } = require('node:worker_threads'); - const { types: { isKeyObject } } = require('node:util'); +function workerMain() { + const { parentPort } = require('node:worker_threads'); + const { types: { isKeyObject: workerIsKeyObject } } = require('node:util'); - parentPort.once('message', ({ key, expectedType }) => { - try { - if (!isKeyObject(key) || key.type !== expectedType) { - throw new Error('KeyObject slot mismatch in worker'); - } - parentPort.postMessage({ key }); - } catch (err) { - parentPort.postMessage({ error: err.stack || err.message }); + parentPort.once('message', ({ key, expectedType }) => { + try { + if (!workerIsKeyObject(key) || key.type !== expectedType) { + throw new Error('KeyObject slot mismatch in worker'); } - }); - `, { eval: true }); + parentPort.postMessage({ key }); + } catch (err) { + parentPort.postMessage({ error: err.stack || err.message }); + } + }); +} + +async function roundTripViaWorker(key) { + const worker = new Worker( + `'use strict';(${workerMain.toString()})()`, { eval: true }); worker.postMessage({ key, expectedType: key.type }); const [msg] = await once(worker, 'message');