@crombolo/server 0.61.0 → 0.62.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.61.0",
3
+ "version": "0.62.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.61.0",
35
- "@crombolo/api-management": "0.61.0",
36
- "@crombolo/auth": "0.61.0",
37
- "@crombolo/backoffice-host": "0.61.0",
38
- "@crombolo/common": "0.61.0",
39
- "@crombolo/content": "0.61.0",
40
- "@crombolo/contracts": "0.61.0",
41
- "@crombolo/core": "0.61.0",
42
- "@crombolo/data": "0.61.0",
43
- "@crombolo/extension": "0.61.0",
44
- "@crombolo/render": "0.61.0",
45
- "@crombolo/schema": "0.61.0",
46
- "@crombolo/transfer": "0.61.0",
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",
47
47
  "@logtape/logtape": "^2.3.8",
48
48
  "@opentelemetry/api": "1.10.0",
49
49
  "@opentelemetry/context-async-hooks": "3.0.0",
@@ -18,13 +18,22 @@ import { tmpdir } from 'node:os'
18
18
  import { dirname, join, relative } from 'node:path'
19
19
  import {
20
20
  discoverBundles,
21
+ INSTALLED_AS_DEPENDENCY,
21
22
  isSemverRange,
22
23
  type PackageJson,
24
+ packageInRoot,
23
25
  peerRangeProblem,
26
+ RECORD_FILE,
27
+ type RecordedExtension,
28
+ ROOTS_DIR,
29
+ readPackageJson,
30
+ readRecord,
31
+ recordProblems,
24
32
  resolvePackageDir,
25
33
  } from '@crombolo/backoffice-host/registry'
26
34
  import { loadBundleCode } from '@crombolo/transfer'
27
35
  import { VERSION } from './config.ts'
36
+ import { lockedIntegrity } from './extension-install.ts'
28
37
 
29
38
  const SCOPE = '@crombolo/'
30
39
  const CORE_PACKAGE = '@crombolo/crombolo'
@@ -43,10 +52,19 @@ export interface BundleCodeCheck {
43
52
  files: number
44
53
  }
45
54
 
55
+ /** An extension's root the code carries, and whether it installed as its record says (story 332). */
56
+ export interface BundleCodeRoot {
57
+ id: string
58
+ ok: boolean
59
+ problem?: string
60
+ }
61
+
46
62
  export interface BundleCodeInstall {
47
63
  problems: string[]
48
64
  dir: string
49
65
  files: number
66
+ /** Each extension root the code carries, installed from its own lockfile. */
67
+ roots: BundleCodeRoot[]
50
68
  }
51
69
 
52
70
  /** `bun install` exactly as the lockfile says: no lifecycle scripts, and no peers. */
@@ -123,10 +141,70 @@ function linkCms(json: PackageJson, dir: string): string[] {
123
141
  return problems
124
142
  }
125
143
 
