Skip to content

Commit 1c55aa5

Browse files
authored
fix: dynamic require imports for crypto package in HMAC signature function (#572)
Uses synchronous `require` imports where available to improve compatibility with older Node versions and test frameworks. See failing Jest test in [Node 16](https://github.com/apify/apify-client-js/actions/runs/19298598492/job/55186768541?pr=782#step:6:98) and [Node 18](https://github.com/apify/apify-client-js/actions/runs/19298598492/job/55186768526?pr=782#step:6:347).
1 parent 73ff70a commit 1c55aa5

File tree

1 file changed

+18
-7
lines changed

1 file changed

+18
-7
lines changed

packages/utilities/src/hmac.ts

Lines changed: 18 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -37,11 +37,22 @@ export function createHmacSignature(secretKey: string, message: string): string
3737
return encodeBase62(BigInt(`0x${signature}`));
3838
}
3939

40-
let webcrypto = globalThis.crypto?.subtle;
40+
let subtleCrypto = globalThis.crypto?.subtle;
4141

42-
async function ensureCryptoSubtleExists() {
43-
// this might happen in Node.js versions < 19
44-
webcrypto ??= (await import('node:crypto')).webcrypto.subtle as typeof webcrypto;
42+
async function ensureSubtleCryptoExists() {
43+
if (!subtleCrypto) {
44+
if (globalThis.require) {
45+
subtleCrypto = globalThis.require('node:crypto')?.webcrypto?.subtle;
46+
} else {
47+
subtleCrypto = (await import('node:crypto'))?.webcrypto?.subtle as SubtleCrypto;
48+
}
49+
50+
if (!subtleCrypto) {
51+
throw new Error(`SubtleCrypto is not available in this environment.
52+
Please ensure you're running in an environment that supports Web Crypto API,
53+
or submit an issue to https://github.com/apify/apify-shared-js so we can help you further.`);
54+
}
55+
}
4556
}
4657

4758
/**
@@ -53,18 +64,18 @@ async function ensureCryptoSubtleExists() {
5364
* @returns Promise<string>
5465
*/
5566
export async function createHmacSignatureAsync(secretKey: string, message: string): Promise<string> {
56-
await ensureCryptoSubtleExists();
67+
await ensureSubtleCryptoExists();
5768
const encoder = new TextEncoder();
5869

59-
const key = await webcrypto.importKey(
70+
const key = await subtleCrypto.importKey(
6071
'raw',
6172
encoder.encode(secretKey),
6273
{ name: 'HMAC', hash: 'SHA-256' },
6374
false,
6475
['sign'],
6576
);
6677

67-
const signatureBuffer = await webcrypto.sign(
78+
const signatureBuffer = await subtleCrypto.sign(
6879
'HMAC',
6980
key,
7081
encoder.encode(message),

0 commit comments

Comments
 (0)