@crombolo/backoffice-host 0.56.0 → 0.58.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.
@@ -8,7 +8,7 @@
8
8
  */
9
9
  import { existsSync, readFileSync, statSync } from 'node:fs'
10
10
  import { dirname, join, normalize } from 'node:path'
11
- import { permissionsProblem } from './bundle-permissions.ts'
11
+ import { permissionsProblem, readSettings } from './bundle-permissions.ts'
12
12
  import type { PackageManifestImportmap } from './manifests.ts'
13
13
 
14
14
  /** The package a bundle declares its peer range on. */
@@ -27,9 +27,26 @@ export const PAYLOAD_MANIFEST = 'bundle.json'
27
27
  /** An exported binding name: what a site imports to wire the server half. */
28
28
  const EXPORT_NAME = /^[A-Za-z_$][A-Za-z0-9_$]*$/
29
29
 
30
+ /**
31
+ * What a bundle is (story 306): a site package, made from a site to move it and
32
+ * only ever applied from a file, or an extension, installed as a dependency.
33
+ * Every bundle says which.
34
+ */
35
+ export type BundleType = 'site' | 'extension'
36
+
37
+ /** Said when a bundle does not say what it is. */
38
+ export const UNTYPED_BUNDLE =
39
+ 'it does not say what it is: its package.json needs "crombolo.bundleType", "site" or "extension"'
40
+
41
+ /** Said when a site package is offered as a dependency. */
42
+ export const SITE_PACKAGE_NOT_INSTALLED =
43
+ 'it is a site package, which is applied to a site with `crombolo site apply`, never installed'
44
+
30
45
  /** The `crombolo` field, as a bundle declares it. */
31
46
  export interface CromboloField {
32
47
  id: string
48
+ /** A site package or an extension (story 306); required. */
49
+ bundleType: BundleType
33
50
  name?: string
34
51
  allowPublicAccess?: boolean
35
52
  allowTelemetry?: boolean
@@ -57,17 +74,29 @@ export interface CromboloField {
57
74
  */
58
75
  anonymise?: Record<string, 'keep' | Record<string, 'member' | 'email' | 'scrub'>>
59
76
  /**
60
- * What its server half may do with the site (story 222), granted as a whole
61
- * by an administrator. Required of a server half from schema 3.
77
+ * What it may do with the site (stories 222, 308), granted as a whole. From
78
+ * schema 4, each permission with its reason; schema 3 listed names only.
62
79
  */
63
- permissions?: string[]
80
+ permissions?: string[] | Record<string, string | { reason: string; origins?: string[] }>
81
+ /** What it may be set to, by the config or in the back office (story 310). */
82
+ settings?: Record<string, unknown>
64
83
  }
65
84
 
66
85
  /**
67
86
  * The bundle schema a server half must be written for: 3 since it declares the
68
87
  * permissions it needs (story 222); 2 made its routes route handlers (211).
69
88
  */
70
- export const BUNDLE_SCHEMA_VERSION = 3
89
+ export const BUNDLE_SCHEMA_VERSION = 4
90
+
91
+ /**
92
+ * The oldest schema read, for an extension already installed: 3 listed its
93
+ * permissions without reasons (story 308). A new install needs 4.
94
+ */
95
+ export const OLDEST_BUNDLE_SCHEMA_VERSION = 3
96
+
97
+ /** Said when a schema 3 extension is offered for a new install (story 308). */
98
+ export const SCHEMA_3_NOT_INSTALLED =
99
+ 'it asks for permissions without saying why (bundle schema 3); install a version written for schema 4'
71
100
 
72
101
  /** A bundle as read from its package. */
73
102
  export interface BundlePackage {
@@ -79,6 +108,7 @@ export interface BundlePackage {
79
108
  /** `peerDependencies["@crombolo/crombolo"]`. */
80
109
  peerRange: string
81
110
  private: boolean
111
+ bundleType: BundleType
82
112
  field: CromboloField
83
113
  /** The package's directory, when it carries content: the payload is the package. */
84
114
  contentDir: string | undefined
@@ -123,7 +153,7 @@ export function schemaProblem(schema: number): string {
123
153
  ? 'it declares the permissions it needs in "crombolo.permissions" (docs/bundles.md, "Permissions")'
124
154
  : '',
125
155
  ].filter(Boolean)
126
- return `its server half is written for bundle schema ${schema}, and this release reads ${BUNDLE_SCHEMA_VERSION}: ${changes.join(', and ')}, with "crombolo.schemaVersion": ${BUNDLE_SCHEMA_VERSION}`
156
+ return `its server half is written for bundle schema ${schema}, and this release reads ${OLDEST_BUNDLE_SCHEMA_VERSION} to ${BUNDLE_SCHEMA_VERSION}: ${changes.join(', and ')}, with "crombolo.schemaVersion": ${BUNDLE_SCHEMA_VERSION}`
127
157
  }
128
158
 
129
159
  const isPlainObject = (value: unknown): value is Record<string, unknown> =>
@@ -160,6 +190,19 @@ export function validateBundlePackage(json: PackageJson, directory?: string): st
160
190
  typeof f.id === 'string' ? `, not "${f.id}"` : ''
161
191
  }`,
162
192
  )
193
+ if (f.bundleType !== 'site' && f.bundleType !== 'extension') problems.push(UNTYPED_BUNDLE)
194
+ else if (f.bundleType === 'site') {
195
+ // A site's own extensions travel as dependencies in the package.json it carries.
196
+ for (const key of ['server', 'extensions', 'permissions', 'importmap'])
197
+ if (f[key] !== undefined)
198
+ problems.push(
199
+ `it is a site package, which declares no "crombolo.${key}": that is an extension's`,
200
+ )
201
+ if (json.private !== true)
202
+ problems.push(
203
+ 'it is a site package, which is never published: its package.json needs "private": true',
204
+ )
205
+ }
163
206
  if (f.name !== undefined && (typeof f.name !== 'string' || f.name.trim() === ''))
