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
22 changes: 20 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,8 @@ MIT, © 2025 Zach Grimaldi (`apps/web/LICENSE`).
| The site's name and source link | `apps/web/src/lib/site.ts` |
| The health route the deploy's smoke reads | `apps/web/src/app/api/health/route.ts` |
| Workers build, bindings and deploy contract | `apps/web/next.config.mjs`, `open-next.config.ts`, `wrangler.template.jsonc` + `wiring.fixture.json` (→ the committed `wrangler.jsonc`), `component.yaml` |
| The schema (migrations) and the runner that applies them over the D1 REST API | `packages/db` |
| The D1 database, the KV namespace and the R2 bucket (stage, prod) | `infra/terraform/cloudflare-d1`, `cloudflare-kv`, `cloudflare-r2` |
| The schema (migrations) and the runner that applies them over the D1 REST API | `packages/db`, run by `infra/db-migrate` |
| Tests | `tests/web` (the providers, the generated secret, the health route, the redirects), `tests/db` (the migrations through the runner, into real SQLite) |

## Getting started
Expand Down Expand Up @@ -60,10 +61,27 @@ No mail sender is configured, so email addresses are not verified.
|---|---|
| `wrangler.toml` with placeholder database, namespace and bucket ids | `wrangler.template.jsonc` → `wrangler.jsonc`, rendered per environment from wiring documents (`tooling/wire`); the binding names (`DATABASE`, `KV`, `R2_BUCKET`) are the example's |
| `better-auth-cloudflare: file:../../` (the repository's own build) | `better-auth-cloudflare@0.4.1` from npm, exact, with `better-auth` and the Drizzle adapter at `1.7.3` |
| drizzle-kit migrations, `wrangler d1 migrations apply` | `packages/db` migrations — `010_auth` (the three drizzle files' end state), `020_app_secrets` — applied locally by `db:migrate:local` |
| drizzle-kit migrations, `wrangler d1 migrations apply` | `packages/db` migrations — `010_auth` (the three drizzle files' end state), `020_app_secrets` — applied by `infra/db-migrate` before the Worker deploys, and locally by `db:migrate:local` |
| a database, a namespace and a bucket created by hand in the dashboard | `infra/terraform/cloudflare-{d1,kv,r2}`, applied by Orun before the migrations and the Worker |
| `BETTER_AUTH_SECRET` typed into `.dev.vars` | generated once per database by `020_app_secrets`; a `BETTER_AUTH_SECRET` secret wins |
| `BETTER_AUTH_URL` / `BETTER_AUTH_TRUSTED_ORIGINS` vars | optional; unset, the base URL and the trusted origin are the origin the request came to |
| anonymous sign-in only | anonymous, email and password, and GitHub/Google when their keys are stored |
| Next.js 15 `middleware.ts` | Next.js 16 `proxy.ts`, the same self-request to `/api/auth/get-session` |
| `next build` ignoring lint and type errors | `pnpm lint` and `pnpm typecheck` clean; the build checks types |
| `[placement] mode = "smart"` | not set: D1, KV and R2 are in the Worker's own account |

## How the data reaches the Worker

```
infra/terraform/cloudflare-d1 ──apply──► WIRING_CLOUDFLARE_D1 ─┬─► infra/db-migrate apply: packages/db's runner → POST …/d1/database/<id>/query
infra/terraform/cloudflare-kv ──apply──► WIRING_CLOUDFLARE_KV ─┤ (better-auth's tables, the generated auth secret)
infra/terraform/cloudflare-r2 ──apply──► WIRING_CLOUDFLARE_R2 ─┴─► apps/web build: tooling/wire/live.mjs → wrangler.jsonc with the ids
(dev, verify-only, renders the fixture) → next build → OpenNext → deploy
```

Each reader declares an enforced `dependsOn` on what it reads on a push to
`main` (advisory on a pull request), so one convergence per environment runs
the three roots, then the migrations, then the Worker. `wrangler.jsonc` is
committed as the fixture render of `wrangler.template.jsonc`, because the
deploy lane's `verify-app-structure` step checks the config exists before it
builds.
53 changes: 49 additions & 4 deletions apps/web/component.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,47 @@ spec:
# Its own lane per environment: the Next.js build is the longest job in the
# plan, and a shared lane would wait on it.
lane: isolated
# INFRA BEFORE APP. The Worker binds the D1 database by id, the KV namespace
# by id and the R2 bucket by name, each rendered into its config during the
# build from the wiring document its root lease-publishes after its apply;
# and better-auth reads its tables and the generated auth secret, which
# db-migrate creates in that database. A job resolves its secrets when it
# STARTS, so on a merge to main this deploy waits for all four (enforced) —
# one convergence runs cloudflare-d1 → db-migrate, cloudflare-kv and
# cloudflare-r2 → web per environment, and the documents and the schema are
# there. A pull request deploys nothing, so nothing on one waits (advisory).
dependsOn:
- component: cloudflare-d1
mode: enforced
modeRules:
- mode: advisory
when:
triggerRef: github-pull-request
- component: cloudflare-kv
mode: enforced
modeRules:
- mode: advisory
when:
triggerRef: github-pull-request
- component: cloudflare-r2
mode: enforced
modeRules:
- mode: advisory
when:
triggerRef: github-pull-request
- component: db-migrate
mode: enforced
modeRules:
- mode: advisory
when:
triggerRef: github-pull-request
secretEnv:
WIRING_CLOUDFLARE_D1_STAGE: "secret://better-auth-starter/better-auth-starter/stage/WIRING_CLOUDFLARE_D1"
WIRING_CLOUDFLARE_D1_PROD: "secret://better-auth-starter/better-auth-starter/prod/WIRING_CLOUDFLARE_D1"
WIRING_CLOUDFLARE_KV_STAGE: "secret://better-auth-starter/better-auth-starter/stage/WIRING_CLOUDFLARE_KV"
WIRING_CLOUDFLARE_KV_PROD: "secret://better-auth-starter/better-auth-starter/prod/WIRING_CLOUDFLARE_KV"
WIRING_CLOUDFLARE_R2_STAGE: "secret://better-auth-starter/better-auth-starter/stage/WIRING_CLOUDFLARE_R2"
WIRING_CLOUDFLARE_R2_PROD: "secret://better-auth-starter/better-auth-starter/prod/WIRING_CLOUDFLARE_R2"
# The OAuth providers' client ids and secrets, stored per environment as the
# product's secrets (README → Sign-in providers). BEST-EFFORT,
# wire-now-seed-later: a key nobody has stored is skipped when the job
Expand Down Expand Up @@ -67,16 +108,20 @@ spec:
workersDevSubdomain: your-workers-subdomain

installCommand: pnpm install --frozen-lockfile
# Render this environment's wrangler config, then build. Until the D1, KV
# and R2 roots land (BA2) every environment renders from the committed
# fixture. The OAuth secrets never reach the build (`env -u`): the Worker
# Render this environment's wrangler config, then build. stage and prod
# render from the wiring documents their cloudflare-d1, cloudflare-kv and
# cloudflare-r2 applies published (secretEnv above, resolved before the
# job's first step); dev, which no root applies to and which only
# verifies, renders from the committed fixture. The committed
# wrangler.jsonc (the fixture render) is what the composition's
# verify-app-structure step finds before this runs. The OAuth secrets never reach the build (`env -u`): the Worker
# reads them at request time, so neither a bundle nor the bundler's cache
# holds them. Then each one the environment has goes to the Worker as a
# SECRET (tooling/wire/worker-secrets.mjs: `wrangler secret bulk`, the
# values over stdin) before the composition deploys it. Only the deploy
# lane holds a Cloudflare credential, so a verify lane builds the same and
# pushes nothing.
buildCommand: node ../../tooling/wire/live.mjs --template wrangler.template.jsonc --out wrangler.jsonc --components cloudflare-d1,cloudflare-kv,cloudflare-r2 --env "${ORUN_ENVIRONMENT}" --fixture wiring.fixture.json --fixture-envs dev,stage,prod && env -u GITHUB_CLIENT_ID -u GITHUB_CLIENT_SECRET -u GOOGLE_CLIENT_ID -u GOOGLE_CLIENT_SECRET -u BETTER_AUTH_SECRET pnpm exec turbo run build --filter=@app/web && node ../../tooling/wire/worker-secrets.mjs --secret GITHUB_CLIENT_ID --secret GITHUB_CLIENT_SECRET --secret GOOGLE_CLIENT_ID --secret GOOGLE_CLIENT_SECRET --secret BETTER_AUTH_SECRET --worker "better-auth-starter-web-${ORUN_ENVIRONMENT}" --config wrangler.jsonc
buildCommand: node ../../tooling/wire/live.mjs --template wrangler.template.jsonc --out wrangler.jsonc --components cloudflare-d1,cloudflare-kv,cloudflare-r2 --env "${ORUN_ENVIRONMENT}" --fixture wiring.fixture.json --fixture-envs dev && env -u GITHUB_CLIENT_ID -u GITHUB_CLIENT_SECRET -u GOOGLE_CLIENT_ID -u GOOGLE_CLIENT_SECRET -u BETTER_AUTH_SECRET pnpm exec turbo run build --filter=@app/web && node ../../tooling/wire/worker-secrets.mjs --secret GITHUB_CLIENT_ID --secret GITHUB_CLIENT_SECRET --secret GOOGLE_CLIENT_ID --secret GOOGLE_CLIENT_SECRET --secret BETTER_AUTH_SECRET --worker "better-auth-starter-web-${ORUN_ENVIRONMENT}" --config wrangler.jsonc

# Smoke: the sign-in page renders to its end (`</html>` — a render that
# throws partway through a streamed page still sent a 200), and
Expand Down
6 changes: 4 additions & 2 deletions apps/web/wrangler.template.jsonc
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
// The source of wrangler.jsonc, which tooling/wire renders from it: from
// wiring.fixture.json for local work (`pnpm run wire:fixture`, committed as
// that render) — and on every Orun lane, once the Terraform roots exist, from
// the wiring documents they lease-publish. Edit this file, never
// that render), and on every Orun lane from the wiring documents the
// `cloudflare-d1`, `cloudflare-kv` and `cloudflare-r2` Terraform roots
// lease-publish (WIRING_CLOUDFLARE_{D1,KV,R2}_<ENV>) — dev, which no root
// applies to, from the fixture (component.yaml's buildCommand). Edit this file, never
// wrangler.jsonc. The workers-assets composition deploys one environment per
// job with no wrangler `--env`, so `__ENV__` names the environment this is
// rendered for.
Expand Down
69 changes: 69 additions & 0 deletions infra/db-migrate/component.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
apiVersion: sourceplane.io/v1
kind: Component
metadata:
name: db-migrate
description: Applies better-auth's schema and the generated auth secret (packages/db's migrations) to the stage and prod Cloudflare D1 databases
labels:
domain: infra
scope: database
team: platform
layer: data

spec:
type: db-migrate
lifecycle: production
owner: platform
domain: infra

# THE SCHEMA BETWEEN THE DATABASE AND THE APP. Migrations target the
# database the `cloudflare-d1` component creates, and find it through the
# wiring document that component lease-publishes after its apply — and a
# job resolves its secrets when it STARTS, so on a merge to main this waits
# for that environment's apply (enforced). apps/web waits on this the same
# way, so one convergence runs cloudflare-d1 → db-migrate → web per
# environment. A pull request applies nothing (this plans offline there), so
# nothing on one waits (advisory). `db` is the package this builds and runs;
# a change to it re-plans this.
dependsOn:
- component: db
- component: cloudflare-d1
mode: enforced
modeRules:
- mode: advisory
when:
triggerRef: github-pull-request

path: packages/db/src/migrations

parameters:
nodeVersion: "22"
pnpmVersion: "10.12.1"
owner: sourceplane
repo: better-auth-starter

# Everything the runner needs to reach D1 over the REST API, all resolved
# from orun secrets: the provider credential is minted fresh per run from the
# Cloudflare integration's d1-edit template (the workers-deploy token cannot
# touch D1), the account id is a non-secret connection fact, and the
# database id arrives in the wiring document the cloudflare-d1 component
# lease-publishes.
secretEnv:
CLOUDFLARE_API_TOKEN: "secret://better-auth-starter/better-auth-starter/{{ .environment }}/CLOUDFLARE_D1_TOKEN"
CLOUDFLARE_ACCOUNT_ID: "secret://better-auth-starter/better-auth-starter/{{ .environment }}/CLOUDFLARE_ACCOUNT_ID"
WIRING_CLOUDFLARE_D1: "secret://better-auth-starter/better-auth-starter/{{ .environment }}/WIRING_CLOUDFLARE_D1"

subscribe:
environments:
- name: stage
profile: plan
profileRules:
- profile: apply
when:
triggerRef: github-push-main

- name: prod
profile: plan
profileRules:
- profile: apply
when:
triggerRef: github-push-main
53 changes: 53 additions & 0 deletions infra/terraform/cloudflare-d1/component.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
apiVersion: sourceplane.io/v1
kind: Component

metadata:
name: cloudflare-d1
description: Provisions the Cloudflare D1 database for stage and prod — better-auth's users, sessions, accounts and files, and the generated auth secret
labels:
domain: infra
scope: runtime-database

spec:
type: terraform
lifecycle: production
owner: platform
domain: infra

parameters:
orgName: sourceplane
stackName: cloudflare-d1
terraformDir: terraform
terraformVersion: "1.15.3"
repo: better-auth-starter
# SEC-JOB: the wiring document (database id/name) is lease-published
# post-apply; worker deploys read it back as WIRING_CLOUDFLARE_D1_<ENV>,
# and db-migrate reads it to find the database it migrates.
secretOutputs: "WIRING_CLOUDFLARE_D1=wiring"

# The Cloudflare Terraform provider authenticates via the CLOUDFLARE_API_TOKEN
# env var, resolved by orun from the project-rung brokered secret — minted
# fresh per run from the d1-edit template (D1 Write; the workers-deploy token
# deliberately cannot touch D1). Declared at component level because
# plan-only lanes refresh against the live Cloudflare API too, not just apply.
secretEnv:
CLOUDFLARE_API_TOKEN: "secret://better-auth-starter/better-auth-starter/{{ .environment }}/CLOUDFLARE_D1_TOKEN"
# Non-secret connection fact (account-id template).
CLOUDFLARE_ACCOUNT_ID: "secret://better-auth-starter/better-auth-starter/{{ .environment }}/CLOUDFLARE_ACCOUNT_ID"
TF_VAR_cloudflare_account_id: "secret://better-auth-starter/better-auth-starter/{{ .environment }}/CLOUDFLARE_ACCOUNT_ID"

subscribe:
environments:
- name: stage
profile: plan-only
profileRules:
- profile: apply
when:
triggerRef: github-push-main

- name: prod
profile: plan-only
profileRules:
- profile: apply
when:
triggerRef: github-push-main
43 changes: 43 additions & 0 deletions infra/terraform/cloudflare-d1/terraform/adopt.tf
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
# --- Self-healing adoption ---
#
# When the platform state does not yet track the database but Cloudflare
# already has one under this name (a re-bootstrap after a torn-down workspace,
# or state recovered onto a fresh backend), the create would collide with the
# duplicate-name guard. Instead: look the database up at plan time with the
# job's brokered credentials and import it. Fresh products resolve to id = ""
# and create normally, and a resource already tracked in state short-circuits
# the lookup — so this block is inert everywhere except the one case it exists
# for. Both lookups run inside the job: process env carries the brokered
# CLOUDFLARE_API_TOKEN/CLOUDFLARE_ACCOUNT_ID and the TF_HTTP_* state
# credentials, so no extra secrets are needed.

data "external" "adopt_platform_database" {
program = ["bash", "-c", <<-EOT
set -euo pipefail
name="$(jq -r .name)"
state_file="$(mktemp)"
trap 'rm -f "$state_file"' EXIT
code="$(curl -s -o "$state_file" -w '%%{http_code}' \
-u "$TF_HTTP_USERNAME:$TF_HTTP_PASSWORD" "$TF_HTTP_ADDRESS" || echo 000)"
if [ "$code" = "200" ] && jq -e \
'[.resources[]? | select(.type == "cloudflare_d1_database" and .name == "platform")] | length > 0' \
"$state_file" >/dev/null 2>&1; then
jq -n '{id: ""}'
exit 0
fi
resp="$(curl -fsS --retry 3 -H "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
"https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/d1/database?per_page=100")"
printf '%s' "$resp" | jq -c --arg n "$name" \
'{id: ([.result[] | select(.name == $n) | .uuid] | first // "")}'
EOT
]
query = {
name = local.database_name
}
}

import {
for_each = toset(compact([data.external.adopt_platform_database.result.id]))
to = cloudflare_d1_database.platform
id = "${var.cloudflare_account_id}/${each.value}"
}
5 changes: 5 additions & 0 deletions infra/terraform/cloudflare-d1/terraform/backend.tf
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
# Terraform backend configuration is provided by Orun at runtime
# through environment variables and automatic backend initialization.
#
# S3 backend details are set via CLI args in the Orun runner.
# Local placeholder file for clarity.
Loading
Loading