Skip to content

Commit

Permalink
fix(vm): make sure instanceof checks for ArrayBuffer work when using …
Browse files Browse the repository at this point in the history
…crypto

This fixes #62
  • Loading branch information
Schniz committed Aug 2, 2022
1 parent 29de2c5 commit 17475e4
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 1 deletion.
22 changes: 21 additions & 1 deletion packages/vm/src/edge-vm.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import type { VMContext, VMOptions } from './vm'
import { Buffer } from 'buffer'
import { requireWithCache } from './require'
import { VM } from './vm'
import { runInContext } from 'vm'

export interface EdgeVMOptions<T> {
/**
Expand Down Expand Up @@ -236,7 +237,26 @@ function addPrimitives(context: VMContext) {
['process', { exports: require('process') }],
]),
path: require.resolve('@edge-runtime/primitives/crypto'),
scopedContext: { Buffer },
scopedContext: {
Buffer,
Uint8Array: new Proxy(runInContext('Uint8Array', context), {
// on every construction (new Uint8Array(...))
construct(target, args) {
// construct it
const value: Uint8Array = new target(...args)

// if this is not a buffer
if (!(args[0] instanceof Buffer)) {
// return what we just constructed
return value
}

// if it is a buffer, then we spread the binary data into an array,
// and build the Uint8Array from that
return new target([...value])
},
}),
},
}),
enumerable: ['crypto'],
nonenumerable: ['Crypto', 'CryptoKey', 'SubtleCrypto'],
Expand Down
18 changes: 18 additions & 0 deletions packages/vm/tests/integration/crypto.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { EdgeVM } from '../../src'

test('crypto.subtle.digest returns an ArrayBuffer', async () => {
const vm = new EdgeVM()

async function fn() {
const digest = await crypto.subtle.digest(
'SHA-256',
crypto.getRandomValues(new Uint8Array(32))
)
return digest
}

const fromContext = vm.evaluate(`({ ArrayBuffer })`)

const digest = await vm.evaluate(`(${fn})()`)
expect(digest).toBeInstanceOf(fromContext.ArrayBuffer)
})

0 comments on commit 17475e4

Please sign in to comment.