Unverified Commit e570ad4e authored by Wojciech Grzebieniowski's avatar Wojciech Grzebieniowski Committed by GitHub

Fix Node Crypto polyfill (#49288)

### 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: 's avatarTim Neutkens <tim@timneutkens.nl>
parent 04799216
/* 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)
})
})
// 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
},
})
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment