carlos / platform Public

plans 6c: approved price book, live path in stripe-setup.sh, runbook

Paul approved the draft's amounts on 2026-11-01. The approved book is a
new file and version, deploy/billing/pricebook-2026-11-01-v1.json, with
the same amounts, currencies and country map, priced against catalog
2026-10-20-v1 (what dev runs: 2026-10-20-v1@063079f07e32). Its price keys
are 2026-11-01-v1/<plan>/<cur> and 2026-11-01-v1/pack/<pack>/<cur>.

scripts/stripe-setup.sh gets --live. It needs STRIPE_LIVE_ACCOUNT naming
the live account (never the sandbox), refuses a book that is not
approved, passes --live on every call, and requires the account Stripe
reports, the balance and every object listed or made to be in the run's
mode. Dry run and --check work the same in live mode. The default book
is now the approved one, and the house coupon is named House.

cmd/console/stripesetup_script_test.go runs the script against a fake
stripe CLI (this test binary, as TestMain already does for aws): a live
apply, a sandbox apply, a live dry run that sends nothing, ten refusals,
and every repo book loading against the example catalog.

The runbook's live section now has Paul's decisions (book, tax as Tito
Go, sponsor_accounts_before for existing accounts, ops exempt), the tax
code as the accountant's to confirm, the script's live guards, and the
switch-on order: Paul's Stripe Tax, retries, live login and rk_live_
key, then our live run, the flagship's files, one restart, the readiness
check and a house Checkout at zero.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by claude agent, operated by paul@keymail.dev bcde967226d6b5031f3154709a3fdc3aa5662fb4 parent 030721e
5 files changed, +676 −83
  • cmd/console/main_test.go +4 −0
  • cmd/console/stripesetup_script_test.go +482 −0
  • deploy/billing/pricebook-2026-11-01-v1.json +23 −0
  • docs/superpowers/plans/2026-10-27-plans-6c-stripe-setup.md +83 −45
  • scripts/stripe-setup.sh +84 −38

CI cancelled — superseded by a newer push — run details

