@crombolo/data 0.37.0 → 0.39.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 (76) hide show
  1. package/package.json +3 -2
  2. package/src/audit.ts +164 -134
  3. package/src/change-report.ts +66 -43
  4. package/src/cluster.ts +119 -59
  5. package/src/content-query.ts +205 -200
  6. package/src/{bundle-tables → custom-tables}/builder.ts +104 -12
  7. package/src/custom-tables/chain.ts +150 -0
  8. package/src/custom-tables/ddl.ts +159 -0
  9. package/src/custom-tables/handle.ts +141 -0
  10. package/src/{bundle-tables → custom-tables}/index.ts +3 -2
  11. package/src/custom-tables/names.ts +94 -0
  12. package/src/custom-tables/owners.ts +299 -0
  13. package/src/{bundle-tables → custom-tables}/schema.ts +263 -90
  14. package/src/custom-tables/values.ts +181 -0
  15. package/src/database.ts +40 -5
  16. package/src/dialect.ts +43 -16
  17. package/src/index.ts +9 -1
  18. package/src/migrations.ts +130 -88
  19. package/src/query.ts +158 -0
  20. package/src/relations.ts +49 -28
  21. package/src/repositories/approvals.ts +130 -89
  22. package/src/repositories/bundle-grants.ts +105 -0
  23. package/src/repositories/bundles.ts +85 -76
  24. package/src/repositories/content-applied.ts +47 -28
  25. package/src/repositories/content-events.ts +114 -67
  26. package/src/repositories/content-notifications.ts +102 -74
  27. package/src/repositories/content-types.ts +449 -320
  28. package/src/repositories/data-types.ts +105 -56
  29. package/src/repositories/delivery-member-tokens.ts +37 -28
  30. package/src/repositories/dictionary.ts +77 -58
  31. package/src/repositories/documents.ts +956 -580
  32. package/src/repositories/domains.ts +28 -16
  33. package/src/repositories/dynamic-roots.ts +32 -17
  34. package/src/repositories/external-logins.ts +38 -24
  35. package/src/repositories/folders.ts +7 -4
  36. package/src/repositories/form-entries.ts +120 -103
  37. package/src/repositories/form-workflows.ts +87 -62
  38. package/src/repositories/jobs.ts +296 -0
  39. package/src/repositories/languages.ts +51 -38
  40. package/src/repositories/log-searches.ts +7 -5
  41. package/src/repositories/media-access.ts +173 -123
  42. package/src/repositories/media-listing.ts +155 -92
  43. package/src/repositories/members.ts +189 -162
  44. package/src/repositories/nodes.ts +227 -181
  45. package/src/repositories/notifications.ts +22 -17
  46. package/src/repositories/public-access.ts +77 -61
  47. package/src/repositories/redirects.ts +113 -70
  48. package/src/repositories/references.ts +55 -44
  49. package/src/repositories/remote-jobs.ts +45 -35
  50. package/src/repositories/tags.ts +11 -10
  51. package/src/repositories/templates.ts +24 -14
  52. package/src/repositories/transfer-answers.ts +58 -50
  53. package/src/repositories/transfer-runs.ts +93 -75
  54. package/src/repositories/two-factor.ts +74 -55
  55. package/src/repositories/user-data.ts +54 -36
  56. package/src/repositories/users.ts +345 -300
  57. package/src/repositories/webhooks.ts +196 -137
  58. package/src/schema/bundle-grants.ts +32 -0
  59. package/src/schema/bundles-disabled.ts +29 -0
  60. package/src/schema/jobs.ts +56 -0
  61. package/src/schema/plan.ts +6 -0
  62. package/src/schema-ops.ts +15 -12
  63. package/src/schema-state.ts +53 -38
  64. package/src/search.ts +175 -129
  65. package/src/setup.ts +17 -13
  66. package/src/site-search.ts +134 -83
  67. package/src/table-types.ts +152 -0
  68. package/src/tables.gen.ts +861 -0
  69. package/src/tree-invariants.ts +21 -12
  70. package/src/url-options.ts +17 -13
  71. package/src/workflow-store.ts +17 -13
  72. package/src/bundle-tables/capability.ts +0 -377
  73. package/src/bundle-tables/chain.ts +0 -105
  74. package/src/bundle-tables/ddl.ts +0 -124
  75. package/src/bundle-tables/guard.ts +0 -116
  76. package/src/bundle-tables/names.ts +0 -58
