diff --git a/.github/scripts/apply-migrations.mjs b/.github/scripts/apply-migrations.mjs new file mode 100644 index 0000000..9b65498 --- /dev/null +++ b/.github/scripts/apply-migrations.mjs @@ -0,0 +1,133 @@ +// Deploy auto-upgrade step (WorkerHub tech-scheme §9 item 4): after `wrangler deploy`, this +// script applies the D1 schema migrations by calling the Worker's own POST /api/setup endpoint over +// its *.workers.dev URL, and fails the Deploy run (fail closed) unless every migration the deployed +// source defines is reported back as applied or skipped. It is idempotent: an up-to-date database +// simply returns every migration as "skipped". +// +// Nothing here re-implements the schema: `worker/src/lib/migrations.ts` is the single source of +// truth, and this script only parses the `name: 'schema_vN'` entries out of it to know what to +// assert. The setup secret travels only in the X-Setup-Secret header and is never printed. +import { readFileSync } from 'node:fs' + +const CF_API = 'https://api.cloudflare.com/client/v4' +const MAX_ATTEMPTS = 5 +const REQUEST_TIMEOUT_MS = 20_000 +const SETUP_TIMEOUT_MS = 15_000 + +function fail(message) { + console.error(`::error::apply-migrations: ${message}`) + process.exit(1) +} + +function requiredEnv(name) { + const value = process.env[name]?.trim() + if (!value) fail(`${name} is not set`) + return value +} + +const accountId = requiredEnv('CLOUDFLARE_ACCOUNT_ID') +const apiToken = requiredEnv('CLOUDFLARE_API_TOKEN') +const setupSecret = requiredEnv('SETUP_SECRET') + +// ── Expected migration names, parsed from the deployed source (never hardcoded) ────────────── +const migrationsSource = readFileSync(new URL('../../worker/src/lib/migrations.ts', import.meta.url), 'utf8') +const expectedMigrations = [ + ...new Set([...migrationsSource.matchAll(/name:\s*['"](schema_v\d+)['"]/g)].map((m) => m[1])), +].sort((a, b) => Number(a.replace(/^schema_v/, '')) - Number(b.replace(/^schema_v/, ''))) + +if (expectedMigrations.length === 0) fail('no schema_vN migrations found in worker/src/lib/migrations.ts') + +// ── Worker name, read from the same wrangler.toml that wrangler deploy just published ───────── +const wranglerToml = readFileSync(new URL('../../worker/wrangler.toml', import.meta.url), 'utf8') +const workerName = wranglerToml.match(/^\s*name\s*=\s*"([^"]+)"/m)?.[1] +if (!workerName) fail('could not read the Worker name from worker/wrangler.toml') + +const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)) + +// Cloudflare API client, modelled on worker/src/lib/d1-http.ts. Resource IDs and the token are +// pre-registered as GitHub secret masks, but this function still never echoes them. +async function cfFetch(path, init = {}) { + const res = await fetch(`${CF_API}${path}`, { + ...init, + headers: { + 'Content-Type': 'application/json', + Authorization: `Bearer ${apiToken}`, + ...(init.headers ?? {}), + }, + signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS), + }) + const body = await res.json().catch(() => null) + if (!res.ok || body?.success === false) { + const message = body?.errors?.[0]?.message ?? `HTTP ${res.status}` + throw new Error(message) + } + return body +} + +async function main() { + // §9 item 4 (1)(2): resolve the account's workers.dev subdomain, then make sure the Worker is + // published on it. Both are required for the setup call to reach the just-deployed Worker. + const subdomainBody = await cfFetch(`/accounts/${accountId}/workers/subdomain`).catch((err) => + fail(`could not resolve the account workers.dev subdomain: ${err.message}`) + ) + const subdomain = subdomainBody.result?.subdomain + if (!subdomain) fail('this Cloudflare account has no workers.dev subdomain') + + await cfFetch(`/accounts/${accountId}/workers/scripts/${encodeURIComponent(workerName)}/subdomain`, { + method: 'POST', + body: JSON.stringify({ enabled: true }), + }).catch((err) => fail(`could not enable the ${workerName}.${subdomain}.workers.dev route: ${err.message}`)) + + const setupUrl = `https://${workerName}.${subdomain}.workers.dev/api/setup` + console.log(`Applying D1 migrations via ${setupUrl}`) + + // §9 item 4 (3)(4): POST the setup endpoint with the secret in the header only. Network errors, 429 + // and 5xx retry with backoff (5 attempts, well under a minute); 403 fails immediately. + let lastStatus = null + let lastBody = null + for (let attempt = 1; attempt <= MAX_ATTEMPTS; attempt++) { + if (attempt > 1) await sleep(2 ** (attempt - 1) * 1000) + + let res + try { + res = await fetch(setupUrl, { + method: 'POST', + headers: { 'X-Setup-Secret': setupSecret }, + signal: AbortSignal.timeout(SETUP_TIMEOUT_MS), + }) + } catch (err) { + console.log(`attempt ${attempt}/${MAX_ATTEMPTS}: network error (${err instanceof Error ? err.name : 'unknown'})`) + continue + } + + lastStatus = res.status + lastBody = await res.json().catch(() => null) + + if (res.status === 403) { + fail('POST /api/setup returned 403 (SETUP_SECRET rejected or misconfigured); not retrying.') + } + if (res.status === 200) { + // §9 item 4 (5): every migration the deployed source defines must be present, applied or skipped. + const migrations = Array.isArray(lastBody?.migrations) ? lastBody.migrations : [] + const present = new Set(migrations.map((m) => m?.name)) + const missing = expectedMigrations.filter((name) => !present.has(name)) + const detail = migrations.map((m) => `${m?.name}=${m?.status}`).join(', ') + if (missing.length > 0) { + fail(`setup response is missing migrations: ${missing.join(', ')}`) + } + console.log(`D1 migrations applied: ${expectedMigrations.length} present, ${detail}`) + return + } + if (res.status === 429 || res.status >= 500) { + console.log(`attempt ${attempt}/${MAX_ATTEMPTS}: HTTP ${res.status}, retrying`) + continue + } + fail(`POST /api/setup returned HTTP ${res.status}: ${JSON.stringify(lastBody)}`) + } + + fail( + `POST /api/setup did not succeed after ${MAX_ATTEMPTS} attempts (last status: ${lastStatus ?? 'network error'}, body: ${JSON.stringify(lastBody)})` + ) +} + +await main() diff --git a/.github/scripts/test-apply-migrations.mjs b/.github/scripts/test-apply-migrations.mjs new file mode 100644 index 0000000..c6b0f83 --- /dev/null +++ b/.github/scripts/test-apply-migrations.mjs @@ -0,0 +1,50 @@ +// Regression test for the deploy workflow's "Apply D1 migrations" step, in the same spirit as +// test-deploy-checks.mjs: it reads the step's body out of deploy.yml and asserts the step is wired +// to the right secrets and script, so the workflow cannot drift from the contract without this +// test failing. Nothing here reads a secret value — only key names. +import assert from 'node:assert/strict' +import { readFile } from 'node:fs/promises' +import { describe, it } from 'node:test' +import { fileURLToPath } from 'node:url' + +const WORKFLOW_PATH = fileURLToPath(new URL('../workflows/deploy.yml', import.meta.url)) +const STEP_NAME = 'Apply D1 migrations' + +const workflow = await readFile(WORKFLOW_PATH, 'utf8') +const lines = workflow.split('\n') +const start = lines.findIndex((line) => line.trim() === `- name: ${STEP_NAME}`) +assert.notEqual(start, -1, `deploy.yml has no "${STEP_NAME}" step`) + +const startIndent = lines[start].search(/\S/) +const rest = lines.slice(start + 1) +const end = rest.findIndex((line) => { + const indent = line.search(/\S/) + return indent !== -1 && indent <= startIndent && line.trim().startsWith('- name:') +}) +const body = end === -1 ? rest : rest.slice(0, end) + +const declaredSecrets = Object.fromEntries( + body + .map((line) => line.match(/^\s+([A-Za-z0-9_]+):\s*\$\{\{ secrets\.([A-Za-z0-9_]+) \}\}\s*$/)) + .filter(Boolean) + .map(([, name, secret]) => [name, secret]) +) + +describe(`${STEP_NAME} step`, () => { + it('injects the account ID, API token and setup secret from the matching repository secrets', () => { + for (const [name, secret] of Object.entries(declaredSecrets)) { + assert.equal(secret, name, `env ${name} must read the repository secret of the same name`) + } + assert.deepEqual( + Object.keys(declaredSecrets).sort(), + ['CLOUDFLARE_ACCOUNT_ID', 'CLOUDFLARE_API_TOKEN', 'SETUP_SECRET'].sort() + ) + }) + + it('runs the apply-migrations script (the single migration caller)', () => { + assert.ok( + body.some((line) => /^\s+run:\s*node \.github\/scripts\/apply-migrations\.mjs\s*$/.test(line)), + 'the step must run node .github/scripts/apply-migrations.mjs' + ) + }) +}) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index ab3b07c..2707a79 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -31,7 +31,7 @@ jobs: run: pnpm install --frozen-lockfile - name: Test deploy checks - run: node --test .github/scripts/test-deploy-checks.mjs + run: node --test .github/scripts/ - name: Lint run: pnpm lint diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml index b2ae106..04756f3 100644 --- a/.github/workflows/deploy.yml +++ b/.github/workflows/deploy.yml @@ -83,3 +83,10 @@ jobs: env: CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }} run: pnpm exec wrangler deploy --secrets-file "$RUNNER_TEMP/secrets.json" + + - name: Apply D1 migrations + env: + CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }} + CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }} + SETUP_SECRET: ${{ secrets.SETUP_SECRET }} + run: node .github/scripts/apply-migrations.mjs diff --git a/CLAUDE.md b/CLAUDE.md index d0bfc62..feb2299 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -60,9 +60,10 @@ GitHub's blame view reads the file automatically. - `APP_URL` — your custom domain (e.g. `https://zeta.example.com`); must be the `https://` URL users open (sole CORS origin, passkey RP ID, JWT `iss`/`aud` — changing it signs everybody out). This is a Dashboard **Worker Variable** — **not a GitHub Secret**. - `TABLE_PREFIX` — (optional) prefix for all internal tables. Three states: **unset** → default prefix `zeta`; **set to a value** → that value verbatim, case preserved, with `_` appended (`kp` → `kp_users`, `ZETA` → `ZETA_users`); **set to an empty string** → no prefix. Must be set **before** running setup. Cannot be changed after initialisation. **Upgrade warning:** a deployment that never set `TABLE_PREFIX` used **no prefix** before the three-state change; after upgrading, an unset prefix resolves to `zeta` (different tables). Set it explicitly before upgrading to keep your existing tables (an empty string keeps the old unprefixed tables) or rely on the startup/setup guard, which aborts instead of silently switching — and the guard only matches Zeta's own table family, never other projects' tables in a shared D1 (`SL_*`, `eNotify_*`, `TP_*`, `YL_*`, `TEMP_*`, …). - `ALLOW_APP_DB_AS_TARGET` — (optional, default off) managed as a **GitHub repo Variable** and injected into `wrangler.toml`'s `[vars]` at deploy time by `scripts/patch-wrangler.mjs`; changing it needs a redeploy, not a dashboard edit. Set it to exactly `true` to allow the app's own database as a query target (shared-database deployments); any other value keeps it excluded. Missing or blank fails closed: the patch step injects `"false"` instead of failing the deploy (every other placeholder still fails when its variable is missing). While on, the app DB is guarded: effective permission capped at `write` (destructive statements always rejected, `write_drop` cannot be granted on it) and internal tables (everything `TABLE_PREFIX` resolves to, plus the `__schema_migrations` migration ledger) are read-only, admin included; writes whose target table cannot be determined are rejected. + - `LIVY_JARS_DIR` — (optional, default `/data/jars`) managed as a **GitHub repo Variable** (plain text, **not a secret**) and injected into `wrangler.toml`'s `[vars]` at deploy time by `scripts/patch-wrangler.mjs`; changing it needs a redeploy, not a dashboard edit. The whitelist directory under which a bare Livy submit `file` (a jar name with no `://` scheme and no leading `/`) is resolved before forwarding (see `livyJarsDir()` in `worker/src/routes/livy.ts`). Missing or blank falls back to `/data/jars`. - `CF_ACCOUNT_ID` / `ZETA_APP_DB_ID` are injected automatically at deploy from the GitHub Variables `CLOUDFLARE_ACCOUNT_ID` / `D1_DATABASE_ID` via `wrangler.toml`'s `[vars]` — not set here 5. `pnpm run deploy` to build & deploy -6. Initialise the database: `curl -X POST https:///api/setup -H 'Content-Type: application/json' -d '{"secret":""}'` (the old `GET /api/setup/` form returns 405). It applies the pending schema migrations and records them in the ledger table `__schema_migrations`; re-run it after deploying a version that adds a migration, and it only applies what the ledger does not already record. There is also a `/setup` page for less technical users (the switch to hide it is the `setup_page_enabled` setting, on by default, and only affects the page), and `POST /api/setup` is rate-limited to 3 attempts per 10 minutes per IP. Once initialised, a signed-in admin can run the same check-and-upgrade from **Admin → Settings** (the **Check & upgrade database** button) via `POST /api/admin/setup` — admin-only (`requireAdmin`), no `SETUP_SECRET`; first-time setup still requires the `/setup` page or the `curl` above. +6. The deploy workflow applies the schema automatically after every deploy: `.github/scripts/apply-migrations.mjs` calls `POST /api/setup` over the Worker's `*.workers.dev` URL with the secret in the `X-Setup-Secret` header, and fails the Deploy if any migration the deployed source defines is not reported back. Re-running is idempotent — pending migrations are applied and recorded in the ledger `__schema_migrations`, already-applied ones are skipped. Manual fallback: `curl -X POST https:///api/setup -H 'X-Setup-Secret: '` (the old `GET /api/setup/` form returns 405). The `/setup` page is the less-technical first-time path (its hide switch is the `setup_page_enabled` setting, on by default, and only affects the page); `POST /api/setup` is rate-limited to 3 attempts per 10 minutes per IP. A signed-in admin can also run the same check-and-upgrade from **Admin → Settings** (the **Check & upgrade database** button) via `POST /api/admin/setup`. 7. Register at `/register` — first user automatically becomes admin. On new installs registration then stays closed (`registration_enabled = false`); open it or create users in the Admin Panel ## Schema migrations @@ -72,7 +73,9 @@ The schema lives in exactly one place: `worker/src/lib/migrations.ts`, an ordere `lib/migrations-runner.ts`, which creates the ledger table, skips what it already records, applies the rest in order and records each entry only after its SQL succeeded (first failure stops the run and leaves that entry unrecorded). Both `POST /api/setup` and `POST /api/admin/setup` go through -that one runner. +that one runner, and the deploy workflow calls `POST /api/setup` automatically after every deploy +(`.github/scripts/apply-migrations.mjs`), so a version that adds a migration upgrades the database +without a manual step. - Ledger table: `_` + prefix core + `_schema_migrations` — `_ZETA_schema_migrations` for `TABLE_PREFIX=ZETA`, `_zeta_schema_migrations` for the default prefix, `_schema_migrations` for diff --git a/README.md b/README.md index 5d569b1..2464402 100644 --- a/README.md +++ b/README.md @@ -98,6 +98,7 @@ In your GitHub repo → **Settings → Secrets and variables → Actions**: | `D1_DATABASE_ID` | The D1 Database ID from Step 1 | | `KV_NAMESPACE_ID` | The KV Namespace ID from Step 1 | | `ALLOW_APP_DB_AS_TARGET` | *(Optional, default off — leave unset or empty for off.)* Injected into `wrangler.toml` at deploy time. Set to exactly `true` to allow Zeta's own app database to be added and queried as a target — for deployments that share one D1 database between Zeta and other projects. Any other value keeps the app database excluded. While enabled the app database is guarded: its effective permission is capped at `write` (destructive statements like `DROP`/`TRUNCATE` are always rejected and `write_drop` cannot be granted on it), and its internal tables (`users`, `settings`, `notebooks`, … everything `TABLE_PREFIX` resolves to, plus the `__schema_migrations` migration ledger) are read-only — including for admins. Write statements whose target table cannot be determined are rejected. | +| `LIVY_JARS_DIR` | *(Optional, default `/data/jars`.)* Injected into `wrangler.toml` at deploy time — a plain Variable, **not a secret**. The whitelist directory under which a bare Livy submit `file` (a jar name with no `://` scheme and no leading `/`) is resolved before being forwarded to Spark Livy. Changing it needs a redeploy. | --- @@ -119,9 +120,9 @@ Go to **Workers & Pages → zeta → Settings → Variables and Secrets**: |------|-------| | `APP_URL` | Your Worker URL, e.g. `https://zeta.yourname.workers.dev` or your custom domain. Use the exact `https://` URL users open: it is the only origin CORS allows, the passkey RP ID, the base of email links and the issuer/audience of every login token (changing it later signs everybody out) | | `TABLE_PREFIX` | *(Optional)* Prefix for all internal D1 tables. Three states: **unset** → default prefix `zeta` (`zeta_users`, `zeta_settings`, …); **set to a value** → the value used verbatim, case preserved, with `_` appended (`kp` → `kp_users`, `ZETA` → `ZETA_users`; invalid characters are rejected); **set to an empty string** → no prefix (you accept the risk of table-name collisions). Decide it **before** calling the setup endpoint — it cannot be changed after initialisation. | -> `CF_ACCOUNT_ID`, `ZETA_APP_DB_ID` and `ALLOW_APP_DB_AS_TARGET` are injected at deploy time from the GitHub Variables `CLOUDFLARE_ACCOUNT_ID`, `D1_DATABASE_ID` and `ALLOW_APP_DB_AS_TARGET` (Step 2) — do **not** set them here. `ALLOW_APP_DB_AS_TARGET` is optional and fails closed: when the GitHub Variable is missing or empty the deploy injects `false`, so the switch stays off. The other injected values are required — a missing one fails the deploy. +> `CF_ACCOUNT_ID`, `ZETA_APP_DB_ID`, `ALLOW_APP_DB_AS_TARGET` and `LIVY_JARS_DIR` are injected at deploy time from the GitHub Variables `CLOUDFLARE_ACCOUNT_ID`, `D1_DATABASE_ID`, `ALLOW_APP_DB_AS_TARGET` and `LIVY_JARS_DIR` (Step 2) — do **not** set them here. `ALLOW_APP_DB_AS_TARGET` is optional and fails closed: when the GitHub Variable is missing or empty the deploy injects `false`, so the switch stays off. `LIVY_JARS_DIR` is optional and defaults to `/data/jars`. The other injected values are required — a missing one fails the deploy. -> Changing `ALLOW_APP_DB_AS_TARGET` needs a redeploy (push to `main`, or re-run the deploy workflow): the value reaches the Worker through `wrangler.toml`'s `[vars]`, not through the dashboard. +> Changing `ALLOW_APP_DB_AS_TARGET` or `LIVY_JARS_DIR` needs a redeploy (push to `main`, or re-run the deploy workflow): the value reaches the Worker through `wrangler.toml`'s `[vars]`, not through the dashboard. > `ENCRYPTION_KEY` and the dashboard variables above stay out of GitHub entirely (the three CI secrets live in GitHub Secrets — see Step 2). The `keep_vars = true` setting in `wrangler.toml` ensures each deployment never overwrites those dashboard values. @@ -140,21 +141,23 @@ The [GitHub Actions workflow](.github/workflows/deploy.yml) will: 2. Build the React SPA 3. Patch `wrangler.toml` with the IDs from GitHub Variables 4. Run `wrangler deploy` +5. Apply pending D1 migrations (`POST /api/setup` via the Worker's `*.workers.dev` URL) Watch progress under the **Actions** tab in your repository. --- -### Step 5 — Initialise the database +### Step 5 — Database setup (manual fallback) -After the first successful deployment, send this request **once** (the secret travels in the request body, so it never ends up in browser history, access logs or `Referer` headers): +Deploy applies the schema automatically after every deploy (Step 4, item 5), so you normally do not need to run anything by hand. The request below is a fallback — for example when the automatic step was skipped or failed, or when you want to confirm the schema by hand. It is idempotent and safe to re-run: ```bash curl -X POST https:///api/setup \ - -H 'Content-Type: application/json' \ - -d '{"secret":""}' + -H 'X-Setup-Secret: ' ``` +The secret travels only in the `X-Setup-Secret` header — never in the URL, browser history, access logs or `Referer` headers. + Expected response: ```json @@ -163,11 +166,11 @@ Expected response: > There is also a setup page at `/setup` that most users will find easier than a terminal: it submits the same `POST /api/setup` request with the secret, so it is guarded by the same rate limit. An admin can hide the page in **Admin → Settings** (`setup_page_enabled`, on by default) — the switch only hides the page; `POST /api/setup` keeps working with the secret, as the recovery channel. `POST /api/setup` is rate-limited to **3 attempts per 10 minutes per IP** (beyond that it answers `429` with a `Retry-After` header); the attempt is counted before the secret is checked. -> The endpoint is idempotent — safe to call multiple times. It applies the versioned schema migrations of `worker/src/lib/migrations.ts` and records each one in a ledger table, `__schema_migrations` (see [Schema migrations](#schema-migrations)). Re-running it applies only what the ledger does not already record and reports every migration as `applied` or `skipped` under `migrations`; it is still the call to make after deploying a version that adds one. +> The endpoint is idempotent — safe to call multiple times. It applies the versioned schema migrations of `worker/src/lib/migrations.ts` and records each one in a ledger table, `__schema_migrations` (see [Schema migrations](#schema-migrations)). Re-running it applies only what the ledger does not already record and reports every migration as `applied` or `skipped` under `migrations`. > > Earlier versions used `GET /api/setup/`. That form is gone: it now returns `405` and does nothing. If you ever opened the old URL, consider rotating `SETUP_SECRET`. -> Once the database is initialised, a signed-in admin can run the same check-and-upgrade from **Admin → Settings** (the **Check & upgrade database** button) without the secret — the admin session is the credential. First-time initialisation still needs the `/setup` page or the `curl` command above. +> Once the database is initialised, a signed-in admin can run the same check-and-upgrade from **Admin → Settings** (the **Check & upgrade database** button) without the secret — the admin session is the credential. On a new install, the first account still registers at `/register` — that first user becomes the admin. --- @@ -327,6 +330,7 @@ git config blame.ignoreRevsFile .git-blame-ignore-revs | `D1_DATABASE_ID` | Variable | D1 database ID | | `KV_NAMESPACE_ID` | Variable | KV namespace ID | | `ALLOW_APP_DB_AS_TARGET` | Variable | *(Optional, default off)* Injected into the Worker at deploy time; set to exactly `true` to allow the app's own database as a query target. Missing or empty → `false` injected, switch stays off | +| `LIVY_JARS_DIR` | Variable | *(Optional, default `/data/jars`)* Plain Variable (not a secret) injected at deploy time; the whitelist directory for bare Livy submit jar names. Changing it needs a redeploy. | ### Cloudflare Dashboard (set manually) diff --git a/README_zh-CN.md b/README_zh-CN.md index 68de5dd..986cae0 100644 --- a/README_zh-CN.md +++ b/README_zh-CN.md @@ -98,6 +98,7 @@ | `D1_DATABASE_ID` | 第一步中的 D1 Database ID | | `KV_NAMESPACE_ID` | 第一步中的 KV Namespace ID | | `ALLOW_APP_DB_AS_TARGET` | *(可选,默认关闭——不设置或留空即为关)* 部署时注入 `wrangler.toml`。设为 `true` 后,允许把 Zeta 自身的应用库添加为查询目标——适用于多个项目共用一个 D1 的部署。其他任何取值都保持排除。开启后应用库带有护栏:有效权限封顶为 `write`(`DROP`/`TRUNCATE` 等删除类语句一律被拒,且无法对它授予 `write_drop`),应用内部表(`users`、`settings`、`notebooks`……即 `TABLE_PREFIX` 生效后的全部内部表,外加迁移账本表 `_<前缀>_schema_migrations`)只读——管理员也不例外;无法确定目标表的写语句一律拒绝。 | +| `LIVY_JARS_DIR` | *(可选,默认 `/data/jars`)* 部署时注入 `wrangler.toml`——普通 Variable,**不是密钥**。用于把 Livy 提交时的裸文件名(无 `://` 协议、无前导 `/` 的 jar 名)解析到白名单目录后再转发给 Spark Livy。修改后需重新部署。 | --- @@ -120,9 +121,9 @@ | `APP_URL` | 你的 Worker 地址,例如 `https://zeta.yourname.workers.dev` 或自定义域名。请填写用户实际访问的 `https://` 地址:它是 CORS 唯一允许的来源、Passkey 的 RP ID、邮件链接的前缀,也是所有登录令牌的签发方/受众(之后修改会让所有用户重新登录) | | `TABLE_PREFIX` | *(可选)* 所有内部 D1 表的前缀。三态:**未设置** → 默认前缀 `zeta`(`zeta_users`、`zeta_settings` 等);**设为某个值** → 原样使用该值(大小写保留)并自动补尾 `_`(`kp` → `kp_users`,`ZETA` → `ZETA_users`;非法字符会报错);**设为空字符串** → 不带前缀(由你自行承担表名冲突风险)。必须在**调用 setup 接口之前**定好,初始化后不可更改。 | | `ALLOW_APP_DB_AS_TARGET` | *(可选,默认关闭——不设置或留空即为关)* 部署时注入 `wrangler.toml`。设为 `true` 后,允许把 Zeta 自身的应用库添加为查询目标——适用于多个项目共用一个 D1 的部署。其他任何取值都保持排除。开启后应用库带有护栏:有效权限封顶为 `write`(`DROP`/`TRUNCATE` 等删除类语句一律被拒,且无法对它授予 `write_drop`),应用内部表(`users`、`settings`、`notebooks`……即 `TABLE_PREFIX` 生效后的全部内部表,外加迁移账本表 `_<前缀>_schema_migrations`)只读——管理员也不例外;无法确定目标表的写语句一律拒绝。 | -> `CF_ACCOUNT_ID`、`ZETA_APP_DB_ID` 与 `ALLOW_APP_DB_AS_TARGET` 会在部署时由 GitHub Variables `CLOUDFLARE_ACCOUNT_ID`、`D1_DATABASE_ID`、`ALLOW_APP_DB_AS_TARGET`(第二步)注入,**不要在这里手动设置**。`ALLOW_APP_DB_AS_TARGET` 是可选项且失败关闭:GitHub Variable 未设置或为空时部署注入 `false`,开关保持关闭;其余两个为必填项,缺值会导致部署失败。 +> `CF_ACCOUNT_ID`、`ZETA_APP_DB_ID`、`ALLOW_APP_DB_AS_TARGET` 与 `LIVY_JARS_DIR` 会在部署时由 GitHub Variables `CLOUDFLARE_ACCOUNT_ID`、`D1_DATABASE_ID`、`ALLOW_APP_DB_AS_TARGET`、`LIVY_JARS_DIR`(第二步)注入,**不要在这里手动设置**。`ALLOW_APP_DB_AS_TARGET` 是可选项且失败关闭:GitHub Variable 未设置或为空时部署注入 `false`,开关保持关闭;`LIVY_JARS_DIR` 是可选项,默认 `/data/jars`;其余为必填项,缺值会导致部署失败。 -> 修改 `ALLOW_APP_DB_AS_TARGET` 需要重新部署(推送到 `main` 或重跑部署工作流):该值通过 `wrangler.toml` 的 `[vars]` 到达 Worker,不走 Dashboard。 +> 修改 `ALLOW_APP_DB_AS_TARGET` 或 `LIVY_JARS_DIR` 需要重新部署(推送到 `main` 或重跑部署工作流):该值通过 `wrangler.toml` 的 `[vars]` 到达 Worker,不走 Dashboard。 > `ENCRYPTION_KEY` 与上面这些 Dashboard 变量完全隔离于 GitHub(三个 CI 密钥放在 GitHub Secrets,见第二步)。`wrangler.toml` 中的 `keep_vars = true` 确保每次部署不会覆盖这些 Dashboard 值。 @@ -141,21 +142,23 @@ git push origin main 2. 构建 React 前端 3. 将 GitHub Variables 中的 ID 注入 `wrangler.toml` 4. 运行 `wrangler deploy` +5. 应用待执行的 D1 迁移(经 Worker 的 `*.workers.dev` 地址调 `POST /api/setup`) 在仓库的 **Actions** 标签页可以实时查看部署进度。 --- -### 第五步 — 初始化数据库 +### 第五步 — 数据库初始化(手动兜底) -首次部署成功后,**发送一次**以下请求来创建所有数据表并写入默认配置(secret 放在请求体中,不会出现在浏览器历史、访问日志或 `Referer` 请求头里): +部署现在会在每次部署后自动应用 Schema(第四步第 5 条),正常情况下无需手动操作。下面的请求只是兜底——例如自动步骤被跳过或失败、或你想手动确认 Schema 时使用。它幂等且可重复执行: ```bash curl -X POST https://<你的域名>/api/setup \ - -H 'Content-Type: application/json' \ - -d '{"secret":""}' + -H 'X-Setup-Secret: ' ``` +密钥只放在 `X-Setup-Secret` 请求头里,绝不进 URL、浏览器历史、访问日志或 `Referer` 请求头。 + 成功后返回: ```json @@ -164,11 +167,11 @@ curl -X POST https://<你的域名>/api/setup \ > 现在也有一个 `/setup` 页面入口,对大多数用户而言比在终端里敲命令更方便:它提交的是同一个 `POST /api/setup` 请求(带上密钥),因此受到相同的限流保护。管理员可以在**管理后台 → 设置**里隐藏该页面(`setup_page_enabled`,默认开启)——这个开关**只影响页面**;`POST /api/setup` 仍可用密钥调用,作为升级 / 救急通道。`POST /api/setup` 按来源 IP 限流:**每 10 分钟 3 次**(超限返回 `429` 并带 `Retry-After` 头),计数发生在密钥校验之前。 -> 该接口是幂等的,重复调用不会造成任何破坏,可安全地多次调用。它执行 `worker/src/lib/migrations.ts` 里版本化的 Schema 迁移,并把每条已执行的迁移记录在账本表 `_<前缀>_schema_migrations` 中(见[Schema 迁移](#schema-迁移))。重复调用只会执行账本里尚未记录的迁移,并在响应的 `migrations` 字段里逐条给出 `applied` / `skipped`;部署带新迁移的版本后仍应调用一次。 +> 该接口是幂等的,重复调用不会造成任何破坏,可安全地多次调用。它执行 `worker/src/lib/migrations.ts` 里版本化的 Schema 迁移,并把每条已执行的迁移记录在账本表 `_<前缀>_schema_migrations` 中(见[Schema 迁移](#schema-迁移))。重复调用只会执行账本里尚未记录的迁移,并在响应的 `migrations` 字段里逐条给出 `applied` / `skipped`。 > > 旧版本使用的 `GET /api/setup/` 已废弃:现在会返回 `405` 且不执行任何操作。如果曾经访问过旧 URL,建议轮换 `SETUP_SECRET`。 -> 数据库初始化后,已登录的管理员也可以在**管理后台 → 设置**里直接点「检查并升级数据库」按钮执行同样的检查与升级,无需密钥——管理员会话本身就是凭据。首次初始化仍需通过 `/setup` 页面或上面的 `curl` 命令。 +> 数据库初始化后,已登录的管理员也可以在**管理后台 → 设置**里直接点「检查并升级数据库」按钮执行同样的检查与升级,无需密钥——管理员会话本身就是凭据。全新安装时,第一个账号仍在 `/register` 注册(第一个用户自动成为管理员)。 --- @@ -322,6 +325,7 @@ git config blame.ignoreRevsFile .git-blame-ignore-revs | `D1_DATABASE_ID` | Variable | D1 数据库 ID | | `KV_NAMESPACE_ID` | Variable | KV 命名空间 ID | | `ALLOW_APP_DB_AS_TARGET` | Variable | *(可选,默认关闭)* 部署时注入 Worker;设为 `true` 允许把应用自身的数据库作为查询目标。未设置或为空时注入 `false`,开关保持关闭 | +| `LIVY_JARS_DIR` | Variable | *(可选,默认 `/data/jars`)* 部署时注入的普通 Variable(非密钥),裸 Livy jar 名的白名单目录。修改后需重新部署。 | ### Cloudflare 控制台(手动配置) diff --git a/worker/src/routes/__tests__/setup.test.ts b/worker/src/routes/__tests__/setup.test.ts index 6469fe4..ef4f258 100644 --- a/worker/src/routes/__tests__/setup.test.ts +++ b/worker/src/routes/__tests__/setup.test.ts @@ -109,6 +109,33 @@ describe('setup endpoint', () => { expect((await callWorker(env, '/api/setup', postJson({}))).status).toBe(400) }) + it('accepts the secret from the X-Setup-Secret header (deploy auto-upgrade path)', async () => { + const { db, calls } = fakeD1() + const res = await callWorker(fakeEnv({ DB: db }), '/api/setup', { + method: 'POST', + headers: { 'X-Setup-Secret': 'test-setup-secret' }, + }) + expect(res.status).toBe(200) + expect(await res.json()).toMatchObject({ + ok: true, + migrations: expect.arrayContaining([ + expect.objectContaining({ name: 'schema_v1', status: 'applied' }), + expect.objectContaining({ name: 'schema_v10', status: 'applied' }), + ]), + }) + expect(calls.some((c) => c.sql.includes('CREATE TABLE IF NOT EXISTS livy_batches'))).toBe(true) + }) + + it('rejects a wrong X-Setup-Secret header without initialising the schema', async () => { + const { db, calls } = fakeD1() + const res = await callWorker(fakeEnv({ DB: db }), '/api/setup', { + method: 'POST', + headers: { 'X-Setup-Secret': 'wrong' }, + }) + expect(res.status).toBe(403) + expect(calls.filter((c) => !c.sql.includes('rate_limits'))).toHaveLength(0) + }) + it('refuses to run when SETUP_SECRET is not configured', async () => { const { db, calls } = fakeD1() const res = await callWorker(fakeEnv({ DB: db, SETUP_SECRET: '' }), '/api/setup', postJson({ secret: 'x' })) diff --git a/worker/src/routes/setup.ts b/worker/src/routes/setup.ts index 2fd1363..b6960af 100644 --- a/worker/src/routes/setup.ts +++ b/worker/src/routes/setup.ts @@ -1,8 +1,8 @@ import { Hono } from 'hono' -import type { Env, Variables } from '../types' -import { getSetting } from '../lib/db' import { checkSetupRateLimit } from '../lib/auth' +import { getSetting } from '../lib/db' import { runSetup } from '../lib/setup' +import type { Env, Variables } from '../types' const setup = new Hono<{ Bindings: Env; Variables: Variables }>() @@ -41,7 +41,11 @@ setup.get('/state', async (c) => { // The old GET /api/setup/:secret form put the secret in the URL (history, logs, Referer). // It never initialises anything now; it only points callers at the POST form. setup.get('/*', (c) => - c.json({ error: 'Use POST /api/setup with a JSON body {"secret": ""}.' }, 405, { Allow: 'POST' }) + c.json( + { error: 'Use POST /api/setup with the X-Setup-Secret header (or JSON body {"secret": ""}).' }, + 405, + { Allow: 'POST' } + ) ) // ── POST /api/setup ─────────────────────────────────────────────────────────── @@ -61,11 +65,23 @@ setup.post('/', async (c) => { if (!expected || expected.trim() === '') { return c.json({ error: 'SETUP_SECRET is not configured on this Worker.' }, 500) } - const body = await c.req.json<{ secret?: unknown }>().catch(() => null) - if (typeof body?.secret !== 'string' || !body.secret) { - return c.json({ error: 'A JSON body {"secret": ""} is required.' }, 400) + + // The deploy auto-upgrade step (tech-scheme §9 item 4) is the standard caller and passes the secret in the + // X-Setup-Secret header, so it never lands in a URL, a body log or a Referer. The JSON body form + // is kept only for the browser /setup page, which predates the header contract. + const headerSecret = c.req.header('X-Setup-Secret') + let provided: string | undefined = headerSecret?.length ? headerSecret : undefined + if (provided === undefined) { + const body = await c.req.json<{ secret?: unknown }>().catch(() => null) + if (typeof body?.secret !== 'string' || !body.secret) { + return c.json( + { error: 'A setup secret is required (X-Setup-Secret header, or JSON body {"secret":""}).' }, + 400 + ) + } + provided = body.secret } - if (!(await secretsMatch(body.secret, expected))) { + if (!(await secretsMatch(provided, expected))) { return c.json({ error: 'Invalid setup secret.' }, 403) }