From 2254e248bc5ee1e1eb565aa6751ef5ee11bd8df3 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 15 Oct 2026 20:44:46 +0000 Subject: [PATCH] SS4: supabase-starter becomes an Orun baseline The repository is an Orun baseline on the Cloudflare + Supabase (Lumen) conventions, built the way cirrus-baseline v22 builds a product: ONE landing. 01-product places every module, brands it, links the repository, reconciles four brokered keys (workers-deploy, account-id, management-access, org-id) and lands it as one pull request, then awaits the convergence, WIRING_SUPABASE and Lumen's three database credentials on stage and prod, and / + /api/health; 02-docs restores the promotion gate and dev's lanes and renders the deployment record. No Hyperdrive and no db-migrate: the chain is supabase -> web, enforced on main, advisory on pull requests. The baseline: - blueprint.yaml (card: requires github, cloudflare, supabase; the two Supabase projects the free plan allows stated as a prerequisite) and repo-blueprint.yaml (two phases, one landing) - .baseline/ (identity, task contracts, the product's README), the rename engine with the SITE_NAME seam, the bootstrap helpers, the deployment-record hook, ai/context/, BOOTSTRAP.md, docs/phases/ - testing/: manifest, phases, coverage, rebrand, retouch, bootstrap-defer, leak, placement (offline bootstrap of both phases, the product's own push-to-main plan, --resume) and e2e (the 01-product landing under its checks, the stage web lane's steps in the job tree orun stages, wrangler dev against a local Supabase stand-in: Auth, the Data API's select and the SQL editor's query endpoint over a Postgres with Supabase's roles) - baseline.yml, tag.yml; checks.yml on pull requests only; ci.yml's linked gate and lanes on v2.78.4; stack-tectonic 0.19.0 The product: - the supabase root keeps Lumen's three outputs and publishes WIRING_SUPABASE (URL + publishable key); the service-role key is no longer read out; it sets the project's Auth Site URL and redirect allow-list to the Worker and turns email confirmation off until the project has SMTP (authEmailConfirmation), after waiting for ACTIVE_HEALTHY; provider lock file committed - web depends on supabase (enforced on main), reads its wiring as optional refs, re-renders the committed wrangler.jsonc in stage/prod, and next build inlines the URL and key from that config (next.config.ts) - /api/health (Supabase Auth reachable with the inlined key, sign-up and confirmation state), exempt from the session proxy; the smoke reads it - sign-up goes to /protected when it gets a session; the auth forms explain email_address_not_authorized, the email rate limit and an unreachable service - the tutorial's notes table: RLS on in the same statement, policies keyed on auth.uid() - packages/.gitkeep (orun refused the intent without the discovery root) Not verified: a Terraform apply (the brokered OAuth token's reach to the API-keys and Auth-config endpoints), a live deploy and bootstrap, real email delivery. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01AuyckrXahuAVgdmxamUUtk --- .baseline/identity.json | 9 + .baseline/product/README.md | 126 ++++ .baseline/tasks/01-product.TaskContract.yaml | 29 + .baseline/tasks/02-docs.TaskContract.yaml | 14 + .github/workflows/baseline.yml | 132 ++++ .github/workflows/checks.yml | 22 +- .github/workflows/ci.yml | 38 +- .github/workflows/tag.yml | 97 +++ .gitignore | 4 +- BOOTSTRAP.md | 227 ++++++ README.md | 119 ++- ai/context/deployment.md | 7 + ai/context/operations.md | 169 +++++ apps/web/.dev.vars.example | 15 + apps/web/.env.example | 7 +- apps/web/README.md | 141 +--- apps/web/app/api/health/route.ts | 58 ++ apps/web/app/layout.tsx | 3 +- apps/web/app/page.tsx | 3 +- apps/web/app/protected/layout.tsx | 3 +- apps/web/component.yaml | 48 +- apps/web/components/forgot-password-form.tsx | 3 +- apps/web/components/login-form.tsx | 3 +- apps/web/components/sign-up-form.tsx | 10 +- .../components/tutorial/fetch-data-steps.tsx | 40 +- apps/web/components/update-password-form.tsx | 3 +- apps/web/lib/site.ts | 5 + apps/web/lib/supabase/errors.ts | 23 + apps/web/next.config.ts | 83 ++- apps/web/proxy.ts | 5 +- apps/web/wrangler.jsonc | 38 + apps/web/wrangler.template.jsonc | 25 +- blueprint.yaml | 150 ++++ docs/phases/01-product.md | 112 +++ docs/phases/02-docs.md | 41 + docs/phases/README.md | 101 +++ hooks/render-deployment-docs.sh | 196 +++++ infra/terraform/supabase/component.yaml | 17 +- .../supabase/terraform/.terraform.lock.hcl | 73 ++ infra/terraform/supabase/terraform/main.tf | 108 ++- intent.yaml | 26 +- packages/.gitkeep | 0 pnpm-lock.yaml | 9 +- repo-blueprint.yaml | 700 ++++++++++++++++++ specs/epics/README.md | 2 +- .../supabase-starter/IMPLEMENTATION-STATUS.md | 103 +++ specs/epics/supabase-starter/README.md | 9 +- specs/epics/supabase-starter/design.md | 45 +- specs/epics/supabase-starter/epic.yaml | 10 +- .../supabase-starter/implementation-plan.md | 30 + .../risks-and-open-questions.md | 92 ++- tasks/SS-1.TaskContract.yaml | 3 + tasks/SS-2.TaskContract.yaml | 3 + tasks/SS-3.TaskContract.yaml | 3 + tasks/SS-4.TaskContract.yaml | 3 + tasks/SS-5.TaskContract.yaml | 37 + testing/bootstrap-defer.test.sh | 67 ++ testing/coverage.test.sh | 177 +++++ testing/e2e.test.sh | 555 ++++++++++++++ testing/fixtures/acme.json | 23 + .../baseline-identity.supabase-starter.json | 9 + testing/leak.test.sh | 176 +++++ .../fake-supabase-api.cpython-313.pyc | Bin 0 -> 30457 bytes testing/lib/bootstrap.sh | 63 ++ testing/lib/browser-auth.mjs | 93 +++ testing/lib/fake-supabase-api.py | 416 +++++++++++ testing/lib/local-postgres.sh | 72 ++ testing/lib/run-hooks.py | 72 ++ testing/lib/stage-job.py | 82 ++ testing/manifest.test.sh | 432 +++++++++++ testing/phases.test.sh | 367 +++++++++ testing/placement.test.sh | 449 +++++++++++ testing/rebrand.test.sh | 176 +++++ testing/retouch.test.sh | 199 +++++ tests/web/package.json | 11 +- tests/web/src/auth-errors.test.ts | 31 + tests/web/src/health.test.ts | 69 ++ tests/web/src/next-config.test.ts | 75 ++ tests/web/src/proxy-matcher.test.ts | 25 + tests/web/src/wrangler-config.test.ts | 98 +++ tooling/bootstrap/dev-lanes.mjs | 114 +++ tooling/bootstrap/promotion.mjs | 123 +++ tooling/bootstrap/retouch.mjs | 254 +++++++ tooling/bootstrap/work-tree.mjs | 73 ++ tooling/rebrand/rebrand.mjs | 486 ++++++++++++ tooling/rebrand/values.example.json | 8 + 86 files changed, 7887 insertions(+), 290 deletions(-) create mode 100644 .baseline/identity.json create mode 100644 .baseline/product/README.md create mode 100644 .baseline/tasks/01-product.TaskContract.yaml create mode 100644 .baseline/tasks/02-docs.TaskContract.yaml create mode 100644 .github/workflows/baseline.yml create mode 100644 .github/workflows/tag.yml create mode 100644 BOOTSTRAP.md create mode 100644 ai/context/deployment.md create mode 100644 ai/context/operations.md create mode 100644 apps/web/.dev.vars.example create mode 100644 apps/web/app/api/health/route.ts create mode 100644 apps/web/lib/site.ts create mode 100644 apps/web/lib/supabase/errors.ts create mode 100644 apps/web/wrangler.jsonc create mode 100644 blueprint.yaml create mode 100644 docs/phases/01-product.md create mode 100644 docs/phases/02-docs.md create mode 100644 docs/phases/README.md create mode 100755 hooks/render-deployment-docs.sh create mode 100644 infra/terraform/supabase/terraform/.terraform.lock.hcl create mode 100644 packages/.gitkeep create mode 100644 repo-blueprint.yaml create mode 100644 tasks/SS-5.TaskContract.yaml create mode 100755 testing/bootstrap-defer.test.sh create mode 100755 testing/coverage.test.sh create mode 100644 testing/e2e.test.sh create mode 100644 testing/fixtures/acme.json create mode 100644 testing/fixtures/baseline-identity.supabase-starter.json create mode 100755 testing/leak.test.sh create mode 100644 testing/lib/__pycache__/fake-supabase-api.cpython-313.pyc create mode 100755 testing/lib/bootstrap.sh create mode 100644 testing/lib/browser-auth.mjs create mode 100755 testing/lib/fake-supabase-api.py create mode 100755 testing/lib/local-postgres.sh create mode 100755 testing/lib/run-hooks.py create mode 100755 testing/lib/stage-job.py create mode 100755 testing/manifest.test.sh create mode 100755 testing/phases.test.sh create mode 100755 testing/placement.test.sh create mode 100755 testing/rebrand.test.sh create mode 100755 testing/retouch.test.sh create mode 100644 tests/web/src/auth-errors.test.ts create mode 100644 tests/web/src/health.test.ts create mode 100644 tests/web/src/next-config.test.ts create mode 100644 tests/web/src/proxy-matcher.test.ts create mode 100644 tests/web/src/wrangler-config.test.ts create mode 100755 tooling/bootstrap/dev-lanes.mjs create mode 100644 tooling/bootstrap/promotion.mjs create mode 100644 tooling/bootstrap/retouch.mjs create mode 100644 tooling/bootstrap/work-tree.mjs create mode 100644 tooling/rebrand/rebrand.mjs create mode 100644 tooling/rebrand/values.example.json diff --git a/.baseline/identity.json b/.baseline/identity.json new file mode 100644 index 0000000..9d40bc1 --- /dev/null +++ b/.baseline/identity.json @@ -0,0 +1,9 @@ +{ + "_comment": "THIS TREE'S OWN IDENTITY — the FROM side of every rebrand. tooling/rebrand/rebrand.mjs reads it to know what to rename AWAY from; a product's identity is the --values file, which is the TO side. Change a value here only together with the tree: these strings must be what the tree actually contains, or the rename silently misses and the product ships carrying this baseline's name. `productName` is the SITE_NAME seam in apps/web/lib/site.ts (upstream's header text); `domain` and `subdomain` are placeholders, because this baseline has never deployed under a name of its own; `githubOwner` is the owner in this repository's source link.", + "slug": "supabase-starter", + "pascal": "SupabaseStarter", + "productName": "Next.js Supabase Starter", + "domain": "supabase-starter.example.com", + "subdomain": "your-workers-subdomain", + "githubOwner": "sourceplane" +} diff --git a/.baseline/product/README.md b/.baseline/product/README.md new file mode 100644 index 0000000..91da032 --- /dev/null +++ b/.baseline/product/README.md @@ -0,0 +1,126 @@ +# supabase-starter + +Vercel's [Next.js and Supabase Starter](https://github.com/vercel/next.js/tree/canary/examples/with-supabase) +— Supabase Auth with cookie sessions through `@supabase/ssr`, a +session-refreshing proxy, sign-up / login / password flows and a protected +page — on **Cloudflare Workers + Static Assets** through +[`@opennextjs/cloudflare`](https://opennext.js.org/cloudflare), with a +**Supabase** project per environment provisioned by Terraform, its Auth +pointed at the app, on every merge to `main`. + +## Live deployment + + +Not recorded yet. The bootstrap's last phase writes the live URLs, the +workspace, how sign-up behaves on each environment and the secrets inventory +into [ai/context/deployment.md](ai/context/deployment.md); how the product +deploys and how to operate it is in +[ai/context/operations.md](ai/context/operations.md). + + +## What is here + +| Surface | Where | +|---|---| +| The product's name | `apps/web/lib/site.ts` | +| Home (tutorial), auth pages, `/protected`, `/api/health` | `apps/web/app` | +| Supabase clients (browser, server), the session proxy, what the auth forms say when Supabase refuses | `apps/web/lib/supabase`, `apps/web/proxy.ts` | +| Workers build and deploy contract | `apps/web/next.config.ts`, `open-next.config.ts`, `wrangler.template.jsonc` → `wrangler.jsonc`, `component.yaml` | +| The Supabase project (stage, prod) and its Auth settings | `infra/terraform/supabase` | +| Tests | `tests/web` (vitest) | + +## Getting started + +```bash +pnpm install +pnpm run wire:fixture # re-render apps/web/wrangler.jsonc from its template (it is committed) +pnpm typecheck +pnpm lint +pnpm test +pnpm build # next build + opennextjs-cloudflare build → apps/web/.open-next +``` + +The build needs no Supabase project: without one it inlines the committed +`wrangler.jsonc`'s placeholder values, and nothing calls them. + +## Running it locally + +Against one of the product's own projects (stage is the natural one — its +URL and publishable key are in the Supabase dashboard → Project Settings → +API), or any Supabase project: + +1. Copy `apps/web/.env.example` to `apps/web/.env.local` and fill in the two + values. `next dev` and `pnpm build` read it. +2. Run Next's dev server — + + ```bash + pnpm --filter @app/web dev # http://localhost:3000 + ``` + + — or the built Worker under `wrangler dev`, with the same two values in + `apps/web/.dev.vars` (copy `.dev.vars.example`): + + ```bash + pnpm build + pnpm --filter @app/web preview # http://localhost:8787 + ``` + +Sign-up and sign-in work locally as they do deployed. Links Supabase emails +(password recovery) point at the deployed Worker, which is the project's +Site URL. + +## How it deploys + +Merges to `main` converge through [Orun](https://github.com/sourceplane/orun): +`.github/workflows/ci.yml` plans the changed components and runs each lane +against the workspace in `intent.yaml`. Per environment the order is +enforced — **the Supabase project, then the Worker** — because the app's +build reads what the project's apply published: its URL and publishable key +(`WIRING_SUPABASE`), rendered into the Worker's vars and inlined into the +browser bundle. `stage` deploys first and `prod` once stage has converged on +the same commit; `dev` only verifies. Every deploy is smoke-tested over +HTTP, `/api/health` included, which answers only when the project's Auth +answers the key the build inlined. + +The pipeline holds one credential, GitHub's own `GITHUB_TOKEN`. The +Cloudflare token and account id and the Supabase access token and org id are +brokered per run from the workspace's connections; the project's URL, keys +and database credentials are published by the Terraform apply as orun +secrets. Nothing provider-shaped is stored in the repository or in GitHub. + +## Email + +A Supabase project without an SMTP server of its own emails only the members +of its organization, a few times an hour. So each project is created with +email confirmation **off**: a new user is signed in the moment they sign up, +and anyone can. Password recovery still sends email — until the project has +SMTP, the form says the address cannot be mailed yet. + +To require confirmation, give each project SMTP of its own (Supabase +dashboard → Authentication → Emails → SMTP Settings), then set +`authEmailConfirmation: "true"` in `infra/terraform/supabase/component.yaml` +and merge. The confirmation link lands on `/auth/confirm` when the project's +"Confirm signup" template is +`{{ .SiteURL }}/auth/confirm?token_hash={{ .TokenHash }}&type=email&next=/protected`. + +## Your first table + +The protected page's tutorial creates a `notes` table with **row-level +security on** and policies that let each signed-in user read and add only +their own notes. Keep that rule for every table in `public`: the publishable +key is public by design, and RLS is what protects the data. + +## Custom domain + +The app answers on workers.dev from its first deploy. To serve it on your +own domain, attach the domain to the Worker in Cloudflare (Workers & Pages → +`supabase-starter-web-prod` → Settings → Domains & Routes), then make it +prod's `app_origin` in `infra/terraform/supabase/terraform/main.tf` and merge +— the apply owns the project's Auth Site URL and redirect allow-list. + +## CI + +| Workflow | What it runs | +|---|---| +| `checks.yml` | install, wire fixture, typecheck, lint, test, build — every pull request (not pushes: on `main`, `ci.yml` must be the only run a commit has) | +| `ci.yml` | the Orun pipeline: `orun plan --changed`, then one job per lane; applies and deploys stage → prod on merge | diff --git a/.baseline/tasks/01-product.TaskContract.yaml b/.baseline/tasks/01-product.TaskContract.yaml new file mode 100644 index 0000000..255c67f --- /dev/null +++ b/.baseline/tasks/01-product.TaskContract.yaml @@ -0,0 +1,29 @@ +# Task contract template for the 01-product landing. +# Unbound to a key on purpose: `orun.task/ensure@v1` seals and attaches it to +# the key the allocator issues. It lives under `.baseline/`, not `tasks/`, +# because `tasks/` is this repository's own work tree (`intent.yaml` `work:`), +# where an unkeyed contract is an error. gates: [] is a DECLARATION — merge +# alone finishes this task; the main convergence is the gate the bootstrap +# watches, not one the plane observes as a PR check. +# +# The whole product in one landing. `affects` names COMPONENTS, by +# metadata.name — every one the bootstrap's convergence plans on stage and +# prod (the test package verifies on dev, which the bootstrap keeps off main +# until 02-docs, so a marker on it would re-plan nothing): the phase's +# retouch hook reads this list to decide which component.yaml files get the +# redeploy marker, so a re-run after a failed convergence has a diff and +# re-plans exactly these — the deploy set and the task plane's statement of +# the work are one list. +apiVersion: orun.io/v1 +kind: TaskContract +spec: + goal: The product's repository is born and linked, the whole product lands in one pull request, and one convergence provisions the Supabase project and deploys the app on stage and prod + affects: + - supabase + - web + doneWhen: + - repo pushed, main pinned as default, workspace linked + - WIRING_SUPABASE, SUPABASE_PROJECT_REF, SUPABASE_DB_PASSWORD and SUPABASE_DB_URL published on stage and prod + - the app deployed and smoke-tested on stage and prod, in the order supabase → web + - the home page and /api/health answer on both workers.dev URLs + gates: [] diff --git a/.baseline/tasks/02-docs.TaskContract.yaml b/.baseline/tasks/02-docs.TaskContract.yaml new file mode 100644 index 0000000..bf6e30b --- /dev/null +++ b/.baseline/tasks/02-docs.TaskContract.yaml @@ -0,0 +1,14 @@ +# Task contract template for the 02-docs landing. See 01-product's header. +apiVersion: orun.io/v1 +kind: TaskContract +spec: + goal: The live deployment is recorded from verified facts as agent-readable state in the product's repo, and the bootstrap's deferrals are put back + affects: + - ai/context/deployment.md + - ai/context/operations.md + - README.md + - intent.yaml + doneWhen: + - committed deployment manifest matches probed reality + - prod waits on stage again, and dev verifies every merge to main again + gates: [] diff --git a/.github/workflows/baseline.yml b/.github/workflows/baseline.yml new file mode 100644 index 0000000..2bf16ef --- /dev/null +++ b/.github/workflows/baseline.yml @@ -0,0 +1,132 @@ +name: Baseline CI + +# THE FACTORY'S OWN LANES — this repository tested as a BASELINE: that its +# build document parses with the orun a bootstrap actually runs, that its card +# agrees with it, that every component is placed by exactly one phase, that a +# placed tree comes up branded and carrying nothing of the factory, that the +# product's own push-to-main plan deploys the Supabase project before the app, +# and that the product installs, builds, deploys (dry), serves and signs a +# user up and in through Supabase Auth (a local stand-in). +# +# ─── WHY THIS IS NOT IN ci.yml OR checks.yml ────────────────────────────── +# +# `repo-blueprint.yaml`'s `github-workflows` module copies the WHOLE `.github` +# directory into every product built from this repository. These jobs run +# `testing/*.sh`, and `testing/` is deliberately not placed — so in a product +# they would be steps that cannot pass, red on its very first pull request. This +# file is in the blueprint's `ignore` list, and `testing/coverage.test.sh` +# fails on any workflow that reads `testing/` and is not. + +on: + push: + branches: [main] + pull_request: + +concurrency: + group: baseline-ci-${{ github.event_name == 'pull_request' && github.ref || github.run_id }} + cancel-in-progress: ${{ github.event_name == 'pull_request' }} + +permissions: + contents: read + +jobs: + # Tier 0. bash, python3 and git; node for the tools. No workspace install, + # no network, no credential — the job that most certainly fails a PR. + baseline-contract: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v6 + - uses: actions/setup-node@v5 + with: + node-version: 22 + # setup-node v5 turns on the pnpm cache by itself when package.json + # names a packageManager, and then fails on a runner with no pnpm. + # This job installs nothing. + package-manager-cache: false + - name: Contract tests (manifest, phases, coverage, rebrand, retouch, bootstrap-defer) + run: | + set -euo pipefail + python3 -c 'import yaml' 2>/dev/null || pip install --quiet pyyaml + for t in manifest phases coverage rebrand retouch bootstrap-defer; do + echo "── $t" + bash "testing/$t.test.sh" + done + + # Tier 1. THE BLUEPRINT, READ AND PLACED BY THE BINARY A BOOTSTRAP RUNS. + # + # Pinned at the bootstrap floor (BOOTSTRAP.md), not the product's lane pin: + # every test here reads YAML with PyYAML, which parses anything well-formed; + # only the pinned orun can say whether the document is one a bootstrap can + # run. `--status` parses it, validates every hook against the action + # registry, compiles every `when` and narration template, and writes + # nothing. Then the leak gate (what a product would carry) and the + # placement tier (the offline bootstrap: both phases placed and finished by + # the blueprint's own hooks, then the product's own `orun plan` for the + # 01-product merge — supabase, then web, enforced — and a --resume that + # changes nothing). + blueprint: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v6 + - uses: sourceplane/orun-action@v1.2.0 + with: + version: v2.58.11 + - uses: pnpm/action-setup@v4 + with: + version: 10.12.1 + - uses: actions/setup-node@v5 + with: + node-version: 22 + - name: repo-blueprint.yaml, read by the pinned CLI + run: | + set -euo pipefail + orun --version + python3 -c 'import yaml' 2>/dev/null || pip install --quiet pyyaml + # Required inputs must be supplied for the document to resolve; the + # values are arbitrary and nothing is written. + orun new --blueprint repo-blueprint.yaml --status \ + --out "$(mktemp -d)" \ + --set reponame=acme-auth \ + --set "productname=Acme Cloud" \ + --set productdomain=acme.dev \ + --set githuborg=acme-inc + - name: the leak gate — what a product carries + run: bash testing/leak.test.sh + - name: placement — the offline bootstrap, and the product's own plan + run: | + git config --global user.email ci@example.invalid + git config --global user.name "baseline ci" + bash testing/placement.test.sh + + # Tier 2. THE PRODUCT IT PRODUCES WORKS: the 01-product landing under the + # checks its pull request waits on; a local Postgres with Supabase's roles + # and a stand-in for the Supabase endpoints the app and the SQL editor call + # (Auth, and the Management API's query endpoint); the stage lane's own + # structure check, build — inlining the stage wiring it is handed — output + # check and dry deploy in the job tree orun stages; and the built Worker + # served against that stand-in — its smoke, every route, a sign-up, a + # sign-in, the protected page, the email-confirmation route, and the + # tutorial's table closed to the Data API's roles by row-level security. + # Pinned at the product's lane version, because that is the orun its CI + # runs. The runner image carries PostgreSQL 16 (not started); the test + # starts its own on a random port. + product: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v6 + - uses: sourceplane/orun-action@v1.2.0 + with: + version: v2.78.4 + - uses: pnpm/action-setup@v4 + with: + version: 10.12.1 + - uses: actions/setup-node@v5 + with: + node-version: 22 + cache: pnpm + - name: e2e — the bootstrapped product builds, deploys (dry), serves and signs a user in + run: | + python3 -c 'import yaml' 2>/dev/null || pip install --quiet pyyaml + git config --global user.email ci@example.invalid + git config --global user.name "baseline ci" + bash testing/e2e.test.sh diff --git a/.github/workflows/checks.yml b/.github/workflows/checks.yml index bd8d5df..53a8fd4 100644 --- a/.github/workflows/checks.yml +++ b/.github/workflows/checks.yml @@ -1,14 +1,22 @@ name: Checks -# Credential-free verification: install, render the offline wrangler fixtures, -# typecheck, lint, test and build. Runs on every push and pull request and is -# the merge gate until the product is linked to an Orun workspace, at which -# point `ci.yml` (Orun plan/run with brokered Cloudflare credentials) takes -# over — it stays gated behind the `ORUN_CI` repository variable until then. +# Credential-free verification: install, render the offline wrangler fixture, +# typecheck, lint, test and build, on every pull request, linked or not. No +# Supabase project: the build inlines the fixture's URL and key, and nothing +# here calls them. +# `ci.yml` is the Orun pipeline beside it (plan/run with brokered Cloudflare +# and Supabase credentials, deploys on merge); it plans nothing until +# intent.yaml names a workspace. +# +# PULL REQUESTS ONLY — not pushes to main. A push to main must start exactly +# one workflow, `ci.yml`, because a bootstrap's convergence watch +# (`orun.run/watch@v1` with `sha:`) takes the newest run for the merge commit +# from ANY workflow: with this one on push too, the watch can read this run +# green while ci.yml's deploy lanes failed, and call the product converged. +# On main the convergence builds and tests everything anyway. on: - push: - branches: [main] pull_request: + workflow_dispatch: concurrency: group: checks-${{ github.event_name == 'pull_request' && github.ref || github.run_id }} diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 027b0c4..b4ee243 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -25,7 +25,6 @@ permissions: jobs: plan: - if: ${{ vars.ORUN_CI == 'true' }} runs-on: ubuntu-latest outputs: lane-matrix: ${{ steps.matrix.outputs.lane-matrix }} @@ -33,10 +32,31 @@ jobs: - uses: actions/checkout@v6 with: fetch-depth: 0 - - uses: sourceplane/orun-action@v1.2.0 + # A TREE THAT NAMES NO WORKSPACE PLANS NOTHING. `ws_CHANGE_ME` is the + # placeholder this repository ships with until someone links it; every + # remote op of a plan here would be refused, so the job says so and + # stops green, and `run` below has no lanes to start. A product + # bootstrapped from it never carries the placeholder — the bootstrap + # writes the product's own workspace into intent.yaml — and one that had no + # workspace to write leaves `ws_SET_ME`, which is NOT skipped: it fails + # here loudly rather than deploying nothing in silence. + # + # This replaced an `ORUN_CI` repository variable, which a bootstrap has + # no way to set: every product it built would have converged on nothing. + - id: linked + run: | + if grep -Eq '^[[:space:]]*workspace:[[:space:]]*ws_CHANGE_ME[[:space:]]*$' intent.yaml; then + echo "::notice title=Orun CI::intent.yaml names no Orun workspace (ws_CHANGE_ME) — nothing to plan. Link this repository (orun cloud link) and set execution.state.workspace to turn the pipeline on." + echo "linked=false" >> "$GITHUB_OUTPUT" + else + echo "linked=true" >> "$GITHUB_OUTPUT" + fi + - if: steps.linked.outputs.linked == 'true' + uses: sourceplane/orun-action@v1.2.0 with: - version: v2.78.0 - - env: + version: v2.78.4 + - if: steps.linked.outputs.linked == 'true' + env: # Surface the best-effort catalog auto-sync (execution.state.autopushCatalog). # A successful push prints "✓ pushed catalog …"; ORUN_VERBOSE also makes # any skip/failure visible instead of silent. @@ -57,11 +77,13 @@ jobs: # without lanes gets one per job, exactly the old matrix, and # `orun run --lane ` on it is `--job `. - id: matrix + if: steps.linked.outputs.linked == 'true' run: | echo "lane-matrix=$(jq -c 'if ((.lanes // []) | length) > 0 then [.lanes[] | {"lane": .id, "name": .name}] else [.jobs[] | {"lane": .id, "name": .checkName}] end' plan.json)" >> "$GITHUB_OUTPUT" - - uses: actions/upload-artifact@v7 + - if: steps.linked.outputs.linked == 'true' + uses: actions/upload-artifact@v7 with: name: orun-plan path: plan.json @@ -124,7 +146,7 @@ jobs: password: ${{ secrets.GITHUB_TOKEN }} - uses: sourceplane/orun-action@v1.2.0 with: - version: v2.78.0 + version: v2.78.4 # exec-id is the RUN id alone (no attempt suffix): a `gh run rerun # --failed` then RESUMES the same orun execution — jobs that succeeded in # a prior attempt stay completed, so re-run lanes' cross-job dependencies @@ -173,8 +195,8 @@ jobs: $retry_flag env: # GITHUB_TOKEN is the only credential CI holds — GitHub-issued and - # ephemeral. Every provider credential (the Cloudflare token and - # account id — this baseline has no second provider) is an + # ephemeral. Every provider credential (the Cloudflare deploy token + # and the account id, the Supabase access token and the org id) is an # orun-managed secret: # brokered fresh per run from the workspace's integrations, resolved # lease-bound by the jobs that declare it (profile secretBindings or diff --git a/.github/workflows/tag.yml b/.github/workflows/tag.yml new file mode 100644 index 0000000..c0383e3 --- /dev/null +++ b/.github/workflows/tag.yml @@ -0,0 +1,97 @@ +name: Baseline tag + +# CUTS A `baseline-vN` TAG FOR THIS REPOSITORY. +# +# A baseline tag is what the platform's registry resolves and what every +# product bootstrapped from this repository is built out of, so it is cut by a +# workflow rather than by hand: the version must look like a baseline tag, an +# existing tag is never moved, and the commit is resolved here, once. +# +# Whether a commit is fit to release is decided outside this repository, by +# whoever cuts the tag; nothing here asks for proof beyond a green `main`. + +on: + workflow_dispatch: + inputs: + version: + description: "The tag to cut, e.g. baseline-v2." + required: true + type: string + ref: + description: "Branch, tag or sha to cut it from. Defaults to main." + required: false + default: main + type: string + +concurrency: + group: baseline-tag + cancel-in-progress: false + +permissions: + contents: read + +jobs: + cut: + runs-on: ubuntu-latest + permissions: + contents: write + steps: + - uses: actions/checkout@v6 + with: + # Full history: the ref being cut from may be any commit, and a + # shallow clone cannot resolve one it did not fetch. + fetch-depth: 0 + ref: ${{ inputs.ref }} + + - name: the version must look like a baseline tag + run: | + set -euo pipefail + # Refused here rather than by the API, because the API's error for a + # malformed ref says nothing about the convention it broke. + case "${{ inputs.version }}" in + baseline-v[0-9]*) ;; + *) echo "✕ '${{ inputs.version }}' is not a baseline-vN tag" >&2; exit 1 ;; + esac + + - name: resolve the commit + id: commit + run: | + set -euo pipefail + sha="$(git rev-parse HEAD)" + echo "sha=$sha" >> "$GITHUB_OUTPUT" + echo "Cutting ${{ inputs.version }} from ${{ inputs.ref }} = $sha" + + - name: the tag must not already exist + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + set -euo pipefail + code="$(curl -sS -o /dev/null -w '%{http_code}' \ + -H "Authorization: Bearer $GH_TOKEN" \ + -H "Accept: application/vnd.github+json" \ + "${GITHUB_API_URL}/repos/${GITHUB_REPOSITORY}/git/ref/tags/${{ inputs.version }}")" + if [ "$code" = "200" ]; then + echo "✕ ${{ inputs.version }} already exists. A baseline tag is never moved:" >&2 + echo " products resolve it, and repointing one changes what a build that" >&2 + echo " already shipped was made of. Cut the next number." >&2 + exit 1 + fi + # Anything other than 200 or 404 means the question was not answered, + # and "it probably does not exist" is not a thing to guess about a + # tag that is about to be created. + [ "$code" = "404" ] || { echo "✕ could not check for the tag (HTTP $code)" >&2; exit 1; } + + - name: cut the tag + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + set -euo pipefail + curl -sS -X POST --fail-with-body \ + -H "Authorization: Bearer $GH_TOKEN" \ + -H "Accept: application/vnd.github+json" \ + "${GITHUB_API_URL}/repos/${GITHUB_REPOSITORY}/git/refs" \ + -d "$(printf '{"ref":"refs/tags/%s","sha":"%s"}' \ + "${{ inputs.version }}" "${{ steps.commit.outputs.sha }}")" + echo "" + echo "✓ ${{ inputs.version }} → ${{ steps.commit.outputs.sha }}" + echo " Next: move the registry row in orun-cloud's infra/baselines-registry/baselines.yaml." diff --git a/.gitignore b/.gitignore index 2f07c7b..812fa30 100644 --- a/.gitignore +++ b/.gitignore @@ -11,6 +11,7 @@ coverage/ .env*.local .dev.vars .dev.vars.* +!.dev.vars.example *.log plan.json next-env.d.ts @@ -26,6 +27,3 @@ crash.log **/.orun/runs/ **/.orun/ -# Rendered wrangler configs for wiring-templated deployables (committed as -# wrangler.template.jsonc; rendered by tooling/wire at verify/deploy time). -apps/web/wrangler.jsonc \ No newline at end of file diff --git a/BOOTSTRAP.md b/BOOTSTRAP.md new file mode 100644 index 0000000..a8e8b2d --- /dev/null +++ b/BOOTSTRAP.md @@ -0,0 +1,227 @@ +# BOOTSTRAP — a new product from this baseline, in one landing + +How to go from **nothing** to **a Next.js + Supabase Auth app live on stage +and prod — its own Supabase project per environment, Auth pointed at the +app, sign-up open — documented**, with two provider consents. + +There is one artifact: **`repo-blueprint.yaml`**. It declares what to place, +in what order, what each phase needs first, and what to say while it runs. +`orun new` is the whole runtime — the phases below are its `--phase` names, +not separate workflows. The console card the platform renders is +**`blueprint.yaml`**; it names the build document and states the inputs, the +brokered secrets and the programme, and `testing/manifest.test.sh` holds it +to what the build document does. + +Target wall-clock: **about fifteen minutes** — an estimate summed from the +phases until a bootstrap measures it: one landing, then one convergence per +environment (stage and prod side by side until `02-docs` restores the +promotion gate) that creates the Supabase project (five to seven minutes), +sets its Auth, and builds and deploys the app, in that order. + +## 0. What you need + +- GitHub org access (repository creation) and a machine with `git`, `node` + (≥ 22), `pnpm` (10.12.1), `python3` with PyYAML, `curl`, and the `orun` + CLI **≥ v2.58.11** — the floor for RUNNING the bootstrap (the phase overlay, + landings that wait on the PR's whole CI run, `githubOwner` on the doctor + probe, `environments` on the secrets probe, `from: workspace`). The + product's own `ci.yml` pins its lanes separately (v2.78.4), and that pin is + what reads the per-edge `mode` rules the convergence order relies on. +- A **Cloudflare** account (the free plan is enough for one Worker with + static assets) and its Account API token with the permission groups the + console's Connect recipe lists — Workers Scripts among them. +- **A Supabase organization with room for two more projects** — + `-stage` and `-prod`. Supabase's free plan allows two + active projects per organization, so on the free plan that is the whole + allowance: pause or delete what else is there first, or use a paid + organization. It is connected to the workspace by OAuth consent (console → + Integrations → Supabase) — or by a pasted personal access token. The + connection is anchored on ONE organization, and that is where both + projects are created. +- An Orun Cloud workspace for the product — `orunWorkspace`, or the workspace + the build runs in (ORUN_WORKSPACE) when that is unset — with an + **admin-role API key** for headless runs (secret writes below admin are + masked as `not_found`). +- **The repository allow-listed in the workspace** (console → Settings → Git + repos), unless the credential can write links. `01-product`'s `link` step + stops and names the fix if it is not. +- **Not an SMTP server.** Each project is created with email confirmation + off, so sign-up works on the first deploy without one; the owner adds SMTP + and turns confirmation on later (§3). + +## 1. One command: `--resume` + +The whole bootstrap, unattended. `--resume` places every phase not already +derived as done, in order, honouring each phase's barrier: + +```bash +git clone --depth 1 --branch https://github.com/sourceplane/supabase-starter +cd supabase-starter + +orun new --blueprint repo-blueprint.yaml \ + --out ~/products/acme-notes --run-hooks --resume \ + --set reponame=acme-notes --set productname="Acme Notes" \ + --set productdomain=acme.dev --set githuborg=acme-inc \ + --set orunWorkspace=ws_XXXXXXXX \ + --set subdomain= +``` + +**`--run-hooks` is the difference between placing files and bootstrapping a +product.** Without it `orun new` writes the tree and stops: no repository, no +landing, no convergence watch, no probe. That is deliberate — it is what +makes the offline bootstrap in `testing/` possible with no workspace and no +provider. + +`--resume` is safe to re-run from anywhere, a fresh container with a fresh +`--out` included: **phase state is derived from the tree, never stored.** A +phase whose files are present but branded derives as `drifted`, and +`--resume` leaves it placed rather than reverting the product's identity. + +## 1b. Or phase by phase + +| phase | what it lands | verified by | +|---|---|---| +| `01-product` | the repository, created and linked; the four brokered credentials; then the whole product in one PR — intent, CI, tooling, identity, the Supabase Terraform root, the app and its tests | the convergence green (supabase → web, per environment), the four published secrets on stage and prod, `/` and `/api/health` answering on both workers.dev URLs | +| `02-docs` | `ai/context/deployment.md` from probed facts (how sign-up behaves included); prod's promotion gate and dev's push lanes restored | the final probe | + +```bash +orun new --blueprint repo-blueprint.yaml --out ~/products/acme-notes --run-hooks \ + --phase 01-product --values ~/acme-notes.values.yaml +# … then 02-docs +``` + +`02-docs` reads the identity back from `.rebrand/values.json` in the placed +tree, but the blueprint's **required** inputs — `reponame`, `productname`, +`productdomain`, `githuborg` — are validated before anything runs, so pass +them every time (a `--values` file is easier). The full guide, one page per +phase: [docs/phases/README.md](docs/phases/README.md). + +| flag | what it does | +|---|---| +| `--status` | derives and prints every phase's state and writes nothing. It parses the document, validates each hook against the action registry and compiles every template; it needs no credential and no network | +| `--phase ` | places exactly that phase; its `requires.phases` still gates | +| `--until ` | places every phase through that one and stops | + +What lands in the product is PRODUCT-ONLY: the app, the Terraform root, the +tests, its CI, its tooling, its README and its two context pages. None of +this repository's machinery (`.baseline/`, the blueprints, `tooling/rebrand`, +`tooling/bootstrap`, `hooks/`, `testing/`, `docs/phases/`, `specs/`, +`tasks/`, this file) ships, and no shipped file names any of it. That +promise is a test: `testing/leak.test.sh` derives what every phase would +place and gates the set and every file's text, and +`testing/placement.test.sh` gates the same rules over a placed, branded tree. + +## 2. Headless / container mode + +The blueprint's source is this repository (`sources: [{kind: dir, path: .}]`), +so the container contract is a shallow clone at a pinned tag plus two +tokens: + +```bash +export ORUN_TOKEN=… # orun auth, headless +export GITHUB_TOKEN=… # fine-grained PAT (below) + +git clone --depth 1 --branch https://github.com/sourceplane/supabase-starter +cd supabase-starter +orun new --blueprint repo-blueprint.yaml \ + --out /work/acme-notes --run-hooks --resume --progress json \ + --values /work/acme-notes.values.yaml +``` + +| requirement | detail | +|---|---| +| `GITHUB_TOKEN` | fine-grained PAT: **read** on this repository; on the PRODUCT's repository **contents write**, **pull-requests write**, **actions read+write** (`orun.run/watch@v1` resumes runs with `gh run rerun`), **checks read**; **repository create** on the owner if `01-product` creates it (or pre-create it — supported) | +| classic token caveat | a classic PAT or gh OAuth token also needs the `workflow` scope to push `.github/workflows/` | +| pinning | the clone's `--branch ` pins everything: the blueprint, its modules and its hooks' scripts all come from that one commit | + +## 3. After the product is live + +- **Sign-up works** on both environments: confirmation is off, so a new user + is signed in the moment they sign up. Password recovery sends email — + until a project has an SMTP server of its own, Supabase delivers only to + its organization's members, and the form says so for anyone else. +- **Email confirmation** (per environment, optional): give the project SMTP + of its own (Supabase dashboard → Authentication → Emails → SMTP Settings), + set `authEmailConfirmation: "true"` in the product's + `infra/terraform/supabase/component.yaml` and merge. The product's README, + "Email", is the owner's copy of this, including the confirmation template + that lands on the app's `/auth/confirm`. +- **Tables**: the protected page's tutorial creates `notes` with row-level + security on and per-user policies. Every table in `public` needs RLS — + the publishable key is public by design. +- **Custom domain**: attach it to the Worker in Cloudflare, then make it + prod's Auth Site URL in the product's supabase root (its README, "Custom + domain"). There is no domain phase: attaching a domain needs zone + permissions the brokered `workers-deploy` token does not carry. +- **Refresh the record**: re-run `--phase 02-docs`; it is idempotent, and it + records whether sign-up asks for confirmation. + +## 4. Testing this baseline + +`.github/workflows/baseline.yml` runs three tiers on every pull request, and +each runs locally the same way: + +```bash +for t in manifest phases coverage rebrand retouch bootstrap-defer; do bash testing/$t.test.sh; done +bash testing/leak.test.sh # needs orun +bash testing/placement.test.sh # needs orun, node, pnpm: the offline bootstrap and the product's own plans +bash testing/e2e.test.sh # + network for pnpm, psql and a PostgreSQL server install +``` + +The offline bootstrap (`testing/lib/bootstrap.sh`) places both phases in +order and finishes each with the blueprint's OWN `run:` hooks — read out of +`repo-blueprint.yaml`, not transcribed — so the retouch marker, the rebrand, +the re-tenant, the deferrals and their restore, the lockfile and the +deployment record all run exactly as a real bootstrap runs them. Only the +platform's typed actions (task, repo, reconcile, land, watch, secrets, +probe) and the `link` step are stood in for, a landing becoming a commit. + +What no test here can do is the clouds' half: create a Supabase project, read +its API keys, set its Auth, mint a token, deploy for real. The Terraform root +is held to `fmt`, `init -backend=false` and `validate` (a real `plan` reads +Supabase's API and the platform's state backend); the convergence ORDER is +proven on the product's own `orun plan`; and the app's Supabase is a local +stand-in — a Postgres with Supabase's roles and `auth` schema, and the Auth, +Data API and SQL-editor endpoints the app and its tutorial call +(`testing/lib/fake-supabase-api.py`) — against which the built Worker serves +a sign-up, a sign-in, the protected page and the email-confirmation route, +and the tutorial's table is checked closed to every other user. + +## 5. Cutting a baseline tag (maintainers) + +Every product built from this repository resolves a `baseline-vN` tag, so the +tag is cut by a workflow rather than by hand: + +```bash +gh workflow run tag.yml -f version=baseline-v1 # from main +gh workflow run tag.yml -f version=baseline-v1 -f ref= +``` + +It refuses a version that is not `baseline-v` and a tag that already +exists: a baseline tag is never moved. Then add (or move) the registry row in +orun-cloud's `infra/baselines-registry/baselines.yaml` by pull request — +after the tag exists, because the registry's sync fetches `blueprint.yaml` +at the tag and refuses the whole catalogue if it 404s. + +## Troubleshooting + +| Symptom | Cause → fix | +|---|---| +| `01-product` parks: `waiting for github for ` | the workspace's GitHub connection is to another account. Connect the App installation on `` (console → Integrations → GitHub), then `--resume` | +| `01-product` parks on the `providers` probe for cloudflare or supabase | that connection is missing. Connect it (console → Integrations); the probe is a wait, not a failure | +| `01-product` stops at `link` | the repository is not linked to the workspace and the credential cannot link it. Allow-list it (console → Settings → Git repos) and re-run the phase | +| Secret WRITE fails `not_found` while listings work | the API key's role is below admin; re-mint it with the admin role | +| supabase apply: project limit reached | the organization has no room for the two projects stage and prod need (the free plan allows two active projects per organization). Pause or delete one, or upgrade, then re-run `01-product` | +| supabase apply: `does not support oauth access` | a supabase provider ≥ 1.6 reads billing endpoints the brokered OAuth token cannot; the root pins `~> 1.5.1` — keep it | +| supabase apply: `Unable to read API keys` / `Unable to update auth settings` | the Supabase connection's grant does not cover the project's API keys or its Auth configuration (not yet exercised live with the platform's OAuth app). Reconnect Supabase with a personal access token and re-run `01-product`; the reconcile re-mints only what is missing | +| web: `wire: missing wiring documents … WIRING_SUPABASE_` | the supabase apply for that environment did not publish; its lane's log says why. web waits on it, enforced | +| web smoke: `/api/health` 503 | `auth: key refused` — the inlined key is not the project's; `auth: unreachable` — the project is paused or still coming up | +| `build-app` fails: `Symlink apps/web/node_modules/next is invalid, it points out of the filesystem root` | the product's intent pins stack-tectonic ≥ 0.20.0, whose lane-scoped install links each job's node_modules out of its tree, which Next 16's Turbopack refuses. Pin 0.19.0 (`intent.yaml` says why) | +| `verify-app-structure` fails: `test -f "wrangler.jsonc"` | the product's `apps/web/wrangler.jsonc` is not committed. It must be — the check runs before the build in a fresh checkout (`pnpm run wire:fixture` renders it) | +| Sign-up says the address cannot be mailed | confirmation was turned on without SMTP: Supabase's own email reaches only the organization's members. Add SMTP, or set `authEmailConfirmation` back to `"false"` | +| Convergence failed AFTER the PR merged; re-running lands nothing | expected on its own — the files are on main. Re-run the phase (`--phase 01-product`, `--redo 01-product`, or the console's Retry): its `retouch` hook gives the landing a diff and the components re-plan; the project is adopted, not recreated | +| The convergence reported green, then `verify` got 404 | a second workflow ran on the push to main and the watch took its run. Only `ci.yml` may run on a push to main; `checks.yml` runs on pull requests only | +| The product's `intent.yaml` says `workspace: ws_SET_ME` | `orunWorkspace` was empty and the build ran outside a workspace; set it and re-run `01-product` | +| A bootstrap stopped before `02-docs`; prod no longer waits on stage | the gate is deferred, not dropped: run `02-docs`, or `node tooling/bootstrap/promotion.mjs --restore --file /intent.yaml` | +| `✕ input "productdomain" is required` | all four required inputs must be set on every invocation, single-phase ones included | +| `unknown flag: --phase` or a parse error in the blueprint | the CLI is below the v2.58.11 floor | diff --git a/README.md b/README.md index 05be550..a7ddc92 100644 --- a/README.md +++ b/README.md @@ -7,67 +7,114 @@ page — running on **Cloudflare Workers + Static Assets** through [`@opennextjs/cloudflare`](https://opennext.js.org/cloudflare), with the Supabase project itself provisioned by Terraform through [Orun](https://github.com/sourceplane/orun), the way the -[Lumen baseline](https://github.com/sourceplane/lumen) does it. +[Lumen baseline](https://github.com/sourceplane/lumen) does it — and +packaged as an **Orun baseline**: one command takes a new product from +nothing to live on stage and prod, in its own repository, under its own +name, in ONE landing. -The template's code is the code. What the port adds is the Workers build, -the monorepo wrapper, a test package for the session proxy, the Supabase -Terraform root, and the deploy contract that threads the project's URL and -publishable key into the build and the Worker per environment. See -[`specs/epics/supabase-starter`](specs/epics/supabase-starter/README.md) -for the design, the milestones and the as-built status. +The template's code is the code. What the port changes is what the Workers +runtime and a fresh, unattended deployment force: the build inlines the +project's URL and publishable key from the same wrangler config the Worker +runs with (`next.config.ts`), each project is created with its Auth pointed at +the Worker and email confirmation off (so anyone can sign up on the first +deploy, with no SMTP server), the auth forms explain what a fresh project +refuses instead of echoing it, and the tutorial's table gets row-level +security keyed on `auth.uid()`. What the baseline adds is everything needed to +make a copy of it somebody else's — built the way +[cirrus-baseline](https://github.com/sourceplane/cirrus-baseline) builds a +product, in one landing. See [`specs/epics/supabase-starter`](specs/epics/supabase-starter/README.md) +for the design, the milestones and the as-built status, including every +departure. -## What is here +## Instantiating a product + +```bash +git clone --depth 1 --branch https://github.com/sourceplane/supabase-starter +cd supabase-starter +orun new --blueprint repo-blueprint.yaml --out ~/products/acme-notes --run-hooks --resume \ + --set reponame=acme-notes --set productname="Acme Notes" --set productdomain=acme.dev \ + --set githuborg=acme-inc --set subdomain= +``` + +Or, once the platform's registry lists it, from the Orun console (Baselines → +`supabase-starter` → Build). Two phases: **`01-product`** creates the +repository, mints the four brokered credentials (Cloudflare and Supabase) and +lands the whole product as one pull request, whose convergence on `main` +provisions and deploys it per environment in a fixed order — + +``` +supabase ──▶ web +``` + +— the edge `mode: enforced` on a push to main and advisory on a pull +request; then **`02-docs`** records the live deployment from probed facts. +**[BOOTSTRAP.md](BOOTSTRAP.md)** is the operator guide; +[docs/phases/](docs/phases/README.md) has a page per phase. The Supabase +organization needs room for **two** projects (stage and prod) — the free +plan's limit. + +The new repository receives the **product only** — the app, the Terraform +root, the tests, its CI, its tooling, a README of its own and its operating +contract — renamed throughout to the product's name, repository, Worker and +Supabase projects. None of this repository's machinery ships. + +| What makes it a baseline | Where | +|---|---| +| The console card (inputs, secrets, programme) | `blueprint.yaml` | +| The build document (modules, phases, hooks) | `repo-blueprint.yaml` | +| This tree's identity, the product's README and the bootstrap's task contracts | `.baseline/` | +| The rename engine (product-name seam: `apps/web/lib/site.ts`) | `tooling/rebrand/rebrand.mjs` | +| The bootstrap's helpers (deferrals, redeploy marker, work-tree strip) | `tooling/bootstrap/` | +| The deployment-record renderer | `hooks/render-deployment-docs.sh` | +| The product's context pack | `ai/context/` | +| The baseline's tests: contract, leak, offline bootstrap and plans, end to end | `testing/`, `.github/workflows/baseline.yml` | +| Cutting a `baseline-vN` tag | `.github/workflows/tag.yml` | + +## What is here (the product) | Surface | Where | |---|---| -| Home (tutorial), auth pages, `/protected` | `apps/web/app` | -| Supabase clients (browser, server) and the session proxy | `apps/web/lib/supabase`, `apps/web/proxy.ts` | -| Workers build and deploy contract | `apps/web/next.config.ts`, `apps/web/open-next.config.ts`, `apps/web/wrangler.template.jsonc`, `apps/web/component.yaml` | -| The Supabase project (stage, prod) | `infra/terraform/supabase` | +| The product's name | `apps/web/lib/site.ts` | +| Home (tutorial), auth pages, `/protected`, `/api/health` | `apps/web/app` | +| Supabase clients (browser, server), the session proxy, the auth forms' error wording | `apps/web/lib/supabase`, `apps/web/proxy.ts` | +| Workers build and deploy contract | `apps/web/next.config.ts`, `open-next.config.ts`, `wrangler.template.jsonc` → `wrangler.jsonc` (committed), `component.yaml` | +| The Supabase project (stage, prod), its Auth settings | `infra/terraform/supabase` | | Tests | `tests/web` (vitest) | ## Getting started ```bash pnpm install -pnpm run wire:fixture # render apps/web/wrangler.jsonc from the offline fixture +pnpm run wire:fixture # re-render apps/web/wrangler.jsonc from its template (committed; this changes nothing) pnpm typecheck pnpm lint pnpm test pnpm build # next build + opennextjs-cloudflare build → apps/web/.open-next ``` -To run against a Supabase project, put its URL and publishable key in -`apps/web/.env.local` (see `apps/web/.env.example`), then: - -```bash -pnpm --filter @app/web dev # http://localhost:3000, Next's dev server -pnpm --filter @app/web preview # wrangler dev over the built Worker; set the same two values in apps/web/.dev.vars -``` +The build needs no Supabase project. Running it against one — `.env.local` +for `next dev` and the build, `.dev.vars` for `wrangler dev` — is in the +product's README (`.baseline/product/README.md`), which is what a product +built from here carries. ## How it maps to Vercel | Vercel | Here | |---|---| | Next.js hosting, `proxy.ts` on the edge | One Cloudflare Worker (`.open-next/worker.js`) + Static Assets; the proxy runs in the Worker | -| Project env vars in the dashboard | Build time: `NEXT_PUBLIC_SUPABASE_URL` / `NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY` from orun secrets (inlined by `next build`). Run time: the same values as wrangler `vars`, rendered per environment from the Supabase root's wiring document | -| A Supabase project created by hand | `infra/terraform/supabase`: one project per environment, URL and API keys published as orun secrets | -| Deploy on push | Orun deploys `supabase-starter-web-{stage,prod}` on merge to `main` (`apps/web/component.yaml`) | +| Project env vars in the dashboard | `NEXT_PUBLIC_SUPABASE_URL` / `_PUBLISHABLE_KEY` are wrangler vars rendered per environment from the supabase root's `WIRING_SUPABASE`; `next build` inlines the same two from that config (`next.config.ts`) | +| A Supabase project created by hand, its redirect URLs set in the dashboard | `infra/terraform/supabase`: one project per environment, its Auth Site URL and redirect allow-list set to the Worker, its URL and keys published as orun secrets | +| Email confirmation through Supabase's built-in email | Off until the project has SMTP of its own (`authEmailConfirmation`), because the built-in email reaches only the organization's members | +| "Deploy with Vercel" (clone the template) | `orun new --blueprint repo-blueprint.yaml` — a new repository, branded, provisioned, deployed | The publishable (anon) key is a wrangler var, not a secret: it is shipped to every browser by design, and Row Level Security is the boundary. -## Deploying - -`.github/workflows/checks.yml` runs install, wire, typecheck, lint, test and -build on every push and pull request. `ci.yml` is the Orun pipeline: set -`execution.state.workspace` in `intent.yaml` to this product's workspace -(`orun cloud link`), connect Cloudflare **and Supabase** to that workspace, -and set the `ORUN_CI` repository variable to `true`. A merge to `main` then -applies the Supabase root, builds the app with that environment's URL and -key, and deploys the Worker to `stage`, then `prod`. +## CI -After the first apply, set the project's auth **Site URL** and redirect -allow-list (Supabase dashboard → Authentication → URL Configuration) to the -deployed Worker's origin, e.g. `https://supabase-starter-web-prod..workers.dev`, -so confirmation and recovery emails link back to the app. +| Workflow | What it runs | Ships to a product | +|---|---|---| +| `checks.yml` | install, wire fixture, typecheck, lint, test, build — every PR (not pushes: on main, `ci.yml` must be the only run a commit has, because the bootstrap's convergence watch takes the newest one) | yes | +| `ci.yml` | the Orun pipeline: `orun plan --changed`, then one job per lane; applies and deploys stage → prod on merge. It plans nothing while `intent.yaml` names the placeholder workspace `ws_CHANGE_ME`, as this repository does | yes | +| `baseline.yml` | the baseline's own tiers: contract tests; the blueprint read by the pinned orun, the leak gate, the offline bootstrap and the product's own plans; the product built in the job tree orun stages, dry-deployed, and served against a local Supabase stand-in — a sign-up, a sign-in, the protected page, the confirm route, the tutorial's table under RLS | no | +| `tag.yml` | cuts a `baseline-vN` tag (manual) | no | diff --git a/ai/context/deployment.md b/ai/context/deployment.md new file mode 100644 index 0000000..d03f612 --- /dev/null +++ b/ai/context/deployment.md @@ -0,0 +1,7 @@ +# supabase-starter — live deployment manifest + +> Not rendered yet. The bootstrap's `02-docs` phase probes every live URL and +> regenerates this file from what answered — the workspace, the URLs and +> their status, how sign-up behaves on each environment's Supabase project, +> and the secrets inventory by name. Until then, nothing here claims the +> product is live. The operating contract is [operations.md](operations.md). diff --git a/ai/context/operations.md b/ai/context/operations.md new file mode 100644 index 0000000..98cd98b --- /dev/null +++ b/ai/context/operations.md @@ -0,0 +1,169 @@ +# supabase-starter — operating contract (for humans and agents) + +This is the standing guide to how this product is deployed and operated. +Instance facts (live URLs, workspace, how sign-up behaves on each +environment, the secrets inventory) live in [deployment.md](deployment.md), +rendered from probed reality by the bootstrap's `02-docs` phase; this file is +the contract that stays true between deployments. It is written to give an +agent with repository read access enough context to reason about and operate +the product without any other source. + +## What this system is + +Vercel's Next.js and Supabase Starter — email and password sign-up, sign-in +and password reset through Supabase Auth, the session in cookies refreshed by +a proxy, a protected page — on Cloudflare Workers, its Auth (and its +Postgres) a Supabase project per environment, expressed as an Orun +component-native desired-state repo. Three components: + +- **`infra/terraform/supabase`** (`supabase`) — one Supabase project per + environment, its Auth's Site URL and redirect allow-list pointed at the + app's Worker, and sign-up confirming at once unless `authEmailConfirmation` + is on (below). Its apply publishes `WIRING_SUPABASE` (the project URL and + publishable key) and `SUPABASE_PROJECT_REF`, `SUPABASE_DB_PASSWORD`, + `SUPABASE_DB_URL` onto the environment's secret rung. +- **`apps/web`** (`web`) — the app: Next.js built by `@opennextjs/cloudflare` + into one Worker plus Static Assets. It talks to Supabase over HTTPS with + supabase-js (`@supabase/ssr`): the browser directly, the Worker on the + server — never a Postgres connection. +- **`tests/web`** — the vitest suite, verified on the `dev` rung. + +Environments: **`stage`** and **`prod`** are deployed; **`dev` is +verify-only by design** — lanes build and test, nothing deploys. + +## Identity and tenancy + +Every remote operation runs against ONE Orun workspace, declared in +`intent.yaml` under `execution.state.workspace` — committed, enforced, and +what CI uses. Do not remove it; headless credentials depend on it. If it +reads `ws_SET_ME`, the bootstrap had no workspace to write: set the real one +before anything else. + +## How deployment works + +1. Merge (or push) to `main`. +2. CI (`.github/workflows/ci.yml`) runs `orun plan --changed` — only + components whose files changed are planned — then runs each planned lane + with `orun run --remote-state`, authenticated by GitHub OIDC (the + exchange resolves this repository's linked workspace server-side). +3. Per environment, in this order — the edge `mode: enforced` on a push to + main, advisory on a pull request (which deploys nothing): + **`supabase` → `web`.** A job resolves its secrets when it starts, so the + app's deploy reads the `WIRING_SUPABASE` the apply before it published. + It re-renders `apps/web/wrangler.jsonc` from that document, builds — + `next build` inlines the same URL and key into the browser bundle + (`next.config.ts`) — deploys `supabase-starter-web-`, and smoke-tests + it: the home page, and `/api/health`, which answers 200 only when the + project's Auth answers the key the build inlined. +4. `prod` deploys after `stage` has converged on the same commit + (`environments.prod.promotion` in intent.yaml). +5. **The convergence run is the deployment.** A green run means every + planned lane applied. Failed lanes are retried with + `gh run rerun --failed`, which resumes the same execution. + +Caveats that matter: + +- A push that touches no component files plans zero lanes — that run is + green and deployed nothing. Never treat "latest run green" as "product + converged"; probe the URLs instead. +- `apps/web/wrangler.jsonc` is committed as the render of + `wrangler.template.jsonc` from `wiring.fixture.json` (a placeholder + project): edit the template and run `pnpm run wire:fixture`. The deploy + lanes render the real one in their own job tree; never commit a real + project's URL or key. +- Supabase Auth sends its links (password recovery, and confirmation when it + is on) to the Worker's workers.dev origin — the supabase root sets it from + its `workersDevSubdomain` parameter, and owns it: an edit in the dashboard + is undone by the next apply. On a custom domain, change it there (below). + +## Auth and email + +A Supabase project without an SMTP server of its own delivers email only to +the members of its organization, a few messages an hour. So the supabase +root turns email confirmation OFF (`authEmailConfirmation: "false"` in its +component.yaml): sign-up signs a new user straight in, and works for anyone +on the first deploy. Password recovery still sends an email; until the +project has SMTP, the form says the address cannot be mailed yet (Supabase's +`email_address_not_authorized`) instead of failing. + +To require confirmation: + +1. Give each project SMTP of its own (Supabase dashboard → Authentication → + Emails → SMTP Settings). +2. Optionally point the confirmation email at the app's own route, as the + template's authors recommend — template body + `{{ .SiteURL }}/auth/confirm?token_hash={{ .TokenHash }}&type=email&next=/protected`. +3. Set `authEmailConfirmation: "true"` in `infra/terraform/supabase/component.yaml` + and merge. The apply turns confirmation on; `/api/health` and the + deployment record then say `emailConfirmation: required`. + +The terraform manages only `site_url`, `uri_allow_list` and +`mailer_autoconfirm`; every other Auth setting is the project's own. + +## Data and row-level security + +The app ships no tables: its users live in Supabase's `auth` schema, which +the Data API does not expose. The protected page's tutorial creates a +`notes` table with row-level security ON in the same statement, and policies +that let each signed-in user read and add only their own rows +(`auth.uid() = user_id`). Keep that rule for every table you add to +`public`: the publishable key is public by design, so a table without RLS is +readable by anyone who loads the site. Check with: + +```sql +select relname from pg_class c join pg_namespace n on n.oid = c.relnamespace + where n.nspname = 'public' and c.relkind in ('r','p') and not c.relrowsecurity; +``` + +## Secrets model + +- **Brokered provider secrets**, minted per run from the workspace's + connections — no long-lived values at rest, nothing to rotate by hand: + `CLOUDFLARE_API_TOKEN` (Workers deploy), `CLOUDFLARE_ACCOUNT_ID`, + `SUPABASE_ACCESS_TOKEN` (project create, API keys, Auth settings) and + `SUPABASE_ORG_ID`. +- **Published by the apply** onto the stage and prod rungs: + `WIRING_SUPABASE` (URL and publishable key — what the app reads), + `SUPABASE_PROJECT_REF`, `SUPABASE_DB_PASSWORD`, `SUPABASE_DB_URL` (the + database, for you and for any migration step you add). The service-role + key is never published. +- **No Worker secrets.** The publishable key is a wrangler var: it ships to + every browser by design, and row-level security is the boundary. +- Inspect by NAME only: `orun secrets list --org --project` and + `--env stage|prod`. No tooling in this repository prints a secret value, + and no document in `ai/context/` may contain one. + +## Verifying the system + +```bash +# the app and its Supabase Auth path on each environment (also recorded, probed, in deployment.md) +curl -s -o /dev/null -w '%{http_code}\n' https://supabase-starter-web-stage.your-workers-subdomain.workers.dev/ +curl -s https://supabase-starter-web-prod.your-workers-subdomain.workers.dev/api/health + +# workspace readiness (integrations + repository link) +orun integrations list --org --json && orun cloud check --org +``` + +## Common operations + +| task | how | +|---|---| +| deploy a change | merge to `main`; watch the run; failed lanes → `gh run rerun --failed` | +| require email confirmation | SMTP first, then `authEmailConfirmation: "true"` (above) | +| add a table | create it with `enable row level security` and `auth.uid()` policies (above); the day the product has migrations, Lumen's `packages/db` + `db-migrate` is the shape, reading `SUPABASE_DB_URL` | +| redeploy without a change | edit the last line of the component's `component.yaml` (`# orun: redeploy `) and merge — it is a deploy trigger, nothing reads it | +| serve a custom domain | attach it to the Worker in Cloudflare, then make it prod's `app_origin` in `infra/terraform/supabase/terraform/main.tf` and merge — the apply owns Auth's Site URL and redirect allow-list, so a dashboard edit would be undone | +| headless credentials | `ORUN_TOKEN` (workspace-scoped) + `GITHUB_TOKEN` | + +The deployment record is the bootstrap's `02-docs` phase. Re-running it (the +Orun console's Retry on that phase, or `orun new … --phase 02-docs`) +re-probes the URLs and re-renders [deployment.md](deployment.md); it is +idempotent. + +## Evolution + +Structural changes (a second Worker, a queue, migrations) follow the same +contract that deployed the product: add a component under `apps/`, `infra/` +or `packages/` with a `component.yaml` — declaring `dependsOn` on any +infrastructure whose published secrets it reads, enforced on main — land it +as a pull request, and the convergence run applies it. diff --git a/apps/web/.dev.vars.example b/apps/web/.dev.vars.example new file mode 100644 index 0000000..70d0309 --- /dev/null +++ b/apps/web/.dev.vars.example @@ -0,0 +1,15 @@ +# Local overrides for `wrangler dev` / `opennextjs-cloudflare preview`. +# Copy to .dev.vars (git-ignored). Optional: without it the Worker uses the +# committed wrangler.jsonc's vars, the offline fixture — a project that does +# not exist, so sign-in says the service did not answer. +# +# Your Supabase project (dashboard → Project Settings → API). The deployed +# Worker gets these as wrangler vars, rendered per environment from the +# supabase root's wiring document; they are not secrets — the publishable key +# ships to every browser, and Row Level Security protects the data. +# +# NOTE: `next build` inlines the browser's copy of these from apps/web/.env.local +# (or, without one, from wrangler.jsonc), not from this file — set both, to the +# same project, before `pnpm build`. +# NEXT_PUBLIC_SUPABASE_URL=https://.supabase.co +# NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY=sb_publishable_… diff --git a/apps/web/.env.example b/apps/web/.env.example index 7c386ba..9e58804 100644 --- a/apps/web/.env.example +++ b/apps/web/.env.example @@ -1,5 +1,8 @@ -# Local development (`pnpm --filter @app/web dev`). Values from your Supabase -# project's settings > API. Copy to .env.local (git-ignored). The Worker gets +# Local development (`pnpm --filter @app/web dev`, and `pnpm build`, which +# inlines these into the browser bundle). Values from your Supabase project's +# settings > API. Copy to .env.local (git-ignored). Without it, `next dev` +# shows the template's "connect Supabase" steps and `pnpm build` uses the +# committed wrangler.jsonc's (offline fixture) values. The deployed Worker gets # the same two values as wrangler vars, rendered from the wiring document. NEXT_PUBLIC_SUPABASE_URL=your-project-url NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY=your-publishable-or-anon-key diff --git a/apps/web/README.md b/apps/web/README.md index d417bff..4083bbe 100644 --- a/apps/web/README.md +++ b/apps/web/README.md @@ -1,109 +1,32 @@ - - Next.js and Supabase Starter Kit - the fastest way to build apps with Next.js and Supabase -

Next.js and Supabase Starter Kit

-
- -

- The fastest way to build apps with Next.js and Supabase -

- -

- Features · - Demo · - Deploy to Vercel · - Clone and run locally · - Feedback and issues - More Examples -

-
- -## Features - -- Works across the entire [Next.js](https://nextjs.org) stack - - App Router - - Pages Router - - Proxy - - Client - - Server - - It just works! -- supabase-ssr. A package to configure Supabase Auth to use cookies -- Password-based authentication block installed via the [Supabase UI Library](https://supabase.com/ui/docs/nextjs/password-based-auth) -- Styling with [Tailwind CSS](https://tailwindcss.com) -- Components with [shadcn/ui](https://ui.shadcn.com/) -- Optional deployment with [Supabase Vercel Integration and Vercel deploy](#deploy-your-own) - - Environment variables automatically assigned to Vercel project - -## Demo - -You can view a fully working demo at [demo-nextjs-with-supabase.vercel.app](https://demo-nextjs-with-supabase.vercel.app/). - -## Deploy to Vercel - -Vercel deployment will guide you through creating a Supabase account and project. - -After installation of the Supabase integration, all relevant environment variables will be assigned to the project so the deployment is fully functioning. - -[![Deploy with Vercel](https://vercel.com/button)](https://vercel.com/new/clone?repository-url=https%3A%2F%2Fgithub.com%2Fvercel%2Fnext.js%2Ftree%2Fcanary%2Fexamples%2Fwith-supabase&project-name=nextjs-with-supabase&repository-name=nextjs-with-supabase&demo-title=nextjs-with-supabase&demo-description=This+starter+configures+Supabase+Auth+to+use+cookies%2C+making+the+user%27s+session+available+throughout+the+entire+Next.js+app+-+Client+Components%2C+Server+Components%2C+Route+Handlers%2C+Server+Actions+and+Middleware.&demo-url=https%3A%2F%2Fdemo-nextjs-with-supabase.vercel.app%2F&external-id=https%3A%2F%2Fgithub.com%2Fvercel%2Fnext.js%2Ftree%2Fcanary%2Fexamples%2Fwith-supabase&demo-image=https%3A%2F%2Fdemo-nextjs-with-supabase.vercel.app%2Fopengraph-image.png) - -The above will also clone the Starter kit to your GitHub, you can clone that locally and develop locally. - -If you wish to just develop locally and not deploy to Vercel, [follow the steps below](#clone-and-run-locally). - -## Clone and run locally - -1. You'll first need a Supabase project which can be made [via the Supabase dashboard](https://database.new) - -2. Create a Next.js app using the Supabase Starter template npx command - - ```bash - npx create-next-app --example with-supabase with-supabase-app - ``` - - ```bash - yarn create next-app --example with-supabase with-supabase-app - ``` - - ```bash - pnpm create next-app --example with-supabase with-supabase-app - ``` - -3. Use `cd` to change into the app's directory - - ```bash - cd with-supabase-app - ``` - -4. Rename `.env.example` to `.env.local` and update the following: - - ```env - NEXT_PUBLIC_SUPABASE_URL=[INSERT SUPABASE PROJECT URL] - NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY=[INSERT SUPABASE PROJECT API PUBLISHABLE OR ANON KEY] - ``` - > [!NOTE] - > This example uses `NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY`, which refers to Supabase's new **publishable** key format. - > Both legacy **anon** keys and new **publishable** keys can be used with this variable name during the transition period. Supabase's dashboard may show `NEXT_PUBLIC_SUPABASE_ANON_KEY`; its value can be used in this example. - > See the [full announcement](https://github.com/orgs/supabase/discussions/29260) for more information. - - Both `NEXT_PUBLIC_SUPABASE_URL` and `NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY` can be found in [your Supabase project's API settings](https://supabase.com/dashboard/project/_?showConnect=true) - -5. You can now run the Next.js local development server: - - ```bash - npm run dev - ``` - - The starter kit should now be running on [localhost:3000](http://localhost:3000/). - -6. This template comes with the default shadcn/ui style initialized. If you instead want other ui.shadcn styles, delete `components.json` and [re-install shadcn/ui](https://ui.shadcn.com/docs/installation/next) - -> Check out [the docs for Local Development](https://supabase.com/docs/guides/getting-started/local-development) to also run Supabase locally. - -## Feedback and issues - -Please file feedback and issues over on the [Supabase GitHub org](https://github.com/supabase/supabase/issues/new/choose). - -## More Supabase examples - -- [Next.js Subscription Payments Starter](https://github.com/vercel/nextjs-subscription-payments) -- [Cookie-based Auth and the Next.js 13 App Router (free course)](https://youtube.com/playlist?list=PL5S4mPUpp4OtMhpnp93EFSo42iQ40XjbF) -- [Supabase Auth and the Next.js App Router](https://github.com/supabase/supabase/tree/master/examples/auth/nextjs) +# apps/web — the app + +Vercel's [Next.js and Supabase Starter](https://github.com/vercel/next.js/tree/canary/examples/with-supabase) +(MIT), running on Cloudflare Workers + Static Assets: + +- Supabase Auth with the session in cookies (`@supabase/ssr`), usable from + Server Components, Client Components, Route Handlers and the proxy +- Sign-up, login, forgot and update password (`/auth/*`), an email-confirm + route handler (`/auth/confirm`) and a protected page (`/protected`) that + prints the signed-in user's claims +- A proxy (`proxy.ts`) that refreshes the session on every request and sends + a signed-out visitor of anything but `/` and `/auth/*` to the login page +- A tutorial: sign up a first user, then create a table — with row-level + security keyed on `auth.uid()` — and query it from Next.js +- `/api/health`, which answers 200 only when the Supabase project the build + names answers its key, and says how sign-up behaves there +- Tailwind CSS and shadcn/ui + +The product's name is `lib/site.ts`. The project's URL and publishable key +reach the browser bundle and the Worker from one place, `wrangler.jsonc`'s +vars (`next.config.ts`); what the auth forms say when Supabase refuses is +`lib/supabase/errors.ts`. + +```bash +pnpm dev # next dev on http://localhost:3000 (reads .env.local) +pnpm build # next build + opennextjs-cloudflare build → .open-next/ +pnpm preview # wrangler dev over the built Worker (reads .dev.vars) +``` + +How it runs locally, how it deploys — per environment, after its Supabase +project, on merge to `main` — and how to turn email confirmation on are the +repository's README and `component.yaml` beside this file. diff --git a/apps/web/app/api/health/route.ts b/apps/web/app/api/health/route.ts new file mode 100644 index 0000000..8e92cbc --- /dev/null +++ b/apps/web/app/api/health/route.ts @@ -0,0 +1,58 @@ +import { connection } from "next/server"; + +// Not upstream's: the deploy's smoke check and the bootstrap's probe read +// this. A home page that renders proves the Worker deployed; this proves what +// the home page never touches — the Supabase URL and publishable key this +// Worker was built with name a real project, and its Auth answers them. It +// also says how sign-up behaves there: open or closed, and whether a new user +// must confirm an email address first (the project's own Auth settings). +// +// Supabase's /auth/v1/settings is what supabase-js reads too: public data, +// answered only for a valid API key. +type Health = { + ok: boolean; + auth: string; + signup?: "open" | "closed"; + emailConfirmation?: "required" | "off"; +}; + +function answer(body: Health) { + return Response.json(body, { + status: body.ok ? 200 : 503, + headers: { "cache-control": "no-store" }, + }); +} + +export async function GET() { + await connection(); + const url = process.env.NEXT_PUBLIC_SUPABASE_URL; + const key = process.env.NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY; + if (!url || !key) { + return answer({ ok: false, auth: "not configured" }); + } + try { + const res = await fetch(`${url}/auth/v1/settings`, { + headers: { apikey: key }, + signal: AbortSignal.timeout(10_000), + }); + if (!res.ok) { + return answer({ + ok: false, + auth: res.status === 401 ? "key refused" : `answered ${res.status}`, + }); + } + const settings = (await res.json()) as { + disable_signup?: boolean; + mailer_autoconfirm?: boolean; + }; + return answer({ + ok: true, + auth: "reachable", + signup: settings.disable_signup ? "closed" : "open", + emailConfirmation: settings.mailer_autoconfirm ? "off" : "required", + }); + } catch (error) { + console.error("health: Supabase Auth did not answer", error); + return answer({ ok: false, auth: "unreachable" }); + } +} diff --git a/apps/web/app/layout.tsx b/apps/web/app/layout.tsx index 4d3424a..859a3d3 100644 --- a/apps/web/app/layout.tsx +++ b/apps/web/app/layout.tsx @@ -2,6 +2,7 @@ import type { Metadata } from "next"; import { Geist } from "next/font/google"; import { ThemeProvider } from "next-themes"; import "./globals.css"; +import { SITE_NAME } from "@/lib/site"; const defaultUrl = process.env.VERCEL_URL ? `https://${process.env.VERCEL_URL}` @@ -9,7 +10,7 @@ const defaultUrl = process.env.VERCEL_URL export const metadata: Metadata = { metadataBase: new URL(defaultUrl), - title: "Next.js and Supabase Starter Kit", + title: SITE_NAME, description: "The fastest way to build apps with Next.js and Supabase", }; diff --git a/apps/web/app/page.tsx b/apps/web/app/page.tsx index ac33981..53f5711 100644 --- a/apps/web/app/page.tsx +++ b/apps/web/app/page.tsx @@ -6,6 +6,7 @@ import { ThemeSwitcher } from "@/components/theme-switcher"; import { ConnectSupabaseSteps } from "@/components/tutorial/connect-supabase-steps"; import { SignUpUserSteps } from "@/components/tutorial/sign-up-user-steps"; import { hasEnvVars } from "@/lib/utils"; +import { SITE_NAME } from "@/lib/site"; import Link from "next/link"; import { Suspense } from "react"; @@ -16,7 +17,7 @@ export default function Home() {