144
+ /** The extension roots under a directory: each folder in `extensions/`. */
145
+ function rootIds(dir: string): string[] {
146
+ const roots = join(dir, ROOTS_DIR)
147
+ if (!existsSync(roots)) return []
148
+ return readdirSync(roots, { withFileTypes: true })
149
+ .filter((entry) => entry.isDirectory())
150
+ .map((entry) => entry.name)
151
+ .sort()
152
+ }
153
+
154
+ /** Why what a root installed is not what the record names, or undefined when it is. */
155
+ function rootMismatch(
156
+ dir: string,
157
+ id: string,
158
+ line: RecordedExtension | undefined,
159
+ ): string | undefined {
160
+ if (!line) return undefined
161
+ const installed = readPackageJson(join(packageInRoot(dir, id, line.name), 'package.json'))
162
+ if (!installed) return `its bun.lock does not install ${line.name}, which ${RECORD_FILE} names`
163
+ if (installed.version !== line.version)
164
+ return `it installs ${line.name}@${installed.version}, where ${RECORD_FILE} names ${line.version}`
165
+ const locked = lockedIntegrity(join(dir, ROOTS_DIR, id), line.name)
166
+ if (line.integrity && locked && locked !== line.integrity)
167
+ return `its bun.lock holds ${line.name} as ${locked}, where ${RECORD_FILE} records ${line.integrity}`
168
+ return undefined
169
+ }
170
+
171
+ /**
172
+ * Each extension root installed from its own lockfile, as `site apply` installs
173
+ * one (story 326), then held to its line in the record. One that fails leaves
174
+ * the others to install.
175
+ */
176
+ async function installRoots(dir: string): Promise<BundleCodeRoot[]> {
177
+ const record = readRecord(dir)
178
+ const out: BundleCodeRoot[] = []
179
+ for (const id of rootIds(dir)) {
180
+ const root = join(dir, ROOTS_DIR, id)
181
+ const problem = existsSync(join(root, 'bun.lock'))
182
+ ? ((await frozenInstall(root)) ?? rootMismatch(dir, id, record[id]))
183
+ : 'it has no bun.lock, so it could not be installed as it was tested'
184
+ out.push(problem ? { id, ok: false, problem } : { id, ok: true })
185
+ }
186
+ return out
187
+ }
188
+
189
+ const rootProblems = (roots: readonly BundleCodeRoot[]): string[] =>
190
+ roots.flatMap((root) => (root.problem ? [`${ROOTS_DIR}/${root.id}/: ${root.problem}`] : []))
191
+
192
+ /** Whether the site's config imports a package: the boot runs one it wires, the old way. */
193
+ function configImports(dir: string, name: string): boolean {
194
+ const config = ['crombolo.config.ts', 'crombolo.config.js', 'crombolo.config.mjs']
195
+ .map((file) => join(dir, file))
196
+ .find((file) => existsSync(file))
197
+ if (!config) return false
198
+ const escaped = name.replace(/[.*+?^${}()|[\]\\/]/g, '\\$&')
199
+ return new RegExp(`(?:from|import)\\s*\\(?\\s*['"]${escaped}(?:/[^'"]*)?['"]`).test(
200
+ readFileSync(config, 'utf8'),
201
+ )
202
+ }
203
+
126
204
  /**
127
205
  * Every reason a bundle's code cannot run on this CMS: its hash, a frozen
128
- * install, `@crombolo/*` installed beside it, and the bundle packages it
129
- * declares. All of them, not the first. The site's code is never run here: a
206
+ * install, `@crombolo/*` installed beside it, the bundle packages it declares,
207
+ * and the extension roots it carries against its record. All of them, not the first. The site's code is never run here: a
130
208
  * host has not yet accepted it, so its config's wiring is checked by the boot.
131
209
  */
