@crombolo/content 0.65.1 → 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.
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@crombolo/content",
3
- "version": "0.65.1",
4
- "description": "Internal to crombolo, with no compatibility promise: use @crombolo/crombolo. The rules every page and media write follows, whoever starts it: who may, where it may go, approvals, and what it announces. No transport.",
3
+ "version": "0.66.0",
4
+ "description": "Internal to crombolo, with no compatibility promise: use @crombolo/crombolo. The rules every page, media and Library write follows, whoever starts it: who may, where it may go, approvals, and what it announces. No transport.",
5
5
  "license": "MIT",
6
6
  "author": "Crombolo",
7
7
  "homepage": "https://github.com/kineco-au/crombolo-cms#readme",
@@ -29,7 +29,7 @@
29
29
  "access": "public"
30
30
  },
31
31
  "dependencies": {
32
- "@crombolo/core": "0.65.1",
33
- "@crombolo/data": "0.65.1"
32
+ "@crombolo/core": "0.66.0",
33
+ "@crombolo/data": "0.66.0"
34
34
  }
35
35
  }
package/src/actor.ts CHANGED
@@ -32,8 +32,11 @@ export interface ActorOrigin {
32
32
  }
33
33
 
34
34
  export type Actor =
35
- /** A signed-in user: their permissions, start nodes, languages and approvals. */
36
- | { kind: 'user'; principal: ContentPrincipal; origin: ActorOrigin }
35
+ /**
36
+ * A signed-in user: their permissions, start nodes, languages and approvals.
37
+ * An administrator at the command line may say `skipApproval` (story 350).
38
+ */
39
+ | { kind: 'user'; principal: ContentPrincipal; origin: ActorOrigin; skipApproval?: boolean }
37
40
  /**
38
41
  * Someone at the command line on the box: no permission checks, since they hold
39
42
  * the database, but approvals apply unless they say `skipApproval`, which the
@@ -85,8 +88,14 @@ export const memberActor = (
85
88
 
86
89
  export const userActor = (
87
90
  principal: ContentPrincipal,
88
- origin: Omit<ActorOrigin, 'source'> = {},
89
- ): Actor => ({ kind: 'user', principal, origin: { source: 'request', ...origin } })
91
+ origin: Partial<ActorOrigin> = {},
92
+ options: { skipApproval?: boolean } = {},
93
+ ): Actor => ({
94
+ kind: 'user',
95
+ principal,
96
+ origin: { source: 'request', ...origin },
97
+ ...(options.skipApproval ? { skipApproval: true } : {}),
98
+ })
90
99
 
91
100
  export const operatorActor = (name: string, options: { skipApproval?: boolean } = {}): Actor => ({
92
101
  kind: 'operator',
@@ -0,0 +1,294 @@
1
+ /**
2
+ * Every Library write, once (story 361), as `operations.ts` is for pages and
3
+ * `media-operations.ts` for media: the back office and the command line call
4
+ * these, so a write follows the same rules whoever starts it — the Library
5
+ * verbs a user's groups hold, and one transaction holding the change, its audit
6
+ * entry and the cache instruction.
7
+ *
8
+ * The storage beneath is the elements adapter, which keeps the menu alias rule
9
+ * and appends the cache instruction. The Library has no approvals and no start
10
+ * nodes, so what is decided here is who may, and what is recorded.
11
+ */
12
+ import type { DocumentValidationError } from '@crombolo/core'
13
+ import { type Db, Locks } from '@crombolo/data'
14
+ import { type Actor, actorUserKey } from './actor.ts'
15
+ import type { ElementEvent, ElementEventSink } from './events.ts'
16
+ import type { DocumentInput, Refusal, Result, ScheduleEntry } from './operations.ts'
17
+ import { type ElementWriteKind, mayInLibrary } from './policy.ts'
18
+
19
+ /** An element as a save sends it; it has no template, whatever `componentKey` says. */
20
+ export type ElementInput = DocumentInput
21
+
22
+ /** Whom a version names as its author: a user, by key. */
23
+ export type ElementAuthor = { id: string } | null
24
+
25
+ /** A storage write that did not happen, and why. */
26
+ export interface StoreFailure {
27
+ ok: false
28
+ reason: string
29
+ status?: number
30
+ errors?: DocumentValidationError[]
31
+ }
32
+
33
+ /** The writes beneath the operations, on one database handle: the elements adapter. */
34
+ export interface ElementStore {
35
+ create(
36
+ input: ElementInput,
37
+ author: ElementAuthor,
38
+ ): Promise<{ ok: true; key: string } | StoreFailure>
39
+ update(
40
+ key: string,
41
+ input: ElementInput,
42
+ author: ElementAuthor,
43
+ ): Promise<{ ok: true } | StoreFailure>
44
+ createAndPublish(
45
+ input: ElementInput,
46
+ cultures: string[] | null,
47
+ author: ElementAuthor,
48
+ ): Promise<{ ok: true; key: string } | StoreFailure>
49
+ updateAndPublish(
50
+ key: string,
51
+ input: ElementInput,
52
+ cultures: string[] | null,
53
+ author: ElementAuthor,
54
+ ): Promise<{ ok: true } | StoreFailure>
55
+ publish(
56
+ key: string,
57
+ cultures: string[] | null,
58
+ schedules?: readonly ScheduleEntry[],
59
+ ): Promise<{ ok: true; scheduledOnly: boolean } | StoreFailure>
60
+ unpublish(key: string, cultures: string[] | null): Promise<{ ok: true } | StoreFailure>
61
+ copy(
62
+ key: string,
63
+ targetKey: string | null,
64
+ options: { includeDescendants: boolean },
65
+ author: ElementAuthor,
66
+ ): Promise<{ ok: true; key: string } | StoreFailure>
67
+ move(key: string, targetKey: string | null): Promise<{ ok: true } | StoreFailure>
68
+ moveToRecycleBin(key: string): Promise<boolean>
69
+ moveFolder(key: string, targetKey: string | null): Promise<{ ok: true } | StoreFailure>
70
+ folderToRecycleBin(key: string): Promise<boolean>
71
+ folders: {
72
+ createFolder(input: {
73
+ key?: string
74
+ name: string
75
+ parentKey: string | null
76
+ }): Promise<{ key: string }>
77
+ renameFolder(key: string, name: string): Promise<boolean>
78
+ }
79
+ }
80
+
81
+ export interface ElementOperationsOptions {
82
+ db: Db
83
+ /** The storage on a handle: the operations hand it the change's transaction. */
84
+ store(db: Db): ElementStore
85
+ events: ElementEventSink
86
+ /** Told after every committed change, for a cache held in this process. */
87
+ onChange?(): void | Promise<void>
88
+ }
89
+
90
+ export type ElementOperations = ReturnType<typeof createElementOperations>
91
+
92
+ const FORBIDDEN = 'You may not do that in the Library.'
93
+
94
+ /** A storage failure as a refusal, its status kept for the transport. */
95
+ function refusalOf(failure: StoreFailure): Refusal {
96
+ const status = failure.status ?? 400
97
+ const kind: Refusal['kind'] = failure.errors
98
+ ? 'validation'
99
+ : status === 404
100
+ ? 'notFound'
101
+ : status === 403
102
+ ? 'forbidden'
103
+ : status === 409
104
+ ? 'conflict'
105
+ : 'invalid'
106
+ return {
107
+ ok: false,
108
+ kind,
109
+ status,
110
+ reason: failure.reason,
111
+ ...(failure.errors ? { errors: failure.errors } : {}),
112
+ }
113
+ }
114
+
115
+ /** Thrown inside a write's transaction so a refused write leaves nothing behind. */
116
+ class Refused extends Error {
117
+ constructor(readonly refusal: Refusal) {
118
+ super(refusal.reason)
119
+ }
120
+ }
121
+
122
+ export function createElementOperations(options: ElementOperationsOptions) {
123
+ const { db, events } = options
124
+
125
+ /**
126
+ * Whether the actor may do `kind` in the Library. Only a user is checked: an
127
+ * operator holds the database and the system acts on what was already decided.
128
+ */
129
+ const permits = (actor: Actor, kind: ElementWriteKind): boolean =>
130
+ actor.kind !== 'user' || mayInLibrary(actor.principal, kind)
131
+
132
+ const authorOf = (actor: Actor): ElementAuthor => {
133
+ const key = actorUserKey(actor)
134
+ return key ? { id: key } : null
135
+ }
136
+
137
+ /**
138
+ * The write, its events and the cache instruction in one transaction: a
139
+ * refused write rolls back whatever it began. What only a running server does
140
+ * follows the commit.
141
+ */
142
+ const commit = async <T extends object>(
143
+ actor: Actor,
144
+ kind: ElementWriteKind,
145
+ write: (store: ElementStore) => Promise<({ ok: true } & T) | StoreFailure>,
146
+ announce: (done: { ok: true } & T) => ElementEvent,
147
+ ): Promise<Result<T>> => {
148
+ if (!permits(actor, kind))
149
+ return { ok: false, kind: 'forbidden', status: 403, reason: FORBIDDEN }
150
+ let event: ElementEvent | undefined
151
+ try {
152
+ // The tree lock before the transaction, as every page and element write takes them.
153
+ const done = await db.locks.withLock(Locks.ContentTree, () =>
154
+ db.transaction(async (tx) => {
155
+ const result = await write(options.store(tx))
156
+ if (!result.ok) throw new Refused(refusalOf(result))
157
+ event = announce(result)
158
+ await events.record(tx, event, actor)
159
+ return result
160
+ }),
161
+ )
162
+ if (event) events.afterCommit?.(event, actor)
163
+ await options.onChange?.()
164
+ return done as Result<T>
165
+ } catch (error) {
166
+ if (error instanceof Refused) return error.refusal
167
+ throw error
168
+ }
169
+ }
170
+
171
+ /** A write the storage answers with true or false: false is not found. */
172
+ const found = (done: boolean, reason: string): { ok: true } | StoreFailure =>
173
+ done ? { ok: true } : { ok: false, reason, status: 404 }
174
+
175
+ return {
176
+ create: (actor: Actor, input: ElementInput) =>
177
+ commit(
178
+ actor,
179
+ 'create',
180
+ (store) => store.create(input, authorOf(actor)),
181
+ (done) => ({ type: 'created', key: done.key }),
182
+ ),
183
+
184
+ save: (actor: Actor, key: string, input: ElementInput) =>
185
+ commit(
186
+ actor,
187
+ 'save',
188
+ (store) => store.update(key, input, authorOf(actor)),
189
+ () => ({ type: 'saved', key }),
190
+ ),
191
+
192
+ createAndPublish: (actor: Actor, input: ElementInput, cultures: string[] | null) =>
193
+ commit(
194
+ actor,
195
+ 'createAndPublish',
196
+ (store) => store.createAndPublish(input, cultures, authorOf(actor)),
197
+ (done) => ({ type: 'createdAndPublished', key: done.key }),
198
+ ),
199
+
200
+ saveAndPublish: (actor: Actor, key: string, input: ElementInput, cultures: string[] | null) =>
201
+ commit(
202
+ actor,
203
+ 'saveAndPublish',
204
+ (store) => store.updateAndPublish(key, input, cultures, authorOf(actor)),
205
+ () => ({ type: 'savedAndPublished', key }),
206
+ ),
207
+
208
+ /** Publishes now, or schedules: a publish time still to come schedules that culture. */
209
+ publish: (
210
+ actor: Actor,
211
+ key: string,
212
+ cultures: string[] | null,
213
+ schedules: readonly ScheduleEntry[] = [],
214
+ ) =>
215
+ commit(
216
+ actor,
217
+ 'publish',
218
+ (store) => store.publish(key, cultures, schedules),
219
+ () => ({ type: 'published', key }),
220
+ ),
221
+
222
+ unpublish: (actor: Actor, key: string, cultures: string[] | null) =>
223
+ commit(
224
+ actor,
225
+ 'unpublish',
226
+ (store) => store.unpublish(key, cultures),
227
+ () => ({ type: 'unpublished', key }),
228
+ ),
229
+
230
+ copy: (
231
+ actor: Actor,
232
+ key: string,
233
+ targetKey: string | null,
234
+ copyOptions: { includeDescendants: boolean } = { includeDescendants: false },
235
+ ) =>
236
+ commit(
237
+ actor,
238
+ 'copy',
239
+ (store) => store.copy(key, targetKey, copyOptions, authorOf(actor)),
240
+ (done) => ({ type: 'copied', key, copyKey: done.key }),
241
+ ),
242
+
243
+ move: (actor: Actor, key: string, targetKey: string | null) =>
244
+ commit(
245
+ actor,
246
+ 'move',
247
+ (store) => store.move(key, targetKey),
248
+ () => ({ type: 'moved', key }),
249
+ ),
250
+
251
+ trash: (actor: Actor, key: string) =>
252
+ commit(
253
+ actor,
254
+ 'trash',
255
+ async (store) =>
256
+ found(await store.moveToRecycleBin(key), 'The element could not be found.'),
257
+ () => ({ type: 'trashed', key }),
258
+ ),
259
+
260
+ createFolder: (actor: Actor, input: { key?: string; name: string; parentKey: string | null }) =>
261
+ commit(
262
+ actor,
263
+ 'createFolder',
264
+ async (store) => ({ ok: true as const, ...(await store.folders.createFolder(input)) }),
265
+ (done) => ({ type: 'folderCreated', key: done.key }),
266
+ ),
267
+
268
+ renameFolder: (actor: Actor, key: string, name: string) =>
269
+ commit(
270
+ actor,
271
+ 'renameFolder',
272
+ async (store) =>
273
+ found(await store.folders.renameFolder(key, name), 'The folder could not be found.'),
274
+ () => ({ type: 'folderRenamed', key }),
275
+ ),
276
+
277
+ moveFolder: (actor: Actor, key: string, targetKey: string | null) =>
278
+ commit(
279
+ actor,
280
+ 'moveFolder',
281
+ (store) => store.moveFolder(key, targetKey),
282
+ () => ({ type: 'folderMoved', key }),
283
+ ),
284
+
285
+ trashFolder: (actor: Actor, key: string) =>
286
+ commit(
287
+ actor,
288
+ 'trashFolder',
289
+ async (store) =>
290
+ found(await store.folderToRecycleBin(key), 'The folder could not be found.'),
291
+ () => ({ type: 'folderTrashed', key }),
292
+ ),
293
+ }
294
+ }
package/src/events.ts CHANGED
@@ -248,7 +248,8 @@ export function liveEventsFor(event: DocumentEvent): Array<{
248
248
  */
249
249
  export function auditEntryFor(event: DocumentEvent, actor: Actor) {
250
250
  const entry = auditFor(event)
251
- const skipped = actor.kind === 'operator' && actor.skipApproval === true
251
+ const skipped =
252
+ (actor.kind === 'operator' || actor.kind === 'user') && actor.skipApproval === true
252
253
  return {
253
254
  ...entry,
254
255
  source: actor.origin.source,
@@ -265,3 +266,87 @@ export function auditEntryFor(event: DocumentEvent, actor: Actor) {
265
266
  /** A note as the audit log writes it: a capital first, as its entries read. */
266
267
  const sentence = (note: string | undefined) =>
267
268
  note ? note.charAt(0).toUpperCase() + note.slice(1) : undefined
269
+
270
+ /** What a Library write did (story 361): an element, or one of the folders they sit in. */
271
+ export type ElementEvent =
272
+ | { type: 'created'; key: string }
273
+ | { type: 'saved'; key: string }
274
+ | { type: 'createdAndPublished'; key: string }
275
+ | { type: 'savedAndPublished'; key: string }
276
+ /** Published now, or only scheduled to be. */
277
+ | { type: 'published'; key: string }
278
+ | { type: 'unpublished'; key: string }
279
+ | { type: 'trashed'; key: string }
280
+ | { type: 'moved'; key: string }
281
+ | { type: 'copied'; key: string; copyKey: string }
282
+ | { type: 'folderCreated'; key: string }
283
+ | { type: 'folderRenamed'; key: string }
284
+ | { type: 'folderMoved'; key: string }
285
+ | { type: 'folderTrashed'; key: string }
286
+
287
+ /** Where a Library operation records what it did, inside the change's transaction. */
288
+ export interface ElementEventSink {
289
+ record(tx: Db, event: ElementEvent, actor: Actor): Promise<void>
290
+ afterCommit?(event: ElementEvent, actor: Actor): void
291
+ }
292
+
293
+ /**
294
+ * The audit entry a Library event writes: the category and action names the
295
+ * back office has always written for it. A copy is entered against the original.
296
+ * Pure.
297
+ */
298
+ export function elementAuditFor(event: ElementEvent): {
299
+ category: 'content'
300
+ action: string
301
+ entityType: 'Element' | 'ElementFolder'
302
+ entityKey: string
303
+ } {
304
+ const element = (action: string) => ({
305
+ category: 'content' as const,
306
+ action,
307
+ entityType: 'Element' as const,
308
+ entityKey: event.key,
309
+ })
310
+ const folder = (action: string) => ({ ...element(action), entityType: 'ElementFolder' as const })
311
+ switch (event.type) {
312
+ case 'created':
313
+ return element('Create')
314
+ case 'saved':
315
+ return element('Save')
316
+ case 'createdAndPublished':
317
+ return element('CreateAndPublish')
318
+ case 'savedAndPublished':
319
+ return element('SaveAndPublish')
320
+ case 'published':
321
+ return element('Publish')
322
+ case 'unpublished':
323
+ return element('Unpublish')
324
+ case 'trashed':
325
+ return element('Trash')
326
+ case 'moved':
327
+ return element('Move')
328
+ case 'copied':
329
+ return element('Copy')
330
+ case 'folderCreated':
331
+ return folder('Create')
332
+ case 'folderRenamed':
333
+ return folder('Save')
334
+ case 'folderMoved':
335
+ return folder('Move')
336
+ case 'folderTrashed':
337
+ return folder('Trash')
338
+ }
339
+ }
340
+
341
+ /** The whole audit entry a Library event writes, with who acted and from where. Pure. */
342
+ export function elementAuditEntryFor(event: ElementEvent, actor: Actor) {
343
+ return {
344
+ ...elementAuditFor(event),
345
+ source: actor.origin.source,
346
+ userKey: actorUserKey(actor),
347
+ userName: actorName(actor),
348
+ ipAddress: actor.origin.ipAddress ?? null,
349
+ forwardedFor: actor.origin.forwardedFor ?? null,
350
+ detail: sentence(actorNote(actor)) ?? null,
351
+ }
352
+ }
package/src/index.ts CHANGED
@@ -1,3 +1,4 @@
1
+ export * from './element-operations.ts'
1
2
  export * from './media-operations.ts'
2
3
  export * from './operations.ts'
3
4
  export * from './rules.ts'
package/src/operations.ts CHANGED
@@ -300,7 +300,8 @@ export function createDocumentOperations(options: DocumentOperationsOptions) {
300
300
 
301
301
  /** The approval gate, as the actor meets it; `skip` for the system and an operator who chose to. */
302
302
  const gateFor = (actor: Actor): { skip: boolean; who: ContentPrincipal | undefined } => {
303
- if (actor.kind === 'user') return { skip: false, who: actor.principal }
303
+ if (actor.kind === 'user')
304
+ return { skip: actor.skipApproval === true && actor.principal.isAdmin, who: actor.principal }
304
305
  if (actor.kind === 'operator') return { skip: actor.skipApproval === true, who: undefined }
305
306
  return { skip: true, who: undefined }
306
307
  }
package/src/policy.ts CHANGED
@@ -6,6 +6,7 @@
6
6
  */
7
7
  import {
8
8
  DocumentPermissions as D,
9
+ ElementPermissions as E,
9
10
  fallbackPermissions,
10
11
  hasPathAccess,
11
12
  MediaPermissions as M,
@@ -38,6 +39,45 @@ export const WRITE_VERBS = {
38
39
 
39
40
  export type WriteKind = keyof typeof WRITE_VERBS
40
41
 
42
+ /**
43
+ * The Library verbs each element and element folder write needs (story 361),
44
+ * held in the groups' fallback permissions: group-wide, with no start nodes.
45
+ */
46
+ export const ELEMENT_VERBS = {
47
+ read: [E.Read],
48
+ create: [E.Create],
49
+ save: [E.Update],
50
+ createAndPublish: [E.Publish],
51
+ saveAndPublish: [E.Publish],
52
+ publish: [E.Publish],
53
+ unpublish: [E.Unpublish],
54
+ trash: [E.Delete],
55
+ delete: [E.Delete],
56
+ move: [E.Move],
57
+ copy: [E.Duplicate, E.Create],
58
+ rollback: [E.Rollback],
59
+ /** The recycle bin: restoring moves an element or folder out of it. */
60
+ restore: [E.Move],
61
+ /** Emptying the bin deletes the folders in it as well as the elements. */
62
+ emptyBin: [E.Delete],
63
+ createFolder: [E.Create],
64
+ renameFolder: [E.Update],
65
+ deleteFolder: [E.Delete],
66
+ moveFolder: [E.Move],
67
+ trashFolder: [E.Delete],
68
+ } as const satisfies Record<string, readonly string[]>
69
+
70
+ export type ElementWriteKind = keyof typeof ELEMENT_VERBS
71
+
72
+ /** Whether the user's groups hold every Library verb `kind` needs. Pure. */
73
+ export const mayInLibrary = (
74
+ principal: Pick<ContentPrincipal, 'groups'>,
75
+ kind: ElementWriteKind,
76
+ ): boolean => {
77
+ const granted = fallbackPermissions(principal.groups)
78
+ return ELEMENT_VERBS[kind].every((verb) => granted.has(verb))
79
+ }
80
+
41
81
  /** Whether the user holds a section, named in either vocabulary. Pure. */
42
82
  export const holdsSection = (principal: ContentPrincipal, section: string): boolean =>
43
83
  principal.allowedSections.some((alias) => sectionKey(alias) === sectionKey(section))