@crombolo/server 0.62.0 → 0.63.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@crombolo/server",
3
- "version": "0.62.0",
3
+ "version": "0.63.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",
@@ -31,19 +31,19 @@
31
31
  "access": "public"
32
32
  },
33
33
  "dependencies": {
34
- "@crombolo/api-delivery": "0.62.0",
35
- "@crombolo/api-management": "0.62.0",
36
- "@crombolo/auth": "0.62.0",
37
- "@crombolo/backoffice-host": "0.62.0",
38
- "@crombolo/common": "0.62.0",
39
- "@crombolo/content": "0.62.0",
40
- "@crombolo/contracts": "0.62.0",
41
- "@crombolo/core": "0.62.0",
42
- "@crombolo/data": "0.62.0",
43
- "@crombolo/extension": "0.62.0",
44
- "@crombolo/render": "0.62.0",
45
- "@crombolo/schema": "0.62.0",
46
- "@crombolo/transfer": "0.62.0",
34
+ "@crombolo/api-delivery": "0.63.0",
35
+ "@crombolo/api-management": "0.63.0",
36
+ "@crombolo/auth": "0.63.0",
37
+ "@crombolo/backoffice-host": "0.63.0",
38
+ "@crombolo/common": "0.63.0",
39
+ "@crombolo/content": "0.63.0",
40
+ "@crombolo/contracts": "0.63.0",
41
+ "@crombolo/core": "0.63.0",
42
+ "@crombolo/data": "0.63.0",
43
+ "@crombolo/extension": "0.63.0",
44
+ "@crombolo/render": "0.63.0",
45
+ "@crombolo/schema": "0.63.0",
46
+ "@crombolo/transfer": "0.63.0",
47
47
  "@logtape/logtape": "^2.3.8",
48
48
  "@opentelemetry/api": "1.10.0",
49
49
  "@opentelemetry/context-async-hooks": "3.0.0",
package/src/access.ts CHANGED
@@ -3,7 +3,7 @@
3
3
  * and each signed-in user's combined start nodes, group verbs and languages.
4
4
  */
5
5
  import type { NodeChain, NodeLookup, Principal } from '@crombolo/api-management/domain'
6
- import { combineStartNodes, normaliseUuid, ObjectTypes } from '@crombolo/core'
6
+ import { normaliseUuid, ObjectTypes, unionStartNodes } from '@crombolo/core'
7
7
  import { type Db, fromDbBool, UserRepository } from '@crombolo/data'
8
8
 
9
9
  async function chains(
@@ -98,7 +98,7 @@ export function createNodeLookup(db: Db): NodeLookup {
98
98
  }
99
99
  }
100
100
 
101
- /** A user's languages, combined start nodes per tree, and group verbs. */
101
+ /** A user's languages, their groups' start nodes per tree (story 339), and group verbs. */
102
102
  export async function loadAccess(
103
103
  db: Db,
104
104
  userId: number,
@@ -108,9 +108,9 @@ export async function loadAccess(
108
108
  languages: data.languages,
109
109
  groups: data.groups,
110
110
  startNodes: {
111
- document: combineStartNodes(data.groupStartNodes.document, data.userStartNodes.document),
112
- media: combineStartNodes(data.groupStartNodes.media, data.userStartNodes.media),
113
- element: combineStartNodes(data.groupStartNodes.element, data.userStartNodes.element),
111
+ document: unionStartNodes(data.groupStartNodes.document),
112
+ media: unionStartNodes(data.groupStartNodes.media),
113
+ element: unionStartNodes(data.groupStartNodes.element),
114
114
  },
115
115
  }
116
116
  }
@@ -14,6 +14,7 @@ import type {
14
14
  TemplatePort,
15
15
  TreePage,
16
16
  } from '@crombolo/api-management/domain'
17
+ import { CONTENT_FILES_READ_ONLY } from '@crombolo/api-management/domain'
17
18
  import {
18
19
  type ComponentModel,
19
20
  type ContentTypeAggregate,
@@ -330,8 +331,18 @@ export function createContentTypePort(
330
331
  if (refused) return refused
331
332
  const alias = template.alias || aggregate.alias
332
333
  const name = template.name || aggregate.name
334
+ const existing = await templates.byAlias(alias)
335
+ // Story 337: a site that keeps its templates read-only adds them in its code.
336
+ if (!existing && options.componentFiles?.readOnly) {
337
+ const failure: PortFailure = {
338
+ ok: false,
339
+ reason: `${CONTENT_FILES_READ_ONLY} Add the template to the site's code.`,
340
+ status: 403,
341
+ }
342
+ return failure
343
+ }
333
344
  const saved =
334
- (await templates.byAlias(alias)) ??
345
+ existing ??
335
346
  (await templates.save({
336
347
  key: crypto.randomUUID(),
337
348
  name,
@@ -733,6 +744,7 @@ export function createTemplatePort(db: Db, files: ComponentFileStore): TemplateP
733
744
  })
734
745
 
735
746
  return {
747
+ readOnly: files.readOnly === true,
736
748
  async byKey(key) {
737
749
  const model = await repo.byKey(key)
738
750
  if (!model) return undefined
@@ -15,6 +15,8 @@ export interface FileAreaOptions {
15
15
  rewrites?: readonly string[]
16
16
  /** Other extensions a file here may have, kept as they are. */
17
17
  also?: readonly string[]
18
+ /** The site keeps these files read-only in the back office (story 337). */
19
+ readOnly?: boolean
18
20
  }
19
21
 
20
22
  const INVALID_CHARACTERS = /[<>:"|?*\\/]/
@@ -93,7 +95,7 @@ export function createFileSystemPort(root: string, options: FileAreaOptions): Fi
93
95
  return (await kindOf(parent.file)) === 'folder' ? parent : undefined
94
96
  }
95
97
 
96
- return {
98
+ const port: FileSystemPort = {
97
99
  async children(parentPath) {
98
100
  const parent = locate(parentPath)
99
101
  if (!parent) return undefined
@@ -194,8 +196,30 @@ export function createFileSystemPort(root: string, options: FileAreaOptions): Fi
194
196
  return { ok: true, path: entry.path }
195
197
  },
196
198
  }
199
+ return options.readOnly ? readOnlyPort(port) : port
200
+ }
201
+
202
+ /** Reads as `port` does, and refuses every change (story 337). */
203
+ function readOnlyPort(port: FileSystemPort): FileSystemPort {
204
+ const refused = async (): Promise<FileResult> => ({ ok: false, status: 'ReadOnly' })
205
+ return {
206
+ children: (path) => port.children(path),
207
+ entry: (path) => port.entry(path),
208
+ read: (path) => port.read(path),
209
+ create: refused,
210
+ update: refused,
211
+ rename: refused,
212
+ delete: refused,
213
+ createFolder: refused,
214
+ deleteFolder: refused,
215
+ }
197
216
  }
198
217
 
199
218
  /** The components tree: its views, and the plain modules they import. */
200
- export const createComponentsPort = (root: string): FileSystemPort =>
201
- createFileSystemPort(root, { extension: '.tsx', also: ['.ts'], rewrites: ['.cshtml'] })
219
+ export const createComponentsPort = (root: string, readOnly = false): FileSystemPort =>
220
+ createFileSystemPort(root, {
221
+ extension: '.tsx',
222
+ also: ['.ts'],
223
+ rewrites: ['.cshtml'],
224
+ readOnly,
225
+ })
@@ -7,6 +7,7 @@
7
7
  import { existsSync } from 'node:fs'
8
8
  import { mkdir, readFile, rm, writeFile } from 'node:fs/promises'
9
9
  import { join } from 'node:path'
10
+ import { CONTENT_FILES_READ_ONLY } from '@crombolo/api-management/domain'
10
11
  import type { ComponentFileStore } from '@crombolo/data'
11
12
 
12
13
  /** Aliases become filenames, so they must not be able to escape the directory. */
@@ -24,6 +25,7 @@ function safeAlias(alias: string): string | undefined {
24
25
  export function createTemplateFileStore(
25
26
  dir: string,
26
27
  onChange?: (alias: string) => void | Promise<void>,
28
+ readOnly = false,
27
29
  ): ComponentFileStore {
28
30
  const fileFor = (alias: string): string | undefined => {
29
31
  const safe = safeAlias(alias)
@@ -34,7 +36,13 @@ export function createTemplateFileStore(
34
36
  return !existsSync(file) && existsSync(folder) ? folder : file
35
37
  }
36
38
 
39
+ // Callers check `readOnly` first; this is the backstop (story 337).
40
+ const refuse = () => {
41
+ if (readOnly) throw new Error(CONTENT_FILES_READ_ONLY)
42
+ }
43
+
37
44
  return {
45
+ readOnly,
38
46
  async read(alias) {
39
47
  const file = fileFor(alias)
40
48
  if (!file) return undefined
@@ -45,6 +53,7 @@ export function createTemplateFileStore(
45
53
  }
46
54
  },
47
55
  async write(alias, content) {
56
+ refuse()
48
57
  const file = fileFor(alias)
49
58
  if (!file) throw new Error(`Unsafe template alias '${alias}'.`)
50
59
  await mkdir(dir, { recursive: true })
@@ -54,6 +63,7 @@ export function createTemplateFileStore(
54
63
  await onChange?.(alias)
55
64
  },
56
65
  async remove(alias) {
66
+ refuse()
57
67
  const file = fileFor(alias)
58
68
  if (!file) return
59
69
  await rm(file, { force: true })
@@ -26,17 +26,16 @@ import {
26
26
  verifyPassword,
27
27
  } from '@crombolo/auth'
28
28
  import {
29
+ ADMIN_GROUP_ALIAS,
29
30
  DEFAULT_PASSWORD_CONFIGURATION,
30
31
  generateUserPassword,
31
- hasPathAccess,
32
+ isRemotePermission,
32
33
  isValidEmail,
33
34
  isValidPassword,
34
35
  normaliseUuid,
35
36
  type Page,
36
37
  permissionsForPath,
37
- type StartNodes,
38
38
  sectionAppAlias,
39
- sectionKey,
40
39
  sectionName,
41
40
  } from '@crombolo/core'
42
41
  import {
@@ -105,8 +104,6 @@ function toUserResponse(user: UserRecord, adminKey: string | undefined): UserRes
105
104
  }
106
105
  }
107
106
 
108
- type Tree = 'document' | 'media' | 'element'
109
-
110
107
  export interface UserPortOptions {
111
108
  config: Pick<
112
109
  CromboloConfig,
@@ -145,27 +142,8 @@ export function createUserPorts(
145
142
  return !targets.some((t) => isAdmin(t, admin))
146
143
  }
147
144
 
148
- const chainsFor = async (tree: Tree, keys: readonly string[]) =>
149
- tree === 'media' ? nodes.media(keys) : nodes.documents(keys)
150
-
151
- /** Newly granted start nodes must lie where the performing user may work; root needs root. */
152
- const mayGrantStartNodes = async (
153
- performing: StartNodes,
154
- tree: Tree,
155
- granted: { root: boolean; keys: readonly string[] },
156
- had: { root: boolean; keys: readonly string[] },
157
- ) => {
158
- if (granted.root && !had.root && !performing.root) return false
159
- const added = granted.keys.filter((k) => !had.keys.includes(normaliseUuid(k)))
160
- if (added.length === 0 || tree === 'element') return true
161
- const found = await chainsFor(tree, added)
162
- return added.every((key) => {
163
- const node = found.get(normaliseUuid(key))
164
- return !node || hasPathAccess(performing, node.chain, node.trashed)
165
- })
166
- }
167
-
168
145
  /** Umbraco's `UserEditorAuthorizationHelper`: who may give which groups to whom. */
146
+ /** Story 302: each group added to or taken from a user must be one the caller owns. */
169
147
  const mayAssignGroups = async (
170
148
  principal: Principal,
171
149
  target: UserRecord | undefined,
@@ -174,11 +152,15 @@ export function createUserPorts(
174
152
  if (principal.isAdmin) return true
175
153
  const admin = await adminKey()
176
154
  if (target && isAdmin(target, admin)) return false
177
- const wanted = groupKeys.map(normaliseUuid)
178
- if (admin && wanted.includes(admin)) return false
155
+ const wanted = new Set(groupKeys.map(normaliseUuid))
179
156
  const had = new Set(target?.groupKeys ?? [])
180
- const mine = new Set(principal.groupKeys.map(normaliseUuid))
181
- return wanted.every((k) => had.has(k) || mine.has(k))
157
+ const changed = [
158
+ ...[...wanted].filter((k) => !had.has(k)),
159
+ ...[...had].filter((k) => !wanted.has(k)),
160
+ ]
161
+ if (changed.length === 0) return true
162
+ const owned = new Set(await groups.ownedBy(principal.groupKeys))
163
+ return changed.every((k) => owned.has(k))
182
164
  }
183
165
 
184
166
  const visibleTo = async (principal: Principal) => {
@@ -254,7 +236,7 @@ export function createUserPorts(
254
236
  if ((await groups.byKeys(input.groupKeys)).length !== new Set(input.groupKeys).size)
255
237
  return { status: 'MissingUserGroup' }
256
238
  if (!(await mayAssignGroups(principal, undefined, input.groupKeys)))
257
- return { status: 'Unauthorized' }
239
+ return { status: 'NotGroupOwner' }
258
240
  const created = await users.create({
259
241
  key: input.key ?? crypto.randomUUID(),
260
242
  name: input.name || input.userName,
@@ -432,35 +414,17 @@ export function createUserPorts(
432
414
  if (input.groupKeys.length === 0) return 'NoUserGroup'
433
415
  if ((await groups.byKeys(input.groupKeys)).length !== new Set(input.groupKeys).size)
434
416
  return 'MissingUserGroup'
435
- if (!(await mayAssignGroups(principal, user, input.groupKeys))) return 'Unauthorized'
436
- const startNodes = {
437
- document: { root: input.hasDocumentRootAccess, keys: input.documentStartNodeKeys },
438
- media: { root: input.hasMediaRootAccess, keys: input.mediaStartNodeKeys },
439
- element: { root: input.hasElementRootAccess, keys: input.elementStartNodeKeys },
440
- }
441
- for (const tree of ['document', 'media', 'element'] as const)
442
- if (
443
- !(await mayGrantStartNodes(
444
- principal.startNodes[tree],
445
- tree,
446
- startNodes[tree],
447
- user.startNodes[tree],
448
- ))
449
- )
450
- return 'Unauthorized'
417
+ if (!(await mayAssignGroups(principal, user, input.groupKeys))) return 'NotGroupOwner'
418
+ // Story 339: where a user works is their groups'; start nodes sent here are not kept.
451
419
  const result = await users.update(key, {
452
420
  name: input.name,
453
421
  userName: input.userName,
454
422
  email: input.email,
455
423
  languageIsoCode: input.languageIsoCode || null,
456
424
  groupKeys: input.groupKeys,
457
- startNodes,
458
425
  })
459
426
  if (result === 'not-found') return 'UserNotFound'
460
427
  if (result === 'missing-group') return 'MissingUserGroup'
461
- if (result === 'document') return 'ContentStartNodeNotFound'
462
- if (result === 'media') return 'MediaStartNodeNotFound'
463
- if (result === 'element') return 'ElementStartNodeNotFound'
464
428
  return 'Success'
465
429
  },
466
430
 
@@ -503,7 +467,7 @@ export function createUserPorts(
503
467
  if (!found) return 'UserNotFound'
504
468
  if (!(await mayActOn(principal, found))) return 'Forbidden'
505
469
  for (const user of found)
506
- if (!(await mayAssignGroups(principal, user, groupKeys))) return 'Unauthorized'
470
+ if (!(await mayAssignGroups(principal, user, groupKeys))) return 'NotGroupOwner'
507
471
  return (await users.setGroups(userKeys, groupKeys)) ? 'Success' : 'MissingUserGroup'
508
472
  },
509
473
 
@@ -805,7 +769,8 @@ function sameFileFields(a: SchemaUserGroup, b: SchemaUserGroup): boolean {
805
769
  sameMembers(a.permissions, b.permissions) &&
806
770
  (a.languages === 'all' || b.languages === 'all'
807
771
  ? a.languages === b.languages
808
- : sameMembers(a.languages, b.languages))
772
+ : sameMembers(a.languages, b.languages)) &&
773
+ (a.owners === undefined || b.owners === undefined || sameMembers(a.owners, b.owners))
809
774
  )
810
775
  }
811
776
 
@@ -842,16 +807,26 @@ function createUserGroupPort(
842
807
  elementRootAccess: group.startNodes.element.root,
843
808
  fallbackPermissions: group.permissions,
844
809
  permissions: toPermissions(group.granular),
810
+ owners: group.owners.map((id) => ({ id })),
845
811
  })
846
812
 
847
813
  const isMember = (principal: Principal, key: string) =>
848
- principal.isAdmin || principal.groupKeys.map(normaliseUuid).includes(normaliseUuid(key))
814
+ principal.groupKeys.map(normaliseUuid).includes(normaliseUuid(key))
815
+ /** Story 302: the members of any of a group's owners choose who is in it. */
816
+ const owns = async (principal: Principal, key: string) =>
817
+ principal.isAdmin || (await groups.ownedBy(principal.groupKeys)).includes(normaliseUuid(key))
818
+ const maySee = async (principal: Principal, key: string) =>
819
+ isMember(principal, key) || (await owns(principal, key))
820
+
821
+ /** Only the admin group and a group holding a remote verb may not have owners. */
822
+ const ownable = (alias: string, permissions: readonly string[]) =>
823
+ alias.toLowerCase() !== ADMIN_GROUP_ALIAS && !permissions.some(isRemotePermission)
849
824
 
850
825
  /** Umbraco's `UserGroupService.ValidateAccess` and input rules for create and update. */
851
826
  const validate = async (
852
827
  principal: Principal,
853
828
  input: UserGroupInput,
854
- existing?: { key: string; alias: string },
829
+ existing?: { key: string; alias: string; owners: string[] },
855
830
  ): Promise<UserGroupStatus> => {
856
831
  if (!input.name) return 'MissingName'
857
832
  if (input.name.length > 200) return 'NameTooLong'
@@ -860,25 +835,14 @@ function createUserGroupPort(
860
835
  return 'CanNotUpdateAliasIsSystemUserGroup'
861
836
  const clash = await groups.byAlias(input.alias)
862
837
  if (clash && clash.key !== existing?.key) return 'DuplicateAlias'
863
- const mine = new Set(principal.allowedSections.map(sectionKey))
864
- if (!mine.has('users')) return 'Unauthorized'
865
- if (!principal.isAdmin) {
866
- // A grant is compared by section, not by spelling, so a group may hold an
867
- // extension's section only if the caller holds it too.
868
- if (!input.sections.every((s) => mine.has(sectionKey(s)))) return 'Unauthorized'
869
- for (const [tree, key] of [
870
- ['document', input.documentStartNode],
871
- ['media', input.mediaStartNode],
872
- ] as const) {
873
- if (!key) continue
874
- const found = await (tree === 'media'
875
- ? deps.nodes.media([key])
876
- : deps.nodes.documents([key]))
877
- const node = found.get(normaliseUuid(key))
878
- if (node && !hasPathAccess(principal.startNodes[tree], node.chain, node.trashed))
879
- return 'Unauthorized'
880
- }
881
- }
838
+ // Story 302: what a group grants is an administrator's to decide.
839
+ if (!principal.isAdmin) return 'AdministratorsOnly'
840
+ const owners = input.owners ?? existing?.owners ?? []
841
+ if (owners.length > 0 && !ownable(input.alias, input.fallbackPermissions))
842
+ return 'CannotBeOwned'
843
+ const self = normaliseUuid(existing?.key ?? input.key ?? '')
844
+ const others = [...new Set(input.owners?.map(normaliseUuid) ?? [])].filter((k) => k !== self)
845
+ if ((await groups.byKeys(others)).length !== others.length) return 'OwnerNotFound'
882
846
  return 'Success'
883
847
  }
884
848
 
@@ -959,8 +923,10 @@ function createUserGroupPort(
959
923
  async filter(principal, filter, skip, take) {
960
924
  const admin = await deps.adminKey()
961
925
  const text = filter.toLowerCase()
926
+ // Story 302: anyone else is offered the groups they own, the ones they may hand out.
927
+ const owned = principal.isAdmin ? [] : await groups.ownedBy(principal.groupKeys)
962
928
  const list = (await groups.all())
963
- .filter((g) => principal.isAdmin || (g.key !== admin && isMember(principal, g.key)))
929
+ .filter((g) => principal.isAdmin || (g.key !== admin && owned.includes(g.key)))
964
930
  .filter((g) => !text || g.name.toLowerCase().includes(text))
965
931
  return page(list, skip, take)
966
932
  },
@@ -968,8 +934,8 @@ function createUserGroupPort(
968
934
  async get(principal, key) {
969
935
  const group = await groups.byKey(key)
970
936
  if (!group) return 'NotFound'
971
- if (!isMember(principal, group.key)) return 'Forbidden'
972
- return toResponse(group)
937
+ if (!principal.isAdmin && !(await maySee(principal, group.key))) return 'Forbidden'
938
+ return { ...(await toResponse(group)), canManageMembers: await owns(principal, group.key) }
973
939
  },
974
940
 
975
941
  async items(keys) {
@@ -983,33 +949,38 @@ function createUserGroupPort(
983
949
  },
984
950
 
985
951
  async create(principal, input) {
986
- const valid = await validate(principal, input)
987
- if (valid !== 'Success') return { status: valid }
988
952
  const key = normaliseUuid(input.key ?? crypto.randomUUID())
953
+ const valid = await validate(principal, { ...input, key })
954
+ if (valid !== 'Success') return { status: valid }
989
955
  if (await groups.byKey(key)) return { status: 'DuplicateAlias' }
990
956
  const saved = await save(input, key)
991
957
  if (saved !== 'Success') return { status: saved }
958
+ if (input.owners?.length) await groups.setOwners(key, input.owners)
992
959
  await announcePermissions(principal, new Map(), key)
993
- // A non-admin who creates a group joins it, as in Umbraco
994
- if (!principal.isAdmin) await users.addToGroup(key, [principal.id])
995
960
  return { status: 'Success', key }
996
961
  },
997
962
 
998
963
  async update(principal, key, input) {
999
964
  const group = await groups.byKey(key)
1000
965
  if (!group) return 'NotFound'
1001
- if (!isMember(principal, group.key)) return 'Forbidden'
1002
966
  const valid = await validate(principal, input, group)
1003
967
  if (valid !== 'Success') return valid
1004
968
  // Story 228: its file owns what it is; where it starts is this environment's.
1005
969
  const file = fileOf(group.alias)
1006
970
  const owned = fileFieldsOf(input)
971
+ // Owners are the file's only when it names them; otherwise this environment's.
972
+ if (file?.owners !== undefined) {
973
+ const keys = input.owners ?? group.owners
974
+ const byKey = new Map((await groups.byKeys(keys)).map((g) => [g.key, g.alias]))
975
+ owned.owners = keys.map((k) => byKey.get(normaliseUuid(k)) ?? group.alias)
976
+ }
1007
977
  const rewrite = file !== undefined && !sameFileFields(owned, file)
1008
978
  if (file && (input.alias !== group.alias || (rewrite && !deps.declared?.().writable)))
1009
979
  return 'DeclaredInFiles'
1010
980
  const before = pageVerbs(group)
1011
981
  const saved = await save(input, group.key)
1012
982
  if (saved === 'Success') {
983
+ if (input.owners) await groups.setOwners(group.key, input.owners)
1013
984
  if (rewrite) deps.declared?.().write(owned)
1014
985
  await announcePermissions(principal, before, group.key)
1015
986
  }
@@ -1019,7 +990,7 @@ function createUserGroupPort(
1019
990
  async delete(principal, keys) {
1020
991
  const found = await groups.byKeys(keys)
1021
992
  if (found.length !== new Set(keys.map(normaliseUuid)).size) return 'NotFound'
1022
- if (!found.every((g) => isMember(principal, g.key))) return 'Forbidden'
993
+ if (!principal.isAdmin) return 'AdministratorsOnly'
1023
994
  if (found.some((g) => SYSTEM_GROUPS.has(g.alias))) return 'IsSystemUserGroup'
1024
995
  if (found.some((g) => fileOf(g.alias))) return 'DeclaredInFiles'
1025
996
  for (const group of found) await groups.delete(group.key)
@@ -1029,7 +1000,7 @@ function createUserGroupPort(
1029
1000
  async addUsers(principal, key, userKeys) {
1030
1001
  const group = await groups.byKey(key)
1031
1002
  if (!group) return 'NotFound'
1032
- if (!isMember(principal, group.key)) return 'Forbidden'
1003
+ if (!(await owns(principal, group.key))) return 'NotGroupOwner'
1033
1004
  if ((await users.byKeys(userKeys)).length !== new Set(userKeys.map(normaliseUuid)).size)
1034
1005
  return 'UserNotFound'
1035
1006
  await users.addToGroup(group.key, userKeys)
@@ -1039,7 +1010,7 @@ function createUserGroupPort(
1039
1010
  async removeUsers(principal, key, userKeys) {
1040
1011
  const group = await groups.byKey(key)
1041
1012
  if (!group) return 'NotFound'
1042
- if (!isMember(principal, group.key)) return 'Forbidden'
1013
+ if (!(await owns(principal, group.key))) return 'NotGroupOwner'
1043
1014
  if ((await users.byKeys(userKeys)).length !== new Set(userKeys.map(normaliseUuid)).size)
1044
1015
  return 'UserNotFound'
1045
1016
  if (await adminWouldBeEmpty(group.key, userKeys)) return 'AdminGroupCannotBeEmpty'
@@ -49,6 +49,7 @@ import {
49
49
  import { describeProvenance, type ProvenancePolicy } from './provenance.ts'
50
50
  import { markRestartPending, type RestartPending, restartPending } from './restart-pending.ts'
51
51
  import { sealSecret } from './secrets.ts'
52
+ import { signerTrusted } from './site-trust.ts'
52
53
  import { MASKED } from './webhooks.ts'
53
54
 
54
55
  /** Who acted, and from where, for the audit log. */
@@ -165,7 +166,8 @@ export function createBundleAdmin(options: {
165
166
  config: CromboloConfig
166
167
  marketplace: Marketplace
167
168
  extensions: Pick<ExtensionRegistry, 'bundles'>
168
- bundleGrants: Pick<BundleGrants, 'disable' | 'enable' | 'grant' | 'state' | 'forget'>
169
+ bundleGrants: Pick<BundleGrants, 'disable' | 'enable' | 'grant' | 'state' | 'forget'> &
170
+ Partial<Pick<BundleGrants, 'granted'>>
169
171
  /** Granted extensions that could not start, and why (story 311). */
170
172
  failed?: () => readonly { id: string; reason: string }[]
171
173
  /** Stops an extension's running process, where this node runs one (story 328). */
@@ -545,6 +547,23 @@ export function createBundleAdmin(options: {
545
547
  ok: false,
546
548
  message: `No installed extension with a server half is called "${id}".`,
547
549
  }
550
+ // Story 335: turning on an upper level is granting it again, held to the same rule.
551
+ if (enabled) {
552
+ const level = levelOf(bundleGrants.granted?.(pkg.id) ?? [])
553
+ if (isUpperLevel(level)) {
554
+ const provenance = (await marketplace.installed()).find(
555
+ (item) => item.id === pkg.id,
556
+ )?.provenance
557
+ const refused = grantRefusal({
558
+ level,
559
+ grants: true,
560
+ isAdmin: actor.isAdmin,
561
+ provenance,
562
+ from: config.unrestrictedExtensions ?? 'backoffice',
563
+ })
564
+ if (refused) return { status: 403, ok: false, message: `${pkg.name}: ${refused}` }
565
+ }
566
+ }
548
567
  const state = enabled
549
568
  ? await bundleGrants.enable(pkg)
550
569
  : await bundleGrants.disable(pkg, actor.email ?? actor.name)
@@ -588,6 +607,7 @@ export async function localBundleAdmin(
588
607
  keyword: config.packageKeyword,
589
608
  marketplaceUrl: config.marketplaceUrl,
590
609
  componentsDir: config.componentsDir,
610
+ trustSigner: (provenance) => signerTrusted(db, config, provenance),
591
611
  extensions,
592
612
  siteDir: config.siteDir,
593
613
  grants: bundleGrants,
package/src/bundle-api.ts CHANGED
@@ -140,9 +140,7 @@ export const sectionOfPermission = (permission: string): string | undefined => {
140
140
  /** The verbs a set of permissions needs, for the API's own permission checks. */
141
141
  function verbsOf(granted: ReadonlySet<string>): string[] {
142
142
  const verbs = new Set<string>()
143
- if (granted.has('content.read'))
144
- for (const verb of [DocumentPermissions.Read, DocumentPermissions.PropertyValueRead])
145
- verbs.add(verb)
143
+ if (granted.has('content.read')) verbs.add(DocumentPermissions.Read)
146
144
  if (granted.has('content.write'))
147
145
  for (const verb of Object.values(DocumentPermissions)) {
148
146
  if (verb === DocumentPermissions.Permissions || verb === DocumentPermissions.PublicAccess)
@@ -74,6 +74,7 @@ import {
74
74
  carriedSections,
75
75
  carriesSections,
76
76
  changedFileSections,
77
+ componentChanges,
77
78
  type FileAction,
78
79
  keepDictionary,
79
80
  keptDictionary,
@@ -324,10 +325,19 @@ export interface TransferInput extends SectionOptions {
324
325
  * asked, as story 192 had it. Only where runtime installs are on.
325
326
  */
326
327
  installCode?: boolean
328
+ /**
329
+ * Install the templates it adds or changes, which are code the server runs
330
+ * (story 336); `installCode` unless said. The Transfer dashboard asks for these
331
+ * alone, for a user given "Install code on this site".
332
+ */
333
+ installTemplates?: boolean
327
334
  /** Apply a site bundle older than one this site applied from the same signer (story 316). */
328
335
  allowDowngrade?: boolean
329
336
  }
330
337
 
338
+ /** Why a bundle's code, migrations or templates are refused where installs are off (story 336). */
339
+ export const RUNTIME_INSTALLS_OFF = 'installing code while the site runs is turned off on this site'
340
+
331
341
  /**
332
342
  * Who vouches for a bundle's source in place of a signer, given only by code in
333
343
  * this process and never from a request (story 319):
@@ -769,10 +779,7 @@ export async function installBundleContent(
769
779
  )
770
780
  // The code half (story 241): only when asked, only where installs happen here.
771
781
  const code = effective.installCode ? codeChanges(planCode(config, carried)) : []
772
- const installsElsewhere =
773
- config.installsElsewhere?.message ??
774
- "this site does not install code while it runs: add the bundle's code to the site and deploy it"
775
- if (code.length > 0 && !config.runtimeInstalls) return refuse([installsElsewhere], backup)
782
+ if (code.length > 0 && !config.runtimeInstalls) return refuse([RUNTIME_INSTALLS_OFF], backup)
776
783
  // A bundle's value migrations are code too (story 300), unless they are the site's own.
777
784
  const migrations =
778
785
  vouch?.vouchedBy === 'site' || effective.withoutSchema ? [] : migrationChanges(config, carried)
@@ -780,12 +787,28 @@ export async function installBundleContent(
780
787
  return refuse(
781
788
  [
782
789
  effective.installCode
783
- ? installsElsewhere
790
+ ? RUNTIME_INSTALLS_OFF
784
791
  : 'this bundle brings schema migrations, which are code: install its code to bring them',
785
792
  ...migrations.map((file) => file.path),
786
793
  ],
787
794
  backup,
788
795
  )
796
+ // Templates are code as well (story 336): the server imports and runs them.
797
+ const templates =
798
+ vouch?.vouchedBy === 'site' || effective.withoutFiles ? [] : componentChanges(config, carried)
799
+ if (
800
+ templates.length > 0 &&
801
+ (!(effective.installTemplates ?? effective.installCode) || !config.runtimeInstalls)
802
+ )
803
+ return refuse(
804
+ [
805
+ config.runtimeInstalls
806
+ ? 'this bundle adds or changes templates, which are code: installing them needs the permission to install code on this site'
807
+ : RUNTIME_INSTALLS_OFF,
808
+ ...templates.map((file) => file.path),
809
+ ],
810
+ backup,
811
+ )
789
812
  const needingPermission = [
790
813
  ...(plan ? replacementsNeedingPermission(plan, effective) : []),
791
814
  ...(effective.replaceFiles ? [] : code.filter((file) => file.action === 'overwrite')),
@@ -140,6 +140,16 @@ export function migrationChanges(config: CromboloConfig, carried: CarriedSection
140
140
  .filter((file) => file.action !== 'unchanged')
141
141
  }
142
142
 
143
+ /** The templates a bundle would add or change here: code the server runs (story 336). */
144
+ export function componentChanges(config: CromboloConfig, carried: CarriedSections): SectionFile[] {
145
+ return (carried.carries.components ?? [])
146
+ .map((path) => {
147
+ const target = join(config.componentsDir, withinSection(path, 'components'))
148
+ return { path, target, action: actionFor(target, sourceOf(carried, path)) }
149
+ })
150
+ .filter((file) => file.action !== 'unchanged')
151
+ }
152
+
143
153
  /** Compared as bytes: a public file is an image as often as it is text. */
144
154
  function actionFor(target: string, source: string): FileAction {
145
155
  if (!existsSync(target)) return 'create'
package/src/config.ts CHANGED
@@ -341,6 +341,12 @@ export interface CromboloConfig {
341
341
  * CROMBOLO_SCHEMA_WRITABLE says otherwise outright.
342
342
  */
343
343
  schemaWritable: boolean
344
+ /**
345
+ * The back office may not change templates, stylesheets or scripts (story 337):
346
+ * for a site whose files come from its repository. Off unless set, in
347
+ * production too. `CROMBOLO_CONTENT_FILES_READONLY`.
348
+ */
349
+ contentFilesReadOnly: boolean
344
350
  /** Sync `schema/` at boot; a pipeline that runs `crombolo types sync` turns this off. */
345
351
  syncSchemaAtBoot: boolean
346
352
  /** Which database engine; from CROMBOLO_DB. */
@@ -898,6 +904,7 @@ export function loadConfig(
898
904
  ? setting('CROMBOLO_SCHEMA_WRITABLE') === 'true'
899
905
  : setting('NODE_ENV') !== 'production',
900
906
  syncSchemaAtBoot: setting('CROMBOLO_SYNC_SCHEMA_AT_BOOT') !== 'false',
907
+ contentFilesReadOnly: setting('CROMBOLO_CONTENT_FILES_READONLY') === 'true',
901
908
  dialect: setting('CROMBOLO_DB') === 'postgres' ? 'postgres' : 'sqlite',
902
909
  pgDump: setting('CROMBOLO_PG_DUMP'),
903
910
  upgradePolicy:
@@ -1193,7 +1200,7 @@ export function describeDatabase(
1193
1200
  }
1194
1201
  }
1195
1202
 
1196
- export const VERSION = '0.62.0'
1203
+ export const VERSION = '0.63.0'
1197
1204
 
1198
1205
  /** A whole number of seconds from the environment; undefined when unset or not one. */
1199
1206
  /** A positive number from a setting, else the default. */
@@ -9,7 +9,6 @@ import {
9
9
  DocumentPermissions,
10
10
  type GroupGrant,
11
11
  permissionsForPath,
12
- propertyValuePermissions,
13
12
  ROOT_ACCESS,
14
13
  } from '@crombolo/core'
15
14
  import {
@@ -37,9 +36,8 @@ export function contentQueryScope(principal: Principal): QueryScope {
37
36
  principal.isAdmin || browsesEverything(groups)
38
37
  ? undefined
39
38
  : (chain) => permissionsForPath(groups, chain).has(DocumentPermissions.Read),
40
- readsProperty: (key) =>
41
- principal.isAdmin ||
42
- propertyValuePermissions(groups, key).has(DocumentPermissions.PropertyValueRead),
39
+ // Story 338: a field is never hidden from someone who may see the page.
40
+ readsProperty: () => true,
43
41
  }
44
42
  }
45
43
 
package/src/core.ts CHANGED
@@ -78,6 +78,7 @@ import {
78
78
  import { createFormRegistry, formSigningSecret, signFormToken } from './form-submit.ts'
79
79
  import { formTypesOf } from './form-types.ts'
80
80
  import { createWorkflowRunner } from './form-workflows.ts'
81
+ import { switchOffUntrusted } from './grant-trust.ts'
81
82
  import {
82
83
  createBundleIdentityProviders,
83
84
  IdentityProviderOverrides,
@@ -341,6 +342,11 @@ export async function createCore(config: CromboloConfig, hooks: CoreHooks) {
341
342
  detail: `narrowed to what it asks for: ${declaredPermissions(pkg).join(', ') || 'nothing'}`,
342
343
  source: 'boot',
343
344
  })
345
+ // Story 335: before any extension runs, one nobody this site trusts vouches for loses its upper level.
346
+ if (owns)
347
+ await switchOffUntrusted(db, config, extensions, bundleGrants).catch((error: unknown) =>
348
+ log.error('Checking who vouches for extensions failed: {error}', { error: String(error) }),
349
+ )
344
350
  // A configured schema store is copied down before anything reads `schema/`, and
345
351
  // becomes the schema directory for this boot. Everything after here — loading,
346
352
  // validation, hashing, sync, the writer — works on files exactly as it always has.
@@ -16,9 +16,26 @@ export type UnrestrictedFrom = 'backoffice' | 'config'
16
16
  export const unrestrictedFrom = (value: string | undefined): UnrestrictedFrom =>
17
17
  value?.trim().toLowerCase() === 'config' ? 'config' : 'backoffice'
18
18
 
19
- /** A package someone has vouched for: signed, vouched for by the host, or built here. */
19
+ /**
20
+ * A package someone has vouched for: signed by a signer this site trusts (story
21
+ * 335), vouched for by the host, or built here.
22
+ */
20
23
  export const vouchedFor = (provenance: ProvenanceResult | undefined): boolean =>
21
- provenance?.state === 'signed' || provenance?.state === 'vouched' || provenance?.state === 'local'
24
+ (provenance?.state === 'signed' && provenance.trusted === true) ||
25
+ provenance?.state === 'vouched' ||
26
+ provenance?.state === 'local'
27
+
28
+ /** Who signed it, in words: a key by its name and fingerprint, or the repository that built it. */
29
+ export function signerWords(provenance: ProvenanceResult): string | undefined {
30
+ if (provenance.key)
31
+ return `the key ${provenance.key.comment ? `${provenance.key.comment} ` : ''}(${provenance.key.fingerprint})`
32
+ if (provenance.source) return `a build of github.com/${provenance.source.repository}`
33
+ return undefined
34
+ }
35
+
36
+ /** Why a signature that checks out still does not vouch: its signer is not one this site trusts. */
37
+ export const untrustedSigner = (provenance: ProvenanceResult): string =>
38
+ `It is signed by ${signerWords(provenance) ?? 'someone'}, which this site doesn't trust, so it can't be turned on here. An administrator can add the signer in Settings → Trusted signers.`
22
39
 
23
40
  export const ADMINISTRATOR_GRANTS = 'An administrator can turn this on.'
24
41
  export const NOBODY_VOUCHED =
@@ -52,6 +69,9 @@ export function grantRefusal(options: {
52
69
  if (!options.grants) return undefined
53
70
  if (options.level === 'unrestricted' && options.from === 'config') return CONFIG_GRANTS
54
71
  if (!options.isAdmin) return ADMINISTRATOR_GRANTS
55
- if (isUpperLevel(options.level) && !vouchedFor(options.provenance)) return NOBODY_VOUCHED
72
+ if (isUpperLevel(options.level) && !vouchedFor(options.provenance))
73
+ return options.provenance?.state === 'signed'
74
+ ? untrustedSigner(options.provenance)
75
+ : NOBODY_VOUCHED
56
76
  return undefined
57
77
  }
@@ -0,0 +1,73 @@
1
+ /**
2
+ * Story 335: an extension granted Acts as you or Unrestricted keeps that only
3
+ * while someone this site trusts vouches for it. Checked at every start, before
4
+ * extensions run, so an upgrade, or a signer taken off Trusted signers, switches
5
+ * off what no longer qualifies.
6
+ */
7
+ import { type ExtensionRegistry, isUpperLevel, levelOf } from '@crombolo/backoffice-host/registry'
8
+ import type { Db } from '@crombolo/data'
9
+ import { recordAudit } from './adapters/audit.ts'
10
+ import { APPROVED_BY_CODE, type BundleGrants } from './bundle-grants.ts'
11
+ import type { CromboloConfig } from './config.ts'
12
+ import { signerWords, vouchedFor } from './grant-policy.ts'
13
+ import { logger } from './logging.ts'
14
+ import { createMarketplace } from './marketplace.ts'
15
+ import { signerTrusted } from './site-trust.ts'
16
+
17
+ /** Who switches them off, as the audit log records it. */
18
+ export const SWITCHED_OFF_BY = 'crombolo'
19
+
20
+ /**
21
+ * Withdraws each upper-level grant recorded here that nobody this site trusts
22
+ * vouches for, so it is granted again only by the rule; the ids withdrawn. A
23
+ * grant the site's code makes is the developer's, and kept.
24
+ */
25
+ export async function switchOffUntrusted(
26
+ db: Db,
27
+ config: CromboloConfig,
28
+ extensions: ExtensionRegistry,
29
+ grants: Pick<BundleGrants, 'granted' | 'isOn' | 'state' | 'forget'>,
30
+ ): Promise<string[]> {
31
+ const marketplace = createMarketplace({
32
+ registry: config.npmRegistry,
33
+ keyword: config.packageKeyword,
34
+ marketplaceUrl: config.marketplaceUrl,
35
+ componentsDir: config.componentsDir,
36
+ extensions,
37
+ siteDir: config.siteDir,
38
+ trustSigner: (provenance) => signerTrusted(db, config, provenance),
39
+ })
40
+ const packages = new Map(extensions.bundles().bundles.map((pkg) => [pkg.id, pkg]))
41
+ const switched: string[] = []
42
+ for (const item of await marketplace.installed()) {
43
+ const pkg = packages.get(item.id)
44
+ if (!pkg || !grants.isOn(item.id)) continue
45
+ if (grants.state(pkg).grant?.grantedBy === APPROVED_BY_CODE) continue
46
+ if (!isUpperLevel(levelOf(grants.granted(item.id)))) continue
47
+ // A signature that can't be checked right now is left alone, not judged.
48
+ if (item.provenance.state === 'unchecked' || vouchedFor(item.provenance)) continue
49
+ await grants.forget(pkg.id)
50
+ const signer = signerWords(item.provenance)
51
+ const why = signer
52
+ ? `signed by ${signer}, which this site doesn't trust`
53
+ : 'nobody has vouched for who built it'
54
+ await recordAudit(db, {
55
+ category: 'system',
56
+ action: 'Disable',
57
+ entityType: 'Bundle',
58
+ entityName: `${pkg.packageName}@${pkg.version}`,
59
+ detail: `switched off at start: it acts as you or runs unrestricted, and is ${why}; it needs granting again`,
60
+ source: 'boot',
61
+ userKey: null,
62
+ userName: SWITCHED_OFF_BY,
63
+ ipAddress: null,
64
+ forwardedFor: null,
65
+ })
66
+ logger('server').warn(
67
+ '{extension} is switched off: it acts as you or runs unrestricted, and is {why}. Trust its signer in Settings → Trusted signers, then grant it again.',
68
+ { extension: pkg.packageName, why },
69
+ )
70
+ switched.push(item.id)
71
+ }
72
+ return switched
73
+ }
package/src/index.ts CHANGED
@@ -95,6 +95,7 @@ export * from './git.ts'
95
95
  export * from './git-github.ts'
96
96
  export * from './git-routes.ts'
97
97
  export * from './grant-policy.ts'
98
+ export * from './grant-trust.ts'
98
99
  export * from './host-token.ts'
99
100
  export * from './identity-provider-overrides.ts'
100
101
  export * from './identity-providers.ts'
@@ -176,6 +176,8 @@ export interface MarketplaceOptions {
176
176
  policy?: ProvenancePolicy
177
177
  /** Checks a package directory's signature; `verifyProvenance`, unless a test stands in. */
178
178
  verify?: (dir: string) => Promise<ProvenanceResult>
179
+ /** Whether a signature's signer is on this site's Trusted signers list (story 335). */
180
+ trustSigner?: (provenance: ProvenanceResult) => Promise<boolean>
179
181
  }
180
182
 
181
183
  export interface InstallOutcome {
@@ -336,7 +338,13 @@ export function createMarketplace(options: MarketplaceOptions): Marketplace {
336
338
 
337
339
  const declaresAt = (name: string, wanted?: string) =>
338
340
  declaresAtRegistry(options.registry, name, wanted, call)
339
- const verify = options.verify ?? ((dir: string) => verifyProvenance(dir))
341
+ const verifyOnly = options.verify ?? ((dir: string) => verifyProvenance(dir))
342
+ /** A signature with whether its signer is trusted, asked fresh each time, since the list changes. */
343
+ const withTrust = async (result: ProvenanceResult): Promise<ProvenanceResult> =>
344
+ result.state === 'signed'
345
+ ? { ...result, trusted: (await options.trustSigner?.(result)) ?? false }
346
+ : result
347
+ const verify = async (dir: string) => withTrust(await verifyOnly(dir))
340
348
  const provenanceAt = (name: string, dist: Parameters<typeof provenanceAtRegistry>[1]) =>
341
349
  provenanceAtRegistry(name, dist, { fetch: call, verify })
342
350
 
@@ -379,7 +387,7 @@ export function createMarketplace(options: MarketplaceOptions): Marketplace {
379
387
  const key = `${bundle.packageName}@${bundle.version}`
380
388
  let found = installedProvenance.get(key)
381
389
  if (!found) {
382
- found = verify(bundle.directory).catch((error: unknown) => ({
390
+ found = verifyOnly(bundle.directory).catch((error: unknown) => ({
383
391
  state: 'unchecked' as const,
384
392
  reason: error instanceof Error ? error.message : String(error),
385
393
  }))
@@ -388,7 +396,7 @@ export function createMarketplace(options: MarketplaceOptions): Marketplace {
388
396
  const result = await found
389
397
  // Not kept: the next look may be able to check it.
390
398
  if (result.state === 'unchecked') installedProvenance.delete(key)
391
- return result
399
+ return withTrust(result)
392
400
  }
393
401
 
394
402
  /** What the registry says this package's latest version carries, when it is a valid bundle. */
@@ -618,11 +626,11 @@ export function createMarketplace(options: MarketplaceOptions): Marketplace {
618
626
  const discard = () => {
619
627
  if (kept.copied) rmSync(join(options.siteDir, kept.path), { force: true })
620
628
  }
621
- const provenance = await verifyPackage(join(options.siteDir, kept.path)).catch(
622
- (error: unknown) => ({
629
+ const provenance = await withTrust(
630
+ await verifyPackage(join(options.siteDir, kept.path)).catch((error: unknown) => ({
623
631
  state: 'unchecked' as const,
624
632
  reason: error instanceof Error ? error.message : String(error),
625
- }),
633
+ })),
626
634
  )
627
635
  const refused =
628
636
  refusedBySignature(declared.name, provenance) ??
package/src/ports.ts CHANGED
@@ -122,7 +122,8 @@ function createServerPort(config: CromboloConfig, canSendUserLinks: boolean): Se
122
122
  version: VERSION,
123
123
  assemblyVersion: VERSION,
124
124
  baseUtcOffset: '00:00:00',
125
- runtimeMode: config.development ? 'BackofficeDevelopment' : 'Production',
125
+ // Story 337: the back office keeps templates read-only in production mode, so the mode follows the switch.
126
+ runtimeMode: config.contentFilesReadOnly ? 'Production' : 'BackofficeDevelopment',
126
127
  }),
127
128
  }
128
129
  }
@@ -476,10 +477,14 @@ export function createDeps(options: DepsOptions): ManagementApiDeps {
476
477
  // through the partial-view file API because that one is path-addressed and
477
478
  // already understands folders; the template API is id-addressed and cannot
478
479
  // express a folder at all.
479
- deps.components = createComponentsPort(options.config.componentsDir)
480
+ const readOnly = options.config.contentFilesReadOnly
481
+ deps.components = createComponentsPort(options.config.componentsDir, readOnly)
480
482
  deps.componentSnippets = COMPONENT_SNIPPETS
481
- deps.stylesheets = createFileSystemPort(options.config.stylesheetsDir, { extension: '.css' })
482
- deps.scripts = createFileSystemPort(options.config.scriptsDir, { extension: '.js' })
483
+ deps.stylesheets = createFileSystemPort(options.config.stylesheetsDir, {
484
+ extension: '.css',
485
+ readOnly,
486
+ })
487
+ deps.scripts = createFileSystemPort(options.config.scriptsDir, { extension: '.js', readOnly })
483
488
  if (options.db) {
484
489
  const dynamicRoots = new DynamicRootRepository(options.db)
485
490
  deps.dynamicRoots = { resolve: (query) => dynamicRoots.resolve(query) }
@@ -567,7 +572,11 @@ export function createDeps(options: DepsOptions): ManagementApiDeps {
567
572
  })
568
573
  deps.contentTypes = createContentTypePort(options.db, schemaFiles(options.config), {
569
574
  nodeState: options.schema?.nodeState,
570
- componentFiles: createTemplateFileStore(options.config.componentsDir, options.onViewsChange),
575
+ componentFiles: createTemplateFileStore(
576
+ options.config.componentsDir,
577
+ options.onViewsChange,
578
+ options.config.contentFilesReadOnly,
579
+ ),
571
580
  })
572
581
  deps.mediaTypes = createContentTypePort(options.db, schemaFiles(options.config), {
573
582
  nodeState: options.schema?.nodeState,
@@ -580,7 +589,11 @@ export function createDeps(options: DepsOptions): ManagementApiDeps {
580
589
  deps.dataTypes = createDataTypePort(options.db, schemaFiles(options.config))
581
590
  deps.templates = createTemplatePort(
582
591
  options.db,
583
- createTemplateFileStore(options.config.componentsDir, options.onViewsChange),
592
+ createTemplateFileStore(
593
+ options.config.componentsDir,
594
+ options.onViewsChange,
595
+ options.config.contentFilesReadOnly,
596
+ ),
584
597
  )
585
598
  deps.logViewer = createLogViewerPort(options.db, options.config)
586
599
  deps.modelsBuilder = createModelsBuilderPort(options.config)
@@ -625,7 +638,11 @@ export function createDeps(options: DepsOptions): ManagementApiDeps {
625
638
  nodeId: options.config.nodeId,
626
639
  marketplaceUrl: options.config.marketplaceUrl,
627
640
  secretKey: options.config.secretKey,
628
- componentFiles: createTemplateFileStore(options.config.componentsDir, options.onViewsChange),
641
+ componentFiles: createTemplateFileStore(
642
+ options.config.componentsDir,
643
+ options.onViewsChange,
644
+ options.config.contentFilesReadOnly,
645
+ ),
629
646
  mediaStore: mediaFiles.store,
630
647
  components: deps.components,
631
648
  stylesheets: deps.stylesheets,
package/src/provenance.ts CHANGED
@@ -122,6 +122,11 @@ export interface ProvenanceResult {
122
122
  package?: { name: string; version: string }
123
123
  /** Why a signature was not accepted, in words a person can act on. */
124
124
  reason?: string
125
+ /**
126
+ * Whether its signer is on this site's Trusted signers list (story 335), set by
127
+ * whoever asked; only a trusted signer vouches for an upper level.
128
+ */
129
+ trusted?: boolean
125
130
  }
126
131
 
127
132
  /** A package's `provenance.json`, when it has one that reads. */
@@ -296,7 +301,14 @@ export function describeProvenance(result: ProvenanceResult): string {
296
301
  ? `signed by ${result.key.comment || 'a key'} (${result.key.fingerprint})`
297
302
  : undefined
298
303
  const said = [built, key].filter(Boolean).join(', and ')
299
- return `Signed: ${said}`
304
+ // Story 335: said only where someone asked this site's list.
305
+ const trust =
306
+ result.trusted === undefined
307
+ ? ''
308
+ : result.trusted
309
+ ? '; this site trusts its signer'
310
+ : "; this site doesn't trust its signer"
311
+ return `Signed: ${said}${trust}`
300
312
  }
301
313
  case 'unsigned':
302
314
  return 'Not signed'
package/src/remote.ts CHANGED
@@ -55,6 +55,7 @@ import {
55
55
  } from './bundle-install.ts'
56
56
  import {
57
57
  carriesSections,
58
+ componentChanges,
58
59
  migrationChanges,
59
60
  type SectionFile,
60
61
  swappedSections,
@@ -524,6 +525,8 @@ export function createRemote(options: RemoteOptions): Remote {
524
525
  backupTaken: !canBackUp,
525
526
  label: `push from ${by}`,
526
527
  by,
528
+ // Whoever pushed was held to InstallCode when the push was sent (story 336).
529
+ installTemplates: true,
527
530
  })
528
531
  if (!result.runId) {
529
532
  const items = [
@@ -712,8 +715,12 @@ export function createRemote(options: RemoteOptions): Remote {
712
715
  try {
713
716
  const carried = readBundle(dir, config.siteDir).carried
714
717
  structural = carriesSections(carried)
715
- // A bundle's value migrations are code too (story 300).
716
- code = [...codeChanges(planCode(config, carried)), ...migrationChanges(config, carried)]
718
+ // A bundle's value migrations are code too (story 300), and so are its templates (336).
719
+ code = [
720
+ ...codeChanges(planCode(config, carried)),
721
+ ...migrationChanges(config, carried),
722
+ ...componentChanges(config, carried),
723
+ ]
717
724
  } catch (error) {
718
725
  return problem(400, {
719
726
  code: 'not-a-bundle',
@@ -745,9 +752,7 @@ export function createRemote(options: RemoteOptions): Remote {
745
752
  return problem(409, {
746
753
  code: 'installs-elsewhere',
747
754
  title: 'This site does not install code while it runs',
748
- detail:
749
- config.installsElsewhere?.message ??
750
- "Add the bundle's code to the site and deploy it the way this site is deployed.",
755
+ detail: 'Installing code while the site runs is turned off on this site.',
751
756
  })
752
757
  if (code.length > 0 && !may(principal, RemotePermissions.InstallCode))
753
758
  return problem(403, {
@@ -1026,9 +1031,9 @@ export function createRemote(options: RemoteOptions): Remote {
1026
1031
  title: "That run brought an extension's content",
1027
1032
  detail: `It is put back by uninstalling ${run.packageName ?? 'the extension'}, with its content reverted.`,
1028
1033
  })
1029
- // A run that installed code changes code back, which needs what it did.
1034
+ // A run that installed code or changed templates changes code back, which needs what it did.
1030
1035
  if (
1031
- installedCode(config, runId) &&
1036
+ (installedCode(config, runId) || swappedSections(config, runId).includes('components')) &&
1032
1037
  (!atLeast('all') ||
1033
1038
  !may(principal, RemotePermissions.ApplyStructure) ||
1034
1039
  !may(principal, RemotePermissions.InstallCode))
@@ -1442,10 +1447,12 @@ export function createRemote(options: RemoteOptions): Remote {
1442
1447
  pull: atLeast('read') && may(principal, RemotePermissions.Pull),
1443
1448
  pullFull: atLeast('read') && may(principal, RemotePermissions.PullFull),
1444
1449
  // A whole-site push changes structure, so it needs that right and the top level.
1450
+ // A push replaces templates too, which are code (story 336).
1445
1451
  push:
1446
1452
  atLeast('all') &&
1447
1453
  mayChange(principal) &&
1448
- may(principal, RemotePermissions.ApplyStructure),
1454
+ may(principal, RemotePermissions.ApplyStructure) &&
1455
+ may(principal, RemotePermissions.InstallCode),
1449
1456
  apply: atLeast('content') && mayChange(principal),
1450
1457
  applyStructure:
1451
1458
  atLeast('all') &&
@@ -1518,6 +1525,14 @@ export function createRemote(options: RemoteOptions): Remote {
1518
1525
  detail:
1519
1526
  "A push replaces the site's content types, views and code, which needs Crombolo.Remote.ApplyStructure.",
1520
1527
  })
1528
+ // Its templates are code, and what a push will change is not known until it is uploaded (story 336).
1529
+ if (pushing && mayChange(principal) && !may(principal, RemotePermissions.InstallCode))
1530
+ return problem(403, {
1531
+ code: 'forbidden-code',
1532
+ title: 'You may not push a whole site here',
1533
+ detail:
1534
+ 'A push replaces the site\'s templates, which are code, so it needs "Install code on this site" (Crombolo.Remote.InstallCode).',
1535
+ })
1521
1536
  if (what === 'bundles' && request.method === 'PUT') return applyBundle(request, principal)
1522
1537
  if (what === 'runs' && request.method === 'GET') return listRuns(url, principal)
1523
1538
  const revert = /^runs\/([0-9a-f-]{36})\/revert$/.exec(what)
package/src/server.ts CHANGED
@@ -80,6 +80,7 @@ import {
80
80
  managementApiPrefix,
81
81
  ObjectTypes,
82
82
  PREVIEW_HUB_PATH,
83
+ RemotePermissions,
83
84
  SERVER_EVENT_HUB_PATH,
84
85
  } from '@crombolo/core'
85
86
  import {
@@ -238,10 +239,11 @@ import {
238
239
  signPreviewToken,
239
240
  } from './preview-tokens.ts'
240
241
  import { provenanceProblem } from './provenance.ts'
241
- import { createRemote, type RestartOutcome } from './remote.ts'
242
+ import { createRemote, may, type RestartOutcome } from './remote.ts'
242
243
  import { SiteAssets } from './site-assets.ts'
243
244
  import { unknownHostProvided } from './site-file.ts'
244
245
  import { PublicFiles } from './site-public.ts'
246
+ import { signerTrusted } from './site-trust.ts'
245
247
  import {
246
248
  activeSpan,
247
249
  inSpan,
@@ -497,6 +499,7 @@ export async function createServer(
497
499
  keyword: config.packageKeyword,
498
500
  marketplaceUrl: config.marketplaceUrl,
499
501
  componentsDir: config.componentsDir,
502
+ trustSigner: (provenance) => signerTrusted(db, config, provenance),
500
503
  extensions: { ...extensions, invalidate: () => void bundleReloader.reload() },
501
504
  siteDir: config.siteDir,
502
505
  wired: () => bundles?.mounted.map((bundle) => bundle.id) ?? [],
@@ -3092,6 +3095,7 @@ export async function createServer(
3092
3095
  db,
3093
3096
  config,
3094
3097
  user: principal.email,
3098
+ mayInstallCode: may(principal, RemotePermissions.InstallCode),
3095
3099
  onApplied: () => {
3096
3100
  cache.invalidate()
3097
3101
  mediaCache.clear()
package/src/settings.ts CHANGED
@@ -442,6 +442,14 @@ const DECLARED = [
442
442
  section: 'Schema',
443
443
  description: 'Whether the back office may change the schema files.',
444
444
  },
445
+ {
446
+ env: 'CROMBOLO_CONTENT_FILES_READONLY',
447
+ kind: 'boolean',
448
+ default: 'false',
449
+ section: 'Schema',
450
+ description:
451
+ 'Stops the back office changing templates, stylesheets and scripts, for a site whose files come from its repository.',
452
+ },
445
453
  {
446
454
  env: 'CROMBOLO_SYNC_SCHEMA_AT_BOOT',
447
455
  kind: 'boolean',
package/src/site-trust.ts CHANGED
@@ -119,6 +119,22 @@ export async function trustedSigners(db: Db, config: CromboloConfig): Promise<Tr
119
119
  return entries
120
120
  }
121
121
 
122
+ /** Whether a signature's key, or the repository that built it, is on this site's list (story 335). */
123
+ export async function signerTrusted(
124
+ db: Db,
125
+ config: CromboloConfig,
126
+ result: ProvenanceResult,
127
+ ): Promise<boolean> {
128
+ if (result.state !== 'signed') return false
129
+ const entries = await trustedSigners(db, config)
130
+ if (result.key) return entries.some((entry) => entry.fingerprint === result.key?.fingerprint)
131
+ const source = result.source
132
+ if (!source) return false
133
+ return entries.some(
134
+ (entry) => entry.kind === 'source' && entry.source && sourceAllowed(source, entry.source),
135
+ )
136
+ }
137
+
122
138
  /** What a site bundle's check decided: refused, or applied, flagged or not, and who signed it. */
123
139
  export interface SiteBundleTrust {
124
140
  problem?: string
@@ -84,6 +84,8 @@ export interface TransferActionContext {
84
84
  config: CromboloConfig
85
85
  /** Who is acting, recorded with each answer. */
86
86
  user: string
87
+ /** They were given "Install code on this site", so a bundle's templates may come in (story 336). */
88
+ mayInstallCode?: boolean
87
89
  /** After an import lands: the published cache was built before it. */
88
90
  onApplied(): void
89
91
  }
@@ -185,6 +187,7 @@ export async function handleTransferAction(
185
187
  label: pending.label ?? undefined,
186
188
  by: ctx.user,
187
189
  passphrase,
190
+ installTemplates: ctx.mayInstallCode === true,
188
191
  })
189
192
  if (result.runId) ctx.onApplied()
190
193
  const names = new Map(result.check.plan.map((entry) => [entry.key, entry.name] as const))