Skip to content

Commit

Permalink
Fix Node Crypto polyfill (#49288)
Browse files Browse the repository at this point in the history
### What?

Allow overwriting the `global.crypto` property when polyfilling it.

### Why?

#48941 introduced `global.crypto` polyfill. The problem is that if some
library (e.g.
[xksuid](https://github.com/ValeriaVG/xksuid/blob/main/src/index.node.mjs))
tries to do the same thing, it breaks as `global.crypto` is defined as
non-writable[^1]. Arguably libraries should check for `global.crypto`
presence before overwriting it BUT I think polyfill should match the
actual implementation[^2].



### How?

Make `global.crypto` `enumerable` and `configurable`, as well as define
`set` implementation[^3].

[^1]:
![image](https://user-images.githubusercontent.com/7079786/236440322-7bcf1b18-8fcc-4bb9-b9b4-0f2eb032f5ba.png)

[^2]:
![image](https://user-images.githubusercontent.com/7079786/236437260-d3abdb0c-134f-4c9d-aab8-de7bf4d7c831.png)

[^3]:
![image](https://user-images.githubusercontent.com/7079786/236440393-1c469035-a9f1-4fbe-9ce7-c0308e980510.png)

---------

Co-authored-by: Tim Neutkens <tim@timneutkens.nl>
  • Loading branch information
g12i and timneutkens committed May 9, 2023
1 parent 0479921 commit e570ad4
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 5 deletions.
11 changes: 11 additions & 0 deletions packages/next/src/server/node-polyfill-crypto.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
/* eslint-env jest */
import './node-polyfill-crypto'

describe('node-polyfill-crypto', () => {
test('overwrite crypto', async () => {
expect(global.crypto).not.toBeUndefined()
const a = {} as Crypto
global.crypto = a
expect(global.crypto).toBe(a)
})
})
17 changes: 12 additions & 5 deletions packages/next/src/server/node-polyfill-crypto.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,19 @@
// Polyfill crypto() in the Node.js environment

if (!(global as any).crypto) {
function getCryptoImpl() {
return require('node:crypto').webcrypto
}
if (!global.crypto) {
let webcrypto: Crypto | undefined

Object.defineProperty(global, 'crypto', {
enumerable: false,
configurable: true,
get() {
return getCryptoImpl()
if (!webcrypto) {
webcrypto = require('node:crypto').webcrypto
}
return webcrypto
},
set(value: Crypto) {
webcrypto = value
},
})
}

0 comments on commit e570ad4

Please sign in to comment.