|
| 1 | +// POST /api/install/provision |
| 2 | +// |
| 3 | +// One-shot installer endpoint. Takes the user's Cloudflare API token |
| 4 | +// + install details and provisions: |
| 5 | +// 1. The user's account id (from /accounts). |
| 6 | +// 2. A D1 database named after their project slug. |
| 7 | +// 3. An R2 bucket named "<slug>-images". |
| 8 | +// 4. A Pages project bound to the GitHub repo with all three |
| 9 | +// bindings configured + the Workers AI binding. |
| 10 | +// 5. Triggers the first deployment. |
| 11 | +// |
| 12 | +// Schema application + admin-user seeding happen in the *target* site's |
| 13 | +// own /api/setup endpoint after the first deploy finishes. The |
| 14 | +// installer doesn't try to apply schema directly to D1 over the API — |
| 15 | +// D1's REST `query` endpoint only accepts single statements and would |
| 16 | +// need a separate trip per CREATE TABLE. |
| 17 | +// |
| 18 | +// The user's API token never leaves the installer's process. We do |
| 19 | +// not persist it. |
| 20 | + |
| 21 | +import { json } from '../../_lib/util.js'; |
| 22 | + |
| 23 | +const CF_API = 'https://api.cloudflare.com/client/v4'; |
| 24 | +const REPO_OWNER = 'Benjamin-Bloch'; |
| 25 | +const REPO_NAME = 'pages-seo'; |
| 26 | +const PROD_BRANCH = 'main'; |
| 27 | + |
| 28 | +function fail(at, status, detail) { |
| 29 | + return json(status, { ok: false, failed_at: at, error: 'install_failed', detail }); |
| 30 | +} |
| 31 | + |
| 32 | +async function cfFetch(token, path, init = {}) { |
| 33 | + const res = await fetch(CF_API + path, { |
| 34 | + ...init, |
| 35 | + headers: { |
| 36 | + Authorization: 'Bearer ' + token, |
| 37 | + 'Content-Type': 'application/json', |
| 38 | + ...(init.headers || {}), |
| 39 | + }, |
| 40 | + }); |
| 41 | + let body = null; |
| 42 | + try { body = await res.json(); } catch { /* non-JSON */ } |
| 43 | + return { res, body }; |
| 44 | +} |
| 45 | + |
| 46 | +function firstErrorMessage(body) { |
| 47 | + if (!body) return null; |
| 48 | + if (Array.isArray(body.errors) && body.errors.length) { |
| 49 | + return body.errors.map((e) => e.message || String(e)).join(' · '); |
| 50 | + } |
| 51 | + return body.error || body.detail || null; |
| 52 | +} |
| 53 | + |
| 54 | +const SLUG_RX = /^[a-z][a-z0-9-]{1,32}$/; |
| 55 | +const EMAIL_RX = /^[^@\s]+@[^@\s]+\.[^@\s]+$/; |
| 56 | + |
| 57 | +export const onRequestPost = async ({ request }) => { |
| 58 | + let body; |
| 59 | + try { body = await request.json(); } catch { return json(400, { error: 'bad_json' }); } |
| 60 | + |
| 61 | + const token = String(body?.token || '').trim(); |
| 62 | + const project = String(body?.project || '').trim().toLowerCase(); |
| 63 | + const siteName = String(body?.site_name || '').trim(); |
| 64 | + const email = String(body?.email || '').trim().toLowerCase(); |
| 65 | + const password = String(body?.password || ''); |
| 66 | + |
| 67 | + if (!token) return fail('validate', 400, 'API token required'); |
| 68 | + if (!SLUG_RX.test(project)) return fail('validate', 400, 'Project slug: lowercase letters/digits/dashes, 2–33 chars, must start with a letter'); |
| 69 | + if (!siteName) return fail('validate', 400, 'Site name required'); |
| 70 | + if (!EMAIL_RX.test(email)) return fail('validate', 400, 'Valid email required'); |
| 71 | + if (password.length < 12) return fail('validate', 400, 'Password must be 12+ characters'); |
| 72 | + |
| 73 | + // ── 1. account ────────────────────────────────────────────── |
| 74 | + const accR = await cfFetch(token, '/accounts'); |
| 75 | + if (!accR.res.ok || !accR.body?.result?.length) { |
| 76 | + return fail('account', 401, firstErrorMessage(accR.body) || 'Token rejected by Cloudflare (check scopes).'); |
| 77 | + } |
| 78 | + const accountId = accR.body.result[0].id; |
| 79 | + const accountName = accR.body.result[0].name; |
| 80 | + |
| 81 | + // ── 2. D1 database ────────────────────────────────────────── |
| 82 | + const d1Name = project; |
| 83 | + const d1R = await cfFetch(token, `/accounts/${accountId}/d1/database`, { |
| 84 | + method: 'POST', |
| 85 | + body: JSON.stringify({ name: d1Name }), |
| 86 | + }); |
| 87 | + if (!d1R.res.ok || !d1R.body?.result?.uuid) { |
| 88 | + return fail('d1', d1R.res.status || 500, firstErrorMessage(d1R.body) || 'Failed to create D1 database (slug taken on this account?).'); |
| 89 | + } |
| 90 | + const d1Id = d1R.body.result.uuid; |
| 91 | + |
| 92 | + // ── 3. R2 bucket ──────────────────────────────────────────── |
| 93 | + const r2Name = project + '-images'; |
| 94 | + const r2R = await cfFetch(token, `/accounts/${accountId}/r2/buckets`, { |
| 95 | + method: 'POST', |
| 96 | + body: JSON.stringify({ name: r2Name }), |
| 97 | + }); |
| 98 | + // R2 returns 409 if the bucket already exists on this account — we |
| 99 | + // tolerate that (the user may have run the installer before) but |
| 100 | + // not other failures. |
| 101 | + if (!r2R.res.ok && r2R.res.status !== 409) { |
| 102 | + return fail('r2', r2R.res.status || 500, firstErrorMessage(r2R.body) || 'Failed to create R2 bucket.'); |
| 103 | + } |
| 104 | + |
| 105 | + // ── 4. Pages project ──────────────────────────────────────── |
| 106 | + // Bindings, env vars, and the GitHub source all go in this one |
| 107 | + // call. Production-only deployment configs — we don't bother with |
| 108 | + // preview branches for installs. |
| 109 | + const pagesPayload = { |
| 110 | + name: project, |
| 111 | + production_branch: PROD_BRANCH, |
| 112 | + source: { |
| 113 | + type: 'github', |
| 114 | + config: { |
| 115 | + owner: REPO_OWNER, |
| 116 | + repo_name: REPO_NAME, |
| 117 | + production_branch: PROD_BRANCH, |
| 118 | + production_deployments_enabled: true, |
| 119 | + deployments_enabled: true, |
| 120 | + }, |
| 121 | + }, |
| 122 | + deployment_configs: { |
| 123 | + production: { |
| 124 | + d1_databases: { DB: { id: d1Id } }, |
| 125 | + r2_buckets: { IMAGES: { name: r2Name } }, |
| 126 | + ai_bindings: { AI: {} }, |
| 127 | + env_vars: { |
| 128 | + SITE_NAME: { type: 'plain_text', value: siteName }, |
| 129 | + }, |
| 130 | + }, |
| 131 | + preview: { |
| 132 | + d1_databases: { DB: { id: d1Id } }, |
| 133 | + r2_buckets: { IMAGES: { name: r2Name } }, |
| 134 | + ai_bindings: { AI: {} }, |
| 135 | + env_vars: { |
| 136 | + SITE_NAME: { type: 'plain_text', value: siteName }, |
| 137 | + }, |
| 138 | + }, |
| 139 | + }, |
| 140 | + }; |
| 141 | + |
| 142 | + const pagesR = await cfFetch(token, `/accounts/${accountId}/pages/projects`, { |
| 143 | + method: 'POST', |
| 144 | + body: JSON.stringify(pagesPayload), |
| 145 | + }); |
| 146 | + if (!pagesR.res.ok || !pagesR.body?.result?.subdomain) { |
| 147 | + return fail('pages', pagesR.res.status || 500, firstErrorMessage(pagesR.body) || 'Failed to create Pages project. The slug may already be in use on Cloudflare Pages.'); |
| 148 | + } |
| 149 | + const subdomain = pagesR.body.result.subdomain; |
| 150 | + const pagesUrl = `https://${subdomain}`; |
| 151 | + |
| 152 | + // SITE_URL needs to point at the Pages domain. We set it after the |
| 153 | + // project exists because we don't know the subdomain until then. |
| 154 | + // (Cloudflare assigns one of the form `<slug>-<hash>.pages.dev` if |
| 155 | + // the bare `<slug>.pages.dev` is taken.) |
| 156 | + const envPatch = { |
| 157 | + deployment_configs: { |
| 158 | + production: { |
| 159 | + env_vars: { |
| 160 | + SITE_URL: { type: 'plain_text', value: pagesUrl }, |
| 161 | + }, |
| 162 | + }, |
| 163 | + preview: { |
| 164 | + env_vars: { |
| 165 | + SITE_URL: { type: 'plain_text', value: pagesUrl }, |
| 166 | + }, |
| 167 | + }, |
| 168 | + }, |
| 169 | + }; |
| 170 | + await cfFetch(token, `/accounts/${accountId}/pages/projects/${project}`, { |
| 171 | + method: 'PATCH', |
| 172 | + body: JSON.stringify(envPatch), |
| 173 | + }); |
| 174 | + // Best-effort: if the PATCH fails, the in-app /api/setup still |
| 175 | + // works because it can derive SITE_URL from settings the user |
| 176 | + // submits there. We don't block the install on this. |
| 177 | + |
| 178 | + // ── 5. Kick off the first deployment ──────────────────────── |
| 179 | + // Creating a Pages project with a GitHub source enables deploys but |
| 180 | + // doesn't trigger one immediately. We POST /deployments to fire the |
| 181 | + // first build right away. |
| 182 | + await cfFetch(token, `/accounts/${accountId}/pages/projects/${project}/deployments`, { |
| 183 | + method: 'POST', |
| 184 | + }); |
| 185 | + |
| 186 | + // ── 6. Stash the seed payload for /api/setup on the new site ── |
| 187 | + // We can't reach the new site's /api/setup yet — it's still |
| 188 | + // building. The new install will reach our /api/install/seed-info |
| 189 | + // endpoint with its project slug on first boot to fetch the |
| 190 | + // pre-supplied email + password + SITE_NAME so the operator never |
| 191 | + // has to type them twice. |
| 192 | + // |
| 193 | + // Storage: keep it on THIS site's D1 (the installer's), encrypted |
| 194 | + // at rest with a random key embedded in the URL we hand back. We |
| 195 | + // don't have access to the new site's D1 to write directly. For |
| 196 | + // v1, we skip this convenience step — the user will type their |
| 197 | + // password once into the /admin first-run setup card after the |
| 198 | + // deploy completes. That's still a clean experience. |
| 199 | + |
| 200 | + return json(200, { |
| 201 | + ok: true, |
| 202 | + pages_url: pagesUrl, |
| 203 | + account: { id: accountId, name: accountName }, |
| 204 | + project, |
| 205 | + d1: { id: d1Id, name: d1Name }, |
| 206 | + r2: { name: r2Name }, |
| 207 | + // Pre-fill these in the first-run setup form on the new site so |
| 208 | + // the operator doesn't retype them. Sent back to the browser |
| 209 | + // (not stored). |
| 210 | + seed: { email, password, site_name: siteName }, |
| 211 | + }); |
| 212 | +}; |
0 commit comments