Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 18 additions & 7 deletions packages/utilities/src/hmac.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,11 +37,22 @@ export function createHmacSignature(secretKey: string, message: string): string
return encodeBase62(BigInt(`0x${signature}`));
}

let webcrypto = globalThis.crypto?.subtle;
let subtleCrypto = globalThis.crypto?.subtle;

async function ensureCryptoSubtleExists() {
// this might happen in Node.js versions < 19
webcrypto ??= (await import('node:crypto')).webcrypto.subtle as typeof webcrypto;
async function ensureSubtleCryptoExists() {
if (!subtleCrypto) {
if (globalThis.require) {
subtleCrypto = globalThis.require('node:crypto')?.webcrypto?.subtle;
} else {
subtleCrypto = (await import('node:crypto'))?.webcrypto?.subtle as SubtleCrypto;
}

if (!subtleCrypto) {
throw new Error(`SubtleCrypto is not available in this environment.
Please ensure you're running in an environment that supports Web Crypto API,
or submit an issue to https://github.com/apify/apify-shared-js so we can help you further.`);
}
}
}

/**
Expand All @@ -53,18 +64,18 @@ async function ensureCryptoSubtleExists() {
* @returns Promise<string>
*/
export async function createHmacSignatureAsync(secretKey: string, message: string): Promise<string> {
await ensureCryptoSubtleExists();
await ensureSubtleCryptoExists();
const encoder = new TextEncoder();

const key = await webcrypto.importKey(
const key = await subtleCrypto.importKey(
'raw',
encoder.encode(secretKey),
{ name: 'HMAC', hash: 'SHA-256' },
false,
['sign'],
);

const signatureBuffer = await webcrypto.sign(
const signatureBuffer = await subtleCrypto.sign(
'HMAC',
key,
encoder.encode(message),
Expand Down