@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,182 @@
1
+ /**
2
+ * Where a request a user set up may go (story 301): never this server's own
3
+ * network unless the site allows it, connected to the very address that was
4
+ * checked, so DNS cannot swap it between the check and the connection. And
5
+ * which server variables a header may name. Webhooks use it now; story 304
6
+ * brings the forms workflow and the identity provider test. docs/webhooks.md,
7
+ * "What a webhook may reach".
8
+ */
9
+
10
+ /** A request refused before anything was sent; trying again would be refused the same way. */
11
+ export class OutboundRefused extends Error {
12
+ override readonly name = 'OutboundRefused'
13
+ }
14
+
15
+ export interface OutboundOptions {
16
+ /** Loopback, private and link-local addresses too: for development and an intranet. */
17
+ allowPrivateAddresses?: boolean
18
+ /** A hostname's addresses; `Bun.dns.lookup` unless a test says otherwise. */
19
+ lookup?: (hostname: string) => Promise<string[]>
20
+ fetch?: typeof fetch
21
+ }
22
+
23
+ const IPV4 = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/
24
+
25
+ function ipv4Bytes(address: string): number[] | undefined {
26
+ const match = IPV4.exec(address)
27
+ if (!match) return undefined
28
+ const bytes = match.slice(1).map(Number)
29
+ return bytes.every((b) => b <= 255) ? bytes : undefined
30
+ }
31
+
32
+ function ipv6Bytes(address: string): number[] | undefined {
33
+ if (!address.includes(':')) return undefined
34
+ let text = address.replace(/%.*$/, '')
35
+ const tail: number[] = []
36
+ const lastColon = text.lastIndexOf(':')
37
+ const embedded = ipv4Bytes(text.slice(lastColon + 1))
38
+ if (embedded) {
39
+ tail.push(...embedded)
40
+ text = `${text.slice(0, lastColon + 1)}0:0`
41
+ }
42
+ const halves = text.split('::')
43
+ if (halves.length > 2) return undefined
44
+ const groups = (part: string) => (part === '' ? [] : part.split(':'))
45
+ const head = groups(halves[0] ?? '')
46
+ const rest = halves.length === 2 ? groups(halves[1] ?? '') : []
47
+ const missing = 8 - head.length - rest.length
48
+ if (halves.length === 1 ? missing !== 0 : missing < 0) return undefined
49
+ const all = [...head, ...Array<string>(halves.length === 2 ? missing : 0).fill('0'), ...rest]
50
+ const bytes: number[] = []
51
+ for (const group of all) {
52
+ if (!/^[0-9a-f]{1,4}$/i.test(group)) return undefined
53
+ const value = Number.parseInt(group, 16)
54
+ bytes.push(value >> 8, value & 0xff)
55
+ }
56
+ if (tail.length > 0) bytes.splice(12, 4, ...tail)
57
+ return bytes
58
+ }
59
+
60
+ /** Whether `bytes` starts with the first `bits` of `prefix`. */
61
+ function within(bytes: readonly number[], prefix: readonly number[], bits: number): boolean {
62
+ for (let i = 0; i < bits; i++) {
63
+ const mask = 0x80 >> (i % 8)
64
+ if (((bytes[i >> 3] ?? 0) & mask) !== ((prefix[i >> 3] ?? 0) & mask)) return false
65
+ }
66
+ return true
67
+ }
68
+
69
+ const V4_REFUSED: Array<[number[], number, string]> = [
70
+ [[0, 0, 0, 0], 8, 'an unspecified address'],
71
+ [[10, 0, 0, 0], 8, 'a private address'],
72
+ [[100, 64, 0, 0], 10, 'a carrier-grade NAT address'],
73
+ [[127, 0, 0, 0], 8, 'a loopback address'],
74
+ [[169, 254, 0, 0], 16, 'a link-local address'],
75
+ [[172, 16, 0, 0], 12, 'a private address'],
76
+ [[192, 168, 0, 0], 16, 'a private address'],
77
+ [[224, 0, 0, 0], 4, 'a multicast address'],
78
+ [[240, 0, 0, 0], 4, 'a reserved or broadcast address'],
79
+ ]
80
+
81
+ const V6_REFUSED: Array<[number[], number, string]> = [
82
+ [[0xfc], 7, 'a private address'],
83
+ [[0xfe, 0x80], 10, 'a link-local address'],
84
+ [[0xff], 8, 'a multicast address'],
85
+ ]
86
+
87
+ /** Why an IP address is not one a request may go to, or undefined when it may. Pure. */
88
+ export function refusedAddress(address: string): string | undefined {
89
+ const v4 = ipv4Bytes(address)
90
+ if (v4) return V4_REFUSED.find(([prefix, bits]) => within(v4, prefix, bits))?.[2]
91
+ const v6 = ipv6Bytes(address)
92
+ if (!v6) return 'not an address'
93
+ if (v6.every((b) => b === 0)) return 'an unspecified address'
94
+ if (v6.slice(0, 15).every((b) => b === 0) && v6[15] === 1) return 'a loopback address'
95
+ // ::ffff:a.b.c.d, and the older ::a.b.c.d: an IPv4 address carried in IPv6.
96
+ const carried = (v6[10] === 0xff && v6[11] === 0xff) || (v6[10] === 0 && v6[11] === 0)
97
+ if (v6.slice(0, 10).every((b) => b === 0) && carried) return 'an IPv4 address mapped into IPv6'
98
+ return V6_REFUSED.find(([prefix, bits]) => within(v6, prefix, bits))?.[2]
99
+ }
100
+
101
+ const isIp = (host: string) => Boolean(ipv4Bytes(host) || ipv6Bytes(host))
102
+
103
+ const defaultLookup = async (hostname: string) =>
104
+ (await Bun.dns.lookup(hostname)).map((entry) => entry.address)
105
+
106
+ /**
107
+ * The address a request to `url` connects to, once every address its host has
108
+ * is allowed; refused with the reason otherwise. Undefined when private
109
+ * addresses are allowed, so the request goes as it is.
110
+ */
111
+ export async function checkedAddress(
112
+ url: URL,
113
+ options: OutboundOptions = {},
114
+ ): Promise<string | undefined> {
115
+ if (url.protocol !== 'https:' && url.protocol !== 'http:')
116
+ throw new OutboundRefused(`${url.protocol} is not a web address; use http:// or https://.`)
117
+ if (options.allowPrivateAddresses) return undefined
118
+ const host = url.hostname.replace(/^\[|\]$/g, '')
119
+ const addresses = isIp(host) ? [host] : await (options.lookup ?? defaultLookup)(host)
120
+ if (addresses.length === 0) throw new OutboundRefused(`${host} has no address.`)
121
+ for (const address of addresses) {
122
+ const reason = refusedAddress(address)
123
+ if (reason)
124
+ throw new OutboundRefused(
125
+ `${host === address ? host : `${host} (${address})`} is ${reason}, which this site does not send to. The config's webhooks.allowPrivateAddresses allows it.`,
126
+ )
127
+ }
128
+ return addresses[0]
129
+ }
130
+
131
+ /**
132
+ * `fetch`, to the address that was checked: the hostname stays in the `Host`
133
+ * header and in TLS, so the certificate is still verified against it.
134
+ * Redirects are never followed; a 3xx is the receiver's answer.
135
+ */
136
+ export async function pinnedFetch(
137
+ input: string | URL | Request,
138
+ init: RequestInit = {},
139
+ options: OutboundOptions = {},
140
+ ): Promise<Response> {
141
+ const request = new Request(input, init)
142
+ const url = new URL(request.url)
143
+ const send = options.fetch ?? fetch
144
+ const address = await checkedAddress(url, options)
145
+ const base = {
146
+ method: request.method,
147
+ headers: new Headers(request.headers),
148
+ body: request.body,
149
+ signal: request.signal,
150
+ redirect: 'manual' as const,
151
+ }
152
+ if (!address) return send(url, base)
153
+ const target = new URL(url)
154
+ const host = url.hostname.replace(/^\[|\]$/g, '')
155
+ target.hostname = address.includes(':') ? `[${address}]` : address
156
+ base.headers.set('host', url.host)
157
+ return send(target, {
158
+ ...base,
159
+ ...(url.protocol === 'https:' && !isIp(host) ? { tls: { serverName: host } } : {}),
160
+ } as RequestInit)
161
+ }
162
+
163
+ /** The variables a header may name, besides those the config lists. */
164
+ export const HEADER_VARIABLE_PREFIX = 'CROMBOLO_WEBHOOK_'
165
+
166
+ /** Settings made to be sent: the Next.js front end's shared secret (docs/delivery-api.md). */
167
+ const MADE_TO_SEND = new Set(['CROMBOLO_REVALIDATE_SECRET'])
168
+
169
+ /**
170
+ * Why a header may not send the server variable `variable`, or undefined when
171
+ * it may: one the config lists, one starting `CROMBOLO_WEBHOOK_`, or a setting
172
+ * made to be sent. Never any other `CROMBOLO_` setting, listed or not. Pure.
173
+ */
174
+ export function headerVariableProblem(
175
+ header: string,
176
+ variable: string,
177
+ allowed: readonly string[] = [],
178
+ ): string | undefined {
179
+ if (variable.startsWith(HEADER_VARIABLE_PREFIX) || MADE_TO_SEND.has(variable)) return undefined
180
+ if (allowed.includes(variable) && !variable.startsWith('CROMBOLO_')) return undefined
181
+ return `The header "${header}" names ${variable}, which a webhook may not send. List it in the config's webhooks.headerVariables, or name a variable starting ${HEADER_VARIABLE_PREFIX}.`
182
+ }
package/src/owner-jobs.ts CHANGED
@@ -5,6 +5,7 @@
5
5
  * its owner's public route sees, and nothing acts as the site.
