@crombolo/data 0.80.1 → 0.81.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 +2 -2
- package/src/database.ts +51 -0
- package/src/index.ts +2 -0
- package/src/migrations.ts +13 -6
- package/src/relations.ts +3 -2
- package/src/repositories/documents.ts +51 -15
- package/src/repositories/media-access.ts +5 -1
- package/src/repositories/members.ts +77 -0
- package/src/repositories/nodes.ts +70 -6
- package/src/repositories/public-access.ts +2 -0
- package/src/repositories/references.ts +4 -0
- package/src/repositories/users.ts +94 -2
- package/src/repositories/workspaces.ts +50 -1
- package/src/schema/keys-per-workspace.ts +57 -0
- package/src/schema/plan.ts +4 -0
- package/src/schema/service-account-secrets.ts +25 -0
- package/src/tables.gen.ts +3 -0
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@crombolo/data",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.81.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.
|
|
32
|
+
"@crombolo/core": "0.81.0",
|
|
33
33
|
"kysely": "0.29.6"
|
|
34
34
|
}
|
|
35
35
|
}
|
package/src/database.ts
CHANGED
|
@@ -32,6 +32,17 @@ export interface Db {
|
|
|
32
32
|
confine?(role: string, schema: string): Db
|
|
33
33
|
/** Postgres only: calls `onNotify` for each `NOTIFY` on `channel`; resolves to the way to stop. */
|
|
34
34
|
listen?(channel: string, onNotify: (payload: string) => void): Promise<() => Promise<void>>
|
|
35
|
+
/**
|
|
36
|
+
* SQLite only: runs `fn` with foreign keys off on the connection, as SQLite's own table
|
|
37
|
+
* rebuild needs (story 436). Refused inside a transaction, where SQLite ignores it.
|
|
38
|
+
*/
|
|
39
|
+
withoutForeignKeys?<T>(fn: () => Promise<T>): Promise<T>
|
|
40
|
+
/**
|
|
41
|
+
* SQLite only, inside a transaction with foreign keys off: `table` rebuilt from its
|
|
42
|
+
* definition as `rewrite` makes it, keeping its rows and indexes, as SQLite's guide to
|
|
43
|
+
* changing a column's constraints does; refused if a reference is left broken.
|
|
44
|
+
*/
|
|
45
|
+
rebuildTable?(table: string, rewrite: (definition: string) => string): Promise<void>
|
|
35
46
|
}
|
|
36
47
|
|
|
37
48
|
export interface ConnectOptions {
|
|
@@ -96,6 +107,46 @@ class SqliteDb implements Db {
|
|
|
96
107
|
return this.#db.query(this.dialect.render(sql)).all(...(params as never[])) as T[]
|
|
97
108
|
}
|
|
98
109
|
|
|
110
|
+
async rebuildTable(table: string, rewrite: (definition: string) => string): Promise<void> {
|
|
111
|
+
if (!/^[a-z_]+$/.test(table)) throw new Error(`"${table}" is not a table name.`)
|
|
112
|
+
const [found] = await this.query<{ sql: string }>(
|
|
113
|
+
"SELECT sql FROM sqlite_master WHERE type = 'table' AND name = ?",
|
|
114
|
+
[table],
|
|
115
|
+
)
|
|
116
|
+
if (!found) throw new Error(`There is no ${table} table to rebuild.`)
|
|
117
|
+
const indexes = await this.query<{ sql: string }>(
|
|
118
|
+
"SELECT sql FROM sqlite_master WHERE type = 'index' AND tbl_name = ? AND sql IS NOT NULL",
|
|
119
|
+
[table],
|
|
120
|
+
)
|
|
121
|
+
const definition = rewrite(found.sql)
|
|
122
|
+
if (definition === found.sql) throw new Error(`The ${table} table is not as expected.`)
|
|
123
|
+
const rebuilt = `${table}_rebuilt`
|
|
124
|
+
await this.exec(
|
|
125
|
+
definition.replace(
|
|
126
|
+
new RegExp(`^CREATE TABLE\\s+"?${table}"?`, 'i'),
|
|
127
|
+
`CREATE TABLE ${rebuilt}`,
|
|
128
|
+
),
|
|
129
|
+
)
|
|
130
|
+
await this.exec(`INSERT INTO ${rebuilt} SELECT * FROM ${table}`)
|
|
131
|
+
await this.exec(`DROP TABLE ${table}`)
|
|
132
|
+
await this.exec(`ALTER TABLE ${rebuilt} RENAME TO ${table}`)
|
|
133
|
+
for (const index of indexes) await this.exec(index.sql)
|
|
134
|
+
const broken = await this.query('PRAGMA foreign_key_check')
|
|
135
|
+
if (broken.length > 0)
|
|
136
|
+
throw new Error(`Rebuilding ${table} left ${broken.length} reference(s) broken.`)
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
async withoutForeignKeys<T>(fn: () => Promise<T>): Promise<T> {
|
|
140
|
+
if (this.#inTransaction)
|
|
141
|
+
throw new Error('Foreign keys are turned off only outside a transaction.')
|
|
142
|
+
this.#db.exec('PRAGMA foreign_keys = OFF')
|
|
143
|
+
try {
|
|
144
|
+
return await fn()
|
|
145
|
+
} finally {
|
|
146
|
+
this.#db.exec('PRAGMA foreign_keys = ON')
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
|
|
99
150
|
async exec(sql: string, params: unknown[] = []): Promise<void> {
|
|
100
151
|
this.#db.query(this.dialect.render(sql)).run(...(params as never[]))
|
|
101
152
|
}
|
package/src/index.ts
CHANGED
|
@@ -117,6 +117,7 @@ export * from './schema/group-start-keys.ts'
|
|
|
117
117
|
export * from './schema/identity.ts'
|
|
118
118
|
export * from './schema/image-alt-text.ts'
|
|
119
119
|
export * from './schema/jobs.ts'
|
|
120
|
+
export * from './schema/keys-per-workspace.ts'
|
|
120
121
|
export * from './schema/log-viewer.ts'
|
|
121
122
|
export * from './schema/media-access.ts'
|
|
122
123
|
export * from './schema/media-cache.ts'
|
|
@@ -139,6 +140,7 @@ export * from './schema/search-index.ts'
|
|
|
139
140
|
export * from './schema/search-removals.ts'
|
|
140
141
|
export * from './schema/seed.ts'
|
|
141
142
|
export * from './schema/served-changes.ts'
|
|
143
|
+
export * from './schema/service-account-secrets.ts'
|
|
142
144
|
export * from './schema/session-view-as.ts'
|
|
143
145
|
export * from './schema/since-version.ts'
|
|
144
146
|
export * from './schema/single-use-token.ts'
|
package/src/migrations.ts
CHANGED
|
@@ -32,6 +32,11 @@ export interface Migration {
|
|
|
32
32
|
contracts?: string
|
|
33
33
|
/** Recorded in the ledger, and compared when the plan verifies what ran. Defaults to `name`. */
|
|
34
34
|
checksum?: string
|
|
35
|
+
/**
|
|
36
|
+
* SQLite: the step runs with foreign keys off, as rebuilding a table others refer to
|
|
37
|
+
* needs, and is refused if any reference is left broken (story 436).
|
|
38
|
+
*/
|
|
39
|
+
foreignKeysOff?: boolean
|
|
35
40
|
up(db: Db): Promise<void>
|
|
36
41
|
/**
|
|
37
42
|
* Writes data once `up` has run, in the same transaction. `planUpgrade` cannot
|
|
@@ -507,8 +512,10 @@ export async function migrate(
|
|
|
507
512
|
const started = performance.now()
|
|
508
513
|
// The state and the ledger row commit with the step, so an interrupted
|
|
509
514
|
// run resumes at the first step that did not land and never repeats one.
|
|
510
|
-
|
|
511
|
-
.
|
|
515
|
+
const run = <T>(fn: () => Promise<T>): Promise<T> =>
|
|
516
|
+
next.foreignKeysOff && db.withoutForeignKeys ? db.withoutForeignKeys(fn) : fn()
|
|
517
|
+
await run(() =>
|
|
518
|
+
db.transaction(async (tx) => {
|
|
512
519
|
const step = async (db: Db) => {
|
|
513
520
|
await next.up(db)
|
|
514
521
|
await next.backfill?.(db)
|
|
@@ -526,10 +533,10 @@ export async function migrate(
|
|
|
526
533
|
note: next.release ? `release ${next.release}` : null,
|
|
527
534
|
bundle: plan.bundle ?? null,
|
|
528
535
|
})
|
|
529
|
-
})
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
536
|
+
}),
|
|
537
|
+
).catch((error: unknown) => {
|
|
538
|
+
throw new MigrationStepError(next.name, applied, plan.bundle, error)
|
|
539
|
+
})
|
|
533
540
|
state = next.to
|
|
534
541
|
applied.push(next.name)
|
|
535
542
|
}
|
package/src/relations.ts
CHANGED
|
@@ -220,12 +220,13 @@ export async function loadReferences(db: Db): Promise<ReferenceEdge[]> {
|
|
|
220
220
|
if (wanted.size === 0) return []
|
|
221
221
|
const nodes = await db.q
|
|
222
222
|
.selectFrom('node')
|
|
223
|
-
.select(['id', 'unique_id', 'node_object_type'])
|
|
223
|
+
.select(['id', 'unique_id', 'node_object_type', 'workspace_id'])
|
|
224
224
|
.execute()
|
|
225
225
|
const byKey = new Map<string, KnownNode>()
|
|
226
226
|
for (const node of nodes) {
|
|
227
227
|
const key = normaliseUuid(String(node.unique_id))
|
|
228
|
-
|
|
228
|
+
// Story 436: Shared's item under a key, never a workspace's copy beside it.
|
|
229
|
+
if (wanted.has(key) && (node.workspace_id === null || !byKey.has(key)))
|
|
229
230
|
byKey.set(key, {
|
|
230
231
|
id: Number(node.id),
|
|
231
232
|
key,
|
|
@@ -281,6 +281,11 @@ export interface WorkspacePageMerge {
|
|
|
281
281
|
key: string
|
|
282
282
|
nodeId: number
|
|
283
283
|
made: boolean
|
|
284
|
+
/**
|
|
285
|
+
* Story 436: Shared's node under the same key, when the workspace made its own copy of
|
|
286
|
+
* an item Shared has since: it merges as a change to Shared's from a blank start.
|
|
287
|
+
*/
|
|
288
|
+
twinNodeId?: number
|
|
284
289
|
level: number
|
|
285
290
|
contentTypeKey: string
|
|
286
291
|
parentKey: string | null
|
|
@@ -454,7 +459,7 @@ export class DocumentRepository {
|
|
|
454
459
|
|
|
455
460
|
constructor(db: Db, options: DocumentRepositoryOptions = {}) {
|
|
456
461
|
this.#db = db
|
|
457
|
-
this.#nodes = new NodeRepository(db)
|
|
462
|
+
this.#nodes = new NodeRepository(db, { workspace: options.workspace })
|
|
458
463
|
this.#nodeState = options.nodeState ?? BASELINE_NODE_STATE
|
|
459
464
|
this.#nodeId = options.nodeId
|
|
460
465
|
this.kind = options.kind ?? 'document'
|
|
@@ -1121,6 +1126,22 @@ export class DocumentRepository {
|
|
|
1121
1126
|
|
|
1122
1127
|
async #mergePage(node: NodeRow, wd: WorkspaceDocumentRow): Promise<WorkspacePageMerge> {
|
|
1123
1128
|
const workspace = this.#workspace as number
|
|
1129
|
+
// Story 436: Shared's copy under the key this workspace made its own of, if Shared has one.
|
|
1130
|
+
const twin = wd.created
|
|
1131
|
+
? (
|
|
1132
|
+
await this.#db.q
|
|
1133
|
+
.selectFrom('node')
|
|
1134
|
+
.select('id')
|
|
1135
|
+
.where('unique_id', '=', normaliseUuid(node.key))
|
|
1136
|
+
.where('workspace_id', 'is', null)
|
|
1137
|
+
.where('id', '!=', node.id)
|
|
1138
|
+
.executeTakeFirst()
|
|
1139
|
+
)?.id
|
|
1140
|
+
: undefined
|
|
1141
|
+
const twinId = twin === undefined ? undefined : Number(twin)
|
|
1142
|
+
// Made here and nowhere else: every field the workspace's. With a twin, three ways from blank.
|
|
1143
|
+
const fresh = wd.created && twinId === undefined
|
|
1144
|
+
const theirsId = twinId ?? node.id
|
|
1124
1145
|
const contentTypeNodeId = (await this.#contentTypeNodeId(node.id)) as number
|
|
1125
1146
|
const propertyTypes = await this.#propertyTypes(contentTypeNodeId)
|
|
1126
1147
|
const languages = await this.#languages()
|
|
@@ -1153,17 +1174,17 @@ export class DocumentRepository {
|
|
|
1153
1174
|
? new Map<string, Held>()
|
|
1154
1175
|
: asValues(await this.#valueRowsAsOf(node.id, { eventId: wd.baseEventId }))
|
|
1155
1176
|
const mine = asValues(await this.#workspaceView(node.id, wd))
|
|
1156
|
-
const theirs =
|
|
1177
|
+
const theirs = fresh
|
|
1157
1178
|
? new Map<string, Held>()
|
|
1158
|
-
: asValues(await this.#currentValueRows(
|
|
1179
|
+
: asValues(await this.#currentValueRows(theirsId))
|
|
1159
1180
|
const fields: MergeField[] = []
|
|
1160
1181
|
for (const field of new Set([...base.keys(), ...mine.keys(), ...theirs.keys()])) {
|
|
1161
1182
|
const known = mine.get(field) ?? theirs.get(field) ?? base.get(field)
|
|
1162
1183
|
fields.push({
|
|
1163
1184
|
field,
|
|
1164
|
-
base:
|
|
1185
|
+
base: fresh ? undefined : twinId !== undefined ? null : (base.get(field)?.value ?? null),
|
|
1165
1186
|
mine: mine.get(field)?.value ?? null,
|
|
1166
|
-
theirs:
|
|
1187
|
+
theirs: fresh ? undefined : (theirs.get(field)?.value ?? null),
|
|
1167
1188
|
...(known
|
|
1168
1189
|
? {
|
|
1169
1190
|
value: {
|
|
@@ -1203,13 +1224,18 @@ export class DocumentRepository {
|
|
|
1203
1224
|
const head = await this.#workspaceHead(node.id)
|
|
1204
1225
|
const baseFacts = await eventFacts(wd.baseEventId)
|
|
1205
1226
|
const mineFacts = await eventFacts(head ? Number(head.id) : null)
|
|
1206
|
-
const sharedHead =
|
|
1227
|
+
const sharedHead = fresh ? undefined : await this.#headEvent(theirsId)
|
|
1207
1228
|
const theirsFacts = await eventFacts(sharedHead?.id)
|
|
1208
1229
|
fields.push(
|
|
1209
|
-
{
|
|
1230
|
+
{
|
|
1231
|
+
field: '@name',
|
|
1232
|
+
base: twinId !== undefined ? null : baseFacts?.name,
|
|
1233
|
+
mine: mineFacts?.name,
|
|
1234
|
+
theirs: theirsFacts?.name,
|
|
1235
|
+
},
|
|
1210
1236
|
{
|
|
1211
1237
|
field: '@template',
|
|
1212
|
-
base: baseFacts?.template,
|
|
1238
|
+
base: twinId !== undefined ? null : baseFacts?.template,
|
|
1213
1239
|
mine: mineFacts?.template ?? null,
|
|
1214
1240
|
theirs: theirsFacts?.template,
|
|
1215
1241
|
},
|
|
@@ -1229,7 +1255,7 @@ export class DocumentRepository {
|
|
|
1229
1255
|
.selectFrom('document_culture_variation as dcv')
|
|
1230
1256
|
.innerJoin('language as l', 'l.id', 'dcv.language_id')
|
|
1231
1257
|
.select(['l.iso_code', 'dcv.name', 'dcv.published'])
|
|
1232
|
-
.where('dcv.node_id', '=',
|
|
1258
|
+
.where('dcv.node_id', '=', theirsId)
|
|
1233
1259
|
.execute()
|
|
1234
1260
|
).map((c) => [String(c.iso_code), c]),
|
|
1235
1261
|
)
|
|
@@ -1239,9 +1265,13 @@ export class DocumentRepository {
|
|
|
1239
1265
|
const theirsCulture = theirsCultures.get(iso)
|
|
1240
1266
|
fields.push({
|
|
1241
1267
|
field: `@name:${iso}`,
|
|
1242
|
-
base:
|
|
1268
|
+
base: fresh
|
|
1269
|
+
? undefined
|
|
1270
|
+
: twinId !== undefined
|
|
1271
|
+
? null
|
|
1272
|
+
: (baseFacts?.cultures.get(iso) ?? null),
|
|
1243
1273
|
mine: String(c.name ?? ''),
|
|
1244
|
-
theirs:
|
|
1274
|
+
theirs: fresh ? undefined : theirsCulture ? String(theirsCulture.name ?? '') : null,
|
|
1245
1275
|
})
|
|
1246
1276
|
cultures.push({
|
|
1247
1277
|
iso,
|
|
@@ -1254,7 +1284,7 @@ export class DocumentRepository {
|
|
|
1254
1284
|
await this.#db.q
|
|
1255
1285
|
.selectFrom('document')
|
|
1256
1286
|
.select(['published', 'edited'])
|
|
1257
|
-
.where('node_id', '=',
|
|
1287
|
+
.where('node_id', '=', theirsId)
|
|
1258
1288
|
.execute()
|
|
1259
1289
|
)[0]
|
|
1260
1290
|
const publishedHere =
|
|
@@ -1288,7 +1318,8 @@ export class DocumentRepository {
|
|
|
1288
1318
|
kind: this.kind,
|
|
1289
1319
|
key: node.key,
|
|
1290
1320
|
nodeId: node.id,
|
|
1291
|
-
made:
|
|
1321
|
+
made: fresh,
|
|
1322
|
+
...(twinId !== undefined ? { twinNodeId: twinId } : {}),
|
|
1292
1323
|
level: node.level,
|
|
1293
1324
|
contentTypeKey: normaliseUuid(String(typeRow?.unique_id)),
|
|
1294
1325
|
parentKey: parent && parent.id !== SystemNodes.Root ? parent.key : null,
|
|
@@ -1301,9 +1332,9 @@ export class DocumentRepository {
|
|
|
1301
1332
|
? null
|
|
1302
1333
|
: fromDbBool(based.base_published),
|
|
1303
1334
|
mine: wd.published,
|
|
1304
|
-
theirs:
|
|
1335
|
+
theirs: fresh ? false : fromDbBool(document?.published),
|
|
1305
1336
|
here: publishedHere,
|
|
1306
|
-
sharedEdited:
|
|
1337
|
+
sharedEdited: fresh ? false : fromDbBool(document?.edited),
|
|
1307
1338
|
},
|
|
1308
1339
|
cultures,
|
|
1309
1340
|
}
|
|
@@ -1710,14 +1741,19 @@ export class DocumentRepository {
|
|
|
1710
1741
|
.select('node_id')
|
|
1711
1742
|
.where('workspace_id', '=', workspace)
|
|
1712
1743
|
.execute()
|
|
1744
|
+
const own = new Set<string>()
|
|
1713
1745
|
for (const { node_id } of touched) {
|
|
1714
1746
|
const node = await this.#nodes.byId(Number(node_id))
|
|
1715
1747
|
const wd = node ? await this.#workspaceDocument(node.id) : undefined
|
|
1716
1748
|
if (!node || !wd || node.trashed) continue
|
|
1749
|
+
if (node.workspaceId === workspace) own.add(normaliseUuid(node.key))
|
|
1717
1750
|
const row = wd.published ? await this.#workspacePublishedRow(node, wd) : undefined
|
|
1718
1751
|
if (row) byId.set(node.id, row)
|
|
1719
1752
|
else byId.delete(node.id)
|
|
1720
1753
|
}
|
|
1754
|
+
// Story 436: a key the workspace made its own of is its own, never Shared's beside it.
|
|
1755
|
+
for (const row of shared)
|
|
1756
|
+
if (own.has(normaliseUuid(row.key)) && byId.get(row.id) === row) byId.delete(row.id)
|
|
1721
1757
|
return [...byId.values()].sort(
|
|
1722
1758
|
(a, b) => a.level - b.level || a.sortOrder - b.sortOrder || a.id - b.id,
|
|
1723
1759
|
)
|
|
@@ -249,7 +249,11 @@ export class MediaAccessRepository {
|
|
|
249
249
|
|
|
250
250
|
/** The rule set on this folder or item itself, if any. */
|
|
251
251
|
async byNodeKey(nodeKey: string): Promise<MediaAccessEntry | undefined> {
|
|
252
|
-
|
|
252
|
+
// Story 436: Shared's item under the key first.
|
|
253
|
+
const rows = await entries(this.#db)
|
|
254
|
+
.where('n.unique_id', '=', normaliseUuid(nodeKey))
|
|
255
|
+
.orderBy((eb) => eb.case().when('n.workspace_id', 'is', null).then(0).else(1).end())
|
|
256
|
+
.execute()
|
|
253
257
|
return (await this.#hydrate(rows))[0]
|
|
254
258
|
}
|
|
255
259
|
|
|
@@ -82,6 +82,18 @@ export interface MemberFilter {
|
|
|
82
82
|
take: number
|
|
83
83
|
}
|
|
84
84
|
|
|
85
|
+
export interface MemberPageCriteria {
|
|
86
|
+
group?: string
|
|
87
|
+
type?: string
|
|
88
|
+
approved?: boolean
|
|
89
|
+
text?: string
|
|
90
|
+
/** Made or saved since. */
|
|
91
|
+
since?: Date
|
|
92
|
+
/** The node id to start after; 0 for the first page. */
|
|
93
|
+
after: number
|
|
94
|
+
take: number
|
|
95
|
+
}
|
|
96
|
+
|
|
85
97
|
/** Umbraco's `MemberFilterRepository` order columns; anything else is username. */
|
|
86
98
|
const ORDER_COLUMNS = {
|
|
87
99
|
email: 'm.email',
|
|
@@ -469,6 +481,71 @@ export class MemberRepository {
|
|
|
469
481
|
return { total: Number(counted?.total ?? 0), items }
|
|
470
482
|
}
|
|
471
483
|
|
|
484
|
+
/** Members by a cursor, in the order they were made: each page costs the same however far in (story 207). */
|
|
485
|
+
afterQuery(criteria: MemberPageCriteria) {
|
|
486
|
+
const db = this.#db
|
|
487
|
+
let query = memberColumns(joined(db)).where('m.node_id', '>', criteria.after)
|
|
488
|
+
if (criteria.type) query = query.where('ct.alias', '=', criteria.type)
|
|
489
|
+
if (criteria.approved !== undefined)
|
|
490
|
+
query = query.where(
|
|
491
|
+
'm.is_approved',
|
|
492
|
+
'=',
|
|
493
|
+
db.dialect.boolValue(criteria.approved) as boolean | number,
|
|
494
|
+
)
|
|
495
|
+
if (criteria.group) {
|
|
496
|
+
const name = criteria.group
|
|
497
|
+
query = query.where((eb) =>
|
|
498
|
+
eb.exists(
|
|
499
|
+
eb
|
|
500
|
+
.selectFrom('member_group_member as mg')
|
|
501
|
+
.innerJoin('node as g', 'g.id', 'mg.member_group_id')
|
|
502
|
+
.select(sql<number>`1`.as('one'))
|
|
503
|
+
.whereRef('mg.member_id', '=', 'm.node_id')
|
|
504
|
+
.where('g.text', '=', name),
|
|
505
|
+
),
|
|
506
|
+
)
|
|
507
|
+
}
|
|
508
|
+
if (criteria.since) {
|
|
509
|
+
const since = DbDate.toDb(criteria.since)
|
|
510
|
+
query = query.where((eb) =>
|
|
511
|
+
eb.exists(
|
|
512
|
+
eb
|
|
513
|
+
.selectFrom('content_version as v')
|
|
514
|
+
.select(sql<number>`1`.as('one'))
|
|
515
|
+
.whereRef('v.node_id', '=', 'm.node_id')
|
|
516
|
+
.where('v.current', '=', db.dialect.boolValue(true) as boolean)
|
|
517
|
+
.where('v.version_date', '>=', since),
|
|
518
|
+
),
|
|
519
|
+
)
|
|
520
|
+
}
|
|
521
|
+
const text = criteria.text?.trim().toLowerCase()
|
|
522
|
+
if (text) {
|
|
523
|
+
const like = `%${text}%`
|
|
524
|
+
query = query.where((eb) =>
|
|
525
|
+
eb.or([
|
|
526
|
+
eb(eb.fn('lower', ['m.email']), 'like', like),
|
|
527
|
+
eb(eb.fn('lower', ['m.login_name']), 'like', like),
|
|
528
|
+
eb(eb.fn('lower', ['n.text']), 'like', like),
|
|
529
|
+
]),
|
|
530
|
+
)
|
|
531
|
+
}
|
|
532
|
+
return query.orderBy('m.node_id').limit(criteria.take + 1)
|
|
533
|
+
}
|
|
534
|
+
|
|
535
|
+
/** A page of members, and where the next starts when there is one. */
|
|
536
|
+
async after(
|
|
537
|
+
criteria: MemberPageCriteria,
|
|
538
|
+
): Promise<{ items: MemberCredentials[]; next: number | undefined }> {
|
|
539
|
+
const rows = await this.afterQuery(criteria).execute()
|
|
540
|
+
const page = rows.slice(0, criteria.take)
|
|
541
|
+
const items: MemberCredentials[] = []
|
|
542
|
+
for (const row of page) items.push(await this.#hydrate(row))
|
|
543
|
+
return {
|
|
544
|
+
items,
|
|
545
|
+
next: rows.length > criteria.take ? Number(page.at(-1)?.node_id) : undefined,
|
|
546
|
+
}
|
|
547
|
+
}
|
|
548
|
+
|
|
472
549
|
/** The member picker's search: name, username or e-mail, within the types allowed. */
|
|
473
550
|
async search(
|
|
474
551
|
query: string,
|
|
@@ -81,11 +81,32 @@ const WORKSPACE_OBJECT_TYPES: Record<string, string> = {
|
|
|
81
81
|
[ObjectTypes.DocumentBlueprint]: ObjectTypes.WorkspaceDocumentBlueprint,
|
|
82
82
|
}
|
|
83
83
|
|
|
84
|
+
/**
|
|
85
|
+
* Story 436: which row a key answers when Shared and workspaces each hold one. In a
|
|
86
|
+
* workspace, its own, then Shared's; with none, Shared's. Any other is last, as a key a
|
|
87
|
+
* workspace alone made was found before.
|
|
88
|
+
*/
|
|
89
|
+
export interface NodeScope {
|
|
90
|
+
workspace?: number
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/** Story 436: how near a row is to a scope: lower is the one a key answers. */
|
|
94
|
+
const rank = (row: { workspace_id: unknown }, workspace: number | undefined): number =>
|
|
95
|
+
row.workspace_id === null || row.workspace_id === undefined
|
|
96
|
+
? workspace === undefined
|
|
97
|
+
? 0
|
|
98
|
+
: 1
|
|
99
|
+
: Number(row.workspace_id) === workspace
|
|
100
|
+
? 0
|
|
101
|
+
: 2
|
|
102
|
+
|
|
84
103
|
export class NodeRepository {
|
|
85
104
|
#db: Db
|
|
105
|
+
#workspace: number | undefined
|
|
86
106
|
|
|
87
|
-
constructor(db: Db) {
|
|
107
|
+
constructor(db: Db, scope: NodeScope = {}) {
|
|
88
108
|
this.#db = db
|
|
109
|
+
this.#workspace = scope.workspace
|
|
89
110
|
}
|
|
90
111
|
|
|
91
112
|
async byKey(key: string): Promise<NodeRow | undefined> {
|
|
@@ -94,7 +115,8 @@ export class NodeRepository {
|
|
|
94
115
|
.select(NODE_COLUMNS)
|
|
95
116
|
.where('unique_id', '=', normaliseUuid(key))
|
|
96
117
|
.execute()
|
|
97
|
-
|
|
118
|
+
const best = [...rows].sort((a, b) => rank(a, this.#workspace) - rank(b, this.#workspace))[0]
|
|
119
|
+
return best ? mapNode(best) : undefined
|
|
98
120
|
}
|
|
99
121
|
|
|
100
122
|
async byId(id: number): Promise<NodeRow | undefined> {
|
|
@@ -113,7 +135,14 @@ export class NodeRepository {
|
|
|
113
135
|
.select(NODE_COLUMNS)
|
|
114
136
|
.where('unique_id', 'in', keys.map(normaliseUuid))
|
|
115
137
|
.execute()
|
|
116
|
-
|
|
138
|
+
// Story 436: one row a key, the nearest to the scope.
|
|
139
|
+
const nearest = new Map<string, (typeof rows)[number]>()
|
|
140
|
+
for (const row of rows) {
|
|
141
|
+
const key = String(row.unique_id)
|
|
142
|
+
const held = nearest.get(key)
|
|
143
|
+
if (!held || rank(row, this.#workspace) < rank(held, this.#workspace)) nearest.set(key, row)
|
|
144
|
+
}
|
|
145
|
+
return [...nearest.values()].map(mapNode)
|
|
117
146
|
}
|
|
118
147
|
|
|
119
148
|
/**
|
|
@@ -144,7 +173,18 @@ export class NodeRepository {
|
|
|
144
173
|
workspace_id: init.workspaceId ?? null,
|
|
145
174
|
})
|
|
146
175
|
.execute()
|
|
147
|
-
|
|
176
|
+
// Story 436: the row just made, Shared's or its workspace's, never another under the key.
|
|
177
|
+
const made = await this.#db.q
|
|
178
|
+
.selectFrom('node')
|
|
179
|
+
.select(NODE_COLUMNS)
|
|
180
|
+
.where('unique_id', '=', key)
|
|
181
|
+
.where((eb) =>
|
|
182
|
+
init.workspaceId === undefined
|
|
183
|
+
? eb('workspace_id', 'is', null)
|
|
184
|
+
: eb('workspace_id', '=', init.workspaceId),
|
|
185
|
+
)
|
|
186
|
+
.executeTakeFirst()
|
|
187
|
+
const created = made ? mapNode(made) : undefined
|
|
148
188
|
if (!created) throw new Error('Node insert did not produce a row.')
|
|
149
189
|
|
|
150
190
|
const path = parent ? `${parent.path},${created.id}` : `${SystemNodes.Root},${created.id}`
|
|
@@ -182,7 +222,19 @@ export class NodeRepository {
|
|
|
182
222
|
workspaceId === undefined
|
|
183
223
|
? eb('node_object_type', '=', objectType)
|
|
184
224
|
: eb.or([
|
|
185
|
-
|
|
225
|
+
// Story 436: Shared's, unless the workspace has its own under the key.
|
|
226
|
+
eb.and([
|
|
227
|
+
eb('node_object_type', '=', objectType),
|
|
228
|
+
eb.not(
|
|
229
|
+
eb.exists(
|
|
230
|
+
eb
|
|
231
|
+
.selectFrom('node as own')
|
|
232
|
+
.select('own.id')
|
|
233
|
+
.whereRef('own.unique_id', '=', 'node.unique_id')
|
|
234
|
+
.where('own.workspace_id', '=', workspaceId),
|
|
235
|
+
),
|
|
236
|
+
),
|
|
237
|
+
]),
|
|
186
238
|
eb.and([
|
|
187
239
|
// The workspace's own of this kind (stories 375, 390).
|
|
188
240
|
eb('node_object_type', '=', WORKSPACE_OBJECT_TYPES[objectType] ?? objectType),
|
|
@@ -228,7 +280,19 @@ export class NodeRepository {
|
|
|
228
280
|
.where((eb) =>
|
|
229
281
|
workspace && own.length > 0
|
|
230
282
|
? eb.or([
|
|
231
|
-
|
|
283
|
+
// Story 436: Shared's, unless the workspace has its own under the key.
|
|
284
|
+
eb.and([
|
|
285
|
+
eb('node_object_type', 'in', objectTypes),
|
|
286
|
+
eb.not(
|
|
287
|
+
eb.exists(
|
|
288
|
+
eb
|
|
289
|
+
.selectFrom('node as own')
|
|
290
|
+
.select('own.id')
|
|
291
|
+
.whereRef('own.unique_id', '=', 'node.unique_id')
|
|
292
|
+
.where('own.workspace_id', '=', workspace.id),
|
|
293
|
+
),
|
|
294
|
+
),
|
|
295
|
+
]),
|
|
232
296
|
eb.and([eb('node_object_type', 'in', own), eb('workspace_id', '=', workspace.id)]),
|
|
233
297
|
])
|
|
234
298
|
: eb('node_object_type', 'in', objectTypes),
|
|
@@ -125,6 +125,8 @@ export class PublicAccessRepository {
|
|
|
125
125
|
async byNodeKey(nodeKey: string): Promise<PublicAccessEntry | undefined> {
|
|
126
126
|
const row = await entries(this.#db)
|
|
127
127
|
.where('n.unique_id', '=', normaliseUuid(nodeKey))
|
|
128
|
+
// Story 436: Shared's item under the key first.
|
|
129
|
+
.orderBy((eb) => eb.case().when('n.workspace_id', 'is', null).then(0).else(1).end())
|
|
128
130
|
.executeTakeFirst()
|
|
129
131
|
return row ? this.#hydrate(row) : undefined
|
|
130
132
|
}
|
|
@@ -107,6 +107,8 @@ export class ReferenceRepository {
|
|
|
107
107
|
.selectFrom('node')
|
|
108
108
|
.select('id')
|
|
109
109
|
.where('unique_id', '=', normaliseUuid(key))
|
|
110
|
+
// Story 436: Shared's item under the key first.
|
|
111
|
+
.orderBy((eb) => eb.case().when('workspace_id', 'is', null).then(0).else(1).end())
|
|
110
112
|
.execute()
|
|
111
113
|
const selfId = self[0]?.id
|
|
112
114
|
const ids = (await this.#referencingIds([key])).get(normaliseUuid(key)) ?? []
|
|
@@ -127,6 +129,7 @@ export class ReferenceRepository {
|
|
|
127
129
|
.selectFrom('node')
|
|
128
130
|
.select(['id', 'path'])
|
|
129
131
|
.where('unique_id', '=', normaliseUuid(key))
|
|
132
|
+
.orderBy((eb) => eb.case().when('workspace_id', 'is', null).then(0).else(1).end())
|
|
130
133
|
.execute()
|
|
131
134
|
const node = self[0]
|
|
132
135
|
if (!node) return { total: 0, items: [] }
|
|
@@ -163,6 +166,7 @@ export class ReferenceRepository {
|
|
|
163
166
|
.selectFrom('node')
|
|
164
167
|
.select('id')
|
|
165
168
|
.where('unique_id', '=', key)
|
|
169
|
+
.orderBy((eb) => eb.case().when('workspace_id', 'is', null).then(0).else(1).end())
|
|
166
170
|
.execute()
|
|
167
171
|
if (rows[0]) selfIds.set(key, Number(rows[0].id))
|
|
168
172
|
}
|
|
@@ -50,6 +50,15 @@ export interface UserRecord {
|
|
|
50
50
|
startNodes: Record<StartNodeTree, StartNodeSelection>
|
|
51
51
|
}
|
|
52
52
|
|
|
53
|
+
/** Story 433: a client id an account holds. */
|
|
54
|
+
export interface ClientCredentialDetail {
|
|
55
|
+
clientId: string
|
|
56
|
+
addedAt: Date
|
|
57
|
+
lastUsedAt: Date | undefined
|
|
58
|
+
/** While a replaced secret still works, when it stops. */
|
|
59
|
+
oldSecretUntil: Date | undefined
|
|
60
|
+
}
|
|
61
|
+
|
|
53
62
|
export type UserState = 'Active' | 'Disabled' | 'LockedOut' | 'Invited' | 'Inactive'
|
|
54
63
|
|
|
55
64
|
/** Umbraco's `User.UserState`. */
|
|
@@ -222,6 +231,8 @@ export class UserRepository {
|
|
|
222
231
|
.selectFrom('node')
|
|
223
232
|
.select(['id', 'unique_id'])
|
|
224
233
|
.where('unique_id', 'in', wanted)
|
|
234
|
+
// Story 436: Shared's item under a key last, so the map keeps it.
|
|
235
|
+
.orderBy((eb) => eb.case().when('workspace_id', 'is', null).then(1).else(0).end())
|
|
225
236
|
.execute()
|
|
226
237
|
const map = new Map(rows.map((r) => [normaliseUuid(String(r.unique_id)), Number(r.id)]))
|
|
227
238
|
return wanted.every((k) => map.has(k)) ? map : undefined
|
|
@@ -578,11 +589,90 @@ export class UserRepository {
|
|
|
578
589
|
return true
|
|
579
590
|
}
|
|
580
591
|
|
|
592
|
+
/** Removes the client id, and ends the sessions signed in with it (story 433). */
|
|
581
593
|
async removeClientCredential(userId: number, clientId: string): Promise<void> {
|
|
582
|
-
await this.#db.
|
|
583
|
-
.
|
|
594
|
+
await this.#db.transaction(async (tx) => {
|
|
595
|
+
const now = DbDate.toDb(new Date())
|
|
596
|
+
const sessions = await tx.q
|
|
597
|
+
.selectFrom('auth_token')
|
|
598
|
+
.select('session_id')
|
|
599
|
+
.where('user_id', '=', userId)
|
|
600
|
+
.where('client_id', '=', clientId)
|
|
601
|
+
.execute()
|
|
602
|
+
const ids = [...new Set(sessions.map((s) => s.session_id).filter((s): s is string => !!s))]
|
|
603
|
+
await tx.q
|
|
604
|
+
.updateTable('auth_token')
|
|
605
|
+
.set({ revoked_at: now })
|
|
606
|
+
.where('user_id', '=', userId)
|
|
607
|
+
.where('client_id', '=', clientId)
|
|
608
|
+
.where('revoked_at', 'is', null)
|
|
609
|
+
.execute()
|
|
610
|
+
if (ids.length > 0)
|
|
611
|
+
await tx.q
|
|
612
|
+
.updateTable('user_login_session')
|
|
613
|
+
.set({ logged_out_utc: now })
|
|
614
|
+
.where('session_id', 'in', ids)
|
|
615
|
+
.where('logged_out_utc', 'is', null)
|
|
616
|
+
.execute()
|
|
617
|
+
await tx.q
|
|
618
|
+
.deleteFrom('user_client_credential')
|
|
619
|
+
.where('user_id', '=', userId)
|
|
620
|
+
.where('client_id', '=', clientId)
|
|
621
|
+
.execute()
|
|
622
|
+
})
|
|
623
|
+
}
|
|
624
|
+
|
|
625
|
+
/** Story 433: each client id an account holds, when it was added and last used. */
|
|
626
|
+
async clientCredentialDetails(userId: number): Promise<ClientCredentialDetail[]> {
|
|
627
|
+
const rows = await this.#db.q
|
|
628
|
+
.selectFrom('user_client_credential')
|
|
629
|
+
.select(['client_id', 'create_date', 'last_used_at', 'old_secret_until'])
|
|
584
630
|
.where('user_id', '=', userId)
|
|
631
|
+
.orderBy('client_id')
|
|
632
|
+
.execute()
|
|
633
|
+
const now = Date.now()
|
|
634
|
+
return rows.map((row) => {
|
|
635
|
+
const until = DbDate.fromDb(row.old_secret_until)
|
|
636
|
+
return {
|
|
637
|
+
clientId: String(row.client_id),
|
|
638
|
+
addedAt: DbDate.fromDb(row.create_date) ?? new Date(0),
|
|
639
|
+
lastUsedAt: DbDate.fromDb(row.last_used_at),
|
|
640
|
+
oldSecretUntil: until && until.getTime() > now ? until : undefined,
|
|
641
|
+
}
|
|
642
|
+
})
|
|
643
|
+
}
|
|
644
|
+
|
|
645
|
+
/**
|
|
646
|
+
* Story 433: a new secret for the client id. The one it replaces keeps working until
|
|
647
|
+
* `oldUntil`, or stops at once without one.
|
|
648
|
+
*/
|
|
649
|
+
async replaceClientSecret(
|
|
650
|
+
clientId: string,
|
|
651
|
+
secretHash: string,
|
|
652
|
+
oldUntil: Date | undefined,
|
|
653
|
+
): Promise<boolean> {
|
|
654
|
+
const found = await this.clientCredentialOwner(clientId)
|
|
655
|
+
if (!found) return false
|
|
656
|
+
await this.#db.q
|
|
657
|
+
.updateTable('user_client_credential')
|
|
658
|
+
.set({
|
|
659
|
+
secret_hash: secretHash,
|
|
660
|
+
old_secret_hash: oldUntil ? found.secretHash : null,
|
|
661
|
+
old_secret_until: oldUntil ? DbDate.toDb(oldUntil) : null,
|
|
662
|
+
})
|
|
663
|
+
.where('client_id', '=', clientId)
|
|
664
|
+
.execute()
|
|
665
|
+
return true
|
|
666
|
+
}
|
|
667
|
+
|
|
668
|
+
/** Story 433: the client id was used now; written at most once an hour. */
|
|
669
|
+
async touchClientCredential(clientId: string, now = new Date()): Promise<void> {
|
|
670
|
+
const hourAgo = DbDate.toDb(new Date(now.getTime() - 60 * 60 * 1000))
|
|
671
|
+
await this.#db.q
|
|
672
|
+
.updateTable('user_client_credential')
|
|
673
|
+
.set({ last_used_at: DbDate.toDb(now) })
|
|
585
674
|
.where('client_id', '=', clientId)
|
|
675
|
+
.where((eb) => eb.or([eb('last_used_at', 'is', null), eb('last_used_at', '<', hourAgo)]))
|
|
586
676
|
.execute()
|
|
587
677
|
}
|
|
588
678
|
|
|
@@ -607,6 +697,8 @@ export class UserRepository {
|
|
|
607
697
|
.selectFrom('node')
|
|
608
698
|
.select(NODE_COLUMNS)
|
|
609
699
|
.where('unique_id', 'in', keys)
|
|
700
|
+
// Story 436: Shared's item under a key last, so the map keeps it.
|
|
701
|
+
.orderBy((eb) => eb.case().when('workspace_id', 'is', null).then(1).else(0).end())
|
|
610
702
|
.execute()
|
|
611
703
|
: []
|
|
612
704
|
const byKey = new Map(rows.map((r) => [normaliseUuid(String(r.unique_id)), mapNode(r)]))
|
|
@@ -282,6 +282,29 @@ export class WorkspaceRepository {
|
|
|
282
282
|
}
|
|
283
283
|
|
|
284
284
|
/** Removes the workspace and everything carrying it; Shared is as it was. `by` discarded it. */
|
|
285
|
+
/**
|
|
286
|
+
* Story 434: what outside this workspace is of a content type it made, by name, with the
|
|
287
|
+
* workspace that holds it, null for Shared. While any is, it cannot be discarded.
|
|
288
|
+
*/
|
|
289
|
+
async typesUsedElsewhere(
|
|
290
|
+
id: number,
|
|
291
|
+
): Promise<Array<{ name: string; type: string; workspace: string | null }>> {
|
|
292
|
+
const rows = await this.#db.q
|
|
293
|
+
.selectFrom('content as c')
|
|
294
|
+
.innerJoin('content_type as t', 't.node_id', 'c.content_type_id')
|
|
295
|
+
.innerJoin('node as n', 'n.id', 'c.node_id')
|
|
296
|
+
.leftJoin('workspace as w', 'w.id', 'n.workspace_id')
|
|
297
|
+
.select(['n.text', 't.alias', 'w.name'])
|
|
298
|
+
.where('t.workspace_id', '=', id)
|
|
299
|
+
.where((eb) => eb.or([eb('n.workspace_id', 'is', null), eb('n.workspace_id', '!=', id)]))
|
|
300
|
+
.execute()
|
|
301
|
+
return rows.map((row) => ({
|
|
302
|
+
name: String(row.text ?? ''),
|
|
303
|
+
type: String(row.alias),
|
|
304
|
+
workspace: row.name === null || row.name === undefined ? null : String(row.name),
|
|
305
|
+
}))
|
|
306
|
+
}
|
|
307
|
+
|
|
285
308
|
async discard(id: number, by?: string | null, options: { quiet?: boolean } = {}): Promise<void> {
|
|
286
309
|
await this.#db.locks.withLock(Locks.ContentTree, () =>
|
|
287
310
|
this.#db.transaction(async (tx) => {
|
|
@@ -290,8 +313,19 @@ export class WorkspaceRepository {
|
|
|
290
313
|
await recordWorkspaceEvent(tx, WORKSPACE_DISCARDED, factsOf(gone), { by })
|
|
291
314
|
const versions = () =>
|
|
292
315
|
tx.q.selectFrom('content_version').select('id').where('workspace_id', '=', id)
|
|
316
|
+
// Story 434: its pages first; its types and data types go with its schema, after them.
|
|
293
317
|
const made = (
|
|
294
|
-
await tx.q
|
|
318
|
+
await tx.q
|
|
319
|
+
.selectFrom('node')
|
|
320
|
+
.select('id')
|
|
321
|
+
.where('workspace_id', '=', id)
|
|
322
|
+
.where('id', 'not in', (eb) =>
|
|
323
|
+
eb.selectFrom('content_type').select('node_id').where('workspace_id', '=', id),
|
|
324
|
+
)
|
|
325
|
+
.where('id', 'not in', (eb) =>
|
|
326
|
+
eb.selectFrom('data_type').select('node_id').where('workspace_id', '=', id),
|
|
327
|
+
)
|
|
328
|
+
.execute()
|
|
295
329
|
).map((row) => Number(row.id))
|
|
296
330
|
await tx.q.deleteFrom('property_value').where('workspace_id', '=', id).execute()
|
|
297
331
|
await tx.q
|
|
@@ -532,6 +566,21 @@ export class WorkspaceRepository {
|
|
|
532
566
|
* when. Called inside the merge's transaction, holding the tree's lock.
|
|
533
567
|
*/
|
|
534
568
|
async closeMerged(id: number, by: string): Promise<void> {
|
|
569
|
+
// Story 436: its own copies of items Shared had already went in as changes to Shared's.
|
|
570
|
+
const copies = (
|
|
571
|
+
await this.#db.q
|
|
572
|
+
.selectFrom('node')
|
|
573
|
+
.select('id')
|
|
574
|
+
.where('workspace_id', '=', id)
|
|
575
|
+
.where('id', 'not in', (eb) =>
|
|
576
|
+
eb.selectFrom('content_type').select('node_id').where('workspace_id', '=', id),
|
|
577
|
+
)
|
|
578
|
+
.where('id', 'not in', (eb) =>
|
|
579
|
+
eb.selectFrom('data_type').select('node_id').where('workspace_id', '=', id),
|
|
580
|
+
)
|
|
581
|
+
.execute()
|
|
582
|
+
).map((row) => Number(row.id))
|
|
583
|
+
if (copies.length > 0) await deleteNodeRows(this.#db, { ids: copies })
|
|
535
584
|
const versions = () =>
|
|
536
585
|
this.#db.q.selectFrom('content_version').select('id').where('workspace_id', '=', id)
|
|
537
586
|
await this.#db.q.deleteFrom('property_value').where('workspace_id', '=', id).execute()
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Migration 101 — a key once in Shared, and once in each workspace (story 436). An item's
|
|
3
|
+
* key, `node.unique_id`, was unique across the site, so an open workspace making a page
|
|
4
|
+
* held its key from every other. It is unique among Shared's items and within each
|
|
5
|
+
* workspace now, by two partial indexes, with a plain one for reading by key. SQLite
|
|
6
|
+
* cannot drop a column's `UNIQUE`, so `node` is rebuilt (`Db.rebuildTable`), with foreign
|
|
7
|
+
* keys off for the step.
|
|
8
|
+
*/
|
|
9
|
+
import type { Db } from '../database.ts'
|
|
10
|
+
import type { Migration } from '../migrations.ts'
|
|
11
|
+
import { sql } from '../query.ts'
|
|
12
|
+
import { STATE_USERS_IN_SETTINGS } from './users-in-settings.ts'
|
|
13
|
+
|
|
14
|
+
export const STATE_KEYS_PER_WORKSPACE = '{8d3a5f17-0101-4b2e-9c64-1e7f0a5b0101}'
|
|
15
|
+
|
|
16
|
+
/** The indexes that keep keys apart: one key in Shared, one per workspace, and reads by key. */
|
|
17
|
+
export async function addKeyIndexes(db: Db): Promise<void> {
|
|
18
|
+
const schema = db.q.schema
|
|
19
|
+
await schema
|
|
20
|
+
.createIndex('ux_node_key_shared')
|
|
21
|
+
.on('node')
|
|
22
|
+
.column('unique_id')
|
|
23
|
+
.unique()
|
|
24
|
+
.where(sql.ref('workspace_id'), 'is', null)
|
|
25
|
+
.execute()
|
|
26
|
+
await schema
|
|
27
|
+
.createIndex('ux_node_key_workspace')
|
|
28
|
+
.on('node')
|
|
29
|
+
.columns(['unique_id', 'workspace_id'])
|
|
30
|
+
.unique()
|
|
31
|
+
.where(sql.ref('workspace_id'), 'is not', null)
|
|
32
|
+
.execute()
|
|
33
|
+
await schema.createIndex('ix_node_unique_id').on('node').column('unique_id').execute()
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** `unique_id`'s definition in SQLite's `node`, made unique across the site or not. */
|
|
37
|
+
export const nodeKeyDefinition =
|
|
38
|
+
(unique: boolean) =>
|
|
39
|
+
(definition: string): string =>
|
|
40
|
+
unique
|
|
41
|
+
? definition.replace(/(unique_id\s+\S+\s+NOT NULL)(?!\s+UNIQUE)/i, '$1 UNIQUE')
|
|
42
|
+
: definition.replace(/(unique_id\s+\S+\s+NOT NULL)\s+UNIQUE/i, '$1')
|
|
43
|
+
|
|
44
|
+
export const keysPerWorkspaceMigration: Migration = {
|
|
45
|
+
from: STATE_USERS_IN_SETTINGS,
|
|
46
|
+
to: STATE_KEYS_PER_WORKSPACE,
|
|
47
|
+
name: 'KeysPerWorkspace',
|
|
48
|
+
kind: 'expand',
|
|
49
|
+
release: '0.81.0',
|
|
50
|
+
foreignKeysOff: true,
|
|
51
|
+
async up(db: Db) {
|
|
52
|
+
if (db.rebuildTable) await db.rebuildTable('node', nodeKeyDefinition(false))
|
|
53
|
+
else
|
|
54
|
+
await db.q.schema.alterTable('node').dropConstraint('node_unique_id_key').ifExists().execute()
|
|
55
|
+
await addKeyIndexes(db)
|
|
56
|
+
},
|
|
57
|
+
}
|
package/src/schema/plan.ts
CHANGED
|
@@ -61,6 +61,7 @@ import { groupStartKeysMigration } from './group-start-keys.ts'
|
|
|
61
61
|
import { identityMigration } from './identity.ts'
|
|
62
62
|
import { imageAltTextMigration } from './image-alt-text.ts'
|
|
63
63
|
import { jobsMigration } from './jobs.ts'
|
|
64
|
+
import { keysPerWorkspaceMigration } from './keys-per-workspace.ts'
|
|
64
65
|
import { logViewerMigration } from './log-viewer.ts'
|
|
65
66
|
import { mediaAccessMigration } from './media-access.ts'
|
|
66
67
|
import { mediaCacheMigration } from './media-cache.ts'
|
|
@@ -83,6 +84,7 @@ import { searchIndexMigration } from './search-index.ts'
|
|
|
83
84
|
import { searchRemovalsMigration } from './search-removals.ts'
|
|
84
85
|
import { servedChangesMigration } from './served-changes.ts'
|
|
85
86
|
import { serverRoleMigration } from './server-role.ts'
|
|
87
|
+
import { serviceAccountSecretsMigration } from './service-account-secrets.ts'
|
|
86
88
|
import { sessionViewAsMigration } from './session-view-as.ts'
|
|
87
89
|
import { sinceVersionMigration } from './since-version.ts'
|
|
88
90
|
import { singleUseTokenMigration } from './single-use-token.ts'
|
|
@@ -215,4 +217,6 @@ export const cromboloPlan = new MigrationPlan([
|
|
|
215
217
|
workspacePlacesMigration,
|
|
216
218
|
workspaceDescriptionMigration,
|
|
217
219
|
usersInSettingsMigration,
|
|
220
|
+
keysPerWorkspaceMigration,
|
|
221
|
+
serviceAccountSecretsMigration,
|
|
218
222
|
])
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Migration 102 — service accounts' secrets (story 433): when each client id was last used,
|
|
3
|
+
* and the secret it is moving from with when that stops, so a secret is replaced with no gap.
|
|
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_KEYS_PER_WORKSPACE } from './keys-per-workspace.ts'
|
|
9
|
+
|
|
10
|
+
export const STATE_SERVICE_ACCOUNT_SECRETS = '{3c9e1b74-0102-4f6a-8d25-7b0e4a1c0102}'
|
|
11
|
+
|
|
12
|
+
export const serviceAccountSecretsMigration: Migration = {
|
|
13
|
+
from: STATE_KEYS_PER_WORKSPACE,
|
|
14
|
+
to: STATE_SERVICE_ACCOUNT_SECRETS,
|
|
15
|
+
name: 'AddServiceAccountSecrets',
|
|
16
|
+
kind: 'expand',
|
|
17
|
+
release: '0.81.0',
|
|
18
|
+
async up(db: Db) {
|
|
19
|
+
const ops = schemaOps(db)
|
|
20
|
+
const t = db.dialect.types
|
|
21
|
+
await ops.addColumn('user_client_credential', 'last_used_at', t.timestamp)
|
|
22
|
+
await ops.addColumn('user_client_credential', 'old_secret_hash', t.varchar(255))
|
|
23
|
+
await ops.addColumn('user_client_credential', 'old_secret_until', t.timestamp)
|
|
24
|
+
},
|
|
25
|
+
}
|
package/src/tables.gen.ts
CHANGED
|
@@ -913,6 +913,9 @@ export interface CoreTables {
|
|
|
913
913
|
user_client_credential: {
|
|
914
914
|
client_id: string
|
|
915
915
|
create_date: Timestamp
|
|
916
|
+
last_used_at: Timestamp | null
|
|
917
|
+
old_secret_hash: string | null
|
|
918
|
+
old_secret_until: Timestamp | null
|
|
916
919
|
secret_hash: string
|
|
917
920
|
user_id: number
|
|
918
921
|
}
|