@crombolo/server 0.25.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.25.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,18 +30,18 @@
30
30
  "access": "public"
31
31
  },
32
32
  "dependencies": {
33
- "@crombolo/api-delivery": "0.25.0",
34
- "@crombolo/api-management": "0.25.0",
35
- "@crombolo/assistant": "0.25.0",
36
- "@crombolo/auth": "0.25.0",
37
- "@crombolo/backoffice-host": "0.25.0",
38
- "@crombolo/content": "0.25.0",
39
- "@crombolo/contracts": "0.25.0",
40
- "@crombolo/core": "0.25.0",
41
- "@crombolo/data": "0.25.0",
42
- "@crombolo/render": "0.25.0",
43
- "@crombolo/schema": "0.25.0",
44
- "@crombolo/transfer": "0.25.0",
45
- "@logtape/logtape": "^2.3.8"
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
+ "@logtape/logtape": "^2.3.8",
45
+ "jose": "^6.2.12"
46
46
  }
47
47
  }
@@ -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
@@ -12,10 +12,10 @@ import {
12
12
  type RedirectRule,
13
13
  type SnapshotLimits,
14
14
  } from '@crombolo/render'
15
- import type { AssistantConfig } from './assistant.ts'
16
15
  import type { ServerBundle } from './bundles.ts'
17
16
  import type { EmailPort } from './email.ts'
18
17
  import type { GitConfig } from './git-routes.ts'
18
+ import { checkHost, type HostConfig } from './host-token.ts'
19
19
  import { checkIdentityProviders, type IdentityProvider } from './identity-providers.ts'
20
20
  import type { MediaStore } from './media-store.ts'
21
21
  import type { SchemaStore } from './schema-store.ts'
@@ -380,6 +380,13 @@ export interface CromboloConfig {
380
380
  * (`bundles.ts`, `docs/bundles.md`).
381
381
  */
382
382
  bundles: ServerBundle[]
383
+ /**
384
+ * Package names this installation provides to every site it runs, rather
385
+ * than the site choosing them (story 177): a whole-site file leaves them out
386
+ * of what it requires, so the site starts anywhere without them. Set by
387
+ * whoever runs the installation, in code only, as `bundles` is.
388
+ */
389
+ hostProvided: readonly string[]
383
390
  /**
384
391
  * Whether installing a bundle from the Marketplace also applies the content it
385
392
  * carries — its schema, components and content — straight after `bun add`. On
@@ -414,12 +421,11 @@ export interface CromboloConfig {
414
421
  */
415
422
  git: GitConfig | undefined
416
423
  /**
417
- * The AI helper in the backoffice. Absent means the feature does not exist: no
418
- * route, no tools, no model client, and nothing in the backoffice. When it is
419
- * configured the assistant can read the CMS and propose changes, and a person
420
- * approves each one — it cannot write, and it cannot publish.
424
+ * The host this installation's back office vouches for its user to (story
425
+ * 178): its origin, the key that signs host tokens, and that key's id. From
426
+ * `crombolo.config.ts` only; without it no token is issued.
421
427
  */
422
- assistant: AssistantConfig | undefined
428
+ host: HostConfig | undefined
423
429
  }
424
430
 
425
431
  export type SiteConfig = CromboloConfig
@@ -688,11 +694,13 @@ export function loadConfig(
688
694
  }),
689
695
  // No environment variable: a bundle is an import, which is code.
690
696
  bundles: [],
697
+ // Nor here: it is the installation's decision about that code.
698
+ hostProvided: [],
691
699
  marketplaceUrl: setting('CROMBOLO_MARKETPLACE_URL') ?? DEFAULTS.marketplaceUrl,
692
700
  packageKeyword: setting('CROMBOLO_PACKAGE_KEYWORD') ?? DEFAULTS.packageKeyword,
693
701
  npmRegistry: setting('CROMBOLO_NPM_REGISTRY') ?? DEFAULTS.npmRegistry,
694
- // No environment variable: enabling it takes a provider, which is code.
695
- assistant: undefined,
702
+ // Nor here: a host reads its own variables inside `defineConfig`, if it wants them.
703
+ host: undefined,
696
704
  }
697
705
  const merged: CromboloConfig = { ...fromEnv, ...stripUndefined(overrides) }
698
706
  checkIdentityProviders(merged.memberIdentityProviders, 'member')
