Skip to content

Commit 6e48492

Browse files
committed
fix: adapt Vitest crypto inputs for Node 20
Normalize cross-realm BufferSource values in the jsdom Web Crypto adapter. Assisted-by: GitHub Copilot
1 parent 61e2a73 commit 6e48492

1 file changed

Lines changed: 17 additions & 8 deletions

File tree

‎tests/ts/setup.ts‎

Lines changed: 17 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -24,16 +24,25 @@ if (typeof window !== "undefined" && !window.matchMedia) {
2424
});
2525
}
2626

27-
// jsdom 24+ ships ``window.crypto.subtle``; older versions don't. We only
28-
// need the ``digest`` method for the trust-store hashing tests.
29-
if (
30-
typeof window !== "undefined" &&
31-
(!window.crypto || !window.crypto.subtle)
32-
) {
33-
// Lazy-import the Node implementation. ``webcrypto`` is available since
34-
// Node 18.
27+
// Node 20 Web Crypto rejects BufferSource values created in jsdom's realm.
28+
// Adapt digest inputs to a native Buffer while keeping browser semantics.
29+
if (typeof window !== "undefined") {
3530
// eslint-disable-next-line @typescript-eslint/no-require-imports
3631
const { webcrypto } = require("node:crypto");
32+
const nativeDigest = webcrypto.subtle.digest.bind(webcrypto.subtle);
33+
Object.defineProperty(webcrypto.subtle, "digest", {
34+
value: (algorithm: AlgorithmIdentifier, data: BufferSource) => {
35+
const bytes = ArrayBuffer.isView(data)
36+
? Buffer.from(data.buffer, data.byteOffset, data.byteLength)
37+
: Buffer.from(data);
38+
return nativeDigest(algorithm, bytes);
39+
},
40+
configurable: true,
41+
});
42+
Object.defineProperty(globalThis, "crypto", {
43+
value: webcrypto,
44+
configurable: true,
45+
});
3746
Object.defineProperty(window, "crypto", {
3847
value: webcrypto,
3948
configurable: true,

0 commit comments

Comments
 (0)