@crombolo/server 0.26.0 → 0.27.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/server",
3
- "version": "0.26.0",
3
+ "version": "0.27.0",
4
4
  "description": "The crombolo HTTP server: routing, configuration, media stores and background jobs.",
5
5
  "license": "MIT",
6
6
  "author": "Crombolo",
@@ -30,17 +30,17 @@
30
30
  "access": "public"
31
31
  },
32
32
  "dependencies": {
33
- "@crombolo/api-delivery": "0.26.0",
34
- "@crombolo/api-management": "0.26.0",
35
- "@crombolo/auth": "0.26.0",
36
- "@crombolo/backoffice-host": "0.26.0",
37
- "@crombolo/content": "0.26.0",
38
- "@crombolo/contracts": "0.26.0",
39
- "@crombolo/core": "0.26.0",
40
- "@crombolo/data": "0.26.0",
41
- "@crombolo/render": "0.26.0",
42
- "@crombolo/schema": "0.26.0",
43
- "@crombolo/transfer": "0.26.0",
33
+ "@crombolo/api-delivery": "0.27.0",
34
+ "@crombolo/api-management": "0.27.0",
35
+ "@crombolo/auth": "0.27.0",
36
+ "@crombolo/backoffice-host": "0.27.0",
37
+ "@crombolo/content": "0.27.0",
38
+ "@crombolo/contracts": "0.27.0",
39
+ "@crombolo/core": "0.27.0",
40
+ "@crombolo/data": "0.27.0",
41
+ "@crombolo/render": "0.27.0",
42
+ "@crombolo/schema": "0.27.0",
43
+ "@crombolo/transfer": "0.27.0",
44
44
  "@logtape/logtape": "^2.3.8",
45
45
  "jose": "^6.2.12"
46
46
  }
@@ -6,9 +6,11 @@ import type { AuditHistoryPort, AuditSink } from '@crombolo/api-management'
6
6
  import {
7
7
  AUDIT_CATEGORIES,
8
8
  type AuditCategory,
9
- type AuditEntry,
9
+ type AuditCursor,
10
10
  type AuditEntryInput,
11
+ type AuditFilter,
11
12
  AuditLog,
13
+ auditRecord,
12
14
  type Db,
13
15
  } from '@crombolo/data'
14
16
  import { logger } from '../logging.ts'
@@ -74,20 +76,44 @@ export function createAuditHistory(db: Db, retentionDays: number): AuditHistoryP
74
76
  }
75
77
  }
76
78
 
77
- function toResponse(entry: AuditEntry) {
79
+ /**
80
+ * A page of the log as the remote protocol asks for it (story 156):
81
+ * `before` or `after`, `limit` (1–500, default 100), and the filters `since`,
82
+ * `until`, `user`, `category`, `action` and `entity`. Answers the reason when
83
+ * the query is not one.
84
+ */
85
+ export function readAuditPageQuery(
86
+ search: URLSearchParams,
87
+ ): { filter: AuditFilter; cursor: AuditCursor } | string {
88
+ const limit = Number(search.get('limit') ?? 100)
89
+ if (!Number.isInteger(limit) || limit < 1 || limit > 500)
90
+ return 'limit must be between 1 and 500.'
91
+ const id = (name: string) => {
92
+ const raw = search.get(name)
93
+ if (raw === null) return undefined
94
+ const value = Number(raw)
95
+ return Number.isInteger(value) && value >= 0 ? value : null
96
+ }
97
+ const before = id('before')
98
+ const after = id('after')
99
+ if (before === null || after === null) return 'before and after must be entry ids.'
100
+ if (before !== undefined && after !== undefined) return 'Give before or after, not both.'
101
+ const category = search.get('category') ?? undefined
102
+ if (category && !AUDIT_CATEGORIES.includes(category as AuditCategory))
103
+ return `There is no category "${category}".`
104
+ const since = dateParam(search.get('since'))
105
+ const until = dateParam(search.get('until'))
106
+ if (since === null || until === null) return 'since and until must be dates.'
78
107
  return {
79
- id: entry.id,
80
- occurredAt: entry.occurredAt.toISOString(),
81
- category: entry.category,
82
- action: entry.action,
83
- source: entry.source,
84
- user: entry.userKey || entry.userName ? { key: entry.userKey, name: entry.userName } : null,
85
- item: entry.entityType
86
- ? { type: entry.entityType, key: entry.entityKey, name: entry.entityName }
87
- : null,
88
- ipAddress: entry.ipAddress,
89
- forwardedFor: entry.forwardedFor,
90
- detail: entry.detail,
108
+ filter: {
109
+ user: search.get('user') ?? undefined,
110
+ entityKey: search.get('entity') ?? undefined,
111
+ category: category as AuditCategory | undefined,
112
+ action: search.get('action') ?? undefined,
113
+ since,
114
+ until,
115
+ },
116
+ cursor: { before, after, limit },
91
117
  }
92
118
  }
93
119
 
@@ -140,7 +166,7 @@ export function createAuditHost(db: Db, retentionDays: number) {
140
166
  return Response.json({
141
167
  total: result.total,
142
168
  retentionDays,
143
- items: result.items.map(toResponse),
169
+ items: result.items.map(auditRecord),
144
170
  })
145
171
  },
146
172
  }
