@crombolo/data 0.62.0 → 0.63.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.62.0",
3
+ "version": "0.63.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.62.0",
32
+ "@crombolo/core": "0.63.0",
33
33
  "kysely": "0.29.6"
34
34
  }
35
35
  }
package/src/index.ts CHANGED
@@ -109,6 +109,7 @@ export * from './schema/member-property-type.ts'
109
109
  export * from './schema/members.ts'
110
110
  export * from './schema/plan.ts'
111
111
  export * from './schema/property-searchable.ts'
112
+ export * from './schema/pruned-permissions.ts'
112
113
  export * from './schema/public-access.ts'
113
114
  export * from './schema/recycle-bin.ts'
114
115
  export * from './schema/remote.ts'
@@ -128,6 +129,8 @@ export * from './schema/trashed-date.ts'
128
129
  export * from './schema/trusted-signers.ts'
129
130
  export * from './schema/two-factor.ts'
130
131
  export * from './schema/upgrade-report.ts'
132
+ export * from './schema/user-group-owners.ts'
133
+ export * from './schema/user-start-nodes-dropped.ts'
131
134
  export * from './schema/users-localisation.ts'
132
135
  export * from './schema/values.ts'
133
136
  export * from './schema/webhooks.ts'
@@ -13,6 +13,8 @@ import type { Db } from '../database.ts'
13
13
  import { NodeRepository } from './nodes.ts'
14
14
 