@@ -0,0 +1,94 @@
1
+ /**
2
+ * The names custom tables live under (story 189): each owner's schema, role and
3
+ * file, and the rules for the names an owner writes. docs/data-model.md,
4
+ * "Custom tables".
5
+ *
6
+ * An owner is the site, or a bundle that declares tables, by its id. On
7
+ * Postgres each owner has a schema of its own, owned by a login-less role whose
8
+ * name is unique to the database (decision 11); on SQLite, a file of its own.
9
+ */
10
+ import { basename, dirname, join } from 'node:path'
11
+
12
+ /** Postgres truncates a longer identifier silently, so a longer one is refused. */
13
+ export const MAX_IDENTIFIER = 63
14
+
15
+ /** The site's own tables are ledgered under this, as a bundle's are under its id. */
16
+ export const SITE_OWNER = 'site'
17
+
18
+ /** Table and column names, as an owner writes them. */
19
+ export const LOGICAL_NAME = /^[a-z][a-z0-9_]*$/
20
+
21
+ const underscored = (id: string): string => id.replaceAll('-', '_')
22
+
23
+ /** The owner's Postgres schema: `site`, or `bundle_<id>` with the id's hyphens as underscores. */
24
+ export function schemaName(owner: string): string {
25
+ return owner === SITE_OWNER ? SITE_OWNER : `bundle_${underscored(owner)}`
26
+ }
27
+
28
+ /** `siteName` as a role name's first part: lowercased, letters and digits, at most 13. */
29
+ export function siteSlug(siteName: string): string {
30
+ const slug = siteName
31
+ .toLowerCase()
32
+ .replace(/[^a-z0-9]+/g, '_')
33
+ .replace(/^_+|_+$/g, '')
34
+ .slice(0, 13)
35
+ .replace(/_+$/, '')
36
+ return slug === '' ? 'site' : slug
37
+ }
38
+
39
+ /** The first 8 hex characters of a hash of the database's name. */
40
+ export function databaseHash(database: string): string {
41
+ return new Bun.CryptoHasher('sha256').update(database).digest('hex').slice(0, 8)
42
+ }
43
+
44
+ /**
45
+ * The owner's role: `{site}_{hash}` for the site, `{site}_{bundle id}_{hash}`
46
+ * for a bundle. At most 62 characters: 13, the longest bundle id (39), 8 and
47
+ * two separators.
48
+ */
49
+ export function roleName(siteName: string, owner: string, database: string): string {
50
+ const parts = [siteSlug(siteName)]
51
+ if (owner !== SITE_OWNER) parts.push(underscored(owner))
52
+ parts.push(databaseHash(database))
53
+ return parts.join('_')
54
+ }
55
+
56
+ /** What a role's comment says, so a role made for another database is never taken. */
57
+ export const roleComment = (database: string): string => `crombolo custom tables for ${database}`
58
+
59
+ /**
60
+ * The owner's SQLite file, beside crombolo's own: `crombolo.sqlite` gives
61
+ * `crombolo.site.sqlite` and `crombolo.bundle.<id>.sqlite`. In memory, in memory.
62
+ */
63
+ export function ownerFile(mainFile: string, owner: string): string {
64
+ if (mainFile === ':memory:') return ':memory:'
65
+ const stem = basename(mainFile).replace(/\.(sqlite3?|db)$/i, '')
66
+ const middle = owner === SITE_OWNER ? SITE_OWNER : `bundle.${owner}`
67
+ return join(dirname(mainFile), `${stem}.${middle}.sqlite`)
68
+ }
69
+
70
+ /**
71
+ * An index's name, generated rather than chosen, from what it covers. The
72
+ * `ix_` it starts with is a namespace a table may not enter, because Postgres
73
+ * keeps a schema's tables and indexes in one.
74
+ */
75
+ export function indexName(table: string, columns: readonly string[]): string {
76
+ const hash = new Bun.CryptoHasher('sha256').update(`${table}(${columns.join(',')})`).digest('hex')
77
+ return `ix_${hash.slice(0, 12)}`
78
+ }
79
+
80
+ /** Why a table or column name is not allowed, or undefined when it is. */
81
+ export function logicalNameProblem(kind: 'table' | 'column', name: string): string | undefined {
82
+ if (typeof name !== 'string' || !LOGICAL_NAME.test(name))
83
+ return `the ${kind} name "${String(name)}" is not lowercase letters, digits and underscores starting with a letter`
84
+ if (kind === 'table' && name.startsWith('ix_'))
85
+ return `the table name "${name}" starts with "ix_", which index names use`
86
+ return lengthProblem(name)
87
+ }
88
+
89
+ /** Why a name is too long for Postgres, or undefined when it fits. */
90
+ export function lengthProblem(name: string): string | undefined {
91
+ return name.length > MAX_IDENTIFIER
92
+ ? `"${name}" is ${name.length} characters, past the ${MAX_IDENTIFIER} Postgres keeps`
93
+ : undefined
94
+ }
@@ -0,0 +1,299 @@
1
+ /**
2
+ * Where an owner's tables live, and the connection that reaches only them
3
+ * (story 189). docs/data-model.md, "Custom tables".
4
+ *
5
+ * - **Postgres:** the owner's schema, owned by a login-less role granted to the
6
+ * CMS's own. Every transaction on the owner's handle begins `SET LOCAL ROLE`,
7
+ * so the role drops back at commit, and the role has no privilege on
8
+ * crombolo's tables or another owner's.
9
+ * - **SQLite:** a file of the owner's own, on a connection of its own, with
10
+ * crombolo's database and the other owners' files never attached.
11
+ */
12
+ import { type Kysely, sql } from 'kysely'
13
+ import { connect, type Db } from '../database.ts'
14
+ import { Locks } from '../locks.ts'
15
+ import { deleteKeyValue, readKeyValue, writeKeyValue } from '../migrations.ts'
16
+ import { queryFor } from '../query.ts'
17
+ import { ownerFile, roleComment, roleName, schemaName } from './names.ts'
18
+
19
+ /** Where one owner's tables are. */
20
+ export interface OwnerPlace {
21
+ /** `site`, or the bundle's id. */
22
+ id: string
23
+ dialect: Db['dialect']['name']
24
+ /** Postgres: the schema and the role that owns it. */
25
+ schema: string
26
+ role?: string
27
+ /** SQLite: the file. */
28
+ file?: string
29
+ }
30
+
31
+ /** What naming an owner's place needs from the site. */
32
+ export interface OwnerSettings {
33
+ siteName: string
34
+ /** crombolo's own SQLite file, which an owner's sits beside. */
35
+ sqliteFile: string
36
+ }
37
+
38
+ const roleKey = (owner: string): string => `Crombolo.Tables.${owner}.Role`
39
+
40
+ /**
41
+ * The CMS may not create the owner's role or schema itself: the SQL for an
42
+ * operator to run once, after which boot checks what it made.
43
+ */
44
+ export class OwnerSetupNeededError extends Error {
45
+ constructor(
46
+ readonly owner: string,
47
+ readonly reason: string,
48
+ readonly statements: string[],
49
+ ) {
50
+ super(
51
+ `The ${owner === 'site' ? "site's own tables" : `bundle "${owner}"'s tables`} need a database role and schema, and ${reason}. ` +
52
+ `Run this once as a role that may, then start again:\n\n${statements.join('\n')}\n`,
53
+ )
54
+ }
55
+ }
56
+
57
+ /** The role exists, made for another database: taking it would share it. */
58
+ export class OwnerRoleTakenError extends Error {
59
+ constructor(
60
+ readonly role: string,
61
+ readonly comment: string | null,
62
+ ) {
63
+ super(
64
+ `The database role "${role}" already exists ${comment ? `("${comment}")` : 'without a crombolo comment'}, and was not made for this database. ` +
65
+ 'Two databases cannot share a role: rename the site, or drop the role if nothing uses it.',
66
+ )
67
+ }
68
+ }
69
+
70
+ /** The schema exists and belongs to a role other than the owner's. */
71
+ export class OwnerSchemaTakenError extends Error {
72
+ constructor(
73
+ readonly schema: string,
74
+ readonly role: string,
75
+ readonly holder: string,
76
+ ) {
77
+ super(
78
+ `The schema "${schema}" already exists and belongs to "${holder}", not "${role}". Move it aside, or give it to "${role}".`,
79
+ )
80
+ }
81
+ }
82
+
83
+ const literal = (value: string): string => `'${value.replaceAll("'", "''")}'`
84
+
85
+ /** The statements that make an owner's role and schema, as an operator would run them. */
86
+ export function ownerSetupStatements(
87
+ db: Db,
88
+ place: { role: string; schema: string },
89
+ database: string,
90
+ grantee: string,
91
+ ): string[] {
92
+ const q = (id: string) => db.dialect.quote(id)
93
+ return [
94
+ `CREATE ROLE ${q(place.role)} NOLOGIN;`,
95
+ `COMMENT ON ROLE ${q(place.role)} IS ${literal(roleComment(database))};`,
96
+ `GRANT ${q(place.role)} TO ${q(grantee)};`,
97
+ `CREATE SCHEMA IF NOT EXISTS ${q(place.schema)} AUTHORIZATION ${q(place.role)};`,
98
+ ]
99
+ }
100
+
101
+ interface Catalogue {
102
+ database: string
103
+ user: string
104
+ mayCreateRoles: boolean
105
+ /** `SET` from 16, where membership alone no longer lets a role be taken. */
106
+ membership: 'SET' | 'MEMBER'
107
+ }
108
+
109
+ /** Postgres's catalogue, which is not crombolo's tables. */
110
+ interface PgCatalogue {
111
+ pg_roles: { oid: number; rolname: string; rolcreaterole: boolean; rolsuper: boolean }
112
+ pg_namespace: { nspname: string; nspowner: number }
113
+ }
114
+
115
+ const catalogueOf = (db: Db) => db.q as unknown as Kysely<PgCatalogue>
116
+
117
+ async function catalogue(db: Db): Promise<Catalogue> {
118
+ const row = await db.q
119
+ .selectNoFrom([
120
+ sql<string>`current_database()`.as('database'),
121
+ sql<string>`current_user`.as('user'),
122
+ sql<number>`current_setting('server_version_num')::int`.as('version'),
123
+ ])
124
+ .executeTakeFirstOrThrow()
125
+ const self = await catalogueOf(db)
126
+ .selectFrom('pg_roles')
127
+ .select(['rolcreaterole', 'rolsuper'])
128
+ .where('rolname', '=', row.user)
129
+ .executeTakeFirst()
130
+ return {
131
+ database: row.database,
132
+ user: row.user,
133
+ mayCreateRoles: self?.rolcreaterole === true || self?.rolsuper === true,
134
+ membership: Number(row.version) >= 160000 ? 'SET' : 'MEMBER',
135
+ }
136
+ }
137
+
138
+ async function roleOf(db: Db, role: string) {
139
+ return catalogueOf(db)
140
+ .selectFrom('pg_roles')
141
+ .select(['rolname', sql<string | null>`shobj_description(oid, 'pg_authid')`.as('comment')])
142
+ .where('rolname', '=', role)
143
+ .executeTakeFirst()
144
+ }
145
+
146
+ async function schemaHolder(db: Db, schema: string): Promise<string | undefined> {
147
+ const row = await catalogueOf(db)
148
+ .selectFrom('pg_namespace')
149
+ .select(sql<string>`nspowner::regrole::text`.as('holder'))
150
+ .where('nspname', '=', schema)
151
+ .executeTakeFirst()
152
+ return row ? String(row.holder).replace(/^"|"$/g, '') : undefined
153
+ }
154
+
155
+ /**
156
+ * Makes sure the owner's place exists and is the owner's, creating what the CMS
157
+ * may, and records its role's name so renaming the site moves nothing.
158
+ */
159
+ export async function provisionOwner(
160
+ db: Db,
161
+ settings: OwnerSettings,
162
+ owner: string,
163
+ ): Promise<OwnerPlace> {
164
+ const schema = schemaName(owner)
165
+ if (db.dialect.name === 'sqlite')
166
+ return { id: owner, dialect: 'sqlite', schema, file: ownerFile(settings.sqliteFile, owner) }
167
+
168
+ return db.locks.withLock(Locks.KeyValues, async () => {
169
+ const found = await catalogue(db)
170
+ const role =
171
+ (await readKeyValue(db, roleKey(owner))) ?? roleName(settings.siteName, owner, found.database)
172
+ const place = { role, schema }
173
+ const statements = ownerSetupStatements(db, place, found.database, found.user)
174
+ const q = (id: string) => db.dialect.quote(id)
175
+ const k = queryFor(db)
176
+
177
+ const existing = await roleOf(db, role)
178
+ if (existing && existing.comment !== roleComment(found.database))
179
+ throw new OwnerRoleTakenError(role, existing.comment)
180
+ if (!existing) {
181
+ if (!found.mayCreateRoles)
182
+ throw new OwnerSetupNeededError(
183
+ owner,
184
+ 'this database user may not create roles',
185
+ statements,
186
+ )
187
+ await sql.raw(`CREATE ROLE ${q(role)} NOLOGIN`).execute(k)
188
+ await sql
189
+ .raw(`COMMENT ON ROLE ${q(role)} IS ${literal(roleComment(found.database))}`)
190
+ .execute(k)
191
+ }
192
+ const member = await k
193
+ .selectNoFrom(
194
+ sql<boolean>`pg_has_role(current_user, ${role}, ${found.membership})`.as('member'),
195
+ )
196
+ .executeTakeFirstOrThrow()
197
+ if (!member.member) {
198
+ if (!found.mayCreateRoles)
199
+ throw new OwnerSetupNeededError(
200
+ owner,
201
+ `"${found.user}" is not granted its role`,
202
+ statements,
203
+ )
204
+ await sql.raw(`GRANT ${q(role)} TO ${q(found.user)}`).execute(k)
205
+ }
206
+
207
+ const holder = await schemaHolder(db, schema)
208
+ if (holder === undefined) {
209
+ try {
210
+ await sql.raw(`CREATE SCHEMA ${q(schema)} AUTHORIZATION ${q(role)}`).execute(k)
211
+ } catch (error) {
212
+ throw new OwnerSetupNeededError(
213
+ owner,
214
+ `the schema could not be created (${error instanceof Error ? error.message : String(error)})`,
215
+ statements,
216
+ )
217
+ }
218
+ } else if (holder !== role) throw new OwnerSchemaTakenError(schema, role, holder)
219
+
220
+ await writeKeyValue(db, roleKey(owner), role)
221
+ return { id: owner, dialect: 'postgres', schema, role }
222
+ })
223
+ }
224
+
225
+ /** An owner's place as recorded, for a node that does not provision: undefined when it never was. */
226
+ export async function recordedOwner(
227
+ db: Db,
228
+ settings: OwnerSettings,
229
+ owner: string,
230
+ ): Promise<OwnerPlace | undefined> {
231
+ const schema = schemaName(owner)
232
+ if (db.dialect.name === 'sqlite')
233
+ return { id: owner, dialect: 'sqlite', schema, file: ownerFile(settings.sqliteFile, owner) }
234
+ const role = await readKeyValue(db, roleKey(owner))
235
+ return role ? { id: owner, dialect: 'postgres', schema, role } : undefined
236
+ }
237
+
238
+ /** Forgets an owner's recorded role, once its schema is gone. */
239
+ export async function forgetOwner(db: Db, owner: string): Promise<void> {
240
+ await deleteKeyValue(db, roleKey(owner))
241
+ }
242
+
243
+ const memory = new WeakMap<Db, Map<string, Db>>()
244
+
245
+ /**
246
+ * The connection that reaches only the owner's tables. On SQLite in memory the
247
+ * owner's database lives as long as crombolo's, so it is kept per handle.
248
+ */
249
+ export async function openOwner(db: Db, place: OwnerPlace): Promise<Db> {
250
+ if (db.dialect.name === 'postgres') {
251
+ if (!db.confine || !place.role) throw new Error(`No role is recorded for "${place.id}".`)
252
+ return db.confine(place.role, place.schema)
253
+ }
254
+ const file = place.file ?? ':memory:'
255
+ if (file !== ':memory:') return connect({ dialect: 'sqlite', file })
256
+ let owners = memory.get(db)
257
+ if (!owners) {
258
+ owners = new Map()
259
+ memory.set(db, owners)
260
+ }
261
+ let owned = owners.get(place.id)
262
+ if (!owned) {
263
+ owned = await connect({ dialect: 'sqlite', file: ':memory:' })
264
+ owners.set(place.id, owned)
265
+ }
266
+ return owned
267
+ }
268
+
269
+ /**
270
+ * Runs `fn` against the owner's tables, as part of `main`'s transaction where
271
+ * the engine allows: on Postgres the transaction takes the owner's role and
272
+ * search path for `fn` and gives them back, so a step and its ledger row commit
273
+ * together. A SQLite file has a transaction of its own, committed just before
274
+ * crombolo's.
275
+ */
276
+ export async function asOwner<T>(
277
+ main: Db,
278
+ place: OwnerPlace,
279
+ owned: Db | undefined,
280
+ fn: (db: Db) => Promise<T>,
281
+ ): Promise<T> {
282
+ if (main.dialect.name === 'sqlite') {
283
+ if (!owned) throw new Error(`No connection is open to "${place.id}"'s tables.`)
284
+ return owned.transaction(fn)
285
+ }
286
+ if (!place.role) throw new Error(`No role is recorded for "${place.id}".`)
287
+ const k = queryFor(main)
288
+ const { path } = await k
289
+ .selectNoFrom(sql<string>`current_setting('search_path')`.as('path'))
290
+ .executeTakeFirstOrThrow()
291
+ const q = (id: string) => main.dialect.quote(id)
292
+ await main.exec(`SET LOCAL ROLE ${q(place.role)}`)
293
+ await main.exec(`SET LOCAL search_path TO ${q(place.schema)}`)
294
+ // On a failure the transaction is rolled back, role and path with it.
295
+ const result = await fn(main)
296
+ await main.exec('SET LOCAL ROLE NONE')
297
+ await k.selectNoFrom(sql`set_config('search_path', ${path}, true)`.as('set')).execute()
298
+ return result
299
+ }