@crombolo/api-management 0.18.0 → 0.20.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.18.0",
3
+ "version": "0.20.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.18.0",
32
- "@crombolo/contracts": "0.18.0"
31
+ "@crombolo/core": "0.20.0",
32
+ "@crombolo/contracts": "0.20.0"
33
33
  }
34
34
  }
@@ -243,6 +243,8 @@ const DOCUMENT_RULES: Record<string, readonly DocumentRule[]> = {
243
243
  GetDocumentByIdAvailableSegmentOptions: [{ verbs: [D.Read], node: id }],
244
244
  GetDocumentByIdPreviewUrl: [{ verbs: [D.Read], node: id }],
245
245
  GetDocumentVersion: [{ verbs: [D.Read], node: { query: 'documentId' } }],
246
+ GetDocumentVersionById: [{ verbs: [D.Read], node: { version: 'id' } }],
247
+ PutDocumentVersionByIdPreventCleanup: [{ verbs: [D.Update], node: { version: 'id' } }],
246
248
  // The list view: it answers with the children's own property values, so it is
247
249
  // a read of the branch and not merely of the tree, and Umbraco filters it per
248
250
  // item (ContentListViewService.FilterAuthorizedKeysAsync). Requiring Read on
@@ -252,6 +254,7 @@ const DOCUMENT_RULES: Record<string, readonly DocumentRule[]> = {
252
254
  PostDocument: [{ verbs: [D.Create], node: { body: ['parent', 'id'] } }],
253
255
  PostDocumentValidate: [{ verbs: [D.Create], node: { body: ['parent', 'id'] } }],
254
256
  PutDocumentById: [{ verbs: [D.Update], node: id }],
257
+ PatchDocumentByIdPatch: [{ verbs: [D.Update], node: id }],
255
258
  PutDocumentByIdValidate: [{ verbs: [D.Update], node: id }],
256
259
  PostDocumentCreateAndPublish: [
257
260
  { verbs: [D.Publish], node: { body: ['parent', 'id'] }, cultures: true },
@@ -386,6 +389,31 @@ async function resolveKeys(
386
389
  return pick(await body(), ref.body).map((key) => key ?? 'root')
387
390
  }
388
391
 
392
+ /**
393
+ * Keys the caller is denied Read on as children of a parent they can read. A
394
+ * child can only lose what its parent grants by an explicit setting on the child
395
+ * itself, so the candidates are the nodes the caller's groups set explicitly; a
396
+ * candidate that is not a child of this parent filters nothing.
397
+ */
398
+ export function deniedChildren(principal: Principal, parentChain: readonly string[]): string[] {
399
+ const candidates = new Set(principal.groups.flatMap((g) => [...g.granular.keys()]))
400
+ return [...candidates].filter(
401
+ (key) => !permissionsForPath(principal.groups, [...parentChain, key]).has(D.Read),
402
+ )
403
+ }
404
+
405
+ /** Whether the caller may read a document's draft: the Content section, its path, and Read on it. */
406
+ export async function canReadDocument(
407
+ principal: Principal,
408
+ key: string,
409
+ nodes: NodeLookup,
410
+ ): Promise<boolean> {
411
+ if (!hasSection(principal, 'content')) return false
412
+ 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)
415
+ }
416
+
389
417
  /** Evaluates the operation's section requirements, then its node rules. */
390
418
  export async function authorize(
391
419
  operation: OperationInfo,
@@ -19,6 +19,7 @@ import {
19
19
  problemResponse,
20
20
  ROOT_ACCESS,
21
21
  } from '@crombolo/core'
22
+ import { deniedChildren } from '../authorization.ts'
22
23
  import type { PreviewPort } from '../ports.ts'
23
24
  import type { ApprovalGatePort, DocumentPort, PortFailure, SaveDocument } from '../ports-content.ts'
24
25
  import type { ManagementApiRouter, RequestContext } from '../router.ts'
@@ -374,6 +375,7 @@ export function registerDocumentHandlers(
374
375
  return problemResponse(notFound(result.reason))
375
376
  return failureResponse('Could not publish the document', result, input.values)
376
377
  }
378
+ await approvals?.afterDirectPublish?.(principalOf(ctx), key, 'published it')
377
379
  return new Response(null, { status: 200 })
378
380
  })
379
381
 
@@ -586,6 +588,7 @@ export function registerDocumentHandlers(
586
588
  )
587
589
  const immediate = schedules.filter((s) => !later(s))
588
590
  if (schedules.length > 0 && immediate.length === 0) {
591
+ await approvals?.afterDirectPublish?.(principalOf(ctx), key, 'rescheduled it')
589
592
  ctx.notifications.push({
590
593
  message: 'Publishing scheduled',
591
594
  category: 'Content',
@@ -607,6 +610,7 @@ export function registerDocumentHandlers(
607
610
  }),
608
611
  )
609
612
  }
613
+ await approvals?.afterDirectPublish?.(principalOf(ctx), key, 'published it')
610
614
  return new Response(null, { status: 200 })
611
615
  })
612
616
 
@@ -626,6 +630,7 @@ export function registerDocumentHandlers(
626
630
  }),
627
631
  )
628
632
  }
633
+ await approvals?.afterDirectPublish?.(principalOf(ctx), key, 'took it down')
629
634
  return new Response(null, { status: 200 })
630
635
  })
631
636
 
