unjs / unenv

🕊️ Convert javaScript code to be runtime agnostic
MIT License
340 stars 18 forks source link

crypto.randomBytes() always returns 0 #277

Open yuetloo opened 6 days ago

yuetloo commented 6 days ago

Environment

"unenv": 1.9.0 node: v20.11.0

Reproduction

Polyfill a Nuxt app using

// nuxt.config.ts
import { env, nodeless } from 'unenv'
const { alias } = env(nodeless, {})

export default defineNuxtConfig({
  vite: {
    define: {
      global: 'globalThis',
    },
    resolve: {
      alias: {
        'node:buffer': alias['node:buffer'],
        crypto: alias['crypto'],
        stream: alias['stream'],
        http: alias['http'],
        https: alias['https'],
        zlib: alias['zlib'],
      },
    },
  },
})
// app.vue
import { randomBytes } from 'crypto'

const rand = randomBytes(32)
for(const num of rand) {
   console.log(num)
}

Describe the bug

Uint8Array.slice in the following line does not update the bytes buffer, use subArray instead as changes to the new array will update the original array.

https://github.com/unjs/unenv/blob/main/src/runtime/node/crypto/internal/node.ts#L44

    getRandomValues(
      Uint8Array.prototype.slice.call(
        bytes,
        generated,
        generated + MAX_RANDOM_VALUE_BYTES,
      ),
    );

Additional context

No response

Logs

No response