diff --git a/cmd/console/main_test.go b/cmd/console/main_test.go
index c498a46da..086b7f6f6 100644
--- a/cmd/console/main_test.go
+++ b/cmd/console/main_test.go
@@ -73,6 +73,10 @@ func TestMain(m *testing.M) {
if filepath.Base(os.Args[0]) == "aws" {
os.Exit(fakeAWS(os.Args[1:]))
}
+ // The fake stripe CLI for scripts/stripe-setup.sh (stripesetup_script_test.go).
+ if filepath.Base(os.Args[0]) == "stripe" {
+ os.Exit(fakeStripe(os.Args[1:]))
+ }
// The GeoIP verifier verb: openGeoIP re-runs its own binary to verify
// the override in a child process, and under `go test` that binary is
// this one.
diff --git a/cmd/console/stripesetup_script_test.go b/cmd/console/stripesetup_script_test.go
new file mode 100644
index 000000000..e07f94972
--- /dev/null
+++ b/cmd/console/stripesetup_script_test.go
@@ -0,0 +1,482 @@
+package main_test
+
+// scripts/stripe-setup.sh (plans 6c), run against a fake `stripe`: this test
+// binary, re-executed under the name stripe (TestMain). The fake keeps one
+// account's objects in world.json and logs every call's arguments, so the
+// tests can check the script's mode guards without ever reaching Stripe.
+
+import (
+ "encoding/json"
+ "errors"
+ "fmt"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "regexp"
+ "slices"
+ "strconv"
+ "strings"
+ "testing"
+
+ "github.com/carlosframework/platform/internal/plans"
+)
+
+const (
+ stripeSetupScript = "../../scripts/stripe-setup.sh"
+ approvedBook = "../../deploy/billing/pricebook-2026-11-01-v1.json"
+ draftBook = "../../deploy/billing/pricebook-2026-10-27-v1.json"
+ sandboxAccount = "acct_1UVFkoIiAD0xflDQ"
+ liveAccount = "acct_LiveTest1"
+)
+
+// fakeStripeWorld is the fake's account: its id, its mode and its objects
+// by list path (products, prices, coupons, ...).
+type fakeStripeWorld struct {
+ Account string `json:"account"`
+ Live bool `json:"live"`
+ Objects map[string][]map[string]any `json:"objects"`
+ Next int `json:"next"`
+}
+
+var stripeIDPrefix = map[string]string{
+ "products": "prod_", "prices": "price_", "billing_portal/configurations": "bpc_",
+ "coupons": "house", "webhook_endpoints": "we_",
+}
+
+func fakeStripe(args []string) int {
+ dir := os.Getenv("FAKE_STRIPE_DIR")
+ if f, err := os.OpenFile(filepath.Join(dir, "calls.jsonl"), os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o600); err == nil {
+ b, _ := json.Marshal(args)
+ f.Write(append(b, '\n'))
+ f.Close()
+ }
+ worldPath := filepath.Join(dir, "world.json")
+ var w fakeStripeWorld
+ if b, err := os.ReadFile(worldPath); err != nil || json.Unmarshal(b, &w) != nil {
+ fmt.Fprintln(os.Stderr, "fake stripe: no world")
+ return 99
+ }
+ if len(args) < 2 {
+ fmt.Fprintln(os.Stderr, "fake stripe: no verb and path")
+ return 99
+ }
+ verb, path := args[0], args[1]
+ var data [][2]string
+ for i := 2; i < len(args); i++ {
+ switch args[i] {
+ case "--confirm", "--live":
+ case "--stripe-version", "--project-name", "-i":
+ i++
+ case "-d":
+ i++
+ k, v, _ := strings.Cut(args[i], "=")
+ data = append(data, [2]string{k, v})
+ default:
+ fmt.Fprintf(os.Stderr, "fake stripe: unexpected argument %q\n", args[i])
+ return 99
+ }
+ }
+ reply := func(v any) int {
+ b, _ := json.Marshal(v)
+ fmt.Println(string(b))
+ return 0
+ }
+ param := func(k string) string {
+ for _, d := range data {
+ if d[0] == k {
+ return d[1]
+ }
+ }
+ return ""
+ }
+ kind := strings.TrimPrefix(path, "/v1/")
+ switch {
+ case verb == "get" && kind == "account":
+ return reply(map[string]any{"id": w.Account, "object": "account"})
+ case verb == "get" && kind == "balance":
+ return reply(map[string]any{"object": "balance", "livemode": w.Live})
+ case verb == "get" && stripeIDPrefix[kind] != "":
+ list := []map[string]any{}
+ for _, o := range w.Objects[kind] {
+ if kind == "prices" && param("product") != "" && o["product"] != param("product") {
+ continue
+ }
+ list = append(list, o)
+ }
+ if param("limit") == "1" && len(list) > 1 {
+ list = list[:1]
+ }
+ return reply(map[string]any{"object": "list", "data": list, "has_more": false})
+ case verb == "post" && stripeIDPrefix[kind] != "":
+ o := nestForm(data)
+ w.Next++
+ o["id"] = stripeIDPrefix[kind] + "Fake" + strconv.Itoa(w.Next)
+ o["livemode"] = w.Live
+ switch kind {
+ case "products":
+ o["active"] = true
+ case "prices":
+ o["active"] = true
+ o["transform_quantity"] = nil
+ o["currency_options"] = map[string]any{o["currency"].(string): map[string]any{
+ "unit_amount": o["unit_amount"], "tax_behavior": o["tax_behavior"]}}
+ case "billing_portal/configurations":
+ o["active"] = true
+ case "coupons":
+ o["valid"] = true
+ o["amount_off"], o["max_redemptions"], o["redeem_by"] = nil, nil, nil
+ o["applies_to"] = map[string]any{"products": []any{}}
+ case "webhook_endpoints":
+ o["status"] = "enabled"
+ o["secret"] = "whsec_FakeSecret"
+ }
+ stored := map[string]any{}
+ for k, v := range o {
+ if k != "secret" {
+ stored[k] = v
+ }
+ }
+ if w.Objects == nil {
+ w.Objects = map[string][]map[string]any{}
+ }
+ w.Objects[kind] = append(w.Objects[kind], stored)
+ b, _ := json.Marshal(w)
+ if err := os.WriteFile(worldPath, b, 0o600); err != nil {
+ return 99
+ }
+ return reply(o)
+ }
+ fmt.Fprintf(os.Stderr, "fake stripe: unexpected call %s %s\n", verb, path)
+ return 99
+}
+
+// nestForm turns Stripe form pairs (a[b][c]=v, a[]=v) into an object, with
+// numbers and booleans as Stripe would answer them.
+func nestForm(data [][2]string) map[string]any {
+ root := map[string]any{}
+ for _, d := range data {
+ if d[0] == "expand[]" {
+ continue
+ }
+ parts := strings.Split(strings.ReplaceAll(d[0], "]", ""), "[")
+ var v any = d[1]
+ if n, err := strconv.ParseInt(d[1], 10, 64); err == nil {
+ v = n
+ } else if d[1] == "true" || d[1] == "false" {
+ v = d[1] == "true"
+ }
+ list := parts[len(parts)-1] == ""
+ if list {
+ parts = parts[:len(parts)-1]
+ }
+ m := root
+ for _, p := range parts[:len(parts)-1] {
+ next, ok := m[p].(map[string]any)
+ if !ok {
+ next = map[string]any{}
+ m[p] = next
+ }
+ m = next
+ }
+ leaf := parts[len(parts)-1]
+ if list {
+ l, _ := m[leaf].([]any)
+ m[leaf] = append(l, v)
+ } else {
+ m[leaf] = v
+ }
+ }
+ return root
+}
+
+// stripeWorld is one test's fake Stripe account, its PATH and its scratch.
+type stripeWorld struct {
+ t *testing.T
+ dir, bin string
+}
+
+func newStripeWorld(t *testing.T, account string, live bool) *stripeWorld {
+ t.Helper()
+ for _, tool := range []string{"bash", "jq"} {
+ if _, err := exec.LookPath(tool); err != nil {
+ t.Skipf("%s not installed", tool)
+ }
+ }
+ exe, err := os.Executable()
+ if err != nil {
+ t.Fatal(err)
+ }
+ dir := t.TempDir()
+ w := &stripeWorld{t: t, dir: dir, bin: filepath.Join(dir, "bin")}
+ if err := os.MkdirAll(w.bin, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.Symlink(exe, filepath.Join(w.bin, "stripe")); err != nil {
+ t.Fatal(err)
+ }
+ w.save(fakeStripeWorld{Account: account, Live: live, Objects: map[string][]map[string]any{}})
+ return w
+}
+
+func (w *stripeWorld) save(fw fakeStripeWorld) {
+ writeJSON(w.t, filepath.Join(w.dir, "world.json"), fw)
+}
+
+func (w *stripeWorld) load() fakeStripeWorld {
+ w.t.Helper()
+ var fw fakeStripeWorld
+ b, err := os.ReadFile(filepath.Join(w.dir, "world.json"))
+ if err != nil || json.Unmarshal(b, &fw) != nil {
+ w.t.Fatalf("read the fake's world: %v", err)
+ }
+ return fw
+}
+
+// calls is every call the fake has answered so far.
+func (w *stripeWorld) calls() [][]string {
+ w.t.Helper()
+ b, err := os.ReadFile(filepath.Join(w.dir, "calls.jsonl"))
+ if errors.Is(err, os.ErrNotExist) {
+ return nil
+ }
+ if err != nil {
+ w.t.Fatal(err)
+ }
+ var out [][]string
+ for _, line := range strings.Split(strings.TrimSpace(string(b)), "\n") {
+ var c []string
+ if err := json.Unmarshal([]byte(line), &c); err != nil {
+ w.t.Fatal(err)
+ }
+ out = append(out, c)
+ }
+ return out
+}
+
+func posts(calls [][]string) int {
+ n := 0
+ for _, c := range calls {
+ if c[0] == "post" {
+ n++
+ }
+ }
+ return n
+}
+
+// run runs the script with the fake first on PATH and no Stripe settings
+// from the caller's environment.
+func (w *stripeWorld) run(env []string, args ...string) (string, string, int) {
+ w.t.Helper()
+ cmd := exec.Command(stripeSetupScript, args...)
+ for _, e := range os.Environ() {
+ if !strings.HasPrefix(e, "STRIPE_") && !strings.HasPrefix(e, "PORTAL_") && !strings.HasPrefix(e, "PRICE_BOOK") &&
+ !strings.HasPrefix(e, "HOUSE_COUPON_NAME=") && !strings.HasPrefix(e, "PRODUCT_NAME_") && !strings.HasPrefix(e, "PATH=") {
+ cmd.Env = append(cmd.Env, e)
+ }
+ }
+ cmd.Env = append(cmd.Env, "PATH="+w.bin+string(os.PathListSeparator)+os.Getenv("PATH"),
+ "FAKE_STRIPE_DIR="+w.dir, "CONSOLE_URL=https://console.example.com")
+ cmd.Env = append(cmd.Env, env...)
+ var stdout, stderr strings.Builder
+ cmd.Stdout, cmd.Stderr = &stdout, &stderr
+ err := cmd.Run()
+ code := 0
+ var ee *exec.ExitError
+ if errors.As(err, &ee) {
+ code = ee.ExitCode()
+ } else if err != nil {
+ w.t.Fatalf("run the script: %v", err)
+ }
+ return stdout.String(), stderr.String(), code
+}
+
+// A live --apply passes --live on every call, makes the whole set in live
+// mode from the approved book, and a second run makes nothing.
+func TestStripeSetupLiveApply(t *testing.T) {
+ w := newStripeWorld(t, liveAccount, true)
+ env := []string{"STRIPE_LIVE_ACCOUNT=" + liveAccount}
+ stdout, stderr, code := w.run(env, "--live", "--apply")
+ if code != 0 {
+ t.Fatalf("live --apply failed (%d):\n%s\n%s", code, stdout, stderr)
+ }
+ calls := w.calls()
+ for _, c := range calls {
+ if !slices.Contains(c, "--live") {
+ t.Fatalf("a live run made a call without --live: %q", c)
+ }
+ }
+ fw := w.load()
+ counts := map[string]int{"products": 8, "prices": 24, "billing_portal/configurations": 1, "coupons": 1, "webhook_endpoints": 1}
+ for kind, want := range counts {
+ if got := len(fw.Objects[kind]); got != want {
+ t.Errorf("%s: made %d, want %d", kind, got, want)
+ }
+ for _, o := range fw.Objects[kind] {
+ if o["livemode"] != true {
+ t.Errorf("%s %v is not live", kind, o["id"])
+ }
+ }
+ }
+ for _, p := range fw.Objects["prices"] {
+ if k, _ := p["lookup_key"].(string); !strings.HasPrefix(k, "2026-11-01-v1/") {
+ t.Errorf("price %v has lookup key %q, not one of the approved book's", p["id"], k)
+ }
+ }
+ if c := fw.Objects["coupons"][0]; c["name"] != "House" {
+ t.Errorf("house coupon name %v, want House", c["name"])
+ }
+ if we := fw.Objects["webhook_endpoints"][0]; we["url"] != "https://console.example.com/billing/webhook" || we["api_version"] != "2025-02-24.acacia" {
+ t.Errorf("webhook endpoint %v at %v", we["url"], we["api_version"])
+ }
+ for _, want := range []string{"CARLOS_BILLING=live", `"2026-11-01-v1/pack/apps/gbp":"price_`, "rk_live_"} {
+ if !strings.Contains(stdout, want) {
+ t.Errorf("stdout lacks %q:\n%s", want, stdout)
+ }
+ }
+ if !strings.Contains(stderr, "CARLOS_STRIPE_WEBHOOK_SECRET=whsec_FakeSecret") || strings.Contains(stdout, "whsec_FakeSecret") {
+ t.Errorf("the signing secret must go to stderr only")
+ }
+
+ before := len(calls)
+ if stdout, stderr, code := w.run(env, "--live", "--check"); code != 0 {
+ t.Fatalf("live --check after apply failed (%d):\n%s\n%s", code, stdout, stderr)
+ }
+ if n := posts(w.calls()[before:]); n != 0 {
+ t.Fatalf("live --check made %d writes", n)
+ }
+}
+
+// A sandbox --apply still never passes --live and makes test-mode objects.
+func TestStripeSetupSandboxApply(t *testing.T) {
+ w := newStripeWorld(t, sandboxAccount, false)
+ if stdout, stderr, code := w.run(nil, "--apply"); code != 0 {
+ t.Fatalf("sandbox --apply failed (%d):\n%s\n%s", code, stdout, stderr)
+ }
+ for _, c := range w.calls() {
+ if slices.Contains(c, "--live") {
+ t.Fatalf("a sandbox run passed --live: %q", c)
+ }
+ }
+ for kind, objs := range w.load().Objects {
+ for _, o := range objs {
+ if o["livemode"] != false {
+ t.Errorf("%s %v is live", kind, o["id"])
+ }
+ }
+ }
+}
+
+// A live dry run sends nothing and prints every call with --live.
+func TestStripeSetupLiveDryRunSendsNothing(t *testing.T) {
+ w := newStripeWorld(t, liveAccount, true)
+ stdout, stderr, code := w.run([]string{"STRIPE_LIVE_ACCOUNT=" + liveAccount}, "--live")
+ if code != 0 {
+ t.Fatalf("live dry run failed (%d):\n%s\n%s", code, stdout, stderr)
+ }
+ if n := len(w.calls()); n != 0 {
+ t.Fatalf("a dry run made %d calls", n)
+ }
+ printed := 0
+ for _, line := range strings.Split(stdout, "\n") {
+ if strings.HasPrefix(line, "stripe ") {
+ printed++
+ if !strings.Contains(line, " --live") {
+ t.Errorf("printed call without --live: %s", line)
+ }
+ }
+ }
+ if printed == 0 || !strings.Contains(stdout, "2026-11-01-v1/personal/usd") || !strings.Contains(stdout, "CARLOS_BILLING=live") {
+ t.Fatalf("the dry run printed no live plan:\n%s", stdout)
+ }
+}
+
+// Every way into the wrong mode or the wrong account stops before a write.
+func TestStripeSetupLiveRefusals(t *testing.T) {
+ // The live product comes first, so the preflight's one-product read
+ // passes and the full listing is what has to catch the test one.
+ liveProduct := map[string]any{"id": "prod_Live", "object": "product", "active": true, "livemode": true,
+ "metadata": map[string]any{"carlos_product": "other"}}
+ testProduct := map[string]any{"id": "prod_Test", "object": "product", "active": true, "livemode": false,
+ "metadata": map[string]any{"carlos_product": "personal"}}
+ cases := []struct {
+ name string
+ account string
+ live bool
+ seed []map[string]any // the world's products
+ env []string
+ args []string
+ want string
+ noCallsAt bool // refused before any call to Stripe
+ }{
+ {name: "no second confirmation", account: liveAccount, live: true, args: []string{"--live", "--check"},
+ want: "STRIPE_LIVE_ACCOUNT", noCallsAt: true},
+ {name: "draft book", account: liveAccount, live: true, args: []string{"--live"},
+ env: []string{"STRIPE_LIVE_ACCOUNT=" + liveAccount, "PRICE_BOOK=" + draftBook}, want: "approved", noCallsAt: true},
+ {name: "sandbox named as live", account: sandboxAccount, live: false, args: []string{"--live", "--apply"},
+ env: []string{"STRIPE_LIVE_ACCOUNT=" + sandboxAccount}, want: "Sandbox", noCallsAt: true},
+ {name: "test key with --live", account: liveAccount, live: true, args: []string{"--live", "--apply"},
+ env: []string{"STRIPE_LIVE_ACCOUNT=" + liveAccount, "STRIPE_API_KEY=rk_test_x"}, want: "not a live key", noCallsAt: true},
+ {name: "live account without --live", account: liveAccount, live: true, args: []string{"--apply"},
+ env: []string{"STRIPE_LIVE_ACCOUNT=" + liveAccount}, want: "--live is not", noCallsAt: true},
+ {name: "live key without --live", account: sandboxAccount, live: false, args: []string{"--apply"},
+ env: []string{"STRIPE_API_KEY=rk_live_x"}, want: "live key", noCallsAt: true},
+ {name: "stripe answers in test mode", account: liveAccount, live: false, args: []string{"--live", "--apply"},
+ env: []string{"STRIPE_LIVE_ACCOUNT=" + liveAccount}, want: "balance is not in live mode"},
+ {name: "another live account", account: "acct_Other", live: true, args: []string{"--live", "--apply"},
+ env: []string{"STRIPE_LIVE_ACCOUNT=" + liveAccount}, want: "not " + liveAccount},
+ {name: "a test object in a live list", account: liveAccount, live: true, seed: []map[string]any{liveProduct, testProduct},
+ args: []string{"--live", "--apply"}, env: []string{"STRIPE_LIVE_ACCOUNT=" + liveAccount}, want: "not in live mode"},
+ {name: "a sandbox run against live", account: sandboxAccount, live: true, args: []string{"--apply"},
+ want: "balance is not in test mode"},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ w := newStripeWorld(t, tc.account, tc.live)
+ if tc.seed != nil {
+ w.save(fakeStripeWorld{Account: tc.account, Live: tc.live,
+ Objects: map[string][]map[string]any{"products": tc.seed}})
+ }
+ stdout, stderr, code := w.run(tc.env, tc.args...)
+ if code == 0 {
+ t.Fatalf("not refused:\n%s", stdout)
+ }
+ if !strings.Contains(stderr, tc.want) {
+ t.Fatalf("refusal %q lacks %q", stderr, tc.want)
+ }
+ calls := w.calls()
+ if tc.noCallsAt && len(calls) != 0 {
+ t.Fatalf("refused after %d calls to Stripe, want none", len(calls))
+ }
+ if n := posts(calls); n != 0 {
+ t.Fatalf("refused after %d writes", n)
+ }
+ })
+ }
+}
+
+// Every book in deploy/billing loads against the example catalog (the one
+// dev runs), and the newest one is approved for live.
+func TestRepoPriceBooksLoad(t *testing.T) {
+ cat, err := plans.LoadCatalog("../../internal/plans/testdata/example-catalog.json")
+ if err != nil {
+ t.Fatal(err)
+ }
+ files, _ := filepath.Glob("../../deploy/billing/pricebook-*.json")
+ if len(files) == 0 {
+ t.Fatal("no price books")
+ }
+ slices.Sort(files)
+ name := regexp.MustCompile(`pricebook-(.+)\.json$`)
+ for _, f := range files {
+ book, err := plans.LoadPriceBook(f, cat)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if v := name.FindStringSubmatch(f)[1]; book.Version != v {
+ t.Errorf("%s holds version %q", f, book.Version)
+ }
+ }
+ if newest, _ := plans.LoadPriceBook(files[len(files)-1], cat); !newest.Approved() || files[len(files)-1] != approvedBook {
+ t.Errorf("the newest book %s is not the approved one", files[len(files)-1])
+ }
+}
diff --git a/deploy/billing/pricebook-2026-11-01-v1.json b/deploy/billing/pricebook-2026-11-01-v1.json
new file mode 100644
index 000000000..a046526a4
--- /dev/null
+++ b/deploy/billing/pricebook-2026-11-01-v1.json
@@ -0,0 +1,23 @@
+{
+ "version": "2026-11-01-v1",
+ "status": "approved",
+ "catalog_version": "2026-10-20-v1",
+ "default_currency": "usd",
+ "currencies": ["usd", "eur", "gbp"],
+ "country_currency": {
+ "eur": ["AT", "BE", "BG", "HR", "CY", "CZ", "DK", "EE", "FI", "FR", "DE", "GR", "HU", "IE", "IT", "LV", "LT", "LU", "MT", "NL", "PL", "PT", "RO", "SK", "SI", "ES", "SE"],
+ "gbp": ["GB"]
+ },
+ "plans": {
+ "personal": {"usd": 2800, "eur": 2400, "gbp": 2200},
+ "community": {"usd": 600, "eur": 500, "gbp": 450},
+ "business": {"usd": 6000, "eur": 5000, "gbp": 4500}
+ },
+ "packs": {
+ "apps": {"usd": 1200, "eur": 1000, "gbp": 900},
+ "disk": {"usd": 3600, "eur": 3100, "gbp": 2800},
+ "storage": {"usd": 1200, "eur": 1000, "gbp": 900},
+ "email": {"usd": 2400, "eur": 2100, "gbp": 1900},
+ "bandwidth": {"usd": 4800, "eur": 4100, "gbp": 3800}
+ }
+}
diff --git a/docs/superpowers/plans/2026-10-27-plans-6c-stripe-setup.md b/docs/superpowers/plans/2026-10-27-plans-6c-stripe-setup.md
index 63ef23539..2e6e66ead 100644
--- a/docs/superpowers/plans/2026-10-27-plans-6c-stripe-setup.md
+++ b/docs/superpowers/plans/2026-10-27-plans-6c-stripe-setup.md
@@ -1,16 +1,18 @@
# Plans 6c: Stripe setup runbook
-This runbook sets up the Stripe objects that console billing (Plans 6a and 6b, merged to main) reads when it starts. It runs in the Carloku Sandbox first (`acct_1UVFkoIiAD0xflDQ`) against the dev console. Live setup is a later step, and only Paul can approve it.
+This runbook sets up the Stripe objects that console billing (Plans 6a and 6b, merged to main) reads when it starts. It runs in the Carloku Sandbox (`acct_1UVFkoIiAD0xflDQ`) against the dev console, and in the live Carloku account against the flagship console (section 6).
It replaces the outline at the end of `2026-10-25-plans-6b-checkout-flow.md` ("Plan 6c: Stripe setup runbook (outline)"). Where the outline and the code differ, the code wins, and the differences are listed below.
-Three files come with it:
+These files come with it:
-- `scripts/stripe-setup.sh` makes the objects with the stripe CLI. It runs in a sandbox or test mode only.
-- `deploy/billing/pricebook-2026-10-27-v1.json` is the price book the prices are made from. It is a `draft`.
+- `scripts/stripe-setup.sh` makes the objects with the stripe CLI, in the sandbox by default and in live mode with `--live` (section 6.3).
+- `deploy/billing/pricebook-2026-11-01-v1.json` is the price book the prices are made from. It is `approved` (Paul, 2026-11-01), and it is the script's default.
+- `deploy/billing/pricebook-2026-10-27-v1.json` is the draft it was approved from, with the same amounts. It stays as it is.
+- `cmd/console/stripesetup_script_test.go` runs the script against a fake stripe CLI and checks its mode guards. No test calls Stripe.
- This runbook.
-Nobody has run any of it against Stripe yet.
+This file records no run against Stripe yet.
## 1. What the console needs
@@ -21,7 +23,7 @@ Nobody has run any of it against Stripe yet.
| The locked customer portal configuration | 1 | `CARLOS_STRIPE_PORTAL_CONFIGURATION` |
| The house coupon | 1 | `CARLOS_STRIPE_HOUSE_COUPON` |
| The webhook endpoint at `https://<console>/billing/webhook` | 1 | its signing secret goes to `CARLOS_STRIPE_WEBHOOK_SECRET` |
-| A restricted `rk_test_` key, made by Paul in the Dashboard | 1 | `CARLOS_STRIPE_SECRET_KEY` |
+| A restricted key, `rk_test_` or `rk_live_`, made by Paul in the Dashboard | 1 | `CARLOS_STRIPE_SECRET_KEY` |
The amounts, in minor units a year:
@@ -60,9 +62,9 @@ The console records each book version's digest the first time it starts with it.
### Price keys and the price map (`internal/billing/prices.go`)
-- A plan's key is `<book>/<plan>/<currency>`. A pack's key is `<book>/pack/<pack>/<currency>` (`prices.go:35-42`). With this book that gives keys like `2026-10-27-v1/personal/usd`, `2026-10-27-v1/community/eur` and `2026-10-27-v1/pack/apps/gbp`.
+- A plan's key is `<book>/<plan>/<currency>`. A pack's key is `<book>/pack/<pack>/<currency>` (`prices.go:35-42`). The book's version is part of every key, so the approved book has keys of its own: `2026-11-01-v1/personal/usd`, `2026-11-01-v1/community/eur`, `2026-11-01-v1/pack/apps/gbp` and so on, 24 in all.
- The currency must be `usd`, `eur` or `gbp`, lower case (`prices.go:59`, `internal/plans/pricebook.go:34`).
-- `CARLOS_BILLING_PRICES` is one JSON object from price key to Stripe price id, for example `{"2026-10-27-v1/personal/usd":"price_..."}` (`prices.go:77-119`). Each id must match `^price_[A-Za-z0-9]{1,250}$` (`prices.go:26`). The same key twice is refused (`prices.go:92`), and so is one id under two keys (`prices.go:104`). Every price of the configured book must be in it (`prices.go:113-117`). Keys of other book versions are allowed, so a subscription bought under an older book keeps working (`prices.go:107`). The whole value is at most 64 KiB (`prices.go:24`).
+- `CARLOS_BILLING_PRICES` is one JSON object from price key to Stripe price id, for example `{"2026-11-01-v1/personal/usd":"price_..."}` (`prices.go:77-119`). Each id must match `^price_[A-Za-z0-9]{1,250}$` (`prices.go:26`). The same key twice is refused (`prices.go:92`), and so is one id under two keys (`prices.go:104`). Every price of the configured book must be in it (`prices.go:113-117`). Keys of other book versions are allowed, so a subscription bought under an older book keeps working (`prices.go:107`). The whole value is at most 64 KiB (`prices.go:24`).
- In a systemd EnvironmentFile the value must be inside single quotes. Without them, systemd treats the JSON's double quotes as quoting and strips them. The script prints it that way.
### Each price (`internal/billingstripe/adapter.go:385-449`)
@@ -89,14 +91,14 @@ The code never reads a price's `lookup_key`. The script sets `lookup_key` to the
- Every paid plan in the catalog is priced, and nothing else is (`:183-205`). Every pack a paid plan offers is priced, and nothing else is (`:206-218`). No paid plan may be called `pack` (`:191`).
- Each price is above 0 and at most 100,000,000 minor units (`:41`, `:233-238`), in exactly the book's currencies (`:228-244`).
-`deploy/billing/pricebook-2026-10-27-v1.json` is priced against catalog `2026-10-20-v1`, the spec's catalog (`internal/plans/testdata/example-catalog.json:2`). It loads cleanly:
+Both books are priced against catalog `2026-10-20-v1`, the spec's catalog (`internal/plans/testdata/example-catalog.json:2`). That is the catalog dev runs: on 2026-11-01 the dev bucket's `control/plans.json` said `2026-10-20-v1@063079f07e32`, the example catalog's exact id. The flagship runs no catalog yet. Both books load cleanly, and `TestRepoPriceBooksLoad` keeps it so:
```sh
go run ./cmd/pricebook-export -catalog internal/plans/testdata/example-catalog.json \
- -book deploy/billing/pricebook-2026-10-27-v1.json
+ -book deploy/billing/pricebook-2026-11-01-v1.json
```
-Its `country_currency` list is the one from the example book: the 27 EU states pay in eur, GB in gbp and everyone else in usd. That list gets approved together with the amounts.
+Its `country_currency` list is the one from the example book: the 27 EU states pay in eur, GB in gbp and everyone else in usd. Paul approved it with the amounts.
Plan 6a's outline expects deployment catalogs and books to live in the deployment's own infrastructure repo, in a `plans/` directory that Plan 7 creates. Until that exists, the book lives here, and the console box keeps a copy at the path `CARLOS_PRICE_BOOK` names.
@@ -169,7 +171,7 @@ Everything in this section happens in the Carloku Sandbox (`acct_1UVFkoIiAD0xflD
### 4.1 Before you start
- The dev console runs a build that includes Plans 6a and 6b, with billing off. `https://platform.dev.carlosframework.com/billing/webhook` answers 404.
-- The dev console has a plan catalog with version `2026-10-20-v1` (spec §12 step 2). Check with `systemctl cat console.service` and the environment it loads. If it has none, install `internal/plans/testdata/example-catalog.json` as `/etc/carlos/plans.json` and set `CARLOS_PLAN_CATALOG`. A catalog puts limits on every account, so mark every existing dev account sponsored straight after (`docs/site/plans.md`, "Sponsored accounts"). `carlos accounts plan` only works once a catalog is configured.
+- The dev console has a plan catalog with version `2026-10-20-v1`. It has had one since 2026-10-28 (the marker above). If it ever has none, install `internal/plans/testdata/example-catalog.json` as `/etc/carlos/plans.json`, with `sponsor_accounts_before` set as in 6.4, and set `CARLOS_PLAN_CATALOG`.
- The stripe CLI is logged in to the sandbox: `stripe login`, then pick the Carloku Sandbox. Unset `STRIPE_API_KEY` in that shell; the script refuses a live key there anyway.
### 4.2 Run the script
@@ -178,7 +180,7 @@ From a checkout of main:
```sh
export CONSOLE_URL=https://platform.dev.carlosframework.com
-export STRIPE_TAX_CODE=txcd_10103000 # the sandbox code; the default
+export STRIPE_TAX_CODE=txcd_10103000 # the default; see 6.2
scripts/stripe-setup.sh # dry run: sends nothing, prints every command
scripts/stripe-setup.sh --check # reads only: what exists, what is wrong, what is missing
scripts/stripe-setup.sh --apply # makes what is missing
@@ -189,7 +191,7 @@ Optional inputs: `PORTAL_HEADLINE`, `PORTAL_PRIVACY_URL`, `PORTAL_TERMS_URL`, `P
What the script does:
-- It checks that the CLI is on the expected account (`STRIPE_ACCOUNT`, default `acct_1UVFkoIiAD0xflDQ`) and in test mode. Every object it reads or makes must say `livemode: false`. It never passes `--live`.
+- It checks that the CLI is on the expected account (`STRIPE_ACCOUNT`, default `acct_1UVFkoIiAD0xflDQ`) and in test mode: `GET /v1/balance` must say `livemode: false`. Every object it reads or makes must say `livemode: false`. Without `--live` it never passes `--live`, and it refuses a live `STRIPE_API_KEY` or a set `STRIPE_LIVE_ACCOUNT`.
- It finds existing objects first: products by `metadata[carlos_product]`, prices by `lookup_key` or `metadata[price_key]` on their product, the portal configuration by `metadata[carlos_portal]=locked`, the coupon by `metadata[carlos_coupon]=house` and the endpoint by its URL. It looks only at live objects: active products, prices and portal configurations, valid coupons and enabled endpoints. It makes only what is missing, so running it twice makes nothing the second time.
- It never deletes, archives or edits anything. If something exists but breaks a rule in section 2, it stops, names the object and the rule, and leaves the fix to you in the Dashboard.
- Each create carries an idempotency key (`stripe-setup:<kind>:<name>`). If a response gets lost, running again within 24 hours returns the same object instead of a second one.
@@ -220,14 +222,15 @@ All of this happens in the sandbox. The CLI cannot do it, or should not.
| Products | Read | readiness |
| Coupons | Read | readiness reads the house coupon |
| Invoices | Read | the late-restore check (Call 18, granted 2026-10-25) |
+ | Accounts | Read | the readiness check's account match, `GET /v1/account` |
Leave these at None: Refunds, Charges, Events, Webhook endpoints, API keys and Subscription schedules.
- The readiness check also reads `GET /v1/account`. The outline has no row for it. Save the key with the list above, start the console (4.4), and read its log. If the check fails with "reading the account", give the key the narrowest read of the account the Dashboard offers, and write down here which row that was.
+ The outline had no row for `GET /v1/account`. The sandbox key has Accounts Read for it. If the readiness check still fails with "reading the account", note here which row fixed it.
If the Dashboard shows subscription items on a row of its own, set it to Write.
- The key starts `rk_test_`. Stripe shows it once. It goes straight into the console's EnvironmentFile (4.4) and nowhere else: not a file in a repo, not a ticket, not a chat.
+ The key starts `rk_test_`. Stripe shows it once. It goes into 1Password and the console's EnvironmentFile (4.4), and nowhere else: not a file in a repo, not a ticket, not a chat.
### 4.4 The dev console's environment
@@ -240,7 +243,7 @@ The dev console's systemd unit, `/etc/systemd/system/console.service`, exists on
```
`/etc/carlos/host.env` is shared with the box's other units, so the Stripe secrets do not go there.
-2. Copy `deploy/billing/pricebook-2026-10-27-v1.json` to `/etc/carlos/pricebook-2026-10-27-v1.json` (root:root 0644). Never edit it in place afterwards (section 2).
+2. Copy `deploy/billing/pricebook-2026-11-01-v1.json` to `/etc/carlos/pricebook-2026-11-01-v1.json` (root:root 0644). Never edit it in place afterwards (section 2).
3. Write `/etc/carlos/billing.env`, root:root, mode 0600, holding:
- the block the script printed (`CARLOS_BILLING=test`, `CARLOS_PLAN_CATALOG`, `CARLOS_PRICE_BOOK`, `CARLOS_BILLING_PRICES` in single quotes, `CARLOS_STRIPE_ACCOUNT`, `CARLOS_STRIPE_PORTAL_CONFIGURATION`, `CARLOS_STRIPE_HOUSE_COUPON`);
- `CARLOS_STRIPE_SECRET_KEY=rk_test_...`, the key from 4.3;
@@ -294,48 +297,83 @@ Also record the answers to the questions the code leaves open:
- [ ] What shape Stripe returns for a single-currency price's expanded `currency_options` (`adapter.go:422-429`). Either shape passes.
- [ ] Whether `name` was accepted in the portal's `allowed_updates` (4.2).
-- [ ] Which Dashboard row lets the key read `GET /v1/account` (4.3).
+- [ ] That Accounts Read is enough for `GET /v1/account` (4.3).
-## 6. Live, later, with Paul's approval
+## 6. Live
-### Decided so far (Paul)
+### 6.1 Decided (Paul)
-- **Product names, approved 2026-10-31 (copy review):** Personal, Community, Business, Apps pack, Disk pack, Storage pack, Email pack, Bandwidth pack: the script's defaults. Set `HOUSE_COUPON_NAME=House` for the live run.
-- **Switch-on condition (2026-10-27, #439):** existing users must not start paying; every existing account is sponsored at its usage before the catalog goes live.
+- **Product names (2026-10-31, copy review):** Personal, Community, Business, Apps pack, Disk pack, Storage pack, Email pack, Bandwidth pack. These are the script's defaults. The coupon is named `House`, also the default.
+- **Price book (2026-11-01, "Go ahead with live price book"):** `deploy/billing/pricebook-2026-11-01-v1.json`, status `approved`, with the draft's amounts, currencies and country map. Its price keys are `2026-11-01-v1/<plan>/<currency>` and `2026-11-01-v1/pack/<pack>/<currency>`.
+- **Tax (2026-10-31):** as Tito Go does it. Irish customers always pay VAT. An EU business with a VAT number gets the reverse charge, and other EU customers pay VAT through OSS. Everyone else pays no tax. Prices are exclusive: tax is added on top.
+- **Existing accounts (2026-10-31):** every account that exists at switch-on is sponsored with no limits, through the catalog's `sponsor_accounts_before` (6f1f6ca, in v0.33.1 and later; `docs/site/plans.md`, "Sponsored accounts"). This replaces per-account `carlos accounts plan --sponsored` and the measurement tool, which is not needed for launch. It meets the switch-on condition (2026-10-27, #439): existing users do not start paying.
+- **The ops account** (`bab`) is exempt from plans and billing (a2e23ba, in v0.33.0 and later). Nothing to do for it.
-### Still open before live
+### 6.2 Tax in the code
-- **Tax:** where to register (Stripe Tax registrations), prices plus tax or tax included, and the product tax code (the sandbox uses `txcd_10103000`). Paul with the accountant.
-- **Price book:** `deploy/billing/pricebook-2026-10-27-v1.json` is `draft`; live needs an `approved` version.
-- **Existing accounts:** a way to sponsor every flagship account at its measured usage before limits act (`carlos accounts plan` needs a configured catalog first).
-- **Flagship console configuration** through carloku-infrastructure (#453 replaces this later).
+Every Checkout sets `automatic_tax[enabled]=true` (`client.go:708`) and `tax_id_collection[enabled]=true` (`prepared.go:80`). Stripe Tax works out the tax from the customer's address and VAT number, using the account's registrations, and charges none where there is no registration. Every price is `tax_behavior=exclusive`. So the Tito Go rules come from the registrations: Ireland, and the EU One Stop Shop.
+The product tax code is `txcd_10103000`, "Software as a service (SaaS), personal use". Stripe's note says personal versus business use (`txcd_10103001`) matters only for US sales. **The accountant confirms the code.** This does not block switch-on, because the console never reads it. If the accountant picks another code before the live `--apply`, set `STRIPE_TAX_CODE`. After that, change it on each product in the Dashboard; the script only warns about a different code. A question to take along: does anywhere outside the EU, the UK for example, need a registration of its own? Until there is one, Stripe charges no tax there.
-Nothing in this section is done yet, and every step is Paul's. `scripts/stripe-setup.sh` has no live path on purpose. Live setup gets its own reviewed change once the rehearsal has passed.
+### 6.3 The script's live path
-**Paul's switch-on condition (2026-10-27): existing users must not have to start paying.** So before the plan catalog goes live on flagship, every existing account is sponsored at its current usage:
+`scripts/stripe-setup.sh --live` makes the same objects as the sandbox run, from the approved book. The guards:
-```sh
-carlos accounts plan --console https://<flagship console> --account <sqid> \
- --set free --sponsored <sqid>-limits.json --reason "existing account"
-```
+- `--live` needs `STRIPE_LIVE_ACCOUNT=acct_...`, the live account's id. That is the second confirmation. The script refuses the run if the variable is unset, names the sandbox, or disagrees with `STRIPE_ACCOUNT`. Without `--live`, a set `STRIPE_LIVE_ACCOUNT` is refused.
+- It refuses a price book that is not `approved`, dry runs included.
+- Every call carries `--live`. `GET /v1/account` must report `STRIPE_LIVE_ACCOUNT`, `GET /v1/balance` must say `livemode: true`, and every object it lists or makes must say `livemode: true`. A test object in a live list stops the run.
+- `STRIPE_API_KEY`, if set, overrides the CLI's login. With `--live` it must be an `sk_live_` or `rk_live_` key. Without `--live` a live key is refused.
+- The dry run sends nothing, and `--check` only reads, exactly as in the sandbox.
+- The printed block says `CARLOS_BILLING=live`.
+
+`cmd/console/stripesetup_script_test.go` runs every one of these against a fake stripe CLI.
+
+The script talks to Stripe through the stripe CLI. That uses the `stripe login` session unless `STRIPE_API_KEY` is set. For the live run, use the login, so no extra live key exists. If the login cannot get live access, Paul can make a one-off `rk_live_` setup key instead. It needs Write on Products, Prices, Coupons, Customer portal and Webhook endpoints, and Read on Balance and the account. Export it as `STRIPE_API_KEY` in the one shell that runs the script, and delete the key in the Dashboard straight after.
+
+### 6.4 Still open before live
+
+Paul's four steps in 6.5 (1 to 4), and the accountant's word on the tax code (6.2), which does not block. The sandbox run (section 4) and the dev rehearsal (section 5) are not recorded here as done. A sandbox `--apply` with the approved book is the cheap way to catch a problem before the live run.
-Each `limits.json` holds that account's measured usage under the catalog's limit names (`running_things`, `disk_bytes`, `storage_bytes`, `email_per_day`, `bandwidth_bytes_month`, `awake_hours_month` and so on). The rule for measuring is spec §8.7: counts and sizes as measured on switch-on day; email, bandwidth and awake hours from the highest full month of the three before it. An account with no statement history gets Personal's caps. A sponsored limit may go above a ceiling, and Paul sees each of those before switch-on.
+The flagship console's files are set by hand on its box, as in 4.4, until #453 brings console configuration into carloku-infrastructure.
-There are two things to settle before then:
+### 6.5 Switch-on, in order
-- There is no tool yet to measure usage and write those files. Plans 1 lists "the sponsored-usage measurement tool" under part 4, and it has not been built.
-- `carlos accounts plan` only works once the console has a catalog (`internal/console/apiaccountplan.go:70`). Sponsoring therefore happens after the catalog is installed, but before any limit acts on an account. The order needs working out, for example with `CARLOS_PLAN_LIMITS=off` on the boxes in the meantime, and checking what the console's hourly warning pass does during that window.
+Paul, in the live Carloku account's Dashboard:
-Then, in order:
+1. **Stripe Tax:** the head office address, and registrations for Ireland and the EU One Stop Shop (Union scheme). Without Stripe Tax set up, every Checkout create fails.
+2. **Retries:** Billing, Revenue recovery, Retries: when all retries fail, cancel the subscription. There is no API for this.
+3. **Live access for the setup run:** on DOCS-T1, run `stripe login`, choose the live Carloku account, and allow live mode. If the Dashboard asks, an Administrator first turns on CLI access (Settings, Team and security, MCP and CLI access). Send us the live account id (`acct_...`).
+4. **The console's key:** Developers, API keys, Create restricted key, in live mode. Name it `console carloku`. Give it the same permissions as the sandbox key, the table in 4.3 with Accounts Read included, and leave everything else at None. It starts `rk_live_`, and Stripe shows it once. Save it in 1Password beside the sandbox key, and nowhere else.
+
+Then us:
+
+5. **The live setup run,** from a checkout of main with this change merged:
+
+ ```sh
+ export CONSOLE_URL=https://console.carloku.com
+ export STRIPE_LIVE_ACCOUNT=acct_... # from step 3
+ scripts/stripe-setup.sh --live # dry run: sends nothing
+ scripts/stripe-setup.sh --live --check # reads only
+ scripts/stripe-setup.sh --live --apply # makes the 8 products, 24 prices, portal, coupon, endpoint
+ scripts/stripe-setup.sh --live --check # everything exists, nothing wrong
+ ```
-1. Spec §12 steps 1 to 4 are done: catalog shipped dormant, the dev rehearsal, flagship accounts sponsored and the catalog configured, a week of warnings watched, and the after-grace stages on.
-2. A new book version, marked `approved`, with the amounts Paul approves. A draft is never edited into an approved book. New version, new file, new price keys.
-3. The product tax codes, confirmed with the accountant (the sandbox uses `txcd_10103000`).
-4. Customer-facing text reviewed: product names (they appear on Checkout and on invoices), the coupon name if there is one, and the portal headline.
-5. Live setup, through its own reviewed change, against the live Carloku account: the same objects with the approved book's keys, the endpoint at `https://<flagship console>/billing/webhook`, retries set to cancel, and an `rk_live_` key with the same permissions.
-6. The flagship console's EnvironmentFile with `CARLOS_BILLING=live`, then a restart, a passing readiness check, and a first house-account Checkout at zero.
-7. Publish `https://<console>/upgrade?plan=<plan>&currency=<cur>`.
+ The webhook signing secret is printed once, on stderr. Save it in 1Password straight away. Whatever the sandbox run learnt about the portal (4.2) applies here too.
+6. **The flagship console's files,** shaped as in 4.4, on a console running v0.33.1 or later:
+ - `/etc/carlos/plans.json`: the example catalog, version `2026-10-20-v1`, plus `"sponsor_accounts_before": "<UTC time>"` in whole seconds, no later than the restart in step 7 (the time you write the file will do). Keep the version: the book prices `2026-10-20-v1`, and a new catalog version would need a new book.
+ - `/etc/carlos/pricebook-2026-11-01-v1.json`, root:root 0644, never edited afterwards.
+ - `/etc/carlos/billing.env`, root:root 0600: the block step 5 printed (`CARLOS_BILLING=live`, `CARLOS_PLAN_CATALOG`, `CARLOS_PRICE_BOOK`, `CARLOS_BILLING_PRICES` in single quotes, `CARLOS_STRIPE_ACCOUNT`, `CARLOS_STRIPE_PORTAL_CONFIGURATION`, `CARLOS_STRIPE_HOUSE_COUPON`), plus `CARLOS_STRIPE_SECRET_KEY` from step 4 and `CARLOS_STRIPE_WEBHOOK_SECRET` from step 5. The secrets reach the box through SSM SecureStrings or an interactive session, never a command line.
+ - `console.service.d/billing.conf` with `EnvironmentFile=/etc/carlos/billing.env`, no leading `-`.
+
+ With the catalog in `billing.env`, plans and billing go on together.
+7. **One restart:** `systemctl daemon-reload && systemctl restart console.service`. In the log:
+ - `console: sponsored N existing accounts with no limits (created before ...)`. N is every account but the ops one. `PLANS ARE OFF` instead means sponsoring failed: plans and billing both stay off, and the log says why.
+ - `console: billing is ready`. `billing not ready:` names the object and the rule. `scripts/stripe-setup.sh --live --check` shows the same from Stripe's side.
+ - `https://console.carloku.com/billing/webhook` no longer answers 503.
+8. **A first house-account Checkout at zero:** mark an account of ours as house, never `bab`, which has no billing: `carlos billing house -account <sqid> -on -note "first live checkout"`. Buy Personal from its billing page. Checkout shows a total of 0, the webhook delivery succeeds in the Dashboard, and the account's billing page shows Personal.
+9. Then publish `https://console.carloku.com/upgrade?plan=<plan>&currency=<cur>` and the pricing page (Plan 7).
+
+To turn billing off again, set `CARLOS_BILLING=off` and restart. Nothing at Stripe changes. Plans stay on, and the existing accounts stay sponsored.
## 7. If something is wrong
diff --git a/scripts/stripe-setup.sh b/scripts/stripe-setup.sh
index 3be48c693..057dae654 100755
--- a/scripts/stripe-setup.sh
+++ b/scripts/stripe-setup.sh
@@ -2,7 +2,7 @@
# shellcheck disable=SC2016 # the single-quoted $names are jq's, not the shell's
#
# stripe-setup.sh: one-time setup of the Stripe objects console billing
-# needs (plans 6c), in a Stripe sandbox or test mode only.
+# needs (plans 6c), in a Stripe sandbox (the default) or in live mode.
#
# It makes, if they are missing:
# - one product per paid plan and per pack in the price book, with
@@ -18,20 +18,26 @@
# CONSOLE_URL=https://console.example.com scripts/stripe-setup.sh
# Dry run. Sends nothing to Stripe: prints every command, in order.
# CONSOLE_URL=... scripts/stripe-setup.sh --check
-# Read only. Checks the account is the sandbox, finds what exists,
+# Read only. Checks the account and its mode, finds what exists,
# checks it the way the console's readiness check does, and prints
# what --apply would create.
# CONSOLE_URL=... scripts/stripe-setup.sh --apply
# As --check, then creates whatever is missing.
+# Add --live to any of the three for the live account. Live needs
+# STRIPE_LIVE_ACCOUNT=acct_... naming the live account, and an approved
+# price book. Start with a live dry run, then a live --check.
#
# Inputs (environment):
# CONSOLE_URL required. https://host[:port], no path.
-# STRIPE_TAX_CODE product tax code. Default txcd_10103000 (the
-# sandbox's; the live code is the accountant's call).
-# STRIPE_ACCOUNT the account the CLI must be using. Default
-# acct_1UVFkoIiAD0xflDQ (the sandbox).
+# STRIPE_TAX_CODE product tax code. Default txcd_10103000 (SaaS,
+# personal use; the accountant confirms it for live).
+# STRIPE_ACCOUNT the sandbox the CLI must be using, without --live.
+# Default acct_1UVFkoIiAD0xflDQ (the Carloku Sandbox).
+# STRIPE_LIVE_ACCOUNT with --live, required: the live account the CLI must
+# be using. It is the second confirmation of a live run.
+# Without --live it must be unset.
# PRICE_BOOK the book file. Default
-# deploy/billing/pricebook-2026-10-27-v1.json.
+# deploy/billing/pricebook-2026-11-01-v1.json.
# PRICE_BOOK_PATH where the console box keeps the book, for the
# printed CARLOS_PRICE_BOOK. Default
# /etc/carlos/<book file name>.
@@ -44,17 +50,22 @@
# "address name tax_id". Default all three.
# PORTAL_PRIVACY_URL optional https privacy policy URL for the portal.
# PORTAL_TERMS_URL optional https terms of service URL for the portal.
-# HOUSE_COUPON_NAME optional coupon name, up to 40 characters.
+# HOUSE_COUPON_NAME coupon name, up to 40 characters. Default House.
# PRODUCT_NAME_<NAME> optional product name override, e.g.
# PRODUCT_NAME_PERSONAL or PRODUCT_NAME_PACK_APPS.
# STRIPE_PROJECT_NAME optional stripe CLI project (--project-name).
+# STRIPE_API_KEY optional; overrides the CLI's login. Without --live
+# it may not be a live key, with --live it must be one.
#
# Rules this script keeps:
-# - It never passes --live and has no live path. Live setup is a later,
-# separate decision that needs Paul's approval (the plans 6c runbook);
-# it gets its own reviewed change, not a flag here.
-# - It refuses to run against anything but the expected account in test
-# mode, and every object it reads or makes must say livemode false.
+# - One mode per run, never mixed. Without --live it never passes --live,
+# and the account must be STRIPE_ACCOUNT in test mode. With --live it
+# passes --live on every call, and the account must be
+# STRIPE_LIVE_ACCOUNT in live mode; the sandbox's id is refused.
+# Either way, the balance it reads, every object it lists and every
+# object it makes must carry the run's livemode, or it stops.
+# - A live run, dry runs included, refuses a price book that is not
+# approved, as a live console does.
# - It never deletes, archives or edits an object. An object that exists
# but is wrong stops the run, naming what is wrong, for a person to fix.
# Lookups see only live objects: active products, prices and portal
@@ -84,15 +95,17 @@ warn() { printf 'stripe-setup.sh: warning: %s\n' "$*" >&2; }
usage() { sed -n '4,/^set -euo/p' "${BASH_SOURCE[0]}" | sed -e '/^set -euo/d' -e 's/^# \{0,1\}//'; }
mode="dry-run"
+live=false
while [[ $# -gt 0 ]]; do
case "$1" in
-h | --help) usage; exit 0 ;;
--apply) mode="apply"; shift ;;
--check) mode="check"; shift ;;
- --live) die "there is no live mode. Live setup is a separate, later decision (see the plans 6c runbook)" ;;
+ --live) live=true; shift ;;
*) die "unknown argument: $1 (try --help)" ;;
esac
done
+if [[ "$live" == true ]]; then mode_word="live"; else mode_word="test"; fi
command -v jq >/dev/null || die "jq is needed"
if [[ "$mode" != "dry-run" ]]; then
@@ -111,10 +124,23 @@ webhook_url="$console_url$WEBHOOK_PATH"
tax_code="${STRIPE_TAX_CODE:-txcd_10103000}"
[[ "$tax_code" =~ ^txcd_[0-9]{8}$ ]] || die "STRIPE_TAX_CODE must look like txcd_ and eight digits"
-account="${STRIPE_ACCOUNT:-acct_1UVFkoIiAD0xflDQ}"
-[[ "$account" =~ ^acct_[A-Za-z0-9]+$ ]] || die "STRIPE_ACCOUNT must look like acct_..."
+readonly SANDBOX_ACCOUNT="acct_1UVFkoIiAD0xflDQ" # the Carloku Sandbox
+if [[ "$live" == true ]]; then
+ # The second confirmation: a live run names the live account itself, and
+ # Stripe has to report that same account (preflight).
+ account="${STRIPE_LIVE_ACCOUNT:-}"
+ [[ -n "$account" ]] || die "--live needs STRIPE_LIVE_ACCOUNT=acct_..., the live account's id, as a second confirmation"
+ [[ "$account" =~ ^acct_[A-Za-z0-9]+$ ]] || die "STRIPE_LIVE_ACCOUNT must look like acct_..."
+ [[ "$account" != "$SANDBOX_ACCOUNT" ]] || die "STRIPE_LIVE_ACCOUNT is the Carloku Sandbox, not a live account"
+ [[ -z "${STRIPE_ACCOUNT:-}" || "${STRIPE_ACCOUNT}" == "$account" ]] ||
+ die "STRIPE_ACCOUNT names another account than STRIPE_LIVE_ACCOUNT. Unset STRIPE_ACCOUNT for a live run"
+else
+ [[ -z "${STRIPE_LIVE_ACCOUNT:-}" ]] || die "STRIPE_LIVE_ACCOUNT is set but --live is not. Pass --live for a live run, or unset it"
+ account="${STRIPE_ACCOUNT:-$SANDBOX_ACCOUNT}"
+ [[ "$account" =~ ^acct_[A-Za-z0-9]+$ ]] || die "STRIPE_ACCOUNT must look like acct_..."
+fi
-book_file="${PRICE_BOOK:-$here/../deploy/billing/pricebook-2026-10-27-v1.json}"
+book_file="${PRICE_BOOK:-$here/../deploy/billing/pricebook-2026-11-01-v1.json}"
[[ -r "$book_file" ]] || die "PRICE_BOOK $book_file cannot be read"
book_path="${PRICE_BOOK_PATH:-/etc/carlos/$(basename "$book_file")}"
catalog_path="${PLAN_CATALOG_PATH:-/etc/carlos/plans.json}"
@@ -123,7 +149,7 @@ return_url="${PORTAL_RETURN_URL:-$console_url/}"
headline="${PORTAL_HEADLINE:-}"
privacy_url="${PORTAL_PRIVACY_URL:-}"
terms_url="${PORTAL_TERMS_URL:-}"
-coupon_name="${HOUSE_COUPON_NAME:-}"
+coupon_name="${HOUSE_COUPON_NAME-House}"
read -r -a customer_updates <<<"${PORTAL_CUSTOMER_UPDATES:-address name tax_id}"
((${#customer_updates[@]} > 0)) || die "PORTAL_CUSTOMER_UPDATES is empty"
for u in "${customer_updates[@]}"; do
@@ -140,10 +166,16 @@ check_text PORTAL_HEADLINE "$headline" 60
check_text HOUSE_COUPON_NAME "$coupon_name" 40
[[ -z "$project" || "$project" =~ ^[A-Za-z0-9_-]+$ ]] || die "STRIPE_PROJECT_NAME must be letters, digits, - and _"
-# A key in the environment overrides the CLI's login. Refuse a live one.
-case "${STRIPE_API_KEY:-}" in
- *_live_*) die "STRIPE_API_KEY holds a live key. This script runs in a sandbox or test mode only" ;;
-esac
+# A key in the environment overrides the CLI's login. It must be in the
+# run's mode: never a live key without --live, only a live key with it.
+if [[ -n "${STRIPE_API_KEY:-}" ]]; then
+ if [[ "$live" == true ]]; then
+ [[ "$STRIPE_API_KEY" == sk_live_* || "$STRIPE_API_KEY" == rk_live_* ]] ||
+ die "STRIPE_API_KEY is not a live key. Unset it to use the CLI's live login, or set a live key"
+ else
+ [[ "$STRIPE_API_KEY" != *_live_* ]] || die "STRIPE_API_KEY holds a live key but --live is not set"
+ fi
+fi
# ---------------------------------------------------------------------------
# The price book: the one source of names, currencies and amounts.
@@ -158,6 +190,10 @@ jq -e '
book_version="$(jq -r .version "$book_file")"
book_status="$(jq -r .status "$book_file")"
+# A live console refuses a draft book (cmd/console/billing.go), so a live
+# run makes nothing from one.
+[[ "$live" != true || "$book_status" == approved ]] ||
+ die "$book_file is $book_status. A live run needs an approved price book"
read -r -a currencies <<<"$(jq -r '.currencies | join(" ")' "$book_file")"
read -r -a plan_names <<<"$(jq -r '.plans | keys_unsorted | join(" ")' "$book_file")"
read -r -a pack_names <<<"$(jq -r '.packs | keys_unsorted | join(" ")' "$book_file")"
@@ -195,6 +231,7 @@ stripe_cmd() {
local verb="$1" path="$2"
shift 2
cmd=(stripe "$verb" "$path" --stripe-version "$API_VERSION")
+ [[ "$live" != true ]] || cmd+=(--live)
[[ -z "$project" ]] || cmd+=(--project-name "$project")
[[ "$verb" != post ]] || cmd+=(--confirm)
cmd+=("$@")
@@ -243,7 +280,8 @@ list_all() {
fi
if [[ "$mode" == "dry-run" ]]; then out="[]"; return 0; fi
jq -e '.object == "list" and (.data | type == "array")' >/dev/null <<<"$out" || die "$path did not answer with a list"
- jq -e '.data | all(.livemode == false)' >/dev/null <<<"$out" || die "$path returned a live-mode object. Stopping"
+ jq -e --argjson live "$live" '.data | all(.livemode == $live)' >/dev/null <<<"$out" ||
+ die "$path returned an object that is not in $mode_word mode. Stopping"
all="$(jq -c --argjson a "$all" '$a + .data' <<<"$out")"
jq -e '.has_more == true and (.data | length) > 0' >/dev/null <<<"$out" || break
after="$(jq -r '.data[-1].id' <<<"$out")"
@@ -251,11 +289,11 @@ list_all() {
out="$all"
}
-# made_object checks a created object is in test mode and sets $id.
+# made_object checks a created object is in the run's mode and sets $id.
id=""
made_object() {
- jq -e --arg p "$1" '.livemode == false and (.id | type == "string" and startswith($p))' >/dev/null <<<"$out" ||
- die "the object just made is not a test-mode $1 object"
+ jq -e --arg p "$1" --argjson live "$live" '.livemode == $live and (.id | type == "string" and startswith($p))' >/dev/null <<<"$out" ||
+ die "the object just made is not a $mode_word-mode $1 object"
id="$(jq -r .id <<<"$out")"
}
@@ -277,7 +315,7 @@ readonly PRICE_PROBLEM='
and $o[$c].unit_amount == $a
and (($o[$c].tax_behavior // "") == "" or $o[$c].tax_behavior == $t));
if .active != true then "not active"
- elif .livemode != false then "in live mode"
+ elif .livemode != '"$live"' then "not in '"$mode_word"' mode"
elif .product != $product then "on another product"
elif .currency != $currency then "in another currency"
elif .unit_amount != $amount then "its amount is not the one in the book"
@@ -294,7 +332,7 @@ readonly PRICE_PROBLEM='
readonly PORTAL_PROBLEM='
.features as $f
| if .active != true then "not active"
- elif .livemode != false then "in live mode"
+ elif .livemode != '"$live"' then "not in '"$mode_word"' mode"
elif $f.payment_method_update.enabled != true then "payment method updates are off"
elif $f.invoice_history.enabled != true then "invoice history is off"
elif $f.subscription_update.enabled == true then "subscription updates are on"
@@ -307,7 +345,7 @@ readonly PORTAL_PROBLEM='
readonly COUPON_PROBLEM='
if .valid != true then "not valid"
- elif .livemode != false then "in live mode"
+ elif .livemode != '"$live"' then "not in '"$mode_word"' mode"
elif .percent_off != 100 then "not 100% off"
elif .amount_off != null then "has an amount off"
elif .duration != "forever" then "not forever"
@@ -317,33 +355,41 @@ readonly COUPON_PROBLEM='
else "" end'
readonly WEBHOOK_PROBLEM='
- if .livemode != false then "in live mode"
+ if .livemode != '"$live"' then "not in '"$mode_word"' mode"
elif .status != "enabled" then "not enabled"
elif .api_version != $version then "its API version is not \($version)"
elif (.enabled_events | sort) != ($events | sort) then "its events are not the six the console reads"
else "" end'
# ---------------------------------------------------------------------------
-# 0. Preflight: the sandbox or test mode, nothing else.
+# 0. Preflight: the expected account, in the run's mode, nothing else.
case "$mode" in
dry-run) echo "# stripe-setup.sh dry run: nothing below has been sent to Stripe." ;;
check) echo "# stripe-setup.sh --check: reads only." ;;
apply) echo "# stripe-setup.sh --apply: creates what is missing." ;;
esac
+if [[ "$live" == true ]]; then echo "# LIVE MODE, account $account."; fi
echo "# Book $book_version ($book_status): ${#plan_names[@]} plans, ${#pack_names[@]} packs, ${#currencies[@]} currencies."
echo "# $(( ${#plan_names[@]} + ${#pack_names[@]} )) products, $(( (${#plan_names[@]} + ${#pack_names[@]}) * ${#currencies[@]} )) prices, API version $API_VERSION."
echo
-echo "## Preflight: the CLI must be on $account in test mode"
+echo "## Preflight: the CLI must be on $account in $mode_word mode"
read_call get /v1/account
if [[ "$mode" != "dry-run" ]]; then
got="$(jq -r '.id // ""' <<<"$out")"
[[ "$got" == "$account" ]] || die "the stripe CLI is on account ${got:-unknown}, not $account. Stopping"
fi
+# The balance says which mode the key is in, even on an account with no
+# objects yet.
+read_call get /v1/balance
+if [[ "$mode" != "dry-run" ]]; then
+ jq -e --argjson live "$live" '.object == "balance" and .livemode == $live' >/dev/null <<<"$out" ||
+ die "the balance is not in $mode_word mode, so the CLI is not either. Stopping"
+fi
read_call get /v1/products -d limit=1
if [[ "$mode" != "dry-run" ]]; then
- jq -e '.object == "list" and (.data | all(.livemode == false))' >/dev/null <<<"$out" ||
- die "the product list is not a test-mode list. Stopping"
+ jq -e --argjson live "$live" '.object == "list" and (.data | all(.livemode == $live))' >/dev/null <<<"$out" ||
+ die "the product list is not a $mode_word-mode list. Stopping"
fi
remember CARLOS_STRIPE_ACCOUNT "$account"
echo
@@ -503,8 +549,8 @@ else
args=(-d percent_off=100 -d duration=forever -d "expand[]=applies_to" -d "metadata[carlos_coupon]=house")
[[ -z "$coupon_name" ]] || args+=(-d "name=$coupon_name")
if write_call post /v1/coupons -i "stripe-setup:coupon:house" "${args[@]}"; then
- jq -e '.livemode == false and (.id | type == "string" and test("^[A-Za-z0-9_-]{1,200}$"))' >/dev/null <<<"$out" ||
- die "the coupon just made is not a test-mode coupon with a usable id"
+ jq -e --argjson live "$live" '.livemode == $live and (.id | type == "string" and test("^[A-Za-z0-9_-]{1,200}$"))' >/dev/null <<<"$out" ||
+ die "the coupon just made is not a $mode_word-mode coupon with a usable id"
coupon="$(jq -r .id <<<"$out")"
problem="$(jq -r "$COUPON_PROBLEM" <<<"$out")"
[[ -z "$problem" ]] || die "the coupon just made ($coupon): $problem. Stopping"
@@ -563,7 +609,7 @@ echo "## Console environment (non-secret). Paste into the console's EnvironmentF
if [[ "$mode" != "apply" ]]; then
echo "# Values in <angle brackets> are ids --apply would create."
fi
-echo "CARLOS_BILLING=test"
+echo "CARLOS_BILLING=$mode_word"
echo "CARLOS_PLAN_CATALOG=$catalog_path"
echo "CARLOS_PRICE_BOOK=$book_path"
# Single quotes: systemd strips double quotes from an EnvironmentFile value.
@@ -571,5 +617,5 @@ echo "CARLOS_BILLING_PRICES='$(jq -cS . <<<"$prices")'"
jq -r 'to_entries[] | "\(.key)=\(.value)"' <<<"$ids"
echo
echo "## Secrets: set them by hand in the same file. Never in the repo."
-echo "# CARLOS_STRIPE_SECRET_KEY the rk_test_ restricted key made in the Dashboard (runbook, step 4)"
+echo "# CARLOS_STRIPE_SECRET_KEY the rk_${mode_word}_ restricted key made in the Dashboard (the plans 6c runbook)"
echo "# CARLOS_STRIPE_WEBHOOK_SECRET the whsec_ signing secret, printed on stderr when the endpoint is made"