@crombolo/data 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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@crombolo/data",
3
- "version": "0.64.0",
3
+ "version": "0.66.0",
4
4
  "description": "Internal to crombolo, with no compatibility promise: use @crombolo/crombolo. SQLite and Postgres storage for crombolo: schema, migrations and repositories.",
5
5
  "license": "MIT",
6
6
  "author": "Crombolo",
@@ -29,7 +29,7 @@
29
29
  "access": "public"
30
30
  },
31
31
  "dependencies": {
32
- "@crombolo/core": "0.64.0",
32
+ "@crombolo/core": "0.66.0",
33
33
  "kysely": "0.29.6"
34
34
  }
35
35
  }
package/src/audit.ts CHANGED
@@ -2,6 +2,7 @@
2
2
  * The audit log: who did what, when and from where. Entries are only ever
3
3
  * added, read and aged out; nothing edits one. docs/audit-log.md.
4
4
  */
5
+ import { AsyncLocalStorage } from 'node:async_hooks'
5
6
  import { normaliseUuid } from '@crombolo/core'
6
7
  import type { Expression, ExpressionBuilder, SqlBool } from 'kysely'
7
8
  import type { Db } from './database.ts'
@@ -173,6 +174,55 @@ function toEntry(row: Record<string, unknown>): AuditEntry {
173
174
  }
174
175
  }
175
176
 
177
+ /**
178
+ * What a request's entries say about how it was made, filled in once the caller
179
+ * is known: an administrator viewing as groups (story 314) has every entry they
180
+ * write say so.
181
+ */
182
+ export interface AuditContext {
183
+ viewing?: { userKey: string; groups: string }
184
+ /** A person acting through one of their command-line tokens (story 351), by its name. */
185
+ token?: { userKey: string; name: string }
186
+ }
187
+
188
+ const contexts = new AsyncLocalStorage<AuditContext>()
189
+
190
+ /** Runs `work` with an audit context of its own, which it fills in as it learns who is asking. */
191
+ export const withAuditContext = <T>(work: () => T): T => contexts.run({}, work)
192
+
193
+ let processContext: AuditContext | undefined
194
+
195
+ /**
196
+ * The context for a whole process that answers no requests, such as one
197
+ * command (story 351); a request's own context always comes first.
198
+ */
199
+ export const setProcessAuditContext = (context: AuditContext | undefined): void => {
200
+ processContext = context
201
+ }
202
+
203
+ /** The context of the request being answered, or of the process; undefined outside both. */
204
+ export const currentAuditContext = (): AuditContext | undefined =>
205
+ contexts.getStore() ?? processContext
206
+
207
+ /**
208
+ * The detail an entry is written with: "while viewing as Editors", or "through
209
+ * the token deploy", added to the person's own.
210
+ */
211
+ export function detailInContext(
212
+ entry: Pick<AuditEntryInput, 'userKey' | 'detail'>,
213
+ context = currentAuditContext(),
214
+ ): string | null | undefined {
215
+ if (!context || !entry.userKey || !UUID.test(entry.userKey)) return entry.detail
216
+ const who = normaliseUuid(entry.userKey)
217
+ const notes = [
218
+ context.viewing?.userKey === who ? `while viewing as ${context.viewing.groups}` : undefined,
219
+ context.token?.userKey === who ? `through the token ${context.token.name}` : undefined,
220
+ ].filter((note): note is string => note !== undefined)
221
+ if (notes.length === 0) return entry.detail
222
+ const note = notes.join(', ')
223
+ return entry.detail ? `${entry.detail}, ${note}` : `${note[0]?.toUpperCase()}${note.slice(1)}`
224
+ }
225
+
176
226
  export class AuditLog {
177
227
  #db: Db
178
228
 
@@ -203,7 +253,7 @@ export class AuditLog {
203
253
  source: entry.source,
204
254
  ip_address: clip(entry.ipAddress, LIMITS.ipAddress),
205
255
  forwarded_for: clip(entry.forwardedFor, LIMITS.forwardedFor),
206
- detail: clip(entry.detail, LIMITS.detail),
256
+ detail: clip(detailInContext(entry), LIMITS.detail),
207
257
  })
