@fabrika/provider-cloudflare 0.3.1 → 0.3.3

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 CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fabrika/provider-cloudflare",
3
- "version": "0.3.1",
3
+ "version": "0.3.3",
4
4
  "type": "module",
5
5
  "repository": {
6
6
  "type": "git",
@@ -42,11 +42,11 @@
42
42
  },
43
43
  "dependencies": {
44
44
  "zod": "^3.25.76",
45
- "@fabrika/auth": "^0.3.1",
46
- "@fabrika/auth-core": "^0.3.1",
47
- "@fabrika/installation-init": "^0.3.1",
48
- "@fabrika/proxy-core": "^0.3.1",
49
- "@fabrika/provider-contract": "^0.3.1",
45
+ "@fabrika/auth": "^0.3.3",
46
+ "@fabrika/auth-core": "^0.3.3",
47
+ "@fabrika/installation-init": "^0.3.3",
48
+ "@fabrika/proxy-core": "^0.3.3",
49
+ "@fabrika/provider-contract": "^0.3.3",
50
50
  "oblaka-iac": "^0.0.18"
51
51
  }
52
52
  }
@@ -1,14 +1,12 @@
1
1
  /**
2
2
  * Cloudflare API helpers for the fabrika CLI — token verification, account resolution, and zone lookup.
3
- * These run from the operator's laptop against the public CF API with the token the operator just
4
- * pasted; the token VALUE is never logged here (only pass/fail + names).
3
+ * These run from the operator's machine against the public CF API with the token from the environment;
4
+ * the token VALUE is never logged here (only pass/fail + names).
5
5
  *
6
6
  * Local schemas validate the consumed fields while tolerating upstream additions.
7
7
  */
8
8
 
9
- import { required, select } from '@fabrika/installation-init'
10
9
  import { z } from 'zod'
11
- import { fromEnv } from './envfile'
12
10
 
13
11
  const CF_API = 'https://api.cloudflare.com/client/v4'
14
12
  const envelopeSchema = z.object({ success: z.boolean(), result: z.unknown(), errors: z.unknown() })
@@ -108,52 +106,28 @@ export async function listAccounts(token: string): Promise<CfAccount[]> {
108
106
  }
109
107
 
110
108
  /**
111
- * Resolve the CF account to deploy into. If `preferred` is given and valid, use it; if the token can
112
- * act on exactly one account, use it; otherwise prompt the operator to pick. Throws if the token can
113
- * reach no account at all.
109
+ * The CF account to deploy into, from the accounts the token lists. An explicit id wins and does not
110
+ * need to be listed — an account-owned token typically cannot list its own account. Without one, the
111
+ * token must act on exactly one account; otherwise the error names them and the flag that picks one.
114
112
  */
