generated from 47ng/typescript-library-starter
-
-
Notifications
You must be signed in to change notification settings - Fork 30
/
Copy pathencryption.ts
247 lines (231 loc) · 7.37 KB
/
encryption.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
import {
cloakedStringRegex,
CloakKeychain,
decryptStringSync,
encryptStringSync,
findKeyForMessage,
makeKeychainSync,
ParsedCloakKey,
parseKeySync
} from '@47ng/cloak'
import { Draft, produce } from 'immer'
import objectPath from 'object-path'
import { debug } from './debugger'
import type { DMMFModels } from './dmmf'
import { errors, warnings } from './errors'
import { hashString } from './hash'
import type { Configuration, MiddlewareParams } from './types'
import { visitInputTargetFields, visitOutputTargetFields } from './visitor'
export interface KeysConfiguration {
encryptionKey: ParsedCloakKey
keychain: CloakKeychain
}
export function configureKeys(config: Configuration): KeysConfiguration {
const encryptionKey =
config.encryptionKey || process.env.PRISMA_FIELD_ENCRYPTION_KEY
if (!encryptionKey) {
throw new Error(errors.noEncryptionKey)
}
const decryptionKeysFromEnv = (process.env.PRISMA_FIELD_DECRYPTION_KEYS ?? '')
.split(',')
.filter(Boolean)
const decryptionKeys: string[] = Array.from(
new Set([
encryptionKey,
...(config.decryptionKeys ?? decryptionKeysFromEnv)
])
)
const keychain = makeKeychainSync(decryptionKeys)
return {
encryptionKey: parseKeySync(encryptionKey),
keychain
}
}
// --
export function encryptOnWrite<Models extends string, Actions extends string>(
params: MiddlewareParams<Models, Actions>,
keys: KeysConfiguration,
models: DMMFModels,
operation: string
) {
debug.encryption('Clear-text input: %O', params)
const encryptionErrors: string[] = []
const mutatedParams = produce(
params,
(draft: Draft<MiddlewareParams<Models, Actions>>) => {
visitInputTargetFields(
draft,
models,
function encryptFieldValue({
fieldConfig,
value: clearText,
path,
model,
field
}) {
const hashedPath = rewriteHashedFieldPath(
path,
field,
fieldConfig.hash?.targetField ?? field + 'Hash'
)
if (hashedPath) {
if (!fieldConfig.hash) {
console.warn(warnings.whereConnectClauseNoHash(operation, path))
} else {
const hash = hashString(clearText, fieldConfig.hash)
debug.encryption(
`Swapping encrypted search of ${model}.${field} with hash search under ${fieldConfig.hash.targetField} (hash: ${hash})`
)
objectPath.del(draft.args, path)
objectPath.set(draft.args, hashedPath, hash)
return
}
}
if (isOrderBy(path, field, clearText)) {
// Remove unsupported orderBy clause on encrypted text
// (makes no sense to sort ciphertext nor to encrypt 'asc' | 'desc')
console.error(errors.orderByUnsupported(model, field))
debug.encryption(
`Removing orderBy clause on ${model}.${field} at path \`${path}: ${clearText}\``
)
objectPath.del(draft.args, path)
return
}
if (!fieldConfig.encrypt) {
return
}
try {
const cipherText = encryptStringSync(clearText, keys.encryptionKey)
objectPath.set(draft.args, path, cipherText)
debug.encryption(`Encrypted ${model}.${field} at path \`${path}\``)
if (fieldConfig.hash) {
const hash = hashString(clearText, fieldConfig.hash)
const hashPath = rewriteWritePath(
path,
field,
fieldConfig.hash.targetField
)
objectPath.set(draft.args, hashPath, hash)
debug.encryption(
`Added hash ${hash} of ${model}.${field} under ${fieldConfig.hash.targetField}`
)
}
} catch (error) {
encryptionErrors.push(
errors.fieldEncryptionError(model, field, path, error)
)
}
}
)
}
)
if (encryptionErrors.length > 0) {
throw new Error(errors.encryptionErrorReport(operation, encryptionErrors))
}
debug.encryption('Encrypted input: %O', mutatedParams)
return mutatedParams
}
export function decryptOnRead<Models extends string, Actions extends string>(
params: MiddlewareParams<Models, Actions>,
result: any,
keys: KeysConfiguration,
models: DMMFModels,
operation: string
) {
// Analyse the query to see if there's anything to decrypt.
const model = models[params.model!]
if (
Object.keys(model.fields).length === 0 &&
!params.args?.include &&
!params.args?.select
) {
// The queried model doesn't have any encrypted field,
// and there are no included connections.
// We can safely skip decryption for the returned data.
// todo: Walk the include/select tree for a better decision.
debug.decryption(
`Skipping decryption: ${params.model} has no encrypted field and no connection was included`
)
return
}
debug.decryption('Raw result from database: %O', result)
const decryptionErrors: string[] = []
const fatalDecryptionErrors: string[] = []
visitOutputTargetFields(
params,
result,
models,
function decryptFieldValue({
fieldConfig,
value: cipherText,
path,
model,
field
}) {
try {
if (!cloakedStringRegex.test(cipherText)) {
return
}
const decryptionKey = findKeyForMessage(cipherText, keys.keychain)
const clearText = decryptStringSync(cipherText, decryptionKey)
objectPath.set(result, path, clearText)
debug.decryption(
`Decrypted ${model}.${field} at path \`${path}\` using key fingerprint ${decryptionKey.fingerprint}`
)
} catch (error) {
const message = errors.fieldDecryptionError(model, field, path, error)
if (fieldConfig.strictDecryption) {
fatalDecryptionErrors.push(message)
} else {
decryptionErrors.push(message)
}
}
}
)
if (decryptionErrors.length > 0) {
console.error(errors.decryptionErrorReport(operation, decryptionErrors))
}
if (fatalDecryptionErrors.length > 0) {
throw new Error(
errors.decryptionErrorReport(operation, fatalDecryptionErrors)
)
}
debug.decryption('Decrypted result: %O', result)
}
function rewriteHashedFieldPath(
path: string,
field: string,
hashField: string
) {
const items = path.split('.').reverse()
// Special case for `where field equals or not` clause
if (items.includes('where') && items[1] === field && ['equals', 'not'].includes(items[0])) {
items[1] = hashField
return items.reverse().join('.')
}
const clauses = ['where', 'connect', 'cursor']
for (const clause of clauses) {
if (items.includes(clause) && items[0] === field) {
items[0] = hashField
return items.reverse().join('.')
}
}
return null
}
function rewriteWritePath(path: string, field: string, hashField: string) {
const items = path.split('.').reverse()
if (items[0] === field) {
items[0] = hashField
} else if (items[0] === 'set' && items[1] === field) {
items[1] = hashField
}
return items.reverse().join('.')
}
function isOrderBy(path: string, field: string, value: string) {
const items = path.split('.').reverse()
return (
items.includes('orderBy') &&
items[0] === field &&
['asc', 'desc'].includes(value.toLowerCase())
)
}