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