@@ -1,122 +1,34 @@
1
1
  /**
2
2
  * The Media section: items stored as documents of the media object type (the
3
3
  * repository takes a kind), never published. An item's file is the path its
4
- * `umbracoFile` holds, served from the media root; deleting an item for good
5
- * deletes its file too.
4
+ * `umbracoFile` holds, served from the media root.
6
5
  */
7
- import type { MediaPort, Principal } from '@crombolo/api-management'
6
+ import type { MediaPort } from '@crombolo/api-management'
8
7
  import {
9
8
  type ContentTypeAggregate,
10
9
  DEFAULT_UPLOAD_SETTINGS,
11
10
  type DocumentAggregate,
12
11
  IMAGE_CROPPER_EDITOR_ALIAS,
12
+ mediaFileOf,
13
13
  normaliseUuid,
14
14
  ObjectTypes,
15
15
  } from '@crombolo/core'
16
16
  import {
17
- appendCacheInstruction,
18
- ContentEventRepository,
19
17
  ContentTypeRepository,
20
18
  DataTypeRepository,
21
19
  type Db,
22
20
  DocumentRepository,
23
- InvalidParentError,
24
21
  type NodeRow,
25
22
  type NodeSchemaState,
26
23
  type ValueIntake,
27
- WriteRejectedError,
28
24
  } from '@crombolo/data'
29
- import { TemporaryFileMissingError } from '../file-intake.ts'
30
- import type { MediaFileStore } from '../media-files.ts'
31
- import type { WebhookService } from '../webhooks.ts'
32
-
33
- /** The file path an item's `umbracoFile` holds, whether an upload or a cropper value. */
34
- export function mediaFileOf(media: DocumentAggregate): string | null {
35
- const value = media.values.find((v) => v.alias === 'umbracoFile')?.value
36
- if (typeof value === 'string') return value || null
37
- const src = (value as { src?: unknown } | null | undefined)?.src
38
- return typeof src === 'string' && src ? src : null
39
- }
40
25
 
