@crombolo/server 0.65.1 → 0.66.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,234 @@
1
+ /**
2
+ * The remote protocol's routes for undoing a change (story 353): a page's
3
+ * history, a version shown, rolled back and kept, and the recycle bin listed and
4
+ * restored from. Each answers as the signed-in person, through the operations the
5
+ * back office's handlers use; CI is refused, since these act for a person.
6
+ */
7
+ import { hasSection, type Principal } from '@crombolo/api-management/domain'
8
+ import {
9
+ type DocumentOperations,
10
+ MEDIA_JOBS,
11
+ type MediaOperations,
12
+ type Refusal,
13
+ userActor,
14
+ } from '@crombolo/content'
15
+ import { type Db, DocumentRepository, JobRepository } from '@crombolo/data'
16
+ import {
17
+ type BinItem,
18
+ type BinKind,
19
+ binItems,
20
+ pageHistory,
21
+ pageVersion,
22
+ placeGone,
23
+ } from './undo.ts'
24
+
25
+ interface Problem {
26
+ code: string
27
+ title: string
28
+ detail?: string
29
+ items?: string[]
30
+ }
31
+
32
+ export interface UndoRouteOptions {
33
+ db: Db
34
+ operations: { documents: DocumentOperations; media: MediaOperations }
35
+ problem(status: number, body: Problem): Response
36
+ /** A refusal when the site's remote access level takes no changes to content. */
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
+ const UUID = new RegExp(`^${KEY}$`)
42
+ const SECTION: Record<BinKind, 'content' | 'media'> = { content: 'content', media: 'media' }
43
+
44
+ const CODES: Partial<Record<Refusal['kind'], string>> = {
45
+ notFound: 'not-found',
46
+ forbidden: 'forbidden',
47
+ needsApproval: 'needs-approval',
48
+ invalid: 'invalid',
49
+ conflict: 'conflict',
50
+ blocked: 'blocked',
51
+ validation: 'invalid',
52
+ stale: 'conflict',
53
+ }
54
+
55
+ const body = async (request: Request): Promise<Record<string, unknown>> => {
56
+ const read = await request.json().catch(() => ({}))
57
+ return read && typeof read === 'object' ? (read as Record<string, unknown>) : {}
58
+ }
59
+
60
+ export function createUndoRoutes(options: UndoRouteOptions) {
61
+ const { db, operations, problem } = options
62
+ const refused = (
63
+ result: Refusal & { blocked?: Array<{ key: string; reasons: string[] }> },
64
+ ): Response =>
65
+ problem(result.kind === 'needsApproval' ? 409 : result.status || 400, {
66
+ code: CODES[result.kind] ?? 'refused',
67
+ title: result.reason,
68
+ ...(result.blocked ? { items: result.blocked.flatMap((b) => b.reasons) } : {}),
69
+ })
70
+ const actorOf = (principal: Principal, request: Request, skipApproval = false) =>
71
+ userActor(
72
+ principal,
73
+ { source: 'request', forwardedFor: request.headers.get('x-forwarded-for') },
74
+ { skipApproval },
75
+ )
76
+ const notHere = (title: string) => problem(404, { code: 'not-found', title })
77
+ const noSection = (what: string) =>
78
+ problem(403, { code: 'forbidden', title: `You may not ${what} here` })
79
+
80
+ async function rollback(request: Request, principal: Principal, id: string) {
81
+ const level = options.levelRefusal()
82
+ if (level) return level
83
+ const asked = await body(request)
84
+ const publish = asked.publish === true
85
+ const skipApproval = asked.skipApproval === true
86
+ if (skipApproval && !principal.isAdmin)
87
+ return problem(403, { code: 'forbidden', title: 'Only an administrator can skip approval' })
88
+ const version = await pageVersion(db, id)
89
+ if (!version) return notHere('There is no such version')
90
+ const actor = actorOf(principal, request, skipApproval)
91
+ const rolled = await operations.documents.rollback(actor, id, { overwrite: true })
92
+ if (!rolled.ok) return refused(rolled)
93
+ if (publish) {
94
+ const published = await operations.documents.publishMany(
95
+ actor,
96
+ [version.page.key],
97
+ null,
98
+ 'publish',
99
+ )
100
+ if (!published.ok)
101
+ return refused({
102
+ ...published,
103
+ reason: `It was rolled back to a draft, and not published: ${published.reason}`,
104
+ })
105
+ }
106
+ return Response.json({ page: version.page, version: id, published: publish })
107
+ }
108
+
109
+ async function keep(request: Request, id: string) {
110
+ const level = options.levelRefusal()
111
+ if (level) return level
112
+ const keeping = (await body(request)).keep !== false
113
+ if (!(await pageVersion(db, id))) return notHere('There is no such version')
114
+ await new DocumentRepository(db).setPreventCleanup(id, keeping)
115
+ return Response.json({ version: id, kept: keeping })
116
+ }
117
+
118
+ const kindsFor = (principal: Principal, asked: string | null): BinKind[] | Response => {
119
+ const held = (['content', 'media'] as const).filter((kind) =>
120
+ hasSection(principal, SECTION[kind]),
121
+ )
122
+ if (asked === 'content' || asked === 'media')
123
+ return held.includes(asked) ? [asked] : noSection(`see the ${asked} recycle bin`)
124
+ if (asked) return problem(400, { code: 'bad-query', title: 'kind is content or media' })
125
+ return held.length > 0 ? held : noSection('see the recycle bin')
126
+ }
127
+
128
+ async function restore(request: Request, principal: Principal, key: string) {
129
+ const level = options.levelRefusal()
130
+ if (level) return level
131
+ const item = (await binItems(db)).find((candidate) => candidate.key === key.toLowerCase())
132
+ if (!item) return notHere('That is not in the recycle bin')
133
+ if (!hasSection(principal, SECTION[item.kind]))
134
+ return noSection(`restore ${item.kind === 'media' ? 'media' : 'pages'}`)
135
+ const asked = await body(request)
136
+ const target = asked.target
137
+ if (
138
+ target !== undefined &&
139
+ target !== null &&
140
+ !(typeof target === 'string' && UUID.test(target))
141
+ )
142
+ return problem(400, { code: 'bad-key', title: 'target is a key, or null for the top level' })
143
+ const gone = placeGone(item)
144
+ if (target === undefined && gone)
145
+ return problem(409, {
146
+ code: 'place-gone',
147
+ title: gone,
148
+ detail: 'Name another place to restore it to.',
149
+ })
150
+ const actor = actorOf(principal, request)
151
+ const to = target === undefined ? undefined : (target as string | null)
152
+ const done =
153
+ item.kind === 'media'
154
+ ? await operations.media.restore(actor, item.key, to)
155
+ : await operations.documents.restore(actor, item.key, to)
156
+ if (!done.ok) return refused(done)
157
+ const queued = (done as { queued?: string }).queued
158
+ if (queued) return Response.json({ item: described(item), queued }, { status: 202 })
159
+ return Response.json({ item: described(item), restored: true })
160
+ }
161
+
162
+ const described = (item: BinItem) => ({ key: item.key, name: item.name, kind: item.kind })
163
+
164
+ async function restoreJob(principal: Principal, id: string) {
165
+ if (!hasSection(principal, 'media')) return noSection('restore media')
166
+ const job = await new JobRepository(db).get(id)
167
+ if (!job || job.name !== MEDIA_JOBS.restore) return notHere('There is no such restore')
168
+ return Response.json({
169
+ state: job.state,
170
+ progress: job.progress,
171
+ error: job.state === 'failed' ? job.lastError : null,
172
+ })
173
+ }
174
+
175
+ return {
176
+ /** Answers one of these routes, or undefined when `what` is none of them. */
177
+ async handle(
178
+ request: Request,
179
+ url: URL,
180
+ principal: Principal,
181
+ what: string,
182
+ ): Promise<Response | undefined> {
183
+ const history = new RegExp(`^content/(${KEY})/history$`).exec(what)
184
+ const version = /^content\/versions\/(\d+)(?:\/(rollback|keep))?$/.exec(what)
185
+ const bin = new RegExp(`^recycle-bin(?:/(${KEY})/restore|/jobs/(${KEY}))?$`).exec(what)
186
+ if (!history && !version && !bin) return undefined
187
+ if (principal.ci)
188
+ return problem(403, {
189
+ code: 'needs-person',
190
+ title: 'Undoing a change needs a person',
191
+ detail: 'Sign in as yourself: CI cannot do this.',
192
+ })
193
+ const method = request.method
194
+ if (history || version) {
195
+ if (!hasSection(principal, 'content')) return noSection('see the history of pages')
196
+ if (history && method === 'GET') {
197
+ const found = await pageHistory(db, history[1] as string)
198
+ return found ? Response.json(found) : notHere('There is no such page')
199
+ }
200
+ const [, id, action] = version as unknown as [string, string, string | undefined]
201
+ if (!action && method === 'GET') {
202
+ const shown = await pageVersion(db, id, { diff: url.searchParams.get('diff') === 'true' })
203
+ return shown ? Response.json(shown) : notHere('There is no such version')
204
+ }
205
+ if (action === 'rollback' && method === 'POST') return rollback(request, principal, id)
206
+ if (action === 'keep' && method === 'PUT') return keep(request, id)
207
+ return new Response(null, { status: 405 })
208
+ }
209
+ const [, restoreKey, jobId] = bin as unknown as [
210
+ string,
211
+ string | undefined,
212
+ string | undefined,
213
+ ]
214
+ if (restoreKey)
215
+ return method === 'POST'
216
+ ? restore(request, principal, restoreKey)
217
+ : new Response(null, { status: 405 })
218
+ if (jobId)
219
+ return method === 'GET' ? restoreJob(principal, jobId) : new Response(null, { status: 405 })
220
+ if (method !== 'GET') return new Response(null, { status: 405 })
221
+ const kinds = kindsFor(principal, url.searchParams.get('kind'))
222
+ if (kinds instanceof Response) return kinds
223
+ const days = url.searchParams.get('olderThan')
224
+ if (days !== null && !/^\d+$/.test(days))
225
+ return problem(400, { code: 'bad-query', title: 'olderThan is a whole number of days' })
226
+ return Response.json({
227
+ items: await binItems(db, {
228
+ kinds,
229
+ ...(days !== null ? { olderThanDays: Number(days) } : {}),
230
+ }),
231
+ })
232
+ },
233
+ }
234
+ }
@@ -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,23 @@ 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'
73
+ import { createBackgroundJobRoutes } from './remote-background-jobs.ts'
68
74
  import { createCiSignIn, readRuleInput, trustedIssuers } 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 { createUndoRoutes } from './remote-undo.ts'
79
+ import { createUserRoutes } from './remote-users.ts'
69
80
  import { openSecret, sealSecret, usableSecretKey } from './secrets.ts'
70
81
  import { exportSite } from './site-file.ts'
71
82
  import { REMOTE_DISCOVERY_PATH } from './site-public.ts'
72
83
  import { replaceSummary } from './site-replace.ts'
73
84
  import { extractTarball } from './tar.ts'
85
+ import type { UserPorts } from './user-admin.ts'
74
86
 
75
87
  export const REMOTE_PROTOCOL_VERSION = '1'
76
88
  export { REMOTE_DISCOVERY_PATH }
@@ -100,6 +112,18 @@ export interface RemoteOptions {
100
112
  restart?: () => Promise<RestartOutcome>
101
113
  /** Installed bundles (story 241); absent where this node does not manage them. */
102
114
  bundles?: BundleAdmin
115
+ /** The content and media operations, for undoing a change (story 353); absent, those routes are not offered. */
116
+ operations?: { documents: DocumentOperations; media: MediaOperations }
117
+ /** The server's own schema state, so a node behind the database writes no members. */
118
+ nodeState?: MemberPortOptions['nodeState']
119
+ /** The server's own user ports, as the Users section uses them; absent, made over the database. */
120
+ userPorts?: () => Pick<UserPorts, 'users' | 'groups'> | undefined
121
+ /** When this node began waiting for a background worker that is not running (story 223), or null. */
122
+ jobsWaitingSince?: () => string | null
123
+ /** The extension activity recorder's flush and the counts' window (story 362); absent, those routes are not offered. */
124
+ activity?: { flush(): Promise<void>; days: number }
125
+ /** Told after a media item's permissions change here (story 355), for this node's media cache. */
126
+ onMediaAccessChange?(key: string): void | Promise<void>
103
127
  }
104
128
 
105
129
  /** What a supervised restart came to: the new server serving, or why the old one still is. */
@@ -221,6 +245,12 @@ export function createRemote(options: RemoteOptions): Remote {
221
245
  'push-check',
222
246
  'audit',
223
247
  'content-query',
248
+ ...(options.operations ? ['content-history', 'recycle-bin'] : []),
249
+ ...memberRoutes.capabilities,
250
+ ...userRoutes.capabilities,
251
+ ...backgroundJobRoutes.capabilities,
252
+ ...(activityRoutes?.capabilities ?? []),
253
+ ...(mediaLibraryRoutes?.capabilities ?? []),
224
254
  ...(settings.approvals ? ['approvals'] : []),
225
255
  ...(options.bundles && atLeast('read') ? ['bundle-manage'] : []),
226
256
  ...(options.restart && atLeast('all') ? ['restart'] : []),
@@ -254,6 +284,73 @@ export function createRemote(options: RemoteOptions): Remote {
254
284
  detail: `${detail}${ciRun(principal)}`,
255
285
  })
256
286
 
287
+ const undo = options.operations
288
+ ? createUndoRoutes({
289
+ db,
290
+ operations: options.operations,
291
+ problem,
292
+ levelRefusal: () =>
293
+ atLeast('content') ? undefined : notAtLevel('content', 'changes to content'),
294
+ })
295
+ : undefined
296
+
297
+ const memberRoutes = createMemberRoutes({
298
+ db,
299
+ ports: () => siteMemberPorts(db, config, options.nodeState),
300
+ operations: options.operations?.documents,
301
+ problem,
302
+ levelRefusal: () =>
303
+ atLeast('content') ? undefined : notAtLevel('content', 'changes to members or pages'),
304
+ })
305
+
306
+ const backgroundJobRoutes = createBackgroundJobRoutes({
307
+ db,
308
+ problem,
309
+ levelRefusal: () => (atLeast('content') ? undefined : notAtLevel('content', 'job retries')),
310
+ waitingSince: options.jobsWaitingSince,
311
+ })
312
+
313
+ const activityRoutes = options.activity
314
+ ? createExtensionActivityRoutes({ db, problem, activity: options.activity })
315
+ : undefined
316
+
317
+ const mediaLibraryRoutes = options.operations
318
+ ? createMediaLibraryRoutes({
319
+ db,
320
+ media: options.operations.media,
321
+ files: async () => new MediaFileStore(await store()),
322
+ problem,
323
+ levelRefusal: () =>
324
+ atLeast('content') ? undefined : notAtLevel('content', 'changes to media'),
325
+ receive: (request, path) => receive(request, path),
326
+ onAccessChange: options.onMediaAccessChange,
327
+ nodeId: config.nodeId,
328
+ })
329
+ : undefined
330
+
331
+ const userRoutes = createUserRoutes({
332
+ db,
333
+ ports: async () => {
334
+ const own = options.userPorts?.()
335
+ if (own) return { db, ...own }
336
+ const auth = new AuthStore(db)
337
+ return {
338
+ db,
339
+ ...createUserPorts(db, {
340
+ config,
341
+ mediaFiles: new MediaFileStore(await store()),
342
+ nodes: createNodeLookup(db),
343
+ endSessions: async (userId) => {
344
+ await auth.endAllSessionsForUser(userId)
345
+ },
346
+ }),
347
+ }
348
+ },
349
+ problem,
350
+ levelRefusal: () =>
351
+ atLeast('content') ? undefined : notAtLevel('content', 'changes to users'),
352
+ })
353
+
257
354
  const trust = new RemoteTrustRepository(db)
258
355
  const ci = createCiSignIn({
259
356
  db,
@@ -1194,6 +1291,12 @@ export function createRemote(options: RemoteOptions): Remote {
1194
1291
  // CI never approves, whatever its rule holds: a second person is the point.
1195
1292
  if (principal.ci)
1196
1293
  return problem(403, { code: 'ci-cannot-approve', title: 'CI cannot approve pushes' })
1294
+ if (principal.viaToken)
1295
+ return problem(403, {
1296
+ code: 'token-cannot-approve',
1297
+ title: 'A command-line token cannot approve pushes',
1298
+ detail: 'Approve or decline it signed in as yourself.',
1299
+ })
1197
1300
  const job = await jobs.get(id)
1198
1301
  if (job?.kind !== 'push')
1199
1302
  return problem(404, { code: 'not-found', title: 'There is no such push' })
@@ -1400,7 +1503,8 @@ export function createRemote(options: RemoteOptions): Remote {
1400
1503
  return (
1401
1504
  url.pathname === `${prefix}pushes` ||
1402
1505
  url.pathname === `${prefix}bundles` ||
1403
- url.pathname.startsWith(`${prefix}media/`)
1506
+ url.pathname.startsWith(`${prefix}media/`) ||
1507
+ (mediaLibraryRoutes?.isUpload(url.pathname.slice(prefix.length), request.method) ?? false)
1404
1508
  )
1405
1509
  },
1406
1510
 
@@ -1459,6 +1563,10 @@ export function createRemote(options: RemoteOptions): Remote {
1459
1563
  mayChange(principal) &&
1460
1564
  may(principal, RemotePermissions.ApplyStructure),
1461
1565
  audit: mayReadAudit(principal),
1566
+ backgroundJobs: backgroundJobRoutes.may(principal),
1567
+ extensionActivity: activityRoutes?.may(principal) ?? false,
1568
+ mediaLibrary: mediaLibraryRoutes?.mayMedia(principal) ?? false,
1569
+ contentShow: mediaLibraryRoutes?.mayContent(principal) ?? false,
1462
1570
  },
1463
1571
  },
1464
1572
  ])
@@ -1502,7 +1610,37 @@ export function createRemote(options: RemoteOptions): Remote {
1502
1610
  await request.json().catch(() => undefined),
1503
1611
  )
1504
1612
  }
