generated from 47ng/typescript-library-starter
-
-
Notifications
You must be signed in to change notification settings - Fork 34
/
Copy pathdmmf.ts
223 lines (209 loc) · 6.62 KB
/
dmmf.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
import type { Encoding } from '@47ng/codec'
import { errors, warnings } from './errors'
import {
DMMFDocument,
dmmfDocumentParser,
FieldConfiguration,
HashFieldConfiguration
} from './types'
export interface ConnectionDescriptor {
modelName: string
isList: boolean
}
export interface DMMFModelDescriptor {
/**
* The field to use to iterate over rows
* in encryption/decryption/key rotation migrations.
*
* See https://github.com/47ng/prisma-field-encryption#migrations
*/
cursor?: string
fields: Record<string, FieldConfiguration> // key: field name
connections: Record<string, ConnectionDescriptor> // key: field name
}
export type DMMFModels = Record<string, DMMFModelDescriptor> // key: model name
const supportedCursorTypes = ['Int', 'String', 'BigInt']
export function analyseDMMF(input: DMMFDocument): DMMFModels {
const dmmf = dmmfDocumentParser.parse(input)
const allModels = [...dmmf.datamodel.models, ...dmmf.datamodel.types];
return allModels.reduce<DMMFModels>((output, model) => {
const idField = model.fields.find(
field => field.isId && supportedCursorTypes.includes(String(field.type))
)
const uniqueField = model.fields.find(
field =>
field.isUnique && supportedCursorTypes.includes(String(field.type))
)
const cursorField = model.fields.find(
field => field.documentation?.includes('@encryption:cursor')
)
if (cursorField) {
// Make sure custom cursor field is valid
if (!cursorField.isUnique) {
throw new Error(errors.nonUniqueCursor(model.name, cursorField.name))
}
if (!supportedCursorTypes.includes(String(cursorField.type))) {
throw new Error(
errors.unsupportedCursorType(
model.name,
cursorField.name,
String(cursorField.type)
)
)
}
if (cursorField.documentation?.includes('@encrypted')) {
throw new Error(errors.encryptedCursor(model.name, cursorField.name))
}
}
const modelDescriptor: DMMFModelDescriptor = {
cursor: cursorField?.name ?? idField?.name ?? uniqueField?.name,
fields: model.fields.reduce<DMMFModelDescriptor['fields']>(
(fields, field) => {
const fieldConfig = parseEncryptedAnnotation(
field.documentation,
model.name,
field.name
)
if (fieldConfig && field.type !== 'String') {
throw new Error(errors.unsupportedFieldType(model, field))
}
return fieldConfig ? { ...fields, [field.name]: fieldConfig } : fields
},
{}
),
connections: model.fields.reduce<DMMFModelDescriptor['connections']>(
(connections, field) => {
const targetModel = allModels.find(model => field.type === model.name)
if (!targetModel) {
return connections
}
const connection: ConnectionDescriptor = {
modelName: targetModel.name,
isList: field.isList
}
return {
...connections,
[field.name]: connection
}
},
{}
)
}
// Inject hash information
model.fields.forEach(field => {
const hashConfig = parseHashAnnotation(
field.documentation,
model.name,
field.name
)
if (!hashConfig) {
return
}
if (field.type !== 'String') {
throw new Error(errors.unsupporteHashFieldType(model, field))
}
const { sourceField, ...hash } = hashConfig
if (!(sourceField in modelDescriptor.fields)) {
throw new Error(
errors.hashSourceFieldNotFound(model, field, sourceField)
)
}
modelDescriptor.fields[hashConfig.sourceField].hash = hash
})
if (
Object.keys(modelDescriptor.fields).length > 0 &&
!modelDescriptor.cursor
) {
console.warn(warnings.noCursorFound(model.name))
}
return {
...output,
[model.name]: modelDescriptor
}
}, {})
}
// --
const encryptedAnnotationRegex = /@encrypted(?<query>\?[\w=&]+)?/
const hashAnnotationRegex =
/@encryption:hash\((?<fieldName>\w+)\)(?<query>\?[\w=&]+)?/
export function parseEncryptedAnnotation(
annotation = '',
model?: string,
field?: string
): FieldConfiguration | null {
const match = annotation.match(encryptedAnnotationRegex)
if (!match) {
return null
}
const query = new URLSearchParams(match.groups?.query ?? '')
const strict = query.get('strict') !== null
const readonly = query.get('readonly') !== null
if (strict && process.env.NODE_ENV === 'development' && model && field) {
console.warn(warnings.deprecatedModeAnnotation(model, field, 'strict'))
}
if (readonly && process.env.NODE_ENV === 'development' && model && field) {
console.warn(warnings.deprecatedModeAnnotation(model, field, 'readonly'))
}
const mode =
query.get('mode') ?? (readonly ? 'readonly' : strict ? 'strict' : 'default')
/* istanbul ignore next */
if (!['default', 'strict', 'readonly'].includes(mode)) {
if (process.env.NODE_ENV === 'development' && model && field) {
console.warn(warnings.unknownFieldModeAnnotation(model, field, mode))
}
}
return {
encrypt: mode !== 'readonly',
strictDecryption: mode === 'strict'
}
}
export function parseHashAnnotation(
annotation = '',
model?: string,
field?: string
): HashFieldConfiguration | null {
const match = annotation.match(hashAnnotationRegex)
if (!match || !match.groups?.fieldName) {
return null
}
const query = new URLSearchParams(match.groups.query ?? '')
const inputEncoding = (query.get('inputEncoding') as Encoding) ?? 'utf8'
if (
!isValidEncoding(inputEncoding) &&
process.env.NODE_ENV === 'development' &&
model &&
field
) {
console.warn(
warnings.unsupportedEncoding(model, field, inputEncoding, 'input')
)
}
const outputEncoding = (query.get('outputEncoding') as Encoding) ?? 'hex'
if (
!isValidEncoding(outputEncoding) &&
process.env.NODE_ENV === 'development' &&
model &&
field
) {
console.warn(
warnings.unsupportedEncoding(model, field, outputEncoding, 'output')
)
}
const saltEnv = query.get('saltEnv')
const salt =
query.get('salt') ??
(saltEnv
? process.env[saltEnv]
: process.env.PRISMA_FIELD_ENCRYPTION_HASH_SALT)
return {
sourceField: match.groups.fieldName,
targetField: field ?? match.groups.fieldName + 'Hash',
algorithm: query.get('algorithm') ?? 'sha256',
salt,
inputEncoding,
outputEncoding
}
}
function isValidEncoding(encoding: string): encoding is Encoding {
return ['hex', 'base64', 'utf8'].includes(encoding)
}