Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
133 changes: 133 additions & 0 deletions .github/scripts/apply-migrations.mjs
Original file line number Diff line number Diff line change
@@ -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()
50 changes: 50 additions & 0 deletions .github/scripts/test-apply-migrations.mjs
Original file line number Diff line number Diff line change
@@ -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'
)
})
})
2 changes: 1 addition & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
7 changes: 7 additions & 0 deletions .github/workflows/deploy.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
7 changes: 5 additions & 2 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 `_<prefix>_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://<your-domain>/api/setup -H 'Content-Type: application/json' -d '{"secret":"<SETUP_SECRET>"}'` (the old `GET /api/setup/<secret>` form returns 405). It applies the pending schema migrations and records them in the ledger table `_<prefix>_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 `_<prefix>_schema_migrations`, already-applied ones are skipped. Manual fallback: `curl -X POST https://<your-domain>/api/setup -H 'X-Setup-Secret: <SETUP_SECRET>'` (the old `GET /api/setup/<secret>` 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
Expand All @@ -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
Expand Down
Loading