Skip to content
WorkerHubPublic

About

自托管数据库查询工具,完全运行在Cloudflare Worker上,支持D1,MySQL,PostgreSQL,SparkSQL。

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

Zeta

中文文档 | English

A self-hosted SQL query interface for Cloudflare D1 databases. Runs entirely on Cloudflare — no servers to manage.

Version 1.2.0

Stack Stack Stack Stack


Features

  • SQL Notebooks — Multiple named SQL editor tabs per user, auto-saved, each independently bound to a database; supports rename, reorder, and up to 20 notebooks per user
  • SQL Editor — Full SQL input with syntax highlighting (CodeMirror 6), Ctrl/Cmd+Enter to run, partial selection execution, execution time and row count display; read queries return at most 5,000 rows, capped in the SQL itself
  • Saved Results — Every notebook run is saved with its results, so they survive switching tabs, leaving the page, reloading and changing devices; a notebook's runs sit in a row of numbered tabs (… #3 #2 #1, newest on the left) to switch between, delete or clear, and the History button in the top bar opens a resizable drawer with every run of the notebook (see Saved Query Results)
  • Multi-database — Connect multiple D1 databases; grant per-user read or write access per database
  • Auth — Email + password login, email verification, password reset, optional TOTP / Email OTP / Passkey (WebAuthn) two-factor authentication
  • Admin Panel — Manage users, database connections, permissions, and email/app settings
  • i18n — Built-in English and Chinese (Simplified) interface
  • Dark / Light / Auto theme — Follows system preference by default
  • 100% Cloudflare — Workers + D1 + KV + Workers Assets; the only external dependency is an email provider (Resend or SMTP)

Architecture