164
207
  problems.push('"crombolo.name" must be a non-empty string')
165
208
  if (typeof json.name !== 'string' || json.name === '')
@@ -184,17 +227,22 @@ export function validateBundlePackage(json: PackageJson, directory?: string): st
184
227
  problems.push('"crombolo.schemaVersion" is a whole number')
185
228
  else if (
186
229
  f.server !== undefined &&
187
- ((f.schemaVersion as number | undefined) ?? 1) < BUNDLE_SCHEMA_VERSION
230
+ ((f.schemaVersion as number | undefined) ?? 1) < OLDEST_BUNDLE_SCHEMA_VERSION
188
231
  )
189
232
  problems.push(schemaProblem((f.schemaVersion as number | undefined) ?? 1))
233
+ const schema = (f.schemaVersion as number | undefined) ?? 1
190
234
  if (f.server !== undefined && f.permissions === undefined)
191
235
  problems.push(
192
- 'its server half declares no "crombolo.permissions": list what it may do with the site, [] for nothing (docs/bundles.md, "Permissions")',
236
+ 'its server half declares no "crombolo.permissions": each permission it asks for with its reason, {} for nothing (docs/bundles.md, "Permissions")',
193
237
  )
194
238
  else if (f.permissions !== undefined) {
195
- const problem = permissionsProblem(f.permissions)
239
+ const problem = permissionsProblem(f.permissions, schema)
196
240
  if (problem) problems.push(problem)
197
241
  }