@@ -745,6 +750,8 @@ export function registerDocumentHandlers(
745
750
  body.includeUnpublishedDescendants === true,
746
751
  )
747
752
  if (!result.ok) return failed('Could not publish the branch', result)
753
+ for (const published of result.published)
754
+ await approvals?.afterDirectPublish?.(principalOf(ctx), published, 'published its branch')
748
755
  const taskId = crypto.randomUUID()
749
756
  branchTasks.set(taskId, { documentKey: key })
750
757
  ctx.notifications.push({
@@ -1006,7 +1013,18 @@ export function registerDocumentHandlers(
1006
1013
  router.handle('GetCollectionDocumentById', async (ctx) => {
1007
1014
  const page = paging(ctx)
1008
1015
  if (!page) return problemResponse(invalidSkipTake())
1009
- const result = await port.collection(ctx.params.id as string, page)
1016
+ // Read on the parent let the request through; a child can still deny it.
1017
+ const parent = ctx.params.id as string
1018
+ const principal = ctx.principal
1019
+ const chain =
1020
+ principal && ctx.nodes
1021
+ ? (await ctx.nodes.documents([parent])).get(parent.toLowerCase())?.chain
1022
+ : undefined
1023
+ const result = await port.collection(
1024
+ parent,
1025
+ page,
1026
+ principal && chain ? deniedChildren(principal, chain) : [],
1027
+ )
1010
1028
  return Response.json({
1011
1029
  total: result.total,
1012
1030
  items: result.items.map((aggregate) => ({
@@ -492,8 +492,13 @@ function registerUsers(router: ManagementApiRouter, users: UserPort): void {
492
492
  if (!provider) return noProvider()
493
493
  const b = await body(ctx)
494
494
  const enabled = await provider.enable(me(ctx).id, str(b.code), str(b.secret))
495
- return enabled.ok
496
- ? Response.json({ $type: 'TwoFactorRecoveryCodes', recoveryCodes: enabled.recoveryCodes })
495
+ if (enabled.ok)
496
+ return Response.json({
497
+ $type: 'TwoFactorRecoveryCodes',
498
+ recoveryCodes: enabled.recoveryCodes,
499
+ })
500
+ return enabled.alreadyEnabled
501
+ ? bad('Two-factor sign-in is already on', enabled.message, 'ProviderAlreadySetup', 400)
497
502
  : refused(enabled.message)
498
503
  })
499
504
  router.handle('DeleteUserCurrent2faByProviderName', async (ctx) => {
@@ -390,7 +390,12 @@ export interface DocumentPort extends TreePort {
390
390
  setPreventCleanup(versionId: string, prevent: boolean): Promise<boolean>
391
391
  /** Published URLs per culture, for the editor's info panel. */
392
392
  urls(key: string): Promise<Array<{ culture: string | null; url: string }>>
393
- collection(parentKey: string | null, paging: SkipTake): Promise<Page<DocumentAggregate>>
393
+ /** A page of a document's children, without `excludeKeys` in the page or the total. */
394
+ collection(
395
+ parentKey: string | null,
396
+ paging: SkipTake,
397
+ excludeKeys?: readonly string[],
398
+ ): Promise<Page<DocumentAggregate>>
394
399
  }
395
400
 
396
401
  export interface SaveDocument {
@@ -621,4 +626,6 @@ export interface ApprovalGatePort {
621
626
  ): Promise<string | undefined>
622
627
  beforeSave(principal: Principal, key: string): Promise<string | undefined>
623
628
  afterSave(principal: Principal, key: string): Promise<void>
629
+ /** A publish, schedule or unpublish that passed the gate: it supersedes a scheduled request. */
630
+ afterDirectPublish?(principal: Principal, key: string, what: string): Promise<void>
624
631
  }
@@ -97,7 +97,9 @@ export interface UserTwoFactorPort {
97
97
  userKey: string,
98
98
  code: string,
99
99
  secret: string,
100
- ): Promise<{ ok: true; recoveryCodes: string[] } | { ok: false; message: string }>
100
+ ): Promise<
101
+ { ok: true; recoveryCodes: string[] } | { ok: false; message: string; alreadyEnabled?: boolean }
102
+ >
101
103
  disable(userKey: string, code: string): Promise<{ ok: true } | { ok: false; message: string }>
102
104
  /** An administrator turning it off for someone who lost their phone. */
103
105
  reset(userKey: string): Promise<void>
package/src/router.ts CHANGED
@@ -75,6 +75,8 @@ export interface RequestContext {
75
75
  * operation can rely on this being set.
76
76
  */
77
77
  principal: Principal | undefined
78
+ /** Node positions, for a handler that filters what it returns per node. */
79
+ nodes?: NodeLookup
78
80
  }
79
81
 
80
82
  export type Authenticator = (request: Request) => Promise<Principal | undefined>
@@ -259,7 +261,15 @@ export class ManagementApiRouter {
259
261
  .catch(() => undefined)
260
262
  : undefined
261
263
  const response = handler
262
- ? await this.#run(handler, { request, url, params, operation, notifications, principal })
264
+ ? await this.#run(handler, {
265
+ request,
266
+ url,
267
+ params,
268
+ operation,
269
+ notifications,
270
+ principal,
271
+ nodes: this.#nodes,
272
+ })
263
273
  : problemResponse(notImplemented(operation.operationId))
264
274
  if (plan && audit && response.status >= 200 && response.status < 300)
265
275
  await this.#recordAudit(plan, audit, params, request, response, principal)