@crombolo/api-management 0.20.0 → 0.22.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.20.0",
3
+ "version": "0.22.0",
4
4
  "description": "Umbraco-compatible Management API handlers for crombolo.",
5
5
  "license": "MIT",
6
6
  "author": "Crombolo",
@@ -28,7 +28,7 @@
28
28
  "access": "public"
29
29
  },
30
30
  "dependencies": {
31
- "@crombolo/core": "0.20.0",
32
- "@crombolo/contracts": "0.20.0"
31
+ "@crombolo/core": "0.22.0",
32
+ "@crombolo/contracts": "0.22.0"
33
33
  }
34
34
  }
@@ -2,16 +2,22 @@
2
2
  * Authorization for every Management API call, as Umbraco's policies apply it:
3
3
  * first the sections an operation's controller demands (any one of a set, and
4
4
  * every set), then, for documents and media, the caller's start nodes and the
5
- * permission verbs the operation needs on the nodes it names. Users and user
6
- * groups carry rules about the people involved, which their port enforces.
7
- * See docs/backoffice-hosting.md for the table's provenance.
5
+ * permission verbs the operation needs on the nodes it names, and for elements
6
+ * the verbs it needs. Users and user groups carry rules about the people
7
+ * involved, which their port enforces. See docs/backoffice-hosting.md for the
8
+ * tables' provenance.
8
9
  */
9
10
  import type { OperationInfo } from '@crombolo/contracts'
10
11
  import {
11
12
  type AppAlias,
12
13
  DocumentPermissions as D,
14
+ ElementPermissions as E,
15
+ ElementContainerPermissions as EC,
16
+ fallbackPermissions,
13
17
  hasPathAccess,
18
+ MediaPermissions as M,
14
19
  permissionsForPath,
20
+ propertyValuePermissions,
15
21
  type StartNodes,
16
22
  sectionKey,
17
23
  } from '@crombolo/core'
@@ -157,9 +163,11 @@ export function sectionRequirements(operation: OperationInfo): Array<Sections |
157
163
  if (second === 'user' || second === 'user-group') return [USERS]
158
164
  if (second === 'member') return [MEMBERS]
159
165
  return []
166
+ case 'redirect-management':
167
+ // Tracking on or off is a setting for the whole site, not an edit to content
168
+ return second === 'status' && write ? [SETTINGS] : [CONTENT]
160
169
  case 'document':
161
170
  case 'document-version':
162
- case 'redirect-management':
163
171
  case 'relation':
164
172
  case 'oembed':
165
173
  case 'dynamic-root':
@@ -296,27 +304,79 @@ const DOCUMENT_RULES: Record<string, readonly DocumentRule[]> = {
296
304
  GetRecycleBinDocumentByIdOriginalParent: [{ verbs: [D.Read], node: 'bin' }],
297
305
  }
298
306
 
