@crombolo/data 0.43.1 → 0.44.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.43.1",
3
+ "version": "0.44.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",
@@ -28,7 +28,7 @@
28
28
  "access": "public"
29
29
  },
30
30
  "dependencies": {
31
- "@crombolo/core": "0.43.1",
31
+ "@crombolo/core": "0.44.0",
32
32
  "kysely": "0.29.6"
33
33
  }
34
34
  }
package/src/index.ts CHANGED
@@ -44,6 +44,7 @@ export * from './repositories/public-access.ts'
44
44
  export * from './repositories/redirects.ts'
45
45
  export * from './repositories/references.ts'
46
46
  export * from './repositories/remote-jobs.ts'
47
+ export * from './repositories/remote-trust.ts'
47
48
  export * from './repositories/tags.ts'
48
49
  export * from './repositories/templates.ts'
49
50
  export * from './repositories/transfer-answers.ts'
@@ -63,6 +64,7 @@ export * from './schema/bundle-grants.ts'
63
64
  export * from './schema/bundle-package.ts'
64
65
  export * from './schema/bundle-schema-picks.ts'
65
66
  export * from './schema/bundles-disabled.ts'
67
+ export * from './schema/bundles-in-settings.ts'
66
68
  export * from './schema/bundles-rename.ts'
67
69
  export * from './schema/change-report.ts'
68
70
  export * from './schema/client-id-prefix.ts'
@@ -77,6 +79,8 @@ export * from './schema/delivery-member-tokens.ts'
77
79
  export * from './schema/diagnostics.ts'
78
80
  export * from './schema/drop-assistant.ts'
79
81
  export * from './schema/elements.ts'
82
+ export * from './schema/form-library.ts'
83
+ export * from './schema/form-library-types.ts'
80
84
  export * from './schema/form-permission-prefix.ts'
81
85
  export * from './schema/group-permissions.ts'
82
86
  export * from './schema/identity.ts'
@@ -94,6 +98,7 @@ export * from './schema/property-searchable.ts'
94
98
  export * from './schema/public-access.ts'
95
99
  export * from './schema/recycle-bin.ts'
96
100
  export * from './schema/remote.ts'
101
+ export * from './schema/remote-trust.ts'
97
102
  export * from './schema/rich-text-ui.ts'
98
103
  export * from './schema/search-index.ts'
99
104
  export * from './schema/seed.ts'
@@ -374,6 +374,12 @@ export class ContentTypeRepository {
374
374
  .set({ site_settings: bool(aggregate.siteSettings) })
375
375
  .where('node_id', '=', nodeId)
376
376
  .execute()
377
+ if (aggregate.formKey !== undefined)
378
+ await tx.q
379
+ .updateTable('content_type')
380
+ .set({ form_key: aggregate.formKey })
381
+ .where('node_id', '=', nodeId)
382
+ .execute()
377
383
 
378
384
  // ---- groups: upsert by key
379
385
  const groupIdByKey = new Map<string, number>()
@@ -925,6 +931,7 @@ export class ContentTypeRepository {
925
931
  'ct.since_version',
926
932
  'ct.site_search',
927
933
  'ct.site_settings',
934
+ 'ct.form_key',
928
935
  'ss.version as since_v',
929
936
  'ss.revision as since_r',
930
937
  ])
