generated from 47ng/typescript-library-starter
-
-
Notifications
You must be signed in to change notification settings - Fork 34
/
Copy pathencryption.ts
182 lines (162 loc) · 4.47 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
import {
cloakedStringRegex,
CloakKeychain,
decryptStringSync,
encryptStringSync,
findKeyForMessage,
makeKeychainSync,
ParsedCloakKey,
parseKeySync
} from '@47ng/cloak'
import produce, { Draft } from 'immer'
import objectPath from 'object-path'
import type { DMMFModels } from './dmmf'
import { errors, warnings } from './errors'
import type { MiddlewareParams, EncryptionFn, DecryptionFn } from './types'
import { visitInputTargetFields, visitOutputTargetFields } from './visitor'
export interface KeysConfiguration {
encryptionKey: ParsedCloakKey
keychain: CloakKeychain
}
export interface ConfigureKeysParams {
encryptionKey?: string
decryptionKeys?: string[]
}
export function configureKeys(config: ConfigureKeysParams): 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
}
}
// --
const writeOperations = [
'create',
'createMany',
'update',
'updateMany',
'upsert'
]
const whereClauseRegExp = /\.where\./
export function encryptOnWrite(
params: MiddlewareParams,
keys: KeysConfiguration,
models: DMMFModels,
operation: string,
encryptFn?: EncryptionFn
) {
if (!writeOperations.includes(params.action)) {
return params // No input data to encrypt
}
const encryptionErrors: string[] = []
const mutatedParams = produce(params, (draft: Draft<MiddlewareParams>) => {
visitInputTargetFields(
draft,
models,
function encryptFieldValue({
fieldConfig,
value: clearText,
path,
model,
field
}) {
if (!fieldConfig.encrypt) {
return
}
if (whereClauseRegExp.test(path)) {
console.warn(warnings.whereClause(operation, path))
}
try {
const cipherText =
encryptFn !== undefined
? encryptFn(clearText)
: encryptStringSync(clearText, keys.encryptionKey)
objectPath.set(draft.args, path, cipherText)
} catch (error) {
encryptionErrors.push(
errors.fieldEncryptionError(model, field, path, error)
)
}
}
)
})
if (encryptionErrors.length > 0) {
throw new Error(errors.encryptionErrorReport(operation, encryptionErrors))
}
return mutatedParams
}
export function decryptOnRead(
params: MiddlewareParams,
result: any,
keys: KeysConfiguration,
models: DMMFModels,
operation: string,
decryptFn?: DecryptionFn
) {
// 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) {
// 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.
return
}
const decryptionErrors: string[] = []
const fatalDecryptionErrors: string[] = []
visitOutputTargetFields(
params,
result,
models,
function decryptFieldValue({
fieldConfig,
value: cipherText,
path,
model,
field
}) {
try {
if (!decryptFn && !cloakedStringRegex.test(cipherText)) {
return
}
const clearText =
decryptFn !== undefined
? decryptFn(cipherText)
: decryptStringSync(
cipherText,
findKeyForMessage(cipherText, keys.keychain)
)
objectPath.set(result, path, clearText)
} 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.encryptionErrorReport(operation, decryptionErrors))
}
if (fatalDecryptionErrors.length > 0) {
throw new Error(
errors.decryptionErrorReport(operation, fatalDecryptionErrors)
)
}
}