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
8 changes: 8 additions & 0 deletions .github/scripts/d1-prefixed-migrations.sh
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,14 @@ elif [[ -n "$own_tables" ]]; then
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
# Silent-switch guard: an unprefixed schema of this app (history with schema_v1,
# or wrangler's d1_migrations) exists → abort rather than silently initialising
# a new prefixed schema. A bare `users` table alone is not a signal — the
# shared D1 database can carry other apps' tables.
if grep -qx d1_migrations <<<"$tables" || (grep -qx _schema_migrations <<<"$tables" && d1_query "SELECT name FROM _schema_migrations" | grep -qx schema_v1); then
echo "::error::The database contains an unprefixed schema (_schema_migrations / d1_migrations), but TABLE_PREFIX resolves to '$prefix'. Refusing to initialise a new '$prefix'-prefixed schema. To keep the existing unprefixed schema, set TABLE_PREFIX='' (or TABLE_PREFIX=none in CI)."
exit 1
fi
applied=""
echo "No ${prefix}_ tables yet — fresh install."
fi
Expand Down
76 changes: 58 additions & 18 deletions .github/scripts/d1-prepare-migrations.sh
Original file line number Diff line number Diff line change
Expand Up @@ -11,33 +11,36 @@
#
# setup.ts migration `schema_vN` <=> migrations/NNNN_*.sql (N zero-padded)
#
# Writes `mode=apply`, `mode=prefixed` or `mode=skip` to $GITHUB_OUTPUT
# (stdout if unset).
# apply — wrangler migrations can run safely
# Writes `mode=apply` or `mode=prefixed` to $GITHUB_OUTPUT (stdout if unset).
# apply — wrangler migrations can run safely (no prefix in use)
# 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
#
# Three-state TABLE_PREFIX (unset → 'sl', '' → no prefix, other → as-is) is
# resolved by the deploy workflow before this script runs; a silent switch
# (database already initialised under a different prefix) aborts with an error.
#
# D1_LOCATION=local runs the queries against the local D1 database instead of
# the remote one (for testing this script).
set -euo pipefail

here="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
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
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
# Three-state resolution: the deploy workflow already resolves vars.TABLE_PREFIX
# (none → '', unset/empty → 'sl') before calling this script. When invoked
# directly with TABLE_PREFIX unset, resolve it to the project default.
# `${TABLE_PREFIX+x}` is empty when unset and 'x' when set (even to ''), which
# is portable across bash 3.x and 5.x.
if [[ -n "${TABLE_PREFIX+x}" ]]; then
prefix="$TABLE_PREFIX"
else
prefix="$(node --disable-warning=MODULE_TYPELESS_PACKAGE_JSON "$here/default-table-prefix.mjs")"
fi