┌─────────────────────────────────┐
│  Cloudflare Worker (Hono.js)    │
│  ┌────────────┐  ┌────────────┐ │
│  │  /api/*    │  │  SPA       │ │
│  │  REST API  │  │  (Assets)  │ │
│  └─────┬──────┘  └────────────┘ │
│        │                        │
│  ┌─────▼──────┐  ┌────────────┐ │
│  │  D1 (app)  │  │  KV        │ │
│  │  + D1 DBs  │  │  (sessions)│ │
│  └────────────┘  └────────────┘ │
└─────────────────────────────────┘
Layer Technology
Runtime Cloudflare Workers
API framework Hono.js v4
App database D1 (SQLite) — users, notebooks, settings, history
Query targets Additional D1 databases (over the Cloudflare D1 HTTP API)
Sessions / 2FA state Cloudflare KV
Frontend React 19 + Vite + Tailwind CSS v4

Deployment via GitHub Actions

Deployment runs automatically on every push to main. No local tooling required beyond a browser.

Step 1 — Create Cloudflare resources

Go to the Cloudflare dashboard and create:

D1 database (Workers & Pages → D1 → Create database)

  • Name: zeta-db (or any name you like)
  • Note the Database ID shown after creation

KV namespace (Workers & Pages → KV → Create namespace)

  • Name: ZETA_KV
  • Note the Namespace ID

API token (My Profile → API Tokens → Create Token)

  • Use the Edit Cloudflare Workers template
  • Also grant D1 → Edit (account-scoped) — the same token authenticates deployments and is used at runtime to list and query D1 databases
  • Note the token value — it is shown only once

Also note your Account ID (right sidebar on the dashboard home).


Step 2 — Configure GitHub repository

In your GitHub repo → Settings → Secrets and variables → Actions:

Secrets (encrypted, for sensitive values):

Name Value
CLOUDFLARE_API_TOKEN The API token from Step 1 — used for Wrangler deploy authentication and at runtime to list and query the D1 databases you add in the admin panel, so it needs D1 → Edit permission (account-scoped)
JWT_SECRET Any random 64-char string — e.g. openssl rand -hex 32
SETUP_SECRET Any random string — e.g. openssl rand -hex 16

Variables (plain-text, for non-sensitive IDs):

Name Value
CLOUDFLARE_ACCOUNT_ID Your Cloudflare Account ID
D1_DATABASE_NAME e.g. zeta-db
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 _<prefix>_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.

Step 3 — Configure Cloudflare Worker secrets & variables

The three Worker secrets JWT_SECRET, SETUP_SECRET and CLOUDFLARE_API_TOKEN (the same token the workflow uses for deploy authentication, so it needs D1 → Edit) are injected at deploy time from the GitHub Secrets you set in Step 2 (the deploy workflow passes them to wrangler deploy --secrets-file) — do not set them here. The remaining values are deployment-specific and set directly in the Cloudflare dashboard, not in GitHub. APP_URL is a Cloudflare Worker Variable (dashboard, type Text) — not a GitHub Secret.

Go to Workers & Pages → zeta → Settings → Variables and Secrets:

Secret (type: Secret, dashboard-only):

Name How to generate
ENCRYPTION_KEY 64-char hex (32 bytes) — AES-GCM key for TOTP secrets and SMTP/Resend credentials. Dashboard-only: keep the existing Cloudflare secret as-is; do not add it to GitHub Secrets or CI (a new value makes stored TOTP credentials and encrypted config undecryptable).

Variables (type: Text):

Name Value
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, 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 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.

Upgrade warning: an existing deployment that never set TABLE_PREFIX used no prefix before the three-state change. After upgrading, an unset prefix resolves to the default zeta and points at different tables. Before upgrading, set TABLE_PREFIX explicitly to preserve your existing tables — an empty string keeps the old unprefixed tables — or rely on the startup/setup guard, which aborts instead of silently switching prefixes. In a shared D1 database, Zeta's migrations and the guard only match Zeta's own table family and never touch other projects' tables (SL_*, eNotify_*, TP_*, YL_*, TEMP_*, …).


Step 4 — Push to deploy

git push origin main

The GitHub Actions workflow will:

  1. Install dependencies
  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 — Database setup (manual fallback)

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:

curl -X POST https://<your-domain>/api/setup \
  -H 'X-Setup-Secret: <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:

{ "ok": true, "message": "Database initialised successfully. You can now register at /register — the first user becomes admin. On new installs registration then stays closed until an admin opens it in Admin → Settings." }

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, _<prefix>_schema_migrations (see 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/<SETUP_SECRET>. 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. On a new install, the first account still registers at /register — that first user becomes the admin.


Step 6 — Create the admin account

Visit https://<your-domain>/register. The first registered user automatically becomes admin.

On new installs, registration closes as soon as that first account exists. Afterwards:

  • Create accounts in Admin → Users, or open self-registration in Admin → Settings (consider also requiring email verification and 2FA there once an email provider is configured)
  • Add queryable D1 databases in Admin → Databases
  • Grant users access in Admin → Databases → Permissions

Schema migrations

The schema is defined exactly once, in worker/src/lib/migrations.ts: an ordered list of { name, sql } entries, parameterised by the effective TABLE_PREFIX. POST /api/setup — and the admin Check & upgrade database button, which runs the same runner — applies the entries the ledger has not recorded yet and records each of them only after its SQL succeeded.

  • Ledger table: _ + the prefix core + _schema_migrations. TABLE_PREFIX=ZETA → _ZETA_schema_migrations, the default prefix → _zeta_schema_migrations, no prefix → _schema_migrations. Like the business tables it is built in exactly one place (migrationsTable() in worker/src/lib/db.ts).
  • Collapsed history: Zeta has no production data, so the former worker/migrations/0001–0006 chain and the PRAGMA-driven upgrade probes were collapsed into a single schema_v1 holding the current whole schema. There is no baseline to seed and no chain to replay; future changes start at schema_v2. The pnpm migrate:* (wrangler d1 migrations apply) path is gone — the setup ledger is the only schema path, including for prefixed and shared deployments.
  • Writing a new migration: append one entry at the end (schema_v2, schema_v3, …). Never edit, reorder or rename an entry that has been merged — databases that already recorded it will not run it again. Migrations must be additive (CREATE TABLE/INDEX IF NOT EXISTS, ALTER TABLE … ADD COLUMN, INSERT OR IGNORE): no drops, no renames, no rewriting of existing data; a destructive change needs its own specification.
  • Guardrails: setup refuses to initialise when the database already holds a Zeta schema under a different prefix (the error names the TABLE_PREFIX that keeps it), and when its own ledger recorded migrations but the tables next to it are missing — in that case dropping the ledger table as well is what re-initialises from scratch.

Breaking change for existing self-hosted deployments. This version replaces the probing upgrade path with the ledger, so an older deployment's tables are not extended in place any more (the old probes added missing columns and rebuilt tables). Upgrade an existing deployment by deleting its own prefixed tables and its ledger table and running POST /api/setup again, or stay on the previous version. Zeta's own deployment has no production data — this concerns external, self-hosted copies only.

Adding a Queryable D1 Database

D1 databases are added from the admin panel — no binding, no GitHub Variables, no redeploy. The Worker reaches them over the Cloudflare D1 HTTP API using the CLOUDFLARE_API_TOKEN secret and CF_ACCOUNT_ID variable configured in Step 2.

  1. In Admin → Databases, click Add database.
  2. Pick a D1 database from your account's list. Zeta's own app database is excluded by default; after setting the ALLOW_APP_DB_AS_TARGET GitHub repo Variable (Step 2) and redeploying, it can be added too — its internal tables then stay read-only and destructive operations (DROP, TRUNCATE, …) are disabled on it.
  3. Optionally set a display name and description, then register it.
  4. Grant users read or write access in Admin → Databases → Permissions.

Databases registered before the HTTP API. A database added by the old binding method has no cf_database_id and can no longer be queried until you re-link it. In Admin → Databases, click Link on such a database and pick the matching Cloudflare database. Permissions, query history and saved runs are kept.


MySQL Compatibility

The SQL editor accepts a small set of MySQL introspection statements and rewrites them into read-only SQLite queries, so familiar MySQL commands work against D1 databases:

MySQL statement Returns Notes
SHOW TABLES name Tables and views of the current database, excluding sqlite_* and _cf_* internal tables
DESCRIBE tbl / DESC tbl / SHOW COLUMNS FROM tbl Field, Type, Null, Key, Default, Extra Null is YES/NO; Key is PRI for primary-key columns and '' otherwise; Default is SQLite's raw default expression
SHOW CREATE TABLE tbl Table, Create Table The original CREATE TABLE DDL
SHOW INDEX FROM tbl (also SHOW INDEXES / SHOW KEYS) Table, Non_unique, Key_name, Seq_in_index, Column_name, Collation, Cardinality, Sub_part, Packed, Null, Index_type, Comment, Index_comment, Visible, Expression Key_name is PRIMARY for the primary key; Cardinality and Expression are NULL

Statements are matched case-insensitively and accept a trailing ;; table names may be backtick-quoted, double-quoted or unquoted. The rewrite is read-only — a read-only user can run these, the 5,000-row cap still applies, and the original statement is what appears in query history and saved runs. SHOW DATABASES is not supported (each connection is bound to a single database) and returns a clear error; other SHOW … forms and any unrecognised syntax fall through to the normal path unchanged.


Saved Query Results

Every run of a notebook (one statement or several) is stored in the app database (notebook_runs) together with its results. Above the results, a notebook's runs are shown as tabs numbered from right to left — … #5 #4 #3 #2 #1, the newest on the left and selected when the notebook opens. The strip scrolls sideways (trackpad, touch, mouse wheel) and loads older runs on reaching its right end; hovering a tab shows when the run ran, its database, row count and SQL. A tab's × deletes that run right away (Delete / Backspace on a focused tab does the same, ←/→ switch tabs). History in the top bar opens a drawer with every run of the notebook: pick one to read its SQL and results, delete a single run, or clear them all after a confirmation; older runs load as the list is scrolled. The drawer opens at half the window width, and dragging its left edge (or moving it with the arrow keys) resizes it. A run's number never changes and is never reused: deleting or pruning runs leaves gaps (the oldest run left may be #37), and each notebook counts on its own.

Two limits keep it bounded, both set in Admin → Settings → Saved query runs:

Limit Default Range Effect
Runs kept per notebook 100 1–1000 Older runs of the notebook are deleted. Users can keep fewer under Profile → Saved query runs; the lower of the two applies.
Saved results per user 50 MB 1–1024 MB Beyond it, the user's oldest runs (in any notebook) are deleted.

Lowering either limit applies to the runs already stored right away. A single run stores at most 512 KB of results (D1 rows are capped at 2 MB); larger results keep their first rows, and the result panel says so. Separately, read queries return at most 5,000 rows: SELECT, VALUES and WITH statements run as SELECT * FROM (<statement>) LIMIT 5001, so the database itself stops early (PRAGMA / EXPLAIN are cut off afterwards).

Sizing: the app database holds up to users × saved results per user of runs — 10 users at the default 50 MB is about 500 MB, the size limit of a D1 database on the Workers Free plan (10 GB on Workers Paid). Adjust the limits to the number of users.

Security: saved results are stored unencrypted in the app database, like the queried data itself in its own database. Only their owner can list or read them, and reading re-checks access to the queried database every time: results stay hidden while a database is deactivated, and are deleted when the user's access to the database is revoked, or when the database, notebook or user is deleted.


Local Development

Run the Worker and web dev server concurrently in two terminals:

# Terminal 1 – Worker (port 8787)
cd worker && pnpm dev

# Terminal 2 – Vite (port 5173, proxies /api → 8787)
cd web && pnpm dev

Create worker/.dev.vars for local secrets (you can copy worker/.dev.vars.example as a template with empty placeholders):

JWT_SECRET=dev-jwt-secret
ENCRYPTION_KEY=0000000000000000000000000000000000000000000000000000000000000001
SETUP_SECRET=dev-setup-secret
APP_URL=http://localhost:8787
CLOUDFLARE_API_TOKEN=<a D1 → Edit API token>
CF_ACCOUNT_ID=<your Cloudflare Account ID>
ZETA_APP_DB_ID=<the D1 Database ID of this app's own database>

Initialise the local database:

curl -X POST http://localhost:8787/api/setup \
  -H 'Content-Type: application/json' \
  -d '{"secret":"dev-setup-secret"}'

Then open http://localhost:5173 in your browser.

Formatting

From the repo root:

pnpm format        # format the codebase with biome
pnpm format:check  # verify formatting without writing (also enforced in CI)

Pure-formatting commits are listed in .git-blame-ignore-revs, which GitHub's blame view reads automatically. To get the same behaviour locally, run once per clone:

git config blame.ignoreRevsFile .git-blame-ignore-revs

Configuration Reference

GitHub Secrets & Variables

Name Where Description
CLOUDFLARE_API_TOKEN Secret Wrangler deploy authentication and runtime D1 API access — lists and queries the D1 databases added in the admin panel (needs D1 → Edit permission)
JWT_SECRET Secret Signs access + refresh JWTs (HS256)
SETUP_SECRET Secret Protects POST /api/setup
CLOUDFLARE_ACCOUNT_ID Variable Cloudflare account ID
D1_DATABASE_NAME Variable D1 database name (e.g. zeta-db)
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)

Name Type Description
ENCRYPTION_KEY Secret 64-char hex — AES-GCM key for TOTP secrets and SMTP/Resend credentials. Dashboard-only: kept as the existing Cloudflare secret, not in GitHub Secrets or CI.
APP_URL Variable Full URL of your deployment; also the JWT iss/aud, so tokens from another deployment sharing JWT_SECRET are rejected
TABLE_PREFIX Variable (Optional) Prefix for 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. Set before first setup run. Immutable after initialisation.

CF_ACCOUNT_ID, ZETA_APP_DB_ID and ALLOW_APP_DB_AS_TARGET are not set here: wrangler.toml's [vars] injects them at deploy time from the GitHub Variables CLOUDFLARE_ACCOUNT_ID, D1_DATABASE_ID and ALLOW_APP_DB_AS_TARGET.

Upgrade warning: an existing deployment that never set TABLE_PREFIX used no prefix before the three-state change. After upgrading, an unset prefix resolves to the default zeta and points at different tables. Before upgrading, set TABLE_PREFIX explicitly to preserve your existing tables (an empty string keeps the old unprefixed tables) or rely on the startup/setup guard, which aborts instead of silently switching prefixes. In a shared D1 database, Zeta's migrations and the guard only match Zeta's own table family and never touch other projects' tables (SL_*, eNotify_*, TP_*, YL_*, TEMP_*, …).


API Overview

All endpoints live under /api/. Authentication uses short-lived JWT access tokens (Authorization header) plus an HttpOnly refresh-token cookie. Request bodies are capped at 4 MB (larger ones get 413).

Prefix Description
POST /api/auth/* Register, login, logout, token refresh, email verification, password reset, 2FA (TOTP / Email OTP / Passkey)
GET/PATCH /api/profile/* Profile, password change, TOTP setup/confirm/delete, passkey registration/delete. Deleting a TOTP or passkey requires a JSON body {"currentPassword": "..."}
GET /api/databases List accessible databases for the current user
POST /api/query Execute SQL against a queryable D1 database (/batch for several statements). Databases run over the D1 HTTP API. Reads return at most 5,000 rows (truncated: true beyond). With notebookId, the run is saved under that notebook and the response carries run_id / seq (its number) / executed_at
GET /api/query/history Query execution history (filterable by database)
GET/POST/PATCH/DELETE /api/notebooks CRUD for SQL notebooks (per-user, max 20)
GET/DELETE /api/notebooks/:id/runs[/:runId] A notebook's saved runs: list (highest number seq first, limit plus before=<seq> or offset), read one with its results, delete one, or clear all
GET/PUT /api/profile/run-settings The user's own run limit (run_limit, null follows the admin limit) and storage usage
GET/PUT /api/profile/theme-color The account's brand-colour preset (theme_color, one of the twelve presets; null = never set, shown as the default terracotta). Until the database has run the schema upgrade, GET answers null and PUT answers 503
GET/POST/PATCH/DELETE /api/admin/* Admin-only: users, databases, permissions, settings
POST /api/admin/setup Admin-only: runs the same schema initialisation/upgrade as POST /api/setup without SETUP_SECRET — the admin session is the credential
POST /api/setup Idempotent schema migration: applies the pending ledger entries and returns tablePrefix plus each migration's applied/skipped result (JSON body {"secret": "<SETUP_SECRET>"}). Rate-limited to 3 attempts / 10 min per IP
GET /api/setup/state Public: {"enabled": boolean} — whether the /setup page is enabled
GET /api/health Health check

Tech Stack

Runtime Cloudflare Workers
API Hono v4
Database Cloudflare D1 (SQLite)
KV Cloudflare KV
Frontend React 19, Vite, Tailwind CSS v4
SQL Editor CodeMirror 6 + @codemirror/lang-sql
Auth PBKDF2-SHA256 passwords, HS256 JWTs, WebAuthn passkeys
2FA TOTP (otpauth), Email OTP, Passkey
Email Resend or custom SMTP
Deploy wrangler deploy via GitHub Actions

License

MIT

About

自托管数据库查询工具,完全运行在Cloudflare Worker上,支持D1,MySQL,PostgreSQL,SparkSQL。

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages