diff --git a/apps/web/component.yaml b/apps/web/component.yaml index e7163c0..79bf992 100644 --- a/apps/web/component.yaml +++ b/apps/web/component.yaml @@ -14,6 +14,27 @@ spec: # Its own lane per environment: the framework build is the longest job in # the plan, and a shared lane would wait on it. lane: isolated + # INFRA BEFORE APP. The Worker's config carries its project's URL and anon + # key, rendered in the build from the wiring document the `supabase` root + # lease-publishes after its apply, and its server reads the tables + # db-migrate creates in that project. A job resolves its secrets when it + # STARTS, so on a merge to main this deploy waits for both (enforced) — one + # convergence runs supabase → db-migrate → web per environment, and the + # document, the key and the schema are there. A pull request deploys + # nothing, so nothing on one waits (advisory). + dependsOn: + - component: supabase + mode: enforced + modeRules: + - mode: advisory + when: + triggerRef: github-pull-request + - component: db-migrate + mode: enforced + modeRules: + - mode: advisory + when: + triggerRef: github-pull-request # The project this environment talks to: its URL and anon key, in the wiring # document the `supabase` Terraform root lease-publishes after its apply. # Rendered into wrangler.jsonc by the build (and inlined into the bundle), diff --git a/infra/db-migrate/component.yaml b/infra/db-migrate/component.yaml new file mode 100644 index 0000000..bdb6b07 --- /dev/null +++ b/infra/db-migrate/component.yaml @@ -0,0 +1,68 @@ +apiVersion: sourceplane.io/v1 +kind: Component +metadata: + name: db-migrate + description: Applies the SaaS schema (packages/db's migrations) to the stage and prod Supabase projects + labels: + domain: infra + scope: database + team: platform + layer: data + +spec: + type: db-migrate + lifecycle: production + owner: platform + domain: infra + + # THE SCHEMA BETWEEN THE PROJECT AND THE APP. Migrations reach the project + # the `supabase` component creates through the Management API, with the + # project ref and credentials that component lease-publishes after its + # apply — and a job resolves its secrets when it STARTS, so on a merge to + # main this waits for that environment's apply (enforced). apps/web waits on + # this the same way, so one convergence runs supabase → db-migrate → web per + # environment. A pull request applies nothing (this plans offline there), so + # nothing on one waits (advisory). `db` is the package this builds and runs; + # a change to it re-plans this. + dependsOn: + - component: db + - component: supabase + mode: enforced + modeRules: + - mode: advisory + when: + triggerRef: github-pull-request + + path: packages/db/src/migrations + + parameters: + nodeVersion: "22" + pnpmVersion: "10.12.1" + owner: sourceplane + repo: sveltekit-saas + + # Everything the runner needs, all resolved from orun secrets: a short-lived + # Management-API token minted fresh per run from the Supabase integration + # (management-access template), and the project ref and its database + # credentials, which the `supabase` component lease-publishes. + secretEnv: + SUPABASE_ACCESS_TOKEN: "secret://sveltekit-saas/sveltekit-saas/{{ .environment }}/SUPABASE_ACCESS_TOKEN" + SUPABASE_PROJECT_REF: "secret://sveltekit-saas/sveltekit-saas/{{ .environment }}/SUPABASE_PROJECT_REF" + SUPABASE_DB_PASSWORD: "secret://sveltekit-saas/sveltekit-saas/{{ .environment }}/SUPABASE_DB_PASSWORD" + SUPABASE_DB_URL: "secret://sveltekit-saas/sveltekit-saas/{{ .environment }}/SUPABASE_DB_URL" + + subscribe: + environments: + - name: stage + profile: plan + profileRules: + - profile: apply + when: + triggerRef: github-push-main + + - name: prod + profile: plan + profileRules: + - profile: apply + when: + triggerRef: github-push-main diff --git a/infra/terraform/supabase/component.yaml b/infra/terraform/supabase/component.yaml new file mode 100644 index 0000000..9f87215 --- /dev/null +++ b/infra/terraform/supabase/component.yaml @@ -0,0 +1,70 @@ +apiVersion: sourceplane.io/v1 +kind: Component + +metadata: + name: supabase + description: Provisions Supabase projects for stage and prod, points their Auth at the app, and wires the URL and keys into orun secrets + labels: + domain: infra + scope: database + +spec: + type: terraform + lifecycle: production + owner: platform + domain: infra + + parameters: + orgName: sourceplane + stackName: supabase + terraformDir: terraform + terraformVersion: "1.15.3" + # Supabase region is surfaced to Terraform as TF_VAR_supabaseRegion by the + # terraform composition's parameter→TF_VAR loop. The org id is NOT committed + # here: it is account-specific and injected as TF_VAR_supabaseOrgId from the + # SUPABASE_ORG_ID CI secret (see .github/workflows/ci.yml). Keeping it out of + # parameters also prevents the param→TF_VAR loop from overriding the secret. + supabaseRegion: ap-southeast-1 + # The app's Worker, which Auth's Site URL and redirect allow-list name: + # -web- on this workers.dev subdomain — the same value + # apps/web/component.yaml carries (TF_VAR_workersDevSubdomain). + workersDevSubdomain: your-workers-subdomain + # "false": sign-up signs the user straight in, because a project without + # SMTP of its own emails only its organization's members. "true" once the + # project sends email (the product's README, "Email"). + authEmailConfirmation: "false" + # SEC-JOB: post-apply, these outputs are queued on the runner's sink and + # lease-published onto the project/{{env}} rung by the runner. The + # project's three database credentials (db-migrate reads them); + # WIRING_SUPABASE — the project URL and the publishable (anon) key, the + # document the app's build renders into its config; and the service-role + # key, which the app's server uses where upstream does (the contact form, + # Stripe customers, account deletion) and which its deploy lane — that + # environment's only — hands the Worker as a secret. + secretOutputs: "SUPABASE_PROJECT_REF=project_ref,SUPABASE_DB_PASSWORD=database_password,SUPABASE_DB_URL=connection_uri,WIRING_SUPABASE=wiring,SUPABASE_SERVICE_ROLE_KEY=service_role_key" + + # Both values resolve from orun secrets (project rung, brokered from the + # Supabase integration): a short-lived Management-API access token minted + # fresh per run (management-access template — the provider reads + # SUPABASE_ACCESS_TOKEN from env natively), and the org id as a non-secret + # connection fact (org-id template) surfaced straight to Terraform. The + # SUPABASE_ORG_ID CI secret and its TF_VAR mapping are retired. + secretEnv: + SUPABASE_ACCESS_TOKEN: "secret://sveltekit-saas/sveltekit-saas/{{ .environment }}/SUPABASE_ACCESS_TOKEN" + TF_VAR_supabaseOrgId: "secret://sveltekit-saas/sveltekit-saas/{{ .environment }}/SUPABASE_ORG_ID" + + subscribe: + environments: + - name: stage + profile: plan-only + profileRules: + - profile: apply + when: + triggerRef: github-push-main + + - name: prod + profile: plan-only + profileRules: + - profile: apply + when: + triggerRef: github-push-main diff --git a/infra/terraform/supabase/terraform/.terraform.lock.hcl b/infra/terraform/supabase/terraform/.terraform.lock.hcl new file mode 100644 index 0000000..5b4468d --- /dev/null +++ b/infra/terraform/supabase/terraform/.terraform.lock.hcl @@ -0,0 +1,73 @@ +# This file is maintained automatically by "terraform init". +# Manual edits may be lost in future updates. + +provider "registry.terraform.io/hashicorp/external" { + version = "2.4.0" + constraints = "~> 2.3" + hashes = [ + "h1:AmY6ZeIvqoTT5ZjzD+P49PeQH6Va1QLMkX+7MUQfYoA=", + "h1:K0eLC86zbhVoyS4THmY00KJZKAQORuz6dt9Ro3xo/wA=", + "h1:gXyK3ZkweDqkwEV9waEDWpljUY4yZXi/nRUSEuJn83k=", + "zh:0772afb42b658468ac5e15df33bf2080456f8f0b8ab163bfe9c50d2b2ea02135", + "zh:0ac31a9aaa43dfcff5944b791596cdc94e153348e4bb4642282d034dff548134", + "zh:32d8492b1bdcc956ca3c6d00c6392d0a83942ff11d4820c7ee63ca6796e06950", + "zh:3c0482e894429f528ce6655a76ab0d8a9f7c0dacc6c828865e1515d4a7dbb852", + "zh:61e68100b4db2f930b31491f23c602126382fd5e51252be1b551f0e17f8ddbee", + "zh:6d60f615a0ad85eb962c9eb94f25e3eba7a72684ce276ba5dfb23f36b295a8f8", + "zh:78d5eefdd9e494defcb3c68d282b8f96630502cac21d1ea161f53cfe9bb483b3", + "zh:9ced2745eb5f1346203027d2dd7bf856ad1d279a25730ff7dbc6eec187aaca0c", + "zh:a8378558a177d43f55aa0d79d4fae91a704695122a1b109668c1daa8fb76f09d", + "zh:aadd98086133d3ebea67437d56512fdcc6dfb3bd34dfc23f276c0db9272e27b4", + "zh:beff701b653841e70441978137768f54e7dc6c27e7bf12a4589087f01f5bbcee", + "zh:c91c2223b29fdbc0044d20e1936ccc051d010727a13f2ff1e75e51f09bff33a3", + "zh:d491f9c2d32a39dc4031628469ae7c8aec0074312a7c1f0286b173cdcf854a54", + ] +} + +provider "registry.terraform.io/hashicorp/random" { + version = "3.9.0" + constraints = "~> 3.0" + hashes = [ + "h1:OO+IuvQJSPmWdN8AyyIEvPJbLvDQpgX/zbktoa9KsJE=", + "h1:UlBuNVuCGJ39tTv2c5gz2NRZnQbXfbIWbTzWcth5o74=", + "h1:lVDv+0AjDjrLfpmaJbWqUmIw/k3/AHXLc3N4m55SNdo=", + "zh:161ad0bd9a75768c82f53fb6e7172a9d8be2d4889b012645a34795031aaf1bf1", + "zh:19dc9a5b17729725ccfc4f45b0500af0ee5bc6b6b160c7adb8f2bf617d2c80ea", + "zh:269eda8fe42daa7974d5a34d166c3ba9defe80cde86c01e4dadcfdf2e1f05e5f", + "zh:373f7c65566f8f2cc7f45d698654feb9d988996957e1266a69ca00c52d6d16d0", + "zh:5599d16804c41c83009ec621b6d6b6f74e102f5827678a4750f8809055546b61", + "zh:583be0440469a22bff70dcfa56593b01566860b29607437264adb51060cf46fc", + "zh:5f211d8ec3f2e1f414870d9584bfe26e6995560ef81c748f8447a48164767398", + "zh:78d5eefdd9e494defcb3c68d282b8f96630502cac21d1ea161f53cfe9bb483b3", + "zh:7b547fd16216761ef86efc3ed516ac5ac0c5c42b7c7eb24a08cef2d93f69ed5e", + "zh:7e7c0679daf2a382151d05068c8c3f0dae6b7b7dccf818827b73dd08638df2ef", + "zh:8089dec888a8038b9b4fb23b3df7e1057293dbc5b60b42cc47ff690d69d4b61b", + "zh:c51f15a031edfd6f23ce8ced3446ca7f8d8d647e2499890d7d5d10d5016d7257", + "zh:c94784f005708890dc6895afd53636ec00ec1e430b15d41e5aebfb1d4b39bd04", + ] +} + +provider "registry.terraform.io/supabase/supabase" { + version = "1.5.1" + constraints = "~> 1.5.1" + hashes = [ + "h1:A4kqrLbrPeyfOXuk2eN8L15ue7JSRtkV/FhqFyY9Dzg=", + "h1:X1mvSyjaWyaJmhijgpsXMP7UMIE5kuwbq4wfjpfcxBA=", + "h1:rTxTmQ7IGlQNi5H1oS8e2+AgmiXeWM+jnJN5TNS69vU=", + "zh:1834f1cfbab811ca53eae9bdb6485032a674aef5d84fa7fe65342f72e50e3880", + "zh:1d53f3c0c6d82c50a7a29d658f77f3e44db0c0196714f0891ec2cadfdeb58764", + "zh:1f4dda08ccb39790f3c11fb6b4006827f09bfb8fb85082886eb46803f44b1722", + "zh:38dcad29e57c4d06374f4b557108d0877bb3ba628878c6648508110ff34f3d0f", + "zh:63782085e8da25d78de2a080072e7cc6a35c781c2bdb04f5ca46f65a6d6988d6", + "zh:79d7e5fe9d1571aa5357f98b97e3f12e61f68500e4270e855c1bc5e4cc772a56", + "zh:890df766e9b839623b1f0437355032a3c006226a6c200cd911e15ee1a9014e9f", + "zh:8c8560f8df33c087ab9133fc32b68c4c16c8c1bc32b546c91dc98c2b39f80c3a", + "zh:ab4189d0c843166a1b4eaefe817192c8cee954c441a3a86ef5118931ce0e9d71", + "zh:c9037e7cfadc468ac961786af7e3004c08196543416842746f95b929e6118fd6", + "zh:ca9546b9ca3a27634a6eb37e069e58a44a26fe8c3c6539a17dc4b628ad6e7ae0", + "zh:d0301164210ea4ed0567c9c1c751d1e250ab163a8b0edd8cf256d25d54e4d1e5", + "zh:f048d76cca0083a2b91bef304949d182b3395b3bc013cc8aa1505219538953a1", + "zh:f85b905aa8f049a8769bac933a56ae0ca9c5bb74a6c2376cf9ee4ac8ecf50126", + "zh:fd26c6f338bfab77b145e0755dc39d9873aec8219b3b53909da418250d013973", + ] +} diff --git a/infra/terraform/supabase/terraform/adopt.tf b/infra/terraform/supabase/terraform/adopt.tf new file mode 100644 index 0000000..b5d6feb --- /dev/null +++ b/infra/terraform/supabase/terraform/adopt.tf @@ -0,0 +1,49 @@ +# --- Self-healing adoption (AWS-free state seeding) --- +# +# Same pattern as cloudflare-kv/terraform/adopt.tf: when the platform state +# does not yet track the Supabase project but the organization already has one +# under this name, import it by ref at plan time instead of colliding with the +# duplicate-name guard. Fresh products resolve to id = "" and create normally; +# a resource already in state short-circuits the lookup. +# +# Cutover caveat: database_password is config-driven (random_password). After +# adoption the first apply RESETS the database password to the newly generated +# one and publishes it through the job-output secrets — db-migrate, hyperdrive +# and the worker fleet re-wire from those in the same run, but anything still +# consuming the pre-adoption credentials breaks until that run converges. + +data "external" "adopt_project" { + program = ["bash", "-c", <<-EOT + set -euo pipefail + name="$(jq -r .name)" + state_file="$(mktemp)" + trap 'rm -f "$state_file"' EXIT + code="$(curl -s -o "$state_file" -w '%%{http_code}' \ + -u "$TF_HTTP_USERNAME:$TF_HTTP_PASSWORD" "$TF_HTTP_ADDRESS" || echo 000)" + if [ "$code" = "200" ] && jq -e \ + '[.resources[]? | select(.type == "supabase_project" and .name == "this")] | length > 0' \ + "$state_file" >/dev/null 2>&1; then + jq -n '{id: ""}' + exit 0 + fi + resp="$(curl -fsS --retry 3 -H "Authorization: Bearer $SUPABASE_ACCESS_TOKEN" \ + "https://api.supabase.com/v1/projects")" + # The org id reaches this job as TF_VAR_supabaseOrgId (the component maps + # the SUPABASE_ORG_ID secret to the terraform variable); plain + # SUPABASE_ORG_ID exists only in older wirings. Accept either; with + # neither set, match by name alone. + org="$${TF_VAR_supabaseOrgId:-$${SUPABASE_ORG_ID:-}}" + printf '%s' "$resp" | jq -c --arg n "$name" --arg org "$org" \ + '{id: ([.[] | select(.name == $n and ($org == "" or .organization_id == $org)) | .id] | first // "")}' + EOT + ] + query = { + name = local.project_name + } +} + +import { + for_each = toset(compact([data.external.adopt_project.result.id])) + to = supabase_project.this + id = each.value +} diff --git a/infra/terraform/supabase/terraform/main.tf b/infra/terraform/supabase/terraform/main.tf new file mode 100644 index 0000000..9fdfea6 --- /dev/null +++ b/infra/terraform/supabase/terraform/main.tf @@ -0,0 +1,283 @@ +terraform { + required_version = ">= 1.15.0" + + # State lives on the platform (SB1): the runner exports TF_HTTP_* per job + # (address = …/state/tfstate/{component}/{env}, run token as password), so + # this block stays empty — no S3 bucket, no AWS role, no workspaces (the + # environment is in the address). + backend "http" {} + + required_providers { + supabase = { + source = "supabase/supabase" + # Pinned below 1.6: from 1.6.0 the provider reads /billing/addons on + # every project create/read, and Supabase does not serve billing + # endpoints to OAuth tokens yet ("does not support oauth access") — + # which is exactly the credential the platform brokers. + version = "~> 1.5.1" + } + random = { + source = "hashicorp/random" + version = "~> 3.0" + } + external = { + source = "hashicorp/external" + version = "~> 2.3" + } + } +} + +# --- Providers --- + +# Authenticates via the SUPABASE_ACCESS_TOKEN env var (provider-native): a +# short-lived Management-API token minted per run from the workspace's +# Supabase integration, resolved into the job env by orun. +provider "supabase" {} + +# --- Variables (standard Orun parameters) --- + +variable "orgName" { + type = string + default = "sourceplane" +} + +variable "owner" { + type = string + default = "sourceplane" +} + +variable "repo" { + type = string + default = "sveltekit-saas" +} + +variable "namespace" { + type = string + default = "sourceplane" +} + +variable "namespacePrefix" { + type = string + default = "" +} + +variable "lane" { + type = string + default = "verify" +} + +variable "environment" { + type = string + default = "stage" +} + +variable "component" { + type = string + default = "supabase" +} + +variable "stackName" { + type = string + default = "supabase" +} + +variable "terraformDir" { + type = string + default = "terraform" +} + +variable "terraformVersion" { + type = string + default = "1.15.3" +} + +# Supabase target identity. supabaseRegion comes from the component's +# `spec.parameters`; supabaseOrgId is injected as TF_VAR_supabaseOrgId from the +# workspace's SUPABASE_ORG_ID secret (org-id connection fact). Both are +# required (no default) so a missing value fails plan loudly instead of +# silently pointing at the wrong org or region. +variable "supabaseOrgId" { + type = string +} + +variable "supabaseRegion" { + type = string +} + +# The workers.dev subdomain the app's Worker answers on (the component's +# `workersDevSubdomain` parameter, surfaced as TF_VAR_workersDevSubdomain — +# the same value apps/web/component.yaml carries). Required, like the two +# above: Supabase Auth sends its links to this origin. +variable "workersDevSubdomain" { + type = string +} + +# Whether a new user must confirm their email before signing in (the +# component's `authEmailConfirmation` parameter). Off by default, because a +# fresh project sends email only to its organization's own members until it +# has an SMTP server of its own: with confirmation on, nobody else could sign +# up. Turn it on once SMTP is set (the product's README, "Email"). +variable "authEmailConfirmation" { + type = bool + default = false +} + +# --- Locals --- + +# The product's own origin when the environment has a custom domain: SITE_URL +# under its `env:` in intent.yaml, which the runner exports to this job as it +# does to the app's build (apps/web/component.yaml) — one setting, so Auth's +# links and the app's absolute URLs name the same origin. Empty when unset. +data "external" "site_url" { + program = ["bash", "-c", "jq -n --arg url \"$${SITE_URL:-}\" '{url: $url}'"] +} + +locals { + supabase_org_id = var.supabaseOrgId + supabase_region = var.supabaseRegion + project_name = "${var.repo}-${var.environment}" + # The environment's Worker, as apps/web/component.yaml names it: + # -web- on the account's workers.dev subdomain — unless SITE_URL + # names the environment's custom domain. + worker_origin = "https://${var.repo}-web-${var.environment}.${var.workersDevSubdomain}.workers.dev" + app_origin = coalesce(trimsuffix(data.external.site_url.result.url, "/"), local.worker_origin) +} + +# --- Generate database password --- + +resource "random_password" "db_password" { + length = 32 + special = true + # Avoid characters that cause issues in connection strings + override_special = "!#$%&*()-_=+[]{}|:,.<>?" +} + +# --- Supabase project --- + +resource "supabase_project" "this" { + organization_id = local.supabase_org_id + name = local.project_name + database_password = random_password.db_password.result + region = local.supabase_region +} + +# --- Outputs --- +# +# Credentials leave this module ONLY through the outputs component.yaml's +# `secretOutputs` names, which the runner lease-publishes onto the project's +# environment rung after the apply (never argv, never a log). The project's +# three database credentials below are published for the owner and for any +# later step that migrates the database; the app reads the `wiring` document +# further down. No Secrets Manager. + +output "project_ref" { + description = "Supabase project reference ID" + value = supabase_project.this.id +} + +output "project_name" { + description = "Supabase project name" + value = supabase_project.this.name +} + +output "project_url" { + description = "Supabase project URL" + value = "https://${supabase_project.this.id}.supabase.co" +} + +output "database_password" { + description = "Generated database password (sensitive; wired to orun secrets)" + value = random_password.db_password.result + sensitive = true +} + +output "connection_uri" { + description = "Direct Postgres connection URI (sensitive; wired to orun secrets)" + value = "postgresql://postgres:${random_password.db_password.result}@db.${supabase_project.this.id}.supabase.co:5432/postgres" + sensitive = true +} + +# --- The project, up --- +# +# The provider returns from a create as soon as the Management API accepts it, +# and a project takes minutes to come up. Its API keys and its Auth +# configuration are read and written below; both wait here until the project +# reports ACTIVE_HEALTHY (ten minutes at most). On an adopted or existing +# project this answers at once. Same tools as adopt.tf: bash, curl, jq and the +# brokered SUPABASE_ACCESS_TOKEN in the environment. + +resource "terraform_data" "project_ready" { + triggers_replace = [supabase_project.this.id] + + provisioner "local-exec" { + interpreter = ["bash", "-c"] + environment = { + PROJECT_REF = supabase_project.this.id + } + command = <<-EOT + set -uo pipefail + for _ in $(seq 1 60); do + status="$(curl -fsS --retry 2 -H "Authorization: Bearer $SUPABASE_ACCESS_TOKEN" \ + "https://api.supabase.com/v1/projects/$PROJECT_REF" | jq -r '.status // empty')" + [ "$status" = ACTIVE_HEALTHY ] && { echo "supabase: $PROJECT_REF is $status"; exit 0; } + echo "supabase: $PROJECT_REF is $${status:-not answering yet}; waiting" + sleep 10 + done + echo "supabase: $PROJECT_REF did not report ACTIVE_HEALTHY within ten minutes" >&2 + exit 1 + EOT + } +} + +# --- API keys --- +# +# The app talks to Supabase from the browser and from the Worker with the +# project URL and the publishable (anon) key; Row Level Security is what +# protects the data, the key is public by design. Both leave this module in +# ONE wiring document, WIRING_SUPABASE, which the app's deploy renders into +# its wrangler config and inlines into its build. The service-role key leaves +# on its own, as SUPABASE_SERVICE_ROLE_KEY: it bypasses Row Level Security, +# so it is never a var and never in a bundle — the app's deploy lane for this +# environment hands it to the Worker as a secret, and the server reads it +# where upstream's does. + +data "supabase_apikeys" "this" { + project_ref = supabase_project.this.id + depends_on = [terraform_data.project_ready] +} + +output "service_role_key" { + description = "The project's service-role key (sensitive; wired to orun secrets as SUPABASE_SERVICE_ROLE_KEY, a Worker secret)" + value = data.supabase_apikeys.this.service_role_key + sensitive = true +} + +output "wiring" { + description = "Wiring document for the app's deploy-time configuration (pushed to orun secrets as WIRING_SUPABASE)" + value = jsonencode({ + supabase_url = "https://${supabase_project.this.id}.supabase.co" + supabase_anon_key = data.supabase_apikeys.this.anon_key + }) + sensitive = true +} + +# --- Auth --- +# +# A fresh project's Auth sends its links to http://localhost:3000 and asks +# every new user to confirm an email address it can only deliver to the +# organization's own members. So the app's Worker is the Site URL and the one +# allowed redirect origin, and sign-up signs the user straight in unless +# `authEmailConfirmation` is on. Only these three keys are managed; every +# other Auth setting stays the project's own, and the dashboard can change it. + +resource "supabase_settings" "this" { + project_ref = supabase_project.this.id + + auth = jsonencode({ + site_url = local.app_origin + uri_allow_list = "${local.app_origin}/**" + mailer_autoconfirm = !var.authEmailConfirmation + }) + + depends_on = [terraform_data.project_ready] +} diff --git a/packages/.gitkeep b/packages/.gitkeep deleted file mode 100644 index e69de29..0000000 diff --git a/packages/db/component.yaml b/packages/db/component.yaml new file mode 100644 index 0000000..4d3cda9 --- /dev/null +++ b/packages/db/component.yaml @@ -0,0 +1,25 @@ +apiVersion: sourceplane.io/v1 +kind: Component +metadata: + name: db + description: The schema as migrations, and the runner that applies them over the Supabase Management API (built by the db-migrate component before it plans or applies) +spec: + type: turbo-package + lifecycle: production + owner: platform + domain: data + # Verified where the code is checked — on dev, by every pull request. On a + # merge the db-migrate component builds this package itself in its own job + # before it applies, so stage and prod need no job of their own here. + subscribe: + environments: + - name: dev + profile: quick-check + parameters: + nodeVersion: "22" + pnpmVersion: "10.12.1" + buildCommand: pnpm exec turbo run build --filter=./ + typecheckCommand: pnpm exec turbo run typecheck --filter=./ + labels: + team: platform + layer: data diff --git a/packages/db/eslint.config.js b/packages/db/eslint.config.js new file mode 100644 index 0000000..2e905dc --- /dev/null +++ b/packages/db/eslint.config.js @@ -0,0 +1,2 @@ +import config from "../../tooling/eslint/index.js"; +export default config; diff --git a/packages/db/package.json b/packages/db/package.json new file mode 100644 index 0000000..6616a77 --- /dev/null +++ b/packages/db/package.json @@ -0,0 +1,30 @@ +{ + "name": "@saas/db", + "version": "0.0.0", + "private": true, + "type": "module", + "description": "The database migrations and their runner (the db-migrate composition builds this package and runs dist/runner/cli.js plan|apply)", + "exports": { + ".": "./src/index.ts", + "./manifest": "./src/manifest.ts", + "./types": "./src/types.ts", + "./runner": "./src/runner/index.ts" + }, + "bin": { + "db-migrate": "./dist/runner/cli.js" + }, + "scripts": { + "build": "tsc --project tsconfig.build.json && cp -r src/migrations dist/", + "typecheck": "tsc --noEmit", + "lint": "eslint src", + "manifest:check": "node ../../tooling/migrations/manifest.mjs check", + "manifest:fix": "node ../../tooling/migrations/manifest.mjs fix", + "migrate:plan": "node dist/runner/cli.js plan" + }, + "devDependencies": { + "@app/eslint-config": "workspace:*", + "@app/tsconfig": "workspace:*", + "@types/node": "^22.9.0", + "typescript": "^5.8.3" + } +} diff --git a/packages/db/src/index.ts b/packages/db/src/index.ts new file mode 100644 index 0000000..9b5ee07 --- /dev/null +++ b/packages/db/src/index.ts @@ -0,0 +1,3 @@ +export { manifest } from "./manifest.js"; +export type { MigrationEntry, MigrationManifest, BoundedContext } from "./types.js"; +export { BOUNDED_CONTEXTS } from "./types.js"; diff --git a/packages/db/src/manifest.ts b/packages/db/src/manifest.ts new file mode 100644 index 0000000..d72f1d2 --- /dev/null +++ b/packages/db/src/manifest.ts @@ -0,0 +1,39 @@ +import type { MigrationManifest } from "./types.js"; + +// Every migration the runner applies, in order, with the sha256 of its file. +// `pnpm --filter @saas/db run manifest:check` verifies the checksums; +// `manifest:fix` rewrites them after a migration file changes (only ever +// before that migration has been applied anywhere — an applied migration's +// checksum is immutable). +export const manifest: MigrationManifest = { + version: 1, + migrations: [ + { + id: "000_control_baseline", + context: "control", + path: "000_control/up.sql", + checksum: + "2a5d7f30684c99e3ff441ca8a2c38038dedd1bab4db4a40e92cd36bb22be297f", + description: + "Baseline control migration — creates the migration tracking schema", + }, + { + id: "010_initial", + context: "app", + path: "010_initial/up.sql", + checksum: + "734210df1340e56e55fdff6eb71161f562814725030a1fde06b88456639e987c", + description: + "The template's schema (supabase/migrations/20240730010101_initial.sql, verbatim): profiles, stripe_customers and contact_requests with row-level security, the trigger that creates a profile for every new auth.users row, and the avatars storage bucket with its policies", + }, + { + id: "020_add_unsubscribed_to_profiles", + context: "app", + path: "020_add_unsubscribed_to_profiles/up.sql", + checksum: + "d45389f3e51aa9e3ea76c3fb2ecb9175cda644a201332282480fddb847150352", + description: + "profiles.unsubscribed (supabase/migrations/20240731051052_add_unsubscribed_to_profiles.sql, verbatim): the email opt-out the account settings write", + }, + ], +}; diff --git a/packages/db/src/migrations/000_control/up.sql b/packages/db/src/migrations/000_control/up.sql new file mode 100644 index 0000000..1764562 --- /dev/null +++ b/packages/db/src/migrations/000_control/up.sql @@ -0,0 +1,16 @@ +-- Baseline control migration +-- Creates the migration tracking schema used by the migration runner. +-- Owner: control bounded context + +CREATE SCHEMA IF NOT EXISTS _migrations; + +CREATE TABLE IF NOT EXISTS _migrations.applied ( + id TEXT PRIMARY KEY, + context TEXT NOT NULL, + checksum TEXT NOT NULL, + applied_at TIMESTAMPTZ NOT NULL DEFAULT now(), + applied_by TEXT NOT NULL DEFAULT current_user +); + +COMMENT ON TABLE _migrations.applied IS + 'Tracks which migrations have been applied to the database.'; diff --git a/packages/db/src/migrations/010_initial/up.sql b/packages/db/src/migrations/010_initial/up.sql new file mode 100644 index 0000000..076ae11 --- /dev/null +++ b/packages/db/src/migrations/010_initial/up.sql @@ -0,0 +1,72 @@ +-- Create a table for public profiles +create table profiles ( + id uuid references auth.users on delete cascade not null primary key, + updated_at timestamp with time zone, + full_name text, + company_name text, + avatar_url text, + website text +); +-- Set up Row Level Security (RLS) +-- See https://supabase.com/docs/guides/auth/row-level-security for more details. +alter table profiles + enable row level security; + +create policy "Profiles are viewable by self." on profiles + for select using (auth.uid() = id); + +create policy "Users can insert their own profile." on profiles + for insert with check (auth.uid() = id); + +create policy "Users can update own profile." on profiles + for update using (auth.uid() = id); + +-- Create Stripe Customer Table +-- One stripe customer per user (PK enforced) +-- Limit RLS policies -- mostly only server side access +create table stripe_customers ( + user_id uuid references auth.users on delete cascade not null primary key, + updated_at timestamp with time zone, + stripe_customer_id text unique +); +alter table stripe_customers enable row level security; + +-- Create a table for "Contact Us" form submissions +-- Limit RLS policies -- only server side access +create table contact_requests ( + id uuid primary key default gen_random_uuid(), + updated_at timestamp with time zone, + first_name text, + last_name text, + email text, + phone text, + company_name text, + message_body text +); +alter table contact_requests enable row level security; + +-- This trigger automatically creates a profile entry when a new user signs up via Supabase Auth. +-- See https://supabase.com/docs/guides/auth/managing-user-data#using-triggers for more details. +create function public.handle_new_user() +returns trigger as $$ +begin + insert into public.profiles (id, full_name, avatar_url) + values (new.id, new.raw_user_meta_data->>'full_name', new.raw_user_meta_data->>'avatar_url'); + return new; +end; +$$ language plpgsql security definer; +create trigger on_auth_user_created + after insert on auth.users + for each row execute procedure public.handle_new_user(); + +-- Set up Storage! +insert into storage.buckets (id, name) + values ('avatars', 'avatars'); + +-- Set up access controls for storage. +-- See https://supabase.com/docs/guides/storage#policy-examples for more details. +create policy "Avatar images are publicly accessible." on storage.objects + for select using (bucket_id = 'avatars'); + +create policy "Anyone can upload an avatar." on storage.objects + for insert with check (bucket_id = 'avatars'); diff --git a/packages/db/src/migrations/020_add_unsubscribed_to_profiles/up.sql b/packages/db/src/migrations/020_add_unsubscribed_to_profiles/up.sql new file mode 100644 index 0000000..1042d6d --- /dev/null +++ b/packages/db/src/migrations/020_add_unsubscribed_to_profiles/up.sql @@ -0,0 +1,2 @@ +ALTER TABLE profiles +ADD COLUMN IF NOT EXISTS unsubscribed boolean NOT NULL DEFAULT false; diff --git a/packages/db/src/runner/cli.ts b/packages/db/src/runner/cli.ts new file mode 100644 index 0000000..c4df1bf --- /dev/null +++ b/packages/db/src/runner/cli.ts @@ -0,0 +1,121 @@ +#!/usr/bin/env node +import { resolve, dirname } from "node:path"; +import { fileURLToPath } from "node:url"; +import { manifest } from "../manifest.js"; +import { runMigrations } from "./runner.js"; +import { loadSecretFromEnv } from "./secrets.js"; +import { SupabaseApiAdapter } from "./supabase-api-adapter.js"; +import type { MigrationAdapter, RunMode } from "./types.js"; + +const __dirname = dirname(fileURLToPath(import.meta.url)); +const MIGRATIONS_DIR = resolve(__dirname, "../migrations"); + +const SUPABASE_ACCESS_TOKEN = process.env["SUPABASE_ACCESS_TOKEN"]; + +function usage(): never { + process.stderr.write( + `Usage: db-migrate --env [--connection-uri ]\n` + + `\n` + + `Modes:\n` + + ` plan — report pending migrations without mutating the database\n` + + ` apply — apply pending migrations\n` + + `\n` + + `Options:\n` + + ` --env target environment (required)\n` + + `\n` + + `Environment:\n` + + ` SUPABASE_ACCESS_TOKEN Supabase management API token (required for apply)\n` + + ` SUPABASE_PROJECT_REF Supabase project ref (required for apply; wired from orun secrets)\n`, + ); + process.exit(1); +} + +interface ParsedArgs { + mode: RunMode; + env: string; +} + +function parseArgs(argv: string[]): ParsedArgs { + const args = argv.slice(2); + + const mode = args[0] as RunMode | undefined; + if (mode !== "plan" && mode !== "apply") { + usage(); + } + + let env: string | undefined; + + for (let i = 1; i < args.length; i++) { + if (args[i] === "--env" && args[i + 1]) { + env = args[++i]; + } + } + + if (!env) { + const envFromEnv = process.env["MIGRATION_ENV"]; + if (envFromEnv) { + env = envFromEnv; + } + } + + if (!env || !["stage", "prod"].includes(env)) { + process.stderr.write("Error: --env must be 'stage' or 'prod'\n"); + process.exit(1); + } + + return { mode, env }; +} + +async function resolveAdapter( + mode: RunMode, + _env: string, +): Promise { + if (mode === "plan") { + return null; + } + + if (!SUPABASE_ACCESS_TOKEN) { + throw new Error("SUPABASE_ACCESS_TOKEN is required for apply mode"); + } + + process.stderr.write(`Loading credentials from the wired environment (orun secrets)\n`); + const secret = loadSecretFromEnv(); + + return new SupabaseApiAdapter(secret.project_ref, SUPABASE_ACCESS_TOKEN); +} + +async function main(): Promise { + const { mode, env } = parseArgs(process.argv); + + process.stderr.write(`db-migrate: mode=${mode} env=${env}\n`); + + const adapter = await resolveAdapter(mode, env); + + const result = await runMigrations(manifest, { + mode, + migrationsDir: MIGRATIONS_DIR, + adapter, + }); + + if (result.failed) { + process.stderr.write( + `FAILED: migration ${result.failed.id} — ${result.failed.error}\n`, + ); + process.exit(1); + } + + const output = { + mode, + env, + applied: result.applied, + skipped: result.skipped, + }; + + process.stdout.write(JSON.stringify(output, null, 2) + "\n"); +} + +main().catch((err: unknown) => { + const message = err instanceof Error ? err.message : String(err); + process.stderr.write(`db-migrate: fatal error — ${message}\n`); + process.exit(1); +}); diff --git a/packages/db/src/runner/index.ts b/packages/db/src/runner/index.ts new file mode 100644 index 0000000..88d97fa --- /dev/null +++ b/packages/db/src/runner/index.ts @@ -0,0 +1,5 @@ +export type { MigrationAdapter, AppliedMigration, RunnerConfig, RunMode, MigrationPlan, MigrationResult } from "./types.js"; +export { runMigrations, buildPlan } from "./runner.js"; +export { SupabaseApiAdapter } from "./supabase-api-adapter.js"; +export { loadConnectionUriFromEnv, loadSecretFromEnv } from "./secrets.js"; +export type { SupabaseSecret } from "./secrets.js"; diff --git a/packages/db/src/runner/runner.ts b/packages/db/src/runner/runner.ts new file mode 100644 index 0000000..9574ca9 --- /dev/null +++ b/packages/db/src/runner/runner.ts @@ -0,0 +1,140 @@ +import { createHash } from "node:crypto"; +import { readFileSync } from "node:fs"; +import { resolve } from "node:path"; +import type { MigrationEntry, MigrationManifest } from "../types.js"; +import type { + MigrationPlan, + MigrationResult, + RunnerConfig, +} from "./types.js"; + +const ADVISORY_LOCK_ID = 839_201_008; + +function computeChecksum(filePath: string): string { + const content = readFileSync(filePath); + return createHash("sha256").update(content).digest("hex"); +} + +export function buildPlan( + manifest: MigrationManifest, + appliedMap: Map, + migrationsDir: string, +): MigrationPlan { + const alreadyApplied: string[] = []; + const pending: MigrationEntry[] = []; + const checksumMismatches: MigrationPlan["checksumMismatches"] = []; + + for (const entry of manifest.migrations) { + const appliedChecksum = appliedMap.get(entry.id); + + if (appliedChecksum !== undefined) { + alreadyApplied.push(entry.id); + + const fileChecksum = computeChecksum( + resolve(migrationsDir, entry.path), + ); + + if (appliedChecksum !== fileChecksum || appliedChecksum !== entry.checksum) { + checksumMismatches.push({ + id: entry.id, + expected: appliedChecksum, + actual: fileChecksum, + }); + } + } else { + pending.push(entry); + } + } + + return { alreadyApplied, pending, checksumMismatches }; +} + +export async function runMigrations( + manifest: MigrationManifest, + config: RunnerConfig, +): Promise { + const { adapter, mode, migrationsDir } = config; + const result: MigrationResult = { applied: [], skipped: [], failed: null }; + + // Offline plan: verify checksums then report all migrations as pending. + if (mode === "plan" && adapter === null) { + for (const entry of manifest.migrations) { + const filePath = resolve(migrationsDir, entry.path); + const fileChecksum = computeChecksum(filePath); + if (fileChecksum !== entry.checksum) { + throw new Error( + `Checksum mismatch for ${entry.id}: manifest says ${entry.checksum}, file has ${fileChecksum}`, + ); + } + } + result.applied = manifest.migrations.map((m) => m.id); + return result; + } + + if (!adapter) { + throw new Error("adapter is required for apply mode"); + } + + await adapter.connect(); + + try { + const locked = await adapter.acquireAdvisoryLock(ADVISORY_LOCK_ID); + if (!locked) { + throw new Error( + "Could not acquire migration advisory lock — another runner may be active", + ); + } + + try { + const appliedRows = await adapter.getAppliedMigrations(); + const appliedMap = new Map(appliedRows.map((r) => [r.id, r.checksum])); + + const plan = buildPlan(manifest, appliedMap, migrationsDir); + + if (plan.checksumMismatches.length > 0) { + const ids = plan.checksumMismatches.map((m) => m.id).join(", "); + throw new Error( + `Checksum mismatch for already-applied migrations: ${ids}`, + ); + } + + result.skipped = plan.alreadyApplied; + + if (mode === "plan") { + result.applied = plan.pending.map((m) => m.id); + return result; + } + + for (const entry of plan.pending) { + const sqlPath = resolve(migrationsDir, entry.path); + const sql = readFileSync(sqlPath, "utf-8"); + const fileChecksum = computeChecksum(sqlPath); + + if (fileChecksum !== entry.checksum) { + throw new Error( + `Checksum mismatch for ${entry.id}: manifest says ${entry.checksum}, file has ${fileChecksum}`, + ); + } + + await adapter.beginTransaction(); + try { + await adapter.executeSql(sql); + await adapter.recordMigration(entry); + await adapter.commitTransaction(); + result.applied.push(entry.id); + } catch (err: unknown) { + await adapter.rollbackTransaction(); + const message = err instanceof Error ? err.message : String(err); + result.failed = { id: entry.id, error: message }; + return result; + } + } + } finally { + await adapter.releaseAdvisoryLock(ADVISORY_LOCK_ID); + } + } finally { + await adapter.disconnect(); + } + + return result; +} diff --git a/packages/db/src/runner/secrets.ts b/packages/db/src/runner/secrets.ts new file mode 100644 index 0000000..e575b57 --- /dev/null +++ b/packages/db/src/runner/secrets.ts @@ -0,0 +1,62 @@ +// Supabase credentials from the ENVIRONMENT (de-AWS): the supabase terraform +// component wires its outputs into the workspace's project/env secret rung +// (composition wire-secrets step), and orun resolves the keys this runner +// declares in its component secretEnv into the job env — SUPABASE_PROJECT_REF, +// SUPABASE_DB_PASSWORD, SUPABASE_DB_URL. No Secrets Manager, no AWS SDK. + +export interface SupabaseSecret { + project_ref: string; + project_url: string; + database_host: string; + database_port: string; + database_name: string; + database_user: string; + database_password: string; + connection_uri: string; +} + +function requireEnv(name: string): string { + const value = process.env[name]?.trim(); + if (!value) { + throw new Error( + `${name} is not set — declare it in the component's secretEnv (wired from the supabase component's outputs)`, + ); + } + return value; +} + +/** Assembles the credential document from the wired env vars. The derived + * fields (host/port/db/user) follow the same convention the supabase + * component's payload always used. */ +export function loadSecretFromEnv(): SupabaseSecret { + const projectRef = requireEnv("SUPABASE_PROJECT_REF"); + const password = requireEnv("SUPABASE_DB_PASSWORD"); + const host = `db.${projectRef}.supabase.co`; + const connectionUri = + process.env["SUPABASE_DB_URL"]?.trim() || + `postgresql://postgres:${encodeURIComponent(password)}@${host}:5432/postgres`; + return { + project_ref: projectRef, + project_url: `https://${projectRef}.supabase.co`, + database_host: host, + database_port: "5432", + database_name: "postgres", + database_user: "postgres", + database_password: password, + connection_uri: connectionUri, + }; +} + +/** Direct or pooler connection URI. When a pooler region is provided, use the + * Supabase session pooler to avoid IPv6 connectivity issues with the direct + * database host — the pooler has IPv4 addresses and supports session-level + * advisory locks and transactions. */ +export function loadConnectionUriFromEnv(poolerRegion?: string): string { + const secret = loadSecretFromEnv(); + if (poolerRegion) { + const poolerHost = `aws-0-${poolerRegion}.pooler.supabase.com`; + const user = `postgres.${secret.project_ref}`; + return `postgresql://${encodeURIComponent(user)}:${encodeURIComponent(secret.database_password)}@${poolerHost}:6543/${secret.database_name}`; + } + return secret.connection_uri; +} diff --git a/packages/db/src/runner/supabase-api-adapter.ts b/packages/db/src/runner/supabase-api-adapter.ts new file mode 100644 index 0000000..e7e400c --- /dev/null +++ b/packages/db/src/runner/supabase-api-adapter.ts @@ -0,0 +1,93 @@ +import type { MigrationEntry } from "../types.js"; +import type { AppliedMigration, MigrationAdapter } from "./types.js"; + +// The Management API's origin. SUPABASE_API_URL overrides it so a test can +// put a local Postgres behind a stand-in for the one endpoint used here; a +// deployment never sets it. +const SUPABASE_API_BASE = (process.env["SUPABASE_API_URL"] ?? "https://api.supabase.com").replace(/\/+$/, ""); + +export class SupabaseApiAdapter implements MigrationAdapter { + private projectRef: string; + private accessToken: string; + + constructor(projectRef: string, accessToken: string) { + this.projectRef = projectRef; + this.accessToken = accessToken; + } + + async connect(): Promise { /* stateless HTTP — no persistent connection */ } + async disconnect(): Promise { /* no-op */ } + + // Advisory locks are session-scoped and can't be held across HTTP calls. + // Idempotent ON CONFLICT DO NOTHING in recordMigration protects against + // duplicate application when concurrent runners are unlikely. + async acquireAdvisoryLock(_lockId: number): Promise { return true; } + async releaseAdvisoryLock(_lockId: number): Promise { /* no-op */ } + + async getAppliedMigrations(): Promise { + try { + const rows = await this.query( + `SELECT id, context, checksum, applied_at::text AS applied_at + FROM _migrations.applied ORDER BY id`, + ); + return rows as unknown as AppliedMigration[]; + } catch (err: unknown) { + const msg = err instanceof Error ? err.message : String(err); + // Table doesn't exist yet — first-ever run. + if (msg.includes("does not exist")) { + return []; + } + throw err; + } + } + + // Transactions: each step is sent immediately in autocommit mode. + // The migration SQL and record insertion are sent as separate calls. + // Migrations must be idempotent; the runner's ON CONFLICT DO NOTHING + // in recordMigration ensures safe re-runs. + async beginTransaction(): Promise { /* no-op */ } + async commitTransaction(): Promise { /* no-op */ } + async rollbackTransaction(): Promise { /* no-op */ } + + async executeSql(sql: string): Promise { + await this.query(sql); + } + + async recordMigration(entry: MigrationEntry): Promise { + const id = entry.id.replace(/'/g, "''"); + const context = entry.context.replace(/'/g, "''"); + const checksum = entry.checksum.replace(/'/g, "''"); + await this.query( + `INSERT INTO _migrations.applied (id, context, checksum) + VALUES ('${id}', '${context}', '${checksum}') + ON CONFLICT (id) DO NOTHING`, + ); + } + + private async query(sql: string): Promise[]> { + const url = `${SUPABASE_API_BASE}/v1/projects/${this.projectRef}/database/query`; + const response = await fetch(url, { + method: "POST", + headers: { + Authorization: `Bearer ${this.accessToken}`, + "Content-Type": "application/json", + }, + body: JSON.stringify({ query: sql }), + }); + + if (!response.ok) { + const body = await response.text(); + let message = `HTTP ${response.status}`; + try { + const parsed = JSON.parse(body) as { message?: string; error?: string }; + message = parsed.message ?? parsed.error ?? body; + } catch { + message = body || message; + } + throw new Error(message); + } + + const data = await response.json(); + return Array.isArray(data) ? data as Record[] : []; + } +} diff --git a/packages/db/src/runner/types.ts b/packages/db/src/runner/types.ts new file mode 100644 index 0000000..849d74a --- /dev/null +++ b/packages/db/src/runner/types.ts @@ -0,0 +1,41 @@ +import type { MigrationEntry } from "../types.js"; + +export interface AppliedMigration { + id: string; + context: string; + checksum: string; + applied_at: string; +} + +export interface MigrationAdapter { + connect(): Promise; + disconnect(): Promise; + acquireAdvisoryLock(lockId: number): Promise; + releaseAdvisoryLock(lockId: number): Promise; + getAppliedMigrations(): Promise; + beginTransaction(): Promise; + commitTransaction(): Promise; + rollbackTransaction(): Promise; + executeSql(sql: string): Promise; + recordMigration(entry: MigrationEntry): Promise; +} + +export type RunMode = "plan" | "apply"; + +export interface RunnerConfig { + mode: RunMode; + migrationsDir: string; + adapter: MigrationAdapter | null; +} + +export interface MigrationPlan { + alreadyApplied: string[]; + pending: MigrationEntry[]; + checksumMismatches: Array<{ id: string; expected: string; actual: string }>; +} + +export interface MigrationResult { + applied: string[]; + skipped: string[]; + failed: { id: string; error: string } | null; +} diff --git a/packages/db/src/types.ts b/packages/db/src/types.ts new file mode 100644 index 0000000..fad6973 --- /dev/null +++ b/packages/db/src/types.ts @@ -0,0 +1,20 @@ +// The migration manifest's shape. A "context" names the slice of the schema +// a migration belongs to: `control` is the runner's own tracking schema, +// `app` is the template's. Add contexts here when a port grows bounded +// contexts of its own. +export const BOUNDED_CONTEXTS = ["control", "app"] as const; + +export type BoundedContext = (typeof BOUNDED_CONTEXTS)[number]; + +export interface MigrationEntry { + id: string; + context: BoundedContext; + path: string; + checksum: string; + description: string; +} + +export interface MigrationManifest { + version: 1; + migrations: MigrationEntry[]; +} diff --git a/packages/db/tsconfig.build.json b/packages/db/tsconfig.build.json new file mode 100644 index 0000000..c6fb252 --- /dev/null +++ b/packages/db/tsconfig.build.json @@ -0,0 +1,7 @@ +{ + "extends": "./tsconfig.json", + "compilerOptions": { + "outDir": "dist", + "rootDir": "src" + } +} diff --git a/packages/db/tsconfig.json b/packages/db/tsconfig.json new file mode 100644 index 0000000..5a609a8 --- /dev/null +++ b/packages/db/tsconfig.json @@ -0,0 +1,10 @@ +{ + "extends": "../../tooling/tsconfig/base.json", + "compilerOptions": { + "module": "NodeNext", + "moduleResolution": "NodeNext", + "types": ["node"] + }, + "include": ["src/**/*.ts"], + "exclude": ["node_modules", "dist"] +} diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 965dfe6..85cf091 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -136,6 +136,45 @@ importers: specifier: ^4.151.0 version: 4.155.0(@types/node@22.20.5) + packages/db: + devDependencies: + '@app/eslint-config': + specifier: workspace:* + version: link:../../tooling/eslint + '@app/tsconfig': + specifier: workspace:* + version: link:../../tooling/tsconfig + '@types/node': + specifier: ^22.9.0 + version: 22.20.5 + typescript: + specifier: ^5.8.3 + version: 5.9.3 + + tests/db: + devDependencies: + '@app/eslint-config': + specifier: workspace:* + version: link:../../tooling/eslint + '@app/tsconfig': + specifier: workspace:* + version: link:../../tooling/tsconfig + '@electric-sql/pglite': + specifier: 0.5.8 + version: 0.5.8 + '@saas/db': + specifier: workspace:* + version: link:../../packages/db + '@types/node': + specifier: ^22.9.0 + version: 22.20.5 + typescript: + specifier: ^5.8.3 + version: 5.9.3 + vitest: + specifier: ^3.2.4 + version: 3.2.7(@types/node@22.20.5)(jiti@2.7.0)(jsdom@24.1.3)(lightningcss@1.32.0) + tests/web: devDependencies: '@app/eslint-config': @@ -258,6 +297,9 @@ packages: resolution: {integrity: sha512-Vd/9EVDiu6PPJt9yAh6roZP6El1xHrdvIVGjyBsHR0RYwNHgL7FJPyIIW4fANJNG6FtyZfvlRPpFI4ZM/lubvw==} engines: {node: '>=18'} + '@electric-sql/pglite@0.5.8': + resolution: {integrity: sha512-n9tsbUOhwx2epK1V0ZG9Ar4SHWUju04dhmzZXiSBXwBoleOvIfals33NAaWgagQVAL4Rbvx/Ptsu3P+pA09f6Q==} + '@emnapi/runtime@1.11.3': resolution: {integrity: sha512-Xz4Tpyki7XyrpbUK1jR1AhdAdaXyhhY4lZ3neLodmhpuWfy2PAQN5B46sAiU4liOXGLkHypn/qU+jvfWSCYYLA==} @@ -2853,6 +2895,8 @@ snapshots: '@csstools/css-tokenizer@3.0.4': {} + '@electric-sql/pglite@0.5.8': {} + '@emnapi/runtime@1.11.3': dependencies: tslib: 2.8.1 diff --git a/tests/db/component.yaml b/tests/db/component.yaml new file mode 100644 index 0000000..35b84f1 --- /dev/null +++ b/tests/db/component.yaml @@ -0,0 +1,23 @@ +apiVersion: sourceplane.io/v1 +kind: Component +metadata: + name: db-tests + description: The migrations' tests (the manifest, upstream's two migrations byte for byte, and the schema they leave on a Supabase-shaped Postgres in process — the profile trigger, the bucket and row-level security) +spec: + type: turbo-package + lifecycle: production + owner: platform + domain: tests + subscribe: + environments: + - name: dev + profile: quick-check + parameters: + nodeVersion: "22" + pnpmVersion: "10.12.1" + buildCommand: pnpm exec turbo run build --filter=./ + typecheckCommand: pnpm exec turbo run typecheck --filter=./ + preBuildCommand: pnpm exec turbo run test --filter=./ + labels: + team: platform + layer: test diff --git a/tests/db/eslint.config.js b/tests/db/eslint.config.js new file mode 100644 index 0000000..2e905dc --- /dev/null +++ b/tests/db/eslint.config.js @@ -0,0 +1,2 @@ +import config from "../../tooling/eslint/index.js"; +export default config; diff --git a/tests/db/package.json b/tests/db/package.json new file mode 100644 index 0000000..ad6e1e3 --- /dev/null +++ b/tests/db/package.json @@ -0,0 +1,21 @@ +{ + "name": "@app/db-tests", + "version": "0.0.0", + "private": true, + "type": "module", + "scripts": { + "build": "tsc --noEmit", + "typecheck": "tsc --noEmit", + "test": "vitest run", + "lint": "eslint src" + }, + "devDependencies": { + "@app/eslint-config": "workspace:*", + "@app/tsconfig": "workspace:*", + "@electric-sql/pglite": "0.5.8", + "@saas/db": "workspace:*", + "@types/node": "^22.9.0", + "typescript": "^5.8.3", + "vitest": "^3.2.4" + } +} diff --git a/tests/db/src/migrations.test.ts b/tests/db/src/migrations.test.ts new file mode 100644 index 0000000..3e93c41 --- /dev/null +++ b/tests/db/src/migrations.test.ts @@ -0,0 +1,84 @@ +import { describe, expect, it } from "vitest"; +import { createHash } from "node:crypto"; +import { readFileSync } from "node:fs"; +import * as path from "node:path"; +import { PGlite } from "@electric-sql/pglite"; +import { manifest } from "@saas/db/manifest"; +import { runMigrations } from "@saas/db/runner"; +import type { MigrationAdapter } from "@saas/db/runner"; +import { SUPABASE_PRELUDE } from "./supabase"; + +const migrationsDir = path.resolve(__dirname, "../../../packages/db/src/migrations"); + +// scosman/CMSaasStarter's supabase/migrations at 2e61406, by sha256: the app +// migrations are upstream's files byte for byte. +const UPSTREAM = { + "010_initial": "734210df1340e56e55fdff6eb71161f562814725030a1fde06b88456639e987c", // 20240730010101_initial.sql + "020_add_unsubscribed_to_profiles": "d45389f3e51aa9e3ea76c3fb2ecb9175cda644a201332282480fddb847150352", // 20240731051052_add_unsubscribed_to_profiles.sql +}; + +// The runner's adapter over an in-process Postgres (PGlite): the same calls +// the Management API adapter makes, one statement batch per call. +function pgliteAdapter(db: PGlite): MigrationAdapter { + return { + async connect() {}, + async disconnect() {}, + async acquireAdvisoryLock() { return true; }, + async releaseAdvisoryLock() {}, + async getAppliedMigrations() { + try { + const { rows } = await db.query<{ id: string; context: string; checksum: string; applied_at: string }>( + "select id, context, checksum, applied_at::text as applied_at from _migrations.applied order by id", + ); + return rows; + } catch (e) { + if (String(e).includes("does not exist")) return []; + throw e; + } + }, + async beginTransaction() {}, + async commitTransaction() {}, + async rollbackTransaction() {}, + async executeSql(sql) { await db.exec(sql); }, + async recordMigration(entry) { + await db.query( + "insert into _migrations.applied (id, context, checksum) values ($1, $2, $3) on conflict (id) do nothing", + [entry.id, entry.context, entry.checksum], + ); + }, + }; +} + +describe("the migration manifest (packages/db)", () => { + it("starts with the control migration and names every file with its checksum", () => { + expect(manifest.migrations[0]?.id).toBe("000_control_baseline"); + for (const entry of manifest.migrations) { + const file = readFileSync(path.join(migrationsDir, entry.path)); + expect(createHash("sha256").update(file).digest("hex"), entry.id).toBe(entry.checksum); + } + }); + + it("applies upstream's two migrations, byte for byte, in upstream's order", () => { + const app = manifest.migrations.filter((m) => m.context === "app"); + expect(app.map((m) => m.id)).toEqual(Object.keys(UPSTREAM)); + for (const entry of app) expect(entry.checksum, entry.id).toBe(UPSTREAM[entry.id as keyof typeof UPSTREAM]); + }); + + it("plans every migration as pending offline", async () => { + const result = await runMigrations(manifest, { mode: "plan", migrationsDir, adapter: null }); + expect(result.failed).toBeNull(); + expect(result.applied).toEqual(manifest.migrations.map((m) => m.id)); + }); + + it("applies every migration once to a Supabase-shaped Postgres, and a second apply applies nothing", async () => { + const db = new PGlite(); + await db.exec(SUPABASE_PRELUDE); + const first = await runMigrations(manifest, { mode: "apply", migrationsDir, adapter: pgliteAdapter(db) }); + expect(first.failed).toBeNull(); + expect(first.applied).toEqual(manifest.migrations.map((m) => m.id)); + const again = await runMigrations(manifest, { mode: "apply", migrationsDir, adapter: pgliteAdapter(db) }); + expect(again.failed).toBeNull(); + expect(again.applied).toEqual([]); + expect(again.skipped).toEqual(manifest.migrations.map((m) => m.id)); + }, 60_000); +}); diff --git a/tests/db/src/schema.test.ts b/tests/db/src/schema.test.ts new file mode 100644 index 0000000..9eee98c --- /dev/null +++ b/tests/db/src/schema.test.ts @@ -0,0 +1,117 @@ +import { beforeAll, describe, expect, it } from "vitest"; +import { readFileSync } from "node:fs"; +import * as path from "node:path"; +import { PGlite } from "@electric-sql/pglite"; +import { manifest } from "@saas/db/manifest"; +import { SUPABASE_PRELUDE } from "./supabase"; + +// The schema the app reads, as every migration db-migrate applies leaves it on +// a Supabase-shaped Postgres (PGlite, in process): the three tables with +// row-level security, the trigger that gives every new user a profile, the +// avatars bucket, and the profile policies — a user reads and writes their own +// row only, the anon key reads nothing, and the two server-only tables answer +// no API role at all (the app's server reaches them with the service-role key, +// which bypasses row-level security). +const migrationsDir = path.resolve(__dirname, "../../../packages/db/src/migrations"); + +async function migrated(): Promise { + const db = new PGlite(); + await db.exec(SUPABASE_PRELUDE); + for (const entry of manifest.migrations) { + await db.exec(readFileSync(path.join(migrationsDir, entry.path), "utf8")); + } + return db; +} + +async function as(db: PGlite, role: string, sub: string | null, fn: () => Promise): Promise { + await db.exec(`set role ${role}`); + await db.query("select set_config('request.jwt.claims', $1, false)", [sub ? JSON.stringify({ sub, role }) : ""]); + try { + return await fn(); + } finally { + await db.exec("reset role"); + await db.query("select set_config('request.jwt.claims', '', false)"); + } +} + +const ALICE = "00000000-0000-4000-8000-00000000a11c"; +const BOB = "00000000-0000-4000-8000-000000000b0b"; + +describe("the schema after every migration", () => { + let db: PGlite; + beforeAll(async () => { + db = await migrated(); + await db.query( + "insert into auth.users (id, email, raw_user_meta_data) values ($1, 'alice@example.invalid', $2), ($3, 'bob@example.invalid', '{}')", + [ALICE, JSON.stringify({ full_name: "Alice A", avatar_url: "https://example.invalid/a.png" }), BOB], + ); + }, 60_000); + + it("has the template's three tables, each with row-level security", async () => { + const { rows } = await db.query<{ relname: string; relrowsecurity: boolean }>(` + select c.relname, c.relrowsecurity from pg_class c join pg_namespace n on n.oid = c.relnamespace + where n.nspname = 'public' and c.relkind = 'r' order by c.relname`); + expect(rows).toEqual([ + { relname: "contact_requests", relrowsecurity: true }, + { relname: "profiles", relrowsecurity: true }, + { relname: "stripe_customers", relrowsecurity: true }, + ]); + }); + + it("gives every new user a profile, from their sign-up metadata, subscribed to email", async () => { + const { rows } = await db.query<{ id: string; full_name: string | null; avatar_url: string | null; unsubscribed: boolean }>( + "select id, full_name, avatar_url, unsubscribed from profiles order by full_name nulls last", + ); + expect(rows).toEqual([ + { id: ALICE, full_name: "Alice A", avatar_url: "https://example.invalid/a.png", unsubscribed: false }, + { id: BOB, full_name: null, avatar_url: null, unsubscribed: false }, + ]); + }); + + it("lets a signed-in user read and update their own profile, and nobody else's", async () => { + const seen = await as(db, "authenticated", ALICE, () => db.query<{ id: string }>("select id from profiles")); + expect(seen.rows.map((r) => r.id)).toEqual([ALICE]); + await as(db, "authenticated", ALICE, () => + db.query("update profiles set company_name = 'Acme', unsubscribed = true where id = $1", [ALICE])); + const touched = await as(db, "authenticated", ALICE, () => + db.query<{ n: number }>("with u as (update profiles set company_name = 'Hijack' where id = $1 returning 1) select count(*)::int as n from u", [BOB])); + expect(touched.rows[0]!.n).toBe(0); + const { rows } = await db.query<{ id: string; company_name: string | null; unsubscribed: boolean }>( + "select id, company_name, unsubscribed from profiles order by id"); + expect(rows).toEqual([ + { id: BOB, company_name: null, unsubscribed: false }, + { id: ALICE, company_name: "Acme", unsubscribed: true }, + ]); + }); + + it("refuses a profile written for somebody else", async () => { + await db.query("delete from profiles where id = $1", [BOB]); + await expect( + as(db, "authenticated", ALICE, () => db.query("insert into profiles (id, full_name) values ($1, 'not me')", [BOB])), + ).rejects.toThrow(/row-level security/); + }); + + it("shows the anon key nothing, and the server-only tables to no API role", async () => { + await db.query("insert into contact_requests (email, message_body) values ('x@example.invalid', 'hi')"); + await db.query("insert into stripe_customers (user_id, stripe_customer_id) values ($1, 'cus_1')", [ALICE]); + for (const [role, sub] of [["anon", null], ["authenticated", ALICE]] as const) { + for (const table of ["contact_requests", "stripe_customers"]) { + const { rows } = await as(db, role, sub, () => db.query<{ n: number }>(`select count(*)::int as n from ${table}`)); + expect(rows[0]!.n, `${role} on ${table}`).toBe(0); + } + } + const anonProfiles = await as(db, "anon", null, () => db.query<{ n: number }>("select count(*)::int as n from profiles")); + expect(anonProfiles.rows[0]!.n).toBe(0); + }); + + it("creates the avatars bucket, readable by anyone", async () => { + const { rows } = await db.query<{ id: string; name: string }>("select id, name from storage.buckets"); + expect(rows).toEqual([{ id: "avatars", name: "avatars" }]); + const { rows: policies } = await db.query<{ policyname: string; cmd: string }>( + "select policyname, cmd from pg_policies where schemaname = 'storage' order by policyname"); + expect(policies).toEqual([ + { policyname: "Anyone can upload an avatar.", cmd: "INSERT" }, + { policyname: "Avatar images are publicly accessible.", cmd: "SELECT" }, + ]); + }); +}); diff --git a/tests/db/src/supabase.ts b/tests/db/src/supabase.ts new file mode 100644 index 0000000..be144ee --- /dev/null +++ b/tests/db/src/supabase.ts @@ -0,0 +1,51 @@ +// What a Supabase project has before any migration runs, as far as this +// schema touches it: the API roles, `auth.users` and `auth.uid()`, and +// Storage's `buckets` and `objects`. Supabase creates these itself; a test +// database needs them for upstream's migration to mean here what it means +// there (a trigger on auth.users, policies keyed on auth.uid(), a bucket). +// +// auth.uid() reads the request's JWT subject the way Supabase's own does: +// PostgREST sets `request.jwt.claims` (and the older `request.jwt.claim.sub`) +// for every request it runs as `authenticated`. +export const SUPABASE_PRELUDE = ` +create role anon nologin; +create role authenticated nologin; +create role service_role nologin bypassrls; + +create schema auth; +create table auth.users ( + id uuid primary key default gen_random_uuid(), + email text, + raw_user_meta_data jsonb not null default '{}'::jsonb, + created_at timestamptz not null default now() +); +create function auth.uid() returns uuid language sql stable as $$ + select nullif( + coalesce( + current_setting('request.jwt.claim.sub', true), + (nullif(current_setting('request.jwt.claims', true), '')::jsonb ->> 'sub') + ), + '' + )::uuid +$$; + +create schema storage; +create table storage.buckets ( + id text primary key, + name text not null unique, + public boolean default false, + created_at timestamptz default now() +); +create table storage.objects ( + id uuid primary key default gen_random_uuid(), + bucket_id text references storage.buckets (id), + name text, + owner uuid, + created_at timestamptz default now() +); +alter table storage.objects enable row level security; + +grant usage on schema public, auth, storage to anon, authenticated, service_role; +grant execute on function auth.uid() to anon, authenticated; +alter default privileges in schema public grant all on tables to anon, authenticated, service_role; +`; diff --git a/tests/db/tsconfig.json b/tests/db/tsconfig.json new file mode 100644 index 0000000..47d9ecc --- /dev/null +++ b/tests/db/tsconfig.json @@ -0,0 +1,11 @@ +{ + "extends": "../../tooling/tsconfig/base.json", + "compilerOptions": { + "composite": false, + "declaration": false, + "declarationMap": false, + "noEmit": true, + "types": ["node"] + }, + "include": ["src/**/*.ts"] +} diff --git a/tests/db/vitest.config.ts b/tests/db/vitest.config.ts new file mode 100644 index 0000000..ce36a74 --- /dev/null +++ b/tests/db/vitest.config.ts @@ -0,0 +1,8 @@ +import { defineConfig } from "vitest/config"; + +export default defineConfig({ + test: { + include: ["src/**/*.test.ts"], + environment: "node", + }, +});