d1_query() {
Expand All @@ -47,6 +50,48 @@ d1_query() {

tables="$(d1_query "SELECT name FROM sqlite_master WHERE type = 'table'")"
has_table() { grep -qx "$1" <<<"$tables"; }
has_table_i() { grep -qixF "$1" <<<"$tables"; }

# An unprefixed schema of this app: the legacy setup route records its history
# in `_schema_migrations` (with schema_v1), and wrangler's unprefixed path in
# `d1_migrations`. A bare `users` table alone is NOT a signal — the shared D1
# database can carry other apps' tables.
unprefixed=false
if has_table _schema_migrations && d1_query "SELECT name FROM _schema_migrations" | grep -qx schema_v1; then
unprefixed=true
fi
if has_table d1_migrations; then
unprefixed=true
fi

if [[ -n "$prefix" ]]; then
if ! [[ "$prefix" =~ ^[A-Za-z0-9_]+$ ]]; then
echo "::error::TABLE_PREFIX '$prefix' may only contain letters, digits and underscores."
exit 1
fi
# Already initialised under this prefix → incremental/idempotent migration,
# not a silent switch. Allow it.
if has_table_i "_${prefix}_schema_migrations" || has_table_i "${prefix}_users"; then
echo "TABLE_PREFIX=$prefix — prefixed setup-route migrations will be applied instead of wrangler's."
echo "mode=prefixed" >>"$out"
exit 0
fi
# Current prefix not initialised, but an unprefixed schema of this app exists
# → switching would point at a new set of tables.
if [[ "$unprefixed" == true ]]; then
echo "::error::The database already contains an unprefixed schema (_schema_migrations / d1_migrations), but TABLE_PREFIX resolves to '$prefix'. Refusing to initialise a new '$prefix'-prefixed schema. To keep the existing unprefixed schema, set TABLE_PREFIX='' (or TABLE_PREFIX=none in CI)."
exit 1
fi
echo "TABLE_PREFIX=$prefix — prefixed setup-route migrations will be applied instead of wrangler's."
echo "mode=prefixed" >>"$out"
exit 0
fi

# Prefix resolves to empty (explicit no-prefix).
if [[ "$unprefixed" != true ]] && grep -Eq '^_[A-Za-z0-9_]+_schema_migrations$' <<<"$tables"; then
echo "::error::The database already contains a prefixed schema, but TABLE_PREFIX resolves to an empty string (no prefix). Refusing to initialise an unprefixed schema. To keep the existing prefixed schema, configure TABLE_PREFIX to its current value."
exit 1
fi

if has_table d1_migrations; then
echo "d1_migrations present — database is already tracked by wrangler."
Expand All @@ -55,11 +100,6 @@ if has_table d1_migrations; then
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 so deploys apply prefixed migrations. Skipping D1 migrations."
echo "mode=skip" >>"$out"
exit 0
fi
echo "Empty database — wrangler will apply all migrations."
echo "mode=apply" >>"$out"
exit 0
Expand Down
5 changes: 5 additions & 0 deletions .github/scripts/default-table-prefix.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
// Prints the project default TABLE_PREFIX from the single source of truth
// (apps/worker/src/lib/table-prefix.ts), so bash scripts never hardcode it.
import { DEFAULT_TABLE_PREFIX } from '../../apps/worker/src/lib/table-prefix.ts';

process.stdout.write(DEFAULT_TABLE_PREFIX);
27 changes: 27 additions & 0 deletions .github/scripts/resolve-table-prefix.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
// CI three-state TABLE_PREFIX resolution (the "none" convention).
//
// GitHub Actions `vars.TABLE_PREFIX` cannot distinguish "unset" from "empty",
// so the deploy workflow uses a reserved word to preserve the three runtime
// states:
// unset / empty → DEFAULT_TABLE_PREFIX ('sl')
// 'none' → '' (explicit no prefix; the deployer accepts the
// table-collision risk)
// anything else → as-is
//
// The default constant comes from the single source of truth
// (apps/worker/src/lib/table-prefix.ts), loaded via Node type stripping.
// Reads the raw value from the TABLE_PREFIX environment variable and prints the
// resolved value to stdout.
import { DEFAULT_TABLE_PREFIX } from '../../apps/worker/src/lib/table-prefix.ts';

const raw = process.env.TABLE_PREFIX;

let resolved;
if (raw === undefined || raw === '') {
resolved = DEFAULT_TABLE_PREFIX;
} else if (raw === 'none') {
resolved = '';
} else {
resolved = raw;
}
process.stdout.write(resolved);
45 changes: 45 additions & 0 deletions .github/scripts/test-d1-migrations.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -262,3 +262,48 @@ test('已知限制:别的应用占用同名索引时,本应用索引会被
);
assert.throws(() => f.assertOwnIndexes('SL'), /Expected values/);
});

// ─── 防静默切换(部署侧)─────────────────────────────────────────────────────

test('防静默切换:库中已有无前缀 schema + 解析为 sl → 中止并提示显式配置', (t) => {
const f = fixture(t);
f.setup('', ['schema_v1']);
assert.throws(
() => f.script('d1-prepare-migrations.sh', 'sl'),
(err) => /unprefixed schema/.test(err.stdout ?? ''),
);
});

test('防静默切换:库中已有 prefixed schema + 显式空前缀 → 中止并提示显式配置', (t) => {
const f = fixture(t);
f.setup('SL', ['schema_v1']);
assert.throws(
() => f.script('d1-prepare-migrations.sh', ''),
(err) => /prefixed schema/.test(err.stdout ?? ''),
);
});

// ─── 回归:共享库他表 + 三态边界(ONE-206 修复)─────────────────────────────

test('回归:共享库他表 + shortlink 已有 SL 前缀 → 增量迁移放行,不误杀', (t) => {
const f = fixture(t);
const before = f.shared(); // 他应用:bare users + ZETA_*
f.setup('SL', ['schema_v1', 'schema_v2']);
assert.match(f.script('d1-prepare-migrations.sh', 'SL'), /prefixed/);
assert.match(
f.script('d1-prefixed-migrations.sh', 'SL'),
/Planned migrations: none/,
);
assert.deepEqual(f.foreignSnapshot(), before);
});

test('回归:共享库他表 + shortlink 显式空前缀 → 放行,不误判他表为前缀', (t) => {
const f = fixture(t);
// 仅他应用的前缀表,shortlink 自身无任何 schema。
f.query(`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 TABLE eNotify_settings (key TEXT, value TEXT);`);
assert.match(f.script('d1-prepare-migrations.sh', ''), /Empty database/);
});
49 changes: 49 additions & 0 deletions .github/scripts/test-deploy-checks.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -155,3 +155,52 @@ esac
}
});
}

