|
| 1 | +/* eslint-disable @typescript-eslint/no-explicit-any */ |
| 2 | +/* eslint-disable @typescript-eslint/no-unused-vars */ |
| 3 | + |
| 4 | +import { |
| 5 | + FieldInfo, |
| 6 | + NestedWriteVisitor, |
| 7 | + enumerate, |
| 8 | + getModelFields, |
| 9 | + resolveField, |
| 10 | + type PrismaWriteActionType, |
| 11 | +} from '../../cross'; |
| 12 | +import { DbClientContract, CustomEncryption, SimpleEncryption } from '../../types'; |
| 13 | +import { InternalEnhancementOptions } from './create-enhancement'; |
| 14 | +import { DefaultPrismaProxyHandler, PrismaProxyActions, makeProxy } from './proxy'; |
| 15 | +import { QueryUtils } from './query-utils'; |
| 16 | + |
| 17 | +/** |
| 18 | + * Gets an enhanced Prisma client that supports `@encrypted` attribute. |
| 19 | + * |
| 20 | + * @private |
| 21 | + */ |
| 22 | +export function withEncrypted<DbClient extends object = any>( |
| 23 | + prisma: DbClient, |
| 24 | + options: InternalEnhancementOptions |
| 25 | +): DbClient { |
| 26 | + return makeProxy( |
| 27 | + prisma, |
| 28 | + options.modelMeta, |
| 29 | + (_prisma, model) => new EncryptedHandler(_prisma as DbClientContract, model, options), |
| 30 | + 'encrypted' |
| 31 | + ); |
| 32 | +} |
| 33 | + |
| 34 | +class EncryptedHandler extends DefaultPrismaProxyHandler { |
| 35 | + private queryUtils: QueryUtils; |
| 36 | + private encoder = new TextEncoder(); |
| 37 | + private decoder = new TextDecoder(); |
| 38 | + |
| 39 | + constructor(prisma: DbClientContract, model: string, options: InternalEnhancementOptions) { |
| 40 | + super(prisma, model, options); |
| 41 | + |
| 42 | + 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 | + } |
| 53 | + } |
| 54 | + |
| 55 | + private async getKey(secret: Uint8Array): Promise<CryptoKey> { |
| 56 | + return crypto.subtle.importKey('raw', secret, 'AES-GCM', false, ['encrypt', 'decrypt']); |
| 57 | + } |
| 58 | + |
| 59 | + private isCustomEncryption(encryption: CustomEncryption | SimpleEncryption): encryption is CustomEncryption { |
| 60 | + return 'encrypt' in encryption && 'decrypt' in encryption; |
| 61 | + } |
| 62 | + |
| 63 | + private async encrypt(field: FieldInfo, data: string): Promise<string> { |
| 64 | + if (this.isCustomEncryption(this.options.encryption!)) { |
| 65 | + return this.options.encryption.encrypt(this.model, field, data); |
| 66 | + } |
| 67 | + |
| 68 | + const key = await this.getKey(this.options.encryption!.encryptionKey); |
| 69 | + const iv = crypto.getRandomValues(new Uint8Array(12)); |
| 70 | + |
| 71 | + const encrypted = await crypto.subtle.encrypt( |
| 72 | + { |
| 73 | + name: 'AES-GCM', |
| 74 | + iv, |
| 75 | + }, |
| 76 | + key, |
| 77 | + this.encoder.encode(data) |
| 78 | + ); |
| 79 | + |
| 80 | + // Combine IV and encrypted data into a single array of bytes |
| 81 | + const bytes = [...iv, ...new Uint8Array(encrypted)]; |
| 82 | + |
| 83 | + // Convert bytes to base64 string |
| 84 | + return btoa(String.fromCharCode(...bytes)); |
| 85 | + } |
| 86 | + |
| 87 | + private async decrypt(field: FieldInfo, data: string): Promise<string> { |
| 88 | + if (this.isCustomEncryption(this.options.encryption!)) { |
| 89 | + return this.options.encryption.decrypt(this.model, field, data); |
| 90 | + } |
| 91 | + |
| 92 | + const key = await this.getKey(this.options.encryption!.encryptionKey); |
| 93 | + |
| 94 | + // Convert base64 back to bytes |
| 95 | + const bytes = Uint8Array.from(atob(data), (c) => c.charCodeAt(0)); |
| 96 | + |
| 97 | + // First 12 bytes are IV, rest is encrypted data |
| 98 | + const decrypted = await crypto.subtle.decrypt( |
| 99 | + { |
| 100 | + name: 'AES-GCM', |
| 101 | + iv: bytes.slice(0, 12), |
| 102 | + }, |
| 103 | + key, |
| 104 | + bytes.slice(12) |
| 105 | + ); |
| 106 | + |
| 107 | + return this.decoder.decode(decrypted); |
| 108 | + } |
| 109 | + |
| 110 | + // base override |
| 111 | + protected async preprocessArgs(action: PrismaProxyActions, args: any) { |
| 112 | + const actionsOfInterest: PrismaProxyActions[] = ['create', 'createMany', 'update', 'updateMany', 'upsert']; |
| 113 | + if (args && args.data && actionsOfInterest.includes(action)) { |
| 114 | + await this.preprocessWritePayload(this.model, action as PrismaWriteActionType, args); |
| 115 | + } |
| 116 | + return args; |
| 117 | + } |
| 118 | + |
| 119 | + // base override |
| 120 | + protected async processResultEntity<T>(method: PrismaProxyActions, data: T): Promise<T> { |
| 121 | + if (!data || typeof data !== 'object') { |
| 122 | + return data; |
| 123 | + } |
| 124 | + |
| 125 | + for (const value of enumerate(data)) { |
| 126 | + await this.doPostProcess(value, this.model); |
| 127 | + } |
| 128 | + |
| 129 | + return data; |
| 130 | + } |
| 131 | + |
| 132 | + private async doPostProcess(entityData: any, model: string) { |
| 133 | + const realModel = this.queryUtils.getDelegateConcreteModel(model, entityData); |
| 134 | + |
| 135 | + for (const field of getModelFields(entityData)) { |
| 136 | + const fieldInfo = await resolveField(this.options.modelMeta, realModel, field); |
| 137 | + |
| 138 | + if (!fieldInfo) { |
| 139 | + continue; |
| 140 | + } |
| 141 | + |
| 142 | + const shouldDecrypt = fieldInfo.attributes?.find((attr) => attr.name === '@encrypted'); |
| 143 | + if (shouldDecrypt) { |
| 144 | + // Don't decrypt null, undefined or empty string values |
| 145 | + if (!entityData[field]) continue; |
| 146 | + |
| 147 | + try { |
| 148 | + entityData[field] = await this.decrypt(fieldInfo, entityData[field]); |
| 149 | + } catch (error) { |
| 150 | + console.warn('Decryption failed, keeping original value:', error); |
| 151 | + } |
| 152 | + } |
| 153 | + } |
| 154 | + } |
| 155 | + |
| 156 | + private async preprocessWritePayload(model: string, action: PrismaWriteActionType, args: any) { |
| 157 | + const visitor = new NestedWriteVisitor(this.options.modelMeta, { |
| 158 | + field: async (field, _action, data, context) => { |
| 159 | + // Don't encrypt null, undefined or empty string values |
| 160 | + if (!data) return; |
| 161 | + |
| 162 | + const encAttr = field.attributes?.find((attr) => attr.name === '@encrypted'); |
| 163 | + if (encAttr && field.type === 'String') { |
| 164 | + try { |
| 165 | + context.parent[field.name] = await this.encrypt(field, data); |
| 166 | + } catch (error) { |
| 167 | + throw new Error(`Encryption failed for field ${field.name}: ${error}`); |
| 168 | + } |
| 169 | + } |
| 170 | + }, |
| 171 | + }); |
| 172 | + |
| 173 | + await visitor.visit(model, action, args); |
| 174 | + } |
| 175 | +} |
0 commit comments