@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
@@ -0,0 +1,157 @@
1
+ /**
2
+ * An extension's components, rendered in its own process (story 312). The page,
3
+ * its layouts and the site's components render here; when the render reaches one
4
+ * an extension owns, `<id>/<name>`, that one component is a `render` call to the
5
+ * extension, and its HTML goes in its place. docs/extensions.md, "Components".
6
+ */
7
+ import {
8
+ type ComponentModule,
9
+ markPersonal,
10
+ PublishedContent,
11
+ PublishedElement,
12
+ RawHtml,
13
+ } from '@crombolo/render'
14
+ import type { BundleLog } from './bundles.ts'
15
+ import type { ExtensionProcess } from './extension-process.ts'
16
+
17
+ /** One extension whose components may render: its process, and what it may do now. */
18
+ export interface ExtensionComponentSource {
19
+ process: ExtensionProcess
20
+ /** What it may use now, from its grant; `templates` is what lets it render. */
21
+ granted(): readonly string[]
22
+ /** The site layout its page templates sit in: its `layout` setting. */
23
+ layout(): string | undefined
24
+ log: BundleLog
25
+ }
26
+
27
+ export interface ExtensionComponents {
28
+ /** The component `<id>/<name>` as a module the renderer runs, or undefined when none is. */
29
+ module(alias: string): ComponentModule | undefined
30
+ /** The layout each extension's `layout` setting names, where one does. */
31
+ layouts(): { id: string; layout: string }[]
32
+ /** Every component the extensions offer, as `<id>/<name>` with the extension's name: for the template picker. */
33
+ listed(): { alias: string; extension: string }[]
34
+ }
35
+
36
+ const BLOCKS = 'blocks/'
37
+
38
+ /** How many pages and elements one render sends with their values; past it, values are calls. */
39
+ const VALUES_PER_RENDER = 200
40
+
41
+ /**
42
+ * The values sent with each page and element a render lends, so the component
43
+ * reads them synchronously, as a site component does (story 312).
44
+ */
45
+ function valuesSender(): (value: object) => Record<string, unknown> | undefined {
46
+ let left = VALUES_PER_RENDER
47
+ return (value) => {
48
+ if (!(value instanceof PublishedContent || value instanceof PublishedElement)) return undefined
49
+ if (left <= 0) return undefined
50
+ left -= 1
51
+ const values: Record<string, unknown> = {}
52
+ for (const { alias } of value.properties) {
53
+ if (alias in values) continue
54
+ try {
55
+ values[alias] = {
56
+ value: value.value(alias),
57
+ text: value.text(alias),
58
+ html: value.html(alias),
59
+ }
60
+ } catch {
61
+ // Left to a call, which says what went wrong.
62
+ }
63
+ }
64
+ return { $values: values }
65
+ }
66
+ }
67
+
68
+ export function createExtensionComponents(
69
+ sources: readonly ExtensionComponentSource[],
70
+ options: { timeoutMs?: number } = {},
71
+ ): ExtensionComponents {
72
+ const byId = new Map(sources.map((source) => [source.process.id, source]))
73
+ const warned = new Set<string>()
74
+ const offers = (source: ExtensionComponentSource, name: string) =>
75
+ source.process.description?.components?.some((component) => component.name === name) ?? false
76
+
77
+ const render = async (
78
+ source: ExtensionComponentSource,
79
+ name: string,
80
+ props: Record<string, unknown>,
81
+ ): Promise<RawHtml> => {
82
+ const id = source.process.id
83
+ if (!source.granted().includes('templates')) {
84
+ if (!warned.has(id)) {
85
+ warned.add(id)
86
+ source.log.warn(
87
+ 'The extension {id} was not granted templates, so its component {name} renders nothing.',
88
+ { id, name },
89
+ )
90
+ }
91
+ return new RawHtml('')
92
+ }
93
+ // A signed-in member may change what it renders, and its code cannot be read
94
+ // for `member` as a view's can: such a page is not shared.
95
+ if (props.member !== undefined) markPersonal()
96
+ const { searchParams, ...rest } = props
97
+ try {
98
+ const { value } = await source.process.call(
99
+ 'render',
100
+ { name },
101
+ // Read only if the component asks, since reading them makes the page personal.
102
+ { ...rest, readSearchParams: () => searchParams },
103
+ { timeoutMs: options.timeoutMs ?? 10_000, extra: valuesSender() },
104
+ )
105
+ return new RawHtml(typeof value === 'string' ? value : '')
106
+ } catch (error) {
107
+ source.log.error('The extension {id} could not render {name}: {error}', {
108
+ id,
109
+ name,
110
+ error: error instanceof Error ? error.message : String(error),
111
+ })
112
+ return new RawHtml('')
113
+ }
114
+ }
115
+
116
+ // The layout the administrator chose, else the one the component suggests: a
117
+ // site without that layout renders the body on its own.
118
+ const moduleFor = (source: ExtensionComponentSource, name: string): ComponentModule => ({
119
+ default: ((props: Record<string, unknown>) => render(source, name, props)) as never,
120
+ layout:
121
+ source.layout() ??
122
+ source.process.description?.components?.find((component) => component.name === name)?.layout,
123
+ })
124
+
125
+ return {
126
+ module(alias) {
127
+ // A block's component is found by its element type's alias, in whichever
128
+ // extension offers it.
129
+ if (alias.startsWith(BLOCKS)) {
130
+ const name = alias
131
+ const source = sources.find((candidate) => offers(candidate, name))
132
+ return source ? moduleFor(source, name) : undefined
133
+ }
134
+ const slash = alias.indexOf('/')
135
+ if (slash < 1) return undefined
136
+ const source = byId.get(alias.slice(0, slash))
137
+ const name = alias.slice(slash + 1)
138
+ return source && offers(source, name) ? moduleFor(source, name) : undefined
139
+ },
140
+ layouts() {
141
+ return sources.flatMap((source) => {
142
+ const layout = source.layout()
143
+ return layout ? [{ id: source.process.id, layout }] : []
144
+ })
145
+ },
146
+ listed() {
147
+ return sources.flatMap((source) =>
148
+ (source.process.description?.components ?? [])
149
+ .filter((component) => !component.name.startsWith(BLOCKS))
150
+ .map((component) => ({
151
+ alias: `${source.process.id}/${component.name}`,
152
+ extension: source.process.name,
153
+ })),
154
+ )
155
+ },
156
+ }
157
+ }
@@ -0,0 +1,180 @@
1
+ /**
2
+ * Installed extensions run once granted, with nothing imported by the site
3
+ * (story 310), each in a Deno process of its own (story 311). At boot, each
4
+ * dependency with a server half that the config's `extensions` entry grants,
5
+ * or that a recorded grant covers, is built, started with its settings, and
6
+ * mounted from what it describes. One that cannot start is left off, and the
7
+ * site starts without it. docs/bundles.md, "Extensions run once granted".
8
+ */
9
+ import { join } from 'node:path'
10
+ import type { BundlePackage } from '@crombolo/backoffice-host'
11
+ import { type ExtensionSetting, readSettings } from '@crombolo/backoffice-host/registry'
12
+ import {
13
+ type BundleGrant,
14
+ BundleGrantRepository,
15
+ connect,
16
+ ExtensionSettingRepository,
17
+ } from '@crombolo/data'
18
+ import { declaredOrigins, declaredPermissions, grantGaps } from './bundle-grants.ts'
19
+ import type { BundleLog, ServerBundle } from './bundles.ts'
20
+ import type { CromboloConfig, ExtensionEntry } from './config.ts'
21
+ import { ExtensionProcess, isolatedBundle, isolationProblems } from './extension-process.ts'
22
+ import { openSecret } from './secrets.ts'
23
+
24
+ /** What the database says before the boot touches it: the grants and settings recorded. */
25
+ export interface RecordedExtensions {
26
+ grants: Map<string, BundleGrant>
27
+ settings: Map<string, Record<string, unknown>>
28
+ }
29
+
30
+ /**
31
+ * Reads the recorded grants and settings, or nothing where there are none yet:
32
+ * a first boot, an in-memory database, or a release before 0.57.
33
+ */
34
+ export async function readRecordedExtensions(config: CromboloConfig): Promise<RecordedExtensions> {
35
+ const empty = { grants: new Map(), settings: new Map() }
36
+ let db: Awaited<ReturnType<typeof connect>> | undefined
37
+ try {
38
+ db = await connect({ dialect: config.dialect, file: config.sqliteFile })
39
+ const grants = new Map((await new BundleGrantRepository(db).all()).map((g) => [g.bundleId, g]))
40
+ const settings = await new ExtensionSettingRepository(db).all().catch(() => new Map())
41
+ return { grants, settings }
42
+ } catch {
43
+ return empty
44
+ } finally {
45
+ await db?.close().catch(() => {})
46
+ }
47
+ }
48
+
49
+ /** Whether a config entry grants all a version asks for. Pure. */
50
+ export function entryCovers(pkg: BundlePackage, entry: ExtensionEntry | undefined): boolean {
51
+ if (!entry?.grant) return false
52
+ const granted = new Set(entry.grant)
53
+ if (!declaredPermissions(pkg).every((permission) => granted.has(permission))) return false
54
+ const origins = new Set(entry.origins ?? [])
55
+ if (!declaredOrigins(pkg).every((origin) => origins.has(origin))) return false
56
+ return !declaredPermissions(pkg).includes('actAs') || Boolean(entry.actAs)
57
+ }
58
+
59
+ /** Its settings: the manifest's defaults, then what the back office set, then the config's. */
60
+ export function settingsOf(
61
+ pkg: BundlePackage,
62
+ stored: Record<string, unknown> | undefined,
63
+ entry: ExtensionEntry | undefined,
64
+ secretKey?: string,
65
+ ): Record<string, unknown> {
66
+ const declared = readSettings(pkg.field.settings)
67
+ const out: Record<string, unknown> = {}
68
+ if ('settings' in declared)
69
+ for (const [key, setting] of Object.entries(declared.settings) as [string, ExtensionSetting][])
70
+ if (setting.default !== undefined) out[key] = setting.default
71
+ // A secret is kept sealed, and opened only for the extension it is for.
72
+ const opened = Object.fromEntries(
73
+ Object.entries(stored ?? {}).flatMap(([key, value]) => {
74
+ const sealed = (value as { sealed?: unknown } | null)?.sealed
75
+ if (typeof sealed !== 'string') return [[key, value]]
76
+ if (!secretKey) return []
77
+ try {
78
+ return [[key, openSecret(sealed, secretKey)]]
79
+ } catch {
80
+ return []
81
+ }
82
+ }),
83
+ )
84
+ return { ...out, ...opened, ...(entry?.settings ?? {}) }
85
+ }
86
+
87
+ /** Why the config's `extensions` cannot be used: an entry for an extension the site has not got. */
88
+ export function extensionEntryProblems(
89
+ entries: Readonly<Record<string, ExtensionEntry>> | undefined,
90
+ packages: readonly BundlePackage[],
91
+ ): string[] {
92
+ const problems = Object.keys(entries ?? {})
93
+ .filter((id) => !packages.some((pkg) => pkg.id === id))
94
+ .map(
95
+ (id) =>
96
+ `The config's extensions names "${id}", which no extension the site depends on is: add it to package.json, or take it out.`,
97
+ )
98
+ if (Bun.env.NODE_ENV === 'production')
99
+ for (const [id, entry] of Object.entries(entries ?? {}))
100
+ if (entry.dev)
101
+ problems.push(
102
+ `The config's extensions gives "${id}" a dev entry, which widens what it may reach and is for a developer's machine only: take it out in production.`,
103
+ )
104
+ return problems
105
+ }
106
+
107
+ /** An extension that could not start, and why: shown where it is listed. */
108
+ export interface FailedExtension {
109
+ id: string
110
+ reason: string
111
+ }
112
+
113
+ /**
114
+ * The installed server halves to start, each in its own process with its
115
+ * settings: those the config grants and those a recorded grant covers. Ones the
116
+ * config still imports, the old way, are the site's own code and left to it.
117
+ */
118
+ export async function startExtensions(
119
+ config: CromboloConfig,
120
+ packages: readonly BundlePackage[],
121
+ recorded: RecordedExtensions,
122
+ log: (id: string) => BundleLog,
123
+ ): Promise<{
124
+ bundles: ServerBundle[]
125
+ processes: ExtensionProcess[]
126
+ failed: FailedExtension[]
127
+ }> {
128
+ const wired = new Set(config.bundles.map((bundle) => bundle.id))
129
+ const bundles: ServerBundle[] = []
130
+ const processes: ExtensionProcess[] = []
131
+ const failed: FailedExtension[] = []
132
+ for (const pkg of packages) {
133
+ if (!pkg.carries.server || wired.has(pkg.id)) continue
134
+ const entry = config.extensions?.[pkg.id]
135
+ const grant = recorded.grants.get(pkg.id)
136
+ const byConfig = entryCovers(pkg, entry)
137
+ const granted =
138
+ byConfig ||
139
+ Boolean(grant?.recorded && !grant.disabledAt && grantGaps(pkg, grant).length === 0)
140
+ // Nothing of an extension that is not granted is built, let alone run.
141
+ if (!granted) continue
142
+ const process = new ExtensionProcess({
143
+ pkg,
144
+ siteDir: config.siteDir,
145
+ home: join(config.siteDir, '.crombolo', 'extensions', pkg.id),
146
+ settings: settingsOf(pkg, recorded.settings.get(pkg.id), entry, config.secretKey),
147
+ dialect: config.dialect,
148
+ origins: [
149
+ ...((byConfig ? entry?.origins : grant?.origins) ?? []),
150
+ ...(entry?.dev?.allowNet ?? []),
151
+ ],
152
+ reads: entry?.dev?.allowRead,
153
+ timeoutMs: entry?.timeoutMs,
154
+ log: log(pkg.id),
155
+ })
156
+ try {
157
+ const description = await process.start()
158
+ const problems = isolationProblems(description)
159
+ if (description.id !== pkg.id)
160
+ problems.push(
161
+ `it calls itself "${description.id}", where its package.json says "${pkg.id}"`,
162
+ )
163
+ if (problems.length > 0) throw new Error(`It cannot run: ${problems.join('; ')}.`)
164
+ bundles.push(isolatedBundle(process))
165
+ processes.push(process)
166
+ } catch (error) {
167
+ await process.stop()
168
+ const reason = error instanceof Error ? error.message : String(error)
169
+ failed.push({ id: pkg.id, reason })
170
+ log(pkg.id).error(
171
+ '{package} could not be started, and the site starts without it: {reason}',
172
+ {
173
+ package: pkg.packageName,
174
+ reason,
175
+ },
176
+ )
177
+ }
178
+ }
179
+ return { bundles, processes, failed }
180
+ }