@crombolo/server 0.64.0 → 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.
Files changed (46) hide show
  1. package/package.json +15 -14
  2. package/src/access.ts +6 -2
  3. package/src/adapters/blueprints.ts +19 -5
  4. package/src/adapters/elements.ts +49 -36
  5. package/src/adapters/members.ts +37 -3
  6. package/src/adapters/users.ts +18 -0
  7. package/src/approvals.ts +44 -15
  8. package/src/atomic-write.ts +2 -2
  9. package/src/background-jobs.ts +170 -0
  10. package/src/bundle-admin.ts +39 -3
  11. package/src/bundle-reload.ts +2 -1
  12. package/src/bundles.ts +60 -25
  13. package/src/cli-tokens-api.ts +152 -0
  14. package/src/config.ts +52 -3
  15. package/src/content-events.ts +22 -0
  16. package/src/content-operations.ts +26 -1
  17. package/src/core.ts +357 -133
  18. package/src/extension-activity.ts +121 -0
  19. package/src/extension-components.ts +20 -4
  20. package/src/extension-discovery.ts +84 -65
  21. package/src/grant-trust.ts +6 -4
  22. package/src/index.ts +14 -0
  23. package/src/media-access.ts +30 -125
  24. package/src/media-library.ts +953 -0
  25. package/src/member-admin.ts +761 -0
  26. package/src/node-operations.ts +19 -2
  27. package/src/ports.ts +2 -0
  28. package/src/principal.ts +35 -0
  29. package/src/remote-background-jobs.ts +99 -0
  30. package/src/remote-credentials.ts +114 -6
  31. package/src/remote-extension-activity.ts +66 -0
  32. package/src/remote-media-library.ts +297 -0
  33. package/src/remote-media.ts +2 -2
  34. package/src/remote-members.ts +271 -0
  35. package/src/remote-undo.ts +234 -0
  36. package/src/remote-users.ts +229 -0
  37. package/src/remote.ts +141 -3
  38. package/src/routes.ts +22 -3
  39. package/src/seed/values.ts +82 -4
  40. package/src/seo.ts +81 -61
  41. package/src/server.ts +153 -92
  42. package/src/settings.ts +95 -6
  43. package/src/trusted-signers-admin.ts +39 -3
  44. package/src/undo.ts +358 -0
  45. package/src/user-admin.ts +581 -0
  46. package/src/view-as.ts +95 -0
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@crombolo/server",
3
- "version": "0.64.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.64.0",
35
- "@crombolo/api-management": "0.64.0",
36
- "@crombolo/auth": "0.64.0",
37
- "@crombolo/backoffice-host": "0.64.0",
38
- "@crombolo/common": "0.64.0",
39
- "@crombolo/content": "0.64.0",
40
- "@crombolo/contracts": "0.64.0",
41
- "@crombolo/core": "0.64.0",
42
- "@crombolo/data": "0.64.0",
43
- "@crombolo/extension": "0.64.0",
44
- "@crombolo/render": "0.64.0",
45
- "@crombolo/schema": "0.64.0",
46
- "@crombolo/transfer": "0.64.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",
package/src/access.ts CHANGED
@@ -98,12 +98,16 @@ export function createNodeLookup(db: Db): NodeLookup {
98
98
  }
99
99
  }
100
100
 
101
- /** A user's languages, their groups' start nodes per tree (story 339), and group verbs. */
101
+ /**
102
+ * A user's languages, their groups' start nodes per tree (story 339), and group
103
+ * verbs; from the given groups instead while a session views as them (story 314).
104
+ */
102
105
  export async function loadAccess(
103
106
  db: Db,
104
107
  userId: number,
108
+ groupKeys?: readonly string[],
105
109
  ): Promise<Pick<Principal, 'languages' | 'startNodes' | 'groups'>> {
106
- const data = await new UserRepository(db).access(userId)
110
+ const data = await new UserRepository(db).access(userId, groupKeys)
107
111
  return {
108
112
  languages: data.languages,
109
113
  groups: data.groups,
@@ -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: document.variants.map((v) => ({
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 }
@@ -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 { ElementPort, Principal } from '@crombolo/api-management/domain'
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 (principal: Principal): Promise<number | undefined> => {
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', '=', principal.id)
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
- const rows = await db.q
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, principal) {
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(principal) }))
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, principal) {
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, principal) {
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(principal) }),
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, principal) {
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(principal) }),
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, principal) {
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(principal),
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.')
@@ -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
- { ...contentOf(input, existing.contentTypeKey), userId: await userIdOf(principal) },
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,
@@ -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)
@@ -441,6 +454,26 @@ export function createApprovals(options: ApprovalsOptions): Approvals {
441
454
  })
442
455
  }
443
456
 
