carlos / platform Public

plans 6c: Stripe setup script with a guarded live mode

Adds scripts/stripe-setup.sh (sandbox by default; --live needs
STRIPE_LIVE_ACCOUNT and an approved book), the approved price book
deploy/billing/pricebook-2026-11-01-v1.json (Paul, 2026-11-01), the
sponsored-unlimited limits file and the plans 6c runbook. Astra R1-R3,
R3 READY.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Squashed from plans-6c-stripe-setup into main.
Paul Campbell pushed by claude agent, operated by paul@keymail.dev b56ec321dc664cddaf0e0e8d100cb4514792a536 parent ceee7a6
9 files changed, +1,884 −0
  • cmd/console/main_test.go +4 −0
  • cmd/console/stripesetup_script_test.go +620 −0
  • deploy/billing/pricebook-2026-10-27-v1.json +23 −0
  • deploy/billing/pricebook-2026-11-01-v1.json +23 −0
  • deploy/billing/sponsored-unlimited.json +19 −0
  • docs/superpowers/plans/2026-10-27-plans-6c-stripe-setup.md +399 −0
  • docs/superpowers/reviews/CODEX-REVIEW-BRIEF-plans-6c-live.md +36 −0
  • internal/console/plansponsor_file_test.go +41 −0
  • scripts/stripe-setup.sh +719 −0

CI failed — run details

