Cloudflare DevelopersCD
Cloudflare Developersโ€ข2y agoโ€ข
7 replies
q_p

TypeScript node:crypto timingSafeEqual function not found

I'm trying to implement Twitch EventSub webhook handler in my Worker based on Twitch example code https://dev.twitch.tv/docs/eventsub/handling-webhook-events/#simple-nodejs-example

It uses
crypto
library functions
createHmac
and
timingSafeEqual


Reading cloudflare docs I understood that I need to use
node:crypto
and the docs says that both
createHmac
and
timingSafeEqual
are supported in https://developers.cloudflare.com/workers/runtime-apis/nodejs/crypto/

So I created a new worker project as described here https://developers.cloudflare.com/workers/get-started/guide/#1-create-a-new-worker-project
by running
npm create cloudflare@latest
and selecting
"Hello World" Worker
as template and
Yes
for TypeScript support

I then modified
src/index.ts
(didn't change anything else) for testing purposes with this:

import { createHmac, timingSafeEqual } from 'node:crypto';
import { Buffer } from 'node:buffer';

// Prepend this string to the HMAC that's created from the message
const HMAC_PREFIX = 'sha256=';

// Verify whether our hash matches the hash that Twitch passed in the header.
function verifyMessage(hmac, verifySignature) {
    return timingSafeEqual(Buffer.from(hmac), Buffer.from(verifySignature));
}

export default {
    async fetch(request: Request, env: Env, ctx: ExecutionContext): Promise<Response> {
        const hmac = HMAC_PREFIX + createHmac('sha256', 'MySecret')
            .update('MyMessage')
            .digest('hex');

        if (verifyMessage(hmac, hmac)) {
            console.log('timingSafeEqual true');
        } else {
            console.log('timingSafeEqual false');
        }

        return new Response('');
    }
};

Then I ran
npm run start
and opened the local worker page, but in console I see this:
[wrangler:err] TypeError: timingSafeEqual is not a function


Why? The documenation says that
timingSafeEqual
is supported. Am I missing something?
Was this page helpful?