15
15
  export interface ComponentFileStore {
16
+ /** The site keeps template files read-only in the back office (story 337). */
17
+ readOnly?: boolean
16
18
  read(alias: string): Promise<string | undefined>
17
19
  write(alias: string, content: string): Promise<void>
18
20
  remove(alias: string): Promise<void>
@@ -12,7 +12,6 @@ export type UserKind = 'Default' | 'Api'
12
12
  export type StartNodeTree = 'document' | 'media' | 'element'
13
13
 
14
14
  /** Umbraco's `UserStartNodeDto.StartNodeTypeValue`. */
15
- const START_NODE_TYPE: Record<StartNodeTree, number> = { document: 1, media: 2, element: 3 }
16
15
  const ROOT_ID = -1
17
16
 
18
17
  /** A user's own start nodes in one tree: root access, and/or specific nodes by key. */
@@ -81,6 +80,8 @@ export interface UserGroupRecord {
81
80
  startNodes: Record<StartNodeTree, GroupStartNode>
82
81
  permissions: string[]
83
82
  granular: GranularPermission[]
83
+ /** The keys of the groups whose members may choose who is in this one (story 302). */
84
+ owners: string[]
84
85
  }
85
86
 
86
87
  export interface UserGroupInput {
@@ -106,6 +107,8 @@ export interface DeclaredUserGroup {
106
107
  sections: readonly string[]
107
108
  permissions: readonly string[]
108
109
  languages: readonly string[] | 'all'
110
+ /** The aliases of the groups that own it (story 302). */
111
+ owners?: readonly string[]
109
112
  }
110
113
 
111
114
  const sameSet = (a: readonly string[], b: readonly string[]) =>
@@ -142,7 +145,6 @@ export interface UserUpdate {
142
145
  email: string
143
146
  languageIsoCode: string | null
144
147
  groupKeys: string[]
145
- startNodes: Record<StartNodeTree, StartNodeSelection>
146
148
  }
147
149
 
148
150
  /** What access checks need about a user: their groups' grants and every start node's position. */
@@ -151,7 +153,6 @@ export interface UserAccessData {
151
153
  languages: string[]
152
154
  hasAccessToAllLanguages: boolean
153
155
  groupStartNodes: Record<StartNodeTree, StartNodePath[]>
154
- userStartNodes: Record<StartNodeTree, StartNodePath[]>
155
156
  }
156
157
 
157
158
  const USER_COLUMNS = [
@@ -232,31 +233,14 @@ export class UserRepository {
232
233
  .where('m.user_id', 'in', ids)
233
234
  .orderBy('g.id')
234
235
  .execute()
235
- const starts = await this.#db.q
236
- .selectFrom('user_start_node')
237
- .select(['user_id', 'start_node', 'start_node_type'])
238
- .where('user_id', 'in', ids)
239
- .execute()
240
- const nodes = await this.#nodeKeys(starts.map((s) => Number(s.start_node)))
241
236
  return rows.map((row) => {
242
237
  const id = Number(row.id)
243
- const startNodes = Object.fromEntries(
244
- TREES.map((tree) => {
245
- const mine = starts.filter(
246
- (s) => Number(s.user_id) === id && Number(s.start_node_type) === START_NODE_TYPE[tree],
247
- )
248
- return [
249
- tree,
250
- {
251
- root: mine.some((s) => Number(s.start_node) === ROOT_ID),
252
- keys: mine.flatMap((s) => {
253
- const node = nodes.get(Number(s.start_node))
254
- return node ? [node.key] : []
255
- }),
256
- },
257
- ]
258
- }),
259
- ) as Record<StartNodeTree, StartNodeSelection>
238
+ // Story 339: a user has no start nodes of their own; where they work is their groups'.
239
+ const startNodes: Record<StartNodeTree, StartNodeSelection> = {
240
+ document: { root: false, keys: [] },
241
+ media: { root: false, keys: [] },
242
+ element: { root: false, keys: [] },
243
+ }
260
244
  return {
261
245
  id,
262
246
  key: normaliseUuid(String(row.key)),
@@ -366,21 +350,13 @@ export class UserRepository {
366
350
  async update(
367
351
  key: string,
368
352
  change: UserUpdate,
369
- ): Promise<'updated' | 'not-found' | 'missing-group' | Exclude<StartNodeTree, never>> {
353
+ ): Promise<'updated' | 'not-found' | 'missing-group'> {
370
354
  return this.#db.transaction(async (tx) => {
371
355
  const repo = new UserRepository(tx)
372
356
  const user = await repo.byKey(key)
373
357
  if (!user) return 'not-found'
374
358
  const groupIds = await repo.#groupIds(change.groupKeys)
375
359
  if (!groupIds) return 'missing-group'
376
- const nodeIds: Array<{ tree: StartNodeTree; id: number }> = []
377
- for (const tree of TREES) {
378
- const selection = change.startNodes[tree]
379
- if (selection.root) nodeIds.push({ tree, id: ROOT_ID })
380
- const ids = await repo.nodeIds(selection.keys)
381
- if (!ids) return tree
382
- for (const id of ids.values()) nodeIds.push({ tree, id })
383
- }
384
360
  await tx.q
385
361
  .updateTable('user_account')
386
362
  .set({
@@ -393,12 +369,6 @@ export class UserRepository {
393
369
  .where('id', '=', user.id)
394
370
  .execute()
395
371
  await repo.#setGroups(user.id, groupIds)
396
- await tx.q.deleteFrom('user_start_node').where('user_id', '=', user.id).execute()
397
- for (const { tree, id } of nodeIds)
398
- await tx.q
399
- .insertInto('user_start_node')
400
- .values({ user_id: user.id, start_node: id, start_node_type: START_NODE_TYPE[tree] })
401
- .execute()
402
372
  return 'updated'
403
373
  })
404
374
  }
@@ -497,7 +467,6 @@ export class UserRepository {
497
467
  await this.#db.transaction(async (tx) => {
498
468
  for (const table of [
499
469
  'user_group_member',
500
- 'user_start_node',
501
470
  'user_data',
502
471
  'user_token',
503
472
  'user_client_credential',
@@ -623,7 +592,6 @@ export class UserRepository {
623
592
  const key = group.startNodes[tree].key
624
593
  if (key) nodeIds[key] = 0
625
594
  }
626
- for (const tree of TREES) for (const key of user?.startNodes[tree].keys ?? []) nodeIds[key] = 0
627
595
  const keys = Object.keys(nodeIds)
628
596
  const rows =
629
597
  keys.length > 0
@@ -699,9 +667,6 @@ export class UserRepository {
699
667
  ),
700
668
  ]),
701
669
  ) as Record<StartNodeTree, StartNodePath[]>,
702
- userStartNodes: Object.fromEntries(
703
- TREES.map((tree) => [tree, user ? positions(user.startNodes[tree]) : []]),
704
- ) as Record<StartNodeTree, StartNodePath[]>,
705
670
  }
706
671
  }
707
672
 
@@ -786,6 +751,11 @@ export class UserGroupRepository {
786
751
  .where('user_group_key', 'in', keys)
787
752
  .orderBy('id')
788
753
  .execute()
754
+ const owners = await this.#db.q
755
+ .selectFrom('user_group_owner')
756
+ .select(['user_group_key', 'owner_group_key'])
757
+ .where('user_group_key', 'in', keys)
758
+ .execute()
789
759
  const startIds = rows.flatMap((r) =>
790
760
  TREES.map((tree) => Number(r[GROUP_START_COLUMN[tree]] ?? 0)),
791
761
  )
@@ -838,6 +808,9 @@ export class UserGroupRepository {
838
808
  permission: String(g.permission),
839
809
  context: String(g.context),
840
810
  })),
811
+ owners: owners
812
+ .filter((o) => normaliseUuid(String(o.user_group_key)) === key)
813
+ .map((o) => normaliseUuid(String(o.owner_group_key))),
841
814
  }
842
815
  })
843
816
  }
@@ -862,6 +835,35 @@ export class UserGroupRepository {
862
835
  return (await this.#hydrate(await groups(this.#db).where('alias', '=', alias).execute()))[0]
863
836
  }
864
837
 
838
+ /** The keys of the groups that any of `groupKeys` owns. */
839
+ async ownedBy(groupKeys: readonly string[]): Promise<string[]> {
840
+ if (groupKeys.length === 0) return []
841
+ const rows = await this.#db.q
842
+ .selectFrom('user_group_owner')
843
+ .select('user_group_key')
844
+ .distinct()
845
+ .where('owner_group_key', 'in', groupKeys.map(normaliseUuid))
846
+ .execute()
847
+ return rows.map((r) => normaliseUuid(String(r.user_group_key)))
848
+ }
849
+
850
+ /** Replaces the groups that own `key`; false when it or one of them does not exist. */
851
+ async setOwners(key: string, ownerKeys: readonly string[]): Promise<boolean> {
852
+ const group = normaliseUuid(key)
853
+ const owners = [...new Set(ownerKeys.map(normaliseUuid))]
854
+ if ((await this.byKeys([group, ...owners])).length !== new Set([group, ...owners]).size)
855
+ return false
856
+ await this.#db.transaction(async (tx) => {
857
+ await tx.q.deleteFrom('user_group_owner').where('user_group_key', '=', group).execute()
858
+ for (const owner of owners)
859
+ await tx.q
860
+ .insertInto('user_group_owner')
861
+ .values({ user_group_key: group, owner_group_key: owner })
862
+ .execute()
863
+ })
864
+ return true
865
+ }
866
+
865
867
  /** How many users each group has, by group key. */
866
868
  async memberCounts(): Promise<Map<string, number>> {
867
869
  const rows = await this.#db.q
@@ -1010,6 +1012,25 @@ export class UserGroupRepository {
1010
1012
  throw new Error(`The user group "${group.alias}" keeps a start node that no longer exists.`)
1011
1013
  ;(existing ? updated : created).push(group.alias)
1012
1014
  }
1015
+ // Owners second, once every group they name exists.
1016
+ for (const group of groups) {
1017
+ if (!group.owners) continue
1018
+ const record = await this.byAlias(group.alias)
1019
+ if (!record) continue
1020
+ const keys: string[] = []
1021
+ for (const alias of group.owners) {
1022
+ const owner = await this.byAlias(alias)
1023
+ if (!owner)
1024
+ throw new Error(
1025
+ `The user group "${group.alias}" names an owner the site does not have: ${alias}.`,
1026
+ )
1027
+ keys.push(owner.key)
1028
+ }
1029
+ if (sameSet(record.owners, keys)) continue
1030
+ await this.setOwners(record.key, keys)
1031
+ if (!created.includes(group.alias) && !updated.includes(group.alias))
1032
+ updated.push(group.alias)
1033
+ }
1013
1034
  return { created, updated }
1014
1035
  }
1015
1036
 
@@ -1028,6 +1049,12 @@ export class UserGroupRepository {
1028
1049
  .deleteFrom('user_group_granular_permission')
1029
1050
  .where('user_group_key', '=', group.key)
1030
1051
  .execute()
1052
+ await tx.q
1053
+ .deleteFrom('user_group_owner')
1054
+ .where((eb) =>
1055
+ eb.or([eb('user_group_key', '=', group.key), eb('owner_group_key', '=', group.key)]),
1056
+ )
1057
+ .execute()
1031
1058
  await tx.q.deleteFrom('user_group').where('id', '=', group.id).execute()
1032
1059
  })
