@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.
@@ -0,0 +1,184 @@
1
+ /**
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).
5
+ *
6
+ * Local schemas validate the consumed fields while tolerating upstream additions.
7
+ */
8
+
9
+ import { required, select } from '@fabrika/installation-init'
10
+ import { z } from 'zod'
11
+ import { fromEnv } from './envfile'
12
+
13
+ const CF_API = 'https://api.cloudflare.com/client/v4'
14
+ const envelopeSchema = z.object({ success: z.boolean(), result: z.unknown(), errors: z.unknown() })
15
+ const errorSchema = z.object({ message: z.string() })
16
+ const tokenSchema = z.object({ status: z.literal('active') })
17
+ const namedResourceSchema = z.object({ id: z.string(), name: z.string() })
18
+ const entriesSchema = z.array(z.unknown())
19
+
20
+ function namedResources(value: unknown): CfAccount[] {
21
+ const entries = entriesSchema.safeParse(value)
22
+ if (!entries.success) return []
23
+ return entries.data.flatMap((entry) => {
24
+ const parsed = namedResourceSchema.safeParse(entry)
25
+ return parsed.success ? [parsed.data] : []
26
+ })
27
+ }
28
+
29
+ /** The CF account picked for this deploy (id + human name, for display). */
30
+ export interface CfAccount {
31
+ id: string
32
+ name: string
33
+ }
34
+
35
+ /** A resolved CF zone (registrable domain). */
36
+ export interface CfZone {
37
+ id: string
38
+ name: string
39
+ }
40
+
41
+ /** The first `errors[].message` from a CF envelope, or undefined — for a readable failure message. */
42
+ function firstErrorMessage(value: unknown): string | undefined {
43
+ const errors = entriesSchema.safeParse(value)
44
+ if (!errors.success) {
45
+ return undefined
46
+ }
47
+ for (const entry of errors.data) {
48
+ const parsed = errorSchema.safeParse(entry)
49
+ if (parsed.success) {
50
+ return parsed.data.message
51
+ }
52
+ }
53
+ return undefined
54
+ }
55
+
56
+ /**
57
+ * Parse the uniform CF envelope `{ success, result, errors }`, throwing a short message (never the
58
+ * token) on a non-2xx / `success:false`. Returns the `result` field as `unknown` for the caller to
59
+ * narrow. All field access is runtime-checked — no casts.
60
+ */
61
+ async function cfJson(response: Response, what: string): Promise<unknown> {
62
+ const parsed = envelopeSchema.safeParse(await response.json().catch(() => null))
63
+ if (!parsed.success) {
64
+ throw new Error(`${what}: unexpected Cloudflare response (HTTP ${response.status}).`)
65
+ }
66
+ const body = parsed.data
67
+ if (!response.ok || !body.success) {
68
+ throw new Error(`${what} failed: ${firstErrorMessage(body.errors) ?? `HTTP ${response.status}`}`)
69
+ }
70
+ return body.result
71
+ }
72
+
73
+ /** Authorization header for the token. Kept local so the value never leaks into a log statement. */
74
+ function authHeaders(token: string): Record<string, string> {
75
+ return { Authorization: `Bearer ${token}` }
76
+ }
77
+
78
+ /**
79
+ * Best-effort token liveness check → true iff Cloudflare reports the token `active`. Tries the
80
+ * ACCOUNT-scoped endpoint first when an account id is known: an ACCOUNT-OWNED token is NOT visible to
81
+ * `/user/tokens/verify` (which returns "Invalid API Token" for it) — only `/accounts/<id>/tokens/verify`
82
+ * sees it — then falls back to the user endpoint. NEVER throws: a `false` means "couldn't confirm", and
83
+ * the caller decides whether to proceed (the real deploy is the ultimate check).
84
+ */
85
+ export async function verifyToken(token: string, accountId?: string): Promise<boolean> {
86
+ const endpoints = accountId !== undefined && accountId !== ''
87
+ ? [`${CF_API}/accounts/${accountId}/tokens/verify`, `${CF_API}/user/tokens/verify`]
88
+ : [`${CF_API}/user/tokens/verify`]
89
+ for (const endpoint of endpoints) {
90
+ try {
91
+ const response = await fetch(endpoint, { headers: authHeaders(token) })
92
+ const result = await cfJson(response, 'Token verification')
93
+ if (tokenSchema.safeParse(result).success) {
94
+ return true
95
+ }
96
+ } catch {
97
+ // Not fatal — the token may simply be the wrong TYPE for this endpoint; try the next.
98
+ }
99
+ }
100
+ return false
101
+ }
102
+
103
+ /** List the accounts the token can act on: `GET /accounts`. */
104
+ export async function listAccounts(token: string): Promise<CfAccount[]> {
105
+ const response = await fetch(`${CF_API}/accounts`, { headers: authHeaders(token) })
106
+ const result = await cfJson(response, 'Listing accounts')
107
+ return namedResources(result)
108
+ }
109
+
110
+ /**
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.
114
+ */
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)' }
126
+ }
127
+ const only = accounts[0]
128
+ if (accounts.length === 1 && only !== undefined) {
129
+ return only
130
+ }
131
+ 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 })),
135
+ )
136
+ }
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
+ }
157
+ }
158
+
159
+ /**
160
+ * Best-effort zone lookup for the registrable domain of `hostname`. Naively takes the last two
161
+ * dot-labels (e.g. `fabrika.example.com` → `example.com`) and queries `GET /zones?name=<domain>`.
162
+ * Returns the zone or null. The CLI WARNS on null (a custom-domain bind needs the zone) but never
163
+ * fails on it — the operator may add the zone before the real deploy.
164
+ */
165
+ export async function findZone(token: string, hostname: string): Promise<CfZone | null> {
166
+ const domain = registrableDomain(hostname)
167
+ const response = await fetch(`${CF_API}/zones?name=${encodeURIComponent(domain)}`, { headers: authHeaders(token) })
168
+ const result = await cfJson(response, 'Zone lookup')
169
+ const entries = entriesSchema.safeParse(result)
170
+ if (!entries.success) {
171
+ return null
172
+ }
173
+ const first = namedResourceSchema.safeParse(entries.data[0])
174
+ return first.success ? first.data : null
175
+ }
176
+
177
+ /** Naive registrable-domain derivation: the last two dot-labels of a hostname. */
178
+ function registrableDomain(hostname: string): string {
179
+ const labels = hostname.split('.').filter(Boolean)
180
+ if (labels.length <= 2) {
181
+ return labels.join('.')
182
+ }
183
+ return labels.slice(-2).join('.')
184
+ }
@@ -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,2 @@
1
+ export { runInit } from './init'
2
+ export { cloudflareInstallationCli as installationCli } from './installation'