@crombolo/server 0.64.0 → 0.66.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/package.json +15 -14
  2. package/src/access.ts +6 -2
  3. package/src/adapters/blueprints.ts +19 -5
  4. package/src/adapters/elements.ts +49 -36
  5. package/src/adapters/members.ts +37 -3
  6. package/src/adapters/users.ts +18 -0
  7. package/src/approvals.ts +44 -15
  8. package/src/atomic-write.ts +2 -2
  9. package/src/background-jobs.ts +170 -0
  10. package/src/bundle-admin.ts +39 -3
  11. package/src/bundle-reload.ts +2 -1
  12. package/src/bundles.ts +60 -25
  13. package/src/cli-tokens-api.ts +152 -0
  14. package/src/config.ts +52 -3
  15. package/src/content-events.ts +22 -0
  16. package/src/content-operations.ts +26 -1
  17. package/src/core.ts +357 -133
  18. package/src/extension-activity.ts +121 -0
  19. package/src/extension-components.ts +20 -4
  20. package/src/extension-discovery.ts +84 -65
  21. package/src/grant-trust.ts +6 -4
  22. package/src/index.ts +14 -0
  23. package/src/media-access.ts +30 -125
  24. package/src/media-library.ts +953 -0
  25. package/src/member-admin.ts +761 -0
  26. package/src/node-operations.ts +19 -2
  27. package/src/ports.ts +2 -0
  28. package/src/principal.ts +35 -0
  29. package/src/remote-background-jobs.ts +99 -0
  30. package/src/remote-credentials.ts +114 -6
  31. package/src/remote-extension-activity.ts +66 -0
  32. package/src/remote-media-library.ts +297 -0
  33. package/src/remote-media.ts +2 -2
  34. package/src/remote-members.ts +271 -0
  35. package/src/remote-undo.ts +234 -0
  36. package/src/remote-users.ts +229 -0
  37. package/src/remote.ts +141 -3
  38. package/src/routes.ts +22 -3
  39. package/src/seed/values.ts +82 -4
  40. package/src/seo.ts +81 -61
  41. package/src/server.ts +153 -92
  42. package/src/settings.ts +95 -6
  43. package/src/trusted-signers-admin.ts +39 -3
  44. package/src/undo.ts +358 -0
  45. package/src/user-admin.ts +581 -0
  46. package/src/view-as.ts +95 -0