115
- export async function resolveAccountId(token: string, preferred?: string): Promise<CfAccount> {
116
- let accounts: CfAccount[] = []
117
- try {
118
- accounts = await listAccounts(token)
119
- } catch {
120
- accounts = []
121
- }
122
- // An explicit override wins: a `preferred` arg or CLOUDFLARE_ACCOUNT_ID from the environment.
123
- const wanted = preferred !== undefined && preferred !== '' ? preferred : fromEnv('CLOUDFLARE_ACCOUNT_ID')
124
- if (wanted !== undefined && wanted !== '') {
125
- return accounts.find((a) => a.id === wanted) ?? { id: wanted, name: '(from CLOUDFLARE_ACCOUNT_ID)' }
113
+ export function selectAccount(accounts: readonly CfAccount[], accountId: string | undefined): CfAccount {
114
+ if (accountId !== undefined) {
115
+ return accounts.find((a) => a.id === accountId) ?? { id: accountId, name: '(from --account-id / CLOUDFLARE_ACCOUNT_ID)' }
126
116
  }
127
117
  const only = accounts[0]
128
118
  if (accounts.length === 1 && only !== undefined) {
129
119
  return only
130
120
  }
131
121
  if (accounts.length > 1) {
132
- return select(
133
- 'Which Cloudflare account should fabrika deploy into?',
134
- accounts.map((a) => ({ label: `${a.name} (${a.id})`, value: a })),
122
+ throw new Error(
123
+ `the token can act on ${accounts.length} Cloudflare accounts — pick one with --account-id=<id> or CLOUDFLARE_ACCOUNT_ID: `
124
+ + accounts.map((a) => `${a.name} (${a.id})`).join(', '),
135
125
  )
136
126
  }
137
- // The token can't list any account (typical for an account-owned token) — ask for the id directly.
138
- const id = await required('Cloudflare account id (from the dashboard URL / Account Home)')
139
- return { id, name: '(entered)' }
140
- }
141
-
142
- /**
143
- * List the account's zones (`GET /zones?account.id=<id>`), used to SUGGEST a control-plane domain
144
- * (`fabrika.<zone>`). Best-effort: returns [] on any error (the token may lack Zone:Read), so the
145
- * caller then prompts for the domain with no default.
146
- */
147
- export async function listZones(token: string, accountId: string): Promise<CfZone[]> {
148
- try {
149
- const response = await fetch(`${CF_API}/zones?account.id=${encodeURIComponent(accountId)}&per_page=50`, {
150
- headers: authHeaders(token),
151
- })
152
- const result = await cfJson(response, 'Listing zones')
153
- return namedResources(result)
154
- } catch {
155
- return []
156
- }
127
+ throw new Error(
128
+ 'the token lists no Cloudflare account (typical for an account-owned token) — pass --account-id=<id> or set '
129
+ + 'CLOUDFLARE_ACCOUNT_ID to the id in the dashboard URL',
130
+ )
157
131
  }
158
132
 
159
133
  /**
@@ -0,0 +1,326 @@
1
+ // The CLI surface of `fabrika platform init --provider=cloudflare`, parsed once.
2
+ //
3
+ // Every CREDENTIAL comes from the environment and only from the environment; everything else may come
4
+ // from a flag OR the environment variable beside it, flag first. The variables are the names the
5
+ // account's GitHub Environment carries, and the installer env file resumes into them. Nothing here
6
+ // prompts — a missing required value is an error naming both the flag and the variable — so a
7
+ // pipeline or an agent drives init end to end. Its confirmations stay, answered by `--yes`.
8
+
9
+ import {
10
+ CHECKOUT_FLAG,
11
+ type CommandEnv,
12
+ readEnv,
13
+ readFlag,
14
+ requiredSetting,
15
+ setting,
16
+ shellWord,
17
+ sidecarCheckoutDir,
18
+ UNATTENDED_FLAG,
19
+ } from '@fabrika/installation-init'
20
+ import { z } from 'zod'
21
+
22
+ /**
23
+ * Placeholder OIDC — the client id an operator gets by naming none, to bring the base up BEFORE wiring
24
+ * a real SSO provider. IAM boots, machine auth and the bootstrap-admin hatch work; only human SSO login
25
+ * is inert until a real `FABRIKA_IAM_OIDC_CLIENT_ID`/`_SECRET` replace these. The issuer stays a real
26
+ * discoverable host so IAM's OIDC discovery doesn't fail at boot.
27
+ */
28
+ export const PLACEHOLDER_OIDC_CLIENT_ID = 'placeholder.apps.googleusercontent.com'
29
+ export const PLACEHOLDER_OIDC_CLIENT_SECRET = 'placeholder-oidc-client-secret-rotate-when-sso-wired'
30
+ const DEFAULT_OIDC_ISSUER = 'https://accounts.google.com'
31
+
32
+ export interface OidcInput {
33
+ readonly issuer: string
34
+ /** `PLACEHOLDER_OIDC_CLIENT_ID` when the operator deferred real SSO. */
35
+ readonly clientId: string
36
+ /** Environment only. The placeholder secret pairs with the placeholder client id. */
37
+ readonly clientSecret: string
38
+ /** Email domains admitted as a human at IAM login (self-provisioning allowlist). */
39
+ readonly humanEmailDomains: readonly string[]
40
+ }
41
+
42
+ export type EmailInput =
43
+ | { readonly provider: 'none' }
44
+ | { readonly provider: 'resend'; readonly from: string; /** Environment only. */ readonly apiKey: string }
45
+
46
+ /** Every input `runInit` takes from the operator. */
47
+ export interface InitInput {
48
+ /** Names the GitHub Environment, the installer env file, the default repository and checkout. */
49
+ readonly account: string
50
+ /** Absent: the one account the token can act on. */
51
+ readonly accountId?: string
52
+ /** The Cloudflare account API token. Environment only. */
53
+ readonly apiToken: string
54
+ readonly repo: string
55
+ /** The absolute local checkout directory of `repo`. */
56
+ readonly checkout: string
57
+ readonly hosts: { readonly control: string; readonly operations: string; readonly iam: string }
58
+ /** Absent when OIDC login is not enabled. */
59
+ readonly oidc?: OidcInput
60
+ readonly passwordEnabled: boolean
61
+ readonly email: EmailInput
62
+ /** First-admin emails for the escape hatch, admitted to both control and IAM. */
63
+ readonly bootstrapAdmins: readonly string[]
64
+ /** `--yes`: answer every confirmation yes. */
65
+ readonly unattended: boolean
66
+ }
67
+
68
+ const FLAGS = [
69
+ '--account-id',
70
+ '--repo',
71
+ '--console-host',
72
+ '--operations-host',
73
+ '--iam-host',
74
+ '--admins',
75
+ '--auth-methods',
76
+ '--oidc-issuer',
77
+ '--oidc-client-id',
78
+ '--human-email-domains',
79
+ '--email-provider',
80
+ '--email-from',
81
+ CHECKOUT_FLAG,
82
+ ] as const
83
+
84
+ const REPO_PATTERN = /^[^/\s]+\/[^/\s]+$/
85
+
86
+ const AUTH_METHODS = ['oidc', 'password'] as const
87
+
88
+ const assertKnownArguments = (argv: readonly string[]): void => {
89
+ for (const arg of argv) {
90
+ if (arg === UNATTENDED_FLAG || !arg.startsWith('-')) {
91
+ continue
92
+ }
93
+ const name = arg.split('=')[0] ?? arg
94
+ if (!FLAGS.some((flag) => flag === name) || !arg.includes('=')) {
95
+ throw new Error(
96
+ `unexpected argument \`${name}\`${
97
+ arg.includes('=') ? ' (its value is not shown)' : ''
98
+ }. Credentials are read from the environment and have no flag; run `
99
+ + '`fabrika platform init --provider=cloudflare --help` for the surface',
100
+ )
101
+ }
102
+ }
103
+ }
104
+
105
+ /**
106
+ * The account name, after refusing any argument init does not know.
107
+ *
108
+ * Read on its own because the installer env file is named after it, and that file has to be loaded
109
+ * before the rest is parsed: a resumed run reads its earlier answers from it.
110
+ */
111
+ export const parseInitAccount = (argv: readonly string[]): string => {
112
+ assertKnownArguments(argv)
113
+ const positional = argv.filter((arg) => !arg.startsWith('-')).map((arg) => arg.trim())
114
+ if (positional.length > 1) {
115
+ throw new Error('unexpected second positional argument (its value is not shown): name ONE account')
116
+ }
117
+ const account = positional[0]
118
+ if (account === undefined || account === '') {
119
+ throw new Error('Cloudflare installation init requires an account name, for example `fabrika platform init --provider=cloudflare acme`')
120
+ }
121
+ return account
122
+ }
123
+
124
+ /** A credential, with the one message that says why there is no flag for it. */
125
+ const credential = (env: CommandEnv, variable: string, what: string): string => {
126
+ const value = readEnv(env, variable)
127
+ if (value === undefined) {
128
+ throw new Error(`${variable} is required: ${what}. It has no flag — a credential on a command line lands in logs and shell history`)
129
+ }
130
+ return value
131
+ }
132
+
133
+ /** A bare hostname: no scheme, path, port or credentials. */
134
+ const checkedHost = (value: string, flag: string, variable: string): string => {
135
+ const host = value.toLowerCase()
136
+ const parsed = URL.canParse(`https://${host}`) ? new URL(`https://${host}`) : undefined
137
+ if (parsed === undefined || parsed.hostname !== host || parsed.pathname !== '/' || !host.includes('.')) {
138
+ throw new Error(`${flag} / ${variable} must be a bare hostname such as iam.example.com, not \`${value}\``)
139
+ }
140
+ return host
141
+ }
142
+
143
+ const requiredHost = (argv: readonly string[], env: CommandEnv, flag: string, variable: string): string =>
144
+ checkedHost(requiredSetting(setting(argv, env, flag, variable), flag, variable), flag, variable)
145
+
146
+ const listSchema = z.array(z.string())
147
+
148
+ /** A comma-separated list, or the JSON array the GitHub Environment stores under the same variable. */
149
+ const parseList = (raw: string | undefined, flag: string, variable: string): string[] => {
150
+ if (raw === undefined) return []
151
+ if (!raw.startsWith('[')) return raw.split(',').map((item) => item.trim()).filter((item) => item !== '')
152
+ let decoded: unknown
153
+ try {
154
+ decoded = JSON.parse(raw)
155
+ } catch {
156
+ decoded = undefined
157
+ }
158
+ const parsed = listSchema.safeParse(decoded)
159
+ if (!parsed.success) {
160
+ throw new Error(`${flag} / ${variable} must be a comma-separated list or a JSON array of strings`)
161
+ }
162
+ return parsed.data.map((item) => item.trim()).filter((item) => item !== '')
163
+ }
164
+
165
+ const parseBoolean = (value: string, name: string): boolean => {
166
+ if (value === 'true') return true
167
+ if (value === 'false') return false
168
+ throw new Error(`${name} must be true or false`)
169
+ }
170
+
171
+ interface AuthMethods {
172
+ readonly oidcEnabled: boolean
173
+ readonly passwordEnabled: boolean
174
+ }
175
+
176
+ /** `--auth-methods`, or the pair of switches the Environment carries. */
177
+ const readAuthMethods = (argv: readonly string[], env: CommandEnv): AuthMethods => {
178
+ const flag = readFlag(argv, '--auth-methods')
179
+ if (flag !== undefined) {
180
+ const methods = flag.split(',').map((item) => item.trim())
181
+ const unknown = methods.find((method) => !AUTH_METHODS.some((known) => known === method))
182
+ if (unknown !== undefined || methods.length > AUTH_METHODS.length) {
183
+ throw new Error(`--auth-methods takes oidc, password, or oidc,password — not \`${flag}\``)
184
+ }
185
+ return { oidcEnabled: methods.includes('oidc'), passwordEnabled: methods.includes('password') }
186
+ }
187
+ const oidc = readEnv(env, 'FABRIKA_IAM_OIDC_ENABLED')
188
+ const password = readEnv(env, 'FABRIKA_IAM_PASSWORD_ENABLED')
189
+ if (oidc === undefined && password === undefined) {
190
+ throw new Error('--auth-methods=<oidc|password|oidc,password> or FABRIKA_IAM_OIDC_ENABLED + FABRIKA_IAM_PASSWORD_ENABLED is required')
191
+ }
192
+ if (oidc === undefined || password === undefined) {
193
+ throw new Error('FABRIKA_IAM_OIDC_ENABLED and FABRIKA_IAM_PASSWORD_ENABLED must be configured together')
194
+ }
195
+ const methods = {
196
+ oidcEnabled: parseBoolean(oidc, 'FABRIKA_IAM_OIDC_ENABLED'),
197
+ passwordEnabled: parseBoolean(password, 'FABRIKA_IAM_PASSWORD_ENABLED'),
198
+ }
199
+ if (!methods.oidcEnabled && !methods.passwordEnabled) {
200
+ throw new Error('At least one IAM authentication method must be enabled')
201
+ }
202
+ return methods
203
+ }
204
+
205
+ /** A flag that only means something under a selection the run did not make is refused, not ignored. */
206
+ const refuseFlags = (argv: readonly string[], flags: readonly string[], why: string): void => {
207
+ const given = flags.find((flag) => readFlag(argv, flag) !== undefined)
208
+ if (given !== undefined) {
209
+ throw new Error(`${given} was given, but ${why}`)
210
+ }
211
+ }
212
+
213
+ const readOidc = (argv: readonly string[], env: CommandEnv): OidcInput => {
214
+ const issuer = setting(argv, env, '--oidc-issuer', 'FABRIKA_IAM_OIDC_ISSUER') ?? DEFAULT_OIDC_ISSUER
215
+ if (!URL.canParse(issuer)) {
216
+ throw new Error(`--oidc-issuer / FABRIKA_IAM_OIDC_ISSUER is not a URL: \`${issuer}\``)
217
+ }
218
+ const clientId = setting(argv, env, '--oidc-client-id', 'FABRIKA_IAM_OIDC_CLIENT_ID') ?? PLACEHOLDER_OIDC_CLIENT_ID
219
+ const humanEmailDomains = parseList(
220
+ setting(argv, env, '--human-email-domains', 'FABRIKA_IAM_HUMAN_EMAIL_DOMAINS'),
221
+ '--human-email-domains',
222
+ 'FABRIKA_IAM_HUMAN_EMAIL_DOMAINS',
223
+ )
224
+ if (clientId === PLACEHOLDER_OIDC_CLIENT_ID) {
225
+ return {
226
+ issuer,
227
+ clientId,
228
+ clientSecret: readEnv(env, 'FABRIKA_IAM_OIDC_CLIENT_SECRET') ?? PLACEHOLDER_OIDC_CLIENT_SECRET,
229
+ humanEmailDomains,
230
+ }
231
+ }
232
+ const clientSecret = credential(env, 'FABRIKA_IAM_OIDC_CLIENT_SECRET', `the OIDC client secret for client ${clientId}`)
233
+ if (clientSecret === PLACEHOLDER_OIDC_CLIENT_SECRET) {
234
+ throw new Error(
235
+ `FABRIKA_IAM_OIDC_CLIENT_SECRET still holds the placeholder secret, but client ${clientId} is a real one. `
236
+ + 'Set the real secret in the environment',
237
+ )
238
+ }
239
+ return { issuer, clientId, clientSecret, humanEmailDomains }
240
+ }
241
+
242
+ const readEmail = (argv: readonly string[], env: CommandEnv): EmailInput => {
243
+ const provider = requiredSetting(setting(argv, env, '--email-provider', 'FABRIKA_EMAIL_PROVIDER'), '--email-provider', 'FABRIKA_EMAIL_PROVIDER')
244
+ if (provider === 'none') {
245
+ refuseFlags(argv, ['--email-from'], 'the email provider is none')
246
+ return { provider }
247
+ }
248
+ if (provider !== 'resend') {
249
+ throw new Error(`--email-provider / FABRIKA_EMAIL_PROVIDER must be none or resend, not \`${provider}\``)
250
+ }
251
+ return {
252
+ provider,
253
+ from: requiredSetting(setting(argv, env, '--email-from', 'FABRIKA_EMAIL_FROM'), '--email-from', 'FABRIKA_EMAIL_FROM'),
254
+ apiKey: credential(env, 'FABRIKA_EMAIL_RESEND_API_KEY', 'the Resend API key the email transport sends with'),
255
+ }
256
+ }
257
+
258
+ const readRepo = (argv: readonly string[], account: string): string => {
259
+ const repo = readFlag(argv, '--repo')
260
+ if (repo === undefined) {
261
+ return `${account}/fabrika-platform`
262
+ }
263
+ if (!REPO_PATTERN.test(repo)) {
264
+ throw new Error(`\`${repo}\` is not a <owner>/<name> repository`)
265
+ }
266
+ return repo
267
+ }
268
+
269
+ /**
270
+ * Parse the command's arguments and environment into the one input `runInit` takes.
271
+ *
272
+ * `env` must already hold the installer env file's values (`openEnvFile`), so a resumed run reuses them.
273
+ */
274
+ export const parseInitArgs = (argv: readonly string[], env: CommandEnv, cwd: string = process.cwd()): InitInput => {
275
+ const account = parseInitAccount(argv)
276
+ const methods = readAuthMethods(argv, env)
277
+ const accountId = setting(argv, env, '--account-id', 'CLOUDFLARE_ACCOUNT_ID')
278
+ if (!methods.oidcEnabled) {
279
+ refuseFlags(argv, ['--oidc-issuer', '--oidc-client-id', '--human-email-domains'], 'OIDC is not among the IAM authentication methods')
280
+ }
281
+ return {
282
+ account,
283
+ apiToken: credential(env, 'CLOUDFLARE_API_TOKEN', "the Cloudflare account API token; it also becomes the control plane's runtime token"),
284
+ repo: readRepo(argv, account),
285
+ checkout: sidecarCheckoutDir(readFlag(argv, CHECKOUT_FLAG), `fabrika-platform-${account}`, cwd),
286
+ hosts: {
287
+ control: requiredHost(argv, env, '--console-host', 'FABRIKA_CONTROL_DOMAIN'),
288
+ operations: requiredHost(argv, env, '--operations-host', 'OPERATIONS_HOSTNAME'),
289
+ iam: requiredHost(argv, env, '--iam-host', 'FABRIKA_IAM_HOSTNAME'),
290
+ },
291
+ passwordEnabled: methods.passwordEnabled,
292
+ email: readEmail(argv, env),
293
+ bootstrapAdmins: parseList(
294
+ setting(argv, env, '--admins', 'FABRIKA_CONTROL_BOOTSTRAP_ADMINS'),
295
+ '--admins',
296
+ 'FABRIKA_CONTROL_BOOTSTRAP_ADMINS',
297
+ ),
298
+ unattended: argv.includes(UNATTENDED_FLAG),
299
+ ...(methods.oidcEnabled ? { oidc: readOidc(argv, env) } : {}),
300
+ ...(accountId === undefined ? {} : { accountId }),
301
+ }
302
+ }
303
+
304
+ /** The command that repeats this run, with every value but the credentials, which stay in the environment. */
305
+ export const rerunCommand = (input: InitInput, accountId: string): string =>
306
+ [
307
+ 'fabrika platform init --provider=cloudflare',
308
+ ...[
309
+ input.account,
310
+ `--account-id=${accountId}`,
311
+ `--repo=${input.repo}`,
312
+ `--console-host=${input.hosts.control}`,
313
+ `--operations-host=${input.hosts.operations}`,
314
+ `--iam-host=${input.hosts.iam}`,
315
+ `--auth-methods=${[...(input.oidc === undefined ? [] : ['oidc']), ...(input.passwordEnabled ? ['password'] : [])].join(',')}`,
316
+ ...(input.oidc === undefined ? [] : [
317
+ `--oidc-issuer=${input.oidc.issuer}`,
318
+ ...(input.oidc.clientId === PLACEHOLDER_OIDC_CLIENT_ID ? [] : [`--oidc-client-id=${input.oidc.clientId}`]),
319
+ ...(input.oidc.humanEmailDomains.length === 0 ? [] : [`--human-email-domains=${input.oidc.humanEmailDomains.join(',')}`]),
320
+ ]),
321
+ `--email-provider=${input.email.provider}`,
322
+ ...(input.email.provider === 'resend' ? [`--email-from=${input.email.from}`] : []),
323
+ ...(input.bootstrapAdmins.length === 0 ? [] : [`--admins=${input.bootstrapAdmins.join(',')}`]),
324
+ `${CHECKOUT_FLAG}=${input.checkout}`,
325
+ ].map(shellWord),
326
+ ].join(' ')
@@ -1,10 +1,13 @@
1
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.
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
6
  *
7
- * Order: CF token → account + zones → smart-default prompts → vault key → provisioning key → runner key →
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 →
8
11
  * scaffold the base repo → write the GitHub Environment → trigger. Secret VALUES flow only into the env
9
12
  * file, `gh` over stdin, and child env — never through `log.ts`. GitHub source connections are made later
10
13
  * from the console (ADR-0029); init creates no GitHub App.
@@ -14,25 +17,24 @@ import {
14
17
  action,
15
18
  branchProtectionCommand,
16
19
  configureEnvironment,
17
- confirm,
20
+ type Confirmations,
21
+ confirmations,
18
22
  detail,
23
+ type EnvironmentConfig,
24
+ ghRepoExists,
19
25
  info,
20
26
  ok,
21
27
  type ProtectionOutcome,
22
- retry,
23
- secret,
24
- secretOrEnv,
25
- select,
26
28
  step,
27
- text,
28
29
  triggerPlatformWorkflow,
29
30
  url,
30
31
  warn,
31
32
  } from '@fabrika/installation-init'
32
33
  import { createHash, generateKeyPairSync, randomBytes } from 'node:crypto'
33
- import { findZone, listZones, resolveAccountId, verifyToken } from './cloudflare'
34
+ import { type CfAccount, type CfZone, findZone, listAccounts, selectAccount, verifyToken } from './cloudflare'
34
35
  import { envPath, fromEnv, openEnvFile, persistEnv } from './envfile'
35
- import { defaultCheckoutDir, readFabrikaRef, scaffoldPlatformRepo } from './scaffold'
36
+ import { type InitInput, parseInitAccount, parseInitArgs, PLACEHOLDER_OIDC_CLIENT_ID, rerunCommand } from './init-options'
37
+ import { readFabrikaRef, type ScaffoldInput, scaffoldPlatformRepo, type ScaffoldResult } from './scaffold'
36
38
 
37
39
  /** Everything collected before the scaffold + environment write. */
38
40
  export interface Collected {
@@ -58,14 +60,6 @@ export interface Collected {
58
60
  bootstrapAdmins: string[]
59
61
  }
60
62
 
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
63
  const ENVIRONMENT_SOURCE: Readonly<Record<string, string | undefined>> = process.env
70
64
 
71
65
  /** A resume read off an injectable source, with fromEnv's empty-string-is-absent semantics. */
@@ -74,71 +68,68 @@ export function readResumeValue(source: Readonly<Record<string, string | undefin
74
68
  return value === undefined || value === '' ? undefined : value
75
69
  }
76
70
 
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
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>
98
82
  }
99
83
 
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
84
+ export interface InitCollaborators {
85
+ readonly prompts: Confirmations
86
+ readonly effects: InitEffects
108
87
  }
109
88
 
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> {
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)
118
92
  console.log(`\nfabrika platform init — bring up the ${account} Cloudflare control-plane base\n`)
119
-
120
93
  step('Open the installer env file')
121
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
+ }
122
98
 
123
- const collected = await collect(account)
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)
124
106
  const vaultKey = await ensureVaultKey()
125
107
  const provisioning = await ensureProvisioningKey()
126
108
  const operationsSyncKey = await ensureOperationsSyncKey()
127
109
  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
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
132
112
  const runnerKey = await ensureRunnerKey()
133
113
 
134
- const { dir, branchProtection } = await scaffoldPlatformRepo({
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({
135
126
  repo: collected.platformRepo,
136
127
  account: collected.account,
137
- dir: defaultCheckoutDir(collected.account),
128
+ dir: input.checkout,
138
129
  })
139
- let environmentPolicy: ProtectionOutcome | undefined
140
130
 
141
- await configureEnvironment({
131
+ let environmentPolicy: ProtectionOutcome | undefined
132
+ const environment: EnvironmentConfig = {
142
133
  repo: collected.platformRepo,
143
134
  environment: collected.account,
144
135
  onProtection: (outcome) => {
@@ -153,9 +144,19 @@ export async function runInit(account: string): Promise<void> {
153
144
  ...(oidcClientSecret === undefined ? {} : { oidcClientSecret }),
154
145
  ...(emailApiKey === undefined ? {} : { emailApiKey }),
155
146
  }),
156
- })
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)
157
158
 
158
- await triggerDeploy(collected.platformRepo)
159
+ await triggerDeploy(collected.platformRepo, collaborators)
159
160
  finalNotes({
160
161
  repo: collected.platformRepo,
161
162
  account: collected.account,
@@ -168,6 +169,28 @@ export async function runInit(account: string): Promise<void> {
168
169
  })
169
170
  }
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
+
171
194
  /** Everything `init` generated or fetched, ready to be split into the Environment's two halves. */
172
195
  export interface GeneratedInstallation {
173
196
  readonly vaultKey: string
@@ -225,132 +248,90 @@ export function environmentPayload(
225
248
  }
226
249
  }
227
250
 
228
- /** Collect the CF token + account, then the smart-default prompts. */
229
- async function collect(account: string): Promise<Collected> {
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> {
230
257
  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
- }
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
244
271
  }
245
- return { apiToken, cfAccount }
246
- })
247
- const { apiToken, cfAccount } = verified
272
+ }
248
273
  ok(`Account: ${cfAccount.name} (${cfAccount.id})`)
