@crombolo/server 0.65.1 → 0.66.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +15 -14
- package/src/adapters/blueprints.ts +19 -5
- package/src/adapters/elements.ts +49 -36
- package/src/adapters/members.ts +37 -3
- package/src/adapters/users.ts +18 -0
- package/src/approvals.ts +15 -0
- package/src/atomic-write.ts +2 -2
- package/src/background-jobs.ts +170 -0
- package/src/cli-tokens-api.ts +152 -0
- package/src/config.ts +35 -1
- package/src/content-events.ts +22 -0
- package/src/content-operations.ts +26 -1
- package/src/extension-activity.ts +121 -0
- package/src/index.ts +14 -0
- package/src/media-access.ts +30 -125
- package/src/media-library.ts +953 -0
- package/src/member-admin.ts +761 -0
- package/src/node-operations.ts +19 -2
- package/src/ports.ts +2 -0
- package/src/principal.ts +35 -0
- package/src/remote-background-jobs.ts +99 -0
- package/src/remote-credentials.ts +114 -6
- package/src/remote-extension-activity.ts +66 -0
- package/src/remote-media-library.ts +297 -0
- package/src/remote-media.ts +2 -2
- package/src/remote-members.ts +271 -0
- package/src/remote-undo.ts +234 -0
- package/src/remote-users.ts +229 -0
- package/src/remote.ts +141 -3
- package/src/seed/values.ts +82 -4
- package/src/seo.ts +81 -61
- package/src/server.ts +97 -94
- package/src/settings.ts +86 -0
- package/src/undo.ts +358 -0
- package/src/user-admin.ts +581 -0
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@crombolo/server",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.66.0",
|
|
4
4
|
"description": "Internal to crombolo, with no compatibility promise: use @crombolo/crombolo. The crombolo HTTP server: routing, configuration, media stores and background jobs.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"author": "Crombolo",
|
|
@@ -21,6 +21,7 @@
|
|
|
21
21
|
".": "./src/index.ts",
|
|
22
22
|
"./remote-credentials": "./src/remote-credentials.ts",
|
|
23
23
|
"./atomic-write": "./src/atomic-write.ts",
|
|
24
|
+
"./settings": "./src/settings.ts",
|
|
24
25
|
"./worker": "./src/worker.ts"
|
|
25
26
|
},
|
|
26
27
|
"files": [
|
|
@@ -31,19 +32,19 @@
|
|
|
31
32
|
"access": "public"
|
|
32
33
|
},
|
|
33
34
|
"dependencies": {
|
|
34
|
-
"@crombolo/api-delivery": "0.
|
|
35
|
-
"@crombolo/api-management": "0.
|
|
36
|
-
"@crombolo/auth": "0.
|
|
37
|
-
"@crombolo/backoffice-host": "0.
|
|
38
|
-
"@crombolo/common": "0.
|
|
39
|
-
"@crombolo/content": "0.
|
|
40
|
-
"@crombolo/contracts": "0.
|
|
41
|
-
"@crombolo/core": "0.
|
|
42
|
-
"@crombolo/data": "0.
|
|
43
|
-
"@crombolo/extension": "0.
|
|
44
|
-
"@crombolo/render": "0.
|
|
45
|
-
"@crombolo/schema": "0.
|
|
46
|
-
"@crombolo/transfer": "0.
|
|
35
|
+
"@crombolo/api-delivery": "0.66.0",
|
|
36
|
+
"@crombolo/api-management": "0.66.0",
|
|
37
|
+
"@crombolo/auth": "0.66.0",
|
|
38
|
+
"@crombolo/backoffice-host": "0.66.0",
|
|
39
|
+
"@crombolo/common": "0.66.0",
|
|
40
|
+
"@crombolo/content": "0.66.0",
|
|
41
|
+
"@crombolo/contracts": "0.66.0",
|
|
42
|
+
"@crombolo/core": "0.66.0",
|
|
43
|
+
"@crombolo/data": "0.66.0",
|
|
44
|
+
"@crombolo/extension": "0.66.0",
|
|
45
|
+
"@crombolo/render": "0.66.0",
|
|
46
|
+
"@crombolo/schema": "0.66.0",
|
|
47
|
+
"@crombolo/transfer": "0.66.0",
|
|
47
48
|
"@logtape/logtape": "^2.3.8",
|
|
48
49
|
"@opentelemetry/api": "1.10.0",
|
|
49
50
|
"@opentelemetry/context-async-hooks": "3.0.0",
|
|
@@ -9,6 +9,7 @@ import {
|
|
|
9
9
|
type Db,
|
|
10
10
|
DocumentRepository,
|
|
11
11
|
FolderRepository,
|
|
12
|
+
LanguageRepository,
|
|
12
13
|
type NodeSchemaState,
|
|
13
14
|
type ValueIntake,
|
|
14
15
|
WriteRejectedError,
|
|
@@ -43,6 +44,8 @@ export function createBlueprintPort(
|
|
|
43
44
|
.execute()
|
|
44
45
|
return rows[0] ? Number(rows[0].id) : undefined
|
|
45
46
|
}
|
|
47
|
+
const defaultCulture = async (): Promise<string | undefined> =>
|
|
48
|
+
(await new LanguageRepository(db).all()).find((l) => l.isDefault)?.isoCode
|
|
46
49
|
const failure = (error: unknown) => {
|
|
47
50
|
if (error instanceof WriteRejectedError)
|
|
48
51
|
return { ok: false as const, reason: error.message, status: 409 }
|
|
@@ -86,17 +89,28 @@ export function createBlueprintPort(
|
|
|
86
89
|
if (!document)
|
|
87
90
|
return { ok: false as const, reason: 'The document could not be found.', status: 404 }
|
|
88
91
|
try {
|
|
92
|
+
// As Umbraco names one: a page in several languages gets the name in its
|
|
93
|
+
// default one, which comes first so the tree shows it; the others keep theirs.
|
|
94
|
+
const defaultIso = (await defaultCulture())?.toLowerCase()
|
|
95
|
+
const named =
|
|
96
|
+
document.variants.find((v) => v.culture === null) ??
|
|
97
|
+
document.variants.find((v) => v.culture?.toLowerCase() === defaultIso) ??
|
|
98
|
+
document.variants[0]
|
|
99
|
+
const variants = [
|
|
100
|
+
...(named ? [named] : []),
|
|
101
|
+
...document.variants.filter((v) => v !== named),
|
|
102
|
+
].map((v) => ({
|
|
103
|
+
culture: v.culture,
|
|
104
|
+
segment: v.segment,
|
|
105
|
+
name: v === named ? init.name : v.name,
|
|
106
|
+
}))
|
|
89
107
|
const created = await repo.create({
|
|
90
108
|
key: init.key,
|
|
91
109
|
contentTypeKey: document.contentTypeKey,
|
|
92
110
|
componentKey: null,
|
|
93
111
|
parentKey: init.parentKey,
|
|
94
112
|
values: document.values,
|
|
95
|
-
variants
|
|
96
|
-
culture: v.culture,
|
|
97
|
-
segment: v.segment,
|
|
98
|
-
name: v.culture === null ? init.name : v.name,
|
|
99
|
-
})),
|
|
113
|
+
variants,
|
|
100
114
|
userId: await userIdOf(principal),
|
|
101
115
|
})
|
|
102
116
|
return { ok: true as const, key: created.key }
|
package/src/adapters/elements.ts
CHANGED
|
@@ -11,7 +11,7 @@
|
|
|
11
11
|
* by the generic folder repository, which is why they worked before elements
|
|
12
12
|
* themselves did.
|
|
13
13
|
*/
|
|
14
|
-
import type {
|
|
14
|
+
import type { ElementAuthor, ElementPort } from '@crombolo/api-management/domain'
|
|
15
15
|
import {
|
|
16
16
|
type ElementTreeItem,
|
|
17
17
|
MENU_ALIAS_PROPERTY,
|
|
@@ -37,11 +37,43 @@ import {
|
|
|
37
37
|
import { TemporaryFileMissingError } from '../file-intake.ts'
|
|
38
38
|
import { createFolderPort, createSettingsTree } from './content.ts'
|
|
39
39
|
|
|
40
|
+
/** The menus, not in the bin, that answer to `alias`, by key. */
|
|
41
|
+
async function menuKeysByAlias(db: Db, alias: string): Promise<string[]> {
|
|
42
|
+
const rows = await db.q
|
|
43
|
+
.selectFrom('property_value as pv')
|
|
44
|
+
.innerJoin('property_type as p', 'p.id', 'pv.property_type_id')
|
|
45
|
+
.innerJoin('node as n', 'n.id', 'pv.node_id')
|
|
46
|
+
.innerJoin('content as c', 'c.node_id', 'n.id')
|
|
47
|
+
.innerJoin('node as ct', 'ct.id', 'c.content_type_id')
|
|
48
|
+
.select('n.unique_id')
|
|
49
|
+
.where('p.alias', '=', MENU_ALIAS_PROPERTY)
|
|
50
|
+
.where('pv.is_current', '=', db.dialect.boolValue(true) as boolean)
|
|
51
|
+
.where('n.trashed', '=', db.dialect.boolValue(false) as boolean)
|
|
52
|
+
.where('ct.unique_id', '=', SYSTEM_CONTENT_TYPE_KEYS.Menu)
|
|
53
|
+
.where(
|
|
54
|
+
(eb) => eb.fn('lower', [eb.fn.coalesce('pv.varchar_value', 'pv.text_value')]),
|
|
55
|
+
'=',
|
|
56
|
+
alias.toLowerCase(),
|
|
57
|
+
)
|
|
58
|
+
.execute()
|
|
59
|
+
return [...new Set(rows.map((row) => normaliseUuid(String(row.unique_id))))]
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* The menu a template's `menu(alias)` names, by the draft's key (story 361);
|
|
64
|
+
* undefined when no menu outside the bin has that alias.
|
|
65
|
+
*/
|
|
66
|
+
export async function menuByAlias(db: Db, alias: string): Promise<string | undefined> {
|
|
67
|
+
return (await menuKeysByAlias(db, alias))[0]
|
|
68
|
+
}
|
|
69
|
+
|
|
40
70
|
export function createElementPort(
|
|
41
71
|
db: Db,
|
|
42
72
|
options: {
|
|
43
73
|
nodeState?: NodeSchemaState
|
|
44
74
|
nodeId?: string
|
|
75
|
+
/** Who its cache instructions say they are from; the node, unless said otherwise. */
|
|
76
|
+
instructedBy?: string
|
|
45
77
|
valueIntake?: ValueIntake
|
|
46
78
|
/** Told after every change, so pages that resolved an element refresh. */
|
|
47
79
|
onChange?: () => void | Promise<void>
|
|
@@ -55,17 +87,18 @@ export function createElementPort(
|
|
|
55
87
|
await appendCacheInstruction(db, {
|
|
56
88
|
kind: 'content',
|
|
57
89
|
payload: { elements: true },
|
|
58
|
-
by: options.nodeId,
|
|
90
|
+
by: options.instructedBy ?? options.nodeId,
|
|
59
91
|
})
|
|
60
92
|
await options.onChange?.()
|
|
61
93
|
}
|
|
62
94
|
const tree = createSettingsTree(nodes, ObjectTypes.ElementContainer, ObjectTypes.Element, changed)
|
|
63
95
|
|
|
64
|
-
const userIdOf = async (
|
|
96
|
+
const userIdOf = async (author: ElementAuthor): Promise<number | undefined> => {
|
|
97
|
+
if (!author) return undefined
|
|
65
98
|
const rows = await db.q
|
|
66
99
|
.selectFrom('user_account')
|
|
67
100
|
.select('id')
|
|
68
|
-
.where('key', '=',
|
|
101
|
+
.where('key', '=', author.id)
|
|
69
102
|
.execute()
|
|
70
103
|
return rows[0] ? Number(rows[0].id) : undefined
|
|
71
104
|
}
|
|
@@ -88,26 +121,8 @@ export function createElementPort(
|
|
|
88
121
|
const saved = <T extends object>(input: T) => ({ ...input, componentKey: null })
|
|
89
122
|
|
|
90
123
|
/** Whether another menu, not in the bin, already answers to `alias`. */
|
|
91
|
-
const menuAliasTaken = async (alias: string, key: string | undefined): Promise<boolean> =>
|
|
92
|
-
|
|
93
|
-
.selectFrom('property_value as pv')
|
|
94
|
-
.innerJoin('property_type as p', 'p.id', 'pv.property_type_id')
|
|
95
|
-
.innerJoin('node as n', 'n.id', 'pv.node_id')
|
|
96
|
-
.innerJoin('content as c', 'c.node_id', 'n.id')
|
|
97
|
-
.innerJoin('node as ct', 'ct.id', 'c.content_type_id')
|
|
98
|
-
.select('n.unique_id')
|
|
99
|
-
.where('p.alias', '=', MENU_ALIAS_PROPERTY)
|
|
100
|
-
.where('pv.is_current', '=', db.dialect.boolValue(true) as boolean)
|
|
101
|
-
.where('n.trashed', '=', db.dialect.boolValue(false) as boolean)
|
|
102
|
-
.where('ct.unique_id', '=', SYSTEM_CONTENT_TYPE_KEYS.Menu)
|
|
103
|
-
.where(
|
|
104
|
-
(eb) => eb.fn('lower', [eb.fn.coalesce('pv.varchar_value', 'pv.text_value')]),
|
|
105
|
-
'=',
|
|
106
|
-
alias.toLowerCase(),
|
|
107
|
-
)
|
|
108
|
-
.execute()
|
|
109
|
-
return rows.some((row) => normaliseUuid(String(row.unique_id)) !== key?.toLowerCase())
|
|
110
|
-
}
|
|
124
|
+
const menuAliasTaken = async (alias: string, key: string | undefined): Promise<boolean> =>
|
|
125
|
+
(await menuKeysByAlias(db, alias)).some((found) => found !== key?.toLowerCase())
|
|
111
126
|
|
|
112
127
|
/**
|
|
113
128
|
* A menu's alias, filled from its name when left empty, as Umbraco makes a type's
|
|
@@ -195,11 +210,11 @@ export function createElementPort(
|
|
|
195
210
|
byKeyPublished: (key) => repo.byKeyPublished(key),
|
|
196
211
|
validate: (input, cultures) => repo.validate(input, cultures),
|
|
197
212
|
|
|
198
|
-
async create(sent,
|
|
213
|
+
async create(sent, author) {
|
|
199
214
|
const input = await withMenuAlias(sent)
|
|
200
215
|
if (refused(input)) return input
|
|
201
216
|
try {
|
|
202
|
-
const created = await repo.create(saved({ ...input, userId: await userIdOf(
|
|
217
|
+
const created = await repo.create(saved({ ...input, userId: await userIdOf(author) }))
|
|
203
218
|
await changed()
|
|
204
219
|
return { ok: true as const, key: created.key }
|
|
205
220
|
} catch (error) {
|
|
@@ -207,13 +222,11 @@ export function createElementPort(
|
|
|
207
222
|
}
|
|
208
223
|
},
|
|
209
224
|
|
|
210
|
-
async update(key, sent,
|
|
225
|
+
async update(key, sent, author) {
|
|
211
226
|
const input = await withMenuAlias(sent, key)
|
|
212
227
|
if (refused(input)) return input
|
|
213
228
|
try {
|
|
214
|
-
const updated = await repo.update(
|
|
215
|
-
saved({ ...input, key, userId: await userIdOf(principal) }),
|
|
216
|
-
)
|
|
229
|
+
const updated = await repo.update(saved({ ...input, key, userId: await userIdOf(author) }))
|
|
217
230
|
if (!updated) return notFound()
|
|
218
231
|
await changed()
|
|
219
232
|
return { ok: true as const }
|
|
@@ -222,12 +235,12 @@ export function createElementPort(
|
|
|
222
235
|
}
|
|
223
236
|
},
|
|
224
237
|
|
|
225
|
-
async createAndPublish(sent, cultures,
|
|
238
|
+
async createAndPublish(sent, cultures, author) {
|
|
226
239
|
const input = await withMenuAlias(sent)
|
|
227
240
|
if (refused(input)) return input
|
|
228
241
|
try {
|
|
229
242
|
const result = await repo.createAndPublish(
|
|
230
|
-
saved({ ...input, userId: await userIdOf(
|
|
243
|
+
saved({ ...input, userId: await userIdOf(author) }),
|
|
231
244
|
cultures,
|
|
232
245
|
)
|
|
233
246
|
if (!result.ok)
|
|
@@ -244,12 +257,12 @@ export function createElementPort(
|
|
|
244
257
|
}
|
|
245
258
|
},
|
|
246
259
|
|
|
247
|
-
async updateAndPublish(key, sent, cultures,
|
|
260
|
+
async updateAndPublish(key, sent, cultures, author) {
|
|
248
261
|
const input = await withMenuAlias(sent, key)
|
|
249
262
|
if (refused(input)) return input
|
|
250
263
|
try {
|
|
251
264
|
const result = await repo.updateAndPublish(
|
|
252
|
-
saved({ ...input, key, userId: await userIdOf(
|
|
265
|
+
saved({ ...input, key, userId: await userIdOf(author) }),
|
|
253
266
|
cultures,
|
|
254
267
|
)
|
|
255
268
|
if (!result) return notFound()
|
|
@@ -306,11 +319,11 @@ export function createElementPort(
|
|
|
306
319
|
}
|
|
307
320
|
},
|
|
308
321
|
|
|
309
|
-
async copy(key, targetKey, copyOptions,
|
|
322
|
+
async copy(key, targetKey, copyOptions, author) {
|
|
310
323
|
try {
|
|
311
324
|
const copied = await repo.copy(key, targetKey, {
|
|
312
325
|
includeDescendants: copyOptions.includeDescendants,
|
|
313
|
-
userId: await userIdOf(
|
|
326
|
+
userId: await userIdOf(author),
|
|
314
327
|
})
|
|
315
328
|
// The repository answers the new key, or undefined when either end is missing.
|
|
316
329
|
if (!copied) return notFound('The element or target could not be found.')
|
package/src/adapters/members.ts
CHANGED
|
@@ -8,7 +8,8 @@
|
|
|
8
8
|
* - **Uniqueness.** Umbraco refuses a duplicate username or e-mail; the columns
|
|
9
9
|
* are case-insensitive in both dialects, so "A@b.com" and "a@b.com" clash.
|
|
10
10
|
* - **Sensitive values.** A member property marked sensitive is withheld from a
|
|
11
|
-
* user outside the Sensitive data group, compositions included
|
|
11
|
+
* user outside the Sensitive data group, compositions included, and a save
|
|
12
|
+
* by them keeps each such value they were not shown.
|
|
12
13
|
* - **Passwords.** Plaintext arrives here and nowhere deeper; a change of one
|
|
13
14
|
* rotates the security stamp, which ends the member's sessions.
|
|
14
15
|
*
|
|
@@ -106,7 +107,7 @@ export function createMemberPort(db: Db, options: MemberPortOptions = {}): Membe
|
|
|
106
107
|
): Promise<MemberResponse | undefined> => {
|
|
107
108
|
const content = await members.content.byKey(member.key)
|
|
108
109
|
if (!content) return undefined
|
|
109
|
-
const withheld = hasAccessToSensitiveData(viewer.groups)
|
|
110
|
+
const withheld = hasAccessToSensitiveData(viewer.groups ?? [])
|
|
110
111
|
? new Set<string>()
|
|
111
112
|
: await sensitiveAliases(member.contentTypeKey)
|
|
112
113
|
return {
|
|
@@ -150,6 +151,35 @@ export function createMemberPort(db: Db, options: MemberPortOptions = {}): Membe
|
|
|
150
151
|
}
|
|
151
152
|
}
|
|
152
153
|
|
|
154
|
+
/**
|
|
155
|
+
* The values a save writes: what it was sent, and, for someone outside
|
|
156
|
+
* Sensitive data, each stored sensitive value they were never shown.
|
|
157
|
+
*/
|
|
158
|
+
const keepingWithheld = async (
|
|
159
|
+
existing: MemberCredentials,
|
|
160
|
+
sent: SaveMember['values'],
|
|
161
|
+
principal: Principal,
|
|
162
|
+
): Promise<SaveMember['values']> => {
|
|
163
|
+
if (hasAccessToSensitiveData(principal.groups ?? [])) return sent
|
|
164
|
+
const withheld = await sensitiveAliases(existing.contentTypeKey)
|
|
165
|
+
if (withheld.size === 0) return sent
|
|
166
|
+
const stored = (await members.content.byKey(existing.key))?.values ?? []
|
|
167
|
+
const kept = stored.filter(
|
|
168
|
+
(value) =>
|
|
169
|
+
withheld.has(value.alias) &&
|
|
170
|
+
!sent.some(
|
|
171
|
+
(v) =>
|
|
172
|
+
v.alias === value.alias &&
|
|
173
|
+
(v.culture ?? null) === value.culture &&
|
|
174
|
+
(v.segment ?? null) === value.segment,
|
|
175
|
+
),
|
|
176
|
+
)
|
|
177
|
+
return [
|
|
178
|
+
...sent,
|
|
179
|
+
...kept.map(({ alias, culture, segment, value }) => ({ alias, culture, segment, value })),
|
|
180
|
+
]
|
|
181
|
+
}
|
|
182
|
+
|
|
153
183
|
const toItem = (member: MemberCredentials): MemberItem => ({
|
|
154
184
|
id: member.key,
|
|
155
185
|
memberType: { id: member.contentTypeKey, icon: member.contentTypeIcon ?? 'icon-user' },
|
|
@@ -236,9 +266,13 @@ export function createMemberPort(db: Db, options: MemberPortOptions = {}): Membe
|
|
|
236
266
|
if (input.oldPassword && !(await verifyPassword(input.oldPassword, existing.passwordHash)))
|
|
237
267
|
return { ok: false as const, reason: 'The current password is not correct.', status: 400 }
|
|
238
268
|
try {
|
|
269
|
+
const values = await keepingWithheld(existing, input.values, principal)
|
|
239
270
|
const updated = await members.update(
|
|
240
271
|
key,
|
|
241
|
-
{
|
|
272
|
+
{
|
|
273
|
+
...contentOf({ ...input, values }, existing.contentTypeKey),
|
|
274
|
+
userId: await userIdOf(principal),
|
|
275
|
+
},
|
|
242
276
|
{
|
|
243
277
|
email: input.email,
|
|
244
278
|
username: input.username,
|
package/src/adapters/users.ts
CHANGED
|
@@ -255,6 +255,19 @@ export function createUserPorts(
|
|
|
255
255
|
return found.length === new Set(keys.map(normaliseUuid)).size ? found : undefined
|
|
256
256
|
}
|
|
257
257
|
|
|
258
|
+
/** Whether giving these users these groups, or with none removing them, leaves no administrator. */
|
|
259
|
+
const leavesNoAdmin = async (
|
|
260
|
+
changing: readonly UserRecord[],
|
|
261
|
+
groupKeys: readonly string[] | undefined,
|
|
262
|
+
) => {
|
|
263
|
+
const admin = await adminKey()
|
|
264
|
+
if (!admin) return false
|
|
265
|
+
const keeps = groupKeys?.map(normaliseUuid).includes(admin) ?? false
|
|
266
|
+
if (keeps || !changing.some((u) => isAdmin(u, admin))) return false
|
|
267
|
+
const gone = new Set(changing.map((u) => u.key))
|
|
268
|
+
return !(await users.all()).some((u) => isAdmin(u, admin) && !gone.has(u.key))
|
|
269
|
+
}
|
|
270
|
+
|
|
258
271
|
const userPort: UserPort = {
|
|
259
272
|
configuration: () => ({
|
|
260
273
|
canInviteUsers: Boolean(config.sendUserLink),
|
|
@@ -415,6 +428,7 @@ export function createUserPorts(
|
|
|
415
428
|
if ((await groups.byKeys(input.groupKeys)).length !== new Set(input.groupKeys).size)
|
|
416
429
|
return 'MissingUserGroup'
|
|
417
430
|
if (!(await mayAssignGroups(principal, user, input.groupKeys))) return 'NotGroupOwner'
|
|
431
|
+
if (await leavesNoAdmin([user], input.groupKeys)) return 'AdminGroupCannotBeEmpty'
|
|
418
432
|
// Story 339: where a user works is their groups'; start nodes sent here are not kept.
|
|
419
433
|
const result = await users.update(key, {
|
|
420
434
|
name: input.name,
|
|
@@ -433,6 +447,9 @@ export function createUserPorts(
|
|
|
433
447
|
const found = await findAll(keys)
|
|
434
448
|
if (!found) return 'UserNotFound'
|
|
435
449
|
if (!(await mayActOn(principal, found))) return 'Forbidden'
|
|
450
|
+
// The site's own administrator, whom the Users section shows to nobody else.
|
|
451
|
+
if (found.some((u) => normaliseUuid(u.key) === SUPER_USER_KEY)) return 'CannotDelete'
|
|
452
|
+
if (await leavesNoAdmin(found, undefined)) return 'AdminGroupCannotBeEmpty'
|
|
436
453
|
if (found.some((u) => u.lastLoginDate)) return 'CannotDeleteUserWithLoginHistory'
|
|
437
454
|
for (const user of found) {
|
|
438
455
|
if (user.avatar) await options.mediaFiles.remove(user.avatar)
|
|
@@ -468,6 +485,7 @@ export function createUserPorts(
|
|
|
468
485
|
if (!(await mayActOn(principal, found))) return 'Forbidden'
|
|
469
486
|
for (const user of found)
|
|
470
487
|
if (!(await mayAssignGroups(principal, user, groupKeys))) return 'NotGroupOwner'
|
|
488
|
+
if (await leavesNoAdmin(found, groupKeys)) return 'AdminGroupCannotBeEmpty'
|
|
471
489
|
return (await users.setGroups(userKeys, groupKeys)) ? 'Success' : 'MissingUserGroup'
|
|
472
490
|
},
|
|
473
491
|
|
package/src/approvals.ts
CHANGED
|
@@ -268,6 +268,19 @@ export function scheduleRefusal(
|
|
|
268
268
|
return undefined
|
|
269
269
|
}
|
|
270
270
|
|
|
271
|
+
/**
|
|
272
|
+
* CI and a command-line token never decide (stories 160, 351): a person
|
|
273
|
+
* deciding, signed in, is the point of an approval.
|
|
274
|
+
*/
|
|
275
|
+
function refuseUnattended(principal: Principal): void {
|
|
276
|
+
if (principal.ci) throw new ApprovalRefused('CI cannot approve or send back a request.', 403)
|
|
277
|
+
if (principal.viaToken)
|
|
278
|
+
throw new ApprovalRefused(
|
|
279
|
+
'A command-line token cannot approve or send back a request. Decide it signed in as yourself.',
|
|
280
|
+
403,
|
|
281
|
+
)
|
|
282
|
+
}
|
|
283
|
+
|
|
271
284
|
export function createApprovals(options: ApprovalsOptions): Approvals {
|
|
272
285
|
const { db } = options
|
|
273
286
|
const requests = (tx: Db = db): ApprovalRepositoryType => new ApprovalRepository(tx)
|
|
@@ -947,6 +960,7 @@ export function createApprovals(options: ApprovalsOptions): Approvals {
|
|
|
947
960
|
},
|
|
948
961
|
|
|
949
962
|
async approve(principal, requestKey, stage, comment) {
|
|
963
|
+
refuseUnattended(principal)
|
|
950
964
|
const request = await waitingRequest(requestKey)
|
|
951
965
|
const current = await view(principal, request)
|
|
952
966
|
const target = stage ?? current.can.approve[0]
|
|
@@ -985,6 +999,7 @@ export function createApprovals(options: ApprovalsOptions): Approvals {
|
|
|
985
999
|
},
|
|
986
1000
|
|
|
987
1001
|
async sendBack(principal, requestKey, stage, comment) {
|
|
1002
|
+
refuseUnattended(principal)
|
|
988
1003
|
const request = await waitingRequest(requestKey)
|
|
989
1004
|
const current = await view(principal, request)
|
|
990
1005
|
const from = stage ?? current.can.sendBack[0]
|
package/src/atomic-write.ts
CHANGED
|
@@ -5,9 +5,9 @@
|
|
|
5
5
|
import { mkdirSync, renameSync, writeFileSync } from 'node:fs'
|
|
6
6
|
import { dirname } from 'node:path'
|
|
7
7
|
|
|
8
|
-
export function writeFileAtomic(path: string, data: string | Uint8Array): void {
|
|
8
|
+
export function writeFileAtomic(path: string, data: string | Uint8Array, mode?: number): void {
|
|
9
9
|
mkdirSync(dirname(path), { recursive: true })
|
|
10
10
|
const temporary = `${path}.${process.pid}.${Date.now().toString(36)}.tmp`
|
|
11
|
-
writeFileSync(temporary, data)
|
|
11
|
+
writeFileSync(temporary, data, mode === undefined ? undefined : { mode })
|
|
12
12
|
renameSync(temporary, path)
|
|
13
13
|
}
|
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The site's background jobs as Settings → Background jobs shows them (story
|
|
3
|
+
* 187), shared by its dashboard, the command line and the remote protocol (story
|
|
4
|
+
* 359): a page of jobs, one job named by its id or a prefix of it, and a failed
|
|
5
|
+
* one run again, audited as the dashboard audits it.
|
|
6
|
+
*/
|
|
7
|
+
import {
|
|
8
|
+
type AuditSource,
|
|
9
|
+
type Db,
|
|
10
|
+
type JobProgress,
|
|
11
|
+
JobRepository,
|
|
12
|
+
type JobRow,
|
|
13
|
+
type JobState,
|
|
14
|
+
} from '@crombolo/data'
|
|
15
|
+
import { recordAudit } from './adapters/audit.ts'
|
|
16
|
+
|
|
17
|
+
export const JOB_STATES: readonly JobState[] = ['queued', 'running', 'succeeded', 'failed']
|
|
18
|
+
|
|
19
|
+
/** Each state as the dashboard words it. */
|
|
20
|
+
export const JOB_STATE_WORDS: Record<JobState, string> = {
|
|
21
|
+
queued: 'Waiting',
|
|
22
|
+
running: 'Running',
|
|
23
|
+
failed: 'Failed',
|
|
24
|
+
succeeded: 'Done',
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** The shortest prefix of an id that names a job. */
|
|
28
|
+
export const JOB_PREFIX_LENGTH = 8
|
|
29
|
+
|
|
30
|
+
export interface BackgroundJob {
|
|
31
|
+
id: string
|
|
32
|
+
/** `site`, or the bundle's id. */
|
|
33
|
+
owner: string
|
|
34
|
+
name: string
|
|
35
|
+
state: JobState
|
|
36
|
+
attempts: number
|
|
37
|
+
maxAttempts: number
|
|
38
|
+
nextAttemptAt: string
|
|
39
|
+
progress: JobProgress | null
|
|
40
|
+
error: string | null
|
|
41
|
+
queuedBy: string | null
|
|
42
|
+
createdAt: string
|
|
43
|
+
finishedAt: string | null
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export interface JobPage {
|
|
47
|
+
total: number
|
|
48
|
+
items: BackgroundJob[]
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export interface JobQuery {
|
|
52
|
+
owner?: string
|
|
53
|
+
state?: JobState
|
|
54
|
+
skip?: number
|
|
55
|
+
take?: number
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export type BackgroundJobErrorKind = 'not_found' | 'usage' | 'conflict'
|
|
59
|
+
|
|
60
|
+
/** Why a job could not be found or run again, in words for a person. */
|
|
61
|
+
export class BackgroundJobError extends Error {
|
|
62
|
+
constructor(
|
|
63
|
+
readonly kind: BackgroundJobErrorKind,
|
|
64
|
+
message: string,
|
|
65
|
+
readonly hint?: string,
|
|
66
|
+
) {
|
|
67
|
+
super(message)
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** Who runs a job again, for its audit entry. */
|
|
72
|
+
export interface JobRetrier {
|
|
73
|
+
key?: string | null
|
|
74
|
+
name: string
|
|
75
|
+
source: AuditSource
|
|
76
|
+
address?: { ipAddress?: string | null; forwardedFor?: string | null }
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
export const jobView = (job: JobRow): BackgroundJob => ({
|
|
80
|
+
id: job.id,
|
|
81
|
+
owner: job.owner,
|
|
82
|
+
name: job.name,
|
|
83
|
+
state: job.state,
|
|
84
|
+
attempts: job.attempts,
|
|
85
|
+
maxAttempts: job.maxAttempts,
|
|
86
|
+
nextAttemptAt: job.nextAttemptAt.toISOString(),
|
|
87
|
+
progress: job.progress,
|
|
88
|
+
error: job.lastError,
|
|
89
|
+
queuedBy: job.queuedBy,
|
|
90
|
+
createdAt: job.createdAt.toISOString(),
|
|
91
|
+
finishedAt: job.finishedAt?.toISOString() ?? null,
|
|
92
|
+
})
|
|
93
|
+
|
|
94
|
+
/** A list's query as a request gives it, read as the dashboard reads it. */
|
|
95
|
+
export function readJobQuery(params: URLSearchParams): JobQuery {
|
|
96
|
+
const state = params.get('state')
|
|
97
|
+
return {
|
|
98
|
+
owner: params.get('owner') || undefined,
|
|
99
|
+
state: JOB_STATES.includes(state as JobState) ? (state as JobState) : undefined,
|
|
100
|
+
skip: Math.max(0, Number(params.get('skip')) || 0),
|
|
101
|
+
take: Math.min(200, Math.max(1, Number(params.get('take')) || 50)),
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/** A page of jobs, the newest first. */
|
|
106
|
+
export async function listJobs(db: Db, query: JobQuery = {}): Promise<JobPage> {
|
|
107
|
+
const listed = await new JobRepository(db).list(query)
|
|
108
|
+
return { total: listed.total, items: listed.items.map(jobView) }
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
async function find(db: Db, named: string): Promise<JobRow> {
|
|
112
|
+
const wanted = named.trim().toLowerCase()
|
|
113
|
+
if (wanted.length < JOB_PREFIX_LENGTH || !/^[0-9a-f-]+$/.test(wanted))
|
|
114
|
+
throw new BackgroundJobError(
|
|
115
|
+
'usage',
|
|
116
|
+
`A job is named by its id, or at least the first ${JOB_PREFIX_LENGTH} characters of it.`,
|
|
117
|
+
'crombolo jobs list gives each one.',
|
|
118
|
+
)
|
|
119
|
+
const found = await new JobRepository(db).byPrefix(wanted)
|
|
120
|
+
if (found.length === 0) throw new BackgroundJobError('not_found', `There is no job ${named}.`)
|
|
121
|
+
const exact = found.find((job) => job.id === wanted)
|
|
122
|
+
if (exact) return exact
|
|
123
|
+
if (found.length > 1)
|
|
124
|
+
throw new BackgroundJobError(
|
|
125
|
+
'conflict',
|
|
126
|
+
`${named} names more than one job: ${found.map((job) => `${job.id} (${job.name})`).join(', ')}.`,
|
|
127
|
+
'Give more of its id.',
|
|
128
|
+
)
|
|
129
|
+
return found[0] as JobRow
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/** One job, by its id or a prefix of it that names only it. */
|
|
133
|
+
export async function jobOf(db: Db, named: string): Promise<BackgroundJob> {
|
|
134
|
+
return jobView(await find(db, named))
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/** Runs a failed job again from its first attempt, and audits it as the dashboard does. */
|
|
138
|
+
export async function retryJob(
|
|
139
|
+
db: Db,
|
|
140
|
+
named: string,
|
|
141
|
+
by: JobRetrier,
|
|
142
|
+
): Promise<{ job: BackgroundJob; message: string }> {
|
|
143
|
+
const job = await find(db, named)
|
|
144
|
+
const queue = new JobRepository(db)
|
|
145
|
+
if (job.state !== 'failed' || !(await queue.retry(job.id))) {
|
|
146
|
+
const now = (await queue.get(job.id))?.state ?? job.state
|
|
147
|
+
throw new BackgroundJobError(
|
|
148
|
+
'conflict',
|
|
149
|
+
'Only a job that has failed can be run again.',
|
|
150
|
+
`${job.name} is ${JOB_STATE_WORDS[now].toLowerCase()}.`,
|
|
151
|
+
)
|
|
152
|
+
}
|
|
153
|
+
await recordAudit(db, {
|
|
154
|
+
category: 'system',
|
|
155
|
+
action: 'Retry',
|
|
156
|
+
entityType: 'Job',
|
|
157
|
+
entityName: `${job.owner}/${job.name}`,
|
|
158
|
+
detail: job.lastError ? `after: ${job.lastError.slice(0, 200)}` : null,
|
|
159
|
+
source: by.source,
|
|
160
|
+
userKey: by.key ?? null,
|
|
161
|
+
userName: by.name,
|
|
162
|
+
ipAddress: by.address?.ipAddress ?? null,
|
|
163
|
+
forwardedFor: by.address?.forwardedFor ?? null,
|
|
164
|
+
})
|
|
165
|
+
const retried = await queue.get(job.id)
|
|
166
|
+
return {
|
|
167
|
+
job: jobView(retried ?? job),
|
|
168
|
+
message: `${job.name} is queued to run again.`,
|
|
169
|
+
}
|
|
170
|
+
}
|