457
+ /** Whether the person who made the change is in one of these groups. */
458
+ const requesterIn = async (
459
+ request: ApprovalRequest,
460
+ approvers: readonly string[],
461
+ actor: Principal | undefined,
462
+ ): Promise<boolean> => {
463
+ // Story 314: the requester viewing as groups is in exactly those.
464
+ if (actor?.viewingAs && normaliseUuid(actor.id) === request.requestedBy)
465
+ return actor.groups.some((g) => approvers.includes(g.alias))
466
+ const member = await db.q
467
+ .selectFrom('user_group_member as m')
468
+ .innerJoin('user_group as g', 'g.id', 'm.user_group_id')
469
+ .innerJoin('user_account as u', 'u.id', 'm.user_id')
470
+ .select((eb) => eb.fn.countAll().as('n'))
471
+ .where('u.key', '=', request.requestedBy)
472
+ .where('g.alias', 'in', approvers.length > 0 ? approvers : [''])
473
+ .execute()
474
+ return Number(member[0]?.n ?? 0) > 0
475
+ }
476
+
444
477
  /**
445
478
  * Stages just reached count the person who made the change as approving
446
479
  * when the workflow says so and they are in the stage's groups.
@@ -449,20 +482,13 @@ export function createApprovals(options: ApprovalsOptions): Approvals {
449
482
  repo: ApprovalRepositoryType,
450
483
  request: ApprovalRequest,
451
484
  stages: readonly string[],
485
+ actor: Principal | undefined,
452
486
  ): Promise<void> => {
453
487
  for (const stage of stages) {
454
488
  const stepId = await repo.addStep(request.id, stage)
455
489
  if (request.workflow.selfApproval !== 'automatic') continue
456
490
  const approvers = stageOf(request.workflow, stage)?.approvers ?? []
457
- const member = await db.q
458
- .selectFrom('user_group_member as m')
459
- .innerJoin('user_group as g', 'g.id', 'm.user_group_id')
460
- .innerJoin('user_account as u', 'u.id', 'm.user_id')
461
- .select((eb) => eb.fn.countAll().as('n'))
462
- .where('u.key', '=', request.requestedBy)
463
- .where('g.alias', 'in', approvers.length > 0 ? approvers : [''])
464
- .execute()
465
- if (Number(member[0]?.n ?? 0) > 0)
491
+ if (await requesterIn(request, approvers, actor))
466
492
  await repo.record(request.id, {
467
493
  kind: 'approved',
468
494
  stepId,
@@ -478,6 +504,7 @@ export function createApprovals(options: ApprovalsOptions): Approvals {
478
504
  const settle = async (
479
505
  repo: ApprovalRepositoryType,
480
506
  request: ApprovalRequest,
507
+ actor: Principal | undefined,
481
508
  ): Promise<boolean> => {
482
509
  for (let round = 0; round < request.workflow.stages.length + 1; round++) {
483
510
  const steps = await repo.steps(request.id)
@@ -499,7 +526,7 @@ export function createApprovals(options: ApprovalsOptions): Approvals {
499
526
  if (workflowComplete(request.workflow, approved)) return true
500
527
  const next = stagesNowWaiting(request.workflow, approved, reached)
501
528
  if (next.length > 0) {
502
- await reach(repo, request, next)
529
+ await reach(repo, request, next, actor)
503
530
  const facts = await page(request.nodeKey)
504
531
  await notify(
505
532
  'approvers',
@@ -912,7 +939,7 @@ export function createApprovals(options: ApprovalsOptions): Approvals {
912
939
  comment: [comment?.trim(), when && `to be ${when}`].filter(Boolean).join('\n\n') || null,
913
940
  })
914
941
  const first = startStages(workflow)
915
- await reach(repo, request, first)
942
+ await reach(repo, request, first, principal)
916
943
  await notify(
917
944
  'approvers',
918
945
  request,
@@ -920,7 +947,7 @@ export function createApprovals(options: ApprovalsOptions): Approvals {
920
947
  `Waiting for your approval: ${facts.name}`,
921
948
  `${principal.name} sent "${facts.name}" for approval through "${workflow.name}".${when ? ` It is to be ${when}.` : ''}${comment ? `\n\n${comment}` : ''}`,
922
949
  )
923
- const complete = await settle(repo, request)
950
+ const complete = await settle(repo, request, principal)
924
951
  await auditStep(
925
952
  principal,
926
953
  facts,
@@ -933,6 +960,7 @@ export function createApprovals(options: ApprovalsOptions): Approvals {
933
960
  },
934
961
 
935
962
  async approve(principal, requestKey, stage, comment) {
963
+ refuseUnattended(principal)
936
964
  const request = await waitingRequest(requestKey)
937
965
  const current = await view(principal, request)
938
966
  const target = stage ?? current.can.approve[0]
@@ -958,7 +986,7 @@ export function createApprovals(options: ApprovalsOptions): Approvals {
958
986
  userKey: principal.id,
959
987
  comment: comment?.trim() || null,
960
988
  })
961
- const complete = await settle(repo, request)
989
+ const complete = await settle(repo, request, principal)
962
990
  await auditStep(
963
991
  principal,
964
992
  await page(request.nodeKey),
@@ -971,6 +999,7 @@ export function createApprovals(options: ApprovalsOptions): Approvals {
971
999
  },
972
1000
 
973
1001
  async sendBack(principal, requestKey, stage, comment) {
1002
+ refuseUnattended(principal)
974
1003
  const request = await waitingRequest(requestKey)
975
1004
  const current = await view(principal, request)
976
1005
  const from = stage ?? current.can.sendBack[0]
@@ -1011,7 +1040,7 @@ export function createApprovals(options: ApprovalsOptions): Approvals {
1011
1040
  (s) => (s.state === 'waiting' || s.state === 'approved') && redo.has(s.stage),
1012
1041
  ))
1013
1042
  await repo.setStepState(step.id, step.stage === from ? 'sent-back' : 'discarded')
1014
- await reach(repo, request, [to])
1043
+ await reach(repo, request, [to], principal)
1015
1044
  await notify(
1016
1045
  'approvers',
1017
1046
  request,
@@ -1019,7 +1048,7 @@ export function createApprovals(options: ApprovalsOptions): Approvals {
1019
1048
  `Back for your approval: ${facts?.name ?? 'a page'}`,
1020
1049
  `"${facts?.name}" was sent back to you${comment ? `:\n\n${comment}` : '.'}`,
1021
1050
  )
1022
- complete = await settle(repo, request)
1051
+ complete = await settle(repo, request, principal)
1023
1052
  }
1024
1053
  await auditStep(
1025
1054
  principal,
@@ -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
  }