@crombolo/server 0.65.1 → 0.67.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/src/settings.ts CHANGED
@@ -284,6 +284,13 @@ const DECLARED = [
284
284
  description:
285
285
  "Identity providers nobody can change in the back office, by id, separated by commas, or `all`: they sign in by the site's configuration alone. A provider declared `locked: true` is locked too.",
286
286
  },
287
+ {
288
+ env: 'CROMBOLO_REMOTE_EXCHANGE_PROVIDERS',
289
+ kind: 'list',
290
+ section: 'Sign-in and secrets',
291
+ description:
292
+ "Back-office identity providers, by id, separated by commas, whose tokens the remote exchanges for a sign-in as the person they name, besides those the site's configuration opts in.",
293
+ },
287
294
  {
288
295
  env: 'CROMBOLO_SECRET_KEY',
289
296
  kind: 'string',
@@ -1131,6 +1138,92 @@ const DECLARED = [
1131
1138
  description: 'Who the audit log records for a command, for a pipeline acting for someone.',
1132
1139
  appliesTo: 'cli',
1133
1140
  },
1141
+ {
1142
+ env: 'CROMBOLO_PROFILE',
1143
+ kind: 'string',
1144
+ section: 'Command line',
1145
+ description:
1146
+ 'The profile a command acts on when it is not given `--profile`, for a shell or a job.',
1147
+ appliesTo: 'cli',
1148
+ },
1149
+ {
1150
+ env: 'CROMBOLO_PROFILES_FILE',
1151
+ kind: 'string',
1152
+ default: '~/.crombolo/profiles',
1153
+ section: 'Command line',
1154
+ description: 'Where the profiles are kept, for tests and unusual machines.',
1155
+ appliesTo: 'cli',
1156
+ },
1157
+ {
1158
+ env: 'CROMBOLO_PROFILE_URL',
1159
+ kind: 'string',
1160
+ section: 'Command line',
1161
+ description:
1162
+ "The address of a hosted site a command acts on when neither `--profile` nor CROMBOLO_PROFILE names one: how a CI job names its site. A Next.js front end reads it as the CMS's address.",
1163
+ appliesTo: 'cli',
1164
+ },
1165
+ {
1166
+ env: 'CROMBOLO_PROFILE_ENVIRONMENT',
1167
+ kind: 'string',
1168
+ section: 'Command line',
1169
+ description: "With CROMBOLO_PROFILE_URL: that site's environment, when it has more than one.",
1170
+ appliesTo: 'cli',
1171
+ },
1172
+ {
1173
+ env: 'CROMBOLO_CREDENTIALS',
1174
+ kind: 'enum',
1175
+ values: ['keychain', 'file'],
1176
+ default: 'the keychain where there is one',
1177
+ section: 'Command line',
1178
+ description:
1179
+ "Where sign-ins are kept: the operating system's keychain, or ~/.crombolo/credentials, which only you can read. Left unset, a machine with no keychain uses the file.",
1180
+ appliesTo: 'both',
1181
+ },
1182
+ {
1183
+ env: 'CROMBOLO_CREDENTIALS_FILE',
1184
+ kind: 'string',
1185
+ default: '~/.crombolo/credentials',
1186
+ section: 'Command line',
1187
+ description:
1188
+ 'The file sign-ins are kept in when they are not in the keychain, for tests and unusual machines.',
1189
+ appliesTo: 'both',
1190
+ },
1191
+ {
1192
+ env: 'CROMBOLO_CLI_ACCESS',
1193
+ kind: 'enum',
1194
+ values: ['open', 'sign-in'],
1195
+ default: '`sign-in` in production, `open` otherwise',
1196
+ section: 'Command line',
1197
+ description:
1198
+ 'Whether a command that reads or changes the site needs someone signed in with `crombolo login`. At `open` it runs as the command line unless someone is signed in; at `sign-in` it acts as the person, with their permissions.',
1199
+ appliesTo: 'both',
1200
+ },
1201
+ {
1202
+ env: 'CROMBOLO_CLI_TOKENS',
1203
+ kind: 'boolean',
1204
+ default: 'false',
1205
+ section: 'Command line',
1206
+ description:
1207
+ 'Whether people may create command-line tokens, for a script or a CI job to run commands as them. Off, no token is made and every existing one is refused, but kept.',
1208
+ appliesTo: 'both',
1209
+ },
1210
+ {
1211
+ env: 'CROMBOLO_CLI_TOKEN_MAX_DAYS',
1212
+ kind: 'number',
1213
+ default: '90',
1214
+ section: 'Command line',
1215
+ description: 'The most days a command-line token may last.',
1216
+ appliesTo: 'both',
1217
+ },
1218
+ {
1219
+ env: 'CROMBOLO_TOKEN',
1220
+ kind: 'string',
1221
+ section: 'Command line',
1222
+ description:
1223
+ "A command-line token: commands act as the person who made it, here or on a hosted site, before anyone's stored sign-in.",
1224
+ secret: true,
1225
+ appliesTo: 'cli',
1226
+ },
1134
1227
  {
1135
1228
  env: 'CROMBOLO_BUNDLE_PASSPHRASE',
1136
1229
  kind: 'string',
package/src/undo.ts ADDED
@@ -0,0 +1,358 @@
1
+ /**
2
+ * Undoing a change (story 353): a page's history, one of its versions, and what
3
+ * is in the recycle bin, read the same way for the command line on the site's
4
+ * own database and for the remote protocol. The writes go through the content
5
+ * and media operations, as the back office's do.
6
+ */
7
+ import { type DocumentAggregate, normaliseUuid, ObjectTypes } from '@crombolo/core'
8
+ import { currentSchemaState, type Db, DocumentRepository, NodeRepository } from '@crombolo/data'
9
+ import { type PathKind, schemaLookup, shorthandReader } from './seed/index.ts'
10
+
11
+ const OBJECT_TYPES: Record<PathKind, string> = {
12
+ content: ObjectTypes.Document,
13
+ library: ObjectTypes.Element,
14
+ media: ObjectTypes.Media,
15
+ }
16
+
17
+ /** A node's place by its names, `Home/Visit us`, as a path argument names it. */
18
+ export async function namedPath(db: Db, key: string, kind: PathKind): Promise<string | undefined> {
19
+ const nodes = new NodeRepository(db)
20
+ const node = await nodes.byKey(normaliseUuid(key))
21
+ if (!node || node.objectType !== OBJECT_TYPES[kind]) return undefined
22
+ const names: string[] = []
23
+ for (const id of node.path
24
+ .split(',')
25
+ .map(Number)
26
+ .filter((id) => id > 0)) {
27
+ const row = await nodes.byId(id)
28
+ if (!row) return undefined
29
+ names.push(row.text ?? row.key)
30
+ }
31
+ return names.join('/')
32
+ }
33
+
34
+ /** Values as `content show` gives them: in the shorthand content files use, segments left out. */
35
+ export function pageReader(db: Db, lookup = schemaLookup(db)) {
36
+ const typeAliases = new Map<string, string>()
37
+ const aliasOf = async (typeKey: string) => {
38
+ const key = normaliseUuid(typeKey)
39
+ if (!typeAliases.has(key))
40
+ typeAliases.set(key, (await lookup.typeByKey('document', key))?.alias ?? key)
41
+ return typeAliases.get(key) as string
42
+ }
43
+ return shorthandReader(lookup, aliasOf, (key, kind) => namedPath(db, key, kind))
44
+ }
45
+
46
+ export interface ShownValue {
47
+ property: string
48
+ culture: string | null
49
+ value: unknown
50
+ }
51
+
52
+ async function shownValues(db: Db, doc: DocumentAggregate): Promise<ShownValue[]> {
53
+ const lookup = schemaLookup(db)
54
+ const reader = pageReader(db, lookup)
55
+ const type = await lookup.typeByKey('document', doc.contentTypeKey)
56
+ const editors = type ? await lookup.editorsOf('document', type) : new Map()
57
+ const out: ShownValue[] = []
58
+ for (const v of doc.values) {
59
+ if (v.segment !== null) continue
60
+ out.push({
61
+ property: v.alias,
62
+ culture: v.culture,
63
+ value: await reader.shorthand(editors.get(v.alias)?.editor ?? '', v.value),
64
+ })
65
+ }
66
+ return out
67
+ }
68
+
69
+ /** Who made a change: a person by key and name, or null for the command line or the site. */
70
+ export type Who = { key: string; name: string } | null
71
+
72
+ export interface HistoryEntry {
73
+ /** The version's key, which names it to `show`, `keep` and `rollback`. */
74
+ id: string
75
+ date: string
76
+ /** What made it: a save, a publish, a rollback, or an upgrade's migration. */
77
+ kind: string
78
+ by: Who
79
+ /** The page's draft now. */
80
+ draft: boolean
81
+ /** What is published now. */
82
+ live: boolean
83
+ /** Kept from cleanup. */
84
+ kept: boolean
85
+ }
86
+
87
+ async function userNames(db: Db, keys: readonly string[]): Promise<Map<string, string>> {
88
+ const wanted = [...new Set(keys)]
89
+ if (wanted.length === 0) return new Map()
90
+ const rows = await db.q
91
+ .selectFrom('user_account')
92
+ .select(['key', 'user_name'])
93
+ .where('key', 'in', wanted)
94
+ .execute()
95
+ return new Map(rows.map((row) => [normaliseUuid(String(row.key)), String(row.user_name)]))
96
+ }
97
+
98
+ /** Pages read as of the schema the site is at now, as the site's own reads are. */
99
+ async function documents(db: Db, kind: 'document' | 'media' = 'document') {
100
+ const state = await currentSchemaState(db)
101
+ return new DocumentRepository(db, {
102
+ kind,
103
+ nodeState: { version: state.version, revision: state.revision },
104
+ })
105
+ }
106
+
107
+ const pageNode = async (db: Db, key: string) => {
108
+ const node = await new NodeRepository(db).byKey(normaliseUuid(key))
109
+ return node?.objectType === ObjectTypes.Document ? node : undefined
110
+ }
111
+
112
+ /** A page's versions, newest first; undefined when there is no such page. */
113
+ export async function pageHistory(
114
+ db: Db,
115
+ key: string,
116
+ ): Promise<{ page: { key: string; name: string }; versions: HistoryEntry[] } | undefined> {
117
+ const node = await pageNode(db, key)
118
+ if (!node) return undefined
119
+ const versions = await (await documents(db)).versions(node.key)
120
+ const names = await userNames(
121
+ db,
122
+ versions.flatMap((v) => (v.userKey ? [v.userKey] : [])),
123
+ )
124
+ return {
125
+ page: { key: node.key, name: node.text ?? node.key },
126
+ versions: versions.map((v) => ({
127
+ id: v.id,
128
+ date: v.versionDate.toISOString(),
129
+ kind: v.kind ?? 'save',
130
+ by: v.userKey ? { key: v.userKey, name: names.get(v.userKey) ?? v.userKey } : null,
131
+ draft: v.isCurrentDraft,
132
+ live: v.isCurrentPublished,
133
+ kept: v.preventCleanup,
134
+ })),
135
+ }
136
+ }
137
+
138
+ export interface ValueChange {
139
+ property: string
140
+ culture: string | null
141
+ /** `added`: this version has it and the draft does not; `removed`, the other way round. */
142
+ change: 'added' | 'removed' | 'changed'
143
+ draft?: unknown
144
+ version?: unknown
145
+ }
146
+
147
+ export interface PageVersion {
148
+ id: string
149
+ page: { key: string; name: string }
150
+ /** The page's name in this version. */
151
+ name: string
152
+ values: ShownValue[]
153
+ /** What differs from the current draft, when asked for. */
154
+ diff?: ValueChange[]
155
+ }
156
+
157
+ const same = (a: unknown, b: unknown) => JSON.stringify(a) === JSON.stringify(b)
158
+
159
+ /** What a version holds against what the draft does, property by property. */
160
+ export function diffValues(draft: readonly ShownValue[], version: readonly ShownValue[]) {
161
+ const id = (v: ShownValue) => `${v.property}\u0000${v.culture ?? ''}`
162
+ const now = new Map(draft.map((v) => [id(v), v]))
163
+ const then = new Map(version.map((v) => [id(v), v]))
164
+ const changes: ValueChange[] = []
165
+ for (const [at, v] of then) {
166
+ const current = now.get(at)
167
+ if (!current)
168
+ changes.push({ property: v.property, culture: v.culture, change: 'added', version: v.value })
169
+ else if (!same(current.value, v.value))
170
+ changes.push({
171
+ property: v.property,
172
+ culture: v.culture,
173
+ change: 'changed',
174
+ draft: current.value,
175
+ version: v.value,
176
+ })
177
+ }
178
+ for (const [at, v] of now)
179
+ if (!then.has(at))
180
+ changes.push({ property: v.property, culture: v.culture, change: 'removed', draft: v.value })
181
+ return changes.sort((a, b) => a.property.localeCompare(b.property))
182
+ }
183
+
184
+ /** One version of a page: its values as `content show` gives them, and with `diff` what differs from the draft. */
185
+ export async function pageVersion(
186
+ db: Db,
187
+ versionId: string,
188
+ options: { diff?: boolean } = {},
189
+ ): Promise<PageVersion | undefined> {
190
+ const repo = await documents(db)
191
+ const found = await repo.atVersion(versionId)
192
+ if (!found) return undefined
193
+ const doc = found.document
194
+ const values = await shownValues(db, doc)
195
+ const name = doc.variants.find((v) => v.culture === null)?.name ?? doc.variants[0]?.name ?? ''
196
+ const node = await pageNode(db, doc.key)
197
+ const out: PageVersion = {
198
+ id: found.versionId,
199
+ page: { key: doc.key, name: node?.text ?? name },
200
+ name,
201
+ values,
202
+ }
203
+ if (options.diff) {
204
+ const draft = await repo.byKey(doc.key)
205
+ out.diff = diffValues(draft ? await shownValues(db, draft) : [], values)
206
+ }
207
+ return out
208
+ }
209
+
210
+ /** A page as `content show` gives it: its place, type, names in each language, and values. */
211
+ export interface ShownPage {
212
+ key: string
213
+ /** Its place by name, `/Home/Visit us`. */
214
+ path: string
215
+ type: string
216
+ typeName: string
217
+ variants: Array<{ culture: string | null; name: string; state: string }>
218
+ values: ShownValue[]
219
+ }
220
+
221
+ /** A page's draft as `content show` gives it; undefined when there is no such page (story 355). */
222
+ export async function pageShown(db: Db, key: string): Promise<ShownPage | undefined> {
223
+ if (!(await pageNode(db, key))) return undefined
224
+ const doc = await (await documents(db)).byKey(normaliseUuid(key))
225
+ if (!doc) return undefined
226
+ const type = await schemaLookup(db).typeByKey('document', doc.contentTypeKey)
227
+ return {
228
+ key: doc.key,
229
+ path: `/${(await namedPath(db, doc.key, 'content')) ?? ''}`,
230
+ type: type?.alias ?? doc.contentTypeAlias,
231
+ typeName: type?.name ?? doc.contentTypeAlias,
232
+ variants: doc.variants.map((v) => ({ culture: v.culture, name: v.name, state: v.state })),
233
+ values: await shownValues(db, doc),
234
+ }
235
+ }
236
+
237
+ export type BinKind = 'content' | 'media'
238
+
239
+ export interface BinItem {
240
+ key: string
241
+ name: string
242
+ kind: BinKind
243
+ trashedAt: string | null
244
+ by: Who
245
+ /**
246
+ * Where it came from: the place's key and path, a null key and `/` for the
247
+ * top level. `gone` when that place has been deleted or is itself in the bin,
248
+ * when its path is null.
249
+ */
250
+ from: { key: string | null; path: string | null; gone: boolean }
251
+ }
252
+
253
+ const BIN_TYPES: Record<BinKind, { objectType: string; kind: 'document' | 'media' }> = {
254
+ content: { objectType: ObjectTypes.Document, kind: 'document' },
255
+ media: { objectType: ObjectTypes.Media, kind: 'media' },
256
+ }
257
+
258
+ /** What is in the recycle bin, newest first: what was trashed directly, not what went with it. */
259
+ export async function binItems(
260
+ db: Db,
261
+ options: { kinds?: readonly BinKind[]; olderThanDays?: number; now?: number } = {},
262
+ ): Promise<BinItem[]> {
263
+ const kinds = options.kinds ?? ['content', 'media']
264
+ const cutoff =
265
+ options.olderThanDays === undefined
266
+ ? undefined
267
+ : (options.now ?? Date.now()) - options.olderThanDays * 86_400_000
268
+ const nodes = new NodeRepository(db)
269
+ const items: BinItem[] = []
270
+ for (const kind of kinds) {
271
+ const repo = await documents(db, BIN_TYPES[kind].kind)
272
+ const roots = await repo.trashedRoots()
273
+ if (roots.length === 0) continue
274
+ const ids = roots.map((node) => node.id)
275
+ const dates = await repo.trashedDates(ids)
276
+ const parents = new Map(
277
+ (
278
+ await db.q
279
+ .selectFrom('document')
280
+ .select(['node_id', 'original_parent_id'])
281
+ .where('node_id', 'in', ids)
282
+ .execute()
283
+ ).map((row) => [Number(row.node_id), row.original_parent_id]),
284
+ )
285
+ const trashers = await trashedBy(
286
+ db,
287
+ roots.map((node) => node.key),
288
+ )
289
+ for (const node of roots) {
290
+ const trashedAt = dates.get(node.id)
291
+ if (cutoff !== undefined && (!trashedAt || trashedAt.getTime() > cutoff)) continue
292
+ const parentId = parents.get(node.id)
293
+ let from: BinItem['from'] = { key: null, path: '/', gone: false }
294
+ if (parentId !== null && parentId !== undefined) {
295
+ const parent = await nodes.byId(Number(parentId))
296
+ from = parent
297
+ ? {
298
+ key: parent.key,
299
+ path: parent.trashed
300
+ ? null
301
+ : `/${(await namedPath(db, parent.key, kind === 'media' ? 'media' : 'content')) ?? ''}`,
302
+ gone: parent.trashed,
303
+ }
304
+ : { key: null, path: null, gone: true }
305
+ }
306
+ items.push({
307
+ key: node.key,
308
+ name: node.text ?? node.key,
309
+ kind,
310
+ trashedAt: trashedAt?.toISOString() ?? null,
311
+ by: trashers.get(node.key) ?? null,
312
+ from,
313
+ })
314
+ }
315
+ }
316
+ return items.sort((a, b) => (b.trashedAt ?? '').localeCompare(a.trashedAt ?? ''))
317
+ }
318
+
319
+ /** Who put each item in the bin, from the audit log's latest Trash entry for it. */
320
+ async function trashedBy(db: Db, keys: readonly string[]): Promise<Map<string, Who>> {
321
+ const rows = await db.q
322
+ .selectFrom('audit_entry')
323
+ .select(['entity_key', 'user_key', 'user_name', 'occurred_at'])
324
+ .where('action', '=', 'Trash')
325
+ .where('entity_key', 'in', [...keys])
326
+ .orderBy('id', 'asc')
327
+ .execute()
328
+ const out = new Map<string, Who>()
329
+ for (const row of rows) {
330
+ const key = normaliseUuid(String(row.entity_key))
331
+ out.set(
332
+ key,
333
+ row.user_key
334
+ ? { key: normaliseUuid(String(row.user_key)), name: String(row.user_name ?? '') }
335
+ : null,
336
+ )
337
+ }
338
+ return out
339
+ }
340
+
341
+ /** The bin's items a name, path or key could mean: its key, the path it came from, or its name alone. */
342
+ export function binMatches(items: readonly BinItem[], ref: string): BinItem[] {
343
+ const wanted = ref.trim()
344
+ const byKey = items.filter((item) => item.key === wanted.toLowerCase())
345
+ if (byKey.length > 0) return byKey
346
+ const fold = (text: string) => text.replace(/^\/+|\/+$/g, '').toLowerCase()
347
+ const at = (item: BinItem) =>
348
+ fold(item.from.path && item.from.path !== '/' ? `${item.from.path}/${item.name}` : item.name)
349
+ const byPath = items.filter((item) => at(item) === fold(wanted))
350
+ if (byPath.length > 0) return byPath
351
+ return items.filter((item) => fold(item.name) === fold(wanted))
352
+ }
353
+
354
+ /** Why an item cannot go back where it was, or undefined when it can. */
355
+ export function placeGone(item: BinItem): string | undefined {
356
+ if (!item.from.gone) return undefined
357
+ return `"${item.name}" came from a place that is ${item.from.key ? 'in the recycle bin too' : 'no longer there'}.`
358
+ }