// ─── CI 三态解析(none 约定)─────────────────────────────────────────────────

for (const scenario of [
{ name: 'vars 未设 → 默认 sl', env: undefined, expected: 'sl' },
{ name: 'vars 为空 → 默认 sl', env: '', expected: 'sl' },
{ name: 'vars 为保留字 none → 空字符串', env: 'none', expected: '' },
{ name: 'vars 为其他值 → 原样(含大小写)', env: 'SL', expected: 'SL' },
]) {
test(`三态解析(none 约定):${scenario.name}`, (t) => {
const f = fixture(t);
const env = { ...f.env };
if (scenario.env === undefined) {
delete env.TABLE_PREFIX;
} else {
env.TABLE_PREFIX = scenario.env;
}
const out = execFileSync(
'node',
[
'--disable-warning=MODULE_TYPELESS_PACKAGE_JSON',
join(scripts, 'resolve-table-prefix.mjs'),
],
{ env, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] },
);
assert.equal(out, scenario.expected);
});
}

test('worker-table-prefix.sh:未设置绑定 → 默认 sl', (t) => {
const f = fixture(t);
writeFileSync(
join(f.dir, 'pnpm'),
`#!/bin/sh
case "$*" in
'exec wrangler versions view v1 --json')
printf '%s\\n' '{"id":"v1","resources":{"bindings":[]}}' ;;
*) exit 99 ;;
esac
`,
{ mode: 0o755 },
);
const out = execFileSync(
'bash',
[join(scripts, 'worker-table-prefix.sh'), 'v1'],
{ env: f.env, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] },
);
assert.equal(out, 'sl');
});
12 changes: 6 additions & 6 deletions .github/scripts/verify-deployment.sh
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
# 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)
# TABLE_PREFIX — resolved prefix ('' means explicit no prefix)
set -euo pipefail

here="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
Expand Down Expand Up @@ -41,12 +41,12 @@ done

live="$(bash "$here/worker-table-prefix.sh" "$version")"
live="${live//[^A-Za-z0-9_]/}"
# worker-table-prefix.sh already maps an unset Worker binding to the default
# 'sl'; compare literally (case-sensitive) so e.g. production `SL` is never
# folded into `sl` and reported as a false match.
expected="${TABLE_PREFIX:-}"
if [[ -n "$expected" && "$live" != "$expected" ]]; then
echo "::error::Deployed version uses TABLE_PREFIX='$live', but migrations were applied for '$expected'."
if [[ "$live" != "$expected" ]]; then
echo "::error::Deployed version uses TABLE_PREFIX='$live', but migrations were applied for '${expected:-<none>}'."
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:-<none>}"
9 changes: 7 additions & 2 deletions .github/scripts/worker-table-prefix.sh
Original file line number Diff line number Diff line change
@@ -1,20 +1,25 @@
#!/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).
# Prints the effective TABLE_PREFIX of a deployed Worker version. When the
# Worker has no TABLE_PREFIX binding, the project default ('sl') is printed —
# matching the runtime three-state resolution in src/lib/table-prefix.ts.
# Run from apps/worker (needs wrangler.toml with real IDs injected).
#
# bash worker-table-prefix.sh <version-id>
#
# 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

here="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
version="${1:?usage: worker-table-prefix.sh <version-id>}"

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
# No binding: the runtime resolves this to the project default prefix.
node --disable-warning=MODULE_TYPELESS_PACKAGE_JSON "$here/default-table-prefix.mjs"
exit 0
fi

Expand Down
15 changes: 12 additions & 3 deletions .github/workflows/deploy.yml
Original file line number Diff line number Diff line change
Expand Up @@ -91,12 +91,21 @@ jobs:
# Order: migrate first, then deploy code. Migrations must therefore be
# backward compatible with the code currently live (expand → deploy →
# contract: add columns/tables now, drop old ones in a later release).
- name: Resolve TABLE_PREFIX (three-state)
id: prefix
env:
TABLE_PREFIX: ${{ vars.TABLE_PREFIX }}
run: |
resolved="$(node --disable-warning=MODULE_TYPELESS_PACKAGE_JSON .github/scripts/resolve-table-prefix.mjs)"
echo "resolved TABLE_PREFIX: ${resolved:-<empty>}"
echo "table_prefix=${resolved}" >> "$GITHUB_OUTPUT"

- name: Prepare D1 migrations
id: d1
working-directory: apps/worker
env:
CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}
TABLE_PREFIX: ${{ vars.TABLE_PREFIX }}
TABLE_PREFIX: ${{ steps.prefix.outputs.table_prefix }}
run: bash ../../.github/scripts/d1-prepare-migrations.sh

