@crombolo/server 0.64.0 → 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.
Files changed (46) hide show
  1. package/package.json +15 -14
  2. package/src/access.ts +6 -2
  3. package/src/adapters/blueprints.ts +19 -5
  4. package/src/adapters/elements.ts +49 -36
  5. package/src/adapters/members.ts +37 -3
  6. package/src/adapters/users.ts +18 -0
  7. package/src/approvals.ts +44 -15
  8. package/src/atomic-write.ts +2 -2
  9. package/src/background-jobs.ts +170 -0
  10. package/src/bundle-admin.ts +39 -3
  11. package/src/bundle-reload.ts +2 -1
  12. package/src/bundles.ts +60 -25
  13. package/src/cli-tokens-api.ts +152 -0
  14. package/src/config.ts +52 -3
  15. package/src/content-events.ts +22 -0
  16. package/src/content-operations.ts +26 -1
  17. package/src/core.ts +357 -133
  18. package/src/extension-activity.ts +121 -0
  19. package/src/extension-components.ts +20 -4
  20. package/src/extension-discovery.ts +84 -65
  21. package/src/grant-trust.ts +6 -4
  22. package/src/index.ts +14 -0
  23. package/src/media-access.ts +30 -125
  24. package/src/media-library.ts +953 -0
  25. package/src/member-admin.ts +761 -0
  26. package/src/node-operations.ts +19 -2
  27. package/src/ports.ts +2 -0
  28. package/src/principal.ts +35 -0
  29. package/src/remote-background-jobs.ts +99 -0
  30. package/src/remote-credentials.ts +114 -6
  31. package/src/remote-extension-activity.ts +66 -0
  32. package/src/remote-media-library.ts +297 -0
  33. package/src/remote-media.ts +2 -2
  34. package/src/remote-members.ts +271 -0
  35. package/src/remote-undo.ts +234 -0
  36. package/src/remote-users.ts +229 -0
  37. package/src/remote.ts +141 -3
  38. package/src/routes.ts +22 -3
  39. package/src/seed/values.ts +82 -4
  40. package/src/seo.ts +81 -61
  41. package/src/server.ts +153 -92
  42. package/src/settings.ts +95 -6
  43. package/src/trusted-signers-admin.ts +39 -3
  44. package/src/undo.ts +358 -0
  45. package/src/user-admin.ts +581 -0
  46. package/src/view-as.ts +95 -0
@@ -5,14 +5,17 @@
5
5
  * person, in one minute, fold into one row. A crash loses at most a second of
6
6
  * activity; the audit log still has every write the API made.
7
7
  */
8
+ import { normaliseUuid } from '@crombolo/core'
8
9
  import {
9
10
  ACTIVITY_KINDS,
11
+ type ActivityEntry,
10
12
  type ActivityFilter,
11
13
  type ActivityInput,
12
14
  type ActivityKind,
13
15
  type ActivityOutcome,
14
16
  type Db,
15
17
  ExtensionActivityLog,
18
+ UserRepository,
16
19
  } from '@crombolo/data'
17
20
  import type { BundleCaller } from './bundles.ts'
18
21
  import { logger } from './logging.ts'
@@ -235,3 +238,121 @@ export async function activityCsv(
235
238
  }
236
239
  return `${lines.join('\n')}\n`
237
240
  }