242
+ {
243
+ const settings = readSettings(f.settings)
244
+ if ('problem' in settings) problems.push(settings.problem)
245
+ }
198
246
  if (f.content !== undefined) {
199
247
  if (typeof f.content === 'string')
200
248
  problems.push(
@@ -206,6 +254,14 @@ export function validateBundlePackage(json: PackageJson, directory?: string): st
206
254
  problems.push(`it declares content, and holds no ${PAYLOAD_MANIFEST} at its root`)
207
255
  }
208
256
 
257
+ if (f.bundleType === 'extension' && directory) {
258
+ const code = carriedCode(directory)
259
+ if (code)
260
+ problems.push(
261
+ `it is an extension, which never carries the site's code, and ${PAYLOAD_MANIFEST} lists ${code}`,
262
+ )
263
+ }
264
+
209
265
  const hasExtensions = Array.isArray(f.extensions) && f.extensions.length > 0
210
266
  if (!hasExtensions && f.content === undefined && f.server === undefined)
211
267
  problems.push(
@@ -218,6 +274,19 @@ export function validateBundlePackage(json: PackageJson, directory?: string): st
218
274
  return problems
219
275
  }
220
276
 
277
+ /** What a bundle's `bundle.json` lists under `code/`, said briefly; undefined when nothing. */
278
+ function carriedCode(directory: string): string | undefined {
279
+ try {
280
+ const manifest = JSON.parse(readFileSync(join(directory, PAYLOAD_MANIFEST), 'utf8')) as {
281
+ carries?: { code?: unknown[] }
282
+ }
283
+ const code = manifest.carries?.code ?? []
284
+ return code.length > 0 ? `${code.length} file(s) under code/` : undefined
285
+ } catch {
286
+ return undefined
287
+ }
288
+ }
289
+
221
290
  /**
222
291
  * The package at a directory, read as a bundle.
223
292
  *
@@ -227,10 +296,15 @@ export function validateBundlePackage(json: PackageJson, directory?: string): st
227
296
  export function readBundlePackage(directory: string): {
228
297
  bundle: BundlePackage | undefined
229
298
  problems: string[]
299
+ /** Its only fault is that it does not say what it is: an extension from before 306, turned off. */
300
+ untyped?: { id: string }
230
301
  } {
231
302
  const json = readPackageJson(join(directory, 'package.json'))
232
303
  if (!declaresBundle(json)) return { bundle: undefined, problems: [] }
233
304
  const problems = validateBundlePackage(json as PackageJson, directory)
305
+ const declared = (json as PackageJson).crombolo as Record<string, unknown>
306
+ if (problems.length === 1 && problems[0] === UNTYPED_BUNDLE && typeof declared.id === 'string')
307
+ return { bundle: undefined, problems, untyped: { id: declared.id } }
234
308
  if (problems.length > 0) return { bundle: undefined, problems }
235
309
  const pkg = json as Required<Pick<PackageJson, 'name' | 'version'>> & PackageJson
236
310
  const field = pkg.crombolo as CromboloField
@@ -243,6 +317,7 @@ export function readBundlePackage(directory: string): {
243
317
  name: field.name ?? pkg.name,
244
318
  peerRange: pkg.peerDependencies?.[CORE_PACKAGE] as string,
245
319
  private: pkg.private === true,
320
+ bundleType: field.bundleType,
246
321
  field,
247
322
  contentDir: field.content === true ? directory : undefined,
248
323
  carries: {
@@ -293,8 +368,12 @@ export function resolvePackageDir(from: string, name: string): string | undefine
293
368
 
294
369
  export interface DiscoveredBundles {
295
370
  bundles: BundlePackage[]
296
- /** A declared dependency that claims to be a bundle and is not a valid one. */
297
- problems: { packageName: string; problems: string[] }[]
371
+ /**
372
+ * A declared dependency that claims to be a bundle and is not a valid one, or
373
+ * is a site package, which is never a dependency. `untyped` names the id of
374
+ * one whose only fault is that it does not say what it is: it is turned off.
375
+ */
376
+ problems: { packageName: string; problems: string[]; untyped?: { id: string } }[]
298
377
  }
299
378
 
300
379
  /**
@@ -316,9 +395,15 @@ export function discoverBundles(siteDir: string): DiscoveredBundles {
316
395
  const directory = resolvePackageDir(siteDir, name)
317
396
  if (!directory) continue
318
397
  const read = readBundlePackage(directory)
319
- if (read.bundle) found.bundles.push(read.bundle)
398
+ if (read.bundle?.bundleType === 'site')
399
+ found.problems.push({ packageName: name, problems: [SITE_PACKAGE_NOT_INSTALLED] })
400
+ else if (read.bundle) found.bundles.push(read.bundle)
320
401
  else if (read.problems.length > 0)
321
- found.problems.push({ packageName: name, problems: read.problems })
402
+ found.problems.push({
403
+ packageName: name,
404
+ problems: read.problems,
405
+ ...(read.untyped ? { untyped: read.untyped } : {}),
406
+ })
322
407
  }
323
408
  return found
324
409
  }
@@ -1,44 +1,256 @@
1
1
  /**
2
- * What a bundle may ask to do with the site (story 222): each permission, and
3
- * the sentence an administrator reads before granting it. A bundle's package
4
- * declares the ones it needs in `crombolo.permissions`; an administrator grants
5
- * the whole list, or the bundle stays off. docs/bundles.md, "Permissions".
2
+ * What an extension may ask to do with the site (stories 222, 308): each
3
+ * permission, and the sentence an administrator reads before granting it.
4
+ *
5
+ * Schema 4 asks for each with a reason, which the install shows beside the
6
+ * sentence; `http.outbound` also names its origins. Schema 3 listed names
7
+ * only, and is still read for an extension already installed.
8
+ * docs/bundles.md, "Permissions".
6
9
  */
7
10
 
11
+ /** Schema 4's catalogue: every area asks to read and to write apart. */
8
12
  export const BUNDLE_PERMISSIONS = {
13
+ 'content.read': "Read the site's pages, their values and where they are",
14
+ 'content.write': 'Create, change, publish, unpublish, move and delete pages',
15
+ 'media.read': 'See media in the folders it names',
16
+ 'media.write': 'Add and change media in the folders it names',
17
+ 'members.read': 'See members and their groups, never their passwords',
18
+ 'members.write': 'Add, change and remove members, and put them in groups',
19
+ 'users.read':
20
+ 'See back-office users and their groups, never their passwords, tokens or second factors',
21
+ 'forms.read': "See the site's forms",
22
+ 'forms.write': 'Create and change forms',
23
+ 'formEntries.read': 'Read what people sent through the forms',
24
+ 'formEntries.write': 'Change and delete what people sent through the forms',
25
+ 'dictionary.read': "Read the site's dictionary words",
26
+ 'dictionary.write': 'Add, change and remove dictionary words',
27
+ 'contentTypes.read': 'See the content, media and member types and data types',
28
+ 'contentTypes.write': 'Create and change content, media and member types and data types',
29
+ 'webhooks.read': "See the site's webhooks",
30
+ 'webhooks.write': 'Add, change and remove webhooks, sending only where it may reach',
31
+ 'workflows.read': 'See the approval workflows and what waits for approval',
32
+ 'workflows.write': 'Change the approval workflows, and send and decide approvals',
9
33
  'redirects.read': "See the site's redirects",
10
34
  'redirects.write': 'Add, change and remove redirects',
11
- 'documents.read': "Look up the addresses of the site's pages",
12
35
  'identityProviders.read':
13
36
  'See the sign-in providers the site uses and their settings, never their secrets',
14
37
  'identityProviders.write': "Change administrators' settings for those sign-in providers",
15
- 'media.read': 'See media in the folders it names',
16
- 'media.write': 'Add and change media in the folders it names',
17
38
  'member.delegate':
18
39
  'Act for a signed-in member who uses it: what it adds is theirs, and it sees only what they may see',
40
+ actAs: 'Act for a back-office user, as chosen when it is granted, within what that user may do',
41
+ 'events.content': 'Be told when pages are saved, published, moved or deleted',
42
+ 'http.outbound':
43
+ 'Send requests from the server, and from its screens in your browser, to the addresses it names',
44
+ 'routes.public': 'Answer addresses on the site that anyone may call',
45
+ templates: "Render its own components into the site's pages",
19
46
  } as const
20
47
 
21
48
  export type BundlePermission = keyof typeof BUNDLE_PERMISSIONS
22
49
 
50
+ /** Schema 3's names, read only for an extension installed before schema 4. */
51
+ export const SCHEMA_3_PERMISSIONS = {
52
+ 'redirects.read': BUNDLE_PERMISSIONS['redirects.read'],
53
+ 'redirects.write': BUNDLE_PERMISSIONS['redirects.write'],
54
+ 'documents.read': "Look up the addresses of the site's pages",
55
+ 'identityProviders.read': BUNDLE_PERMISSIONS['identityProviders.read'],
56
+ 'identityProviders.write': BUNDLE_PERMISSIONS['identityProviders.write'],
57
+ 'media.read': BUNDLE_PERMISSIONS['media.read'],
58
+ 'media.write': BUNDLE_PERMISSIONS['media.write'],
59
+ 'member.delegate': BUNDLE_PERMISSIONS['member.delegate'],
60
+ } as const
61
+
62
+ /** Never offered, whatever an extension asks: writing users could make anyone an administrator. */
63
+ export const NEVER_OFFERED: ReadonlySet<string> = new Set(['users.write'])
64
+
23
65
  export const isBundlePermission = (value: unknown): value is BundlePermission =>
24
66
  typeof value === 'string' && Object.hasOwn(BUNDLE_PERMISSIONS, value)
25
67
 
26
- /** Each permission with what it lets the bundle do, in the order declared. */
68
+ const SENTENCES: Readonly<Record<string, string>> = {
69
+ ...SCHEMA_3_PERMISSIONS,
70
+ ...BUNDLE_PERMISSIONS,
71
+ }
72
+
73
+ /** A permission as an extension declares it: its name, its reason, and for `http.outbound` its origins. */
74
+ export interface DeclaredPermission {
75
+ permission: string
76
+ reason: string | null
77
+ origins?: string[]
78
+ }
79
+
80
+ /** The longest reason the install shows. */
81
+ export const REASON_MAX = 200
82
+
83
+ /** `https://host[:port]`, or on a development site `http://localhost[:port]`. */
84
+ const ORIGIN = /^https:\/\/[a-z0-9.-]+(:\d{1,5})?$/i
85
+ const LOCAL_ORIGIN = /^http:\/\/(localhost|127\.0\.0\.1)(:\d{1,5})?$/i
86
+
87
+ export const isOrigin = (value: unknown): value is string =>
88
+ typeof value === 'string' && (ORIGIN.test(value) || LOCAL_ORIGIN.test(value))
89
+
90
+ /** What a schema 4 `permissions` object declares, or why it is not one. */
91
+ export function readPermissions(
92
+ value: unknown,
93
+ ): { declared: DeclaredPermission[] } | { problem: string } {
94
+ if (!value || typeof value !== 'object' || Array.isArray(value))
95
+ return {
96
+ problem:
97
+ '"crombolo.permissions" is an object: each permission it asks for, with the reason it needs it',
98
+ }
99
+ const declared: DeclaredPermission[] = []
100
+ const problems: string[] = []
101
+ for (const [permission, given] of Object.entries(value as Record<string, unknown>)) {
102
+ if (NEVER_OFFERED.has(permission)) {
103
+ problems.push(`"${permission}" is never offered: only an administrator changes users`)
104
+ continue
105
+ }
106
+ if (!isBundlePermission(permission)) {
107
+ problems.push(`"${permission}" is not a permission this release offers`)
108
+ continue
109
+ }
110
+ const entry =
111
+ given && typeof given === 'object' && !Array.isArray(given)
112
+ ? (given as { reason?: unknown; origins?: unknown })
113
+ : { reason: given }
114
+ const reason = typeof entry.reason === 'string' ? entry.reason.trim() : ''
115
+ if (reason.length === 0) problems.push(`"${permission}" gives no reason`)
116
+ else if (reason.length > REASON_MAX)
117
+ problems.push(`"${permission}"'s reason is longer than ${REASON_MAX} characters`)
118
+ if (permission === 'http.outbound') {
119
+ const origins = Array.isArray(entry.origins) ? entry.origins : []
120
+ if (origins.length === 0)
121
+ problems.push('"http.outbound" names no "origins": the addresses it sends to')
122
+ for (const origin of origins.filter((candidate) => !isOrigin(candidate)))
123
+ problems.push(
124
+ `"http.outbound" names ${JSON.stringify(origin)}, which is not an origin like https://api.example.com`,
125
+ )
126
+ declared.push({ permission, reason, origins: origins.filter(isOrigin) })
127
+ } else declared.push({ permission, reason })
128
+ }
129
+ return problems.length > 0 ? { problem: problems.join('; ') } : { declared }
130
+ }
131
+
132
+ /** Each permission with what it lets the extension do, and its reason, in the order declared. */
27
133
  export function describePermissions(
28
- permissions: readonly string[],
29
- ): { permission: string; allows: string }[] {
30
- return permissions.map((permission) => ({
31
- permission,
32
- allows: isBundlePermission(permission) ? BUNDLE_PERMISSIONS[permission] : permission,
33
- }))
134
+ permissions: readonly (string | DeclaredPermission)[],
135
+ ): { permission: string; allows: string; reason: string | null; origins?: string[] }[] {
136
+ return permissions.map((entry) => {
137
+ const declared = typeof entry === 'string' ? { permission: entry, reason: null } : entry
138
+ return {
139
+ permission: declared.permission,
140
+ allows: SENTENCES[declared.permission] ?? declared.permission,
141
+ reason: declared.reason,
142
+ ...(declared.origins ? { origins: declared.origins } : {}),
143
+ }
144
+ })
34
145
  }
35
146
 
36
- /** Why a declared list is not one, or undefined when it is. */
37
- export function permissionsProblem(value: unknown): string | undefined {
147
+ /** Why a declared list or object is not one, or undefined when it is; schema 3 is a list of names. */
148
+ export function permissionsProblem(value: unknown, schemaVersion = 4): string | undefined {
149
+ if (schemaVersion >= 4) {
150
+ const read = readPermissions(value)
151
+ return 'problem' in read ? read.problem : undefined
152
+ }
38
153
  if (!Array.isArray(value)) return '"crombolo.permissions" must be a list of permissions'
39
- const unknown = value.filter((permission) => !isBundlePermission(permission))
154
+ const unknown = value.filter(
155
+ (permission) =>
156
+ typeof permission !== 'string' || !Object.hasOwn(SCHEMA_3_PERMISSIONS, permission),
157
+ )
40
158
  if (unknown.length > 0)
41
- return `"crombolo.permissions" names ${unknown.map((p) => JSON.stringify(p)).join(', ')}, which this release does not offer: ${Object.keys(BUNDLE_PERMISSIONS).join(', ')}`
159
+ return `"crombolo.permissions" names ${unknown.map((p) => JSON.stringify(p)).join(', ')}, which schema 3 does not offer: ${Object.keys(SCHEMA_3_PERMISSIONS).join(', ')}`
42
160
  if (new Set(value).size !== value.length) return '"crombolo.permissions" names a permission twice'
43
161
  return undefined
44
162
  }
163
+
164
+ /**
165
+ * What a `crombolo` field asks for, in schema 4's terms. Schema 3's list is read
166
+ * name by name, `documents.read` as `content.read`; it gives no reasons.
167
+ */
168
+ export function askedPermissions(
169
+ field: { permissions?: unknown } | undefined,
170
+ ): DeclaredPermission[] {
171
+ const given = field?.permissions
172
+ if (Array.isArray(given))
173
+ return given
174
+ .filter((permission): permission is string => typeof permission === 'string')
175
+ .map((permission) => ({
176
+ permission: permission === 'documents.read' ? 'content.read' : permission,
177
+ reason: null,
178
+ }))
179
+ if (!given) return []
180
+ const read = readPermissions(given)
181
+ return 'declared' in read ? read.declared : []
182
+ }
183
+
184
+ /**
185
+ * Whether a field is written for schema 3: a server half or permissions that
186
+ * give no reasons. Installed, it still runs; a new install of it is refused.
187
+ */
188
+ export function isSchema3Field(
189
+ field: { server?: unknown; permissions?: unknown; schemaVersion?: unknown } | undefined,
190
+ ): boolean {
191
+ if (!field) return false
192
+ const schema = typeof field.schemaVersion === 'number' ? field.schemaVersion : 1
193
+ return schema < 4 && (field.server !== undefined || Array.isArray(field.permissions))
194
+ }
195
+
196
+ /** One setting an extension declares (story 310): what the back office shows and the config may lock. */
197
+ export interface ExtensionSetting {
198
+ label: string
199
+ /** `layout`: one of the site's components, the layout its page templates sit in (story 312). */
200
+ type: 'text' | 'number' | 'boolean' | 'choice' | 'layout'
201
+ /** With `choice`: the values it may take. */
202
+ values?: string[]
203
+ default?: string | number | boolean
204
+ /** Kept sealed, and never shown again once saved. */
205
+ secret?: boolean
206
+ }
207
+
208
+ const SETTING_KEY = /^[a-z][A-Za-z0-9]{0,39}$/
209
+
210
+ /** Its settings, or why `crombolo.settings` is not a set of them. */
211
+ export function readSettings(
212
+ value: unknown,
213
+ ): { settings: Record<string, ExtensionSetting> } | { problem: string } {
214
+ if (value === undefined) return { settings: {} }
215
+ if (!value || typeof value !== 'object' || Array.isArray(value))
216
+ return { problem: '"crombolo.settings" maps each setting\'s key to its label and type' }
217
+ const settings: Record<string, ExtensionSetting> = {}
218
+ const problems: string[] = []
219
+ for (const [key, raw] of Object.entries(value as Record<string, unknown>)) {
220
+ const setting = raw as Partial<ExtensionSetting>
221
+ if (!SETTING_KEY.test(key)) problems.push(`the setting "${key}" is not a camelCase key`)
222
+ if (!setting || typeof setting.label !== 'string' || !setting.label.trim())
223
+ problems.push(`the setting "${key}" has no label`)
224
+ if (!['text', 'number', 'boolean', 'choice', 'layout'].includes(setting?.type as string))
225
+ problems.push(`the setting "${key}" is text, number, boolean, choice or layout`)
226
+ if (
227
+ setting?.type === 'choice' &&
228
+ (!Array.isArray(setting.values) || setting.values.length === 0)
229
+ )
230
+ problems.push(`the choice "${key}" names no values`)
231
+ if (problems.length === 0) settings[key] = setting as ExtensionSetting
232
+ }
233
+ return problems.length > 0 ? { problem: problems.join('; ') } : { settings }
234
+ }
235
+
236
+ /** A value as a setting holds it, or why it cannot. Pure. */
237
+ export function settingValueProblem(setting: ExtensionSetting, value: unknown): string | undefined {
238
+ switch (setting.type) {
239
+ case 'text':
240
+ return typeof value === 'string' ? undefined : `${setting.label} is text`
241
+ case 'number':
242
+ return typeof value === 'number' && Number.isFinite(value)
243
+ ? undefined
244
+ : `${setting.label} is a number`
245
+ case 'boolean':
246
+ return typeof value === 'boolean' ? undefined : `${setting.label} is yes or no`
247
+ case 'layout':
248
+ return typeof value === 'string' && /^[A-Za-z0-9_-]+(\/[A-Za-z0-9_-]+)*$/.test(value)
249
+ ? undefined
250
+ : `${setting.label} is one of the site's layouts`
251
+ case 'choice':
252
+ return typeof value === 'string' && (setting.values ?? []).includes(value)
253
+ ? undefined
254
+ : `${setting.label} is one of ${(setting.values ?? []).join(', ')}`
255
+ }
256
+ }
@@ -0,0 +1,78 @@
1
+ /**
2
+ * The back office's content security policy (story 313): its pages talk to the
3
+ * site, and to the origins the granted extensions declare in `http.outbound`,
4
+ * and to nowhere else. An extension's screens run as the signed-in user, so
5
+ * this is what stops one sending what it sees anywhere it did not declare.
6
+ * Each page's inline scripts carry its nonce. docs/backoffice-hosting.md,
7
+ * "Content security policy".
8
+ */
9
+
10
+ export interface BackOfficePolicyInput {
11
+ /** This page's nonce, on its inline scripts. */
12
+ nonce: string
13
+ /** The origins granted extensions declare in `http.outbound`. */
14
+ connect?: readonly string[]
15
+ /** Where the site's media is served from when not here: a CDN or a bucket. */
16
+ media?: readonly string[]
17
+ /** Pages the back office frames: the front end, for the member preview. */
18
+ frames?: readonly string[]
19
+ /** Where the browser reports what it blocked. */
20
+ reportUri?: string
21
+ }
22
+
23
+ /** The oEmbed providers' players, which a rich text editor's embed shows. */
24
+ export const EMBED_FRAMES = [
25
+ 'https://www.youtube.com',
26
+ 'https://www.youtube-nocookie.com',
27
+ 'https://player.vimeo.com',
28
+ 'https://platform.twitter.com',
29
+ ]
30
+
31
+ /** Their thumbnails. */
32
+ const EMBED_IMAGES = ['https://i.ytimg.com', 'https://i.vimeocdn.com', 'https://pbs.twimg.com']
33
+
34
+ /** An origin as a policy names it, or undefined when the value is not one. */
35
+ export function originOf(value: string | undefined): string | undefined {
36
+ if (!value) return undefined
37
+ try {
38
+ const url = new URL(value)
39
+ return url.protocol === 'https:' || url.protocol === 'http:' ? url.origin : undefined
40
+ } catch {
41
+ return undefined
42
+ }
43
+ }
44
+
45
+ const sources = (values: readonly (string | undefined)[]) => [
46
+ ...new Set(values.map(originOf).filter((value): value is string => value !== undefined)),
47
+ ]
48
+
49
+ /** The header's value. Pure. */
50
+ export function backOfficePolicy(input: BackOfficePolicyInput): string {
51
+ const media = sources(input.media ?? [])
52
+ const directives: [string, string[]][] = [
53
+ ['default-src', ["'self'"]],
54
+ ['script-src', ["'self'", `'nonce-${input.nonce}'`]],
55
+ // The client's components set `style` attributes.
56
+ ['style-src', ["'self'", "'unsafe-inline'"]],
57
+ ['connect-src', ["'self'", ...sources(input.connect ?? [])]],
58
+ ['img-src', ["'self'", 'data:', 'blob:', ...media, ...EMBED_IMAGES]],
59
+ ['media-src', ["'self'", 'blob:', ...media]],
60
+ ['font-src', ["'self'", 'data:']],
61
+ // The code editor's workers.
62
+ ['worker-src', ["'self'", 'blob:']],
63
+ ['frame-src', ["'self'", ...EMBED_FRAMES, ...sources(input.frames ?? [])]],
64
+ ['frame-ancestors', ["'self'"]],
65
+ ['object-src', ["'none'"]],
66
+ ['base-uri', ["'self'"]],
67
+ ]
68
+ const policy = directives.map(([name, values]) => `${name} ${values.join(' ')}`)
69
+ if (input.reportUri) policy.push(`report-uri ${input.reportUri}`)
70
+ return policy.join('; ')
71
+ }
72
+
73
+ /** A fresh nonce for one page. */
74
+ export function newNonce(): string {
75
+ const bytes = new Uint8Array(18)
76
+ crypto.getRandomValues(bytes)
77
+ return btoa(String.fromCharCode(...bytes))
78
+ }
package/src/extensions.ts CHANGED
@@ -23,7 +23,10 @@ import type { PackageManifest, PackageManifestImportmap } from './manifests.ts'
23
23
  export const EXTENSION_PATH = '/bundles'
24
24
 
25
25
  /** The npm keyword a bundle publishes so the marketplace can find it. */
26
- export const EXTENSION_KEYWORD = 'crombolo-bundle'
26
+ export const EXTENSION_KEYWORD = 'crombolo-extension'
27
+
28
+ /** The keyword extensions published before 0.57 carry, which the Marketplace still finds. */
29
+ export const LEGACY_EXTENSION_KEYWORD = 'crombolo-bundle'
27
30
 
28
31
  /** A bundle's backoffice half, as the manifest endpoint serves it. */
29
32
  export interface InstalledExtension {
package/src/index.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  export * from './bundle-package.ts'
2
2
  export * from './bundle-permissions.ts'
3
+ export * from './content-security.ts'
3
4
  export * from './extensions.ts'
4
5
  export * from './graphics.ts'
5
6
  export * from './login-assets.ts'