Skip to content

Commit 29b7d15

Browse files
committed
refactor: enhance encryption validation and update key handling in EncryptedHandler
1 parent 9d16be0 commit 29b7d15

File tree

1 file changed

+16
-6
lines changed

1 file changed

+16
-6
lines changed

packages/runtime/src/enhancements/node/encrypted.ts

Lines changed: 16 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,6 @@
1+
/* eslint-disable @typescript-eslint/no-explicit-any */
2+
/* eslint-disable @typescript-eslint/no-unused-vars */
3+
14
import {
25
FieldInfo,
36
NestedWriteVisitor,
@@ -37,13 +40,20 @@ class EncryptedHandler extends DefaultPrismaProxyHandler {
3740
super(prisma, model, options);
3841

3942
this.queryUtils = new QueryUtils(prisma, options);
43+
44+
if (!options.encryption) throw new Error('Encryption options must be provided');
45+
46+
if (this.isCustomEncryption(options.encryption!)) {
47+
if (!options.encryption.encrypt || !options.encryption.decrypt)
48+
throw new Error('Custom encryption must provide encrypt and decrypt functions');
49+
} else {
50+
if (!options.encryption.encryptionKey) throw new Error('Encryption key must be provided');
51+
if (options.encryption.encryptionKey.length !== 32) throw new Error('Encryption key must be 32 bytes');
52+
}
4053
}
4154

42-
private async getKey(secret: string): Promise<CryptoKey> {
43-
return crypto.subtle.importKey('raw', this.encoder.encode(secret).slice(0, 32), 'AES-GCM', false, [
44-
'encrypt',
45-
'decrypt',
46-
]);
55+
private async getKey(secret: Uint8Array): Promise<CryptoKey> {
56+
return crypto.subtle.importKey('raw', secret, 'AES-GCM', false, ['encrypt', 'decrypt']);
4757
}
4858

4959
private isCustomEncryption(encryption: CustomEncryption | SimpleEncryption): encryption is CustomEncryption {
@@ -82,7 +92,7 @@ class EncryptedHandler extends DefaultPrismaProxyHandler {
8292
const key = await this.getKey(this.options.encryption!.encryptionKey);
8393

8494
// Convert base64 back to bytes
85-
const bytes = Uint8Array.from(atob(data));
95+
const bytes = Uint8Array.from(atob(data), (c) => c.charCodeAt(0));
8696

8797
// First 12 bytes are IV, rest is encrypted data
8898
const decrypted = await crypto.subtle.decrypt(

0 commit comments

Comments
 (0)