26
+ /** The Media section's reads; its writes go through the media operations (story 165). */
41
27
  export function createMediaPort(
42
28
  db: Db,
43
- files: MediaFileStore,
44
- options: {
45
- nodeState?: NodeSchemaState
46
- nodeId?: string
47
- valueIntake?: ValueIntake
48
- /** Told after every change, so pages that show media refresh. */
49
- onChange?: () => void | Promise<void>
50
- /** Reads what a `MediaSave` or `MediaDelete` delivery needs, inside the change. */
51
- webhooks?: Pick<WebhookService, 'factsFor'>
52
- /** Told after a commit that left an event in the outbox (story 171). */
53
- nudge?: () => void
54
- } = {},
29
+ options: { nodeState?: NodeSchemaState; nodeId?: string; valueIntake?: ValueIntake } = {},
55
30
  ): MediaPort {
56
- /** Every node is told inside the change's transaction; this node's pages refresh after. */
57
- const instruct = (on: Db) =>
58
- appendCacheInstruction(on, { kind: 'content', payload: { media: true }, by: options.nodeId })
59
- const changed = async () => {
60
- await instruct(db)
61
- await options.onChange?.()
62
- }
63
31
  const repo = new DocumentRepository(db, { ...options, kind: 'media' })
64
-
65
- /**
66
- * Writes a media change, its cache instruction and its webhook event in one
67
- * transaction (story 171), so the event commits with the change or not at all.
68
- */
69
- const commit = async <T>(
70
- write: (tx: DocumentRepository) => Promise<T>,
71
- announce: (result: T) => { alias: string; key: string } | undefined,
72
- principal?: Principal,
73
- ): Promise<T> => {
74
- let recorded = false
75
- const result = await repo.atomically(async (tx, txDb) => {
76
- const written = await write(tx)
77
- const event = announce(written)
78
- if (!event) return written
79
- await instruct(txDb)
80
- const webhook = await options.webhooks?.factsFor(txDb, event)
81
- if (webhook) {
82
- await new ContentEventRepository(txDb).record({
83
- kind: event.alias === 'Umbraco.MediaDelete' ? 'mediaDeleted' : 'mediaSaved',
84
- entityType: 'Media',
85
- entityKey: event.key,
86
- facts: { v: 1, webhook },
87
- actor: principal
88
- ? { kind: 'user', name: principal.name, userKey: principal.id }
89
- : { kind: 'system', name: 'The site', userKey: null },
90
- })
91
- recorded = true
92
- }
93
- return written
94
- })
95
- if (announce(result)) await options.onChange?.()
96
- if (recorded) options.nudge?.()
97
- return result
98
- }
99
-
100
- const userIdOf = async (principal: Principal): Promise<number | undefined> => {
101
- const rows = await db.query<{ id: number }>('SELECT id FROM user_account WHERE key = ?', [
102
- principal.id,
103
- ])
104
- return rows[0] ? Number(rows[0].id) : undefined
105
- }
106
- const failure = (error: unknown) => {
107
- if (error instanceof WriteRejectedError)
108
- return { ok: false as const, reason: error.message, status: 409 }
109
- if (error instanceof InvalidParentError)
110
- return { ok: false as const, reason: error.message, status: 400 }
111
- if (error instanceof TemporaryFileMissingError)
112
- return { ok: false as const, reason: error.message, status: 400 }
113
- throw error
114
- }
115
- const notFound = (what = 'The media item could not be found.') => ({
116
- ok: false as const,
117
- reason: what,
118
- status: 404,
119
- })
120
32
  const tree = async (rows: readonly NodeRow[]) => repo.treeItems(rows)
121
33
  const mediaTypes = new ContentTypeRepository(db, { kind: 'media' })
122
34
  const dataTypes = new DataTypeRepository(db)
@@ -153,119 +65,10 @@ export function createMediaPort(
153
65
  .map((e) => e.replace(/^\./, '').toLowerCase())
154
66
  }
155
67
 
156
- /** Every file in a branch, gathered before the branch is deleted. */
157
- const filesIn = async (key: string): Promise<string[]> => {
158
- const root = await repo.nodes.byKey(key)
159
- if (!root) return []
160
- const rows = await db.query<{ unique_id: string }>(
161
- 'SELECT unique_id FROM node WHERE (id = ? OR path LIKE ?) AND node_object_type = ?',
162
- [root.id, `${root.path},%`, ObjectTypes.Media],
163
- )
164
- const found: string[] = []
165
- for (const row of rows) {
166
- const media = await repo.byKey(normaliseUuid(String(row.unique_id)))
167
- const file = media ? mediaFileOf(media) : null
168
- if (file) found.push(file)
169
- }
170
- return found
171
- }
172
- const removeBranch = async (key: string) => {
173
- const paths = await filesIn(key)
174
- const removed = await commit(
175
- (tx) => tx.delete(key),
176
- (done) => (done ? { alias: 'Umbraco.MediaDelete', key } : undefined),
177
- )
178
- // The files go once the rows have: a failed delete leaves both.
179
- if (removed) for (const path of paths) await files.remove(path)
180
- return removed
181
- }
182
-
183
68
  return {
184
69
  byKey: (key) => repo.byKey(key),
185
70
  validate: (input) => repo.validate(input, null),
186
71
 
187
- async create(input, principal) {
188
- try {
189
- const userId = await userIdOf(principal)
190
- const created = await commit(
191
- (tx) => tx.create({ ...input, componentKey: null, userId }),
192
- (doc) => ({ alias: 'Umbraco.MediaSave', key: doc.key }),
193
- principal,
194
- )
195
- return { ok: true as const, key: created.key }
196
- } catch (error) {
197
- return failure(error)
198
- }
199
- },
200
-
201
- async update(key, input, principal) {
202
- try {
203
- const before = await repo.byKey(key)
204
- const userId = await userIdOf(principal)
205
- const updated = await commit(
206
- (tx) => tx.update({ ...input, key, componentKey: null, userId }),
207
- (doc) => (doc ? { alias: 'Umbraco.MediaSave', key } : undefined),
208
- principal,
209
- )
210
- if (!updated) return notFound()
211
- // A replaced file is no longer anyone's: Umbraco deletes it too.
212
- const was = before ? mediaFileOf(before) : null
213
- if (was && was !== mediaFileOf(updated)) await files.remove(was)
214
- return { ok: true as const }
215
- } catch (error) {
216
- return failure(error)
217
- }
218
- },
219
-
220
- remove: removeBranch,
221
- async moveToRecycleBin(key) {
222
- const moved = await repo.moveToRecycleBin(key)
223
- if (moved) await changed()
224
- return moved
225
- },
226
-
227
- async move(key, targetKey) {
228
- const result = await repo.move(key, targetKey)
229
- if (result === 'moved') {
230
- await changed()
231
- return { ok: true as const }
232
- }
233
- return result === 'notFound'
234
- ? notFound('The media item or target could not be found.')
235
- : { ok: false as const, reason: 'A media item cannot move below itself.', status: 400 }
236
- },
237
-
238
- async sort(parentKey, sorting) {
239
- return (await repo.sort(parentKey, sorting)) === 'sorted'
240
- ? { ok: true as const }
241
- : notFound('The parent, or one of the items, could not be found under it.')
242
- },
243
-
244
- async sortChildrenBy(parentKey, field, direction) {
245
- return (await repo.sortChildrenBy(parentKey, field, direction)) === 'sorted'
246
- ? { ok: true as const }
247
- : notFound()
248
- },
249
-
250
- async restore(key, targetKey) {
251
- const result = await repo.restore(key, targetKey)
252
- if (result === 'restored') {
253
- await changed()
254
- return { ok: true as const }
255
- }
256
- return result === 'notFound'
257
- ? notFound('The media item is not in the recycle bin.')
258
- : {
259
- ok: false as const,
260
- reason: 'The restore target does not exist or is in the recycle bin.',
261
- status: 400,
262
- }
263
- },
264
-
265
- async emptyRecycleBin() {
266
- for (const node of await repo.trashedRoots()) await removeBranch(node.key)
267
- },
268
-
269
72
  originalParent: (key) => repo.originalParent(key),
270
73
  versions: (key) => repo.versions(key),
271
74
  async systemUserKey() {
package/src/config.ts CHANGED
@@ -813,7 +813,7 @@ export function describeDatabase(
813
813
  }
814
814
  }
815
815
 
816
- export const VERSION = '0.26.0'
816
+ export const VERSION = '0.27.0'
817
817
 
818
818
  /** A whole number of seconds from the environment; undefined when unset or not one. */
819
819
  function numberSetting(name: Parameters<typeof setting>[0]): number | undefined {
@@ -14,6 +14,9 @@ import {
14
14
  type DocumentEvent,
15
15
  type EventSink,
16
16
  liveEventsFor,
17
+ type MediaEventSink,
18
+ mediaAuditEntryFor,
19
+ mediaWebhookFor,
17
20
  notificationFor,
18
21
  webhookFor,
19
22
  } from '@crombolo/content'
@@ -87,3 +90,45 @@ export function createContentEventSink(options: ContentEventSinkOptions): EventS
87
90
  },
88
91
  }
89
92
  }