249
- await persistEnv('CLOUDFLARE_API_TOKEN', apiToken)
274
+ await persistEnv('CLOUDFLARE_API_TOKEN', input.apiToken)
250
275
  await persistEnv('CLOUDFLARE_ACCOUNT_ID', cfAccount.id)
276
+ return cfAccount
277
+ }
251
278
 
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)
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)
260
282
  if (zone === null) {
261
- warn(`No Cloudflare zone found for ${controlPlaneDomain} — a custom-domain bind would fail. Add the zone before the deploy.`)
283
+ warn(`No Cloudflare zone found for ${hostname} — ${consequence}`)
262
284
  } else {
263
285
  ok(`Zone found: ${zone.name}`)
264
286
  }
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.`)
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.')
272
299
  } else {
273
- ok(`Zone found: ${operationsZone.name}`)
300
+ ok(`First admins: ${input.bootstrapAdmins.join(', ')}`)
274
301
  }
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
302
 
287
- // IAM Stage 1 config: select independent authentication methods, then ask only for the
288
- // provider-specific values that the selection needs.
289
303
  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 === '') {
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
311
  warn('Placeholder OIDC — human SSO login is inert until you set real FABRIKA_IAM_OIDC_CLIENT_ID + _SECRET.')
312
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)
313
+ await persistEnv('FABRIKA_IAM_OIDC_CLIENT_ID', oidc.clientId)
317
314
  }
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)
315
+ await persistEnv('FABRIKA_EMAIL_PROVIDER', input.email.provider)
316
+ if (input.email.provider === 'resend') await persistEnv('FABRIKA_EMAIL_FROM', input.email.from)
336
317
 
337
318
  return {
338
- account,
319
+ account: input.account,
339
320
  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,
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],
354
335
  }
355
336
  }
356
337
 
@@ -476,56 +457,37 @@ async function ensureSigningKeys(): Promise<string> {
476
457
  }
477
458
 
478
459
  /**
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.
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.
482
462
  */
483
- async function ensureOidcClientSecret(placeholder: boolean): Promise<string> {
463
+ async function ensureOidcClientSecret(value: string): Promise<string> {
484
464
  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
465
  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.')
466
+ ok('OIDC client secret saved to the installer env file.')
494
467
  return value
495
468
  }
496
469
 
497
- /** Resolve the Resend API key without ever writing it to user-facing output. */
498
- async function ensureResendApiKey(): Promise<string> {
470
+ /** Persist the Resend API key without ever writing it to user-facing output. */
471
+ async function ensureResendApiKey(value: string): Promise<string> {
499
472
  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
473
  await persistEnv('FABRIKA_EMAIL_RESEND_API_KEY', value)
511
474
  ok('Resend API key saved to the installer env file.')
512
475
  return value
513
476
  }
514
477
 
515
478
  /** Trigger the platform workflow (each deploy builds the runner image into this account's registry). */
516
- async function triggerDeploy(repo: string): Promise<void> {
479
+ async function triggerDeploy(repo: string, { prompts, effects }: InitCollaborators): Promise<void> {
517
480
  step('Trigger the platform deploy (GitHub Actions)')
518
481
  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) {
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))) {
522
484
  action('OPERATOR ACTION — run it when ready', [
523
485
  `gh workflow run platform.yml --repo ${repo}`,
524
486
  `or: ${url(`https://github.com/${repo}/actions`)} → platform → Run workflow`,
525
487
  ])
526
488
  return
527
489
  }
528
- await triggerPlatformWorkflow(repo)
490
+ await effects.triggerWorkflow(repo)
529
491
  ok('Platform workflow triggered.')
530
492
  detail(`Watch: ${url(`https://github.com/${repo}/actions`)} (or: gh run watch --repo ${repo})`)
531
493
  }
@@ -2,17 +2,42 @@ import type { InstallationCli, InstallationCommand } from '@fabrika/provider-con
2
2
  import { resolve } from 'node:path'
3
3
  import { parseCloudflareArgs, platformComponents } from '../cli-args'
4
4
  import { deployCloudflareConfig } from '../command'
5
- import { runInit } from './init'
5
+ import { initCommand } from './init'
6
6
 
7
7
  const USAGE = `Cloudflare installation