- name: Apply D1 migrations
Expand All @@ -113,7 +122,7 @@ jobs:
working-directory: apps/worker
env:
CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}
TABLE_PREFIX: ${{ vars.TABLE_PREFIX }}
TABLE_PREFIX: ${{ steps.prefix.outputs.table_prefix }}
run: bash ../../.github/scripts/d1-prefixed-migrations.sh

# Web and worker were built above; deploy the worker directly so wrangler
Expand All @@ -133,7 +142,7 @@ jobs:
env:
CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}
WRANGLER_OUTPUT_FILE_PATH: ${{ runner.temp }}/wrangler-output.ndjson
TABLE_PREFIX: ${{ vars.TABLE_PREFIX }}
TABLE_PREFIX: ${{ steps.prefix.outputs.table_prefix }}
run: bash ../../.github/scripts/verify-deployment.sh

- name: Smoke test
Expand Down
7 changes: 4 additions & 3 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,8 @@ shortlink/
│ │ │ │ └── auth.ts # requireAuth and requireAdmin middleware (JWT verification)
│ │ │ └── lib/
│ │ │ ├── crypto.ts # PBKDF2 password hash/verify; AES-256-GCM encrypt/decrypt TOTP
│ │ │ ├── db.ts # tbl() helper: applies TABLE_PREFIX to all table names
│ │ │ ├── db.ts # tbl(env, name) helper: applies the three-state TABLE_PREFIX to all table names
│ │ │ ├── table-prefix.ts # DEFAULT_TABLE_PREFIX + three-state resolveTablePrefix() (single source)
│ │ │ ├── jwt.ts # issueTokenPair, verifyAccessToken, verifyRefreshToken
│ │ │ ├── slug.ts # generateSlug (rejection-sampling), isValidSlug, isReservedSlug, RESERVED_SLUGS
│ │ │ ├── totp.ts # TOTP generate/verify with otpauth library
Expand Down Expand Up @@ -228,7 +229,7 @@ All set via the Cloudflare dashboard (Variables and Secrets). `keep_vars = true`
| `APP_NAME` | Yes | Default app name (overridable in admin UI) |
| `RP_ID` | Yes | WebAuthn relying party ID (domain only, no protocol) |
| `APP_ORIGIN` | Yes | WebAuthn origin (full URL with protocol) |
| `TABLE_PREFIX` | No | Prefix for all D1 table names (e.g. `sl` → `sl_users`, `sl_links`, …). Default: empty (no prefix). Must be configured **before** running the setup route — changing it after initial setup requires renaming all tables manually. Only alphanumeric and underscore characters are used; all others are stripped. |
| `TABLE_PREFIX` | No | Three-state prefix for all D1 table names. Unset → default `sl` (`sl_users`, `sl_links`, …); a custom value → that value (case preserved, `[^a-zA-Z0-9_]` stripped); explicit empty string → no prefix (deployer accepts table-collision risk). Must be configured **before** running the setup route — changing it after initial setup requires renaming all tables manually. On GitHub Actions, `none` is the reserved word for the explicit empty string (unset/empty both become the default `sl`). A silent switch (database initialised under a different prefix) aborts setup/migrations with an error. |

Email sender config and API keys are managed in the **admin UI settings**, not here.

Expand All @@ -245,7 +246,7 @@ Two files in `apps/worker/migrations/`:

**HTTP setup route (production):**
The public initialization page lives at `/setup` (an SPA route). `POST /api/setup` with a JSON body `{"secret": "<SETUP_SECRET>"}` runs migrations via the shared `lib/migrations-runner.ts` (`runMigrations`). Two migrations:
- `schema_v1` — identical DDL as `0001_init.sql`, but parameterized by `TABLE_PREFIX` and tracked in `_schema_migrations` table
- `schema_v1` — identical DDL as `0001_init.sql`, but parameterized by `TABLE_PREFIX` and tracked in `_<prefix>_schema_migrations` table
- `schema_v2` — adds `token_version` to `users` (mirrors `0002_token_version.sql`)

The legacy `X-Setup-Secret` header is still accepted when the body is empty. The endpoint is rate-limited to 3 attempts per IP per 10 minutes (counted before the secret check; a `429` carries a `Retry-After` header). `GET /api/setup/state` (public) reports `{ enabled }` from the `setup_page_enabled` setting (default enabled); `GET /api/setup/*` returns `405` pointing at the POST form. An admin can run the same migrations keylessly via `POST /api/admin/setup` (no IP rate limit; writes an audit log entry). `setup_page_enabled` only hides the setup page — it never disables the `POST` migration channel.
Expand Down
Loading
Loading