@crombolo/server 0.65.1 → 0.67.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.
@@ -0,0 +1,229 @@
1
+ /**
2
+ * The remote protocol's routes for back-office users (story 356): a user found,
3
+ * changed and removed, open sign-ins listed and ended, and where a group starts
4
+ * and who owns it. Each answers as the signed-in person through the core the
5
+ * command line uses; CI is refused, since these act for a person. A write is
6
+ * audited as the Management API audits the same change, by key.
7
+ */
8
+ import { hasSection, type Principal } from '@crombolo/api-management/domain'
9
+ import { AuthStore } from '@crombolo/auth'
10
+ import type { Db } from '@crombolo/data'
11
+ import { recordAudit } from './adapters/audit.ts'
12
+ import {
13
+ changeUser,
14
+ endSignIn,
15
+ findUser,
16
+ type GroupPlaceChange,
17
+ placeGroup,
18
+ removeUser,
19
+ signIns,
20
+ UserAdminError,
21
+ type UserChange,
22
+ type UserPorts,
23
+ } from './user-admin.ts'
24
+
25
+ interface Problem {
26
+ code: string
27
+ title: string
28
+ detail?: string
29
+ items?: string[]
30
+ }
31
+
32
+ export interface UserRouteOptions {
33
+ db: Db
34
+ ports: () => Promise<UserPorts> | UserPorts
35
+ problem(status: number, body: Problem): Response
36
+ /** A refusal when the site's remote access level takes no changes. */
37
+ levelRefusal(): Response | undefined
38
+ }
39
+
40
+ const KEY = /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/
41
+
42
+ const STATUS: Record<UserAdminError['kind'], [number, string]> = {
43
+ not_found: [404, 'not-found'],
44
+ refused: [403, 'forbidden'],
45
+ usage: [400, 'bad-request'],
46
+ conflict: [409, 'conflict'],
47
+ }
48
+
49
+ const body = async (request: Request): Promise<Record<string, unknown>> => {
50
+ const read = await request.json().catch(() => ({}))
51
+ return read && typeof read === 'object' ? (read as Record<string, unknown>) : {}
52
+ }
53
+
54
+ const text = (value: unknown): string | undefined => (typeof value === 'string' ? value : undefined)
55
+ const texts = (value: unknown): string[] =>
56
+ Array.isArray(value) ? value.filter((v): v is string => typeof v === 'string') : []
57
+
58
+ /** A user change as a request names it: only the fields it gives. */
59
+ function userChangeOf(asked: Record<string, unknown>): UserChange {
60
+ const change: UserChange = {}
61
+ if (text(asked.name) !== undefined) change.name = text(asked.name)
62
+ if (text(asked.email) !== undefined) change.email = text(asked.email)
63
+ if (text(asked.uiLanguage) !== undefined) change.uiLanguage = text(asked.uiLanguage)
64
+ if (Array.isArray(asked.addGroups)) change.addGroups = texts(asked.addGroups)
65
+ if (Array.isArray(asked.removeGroups)) change.removeGroups = texts(asked.removeGroups)
66
+ return change
67
+ }
68
+
69
+ function placeChangeOf(asked: Record<string, unknown>): GroupPlaceChange {
70
+ const change: GroupPlaceChange = {}
71
+ for (const tree of ['content', 'media', 'library'] as const)
72
+ if (text(asked[tree]) !== undefined) change[tree] = text(asked[tree])
73
+ if (Array.isArray(asked.addOwners)) change.addOwners = texts(asked.addOwners)
74
+ if (Array.isArray(asked.removeOwners)) change.removeOwners = texts(asked.removeOwners)
75
+ return change
76
+ }
77
+
78
+ /** The session a request's bearer token belongs to, so its own sign-in is marked. */
79
+ async function sessionOf(db: Db, request: Request): Promise<string | undefined> {
80
+ const header = request.headers.get('authorization')
81
+ if (!header?.toLowerCase().startsWith('bearer ')) return undefined
82
+ return (await new AuthStore(db).findToken(header.slice(7).trim(), 'access'))?.sessionId
83
+ }
84
+
85
+ export function createUserRoutes(options: UserRouteOptions) {
86
+ const { db, problem } = options
87
+ const refused = (error: unknown): Response => {
88
+ if (!(error instanceof UserAdminError)) throw error
89
+ const [status, code] = STATUS[error.kind]
90
+ return problem(status, {
91
+ code,
92
+ title: error.message,
93
+ ...(error.hint ? { detail: error.hint } : {}),
94
+ })
95
+ }
96
+ const audited = (
97
+ principal: Principal,
98
+ request: Request,
99
+ entry: { category: 'user' | 'permission'; action: string; entityType: string; key: string },
100
+ ) =>
101
+ recordAudit(db, {
102
+ category: entry.category,
103
+ action: entry.action,
104
+ source: 'request',
105
+ userKey: principal.id,
106
+ userName: principal.name,
107
+ entityType: entry.entityType,
108
+ entityKey: entry.key,
109
+ forwardedFor: request.headers.get('x-forwarded-for'),
110
+ detail: 'Through the remote protocol',
111
+ })
112
+
113
+ async function users(request: Request, url: URL, principal: Principal, key?: string) {
114
+ const ports = await options.ports()
115
+ const method = request.method
116
+ if (method === 'GET') {
117
+ const find = key ?? url.searchParams.get('find')
118
+ if (!find) return problem(400, { code: 'bad-request', title: 'Name the user with ?find=' })
119
+ return Response.json(await findUser(ports, principal, find))
120
+ }
121
+ if (!key || !KEY.test(key))
122
+ return problem(400, { code: 'bad-key', title: 'A user is changed by their key' })
123
+ const level = options.levelRefusal()
124
+ if (level) return level
125
+ if (method === 'PATCH') {
126
+ const done = await changeUser(ports, principal, key, userChangeOf(await body(request)))
127
+ if (done.changed.length > 0)
128
+ await audited(principal, request, {
129
+ category: 'user',
130
+ action: 'Save',
131
+ entityType: 'User',
132
+ key: done.user.key,
133
+ })
134
+ return Response.json(done)
135
+ }
136
+ if (method === 'DELETE') {
137
+ const gone = await removeUser(ports, principal, key)
138
+ await audited(principal, request, {
139
+ category: 'user',
140
+ action: 'Delete',
141
+ entityType: 'User',
142
+ key: gone.key,
143
+ })
144
+ return Response.json(gone)
145
+ }
146
+ return new Response(null, { status: 405 })
147
+ }
148
+
149
+ async function sessions(request: Request, url: URL, principal: Principal, id?: string) {
150
+ const current = await sessionOf(db, request)
151
+ if (request.method === 'GET' && !id) {
152
+ const user = url.searchParams.get('user') ?? undefined
153
+ return Response.json({ items: await signIns(db, principal, { user, current }) })
154
+ }
155
+ if (request.method === 'DELETE' && id) {
156
+ const level = options.levelRefusal()
157
+ if (level) return level
158
+ const ended = await endSignIn(db, principal, id, { current })
159
+ await audited(principal, request, {
160
+ category: 'user',
161
+ action: 'EndSession',
162
+ entityType: 'User',
163
+ key: ended.user.key,
164
+ })
165
+ return Response.json(ended)
166
+ }
167
+ return new Response(null, { status: 405 })
168
+ }
169
+
170
+ async function group(request: Request, url: URL, principal: Principal, alias: string) {
171
+ if (request.method !== 'PATCH') return new Response(null, { status: 405 })
172
+ const dryRun = url.searchParams.get('dryRun') === 'true'
173
+ if (!dryRun) {
174
+ const level = options.levelRefusal()
175
+ if (level) return level
176
+ }
177
+ const placed = await placeGroup(
178
+ await options.ports(),
179
+ principal,
180
+ alias,
181
+ placeChangeOf(await body(request)),
182
+ { dryRun },
183
+ )
184
+ if (!dryRun && placed.changed.length > 0)
185
+ await audited(principal, request, {
186
+ category: 'permission',
187
+ action: 'Save',
188
+ entityType: 'UserGroup',
189
+ key: placed.group.key,
190
+ })
191
+ return Response.json(placed)
192
+ }
193
+
194
+ return {
195
+ /** The capability these routes add to discovery. */
196
+ capabilities: ['users'],
197
+
198
+ /** Answers one of these routes, or undefined when `what` is none of them. */
199
+ async handle(
200
+ request: Request,
201
+ url: URL,
202
+ principal: Principal,
203
+ what: string,
204
+ ): Promise<Response | undefined> {
205
+ const user = /^users(?:\/([^/]+))?$/.exec(what)
206
+ const signIn = /^sign-ins(?:\/([^/]+))?$/.exec(what)
207
+ const userGroup = /^user-groups\/([^/]+)$/.exec(what)
208
+ if (!user && !signIn && !userGroup) return undefined
209
+ if (principal.ci)
210
+ return problem(403, {
211
+ code: 'ci-cannot-change-people',
212
+ title: 'Changing people needs a person',
213
+ detail: 'Sign in as yourself: CI cannot do this.',
214
+ })
215
+ const named = (user ?? signIn ?? userGroup)?.[1]
216
+ const decoded = named === undefined ? undefined : decodeURIComponent(named)
217
+ try {
218
+ if (signIn) return await sessions(request, url, principal, decoded)
219
+ if (!hasSection(principal, 'users'))
220
+ return problem(403, { code: 'forbidden', title: 'You may not look after users here' })
221
+ return user
222
+ ? await users(request, url, principal, decoded)
223
+ : await group(request, url, principal, decoded as string)
224
+ } catch (error) {
225
+ return refused(error)
226
+ }
227
+ },
228
+ }
229
+ }
package/src/remote.ts CHANGED
@@ -16,8 +16,9 @@ import { mkdir, rm } from 'node:fs/promises'
16
16
  import { tmpdir } from 'node:os'