6
6
  * docs/rendering.md, "Background jobs"; docs/bundles.md, "Jobs".
7
7
  */
8
+
8
9
  import {
9
10
  type Db,
10
11
  type JobProgress,
@@ -14,6 +15,7 @@ import {
14
15
  } from '@crombolo/data'
15
16
  import { type Cron, isTimezone, nextOccurrence, parseCron } from './cron.ts'
16
17
  import { logger } from './logging.ts'
18
+ import { withSiteWrites } from './site-content.ts'
17
19
  import { inSpan, recordJob } from './telemetry.ts'
18
20
 
19
21
  /**
@@ -283,7 +285,11 @@ export function createJobRunner(options: {
283
285
  `job ${job.owner}/${job.name}`,
284
286
  { ...attributes, 'crombolo.job.attempt': job.attempts },
285
287
  async () => {
286
- await handler(job.payload, { ...owner.context(), job: info })
288
+ const run = () => handler(job.payload, { ...owner.context(), job: info })
289
+ // The site's jobs may change content (story 298), named for the audit.
290
+ await (owner.id === 'site'
291
+ ? withSiteWrites({ via: `job ${job.name}`, source: 'job' }, run)
292
+ : run())
287
293
  },
288
294
  )
289
295
  await jobs.succeed(job.id)
package/src/ports.ts CHANGED
@@ -357,6 +357,10 @@ export function resolveUserLinkSender(
357
357
  export interface DepsOptions {
358
358
  /** Published pages a site route answers in place of, for the health check (story 211). */
359
359
  hiddenByRoutes?: () => Promise<Array<{ route: string; owner: string; page: string; url: string }>>
360
+ /** Granted extensions that could not start, and why (story 311). */
361
+ failedExtensions?: () => readonly { id: string; reason: string }[]
362
+ /** Extensions whose `layout` setting names a layout the site no longer has (story 312). */
363
+ lostLayouts?: () => readonly { id: string; layout: string }[]
360
364
  siteSettingsFindings?: () => Promise<
361
365
  Array<{ kind: 'second' | 'deep'; name: string; counted?: string }>
362
366
  >
@@ -486,6 +490,9 @@ export function createDeps(options: DepsOptions): ManagementApiDeps {
486
490
  fetch: options.fetch,
487
491
  hiddenByRoutes: options.hiddenByRoutes,
488
492
  siteSettingsFindings: options.siteSettingsFindings,
493
+ bundleProblems: () => options.extensions.bundles().problems,
494
+ failedExtensions: options.failedExtensions,
495
+ lostLayouts: options.lostLayouts,
489
496
  })
