From 09e6cb5247c514e5cf50faced6452fae956edeb9 Mon Sep 17 00:00:00 2001 From: Alex Robinson Date: Fri, 13 Oct 2023 16:39:00 -0500 Subject: [PATCH] Update Cloudflare createHash polyfill to support md5 and hex encoding Since the md5 method in cf/src/connection.js expects to be able to call crypto.createHash('md5').update(x).digest('hex') This was causing md5 password auth to hang when used from a Cloudflare worker, but now I've confirmed md5 password auth works. --- cf/polyfills.js | 23 ++++++++++++++++++----- 1 file changed, 18 insertions(+), 5 deletions(-) diff --git a/cf/polyfills.js b/cf/polyfills.js index f7809003..53c5203d 100644 --- a/cf/polyfills.js +++ b/cf/polyfills.js @@ -47,12 +47,25 @@ export const crypto = { ), createHash: type => ({ update: x => ({ - digest: () => { - if (type !== 'sha256') - throw Error('createHash only supports sha256 in this environment.') - if (!(x instanceof Uint8Array)) + digest: encoding => { + if (!(x instanceof Uint8Array)) { x = textEncoder.encode(x) - return Crypto.subtle.digest('SHA-256', x) + } + let prom + if (type === 'sha256') { + prom = Crypto.subtle.digest('SHA-256', x) + } else if (type === 'md5') { + prom = Crypto.subtle.digest('md5', x) + } else { + throw Error('createHash only supports sha256 or md5 in this environment, not ${type}.') + } + if (encoding === 'hex') { + return prom.then((arrayBuf) => Buffer.from(arrayBuf).toString('hex')) + } else if (encoding) { + throw Error(`createHash only supports hex encoding or unencoded in this environment, not ${encoding}`) + } else { + return prom + } } }) }),