1033
1060
  }
@@ -63,6 +63,7 @@ import { mediaTreeOrderMigration } from './media-tree-order.ts'
63
63
  import { memberPropertyTypeMigration } from './member-property-type.ts'
64
64
  import { membersMigration } from './members.ts'
65
65
  import { propertySearchableMigration } from './property-searchable.ts'
66
+ import { prunedPermissionsMigration } from './pruned-permissions.ts'
66
67
  import { publicAccessMigration } from './public-access.ts'
67
68
  import { recycleBinMigration } from './recycle-bin.ts'
68
69
  import { redirectsMigration } from './redirects.ts'
@@ -83,6 +84,8 @@ import { trashedDateMigration } from './trashed-date.ts'
83
84
  import { trustedSignersMigration } from './trusted-signers.ts'
84
85
  import { twoFactorMigration } from './two-factor.ts'
85
86
  import { upgradeReportMigration } from './upgrade-report.ts'
87
+ import { userGroupOwnersMigration } from './user-group-owners.ts'
88
+ import { userStartNodesDroppedMigration } from './user-start-nodes-dropped.ts'
86
89
  import { usersLocalisationMigration } from './users-localisation.ts'
87
90
  import { valuesMigration } from './values.ts'
88
91
  import { webhooksMigration } from './webhooks.ts'