490
497
  const tags = new TagRepository(options.db)
491
498
  deps.tags = { list: (filter) => tags.all(filter) }
@@ -615,6 +622,7 @@ export function createDeps(options: DepsOptions): ManagementApiDeps {
615
622
  siteName: options.config.siteName,
616
623
  nodeId: options.config.nodeId,
617
624
  marketplaceUrl: options.config.marketplaceUrl,
625
+ secretKey: options.config.secretKey,
618
626
  componentFiles: createTemplateFileStore(options.config.componentsDir, options.onViewsChange),
619
627
  mediaStore: mediaFiles.store,
620
628
  components: deps.components,
package/src/provenance.ts CHANGED
@@ -13,6 +13,14 @@ import { bundleFromJSON, type SerializedBundle } from '@sigstore/bundle'
13
13
  import { X509Certificate } from '@sigstore/core'
14
14
  import { TrustedRoot } from '@sigstore/protobuf-specs'
15
15
  import { toSignedEntity, toTrustMaterial, Verifier } from '@sigstore/verify'
16
+ import {
17
+ type KeyPair,
18
+ type PublicKey,
19
+ readPublicKey,
20
+ signedStatement,
21
+ signWith,
22
+ verifiedBy,
23
+ } from './signing-keys.ts'
16
24
 
17
25
  /** The file in a package that holds its signature, and the one file the digest leaves out. */
18
26
  export const PROVENANCE_FILE = 'provenance.json'
@@ -67,13 +75,22 @@ export interface ProvenanceLinks {
67
75
  log: string | null
68
76
  }
69
77
 
70
- /** `provenance.json`. */
78
+ /** A key's signature (story 316): its public line, over the digest, name and version. */
79
+ export interface KeySignatureFile {
80
+ publicKey: string
81
+ signature: string
82
+ name: string
83
+ version: string
84
+ }
85
+
86
+ /** `provenance.json`: a Sigstore signature from CI, a key's, or both. */
71
87
  export interface ProvenanceFile {
72
88
  format: 1
73
89
  digest: string
74
- signature: SerializedBundle
75
- source: ProvenanceSource
76
- links: ProvenanceLinks
90
+ signature?: SerializedBundle
91
+ source?: ProvenanceSource
92
+ links?: ProvenanceLinks
93
+ key?: KeySignatureFile
77
94
  }
78
95
 
79
96
  /**
@@ -85,12 +102,26 @@ export type ProvenanceState = 'signed' | 'unsigned' | 'invalid' | 'unchecked' |
85
102
  export interface ProvenanceResult {
86
103
  state: ProvenanceState
87
104
  digest?: string
105
+ /** The CI build that signed it, by Sigstore. */
88
106
  source?: ProvenanceSource
89
107
  links?: ProvenanceLinks
108
+ /** The key that signed it (story 316). */
109
+ key?: PublicKey
110
+ /** The package it is, from its own signed `package.json`, for the downgrade check. */
111
+ package?: { name: string; version: string }
90
112
  /** Why a signature was not accepted, in words a person can act on. */
91
113
  reason?: string
92
114
  }