93
+
94
+ /**
95
+ * Where media operations record what they did (story 165): the audit entry and,
96
+ * for a save or a delete, the webhook event, in the change's own transaction.
97
+ */
98
+ export function createMediaEventSink(options: {
99
+ webhooks?: Pick<WebhookService, 'factsFor'>
100
+ nudge?(): void
101
+ }): MediaEventSink {
102
+ return {
103
+ async record(tx: Db, event, actor) {
104
+ const entry = mediaAuditEntryFor(event, actor)
105
+ const audit = new AuditLog(tx)
106
+ const subject =
107
+ event.type === 'deleted'
108
+ ? { entityType: entry.entityType, entityKey: event.key, entityName: event.name }
109
+ : entry.entityKey
110
+ ? await audit.describe(entry.entityType, entry.entityKey)
111
+ : undefined
112
+ await audit.record({
113
+ ...entry,
114
+ entityType: subject?.entityType ?? entry.entityType,
115
+ entityKey: subject?.entityKey ?? entry.entityKey,
116
+ entityName: subject?.entityName ?? null,
117
+ })
118
+ const hook = mediaWebhookFor(event)
119
+ const webhook =
120
+ hook && options.webhooks ? await options.webhooks.factsFor(tx, hook) : undefined
121
+ if (!webhook || !hook) return
122
+ await new ContentEventRepository(tx).record({
123
+ kind: event.type === 'deleted' ? 'mediaDeleted' : 'mediaSaved',
124
+ entityType: 'Media',
125
+ entityKey: hook.key,
126
+ facts: { v: 1, webhook },
127
+ actor: outboxActor(actor),
128
+ })
129
+ },
130
+ afterCommit(event) {
131
+ if (mediaWebhookFor(event)) options.nudge?.()
132
+ },
133
+ }
134
+ }
@@ -8,8 +8,10 @@
8
8
 