132
210
  export async function checkBundleCode(
@@ -157,6 +235,8 @@ export async function checkBundleCode(
157
235
  `${copy} is installed with the code; the CMS provides @crombolo packages, so nothing the site installs may depend on one directly`,
158
236
  )
159
237
  result.problems.push(...linkCms(json, work))
238
+ result.problems.push(...rootProblems(await installRoots(work)))
239
+ result.problems.push(...recordProblems(work))
160
240
 
161
241
  const discovered = discoverBundles(work)
162
242
  for (const entry of discovered.problems)
@@ -164,6 +244,9 @@ export async function checkBundleCode(
164
244
  for (const bundle of discovered.bundles) {
165
245
  const peer = peerRangeProblem(bundle, coreVersion)
166
246
  if (peer) result.problems.push(peer)
247
+ // Story 332: the boot names an extension the site depends on, and does not run it.
248
+ if (bundle.dependency && !(bundle.carries.server && configImports(work, bundle.packageName)))
249
+ result.problems.push(`${bundle.packageName} (${bundle.id}): ${INSTALLED_AS_DEPENDENCY}`)
167
250
  }
168
251
  result.serverBundles = discovered.bundles
169
252
  .filter((bundle) => bundle.carries.server)
@@ -176,7 +259,7 @@ export async function checkBundleCode(
176
259
 
177
260
  /**
178
261
  * The bundle's code installed into `dir`, ready for a host to start once it
179
- * provides the `@crombolo/*` packages. Refuses a directory that already holds
262
+ * provides the `@crombolo/*` packages, with each extension root it carries. Refuses a directory that already holds
180
263
  * files, rather than mixing two sites' code.
181
264
  */
182
265
  export async function installBundleCode(
@@ -184,12 +267,14 @@ export async function installBundleCode(
184
267
  dir: string,
185
268
  ): Promise<BundleCodeInstall> {
186
269
  const loaded = loadBundleCode(packageDir)
187
- if (!loaded.dir || loaded.problems.length > 0) return { problems: loaded.problems, dir, files: 0 }
270
+ if (!loaded.dir || loaded.problems.length > 0)
271
+ return { problems: loaded.problems, dir, files: 0, roots: [] }
188
272
  if (existsSync(dir) && readdirSync(dir).length > 0)
189
273
  return {
190
274
  problems: [`${dir} already holds files; install into an empty directory`],
191
275
  dir,
192
276
  files: 0,
277
+ roots: [],
193
278
  }
194
279
  mkdirSync(dir, { recursive: true })
195
280
  cpSync(loaded.dir, dir, { recursive: true })
@@ -201,5 +286,8 @@ export async function installBundleCode(
201
286
  problems.push(
202
287
  `${copy} was installed with the code; the CMS provides @crombolo packages, so nothing the site installs may depend on one directly`,
203
288
  )
204
- return { problems, dir, files: loaded.paths.length }
289
+ // Story 332: each extension root the code carries, as `site apply` installs it.
290
+ const roots = await installRoots(dir)
291
+ problems.push(...rootProblems(roots))
292
+ return { problems, dir, files: loaded.paths.length, roots }
205
293
  }
package/src/config.ts CHANGED
@@ -25,7 +25,11 @@ import type { EmailPort } from './email.ts'
25
25
  import type { GitConfig } from './git-routes.ts'
26
26
  import { type UnrestrictedFrom, unrestrictedFrom } from './grant-policy.ts'
27
27
  import { checkHost, type HostConfig } from './host-token.ts'
28
- import { checkIdentityProviders, type IdentityProvider } from './identity-providers.ts'
28
+ import {
29
+ checkIdentityProviders,
30
+ type IdentityProvider,
31
+ type LockedIdentityProviders,
32
+ } from './identity-providers.ts'
29
33
  import type { MediaStore } from './media-store.ts'
30
34
  import type { JobSchedule } from './owner-jobs.ts'
31
35
  import type { ProvenancePolicy, SignaturePolicy } from './provenance.ts'
@@ -176,6 +180,18 @@ export interface CromboloConfig {
176
180
  * except under `bun test`.
177
181
  */
178
182
  liveReload: boolean
183
+ /**
184
+ * Whether webhooks, a form's send-to-URL workflow and an identity provider's
185
+ * test may reach loopback, private and link-local addresses (stories 301,
186
+ * 304). `CROMBOLO_ALLOW_PRIVATE_ADDRESSES`; on in development only.
187
+ */
188
+ allowPrivateAddresses: boolean
189
+ /**
190
+ * Identity providers no change from the back office reaches (story 305), by
191
+ * id, or all of them: `CROMBOLO_LOCKED_IDENTITY_PROVIDERS`, so a host locks
192
+ * them without the site's code. A provider's own `locked: true` does too.
193
+ */
194
+ lockedIdentityProviders: LockedIdentityProviders
179
195
  /**
180
196
  * Whether the cache-busted asset path may be cached immutably. Defaults to
181
197
  * `!development`.
@@ -543,12 +559,10 @@ export interface CromboloConfig {
543
559
  */
544
560
  events?: Readonly<Record<string, SiteEventHandler>>
545
561
  /**
546
- * What a webhook may reach (story 301): the server variables a header's
547
- * `env:NAME` may name besides `CROMBOLO_WEBHOOK_*`, and whether deliveries may
548
- * go to loopback, private and link-local addresses: by default only on a
549
- * development site. docs/webhooks.md.
562
+ * The server variables a webhook header's `env:NAME` may name besides
563
+ * `CROMBOLO_WEBHOOK_*` (story 301). docs/webhooks.md.
550
564
  */
551
- webhooks?: { headerVariables?: readonly string[]; allowPrivateAddresses?: boolean }
565
+ webhooks?: { headerVariables?: readonly string[] }
552
566
  /**
553
567
  * Installed extensions the site's code grants and sets (story 310), by bundle
554
568
  * id: what it grants, as "Developer installed", and settings, which lock them
@@ -978,6 +992,8 @@ export function loadConfig(
978
992
  // Resolved again below, once it is known whether this is development.
979
993
  errors: { showDetails: envFlag(setting('CROMBOLO_SHOW_ERROR_DETAILS')) ?? false },
980
994
  liveReload: envFlag(setting('CROMBOLO_LIVE_RELOAD')) ?? false,
995
+ allowPrivateAddresses: envFlag(setting('CROMBOLO_ALLOW_PRIVATE_ADDRESSES')) ?? false,
996
+ lockedIdentityProviders: lockedProviders(setting('CROMBOLO_LOCKED_IDENTITY_PROVIDERS')),
981
997
  seo: stripUndefined({
982
998
  sitemap: envFlag(setting('CROMBOLO_SITEMAP')),
983
999
  indexable: envFlag(setting('CROMBOLO_INDEXABLE')),
@@ -1054,6 +1070,14 @@ export function loadConfig(
1054
1070
  overrides.liveReload ??
1055
1071
  envFlag(setting('CROMBOLO_LIVE_RELOAD')) ??
1056
1072
  (merged.development && setting('NODE_ENV') !== 'test')
1073
+ merged.allowPrivateAddresses =
1074
+ overrides.allowPrivateAddresses ??
1075
+ envFlag(setting('CROMBOLO_ALLOW_PRIVATE_ADDRESSES')) ??
1076
+ merged.development
1077
+ if (overrides.webhooks && 'allowPrivateAddresses' in overrides.webhooks)
1078
+ throw new Error(
1079
+ 'webhooks.allowPrivateAddresses is now CROMBOLO_ALLOW_PRIVATE_ADDRESSES (allowPrivateAddresses in the config), which covers forms and identity providers too (story 304).',
1080
+ )
1057
1081
  checkApiClient(merged.apiClient)
1058
1082
  checkHost(merged.host)
1059
1083
  // The key itself is refused, so a config left over from before says so rather
@@ -1126,6 +1150,14 @@ function nonNegative(value: string | undefined, fallback: number): number {
1126
1150
  return Number.isInteger(parsed) && parsed >= 0 ? parsed : fallback
1127
1151
  }
1128
1152
 
1153
+ function lockedProviders(value: string | undefined): LockedIdentityProviders {
1154
+ const ids = (value ?? '')
1155
+ .split(',')
1156
+ .map((id) => id.trim())
1157
+ .filter(Boolean)
1158
+ return ids.includes('all') ? 'all' : ids
1159
+ }
1160
+
1129
1161
  function envFlag(value: string | undefined): boolean | undefined {
1130
1162
  return value === undefined ? undefined : value !== 'false'
1131
1163
  }
@@ -1161,7 +1193,7 @@ export function describeDatabase(
1161
1193
  }
1162
1194
  }
1163
1195
 
1164
- export const VERSION = '0.61.0'
1196
+ export const VERSION = '0.62.0'
1165
1197
 
1166
1198
  /** A whole number of seconds from the environment; undefined when unset or not one. */
1167
1199
  /** A positive number from a setting, else the default. */
package/src/core.ts CHANGED
@@ -40,7 +40,7 @@ import {
40
40
  ViewSnapshots,
41
41
  } from '@crombolo/render'
42
42
  import type { SyncReport } from '@crombolo/schema'
43
- import { recordAudit } from './adapters/audit.ts'
43
+ import { attributed, recordAudit } from './adapters/audit.ts'
44
44
  import { createMediaSource, createPublishedContentSource } from './adapters/documents.ts'
45
45
  import { backOfficeUrl, documentEditUrl } from './back-office-url.ts'
46
46
  import { BACKOFFICE_EXTERNAL_PATH } from './backoffice-external.ts'
@@ -500,7 +500,7 @@ export async function createCore(config: CromboloConfig, hooks: CoreHooks) {
500
500
  // A development site's receivers are on this machine, as the Next.js template's is.
501
501
  outbound: {
502
502
  ...config.webhooks,
503
- allowPrivateAddresses: config.webhooks?.allowPrivateAddresses ?? config.development,
503
+ allowPrivateAddresses: config.allowPrivateAddresses,
504
504
  },
505
505
  isBundleOn: (bundleId) => bundleGrants.isOn(bundleId),
506
506
  bundleOrigins: (bundleId) => {
@@ -575,6 +575,60 @@ export async function createCore(config: CromboloConfig, hooks: CoreHooks) {
575
575
  * boot — see `createServerBundles`.
576
576
  */
577
577
  // Story 198: media as the member, built at the first request.
578
+ /** The identity providers an extension edits (story 033), auditing each change when told how (305). */
579
+ const identityProvidersFor = (
580
+ audit?: Parameters<typeof createBundleIdentityProviders>[0]['audit'],
581
+ ) =>
582
+ createBundleIdentityProviders({
583
+ audit,
584
+ overrides: new IdentityProviderOverrides(
585
+ db,
586
+ config.secretKey,
587
+ config.lockedIdentityProviders,
588
+ ),
589
+ members: config.memberIdentityProviders,
590
+ backoffice: config.backofficeIdentityProviders,
591
+ memberCallbackPath: MEMBER_EXTERNAL_SIGN_IN_PATH,
592
+ backofficeCallbackPath: BACKOFFICE_EXTERNAL_PATH,
593
+ outbound: { allowPrivateAddresses: config.allowPrivateAddresses },
594
+ groups: async (audience) =>
595
+ audience === 'user'
596
+ ? (await new UserGroupRepository(db).all()).map((g) => ({
597
+ value: g.alias,
598
+ name: g.name,
599
+ }))
600
+ : (
601
+ await db.q
602
+ .selectFrom('node')
603
+ .select('text')
604
+ .where('node_object_type', '=', ObjectTypes.MemberGroup)
605
+ .orderBy('text')
606
+ .execute()
607
+ ).map((g) => ({ value: String(g.text), name: String(g.text) })),
608
+ })
609
+ // Story 305: said at boot, a provider that signs nobody in and a locked id that names none.
610
+ void (async () => {
611
+ const overrides = new IdentityProviderOverrides(
612
+ db,
613
+ config.secretKey,
614
+ config.lockedIdentityProviders,
615
+ )
616
+ const declared = [
617
+ ...config.memberIdentityProviders.map((provider) => ['member', provider] as const),
618
+ ...config.backofficeIdentityProviders.map((provider) => ['user', provider] as const),
619
+ ]
620
+ for (const [audience, provider] of declared) {
621
+ const effective = await overrides.apply(audience, provider).catch(() => provider)
622
+ if (effective.unavailable) log.warning('{reason}', { reason: effective.unavailable })
623
+ }
624
+ if (Array.isArray(config.lockedIdentityProviders))
625
+ for (const id of config.lockedIdentityProviders)
626
+ if (!declared.some(([, provider]) => provider.oidc.id === id))
627
+ log.warning(
628
+ 'CROMBOLO_LOCKED_IDENTITY_PROVIDERS names {id}, which the config declares no identity provider as.',
629
+ { id },
630
+ )
631
+ })()
578
632
  let bundleMedia: BundleMediaFactory | undefined
579
633
  let bundleMediaFolders = new Map<string, ResolvedMediaFolder[]>()
580
634
  const bundles =
@@ -601,30 +655,27 @@ export async function createCore(config: CromboloConfig, hooks: CoreHooks) {
601
655
  },
602
656
  },
603
657
  log: bundleLog('bundle'),
604
- identityProviders: createBundleIdentityProviders({
605
- overrides: new IdentityProviderOverrides(db, config.secretKey),
606
- members: config.memberIdentityProviders,
607
- backoffice: config.backofficeIdentityProviders,
608
- memberCallbackPath: MEMBER_EXTERNAL_SIGN_IN_PATH,
609
- backofficeCallbackPath: BACKOFFICE_EXTERNAL_PATH,
610
- groups: async (audience) =>
611
- audience === 'user'
612
- ? (await new UserGroupRepository(db).all()).map((g) => ({
613
- value: g.alias,
614
- name: g.name,
615
- }))
616
- : (
617
- await db.q
618
- .selectFrom('node')
619
- .select('text')
620
- .where('node_object_type', '=', ObjectTypes.MemberGroup)
621
- .orderBy('text')
622
- .execute()
623
- ).map((g) => ({ value: String(g.text), name: String(g.text) })),
624
- }),
658
+ identityProviders: identityProvidersFor(),
625
659
  },
626
660
  log: (id) => bundleLog(id),
627
661
  callerHost: {
662
+ // Story 305: each change audited as the person, by the extension.
663
+ identityProviders: (caller, bundle) =>
664
+ identityProvidersFor(async (action, provider, detail) => {
665
+ const person = personOf(caller)
666
+ const name = bundlePackages.find((pkg) => pkg.id === bundle.id)?.name ?? bundle.id
667
+ await recordAudit(db, {
668
+ category: 'settings',
669
+ action,
670
+ source: 'request',
671
+ userKey: person.personKey,
672
+ userName: person.personName,
673
+ entityType: 'IdentityProvider',
674
+ entityKey: `${provider.audience}:${provider.id}`,
675
+ entityName: provider.name,
676
+ detail: attributed(name, person.personName, detail),
677
+ })
678
+ }),
628
679
  // Story 308: the site's areas, as the extension; story 325, or as the person using it.
629
680
  api: (caller, bundle) => {
630
681
  const pkg = bundlePackages.find((candidate) => candidate.id === bundle.id)
@@ -678,8 +729,7 @@ export async function createCore(config: CromboloConfig, hooks: CoreHooks) {
678
729
  }
679
730
  return timed(activity, event, () =>
680
731
  pinnedFetch(input, init, {
681
- allowPrivateAddresses:
682
- config.webhooks?.allowPrivateAddresses ?? config.development,
732
+ allowPrivateAddresses: config.allowPrivateAddresses,
683
733
  }),
684
734
  )
685
735
  },
@@ -854,6 +904,8 @@ export async function createCore(config: CromboloConfig, hooks: CoreHooks) {
854
904
  resolveForm: (form) => cache.resolveForm(form),
855
905
  operations: operations.documents,
856
906
  bundleWorkflows: formTypes.workflows,
907
+ outbound: { allowPrivateAddresses: config.allowPrivateAddresses },
908
+ secretKey: config.secretKey,
857
909
  renderEmail: (alias, props) => renderer.renderEmail(alias, props),
858
910
  site: async () => ({
859
911
  name: (await hooks.siteName?.()) || config.siteName,