@@ -161,4 +164,7 @@ export const cromboloPlan = new MigrationPlan([
161
164
  bundleGrantDelegateMigration,
162
165
  extensionActivityMigration,
163
166
  formWorkflowSecretsMigration,
167
+ userGroupOwnersMigration,
168
+ prunedPermissionsMigration,
169
+ userStartNodesDroppedMigration,
164
170
  ])
@@ -0,0 +1,102 @@
1
+ /**
2
+ * Migration 075 — the verbs story 338 takes out of the catalogue are rewritten
3
+ * to what replaces them, or removed, in every group's defaults and in every
4
+ * per-page, per-item and per-field row.
5
+ *
6
+ * A per-page or per-field set that held only dropped verbs becomes an explicit
7
+ * "nothing here" row, Umbraco's empty verb, rather than no row: no row would
8
+ * fall back to the group's defaults, and widen what the set allowed.
9
+ *
10
+ * Statements only, never a read, so an upgrade can be planned before it runs.
11
+ */
12
+ import { PRUNED_PERMISSIONS } from '@crombolo/core'
13
+ import type { Db } from '../database.ts'
14
+ import type { Migration } from '../migrations.ts'
15
+ import { STATE_USER_GROUP_OWNERS } from './user-group-owners.ts'
16
+
17
+ export const STATE_PRUNED_PERMISSIONS = '{8b3d1f62-0075-4c1e-9a47-2e6f0d5c0075}'
18
+
19
+ const RENAMED = Object.entries(PRUNED_PERMISSIONS).filter(
20
+ (entry): entry is [string, string] => entry[1] !== null,
21
+ )
22
+ const DROPPED = Object.keys(PRUNED_PERMISSIONS).filter((verb) => PRUNED_PERMISSIONS[verb] === null)
23
+
24
+ export const prunedPermissionsMigration: Migration = {
25
+ from: STATE_USER_GROUP_OWNERS,
26
+ to: STATE_PRUNED_PERMISSIONS,
27
+ name: 'PruneGroupPermissions',
28
+ kind: 'expand',
29
+ release: '0.63.0',
30
+ async up(db: Db) {
31
+ for (const [before, after] of RENAMED) {
32
+ // Defaults: a group already holding the replacement loses the old row, the rest rename it.
33
+ await db.q
34
+ .deleteFrom('user_group_permission')
35
+ .where('permission', '=', before)
36
+ .where('user_group_key', 'in', (eb) =>
37
+ eb
38
+ .selectFrom('user_group_permission')
39
+ .select('user_group_key')
40
+ .where('permission', '=', after),
41
+ )
42
+ .execute()
43
+ await db.q
44
+ .updateTable('user_group_permission')
45
+ .set({ permission: after })
46
+ .where('permission', '=', before)
47
+ .execute()
48
+ // Per place: the same, within each group's set for that place.
49
+ await db.q
50
+ .deleteFrom('user_group_granular_permission as g')
51
+ .where('g.permission', '=', before)
52
+ .where((eb) =>
53
+ eb.exists(
54
+ eb
55
+ .selectFrom('user_group_granular_permission as h')
56
+ .select('h.id')
57
+ .whereRef('h.user_group_key', '=', 'g.user_group_key')
58
+ .whereRef('h.unique_id', '=', 'g.unique_id')
59
+ .whereRef('h.context', '=', 'g.context')
60
+ .where('h.permission', '=', after),
61
+ ),
62
+ )
63
+ .execute()
64
+ await db.q
65
+ .updateTable('user_group_granular_permission')
66
+ .set({ permission: after })
67
+ .where('permission', '=', before)
68
+ .execute()
69
+ }
70
+
71
+ // A place whose set held only dropped verbs keeps an explicit "nothing here".
72
+ await db.q
73
+ .insertInto('user_group_granular_permission')
74
+ .columns(['user_group_key', 'unique_id', 'permission', 'context'])
75
+ .expression((eb) =>
76
+ eb
77
+ .selectFrom('user_group_granular_permission as g')
78
+ .select(['g.user_group_key', 'g.unique_id', eb.val('').as('permission'), 'g.context'])
79
+ .distinct()
80
+ .where('g.permission', 'in', DROPPED)
81
+ .where((inner) =>
82
+ inner.not(
83
+ inner.exists(
84
+ inner
85
+ .selectFrom('user_group_granular_permission as h')
86
+ .select('h.id')
87
+ .whereRef('h.user_group_key', '=', 'g.user_group_key')
88
+ .whereRef('h.unique_id', '=', 'g.unique_id')
89
+ .whereRef('h.context', '=', 'g.context')
90
+ .where('h.permission', 'not in', DROPPED),
91
+ ),
92
+ ),
93
+ ),
94
+ )
95
+ .execute()
96
+ await db.q
97
+ .deleteFrom('user_group_granular_permission')
98
+ .where('permission', 'in', DROPPED)
99
+ .execute()
100
+ await db.q.deleteFrom('user_group_permission').where('permission', 'in', DROPPED).execute()
101
+ },
102
+ }
@@ -18,11 +18,6 @@ const ELEMENT_EDIT = [
18
18
  'Umb.Element.Unpublish',
19
19
  'Umb.Element.Read',
20
20
  'Umb.Element.Rollback',
21
- 'Umb.ElementContainer.Create',
22
- 'Umb.ElementContainer.Update',
23
- 'Umb.ElementContainer.Delete',
24
- 'Umb.ElementContainer.Move',
25
- 'Umb.ElementContainer.Read',
26
21
  ]
