@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,238 @@
1
+ /**
2
+ * Which site bundles a site applies (story 316): those signed by a key or a CI
3
+ * source it trusts, this site's own key always among them, and never an older
4
+ * version than it last applied from the same signer. Required in production,
5
+ * flagged in development. docs/bundles.md, "Signing a bundle".
6
+ */
7
+ import {
8
+ type Db,
9
+ readKeyValue,
10
+ TransferRunRepository,
11
+ type TrustedSigner,
12
+ TrustedSignerRepository,
13
+ writeKeyValue,
14
+ } from '@crombolo/data'
15
+ import type { CromboloConfig } from './config.ts'
16
+ import {
17
+ keySignatureOver,
18
+ PROVENANCE_FILE,
19
+ type ProvenanceResult,
20
+ refName,
21
+ sourceAllowed,
22
+ } from './provenance.ts'
23
+ import { openSecret, sealSecret } from './secrets.ts'
24
+ import { createKeyPair, type KeyPair, readPublicKey } from './signing-keys.ts'
25
+
26
+ const SITE_KEY = 'Crombolo.Signing.SiteKey'
27
+
28
+ /**
29
+ * This site's own key, made the first time it is needed, its private half
30
+ * sealed with the site's secret key; undefined where there is no secret key to
31
+ * seal it with.
32
+ */
33
+ export async function siteSigningKey(
34
+ db: Db,
35
+ config: Pick<CromboloConfig, 'secretKey' | 'siteName'>,
36
+ ): Promise<KeyPair | undefined> {
37
+ if (!config.secretKey) return undefined
38
+ const stored = await readKeyValue(db, SITE_KEY).catch(() => undefined)
39
+ if (stored) {
40
+ const { publicKey, sealed } = JSON.parse(stored) as { publicKey: string; sealed: string }
41
+ const read = readPublicKey(publicKey)
42
+ if ('problem' in read) throw new Error(`This site's signing key is damaged: ${read.problem}`)
43
+ return { publicKey: read, privateKey: openSecret(sealed, config.secretKey) }
44
+ }
45
+ const pair = createKeyPair(config.siteName || 'site')
46
+ await writeKeyValue(
47
+ db,
48
+ SITE_KEY,
49
+ JSON.stringify({
50
+ publicKey: pair.publicKey.line,
51
+ sealed: sealSecret(pair.privateKey, config.secretKey),
52
+ }),
53
+ )
54
+ return pair
55
+ }
56
+
57
+ /** One signer this site trusts, wherever it is listed. */
58
+ export interface TrustEntry {
59
+ /** The stored row's id; absent for one the config or this site provides. */
60
+ id?: string
61
+ kind: 'user' | 'site' | 'source'
62
+ name: string
63
+ publicKey?: string
64
+ fingerprint?: string
65
+ source?: string
66
+ /** Set in the config or the environment, or this site's own: not removed in Settings. */
67
+ locked: boolean
68
+ /** This site's own key. */
69
+ own?: boolean
70
+ addedBy?: string | null
71
+ addedAt?: string
72
+ lastSignedAt?: string | null
73
+ }
74
+
75
+ const fromRow = (row: TrustedSigner): TrustEntry => ({
76
+ id: row.id,
77
+ kind: row.kind,
78
+ name: row.name,
79
+ ...(row.publicKey ? { publicKey: row.publicKey } : {}),
80
+ ...(row.fingerprint ? { fingerprint: row.fingerprint } : {}),
81
+ ...(row.source ? { source: row.source } : {}),
82
+ locked: false,
83
+ addedBy: row.addedBy,
84
+ addedAt: row.addedAt.toISOString(),
85
+ lastSignedAt: row.lastSignedAt?.toISOString() ?? null,
86
+ })
87
+
88
+ /** Everything this site trusts: its own key first, then the config's, then what was added here. */
89
+ export async function trustedSigners(db: Db, config: CromboloConfig): Promise<TrustEntry[]> {
90
+ const own = await siteSigningKey(db, config).catch(() => undefined)
91
+ const entries: TrustEntry[] = []
92
+ if (own)
93
+ entries.push({
94
+ kind: 'site',
95
+ name: `${config.siteName || 'This site'} (this site)`,
96
+ publicKey: own.publicKey.line,
97
+ fingerprint: own.publicKey.fingerprint,
98
+ locked: true,
99
+ own: true,
100
+ })
101
+ for (const key of config.trustedKeys ?? []) {
102
+ const read = readPublicKey(key.publicKey)
103
+ if ('problem' in read) continue
104
+ entries.push({
105
+ kind: key.kind ?? 'user',
106
+ name: key.name,
107
+ publicKey: read.line,
108
+ fingerprint: read.fingerprint,
109
+ locked: true,
110
+ })
111
+ }
112
+ for (const source of [
113
+ ...(config.trustedSources ?? []),
114
+ ...config.bundlePolicy.sources.map((entry) => ({ name: entry, source: entry })),
115
+ ])
116
+ entries.push({ kind: 'source', name: source.name, source: source.source, locked: true })
117
+ const rows = await new TrustedSignerRepository(db).all().catch(() => [])
118
+ entries.push(...rows.map(fromRow))
119
+ return entries
120
+ }
121
+
122
+ /** What a site bundle's check decided: refused, or applied, flagged or not, and who signed it. */
123
+ export interface SiteBundleTrust {
124
+ problem?: string
125
+ /** Applied, but a person should know: unsigned or untrusted, in development. */
126
+ warning?: string
127
+ /** Who signed it, as the run records it: a key's fingerprint or a CI source's repository. */
128
+ signedBy?: string
129
+ /** The stored entry that trusted it, to note it signed something. */
130
+ entryId?: string
131
+ /** An older version applied on purpose, with `allowDowngrade`: for the audit log. */
132
+ downgraded?: { from: string; to: string }
133
+ }
134
+
135
+ /**
136
+ * Whether a site bundle may be applied here. A signature that does not check
137
+ * out is refused always; in production, so is one nobody this site trusts
138
+ * signed, and an older version from the same signer without `allowDowngrade`.
139
+ */
140
+ export async function siteBundleTrust(
141
+ db: Db,
142
+ config: CromboloConfig,
143
+ result: ProvenanceResult,
144
+ options: { allowDowngrade?: boolean } = {},
145
+ ): Promise<SiteBundleTrust> {
146
+ if (result.state === 'local') return {}
147
+ if (result.state === 'invalid')
148
+ return {
149
+ problem: `its signature was not accepted: ${result.reason ?? 'it does not check out'}`,
150
+ }
151
+ if (result.state === 'unchecked')
152
+ return {
153
+ problem: `its signature could not be checked right now (${result.reason ?? 'try again'}); try again`,
154
+ }
155
+ // Required in production, and wherever the site asks for signatures (story 060).
156
+ const production = !config.development || config.bundlePolicy.signatures === 'required'
157
+ const refuse = (problem: string): SiteBundleTrust =>
158
+ production ? { problem } : { warning: `${problem}. It is applied, as this is not production` }
159
+ if (result.state === 'unsigned')
160
+ return refuse(
161
+ 'it is not signed, and this site applies only site bundles signed by a key or a build it trusts (Settings → Trusted signers)',
162
+ )
163
+ const entries = await trustedSigners(db, config)
164
+ const byKey = result.key
165
+ ? entries.find((entry) => entry.fingerprint === result.key?.fingerprint)
166
+ : undefined
167
+ const bySource = result.source
168
+ ? entries.find(
169
+ (entry) =>
170
+ entry.kind === 'source' &&
171
+ entry.source &&
172
+ sourceAllowed(result.source as NonNullable<ProvenanceResult['source']>, entry.source),
173
+ )
174
+ : undefined
175
+ const trusted = byKey ?? bySource
176
+ const signedBy = byKey
177
+ ? (result.key?.fingerprint as string)
178
+ : bySource
179
+ ? (result.source?.repository as string)
180
+ : (result.key?.fingerprint ?? result.source?.repository)
181
+ if (!trusted) {
182
+ const who = result.key
183
+ ? `the key ${result.key.comment || ''} (${result.key.fingerprint})`.replace(' ', ' ')
184
+ : `a build of github.com/${result.source?.repository} at ${refName(result.source?.ref ?? '')}`
185
+ return {
186
+ ...refuse(`it is signed by ${who}, which this site does not trust`),
187
+ ...(signedBy ? { signedBy } : {}),
188
+ }
189
+ }
190
+ // An older version from the same signer is an old bundle put back.
191
+ const pkg = result.package
192
+ let downgraded: SiteBundleTrust['downgraded']
193
+ if (pkg && signedBy) {
194
+ const applied = await new TransferRunRepository(db)
195
+ .versionsSignedBy(signedBy, pkg.name)
196
+ .catch(() => [] as string[])
197
+ const newer = applied
198
+ .filter((version) => Bun.semver.order(version, pkg.version) > 0)
199
+ .sort(Bun.semver.order)
200
+ .at(-1)
201
+ if (newer && !options.allowDowngrade)
202
+ return {
203
+ problem: `it is version ${pkg.version}, older than ${newer}, which this site already applied from the same signer. To roll back on purpose, apply it with --allow-downgrade`,
204
+ signedBy,
205
+ }
206
+ if (newer) downgraded = { from: newer, to: pkg.version }
207
+ }
208
+ return {
209
+ signedBy,
210
+ ...(trusted.id ? { entryId: trusted.id } : {}),
211
+ ...(downgraded ? { downgraded } : {}),
212
+ }
213
+ }
214
+
215
+ /**
216
+ * A package's files with this site's key signature added as `provenance.json`
217
+ * (story 316); as they were where the site has no key.
218
+ */
219
+ export async function signedWithSiteKey(
220
+ db: Db,
221
+ config: Pick<CromboloConfig, 'secretKey' | 'siteName'>,
222
+ files: readonly { path: string; bytes?: Uint8Array; text?: string }[],
223
+ ): Promise<{ path: string; bytes?: Uint8Array; text?: string }[]> {
224
+ const key = await siteSigningKey(db, config)
225
+ if (!key) return [...files]
226
+ const encoder = new TextEncoder()
227
+ const signed = keySignatureOver(
228
+ files.map((file) => ({
229
+ path: file.path,
230
+ bytes: file.bytes ?? encoder.encode(file.text ?? ''),
231
+ })),
232
+ key,
233
+ )
234
+ return [
235
+ ...files.filter((file) => file.path !== PROVENANCE_FILE),
236
+ { path: PROVENANCE_FILE, text: `${JSON.stringify(signed, null, 2)}\n` },
237
+ ]
238
+ }
@@ -27,6 +27,11 @@ import type { CromboloConfig } from './config.ts'
27
27
  export interface PendingTransferView {
28
28
  bundleId: string
29
29
  label: string | null
30
+ /**
31
+ * A site package, applied from a file or a directory, rather than an
32
+ * extension's content, installed with it (story 306).
33
+ */
34
+ sitePackage: boolean
30
35
  checkedAt: string
31
36
  publish: boolean
32
37
  allowMissingBlobs: boolean
@@ -41,6 +46,7 @@ export async function pendingTransfers(db: Db): Promise<PendingTransferView[]> {
41
46
  out.push({
42
47
  bundleId: pending.bundleId,
43
48
  label: pending.label,
49
+ sitePackage: pending.targetKind === 'directory',
44
50
  checkedAt: pending.checkedAt.toISOString(),
45
51
  publish: pending.publish,
46
52
  allowMissingBlobs: pending.allowMissingBlobs,
@@ -0,0 +1,132 @@
1
+ /**
2
+ * Trusted signers, as an administrator manages them (story 316): the keys and
3
+ * CI sources this site trusts to sign the site bundles it applies, added,
4
+ * renamed and removed, each change audited. What the config lists, and this
5
+ * site's own key, are shown and never removed here. Settings, the CLI and the
6
+ * back-office endpoint share it.
7
+ */
8
+ import { type Db, TrustedSignerRepository } from '@crombolo/data'
9
+ import { recordAudit } from './adapters/audit.ts'
10
+ import type { CromboloConfig } from './config.ts'
11
+ import { readPublicKey } from './signing-keys.ts'
12
+ import { type TrustEntry, trustedSigners } from './site-trust.ts'
13
+
14
+ /** Who changed the list, for the audit log. */
15
+ export interface SignerActor {
16
+ id: string | null
17
+ name: string
18
+ email: string | null
19
+ source: 'request' | 'cli'
20
+ ipAddress?: string | null
21
+ }
22
+
23
+ export type SignerOutcome =
24
+ | { ok: true; entry?: TrustEntry }
25
+ | { ok: false; status: number; message: string }
26
+
27
+ /** `org/repo`, `org/*`, or either `@` a ref pattern such as `v*`. */
28
+ const SOURCE = /^[A-Za-z0-9_.-]+\/(\*|[A-Za-z0-9_.-]+)(@[A-Za-z0-9_.*/-]+)?$/
29
+
30
+ export function createTrustedSignersAdmin(db: Db, config: CromboloConfig) {
31
+ const repo = new TrustedSignerRepository(db)
32
+ const audit = (actor: SignerActor, action: string, name: string, detail: string | null) =>
33
+ recordAudit(db, {
34
+ category: 'system',
35
+ action,
36
+ entityType: 'Trusted signer',
37
+ entityName: name,
38
+ detail,
39
+ source: actor.source,
40
+ userKey: actor.id,
41
+ userName: actor.name,
42
+ ipAddress: actor.ipAddress ?? null,
43
+ forwardedFor: null,
44
+ })
45
+ const stored = async (id: string) => (await repo.all()).find((row) => row.id === id)
46
+
47
+ return {
48
+ list: () => trustedSigners(db, config),
49
+
50
+ async add(
51
+ actor: SignerActor,
52
+ input: { name?: unknown; kind?: unknown; publicKey?: unknown; source?: unknown },
53
+ ): Promise<SignerOutcome> {
54
+ const name = typeof input.name === 'string' ? input.name.trim() : ''
55
+ if (!name) return { ok: false, status: 400, message: 'Give it a name you will recognise.' }
56
+ if (name.length > 255) return { ok: false, status: 400, message: 'That name is too long.' }
57
+ const listed = await trustedSigners(db, config)
58
+ if (input.kind === 'source') {
59
+ const source = typeof input.source === 'string' ? input.source.trim() : ''
60
+ if (!SOURCE.test(source))
61
+ return {
62
+ ok: false,
63
+ status: 400,
64
+ message:
65
+ 'A build is named as owner/repository, owner/*, or either @ a tag pattern such as v*.',
66
+ }
67
+ if (listed.some((entry) => entry.source === source))
68
+ return { ok: false, status: 409, message: 'That build is already trusted.' }
69
+ const row = await repo.add({
70
+ kind: 'source',
71
+ name,
72
+ publicKey: null,
73
+ fingerprint: null,
74
+ source,
75
+ addedBy: actor.email ?? actor.name,
76
+ })
77
+ await audit(actor, 'Trust', name, `builds of ${source}`)
78
+ return { ok: true, entry: (await trustedSigners(db, config)).find((e) => e.id === row.id) }
79
+ }
80
+ const kind = input.kind === 'site' ? 'site' : 'user'
81
+ const key = readPublicKey(typeof input.publicKey === 'string' ? input.publicKey : '')
82
+ if ('problem' in key) return { ok: false, status: 400, message: key.problem }
83
+ if (listed.some((entry) => entry.fingerprint === key.fingerprint))
84
+ return { ok: false, status: 409, message: 'That key is already trusted.' }
85
+ const row = await repo.add({
86
+ kind,
87
+ name,
88
+ publicKey: key.line,
89
+ fingerprint: key.fingerprint,
90
+ source: null,
91
+ addedBy: actor.email ?? actor.name,
92
+ })
93
+ await audit(actor, 'Trust', name, `${kind} key ${key.fingerprint}`)
94
+ return { ok: true, entry: (await trustedSigners(db, config)).find((e) => e.id === row.id) }
95
+ },
96
+
97
+ async rename(actor: SignerActor, id: string, name: unknown): Promise<SignerOutcome> {
98
+ const given = typeof name === 'string' ? name.trim() : ''
99
+ if (!given) return { ok: false, status: 400, message: 'Give it a name you will recognise.' }
100
+ const found = await stored(id)
101
+ if (!found)
102
+ return {
103
+ ok: false,
104
+ status: 404,
105
+ message: 'That one is not on the list, or is set in the site’s configuration.',
106
+ }
107
+ await repo.rename(id, given)
108
+ await audit(actor, 'Rename', given, `was ${found.name}`)
109
+ return { ok: true }
110
+ },
111
+
112
+ async remove(actor: SignerActor, id: string): Promise<SignerOutcome> {
113
+ const found = await stored(id)
114
+ if (!found)
115
+ return {
116
+ ok: false,
117
+ status: 404,
118
+ message: 'That one is not on the list, or is set in the site’s configuration.',
119
+ }
120
+ await repo.remove(id)
121
+ await audit(
122
+ actor,
123
+ 'Untrust',
124
+ found.name,
125
+ found.fingerprint ? `${found.kind} key ${found.fingerprint}` : `builds of ${found.source}`,
126
+ )
127
+ return { ok: true }
128
+ },
129
+ }
130
+ }
131
+
132
+ export type TrustedSignersAdmin = ReturnType<typeof createTrustedSignersAdmin>