299
- /** Media carries no verbs: a rule names the nodes whose path the caller must be able to reach. */
300
- const MEDIA_RULES: Record<string, readonly NodeRef[]> = {
301
- GetMediaById: [id],
307
+ /**
308
+ * Media verbs are the groups' fallback ones (media has no per-node permissions),
309
+ * on top of the start-node path checks on the nodes a rule names. Trees and
310
+ * items stay open to pickers, as for documents.
311
+ */
312
+ interface MediaRule {
313
+ verbs: readonly string[]
314
+ nodes: readonly NodeRef[]
315
+ }
316
+
317
+ const MEDIA_RULES: Record<string, MediaRule> = {
318
+ GetMediaById: { verbs: [M.Read], nodes: [id] },
302
319
  // As for documents above. `id` is a query parameter here and omitting it means
303
320
  // the root, so the rule says so rather than leaving the absent case unchecked.
304
- GetCollectionMedia: [{ query: 'id', orRoot: true }],
305
- PutMediaById: [id],
306
- DeleteMediaById: [id],
307
- GetMediaByIdAuditLog: [id],
308
- PutMediaByIdMove: [id, { body: ['target', 'id'] }],
309
- PutMediaByIdMoveToRecycleBin: [id],
310
- PutMediaByIdSortChildren: [id],
311
- PutMediaByIdValidate: [id],
312
- PostMedia: [{ body: ['parent', 'id'] }],
313
- PostMediaValidate: [{ body: ['parent', 'id'] }],
314
- PutMediaSort: [{ body: ['parent', 'id'] }, { body: ['sorting', '*', 'id'] }],
315
- PutMediaRootSortChildren: ['root'],
316
- DeleteRecycleBinMedia: ['bin'],
317
- DeleteRecycleBinMediaById: ['bin'],
318
- PutRecycleBinMediaByIdRestore: ['bin'],
319
- GetRecycleBinMediaByIdOriginalParent: ['bin'],
321
+ GetCollectionMedia: { verbs: [M.Read], nodes: [{ query: 'id', orRoot: true }] },
322
+ GetMediaByIdAuditLog: { verbs: [M.Read], nodes: [id] },
323
+ GetRecycleBinMediaByIdOriginalParent: { verbs: [M.Read], nodes: ['bin'] },
324
+ PutMediaById: { verbs: [M.Update], nodes: [id] },
325
+ PutMediaByIdValidate: { verbs: [M.Update], nodes: [id] },
326
+ DeleteMediaById: { verbs: [M.Update], nodes: [id] },
327
+ PutMediaByIdMove: { verbs: [M.Update], nodes: [id, { body: ['target', 'id'] }] },
328
+ PutMediaByIdMoveToRecycleBin: { verbs: [M.Update], nodes: [id] },
329
+ PutMediaByIdSortChildren: { verbs: [M.Update], nodes: [id] },
330
+ PostMedia: { verbs: [M.Update], nodes: [{ body: ['parent', 'id'] }] },
331
+ PostMediaValidate: { verbs: [M.Update], nodes: [{ body: ['parent', 'id'] }] },
332
+ PutMediaSort: {
333
+ verbs: [M.Update],
334
+ nodes: [{ body: ['parent', 'id'] }, { body: ['sorting', '*', 'id'] }],
335
+ },
336
+ PutMediaRootSortChildren: { verbs: [M.Update], nodes: ['root'] },
337
+ DeleteRecycleBinMedia: { verbs: [M.Update], nodes: ['bin'] },
338
+ DeleteRecycleBinMediaById: { verbs: [M.Update], nodes: ['bin'] },
339
+ PutRecycleBinMediaByIdRestore: { verbs: [M.Update], nodes: ['bin'] },
340
+ }
341
+
342
+ /**
343
+ * The element and element folder verbs each Library operation needs, held in
344
+ * the groups' fallback permissions. Mirrors DOCUMENT_RULES verb for verb.
345
+ */
346
+ const ELEMENT_RULES: Record<string, readonly string[]> = {
347
+ GetElementById: [E.Read],
348
+ GetElementByIdPublished: [E.Read],
349
+ GetElementByIdAuditLog: [E.Read],
350
+ GetElementVersion: [E.Read],
351
+ GetElementVersionById: [E.Read],
352
+ GetRecycleBinElementByIdOriginalParent: [E.Read],
353
+ PostElement: [E.Create],
354
+ PostElementValidate: [E.Create],
355
+ PutElementById: [E.Update],
356
+ PutElementByIdValidate: [E.Update],
357
+ PutElementVersionByIdPreventCleanup: [E.Update],
358
+ PostElementCreateAndPublish: [E.Publish],
359
+ PutElementByIdUpdateAndPublish: [E.Publish],
360
+ PutElementByIdPublish: [E.Publish],
361
+ PutElementByIdUnpublish: [E.Unpublish],
362
+ DeleteElementById: [E.Delete],
363
+ PutElementByIdMoveToRecycleBin: [E.Delete],
364
+ PutElementByIdMove: [E.Move],
365
+ PostElementByIdCopy: [E.Duplicate, E.Create],
366
+ PostElementVersionByIdRollback: [E.Rollback],
367
+ DeleteRecycleBinElementById: [E.Delete],
368
+ PutRecycleBinElementByIdRestore: [E.Move],
369
+ // Emptying the bin deletes the folders in it as well as the elements
370
+ DeleteRecycleBinElement: [E.Delete, EC.Delete],
371
+ GetElementFolderById: [EC.Read],
372
+ GetRecycleBinElementFolderByIdOriginalParent: [EC.Read],
373
+ PostElementFolder: [EC.Create],
374
+ PutElementFolderById: [EC.Update],
375
+ DeleteElementFolderById: [EC.Delete],
376
+ PutElementFolderByIdMoveToRecycleBin: [EC.Delete],
377
+ DeleteRecycleBinElementFolderById: [EC.Delete],
378
+ PutElementFolderByIdMove: [EC.Move],
379
+ PutRecycleBinElementFolderByIdRestore: [EC.Move],
320
380
  }
321
381
 
322
382
  /** Values at `path` in `body`; `*` walks every element of an array. A missing or null step means the root. */
@@ -402,16 +462,80 @@ export function deniedChildren(principal: Principal, parentChain: readonly strin
402
462
  )
403
463
  }
