@crombolo/api-management 0.22.0 → 0.23.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,6 +1,6 @@
1
1
  {
2
2
  "name": "@crombolo/api-management",
3
- "version": "0.22.0",
3
+ "version": "0.23.0",
4
4
  "description": "Umbraco-compatible Management API handlers for crombolo.",
5
5
  "license": "MIT",
6
6
  "author": "Crombolo",
@@ -28,7 +28,8 @@
28
28
  "access": "public"
29
29
  },
30
30
  "dependencies": {
31
- "@crombolo/core": "0.22.0",
32
- "@crombolo/contracts": "0.22.0"
31
+ "@crombolo/content": "0.23.0",
32
+ "@crombolo/contracts": "0.23.0",
33
+ "@crombolo/core": "0.23.0"
33
34
  }
34
35
  }
@@ -7,6 +7,7 @@
7
7
  * involved, which their port enforces. See docs/backoffice-hosting.md for the
8
8
  * tables' provenance.
9
9
  */
10
+ import { WRITE_VERBS as W } from '@crombolo/content/rules'
10
11
  import type { OperationInfo } from '@crombolo/contracts'
11
12
  import {
12
13
  type AppAlias,
@@ -17,12 +18,13 @@ import {
17
18
  hasPathAccess,
18
19
  MediaPermissions as M,
19
20
  permissionsForPath,
20
- propertyValuePermissions,
21
21
  type StartNodes,
22
22
  sectionKey,
23
23
  } from '@crombolo/core'
24
24
  import type { Principal } from './router.ts'
25
25
 
26
+ export { deniedPropertyWrite, type PropertyValueRef } from '@crombolo/content/rules'
27
+
26
28
  /**
27
29
  * Operations behind Umbraco's `DenyLocalLoginIfConfigured` policy: the contract
28
30
  * marks them secured, but while local login is allowed the policy lets anyone
@@ -241,6 +243,7 @@ interface DocumentRule {
241
243
  }
242
244
 
243
245
  const id: NodeRef = { param: 'id' }
246
+ // The writes take their verbs from the operations' table, which applies them again.
244
247
  const DOCUMENT_RULES: Record<string, readonly DocumentRule[]> = {
245
248
  GetDocumentById: [{ verbs: [D.Read], node: id }],
246
249
  GetDocumentByIdPublished: [{ verbs: [D.Read], node: id }],
@@ -259,48 +262,48 @@ const DOCUMENT_RULES: Record<string, readonly DocumentRule[]> = {
259
262
  // the parent is the same boundary expressed once: a caller who cannot reach the
260
263
  // parent's path cannot reach anything below it either.
261
264
  GetCollectionDocumentById: [{ verbs: [D.Read], node: id }],
262
- PostDocument: [{ verbs: [D.Create], node: { body: ['parent', 'id'] } }],
265
+ PostDocument: [{ verbs: W.create, node: { body: ['parent', 'id'] } }],
263
266
  PostDocumentValidate: [{ verbs: [D.Create], node: { body: ['parent', 'id'] } }],
264
- PutDocumentById: [{ verbs: [D.Update], node: id }],
265
- PatchDocumentByIdPatch: [{ verbs: [D.Update], node: id }],
267
+ PutDocumentById: [{ verbs: W.save, node: id }],
268
+ PatchDocumentByIdPatch: [{ verbs: W.save, node: id }],
266
269
  PutDocumentByIdValidate: [{ verbs: [D.Update], node: id }],
267
270
  PostDocumentCreateAndPublish: [
268
- { verbs: [D.Publish], node: { body: ['parent', 'id'] }, cultures: true },
271
+ { verbs: W.publish, node: { body: ['parent', 'id'] }, cultures: true },
269
272
  ],
270
- PutDocumentByIdUpdateAndPublish: [{ verbs: [D.Publish], node: id, cultures: true }],
271
- PutDocumentByIdPublish: [{ verbs: [D.Publish], node: id, cultures: true }],
273
+ PutDocumentByIdUpdateAndPublish: [{ verbs: W.publish, node: id, cultures: true }],
274
+ PutDocumentByIdPublish: [{ verbs: W.publish, node: id, cultures: true }],
272
275
  PutDocumentByIdPublishWithDescendants: [
273
- { verbs: [D.Publish], node: id, branch: true, cultures: true },
276
+ { verbs: W.publish, node: id, branch: true, cultures: true },
274
277
  ],
275
- PutDocumentByIdUnpublish: [{ verbs: [D.Unpublish], node: id, cultures: true }],
276
- DeleteDocumentById: [{ verbs: [D.Delete], node: id }],
277
- PutDocumentByIdMoveToRecycleBin: [{ verbs: [D.Delete], node: id }],
278
+ PutDocumentByIdUnpublish: [{ verbs: W.unpublish, node: id, cultures: true }],
279
+ DeleteDocumentById: [{ verbs: W.delete, node: id }],
280
+ PutDocumentByIdMoveToRecycleBin: [{ verbs: W.trash, node: id }],
278
281
  PutDocumentByIdMove: [
279
- { verbs: [D.Move], node: id },
280
- { verbs: [D.Create], node: { body: ['target', 'id'] } },
282
+ { verbs: W.move, node: id },
283
+ { verbs: W.intoTarget, node: { body: ['target', 'id'] } },
281
284
  ],
282
285
  PostDocumentByIdCopy: [
283
- { verbs: [D.Duplicate], node: id },
284
- { verbs: [D.Create], node: { body: ['target', 'id'] } },
286
+ { verbs: W.copy, node: id },
287
+ { verbs: W.intoTarget, node: { body: ['target', 'id'] } },
285
288
  ],
286
289
  PutDocumentSort: [
287
- { verbs: [D.Sort], node: { body: ['parent', 'id'] } },
288
- { verbs: [D.Sort], node: { body: ['sorting', '*', 'id'] } },
290
+ { verbs: W.sort, node: { body: ['parent', 'id'] } },
291
+ { verbs: W.sort, node: { body: ['sorting', '*', 'id'] } },
289
292
  ],
290
- PutDocumentByIdSortChildren: [{ verbs: [D.Sort], node: id }],
291
- PutDocumentRootSortChildren: [{ verbs: [D.Sort], node: 'root' }],
293
+ PutDocumentByIdSortChildren: [{ verbs: W.sort, node: id }],
294
+ PutDocumentRootSortChildren: [{ verbs: W.sort, node: 'root' }],
292
295
  GetDocumentByIdPublicAccess: [{ verbs: [D.PublicAccess], node: id }],
293
- PostDocumentByIdPublicAccess: [{ verbs: [D.PublicAccess], node: id }],
294
- PutDocumentByIdPublicAccess: [{ verbs: [D.PublicAccess], node: id }],
295
- DeleteDocumentByIdPublicAccess: [{ verbs: [D.PublicAccess], node: id }],
296
- PutDocumentByIdDomains: [{ verbs: [D.CultureAndHostnames], node: id }],
297
- PostDocumentVersionByIdRollback: [{ verbs: [D.Rollback], node: { version: 'id' } }],
296
+ PostDocumentByIdPublicAccess: [{ verbs: W.publicAccess, node: id }],
297
+ PutDocumentByIdPublicAccess: [{ verbs: W.publicAccess, node: id }],
298
+ DeleteDocumentByIdPublicAccess: [{ verbs: W.publicAccess, node: id }],
299
+ PutDocumentByIdDomains: [{ verbs: W.domains, node: id }],
300
+ PostDocumentVersionByIdRollback: [{ verbs: W.rollback, node: { version: 'id' } }],
298
301
  PostDocumentBlueprintFromDocument: [
299
302
  { verbs: [D.CreateBlueprint], node: { body: ['document', 'id'] } },
300
303
  ],
301
- DeleteRecycleBinDocument: [{ verbs: [D.Delete], node: 'bin' }],
302
- DeleteRecycleBinDocumentById: [{ verbs: [D.Delete], node: 'bin' }],
303
- PutRecycleBinDocumentByIdRestore: [{ verbs: [D.Move], node: 'bin' }],
304
+ DeleteRecycleBinDocument: [{ verbs: W.emptyBin, node: 'bin' }],
305
+ DeleteRecycleBinDocumentById: [{ verbs: W.delete, node: 'bin' }],
306
+ PutRecycleBinDocumentByIdRestore: [{ verbs: W.restore, node: 'bin' }],
304
307
  GetRecycleBinDocumentByIdOriginalParent: [{ verbs: [D.Read], node: 'bin' }],
305
308
  }
306
309
 
@@ -462,61 +465,6 @@ export function deniedChildren(principal: Principal, parentChain: readonly strin
462
465
  )
463
466
  }
464
467
 
465
- /** One property value as a save carries it. */
466
- export interface PropertyValueRef {
467
- alias: string
468
- culture: string | null
469
- segment: string | null
470
- value: unknown
471
- }
472
-
473
- /** JSON with object keys in order, so equal values compare equal however they were built. */
474
- const canonical = (value: unknown): string =>
475
- JSON.stringify(value ?? null, (_key, v) =>
476
- v && typeof v === 'object' && !Array.isArray(v)
477
- ? Object.fromEntries(Object.entries(v).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)))
478
- : v,
479
- )
480
-
481
- /** Each property's values by culture and segment, nulls left out: what a save would leave stored. */
482
- function valuesByAlias(values: readonly PropertyValueRef[]): Map<string, Map<string, string>> {
483
- const out = new Map<string, Map<string, string>>()
484
- for (const v of values) {
485
- if (v.value === null || v.value === undefined) continue
486
- const alias = v.alias.toLowerCase()
487
- const variants = out.get(alias) ?? new Map<string, string>()
488
- const where = `${v.culture?.toLowerCase() ?? ''}|${v.segment ?? ''}`
489
- if (!variants.has(where)) variants.set(where, canonical(v.value))
490
- out.set(alias, variants)
491
- }
492
- return out
493
- }
494
-
495
- /**
496
- * The first property a save would change that the caller's groups may not
497
- * write (`Umb.Document.PropertyValue.Write`, per property type), or undefined.
498
- * A value sent back as it was is not a change; one left out that was stored is.
499
- */
500
- export function deniedPropertyWrite<P extends { alias: string; key: string }>(
501
- principal: Principal,
502
- properties: readonly P[],
503
- before: readonly PropertyValueRef[],
504
- after: readonly PropertyValueRef[],
505
- ): P | undefined {
506
- const old = valuesByAlias(before)
507
- const next = valuesByAlias(after)
508
- for (const property of properties) {
509
- const alias = property.alias.toLowerCase()
510
- const a = old.get(alias) ?? new Map<string, string>()
511
- const b = next.get(alias) ?? new Map<string, string>()
512
- const changed = a.size !== b.size || [...a].some(([where, value]) => b.get(where) !== value)
513
- if (!changed) continue
514
- if (!propertyValuePermissions(principal.groups, property.key).has(D.PropertyValueWrite))
515
- return property
516
- }
517
- return undefined
518
- }
519
-
520
468
  /** Whether the caller may read a document's draft: the Content section, its path, and Read on it. */