9
9
  import {
10
10
  createDocumentOperations,
11
+ createMediaOperations,
11
12
  type DocumentOperations,
12
13
  type EventSink,
14
+ type MediaOperations,
13
15
  } from '@crombolo/content'
14
16
  import {
15
17
  appendCacheInstruction,
@@ -21,11 +23,12 @@ import { PublishedCache } from '@crombolo/render'
21
23
  import { createPublishedContentSource } from './adapters/documents.ts'
22
24
  import { createApprovals } from './approvals.ts'
23
25
  import type { CromboloConfig } from './config.ts'
24
- import { createContentEventSink } from './content-events.ts'
26
+ import { createContentEventSink, createMediaEventSink } from './content-events.ts'
25
27
  import { createContentNotifier } from './content-notifications.ts'
26
28
  import { writeDomainsFor } from './domains.ts'
27
29
  import { resolveEmailPort } from './email.ts'
28
- import { TemporaryFileMissingError } from './file-intake.ts'
30
+ import { createFileIntake, TemporaryFileMissingError } from './file-intake.ts'
31
+ import { MediaFileStore, mediaStoreFor } from './media-files.ts'
29
32
  import { approvalsGate, backOfficeUrl } from './ports.ts'
30
33
  import { createRedirectTracker } from './redirects.ts'
31
34
  import { createWebhookService } from './webhooks.ts'
@@ -87,9 +90,44 @@ export async function siteDocumentOperations(
87
90
  by: `cli:${config.nodeId}`,
88
91
  }),
89
92
  }),
93
+ // The routes a redirect is tracked from are read from this cache once a change
94
+ // has committed, so the change has to drop it first.
95
+ onChange: () => cache.invalidate(),
90
96
  afterDomains: (node, assignment) => writeDomainsFor(db, config.siteDir, node, assignment),
91
97
  refusalReason: (error) =>
92
98
  error instanceof TemporaryFileMissingError ? error.message : undefined,
93
99
  })
94
100
  return { operations, events }
95
101
  }
