miniflare
miniflare copied to clipboard
Typescript libsodium-wrapper return promise rejection
bindings.d.ts
required to set window
and importScript
global to undefined in order to load libsodium wasm correctly
export {};
declare global {
const USERS: KVNamespace;
var window: any;
var importScripts: any;
}
index.ts
import libsodium from 'libsodium-wrappers';
import { handleRequest } from './handler'
addEventListener('fetch', (event) => {
globalThis.window = undefined;
globalThis.importScripts = undefined;
await libsodium.ready;
event.respondWith(handleRequest(event.request))
})
miniflare
console response
[mf:inf] Listening on :8787
[mf:inf] - http://127.0.0.1:8787
[mf:inf] - http://172.27.186.253:8787
[mf:inf] - http://172.19.0.1:8787
[mf:inf] - http://172.18.0.1:8787
[mf:err] No secure random number generator found
[mf:err] No secure random number generator found
GET / 500 Internal Server Error (40.13ms)
(node:715) PromiseRejectionHandledWarning: Promise rejection was handled asynchronously (rejection id: 1)
(Use `node --trace-warnings ...` to show where the warning was created)
[mf:err] No secure random number generator found
GET /favicon.ico 500 Internal Server Error (1.81ms)
How ever when I use wrangler dev
everything works as expected
Hey! 👋 Apologies for the delayed response. I've recently returned from a long holiday and am just starting to catch up on issues now.
It looks like libsodium-wrappers
is trying to call crypto.getRandomValues
on import to detect a secure random number generator. Technically, you can only call this inside a request handler (even though you await libsodium.ready
inside the handler, libsodium
starts loading immediately on import). My guess is that due to scheduling in the workers runtime (what you get with wrangler dev
), the getRandomValues
is delayed somehow until the request is dispatched, but in Miniflare, since we immediately load the script when you start the dev server (not when a request comes in), you're seeing this error.
A temporary solution is to allow getRandomValues
outside requests with the --global-random
option.
This issue should be resolved when Miniflare switches to using the recently announced open-source runtime.
Hey! 👋 This should be fixed in Miniflare 3, which uses the same workerd
runtime as production, so shouldn't have these behaviour mismatches. I'm going to close this as it's unlikely we'll have time to fix this in Miniflare 2. Our development effort is primarily focused on version 3.