@crombolo/server 0.33.0 → 0.34.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/README.md ADDED
@@ -0,0 +1,14 @@
1
+ # @crombolo/server
2
+
3
+ **Internal to crombolo.** This package is published because
4
+ [`@crombolo/crombolo`](https://www.npmjs.com/package/@crombolo/crombolo)
5
+ depends on it, and its exports can change in any release, a patch included.
6
+
7
+ Import from `@crombolo/crombolo` instead:
8
+
9
+ - `@crombolo/crombolo` for a site: its config, its boot and its views.
10
+ - `@crombolo/crombolo/bundle` for a server bundle's author.
11
+ - `@crombolo/crombolo/host` for whoever runs sites.
12
+
13
+ Those three entry points carry the compatibility promise in
14
+ [`docs/api.md`](https://github.com/kineco-au/crombolo-cms/blob/main/docs/api.md).
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@crombolo/server",
3
- "version": "0.33.0",
4
- "description": "The crombolo HTTP server: routing, configuration, media stores and background jobs.",
3
+ "version": "0.34.0",
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",
7
7
  "homepage": "https://github.com/kineco-au/crombolo-cms#readme",
@@ -30,17 +30,17 @@
30
30
  "access": "public"
31
31
  },
32
32
  "dependencies": {
33
- "@crombolo/api-delivery": "0.33.0",
34
- "@crombolo/api-management": "0.33.0",
35
- "@crombolo/auth": "0.33.0",
36
- "@crombolo/backoffice-host": "0.33.0",
37
- "@crombolo/content": "0.33.0",
38
- "@crombolo/contracts": "0.33.0",
39
- "@crombolo/core": "0.33.0",
40
- "@crombolo/data": "0.33.0",
41
- "@crombolo/render": "0.33.0",
42
- "@crombolo/schema": "0.33.0",
43
- "@crombolo/transfer": "0.33.0",
33
+ "@crombolo/api-delivery": "0.34.0",
34
+ "@crombolo/api-management": "0.34.0",
35
+ "@crombolo/auth": "0.34.0",
36
+ "@crombolo/backoffice-host": "0.34.0",
37
+ "@crombolo/content": "0.34.0",
38
+ "@crombolo/contracts": "0.34.0",
39
+ "@crombolo/core": "0.34.0",
40
+ "@crombolo/data": "0.34.0",
41
+ "@crombolo/render": "0.34.0",
42
+ "@crombolo/schema": "0.34.0",
43
+ "@crombolo/transfer": "0.34.0",
44
44
  "@logtape/logtape": "^2.3.8",
45
45
  "jose": "^6.2.12"
46
46
  }
package/src/config.ts CHANGED
@@ -829,7 +829,7 @@ export function describeDatabase(
829
829
  }
830
830
  }
831
831
 
832
- export const VERSION = '0.33.0'
832
+ export const VERSION = '0.34.0'
833
833
 
834
834
  /** A whole number of seconds from the environment; undefined when unset or not one. */