102
+
103
+ /**
104
+ * Media operations for a process that is not serving requests (story 165): the
105
+ * same rules, audit entries and webhook events as the server's, with the site's
106
+ * media store for the files a delete removes.
107
+ */
108
+ export async function siteMediaOperations(
109
+ db: Db,
110
+ config: CromboloConfig,
111
+ ): Promise<MediaOperations> {
112
+ const state = await currentSchemaState(db)
113
+ const files = new MediaFileStore(await mediaStoreFor(config))
114
+ const webhooks = createWebhookService({
115
+ db,
116
+ schemaDir: config.schemaDir,
117
+ filesWritable: config.schemaWritable,
118
+ secretKey: config.secretKey,
119
+ bundles: config.bundles,
120
+ })
121
+ return createMediaOperations({
122
+ db,
123
+ repository: {
124
+ nodeState: { version: state.version, revision: state.revision },
125
+ nodeId: config.nodeId,
126
+ valueIntake: createFileIntake(files),
127
+ },
128
+ events: createMediaEventSink({ webhooks }),
129
+ files,
130
+ refusalReason: (error) =>
131
+ error instanceof TemporaryFileMissingError ? error.message : undefined,
132
+ })
133
+ }
package/src/ports.ts CHANGED
@@ -26,6 +26,7 @@ import {
26
26
  type ApprovalsGate,
27
27
  type ContentPrincipal,
28
28
  createDocumentOperations,
29
+ createMediaOperations,
29
30
  type DocumentOperations,
30
31
  type EventSink,
31
32
  SILENT,
@@ -84,6 +85,7 @@ import { createWebhookPort } from './adapters/webhooks.ts'
84
85
  import { type Approvals, createApprovals } from './approvals.ts'
85
86
  import { COMPONENT_SNIPPETS } from './component-snippets.ts'
86
87
  import { type CromboloConfig, type UserLinkSender, VERSION } from './config.ts'
88
+ import { createMediaEventSink } from './content-events.ts'
87
89
  import type { ContentNotifier } from './content-notifications.ts'
88
90
  import { writeDomainsFor } from './domains.ts'
89
91
  import { type EmailPort, resolveEmailPort } from './email.ts'
@@ -574,13 +576,24 @@ export function createDeps(options: DepsOptions): ManagementApiDeps {
574
576
  }
575
577
  deps.userGroups = userPorts.groups
576
578
  deps.userData = userPorts.userData
577
- deps.media = createMediaPort(options.db, mediaFiles, {
579
+ deps.media = createMediaPort(options.db, {
578
580
  nodeState: options.schema?.nodeState,
579
581
  nodeId: options.schema?.nodeId,
580
582
  valueIntake,
583
+ })
584
+ // Every media write, whoever starts it (story 165).
585
+ deps.mediaOperations = createMediaOperations({
586
+ db: options.db,
587
+ repository: {
588
+ nodeState: options.schema?.nodeState,
589
+ nodeId: options.schema?.nodeId,
590
+ valueIntake,
591
+ },
592
+ events: createMediaEventSink({ webhooks: options.webhooks, nudge: options.nudgeEvents }),
593
+ files: mediaFiles,
581
594
  onChange: () => options.cache?.invalidate(),
582
- webhooks: options.webhooks,
583
- nudge: options.nudgeEvents,
595
+ refusalReason: (error) =>
596
+ error instanceof TemporaryFileMissingError ? error.message : undefined,
584
597
  })
585
598
  deps.blueprints = createBlueprintPort(options.db, {
586
599
  nodeState: options.schema?.nodeState,
package/src/remote.ts CHANGED
@@ -15,12 +15,12 @@ import { createWriteStream } from 'node:fs'
15
15
  import { mkdir, rm } from 'node:fs/promises'
16
16
  import { tmpdir } from 'node:os'
17
17
  import { join, sep } from 'node:path'
18
- import type { Principal } from '@crombolo/api-management'
18
+ import { hasSection, type Principal } from '@crombolo/api-management'
19
19
  import { DEVICE_CODE_GRANT, REMOTE_CLIENT_ID } from '@crombolo/auth'
20
20
  import { managementApiPath, RemotePermissions, type RemoteVerb } from '@crombolo/core'
21
- import { type Db, type RemoteJob, RemoteJobRepository } from '@crombolo/data'
21
+ import { AuditLog, auditRecord, type Db, type RemoteJob, RemoteJobRepository } from '@crombolo/data'
22
22
  import type { ContentSet } from '@crombolo/transfer'
23
- import { recordAudit } from './adapters/audit.ts'
23
+ import { readAuditPageQuery, recordAudit } from './adapters/audit.ts'
24
24
  import { installBundleContent } from './bundle-install.ts'
25
25
  import type { CromboloConfig } from './config.ts'
26
26
  import { mediaStoreFor } from './media-files.ts'
@@ -78,6 +78,9 @@ const problem = (status: number, body: Problem) =>
78
78
  const may = (principal: Principal, verb: RemoteVerb) =>
79
79
  principal.isAdmin || principal.permissions.includes(verb)
80
80
 
81
+ /** Who may read the audit log: whoever has its dashboard, in Settings. */
82
+ const mayReadAudit = (principal: Principal) => hasSection(principal, 'settings')
83
+
81
84
  /** A cookie-authenticated write must come from this site; a bearer token is a client's own. */
82
85
  const fromThisSiteOrBearer = (request: Request) => {
83
86
  if (request.headers.get('authorization')?.toLowerCase().startsWith('bearer ')) return true
@@ -131,7 +134,12 @@ export function createRemote(options: RemoteOptions): Remote {
131
134
  clientId: REMOTE_CLIENT_ID,
132
135
  grantType: DEVICE_CODE_GRANT,
133
136
  },
134
- capabilities: ['media-fetch', 'push-check', ...(settings.approvals ? ['approvals'] : [])],
137
+ capabilities: [
138
+ 'media-fetch',
139
+ 'push-check',
140
+ 'audit',
141
+ ...(settings.approvals ? ['approvals'] : []),
142
+ ],
135
143
  environments: [environment()],
136
144
  })
137
145
 
@@ -342,6 +350,22 @@ export function createRemote(options: RemoteOptions): Remote {
342
350
  })
343
351
  : undefined
344
352
 
353
+ /**
354
+ * A page of the audit log (story 156), for whoever may read it in the back
355
+ * office: the Settings section, as the dashboard asks. Reading is not audited.
356
+ */
357
+ async function readAudit(url: URL, principal: Principal): Promise<Response> {
358
+ if (!mayReadAudit(principal))
359
+ return problem(403, { code: 'forbidden', title: 'You may not read the audit log' })
360
+ const query = readAuditPageQuery(url.searchParams)
361
+ if (typeof query === 'string') return problem(400, { code: 'bad-query', title: query })
362
+ const page = await new AuditLog(db).page(query.filter, query.cursor)
363
+ return Response.json(
364
+ { items: page.items.map(auditRecord), next: page.next, truncated: page.truncated },
365
+ { headers: { 'cache-control': 'no-store' } },
366
+ )
367
+ }
368
+
345
369
  async function startPull(request: Request, url: URL, principal: Principal): Promise<Response> {
346
370
  if (!may(principal, RemotePermissions.Pull))
347
371
  return problem(403, { code: 'forbidden', title: 'You may not pull from this environment' })
@@ -718,6 +742,7 @@ export function createRemote(options: RemoteOptions): Remote {
718
742
  push:
719
743
  may(principal, RemotePermissions.Push) &&
720
744
  (!settings.protected || may(principal, RemotePermissions.PushProtected)),
745
+ audit: mayReadAudit(principal),
721
746
  },
722
747
  },
723
748
  ])
@@ -750,6 +775,7 @@ export function createRemote(options: RemoteOptions): Remote {
750
775
  title: `There is no environment "${envId}"`,
751
776
  })
752
777
 
778
+ if (what === 'audit' && request.method === 'GET') return readAudit(url, principal)
753
779
  if (what === 'pulls' && request.method === 'POST') return startPull(request, url, principal)
754
780
  if (what === 'pushes' && request.method === 'PUT') return startPush(request, url, principal)
755
781
  if (what === 'pushes/check' && request.method === 'POST') {