From 9463c47020030d56831d06baa4d8d54ae09bddc5 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 15 Oct 2026 20:56:25 +0000 Subject: [PATCH] SP5: subscription-payments becomes an Orun baseline MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The repository is an Orun baseline on the Cloudflare + Supabase (Lumen) conventions, built the way cirrus-baseline v22 builds a product: ONE landing, after the saas-starter reference without its Hyperdrive. 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, Lumen's three database credentials and WIRING_SUPABASE on stage and prod, and / + /api/health; 02-docs restores the promotion gate and dev's lanes and renders the deployment record. The chain is supabase -> db-migrate -> 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 (utils/site.ts) and the upstream's identity protected, the bootstrap helpers, the deployment-record hook, ai/context/, BOOTSTRAP.md, docs/phases/ - testing/: manifest, phases, coverage, rebrand, retouch, bootstrap-defer, leak, placement and e2e — the e2e over a local Supabase made of the real Auth (GoTrue 2.180.0) and Data API (PostgREST 12.2.12), pinned and checksummed, behind a gateway that checks the API key; the db-migrate and web lanes' own steps in the job trees orun stages; a sign-up, sign-out and sign-in through the app's own server actions; the anon key refused every row the policies do not give it - 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: - WIRING_SUPABASE carries the project URL, the anon key and the service-role key; the supabase root publishes it beside Lumen's three database credentials and nothing else, waits for ACTIVE_HEALTHY, and points the project's Auth at the Worker (Site URL, redirect allow-list, autoconfirm until SMTP). Lumen's lock file committed - web reads only its own environment's WIRING_SUPABASE, re-renders the committed wrangler.jsonc in stage/prod (URL, anon key, site origin, which next build inlines from it), and pushes the service-role key to the Worker with `wrangler secret bulk` from the deploy lane (tooling/wire/secrets.mjs) — never a var or a bundle. NEXT_PUBLIC_SITE_URL no longer comes out empty - Stripe optional: pricing shows the DB's plans or the template's sample plans with checkout off and "Connect Stripe to enable checkout"; checkout and the portal answer "Stripe is not connected."; the webhook answers 503; the publishable key is read per request - migration 020_row_level_security re-enables RLS on the five tables (upstream's policies kept) and refuses if any table in public lacks it; tests/db checks it in PGlite after every migration - /api/health (the project reachable with the built keys, the schema migrated, the service-role secret valid); the smoke and probes read it Not verified: a Terraform apply (the brokered OAuth token's reach to the API-keys and Auth-config endpoints), the secret push and a deploy to a real account, a live bootstrap, a real Stripe round-trip. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01AuyckrXahuAVgdmxamUUtk --- .baseline/identity.json | 9 + .baseline/product/README.md | 172 +++++ .baseline/tasks/01-product.TaskContract.yaml | 31 + .baseline/tasks/02-docs.TaskContract.yaml | 14 + .github/workflows/baseline.yml | 135 ++++ .github/workflows/checks.yml | 21 +- .github/workflows/ci.yml | 38 +- .github/workflows/tag.yml | 97 +++ .gitignore | 4 - BOOTSTRAP.md | 251 +++++++ README.md | 203 ++--- ai/context/deployment.md | 7 + ai/context/operations.md | 209 ++++++ apps/web/.dev.vars.example | 29 +- apps/web/README.md | 301 +------- apps/web/app/api/health/route.ts | 76 ++ apps/web/app/api/webhooks/route.ts | 22 +- apps/web/app/layout.tsx | 3 +- apps/web/app/page.tsx | 20 +- apps/web/component.yaml | 73 +- apps/web/components/ui/Footer/Footer.tsx | 5 +- apps/web/components/ui/Pricing/Pricing.tsx | 40 +- apps/web/next.config.mjs | 85 ++- apps/web/utils/site.ts | 5 + apps/web/utils/stripe/client.ts | 10 +- apps/web/utils/stripe/config.ts | 94 ++- apps/web/utils/stripe/sample-plans.ts | 53 ++ apps/web/utils/stripe/server.ts | 26 +- apps/web/utils/supabase/admin.ts | 12 +- apps/web/wiring.fixture.json | 6 +- apps/web/wrangler.jsonc | 46 ++ apps/web/wrangler.template.jsonc | 41 +- blueprint.yaml | 153 ++++ docs/phases/01-product.md | 128 ++++ docs/phases/02-docs.md | 41 + docs/phases/README.md | 108 +++ hooks/render-deployment-docs.sh | 194 +++++ infra/db-migrate/component.yaml | 12 +- infra/terraform/supabase/component.yaml | 17 +- .../supabase/terraform/.terraform.lock.hcl | 73 ++ infra/terraform/supabase/terraform/adopt.tf | 6 +- infra/terraform/supabase/terraform/main.tf | 121 ++- intent.yaml | 26 +- packages/db/src/manifest.ts | 9 + .../migrations/020_row_level_security/up.sql | 43 ++ .../db/src/runner/supabase-api-adapter.ts | 5 +- pnpm-lock.yaml | 20 +- pnpm-workspace.yaml | 6 + repo-blueprint.yaml | 710 ++++++++++++++++++ specs/epics/README.md | 2 +- .../IMPLEMENTATION-STATUS.md | 120 +++ specs/epics/subscription-payments/README.md | 7 +- specs/epics/subscription-payments/design.md | 80 +- specs/epics/subscription-payments/epic.yaml | 11 +- .../implementation-plan.md | 40 + .../risks-and-open-questions.md | 141 +++- tasks/SP-1.TaskContract.yaml | 3 + tasks/SP-2.TaskContract.yaml | 3 + tasks/SP-3.TaskContract.yaml | 3 + tasks/SP-4.TaskContract.yaml | 3 + tasks/SP-5.TaskContract.yaml | 3 + tasks/SP-6.TaskContract.yaml | 40 + testing/bootstrap-defer.test.sh | 67 ++ testing/coverage.test.sh | 177 +++++ testing/e2e.test.sh | 658 ++++++++++++++++ testing/fixtures/acme.json | 23 + ...seline-identity.subscription-payments.json | 9 + testing/leak.test.sh | 176 +++++ testing/lib/bootstrap.sh | 63 ++ testing/lib/fake-supabase-api.py | 67 ++ testing/lib/local-postgres.sh | 73 ++ testing/lib/local-supabase.sh | 147 ++++ testing/lib/run-hooks.py | 72 ++ testing/lib/stage-job.py | 82 ++ testing/lib/supabase-gateway.py | 74 ++ testing/manifest.test.sh | 432 +++++++++++ testing/phases.test.sh | 368 +++++++++ testing/placement.test.sh | 429 +++++++++++ testing/rebrand.test.sh | 185 +++++ testing/retouch.test.sh | 199 +++++ tests/db/package.json | 1 + tests/db/src/migrations.test.ts | 11 + tests/db/src/row-level-security.test.ts | 171 +++++ tests/web/package.json | 1 + tests/web/src/health.test.ts | 84 +++ tests/web/src/next-config.d.ts | 9 + tests/web/src/stripe-not-connected.test.ts | 131 ++++ tests/web/src/webhooks.test.ts | 18 +- tests/web/src/wrangler-config.test.ts | 195 +++++ 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 | 488 ++++++++++++ tooling/rebrand/values.example.json | 8 + tooling/wire/secrets.mjs | 118 +++ 96 files changed, 8778 insertions(+), 588 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/app/api/health/route.ts create mode 100644 apps/web/utils/site.ts create mode 100644 apps/web/utils/stripe/sample-plans.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/db/src/migrations/020_row_level_security/up.sql create mode 100644 repo-blueprint.yaml create mode 100644 tasks/SP-6.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.subscription-payments.json create mode 100755 testing/leak.test.sh create mode 100755 testing/lib/bootstrap.sh create mode 100755 testing/lib/fake-supabase-api.py create mode 100755 testing/lib/local-postgres.sh create mode 100644 testing/lib/local-supabase.sh create mode 100755 testing/lib/run-hooks.py create mode 100755 testing/lib/stage-job.py create mode 100644 testing/lib/supabase-gateway.py create mode 100755 testing/manifest.test.sh create mode 100755 testing/phases.test.sh create mode 100644 testing/placement.test.sh create mode 100755 testing/rebrand.test.sh create mode 100755 testing/retouch.test.sh create mode 100644 tests/db/src/row-level-security.test.ts create mode 100644 tests/web/src/health.test.ts create mode 100644 tests/web/src/next-config.d.ts create mode 100644 tests/web/src/stripe-not-connected.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 create mode 100644 tooling/wire/secrets.mjs diff --git a/.baseline/identity.json b/.baseline/identity.json new file mode 100644 index 0000000..08f4925 --- /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/utils/site.ts (upstream's footer brand); `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": "subscription-payments", + "pascal": "SubscriptionPayments", + "productName": "ACME", + "domain": "subscription-payments.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..4f48e72 --- /dev/null +++ b/.baseline/product/README.md @@ -0,0 +1,172 @@ +# subscription-payments + +Vercel's [Next.js Subscription Payments Starter](https://github.com/vercel/nextjs-subscription-payments) +— Supabase Auth with cookie sessions through `@supabase/ssr`, an account +page, a Postgres schema of users, customers, products, prices and +subscriptions kept in sync by Stripe's webhooks, Stripe Checkout to subscribe +and the Customer Portal to manage — on **Cloudflare Workers + Static Assets** +through [`@opennextjs/cloudflare`](https://opennext.js.org/cloudflare), with a +**Supabase** project per environment. Terraform provisions the project and +Orun's `db-migrate` applies the schema, row-level security on every table +included, 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/utils/site.ts` | +| Pricing (`/`), sign-in views (`/signin/[id]`), the account page (`/account`), the auth code exchanges, the Stripe webhook (`/api/webhooks`), `/api/health` | `apps/web/app` | +| Supabase clients (browser, server, admin, the session-refreshing proxy) and their queries | `apps/web/utils/supabase`, `apps/web/proxy.ts` | +| Stripe: the client and whether it is connected, Checkout and the Customer Portal, the sample plans shown before it is | `apps/web/utils/stripe` | +| Workers build and deploy contract | `apps/web/next.config.mjs`, `open-next.config.ts`, `wrangler.template.jsonc` → `wrangler.jsonc`, `component.yaml` | +| The deploy-time wiring: the wrangler render and the Worker-secret push | `tooling/wire` | +| The schema as migrations, and their runner | `packages/db` (`@saas/db`) | +| The Supabase project and the migration step | `infra/terraform/supabase`, `infra/db-migrate` | +| Local development with the Supabase CLI and the Stripe CLI | `apps/web/supabase`, `apps/web/fixtures`, `apps/web/types_db.ts` | +| 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 # tests/db runs every migration in PGlite and checks row-level security +pnpm build # next build + opennextjs-cloudflare build → apps/web/.open-next +``` + +The build needs no Supabase project and no Stripe account: it inlines the +placeholder project from the committed `wrangler.jsonc`. + +## Running it locally + +1. **A Supabase project.** Either the Supabase CLI's local stack + (`pnpm --filter @app/web supabase:start`, which applies + `apps/web/supabase/migrations`; pnpm 10 blocks the `supabase` package's + binary download until you `pnpm approve-builds` it), or a hosted project + you apply `packages/db/src/migrations` to. +2. **Environment.** Copy `apps/web/.env.local.example` to + `apps/web/.env.local`: the project URL, anon and service-role keys, and — + optionally — the Stripe keys. `next dev` reads it: + + ```bash + pnpm --filter @app/web dev # http://localhost:3000 + ``` + +3. **Or the built Worker** under `wrangler dev`, which reads the Supabase URL + and anon key from `wrangler.jsonc` (point them at your project in + `wiring.fixture.json` and re-render, or override them in `.dev.vars`) and + its secrets from `apps/web/.dev.vars` (copy `.dev.vars.example`): + + ```bash + pnpm build + pnpm --filter @app/web preview # http://localhost:8787 + ``` + +4. **Stripe.** `pnpm --filter @app/web stripe:login`, then forward webhooks + to the server you are running and create the template's plans: + + ```bash + pnpm --filter @app/web stripe:listen # → localhost:3000/api/webhooks + pnpm --filter @app/web stripe:fixtures # Hobby and Freelancer, monthly and yearly + ``` + + Test checkout with card `4242 4242 4242 4242`, any future date, any CVC. + Without Stripe keys 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 migrations, then the Worker** — +because each reads what the one before it published: the project's +credentials, then `WIRING_SUPABASE` (the project URL and anon key the build +inlines, and the service-role key the deploy hands the Worker as a secret). +`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 its +migrated project with a valid service-role key. + +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 Supabase project's +credentials and keys are published by the Terraform apply as orun secrets. +Nothing provider-shaped is stored in the repository or in GitHub, and the +service-role key is never in a wrangler file or a browser bundle. + +Every table in `public` has row-level security, with the template's +policies: a visitor reads the plans and their own user row and subscriptions, +never anyone else's, and the user→Stripe-customer map is the service role's +alone. Migration `020_row_level_security` stops a deploy that would leave a +table without it. + +## Connect Stripe + +Stripe is a third party no platform brokers, so the product deploys without +it: sign-up, sign-in and the account page work, the pricing page shows the +template's sample plans and says **"Connect Stripe to enable checkout."**, +and the webhook answers 503. To turn payments on, per environment (test mode +first): + +1. Add a webhook endpoint at + `https://subscription-payments-web-prod.your-workers-subdomain.workers.dev/api/webhooks` + (and `-stage` for stage) for `product.*`, `price.*`, + `checkout.session.completed` and `customer.subscription.*`. +2. Set the three Worker secrets: + + ```bash + wrangler secret put STRIPE_SECRET_KEY --name subscription-payments-web-prod + wrangler secret put STRIPE_WEBHOOK_SECRET --name subscription-payments-web-prod # the endpoint's signing secret + wrangler secret put STRIPE_PUBLISHABLE_KEY --name subscription-payments-web-prod # pk_…: public, read per request + ``` + +3. Create your products and prices in Stripe — after the endpoint exists, + so the webhook syncs them into the database — or run + `pnpm --filter @app/web stripe:fixtures` with that account for the + template's two plans. +4. Configure the Customer Portal (Stripe → Settings → Billing → Customer + portal). + +Worker secrets survive every later deploy; the next request sees them. + +## Supabase Auth email + +The Supabase project's Auth sends visitors back to the Worker (its Site URL +and redirect allow-list are set by `infra/terraform/supabase`), and new +sign-ups are signed straight in, because a project without SMTP of its own +emails only its organization's members. Before real users arrive, give the +project an SMTP server (Supabase dashboard → Authentication → Emails → SMTP +Settings), then set `authEmailConfirmation: "true"` in +`infra/terraform/supabase/component.yaml` and merge: sign-up then confirms +the address first, and magic links and password resets reach anyone. OAuth +providers are enabled in the same dashboard. + +## 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 → +`subscription-payments-web-prod` → Settings → Domains & Routes), set +`NEXT_PUBLIC_SITE_URL` in `apps/web/wrangler.template.jsonc` and the Auth +origin (`app_origin`) in `infra/terraform/supabase/terraform/main.tf` to it, +run `pnpm run wire:fixture`, merge, and point Stripe's webhook at the new +origin. + +## 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..cf66f75 --- /dev/null +++ b/.baseline/tasks/01-product.TaskContract.yaml @@ -0,0 +1,31 @@ +# 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 the Supabase project, migrates the schema with its row-level security and deploys the app on stage and prod + affects: + - supabase + - db + - db-migrate + - web + doneWhen: + - repo pushed, main pinned as default, workspace linked + - SUPABASE_PROJECT_REF, SUPABASE_DB_PASSWORD, SUPABASE_DB_URL and WIRING_SUPABASE published on stage and prod + - migrations applied and the app deployed, its service-role key a Worker secret, and smoke-tested on stage and prod, in the order supabase → db-migrate → web + - the pricing 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..bf641bf --- /dev/null +++ b/.github/workflows/baseline.yml @@ -0,0 +1,135 @@ +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, in and out with no Stripe key — through Supabase Auth and the Data API, +# with every table in `public` behind row-level security. +# +# ─── 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 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-pay \ + --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 Supabase project's API on the runner — + # its own Postgres, Supabase Auth and the Data API (the pinned GoTrue and + # PostgREST releases, checksummed) behind one gateway that checks the API + # key; the migrations applied by the product's own runner (through a + # stand-in for the one Management API endpoint it calls); the stage lane's + # own structure check, build, output check and dry deploy in the job tree + # orun stages, handed the stage wiring document; and the built Worker served + # over that project with no Stripe key — its smoke, every route, a sign-up, + # sign-out, sign-in and the account page through its own server actions, and + # the anon key refused every row the policies do not give it. 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..48fdf55 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 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 17062c1..bfcd1af 100644 --- a/.gitignore +++ b/.gitignore @@ -26,7 +26,3 @@ crash.log # orun per-job staged workspaces and object-model caches. **/.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..4cb5a0c --- /dev/null +++ b/BOOTSTRAP.md @@ -0,0 +1,251 @@ +# BOOTSTRAP — a new subscription product from this baseline, in one landing + +How to go from **nothing** to **a subscription site live on stage and prod — +its own Supabase project per environment, its Auth pointed at the app, the +schema and its row-level security 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), +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 its Account API token with the permission groups the + console's Connect recipe lists — Workers Scripts Write among them: the + deploy token sets the Worker's service-role secret as well as deploying it. +- A **Supabase** organization **with room for two more projects** + (`-stage` and `-prod`) — Supabase's free plan allows + exactly two active projects per organization, so a free organization holds + one product built from here — 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: for an account in several organizations, the OAuth + consent, where you pick one, is the way to be sure which. +- 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 the keys 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/subscription-payments +cd subscription-payments + +orun new --blueprint repo-blueprint.yaml \ + --out ~/products/acme-pay --run-hooks --resume \ + --set reponame=acme-pay --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 four brokered credentials; then the whole product in one PR — intent, CI, tooling, identity, the Supabase Terraform root, the migrations, the app and its tests | the convergence green (supabase → 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-pay --run-hooks \ + --phase 01-product --values ~/acme-pay.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 +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/subscription-payments +cd subscription-payments +orun new --blueprint repo-blueprint.yaml \ + --out /work/acme-pay --run-hooks --resume --progress json \ + --values /work/acme-pay.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): add the webhook endpoint + `https://-web-..workers.dev/api/webhooks` + (`product.*`, `price.*`, `checkout.session.completed`, + `customer.subscription.*`), set the three Worker secrets — + + ```bash + wrangler secret put STRIPE_SECRET_KEY --name -web- + wrangler secret put STRIPE_WEBHOOK_SECRET --name -web- # the endpoint's signing secret + wrangler secret put STRIPE_PUBLISHABLE_KEY --name -web- # pk_…, read per request + ``` + + — then create the products and prices in Stripe (or run + `pnpm --filter @app/web stripe:fixtures` for the template's Hobby and + Freelancer plans): the webhook syncs them into the database, and the + pricing page shows them. Configure the Customer Portal (Stripe → Settings + → Billing → Customer portal). Until then the pricing page shows the + template's sample plans and "Connect Stripe to enable checkout", checkout + and the portal say Stripe is not connected and the webhook answers 503 — + sign-up, sign-in and the account page work either way. The product's + README, "Connect Stripe", is the owner's copy of this. +- **Supabase Auth email** (per environment): the supabase root sets the Site + URL and the redirect allow-list to the Worker and signs new users straight + in, because a project without SMTP of its own emails only its + organization's members. Before real users arrive, give each project an SMTP + server (Supabase dashboard → Authentication → Emails → SMTP Settings), then + set `authEmailConfirmation: "true"` in the product's + `infra/terraform/supabase/component.yaml` and merge. OAuth providers are + enabled in the same dashboard. The product's README, "Supabase Auth + email", is the owner's copy. +- **The service-role key** needs nothing: every deploy pushes it to the + Worker from `WIRING_SUPABASE`. +- **Custom domain**: attach it to the Worker in Cloudflare, then set + `NEXT_PUBLIC_SITE_URL` in the product's `apps/web/wrangler.template.jsonc` + and the Auth origin in its 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 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 and two pinned releases, 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 keys and write its Auth settings, mint a token, push the Worker +secret and 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 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`), under +the REAL Supabase Auth and Data API — pinned, checksummed releases of GoTrue +and PostgREST behind a gateway that checks the API key +(`testing/lib/local-supabase.sh`, `testing/lib/supabase-gateway.py`) — +before the built Worker serves a sign-up, a sign-out and a sign-in over +them, and the anon key is refused every row the policies do not give it. + +## 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 organization has no room for stage + prod (the free plan allows two active projects); pause or delete one, or upgrade, then re-run `01-product` | +| supabase apply: forbidden reading the API keys or writing the Auth config | the brokered token's scopes do not reach those endpoints (untested before a live run — the epic's SP-M). Connect Supabase with a personal access token, or set the Auth values by hand and drop `supabase_settings` from the product's root | +| db-migrate: `secret resolution failed … SUPABASE_*` | the supabase apply for that environment did not publish; its lane's log says why. db-migrate waits on it, enforced | +| db-migrate: `tables in public without row-level security …` | migration 020 refused: a table in `public` has no RLS, so the anon key could read it. Nothing deployed; enable RLS (and the policies the app needs) in a new migration, then re-run `01-product` | +| web `build-app`: `wrangler secret bulk failed` | the deploy token cannot write the Worker's secrets; reconnect Cloudflare with the recipe's permission groups (Workers Scripts Write) and re-run the phase | +| web smoke: `/api/health` 503 | `supabase: unreachable` — the project is paused or the URL wrong; `schema: missing` — db-migrate did not run for that environment; `serviceRole: missing`/`invalid` — the secret push did not happen or the key is not the project's | +| `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 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 28cd190..12b8c50 100644 --- a/README.md +++ b/README.md @@ -5,127 +5,130 @@ Vercel's [Next.js Subscription Payments Starter](https://github.com/vercel/nextj schema of users, customers, products, prices and subscriptions kept in sync by Stripe webhooks, Stripe Checkout to subscribe and the Customer Portal to manage — running on **Cloudflare Workers + Static Assets** through -[`@opennextjs/cloudflare`](https://opennext.js.org/cloudflare), with the -Supabase project provisioned by Terraform and its schema applied by the -`db-migrate` runner through [Orun](https://github.com/sourceplane/orun), the -way the [Lumen baseline](https://github.com/sourceplane/lumen) does it. +[`@opennextjs/cloudflare`](https://opennext.js.org/cloudflare), with a +**Supabase** project per environment provisioned by Terraform and its schema +applied by the `db-migrate` runner through +[Orun](https://github.com/sourceplane/orun) — 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, moved to Next 16 / React 19 with only the -changes Next 16 and Workers force (every one is listed in the -[as-built status](specs/epics/subscription-payments/IMPLEMENTATION-STATUS.md)). -What the port adds is the Workers build, the monorepo wrapper, test packages, -the migrations package and the db-migrate component, the Supabase Terraform -root, and the deploy contract that threads the project's URL, keys and the -site origin into the build and the Worker per environment. See +changes Next 16 and Workers force. What a fresh, unattended deployment forces +on top: the app reads its Supabase project from ONE wiring document per +environment (`WIRING_SUPABASE`: the URL and anon key the build inlines, and +the service-role key the deploy pushes to the Worker as a secret — never a +var or a bundle); the Stripe client exists only once a key does, so the app +deploys, signs users up and in and renders the account page with no Stripe +account, while pricing shows the template's sample plans and says checkout +is not connected and the webhook answers 503; and every table in `public` +keeps upstream's row-level security, checked by a migration of its own. +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/subscription-payments`](specs/epics/subscription-payments/README.md) -for the design, the milestones and the as-built status. +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/subscription-payments +cd subscription-payments +orun new --blueprint repo-blueprint.yaml --out ~/products/acme-pay --run-hooks --resume \ + --set reponame=acme-pay --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 → +`subscription-payments` → 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 ──▶ 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. +The Supabase organization needs room for **two** projects (stage and prod; +its free plan allows exactly two active ones). +**[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 +root, 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 and Supabase project. 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. Neither is Supabase Auth's email: the project signs new users straight +in until its owner gives it SMTP (the product's README, "Supabase Auth +email"). + +| 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/utils/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 | |---|---| -| Pricing (`/`), sign-in views (`/signin/[id]`), account (`/account`), auth code exchanges, the Stripe webhook (`/api/webhooks`) | `apps/web/app` | -| Supabase clients (browser, server, admin, middleware), Stripe clients and server actions, auth server actions, helpers | `apps/web/utils`, `apps/web/proxy.ts` | +| The product's name | `apps/web/utils/site.ts` | +| Pricing (`/`), sign-in views (`/signin/[id]`), the account page (`/account`), the auth code exchanges, the Stripe webhook (`/api/webhooks`), `/api/health` | `apps/web/app` | +| Supabase clients (browser, server, admin, the proxy), Stripe (whether it is connected, Checkout, the portal, the sample plans), auth server actions, helpers | `apps/web/utils`, `apps/web/proxy.ts` | | The schema and the Stripe fixtures, for local Supabase-CLI / Stripe-CLI development | `apps/web/supabase`, `apps/web/schema.sql`, `apps/web/fixtures`, `apps/web/types_db.ts` | -| The same schema as the migration CI applies | `packages/db/src/migrations/010_subscriptions_init/up.sql` (+ `000_control`), `infra/db-migrate` | -| Workers build and deploy contract | `apps/web/next.config.mjs`, `apps/web/open-next.config.ts`, `apps/web/wrangler.template.jsonc`, `apps/web/component.yaml`, `apps/web/.dev.vars.example` | -| The Supabase project (stage, prod) | `infra/terraform/supabase` | -| Tests | `tests/web` (helpers, auth settings, the webhook route's decisions), `tests/db` (manifest, offline plan) — vitest | +| The same schema as the migrations CI applies, and row-level security checked | `packages/db/src/migrations` (`010_subscriptions_init`, `020_row_level_security`), `infra/db-migrate` | +| Workers build and deploy contract | `apps/web/next.config.mjs`, `open-next.config.ts`, `wrangler.template.jsonc` → `wrangler.jsonc` (committed), `component.yaml` | +| The deploy-time wiring: the wrangler render and the Worker-secret push | `tooling/wire` | +| The Supabase project (stage, prod) and its Auth settings | `infra/terraform/supabase` | +| Tests | `tests/web`, `tests/db` (vitest; `tests/db` runs every migration in PGlite and checks row-level security) | ## 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 # packages/db → dist; next build + opennextjs-cloudflare build → apps/web/.open-next ``` -To run against a Supabase project and a Stripe test account, copy -`apps/web/.env.local.example` to `apps/web/.env.local` and fill it in (the -Supabase URL, anon and service-role keys; the Stripe publishable, secret and -webhook keys; `NEXT_PUBLIC_SITE_URL=http://localhost:3000`), then: - -```bash -pnpm --filter @app/web dev # http://localhost:3000, Next's dev server -pnpm --filter @app/web stripe:listen # in another terminal: forwards Stripe events to /api/webhooks -pnpm --filter @app/web stripe:fixtures # once: two products with monthly and yearly prices -``` - -To preview the built Worker instead, copy `apps/web/.dev.vars.example` to -`apps/web/.dev.vars` with the three server secrets, then -`pnpm --filter @app/web preview` (or `pnpm exec wrangler dev --config -wrangler.jsonc` in `apps/web`); the rendered `wrangler.jsonc` supplies the -Supabase URL and anon key as vars. - -The upstream README (`apps/web/README.md`) describes local development with -the Supabase CLI and Docker (`pnpm --filter @app/web supabase:start`, …). -pnpm 10 blocks the `supabase` package's postinstall, which downloads the CLI -binary; run `pnpm approve-builds` once and pick `supabase` if you want the -local stack (it allow-lists the package in your checkout's -`pnpm-workspace.yaml`; a plain `pnpm rebuild` does not run a blocked script). -CI never needs it: the runner applies the schema. +The build needs no Supabase project and no Stripe account. Running it +locally — the Supabase CLI's stack or a hosted project, `.env.local`, +`next dev` or `wrangler dev`, the Stripe CLI — 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 runs in the Worker as `proxy.ts` | -| Project env vars in the dashboard | Build time: `NEXT_PUBLIC_SUPABASE_URL` / `NEXT_PUBLIC_SUPABASE_ANON_KEY` from orun secrets (inlined by `next build`), `NEXT_PUBLIC_SITE_URL` = the environment's Worker URL. Run time: the two Supabase values as wrangler `vars` rendered per environment from the Supabase root's wiring document; `SUPABASE_SERVICE_ROLE_KEY`, `STRIPE_SECRET_KEY`, `STRIPE_WEBHOOK_SECRET` as Worker secrets | -| A Supabase project created by the Vercel integration | `infra/terraform/supabase`: one project per environment, URL and API keys published as orun secrets | -| The integration running `schema.sql` (or `supabase db push`) | `packages/db` carries the same SQL as migration `010_subscriptions_init`; `infra/db-migrate` plans it on pull requests and applies it on merge through Supabase's Management API | -| Stripe webhook at `https:///api/webhooks` | The same route on the Worker: `https://subscription-payments-web-..workers.dev/api/webhooks` | -| Deploy on push | Orun deploys `subscription-payments-web-{stage,prod}` on merge to `main`, after the Supabase root and the migrations (`apps/web/component.yaml`) | - -The anon key is a wrangler var, not a secret: it is shipped to every browser -by design, and Row Level Security is the boundary. The service-role key and -the Stripe secrets are Worker secrets and never appear in a wrangler file. - -## 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, applies the migrations, builds the app with that -environment's URL, key and site origin, and deploys the Worker to `stage`, -then `prod`. - -### Stripe (once per environment — the one manual step) - -1. In the Stripe dashboard (test mode), create products and prices — or run - `pnpm --filter @app/web stripe:fixtures` against your account for the - template's two products with monthly and yearly prices. -2. Add a webhook endpoint at - `https://subscription-payments-web-..workers.dev/api/webhooks` - listening to all events; copy its signing secret (`whsec_…`). -3. Set the Worker's secrets: - ```bash - cd apps/web - wrangler secret put STRIPE_SECRET_KEY --name subscription-payments-web- - wrangler secret put STRIPE_WEBHOOK_SECRET --name subscription-payments-web- - ``` - (or store them as orun secrets the deploy lane reads). The deploy lane - sets `SUPABASE_SERVICE_ROLE_KEY` from the Supabase root's published - secret. `NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY` is public and build-time: - export it in the component's `buildCommand`; while it is empty the app - builds and renders, and Checkout is unreachable. -4. Configure the Customer Portal (`Settings → Billing → Customer portal`) as - the upstream README describes. - -Products and prices reach the database through the webhook, so create them -after the endpoint exists; the pricing page shows "No subscription pricing -plans found" until then. - -### Supabase auth URLs - -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://subscription-payments-web-prod..workers.dev`, so -confirmation, magic-link and recovery emails link back to the app; -`getURL()` already builds those links from `NEXT_PUBLIC_SITE_URL`, which the -build sets to the same origin. +| 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 | +| Project env vars set by the Supabase integration | `WIRING_SUPABASE` per environment: the URL and anon key as wrangler vars the build inlines, the service-role key a Worker secret every deploy pushes | +| The integration running `schema.sql` (or `supabase db push`) | `infra/db-migrate` applies `packages/db/src/migrations` through Supabase's Management API per environment, after the project exists, before the Worker deploys | +| Stripe keys in the project's env vars | Worker secrets the owner adds when ready; until then pricing shows the sample plans and checkout says it is not connected | +| The Supabase project's Site URL, set by hand | `infra/terraform/supabase` sets it (and the redirect allow-list) to the Worker | +| A Supabase project created by the integration | `infra/terraform/supabase` (one project per environment), credentials and keys 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 Supabase (its real Auth and Data API), dry-deployed, served and signed up, out and in 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..c3276cb --- /dev/null +++ b/ai/context/deployment.md @@ -0,0 +1,7 @@ +# subscription-payments — 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..59f5492 --- /dev/null +++ b/ai/context/operations.md @@ -0,0 +1,209 @@ +# subscription-payments — 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 Subscription Payments Starter — Supabase Auth (password, +magic link, OAuth) with cookie sessions through `@supabase/ssr`, an account +page, and a Postgres schema of users, customers, products, prices and +subscriptions kept in sync by Stripe's webhooks, Stripe Checkout to subscribe +and the Customer Portal to manage — on Cloudflare Workers, with a Supabase +project per environment, expressed as an Orun component-native desired-state +repo. Six components: + +- **`infra/terraform/supabase`** (`supabase`) — one Supabase project per + environment, its Auth pointed at the app (Site URL, redirect allow-list, + sign-up confirmation). Its apply publishes `SUPABASE_PROJECT_REF`, + `SUPABASE_DB_PASSWORD`, `SUPABASE_DB_URL` and `WIRING_SUPABASE` (the + project URL, the anon key and the service-role key, one document) onto the + environment's secret rung. +- **`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 Supabase through + supabase-js — Auth and the Data API — with the anon key and the visitor's + session, and with the service-role key for the Stripe webhook's sync and + the customer mapping (`utils/supabase/admin.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` → `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_SUPABASE` before + it builds (the URL, the anon key and the Worker's origin are inlined into + the build), pushes the document's service-role key to the Worker as a + Worker secret (`tooling/wire/secrets.mjs`, `wrangler secret bulk`, the + value over stdin), deploys `subscription-payments-web-`, and + smoke-tests it: the pricing page, and `/api/health`, which answers 200 + only when the project is reachable with those keys, the schema is + migrated, and the service-role secret is the project's own. +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 + URL and key): 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 key. + The service-role key is never in a wrangler file: it is a Worker secret. +- Every table in `public` has row-level security. Supabase's Data API + serves `public` to the anon key, which every browser has, so the policies + ARE the access control: a visitor reads the plans (`products`, `prices`), + their own `users` row (and updates it) and their own `subscriptions`; the + user→Stripe-customer map (`customers`) has no policy and is the service + role's alone. Migration `020_row_level_security` fails the deploy if any + table in `public` is without RLS; give every new table RLS and the policies + the app needs in its own migration, and never `FORCE` it. +- 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 the same + SQL in `apps/web/supabase/migrations` for the Supabase CLI's local stack). + +## 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` (the Worker's deploy and its secrets), + `CLOUDFLARE_ACCOUNT_ID`, `SUPABASE_ACCESS_TOKEN` (project create, its Auth + settings, migrations) and `SUPABASE_ORG_ID`. +- **Published by the apply** onto the stage and prod rungs: + `SUPABASE_PROJECT_REF`, `SUPABASE_DB_PASSWORD`, `SUPABASE_DB_URL`, + `WIRING_SUPABASE`. +- **The service-role key** bypasses row-level security. It travels only in + `WIRING_SUPABASE` and reaches the Worker as the Worker secret + `SUPABASE_SERVICE_ROLE_KEY`, set by every deploy; it is never a wrangler + var and never in a client bundle (only server code — the webhook and the + checkout and portal actions — reads it). +- **Worker secrets the owner adds**, because no platform brokers Stripe: + `STRIPE_SECRET_KEY`, `STRIPE_WEBHOOK_SECRET` and `STRIPE_PUBLISHABLE_KEY` + (below). Until they exist the pricing page shows the template's sample + plans with checkout off and a "Connect Stripe" notice, the checkout and + portal actions answer with that notice, and the webhook answers 503. +- 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. Add a webhook endpoint at + `https://subscription-payments-web-.your-workers-subdomain.workers.dev/api/webhooks` + listening to the product, price, checkout-session and + customer-subscription events (`product.*`, `price.*`, + `checkout.session.completed`, `customer.subscription.*`); copy its signing + secret. +2. Set the three Worker secrets: + + ```bash + wrangler secret put STRIPE_SECRET_KEY --name subscription-payments-web- + wrangler secret put STRIPE_WEBHOOK_SECRET --name subscription-payments-web- # the endpoint's signing secret + wrangler secret put STRIPE_PUBLISHABLE_KEY --name subscription-payments-web- # pk_…, public, read per request + ``` + +3. Create the products and prices — after the endpoint exists, because they + reach the database through it: in the dashboard, or + `pnpm --filter @app/web stripe:fixtures` for the template's Hobby and + Freelancer plans, monthly and yearly. +4. Configure the Customer Portal (Stripe → Settings → Billing → Customer + portal). + +Worker secrets survive every later deploy; nothing in CI touches them. The +pricing page shows the synced plans with checkout on from the next request. +Re-running the bootstrap's `02-docs` phase records the change in +[deployment.md](deployment.md). + +## Supabase Auth email + +The supabase root manages three Auth settings and leaves every other one to +the project: the Site URL and the one allowed redirect origin (the +environment's Worker), and whether sign-up needs a confirmed email — +off (`authEmailConfirmation: "false"` in `infra/terraform/supabase/component.yaml`), +because a project without SMTP of its own emails only its organization's +members. Before real users arrive: + +1. Give the project an SMTP server (Supabase dashboard → Authentication → + Emails → SMTP Settings), so confirmation, magic-link and password-reset + emails reach anyone. +2. Set `authEmailConfirmation: "true"` and merge: new sign-ups then confirm + their address first (the account page and the magic link already link + back to the Worker). +3. A custom domain: also change the Site URL and allow-list (the root's + `app_origin`) and `NEXT_PUBLIC_SITE_URL` in `apps/web/wrangler.template.jsonc`. + +OAuth providers (GitHub, Google, …) are dashboard settings of the project; +the sign-in page's OAuth button works once one is enabled there. + +## Verifying the system + +```bash +# the app and its Supabase path on each environment (also recorded, probed, in deployment.md) +curl -s -o /dev/null -w '%{http_code}\n' https://subscription-payments-web-stage.your-workers-subdomain.workers.dev/ +curl -s https://subscription-payments-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 | a new `packages/db/src/migrations/_/up.sql` and its manifest entry (`pnpm --filter @saas/db run manifest:fix` for its checksum) — with RLS and the policies the app needs on any new table — then merge: db-migrate applies it before the app deploys. `pnpm test` fails on a table in `public` without row-level security; regenerate `apps/web/types_db.ts` with the Supabase CLI | +| 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 | +| turn on email confirmation | above, "Supabase Auth email" | +| rotate the service-role key | rotate it in the Supabase dashboard (API keys), then re-run the supabase apply (a merge touching `infra/terraform/supabase`): it republishes `WIRING_SUPABASE`, and the next web deploy pushes the new key | +| serve a custom domain | attach it to the Worker in Cloudflare; change `NEXT_PUBLIC_SITE_URL` in `apps/web/wrangler.template.jsonc` and the Auth origin in the supabase root; add the new webhook URL in Stripe | +| 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 14fecb5..d3e8f93 100644 --- a/apps/web/.dev.vars.example +++ b/apps/web/.dev.vars.example @@ -1,18 +1,23 @@ # Local Worker secrets for `wrangler dev` / `opennextjs-cloudflare preview`. # Copy to .dev.vars (git-ignored); never commit a value. # -# In stage/prod these three are Worker secrets, not wrangler vars: the deploy -# lane sets SUPABASE_SERVICE_ROLE_KEY from the orun secret the `supabase` root -# publishes, and the product sets the two Stripe values once per environment -# (`wrangler secret put STRIPE_SECRET_KEY` / `STRIPE_WEBHOOK_SECRET` on the -# `subscription-payments-web-` Worker, or as orun secrets the deploy lane -# reads). See specs/epics/subscription-payments/design.md. +# The service-role key: server code only (the Stripe webhook's sync, the +# customer mapping, /api/health). In stage and prod every deploy sets it as a +# Worker secret from the Supabase root's wiring document; here it is yours. SUPABASE_SERVICE_ROLE_KEY= -STRIPE_SECRET_KEY= -STRIPE_WEBHOOK_SECRET= - -# The Supabase URL and anon key are wrangler vars (rendered into -# wrangler.jsonc from wiring.fixture.json by `pnpm run wire:fixture`); put -# real values here only to point a local Worker at a real project. +# +# Stripe. Unset, the pricing page shows the template's sample plans with +# checkout off, checkout and the portal answer "Stripe is not connected." and +# the webhook answers 503. In stage and prod these are Worker secrets the +# owner sets once per environment: +# `wrangler secret put --name subscription-payments-web-` +# (README, "Connect Stripe"). +# STRIPE_SECRET_KEY=sk_test_*** +# STRIPE_WEBHOOK_SECRET=whsec_*** +# STRIPE_PUBLISHABLE_KEY=pk_test_*** +# +# The Supabase URL and anon key, and the site's origin, are wrangler vars +# (rendered into wrangler.jsonc, which the build inlines); put real values +# here only to point a local Worker at a real project's server side. # NEXT_PUBLIC_SUPABASE_URL= # NEXT_PUBLIC_SUPABASE_ANON_KEY= diff --git a/apps/web/README.md b/apps/web/README.md index 32b9a83..8e1219f 100644 --- a/apps/web/README.md +++ b/apps/web/README.md @@ -1,261 +1,40 @@ -# Next.js Subscription Payments Starter - - -> [!WARNING] -> This repo has been sunset and replaced by a new template: https://github.com/nextjs/saas-starter - -## Features - -- Secure user management and authentication with [Supabase](https://supabase.io/docs/guides/auth) -- Powerful data access & management tooling on top of PostgreSQL with [Supabase](https://supabase.io/docs/guides/database) -- Integration with [Stripe Checkout](https://stripe.com/docs/payments/checkout) and the [Stripe customer portal](https://stripe.com/docs/billing/subscriptions/customer-portal) -- Automatic syncing of pricing plans and subscription statuses via [Stripe webhooks](https://stripe.com/docs/webhooks) - -## Demo - -- https://subscription-payments.vercel.app/ - -[![Screenshot of demo](./public/demo.png)](https://subscription-payments.vercel.app/) - -## Architecture - -![Architecture diagram](./public/architecture_diagram.png) - -## Step-by-step setup - -When deploying this template, the sequence of steps is important. Follow the steps below in order to get up and running. - -### Initiate Deployment - -#### Vercel Deploy Button - -[![Deploy with Vercel](https://vercel.com/button)](https://vercel.com/new/clone?repository-url=https%3A%2F%2Fgithub.com%2Fvercel%2Fnextjs-subscription-payments&env=NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY,STRIPE_SECRET_KEY&envDescription=Enter%20your%20Stripe%20API%20keys.&envLink=https%3A%2F%2Fdashboard.stripe.com%2Fapikeys&project-name=nextjs-subscription-payments&repository-name=nextjs-subscription-payments&integration-ids=oac_VqOgBHqhEoFTPzGkPd7L0iH6&external-id=https%3A%2F%2Fgithub.com%2Fvercel%2Fnextjs-subscription-payments%2Ftree%2Fmain) - -The Vercel Deployment will create a new repository with this template on your GitHub account and guide you through a new Supabase project creation. The [Supabase Vercel Deploy Integration](https://vercel.com/integrations/supabase) will set up the necessary Supabase environment variables and run the [SQL migrations](./supabase/migrations/20230530034630_init.sql) to set up the Database schema on your account. You can inspect the created tables in your project's [Table editor](https://app.supabase.com/project/_/editor). - -Should the automatic setup fail, please [create a Supabase account](https://app.supabase.com/projects), and a new project if needed. In your project, navigate to the [SQL editor](https://app.supabase.com/project/_/sql) and select the "Stripe Subscriptions" starter template from the Quick start section. - -### Configure Auth - -Follow [this guide](https://supabase.com/docs/guides/auth/social-login/auth-github) to set up an OAuth app with GitHub and configure Supabase to use it as an auth provider. - -In your Supabase project, navigate to [auth > URL configuration](https://app.supabase.com/project/_/auth/url-configuration) and set your main production URL (e.g. https://your-deployment-url.vercel.app) as the site url. - -Next, in your Vercel deployment settings, add a new **Production** environment variable called `NEXT_PUBLIC_SITE_URL` and set it to the same URL. Make sure to deselect preview and development environments to make sure that preview branches and local development work correctly. - -#### [Optional] - Set up redirect wildcards for deploy previews (not needed if you installed via the Deploy Button) - -If you've deployed this template via the "Deploy to Vercel" button above, you can skip this step. The Supabase Vercel Integration will have set redirect wildcards for you. You can check this by going to your Supabase [auth settings](https://app.supabase.com/project/_/auth/url-configuration) and you should see a list of redirects under "Redirect URLs". - -Otherwise, for auth redirects (email confirmations, magic links, OAuth providers) to work correctly in deploy previews, navigate to the [auth settings](https://app.supabase.com/project/_/auth/url-configuration) and add the following wildcard URL to "Redirect URLs": `https://*-username.vercel.app/**`. You can read more about redirect wildcard patterns in the [docs](https://supabase.com/docs/guides/auth#redirect-urls-and-wildcards). - -If you've deployed this template via the "Deploy to Vercel" button above, you can skip this step. The Supabase Vercel Integration will have run database migrations for you. You can check this by going to [the Table Editor for your Supabase project](https://supabase.com/dashboard/project/_/editor), and confirming there are tables with seed data. - -Otherwise, navigate to the [SQL Editor](https://supabase.com/dashboard/project/_/sql/new), paste the contents of [the Supabase `schema.sql` file](./schema.sql), and click RUN to initialize the database. - -#### [Maybe Optional] - Set up Supabase environment variables (not needed if you installed via the Deploy Button) - -If you've deployed this template via the "Deploy to Vercel" button above, you can skip this step. The Supabase Vercel Integration will have set your environment variables for you. You can check this by going to your Vercel project settings, and clicking on 'Environment variables', there will be a list of environment variables with the Supabase icon displayed next to them. - -Otherwise navigate to the [API settings](https://app.supabase.com/project/_/settings/api) and paste them into the Vercel deployment interface. Copy project API keys and paste into the `NEXT_PUBLIC_SUPABASE_ANON_KEY` and `SUPABASE_SERVICE_ROLE_KEY` fields, and copy the project URL and paste to Vercel as `NEXT_PUBLIC_SUPABASE_URL`. - -Congrats, this completes the Supabase setup, almost there! - -### Configure Stripe - -Next, we'll need to configure [Stripe](https://stripe.com/) to handle test payments. If you don't already have a Stripe account, create one now. - -For the following steps, make sure you have the ["Test Mode" toggle](https://stripe.com/docs/testing) switched on. - -#### Create a Webhook - -We need to create a webhook in the `Developers` section of Stripe. Pictured in the architecture diagram above, this webhook is the piece that connects Stripe to your Vercel Serverless Functions. - -1. Click the "Add Endpoint" button on the [test Endpoints page](https://dashboard.stripe.com/test/webhooks). -1. Enter your production deployment URL followed by `/api/webhooks` for the endpoint URL. (e.g. `https://your-deployment-url.vercel.app/api/webhooks`) -1. Click `Select events` under the `Select events to listen to` heading. -1. Click `Select all events` in the `Select events to send` section. -1. Copy `Signing secret` as we'll need that in the next step (e.g `whsec_xxx`) (/!\ be careful not to copy the webook id we_xxxx). -1. In addition to the `NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY` and the `STRIPE_SECRET_KEY` we've set earlier during deployment, we need to add the webhook secret as `STRIPE_WEBHOOK_SECRET` env var. - -#### Redeploy with new env vars - -For the newly set environment variables to take effect and everything to work together correctly, we need to redeploy our app in Vercel. In your Vercel Dashboard, navigate to deployments, click the overflow menu button and select "Redeploy" (do NOT enable the "Use existing Build Cache" option). Once Vercel has rebuilt and redeployed your app, you're ready to set up your products and prices. - -#### Create product and pricing information - -Your application's webhook listens for product updates on Stripe and automatically propagates them to your Supabase database. So with your webhook listener running, you can now create your product and pricing information in the [Stripe Dashboard](https://dashboard.stripe.com/test/products). - -Stripe Checkout currently supports pricing that bills a predefined amount at a specific interval. More complex plans (e.g., different pricing tiers or seats) are not yet supported. - -For example, you can create business models with different pricing tiers, e.g.: - -- Product 1: Hobby - - Price 1: 10 USD per month - - Price 2: 100 USD per year -- Product 2: Freelancer - - Price 1: 20 USD per month - - Price 2: 200 USD per year - -Optionally, to speed up the setup, we have added a [fixtures file](fixtures/stripe-fixtures.json) to bootstrap test product and pricing data in your Stripe account. The [Stripe CLI](https://stripe.com/docs/stripe-cli#install) `fixtures` command executes a series of API requests defined in this JSON file. Simply run `stripe fixtures fixtures/stripe-fixtures.json`. - -**Important:** Make sure that you've configured your Stripe webhook correctly and redeployed with all needed environment variables. - -#### Configure the Stripe customer portal - -1. Set your custom branding in the [settings](https://dashboard.stripe.com/settings/branding) -1. Configure the Customer Portal [settings](https://dashboard.stripe.com/test/settings/billing/portal) -1. Toggle on "Allow customers to update their payment methods" -1. Toggle on "Allow customers to update subscriptions" -1. Toggle on "Allow customers to cancel subscriptions" -1. Add the products and prices that you want -1. Set up the required business information and links - -### That's it - -I know, that was quite a lot to get through, but it's worth it. You're now ready to earn recurring revenue from your customers. 🥳 - -## Develop locally - -If you haven't already done so, clone your Github repository to your local machine. - -### Install dependencies - -Ensure you have [pnpm](https://pnpm.io/installation) installed and run: - -```bash -pnpm install -``` - -Next, use the [Vercel CLI](https://vercel.com/docs/cli) to link your project: - -```bash -pnpm dlx vercel login -pnpm dlx vercel link -``` - -`pnpm dlx` runs a package from the registry, without installing it as a dependency. Alternatively, you can install these packages globally, and drop the `pnpm dlx` part. - -If you don't intend to use a local Supabase instance for development and testing, you can use the Vercel CLI to download the development env vars: - -```bash -pnpm dlx vercel env pull .env.local -``` - -Running this command will create a new `.env.local` file in your project folder. For security purposes, you will need to set the `SUPABASE_SERVICE_ROLE_KEY` manually from your [Supabase dashboard](https://app.supabase.io/) (`Settings > API`). If you are not using a local Supabase instance, you should also change the `--local` flag to `--linked' or '--project-id ' in the `supabase:generate-types` script in `package.json`.(see -> [https://supabase.com/docs/reference/cli/supabase-gen-types-typescript]) - -### Local development with Supabase - -It's highly recommended to use a local Supabase instance for development and testing. We have provided a set of custom commands for this in `package.json`. - -First, you will need to install [Docker](https://www.docker.com/get-started/). You should also copy or rename: - -- `.env.local.example` -> `.env.local` -- `.env.example` -> `.env` - -Next, run the following command to start a local Supabase instance and run the migrations to set up the database schema: - -```bash -pnpm supabase:start -``` - -The terminal output will provide you with URLs to access the different services within the Supabase stack. The Supabase Studio is where you can make changes to your local database instance. - -Copy the value for the `service_role_key` and paste it as the value for the `SUPABASE_SERVICE_ROLE_KEY` in your `.env.local` file. - -You can print out these URLs at any time with the following command: - -```bash -pnpm supabase:status -``` - -To link your local Supabase instance to your project, run the following command, navigate to the Supabase project you created above, and enter your database password. - -```bash -pnpm supabase:link -``` - -If you need to reset your database password, head over to [your database settings](https://supabase.com/dashboard/project/_/settings/database) and click "Reset database password", and this time copy it across to a password manager! 😄 - -🚧 Warning: This links our Local Development instance to the project we are using for `production`. Currently, it only has test records, but once it has customer data, we recommend using [Branching](https://supabase.com/docs/guides/platform/branching) or manually creating a separate `preview` or `staging` environment, to ensure your customer's data is not used locally, and schema changes/migrations can be thoroughly tested before shipping to `production`. - -Once you've linked your project, you can pull down any schema changes you made in your remote database with: - -```bash -pnpm supabase:pull -``` - -You can seed your local database with any data you added in your remote database with: - -```bash -pnpm supabase:generate-seed -pnpm supabase:reset -``` - -🚧 Warning: this is seeding data from the `production` database. Currently, this only contains test data, but we recommend using [Branching](https://supabase.com/docs/guides/platform/branching) or manually setting up a `preview` or `staging` environment once this contains real customer data. - -You can make changes to the database schema in your local Supabase Studio and run the following command to generate TypeScript types to match your schema: - -```bash -pnpm supabase:generate-types -``` - -You can also automatically generate a migration file with all the changes you've made to your local database schema with the following command: - -```bash -pnpm supabase:generate-migration -``` - -And push those changes to your remote database with: - -```bash -pnpm supabase:push -``` - -Remember to test your changes thoroughly in your `local` and `staging` or `preview` environments before deploying them to `production`! - -### Use the Stripe CLI to test webhooks - -Use the [Stripe CLI](https://stripe.com/docs/stripe-cli) to [login to your Stripe account](https://stripe.com/docs/stripe-cli#login-account): - -```bash -pnpm stripe:login -``` - -This will print a URL to navigate to in your browser and provide access to your Stripe account. - -Next, start local webhook forwarding: - -```bash -pnpm stripe:listen -``` - -Running this Stripe command will print a webhook secret (such as, `whsec_***`) to the console. Set `STRIPE_WEBHOOK_SECRET` to this value in your `.env.local` file. If you haven't already, you should also set `NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY` and `STRIPE_SECRET_KEY` in your `.env.local` file using the **test mode**(!) keys from your Stripe dashboard. - -### Run the Next.js client - -In a separate terminal, run the following command to start the development server: - -```bash -pnpm dev -``` - -Note that webhook forwarding and the development server must be running concurrently in two separate terminals for the application to work correctly. - -Finally, navigate to [http://localhost:3000](http://localhost:3000) in your browser to see the application rendered. - -## Going live - -### Archive testing products - -Archive all test mode Stripe products before going live. Before creating your live mode products, make sure to follow the steps below to set up your live mode env vars and webhooks. - -### Configure production environment variables - -To run the project in live mode and process payments with Stripe, switch Stripe from "test mode" to "production mode." Your Stripe API keys will be different in production mode, and you will have to create a separate production mode webhook. Copy these values and paste them into Vercel, replacing the test mode values. - -### Redeploy - -Afterward, you will need to rebuild your production deployment for the changes to take effect. Within your project Dashboard, navigate to the "Deployments" tab, select the most recent deployment, click the overflow menu button (next to the "Visit" button) and select "Redeploy" (do NOT enable the "Use existing Build Cache" option). - -To verify you are running in production mode, test checking out with the [Stripe test card](https://stripe.com/docs/testing). The test card should not work. +# apps/web — the app + +A subscription site from Vercel's +[Next.js Subscription Payments Starter](https://github.com/vercel/nextjs-subscription-payments) +(MIT, see `LICENSE`; its demo is https://subscription-payments.vercel.app/), +running on Cloudflare Workers + Static Assets: + +- Secure user management and authentication with Supabase Auth — password, + magic link and OAuth sign-in, sign-up, password reset — with cookie + sessions through `@supabase/ssr` and a proxy that refreshes them +- Pricing (`/`) from the `products` and `prices` tables, which Stripe's + webhooks keep in sync — or, until Stripe is connected, the template's + sample plans with checkout off and a notice saying so +- Stripe Checkout to subscribe and the Stripe Customer Portal to manage, + from the account page (`/account`) +- The Stripe webhook (`/api/webhooks`), which syncs products, prices and + subscription statuses — and answers 503 until Stripe is connected +- `/api/health`, which answers 200 only when the Supabase project is + reachable with the keys the Worker was built with, migrated, and its + service-role key valid + +The product's name is `utils/site.ts`. The Supabase URL, the anon key and +the site's origin come from `wrangler.jsonc`'s vars, which `next build` +inlines (`next.config.mjs`); the service-role key is a Worker secret, read +only by server code (`utils/supabase/admin.ts`); the Stripe client exists +only once `STRIPE_SECRET_KEY` does (`utils/stripe/config.ts`). + +```bash +pnpm dev # next dev on http://localhost:3000, with .env.local +pnpm build # next build + opennextjs-cloudflare build → .open-next/ +pnpm preview # wrangler dev over the built Worker, with .dev.vars +pnpm supabase:start # the Supabase CLI's local stack (supabase/migrations, supabase/config.toml) +pnpm stripe:listen # forward Stripe's events to localhost:3000/api/webhooks +pnpm stripe:fixtures # the template's plans in your Stripe account (fixtures/stripe-fixtures.json) +``` + +How it runs locally, how it deploys — per environment, after the Supabase +project and the migrations, on merge to `main` — how to connect Stripe and +how to configure Supabase Auth's email 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..7e5fd19 --- /dev/null +++ b/apps/web/app/api/health/route.ts @@ -0,0 +1,76 @@ +import { createClient } from '@supabase/supabase-js'; + +// Not upstream's: the deploy's smoke check and the bootstrap's probe read +// this. A pricing page that renders proves the Worker deployed; this proves +// what that page does not — the Worker reaches its environment's Supabase +// project with the URL and anon key it was built with, the schema db-migrate +// applies is there (the `products` table, which the anon key may read), and +// the service-role key the deploy pushed as a Worker secret is the project's +// own (only a service-role key may list Auth's users). The Stripe webhook's +// sync and the customer mapping use that key; nothing else here needs it. +export const dynamic = 'force-dynamic'; + +type Health = { + ok: boolean; + supabase: 'reachable' | 'unreachable' | 'unconfigured'; + schema?: 'migrated' | 'missing' | 'unknown'; + serviceRole?: 'valid' | 'invalid' | 'missing'; +}; + +const options = { + auth: { persistSession: false, autoRefreshToken: false } +} as const; + +function answer(health: Health) { + return Response.json(health, { + status: health.ok ? 200 : 503, + headers: { 'cache-control': 'no-store' } + }); +} + +export async function GET() { + const url = process.env.NEXT_PUBLIC_SUPABASE_URL; + const anonKey = process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY; + const serviceRoleKey = process.env.SUPABASE_SERVICE_ROLE_KEY; + if (!url || !anonKey) { + return answer({ ok: false, supabase: 'unconfigured' }); + } + + try { + const anon = createClient(url, anonKey, options); + const { error, status } = await anon.from('products').select('id').limit(1); + if (error && status === 0) { + console.error('health: Supabase unreachable', error.message); + return answer({ ok: false, supabase: 'unreachable' }); + } + // PostgREST answers 404 (PGRST205, or 42P01 from Postgres) for a table + // its schema cache does not have: the migrations have not run. + const schema = !error + ? 'migrated' + : status === 404 || error.code === 'PGRST205' || error.code === '42P01' + ? 'missing' + : 'unknown'; + if (error) console.error('health: products query failed', status, error.message); + + let serviceRole: Health['serviceRole'] = 'missing'; + if (serviceRoleKey) { + const admin = createClient(url, serviceRoleKey, options); + const { error: adminError } = await admin.auth.admin.listUsers({ + page: 1, + perPage: 1 + }); + serviceRole = adminError ? 'invalid' : 'valid'; + if (adminError) console.error('health: service-role check failed', adminError.message); + } + + return answer({ + ok: schema === 'migrated' && serviceRole === 'valid', + supabase: 'reachable', + schema, + serviceRole + }); + } catch (error) { + console.error('health: Supabase check failed', error); + return answer({ ok: false, supabase: 'unreachable' }); + } +} diff --git a/apps/web/app/api/webhooks/route.ts b/apps/web/app/api/webhooks/route.ts index f88b9fb..5286fde 100644 --- a/apps/web/app/api/webhooks/route.ts +++ b/apps/web/app/api/webhooks/route.ts @@ -1,5 +1,10 @@ import Stripe from 'stripe'; -import { stripe } from '@/utils/stripe/config'; +import { + getStripe, + isStripeConnected, + stripeWebhookSecret, + STRIPE_NOT_CONNECTED +} from '@/utils/stripe/config'; import { upsertProductRecord, upsertPriceRecord, @@ -22,15 +27,22 @@ const relevantEvents = new Set([ ]); export async function POST(req: Request) { + // Until the owner connects Stripe (the secret key and this endpoint's + // signing secret, README "Connect Stripe") there is nothing to verify a + // delivery against: say so with a 503, which Stripe retries, rather than a + // 500, or a 400 that reads as a forged event. + const webhookSecret = stripeWebhookSecret(); + if (!isStripeConnected() || !webhookSecret) { + return Response.json({ error: STRIPE_NOT_CONNECTED }, { status: 503 }); + } + const body = await req.text(); const sig = req.headers.get('stripe-signature') as string; - const webhookSecret = process.env.STRIPE_WEBHOOK_SECRET; let event: Stripe.Event; try { - if (!sig || !webhookSecret) - return new Response('Webhook secret not found.', { status: 400 }); - event = await stripe.webhooks.constructEventAsync( + if (!sig) return new Response('Webhook secret not found.', { status: 400 }); + event = await getStripe().webhooks.constructEventAsync( body, sig, webhookSecret, diff --git a/apps/web/app/layout.tsx b/apps/web/app/layout.tsx index 98b7ff0..815283b 100644 --- a/apps/web/app/layout.tsx +++ b/apps/web/app/layout.tsx @@ -4,9 +4,10 @@ import Navbar from '@/components/ui/Navbar'; import { Toaster } from '@/components/ui/Toasts/toaster'; import { PropsWithChildren, Suspense } from 'react'; import { getURL } from '@/utils/helpers'; +import { SITE_NAME } from '@/utils/site'; import 'styles/main.css'; -const title = 'Next.js Subscription Starter'; +const title = SITE_NAME; const description = 'Brought to you by Vercel, Stripe, and Supabase.'; export const metadata: Metadata = { diff --git a/apps/web/app/page.tsx b/apps/web/app/page.tsx index 16ad2e6..6e1bae5 100644 --- a/apps/web/app/page.tsx +++ b/apps/web/app/page.tsx @@ -5,6 +5,11 @@ import { getSubscription, getUser } from '@/utils/supabase/queries'; +import { + isCheckoutEnabled, + stripePublishableKey +} from '@/utils/stripe/config'; +import { SAMPLE_PLANS } from '@/utils/stripe/sample-plans'; export default async function PricingPage() { const supabase = await createClient(); @@ -14,11 +19,24 @@ export default async function PricingPage() { getSubscription(supabase) ]); + // Without Stripe the page still shows plans — what the database holds, or, + // on a fresh deployment whose webhook has synced nothing, the template's + // sample plans — with checkout off and a notice saying why + // (utils/stripe/config.ts). With Stripe connected it is upstream's page. + const checkoutEnabled = isCheckoutEnabled(); + const synced = products ?? []; + const sample = !checkoutEnabled && synced.length === 0; + return ( ); } diff --git a/apps/web/component.yaml b/apps/web/component.yaml index 5416f13..e021721 100644 --- a/apps/web/component.yaml +++ b/apps/web/component.yaml @@ -12,38 +12,47 @@ spec: # Its own lane per environment: the Next.js build is the longest job in the # plan, and a shared lane would wait on it. lane: isolated - # The Supabase project must exist before this deploys: its URL and anon key - # are read at build time (NEXT_PUBLIC_* are inlined) and rendered into - # wrangler vars for the Worker. The schema must be applied too: the pricing - # page reads products/prices and the webhook writes them. + # INFRA BEFORE APP, ENFORCED ON MAIN. A merge to main converges the whole + # product in one run: the Supabase project, then the migrations, then this + # Worker. Its deploy reads the project's URL and keys + # (WIRING_SUPABASE_, rendered into wrangler.jsonc and pushed as a + # Worker secret) and needs the schema applied, and a job resolves its + # secrets when it STARTS — so it waits on both, `mode: enforced`, and the + # document the supabase apply lease-published is there. A pull request + # deploys nothing, so nothing on one waits: every edge is advisory there. dependsOn: - component: supabase + mode: enforced + modeRules: + - mode: advisory + when: + triggerRef: github-pull-request - component: db-migrate - secretEnv: - # Build time, under the template's own names (`next build` inlines them). - NEXT_PUBLIC_SUPABASE_URL: "secret://subscription-payments/subscription-payments/{{ .environment }}/SUPABASE_URL" - NEXT_PUBLIC_SUPABASE_ANON_KEY: "secret://subscription-payments/subscription-payments/{{ .environment }}/SUPABASE_ANON_KEY" - # Server only, never inlined into a client bundle: the admin client in - # utils/supabase/admin.ts (webhook upserts, customer mapping) reads it as a - # Worker secret; declaring it here lets the deploy lane set it. The two - # Stripe secrets (STRIPE_SECRET_KEY, STRIPE_WEBHOOK_SECRET) are the - # product's own and are set once per environment — see .dev.vars.example. - SUPABASE_SERVICE_ROLE_KEY: "secret://subscription-payments/subscription-payments/{{ .environment }}/SUPABASE_SERVICE_ROLE_KEY" - # The wiring document the wrangler template is rendered from per environment. - WIRING_SUPABASE_STAGE: "secret://subscription-payments/subscription-payments/stage/WIRING_SUPABASE" - WIRING_SUPABASE_PROD: "secret://subscription-payments/subscription-payments/prod/WIRING_SUPABASE" + mode: enforced + modeRules: + - mode: advisory + when: + triggerRef: github-pull-request subscribe: environments: + # dev verifies with the committed fixture render and reads no wiring. - name: dev profile: verify + # Each deployed environment reads ITS OWN wiring document (Lumen's + # scoping): stage never waits on prod's project to exist, and dev + # resolves no credential it could never use. - name: stage profile: verify + secretEnv: + WIRING_SUPABASE_STAGE: "secret://subscription-payments/subscription-payments/stage/WIRING_SUPABASE" profileRules: - profile: deploy when: triggerRef: github-push-main - name: prod profile: verify + secretEnv: + WIRING_SUPABASE_PROD: "secret://subscription-payments/subscription-payments/prod/WIRING_SUPABASE" profileRules: - profile: deploy when: @@ -72,20 +81,24 @@ spec: workersDevSubdomain: your-workers-subdomain installCommand: pnpm install --frozen-lockfile - # Render this environment's wrangler config from the wiring document, then - # build (the verify lane already rendered from the fixture through - # `wire:fixture`; a deploy lane re-renders with the real values). The - # site's public origin — Stripe success/cancel URLs, auth email redirects, - # metadataBase — is the environment's Worker URL (`getURL()` in - # utils/helpers.ts reads NEXT_PUBLIC_SITE_URL); override it for a custom - # domain. NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY is the product's public Stripe - # key, a build-time value to export here once it has one (empty is a valid - # build: Checkout is simply unreachable until it is set). - buildCommand: node ../../tooling/wire/live.mjs --template wrangler.template.jsonc --out wrangler.jsonc --components supabase --env "${ORUN_ENVIRONMENT}" && NEXT_PUBLIC_SITE_URL="https://subscription-payments-web-${ORUN_ENVIRONMENT}.${WORKERS_DEV_SUBDOMAIN}.workers.dev" pnpm exec turbo run build --filter=@app/web + # wrangler.jsonc is COMMITTED — the fixture render, so the composition's + # structure check (`test -f wrangler.jsonc`, before the build, in a fresh + # checkout) passes. Stage and prod re-render it here, in their own job + # tree, from this environment's wiring document — the project URL, the + # anon key and the Worker's origin, which `next build` inlines + # (next.config.mjs) — then build, then hand the document's service-role + # key to the Worker as a SECRET (tooling/wire/secrets.mjs: `wrangler + # secret bulk`, the value over stdin). Only the deploy lane holds a + # Cloudflare credential, so a verify lane renders and builds the same and + # pushes nothing. dev verifies with the fixture and has no wiring. + buildCommand: if [ "${ORUN_ENVIRONMENT}" != dev ]; then node ../../tooling/wire/live.mjs --template wrangler.template.jsonc --out wrangler.jsonc --components supabase --env "${ORUN_ENVIRONMENT}"; fi && pnpm exec turbo run build --filter=@app/web && if [ "${ORUN_ENVIRONMENT}" != dev ]; then node ../../tooling/wire/secrets.mjs --component supabase --env "${ORUN_ENVIRONMENT}" --secret SUPABASE_SERVICE_ROLE_KEY=supabase_service_role_key --worker "subscription-payments-web-${ORUN_ENVIRONMENT}" --config wrangler.jsonc; fi - # Smoke: the pricing page renders (with or without products) and the - # navbar carries its link. - smokeCommand: "html=$(curl -sfL \"${DEPLOYED_URL}/\") && echo \"${html}\" | grep -q 'Pricing'" + # Smoke: the pricing page renders (its navbar carries the Pricing link, + # with or without plans), and /api/health answers ok — the + # Supabase project reachable with the keys the Worker was built with, the + # schema migrated, and the service-role secret the project's own. Each + # response is buffered before grep so an early match cannot SIGPIPE curl. + smokeCommand: "html=$(curl -sfL \"${DEPLOYED_URL}/\") && echo \"${html}\" | grep -q 'Pricing' && health=$(curl -sf \"${DEPLOYED_URL}/api/health\") && echo \"${health}\" | grep -q '\"ok\":true'" labels: team: platform layer: delivery diff --git a/apps/web/components/ui/Footer/Footer.tsx b/apps/web/components/ui/Footer/Footer.tsx index 1f04056..5f25438 100644 --- a/apps/web/components/ui/Footer/Footer.tsx +++ b/apps/web/components/ui/Footer/Footer.tsx @@ -2,6 +2,7 @@ import Link from 'next/link'; import Logo from '@/components/icons/Logo'; import GitHub from '@/components/icons/GitHub'; +import { SITE_NAME } from '@/utils/site'; export default function Footer() { return ( @@ -15,7 +16,7 @@ export default function Footer() { - ACME + {SITE_NAME}
@@ -93,7 +94,7 @@ export default function Footer() {
- © {new Date().getFullYear()} ACME, Inc. All rights reserved. + © {new Date().getFullYear()} {SITE_NAME}, Inc. All rights reserved.
diff --git a/apps/web/components/ui/Pricing/Pricing.tsx b/apps/web/components/ui/Pricing/Pricing.tsx index 327e759..c468050 100644 --- a/apps/web/components/ui/Pricing/Pricing.tsx +++ b/apps/web/components/ui/Pricing/Pricing.tsx @@ -28,11 +28,23 @@ interface Props { user: User | null | undefined; products: ProductWithPrices[]; subscription: SubscriptionWithProduct | null; + // Whether Stripe is connected (app/page.tsx, utils/stripe/config.ts): its + // publishable key comes from the server, so connecting needs no rebuild. + checkout: { + enabled: boolean; + publishableKey?: string; + samplePlans: boolean; + }; } type BillingInterval = 'lifetime' | 'year' | 'month'; -export default function Pricing({ user, products, subscription }: Props) { +export default function Pricing({ + user, + products, + subscription, + checkout +}: Props) { const intervals = Array.from( new Set( products.flatMap((product) => @@ -47,6 +59,7 @@ export default function Pricing({ user, products, subscription }: Props) { const currentPath = usePathname(); const handleStripeCheckout = async (price: Price) => { + if (!checkout.enabled) return; setPriceIdLoading(price.id); if (!user) { @@ -75,7 +88,7 @@ export default function Pricing({ user, products, subscription }: Props) { ); } - const stripe = await getStripe(); + const stripe = await getStripe(checkout.publishableKey); stripe?.redirectToCheckout({ sessionId }); setPriceIdLoading(undefined); @@ -114,6 +127,9 @@ export default function Pricing({ user, products, subscription }: Props) { Start building for free, then add a site plan to go live. Account plans unlock additional features.

+ {!checkout.enabled && ( + + )}
{intervals.includes('month') && (