diff --git a/.github/scripts/d1-migrations.mjs b/.github/scripts/d1-migrations.mjs new file mode 100644 index 0000000..fca89f7 --- /dev/null +++ b/.github/scripts/d1-migrations.mjs @@ -0,0 +1,100 @@ +// Emits the setup-route migrations for a TABLE_PREFIX as JSON, for +// d1-prefixed-migrations.sh. The migrations come straight from +// apps/worker/src/lib/migrations.ts (loaded via Node's TypeScript type +// stripping), so the deploy workflow and POST /setup can never drift apart. +// +// node d1-migrations.mjs +// -> { "historyTable": "_SL_schema_migrations", +// "migrations": [{ "name": "schema_v1", "sql": "" }, ...] } +// +// The production D1 database is shared with other applications, so every +// statement is checked before anything is emitted: only additive statements +// (CREATE TABLE/INDEX IF NOT EXISTS, ALTER TABLE ... ADD, INSERT INTO) are +// allowed, and each must target a table carrying this app's prefix. Anything +// else aborts the deploy. + +import { + createMigrationsTableSql, + getMigrations, + migrationsTable, +} from '../../apps/worker/src/lib/migrations.ts'; + +const prefix = process.argv[2] ?? ''; +if (!/^[A-Za-z0-9_]+$/.test(prefix)) { + console.error( + `Invalid table prefix ${JSON.stringify(prefix)}: expected [A-Za-z0-9_]+`, + ); + process.exit(1); +} + +const ownTable = (name) => name.startsWith(`${prefix}_`); + +// Statement shapes allowed in a migration; the capture group is the table +// written to. Quoted identifiers deliberately do not match. +const ALLOWED = [ + /^CREATE TABLE IF NOT EXISTS (\w+) ?\(/i, + /^CREATE INDEX IF NOT EXISTS \w+ ON (\w+) ?\(/i, + /^ALTER TABLE (\w+) ADD (?:COLUMN )?\w+ /i, + /^INSERT OR IGNORE INTO (\w+) ?\(/i, +]; + +function statements(sql) { + return sql + .replace(/'(?:[^']|'')*'/g, "''") // string literals can't hide SQL + .replace(/--[^\n]*/g, '') + .split(';') + .map((s) => s.replace(/\s+/g, ' ').trim()) + .filter(Boolean); +} + +function check(migration) { + if (!/^schema_v\d+$/.test(migration.name)) { + throw new Error(`unexpected migration name ${migration.name}`); + } + for (const stmt of statements(migration.sql)) { + const match = ALLOWED.map((re) => stmt.match(re)).find(Boolean); + if (!match) { + throw new Error( + `${migration.name}: statement is not additive: ${stmt.slice(0, 120)}`, + ); + } + const touched = [ + match[1], + ...Array.from(stmt.matchAll(/REFERENCES (\w+)/gi), (m) => m[1]), + ]; + const foreign = touched.filter((t) => !ownTable(t)); + if (foreign.length > 0) { + throw new Error( + `${migration.name}: references table(s) without prefix "${prefix}_": ${foreign.join(', ')}`, + ); + } + } +} + +try { + const historyTable = migrationsTable(prefix); + const migrations = getMigrations(prefix); + const names = migrations.map((m) => m.name); + if (new Set(names).size !== names.length) { + throw new Error(`duplicate migration names: ${names.join(', ')}`); + } + for (const m of migrations) check(m); + + // Same history table and row format as POST /setup. The history row goes in + // the same request, after the DDL: D1 stops at the first failing statement, + // so a migration is never recorded without having run. + const out = migrations.map((m) => ({ + name: m.name, + sql: [ + `${createMigrationsTableSql(prefix)};`, + m.sql.trim(), + `INSERT INTO ${historyTable} (name) VALUES ('${m.name}');`, + ].join('\n'), + })); + process.stdout.write( + `${JSON.stringify({ historyTable, migrations: out }, null, 2)}\n`, + ); +} catch (err) { + console.error(`Refusing to emit migrations: ${err.message}`); + process.exit(1); +} diff --git a/.github/scripts/d1-prefixed-migrations.sh b/.github/scripts/d1-prefixed-migrations.sh new file mode 100644 index 0000000..322119e --- /dev/null +++ b/.github/scripts/d1-prefixed-migrations.sh @@ -0,0 +1,136 @@ +#!/usr/bin/env bash +# Applies the setup-route migrations (apps/worker/src/lib/migrations.ts) to a +# D1 database whose tables carry TABLE_PREFIX. Runs before the new code is +# deployed, so migrations must stay additive (expand → deploy → contract). +# Applied migrations are recorded in `__schema_migrations`, exactly +# like POST /setup does, so both paths stay interchangeable. +# Run from apps/worker (needs wrangler.toml with real IDs injected). +# +# The production database is shared with other applications, hence: +# - d1-migrations.mjs rejects any statement that is not additive or that +# targets a table without this app's prefix; +# - every deployed Worker version must use the same TABLE_PREFIX, so a +# mistyped GitHub variable can't migrate another app's tables; +# - prefixed tables without a migration history are never touched. +# +# D1_LOCATION=local targets the local D1 database instead (for testing this +# script); the deployed-Worker check is skipped then. +set -euo pipefail + +prefix="${TABLE_PREFIX:-}" +location="${D1_LOCATION:-remote}" +here="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" + +if ! [[ "$prefix" =~ ^[A-Za-z0-9_]+$ ]]; then + echo "::error::TABLE_PREFIX must be set and may only contain letters, digits and underscores (got '$prefix')." + exit 1 +fi +if [[ "$location" != remote && "$location" != local ]]; then + echo "::error::D1_LOCATION must be 'remote' or 'local', got '$location'" + exit 1 +fi + +d1_query() { + pnpm exec wrangler d1 execute DB "--$location" --json --command "$1" | + jq -r '.[0].results[] | .name' +} + +# Fails (and so aborts the deploy) if any migration is not additive or touches +# a table outside this app's prefix. +plan="$(node --disable-warning=MODULE_TYPELESS_PACKAGE_JSON "$here/d1-migrations.mjs" "$prefix")" +history="$(jq -r '.historyTable' <<<"$plan")" +known=() +while IFS= read -r name; do + known+=("$name") +done < <(jq -r '.migrations[].name' <<<"$plan") + +tables="$(d1_query "SELECT name FROM sqlite_master WHERE type = 'table'")" +# SQLite identifiers are case-insensitive, so match the prefix the same way. +own_tables="$(grep -i "^${prefix}_" <<<"$tables" || true)" +has_history=false +if grep -qixF "$history" <<<"$tables"; then + has_history=true +fi + +if [[ "$location" == remote ]]; then + err="$(mktemp)" + trap 'rm -f "$err"' EXIT + if status="$(pnpm exec wrangler deployments status --json 2>"$err")"; then + versions="$(jq -er '.versions | select(length > 0) | .[].version_id | strings | select(length > 0)' <<<"$status")" + if [[ -z "$versions" ]]; then + echo "::error::No active Worker versions returned; refusing to migrate." + exit 1 + fi + for version in $versions; do + live="$(bash "$here/worker-table-prefix.sh" "$version")" + live="${live//[^A-Za-z0-9_]/}" + if [[ "$live" != "$prefix" ]]; then + echo "::error::Deployed Worker version $version uses TABLE_PREFIX='$live', but the GitHub variable is '$prefix'. Make them match before deploying; refusing to migrate." + exit 1 + fi + done + echo "Deployed Worker uses TABLE_PREFIX=$prefix (version(s): $(tr '\n' ' ' <<<"$versions"))." + elif [[ "$has_history" == false && -z "$own_tables" ]]; then + cat "$err" >&2 + echo "::warning::Could not read the deployed Worker (first deploy?). The database has no ${prefix}_ tables yet, so creating them is safe." + else + cat "$err" >&2 + echo "::error::Could not read the deployed Worker's TABLE_PREFIX to confirm which tables belong to this app; refusing to migrate existing ${prefix}_ tables." + exit 1 + fi +fi + +if [[ "$has_history" == true ]]; then + applied="$(d1_query "SELECT name FROM $history ORDER BY applied_at, name")" +elif [[ -n "$own_tables" ]]; then + echo "::error::Found ${prefix}_ tables but no $history table: $(tr '\n' ' ' <<<"$own_tables")" + echo "::error::They may belong to another application or predate the migration history; refusing to migrate. Record the applied migrations in $history first." + exit 1 +else + applied="" + echo "No ${prefix}_ tables yet — fresh install." +fi + +# Don't guess a baseline for existing tables, even if the history table exists +# but is empty. Replaying v1 could silently record a partial or foreign schema. +if [[ -n "$own_tables" ]] && ! grep -qxF schema_v1 <<<"$applied"; then + echo "::error::Existing ${prefix}_ tables have no schema_v1 record in $history; refusing to baseline or replay migrations." + exit 1 +fi + +pending=() +for name in "${known[@]}"; do + if ! grep -qxF "$name" <<<"$applied"; then + pending+=("$name") + fi +done +while IFS= read -r name; do + if [[ -n "$name" ]] && ! printf '%s\n' "${known[@]}" | grep -qxF "$name"; then + echo "::warning::$history records '$name', which this commit does not know (deploying older code?). Ignoring it." + fi +done <<<"$applied" + +echo "Migration history ($history, $location): $(tr '\n' ' ' <<<"${applied:-}")" +if [[ ${#pending[@]} -eq 0 ]]; then + echo "Planned migrations: none — schema is up to date." + exit 0 +fi +echo "Planned migrations: ${pending[*]}" + +for name in "${pending[@]}"; do + sql="$(jq -r --arg n "$name" '.migrations[] | select(.name == $n) | .sql' <<<"$plan")" + echo "::group::$name" + echo "$sql" + echo "::endgroup::" + echo "Applying ${name}..." + pnpm exec wrangler d1 execute DB "--$location" --command "$sql" +done + +recorded="$(d1_query "SELECT name FROM $history")" +for name in "${known[@]}"; do + if ! grep -qxF "$name" <<<"$recorded"; then + echo "::error::$name is not recorded in $history after applying migrations." + exit 1 + fi +done +echo "Applied: ${pending[*]}" diff --git a/.github/scripts/d1-prepare-migrations.sh b/.github/scripts/d1-prepare-migrations.sh index e69e06d..4f1f9b5 100755 --- a/.github/scripts/d1-prepare-migrations.sh +++ b/.github/scripts/d1-prepare-migrations.sh @@ -11,22 +11,37 @@ # # setup.ts migration `schema_vN` <=> migrations/NNNN_*.sql (N zero-padded) # -# Writes `mode=apply` or `mode=skip` to $GITHUB_OUTPUT (stdout if unset). -# apply — wrangler migrations can run safely -# skip — TABLE_PREFIX is in use; migrations/*.sql are not prefix-aware, so -# the schema must keep being managed through the setup route +# Writes `mode=apply`, `mode=prefixed` or `mode=skip` to $GITHUB_OUTPUT +# (stdout if unset). +# apply — wrangler migrations can run safely +# prefixed — TABLE_PREFIX is in use; migrations/*.sql are not prefix-aware, +# so d1-prefixed-migrations.sh applies the setup-route migrations +# skip — prefixed tables found but TABLE_PREFIX is not set here; the +# schema must keep being managed through the setup route +# +# D1_LOCATION=local runs the queries against the local D1 database instead of +# the remote one (for testing this script). set -euo pipefail out="${GITHUB_OUTPUT:-/dev/stdout}" +location="${D1_LOCATION:-remote}" +if [[ "$location" != remote && "$location" != local ]]; then + echo "::error::D1_LOCATION must be 'remote' or 'local', got '$location'" + exit 1 +fi if [[ -n "${TABLE_PREFIX:-}" ]]; then - echo "::warning::TABLE_PREFIX is set; skipping wrangler D1 migrations. Run the setup route after deploy to apply schema changes." - echo "mode=skip" >>"$out" + if ! [[ "$TABLE_PREFIX" =~ ^[A-Za-z0-9_]+$ ]]; then + echo "::error::TABLE_PREFIX '$TABLE_PREFIX' may only contain letters, digits and underscores." + exit 1 + fi + echo "TABLE_PREFIX=$TABLE_PREFIX — prefixed setup-route migrations will be applied instead of wrangler's." + echo "mode=prefixed" >>"$out" exit 0 fi d1_query() { - pnpm exec wrangler d1 execute DB --remote --json --command "$1" | + pnpm exec wrangler d1 execute DB "--$location" --json --command "$1" | jq -r '.[0].results[] | .name' } @@ -41,7 +56,7 @@ fi if ! has_table users; then if grep -Eq '^(_[A-Za-z0-9_]+_schema_migrations|[A-Za-z0-9_]+_users)$' <<<"$tables"; then - echo "::warning::Found prefixed tables but no unprefixed schema; looks like TABLE_PREFIX is in use. Set the TABLE_PREFIX variable on the production environment. Skipping wrangler D1 migrations." + echo "::warning::Found prefixed tables but no unprefixed schema; looks like TABLE_PREFIX is in use. Set the TABLE_PREFIX variable on the production environment so deploys apply prefixed migrations. Skipping D1 migrations." echo "mode=skip" >>"$out" exit 0 fi @@ -88,7 +103,7 @@ if [[ ${#values[@]} -eq 0 ]]; then fi echo "Baselining d1_migrations with: ${values[*]}" -pnpm exec wrangler d1 execute DB --remote --command " +pnpm exec wrangler d1 execute DB "--$location" --command " CREATE TABLE IF NOT EXISTS d1_migrations ( id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT UNIQUE, diff --git a/.github/scripts/smoke-test.sh b/.github/scripts/smoke-test.sh new file mode 100644 index 0000000..c936c00 --- /dev/null +++ b/.github/scripts/smoke-test.sh @@ -0,0 +1,50 @@ +#!/usr/bin/env bash +# Public-hostname probes. A 403 with Cloudflare's documented challenge header is +# inconclusive (warning), not an application failure. The separate control-plane +# deployment check must succeed even if every HTTP probe is challenged. +set -euo pipefail + +if [[ -z "${APP_URL:-}" ]]; then + echo "::error::Variable APP_URL is not set; cannot verify the deployment" + exit 1 +fi +base="${APP_URL%/}" +tmp="$(mktemp -d)" +trap 'rm -rf "$tmp"' EXIT + +probe() { # probe [jq filter the JSON body must satisfy] + local path="$1" filter="${2:-}" code attempt + for attempt in 1 2 3 4 5 6; do + # One request per attempt keeps the headers/body/status together: curl's + # built-in retries can leave earlier responses in the headers file. + if ! code="$(curl -sS --connect-timeout 10 --max-time 15 \ + -D "$tmp/headers" -o "$tmp/body" -w '%{http_code}' "$base$path")"; then + code=000 + fi + if [[ "$code" == 2?? ]]; then + if [[ -n "$filter" ]] && ! jq -e "$filter" "$tmp/body" >/dev/null; then + echo "::error::GET $path -> $code, but the response failed the check: $filter" + return 1 + fi + echo "GET $path -> $code" + return 0 + fi + if [[ "$code" == 403 ]] && grep -qiE '^cf-mitigated:[[:blank:]]*challenge[[:space:]]*$' "$tmp/headers"; then + echo "::warning::GET $path -> 403 Cloudflare challenge (cf-mitigated: challenge). HTTP check inconclusive; relying on the API-side deployment check. Keep Bot Fight Mode enabled." + return 0 + fi + if [[ $attempt -lt 6 ]]; then + sleep 5 + fi + done + echo "::error::GET $path -> HTTP $code (000 means transport failure)" + return 1 +} + +probe /api/health '.status == "ok"' +probe / +# This reads the settings table for both migration paths, including TABLE_PREFIX. +# A challenge still means inconclusive, NOT that the DB check passed. +if [[ "${CHECK_DB:-false}" == true ]]; then + probe /api/config 'has("appName")' +fi diff --git a/.github/scripts/test-d1-migrations.mjs b/.github/scripts/test-d1-migrations.mjs new file mode 100644 index 0000000..6e8230b --- /dev/null +++ b/.github/scripts/test-d1-migrations.mjs @@ -0,0 +1,258 @@ +// 本地 D1 回归测试,不需要 Cloudflare 凭据,也不接触 apps/worker/.wrangler。 +// 在仓库根目录运行:node --test .github/scripts/test-d1-migrations.mjs +import assert from 'node:assert/strict'; +import { execFileSync } from 'node:child_process'; +import { mkdtempSync, rmSync, symlinkSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { test } from 'node:test'; +import { fileURLToPath } from 'node:url'; +import { + createMigrationsTableSql, + getMigrations, + migrationsTable, +} from '../../apps/worker/src/lib/migrations.ts'; + +const scripts = fileURLToPath(new URL('.', import.meta.url)); +const worker = fileURLToPath(new URL('../../apps/worker/', import.meta.url)); + +function fixture(t) { + const cwd = mkdtempSync(join(tmpdir(), 'shortlink-d1-test-')); + t.after(() => rmSync(cwd, { recursive: true, force: true })); + writeFileSync(join(cwd, 'package.json'), '{"private":true}'); + writeFileSync( + join(cwd, 'wrangler.toml'), + `name = "shortlink-migration-test" +compatibility_date = "2025-04-01" +[[d1_databases]] +binding = "DB" +database_name = "shortlink-test" +database_id = "00000000-0000-0000-0000-000000000000" +migrations_dir = "migrations" +`, + ); + symlinkSync(join(worker, 'node_modules'), join(cwd, 'node_modules')); + symlinkSync(join(worker, 'migrations'), join(cwd, 'migrations')); + const env = { + ...process.env, + WRANGLER_SEND_METRICS: 'false', + D1_LOCATION: 'local', + GITHUB_OUTPUT: join(cwd, 'outputs'), + }; + const run = (command, args, extraEnv = {}) => + execFileSync(command, args, { + cwd, + env: { ...env, ...extraEnv }, + encoding: 'utf8', + stdio: ['ignore', 'pipe', 'pipe'], + }); + const query = (sql) => + JSON.parse( + run('pnpm', [ + 'exec', + 'wrangler', + 'd1', + 'execute', + 'DB', + '--local', + '--json', + '--command', + sql, + ]), + ).map((r) => r.results); + const script = (name, prefix) => + run('bash', [join(scripts, name)], { TABLE_PREFIX: prefix }); + const setup = (prefix, names) => { + query( + `${createMigrationsTableSql(prefix)};${getMigrations(prefix) + .filter((m) => names.includes(m.name)) + .map( + (m) => + `${m.sql}\nINSERT INTO ${migrationsTable(prefix)} (name) VALUES ('${m.name}');`, + ) + .join('\n')}`, + ); + }; + const foreignSnapshot = () => + query(`SELECT type,name,tbl_name,sql FROM sqlite_master + WHERE tbl_name IN ('users','ZETA_users','ZETA_links') ORDER BY name; + SELECT * FROM users ORDER BY id; + SELECT * FROM ZETA_users ORDER BY id; + SELECT * FROM ZETA_links ORDER BY id;`); + const shared = () => { + query(`CREATE TABLE users (id TEXT PRIMARY KEY, email TEXT); + INSERT INTO users VALUES ('other-user', 'keep@example.com'); + CREATE TABLE ZETA_users (id TEXT PRIMARY KEY); + INSERT INTO ZETA_users VALUES ('zeta-user'); + CREATE TABLE ZETA_links (id TEXT, slug TEXT); + INSERT INTO ZETA_links VALUES ('zeta-link', 'keep'); + CREATE INDEX idx_ZETA_links_slug ON ZETA_links(slug);`); + return foreignSnapshot(); + }; + // SQLite 索引名全库唯一:若别的应用已占用同名索引,CREATE INDEX IF NOT EXISTS + // 会静默跳过。逐个核对迁移声明的索引确实建在本应用的表上。 + const assertOwnIndexes = (prefix) => { + const expected = getMigrations(prefix) + .flatMap((m) => + Array.from( + m.sql.matchAll(/CREATE INDEX IF NOT EXISTS (\w+)\s+ON (\w+)/g), + ([, name, tbl_name]) => ({ name, tbl_name }), + ), + ) + .sort((a, b) => a.name.localeCompare(b.name)); + assert.ok(expected.length > 0); + assert.deepEqual( + query(`SELECT name, tbl_name FROM sqlite_master + WHERE type = 'index' AND name IN (${expected.map((i) => `'${i.name}'`).join(',')}) + ORDER BY name`)[0], + expected, + ); + }; + return { + run, + query, + script, + setup, + shared, + foreignSnapshot, + assertOwnIndexes, + env, + cwd, + }; +} + +test('无前缀:保留 Wrangler 迁移路径及重复执行行为', (t) => { + const f = fixture(t); + assert.match(f.script('d1-prepare-migrations.sh', ''), /Empty database/); + f.run('pnpm', [ + 'exec', + 'wrangler', + 'd1', + 'migrations', + 'apply', + 'DB', + '--local', + ]); + assert.deepEqual(f.query('SELECT name FROM d1_migrations ORDER BY name')[0], [ + { name: '0001_init.sql' }, + { name: '0002_token_version.sql' }, + ]); + assert.match(f.script('d1-prepare-migrations.sh', ''), /already tracked/); + assert.match( + f.run('pnpm', [ + 'exec', + 'wrangler', + 'd1', + 'migrations', + 'apply', + 'DB', + '--local', + ]), + /No migrations to apply/, + ); +}); + +test('无前缀:setup 历史可 baseline 为 Wrangler 历史', (t) => { + const f = fixture(t); + f.setup('', ['schema_v1', 'schema_v2']); + assert.match(f.script('d1-prepare-migrations.sh', ''), /Baselining/); + assert.deepEqual(f.query('SELECT name FROM d1_migrations ORDER BY name')[0], [ + { name: '0001_init.sql' }, + { name: '0002_token_version.sql' }, + ]); +}); + +test('有前缀且已全部执行:只打印空计划,仅执行 SELECT,共享库不变', (t) => { + const f = fixture(t); + const before = f.shared(); + f.setup('SL', ['schema_v1', 'schema_v2']); + assert.match(f.script('d1-prepare-migrations.sh', 'SL'), /prefixed/); + // Bash trace 核对脚本实际调用的每条 D1 SQL,不能只比较最终数据。 + const trace = f.run( + 'bash', + [ + '-c', + 'bash -x "$1" 2>&1', + 'test', + join(scripts, 'd1-prefixed-migrations.sh'), + ], + { TABLE_PREFIX: 'SL' }, + ); + assert.match(trace, /Planned migrations: none/); + const calls = trace + .split('\n') + .filter((line) => /^\++ pnpm exec wrangler d1 execute /.test(line)); + assert.equal(calls.length, 2, trace); + for (const call of calls) { + assert.match(call, /--local --json --command 'SELECT /); + } + assert.deepEqual(f.foreignSnapshot(), before); +}); + +test('有前缀且有待执行迁移:仅应用 v2,保留其他应用的表、索引和数据', (t) => { + const f = fixture(t); + const before = f.shared(); + f.setup('SL', ['schema_v1']); + f.query(`INSERT INTO SL_users (email,username,password_hash) + VALUES ('sl@example.com','sl-user','hash')`); + assert.match( + f.script('d1-prefixed-migrations.sh', 'SL'), + /Planned migrations: schema_v2\n/, + ); + assert.deepEqual( + f.query('SELECT name FROM _SL_schema_migrations ORDER BY name')[0], + [{ name: 'schema_v1' }, { name: 'schema_v2' }], + ); + f.assertOwnIndexes('SL'); + assert.deepEqual(f.query('SELECT email,token_version FROM SL_users')[0], [ + { email: 'sl@example.com', token_version: 0 }, + ]); + assert.deepEqual(f.foreignSnapshot(), before); + assert.match( + f.script('d1-prefixed-migrations.sh', 'SL'), + /Planned migrations: none/, + ); +}); + +test('有前缀的新安装:只创建本应用的表,共享库保持不变', (t) => { + const f = fixture(t); + const before = f.shared(); + assert.match( + f.script('d1-prefixed-migrations.sh', 'SL'), + /Planned migrations: schema_v1 schema_v2/, + ); + assert.deepEqual(f.foreignSnapshot(), before); + assert.deepEqual( + f.query('SELECT name FROM _SL_schema_migrations ORDER BY name')[0], + [{ name: 'schema_v1' }, { name: 'schema_v2' }], + ); + f.assertOwnIndexes('SL'); +}); + +test('已有业务表但无历史或历史为空:拒绝猜测 baseline,不写入其他应用', (t) => { + const f = fixture(t); + const before = f.shared(); + f.query('CREATE TABLE SL_users (id TEXT)'); + assert.throws( + () => f.script('d1-prefixed-migrations.sh', 'SL'), + /Command failed/, + ); + f.query(createMigrationsTableSql('SL')); + assert.throws( + () => f.script('d1-prefixed-migrations.sh', 'SL'), + /Command failed/, + ); + assert.deepEqual(f.query('SELECT name FROM _SL_schema_migrations')[0], []); + assert.deepEqual(f.foreignSnapshot(), before); +}); + +test('已知限制:别的应用占用同名索引时,本应用索引会被静默跳过(检查可发现)', (t) => { + const f = fixture(t); + f.shared(); + f.query('CREATE INDEX idx_links_slug ON ZETA_links(slug)'); + assert.match( + f.script('d1-prefixed-migrations.sh', 'SL'), + /Planned migrations: schema_v1 schema_v2/, + ); + assert.throws(() => f.assertOwnIndexes('SL'), /Expected values/); +}); diff --git a/.github/scripts/test-deploy-checks.mjs b/.github/scripts/test-deploy-checks.mjs new file mode 100644 index 0000000..41707d6 --- /dev/null +++ b/.github/scripts/test-deploy-checks.mjs @@ -0,0 +1,157 @@ +// 在仓库根目录运行:node --test .github/scripts/test-deploy-checks.mjs +// HTTP 检查使用真实本地服务;控制面检查用固定响应模拟 Wrangler,不调用生产 API。 +import assert from 'node:assert/strict'; +import { execFile, execFileSync } from 'node:child_process'; +import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'; +import { createServer } from 'node:http'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { test } from 'node:test'; +import { fileURLToPath } from 'node:url'; +import { promisify } from 'node:util'; + +const scripts = fileURLToPath(new URL('.', import.meta.url)); +const exec = promisify(execFile); + +function fixture(t) { + const dir = mkdtempSync(join(tmpdir(), 'shortlink-deploy-test-')); + t.after(() => rmSync(dir, { recursive: true, force: true })); + // 仅跳过重试等待,不替换 curl 或 jq。 + writeFileSync(join(dir, 'sleep'), '#!/bin/sh\nexit 0\n', { mode: 0o755 }); + return { + dir, + env: { ...process.env, PATH: `${dir}:${process.env.PATH}` }, + }; +} + +for (const scenario of [ + { name: '正常响应,包含数据库检查', code: 200, ok: true }, + { + name: '403 challenge 仅警告,仍检查全部路径', + code: 403, + challenge: true, + ok: true, + }, + { name: '普通 403 必须失败', code: 403, ok: false }, + { + name: '500 必须失败,即使有 challenge 头', + code: 500, + challenge: true, + ok: false, + }, + { name: '302 不得当成成功', code: 302, ok: false }, + { + name: '200 但数据库响应错误必须失败', + code: 200, + badConfig: true, + ok: false, + }, +]) { + test(`冒烟:${scenario.name}`, async (t) => { + const f = fixture(t); + const paths = []; + const server = createServer((req, res) => { + paths.push(req.url); + res.writeHead( + scenario.code, + scenario.challenge ? { 'Cf-Mitigated': 'challenge' } : {}, + ); + res.end( + req.url === '/api/health' + ? '{"status":"ok"}' + : req.url === '/api/config' + ? scenario.badConfig + ? '{"error":"database unavailable"}' + : '{"appName":"ShortLink"}' + : 'ShortLink', + ); + }); + await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)); + t.after(() => new Promise((resolve) => server.close(resolve))); + const result = await exec('bash', [join(scripts, 'smoke-test.sh')], { + env: { + ...f.env, + APP_URL: `http://127.0.0.1:${server.address().port}`, + CHECK_DB: 'true', + }, + }).then( + (r) => ({ ok: true, output: r.stdout }), + (e) => ({ ok: false, output: e.stdout }), + ); + assert.equal(result.ok, scenario.ok, result.output); + if (scenario.ok) { + assert.deepEqual(paths, ['/api/health', '/', '/api/config']); + if (scenario.challenge) { + assert.equal(result.output.match(/::warning::/g)?.length, 3); + assert.doesNotMatch(result.output, /::error::/); + } + } else { + assert.match(result.output, /::error::/); + } + }); +} + +for (const scenario of [ + { + name: '本次上传版本承载 100% 流量', + version: 'uploaded', + percentage: 100, + prefix: 'SL', + ok: true, + }, + { + name: '仍在运行旧版本', + version: 'old', + percentage: 100, + prefix: 'SL', + ok: false, + }, + { + name: '本次版本只承载部分流量', + version: 'uploaded', + percentage: 50, + prefix: 'SL', + ok: false, + }, + { + name: '版本正确但前缀不一致', + version: 'uploaded', + percentage: 100, + prefix: 'ZETA', + ok: false, + }, +]) { + test(`控制面:${scenario.name}`, (t) => { + const f = fixture(t); + writeFileSync( + join(f.dir, 'pnpm'), + `#!/bin/sh +case "$*" in + 'exec wrangler deployments status --json') + printf '%s\\n' '{"versions":[{"version_id":"${scenario.version}","percentage":${scenario.percentage}}]}' ;; + 'exec wrangler versions view uploaded --json') + printf '%s\\n' '{"id":"uploaded","resources":{"bindings":[{"name":"TABLE_PREFIX","type":"plain_text","text":"${scenario.prefix}"}]}}' ;; + *) exit 99 ;; +esac +`, + { mode: 0o755 }, + ); + const output = join(f.dir, 'deploy.ndjson'); + writeFileSync(output, '{"type":"deploy","version_id":"uploaded"}\n'); + const run = () => + execFileSync('bash', [join(scripts, 'verify-deployment.sh')], { + env: { + ...f.env, + TABLE_PREFIX: 'SL', + WRANGLER_OUTPUT_FILE_PATH: output, + }, + encoding: 'utf8', + stdio: ['ignore', 'pipe', 'pipe'], + }); + if (scenario.ok) { + assert.match(run(), /serves 100% of production traffic/); + } else { + assert.throws(run, /Command failed/); + } + }); +} diff --git a/.github/scripts/verify-deployment.sh b/.github/scripts/verify-deployment.sh new file mode 100644 index 0000000..f4f99ee --- /dev/null +++ b/.github/scripts/verify-deployment.sh @@ -0,0 +1,52 @@ +#!/usr/bin/env bash +# Confirms through the Cloudflare API that the version uploaded by +# `wrangler deploy` is serving 100% of production traffic, with the +# TABLE_PREFIX the migrations were applied for. Unlike an HTTP probe of the +# public hostname this can't be intercepted by the zone's bot protection (Bot +# Fight Mode challenges GitHub-hosted runners and cannot be bypassed). +# Run from apps/worker (needs wrangler.toml with real IDs injected). +# +# Env: WRANGLER_OUTPUT_FILE_PATH — the ND-JSON file `wrangler deploy` wrote +# TABLE_PREFIX — GitHub variable (may be empty) +set -euo pipefail + +here="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +output="${WRANGLER_OUTPUT_FILE_PATH:?WRANGLER_OUTPUT_FILE_PATH is not set}" + +version="" +if [[ -f "$output" ]]; then + version="$(jq -rs '[.[] | select(.type == "deploy")] | last | .version_id // empty' "$output")" +fi +if [[ -z "$version" ]]; then + echo "::error::No deployed version ID found in $output; cannot verify the deployment." + exit 1 +fi +echo "Uploaded version: $version" + +status="" +for attempt in 1 2 3 4 5; do + if status="$(pnpm exec wrangler deployments status --json)" && + jq -e --arg v "$version" \ + '.versions | length == 1 and .[0].version_id == $v and .[0].percentage == 100' \ + <<<"$status" >/dev/null; then + echo "Version $version serves 100% of production traffic." + break + fi + if [[ $attempt -eq 5 ]]; then + echo "::error::Version $version is not the active deployment. Current versions: $(jq -c '.versions' <<<"${status:-null}" 2>/dev/null || echo unknown)" + exit 1 + fi + sleep 5 +done + +live="$(bash "$here/worker-table-prefix.sh" "$version")" +live="${live//[^A-Za-z0-9_]/}" +expected="${TABLE_PREFIX:-}" +if [[ -n "$expected" && "$live" != "$expected" ]]; then + echo "::error::Deployed version uses TABLE_PREFIX='$live', but migrations were applied for '$expected'." + exit 1 +fi +if [[ -z "$expected" && -n "$live" ]]; then + echo "::warning::The Worker uses TABLE_PREFIX=$live but the GitHub TABLE_PREFIX variable is unset; set it on the production environment so deploys apply schema migrations automatically." +fi +echo "TABLE_PREFIX: ${live:-}" diff --git a/.github/scripts/worker-table-prefix.sh b/.github/scripts/worker-table-prefix.sh new file mode 100644 index 0000000..f55f99a --- /dev/null +++ b/.github/scripts/worker-table-prefix.sh @@ -0,0 +1,26 @@ +#!/usr/bin/env bash +# Prints the TABLE_PREFIX variable of a deployed Worker version (nothing if it +# is unset). Run from apps/worker (needs wrangler.toml with real IDs injected). +# +# bash worker-table-prefix.sh +# +# Fails if the lookup fails, or if TABLE_PREFIX is stored as a secret: its +# value can't be read back, so it can't be compared with the GitHub variable. +set -euo pipefail + +version="${1:?usage: worker-table-prefix.sh }" + +view="$(pnpm exec wrangler versions view "$version" --json)" +# Don't interpret an unexpected API response as an unset prefix. +jq -e --arg v "$version" '.id == $v and (.resources.bindings | type == "array")' <<<"$view" >/dev/null +binding="$(jq -c '[.resources.bindings[] | select(.name == "TABLE_PREFIX")] | first // empty' <<<"$view")" +if [[ -z "$binding" ]]; then + exit 0 +fi + +type="$(jq -r '.type' <<<"$binding")" +if [[ "$type" != plain_text ]]; then + echo "::error::TABLE_PREFIX on Worker version $version is a '$type' binding; make it a plain-text variable so the deploy workflow can check it." >&2 + exit 1 +fi +jq -r '.text' <<<"$binding" diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index cf3ce62..07cace8 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -41,6 +41,14 @@ jobs: - name: Build run: pnpm build + # Deploy scripts: local D1 migration scenarios plus smoke/verify checks. + # No Cloudflare credentials needed. + - name: Shellcheck deploy scripts + run: shellcheck .github/scripts/*.sh + + - name: Test deploy scripts + run: node --test .github/scripts/test-d1-migrations.mjs .github/scripts/test-deploy-checks.mjs + audit: name: Dependency audit runs-on: ubuntu-latest diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml index bd3b64a..d1eace1 100644 --- a/.github/workflows/deploy.yml +++ b/.github/workflows/deploy.yml @@ -102,36 +102,46 @@ jobs: CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }} run: pnpm run db:migrate + # TABLE_PREFIX in use: apply the prefix-aware migrations from + # src/lib/migrations.ts (the same ones POST /setup runs). + - name: Apply prefixed D1 migrations + if: steps.d1.outputs.mode == 'prefixed' + working-directory: apps/worker + env: + CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }} + TABLE_PREFIX: ${{ vars.TABLE_PREFIX }} + run: bash ../../.github/scripts/d1-prefixed-migrations.sh + + # Web and worker were built above; deploy the worker directly so wrangler + # can record the uploaded version ID for the verification step. - name: Deploy + working-directory: apps/worker + env: + CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }} + WRANGLER_OUTPUT_FILE_PATH: ${{ runner.temp }}/wrangler-output.ndjson run: pnpm run deploy + + # Checked through the Cloudflare API rather than the public hostname, so + # the zone's bot protection can't make it inconclusive. + - name: Verify deployment + id: verify + working-directory: apps/worker env: CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }} + WRANGLER_OUTPUT_FILE_PATH: ${{ runner.temp }}/wrangler-output.ndjson + TABLE_PREFIX: ${{ vars.TABLE_PREFIX }} + run: bash ../../.github/scripts/verify-deployment.sh - name: Smoke test id: smoke env: APP_URL: ${{ vars.APP_URL }} - CHECK_DB: ${{ steps.d1.outputs.mode == 'apply' }} - run: | - if [[ -z "$APP_URL" ]]; then - echo "::error::Variable APP_URL is not set; cannot verify the deployment" - exit 1 - fi - base="${APP_URL%/}" - probe() { - curl -fsS --retry 5 --retry-delay 5 --retry-all-errors --max-time 15 "$base$1" - } - probe /api/health | jq -e '.status == "ok"' - probe / >/dev/null - # /api/config reads the settings table — confirms the schema is usable. - # Skipped when migrations are managed by the setup route instead. - if [[ "$CHECK_DB" == "true" ]]; then - probe /api/config | jq -e 'has("appName")' - fi + CHECK_DB: ${{ steps.d1.outputs.mode == 'apply' || steps.d1.outputs.mode == 'prefixed' }} + run: bash .github/scripts/smoke-test.sh - name: Rollback hint - if: failure() && steps.smoke.outcome == 'failure' + if: failure() && (steps.verify.outcome == 'failure' || steps.smoke.outcome == 'failure') run: | - echo "::error::Smoke test failed after deploy. To roll back the Worker to the previous version:" + echo "::error::Post-deploy verification failed. To roll back the Worker to the previous version:" echo " cd apps/worker && pnpm exec wrangler rollback" echo "D1 migrations are NOT rolled back automatically; they are designed to stay compatible with the previous code." diff --git a/README.md b/README.md index 428c9c0..82c3898 100644 --- a/README.md +++ b/README.md @@ -94,8 +94,23 @@ This will deploy the code to Cloudflare Workers. ### 6. Run database migrations -After deploying, trigger the migrations once via a `POST` request with the setup -secret in a header (it is no longer accepted in the URL): +The Deploy workflow applies migrations automatically **before** deploying the code. +Without a prefix it uses `wrangler d1 migrations apply` as before. With `TABLE_PREFIX` +set it applies the migrations from `apps/worker/src/lib/migrations.ts` (the same ones +the setup route runs), skips those already recorded in `__schema_migrations`, +and prints the planned migrations in the log. Migrations must stay backward compatible: +only add tables, indexes or columns — never drop, rename or rewrite existing data. + +When using a prefix, set `TABLE_PREFIX` under the GitHub **production environment → +Variables** to exactly the same value as the Worker's `TABLE_PREFIX` **plain-text +variable** in Cloudflare (e.g. `SL`; letters, digits and underscores only). Do not store +it as a secret, and do not change it once data exists. The GitHub `APP_URL` variable must +point at the production URL. `CLOUDFLARE_API_TOKEN` needs edit access to the D1 database +and edit/version-read access to the Worker. + +You no longer need to call `/setup` after each deploy. For manual deployments or +emergencies it can still be triggered with a `POST` request carrying the setup secret in +a header (it is no longer accepted in the URL): ``` curl -X POST https://your-worker.workers.dev/setup \ @@ -111,7 +126,13 @@ Response on success: } ``` -Re-visiting is safe — already-applied migrations return `"skipped"`. Run it again after future migrations are added. +Re-running it is safe — already-applied migrations return `"skipped"`. + +After deploying, the workflow first confirms through the Cloudflare API that the uploaded +version serves 100% of production traffic, then probes the public URL. A `403` carrying +`cf-mitigated: challenge` (e.g. Bot Fight Mode challenging the CI runner) only produces a +warning, since the HTTP/database check could not run; any other non-2xx status or an +unexpected JSON body fails the deploy. Bot Fight Mode can stay enabled. ### 7. First login diff --git a/README.zh-CN.md b/README.zh-CN.md index cf3fd8b..7bd31c9 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -97,7 +97,18 @@ ### 6. 运行数据库迁移 -部署后,通过 `POST` 请求触发迁移一次,密钥放在请求头中(不再通过 URL 传递): +GitHub Actions 会在部署代码**之前**自动执行迁移:无前缀时仍使用 +`wrangler d1 migrations apply`;有前缀时使用与 setup 路由共享的 +`apps/worker/src/lib/migrations.ts`,按 `__schema_migrations` 跳过已执行项, +并在日志中打印待执行计划。迁移必须向后兼容,只添加表、索引或列,不删除、重命名或修改现有数据。 + +使用前缀时,在 GitHub 的 **production environment → Variables** 中设置 +`TABLE_PREFIX`,与 Cloudflare Worker 的同名**明文变量**完全一致(例如 `SL`,仅字母、数字和下划线)。 +不要把它设为 Secret,也不要在已有数据后更换前缀。GitHub 中的 `APP_URL` 也必须指向生产地址。 +现有 `CLOUDFLARE_API_TOKEN` 需要有目标 D1 的编辑权限和 Worker 的编辑/版本读取权限。 + +无需在每次部署后调用 `/setup`。手动部署或应急操作仍可通过 `POST` 请求触发, +密钥放在请求头中(不再通过 URL 传递): ``` curl -X POST https://your-worker.workers.dev/setup \ @@ -113,7 +124,10 @@ curl -X POST https://your-worker.workers.dev/setup \ } ``` -重复访问是安全的 — 已应用的迁移会返回 `"skipped"`。添加新迁移后再次运行即可。 +重复调用是安全的,已执行的迁移会返回 `"skipped"`。自动部署不需要手动调用。 +部署后还会通过 Cloudflare API 核对本次上传的版本承载 100% 流量,再检查公开 URL。 +公开 URL 返回带 `cf-mitigated: challenge` 的 403 时仅警告(HTTP/数据库检查未能验证), +其余非 2xx 或错误的 JSON 均失败;无需关闭 Bot Fight Mode。 ### 7. 首次登录 diff --git a/apps/worker/src/lib/migrations.ts b/apps/worker/src/lib/migrations.ts new file mode 100644 index 0000000..6741db6 --- /dev/null +++ b/apps/worker/src/lib/migrations.ts @@ -0,0 +1,153 @@ +// Schema migrations, parameterised by TABLE_PREFIX. Single source of truth for +// both the HTTP setup route (routes/setup.ts) and the deploy workflow +// (.github/scripts/d1-migrations.mjs loads this file with Node's built-in +// TypeScript type stripping) — so keep it free of imports and of TS-only +// runtime syntax (enums, namespaces, parameter properties). +// +// Migrations must stay additive (CREATE TABLE/INDEX IF NOT EXISTS, ALTER TABLE +// ADD COLUMN, INSERT OR IGNORE): the deploy workflow runs them before the new +// code goes live, and its guard rejects anything else. + +// ─── Table-prefix helper (mirrors src/lib/db.ts) ────────────────────────────── + +export function tbl(prefix: string, name: string): string { + const p = prefix.replace(/[^a-zA-Z0-9_]/g, ''); + return p ? `${p}_${name}` : name; +} + +// Name of the table recording applied migrations, e.g. `_SL_schema_migrations`. +export function migrationsTable(prefix: string): string { + return `_${tbl(prefix, 'schema_migrations')}`; +} + +export function createMigrationsTableSql(prefix: string): string { + return `CREATE TABLE IF NOT EXISTS ${migrationsTable(prefix)} (name TEXT PRIMARY KEY, applied_at INTEGER NOT NULL DEFAULT (unixepoch()))`; +} + +// ─── Migration factory ──────────────────────────────────────────────────────── +// Returns migrations parameterised by the table prefix so setup works whether +// TABLE_PREFIX is empty or set to a custom value. + +export function getMigrations(p: string): { name: string; sql: string }[] { + const t = (name: string) => tbl(p, name); + return [ + { + name: 'schema_v1', + sql: ` +CREATE TABLE IF NOT EXISTS ${t('users')} ( + id TEXT PRIMARY KEY DEFAULT (lower(hex(randomblob(16)))), + email TEXT UNIQUE NOT NULL, + username TEXT UNIQUE NOT NULL, + password_hash TEXT NOT NULL, + role TEXT NOT NULL DEFAULT 'user' CHECK (role IN ('admin', 'user')), + totp_secret TEXT, + totp_enabled INTEGER NOT NULL DEFAULT 0, + totp_backup_codes TEXT, + email_2fa_enabled INTEGER NOT NULL DEFAULT 0, + passkey_enabled INTEGER NOT NULL DEFAULT 0, + is_active INTEGER NOT NULL DEFAULT 1, + created_at INTEGER NOT NULL DEFAULT (unixepoch()), + updated_at INTEGER NOT NULL DEFAULT (unixepoch()) +); +CREATE TABLE IF NOT EXISTS ${t('passkeys')} ( + id TEXT PRIMARY KEY, + user_id TEXT NOT NULL REFERENCES ${t('users')}(id) ON DELETE CASCADE, + public_key TEXT NOT NULL, + counter INTEGER NOT NULL DEFAULT 0, + name TEXT, + aaguid TEXT, + transports TEXT, + created_at INTEGER NOT NULL DEFAULT (unixepoch()), + last_used_at INTEGER +); +CREATE INDEX IF NOT EXISTS idx_passkeys_user_id ON ${t('passkeys')}(user_id); +CREATE TABLE IF NOT EXISTS ${t('links')} ( + id TEXT PRIMARY KEY DEFAULT (lower(hex(randomblob(16)))), + user_id TEXT NOT NULL REFERENCES ${t('users')}(id) ON DELETE CASCADE, + slug TEXT UNIQUE NOT NULL, + destination_url TEXT NOT NULL, + title TEXT, + expires_at INTEGER, + is_active INTEGER NOT NULL DEFAULT 1, + user_seq INTEGER NOT NULL DEFAULT 0, + created_at INTEGER NOT NULL DEFAULT (unixepoch()), + updated_at INTEGER NOT NULL DEFAULT (unixepoch()) +); +CREATE INDEX IF NOT EXISTS idx_links_slug ON ${t('links')}(slug); +CREATE INDEX IF NOT EXISTS idx_links_user_id ON ${t('links')}(user_id); +CREATE INDEX IF NOT EXISTS idx_links_expires_at ON ${t('links')}(expires_at) WHERE expires_at IS NOT NULL; +CREATE TABLE IF NOT EXISTS ${t('click_logs')} ( + id TEXT PRIMARY KEY DEFAULT (lower(hex(randomblob(16)))), + link_id TEXT NOT NULL REFERENCES ${t('links')}(id) ON DELETE CASCADE, + ip_address TEXT, + user_agent TEXT, + referer TEXT, + country TEXT, + city TEXT, + device_type TEXT, + browser TEXT, + os TEXT, + created_at INTEGER NOT NULL DEFAULT (unixepoch()) +); +CREATE INDEX IF NOT EXISTS idx_click_logs_link_id ON ${t('click_logs')}(link_id); +CREATE INDEX IF NOT EXISTS idx_click_logs_created_at ON ${t('click_logs')}(created_at); +CREATE INDEX IF NOT EXISTS idx_click_logs_link_time ON ${t('click_logs')}(link_id, created_at); +CREATE TABLE IF NOT EXISTS ${t('verifications')} ( + id TEXT PRIMARY KEY DEFAULT (lower(hex(randomblob(16)))), + identifier TEXT NOT NULL, + type TEXT NOT NULL CHECK (type IN ('email_otp', 'password_reset', 'email_verify')), + code_hash TEXT NOT NULL, + expires_at INTEGER NOT NULL, + attempts INTEGER NOT NULL DEFAULT 0, + used INTEGER NOT NULL DEFAULT 0, + created_at INTEGER NOT NULL DEFAULT (unixepoch()) +); +CREATE INDEX IF NOT EXISTS idx_verifications_identifier ON ${t('verifications')}(identifier, type); +CREATE TABLE IF NOT EXISTS ${t('settings')} ( + key TEXT PRIMARY KEY, + value TEXT NOT NULL, + updated_at INTEGER NOT NULL DEFAULT (unixepoch()) +); +INSERT OR IGNORE INTO ${t('settings')} (key, value) VALUES + ('registration_enabled', 'true'), + ('require_email_verification', 'false'), + ('app_name', 'ShortLink'), + ('email_provider', 'resend'), + ('smtp_host', ''), + ('smtp_port', '587'), + ('smtp_user', ''), + ('smtp_pass', ''), + ('smtp_from', ''), + ('resend_api_key', ''), + ('email_from_domain', ''), + ('email_from_name', ''); +CREATE TABLE IF NOT EXISTS ${t('audit_logs')} ( + id TEXT PRIMARY KEY DEFAULT (lower(hex(randomblob(16)))), + admin_id TEXT REFERENCES ${t('users')}(id) ON DELETE SET NULL, + action TEXT NOT NULL, + target_id TEXT NOT NULL, + details TEXT, + created_at INTEGER NOT NULL DEFAULT (unixepoch()) +); +CREATE INDEX IF NOT EXISTS idx_audit_logs_admin_id ON ${t('audit_logs')}(admin_id); +CREATE INDEX IF NOT EXISTS idx_audit_logs_created_at ON ${t('audit_logs')}(created_at); +CREATE INDEX IF NOT EXISTS idx_audit_logs_target_id ON ${t('audit_logs')}(target_id); +CREATE TABLE IF NOT EXISTS ${t('totp_used')} ( + user_id TEXT NOT NULL, + code TEXT NOT NULL, + used_at INTEGER NOT NULL DEFAULT (unixepoch()), + PRIMARY KEY (user_id, code) +); +CREATE INDEX IF NOT EXISTS idx_totp_used_at ON ${t('totp_used')}(used_at); +`, + }, + { + // BE-S3/S4: per-user token_version — bumping it revokes all of a user's + // sessions (password change/reset, admin disable/demote). + name: 'schema_v2', + sql: ` +ALTER TABLE ${t('users')} ADD COLUMN token_version INTEGER NOT NULL DEFAULT 0; +`, + }, + ]; +} diff --git a/apps/worker/src/routes/setup.ts b/apps/worker/src/routes/setup.ts index 54e17df..23f3939 100644 --- a/apps/worker/src/routes/setup.ts +++ b/apps/worker/src/routes/setup.ts @@ -1,145 +1,15 @@ import { Hono } from 'hono'; import { constantTimeEqual } from '../lib/crypto.js'; import { checkSetupRateLimit } from '../lib/kv.js'; +import { + createMigrationsTableSql, + getMigrations, + migrationsTable, +} from '../lib/migrations.js'; import type { Env, Variables } from '../types.js'; const app = new Hono<{ Bindings: Env; Variables: Variables }>(); -// ─── Table-prefix helper (mirrors src/lib/db.ts) ────────────────────────────── - -function tbl(prefix: string, name: string): string { - const p = prefix.replace(/[^a-zA-Z0-9_]/g, ''); - return p ? `${p}_${name}` : name; -} - -// ─── Migration factory ──────────────────────────────────────────────────────── -// Returns migrations parameterised by the table prefix so setup works whether -// TABLE_PREFIX is empty or set to a custom value. - -function getMigrations(p: string): { name: string; sql: string }[] { - const t = (name: string) => tbl(p, name); - return [ - { - name: 'schema_v1', - sql: ` -CREATE TABLE IF NOT EXISTS ${t('users')} ( - id TEXT PRIMARY KEY DEFAULT (lower(hex(randomblob(16)))), - email TEXT UNIQUE NOT NULL, - username TEXT UNIQUE NOT NULL, - password_hash TEXT NOT NULL, - role TEXT NOT NULL DEFAULT 'user' CHECK (role IN ('admin', 'user')), - totp_secret TEXT, - totp_enabled INTEGER NOT NULL DEFAULT 0, - totp_backup_codes TEXT, - email_2fa_enabled INTEGER NOT NULL DEFAULT 0, - passkey_enabled INTEGER NOT NULL DEFAULT 0, - is_active INTEGER NOT NULL DEFAULT 1, - created_at INTEGER NOT NULL DEFAULT (unixepoch()), - updated_at INTEGER NOT NULL DEFAULT (unixepoch()) -); -CREATE TABLE IF NOT EXISTS ${t('passkeys')} ( - id TEXT PRIMARY KEY, - user_id TEXT NOT NULL REFERENCES ${t('users')}(id) ON DELETE CASCADE, - public_key TEXT NOT NULL, - counter INTEGER NOT NULL DEFAULT 0, - name TEXT, - aaguid TEXT, - transports TEXT, - created_at INTEGER NOT NULL DEFAULT (unixepoch()), - last_used_at INTEGER -); -CREATE INDEX IF NOT EXISTS idx_passkeys_user_id ON ${t('passkeys')}(user_id); -CREATE TABLE IF NOT EXISTS ${t('links')} ( - id TEXT PRIMARY KEY DEFAULT (lower(hex(randomblob(16)))), - user_id TEXT NOT NULL REFERENCES ${t('users')}(id) ON DELETE CASCADE, - slug TEXT UNIQUE NOT NULL, - destination_url TEXT NOT NULL, - title TEXT, - expires_at INTEGER, - is_active INTEGER NOT NULL DEFAULT 1, - user_seq INTEGER NOT NULL DEFAULT 0, - created_at INTEGER NOT NULL DEFAULT (unixepoch()), - updated_at INTEGER NOT NULL DEFAULT (unixepoch()) -); -CREATE INDEX IF NOT EXISTS idx_links_slug ON ${t('links')}(slug); -CREATE INDEX IF NOT EXISTS idx_links_user_id ON ${t('links')}(user_id); -CREATE INDEX IF NOT EXISTS idx_links_expires_at ON ${t('links')}(expires_at) WHERE expires_at IS NOT NULL; -CREATE TABLE IF NOT EXISTS ${t('click_logs')} ( - id TEXT PRIMARY KEY DEFAULT (lower(hex(randomblob(16)))), - link_id TEXT NOT NULL REFERENCES ${t('links')}(id) ON DELETE CASCADE, - ip_address TEXT, - user_agent TEXT, - referer TEXT, - country TEXT, - city TEXT, - device_type TEXT, - browser TEXT, - os TEXT, - created_at INTEGER NOT NULL DEFAULT (unixepoch()) -); -CREATE INDEX IF NOT EXISTS idx_click_logs_link_id ON ${t('click_logs')}(link_id); -CREATE INDEX IF NOT EXISTS idx_click_logs_created_at ON ${t('click_logs')}(created_at); -CREATE INDEX IF NOT EXISTS idx_click_logs_link_time ON ${t('click_logs')}(link_id, created_at); -CREATE TABLE IF NOT EXISTS ${t('verifications')} ( - id TEXT PRIMARY KEY DEFAULT (lower(hex(randomblob(16)))), - identifier TEXT NOT NULL, - type TEXT NOT NULL CHECK (type IN ('email_otp', 'password_reset', 'email_verify')), - code_hash TEXT NOT NULL, - expires_at INTEGER NOT NULL, - attempts INTEGER NOT NULL DEFAULT 0, - used INTEGER NOT NULL DEFAULT 0, - created_at INTEGER NOT NULL DEFAULT (unixepoch()) -); -CREATE INDEX IF NOT EXISTS idx_verifications_identifier ON ${t('verifications')}(identifier, type); -CREATE TABLE IF NOT EXISTS ${t('settings')} ( - key TEXT PRIMARY KEY, - value TEXT NOT NULL, - updated_at INTEGER NOT NULL DEFAULT (unixepoch()) -); -INSERT OR IGNORE INTO ${t('settings')} (key, value) VALUES - ('registration_enabled', 'true'), - ('require_email_verification', 'false'), - ('app_name', 'ShortLink'), - ('email_provider', 'resend'), - ('smtp_host', ''), - ('smtp_port', '587'), - ('smtp_user', ''), - ('smtp_pass', ''), - ('smtp_from', ''), - ('resend_api_key', ''), - ('email_from_domain', ''), - ('email_from_name', ''); -CREATE TABLE IF NOT EXISTS ${t('audit_logs')} ( - id TEXT PRIMARY KEY DEFAULT (lower(hex(randomblob(16)))), - admin_id TEXT REFERENCES ${t('users')}(id) ON DELETE SET NULL, - action TEXT NOT NULL, - target_id TEXT NOT NULL, - details TEXT, - created_at INTEGER NOT NULL DEFAULT (unixepoch()) -); -CREATE INDEX IF NOT EXISTS idx_audit_logs_admin_id ON ${t('audit_logs')}(admin_id); -CREATE INDEX IF NOT EXISTS idx_audit_logs_created_at ON ${t('audit_logs')}(created_at); -CREATE INDEX IF NOT EXISTS idx_audit_logs_target_id ON ${t('audit_logs')}(target_id); -CREATE TABLE IF NOT EXISTS ${t('totp_used')} ( - user_id TEXT NOT NULL, - code TEXT NOT NULL, - used_at INTEGER NOT NULL DEFAULT (unixepoch()), - PRIMARY KEY (user_id, code) -); -CREATE INDEX IF NOT EXISTS idx_totp_used_at ON ${t('totp_used')}(used_at); -`, - }, - { - // BE-S3/S4: per-user token_version — bumping it revokes all of a user's - // sessions (password change/reset, admin disable/demote). - name: 'schema_v2', - sql: ` -ALTER TABLE ${t('users')} ADD COLUMN token_version INTEGER NOT NULL DEFAULT 0; -`, - }, - ]; -} - // D1's exec() only processes the first line of a multi-line string. // Strip SQL line comments and collapse all whitespace to a single line. function toSingleLine(sql: string): string { @@ -173,15 +43,13 @@ app.post('/', async (c) => { } const prefix = c.env.TABLE_PREFIX ?? ''; - const migrationsTable = `_${tbl(prefix, 'schema_migrations')}`; + const historyTable = migrationsTable(prefix); // Use prepare().run() for single-statement DDL — avoids exec()'s newline limitation - await c.env.DB.prepare( - `CREATE TABLE IF NOT EXISTS ${migrationsTable} (name TEXT PRIMARY KEY, applied_at INTEGER NOT NULL DEFAULT (unixepoch()))`, - ).run(); + await c.env.DB.prepare(createMigrationsTableSql(prefix)).run(); const { results } = await c.env.DB.prepare( - `SELECT name FROM ${migrationsTable}`, + `SELECT name FROM ${historyTable}`, ).all<{ name: string }>(); const applied = new Set(results.map((r) => r.name)); @@ -198,7 +66,7 @@ app.post('/', async (c) => { } try { await c.env.DB.exec(toSingleLine(migration.sql)); - await c.env.DB.prepare(`INSERT INTO ${migrationsTable} (name) VALUES (?)`) + await c.env.DB.prepare(`INSERT INTO ${historyTable} (name) VALUES (?)`) .bind(migration.name) .run(); log.push({ name: migration.name, status: 'applied' });