From 4833f53e0d5a8dc5d1b35f19c357e1a56d838d9c Mon Sep 17 00:00:00 2001 From: David Young Date: Wed, 25 Nov 2026 13:21:25 -0700 Subject: [PATCH] Phase 14, part 3: Stripe's events /billing/stripe takes Stripe's webhooks, signatures checked, each event handled once, and keeps each team's subscription up to date: checkout, its status, seats and period, failed and paid invoices, cancellation. Co-Authored-By: Claude Opus 5.5 --- PLAN.md | 17 +++ internal/billing/billing_test.go | 69 +++++++++++ internal/billing/webhook.go | 204 +++++++++++++++++++++++++++++++ internal/web/access.go | 2 + internal/web/activity.go | 2 +- internal/web/auth.go | 2 +- internal/web/billing.go | 73 +++++++++++ internal/web/billing_test.go | 53 ++++++++ internal/web/server.go | 1 + 9 files changed, 421 insertions(+), 2 deletions(-) create mode 100644 internal/billing/webhook.go diff --git a/PLAN.md b/PLAN.md index 6f0b5a6..7941175 100644 --- a/PLAN.md +++ b/PLAN.md @@ -3255,6 +3255,23 @@ Checkout; both are off until set. cancelling). Admins see the plan without the payment details or the buttons. +**Part 3 built 2026-11-26.** +- `POST /billing/stripe` takes Stripe's events: its `Stripe-Signature` + checked (HMAC-SHA256 of the timestamp and body, with + `SUPERMARKET_STRIPE_WEBHOOK_SECRET`; within 5 minutes; either of two + signatures while a secret is rolled). Each event is handled once + (`stripe_events`), whichever copy it reaches; a failure answers 500, so + Stripe sends it again. +- Followed: `checkout.session.completed` (the team's customer and + subscription), `customer.subscription.created`, `.updated` and + `.deleted` (status, people paid for, the period's end, the trial's end; + `unpaid` and `incomplete` count as past due), `invoice.payment_failed` + and `invoice.paid`. Falling past due notes when; catching up forgets it. + Customers that aren't a team's (another product on the same Stripe + account) are left alone. Each change goes in the team's audit log. +- Stripe's dashboard needs the endpoint `https:///billing/stripe` + with those events. + #### Order ``` diff --git a/internal/billing/billing_test.go b/internal/billing/billing_test.go index 9873d23..9f30cf0 100644 --- a/internal/billing/billing_test.go +++ b/internal/billing/billing_test.go @@ -81,3 +81,72 @@ func TestAccounts(t *testing.T) { t.Error("event twice") } } + +func TestWebhookSignature(t *testing.T) { + body := []byte(`{"id":"evt_1"}`) + now := time.Now() + h := Sign(body, "whsec_x", now) + if err := VerifySignature(h, body, "whsec_x", now); err != nil { + t.Fatal(err) + } + if VerifySignature(h, body, "whsec_y", now) == nil || VerifySignature(h, []byte(`{"id":"evt_2"}`), "whsec_x", now) == nil { + t.Error("a wrong secret or body passed") + } + if VerifySignature(h, body, "whsec_x", now.Add(10*time.Minute)) == nil { + t.Error("an old event passed") + } + if VerifySignature("t=1,v0=abc", body, "whsec_x", now) == nil || VerifySignature("", body, "whsec_x", now) == nil { + t.Error("a malformed header passed") + } + // Stripe may send two signatures while a secret is rolled. + if err := VerifySignature(h+",v1=00ff", body, "whsec_x", now); err != nil { + t.Error("two signatures") + } +} + +func TestApplyEvents(t *testing.T) { + p := Defaults() + now := time.Now() + acct := &Account{Team: 7, Status: Trialing, TrialEnds: now.Add(time.Hour)} + load := func(team int64, customer string) (*Account, error) { + if team == 7 || (customer != "" && customer == acct.Customer) { + return acct, nil + } + return nil, nil + } + ev := func(typ, obj string) *Event { + e := &Event{ID: "evt", Type: typ} + e.Data.Object = []byte(obj) + return e + } + a, c, err := Apply(load, p, ev("checkout.session.completed", `{"client_reference_id":"7","customer":"cus_1","subscription":"sub_1"}`), now) + if err != nil || a.Customer != "cus_1" || a.Subscription != "sub_1" || c.Team != 7 { + t.Fatalf("checkout: %+v %v", a, err) + } + a, c, _ = Apply(load, p, ev("customer.subscription.updated", `{"id":"sub_1","customer":"cus_1","status":"active","metadata":{"team":"7"},"items":{"data":[{"quantity":4,"current_period_end":1900000000}]}}`), now) + if a.Status != Active || a.Seats != 4 || a.PeriodEnd.Unix() != 1900000000 || c.Before != Trialing { + t.Errorf("updated: %+v", a) + } + a, _, _ = Apply(load, p, ev("invoice.payment_failed", `{"customer":"cus_1"}`), now) + if a.Status != PastDue || !a.PastDueSince.Equal(now) { + t.Errorf("failed: %+v", a) + } + a, _, _ = Apply(load, p, ev("invoice.payment_failed", `{"customer":"cus_1"}`), now.Add(time.Hour)) + if !a.PastDueSince.Equal(now) { + t.Error("past due since moved") + } + a, _, _ = Apply(load, p, ev("invoice.paid", `{"customer":"cus_1"}`), now) + if a.Status != Active || !a.PastDueSince.IsZero() { + t.Errorf("paid: %+v", a) + } + a, _, _ = Apply(load, p, ev("customer.subscription.deleted", `{"id":"sub_1","customer":"cus_1","status":"canceled","metadata":{"team":"7"}}`), now) + if a.Status != Canceled || a.Subscription != "" { + t.Errorf("deleted: %+v", a) + } + if a, c, err := Apply(load, p, ev("invoice.paid", `{"customer":"cus_other"}`), now); a != nil || c != nil || err != nil { + t.Error("another product's customer") + } + if a, _, _ := Apply(load, p, ev("charge.refunded", `{}`), now); a != nil { + t.Error("an event billing doesn't follow") + } +} diff --git a/internal/billing/webhook.go b/internal/billing/webhook.go new file mode 100644 index 0000000..24244a1 --- /dev/null +++ b/internal/billing/webhook.go @@ -0,0 +1,204 @@ +package billing + +import ( + "crypto/hmac" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "errors" + "strconv" + "strings" + "time" +) + +// Stripe's webhooks. + +// Tolerance is how old a signed event may be. +const Tolerance = 5 * time.Minute + +// ErrSignature is an event whose signature doesn't check. +var ErrSignature = errors.New("the event's signature doesn't match") + +// VerifySignature checks Stripe's Stripe-Signature header (t=…,v1=…) on a +// body: an HMAC-SHA256, with the webhook's secret, of ".". +func VerifySignature(header string, body []byte, secret string, now time.Time) error { + var t int64 + var sigs []string + for _, part := range strings.Split(header, ",") { + k, v, ok := strings.Cut(strings.TrimSpace(part), "=") + if !ok { + continue + } + switch k { + case "t": + t, _ = strconv.ParseInt(v, 10, 64) + case "v1": + sigs = append(sigs, v) + } + } + if t == 0 || len(sigs) == 0 || secret == "" { + return ErrSignature + } + if d := now.Sub(time.Unix(t, 0)); d > Tolerance || d < -Tolerance { + return errors.New("the event is too old, or from the future") + } + mac := hmac.New(sha256.New, []byte(secret)) + mac.Write([]byte(strconv.FormatInt(t, 10) + "." + string(body))) + want := mac.Sum(nil) + for _, s := range sigs { + got, err := hex.DecodeString(s) + if err == nil && hmac.Equal(got, want) { + return nil + } + } + return ErrSignature +} + +// Sign makes a Stripe-Signature header: for tests. +func Sign(body []byte, secret string, at time.Time) string { + t := strconv.FormatInt(at.Unix(), 10) + mac := hmac.New(sha256.New, []byte(secret)) + mac.Write([]byte(t + "." + string(body))) + return "t=" + t + ",v1=" + hex.EncodeToString(mac.Sum(nil)) +} + +// Event is a Stripe event, as far as billing reads it. +type Event struct { + ID string `json:"id"` + Type string `json:"type"` + Data struct { + Object json.RawMessage `json:"object"` + } `json:"data"` +} + +// The objects billing reads. +type checkoutSession struct { + ClientReference string `json:"client_reference_id"` + Customer string `json:"customer"` + Subscription string `json:"subscription"` +} + +type subscription struct { + ID string `json:"id"` + Customer string `json:"customer"` + Status string `json:"status"` + CurrentPeriodEnd int64 `json:"current_period_end"` + TrialEnd int64 `json:"trial_end"` + Metadata map[string]string `json:"metadata"` + Items struct { + Data []struct { + Quantity int `json:"quantity"` + CurrentPeriodEnd int64 `json:"current_period_end"` + Price struct { + ID string `json:"id"` + } `json:"price"` + } `json:"data"` + } `json:"items"` +} + +type invoice struct { + Customer string `json:"customer"` + Subscription string `json:"subscription"` +} + +// Change is what an event did to a team's account, for the log. +type Change struct { + Team int64 + Before string // the status before + After string + Note string +} + +// Apply updates the accounts for an event. Events about customers +// Supermarket doesn't know (another product on the same Stripe account) +// are ignored: a nil Change. +func Apply(load func(team int64, customer string) (*Account, error), p *Plans, e *Event, now time.Time) (*Account, *Change, error) { + switch e.Type { + case "checkout.session.completed": + var cs checkoutSession + if err := json.Unmarshal(e.Data.Object, &cs); err != nil { + return nil, nil, err + } + team, _ := strconv.ParseInt(cs.ClientReference, 10, 64) + a, err := load(team, cs.Customer) + if err != nil || a == nil { + return nil, nil, err + } + before := a.Status + a.Customer = cs.Customer + if cs.Subscription != "" { + a.Subscription = cs.Subscription + } + return a, &Change{Team: a.Team, Before: before, After: a.Status, Note: "subscribed through Checkout"}, nil + + case "customer.subscription.created", "customer.subscription.updated", "customer.subscription.deleted": + var sub subscription + if err := json.Unmarshal(e.Data.Object, &sub); err != nil { + return nil, nil, err + } + team, _ := strconv.ParseInt(sub.Metadata["team"], 10, 64) + a, err := load(team, sub.Customer) + if err != nil || a == nil { + return nil, nil, err + } + before := a.Status + a.Customer, a.Subscription, a.Plan = sub.Customer, sub.ID, p.Paid + status := sub.Status + switch status { + case "unpaid", "incomplete": + status = PastDue + case "incomplete_expired", "paused": + status = Canceled + } + if e.Type == "customer.subscription.deleted" { + status, a.Subscription = Canceled, "" + } + a.Status = status + if len(sub.Items.Data) > 0 { + a.Seats = sub.Items.Data[0].Quantity + } + end := sub.CurrentPeriodEnd + if end == 0 && len(sub.Items.Data) > 0 { + end = sub.Items.Data[0].CurrentPeriodEnd // newer API versions keep it on the item + } + if end > 0 { + a.PeriodEnd = time.Unix(end, 0) + } + if sub.TrialEnd > 0 { + a.TrialEnds = time.Unix(sub.TrialEnd, 0) + } + markPastDue(a, now) + return a, &Change{Team: a.Team, Before: before, After: a.Status}, nil + + case "invoice.payment_failed", "invoice.paid": + var inv invoice + if err := json.Unmarshal(e.Data.Object, &inv); err != nil { + return nil, nil, err + } + a, err := load(0, inv.Customer) + if err != nil || a == nil { + return nil, nil, err + } + before := a.Status + if e.Type == "invoice.payment_failed" && a.Subscription != "" { + a.Status = PastDue + } else if e.Type == "invoice.paid" && a.Status == PastDue { + a.Status = Active + } + markPastDue(a, now) + return a, &Change{Team: a.Team, Before: before, After: a.Status, Note: strings.ReplaceAll(e.Type, "_", " ")}, nil + } + return nil, nil, nil // not an event billing follows +} + +// markPastDue notes when a team fell behind, and forgets it when it's +// caught up. +func markPastDue(a *Account, now time.Time) { + if a.Status == PastDue { + if a.PastDueSince.IsZero() { + a.PastDueSince = now + } + return + } + a.PastDueSince, a.Warned = time.Time{}, "" +} diff --git a/internal/web/access.go b/internal/web/access.go index bd12d61..7c23077 100644 --- a/internal/web/access.go +++ b/internal/web/access.go @@ -30,6 +30,8 @@ var routeAreas = map[string]string{ "/static": areaPublic, "=/favicon.ico": areaPublic, "=/healthz": areaPublic, "=/mcp": areaPublic, "/signin": areaPublic, "=/signout": areaPublic, "=/forgot": areaPublic, "/reset": areaPublic, "/setup": areaPublic, "/invite": areaPublic, "/signup": areaPublic, + // Stripe's events: signed with the webhook's secret instead. + "=/billing/stripe": areaPublic, "/teams": areaSignedIn, // The JSON API: its own keys, like /mcp. "/api": areaPublic, diff --git a/internal/web/activity.go b/internal/web/activity.go index d831352..3a4a6d1 100644 --- a/internal/web/activity.go +++ b/internal/web/activity.go @@ -180,7 +180,7 @@ var actionLabels = map[string]string{ "key-made": "made a new key for", "key-revoked": "revoked a key of", "asked-approval": "asked for approval to", "did-on-its-own": "did on its own:", "approved": "approved", "refused": "refused", "allowed-on-its-own": "let an agent act on its own:", "withdrew-on-its-own": "took back what an agent may do on its own:", - "signin-settings": "changed how people sign in:", "billing-checkout": "went to subscribe:", "team-created": "set up the team", "viewed-as": "looked at the team's data:", "team-suspended": "suspended the team", "team-restored": "restored the team", + "signin-settings": "changed how people sign in:", "billing-checkout": "went to subscribe:", "billing": "billing changed:", "team-created": "set up the team", "viewed-as": "looked at the team's data:", "team-suspended": "suspended the team", "team-restored": "restored the team", "domain-released": "released the domain", "exported": "exported", "downloaded-export": "downloaded the export", "team-deleting": "asked to delete the team", "team-undeleted": "undid the team's deletion", "invitations-resent": "sent the invitations again:", "domain-proved": "proved the domain", "agent-paused": "paused the agent", "agent-resumed": "resumed the agent", "agent-limits": "changed the limits of", "wrote-draft": "wrote a draft:", "edited-draft": "edited a draft:", "edited-change": "edited a proposed change to", "market-added": "added to the Market", "market-changed": "changed in the Market", } diff --git a/internal/web/auth.go b/internal/web/auth.go index c33b712..c195388 100644 --- a/internal/web/auth.go +++ b/internal/web/auth.go @@ -298,7 +298,7 @@ func (s *Server) csrf(next http.Handler) http.Handler { if c, err := r.Cookie(name); err == nil && len(c.Value) >= 32 { token = c.Value } - if !safeMethod(r.Method) && r.URL.Path != "/mcp" && !strings.HasPrefix(r.URL.Path, "/api/v1/") { + if !safeMethod(r.Method) && r.URL.Path != "/mcp" && !strings.HasPrefix(r.URL.Path, "/api/v1/") && r.URL.Path != "/billing/stripe" { if token == "" || !sameToken(token, sentToken(r)) { http.Error(w, "This form has expired: reload the page and try again.", http.StatusForbidden) return diff --git a/internal/web/billing.go b/internal/web/billing.go index 50ced8e..c62b173 100644 --- a/internal/web/billing.go +++ b/internal/web/billing.go @@ -2,10 +2,13 @@ package web import ( "context" + "encoding/json" "fmt" + "io" "net/http" "time" + "supermarket/internal/audit" "supermarket/internal/billing" "supermarket/internal/users" ) @@ -172,3 +175,73 @@ func (s *Server) billingPortal(w http.ResponseWriter, r *http.Request) { } http.Redirect(w, r, addr, http.StatusSeeOther) } + +// stripeWebhook takes Stripe's events (POST /billing/stripe), with their +// signatures checked; each is handled once. +func (s *Server) stripeWebhook(w http.ResponseWriter, r *http.Request) { + if !s.billingOn() || s.Config == nil { + http.NotFound(w, r) + return + } + body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, 1<<20)) + if err != nil { + http.Error(w, "too large", http.StatusRequestEntityTooLarge) + return + } + now := time.Now() + if err := billing.VerifySignature(r.Header.Get("Stripe-Signature"), body, s.Config.StripeWebhookSecret, now); err != nil { + s.Log.Warn("billing: a webhook refused", "err", err, "ip", clientIP(r)) + http.Error(w, "bad signature", http.StatusBadRequest) + return + } + var e billing.Event + if err := json.Unmarshal(body, &e); err != nil || e.ID == "" { + http.Error(w, "unreadable event", http.StatusBadRequest) + return + } + var seen int + _ = s.platform().QueryRow(`SELECT count(*) FROM stripe_events WHERE id = ?`, e.ID).Scan(&seen) + if seen > 0 { + w.WriteHeader(http.StatusOK) // already handled + return + } + load := func(team int64, customer string) (*billing.Account, error) { + if customer != "" { + if a, err := billing.ByCustomer(s.platform(), customer); err == nil { + return a, nil + } + } + if team == 0 { + return nil, nil + } + if _, err := users.GetTeam(s.platform(), team); err != nil { + return nil, nil // not one of ours + } + return billing.Get(s.platform(), team) + } + a, change, err := billing.Apply(load, s.Plans, &e, now) + if err != nil { + s.Log.Error("billing: handling an event", "event", e.ID, "type", e.Type, "err", err) + http.Error(w, "couldn't handle it", http.StatusInternalServerError) // Stripe tries again + return + } + if a != nil { + if err := billing.Save(s.platform(), a, now); err != nil { + s.Log.Error("billing: saving", "event", e.ID, "err", err) + http.Error(w, "couldn't save it", http.StatusInternalServerError) + return + } + if ts, err := s.forTeam(a.Team); err == nil { + detail := e.Type + if change.Note != "" { + detail = change.Note + } + ts.record(audit.Entry{Kind: audit.System, Action: "billing", Target: change.Before + " → " + change.After, Detail: detail}) + } + s.Log.Info("billing: event", "type", e.Type, "team", a.Team, "status", a.Status) + } + if _, err := billing.SeenEvent(s.platform(), e.ID, e.Type, now); err != nil { + s.Log.Warn("billing: noting an event", "err", err) + } + w.WriteHeader(http.StatusOK) +} diff --git a/internal/web/billing_test.go b/internal/web/billing_test.go index 622afe5..9d6885d 100644 --- a/internal/web/billing_test.go +++ b/internal/web/billing_test.go @@ -1,6 +1,7 @@ package web import ( + "bytes" "net/http" "net/http/httptest" "net/url" @@ -10,6 +11,7 @@ import ( "testing" "time" + "supermarket/internal/audit" "supermarket/internal/billing" "supermarket/internal/users" ) @@ -253,3 +255,54 @@ func TestBillingPage(t *testing.T) { } _ = ts } + +// postEvent sends a signed Stripe event. +func postEvent(t *testing.T, s *Server, h http.Handler, id, typ, obj string, sign bool) int { + t.Helper() + body := []byte(`{"id":"` + id + `","type":"` + typ + `","data":{"object":` + obj + `}}`) + sig := "t=1,v1=00" + if sign { + sig = billing.Sign(body, s.Config.StripeWebhookSecret, time.Now()) + } + rec := do(h, http.MethodPost, "/billing/stripe", bytes.NewReader(body), map[string]string{"Stripe-Signature": sig, "Content-Type": "application/json", csrfHeader: ""}) + return rec.Code +} + +func TestStripeWebhooks(t *testing.T) { + s, h := newBilled(t) + s.Config.StripeWebhookSecret = "whsec_test" + signUp(t, h, "olu@acme.example", "Acme", "acme.example") + u, _ := users.ByEmail(s.platform(), "olu@acme.example") + list, _ := users.TeamsOf(s.platform(), u.ID) + team := strconv.FormatInt(list[0].ID, 10) + + if code := postEvent(t, s, h, "evt_0", "checkout.session.completed", `{"client_reference_id":"`+team+`","customer":"cus_9","subscription":"sub_9"}`, false); code != http.StatusBadRequest { + t.Errorf("unsigned: %d", code) + } + if code := postEvent(t, s, h, "evt_1", "checkout.session.completed", `{"client_reference_id":"`+team+`","customer":"cus_9","subscription":"sub_9"}`, true); code != http.StatusOK { + t.Fatalf("checkout: %d", code) + } + active := `{"id":"sub_9","customer":"cus_9","status":"active","metadata":{"team":"` + team + `"},"items":{"data":[{"quantity":3,"current_period_end":1900000000}]}}` + postEvent(t, s, h, "evt_2", "customer.subscription.updated", active, true) + a, _ := billing.Get(s.platform(), list[0].ID) + if a.Status != billing.Active || a.Customer != "cus_9" || a.Seats != 3 { + t.Fatalf("active: %+v", a) + } + postEvent(t, s, h, "evt_3", "invoice.payment_failed", `{"customer":"cus_9","subscription":"sub_9"}`, true) + // evt_2 again (Stripe retries): handled once, so it doesn't undo evt_3. + if code := postEvent(t, s, h, "evt_2", "customer.subscription.updated", active, true); code != http.StatusOK { + t.Errorf("replay: %d", code) + } + if a, _ = billing.Get(s.platform(), list[0].ID); a.Status != billing.PastDue || a.PastDueSince.IsZero() { + t.Errorf("past due: %+v", a) + } + // Someone else's customer on the same Stripe account: ignored. + if code := postEvent(t, s, h, "evt_4", "invoice.paid", `{"customer":"cus_other"}`, true); code != http.StatusOK { + t.Errorf("another customer: %d", code) + } + ts, _ := s.forTeam(list[0].ID) + entries, _ := audit.List(ts.DB, audit.Filter{Action: "billing"}, 10) + if len(entries) != 3 || !strings.Contains(entries[0].Target, "active → past_due") { + t.Errorf("log: %+v", entries) + } +} diff --git a/internal/web/server.go b/internal/web/server.go index 0902b50..a65f628 100644 --- a/internal/web/server.go +++ b/internal/web/server.go @@ -345,6 +345,7 @@ func (s *Server) Handler() (http.Handler, error) { // Signing in (the server edition). mux.HandleFunc("GET /setup/{token}", (*Server).setupPage) mux.HandleFunc("POST /setup/{token}", (*Server).setupSave) + mux.HandleFunc("POST /billing/stripe", (*Server).stripeWebhook) mux.HandleFunc("GET /settings/billing", (*Server).billingPage) mux.HandleFunc("POST /settings/billing/checkout", (*Server).billingCheckout) mux.HandleFunc("POST /settings/billing/portal", (*Server).billingPortal)