27
22
 
28
23
  /**
@@ -59,13 +54,10 @@ export const BUILT_IN_GROUP_PERMISSIONS: Record<string, readonly string[]> = {
59
54
  'Umb.Document.Permissions',
60
55
  'Umb.Document.Unpublish',
61
56
  'Umb.Document.Read',
62
- 'Umb.Document.CreateBlueprint',
63
- 'Umb.Document.Notifications',
64
57
  ':',
65
58
  '5',
66
59
  '7',
67
60
  'T',
68
- 'Umb.Document.PropertyValue.Read',
69
61
  'Umb.Document.PropertyValue.Write',
70
62
  ...FORM_FULL,
71
63
  ...ELEMENT_EDIT,
@@ -85,12 +77,9 @@ export const BUILT_IN_GROUP_PERMISSIONS: Record<string, readonly string[]> = {
85
77
  'Umb.Document.Publish',
86
78
  'Umb.Document.Unpublish',
87
79
  'Umb.Document.Read',
88
- 'Umb.Document.CreateBlueprint',
89
- 'Umb.Document.Notifications',
90
80
  ':',
91
81
  '5',
92
82
  'T',
93
- 'Umb.Document.PropertyValue.Read',
94
83
  'Umb.Document.PropertyValue.Write',
95
84
  // An editor reads entries and acts on them, but does not design forms and
96
85
  // does not see what a definition marks sensitive.
@@ -104,16 +93,11 @@ export const BUILT_IN_GROUP_PERMISSIONS: Record<string, readonly string[]> = {
104
93
  'Umb.Document.Create',
105
94
  'Umb.Document.Update',
106
95
  'Umb.Document.Read',
107
- 'Umb.Document.Notifications',
108
96
  ':',
109
- 'Umb.Document.PropertyValue.Read',
110
97
  'Umb.Document.PropertyValue.Write',
111
98
  'Umb.Element.Create',
112
99
  'Umb.Element.Update',
113
100
  'Umb.Element.Read',
114
- 'Umb.ElementContainer.Create',
115
- 'Umb.ElementContainer.Update',
116
- 'Umb.ElementContainer.Read',
117
101
  ],
118
102
  // The group that exists only to carry sensitive-data access; it has no
119
103
  // sections of its own and is added alongside another group.
@@ -121,12 +105,9 @@ export const BUILT_IN_GROUP_PERMISSIONS: Record<string, readonly string[]> = {
121
105
  translator: [
122
106
  'Umb.Document.Update',
123
107
  'Umb.Document.Read',
124
- 'Umb.Document.PropertyValue.Read',
125
108
  'Umb.Document.PropertyValue.Write',
126
109
  'Umb.Element.Update',
127
110
  'Umb.Element.Read',
128
- 'Umb.ElementContainer.Update',
129
- 'Umb.ElementContainer.Read',
130
111
  ],
131
112
  }
132
113
 
@@ -0,0 +1,29 @@
1
+ /**
2
+ * Migration 074 — the groups that own a group (story 302): their members may
3
+ * choose who is in it, while what it grants stays an administrator's.
4
+ */
5
+ import type { Db } from '../database.ts'
6
+ import type { Migration } from '../migrations.ts'
7
+ import { sql } from '../query.ts'
8
+ import { STATE_FORM_WORKFLOW_SECRETS } from './form-workflow-secrets.ts'
9
+
10
+ export const STATE_USER_GROUP_OWNERS = '{5e2a9c41-0074-4b7d-9f30-6c1d8e4a0074}'
11
+
12
+ export const userGroupOwnersMigration: Migration = {
13
+ from: STATE_FORM_WORKFLOW_SECRETS,
14
+ to: STATE_USER_GROUP_OWNERS,
15
+ name: 'AddUserGroupOwners',
16
+ kind: 'expand',
17
+ release: '0.63.0',
18
+ async up(db: Db) {
19
+ const t = db.dialect.types
20
+ await db.q.schema
21
+ .createTable('user_group_owner')
22
+ .addColumn('user_group_key', sql.raw(t.uuid), (c) => c.notNull().references('user_group.key'))
23
+ .addColumn('owner_group_key', sql.raw(t.uuid), (c) =>
24
+ c.notNull().references('user_group.key'),
25
+ )
26
+ .addPrimaryKeyConstraint('user_group_owner_pk', ['user_group_key', 'owner_group_key'])
27
+ .execute()
28
+ },
29
+ }
@@ -0,0 +1,121 @@
1
+ /**
2
+ * Migration 076 — a user's own start nodes are dropped (story 339): where a user
3
+ * may work comes only from their groups.
4
+ *
5
+ * A user's own start nodes replaced any group start node they overlapped, so
6
+ * they usually narrowed someone; without them that user reaches what their
7
+ * groups do. Nothing converts them faithfully, so each one is named on the
8
+ * Changes dashboard and in the audit log, where the user had been held, before
9
+ * the table goes. Statements only, never a read, so the upgrade can be planned.
10
+ */
11
+ import type { Kysely } from 'kysely'
12
+ import type { Db } from '../database.ts'
13
+ import { DbDate } from '../dialect.ts'
14
+ import type { Migration } from '../migrations.ts'
15
+ import { sql } from '../query.ts'
16
+ import { STATE_PRUNED_PERMISSIONS } from './pruned-permissions.ts'
17
+
18
+ export const STATE_USER_START_NODES_DROPPED = '{3c7e2a90-0076-4f1b-8d64-1a5e9b2c0076}'
19
+
20
+ export const userStartNodesDroppedMigration: Migration = {
21
+ from: STATE_PRUNED_PERMISSIONS,
22
+ to: STATE_USER_START_NODES_DROPPED,
23
+ name: 'DropUserStartNodes',
24
+ kind: 'expand',
25
+ release: '0.63.0',
26
+ async up(db: Db) {
27
+ // Untyped: the table is gone from the generated types once this runs.
28
+ const old = db.q as unknown as Kysely<Record<string, Record<string, unknown>>>
29
+ // Cast: a bare parameter in a select is text, which Postgres won't put in a timestamp.
30
+ const now = sql`CAST(${DbDate.toDb(new Date())} AS ${sql.raw(db.dialect.types.timestamp)})`
31
+ // "all media", or "pages under News": where this row held the user.
32
+ const place = sql<string>`(CASE WHEN s.start_node = -1 THEN 'all ' ELSE '' END)
33
+ || (CASE s.start_node_type WHEN 1 THEN 'pages' WHEN 2 THEN 'media' ELSE 'Library items' END)
34
+ || (CASE WHEN s.start_node = -1 THEN '' ELSE ' under ' || COALESCE(n.text, 'a removed item') END)`
35
+ const rows = () =>
36
+ old
37
+ .selectFrom('user_start_node as s')
38
+ .innerJoin('user_account as u', 'u.id', 's.user_id')
39
+ .leftJoin('node as n', 'n.id', 's.start_node')
40
+
41
+ await old
42
+ .insertInto('change_report')
43
+ .columns([
44
+ 'run_id',
45
+ 'source',
46
+ 'scope',
47
+ 'status',
48
+ 'kind',
49
+ 'code',
50
+ 'subject_type',
51
+ 'subject_key',
52
+ 'subject_name',
53
+ 'property_alias',
54
+ 'culture',
55
+ 'message',
56
+ 'link',
57
+ 'first_seen',
58
+ 'last_seen',
59
+ ])
60
+ .expression((eb) =>
61
+ rows().select([
62
+ eb.val('migration-076').as('run_id'),
63
+ eb.val('upgrade').as('source'),
64
+ eb.val('user-start-nodes').as('scope'),
65
+ eb.val('open').as('status'),
66
+ eb.val('person').as('kind'),
67
+ eb.val('user-start-nodes-dropped').as('code'),
68
+ eb.val('user').as('subject_type'),
69
+ 'u.key',
70
+ 'u.user_name',
71
+ sql`NULL`.as('property_alias'),
72
+ sql`NULL`.as('culture'),
73
+ sql<string>`u.user_name || ' was held to ' || ${place} || '. A user''s own start nodes are gone, so they now work wherever their groups do. Put them in a group that reaches only there if that was meant.'`.as(
74
+ 'message',
75
+ ),
76
+ sql<string>`'section/user-management/workspace/user/edit/' || u.key`.as('link'),
77
+ now.as('first_seen'),
78
+ now.as('last_seen'),
79
+ ]),
80
+ )
81
+ .execute()
82
+
83
+ await old
84
+ .insertInto('audit_entry')
85
+ .columns([
86
+ 'category',
87
+ 'action',
88
+ 'entity_type',
89
+ 'entity_key',
90
+ 'entity_name',
91
+ 'detail',
92
+ 'source',
93
+ 'user_key',
94
+ 'user_name',
95
+ 'ip_address',
96
+ 'forwarded_for',
97
+ 'occurred_at',
98
+ ])
99
+ .expression((eb) =>
100
+ rows().select([
101
+ eb.val('permission').as('category'),
102
+ eb.val('StartNodesDropped').as('action'),
103
+ eb.val('User').as('entity_type'),
104
+ 'u.key',
105
+ 'u.user_name',
106
+ sql<string>`'own start node dropped on upgrade (story 339): was held to ' || ${place}`.as(
107
+ 'detail',
108
+ ),
109
+ eb.val('boot').as('source'),
110
+ sql`NULL`.as('user_key'),
111
+ eb.val('crombolo').as('user_name'),
112
+ sql`NULL`.as('ip_address'),
113
+ sql`NULL`.as('forwarded_for'),
114
+ now.as('occurred_at'),
115
+ ]),
116
+ )
117
+ .execute()
118
+
119
+ await db.q.schema.dropTable('user_start_node').execute()
120
+ },
121
+ }
package/src/tables.gen.ts CHANGED
@@ -866,6 +866,10 @@ export interface CoreTables {
866
866
  user_group_id: number
867
867
  user_id: Generated<number>
868
868
  }
869
+ user_group_owner: {
870
+ owner_group_key: string
871
+ user_group_key: string
872
+ }
869
873
  user_group_permission: {
870
874
  id: Generated<number>
871
875
  permission: string
@@ -888,12 +892,6 @@ export interface CoreTables {
888
892
  node_id: number
889
893
  user_id: Generated<number>
890
894
  }
891
- user_start_node: {
892
- id: Generated<number>
893
- start_node: number
894
- start_node_type: number
895
- user_id: number
896
- }
897
895
  user_token: {
898
896
  expires_at: Timestamp
899
897
  purpose: string