landed from plans-6c-stripe-setup

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..06fe505e2
--- /dev/null
+++ b/cmd/console/stripesetup_script_test.go
@@ -0,0 +1,620 @@
+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"`
+ // Idem is every create's first response by idempotency key. As Stripe
+ // does, a create under a key it has seen gets that response again,
+ // whatever has happened to the object since.
+ Idem map[string]json.RawMessage `json:"idem"`
+}
+
+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
+ idem := ""
+ for i := 2; i < len(args); i++ {
+ switch args[i] {
+ case "--confirm", "--live":
+ case "--stripe-version", "--project-name":
+ i++
+ case "-i":
+ i++
+ idem = args[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/")
+ for k := range stripeIDPrefix {
+ id, ok := strings.CutPrefix(kind, k+"/")
+ if !ok || verb != "get" {
+ continue
+ }
+ for _, o := range w.Objects[k] {
+ if o["id"] == id {
+ return reply(o)
+ }
+ }
+ fmt.Println(`{"error":{"type":"invalid_request_error","message":"No such object"}}`)
+ return 1
+ }
+ if raw, ok := w.Idem[idem]; ok && verb == "post" && idem != "" {
+ fmt.Println(string(raw))
+ return 0
+ }
+ 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"
+ o["application"] = nil // an account endpoint, not a Connect one
+ }
+ 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)
+ if idem != "" {
+ if w.Idem == nil {
+ w.Idem = map[string]json.RawMessage{}
+ }
+ w.Idem[idem], _ = json.Marshal(o)
+ }
+ 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()
+ return w.runWith(exec.Command(stripeSetupScript, args...), env)
+}
+
+// runWith runs cmd, the script under some interpreter, as run does.
+func (w *stripeWorld) runWith(cmd *exec.Cmd, env []string) (string, string, int) {
+ w.t.Helper()
+ for _, e := range os.Environ() {
+ if strings.HasPrefix(e, "BASH_ENV=") || strings.HasPrefix(e, "SHELLOPTS=") || strings.HasPrefix(e, "BASH_XTRACEFD=") ||
+ strings.HasPrefix(e, "TMPDIR=") {
+ continue
+ }
+ 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", "TMPDIR="+w.dir)
+ 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)
+ }
+ }
+ // The signing secret is in the file alone, never on either stream.
+ if strings.Contains(stdout+stderr, "FakeSecret") {
+ t.Errorf("the signing secret reached the output")
+ }
+ m := regexp.MustCompile(`signing secret is in (\S+) `).FindStringSubmatch(stdout)
+ if m == nil {
+ t.Fatalf("stdout does not name the secret file:\n%s", stdout)
+ }
+ secretFile := m[1]
+ if filepath.Dir(filepath.Dir(secretFile)) != w.dir {
+ t.Errorf("secret file %s is not in a new directory under TMPDIR", secretFile)
+ }
+ for path, want := range map[string]os.FileMode{secretFile: 0o600, filepath.Dir(secretFile): 0o700} {
+ fi, err := os.Lstat(path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if fi.Mode().Perm() != want {
+ t.Errorf("%s mode %v, want %v", path, fi.Mode().Perm(), want)
+ }
+ }
+ if b, _ := os.ReadFile(secretFile); string(b) != "CARLOS_STRIPE_WEBHOOK_SECRET=whsec_FakeSecret\n" {
+ t.Errorf("secret file holds %q", b)
+ }
+
+ 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"},
+ {name: "inherited SHELLOPTS xtrace", account: liveAccount, live: true, args: []string{"--live", "--apply"},
+ env: []string{"STRIPE_LIVE_ACCOUNT=" + liveAccount, "SHELLOPTS=xtrace"}, want: "refusing to run traced", noCallsAt: true},
+ {name: "BASH_XTRACEFD set", account: liveAccount, live: true, args: []string{"--live", "--apply"},
+ env: []string{"STRIPE_LIVE_ACCOUNT=" + liveAccount, "BASH_XTRACEFD=2"}, want: "refusing to run traced", noCallsAt: true},
+ {name: "BASH_ENV set", account: liveAccount, live: true, args: []string{"--live", "--apply"},
+ env: []string{"STRIPE_LIVE_ACCOUNT=" + liveAccount, "BASH_ENV=/dev/null"}, want: "BASH_ENV", noCallsAt: true},
+ }
+ 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)
+ }
+ if left, _ := filepath.Glob(filepath.Join(w.dir, "tmp.*")); len(left) != 0 {
+ t.Fatalf("a refused run left %v behind", left)
+ }
+ })
+ }
+}
+
+// bash -x, the explicit form of tracing, is refused before any call.
+func TestStripeSetupRefusesBashX(t *testing.T) {
+ w := newStripeWorld(t, liveAccount, true)
+ stdout, stderr, code := w.runWith(exec.Command("bash", "-x", stripeSetupScript, "--live", "--apply"),
+ []string{"STRIPE_LIVE_ACCOUNT=" + liveAccount})
+ if code == 0 || !strings.Contains(stderr, "refusing to run traced") {
+ t.Fatalf("bash -x was not refused (%d):\n%s\n%s", code, stdout, stderr)
+ }
+ if n := len(w.calls()); n != 0 {
+ t.Fatalf("refused after %d calls to Stripe", n)
+ }
+}
+
+// A Connect application's endpoint at the console's URL is not the
+// account's endpoint: it is ignored, and the account's own is made.
+func TestStripeSetupIgnoresConnectEndpoint(t *testing.T) {
+ w := newStripeWorld(t, sandboxAccount, false)
+ connect := map[string]any{"id": "we_Connect", "object": "webhook_endpoint", "livemode": false, "status": "enabled",
+ "application": "ca_Other", "url": "https://console.example.com/billing/webhook", "api_version": "2025-02-24.acacia",
+ "enabled_events": []any{"checkout.session.completed", "customer.subscription.created", "customer.subscription.updated",
+ "customer.subscription.deleted", "invoice.paid", "invoice.payment_failed"}}
+ w.save(fakeStripeWorld{Account: sandboxAccount, Objects: map[string][]map[string]any{"webhook_endpoints": {connect}}})
+ if stdout, stderr, code := w.run(nil, "--apply"); code != 0 {
+ t.Fatalf("apply failed (%d):\n%s\n%s", code, stdout, stderr)
+ }
+ eps := w.load().Objects["webhook_endpoints"]
+ if len(eps) != 2 || eps[0]["id"] != "we_Connect" || eps[1]["application"] != nil {
+ t.Fatalf("endpoints after apply: %v", eps)
+ }
+}
+
+// A price archived (lookup key cleared) after it was made is not made again
+// under the same book version: Stripe answers the create by replaying the
+// first response, which still says active, so the script reads the price
+// back and stops, naming the way out (a new book version).
+func TestStripeSetupReplayedArchivedPriceStops(t *testing.T) {
+ w := newStripeWorld(t, sandboxAccount, false)
+ if stdout, stderr, code := w.run(nil, "--apply"); code != 0 {
+ t.Fatalf("first apply failed (%d):\n%s\n%s", code, stdout, stderr)
+ }
+ fw := w.load()
+ archived := ""
+ for _, p := range fw.Objects["prices"] {
+ if p["lookup_key"] == "2026-11-01-v1/personal/usd" {
+ p["active"], p["lookup_key"] = false, nil
+ archived = p["id"].(string)
+ }
+ }
+ if archived == "" {
+ t.Fatal("no personal/usd price was made")
+ }
+ w.save(fw)
+ stdout, stderr, code := w.run(nil, "--apply")
+ if code == 0 {
+ t.Fatalf("a replayed archived price was accepted:\n%s", stdout)
+ }
+ if !strings.Contains(stderr, archived) || !strings.Contains(stderr, "new price book version") {
+ t.Fatalf("refusal does not name the price and the way out: %s", stderr)
+ }
+ if strings.Contains(stdout, "CARLOS_BILLING_PRICES=") {
+ t.Fatalf("the environment block was printed after the refusal")
+ }
+ if n := len(w.load().Objects["prices"]); n != 24 {
+ t.Fatalf("%d prices, want the first run's 24", 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-10-27-v1.json b/deploy/billing/pricebook-2026-10-27-v1.json
new file mode 100644
index 000000000..6df59b7d4
--- /dev/null
+++ b/deploy/billing/pricebook-2026-10-27-v1.json
@@ -0,0 +1,23 @@
+{
+ "version": "2026-10-27-v1",
+ "status": "draft",
+ "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/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/deploy/billing/sponsored-unlimited.json b/deploy/billing/sponsored-unlimited.json
new file mode 100644
index 000000000..ead502d73
--- /dev/null
+++ b/deploy/billing/sponsored-unlimited.json
@@ -0,0 +1,19 @@
+{
+ "running_things": 2305843009213693951,
+ "sidecars_per_app": 2305843009213693951,
+ "idle_seconds": 9223372036,
+ "memory_tier": "default",
+ "awake_hours_month": 2305843009213693951,
+ "disk_bytes": 2305843009213693951,
+ "storage_bytes": 2305843009213693951,
+ "storage_self_serve": true,
+ "email_per_day": 2305843009213693951,
+ "bandwidth_bytes_month": 2305843009213693951,
+ "custom_domains": true,
+ "fleets": true,
+ "min_schedule_seconds": 1,
+ "history_days": 106751,
+ "rate_client_share": 1000000,
+ "rate_per_second": 1000000,
+ "rate_burst": 1000000
+}
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
new file mode 100644
index 000000000..9881fc978
--- /dev/null
+++ b/docs/superpowers/plans/2026-10-27-plans-6c-stripe-setup.md
@@ -0,0 +1,399 @@
+# 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 (`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.
+
+These files come with it:
+
+- `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.
+
+This file records no run against Stripe yet.
+
+## 1. What the console needs
+
+| Object | Count | Where its id goes |
+| --- | --- | --- |
+| Products: personal, community, business and the packs apps, disk, storage, email, bandwidth | 8 | nowhere; each price names its product |
+| Prices: one per product and currency (usd, eur, gbp) | 24 | `CARLOS_BILLING_PRICES` |
+| 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 key, `rk_test_` or `rk_live_`, made by Paul in the Dashboard | 1 | `CARLOS_STRIPE_SECRET_KEY` |
+
+The amounts, in minor units a year:
+
+| Item | usd | eur | gbp |
+| --- | --- | --- | --- |
+| personal | 2800 | 2400 | 2200 |
+| community, per member | 600 | 500 | 450 |
+| business, per member | 6000 | 5000 | 4500 |
+| pack apps | 1200 | 1000 | 900 |
+| pack disk | 3600 | 3100 | 2800 |
+| pack storage | 1200 | 1000 | 900 |
+| pack email | 2400 | 2100 | 1900 |
+| pack bandwidth | 4800 | 4100 | 3800 |
+
+Community and Business are team plans: a price per member, with a minimum of 10 members (`internal/plans/testdata/example-catalog.json:56` and `:72`). In Stripe they are ordinary per-unit prices. The console sets the quantity.
+
+## 2. Exact requirements from the code
+
+These are what the console checks when it starts. The setup script applies the same rules to anything it finds or makes, and stops if an object breaks one.
+
+### The console's variables (`cmd/console/billing.go`)
+
+The console reads them in this order and stops at the first bad one, naming the variable and never its value.
+
+- `CARLOS_BILLING` is `off`, `test` or `live`. Unset is off (`billing.go:25-31`).
+- `CARLOS_PLAN_CATALOG` must be set when billing is on (`billing.go:33-35`, `cmd/console/main.go:1953`). It is a file path.
+- `CARLOS_STRIPE_SECRET_KEY` starts `rk_test_` in test mode and `rk_live_` in live mode (`billing.go:36-43`, again in `internal/billingstripe/adapter.go:63-69`). A standard `sk_` key is refused.
+- `CARLOS_STRIPE_ACCOUNT` starts `acct_` (`billing.go:44-47`). The readiness check also requires it to be the account the key belongs to, read from `GET /v1/account` (`adapter.go:267-273`, `merchant.go:17`).
+- `CARLOS_STRIPE_WEBHOOK_SECRET` starts `whsec_` (`billing.go:48-51`). `CARLOS_STRIPE_PREVIOUS_WEBHOOK_SECRETS` is optional: up to two older `whsec_` secrets, comma separated, for a rotation (`billing.go:53-66`).
+- `CARLOS_PRICE_BOOK` is the path to the price book file, not its content (`billing.go:67-74`). A live console refuses a draft book (`billing.go:72`).
+- `CARLOS_BILLING_PRICES` is the price map (`billing.go:75`; format below).
+- `CARLOS_STRIPE_PORTAL_CONFIGURATION` must start `bpc_` and be id-shaped (`billing.go:79-82`, `adapter.go:39-41`).
+- `CARLOS_STRIPE_HOUSE_COUPON` is optional. If set, it must match `^[A-Za-z0-9_-]{1,200}$` (`billing.go:83-86`, `internal/billingstripe/catalog.go:285`).
+
+The console records each book version's digest the first time it starts with it. If the file under that version changes later, the console refuses to start (`cmd/console/main.go:377`). To change a price, write a new book with a new version.
+
+### 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`). 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-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`)
+
+For every price in the map under the configured book, the readiness check reads `GET /v1/prices/<id>` with `currency_options` expanded (`catalog.go:107`) and requires all of these:
+
+- the book prices it (`adapter.go:394`);
+- active (`:396`), and in the console's mode (`:398`);
+- in the key's currency (`:400`), at the book's amount exactly (`:402`);
+- recurring once a year: interval `year`, interval count 1 (`:404`);
+- usage type `licensed` (`:406`), billing scheme `per_unit` (`:408`), tax behaviour `exclusive` (`:410`);
+- no `transform_quantity` (`:412`);
+- no currency option except its own currency at its own amount (`:414`, `:430-449`);
+- `metadata[price_key]` equal to its key (`:416`).
+
+Each price's product must be active and in the same mode (`adapter.go:285-295`). The product's tax code is not checked.
+
+The code never reads a price's `lookup_key`. The script sets `lookup_key` to the price key anyway, so it can find a price again. The products carry `metadata[carlos_product]` (`personal`, `pack/apps` and so on) for the same reason. The code does not read that either.
+
+### The price book (`internal/plans/pricebook.go`)
+
+- Unknown fields, the same key twice and trailing content are refused (`pricebook.go:74-89`).
+- `status` is `draft` or `approved` (`:142`). `catalog_version` must equal the installed catalog's `version` (`:145`).
+- 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`).
+
+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-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. 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.
+
+### The locked portal configuration (`adapter.go:308-349`)
+
+The check reads `GET /v1/billing_portal/configurations/<id>` and requires:
+
+- active (`:325`), in the console's mode (`:327`);
+- payment method update on (`:329`) and invoice history on (`:331`);
+- subscription update off (`:333`) and cancellation off (`:335`);
+- customer update either off, or limited to `address`, `name` and `tax_id` (`:311`, `:337-343`).
+
+The code does not read pause. The outline wants it off, and it is off unless someone turns it on. The script does not send it, and refuses a configuration whose read-back shows it on. The code ignores `business_profile` and the default return URL (`portal.go:34-39`). The console passes its own return URL with each portal session (`client.go:749`).
+
+### The house coupon (`adapter.go:351-383`)
+
+The check reads `GET /v1/coupons/<id>` with `applies_to` expanded (`catalog.go:298`) and requires:
+
+- valid (`:362`), in the console's mode (`:364`);
+- 100% off (`:366`) with no amount off (`:368`);
+- duration `forever` (`:370`);
+- not limited to any products (`:372`);
+- no `max_redemptions` (`:374`) and no `redeem_by` (`:376`).
+
+The code does not check for a promotion code. A house Checkout sends the coupon directly as `discounts[0][coupon]`, and only other Checkouts allow promotion codes (`client.go:704-711`). The script makes no promotion code.
+
+### The webhook endpoint
+
+- The route is `POST /billing/webhook` (`internal/console/server.go:1935`). It answers 404 with billing off and 503 until the readiness check has passed, so Stripe tries again later (`internal/console/billingwebhook.go:16-38`).
+- The console uses six events: `checkout.session.completed`, `customer.subscription.created`, `customer.subscription.updated`, `customer.subscription.deleted`, `invoice.paid` and `invoice.payment_failed` (`adapter.go:176-199`). Other events are ignored.
+- The API version is pinned to `2025-02-24.acacia` on every call (`client.go:34`, `:251`). The endpoint must use the same version, because the handler reads `subscription` directly off an invoice event (`adapter.go:187-198`), and later versions move that field.
+- A signature older or newer than 5 minutes is refused (`webhook.go:15`), so the console box's clock matters.
+
+### The restricted key
+
+These are the endpoints `internal/billingstripe` calls:
+
+| Endpoint | Method | Used for |
+| --- | --- | --- |
+| `/v1/account` | GET | the readiness check's account match (`merchant.go:17`) |
+| `/v1/prices/<id>` | GET | readiness and the clock probe (`catalog.go:107`, `prepared.go:461`) |
+| `/v1/products/<id>` | GET | readiness (`merchant.go:67`) |
+| `/v1/coupons/<id>` | GET | readiness (`catalog.go:298`) |
+| `/v1/billing_portal/configurations/<id>` | GET | readiness (`portal.go:123`) |
+| `/v1/billing_portal/sessions` | POST | Payment and invoices (`client.go:764`) |
+| `/v1/customers`, `/v1/customers/<id>` | POST, GET | the account's customer (`customer.go:171`, `:205`, `:221`) |
+| `/v1/checkout/sessions` and `.../<id>`, `.../<id>/expire` | POST, GET, list | Checkout (`prepared.go:72`, `client.go:726`, `:738`, `catalog.go:162`, `prepared.go:346`) |
+| `/v1/subscriptions/<id>`, `/v1/subscriptions` | GET, POST, list | sync, packs, upgrades, renewal (`client.go:786`, `:940`, `prepared.go:138`, `:149`, `:321`) |
+| `/v1/subscription_items/<id>` | POST | seat and pack quantities (`client.go:839`, `:891`) |
+| `/v1/invoices`, `/v1/invoices/<id>/lines` | list | the late-restore check (`prepared.go:398`, `:420`) |
+
+`ActiveTaxRegistrations` (`catalog.go:209`) has no caller, so the key does not need tax registrations. Plan 6a's outline listed them; the 6b outline does not.
+
+## 3. Where the outline and the code differ
+
+- **Price keys.** The outline says only "set to the key". The keys are `<book>/<plan>/<currency>` and `<book>/pack/<pack>/<currency>`. The team plans' keys are plain `community` and `business`, with no "per member" in them.
+- **`CARLOS_BILLING_PRICES`.** The outline gives no format. It is a JSON object from price key to price id. Every price of the configured book must be there, and it must be single-quoted in an EnvironmentFile.
+- **`CARLOS_PRICE_BOOK`.** It is a file path. The book's `catalog_version` must equal the installed catalog's version.
+- **Pause.** The outline wants it off. The code does not check it.
+- **The house coupon.** The code also refuses an amount off, and "unrestricted" means three things: no products, no redemption limit and no deadline. "No promotion code" is not checked. The console just never offers one with the house coupon.
+- **Price checks the outline leaves out.** Active, the right mode, an active product, no quantity transform, no second currency, and an interval count of 1.
+- **The account read.** The readiness check reads `GET /v1/account`. The outline's key permissions have no row for it (see step 4).
+- **The webhook path, the API version, the six events and `metadata[price_key]`** all match the outline.
+- **Rotation.** `CARLOS_STRIPE_PREVIOUS_WEBHOOK_SECRETS` exists but is missing from the outline's list of variables.
+
+## 4. The sandbox run
+
+Everything in this section happens in the Carloku Sandbox (`acct_1UVFkoIiAD0xflDQ`) and on the dev console (`https://platform.dev.carlosframework.com`). None of it touches live.
+
+### 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`. 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
+
+From a checkout of main:
+
+```sh
+export CONSOLE_URL=https://platform.dev.carlosframework.com
+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
+scripts/stripe-setup.sh --check # again: everything exists and nothing is wrong
+```
+
+Optional inputs: `PORTAL_HEADLINE`, `PORTAL_PRIVACY_URL`, `PORTAL_TERMS_URL`, `PORTAL_RETURN_URL` (default `$CONSOLE_URL/`), `PORTAL_CUSTOMER_UPDATES` (default `address name tax_id`), `HOUSE_COUPON_NAME`, `PRODUCT_NAME_<NAME>` and `STRIPE_PROJECT_NAME`. `scripts/stripe-setup.sh --help` lists them.
+
+What the script does:
+
+- 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 naming the book version (`stripe-setup:<book>:<kind>:<name>`). If a response gets lost, running again within 24 hours returns the same object instead of a second one.
+- After every create it reads the object back by id. It stops unless the object is active, in the run's mode, and the one it asked for (key, amount, metadata). A create Stripe answers by replaying an earlier response, for an object archived since, therefore stops the run (section 7).
+- If it makes the webhook endpoint, it writes `CARLOS_STRIPE_WEBHOOK_SECRET=whsec_...` to a file of its own and prints only the file's path. Before any write, `--apply` makes a new 0700 directory with `mktemp -d` (under `$TMPDIR`) and creates the file in it, 0600, holding it open; the secret goes through that descriptor. If no endpoint is made, the file and directory are removed. The secret never goes to stdout or stderr, so it stays out of logs and transcripts. Move it into 1Password and the console's EnvironmentFile (4.4), then delete the file and its directory. If you lose it, roll the secret in the Dashboard.
+- It refuses to run traced (`bash -x`, `xtrace` in an inherited `SHELLOPTS`, or `BASH_XTRACEFD` set) or with `BASH_ENV` set, before it touches a key: a trace would print the secret.
+- It looks only at the account's own webhook endpoints. An endpoint of a Connect application (`application` set) at the same URL gets connected accounts' events, so it is ignored and the account's endpoint is made beside it.
+- At the end it prints the console's non-secret variables, ready to paste.
+
+Two questions only the sandbox can answer:
+
+- Whether Stripe accepts `name` in the portal's `allowed_updates` at `2025-02-24.acacia`. If it refuses, run again with `PORTAL_CUSTOMER_UPDATES="address tax_id"`. The console accepts any subset.
+- Whether the portal configuration needs a `business_profile` at this API version. If it does, set `PORTAL_PRIVACY_URL` and `PORTAL_TERMS_URL`.
+
+### 4.3 What Paul does in the Dashboard
+
+All of this happens in the sandbox. The CLI cannot do it, or should not.
+
+1. **Stripe Tax.** Every Checkout sets `automatic_tax[enabled]=true` (`client.go:697`). Stripe Tax needs to be set up in the sandbox (head office address, and at least one registration if you want to see a tax line), or every Checkout create fails.
+2. **Retries.** Billing, Revenue recovery, Retries: when all retries fail, cancel the subscription (outline step 6). There is no API for this.
+3. **The restricted key.** Developers, API keys, Create restricted key. Name it after the console it is for, for example `console dev`. Set these permissions and leave every other one at None:
+
+ | Dashboard permission | Level | Why |
+ | --- | --- | --- |
+ | Checkout Sessions | Write | create, read, list and expire Checkout sessions, including a customer's |
+ | Customers | Write | create, update and read the account's customer |
+ | Subscriptions | Write | read, list and change subscriptions, and their items (seat and pack quantities) |
+ | Customer portal | Write | open portal sessions |
+ | Billing portal configurations (if the Dashboard lists it on its own row) | Read | the readiness check reads the locked configuration |
+ | Prices | Read | readiness and the clock probe |
+ | 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 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 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
+
+The dev console's systemd unit, `/etc/systemd/system/console.service`, exists only on the dev console box (carlos-dev-ie: profile `kass`, eu-west-1, `i-05498eada6f0afd23` when last recorded; confirm the instance before using it). It is not in any repo. Its drop-ins already follow one pattern: `console.service.d/release-key.conf` loads `EnvironmentFile=-/etc/carlos/release.env` (root:root 0600). Billing gets a drop-in of its own the same way.
+
+1. Look at what the unit loads now:
+
+ ```sh
+ systemctl cat console.service | grep -i EnvironmentFile
+ ```
+
+ `/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-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;
+ - `CARLOS_STRIPE_WEBHOOK_SECRET=whsec_...`, the line in the file whose path the script printed.
+
+ Keep the secrets off any command line, and out of SSM send-command output. Either put them in SSM Parameter Store as SecureStrings and have the box read them (the pattern in `2026-10-05-scanner-host-rollout.md`, Task 9, steps 3 and 5), or type them in an interactive session on the box.
+4. Add `/etc/systemd/system/console.service.d/billing.conf`:
+
+ ```ini
+ [Service]
+ EnvironmentFile=/etc/carlos/billing.env
+ ```
+
+ There is no leading `-`. If the file goes missing, the unit fails to start, instead of starting with billing quietly off.
+5. Restart and check:
+
+ ```sh
+ systemctl daemon-reload && systemctl restart console.service
+ journalctl -u console.service -n 50
+ ```
+
+ If a variable is wrong, the console stops and names it. If so, fix the file and run `systemctl reset-failed console.service` before you start it again. Otherwise, wait for the readiness check to pass. `/billing/webhook` then stops answering 503, and the Dashboard's webhook page shows deliveries succeeding once there are events.
+
+To turn billing off again, set `CARLOS_BILLING=off` and restart. Nothing at Stripe changes.
+
+## 5. The dev rehearsal (outline step 9)
+
+Use test clocks, and the sandbox's test cards. Tick each line on dev:
+
+- [ ] `/upgrade` while signed out, through sign-up, to Checkout.
+- [ ] Personal with packs. Community at 4 members and at 12.
+- [ ] A declined pack raise, then paid from the portal. A resubmit refused while it is pending. A pending update left to expire.
+- [ ] A deleted pack restored and charged above its paid count.
+- [ ] A buy-back refused within 25 h of renewal, and allowed after it.
+- [ ] A delayed renewal webhook, followed by a pack request.
+- [ ] Member joins with a good card, a declining card and a dropped connection (check `Idempotent-Replayed`). Two joins at once. A join using an already-paid seat inside the margin.
+- [ ] A leave, then a rejoin. Match seats after a CLI removal.
+- [ ] Personal to Business (`pending_if_incomplete` with a price swap).
+- [ ] Stopping and resuming renewal.
+- [ ] Deletion refused while renewing, while collecting, and with an unresolved resume-renewal request, then allowed.
+- [ ] An expiry racing a completed Checkout.
+- [ ] A Checkout create with a lost response, continued from the page.
+- [ ] A 409 while a request is in flight.
+- [ ] An operator closing `operation_unresolved` from the Dashboard request log.
+- [ ] The renewal invoice read used by the late-restore check.
+- [ ] A failed renewal, then cancellation. Out-of-order events. `incomplete_expired`. Webhook secret rotation (with `CARLOS_STRIPE_PREVIOUS_WEBHOOK_SECRETS`).
+- [ ] Readiness refusing a wrong price, an unlocked portal and a bad coupon, with backoff.
+- [ ] A house account at zero. The customer-currency lock.
+
+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).
+- [ ] That Accounts Read is enough for `GET /v1/account` (4.3).
+
+## 6. Live
+
+### 6.1 Decided (Paul)
+
+- **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.
+- **What "existing" means (2026-11-01):** an account created before the cutoff; one created at or after it, during the switch-on window included, is a new account on the normal plan, like any later signup.
+- **One-off sponsoring:** `deploy/billing/sponsored-unlimited.json` holds exactly the limits the console gives at launch, for an operator who later sponsors one account by hand: `carlos accounts plan --console https://console.carloku.com --account <sqid> --set free --sponsored deploy/billing/sponsored-unlimited.json --reason "..."`. `TestSponsoredUnlimitedFileIsTheLaunchSponsorship` keeps it equal to the console's own and checks the plan door accepts it.
+- **The ops account** (`bab`) is exempt from plans and billing (a2e23ba, in v0.33.0 and later). Nothing to do for it.
+
+### 6.2 Tax in the code
+
+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.
+
+### 6.3 The script's live path
+
+`scripts/stripe-setup.sh --live` makes the same objects as the sandbox run, from the approved book. The guards:
+
+- `--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.
+- As in the sandbox, every create is read back by id before it is used, the webhook signing secret goes only to the script's own file, and a traced run is refused (4.2).
+- 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.
+
+The flagship console's files are set by hand on its box, as in 4.4, until #453 brings console configuration into carloku-infrastructure.
+
+### 6.5 Switch-on, in order
+
+Paul, in the live Carloku account's Dashboard:
+
+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
+ ```
+
+ The webhook signing secret is only in the file whose path the `--apply` run printed. Move it into 1Password, and from there into the flagship's `billing.env` (step 6). Then delete the file and its directory, by the printed path. 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"`, written last (step 7). 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. **The cutoff, then one restart.** The console refuses a cutoff later than its start, so the cutoff comes before the restart. An account created between the two is a new account (6.1), not sponsored.
+ 1. With every other file in place, set `sponsor_accounts_before` in `/etc/carlos/plans.json` to the next whole second, for example the output of `date -u -d '+1 second' +%Y-%m-%dT%H:%M:%SZ`.
+ 2. Once that second has passed, `systemctl daemon-reload && systemctl restart console.service`.
+ 3. In the log:
+ - `console: sponsored N existing accounts with no limits (created before ...)`. N is every account created before the cutoff 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,** on a new account. Billing refuses Checkout for a sponsored account, and every account from before the cutoff is sponsored now, so make a fresh one. Never use `bab`, which has no billing:
+
+ ```sh
+ carlos accounts create --console https://console.carloku.com --name house-checkout
+ carlos billing house --console https://console.carloku.com -account <its 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
+
+- **The console refuses to start.** The log names the variable. Fix `/etc/carlos/billing.env`, run `systemctl reset-failed console.service` and start it again. Or set `CARLOS_BILLING=off`.
+- **The readiness check fails.** The log names the price key or the object, and the rule it broke. Run `scripts/stripe-setup.sh --check` to see the same thing from the Stripe side.
+- **A wrong object was made.** Replacing an object within one book version is not supported. Archive the wrong object in the Dashboard (archive a price or product, deactivate a portal configuration, delete a coupon, disable an endpoint). Then write a new book version: a new file and version, with the same or corrected amounts, which gives every price a new key and every create a new idempotency key. Run the script with `PRICE_BOOK` set to the new book, and point `CARLOS_PRICE_BOOK` and `CARLOS_BILLING_PRICES` at it. Prices and products that have been used cannot be deleted, only archived.
+- **The script stops with "Stripe replayed an earlier create".** That is the same case: it asked for an object under a key it used before, and Stripe answered with the earlier object, which has since been archived or changed. The script will not use it. Write a new book version, as above.
diff --git a/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-plans-6c-live.md b/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-plans-6c-live.md
new file mode 100644
index 000000000..3362c289c
--- /dev/null
+++ b/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-plans-6c-live.md
@@ -0,0 +1,36 @@
+# Review brief: branch plans-6c-stripe-setup (live path), round 3 of 3
+
+Repo carlos/platform, branch `plans-6c-stripe-setup`, the commit that adds this brief (named in your prompt).
+Under review: the diff `origin/main...HEAD`. It adds `scripts/stripe-setup.sh` (sandbox setup, now with a guarded `--live` mode), the approved price book `deploy/billing/pricebook-2026-11-01-v1.json` (the draft's amounts, approved by Paul), the runbook `docs/superpowers/plans/2026-10-27-plans-6c-stripe-setup.md`, and fake-CLI tests in `cmd/console/stripesetup_script_test.go`. This script will next run against Carloku's live Stripe account, creating the products, yearly prices, portal configuration, house coupon and webhook endpoint that the flagship console's billing reads.
+
+## Invariant
+
+The script never writes to an account or mode other than the one named. In live mode it writes only live objects that exactly match the approved book and what the console's readiness check expects. A rerun is idempotent and never moves or changes an existing price.
+
+## Round 3 (final)
+
+Round 2 (`~/.cache/plans-6c-live/review-r2.md`) found 4 P1s and a P2. Stopping rule 2 applied, so these were fixed structurally:
+- The script refuses traced execution and BASH_ENV before any key handling.
+- The secret goes only to a script-made 0700 `mktemp -d` directory, through a held descriptor under umask 077.
+- Paul ruled (2026-11-01) that an account created at or after the cutoff, including during the switch-on window, is a new account on the normal plan. The by-hand gap step is gone.
+- Webhook endpoints must have `application == null`.
+- The house command names the flagship console.
+
+## What to check
+
+1. Each round 2 finding is resolved, with no new instance of the secret-handling or webhook-scope families.
+2. Anything still blocking a safe first live run: dry run, `--check`, `--apply`, `--check`.
+
+This is the final round. Report only real defects; P3s go on a follow-up list. Don't reopen Paul's launch-window ruling.
+
+## Severity
+
+- **P1**: unsafe, would not compile, a test fails, or it would not work. Blocks merge.
+- **P2**: wrong or missing. Fixed without reopening this review.
+- **P3**: clarity or polish. Goes on a follow-up list; never a reason for another round.
+
+## Output
+
+Findings ranked P1, P2, P3 with file:line, failure scenario and fix. End with exactly one verdict: **READY**, **READY AFTER FIXES**, or **NOT READY**.
+
+Do not edit files. Do not call Stripe. Do not spawn Anthropic-model reviewers or subagents of your own. Do not run the full test suites.
diff --git a/internal/console/plansponsor_file_test.go b/internal/console/plansponsor_file_test.go
new file mode 100644
index 000000000..cd042d233
--- /dev/null
+++ b/internal/console/plansponsor_file_test.go
@@ -0,0 +1,41 @@
+package console
+
+import (
+ "bytes"
+ "encoding/json"
+ "os"
+ "reflect"
+ "testing"
+
+ "github.com/carlosframework/platform/internal/plans"
+)
+
+// deploy/billing/sponsored-unlimited.json is the limits file the plans 6c
+// runbook gives an operator for one-off sponsoring with `carlos accounts
+// plan --sponsored`. It must be exactly the launch sponsorship's own
+// limits, and the plan door must accept it.
+func TestSponsoredUnlimitedFileIsTheLaunchSponsorship(t *testing.T) {
+ b, err := os.ReadFile("../../deploy/billing/sponsored-unlimited.json")
+ if err != nil {
+ t.Fatal(err)
+ }
+ dec := json.NewDecoder(bytes.NewReader(b))
+ dec.DisallowUnknownFields()
+ var got plans.Limits
+ if err := dec.Decode(&got); err != nil {
+ t.Fatal(err)
+ }
+ if want := sponsorUnlimited(); !reflect.DeepEqual(got, want) {
+ t.Fatalf("the file holds %+v, the launch sponsorship %+v", got, want)
+ }
+ cat, err := plans.LoadCatalog("../plans/testdata/example-catalog.json")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if msg := planRequestProblem(cat, setAccountPlanRequest{Plan: cat.DefaultPlan, Sponsored: &got}); msg != "" {
+ t.Fatal(msg)
+ }
+ if _, err := cat.Effective(cat.DefaultPlan, nil, &got, 1); err != nil {
+ t.Fatalf("the plan door would refuse it: %v", err)
+ }
+}
diff --git a/scripts/stripe-setup.sh b/scripts/stripe-setup.sh
new file mode 100755
index 000000000..5fc236c7d
--- /dev/null
+++ b/scripts/stripe-setup.sh
@@ -0,0 +1,719 @@
+#!/usr/bin/env bash
+# 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 (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
+# metadata[carlos_product] = <plan> or pack/<pack>;
+# - one yearly price per product and currency, with lookup_key and
+# metadata[price_key] both set to the console's price key;
+# - the locked customer portal configuration, metadata[carlos_portal]=locked;
+# - the house coupon, metadata[carlos_coupon]=house;
+# - the webhook endpoint at $CONSOLE_URL/billing/webhook.
+# Then it prints the console's non-secret environment variables.
+#
+# Usage:
+# 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 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. If it makes the
+# webhook endpoint, it writes the endpoint's signing secret to a file
+# of its own, mode 0600 in a new 0700 directory, and prints only the
+# file's path.
+# 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 (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-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>.
+# PLAN_CATALOG_PATH the console box's catalog, for the printed
+# CARLOS_PLAN_CATALOG. Default /etc/carlos/plans.json.
+# PORTAL_RETURN_URL the portal's default return URL. Default
+# $CONSOLE_URL/.
+# PORTAL_HEADLINE optional portal headline, up to 60 characters.
+# PORTAL_CUSTOMER_UPDATES what a customer may edit in the portal, some of
+# "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 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:
+# - 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
+# configurations, valid coupons, enabled endpoints. So once a wrong
+# object is archived in the Dashboard, the next run makes a new one.
+# - It refuses to run traced (bash -x, an inherited SHELLOPTS xtrace,
+# BASH_XTRACEFD) or with BASH_ENV set: a trace would print the keys and
+# the webhook response it handles.
+# - The webhook signing secret never goes to stdout or stderr. Before
+# any write, --apply makes a 0700 directory with mktemp -d and creates
+# the secret file in it, 0600, holding it open; the secret is written
+# through that descriptor. If no endpoint is made, both are removed.
+# - Webhook endpoints of a Connect application (application set) are
+# not this account's endpoint: they are ignored, never reused.
+# - After every create it reads the object back by id, and stops unless
+# it is active, in the run's mode and the object it asked for. Each
+# create's idempotency key names the book version, so a create Stripe
+# answers with an earlier object (one since archived) stops the run:
+# replacing an object within one book version is not supported. Write
+# a new book version, with new price keys, instead.
+#
+# Needs bash, jq and the stripe CLI.
+set -euo pipefail
+
+# No tracing, before anything touches a key or a Stripe response: a trace
+# prints every assignment, the webhook endpoint's signing secret included.
+# BASH_ENV runs arbitrary code (a DEBUG trap, say) before this line.
+if [[ "$-" == *x* || ":${SHELLOPTS:-}:" == *:xtrace:* || -n "${BASH_XTRACEFD+set}" || -n "${BASH_ENV+set}" ]]; then
+ set +x
+ printf 'stripe-setup.sh: refusing to run traced (bash -x, SHELLOPTS xtrace or BASH_XTRACEFD) or with BASH_ENV set: a trace would print secrets\n' >&2
+ exit 1
+fi
+
+readonly API_VERSION="2025-02-24.acacia"
+readonly WEBHOOK_EVENTS=(
+ checkout.session.completed
+ customer.subscription.created
+ customer.subscription.updated
+ customer.subscription.deleted
+ invoice.paid
+ invoice.payment_failed
+)
+readonly WEBHOOK_PATH="/billing/webhook"
+
+here="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
+
+die() { printf 'stripe-setup.sh: %s\n' "$*" >&2; exit 1; }
+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) 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
+ command -v stripe >/dev/null || die "the stripe CLI is needed"
+fi
+
+# ---------------------------------------------------------------------------
+# Inputs
+
+[[ -n "${CONSOLE_URL:-}" ]] || die "CONSOLE_URL is required, e.g. CONSOLE_URL=https://console.example.com"
+console_url="${CONSOLE_URL%/}"
+[[ "$console_url" =~ ^https://[A-Za-z0-9.-]+(:[0-9]+)?$ ]] ||
+ die "CONSOLE_URL must be https://host or https://host:port, with no path"
+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"
+
+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-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}"
+
+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-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
+ case "$u" in address | name | tax_id) ;; *) die "PORTAL_CUSTOMER_UPDATES may hold only address, name and tax_id, not $u" ;; esac
+done
+project="${STRIPE_PROJECT_NAME:-}"
+
+check_url() { [[ -z "$2" || "$2" =~ ^https://[A-Za-z0-9.-]+(:[0-9]+)?(/[A-Za-z0-9._~/%?=\&-]*)?$ ]] || die "$1 must be an https URL"; }
+check_text() { [[ "$2" != *[[:cntrl:]]* ]] || die "$1 has a control character"; ((${#2} <= $3)) || die "$1 is longer than $3 characters"; }
+check_url PORTAL_RETURN_URL "$return_url"
+check_url PORTAL_PRIVACY_URL "$privacy_url"
+check_url PORTAL_TERMS_URL "$terms_url"
+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. 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.
+
+jq -e '
+ (.version | type == "string" and test("^[A-Za-z0-9._-]+$"))
+ and (.status == "draft" or .status == "approved")
+ and (.currencies | type == "array" and length > 0 and all(. == "usd" or . == "eur" or . == "gbp"))
+ and (.plans | type == "object") and (.packs | type == "object")
+ and ([.plans[], .packs[]] | all(type == "object" and all(.[]; type == "number" and . > 0 and . == floor)))
+' "$book_file" >/dev/null || die "$book_file is not a price book this script understands"
+
+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")"
+for c in "${currencies[@]}"; do
+ jq -e --arg c "$c" '[.plans[], .packs[]] | all(has($c))' "$book_file" >/dev/null ||
+ die "$book_file does not price everything in $c"
+done
+[[ " ${plan_names[*]} " != *" pack "* ]] || die "a paid plan may not be named pack"
+
+# ---------------------------------------------------------------------------
+# Printing and running commands
+
+readonly SQ="'\\''"
+quote() {
+ if [[ "$1" =~ ^[A-Za-z0-9_@%+=:,./-]+$ ]]; then
+ printf '%s' "$1"
+ else
+ printf "'%s'" "${1//\'/$SQ}"
+ fi
+}
+show() {
+ local first=1 w
+ for w in "$@"; do
+ if ((first)); then printf '%s' "$w"; first=0
+ elif [[ "$w" == -d ]]; then printf ' \\\n -d'
+ else printf ' %s' "$(quote "$w")"
+ fi
+ done
+ printf '\n'
+}
+
+# stripe_cmd fills the array cmd with one stripe CLI call.
+cmd=()
+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+=("$@")
+}
+
+# call runs cmd and leaves the response in $out. It stops on a failed call
+# or a Stripe error. The response is never printed: a webhook endpoint's
+# carries its signing secret.
+out=""
+call() {
+ local rc=0
+ printf '+ '; show "${cmd[@]}"
+ out="$("${cmd[@]}")" || rc=$?
+ if jq -e 'type == "object" and has("error")' >/dev/null 2>&1 <<<"$out"; then
+ die "Stripe refused the call above: $(jq -r '.error | [.type, .code, .message] | map(select(. != null)) | join(": ")' <<<"$out")"
+ fi
+ ((rc == 0)) || die "the call above failed (exit $rc)"
+ jq -e 'type == "object"' >/dev/null 2>&1 <<<"$out" || die "the call above did not answer with a JSON object"
+}
+
+# read_call is a read: printed in a dry run, run otherwise.
+read_call() {
+ stripe_cmd "$@"
+ if [[ "$mode" == "dry-run" ]]; then show "${cmd[@]}"; return 0; fi
+ call
+}
+
+# write_call is a create: printed in a dry run and in --check, run in --apply.
+# It returns 1 when it did not run.
+write_call() {
+ stripe_cmd "$@"
+ if [[ "$mode" != "apply" ]]; then show "${cmd[@]}"; return 1; fi
+ call
+}
+
+# list_all reads every page of a list into $out as one JSON array.
+list_all() {
+ local path="$1"
+ shift
+ local all="[]" after=""
+ while :; do
+ if [[ -n "$after" ]]; then
+ read_call get "$path" -d limit=100 -d "starting_after=$after" "$@"
+ else
+ read_call get "$path" -d limit=100 "$@"
+ 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 --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")"
+ done
+ out="$all"
+}
+
+# made_object checks a created object is in the run's mode and sets $id.
+id=""
+made_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")"
+}
+
+# read_back reads the object just made, $id, again by id into $out, and
+# stops unless <problem> (a jq program over it, with the given jq args)
+# comes back empty. A create Stripe answers by replaying an earlier response
+# under the same idempotency key carries that object's old state; only a
+# fresh read shows whether it has since been archived or changed.
+read_back() { # <what> <path> <problem> [jq args...] -- [read args...]
+ local what="$1" path="$2" prog="$3" problem
+ shift 3
+ local jqargs=()
+ while [[ $# -gt 0 && "$1" != -- ]]; do jqargs+=("$1"); shift; done
+ [[ $# -gt 0 ]] && shift
+ read_call get "$path/$id" "$@"
+ jq -e --arg id "$id" '.id == $id' >/dev/null <<<"$out" || die "reading $what $id back returned another object. Stopping"
+ problem="$(jq -r "${jqargs[@]}" "$prog" <<<"$out")"
+ [[ -z "$problem" ]] ||
+ die "the create for $what was answered with $id, which is $problem. Stripe replayed an earlier create under the same idempotency key, for an object since archived or changed. Replacing an object within one book version is not supported: write a new price book version (new file, new version, new price keys) and run with it"
+}
+
+ids='{}' # what the env block prints
+prices='{}' # price key -> price id
+remember() { ids="$(jq -c --arg k "$1" --arg v "$2" '. + {($k): $v}' <<<"$ids")"; }
+
+placeholder() { printf '<%s>' "$1"; }
+
+# ---------------------------------------------------------------------------
+# The console's readiness rules (internal/billingstripe/adapter.go), as jq.
+
+readonly PRICE_PROBLEM='
+ def own_options:
+ .currency as $c | .unit_amount as $a | .tax_behavior as $t
+ | (.currency_options // {}) as $o
+ | ($o | length) == 0
+ or (($o | length) == 1 and ($o | has($c))
+ 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 != '"$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"
+ elif (.recurring | type) != "object" then "not recurring"
+ elif .recurring.interval != "year" or .recurring.interval_count != 1 then "not billed once a year"
+ elif .recurring.usage_type != "licensed" then "not licensed"
+ elif .billing_scheme != "per_unit" then "not per unit"
+ elif .tax_behavior != "exclusive" then "not tax exclusive"
+ elif .transform_quantity != null then "has a quantity transform"
+ elif (own_options | not) then "has another currency option"
+ elif (.metadata.price_key // "") != $key then "its metadata price_key is not its key"
+ else "" end'
+
+readonly PRODUCT_PROBLEM='
+ if .active != true then "not active"
+ elif .livemode != '"$live"' then "not in '"$mode_word"' mode"
+ elif (.metadata.carlos_product // "") != $meta then "not the product for \($meta)"
+ else "" end'
+
+readonly PORTAL_PROBLEM='
+ .features as $f
+ | if .active != true then "not active"
+ 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"
+ elif $f.subscription_cancel.enabled == true then "cancellation is on"
+ elif ($f.subscription_pause.enabled // false) == true then "pause is on"
+ elif $f.customer_update.enabled == true
+ and ([$f.customer_update.allowed_updates[]? | select(. != "address" and . != "name" and . != "tax_id")] | length) > 0
+ then "customers may edit more than address, name and tax id"
+ else "" end'
+
+readonly COUPON_PROBLEM='
+ if .valid != true then "not valid"
+ 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"
+ elif ((.applies_to.products // []) | length) > 0 then "limited to some products"
+ elif .max_redemptions != null then "has a redemption limit"
+ elif .redeem_by != null then "has a redemption deadline"
+ else "" end'
+
+readonly WEBHOOK_PROBLEM='
+ if .application != null then "the endpoint of a Connect application"
+ elif .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 expected account, in the run's mode, nothing else.
+
+# The webhook signing secret's file, made before any write: a new 0700
+# directory from mktemp -d, so nobody else can place anything in it, and in
+# it a new file, 0600, created exclusively and held open on descriptor 9.
+# The secret is written through the descriptor, never by reopening the
+# path. Unless a secret was written, both are removed on exit, by exact
+# path.
+secret_dir=""
+secret_file=""
+secret_written=0
+cleanup_secret() {
+ if [[ -n "$secret_dir" && "$secret_written" == 0 ]]; then
+ rm -f -- "$secret_file"
+ rmdir -- "$secret_dir" 2>/dev/null || true
+ fi
+}
+if [[ "$mode" == apply ]]; then
+ secret_dir="$(mktemp -d)" || die "mktemp -d failed"
+ trap cleanup_secret EXIT
+ secret_file="$secret_dir/webhook-secret"
+ old_umask="$(umask)"
+ umask 077
+ set -C
+ exec 9>"$secret_file" || die "could not create $secret_file"
+ set +C
+ umask "$old_umask"
+ [[ -f "$secret_file" && ! -L "$secret_file" ]] || die "$secret_file is not a new regular file"
+fi
+
+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 $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 --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
+
+# ---------------------------------------------------------------------------
+# 1. Products, 2. prices
+
+capitalise() { printf '%s%s' "$(printf '%s' "${1:0:1}" | tr '[:lower:]' '[:upper:]')" "${1:1}"; }
+
+# product_name sets $pname: PRODUCT_NAME_<NAME> if set, else "Personal" for
+# personal and "Apps pack" for pack/apps.
+pname=""
+product_name() { # <product metadata value>
+ local var
+ var="PRODUCT_NAME_$(printf '%s' "$1" | tr '[:lower:]/-' '[:upper:]__')"
+ pname="${!var:-}"
+ if [[ -z "$pname" ]]; then
+ case "$1" in
+ pack/*) pname="$(capitalise "${1#pack/}") pack" ;;
+ *) pname="$(capitalise "$1")" ;;
+ esac
+ fi
+ [[ -n "$pname" ]] || die "$var is empty"
+ check_text "$var" "$pname" 250
+}
+
+echo "## Products: metadata[carlos_product] names each one"
+list_all /v1/products
+all_products="$out"
+echo
+
+setup_product() { # <metadata value> <book section> <book name>
+ local meta="$1" section="$2" name="$3" found n pid made=0
+ echo "## Product $meta"
+ found="$(jq -c --arg m "$meta" '[.[] | select(.metadata.carlos_product == $m and .active == true)]' <<<"$all_products")"
+ n="$(jq length <<<"$found")"
+ if ((n > 1)); then die "$n active products have metadata[carlos_product]=$meta. Keep one, archive the others in the Dashboard, and run again"; fi
+ if ((n == 1)); then
+ pid="$(jq -r '.[0].id' <<<"$found")"
+ local tc
+ tc="$(jq -r '.[0].tax_code // "none"' <<<"$found")"
+ [[ "$tc" == "$tax_code" ]] || warn "product $meta ($pid) has tax code $tc, not $tax_code. This script does not change it"
+ echo "# exists: $pid"
+ else
+ echo "# none yet; this creates it:"
+ product_name "$meta"
+ if write_call post /v1/products -i "stripe-setup:$book_version:product:$meta" \
+ -d "name=$pname" -d "tax_code=$tax_code" -d "metadata[carlos_product]=$meta"; then
+ made_object prod_
+ read_back "product $meta" /v1/products "$PRODUCT_PROBLEM" --arg meta "$meta"
+ pid="$id"
+ made=1
+ echo "# created: $pid"
+ else
+ pid="$(placeholder "product $meta")"
+ fi
+ fi
+
+ local existing="[]"
+ if [[ "$mode" != "dry-run" && "$pid" == prod_* && "$made" == 0 ]]; then
+ list_all /v1/prices -d "product=$pid" -d "expand[]=data.currency_options"
+ existing="$out"
+ elif [[ "$mode" == "dry-run" ]]; then
+ list_all /v1/prices -d "product=$pid" -d "expand[]=data.currency_options"
+ fi
+
+ local cur key amount m problem prid
+ for cur in "${currencies[@]}"; do
+ if [[ "$section" == plans ]]; then key="$book_version/$name/$cur"; else key="$book_version/pack/$name/$cur"; fi
+ amount="$(jq -r --arg s "$section" --arg n "$name" --arg c "$cur" '.[$s][$n][$c]' "$book_file")"
+ echo "# price $key: $amount minor units a year"
+ found="$(jq -c --arg k "$key" '[.[] | select((.lookup_key == $k or .metadata.price_key == $k) and .active == true)]' <<<"$existing")"
+ m="$(jq length <<<"$found")"
+ if ((m > 1)); then die "$m active prices on $pid claim key $key. Archive the extra ones in the Dashboard and run again"; fi
+ if ((m == 1)); then
+ prid="$(jq -r '.[0].id' <<<"$found")"
+ problem="$(jq -r --arg key "$key" --arg currency "$cur" --argjson amount "$amount" --arg product "$pid" ".[0] | $PRICE_PROBLEM" <<<"$found")"
+ [[ -z "$problem" ]] || die "price $key ($prid): $problem. The console would refuse it. Archive it in the Dashboard and run again"
+ [[ "$(jq -r '.[0].lookup_key // ""' <<<"$found")" == "$key" ]] || warn "price $key ($prid) has no lookup_key $key. The console does not read it"
+ echo "# exists: $prid"
+ elif write_call post /v1/prices -i "stripe-setup:$book_version:price:$key" \
+ -d "product=$pid" -d "currency=$cur" -d "unit_amount=$amount" \
+ -d "recurring[interval]=year" -d "recurring[interval_count]=1" -d "recurring[usage_type]=licensed" \
+ -d billing_scheme=per_unit -d tax_behavior=exclusive \
+ -d "lookup_key=$key" -d "metadata[price_key]=$key"; then
+ made_object price_
+ prid="$id"
+ problem="$(jq -r --arg key "$key" --arg currency "$cur" --argjson amount "$amount" --arg product "$pid" "$PRICE_PROBLEM" <<<"$out")"
+ [[ -z "$problem" ]] || die "the price just made for $key ($prid): $problem. Stopping"
+ read_back "price $key" /v1/prices \
+ "($PRICE_PROBLEM) as \$p | if \$p == \"\" and (.lookup_key // \"\") != \$key then \"without lookup key \\(\$key)\" else \$p end" \
+ --arg key "$key" --arg currency "$cur" --argjson amount "$amount" --arg product "$pid" \
+ -- -d "expand[]=currency_options"
+ echo "# created: $prid"
+ else
+ prid="$(placeholder "price $key")"
+ fi
+ prices="$(jq -c --arg k "$key" --arg v "$prid" '. + {($k): $v}' <<<"$prices")"
+ done
+ echo
+}
+
+for p in "${plan_names[@]}"; do setup_product "$p" plans "$p"; done
+for p in "${pack_names[@]}"; do setup_product "pack/$p" packs "$p"; done
+
+# ---------------------------------------------------------------------------
+# 3. The locked portal configuration
+
+echo "## The locked portal configuration: metadata[carlos_portal]=locked"
+list_all /v1/billing_portal/configurations
+found="$(jq -c '[.[] | select(.metadata.carlos_portal == "locked" and .active == true)]' <<<"$out")"
+n="$(jq length <<<"$found")"
+if ((n > 1)); then die "$n active portal configurations have metadata[carlos_portal]=locked. Deactivate the extra ones in the Dashboard and run again"; fi
+if ((n == 1)); then
+ portal="$(jq -r '.[0].id' <<<"$found")"
+ problem="$(jq -r ".[0] | $PORTAL_PROBLEM" <<<"$found")"
+ [[ -z "$problem" ]] || die "portal configuration $portal: $problem. The console would refuse it. Fix it in the Dashboard, or deactivate it, and run again"
+ echo "# exists: $portal"
+else
+ echo "# none yet; this creates it:"
+ args=(
+ -d "features[payment_method_update][enabled]=true"
+ -d "features[invoice_history][enabled]=true"
+ -d "features[customer_update][enabled]=true"
+ -d "features[subscription_update][enabled]=false"
+ -d "features[subscription_cancel][enabled]=false"
+ -d "default_return_url=$return_url"
+ )
+ for u in "${customer_updates[@]}"; do args+=(-d "features[customer_update][allowed_updates][]=$u"); done
+ [[ -z "$headline" ]] || args+=(-d "business_profile[headline]=$headline")
+ [[ -z "$privacy_url" ]] || args+=(-d "business_profile[privacy_policy_url]=$privacy_url")
+ [[ -z "$terms_url" ]] || args+=(-d "business_profile[terms_of_service_url]=$terms_url")
+ args+=(-d "metadata[carlos_portal]=locked")
+ if write_call post /v1/billing_portal/configurations -i "stripe-setup:$book_version:portal:locked" "${args[@]}"; then
+ made_object bpc_
+ portal="$id"
+ problem="$(jq -r "$PORTAL_PROBLEM" <<<"$out")"
+ [[ -z "$problem" ]] || die "the portal configuration just made ($portal): $problem. Stopping"
+ read_back "the locked portal configuration" /v1/billing_portal/configurations \
+ "($PORTAL_PROBLEM) as \$p | if \$p == \"\" and .metadata.carlos_portal != \"locked\" then \"not the locked configuration\" else \$p end"
+ echo "# created: $portal"
+ else
+ portal="$(placeholder "portal configuration")"
+ fi
+fi
+remember CARLOS_STRIPE_PORTAL_CONFIGURATION "$portal"
+echo
+
+# ---------------------------------------------------------------------------
+# 4. The house coupon
+
+echo "## The house coupon: metadata[carlos_coupon]=house"
+list_all /v1/coupons -d "expand[]=data.applies_to"
+found="$(jq -c '[.[] | select(.metadata.carlos_coupon == "house" and .valid == true)]' <<<"$out")"
+n="$(jq length <<<"$found")"
+if ((n > 1)); then die "$n valid coupons have metadata[carlos_coupon]=house. Delete the extra ones in the Dashboard and run again"; fi
+if ((n == 1)); then
+ coupon="$(jq -r '.[0].id' <<<"$found")"
+ problem="$(jq -r ".[0] | $COUPON_PROBLEM" <<<"$found")"
+ [[ -z "$problem" ]] || die "house coupon $coupon: $problem. The console would refuse it. Coupons cannot be changed: delete it in the Dashboard, then run again"
+ echo "# exists: $coupon"
+else
+ echo "# none yet; this creates it (no promotion code):"
+ 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:$book_version:coupon:house" "${args[@]}"; then
+ 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"
+ id="$coupon"
+ read_back "the house coupon" /v1/coupons \
+ "($COUPON_PROBLEM) as \$p | if \$p == \"\" and .metadata.carlos_coupon != \"house\" then \"not the house coupon\" else \$p end" \
+ -- -d "expand[]=applies_to"
+ echo "# created: $coupon"
+ else
+ coupon="$(placeholder "house coupon")"
+ fi
+fi
+remember CARLOS_STRIPE_HOUSE_COUPON "$coupon"
+echo
+
+# ---------------------------------------------------------------------------
+# 5. The webhook endpoint
+
+events_json="$(printf '%s\n' "${WEBHOOK_EVENTS[@]}" | jq -R . | jq -sc .)"
+echo "## The webhook endpoint: $webhook_url"
+list_all /v1/webhook_endpoints
+# A Connect application's endpoint at the same URL gets connected accounts'
+# events, not this account's: it is not the endpoint, and is left alone.
+found="$(jq -c --arg u "$webhook_url" '[.[] | select(.url == $u and .status == "enabled" and .application == null)]' <<<"$out")"
+n="$(jq length <<<"$found")"
+if ((n > 1)); then die "$n enabled webhook endpoints point at $webhook_url. Delete the extra ones in the Dashboard and run again"; fi
+if ((n == 1)); then
+ we="$(jq -r '.[0].id' <<<"$found")"
+ problem="$(jq -r --arg version "$API_VERSION" --argjson events "$events_json" ".[0] | $WEBHOOK_PROBLEM" <<<"$found")"
+ [[ -z "$problem" ]] || die "webhook endpoint $we: $problem. Fix its events in the Dashboard, or, for a wrong API version (fixed when an endpoint is made), disable it and run again"
+ echo "# exists: $we. Its signing secret went to the file the run that made it named."
+ echo "# If you do not have it, roll it in the Dashboard (Developers, Webhooks, the endpoint, Roll secret)."
+else
+ echo "# none yet; this creates it:"
+ args=(-d "url=$webhook_url")
+ for e in "${WEBHOOK_EVENTS[@]}"; do args+=(-d "enabled_events[]=$e"); done
+ args+=(-d "api_version=$API_VERSION" -d "description=console billing" -d "metadata[carlos_webhook]=billing")
+ if write_call post /v1/webhook_endpoints -i "stripe-setup:$book_version:webhook:$webhook_url" "${args[@]}"; then
+ made_object we_
+ problem="$(jq -r --arg version "$API_VERSION" --argjson events "$events_json" "$WEBHOOK_PROBLEM" <<<"$out")"
+ [[ -z "$problem" ]] || die "the webhook endpoint just made ($id): $problem. Stopping"
+ secret="$(jq -r '.secret // ""' <<<"$out")"
+ out=""
+ [[ "$secret" == whsec_* ]] || die "the new webhook endpoint ($id) came back without a signing secret. Roll its secret in the Dashboard"
+ # Read back before the secret is kept: a replayed create carries the
+ # secret of an endpoint that may since have been disabled.
+ read_back "the webhook endpoint" /v1/webhook_endpoints \
+ "($WEBHOOK_PROBLEM) as \$p | if \$p == \"\" and .url != \$url then \"at another URL\" else \$p end" \
+ --arg version "$API_VERSION" --argjson events "$events_json" --arg url "$webhook_url"
+ out=""
+ # noclobber: the file is made new, never written through an existing one.
+ if ! printf 'CARLOS_STRIPE_WEBHOOK_SECRET=%s\n' "$secret" >&9; then
+ secret=""
+ die "could not write $secret_file. The endpoint $id exists: roll its secret in the Dashboard (Developers, Webhooks, the endpoint, Roll secret)"
+ fi
+ secret=""
+ exec 9>&-
+ secret_written=1
+ echo "# created: $id. Its signing secret is in $secret_file (mode 0600, in a new 0700 directory), and nowhere else."
+ echo "# Move it into the password manager and the console's EnvironmentFile, then delete the file and its directory."
+ fi
+fi
+echo
+
+# ---------------------------------------------------------------------------
+# The console's environment
+
+echo "## Console environment (non-secret). Paste into the console's EnvironmentFile."
+if [[ "$mode" != "apply" ]]; then
+ echo "# Values in <angle brackets> are ids --apply would create."
+fi
+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.
+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_${mode_word}_ restricted key made in the Dashboard (the plans 6c runbook)"
+echo "# CARLOS_STRIPE_WEBHOOK_SECRET the whsec_ signing secret, in the file named when the endpoint is made"