208
258
  .execute()
209
259
  }
package/src/cluster.ts CHANGED
@@ -12,13 +12,19 @@ import { sql } from './query.ts'
12
12
  * node has to look at its views tree again. `schema` and `content` invalidate
13
13
  * the published cache; this one makes a node take a new snapshot. `public-files`
14
14
  * is a site's `public/` folder changed by something a watcher cannot see, so a
15
- * node lists it again (story 285).
15
+ * node lists it again (story 285). `extensions` is an extension granted, turned
16
+ * on or off, or removed: each node starts or stops it to match (story 346).
16
17
  */
17
- export type CacheInstructionKind = 'schema' | 'content' | 'components' | 'public-files'
18
+ export type CacheInstructionKind =
19
+ | 'schema'
20
+ | 'content'
21
+ | 'components'
22
+ | 'public-files'
23
+ | 'extensions'
18
24
 
19
- /** Kinds about a site's files, not published content: they move no checkpoint. */
25
+ /** Kinds about a site's files or code, not published content: they move no checkpoint. */
20
26
  const isFileChange = (kind: CacheInstructionKind) =>
21
- kind === 'components' || kind === 'public-files'
27
+ kind === 'components' || kind === 'public-files' || kind === 'extensions'
22
28
 
23
29
  export interface CacheInstruction {
24
30
  id: number
@@ -274,22 +274,34 @@ interface PropertyTarget {
274
274
  storage: ValueStorageTypeName
275
275
  }
276
276
 
277
- /** The documents a query matches, as the scope may see them. */
277
+ /**
278
+ * The documents a query matches, as the scope may see them; with `library`, the
279
+ * Library's elements instead (story 361), placed under its folders.
280
+ */
278
281
  export async function queryDocuments(
279
282
  db: Db,
280
283
  query: ContentQuery,
281
284
  scope: QueryScope,
285
+ options: { library?: boolean } = {},
282
286
  ): Promise<QueryResult> {
283
287
  const run = async (tx: Db) => {
284
288
  if (tx.dialect.name === 'postgres')
285
289
  await tx.exec(`SET LOCAL statement_timeout = ${QUERY_TIMEOUT_MS}`)
286
- return runQuery(tx, query, scope)
290
+ return runQuery(tx, query, scope, options.library === true)
287
291
  }
288
292
  // Postgres's timeout is per transaction; SQLite has none, so the window bounds it.
289
293
  return db.dialect.name === 'postgres' ? db.transaction(run) : run(db)
290
294
  }
291
295
 
292
- async function runQuery(db: Db, query: ContentQuery, scope: QueryScope): Promise<QueryResult> {
296
+ async function runQuery(
297
+ db: Db,
298
+ query: ContentQuery,
299
+ scope: QueryScope,
300
+ library: boolean,
301
+ ): Promise<QueryResult> {
302
+ const objectType = library ? ObjectTypes.Element : ObjectTypes.Document
303
+ /** What `under` and `parent` may name: a page, or an element or its folder. */
304
+ const places = library ? [ObjectTypes.Element, ObjectTypes.ElementContainer] : [objectType]
293
305
  const bool = (value: boolean) => db.dialect.boolValue(value) as boolean
294
306
 
295
307
  // ---- culture
@@ -326,7 +338,7 @@ async function runQuery(db: Db, query: ContentQuery, scope: QueryScope): Promise
326
338
  join.onRef('dcv.node_id', '=', 'n.id').on('dcv.language_id', '=', languageId as number),
327
339
  ),
328
340
  )
329
- .where('n.node_object_type', '=', ObjectTypes.Document)
341
+ .where('n.node_object_type', '=', objectType)
330
342
 
331
343
  // ---- types
332
344
  let typeIds: number[] | undefined
@@ -356,9 +368,12 @@ async function runQuery(db: Db, query: ContentQuery, scope: QueryScope): Promise
356
368
  .selectFrom('node')
357
369
  .select(['id', 'path', 'level'])
358
370
  .where('unique_id', '=', key.toLowerCase())
359
- .where('node_object_type', '=', ObjectTypes.Document)
371
+ .where('node_object_type', 'in', places)
360
372
  .executeTakeFirst()
361
- if (!row) throw new ContentQueryRefused(`"${field}" names no page: ${key}.`)
373
+ if (!row)
374
+ throw new ContentQueryRefused(
375
+ `"${field}" names no ${library ? 'Library folder' : 'page'}: ${key}.`,
376
+ )
362
377
  return { id: Number(row.id), path: String(row.path), level: Number(row.level) }
363
378
  }
