47ng / prisma-field-encryption

Transparent field-level encryption at rest for Prisma
https://github.com/franky47/prisma-field-encryption-sandbox
MIT License
223 stars 27 forks source link

Configuration option to use web-crypto instead of node crypto for Cloudflare Workers #70

Closed polaroidkidd closed 11 months ago

polaroidkidd commented 11 months ago

Hi

First of all, thanks for this amazing library. I'm using it in conjunction with SvelteKit, Prisma (hooked up to a neon db) and lucia-auth along side an upstash redis instance. The whole thing should be deployed to Cloudflare Workers at the end of the day.

However, using the SvelteKit Cloudlfare Adapter Plugin uses the Cloudflare version of Node, which is much closer to browsers than node, the build fails because they don't have the crypto package. Instead we'd have to use the web-crypto API.

I could spend some time on this and code it up, but my relationship with security is the same as it is with electricity.

I know enough about it that I don't know enough about it.

franky47 commented 11 months ago

This could probably be done in a config-free manner, by detecting if the WebCrypto API is available, with a fallback to the Node.js sync APIs from node:crypto.

The main issue is that at the moment everything (encryption, decryption & hashing) assumes a sync/blocking API. The core functionality would have to be converted to an async function to support async crypto, which may be a bit of work.

As a side note on the performance side - which would have to be measured - I've got a feeling going async would bring some Promise allocation overhead per query that would only be compensated on very large encryption operations.

franky47 commented 11 months ago

After doing a quick test, it would require a complete rewrite of the library to allow for async encryption operations to support non-Node.js runtimes through the WebCrypto API.

Moreover, there is a 10x performance hit by going async for small to medium encryption input sizes, which decreases with length, as expected.(run ts-node ./src/tests/crypto.benchmark.ts).

I'll file this one as a wontfix for now, if there is enough traction behind it and performance-worthy solutions can be found, then I'll happily reopen and review PRs.

polaroidkidd commented 11 months ago

ah, understandable. Thanks for looking into it regardless!