Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix - Removed import and usage of nodeCrypto when not running on nodejs #3296

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 6 additions & 15 deletions packages/pg/lib/crypto/utils-webcrypto.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
const nodeCrypto = require('crypto')

module.exports = {
postgresMd5PasswordHash,
randomBytes,
Expand All @@ -13,7 +11,7 @@ module.exports = {
* The Web Crypto API - grabbed from the Node.js library or the global
* @type Crypto
*/
const webCrypto = nodeCrypto.webcrypto || globalThis.crypto
const webCrypto = globalThis.crypto ?? require('node:crypto').webcrypto
/**
* The SubtleCrypto API for low level crypto operations.
* @type SubtleCrypto
Expand All @@ -31,18 +29,11 @@ function randomBytes(length) {
}

async function md5(string) {
try {
return nodeCrypto.createHash('md5').update(string, 'utf-8').digest('hex')
} catch (e) {
// `createHash()` failed so we are probably not in Node.js, use the WebCrypto API instead.
// Note that the MD5 algorithm on WebCrypto is not available in Node.js.
// This is why we cannot just use WebCrypto in all environments.
const data = typeof string === 'string' ? textEncoder.encode(string) : string
const hash = await subtleCrypto.digest('MD5', data)
return Array.from(new Uint8Array(hash))
.map((b) => b.toString(16).padStart(2, '0'))
.join('')
}
const data = typeof string === 'string' ? textEncoder.encode(string) : string
const hash = await subtleCrypto.digest('MD5', data)
return Array.from(new Uint8Array(hash))
.map((b) => b.toString(16).padStart(2, '0'))
.join('')
}

// See AuthenticationMD5Password at https://www.postgresql.org/docs/current/static/protocol-flow.html
Expand Down
3 changes: 1 addition & 2 deletions packages/pg/lib/crypto/utils.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
'use strict'

const useLegacyCrypto = parseInt(process.versions && process.versions.node && process.versions.node.split('.')[0]) < 15
const useLegacyCrypto = parseInt(process.versions && process.versions.node && process.versions.node.split('.')[0]) < 22
if (useLegacyCrypto) {
// We are on an old version of Node.js that requires legacy crypto utilities.
module.exports = require('./utils-legacy')
Expand Down
Loading