364
379
  const under = query.under ? await nodeByKey(query.under, 'under') : undefined
package/src/index.ts CHANGED
@@ -75,6 +75,7 @@ export * from './schema/bundles-disabled.ts'
75
75
  export * from './schema/bundles-in-settings.ts'
76
76
  export * from './schema/bundles-rename.ts'
77
77
  export * from './schema/change-report.ts'
78
+ export * from './schema/cli-tokens.ts'
78
79
  export * from './schema/client-id-prefix.ts'
79
80
  export * from './schema/content.ts'
80
81
  export * from './schema/content-applied.ts'
@@ -118,6 +119,7 @@ export * from './schema/rich-text-ui.ts'
118
119
  export * from './schema/search-index.ts'
119
120
  export * from './schema/search-removals.ts'
120
121
  export * from './schema/seed.ts'
122
+ export * from './schema/session-view-as.ts'
121
123
  export * from './schema/since-version.ts'
122
124
  export * from './schema/site-search.ts'
123
125
  export * from './schema/site-settings-types.ts'
@@ -1566,7 +1566,9 @@ export class DocumentRepository {
1566
1566
  if (!source) return undefined
1567
1567
  if (targetKey) {
1568
1568
  const target = await this.#nodes.byKey(targetKey)
1569
- if (!target || target.objectType !== this.objectType) return undefined
1569
+ const container = KINDS[this.kind].container
1570
+ if (!target || (target.objectType !== this.objectType && target.objectType !== container))
1571
+ return undefined
1570
1572
  }
1571
1573
  const copyOne = async (from: DocumentAggregate, parentKey: string | null): Promise<string> => {
1572
1574
  const siblings = await this.#siblingNames(parentKey)
@@ -111,6 +111,20 @@ export class JobRepository {
111
111
  return row ? rowOf(row) : undefined
112
112
  }
113
113
 
114
+ /** The jobs whose id starts with `prefix`, at most `take` of them, newest first. */
115
+ async byPrefix(prefix: string, take = 10): Promise<JobRow[]> {
116
+ const wanted = prefix.toLowerCase().replace(/[^0-9a-f-]/g, '')
117
+ if (!wanted) return []
118
+ const rows = await this.db.q
119
+ .selectFrom('job')
120
+ .selectAll()
121
+ .where((eb) => eb(eb.cast('id', 'text'), 'like', `${wanted}%`))
122
+ .orderBy('created_at', 'desc')
123
+ .limit(take)
124
+ .execute()
125
+ return rows.map(rowOf)
126
+ }
127
+
114
128
  /** The newest first, for the administrators' view; `owner` and `state` narrow it. */
115
129
  async list(
116
130
  options: { owner?: string; state?: JobState; skip?: number; take?: number } = {},
@@ -582,10 +582,14 @@ export class UserRepository {
582
582
  .execute()
583
583
  }
584
584
 
585
- /** The user's groups' grants, languages and start node positions, for access checks. */
586
- async access(userId: number): Promise<UserAccessData> {
587
- const user = await this.byId(userId)
588
- const groups = user ? await new UserGroupRepository(this.#db).byKeys(user.groupKeys) : []
585
+ /**
586
+ * The user's groups' grants, languages and start node positions, for access
587
+ * checks; the given groups' instead, when they are given (story 314).
588
+ */
589
+ async access(userId: number, groupKeys?: readonly string[]): Promise<UserAccessData> {
590
+ const groups = await new UserGroupRepository(this.#db).byKeys(
591
+ groupKeys ?? (await this.byId(userId))?.groupKeys ?? [],
592
+ )
589
593
  const nodeIds: Record<string, number> = {}
590
594
  for (const group of groups)
591
595
  for (const tree of TREES) {
@@ -0,0 +1,46 @@
1
+ /**
2
+ * Migration 078 — command-line tokens (story 351): each one named, its
3
+ * person's, kept only as a hash, with when it expires, was last used and was
4
+ * revoked. A name is used once per person among those not revoked.
5
+ * Administrators are given `Crombolo.CliTokens.Create` as the seed gives it,
6
+ * through `grantBuiltInPermissions`, as migration 045 gave the media verbs.
7
+ */
8
+ import type { Db } from '../database.ts'
9
+ import type { Migration } from '../migrations.ts'
10
+ import { sql } from '../query.ts'
11
+ import { grantBuiltInPermissions } from './seed.ts'
12
+ import { STATE_SESSION_VIEW_AS } from './session-view-as.ts'
13
+
14
+ export const STATE_CLI_TOKENS = '{3c8e1f57-0078-4d2a-b6e9-1a5f7c3d0078}'
15
+
16
+ export const cliTokensMigration: Migration = {
17
+ from: STATE_SESSION_VIEW_AS,
18
+ to: STATE_CLI_TOKENS,
19
+ name: 'AddCliTokens',
20
+ kind: 'expand',
21
+ release: '0.66.0',
22
+ async up(db: Db) {
23
+ const t = db.dialect.types
24
+ await db.q.schema
25
+ .createTable('cli_token')
26
+ .addColumn('id', sql.raw(t.identity))
27
+ .addColumn('key', sql.raw(t.uuid), (c) => c.notNull().unique())
28
+ .addColumn('user_id', sql.raw(t.integer), (c) => c.notNull())
29
+ .addColumn('name', sql.raw(t.varchar(100)), (c) => c.notNull())
30
+ .addColumn('token_hash', sql.raw(t.varchar(64)), (c) => c.notNull().unique())
31
+ .addColumn('created_at', sql.raw(t.timestamp), (c) => c.notNull())
32
+ .addColumn('expires_at', sql.raw(t.timestamp), (c) => c.notNull())
33
+ .addColumn('last_used_at', sql.raw(t.timestamp))
34
+ .addColumn('revoked_at', sql.raw(t.timestamp))
35
+ .addColumn('revoked_by', sql.raw(t.varchar(64)))
36
+ .execute()
37
+ await db.q.schema
38
+ .createIndex('ux_cli_token_name')
39
+ .unique()
40
+ .on('cli_token')
41
+ .columns(['user_id', 'name'])
42
+ .where(sql.ref('revoked_at'), 'is', null)
43
+ .execute()
44
+ await grantBuiltInPermissions(db)
45
+ },
46
+ }
@@ -28,6 +28,7 @@ import { bundlesDisabledMigration } from './bundles-disabled.ts'
28
28
  import { bundlesInSettingsMigration } from './bundles-in-settings.ts'
29
29
  import { bundlesRenameMigration } from './bundles-rename.ts'
30
30
  import { changeReportMigration } from './change-report.ts'
31
+ import { cliTokensMigration } from './cli-tokens.ts'
31
32
  import { clientIdPrefixMigration } from './client-id-prefix.ts'
32
33
  import { contentMigration } from './content.ts'
33
34
  import { contentAppliedMigration } from './content-applied.ts'
@@ -73,6 +74,7 @@ import { richTextUiMigration } from './rich-text-ui.ts'
73
74
  import { searchIndexMigration } from './search-index.ts'
74
75
  import { searchRemovalsMigration } from './search-removals.ts'
75
76
  import { serverRoleMigration } from './server-role.ts'
77
+ import { sessionViewAsMigration } from './session-view-as.ts'
76
78
  import { sinceVersionMigration } from './since-version.ts'
77
79
  import { siteSearchMigration } from './site-search.ts'
78
80
  import { siteSettingsTypesMigration } from './site-settings-types.ts'
@@ -167,4 +169,6 @@ export const cromboloPlan = new MigrationPlan([
167
169
  userGroupOwnersMigration,
168
170
  prunedPermissionsMigration,
169
171
  userStartNodesDroppedMigration,
172
+ sessionViewAsMigration,
173
+ cliTokensMigration,
170
174
  ])
@@ -4,7 +4,12 @@
4
4
  * Password hashing is injected rather than imported so this package stays free of
5
5
  * a dependency on @crombolo/auth.
6
6
  */
7
- import { EXPLICIT_PERMISSIONS, MediaPermissions, RemotePermissions } from '@crombolo/core'
7
+ import {
8
+ CliTokenPermissions,
9
+ EXPLICIT_PERMISSIONS,
10
+ MediaPermissions,
11
+ RemotePermissions,
12
+ } from '@crombolo/core'
8
13
  import type { Db } from '../database.ts'
9
14
  import { DbDate } from '../dialect.ts'
10
15
 
@@ -64,6 +69,8 @@ export const BUILT_IN_GROUP_PERMISSIONS: Record<string, readonly string[]> = {
64
69
  // Never one a group has to name (story 241): administrators are not given it.
65
70
  ...Object.values(RemotePermissions).filter((verb) => !EXPLICIT_PERMISSIONS.has(verb)),
66
71
  ...MEDIA_FULL,
72
+ // Explicit, so given by name (story 351): taking it away turns tokens off for administrators.
73
+ CliTokenPermissions.Create,
67
74
  ],
68
75
  editor: [
69
76
  'Umb.Document.Create',
@@ -0,0 +1,24 @@
1
+ /**
2
+ * Migration 077 — a back-office session viewing as user groups (story 314):
3
+ * the groups' keys, as JSON, and when the view ends. Both null when the
4
+ * session is its user's own.
5
+ */
6
+ import type { Db } from '../database.ts'
7
+ import type { Migration } from '../migrations.ts'
8
+ import { schemaOps } from '../schema-ops.ts'
9
+ import { STATE_USER_START_NODES_DROPPED } from './user-start-nodes-dropped.ts'
10
+
11
+ export const STATE_SESSION_VIEW_AS = '{7b1d4e62-0077-4a39-9c85-2f6e0d3a0077}'
12
+
13
+ export const sessionViewAsMigration: Migration = {
14
+ from: STATE_USER_START_NODES_DROPPED,
15
+ to: STATE_SESSION_VIEW_AS,
16
+ name: 'AddSessionViewAs',
17
+ kind: 'expand',
18
+ release: '0.65.1',
19
+ async up(db: Db) {
20
+ const t = db.dialect.types
21
+ await schemaOps(db).addColumn('user_login_session', 'view_as_groups', t.text)
22
+ await schemaOps(db).addColumn('user_login_session', 'view_as_until', t.timestamp)
23
+ },
24
+ }
package/src/tables.gen.ts CHANGED
@@ -153,6 +153,18 @@ export interface CoreTables {
153
153
  subject_name: string | null
154
154
  subject_type: string
155
155
  }
156
+ cli_token: {
157
+ created_at: Timestamp
158
+ expires_at: Timestamp
159
+ id: Generated<number>
160
+ key: string
161
+ last_used_at: Timestamp | null
162
+ name: string
163
+ revoked_at: Timestamp | null
164
+ revoked_by: string | null
165
+ token_hash: string
166
+ user_id: number
167
+ }
156
168
  content: {
157
169
  content_type_id: number
158
170
  creator_member_key: string | null
@@ -886,6 +898,8 @@ export interface CoreTables {
886
898
  logged_out_utc: Timestamp | null
887
899
  session_id: string
888
900
  user_id: number
901
+ view_as_groups: string | null
902
+ view_as_until: Timestamp | null
889
903
  }
890
904
  user_notification: {
891
905
  action: string