8
8
 
9
9
  Commands:
10
- fabrika platform init --provider=cloudflare <account>
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]
11
12
  fabrika platform plan --provider=cloudflare --runner-config=<path> --worker-config=<path> [--env=<env>]
12
13
  fabrika platform deploy --provider=cloudflare --runner-config=<path> --worker-config=<path> [--env=<env>]
13
14
  fabrika platform plan --provider=cloudflare --component-config=<path> [--env=<env>]
14
15
  fabrika platform deploy --provider=cloudflare --component-config=<path> [--env=<env>]
15
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
+
16
41
  The pair form deploys the executor then the control plane. The single-component form deploys exactly
17
42
  one platform config (IAM, Operations) — the stages a pipeline runs before that pair exists. Both may
18
43
  name a platform resource; \`fabrika app deploy\` may not.
@@ -51,14 +76,7 @@ const deployPlatform = async (argv: readonly string[], forceDryRun: boolean): Pr
51
76
 
52
77
  const run = async (command: InstallationCommand, argv: readonly string[]): Promise<void> => {
53
78
  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)
79
+ await initCommand(argv)
62
80
  return
63
81
  }
64
82
  if (command !== 'plan' && command !== 'deploy') {
@@ -91,11 +91,6 @@ export async function scaffoldPlatformRepo(input: ScaffoldInput): Promise<Scaffo
91
91
  })
92
92
  }
93
93
 
94
- /** The default local checkout dir for an account: `./fabrika-platform-<account>` under the cwd. */
95
- export function defaultCheckoutDir(account: string): string {
96
- return resolve(process.cwd(), `fabrika-platform-${account}`)
97
- }
98
-
99
94
  /** Read the configured `fabrika.ref` (for display), or 'main' when absent. Used in the final summary. */
100
95
  export async function readFabrikaRef(dir: string): Promise<string> {
101
96
  const file = Bun.file(resolve(dir, 'fabrika.ref'))
@@ -37,7 +37,15 @@ a safe redeploy.
37
37
 
38
38
  ## First bring-up
39
39
 
40
- Run `fabrika platform init --provider=cloudflare {{ACCOUNT}}` from a laptop with the Cloudflare API token in hand. It creates this repo,
40
+ Run init with the Cloudflare API token in `CLOUDFLARE_API_TOKEN`:
41
+
42
+ ```sh
43
+ fabrika platform init --provider=cloudflare {{ACCOUNT}} \
44
+ --console-host=<host> --operations-host=<host> --iam-host=<host> \
45
+ --auth-methods=<oidc|password|oidc,password> --email-provider=<none|resend>
46
+ ```
47
+
48
+ `fabrika platform init --provider=cloudflare --help` lists the optional flags. It creates this repo,
41
49
  the Environment with its secrets and variables, and triggers the workflow. The run builds and pushes the
42
50
  runner container image into the account.
43
51