@@ -0,0 +1,953 @@
1
+ /**
2
+ * The media library as the command line and the remote protocol read and change
3
+ * it (story 355): a page of items, one item with its file and who may see it,
4
+ * what uses it, its details and file changed, folders made, and its permissions
5
+ * read and set with the Permissions dialog's own rules. Each call is made for an
6
+ * actor; a person sees and changes only what their start nodes and permissions
7
+ * allow, as in the back office. Writes go through the media operations.
8
+ */
9
+ import type { Principal } from '@crombolo/api-management/domain'
10
+ import { hasSection } from '@crombolo/api-management/domain'
11
+ import {
12
+ formFor,
13
+ inheritedForm,
14
+ requestFor,
15
+ summarise,
16
+ } from '@crombolo/backoffice-host/media-access-rules'
17
+ import type { Actor, MediaOperations } from '@crombolo/content'
18
+ import {
19
+ type DocumentValue,
20
+ fallbackPermissions,
21
+ hasPathAccess,
22
+ IMAGE_CROPPER_EDITOR_ALIAS,
23
+ isProtectedMedia,
24
+ MEMBER_FILE_TYPES,
25
+ MediaPermissions,
26
+ type MediaPolicy,
27
+ mediaFileOf,
28
+ normaliseUuid,
29
+ ObjectTypes,
30
+ SystemNodes,
31
+ } from '@crombolo/core'
32
+ import {
33
+ appendCacheInstruction,
34
+ ContentTypeRepository,
35
+ currentSchemaState,
36
+ DataTypeRepository,
37
+ type Db,
38
+ DocumentRepository,
39
+ describeRefFailure,
40
+ IMAGE_ALT_TEXT_ALIAS,
41
+ type MediaAccessEntry,
42
+ type MediaAccessGroup,
43
+ type MediaAccessMember,
44
+ MediaAccessRepository,
45
+ MemberRepository,
46
+ NodeRepository,
47
+ type NodeRow,
48
+ ReferenceRepository,
49
+ resolveNodeRef,
50
+ ruleOf,
51
+ } from '@crombolo/data'
52
+ import { createMediaPort } from './adapters/media.ts'
53
+ import type { MediaFileStore } from './media-files.ts'
54
+ import { namedPath } from './undo.ts'
55
+
56
+ export type MediaLibraryErrorKind = 'not_found' | 'usage' | 'refused' | 'forbidden'
57
+
58
+ /** Why a media item could not be read or changed, in words for a person. */
59
+ export class MediaLibraryError extends Error {
60
+ constructor(
61
+ readonly kind: MediaLibraryErrorKind,
62
+ message: string,
63
+ readonly hint?: string,
64
+ ) {
65
+ super(message)
66
+ }
67
+ }
68
+
69
+ /** The editors an item's alternative text can be written to. */
70
+ const TEXT_EDITORS = new Set(['Umbraco.TextBox', 'Umbraco.TextArea'])
71
+
72
+ /** The most a page holds. */
73
+ export const MEDIA_PAGE_MAX = 100
74
+
75
+ export interface FocalPoint {
76
+ left: number
77
+ top: number
78
+ }
79
+
80
+ /** `x,y`, each from 0 to 1, as `--focal` takes it; undefined when it is not. Pure. */
81
+ export function parseFocalPoint(value: string): FocalPoint | undefined {
82
+ const parts = value.split(',')
83
+ if (parts.length !== 2 || parts.some((part) => part.trim() === '')) return undefined
84
+ const [left, top] = parts.map(Number) as [number, number]
85
+ return left >= 0 && left <= 1 && top >= 0 && top <= 1 ? { left, top } : undefined
86
+ }
87
+
88
+ const principalOf = (actor: Actor): Principal | undefined =>
89
+ actor.kind === 'user' ? (actor.principal as Principal) : undefined
90
+
91
+ /** A media node's ancestors' keys then its own, root first. */
92
+ export async function mediaChain(db: Db, path: string): Promise<string[]> {
93
+ const ids = path
94
+ .split(',')
95
+ .map(Number)
96
+ .filter((id) => id > 0)
97
+ const byId = new Map((await new NodeRepository(db).byIds(ids)).map((row) => [row.id, row]))
98
+ return ids.flatMap((id) => {
99
+ const row = byId.get(id)
100
+ return row && row.objectType === ObjectTypes.Media ? [row.key] : []
101
+ })
102
+ }
103
+
104
+ /** Whether a person may see a media node: the Media section, within their start nodes. */
105
+ export async function maySeeMedia(db: Db, principal: Principal, node: NodeRow): Promise<boolean> {
106
+ return (
107
+ hasSection(principal, 'media') &&
108
+ hasPathAccess(principal.startNodes.media, await mediaChain(db, node.path), node.trashed)
109
+ )
110
+ }
111
+
112
+ /** The media item or folder a path or key names, which the actor may see. */
113
+ export async function mediaNode(db: Db, actor: Actor, ref: string): Promise<NodeRow> {
114
+ const resolved = await resolveNodeRef(db, [ObjectTypes.Media], ref)
115
+ if (!resolved.ok) throw new MediaLibraryError('not_found', describeRefFailure(ref, resolved))
116
+ const node = resolved.node
117
+ if (node.objectType !== ObjectTypes.Media)
118
+ throw new MediaLibraryError('not_found', `"${ref}" is not a media item.`)
119
+ if (node.trashed)
120
+ throw new MediaLibraryError(
121
+ 'not_found',
122
+ `"${ref}" is in the recycle bin.`,
123
+ '`crombolo recycle-bin restore` brings it back.',
124
+ )
125
+ const principal = principalOf(actor)
126
+ if (principal && !(await maySeeMedia(db, principal, node)))
127
+ throw new MediaLibraryError('forbidden', `You may not see "${ref}".`)
128
+ return node
129
+ }
130
+
131
+ /** Its place by name, `/Gallery/hero.jpg`. */
132
+ const pathOf = async (db: Db, key: string) => `/${(await namedPath(db, key, 'media')) ?? ''}`
133
+
134
+ async function mediaDocuments(db: Db) {
135
+ const state = await currentSchemaState(db)
136
+ return new DocumentRepository(db, {
137
+ kind: 'media',
138
+ nodeState: { version: state.version, revision: state.revision },
139
+ })
140
+ }
141
+
142
+ const propertyValue = (values: readonly DocumentValue[], alias: string) =>
143
+ values.find((v) => v.alias === alias && v.segment === null)?.value
144
+
145
+ const numberOf = (value: unknown): number | null => {
146
+ const n = typeof value === 'string' ? Number(value) : value
147
+ return typeof n === 'number' && Number.isFinite(n) ? n : null
148
+ }
149
+
150
+ const focalOf = (file: unknown): FocalPoint | null => {
151
+ const focal = (file as { focalPoint?: FocalPoint | null } | null)?.focalPoint
152
+ return focal && typeof focal.left === 'number' && typeof focal.top === 'number'
153
+ ? { left: focal.left, top: focal.top }
154
+ : null
155
+ }
156
+
157
+ /** One item of a page: what the list shows. */
158
+ export interface MediaListItem {
159
+ key: string
160
+ name: string
161
+ path: string
162
+ /** The media type's alias. */
163
+ type: string
164
+ folder: boolean
165
+ /** In bytes; null for a folder, or a file whose size is not known. */
166
+ size: number | null
167
+ }
168
+
169
+ export interface MediaPage {
170
+ total: number
171
+ items: MediaListItem[]
172
+ }
173
+
174
+ export interface MediaQuery {
175
+ /** The folder whose items `list` gives, and below which `find` looks; the top when absent. */
176
+ under?: string
177
+ /** A media type, by alias. */
178
+ type?: string
179
+ /** Text the name holds, for `find`. */
180
+ name?: string
181
+ skip?: number
182
+ take?: number
183
+ }
184
+
185
+ /** The paging a request or a flag asks for: 25 by default, at most 100. Pure. */
186
+ export const mediaPaging = (skip?: number, take?: number) => ({
187
+ skip: Math.max(0, Math.floor(Number(skip) || 0)),
188
+ take: Math.min(MEDIA_PAGE_MAX, Math.max(1, Math.floor(Number(take) || 25))),
189
+ })
190
+
191
+ /** The media types that hold a file; the others are folders. */
192
+ async function fileTypeIds(db: Db): Promise<Set<number>> {
193
+ const rows = await db.q
194
+ .selectFrom('property_type')
195
+ .select('content_type_id')
196
+ .where('alias', '=', 'umbracoFile')
197
+ .execute()
198
+ return new Set(rows.map((row) => Number(row.content_type_id)))
199
+ }
200
+
201
+ async function pageOf(
202
+ db: Db,
203
+ actor: Actor,
204
+ query: MediaQuery,
205
+ below: 'children' | 'descendants',
206
+ ): Promise<MediaPage> {
207
+ const { skip, take } = mediaPaging(query.skip, query.take)
208
+ const folder = query.under ? await mediaNode(db, actor, query.under) : undefined
209
+ const principal = principalOf(actor)
210
+ const start = principal?.startNodes.media
211
+ let startIds: number[] | undefined
212
+ if (start && !start.root) {
213
+ const nodes = new NodeRepository(db)
214
+ startIds = (await Promise.all(start.keys.map((key) => nodes.byKey(key)))).flatMap((row) =>
215
+ row ? [row.id] : [],
216
+ )
217
+ if (startIds.length === 0) return { total: 0, items: [] }
218
+ }
219
+ const name = query.name?.trim().toLowerCase()
220
+ let q = db.q
221
+ .selectFrom('node as n')
222
+ .innerJoin('content as c', 'c.node_id', 'n.id')
223
+ .innerJoin('content_type as ct', 'ct.node_id', 'c.content_type_id')
224
+ .where('n.node_object_type', '=', ObjectTypes.Media)
225
+ .where('n.trashed', '=', db.dialect.boolValue(false))
226
+ if (below === 'children') q = q.where('n.parent_id', '=', folder?.id ?? SystemNodes.Root)
227
+ else if (folder) q = q.where('n.path', 'like', `${folder.path},%`)
228
+ if (query.type) q = q.where('ct.alias', '=', query.type)
229
+ if (name) q = q.where((eb) => eb(eb.fn<string>('lower', ['n.text']), 'like', `%${name}%`))
230
+ if (startIds) {
231
+ const ids = startIds
232
+ q = q.where((eb) =>
233
+ eb.or(
234
+ ids.flatMap((id) => [eb('n.path', 'like', `%,${id},%`), eb('n.path', 'like', `%,${id}`)]),
235
+ ),
236
+ )
237
+ }
238
+ const counted = await q.select((eb) => eb.fn.countAll().as('n')).execute()
239
+ const rows = await q
240
+ .select(['n.unique_id', 'n.text', 'n.path', 'ct.alias', 'c.content_type_id'])
241
+ .orderBy('n.text')
242
+ .orderBy('n.id')
243
+ .offset(skip)
244
+ .limit(take)
245
+ .execute()
246
+ const withFile = await fileTypeIds(db)
247
+ const repo = await mediaDocuments(db)
248
+ const items: MediaListItem[] = []
249
+ for (const row of rows) {
250
+ const key = normaliseUuid(String(row.unique_id))
251
+ const folderType = !withFile.has(Number(row.content_type_id))
252
+ const doc = folderType ? undefined : await repo.byKey(key)
253
+ items.push({
254
+ key,
255
+ name: row.text ?? '',
256
+ path: await pathOf(db, key),
257
+ type: row.alias,
258
+ folder: folderType,
259
+ size: doc ? numberOf(propertyValue(doc.values, 'umbracoBytes')) : null,
260
+ })
261
+ }
262
+ return { total: Number(counted[0]?.n ?? 0), items }
263
+ }
264
+
265
+ /** The items in a folder, or at the top, by name, a page at a time. */
266
+ export const listMedia = (db: Db, actor: Actor, query: MediaQuery = {}) =>
267
+ pageOf(db, actor, query, 'children')
268
+
269
+ /** The items whose names hold `name`, anywhere below `under`, a page at a time. */
270
+ export async function findMedia(db: Db, actor: Actor, query: MediaQuery & { name: string }) {
271
+ if (!query.name.trim()) throw new MediaLibraryError('usage', 'Give some of the name to find.')
272
+ return pageOf(db, actor, query, 'descendants')
273
+ }
274
+
275
+ /** What uses a page or media item: its name, what it is, where and of which type. */
276
+ export interface Reference {
277
+ key: string
278
+ name: string
279
+ kind: 'page' | 'media' | 'library' | 'member' | 'other'
280
+ path: string | null
281
+ type: string | null
282
+ }
283
+
284
+ export interface ReferencePage {
285
+ total: number
286
+ items: Reference[]
287
+ }
288
+
289
+ const KINDS: Record<string, Reference['kind']> = {
290
+ [ObjectTypes.Document]: 'page',
291
+ [ObjectTypes.Media]: 'media',
292
+ [ObjectTypes.Element]: 'library',
293
+ [ObjectTypes.Member]: 'member',
294
+ }
295
+
296
+ /**
297
+ * What uses a page or media item, from the values as they are now: pickers,
298
+ * links and images in rich text, as the back office's "Used by" finds them.
299
+ */
300
+ export async function referencesTo(
301
+ db: Db,
302
+ key: string,
303
+ paging: { skip?: number; take?: number } = {},
304
+ ): Promise<ReferencePage> {
305
+ const { skip, take } = mediaPaging(paging.skip, paging.take)
306
+ const found = await new ReferenceRepository(db).referencedBy(key, skip, take)
307
+ const items: Reference[] = []
308
+ for (const ref of found.items) {
309
+ const kind = (ref.objectType && KINDS[ref.objectType]) || 'other'
310
+ const named =
311
+ kind === 'page'
312
+ ? await namedPath(db, ref.key, 'content')
313
+ : kind === 'media' || kind === 'library'
314
+ ? await namedPath(db, ref.key, kind)
315
+ : undefined
316
+ items.push({
317
+ key: normaliseUuid(ref.key),
318
+ name: ref.name ?? '',
319
+ kind,
320
+ path: named === undefined ? null : kind === 'library' ? `library:/${named}` : `/${named}`,
321
+ type: ref.contentTypeAlias,
322
+ })
323
+ }
324
+ return { total: found.total, items }
325
+ }
326
+
327
+ const plural = (count: number, one: string, many = `${one}s`) =>
328
+ `${count} ${count === 1 ? one : many}`
329
+
330
+ const listed = (parts: string[]) =>
331
+ parts.length <= 1
332
+ ? (parts[0] ?? '')
333
+ : `${parts.slice(0, -1).join(', ')} and ${parts.at(-1) as string}`
334
+
335
+ /** "Used by 3 pages and 1 media item", or "Nothing uses it." when nothing does. Pure. */
336
+ export function usedByWords(references: ReferencePage): string {
337
+ if (references.total === 0) return 'Nothing uses it.'
338
+ if (references.items.length < references.total)
339
+ return `Used by ${plural(references.total, 'item')}.`
340
+ const count = (kind: Reference['kind']) => references.items.filter((r) => r.kind === kind).length
341
+ const parts = [
342
+ count('page') ? plural(count('page'), 'page') : '',
343
+ count('media') ? plural(count('media'), 'media item') : '',
344
+ count('library') ? plural(count('library'), 'Library item') : '',
345
+ count('member') ? plural(count('member'), 'member') : '',
346
+ count('other') ? plural(count('other'), 'other item') : '',
347
+ ].filter(Boolean)
348
+ return `Used by ${listed(parts)}.`
349
+ }
350
+
351
+ /** One media item as `media show` gives it. */
352
+ export interface MediaItem {
353
+ key: string
354
+ name: string
355
+ path: string
356
+ type: { alias: string; name: string }
357
+ folder: boolean
358
+ /** The folder it is in; null at the top. */
359
+ parent: { key: string; name: string; path: string } | null
360
+ /** The address its file is served at; null for a folder or an item with no file. */
361
+ file: string | null
362
+ size: number | null
363
+ width: number | null
364
+ height: number | null
365
+ extension: string | null
366
+ /** Its alternative text; null where its type has none, or none is set. */
367
+ alt: string | null
368
+ focal: FocalPoint | null
369
+ /** Who may see it and change it, in the dialog's words. */
370
+ access: string
371
+ protected: boolean
372
+ references?: ReferencePage
373
+ }
374
+
375
+ /** One item: its type, folder, file, size, alternative text, focal point and who may see it. */
376
+ export async function showMedia(
377
+ db: Db,
378
+ actor: Actor,
379
+ ref: string,
380
+ options: { references?: boolean; skip?: number; take?: number } = {},
381
+ ): Promise<MediaItem> {
382
+ const node = await mediaNode(db, actor, ref)
383
+ const doc = await (await mediaDocuments(db)).byKey(node.key)
384
+ if (!doc) throw new MediaLibraryError('not_found', `"${ref}" is not a media item.`)
385
+ const type = await new ContentTypeRepository(db, { kind: 'media' }).byKey(doc.contentTypeKey)
386
+ const folder = !type?.properties.some((p) => p.alias === 'umbracoFile')
387
+ const parent = node.parentId > 0 ? await new NodeRepository(db).byId(node.parentId) : undefined
388
+ const file = propertyValue(doc.values, 'umbracoFile')
389
+ const alt = propertyValue(doc.values, IMAGE_ALT_TEXT_ALIAS)
390
+ const state = await describeMediaAccess({ db }, node.key)
391
+ return {
392
+ key: node.key,
393
+ name: node.text ?? '',
394
+ path: await pathOf(db, node.key),
395
+ type: { alias: doc.contentTypeAlias, name: type?.name ?? doc.contentTypeAlias },
396
+ folder,
397
+ parent:
398
+ parent && parent.objectType === ObjectTypes.Media
399
+ ? { key: parent.key, name: parent.text ?? '', path: await pathOf(db, parent.key) }
400
+ : null,
401
+ file: mediaFileOf(doc),
402
+ size: numberOf(propertyValue(doc.values, 'umbracoBytes')),
403
+ width: numberOf(propertyValue(doc.values, 'umbracoWidth')),
404
+ height: numberOf(propertyValue(doc.values, 'umbracoHeight')),
405
+ extension: (propertyValue(doc.values, 'umbracoExtension') as string | undefined) || null,
406
+ alt: typeof alt === 'string' && alt !== '' ? alt : null,
407
+ focal: focalOf(file),
408
+ access: state ? summarise(state) : '',
409
+ protected: state?.protected ?? false,
410
+ ...(options.references ? { references: await referencesTo(db, node.key, options) } : {}),
411
+ }
412
+ }
413
+
414
+ /** What `media update` changes; each absent part is left as it is. */
415
+ export interface MediaChange {
416
+ name?: string
417
+ alt?: string
418
+ focal?: FocalPoint
419
+ file?: File
420
+ }
421
+
422
+ /** What the media operations and the file store are, for a change. */
423
+ export interface MediaWriter {
424
+ db: Db
425
+ media: MediaOperations
426
+ files: MediaFileStore
427
+ }
428
+
429
+ export interface MediaUpdated {
430
+ key: string
431
+ name: string
432
+ path: string
433
+ /** What changed, of name, alt, focal and file; empty when nothing did. */
434
+ changed: Array<'name' | 'alt' | 'focal' | 'file'>
435
+ /** With a new file: what uses the item, which keeps working since its key is kept. */
436
+ references?: ReferencePage
437
+ }
438
+
439
+ /** The editor each property of a media type uses, by alias. */
440
+ async function editorsOf(db: Db, typeKey: string): Promise<Map<string, string>> {
441
+ const properties = (await new ContentTypeRepository(db, { kind: 'media' }).byKey(typeKey))
442
+ ?.properties
443
+ const dataTypes = new DataTypeRepository(db)
444
+ const out = new Map<string, string>()
445
+ for (const p of properties ?? [])
446
+ out.set(p.alias, (await dataTypes.byKey(p.dataTypeKey))?.editorAlias ?? '')
447
+ return out
448
+ }
449
+
450
+ /**
451
+ * Refuses alternative text or a focal point a media type cannot hold, naming
452
+ * the item and its type, as `media import` and `media update` both check.
453
+ */
454
+ export async function checkMediaDetails(
455
+ db: Db,
456
+ type: { key: string; name: string },
457
+ shown: string,
458
+ details: { alt?: string; focal?: FocalPoint },
459
+ would = false,
460
+ ): Promise<void> {
461
+ const editors = await editorsOf(db, type.key)
462
+ const is = would ? 'would be' : 'is'
463
+ if (details.alt !== undefined && !TEXT_EDITORS.has(editors.get(IMAGE_ALT_TEXT_ALIAS) ?? ''))
464
+ throw new MediaLibraryError(
465
+ 'refused',
466
+ `${shown} ${is} a ${type.name}, which has no text field for its alternative text.`,
467
+ )
468
+ if (details.focal && editors.get('umbracoFile') !== IMAGE_CROPPER_EDITOR_ALIAS)
469
+ throw new MediaLibraryError(
470
+ 'refused',
471
+ `${shown} ${is} a ${type.name}, which has no focal point.`,
472
+ )
473
+ }
474
+
475
+ /**
476
+ * Changes an item's name, alternative text, focal point or file, through the
477
+ * media operations, audited as the actor. A new file keeps the item's key, so
478
+ * pickers, links and images that name it show the new file; the old file goes.
479
+ */
480
+ export async function updateMedia(
481
+ writer: MediaWriter,
482
+ actor: Actor,
483
+ ref: string,
484
+ change: MediaChange,
485
+ options: { dryRun?: boolean } = {},
486
+ ): Promise<MediaUpdated> {
487
+ const { db } = writer
488
+ const node = await mediaNode(db, actor, ref)
489
+ const doc = await (await mediaDocuments(db)).byKey(node.key)
490
+ if (!doc) throw new MediaLibraryError('not_found', `"${ref}" is not a media item.`)
491
+ const type = await new ContentTypeRepository(db, { kind: 'media' }).byKey(doc.contentTypeKey)
492
+ const typeName = type?.name ?? doc.contentTypeAlias
493
+ const shown = node.text ?? ref
494
+ await checkMediaDetails(db, { key: doc.contentTypeKey, name: typeName }, shown, change)
495
+ if (change.name !== undefined && change.name.trim() === '')
496
+ throw new MediaLibraryError('usage', 'A media item needs a name.')
497
+ if (change.file) {
498
+ const extension = change.file.name.split('.').pop()?.toLowerCase() ?? ''
499
+ const types = await createMediaPort(db).typesForExtension(
500
+ change.file.name.includes('.') ? extension : '',
501
+ )
502
+ if (!types.some((t) => normaliseUuid(t.key) === normaliseUuid(doc.contentTypeKey))) {
503
+ const takers = types.map((t) => t.name)
504
+ throw new MediaLibraryError(
505
+ 'refused',
506
+ `${shown} is a ${typeName}, which does not take a .${extension} file.`,
507
+ takers.length > 0
508
+ ? `A ${listed(takers)} would: import it as a new item instead.`
509
+ : 'No media type on this site takes it.',
510
+ )
511
+ }
512
+ }
513
+
514
+ const changed: MediaUpdated['changed'] = []
515
+ let values = doc.values
516
+ const name = node.text ?? ''
517
+ if (change.name !== undefined && change.name !== name) changed.push('name')
518
+ if (change.alt !== undefined && propertyValue(values, IMAGE_ALT_TEXT_ALIAS) !== change.alt) {
519
+ values = [
520
+ ...values.filter((v) => v.alias !== IMAGE_ALT_TEXT_ALIAS),
521
+ { alias: IMAGE_ALT_TEXT_ALIAS, culture: null, segment: null, value: change.alt },
522
+ ]
523
+ changed.push('alt')
524
+ }
525
+ const fileValue = values.find((v) => v.alias === 'umbracoFile' && v.segment === null)
526
+ const focalWas = focalOf(fileValue?.value)
527
+ const focal = change.focal ?? focalWas
528
+ if (change.focal && (focalWas?.left !== change.focal.left || focalWas?.top !== change.focal.top))
529
+ changed.push('focal')
530
+ if (change.file) changed.push('file')
531
+ const references = change.file
532
+ ? await referencesTo(db, node.key, { take: MEDIA_PAGE_MAX })
533
+ : undefined
534
+ const done = async (): Promise<MediaUpdated> => ({
535
+ key: node.key,
536
+ name: change.name ?? name,
537
+ path: await pathOf(db, node.key),
538
+ changed,
539
+ ...(references ? { references } : {}),
540
+ })
541
+ if (changed.length === 0 || options.dryRun) return done()
542
+
543
+ const editors = await editorsOf(db, doc.contentTypeKey)
544
+ const cropper = editors.get('umbracoFile') === IMAGE_CROPPER_EDITOR_ALIAS
545
+ let upload: string | undefined
546
+ if (change.file) {
547
+ upload = crypto.randomUUID()
548
+ await writer.files.saveTemporary(upload, change.file)
549
+ }
550
+ if (upload || changed.includes('focal')) {
551
+ const was = (fileValue?.value ?? {}) as Record<string, unknown>
552
+ const next = upload
553
+ ? cropper
554
+ ? {
555
+ temporaryFileId: upload,
556
+ crops: Array.isArray(was.crops) ? was.crops : [],
557
+ focalPoint: focal,
558
+ }
559
+ : { temporaryFileId: upload }
560
+ : { ...was, focalPoint: focal }
561
+ values = [
562
+ ...values.filter((v) => !(v.alias === 'umbracoFile' && v.segment === null)),
563
+ { alias: 'umbracoFile', culture: null, segment: null, value: next },
564
+ ]
565
+ }
566
+ const saved = await writer.media.save(actor, node.key, {
567
+ contentTypeKey: doc.contentTypeKey,
568
+ parentKey: doc.parentKey,
569
+ values,
570
+ variants: doc.variants.map((v) => ({
571
+ culture: v.culture,
572
+ segment: v.segment,
573
+ name: change.name ?? v.name,
574
+ })),
575
+ })
576
+ if (!saved.ok)
577
+ throw new MediaLibraryError(
578
+ saved.kind === 'notFound'
579
+ ? 'not_found'
580
+ : saved.kind === 'forbidden'
581
+ ? 'forbidden'
582
+ : 'refused',
583
+ saved.reason,
584
+ )
585
+ return done()
586
+ }
587
+
588
+ export interface FoldersMade {
589
+ /** The folder the path names. */
590
+ key: string
591
+ path: string
592
+ /** The folders made, top first; empty when they were all there. */
593
+ made: string[]
594
+ }
595
+
596
+ /** Each folder along `path` that is missing, through the media operations; none already there. */
597
+ export async function makeFolders(
598
+ writer: Pick<MediaWriter, 'db' | 'media'>,
599
+ actor: Actor,
600
+ path: string,
601
+ ): Promise<FoldersMade> {
602
+ const { db } = writer
603
+ const names = path
604
+ .split('/')
605
+ .map((name) => name.trim())
606
+ .filter(Boolean)
607
+ if (names.length === 0)
608
+ throw new MediaLibraryError('usage', 'Name the folder to make, as /Gallery/2026.')
609
+ const nodes = new NodeRepository(db)
610
+ const folderTypes = await createMediaPort(db).folderTypes()
611
+ const folderType = folderTypes.find((t) => t.name === 'Folder') ?? folderTypes[0]
612
+ const withFile = await fileTypeIds(db)
613
+ const made: string[] = []
614
+ let parent: NodeRow | undefined
615
+ for (const [at, name] of names.entries()) {
616
+ const shown = `/${names.slice(0, at + 1).join('/')}`
617
+ const there = await nodes.childrenNamed(
618
+ parent?.id ?? SystemNodes.Root,
619
+ [ObjectTypes.Media],
620
+ name,
621
+ )
622
+ if (there.length > 1)
623
+ throw new MediaLibraryError('refused', `More than one item is named ${shown}.`)
624
+ const found = there[0]
625
+ if (found) {
626
+ const typeId = await db.q
627
+ .selectFrom('content')
628
+ .select('content_type_id')
629
+ .where('node_id', '=', found.id)
630
+ .executeTakeFirst()
631
+ if (typeId && withFile.has(Number(typeId.content_type_id)))
632
+ throw new MediaLibraryError('refused', `${shown} is a file, not a folder.`)
633
+ parent = found
634
+ continue
635
+ }
636
+ if (!folderType)
637
+ throw new MediaLibraryError('refused', 'This site has no media folder type to make one with.')
638
+ const key = crypto.randomUUID()
639
+ const created = await writer.media.create(actor, {
640
+ key,
641
+ contentTypeKey: folderType.key,
642
+ parentKey: parent?.key ?? null,
643
+ values: [],
644
+ variants: [{ culture: null, segment: null, name }],
645
+ })
646
+ if (!created.ok)
647
+ throw new MediaLibraryError(
648
+ created.kind === 'forbidden' ? 'forbidden' : 'refused',
649
+ `${shown} was not made: ${created.reason}`,
650
+ )
651
+ parent = (await nodes.byKey(created.key)) ?? undefined
652
+ made.push(shown)
653
+ }
654
+ return { key: (parent as NodeRow).key, path: `/${names.join('/')}`, made }
655
+ }
656
+
657
+ /** What reading or setting media permissions needs beyond the database. */
658
+ export interface MediaAccessContext {
659
+ db: Db
660
+ /** The folders wired bundles declare (story 198), by bundle name and node path. */
661
+ bundleFolders?(): ReadonlyArray<{ bundle: string; nodePath: string }>
662
+ /** Told after a change, with the item's key, for the media cache here. */
663
+ onChange?(key: string): void | Promise<void>
664
+ /** This server's name, on the cache instruction an item's change appends. */
665
+ nodeId?: string
666
+ }
667
+
668
+ /** A rule as the back office sends and shows it. */
669
+ export interface RuleBody {
670
+ publicRead: boolean
671
+ groups: MediaAccessGroup[]
672
+ members?: MediaAccessMember[]
673
+ newRead: MediaAccessEntry['newRead']
674
+ newWrite: MediaAccessEntry['newWrite']
675
+ /** File types members may upload below (story 198); empty is none. */
676
+ memberTypes: string[]
677
+ /** The largest file a member may upload below, in bytes; null sets none. */
678
+ memberMaxBytes: number | null
679
+ }
680
+
681
+ const ruleBody = (entry: MediaAccessEntry): RuleBody => ({
682
+ publicRead: entry.publicRead,
683
+ groups: entry.groups,
684
+ ...(entry.members?.length ? { members: [...entry.members] } : {}),
685
+ newRead: entry.newRead,
686
+ newWrite: entry.newWrite,
687
+ memberTypes: entry.memberTypes,
688
+ memberMaxBytes: entry.memberMaxBytes,
689
+ })
690
+
691
+ /** The site's member groups, by name. */
692
+ export async function memberGroupNames(db: Db): Promise<string[]> {
693
+ const rows = await db.q
694
+ .selectFrom('node')
695
+ .select('text')
696
+ .where('node_object_type', '=', ObjectTypes.MemberGroup)
697
+ .orderBy('text')
698
+ .execute()
699
+ return rows.flatMap((row) => (row.text ? [String(row.text)] : []))
700
+ }
701
+
702
+ /** The bundles that use a folder: those declaring it, or one below it. Sorted, each once. */
703
+ export const bundlesUsing = (context: MediaAccessContext, id: number): string[] =>
704
+ [
705
+ ...new Set(
706
+ (context.bundleFolders?.() ?? [])
707
+ .filter((folder) => `,${folder.nodePath},`.includes(`,${id},`))
708
+ .map((folder) => folder.bundle),
709
+ ),
710
+ ].sort()
711
+
712
+ /** What the Permissions dialog shows for a folder or item. */
713
+ export async function describeMediaAccess(context: MediaAccessContext, key: string) {
714
+ const { db } = context
715
+ const nodes = new NodeRepository(db)
716
+ const repo = new MediaAccessRepository(db)
717
+ const node = await nodes.byKey(key)
718
+ if (!node || node.objectType !== ObjectTypes.Media) return undefined
719
+ const own = await repo.byNodeKey(key)
720
+ const inherited = await repo.ruleFor(key, { above: true })
721
+ const item = (await repo.itemAccess(key)) ?? {
722
+ readPolicy: 'inherit' as const,
723
+ writePolicy: 'inherit' as const,
724
+ creatorMemberKey: null,
725
+ }
726
+ const fileRows = await db.q
727
+ .selectFrom('content')
728
+ .select('file_url')
729
+ .where('node_id', '=', node.id)
730
+ .execute()
731
+ const from = inherited ? await nodes.byKey(inherited.nodeKey) : undefined
732
+ const creator = item.creatorMemberKey
733
+ ? await new MemberRepository(db).byKey(item.creatorMemberKey)
734
+ : undefined
735
+ const effective = own ?? inherited
736
+ return {
737
+ key: node.key,
738
+ name: node.text ?? '',
739
+ hasParent: node.parentId > 0,
740
+ hasFile: Boolean(fileRows[0]?.file_url),
741
+ own: own ? ruleBody(own) : null,
742
+ inherited:
743
+ inherited && from
744
+ ? { from: { key: from.key, name: from.text ?? '' }, ...ruleBody(inherited) }
745
+ : null,
746
+ item: {
747
+ readPolicy: item.readPolicy,
748
+ writePolicy: item.writePolicy,
749
+ creator: item.creatorMemberKey
750
+ ? { key: item.creatorMemberKey, name: creator?.name ?? null }
751
+ : null,
752
+ },
753
+ protected: node.trashed || isProtectedMedia(item, effective ? ruleOf(effective) : undefined),
754
+ memberGroups: await memberGroupNames(db),
755
+ memberFileTypes: MEMBER_FILE_TYPES.map((type) => ({ id: type.id, label: type.label })),
756
+ usedBy: bundlesUsing(context, node.id),
757
+ }
758
+ }
759
+
760
+ export type MediaAccessState = NonNullable<Awaited<ReturnType<typeof describeMediaAccess>>>
761
+
762
+ /** What may be refused of a person reading or changing a node's permissions; undefined when allowed. */
763
+ export async function mediaAccessRefusal(
764
+ db: Db,
765
+ principal: Principal,
766
+ node: NodeRow,
767
+ change: boolean,
768
+ ): Promise<'section' | 'forbidden' | undefined> {
769
+ if (!hasSection(principal, 'media')) return 'section'
770
+ if (!(await maySeeMedia(db, principal, node))) return 'forbidden'
771
+ if (change && !fallbackPermissions(principal.groups).has(MediaPermissions.Update))
772
+ return 'forbidden'
773
+ return undefined
774
+ }
775
+
776
+ /** A rule and an item's own policies saved as the dialog saves them; `rule` null takes the rule off. */
777
+ export async function saveMediaAccess(
778
+ context: MediaAccessContext,
779
+ key: string,
780
+ body: {
781
+ rule?: RuleBody | null
782
+ item?: { readPolicy: MediaPolicy; writePolicy: MediaPolicy }
783
+ },
784
+ ): Promise<void> {
785
+ const { rule, item } = body
786
+ await context.db.transaction(async (tx) => {
787
+ const writing = new MediaAccessRepository(tx)
788
+ if (rule === null) await writing.remove(key)
789
+ else if (rule) await writing.save({ nodeKey: key, ...rule })
790
+ if (item) await writing.setItemAccess(key, item)
791
+ // The item carries its own settings in every server's media cache (story 197).
792
+ if (item)
793
+ await appendCacheInstruction(tx, {
794
+ kind: 'content',
795
+ payload: { media: [normaliseUuid(key)] },
796
+ by: context.nodeId,
797
+ })
798
+ })
799
+ await context.onChange?.(normaliseUuid(key))
800
+ }
801
+
802
+ /** A folder's or item's permissions as `media access show` gives them. */
803
+ export interface MediaAccessView {
804
+ key: string
805
+ name: string
806
+ path: string
807
+ /** The dialog's one-line summary. */
808
+ summary: string
809
+ /** The dialog's form: who may see and change it, and whether it follows the folder above. */
810
+ form: ReturnType<typeof formFor>
811
+ /** Everything the dialog reads, including what `set` does not change. */
812
+ state: MediaAccessState
813
+ }
814
+
815
+ async function accessView(context: MediaAccessContext, node: NodeRow): Promise<MediaAccessView> {
816
+ const state = await describeMediaAccess(context, node.key)
817
+ if (!state) throw new MediaLibraryError('not_found', 'The media item could not be found.')
818
+ return {
819
+ key: node.key,
820
+ name: node.text ?? '',
821
+ path: await pathOf(context.db, node.key),
822
+ summary: summarise(state),
823
+ form: formFor(state),
824
+ state,
825
+ }
826
+ }
827
+
828
+ const accessRefused = async (
829
+ context: MediaAccessContext,
830
+ actor: Actor,
831
+ node: NodeRow,
832
+ change: boolean,
833
+ ) => {
834
+ const principal = principalOf(actor)
835
+ const refused = principal && (await mediaAccessRefusal(context.db, principal, node, change))
836
+ if (refused === 'section')
837
+ throw new MediaLibraryError('forbidden', 'Media permissions need the Media section.')
838
+ if (refused)
839
+ throw new MediaLibraryError(
840
+ 'forbidden',
841
+ change
842
+ ? 'You do not have permission to change who can see this.'
843
+ : `You may not see "${node.text ?? node.key}".`,
844
+ )
845
+ }
846
+
847
+ /** Who may see and change a folder or item. */
848
+ export async function mediaAccess(
849
+ context: MediaAccessContext,
850
+ actor: Actor,
851
+ ref: string,
852
+ ): Promise<MediaAccessView> {
853
+ const node = await mediaNode(context.db, actor, ref)
854
+ await accessRefused(context, actor, node, false)
855
+ return accessView(context, node)
856
+ }
857
+
858
+ /** What `media access set` changes; each absent part is kept as it is. */
859
+ export interface MediaAccessChange {
860
+ /** Who may see it: anyone with the link, or back-office users only. */
861
+ see?: 'anyone' | 'back-office'
862
+ /** Member groups, by name, given `level`. */
863
+ groups?: string[]
864
+ /** `read`: they may see it; `change`: see and change it; `none`: neither. */
865
+ level?: 'read' | 'change' | 'none'
866
+ /** True: follow the folder above again. False: its own settings, starting from the folder above's. */
867
+ inherit?: boolean
868
+ }
869
+
870
+ /**
871
+ * The dialog's form with a change made, refused when it names a group the site
872
+ * does not have. Pure: the dialog's own rules turn the form into what is saved.
873
+ */
874
+ export function changedForm(state: MediaAccessState, change: MediaAccessChange) {
875
+ if (change.inherit === true) return { ...inheritedForm(state), inherit: true }
876
+ const form = { ...formFor(state), inherit: false }
877
+ form.groups = form.groups.map((g) => ({ ...g }))
878
+ if (change.see) {
879
+ form.read = change.see === 'anyone' ? 'public' : 'private'
880
+ form.allMembers = false
881
+ }
882
+ for (const wanted of change.groups ?? []) {
883
+ const row = form.groups.find((g) => g.name.toLowerCase() === wanted.trim().toLowerCase())
884
+ if (!row || !state.memberGroups.some((name) => name.toLowerCase() === row.name.toLowerCase()))
885
+ throw new MediaLibraryError(
886
+ 'not_found',
887
+ `There is no member group "${wanted}".`,
888
+ state.memberGroups.length > 0
889
+ ? `The site's member groups are ${listed(state.memberGroups)}.`
890
+ : 'This site has no member groups yet.',
891
+ )
892
+ const level = change.level ?? 'read'
893
+ row.read = level !== 'none'
894
+ row.write = level === 'change'
895
+ if (level === 'read') {
896
+ form.read = 'custom'
897
+ form.allMembers = false
898
+ }
899
+ if (level === 'change') form.write = 'custom'
900
+ }
901
+ return form
902
+ }
903
+
904
+ /**
905
+ * Sets who may see and change a folder or item, as the Permissions dialog sets
906
+ * them; what the change does not name (chosen members, member uploads and the
907
+ * defaults for new files) is kept.
908
+ */
909
+ export async function setMediaAccess(
910
+ context: MediaAccessContext,
911
+ actor: Actor,
912
+ ref: string,
913
+ change: MediaAccessChange,
914
+ ): Promise<MediaAccessView> {
915
+ const node = await mediaNode(context.db, actor, ref)
916
+ await accessRefused(context, actor, node, true)
917
+ const state = await describeMediaAccess(context, node.key)
918
+ if (!state) throw new MediaLibraryError('not_found', 'The media item could not be found.')
919
+ const request = requestFor(changedForm(state, change), state.item)
920
+ await saveMediaAccess(context, node.key, {
921
+ rule: request.rule as RuleBody | null,
922
+ item: request.item as { readPolicy: MediaPolicy; writePolicy: MediaPolicy },
923
+ })
924
+ return accessView(context, node)
925
+ }
926
+
927
+ /** A change to permissions as a request body gives it; a sentence when it is not one. Pure. */
928
+ export function readAccessChange(raw: unknown): MediaAccessChange | string {
929
+ if (!raw || typeof raw !== 'object') return 'Send the change to make.'
930
+ const body = raw as Record<string, unknown>
931
+ const out: MediaAccessChange = {}
932
+ if (body.see !== undefined) {
933
+ if (body.see !== 'anyone' && body.see !== 'back-office') return 'see is anyone or back-office.'
934
+ out.see = body.see
935
+ }
936
+ if (body.groups !== undefined) {
937
+ if (!Array.isArray(body.groups) || body.groups.some((g) => typeof g !== 'string' || !g.trim()))
938
+ return 'groups is a list of member group names.'
939
+ out.groups = body.groups as string[]
940
+ }
941
+ if (body.level !== undefined) {
942
+ if (body.level !== 'read' && body.level !== 'change' && body.level !== 'none')
943
+ return 'level is read, change or none.'
944
+ out.level = body.level
945
+ }
946
+ if (body.inherit !== undefined) {
947
+ if (typeof body.inherit !== 'boolean') return 'inherit is true or false.'
948
+ out.inherit = body.inherit
949
+ }
950
+ if (out.inherit === true && (out.see || out.groups))
951
+ return 'Following the folder above takes no other change.'
952
+ return out
953
+ }