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
99 changes: 99 additions & 0 deletions .github/scripts/d1-prepare-migrations.sh
Original file line number Diff line number Diff line change
@@ -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"
29 changes: 28 additions & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -15,6 +19,8 @@ jobs:
TURBO_TELEMETRY_DISABLED: "1"
steps:
- uses: actions/checkout@v6
with:
persist-credentials: false

- uses: pnpm/action-setup@v6

Expand All @@ -24,7 +30,7 @@ jobs:
cache: pnpm

- name: Install dependencies
run: pnpm install
run: pnpm install --frozen-lockfile

- name: Biome check
run: pnpm check
Expand All @@ -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
108 changes: 102 additions & 6 deletions .github/workflows/deploy.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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."
17 changes: 14 additions & 3 deletions .github/workflows/release.yml
Original file line number Diff line number Diff line change
@@ -1,23 +1,34 @@
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:
runs-on: ubuntu-latest
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,
Expand Down
32 changes: 22 additions & 10 deletions .github/workflows/tag.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand All @@ -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 }}
Loading
Loading