@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.
package/src/site-file.ts CHANGED
@@ -23,10 +23,12 @@ import {
23
23
  MANIFEST_FILE,
24
24
  mediaPath,
25
25
  newSeal,
26
+ packageIdentity,
26
27
  packageNameFor,
27
28
  planStreamedBundle,
28
29
  sanitise,
29
30
  sealBytes,
31
+ updateTrailer,
30
32
  writeManifest,
31
33
  } from '@crombolo/transfer'
32
34
  import { createComponentsPort, createFileSystemPort } from './adapters/file-system.ts'
@@ -34,9 +36,11 @@ import { createTemplateFileStore } from './adapters/template-files.ts'
34
36
  import { type CromboloConfig, VERSION } from './config.ts'
35
37
  import { mediaStoreFor } from './media-files.ts'
36
38
  import { type StoredFile, streamOf } from './media-store.ts'
39
+ import { signPathWithKey } from './provenance.ts'
37
40
  import { readSiteData } from './site-data.ts'
38
41
  import { publicSources } from './site-public.ts'
39
42
  import { siteSections } from './site-sections.ts'
43
+ import { siteSigningKey } from './site-trust.ts'
40
44
  import { TarballWriter } from './tar.ts'
41
45
 
42
46
  export interface SiteExportOptions {
@@ -245,6 +249,7 @@ export async function exportSite(
245
249
  seal,
246
250
  content: options.sealContent ? 'sealed' : 'open',
247
251
  public: publicFiles,
252
+ bundleType: 'site',
248
253
  },
249
254
  )
250
255
 
@@ -256,7 +261,13 @@ export async function exportSite(
256
261
  label: site.manifest.label,
257
262
  private: true,
258
263
  peerRange: `>=${VERSION}`,
264
+ bundleType: 'site',
259
265
  }
266
+ const pkg = bundlePackageJson(info, [
267
+ ...planned.files.map((file) => file.path),
268
+ ...planned.blobs.map(mediaPath),
269
+ ...publicFiles.map((file) => file.path),
270
+ ])
260
271
 
261
272
  const partial = `${options.out}.partial`
262
273
  const writer = TarballWriter.create(partial)
@@ -299,16 +310,19 @@ export async function exportSite(
299
310
  // Outside the bundle's hash: `public.json`, inside it, holds each file's own.
300
311
  for (const file of publicFiles)
301
312
  await writer.addStream(file.path, file.size, Bun.file(file.source).stream())
313
+ // The manifest and the package's identity close the hash, as `bundleIntegrity` has it.
314
+ updateTrailer(hasher, {
315
+ manifest: writeManifest({ ...planned.manifest, integrity: '' }),
316
+ packageIdentity: packageIdentity(pkg),
317
+ })
302
318
  const manifest = { ...planned.manifest, integrity: `sha256-${hasher.digest('hex')}` }
303
319
  await writer.add(MANIFEST_FILE, encoder.encode(writeManifest(manifest)))
304
- await writer.add(
305
- 'package.json',
306
- encoder.encode(
307
- `${JSON.stringify(bundlePackageJson(info, [...paths, ...publicFiles.map((file) => file.path)]), null, 2)}\n`,
308
- ),
309
- )
320
+ await writer.add('package.json', encoder.encode(`${JSON.stringify(pkg, null, 2)}\n`))
310
321
  await writer.close()
311
322
  await rename(partial, options.out)
323
+ // Signed with this site's key, so a site that trusts it knows it came from here (story 316).
324
+ const key = await siteSigningKey(db, config)
325
+ if (key) await signPathWithKey(options.out, key)
312
326
  } catch (error) {
313
327
  await writer.abort()
314
328
  await rm(partial, { force: true })
@@ -14,7 +14,7 @@ import { isSitePath } from './middleware.ts'
14
14
  /** Where a CLI finds out what a server is: never a site's to answer. */
15
15
  export const REMOTE_DISCOVERY_PATH = '/.well-known/crombolo-remote'
16
16
 
17
- /** Above this, `bundle build` says what is making the bundle heavy. */
17
+ /** Above this, `site build` says what is making the bundle heavy. */
18
18
  export const PUBLIC_WARNING_BYTES = 100 * 1024 ** 2
19
19
 
20
20
  const IMMUTABLE = 'public, max-age=31536000, immutable'
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * The sections a bundle carries beyond its content — schema, components,
3
3
  * styles, scripts and the dictionary — gathered from a site. One place, so the
4
- * backoffice's Packages builder (picked items) and `crombolo export --site`
4
+ * backoffice's Packages builder (picked items) and `crombolo site export`
5
5
  * (everything) compose a bundle the same way. `docs/bundles.md`.
6
6
  */
7
7
  import { readdir, readFile } from 'node:fs/promises'
@@ -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>
package/src/webhooks.ts CHANGED
@@ -213,6 +213,11 @@ export interface WebhookServiceOptions {
213
213
  /** Publishes the schema directory to a shared store, when there is one. */
214
214
  onFilesChanged?: () => Promise<void>
215
215
  now?: () => Date
216
+ /**
217
+ * The origins a bundle's event `fetch` may reach (story 308); undefined for a
218
+ * bundle written before schema 4, which the address rule alone holds.
219
+ */
220
+ bundleOrigins?(bundleId: string): readonly string[] | undefined
216
221
  /** Whether a bundle is turned on (story 222); its events are not delivered while it is off. */
217
222
  isBundleOn?(bundleId: string): boolean
218
223
  /** The site's own handlers (story 298): which events it handles, and how one is handed over. */
@@ -634,7 +639,17 @@ export function createWebhookService(options: WebhookServiceOptions): WebhookSer
634
639
  payload: delivery.payload as { Id: string },
635
640
  deliveryId: delivery.id,
636
641
  attempt: delivery.attempts,
637
- fetch: (input, init) => pinnedFetch(input, { signal, ...init }, outbound),
642
+ fetch: (input, init) => {
643
+ const origins = options.bundleOrigins?.(bundleId)
644
+ const url = new URL(input instanceof Request ? input.url : String(input))
645
+ if (origins && !origins.includes(url.origin))
646
+ return Promise.reject(
647
+ new OutboundRefused(
648
+ `${bundleId} may not reach ${url.origin}: its http.outbound names ${origins.join(', ') || 'nothing'}.`,
649
+ ),
650
+ )
651
+ return pinnedFetch(input, { signal, ...init }, outbound)
652
+ },
638
653
  log: {
639
654
  info: (message, properties) => named.info(message, properties),
640
655
  warn: (message, properties) => named.warn(message, properties),