835
835
  function numberSetting(name: Parameters<typeof setting>[0]): number | undefined {
@@ -113,6 +113,11 @@ export interface InstallOutcome {
113
113
  message: string
114
114
  /** What happened to the content the bundle carries; absent when it carries none. */
115
115
  content?: ContentOutcome
116
+ /**
117
+ * Refused because the bundle runs code on the server and the request did not
118
+ * accept that (story 194): the screen asks, and sends the install again.
119
+ */
120
+ needsServerConsent?: boolean
116
121
  }
117
122
 
118
123
  export type PackageInstaller = (
@@ -155,11 +160,21 @@ export interface Marketplace {
155
160
  install(
156
161
  name: string,
157
162
  version: string | undefined,
158
- options?: { applyContent?: boolean },
163
+ options?: { applyContent?: boolean; acceptServerCode?: boolean },
159
164
  ): Promise<InstallOutcome>
160
165
  uninstall(name: string): Promise<InstallOutcome>
161
166
  }
162
167
 
168
+ /**
169
+ * The argv an install runs. `add` never runs a package's install scripts,
170
+ * whatever Bun's own list of trusted packages says (story 194).
171
+ */
172
+ export function installCommand(action: 'add' | 'remove', specifier: string): string[] {
173
+ return action === 'add'
174
+ ? ['bun', 'add', '--ignore-scripts', specifier]
175
+ : ['bun', action, specifier]
176
+ }
177
+
163
178
  /**
164
179
  * `bun add` in the site directory: Bun owns resolution and writes the lockfile.
165
180
  *
@@ -170,7 +185,7 @@ export interface Marketplace {
170
185
  */
171
186
  export const bunInstaller: PackageInstaller = async (action, specifier, siteDir) => {
172
187
  try {
173
- const proc = Bun.spawn(['bun', action, specifier], {
188
+ const proc = Bun.spawn(installCommand(action, specifier), {
174
189
  cwd: siteDir,
175
190
  stdout: 'pipe',
176
191
  stderr: 'pipe',
@@ -213,20 +228,37 @@ export function createMarketplace(options: MarketplaceOptions): Marketplace {
213
228
  options.extensions.bundles().bundles.find((bundle) => bundle.packageName === name)?.version ??
214
229
  null
215
230
 
216
- /** What the registry says this package's latest version carries, when it is a valid bundle. */
217
- const declares = async (name: string): Promise<BundlePackage['carries'] | undefined> => {
231
+ /**
232
+ * What the registry says a version carries: the version asked for (an exact
233
+ * one, or the highest a range admits), or the latest. `not-a-bundle` when that
234
+ * version is no valid bundle, `unreachable` when the registry could not say.
235
+ */
236
+ const declaresAt = async (
237
+ name: string,
238
+ wanted?: string,
239
+ ): Promise<BundlePackage['carries'] | 'not-a-bundle' | 'unreachable'> => {
218
240
  try {
219
241
  const response = await call(`${options.registry}/${encodeURIComponent(name)}`, {
220
242
  headers: { accept: 'application/json' },
221
243
  })
222
- if (!response.ok) return undefined
244
+ if (!response.ok) return response.status === 404 ? 'not-a-bundle' : 'unreachable'
223
245
  const packument = (await response.json()) as {
224
- 'dist-tags'?: { latest?: string }
246
+ 'dist-tags'?: Record<string, string>
225
247
  versions?: Record<string, PackageJson>
226
248
  }
227
- const latest = packument['dist-tags']?.latest
228
- const version = latest ? packument.versions?.[latest] : undefined
229
- if (!version || validateBundlePackage(version).length > 0) return undefined
249
+ const versions = packument.versions ?? {}
250
+ const resolved =
251
+ wanted === undefined
252
+ ? packument['dist-tags']?.latest
253
+ : wanted in versions
254
+ ? wanted
255
+ : (packument['dist-tags']?.[wanted] ??
256
+ Object.keys(versions)
257
+ .filter((v) => Bun.semver.satisfies(v, wanted))
258
+ .sort(Bun.semver.order)
259
+ .at(-1))
260
+ const version = resolved ? versions[resolved] : undefined
261
+ if (!version || validateBundlePackage(version).length > 0) return 'not-a-bundle'
230
262
  const field = version.crombolo as {
231
263
  extensions?: unknown[]
232
264
  content?: boolean
@@ -238,10 +270,16 @@ export function createMarketplace(options: MarketplaceOptions): Marketplace {
238
270
  server: field.server !== undefined,
239
271
  }
240
272
  } catch {
241
- return undefined
273
+ return 'unreachable'
242
274
  }
243
275
  }
244
276
 
277
+ /** What the registry says this package's latest version carries, when it is a valid bundle. */
278
+ const declares = async (name: string): Promise<BundlePackage['carries'] | undefined> => {
279
+ const carries = await declaresAt(name)
280
+ return typeof carries === 'string' ? undefined : carries
281
+ }
282
+
245
283
  return {
246
284
  url: () => options.marketplaceUrl,
247
285
 
@@ -329,6 +367,22 @@ export function createMarketplace(options: MarketplaceOptions): Marketplace {
329
367
  if (version !== undefined && !isValidVersion(version))
330
368
  return { ok: false, message: `'${version}' is not a version npm would accept.` }
331
369
 
370
+ // What the version being installed carries, read before anything is
371
+ // installed: server code needs an explicit yes (story 194), and only a
372
+ // bundle is installed here at all.
373
+ const declared = await declaresAt(name, version)
374
+ if (declared === 'unreachable')
375
+ return {
376
+ ok: false,
377
+ message: `The package registry could not say what ${name} contains, so it was not installed. Try again in a moment.`,
378
+ }
379
+ if (declared === 'not-a-bundle')
380
+ return {
381
+ ok: false,
382
+ message: `${name} is not a bundle for this site, so it was not installed.`,
383
+ }
384
+ if (declared.server && request.acceptServerCode !== true) return serverConsentNeeded(name)
385
+
332
386
  const specifier = version ? `${name}@${version}` : name
333
387
  const result = await install('add', specifier, options.siteDir)
334
388
  options.extensions.invalidate()
@@ -348,6 +402,16 @@ export function createMarketplace(options: MarketplaceOptions): Marketplace {
348
402
  dependency: { name, range, version: version ?? range },
349
403
  message: `${name} was installed, but it is not a valid bundle, so nothing was added to the backoffice.`,
350
404
  }
405
+ // The version that landed is what counts: a release published between
406
+ // reading the registry and installing may have brought server code.
407
+ if (found.carries.server && request.acceptServerCode !== true) {
408
+ await install('remove', name, options.siteDir)
409
+ options.extensions.invalidate()
410
+ return serverConsentNeeded(
411
+ name,
412
+ `${name}@${found.version} turned out to run code on the server, so it was removed again.`,
413
+ )
414
+ }
351
415
 
352
416
  // The content half lands after the dependency, so a refused check leaves
353
417
  // the package installed and says why, rather than undoing an install that
@@ -373,9 +437,9 @@ export function createMarketplace(options: MarketplaceOptions): Marketplace {
373
437
  // committed; saying so is the difference between a surprise and a plan.
374
438
  message: `${name}@${found.version} is installed. Commit the changed package.json and bun.lock to keep it across deployments.${
375
439
  found.carries.server
376
- ? ' Its server half runs only once crombolo.config.ts imports it and the site is deployed.'
440
+ ? " Its server code runs only once your site's developers turn it on and deploy the site."
377
441
  : ''
378
- }`,
442
+ }${found.carries.extensions ? ` ${SCREENS_NOTICE}` : ''}`,
379
443
  ...(content ? { content } : {}),
380
444
  }
381
445
  },
@@ -408,6 +472,18 @@ function descriptionOf(directory: string): string {
408
472
  }
409
473
  }
410
474
 
475
+ /** Said of every bundle installed here: its screens are someone else's code in our browsers. */
476
+ export const SCREENS_NOTICE = 'Its screens run in the browser of everyone who uses the back office.'
477
+
478
+ /** A refusal the screen answers by asking for an explicit yes (story 194). */
479
+ function serverConsentNeeded(name: string, before = ''): InstallOutcome {
480
+ return {
481
+ ok: false,
482
+ needsServerConsent: true,
483
+ message: `${before ? `${before} ` : ''}${name} runs code on the server, with access to the site's data, files and settings. Confirm that you trust its publisher to install it.`,
484
+ }
485
+ }
486
+
411
487
  /** What a site that does not install at runtime says instead, with what to do. */
412
488
  function refusedHere(
413
489
  name: string,
@@ -26,6 +26,7 @@ import {
26
26
  resolveNodeRef,
27
27
  } from '@crombolo/data'
28
28
  import {
29
+ BUNDLE_FORMAT_VERSION,
29
30
  type BundleBlob,
30
31
  type BundleFile,
31
32
  type BundleKind,
@@ -698,7 +699,7 @@ export async function compileSeed(db: Db, config: CromboloConfig): Promise<SeedB
698
699
  for (const node of bundleNodes) tally[node.kind] = (tally[node.kind] ?? 0) + 1
699
700
  const set: ContentSet = {
700
701
  manifest: {
701
- formatVersion: 1,
702
+ formatVersion: BUNDLE_FORMAT_VERSION,
702
703
  id,
703
704
  label: 'Seed',
704
705
  createdAt: new Date(0).toISOString(),
package/src/server.ts CHANGED
@@ -1173,6 +1173,9 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
1173
1173
  const auditPath = `${paths.pluginPath}/api/audit`
1174
1174
  const hostTokenPath = `${paths.pluginPath}/api/host-token`
1175
1175
  const contentQueryPath = `${paths.pluginPath}/api/content-query`
1176
+ const bundleInstallPaths = new Set(
1177
+ ['install', 'uninstall'].map((action) => `${paths.pluginPath}/api/bundles/${action}`),
1178
+ )
1176
1179
  /** Per node: ten a minute for each person, three hundred in all. */
1177
1180
  const hostTokens = new AttemptLimiter({ max: 10, maxAll: 300, windowMs: 60_000 })
1178
1181
  const auditHost = createAuditHost(db, config.auditRetentionDays)
@@ -1308,6 +1311,8 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
1308
1311
  if (pathname === hostTokenPath) return
1309
1312
  // A content query is a POST that reads.
1310
1313
  if (pathname === contentQueryPath) return
1314
+ // Installs and removals write their own entry, with the package (story 194).
1315
+ if (bundleInstallPaths.has(pathname)) return
1311
1316
  const principal = await authenticate(request)
1312
1317
  if (!principal) return
1313
1318
  const plan = pluginAuditPlan(request.method, pathname.slice(prefix.length))
@@ -1492,13 +1497,16 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
1492
1497
  name?: unknown
1493
1498
  version?: unknown
1494
1499
  applyContent?: unknown
1500
+ acceptServerCode?: unknown
1495
1501
  }
1496
1502
  const name = typeof body.name === 'string' ? body.name : ''
1497
1503
  const version = typeof body.version === 'string' ? body.version : undefined
1504
+ const acceptServerCode = body.acceptServerCode === true
1498
1505
  const outcome =
1499
1506
  action === 'install'
1500
1507
  ? await marketplace.install(name, version, {
1501
1508
  applyContent: body.applyContent !== false,
1509
+ acceptServerCode,
1502
1510
  })
1503
1511
  : await marketplace.uninstall(name)
1504
1512
  log.info('{user} {action} the package {name}: {outcome}', {
@@ -1507,6 +1515,20 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
1507
1515
  name,
1508
1516
  outcome: outcome.ok ? 'ok' : outcome.message,
1509
1517
  })
1518
+ // One entry per install, naming the package and whether server code
1519
+ // was accepted (story 194); the generic plugin-write entry skips these.
1520
+ if (outcome.ok)
1521
+ await recordAudit(db, {
1522
+ category: 'system',
1523
+ action: action === 'install' ? 'Install' : 'Uninstall',
1524
+ entityType: 'Bundle',
1525
+ entityName: outcome.dependency ? `${name}@${outcome.dependency.version}` : name,
1526
+ detail: action === 'install' && acceptServerCode ? 'accepted server code' : null,
1527
+ source: 'request',
1528
+ userKey: principal.id,
1529
+ userName: principal.name,
1530
+ ...clientAddress(request),
1531
+ })
1510
1532
  return Response.json(outcome, { status: outcome.ok ? 200 : 400 })
1511
1533
  }
1512
1534