@crombolo/server 0.55.0 → 0.57.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/package.json +16 -13
  2. package/src/actions.ts +6 -1
  3. package/src/adapters/bundles.ts +72 -6
  4. package/src/adapters/health.ts +30 -1
  5. package/src/bundle-admin.ts +246 -23
  6. package/src/bundle-api.ts +299 -0
  7. package/src/bundle-build.ts +4 -3
  8. package/src/bundle-grants.ts +133 -18
  9. package/src/bundle-install.ts +140 -11
  10. package/src/bundle-sections.ts +49 -4
  11. package/src/bundles.ts +87 -7
  12. package/src/component-templates-api.ts +27 -6
  13. package/src/components.ts +7 -0
  14. package/src/config.ts +56 -3
  15. package/src/content-events.ts +17 -1
  16. package/src/core.ts +219 -15
  17. package/src/created-extension.ts +101 -0
  18. package/src/extension-components.ts +157 -0
  19. package/src/extension-discovery.ts +180 -0
  20. package/src/extension-process.ts +854 -0
  21. package/src/extension-sql.ts +85 -0
  22. package/src/index.ts +21 -0
  23. package/src/marketplace.ts +182 -54
  24. package/src/outbound-address.ts +182 -0
  25. package/src/owner-jobs.ts +7 -1
  26. package/src/ports.ts +8 -0
  27. package/src/provenance.ts +181 -15
  28. package/src/remote.ts +62 -10
  29. package/src/routes.ts +13 -1
  30. package/src/schema.ts +37 -6
  31. package/src/seed/compile.ts +4 -2
  32. package/src/seed/export.ts +1 -1
  33. package/src/seed/values.ts +3 -3
  34. package/src/seo.ts +13 -5
  35. package/src/server.ts +192 -45
  36. package/src/settings.ts +12 -4
  37. package/src/signing-keys.ts +155 -0
  38. package/src/site-content-values.ts +97 -0
  39. package/src/site-content.ts +292 -0
  40. package/src/site-events.ts +65 -0
  41. package/src/site-file.ts +20 -6
  42. package/src/site-public.ts +1 -1
  43. package/src/site-sections.ts +1 -1
  44. package/src/site-services.ts +4 -0
  45. package/src/site-trust.ts +238 -0
  46. package/src/transfer-dashboard.ts +6 -0
  47. package/src/trusted-signers-admin.ts +132 -0
  48. package/src/webhooks.ts +182 -17
package/src/remote.ts CHANGED
@@ -34,14 +34,17 @@ import {
34
34
  type TrustRule,
35
35
  } from '@crombolo/data'
36
36
  import {
37
+ BUNDLE_FORMAT_VERSION,
37
38
  type ContentSet,
38
39
  isResolution,
39
40
  type NodeResolutions,
41
+ OLDEST_BUNDLE_FORMAT_VERSION,
40
42
  type Resolution,
41
43
  revertRun,
42
44
  } from '@crombolo/transfer'
43
45
  import { readAuditPageQuery, recordAudit } from './adapters/audit.ts'
44
- import type { BundleAdmin } from './bundle-admin.ts'
46
+ import { type BundleAdmin, settingsIn } from './bundle-admin.ts'
47
+ import { actAsChoice } from './bundle-api.ts'
45
48
  import { codeChanges, installedCode, planCode } from './bundle-code-install.ts'