93
115
 
116
+ /** A package's `provenance.json`, when it has one that reads. */
117
+ function readProvenance(dir: string): ProvenanceFile | undefined {
118
+ try {
119
+ return JSON.parse(readFileSync(join(dir, PROVENANCE_FILE), 'utf8')) as ProvenanceFile
120
+ } catch {
121
+ return undefined
122
+ }
123
+ }
124
+
94
125
  /** Every file a package's digest covers: all of it but its signature, installs and history. */
95
126
  function packageFiles(dir: string): string[] {
96
127
  const out: string[] = []
@@ -113,16 +144,73 @@ function packageFiles(dir: string): string[] {
113
144
  * integrity does not: `package.json` and an extension bundle's code.
114
145
  */
115
146
  export function packageDigest(dir: string): string {
147
+ return digestOfFiles(
148
+ packageFiles(dir).map((path) => ({ path, bytes: readFileSync(join(dir, path)) })),
149
+ )
150
+ }
151
+
152
+ /** The same digest, of files held in memory: a package not yet written out. */
153
+ export function digestOfFiles(files: readonly { path: string; bytes: Uint8Array }[]): string {
116
154
  const hasher = new Bun.CryptoHasher('sha256')
117
- for (const path of packageFiles(dir)) {
118
- hasher.update(path)
155
+ for (const file of files
156
+ .filter((entry) => entry.path !== PROVENANCE_FILE)
157
+ .sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0))) {
158
+ hasher.update(file.path)
119
159
  hasher.update('\0')
120
- hasher.update(readFileSync(join(dir, path)))
160
+ hasher.update(file.bytes)
121
161
  hasher.update('\n')
122
162
  }
123
163
  return `sha256-${hasher.digest('hex')}`
124
164
  }
125
165
 
166
+ /** A package's name and version, from its `package.json`. */
167
+ function packageOf(dir: string): { name: string; version: string } | undefined {
168
+ try {
169
+ const json = JSON.parse(readFileSync(join(dir, 'package.json'), 'utf8')) as {
170
+ name?: unknown
171
+ version?: unknown
172
+ }
173
+ return typeof json.name === 'string' && typeof json.version === 'string'
174
+ ? { name: json.name, version: json.version }
175
+ : undefined
176
+ } catch {
177
+ return undefined
178
+ }
179
+ }
180
+
181
+ /**
182
+ * A key's signature over a package's files (story 316), as `provenance.json`
183
+ * holds it; a Sigstore signature already there is kept beside it.
184
+ */
185
+ export function keySignatureOver(
186
+ files: readonly { path: string; bytes: Uint8Array }[],
187
+ pair: KeyPair,
188
+ existing?: ProvenanceFile,
189
+ ): ProvenanceFile {
190
+ const json = files.find((file) => file.path === 'package.json')
191
+ const pkg = json
192
+ ? (JSON.parse(new TextDecoder().decode(json.bytes)) as { name?: string; version?: string })
193
+ : {}
194
+ if (!pkg.name || !pkg.version) throw new Error('A bundle is signed once it is a package.')
195
+ const digest = digestOfFiles(files)
196
+ if (existing?.digest && existing.digest !== digest)
197
+ throw new Error('The bundle changed after its CI signature: sign it with its key first.')
198
+ return {
199
+ ...(existing ?? {}),
200
+ format: 1,
201
+ digest,
202
+ key: {
203
+ publicKey: pair.publicKey.line,
204
+ signature: signWith(
205
+ pair.privateKey,
206
+ signedStatement({ digest, name: pkg.name, version: pkg.version }),
207
+ ),
208
+ name: pkg.name,
209
+ version: pkg.version,
210
+ },
211
+ }
212
+ }
213
+
126
214
  const hexOf = (digest: string) => digest.replace(/^sha256-/, '')
127
215
 
128
216
  /** The statement signed: the digest alone, so the public log learns nothing of the bundle but it. */
@@ -189,8 +277,15 @@ export const refName = (ref: string): string => ref.replace(/^refs\/(tags|heads)
189
277
  export function describeProvenance(result: ProvenanceResult): string {
190
278
  switch (result.state) {
191
279
  case 'signed': {
192
- const source = result.source as ProvenanceSource
193
- return `Signed: built from github.com/${source.repository} at ${refName(source.ref)} (${source.commit.slice(0, 7)})`
280
+ const source = result.source
281
+ const built = source
282
+ ? `built from github.com/${source.repository} at ${refName(source.ref)} (${source.commit.slice(0, 7)})`
283
+ : undefined
284
+ const key = result.key
285
+ ? `signed by ${result.key.comment || 'a key'} (${result.key.fingerprint})`
286
+ : undefined
287
+ const said = [built, key].filter(Boolean).join(', and ')
288
+ return `Signed: ${said}`
194
289
  }
195
290
  case 'unsigned':
196
291
  return 'Not signed'
@@ -237,7 +332,17 @@ export function repositoryVisibility(): 'public' | 'private' | 'internal' | unde
237
332
  * job needs `id-token: write`; Sigstore turns its identity token into a
238
333
  * short-lived certificate naming the repository, ref, commit and workflow.
239
334
  */
240
- export async function signPackage(dir: string, options: SignOptions = {}): Promise<ProvenanceFile> {
335
+ /** What a Sigstore signing writes: its source and links always there. */
336
+ export type SigstoreProvenance = ProvenanceFile & {
337
+ signature: SerializedBundle
338
+ source: ProvenanceSource
339
+ links: ProvenanceLinks
340
+ }
341
+
342
+ export async function signPackage(
343
+ dir: string,
344
+ options: SignOptions = {},
345
+ ): Promise<SigstoreProvenance> {
241
346
  if (Bun.env.GITHUB_ACTIONS !== 'true' || !Bun.env.ACTIONS_ID_TOKEN_REQUEST_URL)
242
347
  throw new Error(
243
348
  'A bundle is signed in GitHub Actions, by a job with `permissions: id-token: write`: run `crombolo bundle sign` there.',
@@ -252,7 +357,10 @@ export async function signPackage(dir: string, options: SignOptions = {}): Promi
252
357
  const signature = await attest(statement(digest), IN_TOTO)
253
358
  const source = sourceOf(signature)
254
359
  if (!source) throw new Error('The signature Sigstore returned names no GitHub repository.')
255
- const file: ProvenanceFile = {
360
+ // A key's signature already there is over the same digest, and kept (story 316).
361
+ const existing = readProvenance(dir)
362
+ const file: SigstoreProvenance = {
363
+ ...(existing?.digest === digest && existing.key ? { key: existing.key } : {}),
256
364
  format: 1,
257
365
  digest,
258
366
  signature,
@@ -338,11 +446,33 @@ export async function verifyProvenanceWith(
338
446
  } catch {
339
447
  return invalid(`${PROVENANCE_FILE} is not JSON`)
340
448
  }
341
- if (provenance.format !== 1 || !provenance.signature)
449
+ if (provenance.format !== 1 || (!provenance.signature && !provenance.key))
342
450
  return invalid(`${PROVENANCE_FILE} is not a format this release reads`)
343
451
  const digest = packageDigest(dir)
344
452
  if (provenance.digest !== digest)
345
453
  return invalid('the bundle has changed since it was signed', digest)
454
+ const pkg = packageOf(dir)
455
+
456
+ // A key's signature (story 316), checked on its own terms.
457
+ let key: PublicKey | undefined
458
+ if (provenance.key) {
459
+ const read = readPublicKey(provenance.key.publicKey)
460
+ if ('problem' in read) return invalid(`its key is not one: ${read.problem}`, digest)
461
+ if (
462
+ !pkg ||
463
+ provenance.key.name !== pkg.name ||
464
+ provenance.key.version !== pkg.version ||
465
+ !verifiedBy(
466
+ read,
467
+ signedStatement({ digest, name: pkg.name, version: pkg.version }),
468
+ provenance.key.signature,
469
+ )
470
+ )
471
+ return invalid('the key signature does not check out', digest)
472
+ key = read
473
+ }
474
+ if (!provenance.signature)
475
+ return { state: 'signed', digest, key, ...(pkg ? { package: pkg } : {}) }
346
476
 
347
477
  let check = seams.verifySignature
348
478
  if (!check) {
@@ -403,7 +533,14 @@ export async function verifyProvenanceWith(
403
533
  `${PROVENANCE_FILE} says ${key} ${claimed?.[key] ?? '(none)'}, and the certificate says ${source[key]}`,
404
534
  digest,
405
535
  )
406
- return { state: 'signed', digest, source, links: linksFor(source, provenance.signature) }
536
+ return {
537
+ state: 'signed',
538
+ digest,
539
+ source,
540
+ links: linksFor(source, provenance.signature),
541
+ ...(key ? { key } : {}),
542
+ ...(pkg ? { package: pkg } : {}),
543
+ }
407
544
  }
408
545
 
409
546
  export type SignaturePolicy = 'optional' | 'required'
@@ -439,7 +576,9 @@ export function provenanceProblem(
439
576
  return policy.signatures === 'required'
440
577
  ? 'this site takes only signed bundles (CROMBOLO_BUNDLE_SIGNATURES=required); the producer signs it with `crombolo bundle sign` in GitHub Actions'
441
578
  : undefined
442
- const source = result.source as ProvenanceSource
579
+ const source = result.source
580
+ // A bundle signed by a key alone is a site bundle's matter (story 316).
581
+ if (!source) return undefined
443
582
  if (policy.sources.length > 0 && !policy.sources.some((entry) => sourceAllowed(source, entry)))
444
583
  return `it was built from github.com/${source.repository} at ${refName(source.ref)}, and this site takes signed bundles only from ${policy.sources.join(', ')} (CROMBOLO_BUNDLE_SOURCES)`
445
584
  return undefined
@@ -479,7 +618,10 @@ export async function verifyPackage(
479
618
  }
480
619
 
481
620
  /** Signs a package directory, or a `.tgz` in place with `provenance.json` added to it. */
482
- export async function signPath(path: string, options: SignOptions = {}): Promise<ProvenanceFile> {
621
+ export async function signPath(
622
+ path: string,
623
+ options: SignOptions = {},
624
+ ): Promise<SigstoreProvenance> {
483
625
  if (!isTarball(path)) return signPackage(path, options)
484
626
  const { writeNpmTarball } = await import('./tar.ts')
485
627
  return withUnpacked(path, async (dir) => {
@@ -492,3 +634,27 @@ export async function signPath(path: string, options: SignOptions = {}): Promise
492
634
  return signed
493
635
  })
494
636
  }
637
+
638
+ /** Signs a package directory, or a `.tgz` in place, with a key (story 316). */
639
+ export async function signPathWithKey(path: string, pair: KeyPair): Promise<ProvenanceFile> {
640
+ const sign = (dir: string) => {
641
+ const files = packageFiles(dir).map((file) => ({
642
+ path: file,
643
+ bytes: new Uint8Array(readFileSync(join(dir, file))),
644
+ }))
645
+ const signed = keySignatureOver(files, pair, readProvenance(dir))
646
+ writeFileSync(join(dir, PROVENANCE_FILE), `${JSON.stringify(signed, null, 2)}\n`)
647
+ return signed
648
+ }
649
+ if (!isTarball(path)) return sign(path)
650
+ const { writeNpmTarball } = await import('./tar.ts')
651
+ return withUnpacked(path, async (dir) => {
652
+ const signed = sign(dir)
653
+ const entries = [...packageFiles(dir), PROVENANCE_FILE].map((file) => ({
654
+ path: file,
655
+ bytes: new Uint8Array(readFileSync(join(dir, file))),
656
+ }))
657
+ writeFileSync(path, writeNpmTarball(entries))
658
+ return signed
659
+ })
660
+ }