521
469
  export async function canReadDocument(
522
470
  principal: Principal,
@@ -0,0 +1,31 @@
1
+ /**
2
+ * The operations whose document writes go through `@crombolo/content` (story
3
+ * 170). Each announces itself — audit entry, webhook, notification, live event —
4
+ * from the operation, the same way the command line and the jobs do, so the
5
+ * router must not announce them a second time from the operation's name.
6
+ */
7
+ export const DOCUMENT_WRITE_OPERATIONS: ReadonlySet<string> = new Set([
8
+ 'PostDocument',
9
+ 'PutDocumentById',
10
+ 'PatchDocumentByIdPatch',
11
+ 'PostDocumentCreateAndPublish',
12
+ 'PutDocumentByIdUpdateAndPublish',
13
+ 'PutDocumentByIdPublish',
14
+ 'PutDocumentByIdUnpublish',
15
+ 'PutDocumentByIdPublishWithDescendants',
16
+ 'PutDocumentByIdMoveToRecycleBin',
17
+ 'DeleteDocumentById',
18
+ 'DeleteRecycleBinDocumentById',
19
+ 'DeleteRecycleBinDocument',
20
+ 'PutRecycleBinDocumentByIdRestore',
21
+ 'PutDocumentByIdMove',
22
+ 'PostDocumentByIdCopy',
23
+ 'PutDocumentSort',
24
+ 'PutDocumentByIdSortChildren',
25
+ 'PutDocumentRootSortChildren',
26
+ 'PostDocumentVersionByIdRollback',
27
+ 'PutDocumentByIdDomains',
28
+ 'PostDocumentByIdPublicAccess',
29
+ 'PutDocumentByIdPublicAccess',
30
+ 'DeleteDocumentByIdPublicAccess',
31
+ ])
@@ -2,6 +2,8 @@
2
2
  * Documents: the tree, the editor's read/write cycle, publishing and versions.
3
3
  */
4
4
 
5
+ import type { DocumentOperations, Refusal } from '@crombolo/content'
6
+ import { userActor } from '@crombolo/content/rules'
5
7
  import type {
6
8
  DocumentAggregate,
7
9
  DocumentTreeItem,
@@ -19,9 +21,9 @@ import {
19
21
  problemResponse,
20
22
  ROOT_ACCESS,
21
23
  } from '@crombolo/core'
22
- import { deniedChildren, deniedPropertyWrite } from '../authorization.ts'
24
+ import { deniedChildren } from '../authorization.ts'
23
25
  import { APP_PREVIEW_PROVIDER, type PreviewPort } from '../ports.ts'
24
- import type { ApprovalGatePort, DocumentPort, PortFailure, SaveDocument } from '../ports-content.ts'
26
+ import type { DocumentPort, PortFailure, SaveDocument } from '../ports-content.ts'
25
27
  import type { ManagementApiRouter, RequestContext } from '../router.ts'
26
28
  import { created, paging } from './content-type.ts'
27
29
  import {
@@ -277,45 +279,34 @@ export function toDocumentTreeItemResponse(item: DocumentTreeItem, noAccess = fa
277
279
  export function registerDocumentHandlers(
278
280
  router: ManagementApiRouter,
279
281
  port: DocumentPort,
282
+ operations: DocumentOperations,
280
283
  preview?: PreviewPort,
281
- approvals?: ApprovalGatePort,
282
284
  ): void {
283
285
  /** A page a workflow covers goes through it: the gate's refusal, as a problem. */
284
286
  const needsApproval = (title: string, detail: string) =>
285
287
  problemResponse(
286
288
  problemDetails({ title, status: 400, detail, operationStatus: 'NeedsApproval' }),
287
289
  )
288
- const principalOf = (ctx: RequestContext) => ctx.principal as NonNullable<typeof ctx.principal>
289
-
290
- /**
291
- * A 403 naming the first property the save would change that the caller's
292
- * groups may not write. Skipped when a group writes every property anyway.
293
- */
294
- const propertyWriteRefusal = async (
295
- ctx: RequestContext,
296
- key: string,
297
- existing: DocumentAggregate | undefined,
298
- values: readonly DocumentValue[],
299
- ): Promise<Response | undefined> => {
300
- const principal = ctx.principal
301
- if (!principal || !existing || !port.propertyTypes) return undefined
302
- const writesAll = principal.groups.some(
303
- (group) =>
304
- !group.properties?.size && group.defaults.includes(DocumentPermissions.PropertyValueWrite),
305
- )
306
- if (writesAll) return undefined
307
- const denied = deniedPropertyWrite(
308
- principal,
309
- (await port.propertyTypes(key)) ?? [],
310
- existing.values,
311
- values,
312
- )
313
- if (!denied) return undefined
290
+ /** The signed-in user, as the operations know them: their rules apply (story 170). */
291
+ const actorOf = (ctx: RequestContext) =>
292
+ userActor(ctx.principal as NonNullable<typeof ctx.principal>, ctx.client ?? {})
293
+
294
+ /** An operation's refusal as the problem the client reads; `approval` titles a gate refusal. */
295
+ const refused = (
296
+ result: Refusal,
297
+ title: string,
298
+ options: { sent?: readonly DocumentValue[]; approval?: string; operationStatus?: string } = {},
299
+ ) => {
300
+ if (result.kind === 'needsApproval')
301
+ return needsApproval(options.approval ?? title, result.reason)
302
+ if (result.kind === 'validation' && result.errors)
303
+ return problemResponse(validationProblem(result.errors, options.sent ?? []))
314
304
  return problemResponse(
315
305
  problemDetails({
316
- title: 'Could not save the document',
317
- status: 403,
318
- detail: `You may not change "${denied.name}" (${denied.alias}).`,
306
+ title,
307
+ status: result.status,
308
+ detail: result.reason,
309
+ ...(options.operationStatus ? { operationStatus: options.operationStatus } : {}),
319
310
  }),
320
311
  )
321
312
  }
@@ -371,18 +362,12 @@ export function registerDocumentHandlers(
371
362
  const body = await readBody(ctx)
372
363
  const key = typeof body.id === 'string' && body.id ? body.id : crypto.randomUUID()
373
364
  const input = toSaveDocument(key, body)
374
- const refusal = await approvals?.newPageRefusal(
375
- principalOf(ctx),
376
- input.parentKey,
377
- input.contentTypeKey,
378
- )
379
- if (refusal) return needsApproval('The document needs approval before it is published', refusal)
380
- const result = await port.createAndPublish(
381
- input,
382
- readCultures(body),
383
- ctx.principal as NonNullable<typeof ctx.principal>,
384
- )
385
- if (!result.ok) return failureResponse('Could not create the document', result, input.values)
365
+ const result = await operations.createAndPublish(actorOf(ctx), input, readCultures(body))
366
+ if (!result.ok)
367
+ return refused(result, 'Could not create the document', {
368
+ sent: input.values,
369
+ approval: 'The document needs approval before it is published',
370
+ })
386
371
  return created(
387
372
  `${ctx.url.pathname.replace(/\/create-and-publish$/, '')}/${result.key}`,
388
373
  result.key,
@@ -393,24 +378,17 @@ export function registerDocumentHandlers(
393
378
  const body = await readBody(ctx)
394
379
  const key = ctx.params.id as string
395
380
  const input = toSaveDocument(key, body)
396
- const denied = await propertyWriteRefusal(ctx, key, await port.byKey(key), input.values)
397
- if (denied) return denied
398
- const refusal =
399
- (await approvals?.beforeSave(principalOf(ctx), key)) ??
400
- (await approvals?.publishRefusal(principalOf(ctx), key, 'publish'))
401
- if (refusal) return needsApproval('The document needs approval before it is published', refusal)
402
- const result = await port.updateAndPublish(
403
- key,
404
- input,
405
- readCultures(body),
406
- ctx.principal as NonNullable<typeof ctx.principal>,
407
- )
381
+ const result = await operations.saveAndPublish(actorOf(ctx), key, input, readCultures(body))
408
382
  if (!result.ok) {
409
- if (result.reason === 'The document could not be found.')
410
- return problemResponse(notFound(result.reason))
411
- return failureResponse('Could not publish the document', result, input.values)
383
+ if (result.kind === 'notFound') return problemResponse(notFound(result.reason))
384
+ return refused(
385
+ result,
386
+ result.kind === 'forbidden'
387
+ ? 'Could not save the document'
388
+ : 'Could not publish the document',
389
+ { sent: input.values, approval: 'The document needs approval before it is published' },
390
+ )
412
391
  }
413
- await approvals?.afterDirectPublish?.(principalOf(ctx), key, 'published it')
414
392
  return new Response(null, { status: 200 })
415
393
  })
416
394
 
@@ -510,19 +488,8 @@ export function registerDocumentHandlers(
510
488
  router.handle('PostDocument', async (ctx) => {
511
489
  const body = await readBody(ctx)
512
490
  const key = typeof body.id === 'string' && body.id ? body.id : crypto.randomUUID()
513
- const result = await port.create(
514
- toSaveDocument(key, body),
515
- ctx.principal as NonNullable<typeof ctx.principal>,
516
- )
517
- if (!result.ok) {
518
- return problemResponse(
519
- problemDetails({
520
- title: 'Could not create the document',
521
- status: result.status ?? 400,
522
- detail: result.reason,
523
- }),
524
- )
525
- }
491
+ const result = await operations.create(actorOf(ctx), toSaveDocument(key, body))
492
+ if (!result.ok) return refused(result, 'Could not create the document')
526
493
  ctx.notifications.push({ message: 'Document created', category: 'Content', type: 'Success' })
527
494
  return created(`${ctx.url.origin}/umbraco/management/api/v1/document/${result.key}`, result.key)
528
495
  })
@@ -533,29 +500,15 @@ export function registerDocumentHandlers(
533
500
  existing: DocumentAggregate,
534
501
  body: Record<string, unknown>,
535
502
  ) => {
536
- const denied = await propertyWriteRefusal(ctx, key, existing, readValues(body))
537
- if (denied) return denied
538
- const refusal = await approvals?.beforeSave(principalOf(ctx), key)
539
- if (refusal) return needsApproval('The document is waiting for approval', refusal)
540
- const result = await port.update(
541
- key,
542
- {
543
- ...toSaveDocument(key, body),
544
- // The content type never changes on update.
545
- contentTypeKey: existing.contentTypeKey,
546
- },
547
- ctx.principal as NonNullable<typeof ctx.principal>,
548
- )
549
- if (!result.ok) {
550
- return problemResponse(
551
- problemDetails({
552
- title: 'Could not save the document',
553
- status: result.status ?? 400,
554
- detail: result.reason,
555
- }),
556
- )
557
- }
558
- await approvals?.afterSave(principalOf(ctx), key)
503
+ const result = await operations.save(actorOf(ctx), key, {
504
+ ...toSaveDocument(key, body),
505
+ // The content type never changes on update.
506
+ contentTypeKey: existing.contentTypeKey,
507
+ })
508
+ if (!result.ok)
509
+ return refused(result, 'Could not save the document', {
510
+ approval: 'The document is waiting for approval',
511
+ })
559
512
  ctx.notifications.push({ message: 'Document saved', category: 'Content', type: 'Success' })
560
513
  return new Response(null, { status: 200 })
561
514
  }
@@ -607,47 +560,27 @@ export function registerDocumentHandlers(
607
560
  if (!(await port.byKey(key)))
608
561
  return problemResponse(notFound('The document could not be found'))
609
562
  const body = await readBody(ctx)
610
- const refusal = await approvals?.publishRefusal(principalOf(ctx), key, 'publish')
611
- if (refusal) return needsApproval('The document needs approval before it is published', refusal)
612
563
  const schedules = readSchedules(body)
613
564
  if (schedules === 'invalid')
614
565
  return problemResponse(
615
566
  problemDetails({ title: 'A schedule date is not a valid date', status: 400 }),
616
567
  )
617
- const now = Date.now()
618
568
  // A future publish time schedules the variant instead of publishing it now.
619
- const later = (s: (typeof schedules)[number]) =>
620
- s.publishTime !== null && s.publishTime.getTime() > now
621
- if (schedules.length > 0)
622
- await port.schedule(
623
- key,
624
- schedules.map((s) => ({ ...s, publishTime: later(s) ? s.publishTime : null })),
625
- )
626
- const immediate = schedules.filter((s) => !later(s))
627
- if (schedules.length > 0 && immediate.length === 0) {
628
- await approvals?.afterDirectPublish?.(principalOf(ctx), key, 'rescheduled it')
569
+ const result = await operations.publish(actorOf(ctx), key, {
570
+ cultures: readCultures(body),
571
+ schedules,
572
+ })
573
+ if (!result.ok)
574
+ return refused(result, 'Could not publish the document', {
575
+ approval: 'The document needs approval before it is published',
576
+ operationStatus: 'PathNotPublished',
577
+ })
578
+ if (result.scheduledOnly)
629
579
  ctx.notifications.push({
630
580
  message: 'Publishing scheduled',
631
581
  category: 'Content',
632
582
  type: 'Success',
633
583
  })
634
- return new Response(null, { status: 200 })
635
- }
636
- const cultures = immediate.some((s) => s.culture !== null)
637
- ? immediate.flatMap((s) => (s.culture === null ? [] : [s.culture]))
638
- : readCultures(body)
639
- const result = await port.publish(key, cultures)
640
- if (!result.ok) {
641
- return problemResponse(
642
- problemDetails({
643
- title: 'Could not publish the document',
644
- status: result.status ?? 400,
645
- detail: result.reason,
646
- operationStatus: 'PathNotPublished',
647
- }),
648
- )
649
- }
650
- await approvals?.afterDirectPublish?.(principalOf(ctx), key, 'published it')
651
584
  return new Response(null, { status: 200 })
652
585
  })
653
586
 
@@ -655,25 +588,21 @@ export function registerDocumentHandlers(
655
588
  const key = ctx.params.id as string
656
589
  if (!(await port.byKey(key)))
657
590
  return problemResponse(notFound('The document could not be found'))
658
- const refusal = await approvals?.publishRefusal(principalOf(ctx), key, 'unpublish')
659
- if (refusal) return needsApproval('Taking the document down needs approval', refusal)
660
- const result = await port.unpublish(key, readCultures(await readBody(ctx)))
661
- if (!result.ok) {
662
- return problemResponse(
663
- problemDetails({
664
- title: 'Could not unpublish the document',
665
- status: result.status ?? 400,
666
- detail: result.reason,
667
- }),
668
- )
669
- }
670
- await approvals?.afterDirectPublish?.(principalOf(ctx), key, 'took it down')
591
+ const result = await operations.unpublish(actorOf(ctx), key, readCultures(await readBody(ctx)))
592
+ if (!result.ok)
593
+ return refused(result, 'Could not unpublish the document', {
594
+ approval: 'Taking the document down needs approval',
595
+ })
671
596
  return new Response(null, { status: 200 })
672
597
  })
673
598
 
674
599
  router.handle('PutDocumentByIdMoveToRecycleBin', async (ctx) => {
675
- const moved = await port.moveToRecycleBin(ctx.params.id as string)
676
- if (!moved) return problemResponse(notFound('The document could not be found'))
600
+ const moved = await operations.trash(actorOf(ctx), ctx.params.id as string)
601
+ if (!moved.ok) {
602
+ if (moved.kind === 'notFound')
603
+ return problemResponse(notFound('The document could not be found'))
604
+ return refused(moved, 'Could not move the document to the recycle bin')
605
+ }
677
606
  ctx.notifications.push({
678
607
  message: 'Moved to the recycle bin',
679
608
  category: 'Content',
@@ -683,8 +612,12 @@ export function registerDocumentHandlers(
683
612
  })
684
613
 
685
614
  router.handle('DeleteDocumentById', async (ctx) => {
686
- const removed = await port.remove(ctx.params.id as string)
687
- if (!removed) return problemResponse(notFound('The document could not be found'))
615
+ const removed = await operations.delete(actorOf(ctx), ctx.params.id as string)
616
+ if (!removed.ok) {
617
+ if (removed.kind === 'notFound')
618
+ return problemResponse(notFound('The document could not be found'))
619
+ return refused(removed, 'Could not delete the document')
620
+ }
688
621
  return new Response(null, { status: 200 })
689
622
  })
690
623
 
@@ -693,7 +626,7 @@ export function registerDocumentHandlers(
693
626
  const id = (value as Record<string, unknown>).id
694
627
  return typeof id === 'string' && id ? id : null
695
628
  }
696
- const failed = (title: string, result: PortFailure) =>
629
+ const failed = (title: string, result: PortFailure | Refusal) =>
697
630
  problemResponse(problemDetails({ title, status: result.status ?? 400, detail: result.reason }))
698
631
  const done = (ctx: RequestContext, message: string) => {
699
632
  ctx.notifications.push({ message, category: 'Content', type: 'Success' })
@@ -701,17 +634,23 @@ export function registerDocumentHandlers(
701
634
  }
702
635
 
703
636
  router.handle('PutDocumentByIdMove', async (ctx) => {
704
- const result = await port.move(ctx.params.id as string, refId((await readBody(ctx)).target))
637
+ const result = await operations.move(
638
+ actorOf(ctx),
639
+ ctx.params.id as string,
640
+ refId((await readBody(ctx)).target),
641
+ )
705
642
  return result.ok ? done(ctx, 'Document moved') : failed('Could not move the document', result)
706
643
  })
707
644
 
708
645
  router.handle('PostDocumentByIdCopy', async (ctx) => {
709
646
  const body = await readBody(ctx)
710
- const result = await port.copy(
647
+ const result = await operations.copy(
648
+ actorOf(ctx),
711
649
  ctx.params.id as string,
712
650
  refId(body.target),
713
- { includeDescendants: body.includeDescendants === true },
714
- ctx.principal as NonNullable<typeof ctx.principal>,
651
+ {
652
+ includeDescendants: body.includeDescendants === true,
653
+ },
715
654
  )
716
655
  if (!result.ok) return failed('Could not copy the document', result)
717
656
  ctx.notifications.push({ message: 'Document copied', category: 'Content', type: 'Success' })
@@ -726,7 +665,7 @@ export function registerDocumentHandlers(
726
665
  key: String(item.id ?? ''),
727
666
  sortOrder: Number(item.sortOrder ?? 0),
728
667
  }))
729
- const result = await port.sort(refId(body.parent), sorting)
668
+ const result = await operations.sort(actorOf(ctx), refId(body.parent), sorting)
730
669
  return result.ok ? done(ctx, 'Sort order saved') : failed('Could not sort', result)
731
670
  })
732
671
 
@@ -738,7 +677,8 @@ export function registerDocumentHandlers(
738
677
  return problemResponse(problemDetails({ title: 'Unknown sort field', status: 400 }))
739
678
  if (!['Ascending', 'Descending'].includes(direction))
740
679
  return problemResponse(problemDetails({ title: 'Unknown sort direction', status: 400 }))
741
- const result = await port.sortChildrenBy(
680
+ const result = await operations.sortChildrenBy(
681
+ actorOf(ctx),
742
682
  parentKey,
743
683
  field as 'Name' | 'CreateDate' | 'UpdateDate',
744
684
  direction as 'Ascending' | 'Descending',
@@ -751,24 +691,29 @@ export function registerDocumentHandlers(
751
691
  router.handle('PutRecycleBinDocumentByIdRestore', async (ctx) => {
752
692
  const body = await readBody(ctx)
753
693
  const target = 'target' in body ? refId(body.target) : undefined
754
- const result = await port.restore(ctx.params.id as string, target ?? undefined)
694
+ const result = await operations.restore(
695
+ actorOf(ctx),
696
+ ctx.params.id as string,
697
+ target ?? undefined,
698
+ )
755
699
  return result.ok ? done(ctx, 'Document restored') : failed('Could not restore', result)
756
700
  })
757
701
 
758
702
  router.handle('DeleteRecycleBinDocumentById', async (ctx) => {
759
- const key = ctx.params.id as string
760
- const document = await port.byKey(key)
761
- if (!document) return problemResponse(notFound('The document could not be found'))
762
- if (!document.isTrashed)
763
- return problemResponse(
764
- problemDetails({ title: 'The document is not in the recycle bin', status: 400 }),
765
- )
766
- await port.remove(key)
703
+ const result = await operations.delete(actorOf(ctx), ctx.params.id as string, { fromBin: true })
704
+ if (!result.ok) {
705
+ if (result.kind === 'notFound')
706
+ return problemResponse(notFound('The document could not be found'))
707
+ if (result.kind === 'invalid')
708
+ return problemResponse(problemDetails({ title: result.reason, status: 400 }))
709
+ return refused(result, 'Could not delete the document')
710
+ }
767
711
  return done(ctx, 'Document deleted')
768
712
  })
769
713
 
770
714
  router.handle('DeleteRecycleBinDocument', async (ctx) => {
771
- await port.emptyRecycleBin()
715
+ const result = await operations.emptyBin(actorOf(ctx))
716
+ if (!result.ok) return refused(result, 'Could not empty the recycle bin')
772
717
  return done(ctx, 'Recycle bin emptied')
773
718
  })
774
719
 
@@ -776,19 +721,18 @@ export function registerDocumentHandlers(
776
721
  const branchTasks = new Map<string, { documentKey: string }>()
777
722
  router.handle('PutDocumentByIdPublishWithDescendants', async (ctx) => {
778
723
  const key = ctx.params.id as string
779
- const refusal = await approvals?.branchRefusal(principalOf(ctx), key)
780
- if (refusal)
781
- return needsApproval('Part of this branch needs approval before it is published', refusal)
782
724
  const body = await readBody(ctx)
783
725
  const cultures = Array.isArray(body.cultures) ? (body.cultures as unknown[]).map(String) : []
784
- const result = await port.publishBranch(
726
+ const result = await operations.publishBranch(
727
+ actorOf(ctx),
785
728
  key,
786
729
  cultures.length > 0 ? cultures : null,
787
730
  body.includeUnpublishedDescendants === true,
788
731
  )
789
- if (!result.ok) return failed('Could not publish the branch', result)
790
- for (const published of result.published)
791
- await approvals?.afterDirectPublish?.(principalOf(ctx), published, 'published its branch')
732
+ if (!result.ok)
733
+ return refused(result, 'Could not publish the branch', {
734
+ approval: 'Part of this branch needs approval before it is published',
735
+ })
792
736
  const taskId = crypto.randomUUID()
793
737
  branchTasks.set(taskId, { documentKey: key })
794
738
  ctx.notifications.push({
@@ -823,7 +767,7 @@ export function registerDocumentHandlers(
823
767
  isoCode: String(d.isoCode ?? ''),
824
768
  }))
825
769
  : []
826
- const result = await port.setDomains(ctx.params.id as string, {
770
+ const result = await operations.setDomains(actorOf(ctx), ctx.params.id as string, {
827
771
  defaultIsoCode: typeof body.defaultIsoCode === 'string' ? body.defaultIsoCode : null,
828
772
  domains,
829
773
  })
@@ -842,6 +786,10 @@ export function registerDocumentHandlers(
842
786
  )
843
787
  case 'notFound':
844
788
  return problemResponse(notFound('The document could not be found'))
789
+ case 'forbidden':
790
+ return problemResponse(
791
+ problemDetails({ title: 'Could not save culture and hostnames', status: 403 }),
792
+ )
845
793
  case 'conflict':
846
794
  return problemResponse(
847
795
  problemDetails({
@@ -1035,8 +983,12 @@ export function registerDocumentHandlers(
1035
983
  })
1036
984
 
1037
985
  router.handle('PostDocumentVersionByIdRollback', async (ctx) => {
1038
- const rolled = await port.rollback(ctx.params.id as string)
1039
- if (!rolled) return problemResponse(notFound('The version could not be found'))
986
+ const rolled = await operations.rollback(actorOf(ctx), ctx.params.id as string)
987
+ if (!rolled.ok) {
988
+ if (rolled.kind === 'notFound')
989
+ return problemResponse(notFound('The version could not be found'))
990
+ return refused(rolled, 'Could not roll the document back')
991
+ }
1040
992
  return new Response(null, { status: 200 })
1041
993
  })
1042
994
 
@@ -5,6 +5,8 @@
5
5
  * calls the mixture ambiguous and refuses it, and so do we, because the two are
6
6
  * different intentions and the editor offers them as a choice.
7
7
  */
8
+ import type { DocumentOperations } from '@crombolo/content'
9
+ import { userActor } from '@crombolo/content/rules'
8
10
  import { notFound, problemDetails, problemResponse } from '@crombolo/core'
9
11
  import type { PublicAccessPort, PublicAccessStatus } from '../ports-members.ts'
10
12
  import type { ManagementApiRouter, RequestContext } from '../router.ts'
@@ -22,10 +24,14 @@ const names = (value: unknown): string[] =>
22
24
  : []
23
25
 
24
26
  /** Umbraco's `PublicAccessOperationStatus`, as the problem details the client reads. */
25
- function statusResponse(status: PublicAccessStatus, ok: () => Response): Response {
27
+ function statusResponse(status: PublicAccessStatus | 'forbidden', ok: () => Response): Response {
26
28
  switch (status) {
27
29
  case 'ok':
28
30
  return ok()
31
+ case 'forbidden':
32
+ return problemResponse(
33
+ problemDetails({ title: 'Could not change public access', status: 403 }),
34
+ )
29
35
  case 'content-not-found':
30
36
  return problemResponse(notFound('The document could not be found'))
31
37
  case 'login-node-not-found':
@@ -46,7 +52,11 @@ function statusResponse(status: PublicAccessStatus, ok: () => Response): Respons
46
52
  export function registerPublicAccessHandlers(
47
53
  router: ManagementApiRouter,
48
54
  port: PublicAccessPort,
55
+ /** Writes go through these when present, so they are announced as any document write is (story 170). */
56
+ operations?: DocumentOperations,
49
57
  ): void {
58
+ const actorOf = (ctx: RequestContext) =>
59
+ userActor(ctx.principal as NonNullable<typeof ctx.principal>, ctx.client ?? {})
50
60
  router.handle('GetDocumentByIdPublicAccess', async (ctx) => {
51
61
  const result = await port.entry(
52
62
  ctx.params.id as string,
@@ -57,7 +67,7 @@ export function registerPublicAccessHandlers(
57
67
  return Response.json(result.entry)
58
68
  })
59
69
 
60
- const write = async (ctx: RequestContext, ok: () => Response) => {
70
+ const write = async (ctx: RequestContext, ok: () => Response, change: 'added' | 'set') => {
61
71
  const body = await readBody(ctx)
62
72
  const login = refId(body.loginDocument)
63
73
  const error = refId(body.errorDocument)
@@ -82,25 +92,30 @@ export function registerPublicAccessHandlers(
82
92
  status: 400,
83
93
  }),
84
94
  )
85
- const status = await port.save(ctx.params.id as string, {
95
+ const input = {
86
96
  loginDocumentKey: login,
87
97
  errorDocumentKey: error,
88
98
  memberGroupNames,
89
99
  memberUserNames,
90
- })
100
+ }
101
+ const status = operations
102
+ ? await operations.setPublicAccess(actorOf(ctx), ctx.params.id as string, input, change)
103
+ : await port.save(ctx.params.id as string, input)
91
104
  return statusResponse(status, ok)
92
105
  }
93
106
 
94
107
  router.handle('PostDocumentByIdPublicAccess', (ctx) =>
95
- write(ctx, () => new Response(null, { status: 201 })),
108
+ write(ctx, () => new Response(null, { status: 201 }), 'added'),
96
109
  )
97
110
  router.handle('PutDocumentByIdPublicAccess', (ctx) =>
98
- write(ctx, () => new Response(null, { status: 200 })),
111
+ write(ctx, () => new Response(null, { status: 200 }), 'set'),
99
112
  )
100
113
 
101
114
  router.handle('DeleteDocumentByIdPublicAccess', async (ctx) =>
102
115
  statusResponse(
103
- await port.remove(ctx.params.id as string),
116
+ operations
117
+ ? await operations.removePublicAccess(actorOf(ctx), ctx.params.id as string)
118
+ : await port.remove(ctx.params.id as string),
104
119
  () => new Response(null, { status: 200 }),
105
120
  ),
106
121
  )
package/src/index.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  export * from './audit.ts'
2
2
  export * from './authorization.ts'
3
3
  export * from './divergences.ts'
4
+ export * from './document-writes.ts'
4
5
  export * from './handlers/content-type.ts'
5
6
  export * from './handlers/package.ts'
6
7
  export * from './handlers/settings-stubs.ts'
package/src/ports.ts CHANGED
@@ -7,6 +7,7 @@
7
7
  * drifts from the wire shape fails to compile.
8
8
  */
9
9
 
10
+ import type { DocumentOperations } from '@crombolo/content'
10
11
  import type { ResponseOf } from '@crombolo/contracts'
11
12
  import type { UploadSettings } from '@crombolo/core'
12
13
  import type {
@@ -280,6 +281,8 @@ export interface ManagementApiDeps {
280
281
  documents?: DocumentPort
281
282
  /** Approval workflows: the gate on publishing and saving a page a workflow covers. */
282
283
  approvals?: ApprovalGatePort
284
+ /** Every document write, with its rules and its events (story 170); required alongside `documents`. */
285
+ documentOperations?: DocumentOperations
283
286
  dictionary?: DictionaryPort
284
287
  userManagement?: UserPort
285
288
  userGroups?: UserGroupPort
package/src/router.ts CHANGED
@@ -25,6 +25,7 @@ import {
25
25
  auditReadsBody,
26
26
  } from './audit.ts'
27
27
  import { authorize, LOCAL_LOGIN_OPERATIONS, type NodeLookup } from './authorization.ts'
28
+ import { DOCUMENT_WRITE_OPERATIONS } from './document-writes.ts'
28
29
  import {
29
30
  changeReadsBody,
30
31
  contentChangeFor,
@@ -77,6 +78,8 @@ export interface RequestContext {
77
78
  principal: Principal | undefined
78
79
  /** Node positions, for a handler that filters what it returns per node. */
79
80
  nodes?: NodeLookup
81
+ /** Where the request came from, for an operation's audit entry. */
82
+ client?: ClientAddress
80
83
  }
81
84
 
82
85
  export type Authenticator = (request: Request) => Promise<Principal | undefined>
@@ -251,7 +254,10 @@ export class ManagementApiRouter {
251
254
 
252
255
  const handler = this.#handlers.get(operation.operationId)
253
256
  if (!handler) this.#onNotImplemented?.(operation, request)
254
- const plan = handler && this.#audit ? auditPlanFor(operation.operationId) : undefined
257
+ // A document write announces itself from its operation (story 170).
258
+ const announces = !DOCUMENT_WRITE_OPERATIONS.has(operation.operationId)
259
+ const plan =
260
+ handler && this.#audit && announces ? auditPlanFor(operation.operationId) : undefined
255
261
  const audit = plan ? await this.#beforeAudit(plan, params, request) : undefined
256
262
  const changeBody =
257
263
  handler && this.#onContentChange && changeReadsBody(operation.operationId)
@@ -269,19 +275,20 @@ export class ManagementApiRouter {
269
275
  notifications,
270
276
  principal,
271
277
  nodes: this.#nodes,
278
+ client: this.#clientAddress(request),
272
279
  })
273
280
  : problemResponse(notImplemented(operation.operationId))
274
281
  if (plan && audit && response.status >= 200 && response.status < 300)
275
282
  await this.#recordAudit(plan, audit, params, request, response, principal)
276
- if (handler && this.#onServerEvent) {
283
+ if (handler && announces && this.#onServerEvent) {
277
284
  const event = serverEventFor(operation, params, response)
278
285
  if (event) this.#onServerEvent(event)
279
286
  }
280
- if (handler && this.#onWebhookEvent) {
287
+ if (handler && announces && this.#onWebhookEvent) {
281
288
  const event = webhookEventFor(operation.operationId, params, response)
282
289
  if (event) this.#onWebhookEvent(event)
283
290
  }
284
- if (handler && this.#onContentChange) {
291
+ if (handler && announces && this.#onContentChange) {
285
292
  const change = contentChangeFor(operation.operationId, params, response, changeBody)
286
293
  if (change) this.#onContentChange(change, principal)
287
294
  }
package/src/routes.ts CHANGED
@@ -98,7 +98,8 @@ export function createManagementApiRouter(options: ManagementApiOptions = {}): M
98
98
  if (deps.dataTypes) registerDataTypeHandlers(router, deps.dataTypes)
99
99
  if (deps.templates) registerTemplateHandlers(router, deps.templates)
100
100
  if (deps.templateQuery) registerTemplateQueryHandlers(router, deps.templateQuery)
101
- if (deps.documents) registerDocumentHandlers(router, deps.documents, deps.preview, deps.approvals)
101
+ if (deps.documents && deps.documentOperations)
102
+ registerDocumentHandlers(router, deps.documents, deps.documentOperations, deps.preview)
102
103
  if (deps.blueprints) registerDocumentBlueprintHandlers(router, deps.blueprints)
103
104
  if (deps.temporaryFiles) registerTemporaryFileHandlers(router, deps.temporaryFiles)
104
105
  if (deps.media) registerMediaHandlers(router, deps.media)
@@ -121,7 +122,8 @@ export function createManagementApiRouter(options: ManagementApiOptions = {}): M
121
122
  if (deps.temporaryFiles) registerImportHandlers(router, deps.temporaryFiles)
122
123
  if (deps.memberGroups) registerMemberGroupHandlers(router, deps.memberGroups)
123
124
  if (deps.members) registerMemberHandlers(router, deps.members)
124
- if (deps.publicAccess) registerPublicAccessHandlers(router, deps.publicAccess)
125
+ if (deps.publicAccess)
126
+ registerPublicAccessHandlers(router, deps.publicAccess, deps.documentOperations)
125
127
  if (deps.elements) registerElementHandlers(router, deps.elements, deps.references)
126
128
  registerAuditLogHandlers(
127
129
  router,
@@ -24,6 +24,12 @@ export const WEBHOOK_EVENTS: readonly WebhookEventInfo[] = [
24
24
  },
25
25
  { alias: 'Umbraco.ContentMoved', eventName: 'Content Moved', eventType: 'Content' },
26
26
  { alias: 'Umbraco.ContentCopied', eventName: 'Content Copied', eventType: 'Content' },
27
+ { alias: 'Umbraco.ContentSorted', eventName: 'Content Sorted', eventType: 'Content' },
28
+ {
29
+ alias: 'Umbraco.ContentRolledBack',
30
+ eventName: 'Content Rolled Back',
31
+ eventType: 'Content',
32
+ },
27
33
  { alias: 'Umbraco.MediaSave', eventName: 'Media Saved', eventType: 'Media' },
28
34
  { alias: 'Umbraco.MediaDelete', eventName: 'Media Deleted', eventType: 'Media' },
29
35
  ]