46
49
  import {
47
50
  checkBundleContent,
@@ -49,7 +52,12 @@ import {
49
52
  readBundle,
50
53
  revertSections,
51
54
  } from './bundle-install.ts'
52
- import { carriesSections, type SectionFile, swappedSections } from './bundle-sections.ts'
55
+ import {
56
+ carriesSections,
57
+ migrationChanges,
58
+ type SectionFile,
59
+ swappedSections,
60
+ } from './bundle-sections.ts'
53
61
  import { type CromboloConfig, REMOTE_ACCESS_LEVELS, type RemoteAccess } from './config.ts'
54
62
  import { answerContentQuery, contentQueryScope } from './content-query.ts'
55
63
  import { mediaStoreFor } from './media-files.ts'
@@ -192,6 +200,8 @@ export function createRemote(options: RemoteOptions): Remote {
192
200
  const discovery = (origin: string) => ({
193
201
  protocol: 'crombolo-remote',
194
202
  versions: [REMOTE_PROTOCOL_VERSION],
203
+ // The bundle formats this site reads, oldest and newest (story 306).
204
+ bundleFormats: [OLDEST_BUNDLE_FORMAT_VERSION, BUNDLE_FORMAT_VERSION],
195
205
  name: config.siteName,
196
206
  api: `${origin}${REMOTE_API_PATH}`,
197
207
  auth: {
@@ -507,6 +517,7 @@ export function createRemote(options: RemoteOptions): Remote {
507
517
  const canBackUp = config.dialect === 'sqlite' || Boolean(config.pgDump)
508
518
  const result = await installBundleContent(db, config, {
509
519
  bundle: dir,
520
+ expects: 'site' as const,
510
521
  replace: 'replace',
511
522
  passphrase,
512
523
  backupTaken: !canBackUp,
@@ -631,7 +642,7 @@ export function createRemote(options: RemoteOptions): Remote {
631
642
  return { sha256: hasher.digest('hex'), size }
632
643
  }
633
644
 
634
- /** The options a bundle apply was sent with, in `Crombolo-Options` (story 167). */
645
+ /** The options a site apply was sent with, in `Crombolo-Options` (story 167). */
635
646
  const applyOptions = (request: Request) => {
636
647
  let raw: Record<string, unknown> = {}
637
648
  try {
@@ -651,6 +662,7 @@ export function createRemote(options: RemoteOptions): Remote {
651
662
  dryRun: raw.dryRun === true,
652
663
  publish: raw.publish === true,
653
664
  replaceFiles: raw.replaceFiles === true,
665
+ allowDowngrade: raw.allowDowngrade === true,
654
666
  label: typeof raw.label === 'string' ? raw.label.slice(0, 200) : undefined,
655
667
  resolutions,
656
668
  resolveAll,
@@ -659,7 +671,7 @@ export function createRemote(options: RemoteOptions): Remote {
659
671
 
660
672
  /**
661
673
  * A bundle applied here (story 167): checked, and unless a dry run backed up
662
- * and applied in one transaction as `bundle apply` does on a site's own
674
+ * and applied in one transaction as `site apply` does on a site's own
663
675
  * machine. Content needs the `content` level and the right to change this
664
676
  * site; schema, views or code need `all` and Crombolo.Remote.ApplyStructure.
665
677
  */
@@ -699,7 +711,8 @@ export function createRemote(options: RemoteOptions): Remote {
699
711
  try {
700
712
  const carried = readBundle(dir, config.siteDir).carried
701
713
  structural = carriesSections(carried)
702
- code = codeChanges(planCode(config, carried))
714
+ // A bundle's value migrations are code too (story 300).
715
+ code = [...codeChanges(planCode(config, carried)), ...migrationChanges(config, carried)]
703
716
  } catch (error) {
704
717
  return problem(400, {
705
718
  code: 'not-a-bundle',
@@ -744,11 +757,13 @@ export function createRemote(options: RemoteOptions): Remote {
744
757
  })
745
758
  const input = {
746
759
  bundle: dir,
760
+ expects: 'site' as const,
747
761
  publish: asked.publish,
748
762
  replaceFiles: asked.replaceFiles,
749
763
  installCode: code.length > 0,
750
764
  resolutions: asked.resolutions,
751
765
  resolveAll: asked.resolveAll,
766
+ allowDowngrade: asked.allowDowngrade,
752
767
  by: principal.name,
753
768
  }
754
769
  const report = (check: {
@@ -772,6 +787,7 @@ export function createRemote(options: RemoteOptions): Remote {
772
787
  structural,
773
788
  provenance,
774
789
  code: code.map((file) => ({ path: file.path, action: file.action })),
790
+ sitePackage: checked.sitePackage ?? null,
775
791
  bundle: checked.bundle,
776
792
  ...report(checked.check),
777
793
  clean: checked.clean,
@@ -817,7 +833,7 @@ export function createRemote(options: RemoteOptions): Remote {
817
833
  }
818
834
  }
819
835
 
820
- /** The applies on this site, newest first: for `bundle runs --remote`. */
836
+ /** The applies on this site, newest first: for `site runs --remote`. */
821
837
  async function listRuns(url: URL, principal: Principal): Promise<Response> {
822
838
  if (!atLeast('read')) return notAtLevel('read', 'reads')
823
839
  if (!may(principal, RemotePermissions.Pull) && !mayChange(principal))
@@ -837,6 +853,7 @@ export function createRemote(options: RemoteOptions): Remote {
837
853
  bundleId: run.bundleId,
838
854
  bundleLabel: run.bundleLabel ?? null,
839
855
  appliedBy: run.appliedBy ?? null,
856
+ bundleType: run.bundleType,
840
857
  })),
841
858
  })
842
859
  }
@@ -872,6 +889,30 @@ export function createRemote(options: RemoteOptions): Remote {
872
889
  }
873
890
  if (!fromThisSiteOrBearer(request)) return new Response('Forbidden', { status: 403 })
874
891
  if (!atLeast('all')) return notAtLevel('all', 'installing and switching bundles')
892
+ // Story 309: granting an installed extension what it asks for.
893
+ const granting = /^installed\/(.+)\/grant$/.exec(what)
894
+ if (granting && request.method === 'POST') {
895
+ if (!may(principal, RemotePermissions.InstallCode))
896
+ return problem(403, {
897
+ code: 'forbidden-code',
898
+ title: 'You may not grant an extension on this site',
899
+ detail: 'Granting one needs Crombolo.Remote.InstallCode, given by a group.',
900
+ })
901
+ const body = (await request.json().catch(() => ({}))) as Record<string, unknown>
902
+ const { status, ...outcome } = await bundles.grant(
903
+ actor,
904
+ decodeURIComponent(granting[1] as string),
905
+ {
906
+ grant: Array.isArray(body.grant)
907
+ ? body.grant.filter((p): p is string => typeof p === 'string')
908
+ : [],
909
+ actAs: actAsChoice(body.actAs),
910
+ },
911
+ )
912
+ return status === 200
913
+ ? Response.json(outcome)
914
+ : problem(status, { code: 'grant-mismatch', title: outcome.message })
915
+ }
875
916
  const switched = /^installed\/(.+)\/(disable|enable)$/.exec(what)
876
917
  if (switched && request.method === 'POST') {
877
918
  if (principal.ci ? !may(principal, RemotePermissions.ApplyStructure) : !principal.isAdmin)
@@ -914,7 +955,9 @@ export function createRemote(options: RemoteOptions): Remote {
914
955
  })
915
956
  if (removing) {
916
957
  const name = decodeURIComponent(what.slice('installed/'.length))
917
- const outcome = await bundles.uninstall(actor, name)
958
+ const outcome = await bundles.uninstall(actor, name, {
959
+ revertContent: new URL(request.url).searchParams.get('revertContent') === 'true',
960
+ })
918
961
  return outcome.ok
919
962
  ? Response.json(outcome)
920
963
  : problem(409, { code: 'uninstall-refused', title: outcome.message })
@@ -929,11 +972,12 @@ export function createRemote(options: RemoteOptions): Remote {
929
972
  version: typeof body.version === 'string' ? body.version : undefined,
930
973
  applyContent: body.applyContent === true,
931
974
  // Naming the grant is the consent: a script that names what it grants has said yes.
932
- acceptServerCode: true,
933
975
  grant,
976
+ actAs: typeof body.actAs === 'string' ? body.actAs : null,
977
+ settings: settingsIn(body.settings),
934
978
  })
935
979
  if (outcome.ok) return Response.json(outcome)
936
- if (outcome.needsServerConsent) {
980
+ if (outcome.needsGrant) {
937
981
  const asked = (outcome.permissions ?? []).map((p) => p.permission)
938
982
  const missing = asked.filter((p) => !grant.includes(p))
939
983
  const extra = grant.filter((p) => !asked.includes(p))
@@ -950,7 +994,7 @@ export function createRemote(options: RemoteOptions): Remote {
950
994
  return problem(409, { code: 'install-refused', title: outcome.message })
951
995
  }
952
996
 
953
- /** Undoes an apply (story 167), as `bundle revert` does here; files it replaced come back too. */
997
+ /** Undoes an apply (story 167), as `site revert` does here; files it replaced come back too. */
954
998
  async function revertBundleRun(
955
999
  request: Request,
956
1000
  principal: Principal,
@@ -961,6 +1005,14 @@ export function createRemote(options: RemoteOptions): Remote {
961
1005
  return problem(403, { code: 'forbidden', title: 'You may not change this environment' })
962
1006
  if (!fromThisSiteOrBearer(request)) return new Response('Forbidden', { status: 403 })
963
1007
  const body = (await request.json().catch(() => ({}))) as { force?: unknown }
1008
+ // An extension's content is put back by uninstalling it (story 306).
1009
+ const run = await new TransferRunRepository(db).byId(runId)
1010
+ if (run?.bundleType === 'extension')
1011
+ return problem(409, {
1012
+ code: 'extension-run',
1013
+ title: "That run brought an extension's content",
1014
+ detail: `It is put back by uninstalling ${run.packageName ?? 'the extension'}, with its content reverted.`,
1015
+ })
964
1016
  // A run that installed code changes code back, which needs what it did.
965
1017
  if (
966
1018
  installedCode(config, runId) &&
package/src/routes.ts CHANGED
@@ -5,6 +5,7 @@
5
5
  * response — a `Result`'s value as JSON, an outcome as its status, an error as
6
6
  * problem+json or the status page. docs/rendering.md, "Route handlers".
7
7
  */
8
+
8
9
  import { type CorsPolicy, isPreflight, preflightResponse, withCors } from '@crombolo/api-delivery'
9
10
  import {
10
11
  type CookieOptions,
@@ -19,6 +20,7 @@ import {
19
20
  import { ANTIFORGERY_HEADER, type PageOutcome, requestScope } from '@crombolo/render'
20
21
  import { isSitePath, requestCookies } from './middleware.ts'
21
22
  import { RateLimiter } from './rate-limit.ts'
23
+ import { withSiteWrites } from './site-content.ts'
22
24
 
23
25
  /** A member as a route sees them: their key, for limits, and their group names. */
24
26
  export interface RouteMember {
@@ -51,6 +53,9 @@ export interface RouteDeps<Member extends RouteMember> {
51
53
  }
52
54
 
53
55
  /** A route with what it needs added to its context, such as a bundle's capabilities. */
56
+ /** Who the site's own routes are declared by; a bundle's say its id. */
57
+ export const SITE_ROUTE_OWNER = 'the site'
58
+
54
59
  export interface DeclaredRoute {
55
60
  route: SiteRoute
56
61
  /** Who declared it, for errors and logs: the site, or a bundle by id. */
@@ -342,7 +347,14 @@ export function createRoutes<Member extends RouteMember>(
342
347
  let response: Response
343
348
  try {
344
349
  const work = Promise.resolve().then(() =>
345
- requestScope({ headers: request.headers }, site, () => handler(request, context as never)),
350
+ requestScope({ headers: request.headers }, site, () =>
351
+ // The site's own routes may change content (story 298), named for the audit.
352
+ entry.owner === SITE_ROUTE_OWNER
353
+ ? withSiteWrites({ via: `route ${method} ${route.path}`, source: 'request' }, () =>
354
+ handler(request, context as never),
355
+ )
356
+ : handler(request, context as never),
357
+ ),
346
358
  )
347
359
  work.catch(() => {})
348
360
  const answer = await Promise.race([work, overran])
package/src/schema.ts CHANGED
@@ -5,6 +5,7 @@
5
5
  */
6
6
 
7
7
  import { existsSync, watch } from 'node:fs'
8
+ import { discoverBundles } from '@crombolo/backoffice-host/registry'
8
9
  import {
9
10
  CACHE_INSTRUCTION_CHANNEL,
10
11
  type CacheInstructionKind,
@@ -76,7 +77,11 @@ export async function checkSchemaDirectory(
76
77
  db: Db,
77
78
  config: CromboloConfig,
78
79
  node: { nodeId: string; revision: string },
79
- options: { set?: Record<string, unknown> } = {},
80
+ options: {
81
+ set?: Record<string, unknown>
82
+ /** Where the value migrations are loaded from: the schema's own, unless a check says otherwise. */
83
+ migrationsDir?: string
84
+ } = {},
80
85
  ): Promise<CheckReport> {
81
86
  const loaded = loadSchemaDirectory(config.schemaDir, { formTypes: formTypesFor(config) })
82
87
  return runCheck(
@@ -86,7 +91,7 @@ export async function checkSchemaDirectory(
86
91
  {
87
92
  ...syncOptionsFor(config),
88
93
  set: options.set,
89
- migrations: await loadValueMigrations(config.schemaDir),
94
+ migrations: await loadValueMigrations(options.migrationsDir ?? config.schemaDir),
90
95
  backOfficePath: config.backOfficePath,
91
96
  },
92
97
  )
@@ -104,16 +109,42 @@ export class SchemaBootError extends Error {
104
109
 
105
110
  /**
106
111
  * The components a schema may name as templates: every one of them, at any
107
- * depth, keyed by the path that is its alias.
112
+ * depth, keyed by the path that is its alias. With the site's directory, an
113
+ * installed extension's too, as `<id>/<name>` (story 312): its own components
114
+ * are known only once it has started, so any name under its id is accepted, and
115
+ * one it does not offer is logged when a page renders it.
108
116
  */
109
- export function componentAliasesIn(componentsDir: string): Set<string> {
110
- return new Set(listComponents(componentsDir).map((component) => component.alias))
117
+ export function componentAliasesIn(componentsDir: string, siteDir?: string): ReadonlySet<string> {
118
+ const files = new Set(listComponents(componentsDir).map((component) => component.alias))
119
+ if (!siteDir) return files
120
+ const ids = new Set(
121
+ discoverBundles(siteDir)
122
+ .bundles.filter((pkg) => pkg.bundleType === 'extension' && pkg.carries.server)
123
+ .map((pkg) => pkg.id),
124
+ )
125
+ return new ComponentAliases(files, ids)
126
+ }
127
+
128
+ /** The site's component files, and any name under an installed extension's id. */
129
+ class ComponentAliases extends Set<string> {
130
+ readonly #extensions: ReadonlySet<string>
131
+ constructor(files: Iterable<string>, extensions: ReadonlySet<string>) {
132
+ super(files)
133
+ this.#extensions = extensions
134
+ }
135
+ override has(alias: string): boolean {
136
+ const slash = alias.indexOf('/')
137
+ return (
138
+ super.has(alias) ||
139
+ (slash > 0 && slash < alias.length - 1 && this.#extensions.has(alias.slice(0, slash)))
140
+ )
141
+ }
111
142
  }
112
143
 
113
144
  export function syncOptionsFor(config: CromboloConfig): SyncOptions {
114
145
  return {
115
146
  mode: config.development ? 'development' : 'production',
116
- componentAliases: componentAliasesIn(config.componentsDir),
147
+ componentAliases: componentAliasesIn(config.componentsDir, config.siteDir),
117
148
  formTypes: formTypesFor(config),
118
149
  }
119
150
  }
@@ -581,7 +581,7 @@ export async function compileSeed(db: Db, config: CromboloConfig): Promise<SeedB
581
581
  id,
582
582
  label: 'Content files',
583
583
  createdAt: new Date(0).toISOString(),
584
- createdBy: 'crombolo bundle apply',
584
+ createdBy: 'crombolo site apply',
585
585
  integrity: '',
586
586
  snapshot: 'drafts',
587
587
  provenance: {
@@ -622,15 +622,17 @@ export async function compileSeed(db: Db, config: CromboloConfig): Promise<SeedB
622
622
  },
623
623
  ]
624
624
  : [],
625
+ { bundleType: 'site' },
625
626
  )
626
627
  const files = writeBundlePackage(payload, {
627
628
  name: 'crombolo-site-seed',
628
629
  version: '0.0.0',
629
630
  id: 'site-seed',
630
631
  label: 'Content files',
631
- description: `The content files of ${config.siteName}, built by crombolo bundle build`,
632
+ description: `The content files of ${config.siteName}, built by crombolo site build`,
632
633
  private: true,
633
634
  peerRange: `>=${VERSION}`,
635
+ bundleType: 'site',
634
636
  })
635
637
  return { findings, set, blobs, files, counts, ...(dictionary ? { dictionary: entries } : {}) }
636
638
  }
@@ -4,7 +4,7 @@
4
4
  * `content/pages/`, Library elements to `content/library/`, and media, files and
5
5
  * all, to `content/media/`.
6
6
  *
7
- * Values are written in the shorthand `bundle apply` reads back — rich text as
7
+ * Values are written in the shorthand `site apply` reads back — rich text as
8
8
  * `{ html }`, pickers and links as paths to what the export carries, blocks as
9
9
  * `{ type, key, values }` — and in their editor's stored shape where there is
10
10
  * none. A node keeps its key in its file wherever it is not the one its path
@@ -1,9 +1,9 @@
1
1
  /**
2
2
  * Values in the shorthand a person writes, both ways (stories 163, 253):
3
3
  * Markdown, paths and `{ type, alias, values }` blocks into each property
4
- * editor's stored shape, as `bundle apply` reads content files and the
4
+ * editor's stored shape, as `site apply` reads content files and the
5
5
  * `content` commands read `--set`; and stored values back into that shorthand,
6
- * as `bundle export --source` and `content show` write them.
6
+ * as `content export` and `content show` write them.
7
7
  */
8
8
  import { type ContentTypeAggregate, dateFromText, normaliseUuid } from '@crombolo/core'
9
9
  import { ContentTypeRepository, DataTypeRepository, type Db, looksLikeKey } from '@crombolo/data'
@@ -314,7 +314,7 @@ export function valueWriter(lookup: SchemaLookup, refs: ValueRefs) {
314
314
  const link = typeof entry === 'string' ? { path: entry } : entry
315
315
  if (!isRecord(link))
316
316
  return fail('a link is a path, a URL, or { path | url, name, target }')
317
- // A link as the editor stores it, as `bundle export --source` writes one.
317
+ // A link as the editor stores it, as `content export` writes one.
318
318
  if ('unique' in link || 'type' in link) {
319
319
  links.push(link)
320
320
  continue
package/src/seo.ts CHANGED
@@ -175,6 +175,8 @@ export interface DraftModel {
175
175
  content: PublishedContent
176
176
  contentTypeAlias: string
177
177
  published: boolean
178
+ /** The page as visitors see it now, when it is published. */
179
+ live?: PublishedContent
178
180
  culture: string | null
179
181
  }
180
182
 
@@ -412,17 +414,23 @@ export function createSeoHost(options: SeoHostOptions): SeoHost {
412
414
  if (!draft) return Response.json({ message: 'That page could not be found.' }, { status: 404 })
413
415
  const origin = publicOrigin(request, config)
414
416
  const snapshot = await cache.snapshot()
415
- const meta = await effectiveMeta(draft.content, {
416
- origin,
417
- alternates: urlsIn(snapshot, key),
418
- site: await siteDefaults(),
419
- })
417
+ const context = { origin, alternates: urlsIn(snapshot, key), site: await siteDefaults() }
418
+ const meta = await effectiveMeta(draft.content, context)
419
+ // Said only when what search engines see now is not this: unpublished, or changed since.
420
+ const live = draft.live ? await effectiveMeta(draft.live, context) : undefined
421
+ const differs = !draft.published
422
+ ? 'unpublished'
423
+ : live && JSON.stringify(live) !== JSON.stringify(meta)
424
+ ? 'changed'
425
+ : null
420
426
  return Response.json({
421
427
  hasSeoFields: await composesSeoFields(draft.contentTypeAlias),
422
428
  published: draft.published,
429
+ differs,
423
430
  culture: draft.culture,
424
431
  meta,
425
432
  snippet: {
433
+ name: draft.content.name,
426
434
  title: meta.fullTitle,
427
435
  url: meta.canonical.value ?? '',
428
436
  description: meta.description.value ?? '',