@crombolo/server 0.56.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.
@@ -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
+ }