diff --git a/.github/scripts/d1-prepare-migrations.sh b/.github/scripts/d1-prepare-migrations.sh new file mode 100755 index 0000000..e69e06d --- /dev/null +++ b/.github/scripts/d1-prepare-migrations.sh @@ -0,0 +1,99 @@ +#!/usr/bin/env bash +# Prepares the remote D1 database for `wrangler d1 migrations apply --remote`. +# Run from apps/worker (needs wrangler.toml with real IDs injected). +# +# Production databases may have been bootstrapped through the HTTP setup route +# (routes/setup.ts), which records applied migrations as `schema_vN` in its own +# `_schema_migrations` table instead of wrangler's `d1_migrations`. Running +# wrangler against such a database would re-run 0001_init.sql and fail on +# "table already exists". This script baselines `d1_migrations` from +# `_schema_migrations`, by the convention: +# +# 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 +set -euo pipefail + +out="${GITHUB_OUTPUT:-/dev/stdout}" + +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" + exit 0 +fi + +d1_query() { + pnpm exec wrangler d1 execute DB --remote --json --command "$1" | + jq -r '.[0].results[] | .name' +} + +tables="$(d1_query "SELECT name FROM sqlite_master WHERE type = 'table'")" +has_table() { grep -qx "$1" <<<"$tables"; } + +if has_table d1_migrations; then + echo "d1_migrations present — database is already tracked by wrangler." + echo "mode=apply" >>"$out" + exit 0 +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 "mode=skip" >>"$out" + exit 0 + fi + echo "Empty database — wrangler will apply all migrations." + echo "mode=apply" >>"$out" + exit 0 +fi + +# Unprefixed schema created by the setup route: baseline d1_migrations. +applied="" +if has_table _schema_migrations; then + applied="$(d1_query "SELECT name FROM _schema_migrations")" +fi +if [[ -z "$applied" ]]; then + # No history: only assume schema_v1 if the full 0001_init.sql schema is + # really there, rather than marking it applied on a partial/drifted schema. + for t in users passkeys links click_logs verifications settings audit_logs totp_used; do + if ! has_table "$t"; then + echo "::error::Tables exist but no migration history was found, and table '$t' from 0001_init.sql is missing; refusing to baseline." + exit 1 + fi + done + if ! d1_query "SELECT name FROM pragma_table_info('links')" | grep -qx user_seq; then + echo "::error::Tables exist but no migration history was found, and links.user_seq from 0001_init.sql is missing; refusing to baseline." + exit 1 + fi + echo "::warning::Tables exist but no migration history was found; the 0001_init.sql schema is present, baselining it as schema_v1." + applied="schema_v1" +fi + +values=() +for file in migrations/*.sql; do + name="$(basename "$file")" + num="${name%%_*}" + [[ "$num" =~ ^[0-9]+$ ]] || continue + if grep -qx "schema_v$((10#$num))" <<<"$applied"; then + values+=("('$name')") + fi +done + +if [[ ${#values[@]} -eq 0 ]]; then + echo "::error::Could not map any applied setup-route migration to migrations/*.sql; refusing to baseline." + exit 1 +fi + +echo "Baselining d1_migrations with: ${values[*]}" +pnpm exec wrangler d1 execute DB --remote --command " + CREATE TABLE IF NOT EXISTS d1_migrations ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + name TEXT UNIQUE, + applied_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL + ); + INSERT OR IGNORE INTO d1_migrations (name) VALUES $(IFS=,; echo "${values[*]}"); +" +echo "mode=apply" >>"$out" diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 2e2a7b8..cf3ce62 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -7,6 +7,10 @@ on: branches: [main] workflow_dispatch: +# Read-only token: no job here needs to write to the repository. +permissions: + contents: read + jobs: ci: name: Check, Typecheck, Build @@ -15,6 +19,8 @@ jobs: TURBO_TELEMETRY_DISABLED: "1" steps: - uses: actions/checkout@v6 + with: + persist-credentials: false - uses: pnpm/action-setup@v6 @@ -24,7 +30,7 @@ jobs: cache: pnpm - name: Install dependencies - run: pnpm install + run: pnpm install --frozen-lockfile - name: Biome check run: pnpm check @@ -34,3 +40,24 @@ jobs: - name: Build run: pnpm build + + audit: + name: Dependency audit + runs-on: ubuntu-latest + # Non-blocking for now: existing advisories (react-router < 7.18.2) would + # otherwise fail every run. Make this blocking once they are resolved. + continue-on-error: true + steps: + - uses: actions/checkout@v6 + with: + persist-credentials: false + + - uses: pnpm/action-setup@v6 + + - uses: actions/setup-node@v6 + with: + node-version: 24 + + # Audits the lockfile against the advisory database; no install needed. + - name: pnpm audit (prod, high+) + run: pnpm audit --prod --audit-level=high diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml index 65ecf5e..bd3b64a 100644 --- a/.github/workflows/deploy.yml +++ b/.github/workflows/deploy.yml @@ -8,15 +8,38 @@ on: - completed workflow_dispatch: +permissions: + contents: read + +# One production deploy at a time; a newer pending run replaces an older +# pending one, but a running deploy (and its migrations) is never cancelled. +concurrency: + group: deploy-production + cancel-in-progress: false + jobs: deploy: - if: github.event_name == 'workflow_dispatch' || github.event.workflow_run.conclusion == 'success' + # workflow_run: only after a successful CI run for a push to this repo's + # main (the `branches` filter alone also matches fork PRs from a branch + # named "main"). workflow_dispatch: only from main. + if: >- + (github.event_name == 'workflow_dispatch' && github.ref == 'refs/heads/main') || + (github.event.workflow_run.conclusion == 'success' && + github.event.workflow_run.event == 'push' && + github.event.workflow_run.head_repository.full_name == github.repository) runs-on: ubuntu-latest + environment: + name: production + url: ${{ vars.APP_URL }} env: TURBO_TELEMETRY_DISABLED: "1" WRANGLER_SEND_METRICS: "false" steps: + # Deploy exactly the commit CI verified, not whatever main points to now. - uses: actions/checkout@v6 + with: + ref: ${{ github.event.workflow_run.head_sha || github.sha }} + persist-credentials: false - uses: pnpm/action-setup@v6 @@ -26,16 +49,89 @@ jobs: cache: pnpm - name: Install dependencies - run: pnpm install + run: pnpm install --frozen-lockfile - name: Inject resource IDs + env: + D1_DATABASE_ID: ${{ vars.D1_DATABASE_ID }} + D1_DATABASE_NAME: ${{ vars.D1_DATABASE_NAME || 'shortlink' }} + KV_NAMESPACE_ID: ${{ vars.KV_NAMESPACE_ID }} + CLOUDFLARE_ACCOUNT_ID: ${{ vars.CLOUDFLARE_ACCOUNT_ID }} run: | - sed -i "s/D1_DATABASE_ID_PLACEHOLDER/${{ vars.D1_DATABASE_ID }}/g" apps/worker/wrangler.toml - sed -i "s/D1_DATABASE_NAME_PLACEHOLDER/${{ vars.D1_DATABASE_NAME || 'shortlink' }}/g" apps/worker/wrangler.toml - sed -i "s/KV_NAMESPACE_ID_PLACEHOLDER/${{ vars.KV_NAMESPACE_ID }}/g" apps/worker/wrangler.toml - sed -i "s/CLOUDFLARE_ACCOUNT_ID_PLACEHOLDER/${{ vars.CLOUDFLARE_ACCOUNT_ID }}/g" apps/worker/wrangler.toml + check() { + if ! [[ "${!1}" =~ $2 ]]; then + echo "::error::Variable $1 is missing or malformed (expected $2)" + exit 1 + fi + } + check D1_DATABASE_ID '^[0-9a-fA-F-]{32,36}$' + check D1_DATABASE_NAME '^[A-Za-z0-9_-]+$' + check KV_NAMESPACE_ID '^[0-9a-fA-F]{32}$' + check CLOUDFLARE_ACCOUNT_ID '^[0-9a-fA-F]{32}$' + + f=apps/worker/wrangler.toml + sed -i "s/D1_DATABASE_ID_PLACEHOLDER/${D1_DATABASE_ID}/g" "$f" + sed -i "s/D1_DATABASE_NAME_PLACEHOLDER/${D1_DATABASE_NAME}/g" "$f" + sed -i "s/KV_NAMESPACE_ID_PLACEHOLDER/${KV_NAMESPACE_ID}/g" "$f" + sed -i "s/CLOUDFLARE_ACCOUNT_ID_PLACEHOLDER/${CLOUDFLARE_ACCOUNT_ID}/g" "$f" + if grep -q '_PLACEHOLDER' "$f"; then + echo "::error::Unreplaced placeholders remain in $f" + exit 1 + fi + + # Build before touching the database so a broken build never leaves a + # migrated schema behind. + - name: Build + run: pnpm build + + # 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: Prepare D1 migrations + id: d1 + working-directory: apps/worker + env: + CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }} + TABLE_PREFIX: ${{ vars.TABLE_PREFIX }} + run: bash ../../.github/scripts/d1-prepare-migrations.sh + + - name: Apply D1 migrations + if: steps.d1.outputs.mode == 'apply' + working-directory: apps/worker + env: + CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }} + run: pnpm run db:migrate - name: Deploy run: pnpm run deploy env: CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }} + + - 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 + + - name: Rollback hint + if: failure() && steps.smoke.outcome == 'failure' + run: | + echo "::error::Smoke test failed after deploy. 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/.github/workflows/release.yml b/.github/workflows/release.yml index d62e628..7933e0c 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -1,9 +1,20 @@ name: Release on: + # Tags pushed by a person (or a PAT) trigger this directly. push: tags: - 'v*' + # Tags created by tag.yml are pushed with GITHUB_TOKEN, which never triggers + # other workflows, so tag.yml calls this workflow explicitly instead. + workflow_call: + inputs: + tag: + description: 'Tag to release (e.g., v1.0.0)' + required: true + type: string + +permissions: {} jobs: release: @@ -11,13 +22,13 @@ jobs: permissions: contents: write steps: - - uses: actions/checkout@v6 - - name: Create GitHub Release uses: actions/github-script@v9 + env: + TAG: ${{ inputs.tag || github.ref_name }} with: script: | - const tag = context.ref.replace('refs/tags/', ''); + const tag = process.env.TAG; await github.rest.repos.createRelease({ owner: context.repo.owner, repo: context.repo.repo, diff --git a/.github/workflows/tag.yml b/.github/workflows/tag.yml index d6780c0..4e50ab2 100644 --- a/.github/workflows/tag.yml +++ b/.github/workflows/tag.yml @@ -8,31 +8,35 @@ on: required: true type: string +permissions: {} + jobs: create-tag: runs-on: ubuntu-latest - + permissions: + contents: write + env: + TAG: ${{ inputs.tag }} + steps: - name: Validate tag format run: | - TAG="${{ inputs.tag }}" if ! [[ "$TAG" =~ ^v([0-9]+)\.([0-9]+)\.([0-9]+)$ ]]; then echo "❌ Error: Tag format is invalid. Must be semantic version like v1.0.0" echo "Provided: $TAG" exit 1 fi echo "✅ Tag format is valid: $TAG" - + + # Uses the default GITHUB_TOKEN (contents: write) — no long-lived PAT. - name: Checkout repository uses: actions/checkout@v6 with: ref: main fetch-depth: 0 - token: ${{ secrets.PAT_TOKEN }} - + - name: Check if tag already exists run: | - TAG="${{ inputs.tag }}" git fetch --tags if git tag -l | grep -q "^${TAG}$"; then echo "❌ Error: Tag '$TAG' already exists" @@ -41,18 +45,26 @@ jobs: exit 1 fi echo "✅ Tag '$TAG' does not exist, proceeding..." - + - name: Configure Git run: | git config user.name "github-actions[bot]" git config user.email "github-actions[bot]@users.noreply.github.com" - + - name: Create and push tag run: | - TAG="${{ inputs.tag }}" echo "Creating tag: $TAG" git tag "$TAG" echo "Pushing tag to remote..." git push origin "$TAG" echo "✅ Successfully created and pushed tag: $TAG" - echo "🚀 This will trigger the automatic release workflow" + + # A tag pushed with GITHUB_TOKEN does not trigger release.yml's `push` + # trigger, so the release is created here by calling it directly. + release: + needs: create-tag + permissions: + contents: write + uses: ./.github/workflows/release.yml + with: + tag: ${{ inputs.tag }} diff --git a/apps/worker/package.json b/apps/worker/package.json index fc3b36a..c270ca2 100644 --- a/apps/worker/package.json +++ b/apps/worker/package.json @@ -7,8 +7,8 @@ "build": "tsc --noEmit", "typecheck": "tsc --noEmit", "deploy": "wrangler deploy", - "db:migrate:local": "wrangler d1 migrations apply shortlink --local", - "db:migrate": "wrangler d1 migrations apply shortlink" + "db:migrate:local": "wrangler d1 migrations apply DB --local", + "db:migrate": "wrangler d1 migrations apply DB --remote" }, "dependencies": { "hono": "^4.6.12", diff --git a/turbo.json b/turbo.json index 5bdda29..48bd79f 100644 --- a/turbo.json +++ b/turbo.json @@ -14,6 +14,7 @@ }, "deploy": { "dependsOn": ["@shortlink/web#build", "build"], + "cache": false, "passThroughEnv": ["CLOUDFLARE_API_TOKEN"] } }