@crombolo/server 0.56.0 → 0.58.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/package.json +16 -13
- package/src/adapters/bundles.ts +72 -6
- package/src/adapters/health.ts +30 -1
- package/src/bundle-admin.ts +246 -23
- package/src/bundle-api.ts +299 -0
- package/src/bundle-build.ts +4 -3
- package/src/bundle-grants.ts +133 -18
- package/src/bundle-install.ts +153 -21
- package/src/bundle-sections.ts +19 -0
- package/src/bundles.ts +87 -7
- package/src/component-templates-api.ts +27 -6
- package/src/components.ts +7 -0
- package/src/config.ts +36 -3
- package/src/core.ts +188 -16
- package/src/created-extension.ts +101 -0
- package/src/extension-components.ts +157 -0
- package/src/extension-discovery.ts +180 -0
- package/src/extension-process.ts +854 -0
- package/src/extension-sql.ts +85 -0
- package/src/index.ts +17 -0
- package/src/marketplace.ts +182 -54
- package/src/ports.ts +8 -0
- package/src/provenance.ts +186 -17
- package/src/remote.ts +54 -8
- package/src/schema.ts +31 -4
- package/src/seed/compile.ts +4 -2
- package/src/seed/export.ts +1 -1
- package/src/seed/values.ts +3 -3
- package/src/seo.ts +101 -6
- package/src/server.ts +194 -43
- package/src/settings.ts +12 -4
- package/src/signing-keys.ts +155 -0
- package/src/site-content.ts +11 -1
- package/src/site-file.ts +20 -6
- package/src/site-public.ts +1 -1
- package/src/site-sections.ts +1 -1
- package/src/site-trust.ts +267 -0
- package/src/transfer-dashboard.ts +6 -0
- package/src/trusted-signers-admin.ts +132 -0
- package/src/webhooks.ts +16 -1
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Keys that sign site bundles (story 316): a person's own, made on their
|
|
3
|
+
* machine, and each site's, kept sealed in its database. Ed25519. A public key
|
|
4
|
+
* is one line to copy, `crombolo-ed25519 <base64> <name>`, and is known by its
|
|
5
|
+
* fingerprint, `SHA256:…`, as GitHub shows SSH keys. What a key signs is a
|
|
6
|
+
* package's digest (story 060), with its name and version.
|
|
7
|
+
* docs/bundles.md, "Signing a bundle".
|
|
8
|
+
*/
|
|
9
|
+
import {
|
|
10
|
+
createPrivateKey,
|
|
11
|
+
createPublicKey,
|
|
12
|
+
generateKeyPairSync,
|
|
13
|
+
sign as signBytes,
|
|
14
|
+
verify as verifyBytes,
|
|
15
|
+
} from 'node:crypto'
|
|
16
|
+
import { chmodSync, existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from 'node:fs'
|
|
17
|
+
import { homedir } from 'node:os'
|
|
18
|
+
import { join } from 'node:path'
|
|
19
|
+
|
|
20
|
+
const KEY_TYPE = 'crombolo-ed25519'
|
|
21
|
+
/** The DER prefix that makes a raw Ed25519 public key an SPKI one. */
|
|
22
|
+
const SPKI_PREFIX = Buffer.from('302a300506032b6570032100', 'hex')
|
|
23
|
+
|
|
24
|
+
/** A public key as a site reads it. */
|
|
25
|
+
export interface PublicKey {
|
|
26
|
+
/** The 32 bytes, base64. */
|
|
27
|
+
key: string
|
|
28
|
+
/** What its owner called it: the line's last part. */
|
|
29
|
+
comment: string
|
|
30
|
+
/** `SHA256:` and the key's digest, base64 without padding. */
|
|
31
|
+
fingerprint: string
|
|
32
|
+
/** The line, as it is copied: `crombolo-ed25519 <key> <comment>`. */
|
|
33
|
+
line: string
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** A key pair: the public line, and the private half as PKCS#8 PEM. */
|
|
37
|
+
export interface KeyPair {
|
|
38
|
+
publicKey: PublicKey
|
|
39
|
+
privateKey: string
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export function fingerprintOf(raw: Uint8Array): string {
|
|
43
|
+
const digest = new Bun.CryptoHasher('sha256').update(raw).digest('base64')
|
|
44
|
+
return `SHA256:${digest.replace(/=+$/, '')}`
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
const lineOf = (key: string, comment: string) => `${KEY_TYPE} ${key}${comment ? ` ${comment}` : ''}`
|
|
48
|
+
|
|
49
|
+
/** A public key line read, or why it is not one. Pure. */
|
|
50
|
+
export function readPublicKey(text: string): PublicKey | { problem: string } {
|
|
51
|
+
const [type, key, ...rest] = text.trim().split(/\s+/)
|
|
52
|
+
if (type !== KEY_TYPE || !key)
|
|
53
|
+
return { problem: `A key starts ${KEY_TYPE}, then the key itself: paste the whole line.` }
|
|
54
|
+
const raw = Buffer.from(key, 'base64')
|
|
55
|
+
if (raw.length !== 32 || raw.toString('base64') !== key)
|
|
56
|
+
return { problem: 'That is not a whole key: copy the line again.' }
|
|
57
|
+
const comment = rest.join(' ')
|
|
58
|
+
return { key, comment, fingerprint: fingerprintOf(raw), line: lineOf(key, comment) }
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** A new key pair, named `comment`. */
|
|
62
|
+
export function createKeyPair(comment: string): KeyPair {
|
|
63
|
+
const { publicKey, privateKey } = generateKeyPairSync('ed25519')
|
|
64
|
+
const raw = publicKey.export({ format: 'der', type: 'spki' }).subarray(SPKI_PREFIX.length)
|
|
65
|
+
const key = raw.toString('base64')
|
|
66
|
+
return {
|
|
67
|
+
publicKey: {
|
|
68
|
+
key,
|
|
69
|
+
comment,
|
|
70
|
+
fingerprint: fingerprintOf(raw),
|
|
71
|
+
line: lineOf(key, comment),
|
|
72
|
+
},
|
|
73
|
+
privateKey: privateKey.export({ format: 'pem', type: 'pkcs8' }).toString(),
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** What a key signs: the digest, the package's name and version, as one stable string. */
|
|
78
|
+
export function signedStatement(input: { digest: string; name: string; version: string }): Buffer {
|
|
79
|
+
return Buffer.from(
|
|
80
|
+
JSON.stringify({
|
|
81
|
+
type: 'https://crombolo.dev/bundle-key-signature/v1',
|
|
82
|
+
digest: input.digest,
|
|
83
|
+
name: input.name,
|
|
84
|
+
version: input.version,
|
|
85
|
+
}),
|
|
86
|
+
)
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
export function signWith(privateKey: string, statement: Buffer): string {
|
|
90
|
+
return signBytes(null, statement, createPrivateKey(privateKey)).toString('base64')
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
export function verifiedBy(publicKey: PublicKey, statement: Buffer, signature: string): boolean {
|
|
94
|
+
try {
|
|
95
|
+
const key = createPublicKey({
|
|
96
|
+
key: Buffer.concat([SPKI_PREFIX, Buffer.from(publicKey.key, 'base64')]),
|
|
97
|
+
format: 'der',
|
|
98
|
+
type: 'spki',
|
|
99
|
+
})
|
|
100
|
+
return verifyBytes(null, statement, key, Buffer.from(signature, 'base64'))
|
|
101
|
+
} catch {
|
|
102
|
+
return false
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/** Where a person's own keys are kept: their config directory, never the site's. */
|
|
107
|
+
export function userKeysDir(): string {
|
|
108
|
+
return join(Bun.env.XDG_CONFIG_HOME ?? join(homedir(), '.config'), 'crombolo', 'keys')
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
const KEY_NAME = /^[a-z0-9][a-z0-9._-]{0,63}$/
|
|
112
|
+
|
|
113
|
+
/** Writes a new user key, readable by its owner alone. */
|
|
114
|
+
export function createUserKey(name: string, comment = name, dir = userKeysDir()): KeyPair {
|
|
115
|
+
if (!KEY_NAME.test(name))
|
|
116
|
+
throw new Error('A key is named with lowercase letters, digits, dots, hyphens and underscores.')
|
|
117
|
+
const file = join(dir, `${name}.json`)
|
|
118
|
+
if (existsSync(file)) throw new Error(`There is already a key called ${name}.`)
|
|
119
|
+
mkdirSync(dir, { recursive: true, mode: 0o700 })
|
|
120
|
+
const pair = createKeyPair(comment)
|
|
121
|
+
writeFileSync(
|
|
122
|
+
file,
|
|
123
|
+
`${JSON.stringify({ publicKey: pair.publicKey.line, privateKey: pair.privateKey }, null, 2)}\n`,
|
|
124
|
+
{
|
|
125
|
+
mode: 0o600,
|
|
126
|
+
},
|
|
127
|
+
)
|
|
128
|
+
chmodSync(file, 0o600)
|
|
129
|
+
return pair
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/** A user key by its name, or a path to its file. */
|
|
133
|
+
export function readUserKey(nameOrPath: string, dir = userKeysDir()): KeyPair {
|
|
134
|
+
const file = existsSync(nameOrPath) ? nameOrPath : join(dir, `${nameOrPath}.json`)
|
|
135
|
+
if (!existsSync(file))
|
|
136
|
+
throw new Error(`There is no key called ${nameOrPath}: make one with \`crombolo keys create\`.`)
|
|
137
|
+
const stored = JSON.parse(readFileSync(file, 'utf8')) as { publicKey: string; privateKey: string }
|
|
138
|
+
const publicKey = readPublicKey(stored.publicKey)
|
|
139
|
+
if ('problem' in publicKey) throw new Error(`${file} does not hold a key: ${publicKey.problem}`)
|
|
140
|
+
return { publicKey, privateKey: stored.privateKey }
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/** The user keys on this machine, by name. */
|
|
144
|
+
export function listUserKeys(dir = userKeysDir()): { name: string; publicKey: PublicKey }[] {
|
|
145
|
+
if (!existsSync(dir)) return []
|
|
146
|
+
return readdirSync(dir)
|
|
147
|
+
.filter((file) => file.endsWith('.json'))
|
|
148
|
+
.flatMap((file) => {
|
|
149
|
+
try {
|
|
150
|
+
return [{ name: file.slice(0, -5), publicKey: readUserKey(join(dir, file)).publicKey }]
|
|
151
|
+
} catch {
|
|
152
|
+
return []
|
|
153
|
+
}
|
|
154
|
+
})
|
|
155
|
+
}
|
package/src/site-content.ts
CHANGED
|
@@ -60,8 +60,18 @@ export interface SiteContentDeps {
|
|
|
60
60
|
export async function apiUserPrincipal(db: Db, clientId: string): Promise<Principal | undefined> {
|
|
61
61
|
const owner = await new UserRepository(db).clientCredentialOwner(clientId)
|
|
62
62
|
if (!owner) return undefined
|
|
63
|
+
return userPrincipal(db, owner.userId)
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** A back-office user, by key, as the Management API would see them signed in; undefined when none (story 308). */
|
|
67
|
+
export async function userPrincipalByKey(db: Db, key: string): Promise<Principal | undefined> {
|
|
68
|
+
const user = await new UserRepository(db).byKey(key)
|
|
69
|
+
return user ? userPrincipal(db, user.id) : undefined
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
async function userPrincipal(db: Db, userId: number): Promise<Principal | undefined> {
|
|
63
73
|
const store = new AuthStore(db)
|
|
64
|
-
const user = await store.findUserById(
|
|
74
|
+
const user = await store.findUserById(userId)
|
|
65
75
|
if (!user || user.isLockedOut || !user.isApproved) return undefined
|
|
66
76
|
const authorization = await store.loadAuthorization(user.id)
|
|
67
77
|
return {
|
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 })
|
package/src/site-public.ts
CHANGED
|
@@ -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, `
|
|
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'
|
package/src/site-sections.ts
CHANGED
|
@@ -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
|
|
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,267 @@
|
|
|
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
|
+
const pkg = result.package
|
|
191
|
+
const downgrade = pkg && signedBy ? await downgradeCheck(db, signedBy, pkg, options) : {}
|
|
192
|
+
if (downgrade.problem) return { problem: downgrade.problem, signedBy }
|
|
193
|
+
return {
|
|
194
|
+
signedBy,
|
|
195
|
+
...(trusted.id ? { entryId: trusted.id } : {}),
|
|
196
|
+
...(downgrade.downgraded ? { downgraded: downgrade.downgraded } : {}),
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
/** An older version from the same signer is an old bundle put back. */
|
|
201
|
+
async function downgradeCheck(
|
|
202
|
+
db: Db,
|
|
203
|
+
signedBy: string,
|
|
204
|
+
pkg: { name: string; version: string },
|
|
205
|
+
options: { allowDowngrade?: boolean },
|
|
206
|
+
): Promise<Pick<SiteBundleTrust, 'problem' | 'downgraded'>> {
|
|
207
|
+
const applied = await new TransferRunRepository(db)
|
|
208
|
+
.versionsSignedBy(signedBy, pkg.name)
|
|
209
|
+
.catch(() => [] as string[])
|
|
210
|
+
const newer = applied
|
|
211
|
+
.filter((version) => Bun.semver.order(version, pkg.version) > 0)
|
|
212
|
+
.sort(Bun.semver.order)
|
|
213
|
+
.at(-1)
|
|
214
|
+
if (!newer) return {}
|
|
215
|
+
if (!options.allowDowngrade)
|
|
216
|
+
return {
|
|
217
|
+
problem: `it is version ${pkg.version}, older than ${newer}, which this site already applied from the same ${signedBy === HOST_SIGNER ? 'host' : 'signer'}. To roll back on purpose, apply it with --allow-downgrade`,
|
|
218
|
+
}
|
|
219
|
+
return { downgraded: { from: newer, to: pkg.version } }
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
/** What a run vouched for by the host records as its signer (story 319). */
|
|
223
|
+
export const HOST_SIGNER = 'host'
|
|
224
|
+
|
|
225
|
+
/**
|
|
226
|
+
* A bundle the host vouched for (story 319): no signer is asked for, but an
|
|
227
|
+
* older version than one the host already vouched for, by package name, is
|
|
228
|
+
* still refused without `allowDowngrade`.
|
|
229
|
+
*/
|
|
230
|
+
export async function vouchedTrust(
|
|
231
|
+
db: Db,
|
|
232
|
+
pkg: { name: string; version: string },
|
|
233
|
+
options: { allowDowngrade?: boolean } = {},
|
|
234
|
+
): Promise<SiteBundleTrust> {
|
|
235
|
+
const downgrade = await downgradeCheck(db, HOST_SIGNER, pkg, options)
|
|
236
|
+
return downgrade.problem
|
|
237
|
+
? { problem: downgrade.problem, signedBy: HOST_SIGNER }
|
|
238
|
+
: {
|
|
239
|
+
signedBy: HOST_SIGNER,
|
|
240
|
+
...(downgrade.downgraded ? { downgraded: downgrade.downgraded } : {}),
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
/**
|
|
245
|
+
* A package's files with this site's key signature added as `provenance.json`
|
|
246
|
+
* (story 316); as they were where the site has no key.
|
|
247
|
+
*/
|
|
248
|
+
export async function signedWithSiteKey(
|
|
249
|
+
db: Db,
|
|
250
|
+
config: Pick<CromboloConfig, 'secretKey' | 'siteName'>,
|
|
251
|
+
files: readonly { path: string; bytes?: Uint8Array; text?: string }[],
|
|
252
|
+
): Promise<{ path: string; bytes?: Uint8Array; text?: string }[]> {
|
|
253
|
+
const key = await siteSigningKey(db, config)
|
|
254
|
+
if (!key) return [...files]
|
|
255
|
+
const encoder = new TextEncoder()
|
|
256
|
+
const signed = keySignatureOver(
|
|
257
|
+
files.map((file) => ({
|
|
258
|
+
path: file.path,
|
|
259
|
+
bytes: file.bytes ?? encoder.encode(file.text ?? ''),
|
|
260
|
+
})),
|
|
261
|
+
key,
|
|
262
|
+
)
|
|
263
|
+
return [
|
|
264
|
+
...files.filter((file) => file.path !== PROVENANCE_FILE),
|
|
265
|
+
{ path: PROVENANCE_FILE, text: `${JSON.stringify(signed, null, 2)}\n` },
|
|
266
|
+
]
|
|
267
|
+
}
|
|
@@ -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>
|