@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,152 @@
1
+ /**
2
+ * Command-line tokens over HTTP (story 351), at `<plugin>/api/cli-tokens`:
3
+ * GET lists your own, or `?user=<key>` someone's for an administrator; POST
4
+ * `{ name, days }` makes one and answers it once; DELETE `/{key}` revokes your
5
+ * own, or anyone's for an administrator. While tokens are off, GET answers
6
+ * `{ enabled: false }` and the rest are refused. docs/operations.md,
7
+ * "Command-line tokens".
8
+ */
9
+ import type { Principal } from '@crombolo/api-management/domain'
10
+ import {
11
+ CLI_TOKEN_REFUSALS,
12
+ type CliToken,
13
+ type CliTokenPerson,
14
+ type CliTokenRefusal,
15
+ type CliTokens,
16
+ DEFAULT_CLI_TOKEN_DAYS,
17
+ } from '@crombolo/auth'
18
+ import type { Db } from '@crombolo/data'
19
+ import { recordAudit } from './adapters/audit.ts'
20
+
21
+ export interface CliTokenView {
22
+ key: string
23
+ name: string
24
+ createdAt: string
25
+ expiresAt: string
26
+ lastUsedAt: string | null
27
+ }
28
+
29
+ export const cliTokenView = (token: CliToken): CliTokenView => ({
30
+ key: token.key,
31
+ name: token.name,
32
+ createdAt: token.createdAt.toISOString(),
33
+ expiresAt: token.expiresAt.toISOString(),
34
+ lastUsedAt: token.lastUsedAt?.toISOString() ?? null,
35
+ })
36
+
37
+ type Person = CliTokenPerson
38
+
39
+ type Client = { ipAddress: string | null; forwardedFor: string | null }
40
+
41
+ const json = (body: unknown, status = 200) => Response.json(body, { status })
42
+ const refused = (message: string, status = 403) => json({ message }, status)
43
+
44
+ /** A token's refusal, with its reason, for a client that sent one the site would not take. */
45
+ export const tokenRefusal = (reason: CliTokenRefusal): Response =>
46
+ json({ reason, message: CLI_TOKEN_REFUSALS[reason] }, 401)
47
+
48
+ export function createCliTokensApi(db: Db, tokens: CliTokens) {
49
+ const person = (who: string) => tokens.person(who)
50
+ const ownerOf = (token: CliToken) => tokens.ownerOf(token)
51
+
52
+ const audit = (by: Principal, action: string, whose: Person, detail: string, client: Client) =>
53
+ recordAudit(db, {
54
+ category: 'user',
55
+ action,
56
+ source: 'request',
57
+ userKey: by.id,
58
+ userName: by.name,
59
+ entityType: 'User',
60
+ entityKey: whose.key,
61
+ entityName: whose.name,
62
+ detail,
63
+ ...client,
64
+ })
65
+
66
+ return {
67
+ async handle(
68
+ request: Request,
69
+ principal: Principal,
70
+ rest: string,
71
+ client: Client,
72
+ ): Promise<Response> {
73
+ const { enabled, maxDays } = tokens.settings
74
+ const me = await person(principal.id)
75
+ if (!me) return new Response('Unauthorized', { status: 401 })
76
+ if (request.method === 'GET' && rest === '') {
77
+ if (!enabled) return json({ enabled: false })
78
+ const asked = new URL(request.url).searchParams.get('user')
79
+ let whose = me
80
+ if (asked) {
81
+ const found = await person(asked)
82
+ if (found?.key !== me.key) {
83
+ if (!principal.isAdmin)
84
+ return refused("Only an administrator can see other people's tokens.")
85
+ if (!found) return refused('There is no such user.', 404)
86
+ whose = found
87
+ }
88
+ }
89
+ return json({
90
+ enabled: true,
91
+ mayCreate: whose.key === me.key && (await tokens.mayCreate(me.id)),
92
+ maxDays,
93
+ defaultDays: Math.min(DEFAULT_CLI_TOKEN_DAYS, maxDays),
94
+ items: (await tokens.list(whose.id)).map(cliTokenView),
95
+ })
96
+ }
97
+ if (!enabled) return refused(CLI_TOKEN_REFUSALS.off)
98
+ if (request.method === 'POST' && rest === '') {
99
+ const body = (await request.json().catch(() => ({}))) as { name?: unknown; days?: unknown }
100
+ const issued = await tokens.issue(
101
+ me.id,
102
+ typeof body.name === 'string' ? body.name : '',
103
+ body.days === undefined || body.days === null ? undefined : Number(body.days),
104
+ )
105
+ if (!issued.ok) return refused(issued.message, issued.refused === 'not-allowed' ? 403 : 400)
106
+ await audit(
107
+ principal,
108
+ 'CreateToken',
109
+ me,
110
+ `"${issued.issued.name}", until ${issued.issued.expiresAt.toISOString().slice(0, 10)}`,
111
+ client,
112
+ )
113
+ return json({ ...cliTokenView(issued.issued), token: issued.token }, 201)
114
+ }
115
+ const key = /^\/([0-9a-fA-F-]{36})$/.exec(rest)?.[1]
116
+ if (request.method === 'DELETE' && key) {
117
+ const token = await tokens.byKey(key)
118
+ if (!token || token.revokedAt) return refused('There is no such token.', 404)
119
+ if (token.userId !== me.id && !principal.isAdmin)
120
+ return refused('There is no such token.', 404)
121
+ const owner = token.userId === me.id ? me : await ownerOf(token)
122
+ await tokens.revoke(token.key, me.key)
123
+ await audit(
124
+ principal,
125
+ 'RevokeToken',
126
+ owner,
127
+ owner === me ? `"${token.name}"` : `"${token.name}", ${owner.name}'s`,
128
+ client,
129
+ )
130
+ return new Response(null, { status: 204 })
131
+ }
132
+ return new Response('Method Not Allowed', { status: 405 })
133
+ },
134
+
135
+ /** The first use of a token, audited under its person, before the request names the token. */
136
+ async firstUse(token: CliToken, client: Client): Promise<void> {
137
+ const owner = await ownerOf(token)
138
+ await recordAudit(db, {
139
+ category: 'user',
140
+ action: 'FirstUseOfToken',
141
+ source: 'request',
142
+ userKey: owner.key,
143
+ userName: owner.name,
144
+ entityType: 'User',
145
+ entityKey: owner.key,
146
+ entityName: owner.name,
147
+ detail: `"${token.name}"`,
148
+ ...client,
149
+ })
150
+ },
151
+ }
152
+ }
package/src/config.ts CHANGED
@@ -121,6 +121,18 @@ function deliveryApiPublic(): boolean | undefined {
121
121
  return isPrivate === undefined ? undefined : !isPrivate
122
122
  }