404
464
 
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
+
405
520
  /** Whether the caller may read a document's draft: the Content section, its path, and Read on it. */
406
521
  export async function canReadDocument(
407
522
  principal: Principal,
408
523
  key: string,
409
524
  nodes: NodeLookup,
410
525
  ): Promise<boolean> {
411
- if (!hasSection(principal, 'content')) return false
412
526
  const node = (await nodes.documents([key])).get(key.toLowerCase())
413
- if (!node || !hasPathAccess(principal.startNodes.document, node.chain, node.trashed)) return false
414
- return permissionsForPath(principal.groups, node.chain).has(D.Read)
527
+ return node !== undefined && canReadDocumentAt(principal, node.chain, node.trashed)
528
+ }
529
+
530
+ /** `canReadDocument` for a document whose place is known: its ancestors' keys then its own. Pure. */
531
+ export function canReadDocumentAt(
532
+ principal: Principal,
533
+ chain: readonly string[],
534
+ trashed = false,
535
+ ): boolean {
536
+ if (!hasSection(principal, 'content')) return false
537
+ if (!hasPathAccess(principal.startNodes.document, chain, trashed)) return false
538
+ return permissionsForPath(principal.groups, chain).has(D.Read)
415
539
  }
416
540
 
417
541
  /** Evaluates the operation's section requirements, then its node rules. */
@@ -464,17 +588,25 @@ export async function authorize(
464
588
  if (rule.cultures && !hasCultureAccess(principal, culturesIn(await body()))) return false
465
589
  }
466
590
 