17
17
  import { join, sep } from 'node:path'
18
18
  import { hasSection, type Principal } from '@crombolo/api-management/domain'
19
- import { DEVICE_CODE_GRANT, REMOTE_CLIENT_ID } from '@crombolo/auth'
19
+ import { AuthStore, DEVICE_CODE_GRANT, REMOTE_CLIENT_ID } from '@crombolo/auth'
20
20
  import { BACKOFFICE_CODE, BACKOFFICE_CODE_WARNING } from '@crombolo/backoffice-host/registry'
21
+ import type { DocumentOperations, MediaOperations } from '@crombolo/content'
21
22
  import {
22
23
  EXPLICIT_PERMISSIONS,
23
24
  managementApiPath,
@@ -43,7 +44,10 @@ import {
43
44
  type Resolution,
44
45
  revertRun,
45
46
  } from '@crombolo/transfer'
47
+ import { createNodeLookup } from './access.ts'
46
48
  import { readAuditPageQuery, recordAudit } from './adapters/audit.ts'
49
+ import type { MemberPortOptions } from './adapters/members.ts'
50
+ import { createUserPorts } from './adapters/users.ts'
47
51
  import { type BundleAdmin, settingsIn } from './bundle-admin.ts'
48
52
  import { userKeyOf } from './bundle-api.ts'
49
53
  import { codeChanges, installedCode, planCode } from './bundle-code-install.ts'
@@ -62,15 +66,24 @@ import {
62
66
  } from './bundle-sections.ts'
63
67
  import { type CromboloConfig, REMOTE_ACCESS_LEVELS, type RemoteAccess } from './config.ts'
64
68
  import { answerContentQuery, contentQueryScope } from './content-query.ts'
65
- import { mediaStoreFor } from './media-files.ts'
69
+ import { MediaFileStore, mediaStoreFor } from './media-files.ts'
66
70
  import { type MediaStore, streamOf } from './media-store.ts'
71
+ import { siteMemberPorts } from './member-admin.ts'
67
72
  import { describeProvenance, provenanceProblem, verifyProvenance } from './provenance.ts'
68
- import { createCiSignIn, readRuleInput, trustedIssuers } from './remote-ci.ts'
73
+ import { createBackgroundJobRoutes } from './remote-background-jobs.ts'
74
+ import { createCiSignIn, readRuleInput, trustedIssuers, unverifiedIssuer } from './remote-ci.ts'
75
+ import { createExtensionActivityRoutes } from './remote-extension-activity.ts'
76
+ import { createMediaLibraryRoutes } from './remote-media-library.ts'
77
+ import { createMemberRoutes } from './remote-members.ts'
78
+ import type { PeopleExchange } from './remote-people.ts'
79
+ import { createUndoRoutes } from './remote-undo.ts'
80
+ import { createUserRoutes } from './remote-users.ts'
69
81
  import { openSecret, sealSecret, usableSecretKey } from './secrets.ts'
70
82
  import { exportSite } from './site-file.ts'
71
83
  import { REMOTE_DISCOVERY_PATH } from './site-public.ts'
72
84
  import { replaceSummary } from './site-replace.ts'
73
85
  import { extractTarball } from './tar.ts'
86
+ import type { UserPorts } from './user-admin.ts'
74
87
 
75
88
  export const REMOTE_PROTOCOL_VERSION = '1'
76
89
  export { REMOTE_DISCOVERY_PATH }
@@ -90,6 +103,8 @@ export interface RemoteOptions {
90
103
  db: Db
91
104
  config: CromboloConfig
92
105
  authenticate(request: Request): Promise<Principal | undefined>
106
+ /** Story 364: a back-office provider's token exchanged for a sign-in as the person it names. */
107
+ people?: PeopleExchange
93
108
  /**
94
109
  * Told once a push has landed, so this node's published cache is rebuilt: the
95
110
  * import's cache instruction carries this node's id, and a node skips its own.
@@ -100,6 +115,18 @@ export interface RemoteOptions {
100
115
  restart?: () => Promise<RestartOutcome>
101
116
  /** Installed bundles (story 241); absent where this node does not manage them. */
102
117
  bundles?: BundleAdmin
118
+ /** The content and media operations, for undoing a change (story 353); absent, those routes are not offered. */
119
+ operations?: { documents: DocumentOperations; media: MediaOperations }
120
+ /** The server's own schema state, so a node behind the database writes no members. */
121
+ nodeState?: MemberPortOptions['nodeState']
122
+ /** The server's own user ports, as the Users section uses them; absent, made over the database. */
123
+ userPorts?: () => Pick<UserPorts, 'users' | 'groups'> | undefined
124
+ /** When this node began waiting for a background worker that is not running (story 223), or null. */
125
+ jobsWaitingSince?: () => string | null
126
+ /** The extension activity recorder's flush and the counts' window (story 362); absent, those routes are not offered. */
127
+ activity?: { flush(): Promise<void>; days: number }
128
+ /** Told after a media item's permissions change here (story 355), for this node's media cache. */
129
+ onMediaAccessChange?(key: string): void | Promise<void>
103
130
  }
104
131
 
105
132
  /** What a supervised restart came to: the new server serving, or why the old one still is. */
@@ -199,7 +226,7 @@ export function createRemote(options: RemoteOptions): Remote {
199
226
  // Under the back office, as the editor's own API calls are; a command line
200
227
  // follows these addresses rather than building its own.
201
228
  const managementApi = managementApiPath(config.backOfficePath.replace(/\/+$/, ''))
202
- const discovery = (origin: string) => ({
229
+ const discovery = async (origin: string) => ({
203
230
  protocol: 'crombolo-remote',
204
231
  versions: [REMOTE_PROTOCOL_VERSION],
205
232
  // The bundle formats this site reads, oldest and newest (story 306).
@@ -213,6 +240,11 @@ export function createRemote(options: RemoteOptions): Remote {
213
240
  grantType: DEVICE_CODE_GRANT,
214
241
  // Story 160: a CI job's identity token, exchanged for a token acting as a trust rule.
215
242
  ci: ci.discovery(origin, `${origin}${REMOTE_API_PATH}`),
243
+ // Story 364: a person's token from one of this site's own back-office providers.
244
+ ...(await (async () => {
245
+ const people = await options.people?.discovery(origin, `${origin}${REMOTE_API_PATH}`)
246
+ return people ? { people } : {}
247
+ })()),
216
248
  },
217
249
  capabilities: [
218
250
  ...(atLeast('content') ? ['bundle-apply'] : []),
@@ -221,6 +253,12 @@ export function createRemote(options: RemoteOptions): Remote {
221
253
  'push-check',
222
254
  'audit',
223
255
  'content-query',
256
+ ...(options.operations ? ['content-history', 'recycle-bin'] : []),
257
+ ...memberRoutes.capabilities,
258
+ ...userRoutes.capabilities,
259
+ ...backgroundJobRoutes.capabilities,
260
+ ...(activityRoutes?.capabilities ?? []),
261
+ ...(mediaLibraryRoutes?.capabilities ?? []),
224
262
  ...(settings.approvals ? ['approvals'] : []),
225
263
  ...(options.bundles && atLeast('read') ? ['bundle-manage'] : []),
226
264
  ...(options.restart && atLeast('all') ? ['restart'] : []),
@@ -254,6 +292,73 @@ export function createRemote(options: RemoteOptions): Remote {
254
292
  detail: `${detail}${ciRun(principal)}`,
255
293
  })
256
294
 
295
+ const undo = options.operations
296
+ ? createUndoRoutes({
297
+ db,
298
+ operations: options.operations,
299
+ problem,
300
+ levelRefusal: () =>
301
+ atLeast('content') ? undefined : notAtLevel('content', 'changes to content'),
302
+ })
303
+ : undefined
304
+
305
+ const memberRoutes = createMemberRoutes({
306
+ db,
307
+ ports: () => siteMemberPorts(db, config, options.nodeState),
308
+ operations: options.operations?.documents,
309
+ problem,
310
+ levelRefusal: () =>
311
+ atLeast('content') ? undefined : notAtLevel('content', 'changes to members or pages'),
312
+ })
313
+
314
+ const backgroundJobRoutes = createBackgroundJobRoutes({
315
+ db,
316
+ problem,
317
+ levelRefusal: () => (atLeast('content') ? undefined : notAtLevel('content', 'job retries')),
318
+ waitingSince: options.jobsWaitingSince,
319
+ })
320
+
321
+ const activityRoutes = options.activity
322
+ ? createExtensionActivityRoutes({ db, problem, activity: options.activity })
323
+ : undefined
324
+
325
+ const mediaLibraryRoutes = options.operations
326
+ ? createMediaLibraryRoutes({
327
+ db,
328
+ media: options.operations.media,
329
+ files: async () => new MediaFileStore(await store()),
330
+ problem,
331
+ levelRefusal: () =>
332
+ atLeast('content') ? undefined : notAtLevel('content', 'changes to media'),
333
+ receive: (request, path) => receive(request, path),
334
+ onAccessChange: options.onMediaAccessChange,
335
+ nodeId: config.nodeId,
336
+ })
337
+ : undefined
338
+
339
+ const userRoutes = createUserRoutes({
340
+ db,
341
+ ports: async () => {
342
+ const own = options.userPorts?.()
343
+ if (own) return { db, ...own }
344
+ const auth = new AuthStore(db)
345
+ return {
346
+ db,
347
+ ...createUserPorts(db, {
348
+ config,
349
+ mediaFiles: new MediaFileStore(await store()),
350
+ nodes: createNodeLookup(db),
351
+ endSessions: async (userId) => {
352
+ await auth.endAllSessionsForUser(userId)
353
+ },
354
+ }),
355
+ }
356
+ },
357
+ problem,
358
+ levelRefusal: () =>
359
+ atLeast('content') ? undefined : notAtLevel('content', 'changes to users'),
360
+ })
361
+
257
362
  const trust = new RemoteTrustRepository(db)
258
363
  const ci = createCiSignIn({
259
364
  db,
@@ -1194,6 +1299,18 @@ export function createRemote(options: RemoteOptions): Remote {
1194
1299
  // CI never approves, whatever its rule holds: a second person is the point.
1195
1300
  if (principal.ci)
1196
1301
  return problem(403, { code: 'ci-cannot-approve', title: 'CI cannot approve pushes' })
1302
+ if (principal.viaToken)
1303
+ return problem(403, {
1304
+ code: 'token-cannot-approve',
1305
+ title: 'A command-line token cannot approve pushes',
1306
+ detail: 'Approve or decline it signed in as yourself.',
1307
+ })
1308
+ if (principal.viaExchange)
1309
+ return problem(403, {
1310
+ code: 'exchange-cannot-approve',
1311
+ title: 'A sign-in through another service cannot approve pushes',
1312
+ detail: 'Approve or decline it signed in as yourself.',
1313
+ })
1197
1314
  const job = await jobs.get(id)
1198
1315
  if (job?.kind !== 'push')
1199
1316
  return problem(404, { code: 'not-found', title: 'There is no such push' })
@@ -1400,7 +1517,8 @@ export function createRemote(options: RemoteOptions): Remote {
1400
1517
  return (
1401
1518
  url.pathname === `${prefix}pushes` ||
1402
1519
  url.pathname === `${prefix}bundles` ||
1403
- url.pathname.startsWith(`${prefix}media/`)
1520
+ url.pathname.startsWith(`${prefix}media/`) ||
1521
+ (mediaLibraryRoutes?.isUpload(url.pathname.slice(prefix.length), request.method) ?? false)
1404
1522
  )
1405
1523
  },
1406
1524
 
@@ -1409,16 +1527,28 @@ export function createRemote(options: RemoteOptions): Remote {
1409
1527
  if (pathname === REMOTE_DISCOVERY_PATH) {
1410
1528
  if (!settings.enabled) return undefined
1411
1529
  return request.method === 'GET'
1412
- ? Response.json(discovery(url.origin), { headers: { 'cache-control': 'no-store' } })
1530
+ ? Response.json(await discovery(url.origin), {
1531
+ headers: { 'cache-control': 'no-store' },
1532
+ })
1413
1533
  : new Response(null, { status: 405 })
1414
1534
  }
1415
1535
  if (!pathname.startsWith(`${REMOTE_API_PATH}/`)) return undefined
1416
1536
  if (!settings.enabled)
1417
1537
  return problem(404, { code: 'not-enabled', title: 'This site is not a remote' })
1418
- if (pathname === `${REMOTE_API_PATH}/token`)
1419
- return request.method === 'POST'
1420
- ? ci.exchange(request, url, request.headers.get('x-forwarded-for')?.split(',')[0]?.trim())
1421
- : new Response(null, { status: 405 })
1538
+ if (pathname === `${REMOTE_API_PATH}/token`) {
1539
+ if (request.method !== 'POST') return new Response(null, { status: 405 })
1540
+ const ip = request.headers.get('x-forwarded-for')?.split(',')[0]?.trim()
1541
+ // One endpoint for both: the token's issuer says whether it is CI's or a person's.
1542
+ const people = options.people
1543
+ const issuer = people
1544
+ ? unverifiedIssuer(
1545
+ new URLSearchParams(await request.clone().text()).get('subject_token') ?? '',
1546
+ )
1547
+ : undefined
1548
+ return people && issuer && (await people.handles(issuer))
1549
+ ? people.exchange(request, url, ip)
1550
+ : ci.exchange(request, url, ip)
1551
+ }
1422
1552
  // A CI token is good here and nowhere else; a person's is the back office's own.
1423
1553
  const principal = (await ci.principalOf(request)) ?? (await options.authenticate(request))
1424
1554
  if (!principal)
@@ -1459,6 +1589,10 @@ export function createRemote(options: RemoteOptions): Remote {
1459
1589
  mayChange(principal) &&
1460
1590
  may(principal, RemotePermissions.ApplyStructure),
1461
1591
  audit: mayReadAudit(principal),
1592
+ backgroundJobs: backgroundJobRoutes.may(principal),
1593
+ extensionActivity: activityRoutes?.may(principal) ?? false,
1594
+ mediaLibrary: mediaLibraryRoutes?.mayMedia(principal) ?? false,
1595
+ contentShow: mediaLibraryRoutes?.mayContent(principal) ?? false,
1462
1596
  },
1463
1597
  },
1464
1598
  ])
@@ -1502,7 +1636,37 @@ export function createRemote(options: RemoteOptions): Remote {
1502
1636
  await request.json().catch(() => undefined),
1503
1637
  )
1504
1638
  }
1639
+ if (what.startsWith('member') || what.startsWith('content/')) {
1640
+ const answered = await memberRoutes.handle(request, url, principal, what)
1641
+ if (answered) return answered
1642
+ }
1643
+ if (what.startsWith('background-jobs')) {
1644
+ const answered = await backgroundJobRoutes.handle(request, url, principal, what)
1645
+ if (answered) return answered
1646
+ }
1647
+ if (what.startsWith('user') || what.startsWith('sign-ins')) {
1648
+ const answered = await userRoutes.handle(request, url, principal, what)
1649
+ if (answered) return answered
1650
+ }
1651
+ if (
1652
+ undo &&
1653
+ (what.startsWith('content/') || what === 'recycle-bin' || what.startsWith('recycle-bin/'))
1654
+ ) {
1655
+ const answered = await undo.handle(request, url, principal, what)
1656
+ if (answered) return answered
1657
+ }
1658
+ if (
1659
+ mediaLibraryRoutes &&
1660
+ (what.startsWith('media-items') || what.startsWith('content-items/'))
1661
+ ) {
1662
+ const answered = await mediaLibraryRoutes.handle(request, url, principal, what)
1663
+ if (answered) return answered
1664
+ }
1505
1665
  if (what === 'restart' && request.method === 'POST') return restartSite(request, principal)
1666
+ if (activityRoutes && what.startsWith('installed/')) {
1667
+ const answered = await activityRoutes.handle(request, url, principal, what)
1668
+ if (answered) return answered
1669
+ }
1506
1670
  if (what === 'installed' || what.startsWith('installed/'))
1507
1671
  return manageBundles(request, principal, what)
1508
1672
  // Story 167: the site's level first, then the person's permissions.
@@ -11,10 +11,17 @@ import {
11
11
  dateFromText,
12
12
  isBlockValue,
13
13
  normaliseUuid,
14
+ ObjectTypes,
14
15
  readBlocks,
15
16
  SINGLE_BLOCK_EDITOR_ALIAS,
16
17
  } from '@crombolo/core'
17
- import { ContentTypeRepository, DataTypeRepository, type Db, looksLikeKey } from '@crombolo/data'
18
+ import {
19
+ ContentTypeRepository,
20
+ DataTypeRepository,
21
+ type Db,
22
+ looksLikeKey,
23
+ resolveNodeRef,
24
+ } from '@crombolo/data'
18
25
  import { blockKey, pickKey } from './keys.ts'
19
26
 
20
27
  const isRecord = (value: unknown): value is Record<string, unknown> =>
@@ -33,27 +40,30 @@ export interface PropertyEditor {
33
40
  config: Record<string, unknown>
34
41
  }
35
42
 
43
+ type TypeKind = 'document' | 'media' | 'member'
44
+
36
45
  /** The site's types and their properties' editors, looked up once each. */
37
46
  export function schemaLookup(db: Db) {
38
47
  const repos = {
39
48
  document: new ContentTypeRepository(db),
40
49
  media: new ContentTypeRepository(db, { kind: 'media' }),
50
+ member: new ContentTypeRepository(db, { kind: 'member' }),
41
51
  }
42
52
  const dataTypes = new DataTypeRepository(db)
43
53
  const types = new Map<string, ContentTypeAggregate | undefined>()
44
54
  const editors = new Map<string, Map<string, PropertyEditor>>()
45
55
  return {
46
56
  repos,
47
- async typeOf(kind: 'document' | 'media', alias: string) {
57
+ async typeOf(kind: TypeKind, alias: string) {
48
58
  const key = `${kind}:${alias.toLowerCase()}`
49
59
  if (!types.has(key)) types.set(key, await repos[kind].byAlias(alias))
50
60
  return types.get(key)
51
61
  },
52
- async typeByKey(kind: 'document' | 'media', typeKey: string) {
62
+ async typeByKey(kind: TypeKind, typeKey: string) {
53
63
  return repos[kind].byKey(normaliseUuid(typeKey))
54
64
  },
55
65
  async editorsOf(
56
- kind: 'document' | 'media',
66
+ kind: TypeKind,
57
67
  type: Pick<ContentTypeAggregate, 'key'>,
58
68
  ): Promise<Map<string, PropertyEditor>> {
59
69
  const cached = editors.get(type.key)
@@ -91,6 +101,74 @@ export interface ValueRefs {
91
101
  linkedMedia(ref: string): Promise<string | undefined>
92
102
  }
93
103
 
104
+ const OBJECT_TYPES = {
105
+ content: ObjectTypes.Document,
106
+ library: ObjectTypes.Element,
107
+ media: ObjectTypes.Media,
108
+ } as const
109
+
110
+ /** What a value's paths name, in this site's database. */
111
+ export function siteValueRefs(db: Db): ValueRefs {
112
+ const keyOf = async (ref: string, kind: keyof typeof OBJECT_TYPES) => {
113
+ const resolved = await resolveNodeRef(db, [OBJECT_TYPES[kind]], ref)
114
+ return resolved.ok && resolved.node.objectType === OBJECT_TYPES[kind]
115
+ ? resolved.node.key
116
+ : undefined
117
+ }
118
+ return {
119
+ content: (ref) => keyOf(ref, 'content'),
120
+ library: (ref) => keyOf(ref, 'library'),
121
+ // A Library form by its path or key; anything else is a form's own alias, as before.
122
+ async form(ref) {
123
+ if (looksLikeKey(ref)) return normaliseUuid(ref)
124
+ const key = await keyOf(ref, 'library')
125
+ if (!key) return ref
126
+ const rows = await db.q
127
+ .selectFrom('node as n')
128
+ .innerJoin('content as c', 'c.node_id', 'n.id')
129
+ .innerJoin('content_type as ct', 'ct.node_id', 'c.content_type_id')
130
+ .select('ct.form_key')
131
+ .where('n.unique_id', '=', key)
132
+ .execute()
133
+ return rows[0]?.form_key ? key : undefined
134
+ },
135
+ linkedMedia: (ref) => keyOf(ref, 'media'),
136
+ async media(ref) {
137
+ const key = await keyOf(ref, 'media')
138
+ if (!key) return undefined
139
+ const rows = await db.q
140
+ .selectFrom('node as n')
141
+ .innerJoin('content as c', 'c.node_id', 'n.id')
142
+ .innerJoin('content_type as ct', 'ct.node_id', 'c.content_type_id')
143
+ .select('ct.alias')
144
+ .where('n.unique_id', '=', key)
145
+ .execute()
146
+ return { key, typeAlias: rows[0] ? String(rows[0].alias) : 'Image' }
147
+ },
148
+ }
149
+ }
150
+
151
+ const TEXTUAL = new Set([
152
+ 'Umbraco.TextBox',
153
+ 'Umbraco.TextArea',
154
+ 'Umbraco.RichText',
155
+ 'Umbraco.TinyMCE',
156
+ ])
157
+
158
+ /**
159
+ * A value as typed after `--set alias=`: text as it is for a text or rich text
160
+ * property, JSON where it reads as JSON for the rest (`true`, `3`,
161
+ * `["/a", "/b"]`), and the text itself otherwise, such as a path.
162
+ */
163
+ export function typedValue(editor: string, text: string): unknown {
164
+ if (TEXTUAL.has(editor)) return text
165
+ try {
166
+ return JSON.parse(text)
167
+ } catch {
168
+ return text
169
+ }
170
+ }
171
+
94
172
  /** The shorthand into each editor's stored shape. */
95
173
  export function valueWriter(lookup: SchemaLookup, refs: ValueRefs) {
96
174
  const trimPath = (ref: string) => ref.replace(/^\/+|\/+$/g, '')