diff --git a/.baseline/identity.json b/.baseline/identity.json new file mode 100644 index 0000000..c723108 --- /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": "saas-starter", + "pascal": "SaasStarter", + "productName": "ACME", + "domain": "saas-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..58b834f --- /dev/null +++ b/.baseline/product/README.md @@ -0,0 +1,174 @@ +# saas-starter + +Vercel's [Next.js SaaS Starter](https://github.com/nextjs/saas-starter) — +Postgres through Drizzle, Stripe Checkout, Customer Portal and webhooks, +email/password auth with a JWT cookie, a session-refreshing proxy, teams with +roles, invitations and an activity log — on **Cloudflare Workers + Static +Assets** through [`@opennextjs/cloudflare`](https://opennext.js.org/cloudflare), +with its Postgres a **Supabase** project's database reached through +**Cloudflare Hyperdrive**. Terraform provisions both per environment and +Orun's `db-migrate` applies the schema, all on every merge to `main`. + +## Live deployment + + +Not recorded yet. The bootstrap's last phase writes the live URLs, the +workspace, whether Stripe is connected 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` | +| Marketing page, pricing, sign-in / sign-up, the dashboard, the Stripe routes | `apps/web/app` | +| Drizzle schema, queries, the per-request client, the seed | `apps/web/lib/db` (`drizzle.ts` is `getDb()`) | +| Session (jose + bcrypt) and its key, action validation, the proxy | `apps/web/lib/auth`, `apps/web/proxy.ts` | +| Stripe client, checkout, portal, subscription sync | `apps/web/lib/payments` | +| The database check the deploy smoke-tests | `apps/web/app/api/health/route.ts` | +| Workers build and deploy contract | `apps/web/next.config.ts`, `open-next.config.ts`, `wrangler.template.jsonc` → `wrangler.jsonc`, `component.yaml` | +| The schema as migrations, and their runner | `packages/db` (`@saas/db`) | +| The Supabase project, the Hyperdrive config, the migration step | `infra/terraform/supabase`, `infra/terraform/cloudflare-hyperdrive`, `infra/db-migrate` | +| Tests | `tests/web`, `tests/db` (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 database and no Stripe account: nothing pre-renders +against either. + +## Running it locally + +You need a Postgres on `localhost:54322` — the Supabase CLI's default +(`supabase start`), or the Docker container `pnpm db:setup` offers — or any +Postgres whose URL you put in `POSTGRES_URL`. + +1. **Environment.** Copy `apps/web/.env.example` to `apps/web/.env` and fill + it in, or let the setup wizard do it (it can also create the Docker + Postgres and a Stripe CLI webhook secret): + + ```bash + pnpm --filter @app/web db:setup + ``` + + `.env` is read by `next dev`, the seed and drizzle-kit. The Worker never + reads it: its database is the `HYPERDRIVE` binding and its secrets are + `.dev.vars` (below). + +2. **Schema.** drizzle-kit applies the migrations locally + (`pnpm db:generate` after a schema change, `pnpm db:studio` to browse): + + ```bash + pnpm --filter @app/web db:migrate + ``` + + The same SQL lives in `packages/db/src/migrations`, which is what CI + applies to the real databases. + +3. **Seed.** Creates the test user and team and, if `STRIPE_SECRET_KEY` is + set, the two Stripe products (test mode): + + ```bash + pnpm --filter @app/web db:seed # user test@test.com / admin123 + ``` + +4. **Run.** Either Next's dev server, which gets the Worker's bindings + through `getCloudflareContext()` (the `HYPERDRIVE` binding points at + `localhost:54322` through `wrangler.jsonc`'s `localConnectionString`): + + ```bash + pnpm --filter @app/web dev # http://localhost:3000 + ``` + + or the built Worker under `wrangler dev`, which reads + `apps/web/.dev.vars` (copy `.dev.vars.example`; every key is optional): + + ```bash + pnpm build + pnpm --filter @app/web preview # http://localhost:8787 + ``` + +5. **Stripe.** `stripe login`, then forward webhooks to the server you are + running — + + ```bash + stripe listen --forward-to localhost:3000/api/stripe/webhook + ``` + + — and test checkout with card `4242 4242 4242 4242`, any future date, any + CVC. Without a Stripe key everything else runs, and the pricing page says + checkout is not connected. + +## 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 Hyperdrive config over its +database, then the migrations, then the Worker** — because each reads what +the one before it published: the project's ref and password, the Hyperdrive +id the Worker binds, the schema the app queries. `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 Worker reaches a migrated database. + +The pipeline holds one credential, GitHub's own `GITHUB_TOKEN`. The +Cloudflare tokens and account id and the Supabase access token and org id +are brokered per run from the workspace's connections; the Supabase +project's credentials and the Hyperdrive id are published by the Terraform +applies as orun secrets. Nothing provider-shaped is stored in the repository +or in GitHub. + +## Connect Stripe + +Stripe is a third party no platform brokers, so the product deploys without +it: sign-up, sign-in, teams and the dashboard work, and the pricing page says +**"Connect Stripe to enable checkout."** To turn payments on, per +environment: + +1. In the Stripe dashboard (test mode first), create two products, **Base** + and **Plus**, each with one recurring monthly price — the pricing page + finds them by name. +2. Add a webhook endpoint at + `https://saas-starter-web-prod.your-workers-subdomain.workers.dev/api/stripe/webhook` + (and `-stage` for stage) for `customer.subscription.updated` and + `customer.subscription.deleted`. +3. Set the two Worker secrets: + + ```bash + wrangler secret put STRIPE_SECRET_KEY --name saas-starter-web-prod + wrangler secret put STRIPE_WEBHOOK_SECRET --name saas-starter-web-prod # the endpoint's signing secret + ``` + +Worker secrets survive every later deploy; the next request sees them. + +The session cookie needs no secret from you: unless you set an +`AUTH_SECRET` Worker secret, its key is one the environment's database +generated for itself when the migrations first ran. Setting `AUTH_SECRET` +rotates it (every existing session ends). + +## 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 → +`saas-starter-web-prod` → Settings → Domains & Routes), then set `BASE_URL` +in `apps/web/wrangler.template.jsonc` to it — Stripe sends the browser back +there — run `pnpm run wire:fixture`, and merge. + +## 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, migrates 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..6b5ff8d --- /dev/null +++ b/.baseline/tasks/01-product.TaskContract.yaml @@ -0,0 +1,32 @@ +# 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 two test packages verify on dev, which the bootstrap keeps off +# main until 02-docs, so a marker on them 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 Supabase and Hyperdrive, migrates the schema and deploys the app on stage and prod + affects: + - supabase + - cloudflare-hyperdrive + - db + - db-migrate + - web + doneWhen: + - repo pushed, main pinned as default, workspace linked + - SUPABASE_PROJECT_REF, SUPABASE_DB_PASSWORD, SUPABASE_DB_URL and WIRING_CLOUDFLARE_HYPERDRIVE published on stage and prod + - migrations applied and the app deployed and smoke-tested on stage and prod, in the order supabase → cloudflare-hyperdrive → db-migrate → 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..2060aef --- /dev/null +++ b/.github/workflows/baseline.yml @@ -0,0 +1,130 @@ +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 infra before app, and that the +# product installs, builds, migrates, deploys (dry), serves and signs a user +# up with no Stripe key. +# +# ─── 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 cloudflare-hyperdrive, then db-migrate, + # 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-saas \ + --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; the migrations applied by the product's + # own runner to a local Postgres (through a stand-in for the one Supabase + # Management API endpoint it calls); the stage lane's own structure check, + # build, output check and dry deploy in the job tree orun stages; and the + # built Worker served over that database with no Stripe key and no + # AUTH_SECRET — its smoke, every route, and a sign-up, sign-in and dashboard. + # 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, migrates, deploys (dry) and serves + 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..67bd6a0 100644 --- a/.github/workflows/checks.yml +++ b/.github/workflows/checks.yml @@ -1,14 +1,21 @@ 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 +# database and no Stripe account: nothing here connects to either. +# `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..8768611 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 two Cloudflare tokens 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 17062c1..812fa30 100644 --- a/.gitignore +++ b/.gitignore @@ -27,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 diff --git a/BOOTSTRAP.md b/BOOTSTRAP.md new file mode 100644 index 0000000..74cd8ae --- /dev/null +++ b/BOOTSTRAP.md @@ -0,0 +1,227 @@ +# BOOTSTRAP — a new SaaS product from this baseline, in one landing + +How to go from **nothing** to **a SaaS product live on stage and prod — +its own Supabase project per environment, Hyperdrive in front of it, the +schema applied, the app deployed — 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 twenty 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), +the Hyperdrive config, applies the migrations 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 Hyperdrive) and its Account API token with the + permission groups the console's Connect recipe lists — Workers Scripts and + Hyperdrive among them. +- A **Supabase** organization the platform can create projects in, connected + to the workspace (console → Integrations → Supabase). Each environment gets + its own project — mind your plan's project limit. +- 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 Stripe.** No platform brokers it: the product deploys without a + Stripe key and its owner adds one afterwards (§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/saas-starter +cd saas-starter + +orun new --blueprint repo-blueprint.yaml \ + --out ~/products/acme-saas --run-hooks --resume \ + --set reponame=acme-saas --set productname="Acme Cloud" \ + --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 five brokered credentials; then the whole product in one PR — intent, CI, tooling, identity, the Supabase and Hyperdrive Terraform roots, the migrations, the app and its tests | the convergence green (supabase → cloudflare-hyperdrive → db-migrate → 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 (Stripe's state included); prod's promotion gate and dev's push lanes restored | the final probe | + +```bash +orun new --blueprint repo-blueprint.yaml --out ~/products/acme-saas --run-hooks \ + --phase 01-product --values ~/acme-saas.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 roots, the +migrations and their runner, 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/saas-starter +cd saas-starter +orun new --blueprint repo-blueprint.yaml \ + --out /work/acme-saas --run-hooks --resume --progress json \ + --values /work/acme-saas.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 + +- **Connect Stripe** (per environment): create the **Base** and **Plus** + products with a monthly price each, add the webhook endpoint + `https://-web-..workers.dev/api/stripe/webhook` + (`customer.subscription.updated`, `customer.subscription.deleted`), and set + the Worker secrets: + + ```bash + wrangler secret put STRIPE_SECRET_KEY --name -web- + wrangler secret put STRIPE_WEBHOOK_SECRET --name -web- + ``` + + Until then the pricing page says "Connect Stripe to enable checkout", + checkout and the portal send visitors there and the webhook answers 503 — + sign-up, sign-in and the dashboard work either way. The product's README, + "Connect Stripe", is the owner's copy of this. +- **The session key** needs nothing: the database generated one per + environment when the migrations first ran. `AUTH_SECRET` as a Worker secret + overrides it (and ends every session). +- **Custom domain**: attach it to the Worker in Cloudflare, then set + `BASE_URL` in the product's `apps/web/wrangler.template.jsonc` (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 Stripe is connected. + +## 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, +apply the Hyperdrive config, mint a token, deploy for real. The Terraform +roots are 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 migrations are +applied by the product's own runner to a local Postgres through a stand-in +for the one Supabase Management API endpoint it calls +(`testing/lib/fake-supabase-api.py`), before the built Worker serves a +sign-up over that database. + +## 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: `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: project limit reached | the Supabase org's plan allows fewer projects than stage + prod need; free one or upgrade, then re-run `01-product` | +| hyperdrive apply: Authentication error (10000) | the Hyperdrive token lacks the permission; reconnect Cloudflare with the recipe's permission groups and re-run the phase — the reconcile re-mints only what is missing | +| hyperdrive or db-migrate: `secret resolution failed … SUPABASE_*` | the supabase apply for that environment did not publish; its lane's log says why. Both wait on it, enforced | +| db-migrate: `row-level security would lock the app out of …` | migration 030 refused: `postgres` (Hyperdrive's role) neither owns the tables in `public` nor bypasses RLS. Nothing was enabled; give `postgres` the tables or BYPASSRLS and re-run `01-product` | +| web smoke: `/api/health` 503 | `database: unreachable` — the Hyperdrive config is wrong or the project is paused; `schema: missing` — db-migrate did not run for that environment | +| `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) | +| 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 and the config are 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 f6816ff..93703a1 100644 --- a/README.md +++ b/README.md @@ -5,158 +5,120 @@ Postgres through Drizzle, Stripe Checkout, Customer Portal and webhooks, email/password auth with a JWT cookie, a session-refreshing proxy, teams with roles, invitations and an activity log — running on **Cloudflare Workers + Static Assets** through [`@opennextjs/cloudflare`](https://opennext.js.org/cloudflare), -with its Postgres being a **Supabase** project's database reached through +with its Postgres a **Supabase** project's database reached through **Cloudflare Hyperdrive**, both provisioned by Terraform through -[Orun](https://github.com/sourceplane/orun), and its schema applied by Orun's -`db-migrate` component — the way the -[Lumen baseline](https://github.com/sourceplane/lumen) does it. - -The template's code is the code. What the port changes in it is the one thing -the Workers runtime forces — the database client is built per request over -the Hyperdrive binding (`lib/db/drizzle.ts`'s `getDb()`) instead of once at -module load — plus Next 16's `proxy.ts` name for the middleware and the -Stripe SDK's fetch transport. What it adds is the Workers build, the monorepo -wrapper, tests for the session, the proxy and the webhook, the migrations -package with Lumen's runner, three infrastructure components (the Supabase -project, the Hyperdrive config, the migration step) and the deploy contract -that threads the Hyperdrive id into the Worker per environment. See -[`specs/epics/saas-starter`](specs/epics/saas-starter/README.md) for the -design, the milestones and the as-built status, including every departure. - -## What is here +[Orun](https://github.com/sourceplane/orun) and the schema applied by Orun's +`db-migrate` — the way the [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 changes is what the Workers +runtime and a fresh, unattended deployment force: the database client is +built per request over the Hyperdrive binding (`lib/db/drizzle.ts`), the +Stripe client exists only once a key does (so the app deploys and signs users +up with no Stripe account, and the pricing page says checkout is not +connected), and the session key defaults to one the database generates for +itself (so no secret has to be set by hand). 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/saas-starter`](specs/epics/saas-starter/README.md) +for the design, the milestones and the as-built status, including every +departure. + +## Instantiating a product + +```bash +git clone --depth 1 --branch https://github.com/sourceplane/saas-starter +cd saas-starter +orun new --blueprint repo-blueprint.yaml --out ~/products/acme-saas --run-hooks --resume \ + --set reponame=acme-saas --set productname="Acme Cloud" --set productdomain=acme.dev \ + --set githuborg=acme-inc --set subdomain= +``` + +Or, once the platform's registry lists it, from the Orun console (Baselines → +`saas-starter` → Build). Two phases: **`01-product`** creates the repository, +mints the five 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 ──▶ cloudflare-hyperdrive ──▶ db-migrate ──▶ web +``` + +— each 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 new repository receives the **product only** — the app, the Terraform +roots, the migrations, the tests, its CI, its tooling, a README of its own +and its operating contract — renamed throughout to the product's name, +repository, Worker, Supabase project and Hyperdrive config. None of this +repository's machinery ships. **Stripe is the owner's to connect afterwards** +(the product's README, "Connect Stripe"): no platform brokers it, so the card +asks for no Stripe key. + +| 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 | |---|---| -| Marketing page, pricing, sign-in / sign-up, the dashboard, the Stripe routes | `apps/web/app` | +| The product's name | `apps/web/lib/site.ts` | +| Marketing page, pricing, sign-in / sign-up, the dashboard, the Stripe routes, `/api/health` | `apps/web/app` | | Drizzle schema, queries, the per-request client, the seed | `apps/web/lib/db` (`drizzle.ts` is `getDb()`) | -| Session (jose + bcrypt), action validation, the proxy | `apps/web/lib/auth`, `apps/web/proxy.ts` | +| Session (jose + bcrypt) and its key, action validation, the proxy | `apps/web/lib/auth`, `apps/web/proxy.ts` | | Stripe client, checkout, portal, subscription sync | `apps/web/lib/payments` | -| Workers build and deploy contract | `apps/web/next.config.ts`, `open-next.config.ts`, `wrangler.template.jsonc`, `component.yaml` | -| The schema as migrations + Lumen's runner | `packages/db` (`@saas/db`) | -| The migration step, the Supabase project, the Hyperdrive config | `infra/db-migrate`, `infra/terraform/supabase`, `infra/terraform/cloudflare-hyperdrive` | +| Workers build and deploy contract | `apps/web/next.config.ts`, `open-next.config.ts`, `wrangler.template.jsonc` → `wrangler.jsonc` (committed), `component.yaml` | +| The schema as migrations, and Lumen's runner | `packages/db` (`@saas/db`) | +| The Supabase project, the Hyperdrive config, the migration step | `infra/terraform/supabase`, `infra/terraform/cloudflare-hyperdrive`, `infra/db-migrate` | | Tests | `tests/web`, `tests/db` (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 ``` -The build needs no database and no Stripe account: nothing pre-renders -against either (the build script supplies a placeholder `STRIPE_SECRET_KEY` -so the module-level Stripe client can be constructed; it is never called). - -## Running it locally - -You need a Postgres on `localhost:54322` — the Supabase CLI's default -(`supabase start`), or the Docker container upstream's setup script offers — -or any Postgres whose URL you put in `POSTGRES_URL`. - -1. **Environment.** Copy `apps/web/.env.example` to `apps/web/.env` and fill - it in, or let upstream's wizard do it (it also creates the Docker - Postgres and a Stripe CLI webhook secret): - - ```bash - pnpm --filter @app/web db:setup - ``` - - `.env` is read by `next dev`, the seed and drizzle-kit. The Worker never - reads it: its database is the `HYPERDRIVE` binding and its secrets are - `.dev.vars` (below). - -2. **Schema.** Locally, drizzle-kit applies the template's migrations as - upstream (`pnpm db:generate` after a schema change, `pnpm db:studio` to - browse): - - ```bash - pnpm --filter @app/web db:migrate - ``` - - The same SQL lives in `packages/db/src/migrations` and is what CI applies - to the real databases (below). - -3. **Seed.** Creates the test user and team and the two Stripe products in - the account `STRIPE_SECRET_KEY` names (test mode): - - ```bash - pnpm --filter @app/web db:seed # user test@test.com / admin123 - ``` - -4. **Run.** Either Next's dev server, which gets the Worker's bindings - through `getCloudflareContext()` (the `HYPERDRIVE` binding points at - `localhost:54322` via `wrangler.jsonc`'s `localConnectionString`, so - `pnpm run wire:fixture` first): - - ```bash - pnpm --filter @app/web dev # http://localhost:3000 - ``` - - or the built Worker under `wrangler dev`, which reads - `apps/web/.dev.vars` (copy `.dev.vars.example`: `AUTH_SECRET`, - `STRIPE_SECRET_KEY`, `STRIPE_WEBHOOK_SECRET`, `BASE_URL`): - - ```bash - pnpm build - pnpm --filter @app/web preview # http://localhost:8787 - ``` - -5. **Stripe.** As upstream: `stripe login`, then forward webhooks to the - server you are running — - - ```bash - stripe listen --forward-to localhost:3000/api/stripe/webhook - ``` - - — and test checkout with card `4242 4242 4242 4242`, any future date, - any CVC. +The build needs no database and no Stripe account. Running it locally — a +Postgres on `localhost:54322` (`supabase start`), `pnpm db:migrate`, +`pnpm db:seed`, `next dev` or `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, `middleware.ts` on the edge | One Cloudflare Worker (`.open-next/worker.js`) + Static Assets; the middleware is `proxy.ts` (Next 16's name) and runs in the Worker | -| Postgres from the marketplace, `postgres(POSTGRES_URL)` at module scope | The Supabase project's Postgres through Hyperdrive: `getDb()` builds a `postgres` client + Drizzle per request from `env.HYPERDRIVE.connectionString` (the runtime refuses a socket shared across requests); `POSTGRES_URL` is for local scripts | -| `drizzle-kit migrate` | `infra/db-migrate` applies `packages/db/src/migrations` (the template's drizzle-kit SQL, verbatim) through Supabase's Management API per environment, before the Worker deploys | -| Project env vars in the dashboard | `BASE_URL`: a wrangler var per environment. `AUTH_SECRET`, `STRIPE_SECRET_KEY`, `STRIPE_WEBHOOK_SECRET`: Worker secrets (`wrangler secret put`, below) | -| The Stripe SDK over Node's `http` | `Stripe.createFetchHttpClient()`; the webhook verifies with `constructEventAsync` over SubtleCrypto | -| A database created by hand | `infra/terraform/supabase` (one project per environment) + `infra/terraform/cloudflare-hyperdrive` (one config per environment over that database), ids and credentials as orun secrets | -| Deploy on push | Orun deploys `saas-starter-web-{stage,prod}` on merge to `main`, after the Hyperdrive root and the migration step (`apps/web/component.yaml`) | - -## 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, -per environment: applies the Supabase root, applies the Hyperdrive root over -its database, builds `@saas/db` and applies the migrations, renders -`wrangler.jsonc` with that environment's Hyperdrive id, builds the app and -deploys the Worker to `stage`, then `prod`. - -Three things are the product's to set once per environment, because no root -can mint them: - -```bash -# Worker secrets (the deploy lane does not set these) -wrangler secret put AUTH_SECRET --name saas-starter-web-stage # openssl rand -base64 32 -wrangler secret put STRIPE_SECRET_KEY --name saas-starter-web-stage -wrangler secret put STRIPE_WEBHOOK_SECRET --name saas-starter-web-stage # from the webhook you register below -``` - -- **The Worker's origin.** `BASE_URL` is where Stripe sends the browser back - to. `apps/web/wrangler.template.jsonc`, `apps/web/component.yaml` and - `intent.yaml` carry the same `your-workers-subdomain` placeholder: replace - it with the account's workers.dev subdomain (or a custom domain) once. -- **The Stripe webhook.** In the Stripe dashboard, add an endpoint at - `https://saas-starter-web-prod..workers.dev/api/stripe/webhook` - for `customer.subscription.updated` and `customer.subscription.deleted`; - its signing secret is `STRIPE_WEBHOOK_SECRET` above. -- **The Stripe products.** Run the seed against the live account once (or - create Base and Plus by hand); until then the pricing page shows its - defaults with nothing to buy. +| Postgres from the marketplace, `postgres(POSTGRES_URL)` at module scope | The Supabase project's Postgres through Hyperdrive: `getDb()` builds a `postgres` client + Drizzle per request from `env.HYPERDRIVE.connectionString`; `POSTGRES_URL` is for local scripts | +| `drizzle-kit migrate` | `infra/db-migrate` applies `packages/db/src/migrations` through Supabase's Management API per environment, after the project and the Hyperdrive config exist, before the Worker deploys | +| `AUTH_SECRET` from the setup script | Optional: unset, the session key is the one the environment's database generated (`app_private.secrets`) | +| Stripe keys in the project's env vars | Worker secrets the owner adds when ready; until then checkout says it is not connected | +| A database created by hand | `infra/terraform/supabase` (one project per environment) + `infra/terraform/cloudflare-hyperdrive` (one config per environment), ids and credentials as orun secrets | +| "Deploy with Vercel" (clone the template) | `orun new --blueprint repo-blueprint.yaml` — a new repository, branded, provisioned, deployed | + +## CI + +| 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, migrates 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, migrated into a local Postgres, dry-deployed, served and signed up on | 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..cea5104 --- /dev/null +++ b/ai/context/deployment.md @@ -0,0 +1,7 @@ +# saas-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, whether Stripe is connected, 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..4d0a5c9 --- /dev/null +++ b/ai/context/operations.md @@ -0,0 +1,172 @@ +# saas-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, whether Stripe is connected, 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 SaaS Starter — email/password auth with a JWT cookie, teams +with roles and invitations, an activity log, Stripe subscriptions — on +Cloudflare Workers, with its Postgres a Supabase project reached through +Cloudflare Hyperdrive, expressed as an Orun component-native desired-state +repo. Seven components: + +- **`infra/terraform/supabase`** (`supabase`) — one Supabase project per + environment. Its apply publishes `SUPABASE_PROJECT_REF`, + `SUPABASE_DB_PASSWORD` and `SUPABASE_DB_URL` onto the environment's secret + rung. +- **`infra/terraform/cloudflare-hyperdrive`** (`cloudflare-hyperdrive`) — one + Hyperdrive config per environment over that database. Its apply publishes + `WIRING_CLOUDFLARE_HYPERDRIVE` (the config's id and name). +- **`infra/db-migrate`** (`db-migrate`) — applies `packages/db`'s migrations + to the environment's database through Supabase's Management API. Each + migration is recorded with its checksum in `_migrations.applied`; only the + missing ones apply. +- **`packages/db`** (`db`) — the migrations and their runner. +- **`apps/web`** (`web`) — the app: Next.js built by `@opennextjs/cloudflare` + into one Worker plus Static Assets. It reaches Postgres through its + `HYPERDRIVE` binding, one client per request (`lib/db/drizzle.ts`). +- **`tests/web`**, **`tests/db`** — vitest suites, 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 — each edge `mode: enforced` on a push to + main, advisory on a pull request (which deploys nothing): + **`supabase` → `cloudflare-hyperdrive` → `db-migrate` → `web`.** A job + resolves its secrets when it starts, so each one reads what the apply + before it published. The app's deploy re-renders `apps/web/wrangler.jsonc` + from `WIRING_CLOUDFLARE_HYPERDRIVE` before it builds, deploys + `saas-starter-web-`, and smoke-tests it: the home page, and + `/api/health`, which answers 200 only when the database is reachable + through Hyperdrive and migrated. +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 + Hyperdrive id): 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 id. +- Every table in `public` has row-level security and no policy. Supabase's + Data API serves `public` to the anon key, so this is what keeps the users + table (password hashes included) out of it; the app is unaffected because + it connects as `postgres`, the tables' owner. Give a new table + `.enableRLS()`; never `FORCE` it, and never add a policy for `anon` without + meaning to publish that table. +- A migration is immutable once applied: its checksum is in + `packages/db/src/manifest.ts` and in the database's ledger. Change the + schema with a NEW migration (in `packages/db/src/migrations`, and its + drizzle-kit twin in `apps/web/lib/db/migrations` for local databases). + +## 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_HYPERDRIVE_TOKEN` + (Hyperdrive — the deploy token deliberately cannot touch it), + `CLOUDFLARE_ACCOUNT_ID`, `SUPABASE_ACCESS_TOKEN` (project create and + migrations) and `SUPABASE_ORG_ID`. +- **Published by the applies** onto the stage and prod rungs: + `SUPABASE_PROJECT_REF`, `SUPABASE_DB_PASSWORD`, `SUPABASE_DB_URL`, + `WIRING_CLOUDFLARE_HYPERDRIVE`. +- **Worker secrets the owner adds**, because no platform brokers Stripe: + `STRIPE_SECRET_KEY` and `STRIPE_WEBHOOK_SECRET` (below). Until they exist + the pricing page says checkout is not connected, the checkout and portal + actions send visitors there, and the webhook answers 503. +- **The session key.** `AUTH_SECRET`, when set as a Worker secret, signs the + session cookie. Unset, the key is the one the environment's database + generated for itself (`app_private.secrets`, migration `020_app_secrets`) — + so a fresh deployment signs users up without any secret set by hand. + Setting `AUTH_SECRET` rotates it: every existing session ends. +- 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. + +## Connect Stripe + +Per environment (`stage`, `prod`), in the Stripe account you want to charge +from (test mode first): + +1. Create two products, **Base** and **Plus**, each with one recurring + monthly price — the pricing page finds them by those names. (Or run + `pnpm --filter @app/web db:seed` with `STRIPE_SECRET_KEY` and a local + `POSTGRES_URL`: it creates both, and a local test user.) +2. Add a webhook endpoint at + `https://saas-starter-web-.your-workers-subdomain.workers.dev/api/stripe/webhook` + for `customer.subscription.updated` and `customer.subscription.deleted`. +3. Set both Worker secrets: + + ```bash + wrangler secret put STRIPE_SECRET_KEY --name saas-starter-web- + wrangler secret put STRIPE_WEBHOOK_SECRET --name saas-starter-web- # the endpoint's signing secret + ``` + +Worker secrets survive every later deploy; nothing in CI touches them. The +pricing page shows the live plans from the next request on. Re-running the +bootstrap's `02-docs` phase records the change in +[deployment.md](deployment.md). + +## Verifying the system + +```bash +# the app and its database path on each environment (also recorded, probed, in deployment.md) +curl -s -o /dev/null -w '%{http_code}\n' https://saas-starter-web-stage.your-workers-subdomain.workers.dev/ +curl -s https://saas-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` | +| change the schema | add the table to `apps/web/lib/db/schema.ts` with `.enableRLS()`, `pnpm --filter @app/web db:generate`, copy the SQL into a new `packages/db/src/migrations/_/up.sql` and the manifest (`pnpm --filter @saas/db run manifest:fix` for its checksum), merge — db-migrate applies it before the app deploys. `pnpm test` fails on a table in `public` without row-level security | +| 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 | +| connect Stripe | above | +| rotate the session key | `wrangler secret put AUTH_SECRET --name saas-starter-web-` (32+ random bytes); every session ends | +| serve a custom domain | attach it to the Worker in Cloudflare, and change `BASE_URL` in `apps/web/wrangler.template.jsonc` (Stripe redirects back to it) | +| 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, another data store) 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 index 78c1c50..b4aee09 100644 --- a/apps/web/.dev.vars.example +++ b/apps/web/.dev.vars.example @@ -1,11 +1,18 @@ # Local Worker secrets for `wrangler dev` / `opennextjs-cloudflare preview`. -# Copy to .dev.vars (git-ignored). In stage/prod these are Worker secrets, set -# once per environment with `wrangler secret put --name saas-starter-web-` -# (README → Deploying); the deploy lane does not set them. The database is not -# here: the Worker reaches it through the HYPERDRIVE binding (wrangler.jsonc). -AUTH_SECRET=change-me-openssl-rand-base64-32 -STRIPE_SECRET_KEY=sk_test_*** -STRIPE_WEBHOOK_SECRET=whsec_*** +# Copy to .dev.vars (git-ignored). Every key is optional: the database is not +# here (the Worker reaches it through the HYPERDRIVE binding, wrangler.jsonc). +# +# The session key. Unset, it is the one the database generated for itself +# (migration 020_app_secrets, lib/auth/secret.ts). +# AUTH_SECRET=change-me-openssl-rand-base64-32 +# +# Stripe. Unset, the pricing page says checkout is not connected and the +# webhook answers 503. In stage/prod these are Worker secrets the owner sets +# once per environment: `wrangler secret put --name saas-starter-web-` +# (README, "Connect Stripe"). +# STRIPE_SECRET_KEY=sk_test_*** +# STRIPE_WEBHOOK_SECRET=whsec_*** +# # Where Stripe sends the browser back to; wrangler.jsonc's var is the deployed # value, this one overrides it locally. BASE_URL=http://localhost:8787 diff --git a/apps/web/README.md b/apps/web/README.md index 093d91d..b2bd3a6 100644 --- a/apps/web/README.md +++ b/apps/web/README.md @@ -1,119 +1,35 @@ -# Next.js SaaS Starter - -This is a starter template for building a SaaS application using **Next.js** with support for authentication, Stripe integration for payments, and a dashboard for logged-in users. - -**Demo: [https://next-saas-start.vercel.app/](https://next-saas-start.vercel.app/)** - -## Features - -- Marketing landing page (`/`) with animated Terminal element -- Pricing page (`/pricing`) which connects to Stripe Checkout -- Dashboard pages with CRUD operations on users/teams -- Basic RBAC with Owner and Member roles -- Subscription management with Stripe Customer Portal -- Email/password authentication with JWTs stored to cookies -- Global middleware to protect logged-in routes -- Local middleware to protect Server Actions or validate Zod schemas -- Activity logging system for any user events - -## Tech Stack - -- **Framework**: [Next.js](https://nextjs.org/) -- **Database**: [Postgres](https://www.postgresql.org/) -- **ORM**: [Drizzle](https://orm.drizzle.team/) -- **Payments**: [Stripe](https://stripe.com/) -- **UI Library**: [shadcn/ui](https://ui.shadcn.com/) - -## Getting Started - -```bash -git clone https://github.com/nextjs/saas-starter -cd saas-starter -pnpm install -``` - -## Running Locally - -[Install](https://docs.stripe.com/stripe-cli) and log in to your Stripe account: - -```bash -stripe login -``` - -Use the included setup script to create your `.env` file: - -```bash -pnpm db:setup -``` - -Run the database migrations and seed the database with a default user and team: - -```bash -pnpm db:migrate -pnpm db:seed -``` - -This will create the following user and team: - -- User: `test@test.com` -- Password: `admin123` - -You can also create new users through the `/sign-up` route. - -Finally, run the Next.js development server: - -```bash -pnpm dev -``` - -Open [http://localhost:3000](http://localhost:3000) in your browser to see the app in action. - -You can listen for Stripe webhooks locally through their CLI to handle subscription change events: +# apps/web — the app + +A SaaS application from Vercel's +[Next.js SaaS Starter](https://github.com/nextjs/saas-starter) (MIT, see +`LICENSE`), running on Cloudflare Workers + Static Assets: + +- Marketing landing page (`/`) with an animated terminal +- Pricing page (`/pricing`) connected to Stripe Checkout — or, until Stripe is + connected, the template's plans and a notice saying so +- Dashboard pages with CRUD on users and teams, owner and member roles +- Subscription management with the Stripe Customer Portal +- Email/password authentication with a JWT in a cookie, a proxy that guards + `/dashboard` and refreshes the session, validated server actions +- An activity log of every user event +- `/api/health`, which answers 200 only when the database is reachable through + Hyperdrive and migrated + +The product's name is `lib/site.ts`. The database client is built per request +over the `HYPERDRIVE` binding (`lib/db/drizzle.ts`); the session key is +`AUTH_SECRET` or the one the database generated (`lib/auth/secret.ts`); the +Stripe client exists only once `STRIPE_SECRET_KEY` does +(`lib/payments/stripe.ts`). ```bash -stripe listen --forward-to localhost:3000/api/stripe/webhook +pnpm dev # next dev on http://localhost:3000 +pnpm build # next build + opennextjs-cloudflare build → .open-next/ +pnpm preview # wrangler dev over the built Worker +pnpm db:migrate # drizzle-kit, against POSTGRES_URL +pnpm db:seed # the test user (test@test.com / admin123) and, with a key, the Stripe products ``` -## Testing Payments - -To test Stripe payments, use the following test card details: - -- Card Number: `4242 4242 4242 4242` -- Expiration: Any future date -- CVC: Any 3-digit number - -## Going to Production - -When you're ready to deploy your SaaS application to production, follow these steps: - -### Set up a production Stripe webhook - -1. Go to the Stripe Dashboard and create a new webhook for your production environment. -2. Set the endpoint URL to your production API route (e.g., `https://yourdomain.com/api/stripe/webhook`). -3. Select the events you want to listen for (e.g., `checkout.session.completed`, `customer.subscription.updated`). - -### Deploy to Vercel - -1. Push your code to a GitHub repository. -2. Connect your repository to [Vercel](https://vercel.com/) and deploy it. -3. Follow the Vercel deployment process, which will guide you through setting up your project. - -### Add environment variables - -In your Vercel project settings (or during deployment), add all the necessary environment variables. Make sure to update the values for the production environment, including: - -1. `BASE_URL`: Set this to your production domain. -2. `STRIPE_SECRET_KEY`: Use your Stripe secret key for the production environment. -3. `STRIPE_WEBHOOK_SECRET`: Use the webhook secret from the production webhook you created in step 1. -4. `POSTGRES_URL`: Set this to your production database URL. -5. `AUTH_SECRET`: Set this to a random string. `openssl rand -base64 32` will generate one. - -## Other Templates - -While this template is intentionally minimal and to be used as a learning resource, there are other paid versions in the community which are more full-featured: - -- https://achromatic.dev -- https://shipfa.st -- https://makerkit.dev -- https://zerotoshipped.com -- https://turbostarter.dev +How it runs locally, how it deploys — per environment, after the Supabase +project, the Hyperdrive config and the migrations, on merge to `main` — and +how to connect Stripe are the repository's README and `component.yaml` +beside this file. diff --git a/apps/web/app/(dashboard)/layout.tsx b/apps/web/app/(dashboard)/layout.tsx index 5e1d0b1..ad84227 100644 --- a/apps/web/app/(dashboard)/layout.tsx +++ b/apps/web/app/(dashboard)/layout.tsx @@ -15,6 +15,7 @@ import { signOut } from '@/app/(login)/actions'; import { useRouter } from 'next/navigation'; import { User } from '@/lib/db/schema'; import useSWR, { mutate } from 'swr'; +import { SITE_NAME } from '@/lib/site'; const fetcher = (url: string) => fetch(url).then((res) => res.json()); @@ -84,7 +85,7 @@ function Header() {
- ACME + {SITE_NAME}
}> diff --git a/apps/web/app/(dashboard)/pricing/page.tsx b/apps/web/app/(dashboard)/pricing/page.tsx index 4136911..82dae1b 100644 --- a/apps/web/app/(dashboard)/pricing/page.tsx +++ b/apps/web/app/(dashboard)/pricing/page.tsx @@ -1,6 +1,10 @@ import { checkoutAction } from '@/lib/payments/actions'; import { Check } from 'lucide-react'; -import { getStripePrices, getStripeProducts } from '@/lib/payments/stripe'; +import { + getStripePrices, + getStripeProducts, + stripeConfigured +} from '@/lib/payments/stripe'; import { SubmitButton } from './submit-button'; // Upstream: `export const revalidate = 3600` (prices fresh for one hour max, @@ -10,10 +14,13 @@ import { SubmitButton } from './submit-button'; export const dynamic = 'force-dynamic'; export default async function PricingPage() { - const [prices, products] = await Promise.all([ - getStripePrices(), - getStripeProducts(), - ]); + // Without a Stripe key the page still renders — the template's default + // plans, with checkout off and a notice saying why — instead of failing on + // the Stripe call (lib/payments/stripe.ts). + const connected = stripeConfigured(); + const [prices, products] = connected + ? await Promise.all([getStripePrices(), getStripeProducts()]) + : [[], []]; const basePlan = products.find((product) => product.name === 'Base'); const plusPlan = products.find((product) => product.name === 'Plus'); @@ -23,6 +30,7 @@ export default async function PricingPage() { return (
+ {!connected && }
); } +function StripeNotConnected() { + return ( +
+

Connect Stripe to enable checkout.

+

+ The plans below are the template's defaults. This deployment has + no Stripe key yet; once its owner adds STRIPE_SECRET_KEY and + STRIPE_WEBHOOK_SECRET, checkout and the customer portal turn on. +

+
+ ); +} + function PricingCard({ name, price, @@ -60,6 +87,7 @@ function PricingCard({ trialDays, features, priceId, + checkoutEnabled, }: { name: string; price: number; @@ -67,6 +95,7 @@ function PricingCard({ trialDays: number; features: string[]; priceId?: string; + checkoutEnabled: boolean; }) { return (
@@ -90,7 +119,7 @@ function PricingCard({
- +
); diff --git a/apps/web/app/(dashboard)/pricing/submit-button.tsx b/apps/web/app/(dashboard)/pricing/submit-button.tsx index aa04ea9..abca223 100644 --- a/apps/web/app/(dashboard)/pricing/submit-button.tsx +++ b/apps/web/app/(dashboard)/pricing/submit-button.tsx @@ -4,13 +4,13 @@ import { Button } from '@/components/ui/button'; import { ArrowRight, Loader2 } from 'lucide-react'; import { useFormStatus } from 'react-dom'; -export function SubmitButton() { +export function SubmitButton({ disabled = false }: { disabled?: boolean }) { const { pending } = useFormStatus(); return (