467
- for (const ref of MEDIA_RULES[operation.operationId] ?? []) {
591
+ const fallback = fallbackPermissions(principal.groups)
592
+ const elementVerbs = ELEMENT_RULES[operation.operationId]
593
+ if (elementVerbs && !elementVerbs.every((v) => fallback.has(v))) return false
594
+
595
+ const media = MEDIA_RULES[operation.operationId]
596
+ if (media) {
597
+ if (!media.verbs.every((v) => fallback.has(v))) return false
468
598
  const start = principal.startNodes.media
469
- const keys = await resolveKeys(ref, params, url, body, nodes)
470
- const found = await nodes.media(keys.filter((k): k is string => k !== 'root' && k !== 'bin'))
471
- for (const key of keys) {
472
- if (key === 'root' || key === 'bin') {
473
- if (!start.root) return false
474
- continue
599
+ for (const ref of media.nodes) {
600
+ const keys = await resolveKeys(ref, params, url, body, nodes)
601
+ const found = await nodes.media(keys.filter((k): k is string => k !== 'root' && k !== 'bin'))
602
+ for (const key of keys) {
603
+ if (key === 'root' || key === 'bin') {
604
+ if (!start.root) return false
605
+ continue
606
+ }
607
+ const node = found.get(key.toLowerCase())
608
+ if (node && !hasPathAccess(start, node.chain, node.trashed)) return false
475
609
  }
476
- const node = found.get(key.toLowerCase())
477
- if (node && !hasPathAccess(start, node.chain, node.trashed)) return false
478
610
  }
479
611
  }
480
612
  return true
@@ -20,3 +20,32 @@ export const PLANNED_AREAS: Readonly<Record<string, string>> = {}
20
20
 
21
21
  /** Operations outside those areas that a story builds. */
22
22
  export const PLANNED_OPERATIONS: Readonly<Record<string, string>> = {}
23
+
24
+ const MEDIA_VERBS =
25
+ 'Umbraco has no media verbs: the Media section alone lets a group change everything in it. Crombolo asks for `Crombolo.Media.Read` to open media and `Crombolo.Media.Update` to change it (story 088).'
26
+
27
+ /**
28
+ * Operations that answer, but are authorized differently from Umbraco, with the
29
+ * reason. docs/roadmap.md, "Deliberate divergence".
30
+ */
31
+ export const AUTHORIZATION_DIVERGENCES: Readonly<Record<string, string>> = {
32
+ GetMediaById: MEDIA_VERBS,
33
+ GetCollectionMedia: MEDIA_VERBS,
34
+ GetMediaByIdAuditLog: MEDIA_VERBS,
35
+ GetRecycleBinMediaByIdOriginalParent: MEDIA_VERBS,
36
+ PostMedia: MEDIA_VERBS,
37
+ PostMediaValidate: MEDIA_VERBS,
38
+ PutMediaById: MEDIA_VERBS,
39
+ PutMediaByIdValidate: MEDIA_VERBS,
40
+ DeleteMediaById: MEDIA_VERBS,
41
+ PutMediaByIdMove: MEDIA_VERBS,
42
+ PutMediaByIdMoveToRecycleBin: MEDIA_VERBS,
43
+ PutMediaByIdSortChildren: MEDIA_VERBS,
44
+ PutMediaSort: MEDIA_VERBS,
45
+ PutMediaRootSortChildren: MEDIA_VERBS,
46
+ DeleteRecycleBinMedia: MEDIA_VERBS,
47
+ DeleteRecycleBinMediaById: MEDIA_VERBS,
48
+ PutRecycleBinMediaByIdRestore: MEDIA_VERBS,
49
+ PostRedirectManagementStatus:
50
+ 'Umbraco asks only for the Content section. Turning URL tracking on or off is a setting for the whole site, so crombolo asks for Settings; deleting one redirect still needs Content (story 088).',
51
+ }
@@ -19,8 +19,8 @@ import {
19
19
  problemResponse,
20
20
  ROOT_ACCESS,
21
21
  } from '@crombolo/core'
22
- import { deniedChildren } from '../authorization.ts'
23
- import type { PreviewPort } from '../ports.ts'
22
+ import { deniedChildren, deniedPropertyWrite } from '../authorization.ts'
23
+ import { APP_PREVIEW_PROVIDER, type PreviewPort } from '../ports.ts'
24
24
  import type { ApprovalGatePort, DocumentPort, PortFailure, SaveDocument } from '../ports-content.ts'
25
25
  import type { ManagementApiRouter, RequestContext } from '../router.ts'
26
26
  import { created, paging } from './content-type.ts'
@@ -286,6 +286,39 @@ export function registerDocumentHandlers(
286
286
  problemDetails({ title, status: 400, detail, operationStatus: 'NeedsApproval' }),
287
287
  )
288
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
314
+ return problemResponse(
315
+ problemDetails({
316
+ title: 'Could not save the document',
317
+ status: 403,
318
+ detail: `You may not change "${denied.name}" (${denied.alias}).`,
319
+ }),
320
+ )
321
+ }
289
322
  const trees: TreeSource = {
290
323
  treeRoot: (paging) => port.treeRoot(paging),
291
324
  treeChildren: (key, paging) => port.treeChildren(key, paging),
@@ -360,6 +393,8 @@ export function registerDocumentHandlers(
360
393
  const body = await readBody(ctx)
361
394
  const key = ctx.params.id as string
362
395
  const input = toSaveDocument(key, body)
396
+ const denied = await propertyWriteRefusal(ctx, key, await port.byKey(key), input.values)
397
+ if (denied) return denied
363
398
  const refusal =
364
399
  (await approvals?.beforeSave(principalOf(ctx), key)) ??
365
400
  (await approvals?.publishRefusal(principalOf(ctx), key, 'publish'))
@@ -498,6 +533,8 @@ export function registerDocumentHandlers(
498
533
  existing: DocumentAggregate,
499
534
  body: Record<string, unknown>,
500
535
  ) => {
536
+ const denied = await propertyWriteRefusal(ctx, key, existing, readValues(body))
537
+ if (denied) return denied
501
538
  const refusal = await approvals?.beforeSave(principalOf(ctx), key)
502
539
  if (refusal) return needsApproval('The document is waiting for approval', refusal)
503
540
  const result = await port.update(
@@ -881,6 +918,18 @@ export function registerDocumentHandlers(
881
918
  )
882
919
  const culture = ctx.url.searchParams.get('culture') || null
883
920
  const segment = ctx.url.searchParams.get('segment') || null
921
+ const provider = ctx.url.searchParams.get('providerAlias')
922
+ // The app's own address: no preview cookie, since nothing here renders it.
923
+ if (provider === APP_PREVIEW_PROVIDER && preview.inApp && ctx.principal) {
924
+ const inApp = await preview.inApp(key, culture, ctx.principal)
925
+ return Response.json({
926
+ url: 'url' in inApp ? inApp.url : null,
927
+ provider,
928
+ isExternal: true,
929
+ culture,
930
+ message: 'message' in inApp ? inApp.message : null,
931
+ })
932
+ }
884
933
  const query = new URLSearchParams({ id: key, culture: culture ?? '', segment: segment ?? '' })
885
934
  const headers = new Headers({ 'content-type': 'application/json' })
886
935
  for (const cookie of preview.enter()) headers.append('set-cookie', cookie)
@@ -268,6 +268,10 @@ export interface DocumentPort extends TreePort {
268
268
  byKey(key: string): Promise<DocumentAggregate | undefined>
269
269
  /** Every property alias its type has, compositions included. */
270
270
  propertyAliases?(key: string): Promise<string[] | undefined>
271
+ /** Every property type its type has, compositions included: for checking value permissions. */
272
+ propertyTypes?(
273
+ key: string,
274
+ ): Promise<Array<{ alias: string; key: string; name: string }> | undefined>
271
275
  /** The published version's values; undefined when nothing is published. */
272
276
  byKeyPublished(key: string): Promise<DocumentAggregate | undefined>
273
277
  /** What the editor asks before a save: the rules the server would enforce. */
package/src/ports.ts CHANGED
@@ -185,11 +185,23 @@ export interface DynamicRootPort {
185
185
  }
186
186
 
187
187
  /** Preview mode is a cookie; the server owns its name and attributes. */
188
+ /** The provider alias the Preview in app option asks for (story 053). */
189
+ export const APP_PREVIEW_PROVIDER = 'cromboloAppPreview'
190
+
188
191
  export interface PreviewPort {
189
192
  /** `Set-Cookie` values that enter preview for the signed-in editor. */
190
193
  enter(): string[]
191
194
  /** `Set-Cookie` values that leave it. */
192
195
  exit(): string[]
196
+ /**
197
+ * Where a page previews in the site's app, with a preview token for the
198
+ * editor in it, or why it cannot; absent when the site has no app preview.
199
+ */
200
+ inApp?(
201
+ key: string,
202
+ culture: string | null,
203
+ principal: Principal,
204
+ ): Promise<{ url: string } | { message: string }>
193
205
  }
194
206
 
195
207
  export interface DictionaryItemModel {