@fabrika/provider-cloudflare 0.2.0 → 0.3.2
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 +12 -8
- package/src/cli.ts +7 -8
- package/src/codec.ts +4 -57
- package/src/collaborators.ts +11 -6
- package/src/command.ts +16 -34
- package/src/control.ts +237 -119
- package/src/index.ts +5 -5
- package/src/installation/cloudflare.ts +158 -0
- package/src/installation/envfile.ts +180 -0
- package/src/installation/index.ts +2 -0
- package/src/installation/init-options.ts +326 -0
- package/src/installation/init.ts +559 -0
- package/src/installation/installation.ts +95 -0
- package/src/installation/scaffold.ts +101 -0
- package/src/installation/templates/README.md +72 -0
- package/src/installation/templates/fabrika.ref +1 -0
- package/src/installation/templates/gitignore +2 -0
- package/src/installation/templates/platform.yml +181 -0
- package/src/plan.ts +21 -31
- package/src/provider.ts +90 -70
- package/src/proxy-worker.ts +1 -1
- package/src/proxy.ts +1 -1
- package/src/runner-protocol.ts +40 -0
- package/src/schema.ts +21 -83
|
@@ -0,0 +1,559 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `fabrika platform init --provider=cloudflare <account>` — bring up a CF account's fabrika control-plane base.
|
|
3
|
+
* Idempotent + resumable (every captured value lands in the per-account env file `openEnvFile` binds and
|
|
4
|
+
* reloads). The REAL deploy runs in GitHub Actions (the scaffolded pipeline calls `fabrika platform deploy`),
|
|
5
|
+
* so this machine never needs the CF toolchain or docker.
|
|
6
|
+
*
|
|
7
|
+
* It prompts for nothing: every input is a flag or an environment variable (`init-options.ts`). What stays
|
|
8
|
+
* is one confirmation before each step that cannot be taken back, answered by `--yes` when nobody watches.
|
|
9
|
+
*
|
|
10
|
+
* Order: CF token → account + zones → IAM and email config → vault key → provisioning key → runner key →
|
|
11
|
+
* scaffold the base repo → write the GitHub Environment → trigger. Secret VALUES flow only into the env
|
|
12
|
+
* file, `gh` over stdin, and child env — never through `log.ts`. GitHub source connections are made later
|
|
13
|
+
* from the console (ADR-0029); init creates no GitHub App.
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
import {
|
|
17
|
+
action,
|
|
18
|
+
branchProtectionCommand,
|
|
19
|
+
configureEnvironment,
|
|
20
|
+
type Confirmations,
|
|
21
|
+
confirmations,
|
|
22
|
+
detail,
|
|
23
|
+
type EnvironmentConfig,
|
|
24
|
+
ghRepoExists,
|
|
25
|
+
info,
|
|
26
|
+
ok,
|
|
27
|
+
type ProtectionOutcome,
|
|
28
|
+
step,
|
|
29
|
+
triggerPlatformWorkflow,
|
|
30
|
+
url,
|
|
31
|
+
warn,
|
|
32
|
+
} from '@fabrika/installation-init'
|
|
33
|
+
import { createHash, generateKeyPairSync, randomBytes } from 'node:crypto'
|
|
34
|
+
import { type CfAccount, type CfZone, findZone, listAccounts, selectAccount, verifyToken } from './cloudflare'
|
|
35
|
+
import { envPath, fromEnv, openEnvFile, persistEnv } from './envfile'
|
|
36
|
+
import { type InitInput, parseInitAccount, parseInitArgs, PLACEHOLDER_OIDC_CLIENT_ID, rerunCommand } from './init-options'
|
|
37
|
+
import { readFabrikaRef, type ScaffoldInput, scaffoldPlatformRepo, type ScaffoldResult } from './scaffold'
|
|
38
|
+
|
|
39
|
+
/** Everything collected before the scaffold + environment write. */
|
|
40
|
+
export interface Collected {
|
|
41
|
+
account: string
|
|
42
|
+
accountId: string
|
|
43
|
+
apiToken: string
|
|
44
|
+
controlPlaneDomain: string
|
|
45
|
+
operationsHostname: string
|
|
46
|
+
platformRepo: string
|
|
47
|
+
iamUrl: string
|
|
48
|
+
/** IAM's admin hostname (the host of `iamUrl`) — its Custom Domain + token `iss`. */
|
|
49
|
+
iamHostname: string
|
|
50
|
+
oidcEnabled: boolean
|
|
51
|
+
passwordEnabled: boolean
|
|
52
|
+
/** OIDC provider issuer IAM federates human login to (discovery URL base). */
|
|
53
|
+
oidcIssuer: string
|
|
54
|
+
/** OIDC client id (public). The placeholder constant when the operator deferred real SSO. */
|
|
55
|
+
oidcClientId: string
|
|
56
|
+
/** Email domains admitted as a human at IAM login (self-provisioning allowlist). */
|
|
57
|
+
humanEmailDomains: string[]
|
|
58
|
+
emailProvider: 'none' | 'resend'
|
|
59
|
+
emailFrom: string
|
|
60
|
+
bootstrapAdmins: string[]
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
const ENVIRONMENT_SOURCE: Readonly<Record<string, string | undefined>> = process.env
|
|
64
|
+
|
|
65
|
+
/** A resume read off an injectable source, with fromEnv's empty-string-is-absent semantics. */
|
|
66
|
+
export function readResumeValue(source: Readonly<Record<string, string | undefined>>, name: string): string | undefined {
|
|
67
|
+
const value = source[name]
|
|
68
|
+
return value === undefined || value === '' ? undefined : value
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** Everything `runInit` does outside this machine. Each GitHub write is confirmed first. */
|
|
72
|
+
export interface InitEffects {
|
|
73
|
+
/** Only decides how the scaffold confirmation is phrased; the scaffold itself re-reads it. */
|
|
74
|
+
repositoryExists(repo: string): Promise<boolean>
|
|
75
|
+
listAccounts(token: string): Promise<CfAccount[]>
|
|
76
|
+
/** Best effort: `false` means "could not confirm", never "invalid". */
|
|
77
|
+
verifyToken(token: string, accountId: string): Promise<boolean>
|
|
78
|
+
findZone(token: string, hostname: string): Promise<CfZone | null>
|
|
79
|
+
scaffold(input: ScaffoldInput): Promise<ScaffoldResult>
|
|
80
|
+
configureEnvironment(config: EnvironmentConfig): Promise<void>
|
|
81
|
+
triggerWorkflow(repo: string): Promise<void>
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
export interface InitCollaborators {
|
|
85
|
+
readonly prompts: Confirmations
|
|
86
|
+
readonly effects: InitEffects
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** `platform init` from its command line: open the account's env file, parse against it, run. */
|
|
90
|
+
export async function initCommand(argv: readonly string[]): Promise<void> {
|
|
91
|
+
const account = parseInitAccount(argv)
|
|
92
|
+
console.log(`\nfabrika platform init — bring up the ${account} Cloudflare control-plane base\n`)
|
|
93
|
+
step('Open the installer env file')
|
|
94
|
+
info(`Every captured value is persisted here (0600, in a 0700 directory) so a re-run resumes: ${await openEnvFile(account)}`)
|
|
95
|
+
const input = parseInitArgs(argv, process.env)
|
|
96
|
+
await runInit(input, consoleInitCollaborators(input))
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** Run the full bring-up. The installer env file must already be open (`openEnvFile`). */
|
|
100
|
+
export async function runInit(input: InitInput, collaborators: InitCollaborators): Promise<void> {
|
|
101
|
+
const cfAccount = await verifiedAccount(input, collaborators)
|
|
102
|
+
if (cfAccount === undefined) {
|
|
103
|
+
return
|
|
104
|
+
}
|
|
105
|
+
const collected = await collect(input, cfAccount, collaborators.effects)
|
|
106
|
+
const vaultKey = await ensureVaultKey()
|
|
107
|
+
const provisioning = await ensureProvisioningKey()
|
|
108
|
+
const operationsSyncKey = await ensureOperationsSyncKey()
|
|
109
|
+
const signingKeys = await ensureSigningKeys()
|
|
110
|
+
const oidcClientSecret = input.oidc === undefined ? undefined : await ensureOidcClientSecret(input.oidc.clientSecret)
|
|
111
|
+
const emailApiKey = input.email.provider === 'resend' ? await ensureResendApiKey(input.email.apiKey) : undefined
|
|
112
|
+
const runnerKey = await ensureRunnerKey()
|
|
113
|
+
|
|
114
|
+
const { prompts, effects } = collaborators
|
|
115
|
+
const rerun = rerunCommand(input, collected.accountId)
|
|
116
|
+
|
|
117
|
+
step('Scaffold the platform repository')
|
|
118
|
+
const question = (await effects.repositoryExists(collected.platformRepo))
|
|
119
|
+
? `Refresh the platform pipeline on ${collected.platformRepo} and push?`
|
|
120
|
+
: `Create ${collected.platformRepo} (private) on GitHub and push the platform pipeline?`
|
|
121
|
+
if (!(await prompts.confirm(question, true))) {
|
|
122
|
+
action('OPERATOR ACTION — nothing was pushed to GitHub; run init again when ready', [rerun])
|
|
123
|
+
return
|
|
124
|
+
}
|
|
125
|
+
const { dir, branchProtection } = await effects.scaffold({
|
|
126
|
+
repo: collected.platformRepo,
|
|
127
|
+
account: collected.account,
|
|
128
|
+
dir: input.checkout,
|
|
129
|
+
})
|
|
130
|
+
|
|
131
|
+
let environmentPolicy: ProtectionOutcome | undefined
|
|
132
|
+
const environment: EnvironmentConfig = {
|
|
133
|
+
repo: collected.platformRepo,
|
|
134
|
+
environment: collected.account,
|
|
135
|
+
onProtection: (outcome) => {
|
|
136
|
+
environmentPolicy = outcome
|
|
137
|
+
},
|
|
138
|
+
...environmentPayload(collected, {
|
|
139
|
+
vaultKey,
|
|
140
|
+
provisioning,
|
|
141
|
+
operationsSyncKey,
|
|
142
|
+
runnerKey,
|
|
143
|
+
signingKeys,
|
|
144
|
+
...(oidcClientSecret === undefined ? {} : { oidcClientSecret }),
|
|
145
|
+
...(emailApiKey === undefined ? {} : { emailApiKey }),
|
|
146
|
+
}),
|
|
147
|
+
}
|
|
148
|
+
info(
|
|
149
|
+
`${Object.keys(environment.secrets).length} secret(s) and ${
|
|
150
|
+
Object.keys(environment.vars).length
|
|
151
|
+
} variable(s) for the ${collected.account} Environment.`,
|
|
152
|
+
)
|
|
153
|
+
if (!(await prompts.confirm(`Write them to the ${collected.account} Environment now (secret VALUES go to GitHub over \`gh\` stdin)?`, true))) {
|
|
154
|
+
action('OPERATOR ACTION — the pipeline cannot run until the Environment holds these; run init again when ready', [rerun])
|
|
155
|
+
return
|
|
156
|
+
}
|
|
157
|
+
await effects.configureEnvironment(environment)
|
|
158
|
+
|
|
159
|
+
await triggerDeploy(collected.platformRepo, collaborators)
|
|
160
|
+
finalNotes({
|
|
161
|
+
repo: collected.platformRepo,
|
|
162
|
+
account: collected.account,
|
|
163
|
+
controlPlaneDomain: collected.controlPlaneDomain,
|
|
164
|
+
dir,
|
|
165
|
+
ref: await readFabrikaRef(dir),
|
|
166
|
+
passwordEnabled: collected.passwordEnabled,
|
|
167
|
+
...(branchProtection === undefined ? {} : { branchProtection }),
|
|
168
|
+
...(environmentPolicy === undefined ? {} : { environmentPolicy }),
|
|
169
|
+
})
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
/** The real collaborators: a TTY (or `--yes`), the Cloudflare API, `gh` and git. */
|
|
173
|
+
export function consoleInitCollaborators(input: InitInput): InitCollaborators {
|
|
174
|
+
return {
|
|
175
|
+
// Before anything is contacted: a run nobody can confirm does not start.
|
|
176
|
+
prompts: confirmations(
|
|
177
|
+
input.unattended,
|
|
178
|
+
process.stdin,
|
|
179
|
+
(line) => info(line),
|
|
180
|
+
'creates or pushes the platform repository, writes its GitHub Environment secrets and triggers the platform workflow',
|
|
181
|
+
),
|
|
182
|
+
effects: {
|
|
183
|
+
repositoryExists: (repo) => ghRepoExists(repo),
|
|
184
|
+
listAccounts: (token) => listAccounts(token),
|
|
185
|
+
verifyToken: (token, accountId) => verifyToken(token, accountId),
|
|
186
|
+
findZone: (token, hostname) => findZone(token, hostname),
|
|
187
|
+
scaffold: (scaffoldInput) => scaffoldPlatformRepo(scaffoldInput),
|
|
188
|
+
configureEnvironment: (config) => configureEnvironment(config),
|
|
189
|
+
triggerWorkflow: (repo) => triggerPlatformWorkflow(repo),
|
|
190
|
+
},
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
/** Everything `init` generated or fetched, ready to be split into the Environment's two halves. */
|
|
195
|
+
export interface GeneratedInstallation {
|
|
196
|
+
readonly vaultKey: string
|
|
197
|
+
readonly provisioning: string
|
|
198
|
+
readonly operationsSyncKey: string
|
|
199
|
+
readonly runnerKey: string
|
|
200
|
+
readonly signingKeys: string
|
|
201
|
+
readonly oidcClientSecret?: string
|
|
202
|
+
readonly emailApiKey?: string
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
/**
|
|
206
|
+
* What the GitHub Environment holds, split by the one rule: a credential is a SECRET, never a variable
|
|
207
|
+
* (a variable value reaches `gh` on argv).
|
|
208
|
+
*/
|
|
209
|
+
export function environmentPayload(
|
|
210
|
+
collected: Collected,
|
|
211
|
+
generated: GeneratedInstallation,
|
|
212
|
+
): { secrets: Record<string, string>; vars: Record<string, string> } {
|
|
213
|
+
return {
|
|
214
|
+
secrets: {
|
|
215
|
+
CLOUDFLARE_ACCOUNT_ID: collected.accountId,
|
|
216
|
+
CLOUDFLARE_API_TOKEN: collected.apiToken,
|
|
217
|
+
FABRIKA_CONTROL_VAULT_KEY: generated.vaultKey,
|
|
218
|
+
FABRIKA_IAM_PROVISIONING_KEY: generated.provisioning,
|
|
219
|
+
OPERATIONS_SYNC_KEY: generated.operationsSyncKey,
|
|
220
|
+
// The shared key the control plane presents to the deploy runner; both Workers take the same value.
|
|
221
|
+
FABRIKA_RUNNER_KEY: generated.runnerKey,
|
|
222
|
+
// IAM Stage 1 native-auth secrets (pushed as IAM Worker secrets by the pipeline).
|
|
223
|
+
FABRIKA_IAM_SIGNING_KEYS: generated.signingKeys,
|
|
224
|
+
...(generated.oidcClientSecret === undefined ? {} : { FABRIKA_IAM_OIDC_CLIENT_SECRET: generated.oidcClientSecret }),
|
|
225
|
+
...(generated.emailApiKey === undefined ? {} : { FABRIKA_EMAIL_RESEND_API_KEY: generated.emailApiKey }),
|
|
226
|
+
},
|
|
227
|
+
vars: {
|
|
228
|
+
FABRIKA_CONTROL_DOMAIN: collected.controlPlaneDomain,
|
|
229
|
+
OPERATIONS_HOSTNAME: collected.operationsHostname,
|
|
230
|
+
FABRIKA_IAM_ISSUER: collected.iamUrl,
|
|
231
|
+
FABRIKA_CONTROL_BOOTSTRAP_ADMINS: JSON.stringify(collected.bootstrapAdmins),
|
|
232
|
+
// IAM Stage 1 non-secret config (read by IAM's fabrika config).
|
|
233
|
+
FABRIKA_IAM_HOSTNAME: collected.iamHostname,
|
|
234
|
+
FABRIKA_IAM_OIDC_ENABLED: String(collected.oidcEnabled),
|
|
235
|
+
FABRIKA_IAM_PASSWORD_ENABLED: String(collected.passwordEnabled),
|
|
236
|
+
FABRIKA_EMAIL_PROVIDER: collected.emailProvider,
|
|
237
|
+
...(collected.oidcEnabled
|
|
238
|
+
? {
|
|
239
|
+
FABRIKA_IAM_OIDC_ISSUER: collected.oidcIssuer,
|
|
240
|
+
FABRIKA_IAM_OIDC_CLIENT_ID: collected.oidcClientId,
|
|
241
|
+
FABRIKA_IAM_HUMAN_EMAIL_DOMAINS: JSON.stringify(collected.humanEmailDomains),
|
|
242
|
+
}
|
|
243
|
+
: {}),
|
|
244
|
+
...(collected.emailProvider === 'resend' ? { FABRIKA_EMAIL_FROM: collected.emailFrom } : {}),
|
|
245
|
+
// The same first-admin emails admit the operator to IAM itself (its own bootstrap hatch).
|
|
246
|
+
FABRIKA_IAM_BOOTSTRAP_ADMINS: JSON.stringify(collected.bootstrapAdmins),
|
|
247
|
+
},
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
/**
|
|
252
|
+
* Resolve the account the token deploys into and check the token against it.
|
|
253
|
+
*
|
|
254
|
+
* Returns `undefined` when the operator declines an unverified token: nothing has been written then.
|
|
255
|
+
*/
|
|
256
|
+
async function verifiedAccount(input: InitInput, { prompts, effects }: InitCollaborators): Promise<CfAccount | undefined> {
|
|
257
|
+
step('Cloudflare API token')
|
|
258
|
+
info("Read from CLOUDFLARE_API_TOKEN. It authenticates the deploy AND becomes the control plane's runtime CLOUDFLARE_API_TOKEN secret.")
|
|
259
|
+
detail(`Resolving the Cloudflare account for this token (${input.apiToken.length} chars)…`)
|
|
260
|
+
// An unreadable list is not fatal: an account-owned token typically cannot list its own account.
|
|
261
|
+
const accounts = await effects.listAccounts(input.apiToken).catch((): CfAccount[] => [])
|
|
262
|
+
const cfAccount = selectAccount(accounts, input.accountId)
|
|
263
|
+
if (await effects.verifyToken(input.apiToken, cfAccount.id)) {
|
|
264
|
+
ok('Token verified (status active).')
|
|
265
|
+
} else {
|
|
266
|
+
warn('Could not pre-verify the token via the Cloudflare API.')
|
|
267
|
+
detail('Expected for some account-owned tokens (invisible to /user/tokens/verify); the deploy validates it for real.')
|
|
268
|
+
if (!(await prompts.confirm('Proceed anyway?', true))) {
|
|
269
|
+
action('OPERATOR ACTION — nothing was written; check CLOUDFLARE_API_TOKEN, then run init again', [rerunCommand(input, cfAccount.id)])
|
|
270
|
+
return undefined
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
ok(`Account: ${cfAccount.name} (${cfAccount.id})`)
|
|
274
|
+
await persistEnv('CLOUDFLARE_API_TOKEN', input.apiToken)
|
|
275
|
+
await persistEnv('CLOUDFLARE_ACCOUNT_ID', cfAccount.id)
|
|
276
|
+
return cfAccount
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
/** Warn — never fail — when no zone covers `hostname`: the operator may add it before the deploy. */
|
|
280
|
+
async function checkZone(effects: InitEffects, token: string, hostname: string, consequence: string): Promise<void> {
|
|
281
|
+
const zone = await effects.findZone(token, hostname).catch(() => null)
|
|
282
|
+
if (zone === null) {
|
|
283
|
+
warn(`No Cloudflare zone found for ${hostname} — ${consequence}`)
|
|
284
|
+
} else {
|
|
285
|
+
ok(`Zone found: ${zone.name}`)
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
/** Check the hosts against the account's zones and persist the resumable selections. */
|
|
290
|
+
async function collect(input: InitInput, cfAccount: CfAccount, effects: InitEffects): Promise<Collected> {
|
|
291
|
+
step('Account details')
|
|
292
|
+
ok(`Platform repo: ${input.repo}`)
|
|
293
|
+
ok(`fabrika control-plane domain: ${input.hosts.control}`)
|
|
294
|
+
await checkZone(effects, input.apiToken, input.hosts.control, 'a custom-domain bind would fail. Add the zone before the deploy.')
|
|
295
|
+
ok(`Operations ingest domain: ${input.hosts.operations}`)
|
|
296
|
+
await checkZone(effects, input.apiToken, input.hosts.operations, 'the Operations custom-domain bind would fail.')
|
|
297
|
+
if (input.bootstrapAdmins.length === 0) {
|
|
298
|
+
warn('No first admin (--admins / FABRIKA_CONTROL_BOOTSTRAP_ADMINS): nobody is admitted through the escape hatch.')
|
|
299
|
+
} else {
|
|
300
|
+
ok(`First admins: ${input.bootstrapAdmins.join(', ')}`)
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
step('IAM auth config (Stage 1)')
|
|
304
|
+
ok(`IAM hostname: ${input.hosts.iam}`)
|
|
305
|
+
const oidc = input.oidc
|
|
306
|
+
await persistEnv('FABRIKA_IAM_OIDC_ENABLED', String(oidc !== undefined))
|
|
307
|
+
await persistEnv('FABRIKA_IAM_PASSWORD_ENABLED', String(input.passwordEnabled))
|
|
308
|
+
if (oidc !== undefined) {
|
|
309
|
+
await persistEnv('FABRIKA_IAM_OIDC_ISSUER', oidc.issuer)
|
|
310
|
+
if (oidc.clientId === PLACEHOLDER_OIDC_CLIENT_ID) {
|
|
311
|
+
warn('Placeholder OIDC — human SSO login is inert until you set real FABRIKA_IAM_OIDC_CLIENT_ID + _SECRET.')
|
|
312
|
+
}
|
|
313
|
+
await persistEnv('FABRIKA_IAM_OIDC_CLIENT_ID', oidc.clientId)
|
|
314
|
+
}
|
|
315
|
+
await persistEnv('FABRIKA_EMAIL_PROVIDER', input.email.provider)
|
|
316
|
+
if (input.email.provider === 'resend') await persistEnv('FABRIKA_EMAIL_FROM', input.email.from)
|
|
317
|
+
|
|
318
|
+
return {
|
|
319
|
+
account: input.account,
|
|
320
|
+
accountId: cfAccount.id,
|
|
321
|
+
apiToken: input.apiToken,
|
|
322
|
+
controlPlaneDomain: input.hosts.control,
|
|
323
|
+
operationsHostname: input.hosts.operations,
|
|
324
|
+
platformRepo: input.repo,
|
|
325
|
+
iamUrl: `https://${input.hosts.iam}`,
|
|
326
|
+
iamHostname: input.hosts.iam,
|
|
327
|
+
oidcEnabled: oidc !== undefined,
|
|
328
|
+
passwordEnabled: input.passwordEnabled,
|
|
329
|
+
oidcIssuer: oidc?.issuer ?? '',
|
|
330
|
+
oidcClientId: oidc?.clientId ?? '',
|
|
331
|
+
humanEmailDomains: oidc === undefined ? [] : [...oidc.humanEmailDomains],
|
|
332
|
+
emailProvider: input.email.provider,
|
|
333
|
+
emailFrom: input.email.provider === 'resend' ? input.email.from : '',
|
|
334
|
+
bootstrapAdmins: [...input.bootstrapAdmins],
|
|
335
|
+
}
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
/**
|
|
339
|
+
* Generate the M4 vault KEK: 32 random bytes, base64. It lives nowhere else (never in D1 or logs), so
|
|
340
|
+
* losing it is unrecoverable. Persist it locally and tell the operator where to secure it.
|
|
341
|
+
*/
|
|
342
|
+
interface VaultKeyDependencies {
|
|
343
|
+
readonly source: Readonly<Record<string, string | undefined>>
|
|
344
|
+
persist(name: string, value: string): Promise<void>
|
|
345
|
+
generate(): string
|
|
346
|
+
created(message: string, details: string[]): void
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
const vaultKeyDependencies: VaultKeyDependencies = {
|
|
350
|
+
source: ENVIRONMENT_SOURCE,
|
|
351
|
+
persist: persistEnv,
|
|
352
|
+
generate: () => randomBytes(32).toString('base64'),
|
|
353
|
+
created: action,
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
export async function ensureVaultKey(dependencies: VaultKeyDependencies = vaultKeyDependencies): Promise<string> {
|
|
357
|
+
step('Generate the vault master key (FABRIKA_CONTROL_VAULT_KEY)')
|
|
358
|
+
const existing = readResumeValue(dependencies.source, 'FABRIKA_CONTROL_VAULT_KEY')
|
|
359
|
+
if (existing !== undefined) {
|
|
360
|
+
await dependencies.persist('FABRIKA_CONTROL_VAULT_KEY', existing)
|
|
361
|
+
ok('Reusing FABRIKA_CONTROL_VAULT_KEY from the installer env file (resume).')
|
|
362
|
+
return existing
|
|
363
|
+
}
|
|
364
|
+
const key = dependencies.generate()
|
|
365
|
+
await dependencies.persist('FABRIKA_CONTROL_VAULT_KEY', key)
|
|
366
|
+
dependencies.created('SAVED to the installer env file — copy it to your password manager; the vault KEK is unrecoverable if lost', [
|
|
367
|
+
"It is the master key for fabrika's encrypted secret vault.",
|
|
368
|
+
'The value is intentionally not printed.',
|
|
369
|
+
])
|
|
370
|
+
return key
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
/**
|
|
374
|
+
* Generate the operator-side provisioning key (the "seeded key"): a single opaque `px_` bearer, stored
|
|
375
|
+
* once. IAM Stage 1 SEEDS it (the `FABRIKA_IAM_PROVISIONING_KEY` secret — `resolveCaller` admits a
|
|
376
|
+
* bearer matching it as a synthetic admin) and fabrika Stage 2 USES it to authenticate schema reconciles.
|
|
377
|
+
* Shaped like an IAM-native key (`px_` + 160 bits base64url). An operator who already has one can
|
|
378
|
+
* pre-set `FABRIKA_IAM_PROVISIONING_KEY` in env and init reuses it.
|
|
379
|
+
*/
|
|
380
|
+
async function ensureProvisioningKey(): Promise<string> {
|
|
381
|
+
step('Provisioning key (FABRIKA_IAM_PROVISIONING_KEY)')
|
|
382
|
+
const existing = readResumeValue(ENVIRONMENT_SOURCE, 'FABRIKA_IAM_PROVISIONING_KEY')
|
|
383
|
+
if (existing !== undefined) {
|
|
384
|
+
await persistEnv('FABRIKA_IAM_PROVISIONING_KEY', existing)
|
|
385
|
+
ok('Reusing the provisioning key from the installer env file (resume).')
|
|
386
|
+
return existing
|
|
387
|
+
}
|
|
388
|
+
const key = `px_${randomBytes(20).toString('base64url')}`
|
|
389
|
+
await persistEnv('FABRIKA_IAM_PROVISIONING_KEY', key)
|
|
390
|
+
ok('Provisioning key generated + saved to the installer env file.')
|
|
391
|
+
detail('IAM Stage 1 seeds this as an admin credential; the control plane reconciles with it in Stage 2.')
|
|
392
|
+
return key
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
async function ensureOperationsSyncKey(): Promise<string> {
|
|
396
|
+
step('Operations catalog key (OPERATIONS_SYNC_KEY)')
|
|
397
|
+
const existing = fromEnv('OPERATIONS_SYNC_KEY')
|
|
398
|
+
if (existing !== undefined) {
|
|
399
|
+
if (existing.length < 32) throw new Error('OPERATIONS_SYNC_KEY must be at least 32 characters.')
|
|
400
|
+
ok('Reusing OPERATIONS_SYNC_KEY from the installer env file (resume).')
|
|
401
|
+
return existing
|
|
402
|
+
}
|
|
403
|
+
const key = randomBytes(32).toString('base64url')
|
|
404
|
+
await persistEnv('OPERATIONS_SYNC_KEY', key)
|
|
405
|
+
ok('Operations catalog key generated + saved to the installer env file.')
|
|
406
|
+
return key
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
/**
|
|
410
|
+
* Generate the runner key: the shared 256-bit bearer the control plane presents to the deploy executor,
|
|
411
|
+
* whose service binding alone proves nothing about the caller. The SAME value is pushed to both Workers,
|
|
412
|
+
* so it must be durable — a resumed init reuses it rather than rolling half the pair.
|
|
413
|
+
*/
|
|
414
|
+
export async function ensureRunnerKey(): Promise<string> {
|
|
415
|
+
step('Runner key (FABRIKA_RUNNER_KEY)')
|
|
416
|
+
const existing = readResumeValue(ENVIRONMENT_SOURCE, 'FABRIKA_RUNNER_KEY')
|
|
417
|
+
if (existing !== undefined) {
|
|
418
|
+
await persistEnv('FABRIKA_RUNNER_KEY', existing)
|
|
419
|
+
ok('Reusing FABRIKA_RUNNER_KEY from the installer env file (resume).')
|
|
420
|
+
return existing
|
|
421
|
+
}
|
|
422
|
+
const key = randomBytes(32).toString('base64url')
|
|
423
|
+
await persistEnv('FABRIKA_RUNNER_KEY', key)
|
|
424
|
+
ok('Runner key generated + saved to the installer env file.')
|
|
425
|
+
detail('The pipeline pushes it to the control plane and the deploy runner as a Worker secret.')
|
|
426
|
+
return key
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
/** One ES256 (EC P-256) private JWK with an RFC 7638 thumbprint `kid`, shaped exactly as IAM's
|
|
430
|
+
* `Signer.fromPrivateJwks` loads it (index 0 = the active signer). */
|
|
431
|
+
function generateEs256Jwk(): JsonWebKey & { kid: string } {
|
|
432
|
+
const { privateKey } = generateKeyPairSync('ec', { namedCurve: 'P-256' })
|
|
433
|
+
const jwk = privateKey.export({ format: 'jwk' })
|
|
434
|
+
// RFC 7638 thumbprint over the canonical EC members, lexicographic order (crv, kty, x, y).
|
|
435
|
+
const thumbprint = createHash('sha256').update(JSON.stringify({ crv: jwk.crv, kty: jwk.kty, x: jwk.x, y: jwk.y })).digest('base64url')
|
|
436
|
+
return { ...jwk, kid: thumbprint, alg: 'ES256', use: 'sig' }
|
|
437
|
+
}
|
|
438
|
+
|
|
439
|
+
/**
|
|
440
|
+
* Generate IAM's token-signing key (Stage 1): a JSON array with one ES256 private JWK. IAM
|
|
441
|
+
* signs every token it issues with index 0 and publishes the public half in its JWKS. Stored once
|
|
442
|
+
* (`FABRIKA_IAM_SIGNING_KEYS`) and pushed as an IAM Worker secret by Stage 1. Resume-safe; it must be
|
|
443
|
+
* DURABLE — rotating it invalidates every live token (so we never regenerate when one already exists).
|
|
444
|
+
*/
|
|
445
|
+
async function ensureSigningKeys(): Promise<string> {
|
|
446
|
+
step('Generate the IAM signing key (FABRIKA_IAM_SIGNING_KEYS)')
|
|
447
|
+
const existing = readResumeValue(ENVIRONMENT_SOURCE, 'FABRIKA_IAM_SIGNING_KEYS')
|
|
448
|
+
if (existing !== undefined) {
|
|
449
|
+
await persistEnv('FABRIKA_IAM_SIGNING_KEYS', existing)
|
|
450
|
+
ok('Reusing FABRIKA_IAM_SIGNING_KEYS from the installer env file (resume).')
|
|
451
|
+
return existing
|
|
452
|
+
}
|
|
453
|
+
const keys = JSON.stringify([generateEs256Jwk()])
|
|
454
|
+
await persistEnv('FABRIKA_IAM_SIGNING_KEYS', keys)
|
|
455
|
+
ok('IAM signing key generated (1 × ES256) + saved to the installer env file.')
|
|
456
|
+
return keys
|
|
457
|
+
}
|
|
458
|
+
|
|
459
|
+
/**
|
|
460
|
+
* Persist IAM's OIDC client secret (Stage 1) — the real one from the environment, or the placeholder
|
|
461
|
+
* paired with the placeholder client id — so a re-run reuses it. NEVER logged.
|
|
462
|
+
*/
|
|
463
|
+
async function ensureOidcClientSecret(value: string): Promise<string> {
|
|
464
|
+
step('IAM OIDC client secret (FABRIKA_IAM_OIDC_CLIENT_SECRET)')
|
|
465
|
+
await persistEnv('FABRIKA_IAM_OIDC_CLIENT_SECRET', value)
|
|
466
|
+
ok('OIDC client secret saved to the installer env file.')
|
|
467
|
+
return value
|
|
468
|
+
}
|
|
469
|
+
|
|
470
|
+
/** Persist the Resend API key without ever writing it to user-facing output. */
|
|
471
|
+
async function ensureResendApiKey(value: string): Promise<string> {
|
|
472
|
+
step('Resend API key (FABRIKA_EMAIL_RESEND_API_KEY)')
|
|
473
|
+
await persistEnv('FABRIKA_EMAIL_RESEND_API_KEY', value)
|
|
474
|
+
ok('Resend API key saved to the installer env file.')
|
|
475
|
+
return value
|
|
476
|
+
}
|
|
477
|
+
|
|
478
|
+
/** Trigger the platform workflow (each deploy builds the runner image into this account's registry). */
|
|
479
|
+
async function triggerDeploy(repo: string, { prompts, effects }: InitCollaborators): Promise<void> {
|
|
480
|
+
step('Trigger the platform deploy (GitHub Actions)')
|
|
481
|
+
info('GitHub Actions runs the real deploy — fabrika runner then control plane. Each run builds the runner')
|
|
482
|
+
info('container image into this account (CI has docker); this machine deploys nothing.')
|
|
483
|
+
if (!(await prompts.confirm(`Run the platform workflow on ${repo} now?`, true))) {
|
|
484
|
+
action('OPERATOR ACTION — run it when ready', [
|
|
485
|
+
`gh workflow run platform.yml --repo ${repo}`,
|
|
486
|
+
`or: ${url(`https://github.com/${repo}/actions`)} → platform → Run workflow`,
|
|
487
|
+
])
|
|
488
|
+
return
|
|
489
|
+
}
|
|
490
|
+
await effects.triggerWorkflow(repo)
|
|
491
|
+
ok('Platform workflow triggered.')
|
|
492
|
+
detail(`Watch: ${url(`https://github.com/${repo}/actions`)} (or: gh run watch --repo ${repo})`)
|
|
493
|
+
}
|
|
494
|
+
|
|
495
|
+
/** What the closing summary reports beyond the repository itself. */
|
|
496
|
+
export interface FinalNotes {
|
|
497
|
+
readonly repo: string
|
|
498
|
+
readonly account: string
|
|
499
|
+
readonly controlPlaneDomain: string
|
|
500
|
+
readonly dir: string
|
|
501
|
+
readonly ref: string
|
|
502
|
+
readonly passwordEnabled: boolean
|
|
503
|
+
/** Absent when the repository already existed, so this run did not touch its protection. */
|
|
504
|
+
readonly branchProtection?: ProtectionOutcome
|
|
505
|
+
readonly environmentPolicy?: ProtectionOutcome
|
|
506
|
+
}
|
|
507
|
+
|
|
508
|
+
/** Closing notes: the checkout, the env file, what is protected, the escape hatch, and what runs in CI. */
|
|
509
|
+
export function finalNotes(notes: FinalNotes): void {
|
|
510
|
+
const { repo, account, controlPlaneDomain, dir, ref, passwordEnabled } = notes
|
|
511
|
+
step('Done')
|
|
512
|
+
ok(`Base repo: ${repo} (pinned fabrika ref: ${ref})`)
|
|
513
|
+
ok(`Local checkout: ${dir}`)
|
|
514
|
+
ok(`Installer env file (0600): ${envPath()}`)
|
|
515
|
+
reportProtection('Branch protection on main', notes.branchProtection, 'not checked')
|
|
516
|
+
reportEnvironmentPolicy(repo, notes.environmentPolicy, notes.branchProtection)
|
|
517
|
+
info('The fabrika control plane came up with the bootstrap-admin escape hatch OPEN (FABRIKA_CONTROL_BOOTSTRAP_ADMINS set).')
|
|
518
|
+
action('OPERATOR ACTION — close the hatch after IAM grants you the fabrika admin role', [
|
|
519
|
+
`1. gh variable set FABRIKA_CONTROL_BOOTSTRAP_ADMINS --repo ${repo} --env ${account} --body '[]'`,
|
|
520
|
+
`2. gh workflow run platform.yml --repo ${repo}`,
|
|
521
|
+
'3. Authorization is then fully IAM-owned.',
|
|
522
|
+
])
|
|
523
|
+
info('Public repositories deploy without a GitHub App. Connect private GitHub source in Control.')
|
|
524
|
+
action('OPERATOR ACTION — connect GitHub source in Control once the deploy is live', [url(`https://${controlPlaneDomain}/settings/source`)])
|
|
525
|
+
if (passwordEnabled) {
|
|
526
|
+
action('OPERATOR ACTION — enroll the first password user through IAM provisioning', [
|
|
527
|
+
'Password enrollment is provisioning-backed; the installer does not print or invent an administrative credential.',
|
|
528
|
+
'Use the IAM admin surface after the first provisioning-backed administrator is available.',
|
|
529
|
+
])
|
|
530
|
+
}
|
|
531
|
+
}
|
|
532
|
+
|
|
533
|
+
/** One line per hardening rule: applied, or what is open and the command that closes it. */
|
|
534
|
+
function reportProtection(label: string, outcome: ProtectionOutcome | undefined, absent: string): void {
|
|
535
|
+
if (outcome === undefined) {
|
|
536
|
+
info(`${label}: ${absent}.`)
|
|
537
|
+
return
|
|
538
|
+
}
|
|
539
|
+
if (outcome.applied) {
|
|
540
|
+
ok(`${label}: applied.`)
|
|
541
|
+
return
|
|
542
|
+
}
|
|
543
|
+
warn(`${label}: NOT applied (${outcome.reason ?? 'refused'}).`)
|
|
544
|
+
detail(`Apply it later: ${outcome.command}`)
|
|
545
|
+
}
|
|
546
|
+
|
|
547
|
+
/**
|
|
548
|
+
* `protected_branches` admits every branch that carries no protection rule, so the Environment policy is
|
|
549
|
+
* worth nothing until `main` is protected. Never report the policy as sufficient on its own.
|
|
550
|
+
*/
|
|
551
|
+
function reportEnvironmentPolicy(repo: string, policy: ProtectionOutcome | undefined, branch: ProtectionOutcome | undefined): void {
|
|
552
|
+
const label = 'Environment deployment-branch policy'
|
|
553
|
+
if (policy?.applied === true && branch?.applied !== true) {
|
|
554
|
+
warn(`${label}: applied, but it restricts nothing until main carries a protection rule.`)
|
|
555
|
+
detail(`Protect main first: ${branch?.command ?? branchProtectionCommand(repo)}`)
|
|
556
|
+
return
|
|
557
|
+
}
|
|
558
|
+
reportProtection(label, policy, 'not attempted')
|
|
559
|
+
}
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
import type { InstallationCli, InstallationCommand } from '@fabrika/provider-contract/installation'
|
|
2
|
+
import { resolve } from 'node:path'
|
|
3
|
+
import { parseCloudflareArgs, platformComponents } from '../cli-args'
|
|
4
|
+
import { deployCloudflareConfig } from '../command'
|
|
5
|
+
import { initCommand } from './init'
|
|
6
|
+
|
|
7
|
+
const USAGE = `Cloudflare installation
|
|
8
|
+
|
|
9
|
+
Commands:
|
|
10
|
+
fabrika platform init --provider=cloudflare <account> --console-host=<host> --operations-host=<host> --iam-host=<host>
|
|
11
|
+
--auth-methods=<oidc|password|oidc,password> --email-provider=<none|resend> [options] [--yes]
|
|
12
|
+
fabrika platform plan --provider=cloudflare --runner-config=<path> --worker-config=<path> [--env=<env>]
|
|
13
|
+
fabrika platform deploy --provider=cloudflare --runner-config=<path> --worker-config=<path> [--env=<env>]
|
|
14
|
+
fabrika platform plan --provider=cloudflare --component-config=<path> [--env=<env>]
|
|
15
|
+
fabrika platform deploy --provider=cloudflare --component-config=<path> [--env=<env>]
|
|
16
|
+
|
|
17
|
+
init prompts for nothing. Every value is a flag or the environment variable beside it, flag first:
|
|
18
|
+
--account-id=<id> CLOUDFLARE_ACCOUNT_ID required when the token acts on several accounts
|
|
19
|
+
--repo=<owner>/<name> default <account>/fabrika-platform
|
|
20
|
+
--checkout=<dir> default ./fabrika-platform-<account>, outside any git repository
|
|
21
|
+
--console-host=<host> FABRIKA_CONTROL_DOMAIN the control plane's hostname
|
|
22
|
+
--operations-host=<host> OPERATIONS_HOSTNAME the Operations ingest hostname
|
|
23
|
+
--iam-host=<host> FABRIKA_IAM_HOSTNAME IAM's hostname; its issuer is https://<host>
|
|
24
|
+
--admins=<email,...> FABRIKA_CONTROL_BOOTSTRAP_ADMINS first admins for the escape hatch
|
|
25
|
+
--auth-methods=<methods> FABRIKA_IAM_OIDC_ENABLED + FABRIKA_IAM_PASSWORD_ENABLED
|
|
26
|
+
--oidc-issuer=<url> FABRIKA_IAM_OIDC_ISSUER default https://accounts.google.com
|
|
27
|
+
--oidc-client-id=<id> FABRIKA_IAM_OIDC_CLIENT_ID absent: a placeholder, human SSO login stays inert
|
|
28
|
+
--human-email-domains=<d,...> FABRIKA_IAM_HUMAN_EMAIL_DOMAINS who may self-provision at login
|
|
29
|
+
--email-provider=<none|resend> FABRIKA_EMAIL_PROVIDER
|
|
30
|
+
--email-from=<sender> FABRIKA_EMAIL_FROM required for resend
|
|
31
|
+
Credentials come from the environment only: CLOUDFLARE_API_TOKEN, FABRIKA_IAM_OIDC_CLIENT_SECRET (a real
|
|
32
|
+
OIDC client), FABRIKA_EMAIL_RESEND_API_KEY (resend). The account's installer env file resumes all of them.
|
|
33
|
+
The env file resumes the account id, the auth methods, the OIDC issuer and client id, the email provider
|
|
34
|
+
and sender, and every credential; the hosts, repository, checkout and admins are not saved. An empty flag
|
|
35
|
+
(such as --oidc-client-id=) counts as absent and falls back to that saved value; to return to the
|
|
36
|
+
placeholder client, remove FABRIKA_IAM_OIDC_CLIENT_ID and FABRIKA_IAM_OIDC_CLIENT_SECRET from the env file.
|
|
37
|
+
init confirms before it goes on with a token it could not verify ("Proceed anyway?"), creates or pushes the repository,
|
|
38
|
+
writes the Environment and triggers the workflow. --yes answers all of them yes; without it, init needs a
|
|
39
|
+
terminal.
|
|
40
|
+
|
|
41
|
+
The pair form deploys the executor then the control plane. The single-component form deploys exactly
|
|
42
|
+
one platform config (IAM, Operations) — the stages a pipeline runs before that pair exists. Both may
|
|
43
|
+
name a platform resource; \`fabrika app deploy\` may not.
|
|
44
|
+
`
|
|
45
|
+
|
|
46
|
+
const deployPlatform = async (argv: readonly string[], forceDryRun: boolean): Promise<void> => {
|
|
47
|
+
const args = parseCloudflareArgs(['platform', 'deploy', ...argv, ...(forceDryRun ? ['--dry-run'] : [])])
|
|
48
|
+
const env = args.env ?? 'prod'
|
|
49
|
+
const stateNamespace = process.env['CLOUDFLARE_STATE_NAMESPACE']
|
|
50
|
+
const rootCwd = process.cwd()
|
|
51
|
+
for (const component of platformComponents(args)) {
|
|
52
|
+
const absolute = resolve(rootCwd, component.configPath)
|
|
53
|
+
const cwd = resolve(absolute, '..')
|
|
54
|
+
process.chdir(cwd)
|
|
55
|
+
try {
|
|
56
|
+
console.info(`\n▸ ${component.label} → ${env}${args.dryRun ? ' (dry-run)' : ''}`)
|
|
57
|
+
// This IS the platform deploying itself; an application deploy through the runner never gets this.
|
|
58
|
+
const result = await deployCloudflareConfig({
|
|
59
|
+
env,
|
|
60
|
+
configPath: absolute,
|
|
61
|
+
cwd,
|
|
62
|
+
dryRun: args.dryRun,
|
|
63
|
+
platformResources: 'allow',
|
|
64
|
+
// Honoured because the scaffolded workflow states it on the IAM stage; absent elsewhere.
|
|
65
|
+
...(stateNamespace === undefined ? {} : { stateNamespace }),
|
|
66
|
+
})
|
|
67
|
+
console.info(`${result.appId} → ${result.env}: ${result.status}`)
|
|
68
|
+
if (result.status === 'failed') {
|
|
69
|
+
throw new Error(`${component.label} deployment failed`)
|
|
70
|
+
}
|
|
71
|
+
} finally {
|
|
72
|
+
process.chdir(rootCwd)
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
const run = async (command: InstallationCommand, argv: readonly string[]): Promise<void> => {
|
|
78
|
+
if (command === 'init') {
|
|
79
|
+
await initCommand(argv)
|
|
80
|
+
return
|
|
81
|
+
}
|
|
82
|
+
if (command !== 'plan' && command !== 'deploy') {
|
|
83
|
+
// The router already gates on `commands`, so this is unreachable today — and it is the branch that
|
|
84
|
+
// keeps it unreachable: without it, a command added to the contract later falls through to a deploy.
|
|
85
|
+
throw new Error(`Cloudflare installation does not support \`platform ${command}\``)
|
|
86
|
+
}
|
|
87
|
+
await deployPlatform(argv, command === 'plan')
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
export const cloudflareInstallationCli: InstallationCli = {
|
|
91
|
+
provider: 'cloudflare',
|
|
92
|
+
commands: ['init', 'plan', 'deploy'],
|
|
93
|
+
usage: USAGE,
|
|
94
|
+
run,
|
|
95
|
+
}
|