-
Notifications
You must be signed in to change notification settings - Fork 643
/
Copy pathprepare.ts
341 lines (322 loc) · 9.13 KB
/
prepare.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
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
import { CID } from 'multiformats/cid'
import {
AtUri,
ensureValidRecordKey,
ensureValidDatetime,
} from '@atproto/syntax'
import { TID, check, dataToCborBlock } from '@atproto/common'
import {
BlobRef,
LexValue,
LexiconDefNotFoundError,
RepoRecord,
ValidationError,
lexToIpld,
untypedJsonBlobRef,
} from '@atproto/lexicon'
import {
cborToLex,
RecordDeleteOp,
RecordCreateOp,
RecordUpdateOp,
RecordWriteOp,
WriteOpAction,
} from '@atproto/repo'
import {
PreparedCreate,
PreparedUpdate,
PreparedDelete,
InvalidRecordError,
PreparedWrite,
PreparedBlobRef,
ValidationStatus,
} from './types'
import * as lex from '../lexicon/lexicons'
import { isRecord as isFeedGenerator } from '../lexicon/types/app/bsky/feed/generator'
import { isRecord as isStarterPack } from '../lexicon/types/app/bsky/graph/starterpack'
import { isRecord as isPost } from '../lexicon/types/app/bsky/feed/post'
import { isTag } from '../lexicon/types/app/bsky/richtext/facet'
import { isRecord as isList } from '../lexicon/types/app/bsky/graph/list'
import { isRecord as isProfile } from '../lexicon/types/app/bsky/actor/profile'
import { hasExplicitSlur } from '../handle/explicit-slurs'
export const assertValidRecordWithStatus = (
record: Record<string, unknown>,
opts: { requireLexicon: boolean },
): ValidationStatus => {
if (typeof record.$type !== 'string') {
throw new InvalidRecordError('No $type provided')
}
try {
lex.lexicons.assertValidRecord(record.$type, record)
assertValidCreatedAt(record)
} catch (e) {
if (e instanceof LexiconDefNotFoundError) {
if (opts.requireLexicon) {
throw new InvalidRecordError(e.message)
} else {
return 'unknown'
}
}
throw new InvalidRecordError(
`Invalid ${record.$type} record: ${
e instanceof Error ? e.message : String(e)
}`,
)
}
return 'valid'
}
// additional more rigorous check on datetimes
// this check will eventually be in the lex sdk, but this will stop the bleed until then
export const assertValidCreatedAt = (record: Record<string, unknown>) => {
const createdAt = record['createdAt']
if (typeof createdAt !== 'string') {
return
}
try {
ensureValidDatetime(createdAt)
} catch {
throw new ValidationError(
'createdAt must be an valid atproto datetime (both RFC-3339 and ISO-8601)',
)
}
}
export const setCollectionName = (
collection: string,
record: RepoRecord,
validate: boolean,
) => {
if (!record.$type) {
record.$type = collection
}
if (validate && record.$type !== collection) {
throw new InvalidRecordError(
`Invalid $type: expected ${collection}, got ${record.$type}`,
)
}
return record
}
export const prepareCreate = async (opts: {
did: string
collection: string
rkey?: string
swapCid?: CID | null
record: RepoRecord
validate?: boolean
}): Promise<PreparedCreate> => {
const { did, collection, swapCid, validate } = opts
const maybeValidate = validate !== false
const record = setCollectionName(collection, opts.record, maybeValidate)
let validationStatus: ValidationStatus
if (maybeValidate) {
validationStatus = assertValidRecordWithStatus(record, {
requireLexicon: validate === true,
})
}
const nextRkey = TID.next()
const rkey = opts.rkey || nextRkey.toString()
// @TODO: validate against Lexicon record 'key' type, not just overall recordkey syntax
ensureValidRecordKey(rkey)
assertNoExplicitSlurs(rkey, record)
return {
action: WriteOpAction.Create,
uri: AtUri.make(did, collection, rkey),
cid: await cidForSafeRecord(record),
swapCid,
record,
blobs: blobsForWrite(record, maybeValidate),
validationStatus,
}
}
export const prepareUpdate = async (opts: {
did: string
collection: string
rkey: string
swapCid?: CID | null
record: RepoRecord
validate?: boolean
}): Promise<PreparedUpdate> => {
const { did, collection, rkey, swapCid, validate } = opts
const maybeValidate = validate !== false
const record = setCollectionName(collection, opts.record, maybeValidate)
let validationStatus: ValidationStatus
if (maybeValidate) {
validationStatus = assertValidRecordWithStatus(record, {
requireLexicon: validate === true,
})
}
assertNoExplicitSlurs(rkey, record)
return {
action: WriteOpAction.Update,
uri: AtUri.make(did, collection, rkey),
cid: await cidForSafeRecord(record),
swapCid,
record,
blobs: blobsForWrite(record, maybeValidate),
validationStatus,
}
}
export const prepareDelete = (opts: {
did: string
collection: string
rkey: string
swapCid?: CID | null
}): PreparedDelete => {
const { did, collection, rkey, swapCid } = opts
return {
action: WriteOpAction.Delete,
uri: AtUri.make(did, collection, rkey),
swapCid,
}
}
export const createWriteToOp = (write: PreparedCreate): RecordCreateOp => ({
action: WriteOpAction.Create,
collection: write.uri.collection,
rkey: write.uri.rkey,
record: write.record,
})
export const updateWriteToOp = (write: PreparedUpdate): RecordUpdateOp => ({
action: WriteOpAction.Update,
collection: write.uri.collection,
rkey: write.uri.rkey,
record: write.record,
})
export const deleteWriteToOp = (write: PreparedDelete): RecordDeleteOp => ({
action: WriteOpAction.Delete,
collection: write.uri.collection,
rkey: write.uri.rkey,
})
export const writeToOp = (write: PreparedWrite): RecordWriteOp => {
switch (write.action) {
case WriteOpAction.Create:
return createWriteToOp(write)
case WriteOpAction.Update:
return updateWriteToOp(write)
case WriteOpAction.Delete:
return deleteWriteToOp(write)
default:
throw new Error(`Unrecognized action: ${write}`)
}
}
async function cidForSafeRecord(record: RepoRecord) {
try {
const block = await dataToCborBlock(lexToIpld(record))
cborToLex(block.bytes)
return block.cid
} catch (err) {
// Block does not properly transform between lex and cbor
const badRecordErr = new InvalidRecordError('Bad record')
badRecordErr.cause = err
throw badRecordErr
}
}
function assertNoExplicitSlurs(rkey: string, record: RepoRecord) {
let toCheck = ''
if (isProfile(record)) {
toCheck += ' ' + record.displayName
} else if (isList(record)) {
toCheck += ' ' + record.name
} else if (isStarterPack(record)) {
toCheck += ' ' + record.name
} else if (isFeedGenerator(record)) {
toCheck += ' ' + rkey
toCheck += ' ' + record.displayName
} else if (isPost(record)) {
if (record.tags) {
toCheck += record.tags.join(' ')
}
for (const facet of record.facets || []) {
for (const feat of facet.features) {
if (isTag(feat)) {
toCheck += ' ' + feat.tag
}
}
}
}
if (hasExplicitSlur(toCheck)) {
throw new InvalidRecordError('Unacceptable slur in record')
}
}
type FoundBlobRef = {
ref: BlobRef
path: string[]
}
export const blobsForWrite = (
record: RepoRecord,
validate: boolean,
): PreparedBlobRef[] => {
const refs = findBlobRefs(record)
const recordType =
typeof record['$type'] === 'string' ? record['$type'] : undefined
for (const ref of refs) {
if (check.is(ref.ref.original, untypedJsonBlobRef)) {
throw new InvalidRecordError(`Legacy blob ref at '${ref.path.join('/')}'`)
}
}
return refs.map(({ ref, path }) => ({
cid: ref.ref,
mimeType: ref.mimeType,
constraints:
validate && recordType
? CONSTRAINTS[recordType]?.[path.join('/')] ?? {}
: {},
}))
}
export const findBlobRefs = (
val: LexValue,
path: string[] = [],
layer = 0,
): FoundBlobRef[] => {
if (layer > 32) {
return []
}
// walk arrays
if (Array.isArray(val)) {
return val.flatMap((item) => findBlobRefs(item, path, layer + 1))
}
// objects
if (val && typeof val === 'object') {
// convert blobs, leaving the original encoding so that we don't change CIDs on re-encode
if (val instanceof BlobRef) {
return [
{
ref: val,
path,
},
]
}
// retain cids & bytes
if (CID.asCID(val) || val instanceof Uint8Array) {
return []
}
return Object.entries(val).flatMap(([key, item]) =>
findBlobRefs(item, [...path, key], layer + 1),
)
}
// pass through
return []
}
const CONSTRAINTS = {
[lex.ids.AppBskyActorProfile]: {
avatar:
lex.schemaDict.AppBskyActorProfile.defs.main.record.properties.avatar,
banner:
lex.schemaDict.AppBskyActorProfile.defs.main.record.properties.banner,
},
[lex.ids.AppBskyFeedGenerator]: {
avatar:
lex.schemaDict.AppBskyFeedGenerator.defs.main.record.properties.avatar,
},
[lex.ids.AppBskyGraphList]: {
avatar: lex.schemaDict.AppBskyGraphList.defs.main.record.properties.avatar,
},
[lex.ids.AppBskyFeedPost]: {
'embed/images/image':
lex.schemaDict.AppBskyEmbedImages.defs.image.properties.image,
'embed/external/thumb':
lex.schemaDict.AppBskyEmbedExternal.defs.external.properties.thumb,
'embed/media/images/image':
lex.schemaDict.AppBskyEmbedImages.defs.image.properties.image,
'embed/media/external/thumb':
lex.schemaDict.AppBskyEmbedExternal.defs.external.properties.thumb,
},
}