123
123
 
124
+ /** Whether a command needs someone signed in (story 350): `open` lets it run as the command line. */
125
+ export type CliAccess = 'open' | 'sign-in'
126
+
127
+ /** `CROMBOLO_CLI_ACCESS`, or undefined for the default, which follows `development`. */
128
+ function cliAccessSetting(): CliAccess | undefined {
129
+ const value = setting('CROMBOLO_CLI_ACCESS')?.trim().toLowerCase()
130
+ if (!value) return undefined
131
+ if (value !== 'open' && value !== 'sign-in')
132
+ throw new Error(`CROMBOLO_CLI_ACCESS is "${value}": it is open or sign-in.`)
133
+ return value
134
+ }
135
+
124
136
  /** Whether the back office must leave templates, stylesheets and scripts alone. */
125
137
  export const contentFilesLocked = (config: Pick<CromboloConfig, 'contentMode'>) =>
126
138
  config.contentMode === 'production'
@@ -381,6 +393,19 @@ export interface CromboloConfig {
381
393
  * `development` unless set, in production too. `CROMBOLO_CONTENT_MODE`.
382
394
  */
383
395
  contentMode: ContentMode
396
+ /**
397
+ * Whether a command that reads or changes the site needs a signed-in person
398
+ * (story 350): `sign-in` unless `development`, where it is `open`.
399
+ * `CROMBOLO_CLI_ACCESS`. docs/operations.md, "Signing in from the command line".
400
+ */
401
+ cliAccess: CliAccess
402
+ /**
403
+ * Whether people may make command-line tokens, and any is taken (story 351).
404
+ * `CROMBOLO_CLI_TOKENS`, off unless set.
405
+ */
406
+ cliTokens: boolean
407
+ /** The most days a command-line token may last. `CROMBOLO_CLI_TOKEN_MAX_DAYS`, 90. */
408
+ cliTokenMaxDays: number
384
409
  /** Sync `schema/` at boot; a pipeline that runs `crombolo types sync` turns this off. */
385
410
  syncSchemaAtBoot: boolean
386
411
  /** Which database engine; from CROMBOLO_DB. */
@@ -939,6 +964,10 @@ export function loadConfig(
939
964
  : setting('NODE_ENV') !== 'production',
940
965
  syncSchemaAtBoot: setting('CROMBOLO_SYNC_SCHEMA_AT_BOOT') !== 'false',
941
966
  contentMode: contentModeSetting(),
967
+ // Resolved again below, once it is known whether this is development.
968
+ cliAccess: cliAccessSetting() as CliAccess,
969
+ cliTokens: setting('CROMBOLO_CLI_TOKENS') === 'true',
970
+ cliTokenMaxDays: Math.floor(positiveNumber(setting('CROMBOLO_CLI_TOKEN_MAX_DAYS'), 90)),
942
971
  dialect: setting('CROMBOLO_DB') === 'postgres' ? 'postgres' : 'sqlite',
943
972
  pgDump: setting('CROMBOLO_PG_DUMP'),
944
973
  upgradePolicy:
@@ -1096,6 +1125,11 @@ export function loadConfig(
1096
1125
  throw new Error(
1097
1126
  `contentMode is "${String(merged.contentMode)}" in crombolo.config.ts: it is development or production.`,
1098
1127
  )
1128
+ merged.cliAccess ??= merged.development ? 'open' : 'sign-in'
1129
+ if (merged.cliAccess !== 'open' && merged.cliAccess !== 'sign-in')
1130
+ throw new Error(
1131
+ `cliAccess is "${String(merged.cliAccess)}" in crombolo.config.ts: it is open or sign-in.`,
1132
+ )
1099
1133
  checkIdentityProviders(merged.memberIdentityProviders, 'member')
1100
1134
  checkIdentityProviders(merged.backofficeIdentityProviders, 'backoffice')
1101
1135
  // Field by field, so a site setting its title suffix keeps the environment's switches.
@@ -1239,7 +1273,7 @@ export function describeDatabase(
1239
1273
  }
1240
1274
  }
1241
1275
 
1242
- export const VERSION = '0.65.1'
1276
+ export const VERSION = '0.66.0'
1243
1277
 
1244
1278
  /** A whole number of seconds from the environment; undefined when unset or not one. */
1245
1279
  /** A positive number from a setting, else the default. */
@@ -12,7 +12,9 @@ import {
12
12
  actorUserKey,
13
13
  auditEntryFor,
14
14
  type DocumentEvent,
15
+ type ElementEventSink,
15
16
  type EventSink,
17
+ elementAuditEntryFor,
16
18
  liveEventsFor,
17
19
  type MediaActor,
18
20
  type MediaEventSink,
@@ -153,3 +155,23 @@ export function createMediaEventSink(options: {
153
155
  },
154
156
  }
155
157
  }
158
+
159
+ /**
160
+ * Where Library operations record what they did (story 361): the audit entry, in
161
+ * the change's own transaction, as the back office has always written it.
162
+ */
163
+ export function createElementEventSink(): ElementEventSink {
164
+ return {
165
+ async record(tx: Db, event, actor) {
166
+ const entry = elementAuditEntryFor(event, actor)
167
+ const audit = new AuditLog(tx)
168
+ const subject = await audit.describe(entry.entityType, entry.entityKey)
169
+ await audit.record({
170
+ ...entry,
171
+ entityType: subject.entityType,
172
+ entityKey: subject.entityKey,
173
+ entityName: subject.entityName,
174
+ })
175
+ },
176
+ }
177
+ }
@@ -6,7 +6,12 @@
6
6
  * the running nodes instead.
7
7
  */
8
8
 
9
- import type { DocumentOperations, EventSink, MediaOperations } from '@crombolo/content'
9
+ import type {
10
+ DocumentOperations,
11
+ ElementOperations,
12
+ EventSink,
13
+ MediaOperations,
14
+ } from '@crombolo/content'
10
15
  import { currentSchemaState, type Db } from '@crombolo/data'
11
16
  import { PublishedCache } from '@crombolo/render'
12
17
  import { createPublishedContentSource } from './adapters/documents.ts'
@@ -90,3 +95,23 @@ export async function siteMediaOperations(
90
95
  webhooks,
91
96
  }).media
92
97
  }
98
+
99
+ /**
100
+ * Library operations for a process that is not serving requests (story 361): the
101
+ * same rules and audit entries as the back office's. Its cache instructions are
102
+ * the command line's, so a running server refreshes its pages and menus.
103
+ */
104
+ export async function siteElementOperations(
105
+ db: Db,
106
+ config: CromboloConfig,
107
+ ): Promise<ElementOperations> {
108
+ const state = await currentSchemaState(db)
109
+ return createNodeOperations({
110
+ db,
111
+ config,
112
+ nodeState: { version: state.version, revision: state.revision },
113
+ nodeId: config.nodeId,
114
+ instructedBy: `cli:${config.nodeId}`,
115
+ mediaFiles: new MediaFileStore(await mediaStoreFor(config)),
116
+ }).elements
117
+ }
@@ -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
+ }
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'