@@ -701,6 +709,13 @@ export function loadConfig(
701
709
  merged.seo = { ...fromEnv.seo, ...stripUndefined(overrides.seo ?? {}) }
702
710
  merged.remote = { ...fromEnv.remote, ...stripUndefined(overrides.remote ?? {}) }
703
711
  checkApiClient(merged.apiClient)
712
+ checkHost(merged.host)
713
+ // The key itself is refused, so a config left over from before says so rather
714
+ // than starting without the feature it asked for.
715
+ if ('assistant' in overrides)
716
+ throw new Error(
717
+ "The AI assistant was removed from crombolo in 0.26 (story 179), so 'assistant' is no longer a setting. See the 0.26 release notes, and 'Tools a host provides' in docs/bundles.md for how a host offers such a tool now.",
718
+ )
704
719
  if (!/^[a-z][a-z0-9-]{0,62}$/.test(merged.remote.environment))
705
720
  throw new Error(
706
721
  `remote.environment "${merged.remote.environment}" must be lower case letters, digits and dashes.`,
@@ -798,7 +813,7 @@ export function describeDatabase(
798
813
  }
799
814
  }
800
815
 
801
- export const VERSION = '0.25.0'
816
+ export const VERSION = '0.27.0'
802
817
 
803
818
  /** A whole number of seconds from the environment; undefined when unset or not one. */
804
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
+ }
@@ -0,0 +1,69 @@
1
+ /**
2
+ * A host token (story 178): the back office's signed statement, for a service
3
+ * the host runs elsewhere, of who is signed in. Short-lived, addressed to the
4
+ * one host origin configured, and signed with a key the host holds.
5
+ * docs/bundles.md, "Tools a host provides".
6
+ */
7
+ import { SignJWT } from 'jose'
8
+
9
+ /** The installation's host, from `crombolo.config.ts` only. */
10
+ export interface HostConfig {
11
+ /** The host service's origin, which every token is addressed to. */
12
+ origin: string
13
+ /** The HS256 key, at least 32 bytes; it both signs and verifies. */
14
+ signingKey: string
15
+ /** Names the key in each token's header, for a host running many installations. */
16
+ keyId: string
17
+ }
18
+
19
+ /** How long a token lasts, in seconds. */
20
+ export const HOST_TOKEN_SECONDS = 300
21
+
22
+ /** Refuses a `host` that could not be used, naming the field. */
23
+ export function checkHost(host: HostConfig | undefined): void {
24
+ if (!host) return
25
+ let url: URL | undefined
26
+ try {
27
+ url = new URL(host.origin)
28
+ } catch {
29
+ url = undefined
30
+ }
31
+ const local = url?.protocol === 'http:' && ['localhost', '127.0.0.1'].includes(url.hostname)
32
+ if (!url || (url.protocol !== 'https:' && !local) || url.origin !== host.origin)
33
+ throw new Error(
34
+ `host.origin "${host.origin}" must be an https origin with no path, such as https://tools.example.com.`,
35
+ )
36
+ if (new TextEncoder().encode(host.signingKey ?? '').length < 32)
37
+ throw new Error('host.signingKey must be at least 32 bytes.')
38
+ if (typeof host.keyId !== 'string' || host.keyId.trim() === '')
39
+ throw new Error('host.keyId must name the key.')
40
+ }
41
+
42
+ /** Who the token is about, and which site says so. */
43
+ export interface HostTokenSubject {
44
+ user: { key: string; name: string }
45
+ groups: readonly string[]
46
+ sections: readonly string[]
47
+ site: { name: string; nodeId: string; url?: string }
48
+ }
49
+
50
+ export async function issueHostToken(
51
+ host: HostConfig,
52
+ subject: HostTokenSubject,
53
+ now = new Date(),
54
+ ): Promise<string> {
55
+ const issuedAt = Math.floor(now.getTime() / 1000)
56
+ const token = new SignJWT({
57
+ name: subject.user.name,
58
+ groups: [...subject.groups],
59
+ sections: [...subject.sections],
60
+ site: { name: subject.site.name, nodeId: subject.site.nodeId },
61
+ })
62
+ .setProtectedHeader({ alg: 'HS256', kid: host.keyId, typ: 'JWT' })
63
+ .setSubject(subject.user.key)
64
+ .setAudience(host.origin)
65
+ .setIssuedAt(issuedAt)
66
+ .setExpirationTime(issuedAt + HOST_TOKEN_SECONDS)
67
+ if (subject.site.url) token.setIssuer(subject.site.url)
68
+ return token.sign(new TextEncoder().encode(host.signingKey))
69
+ }
package/src/index.ts CHANGED
@@ -53,6 +53,7 @@ export * from './forms.ts'
53
53
  export * from './git.ts'
54
54
  export * from './git-github.ts'
55
55
  export * from './git-routes.ts'
56
+ export * from './host-token.ts'
56
57
  export * from './identity-provider-overrides.ts'
57
58
  export * from './identity-providers.ts'
58
59
  export * from './imaging.ts'