@crombolo/api-management 0.17.0 → 0.19.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.17.0",
3
+ "version": "0.19.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.17.0",
32
- "@crombolo/contracts": "0.17.0"
31
+ "@crombolo/core": "0.19.0",
32
+ "@crombolo/contracts": "0.19.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,
@@ -1,47 +1,35 @@
1
1
  /**
2
2
  * Health checks, telemetry, profiling and the server's troubleshooting and
3
- * upgrade-check answers. Telemetry and profiling are fixed: nothing is
4
- * collected or sent, and there is no profiler. docs/diagnostics.md.
3
+ * upgrade-check answers. Telemetry and profiling are gone — nothing is
4
+ * collected or sent, and there is no profiler — so their endpoints answer 410.
5
+ * docs/diagnostics.md.
5
6
  */
6
7
  import { invalidSkipTake, notFound, problemDetails, problemResponse } from '@crombolo/core'
7
8
  import type { DiagnosticsPort } from '../ports-diagnostics.ts'
8
9
  import type { ManagementApiRouter } from '../router.ts'
9
10
  import { paging } from './content-type.ts'
10
- import { readBody } from './document.ts'
11
-
12
- const TELEMETRY_LEVEL = 'Minimal'
13
11
 
14
12
  const badRequest = (title: string, detail: string) => problemDetails({ title, detail, status: 400 })
15
13
 
14
+ /** An operation for something this server has not got, and never will: 410, with why. */
15
+ const gone = (title: string, detail: string) => () =>
16
+ problemResponse(problemDetails({ title, detail, status: 410 }))
17
+
18
+ const telemetryGone = gone(
19
+ 'Telemetry is not collected',
20
+ 'This site collects no telemetry and sends nothing anywhere.',
21
+ )
22
+ const profilingGone = gone(
23
+ 'There is no profiler',
24
+ 'This site has no profiler to read or switch on.',
25
+ )
26
+
16
27
  export function registerTelemetryAndProfilingHandlers(router: ManagementApiRouter): void {
17
- router.handle('GetTelemetry', (ctx) => {
18
- const page = paging(ctx)
19
- if (!page) return problemResponse(invalidSkipTake())
20
- const items = [{ telemetryLevel: TELEMETRY_LEVEL }]
21
- return Response.json({
22
- total: items.length,
23
- items: items.slice(page.skip, page.skip + page.take),
24
- })
25
- })
26
- router.handle('GetTelemetryLevel', () => Response.json({ telemetryLevel: TELEMETRY_LEVEL }))
27
- router.handle('PostTelemetryLevel', async (ctx) => {
28
- const { telemetryLevel } = await readBody(ctx)
29
- if (telemetryLevel === TELEMETRY_LEVEL) return new Response(null, { status: 200 })
30
- return problemResponse(
31
- badRequest(
32
- 'Telemetry cannot be raised',
33
- 'This site collects no telemetry and sends nothing anywhere, so the level stays at Minimal.',
34
- ),
35
- )
36
- })
37
- router.handle('GetProfilingStatus', () => Response.json({ enabled: false }))
38
- router.handle('PutProfilingStatus', async (ctx) => {
39
- const { enabled } = await readBody(ctx)
40
- if (enabled === false) return new Response(null, { status: 200 })
41
- return problemResponse(
42
- badRequest('Profiling is not available', 'This site has no profiler to switch on.'),
43
- )
44
- })
28
+ router.handle('GetTelemetry', telemetryGone)
29
+ router.handle('GetTelemetryLevel', telemetryGone)
30
+ router.handle('PostTelemetryLevel', telemetryGone)
31
+ router.handle('GetProfilingStatus', profilingGone)
32
+ router.handle('PutProfilingStatus', profilingGone)
45
33
  }
46
34
 
47
35
  export function registerDiagnosticsHandlers(
@@ -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'
@@ -1006,7 +1007,18 @@ export function registerDocumentHandlers(
1006
1007
  router.handle('GetCollectionDocumentById', async (ctx) => {
1007
1008
  const page = paging(ctx)
1008
1009
  if (!page) return problemResponse(invalidSkipTake())
1009
- const result = await port.collection(ctx.params.id as string, page)
1010
+ // Read on the parent let the request through; a child can still deny it.
1011
+ const parent = ctx.params.id as string
1012
+ const principal = ctx.principal
1013
+ const chain =
1014
+ principal && ctx.nodes
1015
+ ? (await ctx.nodes.documents([parent])).get(parent.toLowerCase())?.chain
1016
+ : undefined
1017
+ const result = await port.collection(
1018
+ parent,
1019
+ page,
1020
+ principal && chain ? deniedChildren(principal, chain) : [],
1021
+ )
1010
1022
  return Response.json({
1011
1023
  total: result.total,
1012
1024
  items: result.items.map((aggregate) => ({
@@ -6,7 +6,7 @@
6
6
  * when its story in docs/stories/ lands. Counted
7
7
  * separately by `coverage:api`.
8
8
  */
9
- import { invalidSkipTake, notFound, problemResponse } from '@crombolo/core'
9
+ import { invalidSkipTake, notFound, problemDetails, problemResponse } from '@crombolo/core'
10
10
  import type { ManagementApiRouter } from '../router.ts'
11
11
  import { paging } from './content-type.ts'
12
12
 
@@ -34,10 +34,8 @@ const SIBLINGS = [
34
34
  /** Lookups of one thing in an empty area: there is nothing to find. */
35
35
  const NOT_FOUND: string[] = []
36
36
 
37
- /** Fixed bodies. Umbraco's news dashboard relays umbraco.com; there is no feed to relay here. */
38
- const FIXED: Record<string, unknown> = {
39
- GetNewsDashboard: { items: [] },
40
- }
37
+ /** Fixed bodies. */
38
+ const FIXED: Record<string, unknown> = {}
41
39
 
42
40
  export const EMPTY_SETTINGS_OPERATIONS: readonly string[] = [
43
41
  ...PAGED,
@@ -64,4 +62,15 @@ export function registerSettingsStubHandlers(router: ManagementApiRouter): void
64
62
  for (const [operation, body] of Object.entries(FIXED)) {
65
63
  router.handle(operation, () => Response.json(body))
66
64
  }
65
+ // Umbraco's news dashboard relays umbraco.com's feed. There is no feed here,
66
+ // and the dashboard is not vendored, so the operation is gone rather than empty.
67
+ router.handle('GetNewsDashboard', () =>
68
+ problemResponse(
69
+ problemDetails({
70
+ title: 'There is no news feed',
71
+ detail: 'This site relays no news from anywhere.',
72
+ status: 410,
73
+ }),
74
+ ),
75
+ )
67
76
  }
@@ -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 {
@@ -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)