@fabrika/provider-cloudflare 0.2.0 → 0.3.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +12 -8
- package/src/cli.ts +7 -8
- package/src/codec.ts +4 -57
- package/src/collaborators.ts +11 -6
- package/src/command.ts +16 -34
- package/src/control.ts +237 -119
- package/src/index.ts +5 -5
- package/src/installation/cloudflare.ts +158 -0
- package/src/installation/envfile.ts +180 -0
- package/src/installation/index.ts +2 -0
- package/src/installation/init-options.ts +326 -0
- package/src/installation/init.ts +559 -0
- package/src/installation/installation.ts +95 -0
- package/src/installation/scaffold.ts +101 -0
- package/src/installation/templates/README.md +72 -0
- package/src/installation/templates/fabrika.ref +1 -0
- package/src/installation/templates/gitignore +2 -0
- package/src/installation/templates/platform.yml +181 -0
- package/src/plan.ts +21 -31
- package/src/provider.ts +90 -70
- package/src/proxy-worker.ts +1 -1
- package/src/proxy.ts +1 -1
- package/src/runner-protocol.ts +40 -0
- package/src/schema.ts +21 -83
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Cloudflare API helpers for the fabrika CLI — token verification, account resolution, and zone lookup.
|
|
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
|
+
*
|
|
6
|
+
* Local schemas validate the consumed fields while tolerating upstream additions.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import { z } from 'zod'
|
|
10
|
+
|
|
11
|
+
const CF_API = 'https://api.cloudflare.com/client/v4'
|
|
12
|
+
const envelopeSchema = z.object({ success: z.boolean(), result: z.unknown(), errors: z.unknown() })
|
|
13
|
+
const errorSchema = z.object({ message: z.string() })
|
|
14
|
+
const tokenSchema = z.object({ status: z.literal('active') })
|
|
15
|
+
const namedResourceSchema = z.object({ id: z.string(), name: z.string() })
|
|
16
|
+
const entriesSchema = z.array(z.unknown())
|
|
17
|
+
|
|
18
|
+
function namedResources(value: unknown): CfAccount[] {
|
|
19
|
+
const entries = entriesSchema.safeParse(value)
|
|
20
|
+
if (!entries.success) return []
|
|
21
|
+
return entries.data.flatMap((entry) => {
|
|
22
|
+
const parsed = namedResourceSchema.safeParse(entry)
|
|
23
|
+
return parsed.success ? [parsed.data] : []
|
|
24
|
+
})
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** The CF account picked for this deploy (id + human name, for display). */
|
|
28
|
+
export interface CfAccount {
|
|
29
|
+
id: string
|
|
30
|
+
name: string
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** A resolved CF zone (registrable domain). */
|
|
34
|
+
export interface CfZone {
|
|
35
|
+
id: string
|
|
36
|
+
name: string
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** The first `errors[].message` from a CF envelope, or undefined — for a readable failure message. */
|
|
40
|
+
function firstErrorMessage(value: unknown): string | undefined {
|
|
41
|
+
const errors = entriesSchema.safeParse(value)
|
|
42
|
+
if (!errors.success) {
|
|
43
|
+
return undefined
|
|
44
|
+
}
|
|
45
|
+
for (const entry of errors.data) {
|
|
46
|
+
const parsed = errorSchema.safeParse(entry)
|
|
47
|
+
if (parsed.success) {
|
|
48
|
+
return parsed.data.message
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
return undefined
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* Parse the uniform CF envelope `{ success, result, errors }`, throwing a short message (never the
|
|
56
|
+
* token) on a non-2xx / `success:false`. Returns the `result` field as `unknown` for the caller to
|
|
57
|
+
* narrow. All field access is runtime-checked — no casts.
|
|
58
|
+
*/
|
|
59
|
+
async function cfJson(response: Response, what: string): Promise<unknown> {
|
|
60
|
+
const parsed = envelopeSchema.safeParse(await response.json().catch(() => null))
|
|
61
|
+
if (!parsed.success) {
|
|
62
|
+
throw new Error(`${what}: unexpected Cloudflare response (HTTP ${response.status}).`)
|
|
63
|
+
}
|
|
64
|
+
const body = parsed.data
|
|
65
|
+
if (!response.ok || !body.success) {
|
|
66
|
+
throw new Error(`${what} failed: ${firstErrorMessage(body.errors) ?? `HTTP ${response.status}`}`)
|
|
67
|
+
}
|
|
68
|
+
return body.result
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** Authorization header for the token. Kept local so the value never leaks into a log statement. */
|
|
72
|
+
function authHeaders(token: string): Record<string, string> {
|
|
73
|
+
return { Authorization: `Bearer ${token}` }
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* Best-effort token liveness check → true iff Cloudflare reports the token `active`. Tries the
|
|
78
|
+
* ACCOUNT-scoped endpoint first when an account id is known: an ACCOUNT-OWNED token is NOT visible to
|
|
79
|
+
* `/user/tokens/verify` (which returns "Invalid API Token" for it) — only `/accounts/<id>/tokens/verify`
|
|
80
|
+
* sees it — then falls back to the user endpoint. NEVER throws: a `false` means "couldn't confirm", and
|
|
81
|
+
* the caller decides whether to proceed (the real deploy is the ultimate check).
|
|
82
|
+
*/
|
|
83
|
+
export async function verifyToken(token: string, accountId?: string): Promise<boolean> {
|
|
84
|
+
const endpoints = accountId !== undefined && accountId !== ''
|
|
85
|
+
? [`${CF_API}/accounts/${accountId}/tokens/verify`, `${CF_API}/user/tokens/verify`]
|
|
86
|
+
: [`${CF_API}/user/tokens/verify`]
|
|
87
|
+
for (const endpoint of endpoints) {
|
|
88
|
+
try {
|
|
89
|
+
const response = await fetch(endpoint, { headers: authHeaders(token) })
|
|
90
|
+
const result = await cfJson(response, 'Token verification')
|
|
91
|
+
if (tokenSchema.safeParse(result).success) {
|
|
92
|
+
return true
|
|
93
|
+
}
|
|
94
|
+
} catch {
|
|
95
|
+
// Not fatal — the token may simply be the wrong TYPE for this endpoint; try the next.
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
return false
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/** List the accounts the token can act on: `GET /accounts`. */
|
|
102
|
+
export async function listAccounts(token: string): Promise<CfAccount[]> {
|
|
103
|
+
const response = await fetch(`${CF_API}/accounts`, { headers: authHeaders(token) })
|
|
104
|
+
const result = await cfJson(response, 'Listing accounts')
|
|
105
|
+
return namedResources(result)
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/**
|
|
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.
|
|
112
|
+
*/
|
|
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)' }
|
|
116
|
+
}
|
|
117
|
+
const only = accounts[0]
|
|
118
|
+
if (accounts.length === 1 && only !== undefined) {
|
|
119
|
+
return only
|
|
120
|
+
}
|
|
121
|
+
if (accounts.length > 1) {
|
|
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(', '),
|
|
125
|
+
)
|
|
126
|
+
}
|
|
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
|
+
)
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/**
|
|
134
|
+
* Best-effort zone lookup for the registrable domain of `hostname`. Naively takes the last two
|
|
135
|
+
* dot-labels (e.g. `fabrika.example.com` → `example.com`) and queries `GET /zones?name=<domain>`.
|
|
136
|
+
* Returns the zone or null. The CLI WARNS on null (a custom-domain bind needs the zone) but never
|
|
137
|
+
* fails on it — the operator may add the zone before the real deploy.
|
|
138
|
+
*/
|
|
139
|
+
export async function findZone(token: string, hostname: string): Promise<CfZone | null> {
|
|
140
|
+
const domain = registrableDomain(hostname)
|
|
141
|
+
const response = await fetch(`${CF_API}/zones?name=${encodeURIComponent(domain)}`, { headers: authHeaders(token) })
|
|
142
|
+
const result = await cfJson(response, 'Zone lookup')
|
|
143
|
+
const entries = entriesSchema.safeParse(result)
|
|
144
|
+
if (!entries.success) {
|
|
145
|
+
return null
|
|
146
|
+
}
|
|
147
|
+
const first = namedResourceSchema.safeParse(entries.data[0])
|
|
148
|
+
return first.success ? first.data : null
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/** Naive registrable-domain derivation: the last two dot-labels of a hostname. */
|
|
152
|
+
function registrableDomain(hostname: string): string {
|
|
153
|
+
const labels = hostname.split('.').filter(Boolean)
|
|
154
|
+
if (labels.length <= 2) {
|
|
155
|
+
return labels.join('.')
|
|
156
|
+
}
|
|
157
|
+
return labels.slice(-2).join('.')
|
|
158
|
+
}
|
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Resume support: persist captured secrets to a per-account env file, so an abort (or a crash) at ANY
|
|
3
|
+
* point can be recovered by simply re-running — the second run picks every value back up and SKIPS
|
|
4
|
+
* re-creating the external resources (GitHub App, vault key, provisioning key) that would otherwise be
|
|
5
|
+
* orphaned with their secrets lost.
|
|
6
|
+
*
|
|
7
|
+
* The file is `$XDG_CONFIG_HOME/fabrika/cloudflare/<account>/.env` (0700 directory, 0600 file), NOT
|
|
8
|
+
* `$PWD/.env`: it holds the Cloudflare account token, the vault KEK and IAM's signing key, and the cwd
|
|
9
|
+
* is wherever the operator happened to be — routinely inside an unrelated repository. Living outside
|
|
10
|
+
* every checkout also means Bun no longer auto-loads it, so `openEnvFile` loads it explicitly.
|
|
11
|
+
*
|
|
12
|
+
* Values are encoded so they survive Bun's `.env` loader exactly (see `encodeEnvValue`); `parseEnvFile`
|
|
13
|
+
* is the matching decoder. This module NEVER logs a secret value — only the path and the KEY names.
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
import { warn } from '@fabrika/installation-init'
|
|
17
|
+
import { randomUUID } from 'node:crypto'
|
|
18
|
+
import { existsSync } from 'node:fs'
|
|
19
|
+
import { chmod, mkdir, open, rename, rm } from 'node:fs/promises'
|
|
20
|
+
import { homedir } from 'node:os'
|
|
21
|
+
import { dirname, isAbsolute, join, resolve } from 'node:path'
|
|
22
|
+
|
|
23
|
+
/** Usable as one path segment: no separator, no traversal, no leading dash. */
|
|
24
|
+
const ACCOUNT_SEGMENT = /^[A-Za-z0-9][A-Za-z0-9._-]*$/
|
|
25
|
+
|
|
26
|
+
/** This run's env file, bound by `openEnvFile` — the single source of the path. */
|
|
27
|
+
let envFilePath: string | undefined
|
|
28
|
+
|
|
29
|
+
/** `$XDG_CONFIG_HOME/fabrika/cloudflare/<account>`, falling back to `~/.config`. */
|
|
30
|
+
export function accountEnvDirectory(account: string): string {
|
|
31
|
+
if (!ACCOUNT_SEGMENT.test(account)) {
|
|
32
|
+
throw new Error(`Account ${account} cannot name a config directory — use letters, digits, dot, dash or underscore.`)
|
|
33
|
+
}
|
|
34
|
+
const configured = process.env['XDG_CONFIG_HOME']
|
|
35
|
+
const root = configured !== undefined && configured !== '' && isAbsolute(configured) ? configured : join(homedir(), '.config')
|
|
36
|
+
return join(root, 'fabrika', 'cloudflare', account)
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Bind this run's env file, creating its 0700 directory, and load what it already holds into
|
|
41
|
+
* `process.env`. A value already present in the environment wins, matching Bun's own loader — which is
|
|
42
|
+
* exactly why a stray `$PWD/.env` is called out: Bun loaded it before this ran, so ITS values outrank
|
|
43
|
+
* the per-account file, and one left over from another account would be reused silently.
|
|
44
|
+
*/
|
|
45
|
+
export async function openEnvFile(account: string): Promise<string> {
|
|
46
|
+
const directory = accountEnvDirectory(account)
|
|
47
|
+
await mkdir(directory, { recursive: true, mode: 0o700 })
|
|
48
|
+
await chmod(directory, 0o700)
|
|
49
|
+
const cwdEnv = resolve(process.cwd(), '.env')
|
|
50
|
+
if (existsSync(cwdEnv)) {
|
|
51
|
+
warn(
|
|
52
|
+
`${cwdEnv} exists and Bun already loaded it — its values OUTRANK ${account}'s installer env file, so one left over from`
|
|
53
|
+
+ " another installation would be reused here. Move it away and re-run if it is not this account's.",
|
|
54
|
+
)
|
|
55
|
+
}
|
|
56
|
+
const path = join(directory, '.env')
|
|
57
|
+
const file = Bun.file(path)
|
|
58
|
+
if (await file.exists()) {
|
|
59
|
+
for (const [key, value] of Object.entries(parseEnvFile(await file.text()))) {
|
|
60
|
+
const current = process.env[key]
|
|
61
|
+
if (current === undefined || current === '') {
|
|
62
|
+
process.env[key] = value
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
envFilePath = path
|
|
67
|
+
return path
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** The absolute path of the env file being written (non-secret, printed once in the closing summary). */
|
|
71
|
+
export function envPath(): string {
|
|
72
|
+
if (envFilePath === undefined) {
|
|
73
|
+
throw new Error('The installer env file is not open yet — call openEnvFile(account) first.')
|
|
74
|
+
}
|
|
75
|
+
return envFilePath
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** Read an env var, returning undefined for unset OR empty. Dynamic access by design (no literal-key lint). */
|
|
79
|
+
export function fromEnv(name: string): string | undefined {
|
|
80
|
+
const value = process.env[name]
|
|
81
|
+
return value !== undefined && value !== '' ? value : undefined
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* Upsert `KEY=value` into the env file (creating it if absent) and reflect it into the live `process.env`
|
|
86
|
+
* so the rest of THIS run sees it too. An existing `KEY=` line (with or without a leading `export`) is
|
|
87
|
+
* replaced in place; otherwise the line is appended. NEVER logs the value.
|
|
88
|
+
*/
|
|
89
|
+
export async function persistEnv(key: string, value: string): Promise<void> {
|
|
90
|
+
await persistEnvBundle({ [key]: value })
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/** Persist a related resume bundle with one same-filesystem atomic replacement. */
|
|
94
|
+
export async function persistEnvBundle(values: Readonly<Record<string, string>>): Promise<void> {
|
|
95
|
+
await persistEnvBundleAt(envPath(), values)
|
|
96
|
+
for (const [key, value] of Object.entries(values)) process.env[key] = value
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** Package-local test seam for the same atomic env-file replacement used in production. */
|
|
100
|
+
export async function persistEnvBundleAt(path: string, values: Readonly<Record<string, string>>): Promise<void> {
|
|
101
|
+
const file = Bun.file(path)
|
|
102
|
+
const existing = (await file.exists()) ? await file.text() : ''
|
|
103
|
+
const lines = existing === '' ? [] : existing.split('\n')
|
|
104
|
+
for (const [key, value] of Object.entries(values)) {
|
|
105
|
+
const newLine = `${key}=${encodeEnvValue(value)}`
|
|
106
|
+
const index = lines.findIndex((line) => stripExport(line).startsWith(`${key}=`))
|
|
107
|
+
if (index >= 0) {
|
|
108
|
+
lines[index] = newLine
|
|
109
|
+
} else {
|
|
110
|
+
while (lines.length > 0 && lines[lines.length - 1] === '') {
|
|
111
|
+
lines.pop()
|
|
112
|
+
}
|
|
113
|
+
lines.push(newLine)
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
const temporaryPath = join(dirname(path), `.env.${randomUUID()}.tmp`)
|
|
117
|
+
const temporary = await open(temporaryPath, 'wx', 0o600)
|
|
118
|
+
try {
|
|
119
|
+
await temporary.writeFile(`${lines.join('\n')}\n`, 'utf8')
|
|
120
|
+
await temporary.sync()
|
|
121
|
+
await temporary.close()
|
|
122
|
+
await rename(temporaryPath, path)
|
|
123
|
+
} catch (error) {
|
|
124
|
+
await temporary.close().catch(() => {})
|
|
125
|
+
await rm(temporaryPath, { force: true }).catch(() => {})
|
|
126
|
+
throw error
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/** Drop a leading `export ` so `KEY=` matching works whether or not the line is export-prefixed. */
|
|
131
|
+
function stripExport(line: string): string {
|
|
132
|
+
return line.replace(/^\s*export\s+/, '')
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
const ENV_LINE = /^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)=(.*)$/
|
|
136
|
+
|
|
137
|
+
/** Decode a whole env file written by `encodeEnvValue`. The inverse Bun used to perform for us. */
|
|
138
|
+
export function parseEnvFile(contents: string): Record<string, string> {
|
|
139
|
+
const values: Record<string, string> = {}
|
|
140
|
+
for (const line of contents.split('\n')) {
|
|
141
|
+
const matched = ENV_LINE.exec(line)
|
|
142
|
+
const key = matched?.[1]
|
|
143
|
+
const encoded = matched?.[2]
|
|
144
|
+
if (key === undefined || encoded === undefined) continue
|
|
145
|
+
values[key] = decodeEnvValue(encoded)
|
|
146
|
+
}
|
|
147
|
+
return values
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/** The inverse of `encodeEnvValue`; an unquoted value (hand-written) is taken verbatim. */
|
|
151
|
+
function decodeEnvValue(encoded: string): string {
|
|
152
|
+
const value = encoded.trim()
|
|
153
|
+
if (value.length >= 2 && value.startsWith("'") && value.endsWith("'")) {
|
|
154
|
+
return value.slice(1, -1).replace(/\\\$/g, '$')
|
|
155
|
+
}
|
|
156
|
+
if (value.length >= 2 && value.startsWith('"') && value.endsWith('"')) {
|
|
157
|
+
return value.slice(1, -1).replace(/\\(n|\$)/g, (_: string, character: string) => (character === 'n' ? '\n' : '$'))
|
|
158
|
+
}
|
|
159
|
+
return value
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/**
|
|
163
|
+
* Encode a value so Bun's `.env` loader reads it back EXACTLY. Bun's quoting is quirky (all verified):
|
|
164
|
+
* - it expands `$VAR` / `${VAR}` in BOTH quote styles — so EVERY `$` is escaped to `\$` (a literal `$`),
|
|
165
|
+
* - double quotes re-expand `\n` (used for the PEM); single quotes keep `"`, `\`, backtick, `#`, spaces
|
|
166
|
+
* literal.
|
|
167
|
+
* So: multi-line (only the GitHub App PEM) → double-quote + escape newlines; single-line → single-quote.
|
|
168
|
+
* A single-line value cannot contain a literal `'` (Bun has no in-single-quote escape for it); a secret
|
|
169
|
+
* with one is vanishingly rare, so we throw rather than silently corrupt it.
|
|
170
|
+
*/
|
|
171
|
+
function encodeEnvValue(value: string): string {
|
|
172
|
+
const dollarSafe = value.replace(/\$/g, '\\$')
|
|
173
|
+
if (/[\r\n]/.test(value)) {
|
|
174
|
+
return `"${dollarSafe.replace(/\r/g, '').replace(/\n/g, '\\n')}"`
|
|
175
|
+
}
|
|
176
|
+
if (value.includes("'")) {
|
|
177
|
+
throw new Error('Cannot safely persist a value containing a single quote to the env file — set it manually.')
|
|
178
|
+
}
|
|
179
|
+
return `'${dollarSafe}'`
|
|
180
|
+
}
|
|
@@ -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(' ')
|