Search code examples
rustwebassemblypolyfillscloudflare-workers

How to polyfill performance.now in Rust WebAssembly


I am trying to use the jwt_simple library in a cloudflare workers webassembly runtime. Following the basic example in the linked documentation, everything works fine up until key.authenticate(claims)? is executed, at which point the following stack trace is generated in my terminal running wrangler:

ReferenceError: performance is not defined
    at __wbg_now_63f780680ee9cc56 (./index_bg.mjs:331:15)
    at wasm://wasm/001926f2:wasm-function[264]:0x252a9
    at wasm://wasm/001926f2:wasm-function[409]:0x2925d
    at wasm://wasm/001926f2:wasm-function[167]:0x1fb99
    at wasm://wasm/001926f2:wasm-function[410]:0x292b9
    at wasm://wasm/001926f2:wasm-function[284]:0x25ea0
    at wasm://wasm/001926f2:wasm-function[132]:0x1cbd9
    at wasm://wasm/001926f2:wasm-function[38]:0x9bbc
    at wasm://wasm/001926f2:wasm-function[143]:0x1dc3b
    at wasm://wasm/001926f2:wasm-function[106]:0x19ccb at line 330, col 13

I suspect this is because when key.authenticate is trying to verify the jwt is still valid it calls performance.now, which as per this forum post is not provided by cloudflare workers to prevent timing attacks. I don't fully understand how webassembly works, but I do know that I can polyfill performance.now in javascript as is done here.

How could I use this polyfill in a webassembly environment?


Solution

  • Replace all instances of performace.now() after the file builds:

    $ sed -i '' 's/performance.now()/Date.now()/' index_bg.mjs