1613
+ if (what.startsWith('member') || what.startsWith('content/')) {
1614
+ const answered = await memberRoutes.handle(request, url, principal, what)
1615
+ if (answered) return answered
1616
+ }
1617
+ if (what.startsWith('background-jobs')) {
1618
+ const answered = await backgroundJobRoutes.handle(request, url, principal, what)
1619
+ if (answered) return answered
1620
+ }
1621
+ if (what.startsWith('user') || what.startsWith('sign-ins')) {
1622
+ const answered = await userRoutes.handle(request, url, principal, what)
1623
+ if (answered) return answered
1624
+ }
1625
+ if (
1626
+ undo &&
1627
+ (what.startsWith('content/') || what === 'recycle-bin' || what.startsWith('recycle-bin/'))
1628
+ ) {
1629
+ const answered = await undo.handle(request, url, principal, what)
1630
+ if (answered) return answered
1631
+ }
1632
+ if (
1633
+ mediaLibraryRoutes &&
1634
+ (what.startsWith('media-items') || what.startsWith('content-items/'))
1635
+ ) {
1636
+ const answered = await mediaLibraryRoutes.handle(request, url, principal, what)
1637
+ if (answered) return answered
1638
+ }
1505
1639
  if (what === 'restart' && request.method === 'POST') return restartSite(request, principal)
1640
+ if (activityRoutes && what.startsWith('installed/')) {
1641
+ const answered = await activityRoutes.handle(request, url, principal, what)
1642
+ if (answered) return answered
1643
+ }
1506
1644
  if (what === 'installed' || what.startsWith('installed/'))
1507
1645
  return manageBundles(request, principal, what)
1508
1646
  // Story 167: the site's level first, then the person's permissions.