241
+
242
+ /** What an extension's activity is read for: how to flush what is not yet written, and the counts' window. */
243
+ export interface ActivitySource {
244
+ flush?(): Promise<void>
245
+ days: number
246
+ }
247
+
248
+ export type ActivityPart = 'page' | 'summary' | 'csv'
249
+
250
+ export interface ActivitySummary {
251
+ counts: Record<ActivityKind, number>
252
+ people: Array<{ key: string; name: string }>
253
+ days: number
254
+ }
255
+
256
+ export type ActivityAnswer =
257
+ | { part: 'page'; page: { items: ActivityEntry[]; next: number | null } }
258
+ | { part: 'summary'; summary: ActivitySummary }
259
+ | { part: 'csv'; csv: string }
260
+
261
+ /** Why an activity query was not answered, with the status it is answered with. */
262
+ export class ActivityQueryError extends Error {
263
+ constructor(
264
+ message: string,
265
+ readonly status: 400 | 404,
266
+ ) {
267
+ super(message)
268
+ }
269
+ }
270
+
271
+ const ACTIVITY_PATH = /^installed\/([a-z0-9][a-z0-9-]*)\/activity(\/summary|\.csv)?$/
272
+
273
+ /** The extension and the part a path such as `installed/crm/activity.csv` asks for. */
274
+ export function activityPath(path: string): { id: string; part: ActivityPart } | undefined {
275
+ const found = ACTIVITY_PATH.exec(path)
276
+ if (!found) return undefined
277
+ const part = found[2] === '/summary' ? 'summary' : found[2] === '.csv' ? 'csv' : 'page'
278
+ return { id: found[1] as string, part }
279
+ }
280
+
281
+ const UUID = /^[0-9a-f]{8}-?[0-9a-f]{4}-?[0-9a-f]{4}-?[0-9a-f]{4}-?[0-9a-f]{12}$/i
282
+
283
+ /** A person's key, from a key, `itself`, an e-mail or a login. */
284
+ async function personKey(db: Db, who: string): Promise<string> {
285
+ const asked = who.trim()
286
+ if (asked === 'itself') return asked
287
+ if (UUID.test(asked)) return normaliseUuid(asked)
288
+ const users = new UserRepository(db)
289
+ const lower = asked.toLowerCase()
290
+ const found =
291
+ (await users.byEmail(asked)) ??
292
+ (await users.byUserName(asked)) ??
293
+ (await users.all()).find(
294
+ (user) => user.email.toLowerCase() === lower || user.userName.toLowerCase() === lower,
295
+ )
296
+ if (!found) throw new ActivityQueryError(`There is no user "${asked}".`, 404)
297
+ return found.key
298
+ }
299
+
300
+ /**
301
+ * One extension's activity as Installed's Activity view, the remote protocol and
302
+ * the command line read it: a page, the summary, or the CSV file. What the
303
+ * recorder holds is written first.
304
+ */
305
+ export async function readActivity(
306
+ db: Db,
307
+ source: ActivitySource,
308
+ id: string,
309
+ part: ActivityPart,
310
+ search: URLSearchParams,
311
+ ): Promise<ActivityAnswer> {
312
+ const read = readActivityQuery(search)
313
+ if (typeof read === 'string') throw new ActivityQueryError(read, 400)
314
+ if (read.filter.person) read.filter.person = await personKey(db, read.filter.person)
315
+ await source.flush?.()
316
+ const store = new ExtensionActivityLog(db)
317
+ if (part === 'summary')
318
+ return {
319
+ part,
320
+ summary: {
321
+ counts: await store.counts(id, new Date(Date.now() - source.days * 86_400_000)),
322
+ people: await store.people(id),
323
+ days: source.days,
324
+ },
325
+ }
326
+ if (part === 'csv') return { part, csv: await activityCsv(store, id, read.filter) }
327
+ return { part, page: await store.page(id, read.filter, read.cursor) }
328
+ }
329
+
330
+ /** {@link readActivity} as a response; `refuse` words a query that was not one. */
331
+ export async function answerActivity(
332
+ db: Db,
333
+ source: ActivitySource,
334
+ id: string,
335
+ part: ActivityPart,
336
+ search: URLSearchParams,
337
+ refuse: (status: number, message: string) => Response = (status, detail) =>
338
+ Response.json(
339
+ { title: status === 404 ? 'Not found' : 'Invalid request', status, detail },
340
+ { status },
341
+ ),
342
+ ): Promise<Response> {
343
+ try {
344
+ const answer = await readActivity(db, source, id, part, search)
345
+ if (answer.part === 'summary') return Response.json(answer.summary)
346
+ if (answer.part === 'csv')
347
+ return new Response(answer.csv, {
348
+ headers: {
349
+ 'content-type': 'text/csv; charset=utf-8',
350
+ 'content-disposition': `attachment; filename="${id}-activity.csv"`,
351
+ },
352
+ })
353
+ return Response.json(answer.page)
354
+ } catch (error) {
355
+ if (error instanceof ActivityQueryError) return refuse(error.status, error.message)
356
+ throw error
357
+ }
358
+ }
@@ -32,6 +32,9 @@ export interface ExtensionComponents {
32
32
  layouts(): { id: string; layout: string }[]
33
33
  /** Every component the extensions offer, as `<id>/<name>` with the extension's name: for the template picker. */
34
34
  listed(): { alias: string; extension: string }[]
35
+ /** An extension started while the site runs (story 346), in place of one with its id. */
36
+ add(source: ExtensionComponentSource): void
37
+ remove(id: string): void
35
38
  }