@@ -1056,6 +1063,7 @@ export class ContentTypeRepository {
1056
1063
  allowedInLibrary: fromDbBool(type.allow_in_library),
1057
1064
  siteSearch: fromDbBool(type.site_search),
1058
1065
  siteSettings: fromDbBool(type.site_settings),
1066
+ formKey: (type.form_key as string | null) ?? null,
1059
1067
  collectionKey: type.list_view ? normaliseUuid(String(type.list_view)) : null,
1060
1068
  cleanup: {
1061
1069
  preventCleanup: fromDbBool(type.prevent_cleanup),
@@ -40,6 +40,8 @@ export interface FormEntry {
40
40
  culture: string | null
41
41
  /** The page the form was submitted from, when it was on one. */
42
42
  pageKey: string | null
43
+ /** The Library form it came through (story 239); null for a form picked directly. */
44
+ libraryKey: string | null
43
45
  /** A salted hash, never an address: enough to rate-limit, not a liability. */
44
46
  ipHash: string | null
45
47
  userAgent: string | null
@@ -51,14 +53,17 @@ export interface FormEntry {
51
53
 
52
54
  export type FormEntryInput = Omit<
53
55
  FormEntry,
54
- 'id' | 'createDate' | 'updateDate' | 'state' | 'spam'
56
+ 'id' | 'createDate' | 'updateDate' | 'state' | 'spam' | 'libraryKey'
55
57
  > & {
56
58
  state?: FormEntryState
57
59
  spam?: boolean
60
+ libraryKey?: string | null
58
61
  }
59
62
 
60
63
  export interface FormEntryQuery {
61
64
  formKey: string
65
+ /** Only the entries that came through this Library form; `null` for those that came through none. */
66
+ libraryKey?: string | null
62
67
  state?: FormEntryState
63
68
  /** Inclusive; the entries view defaults to the last month. */
64
69
  from?: Date
@@ -77,6 +82,7 @@ interface EntryRow {
77
82
  state: string
78
83
  culture: string | null
79
84
  page_key: string | null
85
+ library_key: string | null
80
86
  ip_hash: string | null
81
87
  user_agent: string | null
82
88
  spam: unknown
@@ -99,6 +105,7 @@ const COLUMNS = [
99
105
  'state',
100
106
  'culture',
101
107
  'page_key',
108
+ 'library_key',
102
109
  'ip_hash',
103
110
  'user_agent',
104
111
  'spam',
@@ -116,6 +123,7 @@ const hydrate = (row: EntryRow, values: FormEntryValue[]): FormEntry => ({
116
123
  state: state(row.state),
117
124
  culture: row.culture,
118
125
  pageKey: row.page_key,
126
+ libraryKey: row.library_key,
119
127
  ipHash: row.ip_hash,
120
128
  userAgent: row.user_agent,
121
129
  spam: fromDbBool(row.spam),
@@ -182,6 +190,11 @@ export class FormEntryRepository {
182
190
  const matching = this.#db.q
183
191
  .selectFrom('form_entry')
184
192
  .where('form_key', '=', query.formKey)
193
+ .$if(query.libraryKey !== undefined, (q) =>
194
+ query.libraryKey === null
195
+ ? q.where('library_key', 'is', null)
196
+ : q.where('library_key', '=', query.libraryKey as string),
197
+ )
185
198
  .$if(Boolean(query.state), (q) => q.where('state', '=', query.state as FormEntryState))
186
199
  .$if(Boolean(query.from), (q) =>
187
200
  q.where('create_date', '>=', DbDate.toDb(query.from as Date)),
@@ -242,6 +255,7 @@ export class FormEntryRepository {
242
255
  state: input.state ?? 'submitted',
243
256
  culture: input.culture,
244
257
  page_key: input.pageKey,
258
+ library_key: input.libraryKey ?? null,
245
259
  ip_hash: input.ipHash,
246
260
  user_agent: input.userAgent,
247
261
  spam: this.#db.dialect.boolValue(input.spam ?? false),
@@ -23,6 +23,11 @@ export interface FormWorkflowRun {
23
23
  entryId: string | null
24
24
  /** The submitted values, as the workflow needs them. */
25
25
  payload: { fieldAlias: string; values: string[]; labels?: string[] }[]
26
+ /**
27
+ * Who to e-mail in place of a send-e-mail workflow's `to`: a Library form's
28
+ * recipients when it was queued (story 239). Kept in the payload's column.
29
+ */
30
+ recipients?: string[]
26
31
  state: FormWorkflowState
27
32
  attempts: number
28
33
  lastError: string | null
@@ -34,7 +39,7 @@ export interface FormWorkflowRun {
34
39
  export type FormWorkflowEnqueue = Pick<
35
40
  FormWorkflowRun,
36
41
  'formKey' | 'formAlias' | 'workflowName' | 'workflowType' | 'runOn' | 'entryId' | 'payload'
37
- >
42
+ > & { recipients?: string[] }
38
43
 
39
44
  interface Row {
40
45
  id: string
@@ -72,13 +77,22 @@ const COLUMNS = [
72
77
 
73
78
  const STATES: readonly FormWorkflowState[] = ['pending', 'running', 'done', 'failed']
74
79
 
75
- const payloadOf = (value: string): FormWorkflowRun['payload'] => {
80
+ /** The column: the values alone, or with recipients as `{ values, recipients }`. */
81
+ const payloadOf = (value: string): Pick<FormWorkflowRun, 'payload' | 'recipients'> => {
76
82
  try {
77
83
  const parsed = JSON.parse(value) as unknown
78
- return Array.isArray(parsed) ? (parsed as FormWorkflowRun['payload']) : []
84
+ if (Array.isArray(parsed)) return { payload: parsed as FormWorkflowRun['payload'] }
85
+ const wrapped = parsed as { values?: unknown; recipients?: unknown } | null
86
+ const values = Array.isArray(wrapped?.values)
87
+ ? (wrapped.values as FormWorkflowRun['payload'])
88
+ : []
89
+ const recipients = Array.isArray(wrapped?.recipients)
90
+ ? wrapped.recipients.filter((r): r is string => typeof r === 'string')
91
+ : undefined
92
+ return recipients ? { payload: values, recipients } : { payload: values }
79
93
  } catch {
80
94
  // A row edited by hand should still be visible and still be deletable.
81
- return []
95
+ return { payload: [] }
82
96
  }
83
97
  }
84
98
 
@@ -90,7 +104,7 @@ const hydrate = (row: Row): FormWorkflowRun => ({
90
104
  workflowType: row.workflow_type,
91
105
  runOn: row.run_on,
92
106
  entryId: row.entry_id,
93
- payload: payloadOf(row.payload),
107
+ ...payloadOf(row.payload),
94
108
  state: STATES.includes(row.state as FormWorkflowState)
95
109
  ? (row.state as FormWorkflowState)
96
110
  : 'pending',
@@ -122,7 +136,9 @@ export class FormWorkflowRepository {
122
136
  workflow_type: run.workflowType,
123
137
  run_on: run.runOn,
124
138
  entry_id: run.entryId,
125
- payload: JSON.stringify(run.payload),
139
+ payload: JSON.stringify(
140
+ run.recipients ? { values: run.payload, recipients: run.recipients } : run.payload,
141
+ ),
126
142
  state: 'pending',
127
143
  attempts: 0,
128
144
  last_error: null,
@@ -0,0 +1,267 @@
1
+ /**
2
+ * Trust rules and CI tokens (story 160): which CI identities may act on this
3
+ * site, and the short-lived tokens an accepted identity is given. A token is
4
+ * kept only as its hash, and goes with its rule: a disabled or deleted rule's
5
+ * tokens stop working at once. docs/remote-protocol.md, "Signing in from CI".
6
+ */
7
+ import { createHash, randomBytes, randomUUID } from 'node:crypto'
8
+ import type { Db } from '../database.ts'
9
+ import { DbDate } from '../dialect.ts'
10
+
11
+ /** What a rule matches beside the repository: a branch, a tag, or a CI environment. */
12
+ export type TrustRefKind = 'branch' | 'tag' | 'environment'
13
+
14
+ export interface TrustRule {
15
+ key: string
16
+ name: string
17
+ /** The identity token's `iss`, exactly. */
18
+ issuer: string
19
+ /** GitHub's `owner/repo`, GitLab's `group/project`. */
20
+ repository: string
21
+ refKind: TrustRefKind
22
+ refValue: string
23
+ /** Remote permission verbs, and nothing else. */
24
+ permissions: string[]
25
+ disabled: boolean
26
+ createdBy: string | null
27
+ createDate: Date
28
+ updateDate: Date
29
+ lastUsedDate: Date | null
30
+ }
31
+
32
+ export type TrustRuleInput = Pick<
33
+ TrustRule,
34
+ 'name' | 'issuer' | 'repository' | 'refKind' | 'refValue' | 'permissions'
35
+ >
36
+
37
+ /** A CI token, as a request presenting it resolves to. */
38
+ export interface CiToken {
39
+ rule: TrustRule
40
+ /** The identity token's claims that say where the run was: repository, ref, run. */
41
+ claims: Record<string, string>
42
+ expiresAt: Date
43
+ }
44
+
45
+ const listOf = (value: unknown): string[] => {
46
+ try {
47
+ const parsed = JSON.parse(String(value)) as unknown
48
+ return Array.isArray(parsed) ? parsed.filter((p): p is string => typeof p === 'string') : []
49
+ } catch {
50
+ return []
51
+ }
52
+ }
53
+
54
+ const recordOf = (value: unknown): Record<string, string> => {
55
+ try {
56
+ const parsed = JSON.parse(String(value)) as unknown
57
+ return parsed && typeof parsed === 'object'
58
+ ? Object.fromEntries(
59
+ Object.entries(parsed).filter((e): e is [string, string] => typeof e[1] === 'string'),
60
+ )
61
+ : {}
62
+ } catch {
63
+ return {}
64
+ }
65
+ }
66
+
67
+ export const hashCiToken = (token: string): string =>
68
+ createHash('sha256').update(token).digest('hex')
69
+
70
+ interface RuleRow {
71
+ key: string
72
+ name: string
73
+ issuer: string
74
+ repository: string
75
+ ref_kind: string
76
+ ref_value: string
77
+ permissions: unknown
78
+ disabled_at: unknown
79
+ created_by: string | null
80
+ create_date: unknown
81
+ update_date: unknown
82
+ last_used_date: unknown
83
+ }
84
+
85
+ const ruleOf = (row: RuleRow): TrustRule => ({
86
+ key: row.key,
87
+ name: row.name,
88
+ issuer: row.issuer,
89
+ repository: row.repository,
90
+ refKind: (['branch', 'tag', 'environment'].includes(row.ref_kind)
91
+ ? row.ref_kind
92
+ : 'branch') as TrustRefKind,
93
+ refValue: row.ref_value,
94
+ permissions: listOf(row.permissions),
95
+ disabled: row.disabled_at !== null && row.disabled_at !== undefined,
96
+ createdBy: row.created_by,
97
+ createDate: DbDate.fromDb(row.create_date) ?? new Date(0),
98
+ updateDate: DbDate.fromDb(row.update_date) ?? new Date(0),
99
+ lastUsedDate: DbDate.fromDb(row.last_used_date) ?? null,
100
+ })
101
+
102
+ export class RemoteTrustRepository {
103
+ constructor(private readonly db: Db) {}
104
+
105
+ async all(): Promise<TrustRule[]> {
106
+ const rows = await this.db.q
107
+ .selectFrom('remote_trust_rule')
108
+ .selectAll()
109
+ .orderBy('name')
110
+ .execute()
111
+ return rows.map(ruleOf)
112
+ }
113
+
114
+ async byKey(key: string): Promise<TrustRule | undefined> {
115
+ const row = await this.db.q
116
+ .selectFrom('remote_trust_rule')
117
+ .selectAll()
118
+ .where('key', '=', key)
119
+ .executeTakeFirst()
120
+ return row ? ruleOf(row) : undefined
121
+ }
122
+
123
+ /** The live rules for one issuer, which is all a token from it can match. */
124
+ async liveFor(issuer: string): Promise<TrustRule[]> {
125
+ const rows = await this.db.q
126
+ .selectFrom('remote_trust_rule')
127
+ .selectAll()
128
+ .where('issuer', '=', issuer)
129
+ .where('disabled_at', 'is', null)
130
+ .execute()
131
+ return rows.map(ruleOf)
132
+ }
133
+
134
+ async create(input: TrustRuleInput, by: string | null): Promise<TrustRule> {
135
+ const key = randomUUID()
136
+ const now = DbDate.toDb(new Date())
137
+ await this.db.q
138
+ .insertInto('remote_trust_rule')
139
+ .values({
140
+ key,
141
+ name: input.name,
142
+ issuer: input.issuer,
143
+ repository: input.repository,
144
+ ref_kind: input.refKind,
145
+ ref_value: input.refValue,
146
+ permissions: JSON.stringify(input.permissions),
147
+ disabled_at: null,
148
+ created_by: by,
149
+ create_date: now,
150
+ update_date: now,
151
+ last_used_date: null,
152
+ })
153
+ .execute()
154
+ return (await this.byKey(key)) as TrustRule
155
+ }
156
+
157
+ async update(key: string, input: TrustRuleInput): Promise<TrustRule | undefined> {
158
+ await this.db.q
159
+ .updateTable('remote_trust_rule')
160
+ .set({
161
+ name: input.name,
162
+ issuer: input.issuer,
163
+ repository: input.repository,
164
+ ref_kind: input.refKind,
165
+ ref_value: input.refValue,
166
+ permissions: JSON.stringify(input.permissions),
167
+ update_date: DbDate.toDb(new Date()),
168
+ })
169
+ .where('key', '=', key)
170
+ .execute()
171
+ // What it was trusted for has changed, so what it was given goes.
172
+ await this.revokeTokens(key)
173
+ return this.byKey(key)
174
+ }
175
+
176
+ async setDisabled(key: string, disabled: boolean): Promise<TrustRule | undefined> {
177
+ await this.db.q
178
+ .updateTable('remote_trust_rule')
179
+ .set({
180
+ disabled_at: disabled ? DbDate.toDb(new Date()) : null,
181
+ update_date: DbDate.toDb(new Date()),
182
+ })
183
+ .where('key', '=', key)
184
+ .execute()
185
+ if (disabled) await this.revokeTokens(key)
186
+ return this.byKey(key)
187
+ }
188
+
189
+ async remove(key: string): Promise<boolean> {
190
+ await this.revokeTokens(key)
191
+ const result = await this.db.q
192
+ .deleteFrom('remote_trust_rule')
193
+ .where('key', '=', key)
194
+ .executeTakeFirst()
195
+ return Number(result.numDeletedRows) > 0
196
+ }
197
+
198
+ async revokeTokens(ruleKey: string): Promise<void> {
199
+ await this.db.q.deleteFrom('remote_ci_token').where('rule_key', '=', ruleKey).execute()
200
+ }
201
+
202
+ /**
203
+ * A token for an accepted identity token, or undefined when its `jti` was
204
+ * already exchanged: an identity token is good once.
205
+ */
206
+ async issue(
207
+ rule: TrustRule,
208
+ identity: { issuer: string; jti: string; claims: Record<string, string> },
209
+ seconds: number,
210
+ ): Promise<{ token: string; expiresAt: Date } | undefined> {
211
+ const now = new Date()
212
+ // A spent token's row outlives it by its jti only as long as the identity
213
+ // token could still be valid, so old rows are swept as new ones arrive.
214
+ await this.db.q
215
+ .deleteFrom('remote_ci_token')
216
+ .where('expires_at', '<', DbDate.toDb(new Date(now.getTime() - 2 * 60 * 60 * 1000)))
217
+ .execute()
218
+ const seen = await this.db.q
219
+ .selectFrom('remote_ci_token')
220
+ .select('token_hash')
221
+ .where('issuer', '=', identity.issuer)
222
+ .where('jti', '=', identity.jti)
223
+ .executeTakeFirst()
224
+ if (seen) return undefined
225
+ const token = `crci_${randomBytes(32).toString('base64url')}`
226
+ const expiresAt = new Date(now.getTime() + seconds * 1000)
227
+ try {
228
+ await this.db.q
229
+ .insertInto('remote_ci_token')
230
+ .values({
231
+ token_hash: hashCiToken(token),
232
+ rule_key: rule.key,
233
+ issuer: identity.issuer,
234
+ jti: identity.jti,
235
+ claims: JSON.stringify(identity.claims),
236
+ expires_at: DbDate.toDb(expiresAt),
237
+ create_date: DbDate.toDb(now),
238
+ })
239
+ .execute()
240
+ } catch {
241
+ // Two exchanges of one identity token at once: the unique index lets one in.
242
+ return undefined
243
+ }
244
+ await this.db.q
245
+ .updateTable('remote_trust_rule')
246
+ .set({ last_used_date: DbDate.toDb(now) })
247
+ .where('key', '=', rule.key)
248
+ .execute()
249
+ return { token, expiresAt }
250
+ }
251
+
252
+ /** What a presented token is, while it is current and its rule live. */
253
+ async resolve(token: string): Promise<CiToken | undefined> {
254
+ if (!token.startsWith('crci_')) return undefined
255
+ const row = await this.db.q
256
+ .selectFrom('remote_ci_token')
257
+ .selectAll()
258
+ .where('token_hash', '=', hashCiToken(token))
259
+ .executeTakeFirst()
260
+ if (!row) return undefined
261
+ const expiresAt = DbDate.fromDb(row.expires_at) ?? new Date(0)
262
+ if (expiresAt.getTime() <= Date.now()) return undefined
263
+ const rule = await this.byKey(row.rule_key)
264
+ if (!rule || rule.disabled) return undefined
265
+ return { rule, claims: recordOf(row.claims), expiresAt }
266
+ }
267
+ }
@@ -0,0 +1,20 @@
1
+ /**
2
+ * Migration 060: Bundles is a Settings tool (story 238), so no group keeps the
3
+ * Packages section that held it. Whoever has Settings has Bundles.
4
+ */
5
+ import type { Db } from '../database.ts'
6
+ import type { Migration } from '../migrations.ts'
7
+ import { STATE_FORM_LIBRARY } from './form-library.ts'
8
+
9
+ export const STATE_BUNDLES_IN_SETTINGS = '{4b198f00-0060-4ca8-bc39-97d92fca0060}'
10
+
11
+ export const bundlesInSettingsMigration: Migration = {
12
+ from: STATE_FORM_LIBRARY,
13
+ to: STATE_BUNDLES_IN_SETTINGS,
14
+ name: 'MoveBundlesIntoSettings',
15
+ kind: 'expand',
16
+ release: '0.44.0',
17
+ async up(db: Db) {
18
+ await db.q.deleteFrom('user_group_section').where('app_alias', '=', 'packages').execute()
19
+ },
20
+ }
@@ -0,0 +1,188 @@
1
+ /**
2
+ * The element types made from forms (story 239): one per form, allowed in the
3
+ * Library, in a "Forms" folder. Derived from the forms, never from a file of
4
+ * their own, so they are kept here rather than by the schema sync.
5
+ *
6
+ * A form removed retires its type when no Library form uses it; one still in
7
+ * use stays, so its Library forms survive and show as using a missing form.
8
+ */
9
+ import {
10
+ type ContentTypeAggregate,
11
+ LIBRARY_FORM_PROPERTIES,
12
+ libraryFormId,
13
+ libraryFormPropertyKey,
14
+ libraryFormTypeAlias,
15
+ libraryFormTypeKey,
16
+ ObjectTypes,
17
+ type SchemaForm,
18
+ } from '@crombolo/core'
19
+ import type { Db } from '../database.ts'
20
+ import { DbDate, fromDbBool } from '../dialect.ts'
21
+ import { ContentTypeRepository } from '../repositories/content-types.ts'
22
+ import { DataTypeRepository } from '../repositories/data-types.ts'
23
+ import { FolderRepository } from '../repositories/folders.ts'
24
+
25
+ export const FORM_LIBRARY_FOLDER = 'Forms'
26
+
27
+ export interface FormLibraryTypesReport {
28
+ created: string[]
29
+ updated: string[]
30
+ retired: string[]
31
+ /** A form whose type's alias another type already has. */
32
+ clashes: string[]
33
+ }
34
+
35
+ type FormLike = Pick<SchemaForm, 'key' | 'alias' | 'name'>
36
+
37
+ function aggregateFor(
38
+ form: FormLike,
39
+ dataTypeKeys: Map<string, string>,
40
+ parentKey: string | null,
41
+ ): ContentTypeAggregate {
42
+ const formKey = libraryFormId(form)
43
+ const key = libraryFormTypeKey(formKey)
44
+ const tabKey = libraryFormPropertyKey(key, '#tab')
45
+ return {
46
+ key,
47
+ alias: libraryFormTypeAlias(form),
48
+ name: form.name,
49
+ description: `Made from the ${form.name} form.`,
50
+ icon: 'icon-inbox',
51
+ allowedAsRoot: false,
52
+ variesByCulture: false,
53
+ variesBySegment: false,
54
+ isElement: true,
55
+ allowedInLibrary: true,
56
+ collectionKey: null,
57
+ cleanup: {
58
+ preventCleanup: false,
59
+ keepAllVersionsNewerThanDays: null,
60
+ keepLatestVersionPerDayForDays: null,
61
+ },
62
+ containers: [
63
+ { key: tabKey, name: 'Form', alias: 'form', type: 'Tab', sortOrder: 0, parentKey: null },
64
+ ],
65
+ properties: LIBRARY_FORM_PROPERTIES.map((p, sortOrder) => ({
66
+ key: libraryFormPropertyKey(key, p.alias),
67
+ alias: p.alias,
68
+ name: p.name,
69
+ description: p.description,
70
+ dataTypeKey: dataTypeKeys.get(p.dataType) ?? '',
71
+ containerKey: tabKey,
72
+ sortOrder,
73
+ variesByCulture: false,
74
+ variesBySegment: false,
75
+ mandatory: false,
76
+ mandatoryMessage: null,
77
+ regEx: null,
78
+ regExMessage: null,
79
+ labelOnTop: false,
80
+ })),
81
+ compositions: [],
82
+ allowedContentTypes: [],
83
+ allowedComponentKeys: [],
84
+ defaultComponentKey: null,
85
+ parentKey,
86
+ formKey,
87
+ }
88
+ }
89
+
90
+ /** What a saved type would change: its name, alias, folder or fields. */
91
+ const differs = (a: ContentTypeAggregate, b: ContentTypeAggregate): boolean =>
92
+ a.name !== b.name ||
93
+ a.alias !== b.alias ||
94
+ a.parentKey !== b.parentKey ||
95
+ a.formKey !== b.formKey ||
96
+ a.properties.length !== b.properties.length ||
97
+ a.properties.some((p, i) => {
98
+ const q = b.properties[i]
99
+ return !q || q.key !== p.key || q.name !== p.name || q.dataTypeKey !== p.dataTypeKey
100
+ })
101
+
102
+ /** Brings the types made from forms in line with `forms`. Idempotent. */
103
+ export async function ensureFormLibraryTypes(
104
+ db: Db,
105
+ forms: readonly FormLike[],
106
+ ): Promise<FormLibraryTypesReport> {
107
+ const report: FormLibraryTypesReport = { created: [], updated: [], retired: [], clashes: [] }
108
+ const types = new ContentTypeRepository(db, { kind: 'document' })
109
+ const dataTypes = new DataTypeRepository(db)
110
+ const dataTypeKeys = new Map<string, string>()
111
+ for (const { dataType } of LIBRARY_FORM_PROPERTIES) {
112
+ const found = await dataTypes.byAlias(dataType)
113
+ if (found) dataTypeKeys.set(dataType, found.key)
114
+ }
115
+ const folders = new FolderRepository(
116
+ db,
117
+ ObjectTypes.DocumentTypeContainer,
118
+ ObjectTypes.DocumentType,
119
+ )
120
+ const parentKey = forms.length > 0 ? await folders.ensurePath([FORM_LIBRARY_FOLDER]) : null
121
+
122
+ const wanted = new Set<string>()
123
+ for (const form of forms) {
124
+ const aggregate = aggregateFor(form, dataTypeKeys, parentKey)
125
+ wanted.add(aggregate.key)
126
+ const taken = await types.byAlias(aggregate.alias)
127
+ if (taken && taken.key !== aggregate.key) {
128
+ report.clashes.push(form.alias)
129
+ continue
130
+ }
131
+ const existing = await types.byKey(aggregate.key)
132
+ // `taken` is only a live type: a retired one is revived by saving it.
133
+ if (existing && taken && !differs(existing, aggregate)) continue
134
+ await types.save(aggregate)
135
+ if (existing) report.updated.push(aggregate.alias)
136
+ else report.created.push(aggregate.alias)
137
+ }
138
+
139
+ const made = await db.q
140
+ .selectFrom('content_type as ct')
141
+ .innerJoin('node as n', 'n.id', 'ct.node_id')
142
+ .select(['n.unique_id', 'ct.alias', 'ct.node_id'])
143
+ .where('ct.form_key', 'is not', null)
144
+ .where('ct.retired_at', 'is', null)
145
+ .execute()
146
+ for (const row of made) {
147
+ const key = String(row.unique_id).toLowerCase()
148
+ if (wanted.has(key)) continue
149
+ if ((await types.contentCount(key)) > 0) continue
150
+ await db.q
151
+ .updateTable('content_type')
152
+ .set({ retired_at: DbDate.toDb(new Date()) })
153
+ .where('node_id', '=', row.node_id)
154
+ .execute()
155
+ report.retired.push(String(row.alias))
156
+ }
157
+ return report
158
+ }
159
+
160
+ /** One Library form, as a picker and the entries filter list it. */
161
+ export interface LibraryFormItem {
162
+ key: string
163
+ name: string
164
+ /** The form it is made from. */
165
+ formKey: string
166
+ published: boolean
167
+ }
168
+
169
+ /** Every Library form not in the recycle bin, by name. */
170
+ export async function listLibraryForms(db: Db): Promise<LibraryFormItem[]> {
171
+ const rows = await db.q
172
+ .selectFrom('node as n')
173
+ .innerJoin('content as c', 'c.node_id', 'n.id')
174
+ .innerJoin('content_type as ct', 'ct.node_id', 'c.content_type_id')
175
+ .innerJoin('document as d', 'd.node_id', 'n.id')
176
+ .select(['n.unique_id', 'n.text', 'ct.form_key', 'd.published'])
177
+ .where('n.node_object_type', '=', ObjectTypes.Element)
178
+ .where('n.trashed', '=', db.dialect.boolValue(false) as boolean)
179
+ .where('ct.form_key', 'is not', null)
180
+ .orderBy('n.text')
181
+ .execute()
182
+ return rows.map((row) => ({
183
+ key: String(row.unique_id).toLowerCase(),
184
+ name: row.text ?? '',
185
+ formKey: String(row.form_key),
186
+ published: fromDbBool(row.published),
187
+ }))
188
+ }
@@ -0,0 +1,25 @@
1
+ /**
2
+ * Migration 059: forms in the Library (story 239). A content type made from a
3
+ * form names it, and an entry names the Library form it came through.
4
+ */
5
+ import type { Db } from '../database.ts'
6
+ import type { Migration } from '../migrations.ts'
7
+ import { schemaOps } from '../schema-ops.ts'
8
+ import { STATE_BUNDLE_SCHEMA_PICKS } from './bundle-schema-picks.ts'
9
+
10
+ export const STATE_FORM_LIBRARY = '{4b198f00-0059-4ca8-bc39-97d92fca0059}'
11
+
12
+ export const formLibraryMigration: Migration = {
13
+ from: STATE_BUNDLE_SCHEMA_PICKS,
14
+ to: STATE_FORM_LIBRARY,
15
+ name: 'AddFormLibrary',
16
+ kind: 'expand',
17
+ release: '0.44.0',
18
+ async up(db: Db) {
19
+ const ops = schemaOps(db)
20
+ const text = db.dialect.types.text
21
+ await ops.addColumn('content_type', 'form_key', text)
22
+ await ops.addColumn('form_entry', 'library_key', text)
23
+ await ops.addIndex('ix_form_entry_library', 'form_entry', ['form_key', 'library_key'])
24
+ },
25
+ }
@@ -22,6 +22,7 @@ import { bundleGrantsMigration } from './bundle-grants.ts'
22
22
  import { bundlePackageMigration } from './bundle-package.ts'
23
23
  import { bundleSchemaPicksMigration } from './bundle-schema-picks.ts'
24
24
  import { bundlesDisabledMigration } from './bundles-disabled.ts'
25
+ import { bundlesInSettingsMigration } from './bundles-in-settings.ts'
25
26
  import { bundlesRenameMigration } from './bundles-rename.ts'
26
27
  import { changeReportMigration } from './change-report.ts'
27
28
  import { clientIdPrefixMigration } from './client-id-prefix.ts'
@@ -36,6 +37,7 @@ import { deliveryMemberTokensMigration } from './delivery-member-tokens.ts'
36
37
  import { diagnosticsMigration } from './diagnostics.ts'
37
38
  import { dropAssistantMigration } from './drop-assistant.ts'
38
39
  import { elementsMigration } from './elements.ts'
40
+ import { formLibraryMigration } from './form-library.ts'
39
41
  import { formPermissionPrefixMigration } from './form-permission-prefix.ts'
40
42
  import { formPermissionsMigration } from './form-permissions.ts'
41
43
  import { formWorkflowsMigration } from './form-workflows.ts'
@@ -56,6 +58,7 @@ import { publicAccessMigration } from './public-access.ts'
56
58
  import { recycleBinMigration } from './recycle-bin.ts'
57
59
  import { redirectsMigration } from './redirects.ts'
58
60
  import { remoteMigration } from './remote.ts'
61
+ import { remoteTrustMigration } from './remote-trust.ts'
59
62
  import { richTextUiMigration } from './rich-text-ui.ts'
60
63
  import { searchIndexMigration } from './search-index.ts'
61
64
  import { serverRoleMigration } from './server-role.ts'
@@ -131,4 +134,7 @@ export const cromboloPlan = new MigrationPlan([
131
134
  bundlesDisabledMigration,
132
135
  siteSettingsTypesMigration,
133
136
  bundleSchemaPicksMigration,
137
+ formLibraryMigration,
138
+ bundlesInSettingsMigration,
139
+ remoteTrustMigration,
134
140
  ])
@@ -0,0 +1,55 @@
1
+ /**
2
+ * Migration 061: signing in to a remote from CI (story 160). A trust rule says
3
+ * which CI identity, by its provider's signed token, may act on this site and
4
+ * with which remote permissions; a CI token is what an accepted identity token
5
+ * is exchanged for, stored by its hash, its identity token's `jti` once only.
6
+ */
7
+ import { sql } from 'kysely'
8
+ import type { Db } from '../database.ts'
9
+ import type { Migration } from '../migrations.ts'
10
+ import { schemaOps } from '../schema-ops.ts'
11
+ import { STATE_BUNDLES_IN_SETTINGS } from './bundles-in-settings.ts'
12
+
13
+ export const STATE_REMOTE_TRUST = '{4b198f00-0061-4ca8-bc39-97d92fca0061}'
14
+
15
+ export const remoteTrustMigration: Migration = {
16
+ from: STATE_BUNDLES_IN_SETTINGS,
17
+ to: STATE_REMOTE_TRUST,
18
+ name: 'AddRemoteTrust',
19
+ kind: 'expand',
20
+ release: '0.44.0',
21
+ async up(db: Db) {
22
+ const t = db.dialect.types
23
+ await db.q.schema
24
+ .createTable('remote_trust_rule')
25
+ .addColumn('key', sql.raw(t.varchar(36)), (c) => c.primaryKey())
26
+ .addColumn('name', sql.raw(t.varchar(255)), (c) => c.notNull())
27
+ .addColumn('issuer', sql.raw(t.varchar(512)), (c) => c.notNull())
28
+ .addColumn('repository', sql.raw(t.varchar(512)), (c) => c.notNull())
29
+ .addColumn('ref_kind', sql.raw(t.varchar(16)), (c) => c.notNull())
30
+ .addColumn('ref_value', sql.raw(t.varchar(255)), (c) => c.notNull())
31
+ .addColumn('permissions', sql.raw(t.json), (c) => c.notNull())
32
+ .addColumn('disabled_at', sql.raw(t.timestamp))
33
+ .addColumn('created_by', sql.raw(t.varchar(255)))
34
+ .addColumn('create_date', sql.raw(t.timestamp), (c) => c.notNull())
35
+ .addColumn('update_date', sql.raw(t.timestamp), (c) => c.notNull())
36
+ .addColumn('last_used_date', sql.raw(t.timestamp))
37
+ .execute()
38
+ await db.q.schema
39
+ .createTable('remote_ci_token')
40
+ .addColumn('token_hash', sql.raw(t.varchar(64)), (c) => c.primaryKey())
41
+ .addColumn('rule_key', sql.raw(t.varchar(36)), (c) => c.notNull())
42
+ .addColumn('issuer', sql.raw(t.varchar(512)), (c) => c.notNull())
43
+ .addColumn('jti', sql.raw(t.varchar(255)), (c) => c.notNull())
44
+ .addColumn('claims', sql.raw(t.json), (c) => c.notNull())
45
+ .addColumn('expires_at', sql.raw(t.timestamp), (c) => c.notNull())
46
+ .addColumn('create_date', sql.raw(t.timestamp), (c) => c.notNull())
47
+ .execute()
48
+ await schemaOps(db).addIndex(
49
+ 'ux_remote_ci_token_jti',
50
+ 'remote_ci_token',
51
+ ['issuer', 'jti'],
52
+ true,
53
+ )
54
+ },
55
+ }
@@ -159,7 +159,6 @@ export const BUILT_IN_GROUPS = [
159
159
  hasAccessToAllLanguages: true,
160
160
  sections: [
161
161
  'content',
162
- 'packages',
163
162
  'media',
164
163
  'members',
165
164
  'settings',
package/src/tables.gen.ts CHANGED
@@ -239,6 +239,7 @@ export interface CoreTables {
239
239
  allow_at_root: Bool
240
240
  allow_in_library: Bool
241
241
  description: string | null
242
+ form_key: string | null
242
243
  icon: string | null
243
244
  is_element: Bool
244
245
  keep_all_versions_newer_than_days: number | null
@@ -388,6 +389,7 @@ export interface CoreTables {
388
389
  form_key: string
389
390
  id: string
390
391
  ip_hash: string | null
392
+ library_key: string | null
391
393
  page_key: string | null
392
394
  spam: Bool
393
395
  state: string
@@ -614,6 +616,15 @@ export interface CoreTables {
614
616
  target: string
615
617
  target_kind: string
616
618
  }
619
+ remote_ci_token: {
620
+ claims: string
621
+ create_date: Timestamp
622
+ expires_at: Timestamp
623
+ issuer: string
624
+ jti: string
625
+ rule_key: string
626
+ token_hash: string
627
+ }
617
628
  remote_job: {
618
629
  create_date: Timestamp
619
630
  decided_at: Timestamp | null
@@ -636,6 +647,20 @@ export interface CoreTables {
636
647
  stage: string | null
637
648
  state: string
638
649
  }
650
+ remote_trust_rule: {
651
+ create_date: Timestamp
652
+ created_by: string | null
653
+ disabled_at: Timestamp | null
654
+ issuer: string
655
+ key: string
656
+ last_used_date: Timestamp | null
657
+ name: string
658
+ permissions: string
659
+ ref_kind: string
660
+ ref_value: string
661
+ repository: string
662
+ update_date: Timestamp
663
+ }
639
664
  schema_state: {
640
665
  hash: string | null
641
666
  id: Generated<number>