36
39
 
37
40
  const BLOCKS = 'blocks/'
@@ -70,7 +73,8 @@ export function createExtensionComponents(
70
73
  sources: readonly ExtensionComponentSource[],
71
74
  options: { timeoutMs?: number } = {},
72
75
  ): ExtensionComponents {
73
- const byId = new Map(sources.map((source) => [source.process.id, source]))
76
+ const live = [...sources]
77
+ const byId = new Map(live.map((source) => [source.process.id, source]))
74
78
  const warned = new Set<string>()
75
79
  /** Components whose removals were logged this boot, by extension and name. */
76
80
  const stripped = new Set<string>()
@@ -138,13 +142,19 @@ export function createExtensionComponents(
138
142
  source.process.description?.components?.find((component) => component.name === name)?.layout,
139
143
  })
140
144
 
145
+ const remove = (id: string) => {
146
+ const at = live.findIndex((source) => source.process.id === id)
147
+ if (at >= 0) live.splice(at, 1)
148
+ byId.delete(id)
149
+ }
150
+
141
151
  return {
142
152
  module(alias) {
143
153
  // A block's component is found by its element type's alias, in whichever
144
154
  // extension offers it.
145
155
  if (alias.startsWith(BLOCKS)) {
146
156
  const name = alias
147
- const source = sources.find((candidate) => offers(candidate, name))
157
+ const source = live.find((candidate) => offers(candidate, name))
148
158
  return source ? moduleFor(source, name) : undefined
149
159
  }
150
160
  const slash = alias.indexOf('/')
@@ -154,13 +164,13 @@ export function createExtensionComponents(
154
164
  return source && offers(source, name) ? moduleFor(source, name) : undefined
155
165
  },
156
166
  layouts() {
157
- return sources.flatMap((source) => {
167
+ return live.flatMap((source) => {
158
168
  const layout = source.layout()
159
169
  return layout ? [{ id: source.process.id, layout }] : []
160
170
  })
161
171
  },
162
172
  listed() {
163
- return sources.flatMap((source) =>
173
+ return live.flatMap((source) =>
164
174
  (source.process.description?.components ?? [])
165
175
  .filter((component) => !component.name.startsWith(BLOCKS))
166
176
  .map((component) => ({
@@ -169,5 +179,11 @@ export function createExtensionComponents(
169
179
  })),
170
180
  )
171
181
  },
182
+ add(source) {
183
+ remove(source.process.id)
184
+ live.push(source)
185
+ byId.set(source.process.id, source)
186
+ },
187
+ remove,
172
188
  }
173
189
  }
@@ -1,10 +1,11 @@
1
1
  /**
2
2
  * Installed extensions run once granted, with nothing imported by the site
3
- * (story 310), each in a Deno process of its own (story 311). At boot, each
4
- * dependency with a server half that the config's `extensions` entry grants,
5
- * or that a recorded grant covers, is built, started with its settings, and
6
- * mounted from what it describes. One that cannot start is left off, and the
7
- * site starts without it. docs/bundles.md, "Extensions run once granted".
3
+ * (story 310), each in a Deno process of its own (story 311). At boot, and as
4
+ * it is granted while the site runs (story 346), each dependency with a server
5
+ * half that the config's `extensions` entry grants, or that a recorded grant
6
+ * covers, is built, started with its settings, and mounted from what it
7
+ * describes. One that cannot start is left off, and the site runs without it.
8
+ * docs/bundles.md, "Extensions run once granted".
8
9
  */
9
10
  import { join } from 'node:path'
10
11
  import type { BundlePackage } from '@crombolo/backoffice-host'
@@ -125,6 +126,75 @@ export interface FailedExtension {
125
126
  reason: string
126
127
  }
127
128
 
129
+ /** How starting one extension went: running, refused or broken, or not granted. */
130
+ export type ExtensionStart =
131
+ | { status: 'started'; bundle: ServerBundle; process: ExtensionProcess }
132
+ | { status: 'failed'; reason: string }
133
+ | { status: 'not-granted' }
134
+
135
+ /**
136
+ * Starts one installed server half, at boot or while the site runs (story 346):
137
+ * when the config's entry or its recorded grant covers it, built, started with
138
+ * its settings, checked that it can run apart, and given its stand-in.
139
+ */
140
+ export async function startExtension(
141
+ config: CromboloConfig,
142
+ pkg: BundlePackage,
143
+ recorded: { grant?: BundleGrant; settings?: Record<string, unknown> },
144
+ log: BundleLog,
145
+ activity?: ActivityRecorder,
146
+ ): Promise<ExtensionStart> {
147
+ // Story 326: an extension runs from a root of its own, never as a dependency of the site.
148
+ const refused =
149
+ pkg.linked && Bun.env.NODE_ENV === 'production'
150
+ ? LINKED_IN_PRODUCTION
151
+ : pkg.dependency
152
+ ? INSTALLED_AS_DEPENDENCY
153
+ : undefined
154
+ if (refused) {
155
+ log.error('{package} is not started: {reason}', { package: pkg.packageName, reason: refused })
156
+ return { status: 'failed', reason: refused }
157
+ }
158
+ const entry = config.extensions?.[pkg.id]
159
+ const { grant } = recorded
160
+ const byConfig = entryCovers(pkg, entry)
161
+ const granted =
162
+ byConfig || Boolean(grant?.recorded && !grant.disabledAt && grantGaps(pkg, grant).length === 0)
163
+ // Nothing of an extension that is not granted is built, let alone run.
164
+ if (!granted) return { status: 'not-granted' }
165
+ const process = new ExtensionProcess({
166
+ pkg,
167
+ siteDir: config.siteDir,
168
+ home: join(config.siteDir, '.crombolo', 'extensions', pkg.id),
169
+ settings: settingsOf(pkg, recorded.settings, entry, config.secretKey),
170
+ dialect: config.dialect,
171
+ origins: [
172
+ ...((byConfig ? entry?.origins : grant?.origins) ?? []),
173
+ ...(entry?.dev?.allowNet ?? []),
174
+ ],
175
+ reads: entry?.dev?.allowRead,
176
+ timeoutMs: entry?.timeoutMs,
177
+ log,
178
+ activity,
179
+ })
180
+ try {
181
+ const description = await process.start()
182
+ const problems = isolationProblems(description)
183
+ if (description.id !== pkg.id)
184
+ problems.push(`it calls itself "${description.id}", where its package.json says "${pkg.id}"`)
185
+ if (problems.length > 0) throw new Error(`It cannot run: ${problems.join('; ')}.`)
186
+ return { status: 'started', bundle: isolatedBundle(process), process }
187
+ } catch (error) {
188
+ await process.stop()
189
+ const reason = error instanceof Error ? error.message : String(error)
190
+ log.error('{package} could not be started, and the site runs without it: {reason}', {
191
+ package: pkg.packageName,
192
+ reason,
193
+ })
194
+ return { status: 'failed', reason }
195
+ }
196
+ }
197
+
128
198
  /**
129
199
  * The installed server halves to start, each in its own process with its
130
200
  * settings: those the config grants and those a recorded grant covers. Ones the
@@ -147,68 +217,17 @@ export async function startExtensions(
147
217
  const failed: FailedExtension[] = []
148
218
  for (const pkg of packages) {
149
219
  if (!pkg.carries.server || wired.has(pkg.id)) continue
150
- // Story 326: an extension runs from a root of its own, never as a dependency of the site.
151
- if (pkg.linked && Bun.env.NODE_ENV === 'production') {
152
- failed.push({ id: pkg.id, reason: LINKED_IN_PRODUCTION })
153
- log(pkg.id).error('{package} is not started: {reason}', {
154
- package: pkg.packageName,
155
- reason: LINKED_IN_PRODUCTION,
156
- })
157
- continue
158
- }
159
- if (pkg.dependency) {
160
- failed.push({ id: pkg.id, reason: INSTALLED_AS_DEPENDENCY })
161
- log(pkg.id).error('{package} is not started: {reason}', {
162
- package: pkg.packageName,
163
- reason: INSTALLED_AS_DEPENDENCY,
164
- })
165
- continue
166
- }
167
- const entry = config.extensions?.[pkg.id]
168
- const grant = recorded.grants.get(pkg.id)
169
- const byConfig = entryCovers(pkg, entry)
170
- const granted =
171
- byConfig ||
172
- Boolean(grant?.recorded && !grant.disabledAt && grantGaps(pkg, grant).length === 0)
173
- // Nothing of an extension that is not granted is built, let alone run.
174
- if (!granted) continue
175
- const process = new ExtensionProcess({
220
+ const started = await startExtension(
221
+ config,
176
222
  pkg,
177
- siteDir: config.siteDir,
178
- home: join(config.siteDir, '.crombolo', 'extensions', pkg.id),
179
- settings: settingsOf(pkg, recorded.settings.get(pkg.id), entry, config.secretKey),
180
- dialect: config.dialect,
181
- origins: [
182
- ...((byConfig ? entry?.origins : grant?.origins) ?? []),
183
- ...(entry?.dev?.allowNet ?? []),
184
- ],
185
- reads: entry?.dev?.allowRead,
186
- timeoutMs: entry?.timeoutMs,
187
- log: log(pkg.id),
223
+ { grant: recorded.grants.get(pkg.id), settings: recorded.settings.get(pkg.id) },
224
+ log(pkg.id),
188
225
  activity,
189
- })
190
- try {
191
- const description = await process.start()
192
- const problems = isolationProblems(description)
193
- if (description.id !== pkg.id)
194
- problems.push(
195
- `it calls itself "${description.id}", where its package.json says "${pkg.id}"`,
196
- )
197
- if (problems.length > 0) throw new Error(`It cannot run: ${problems.join('; ')}.`)
198
- bundles.push(isolatedBundle(process))
199
- processes.push(process)
200
- } catch (error) {
201
- await process.stop()
202
- const reason = error instanceof Error ? error.message : String(error)
203
- failed.push({ id: pkg.id, reason })
204
- log(pkg.id).error(
205
- '{package} could not be started, and the site starts without it: {reason}',
206
- {
207
- package: pkg.packageName,
208
- reason,
209
- },
210
- )
211
- }
226
+ )
227
+ if (started.status === 'started') {
228
+ bundles.push(started.bundle)
229
+ processes.push(started.process)
230
+ } else if (started.status === 'failed') failed.push({ id: pkg.id, reason: started.reason })
212
231
  }
213
232
  return { bundles, processes, failed }
214
233
  }
@@ -1,8 +1,8 @@
1
1
  /**
2
2
  * Story 335: an extension granted Acts as you or Unrestricted keeps that only
3
3
  * while someone this site trusts vouches for it. Checked at every start, before
4
- * extensions run, so an upgrade, or a signer taken off Trusted signers, switches
5
- * off what no longer qualifies.
4
+ * extensions run, so an upgrade switches off what no longer qualifies; and as a
5
+ * signer is taken off Trusted signers, so what it vouched for stops at once.
6
6
  */
7
7
  import { type ExtensionRegistry, isUpperLevel, levelOf } from '@crombolo/backoffice-host/registry'
8
8
  import type { Db } from '@crombolo/data'
@@ -27,6 +27,8 @@ export async function switchOffUntrusted(
27
27
  config: CromboloConfig,
28
28
  extensions: ExtensionRegistry,
29
29
  grants: Pick<BundleGrants, 'granted' | 'isOn' | 'state' | 'forget'>,
30
+ /** At start, or because a signer was just taken off the list. */
31
+ when: 'start' | 'untrusted' = 'start',
30
32
  ): Promise<string[]> {
31
33
  const marketplace = createMarketplace({
32
34
  registry: config.npmRegistry,
@@ -56,8 +58,8 @@ export async function switchOffUntrusted(
56
58
  action: 'Disable',
57
59
  entityType: 'Bundle',
58
60
  entityName: `${pkg.packageName}@${pkg.version}`,
59
- detail: `switched off at start: it acts as you or runs unrestricted, and is ${why}; it needs granting again`,
60
- source: 'boot',
61
+ detail: `switched off ${when === 'start' ? 'at start' : 'as its signer was taken off Trusted signers'}: it acts as you or runs unrestricted, and is ${why}; it needs granting again`,
62
+ source: when === 'start' ? 'boot' : 'request',
61
63
  userKey: null,
62
64
  userName: SWITCHED_OFF_BY,
63
65
  ipAddress: null,
package/src/index.ts CHANGED
@@ -17,6 +17,7 @@ export * from './adapters/template-files.ts'
17
17
  export { createUserPorts } from './adapters/users.ts'
18
18
  export * from './api-client.ts'
19
19
  export * from './atomic-write.ts'
20
+ export * from './background-jobs.ts'
20
21
  export * from './backup.ts'
21
22
  export * from './boot-failure.ts'
22
23
  export * from './bundle-admin.ts'
@@ -64,9 +65,16 @@ export * from './email-ses.ts'
64
65
  export * from './email-settings.ts'
65
66
  export * from './email-text.ts'
66
67
  export {
68
+ type ActivityAnswer,
69
+ type ActivityPart,
70
+ ActivityQueryError,
71
+ type ActivitySummary,
67
72
  activityCsv,
73
+ activityPath,
74
+ answerActivity,
68
75
  createActivityRecorder,
69
76
  personOf,
77
+ readActivity,
70
78
  readActivityQuery,
71
79
  } from './extension-activity.ts'
72
80
  export {
@@ -113,9 +121,11 @@ export * from './logging.ts'
113
121
  export * from './marketplace.ts'
114
122
  export * from './media-files.ts'
115
123
  export * from './media-folders.ts'
124
+ export * from './media-library.ts'
116
125
  export * from './media-store.ts'
117
126
  export * from './media-store-azure.ts'
118
127
  export * from './media-store-s3.ts'
128
+ export * from './member-admin.ts'
119
129
  export * from './member-auth.ts'
120
130
  export * from './middleware.ts'
121
131
  export * from './models-builder.ts'
@@ -124,6 +134,7 @@ export * from './oembed.ts'
124
134
  export * from './outbound-address.ts'
125
135
  export * from './owner-jobs.ts'
126
136
  export * from './ports.ts'
137
+ export * from './principal.ts'
127
138
  export * from './provenance.ts'
128
139
  export * from './rate-limit.ts'
129
140
  export * from './redirects.ts'
@@ -131,6 +142,7 @@ export * from './remote.ts'
131
142
  export * from './remote-ci.ts'
132
143
  export * from './remote-credentials.ts'
133
144
  export * from './remote-media.ts'
145
+ export { FILE_NAME_HEADER } from './remote-media-library.ts'
134
146
  export * from './restart-pending.ts'
135
147
  export * from './routes.ts'
136
148
  export * from './schema.ts'
@@ -164,8 +176,10 @@ export * from './transfer-dashboard.ts'
164
176
  export * from './trusted-signers-admin.ts'
165
177
  export * from './two-factor.ts'
166
178
  export * from './udt.ts'
179
+ export * from './undo.ts'
167
180
  export * from './upgrade-summary.ts'
168
181
  export * from './url-settings.ts'
182
+ export * from './user-admin.ts'
169
183
  export * from './view-runtime.ts'
170
184
  export * from './webhook-edit.ts'
171
185
  export * from './webhook-files.ts'