Files
commerce/checkout/org_resolver.go
89940a839b Stripe is the only processor for new charges, end to end (#42)
* payment: Square first, Stripe wherever Square cannot take the payment

Stripe was held out of every new charge by a default deny set. It is now
the fallback, by one rule: processor.Registry.Fiat walks the priority
order (Square, Stripe, ...) and returns the first processor that can take
the payment — registered, not denied, configured, in the currency, and,
for a processor that reports its reach, in the buyer's country and by the
buyer's method. A processor the caller names is that processor or none,
never a substitute, since a token belongs to the processor that minted
it. SelectProcessor, the hosted checkout and both public configs read
this one rule.

- Square reports its reach (the eight countries, card, Apple Pay, Google
  Pay, Cash App Pay); Stripe reports card, Apple Pay and Google Pay from
  any country. Registry.Cards is Fiat's answer for a card, per currency.
- COMMERCE_DISABLED_PROCESSORS denies nothing by default; the "none"
  sentinel is gone with the default it overrode.
- Stripe keys: the org's own, else the deployment's of the org's kind
  (STRIPE_SECRET_KEY/STRIPE_PUBLISHABLE_KEY live,
  STRIPE_TEST_SECRET_KEY/STRIPE_TEST_PUBLISHABLE_KEY test); a key whose
  prefix names the other kind is dropped.
- The Stripe provider sends an Idempotency-Key (fitted to 255) on money
  moves, and a PaymentIntent that requires 3-D Secure is a failed charge:
  it used to read as Success, which TakePayment would have credited.
- Saved-card charges name Square: the card on file is Square's.
- GET /v1/commerce/org carries cards (per currency, for the caller's
  country) and stripe {publishableKey, environment}; Square and Stripe are
  enabled only where the rule gives them a currency. GET
  /v1/billing/settings carries cards and stripe as well.

stripetest serves Stripe's contract over HTTP (the OpenAPI spec's
parameters, Stripe's fixtures, its documented test cards and idempotency
rules); the provider and TakePayment tests run the real code against it.
The tests that pinned "Stripe never wins" now pin the rule.


Co-authored-by: Hanzo Dev <[email protected]>

* payment: refuse sanctioned buyers, keep Stripe off top-ups, fix hosted-checkout country gate

From the red review of the Stripe fallback:

- Stripe cannot fund a prepaid balance yet: its refunds and disputes reach
  this service only through a webhook receiver that verifies Stripe's
  signature and maps charge.refunded / charge.dispute.* onto a clawback,
  and neither exists, so credit taken through Stripe could be charged back
  and kept. TakePayment refuses a Stripe-processed top-up before Stripe is
  called.
- processor.Sanctioned (CU, IR, KP, SY, RU, BY) is refused by every
  processor in canTake, so Cards and Fiat offer no card form there.
- Hosted checkout no longer gates Square on the buyer's country (Square's
  countries are where a seller can be); only sanctioned buyers are refused.
- Stripe key slots are checked by prefix: a secret key misfiled as the
  publishable key is never published.

Co-authored-by: Hanzo Dev <[email protected]>

* payment: Stripe is the only processor for new charges, end to end

COMMERCE_CHARGE_PROCESSORS (default "stripe", "*" for all) is the one policy for
which processors take a NEW charge; the deny set is every type it does not name.
Another processor comes back by naming it, not by restoring code. Payment
config, the checkout's providers and the card vault all follow it.

Existing customers do not lapse: a card on file is charged by the processor that
vaulted it (Registry.Existing, which ignores the policy), so a subscription
bought with a Square card renews on Square until its owner saves a card with
Stripe. Cards saved now are vaulted with the processor the policy selects.

Stripe, natively:
- Vault is a SetupIntent (verified, off-session consent); the card on file is the
  PaymentMethod it saved, charged off-session for renewals and reloads. One
  customer per subject, found by reference.
- A card that needs 3-D Secure is an ActionRequired answer, not a decline: the
  refusal carries {code, id, clientSecret} for Stripe.js, and a PaymentIntent the
  buyer then authenticated is completed by naming it ("pi_…"): for its own
  amount and account only, and credited once whatever key the request carries.
  Plan purchases and reloads still decline such a card (see the pay change).
- A 4xx from Stripe is an Answer (it said no, nothing moved).
- The gateway key names the attempt's source (top-up) or card (sale), so a
  decline Stripe replays under a key is not replayed at the next card.
- Webhook receiver: Stripe's signature is checked with STRIPE_WEBHOOK_SECRET,
  each event is applied once (the delivery guard), and payment_intent.succeeded,
  refund.created/updated and charge.dispute.* are mapped onto settlement,
  refund clawback and dispute withhold/restore. Test-mode events book as test
  money. Other events are acknowledged and move nothing.
- Hosted checkout applies a coupon on Stripe as a one-time coupon of the quoted
  discount.
- Sanctioned buyers are refused by every processor; hosted checkout no longer
  gates Square on the buyer's country.

Tests run against Stripe's real test mode with Stripe's test cards (top-up,
decline then another card, 3-D Secure, finished intent, refund, dispute and win,
plan purchase and renewal, auto-reload, declining reload) and a Square renewal
under the Stripe-only policy.

Co-authored-by: Hanzo Dev <[email protected]>

* payment: close the red review's blocking findings on Stripe-only

- A finished 3-D Secure intent's guard is COMPLETED after the credit, so it is not
  re-claimed as a crashed attempt after five minutes and credited again.
- A Stripe call that got no answer (dropped connection, timeout) may have
  charged: the attempt's guard, card and coupon use stay held, and the buyer is
  told the payment is unconfirmed, not declined. Only Stripe's own refusal
  releases a guard. Retrying with a re-tokenized card is refused instead of
  charging twice.
- Top-ups through Stripe are in US dollars, the only currency the host credits.
- The treasury sweep of deposits already received uses the registered MPC
  processor, outside the new-charge policy.
- A Stripe-Signature carrying several v1 values (a secret being rolled) is
  admitted when any matches.
- Tests: the intent guard, a lost answer under a live Stripe, and the stale
  checkout tests (which assumed Square under the Stripe-only default).

Co-authored-by: Hanzo Dev <[email protected]>

* payment: finish 3-D Secure for plans, saves and top-ups, and settle abandoned intents

- Pending intents (models/pendingintent): a PaymentIntent that sends a buyer to
  their bank is recorded with its buyer, amount and purpose BEFORE the answer that
  sends them. The intent's webhook credits a wallet's (top-up, reload) whether or
  not the browser comes back, and the browser's own request credits nothing more.
  The reconciler (run with the renewal sweep) settles what no webhook or sale did:
  money taken for a wallet is credited, money taken for a plan whose sale never
  finished is refunded, an intent that never succeeded is closed. No money taken
  waits on an alarm.
- A card being saved is answered with its SetupIntent ("seti_…") and the retry that
  names the finished one saves the card, for that customer only. A plan's first
  period is charged on-session so the bank can ask, answered with its
  PaymentIntent, and the retry that names the finished intent finishes the sale on
  the card already saved, for its own amount and account, once.
- A card's country is read from the card (PaymentMethod card.country) and a
  sanctioned one is refused by the processor itself on every path: top-up, sale,
  saved-card charge and reload.
- A saved card's vault facts (customer, token, fingerprint, country) cannot be
  written by a caller: PATCH and the create-merge leave them alone. An org's own
  Stripe keys are checked by prefix and mode like the deployment's, and hosted
  checkout uses only those.
- hanzo.yml gains the stripe-test-mode gate.

Tests, against Stripe's real test mode: the step recorded for its buyer, a closed
tab credited by the webhook and not again by the browser, the reconciler crediting
and refunding, a card save finished from a SetupIntent, a plan finished from the
buyer's intent (and refused for another buyer's, and for a second plan), the card
country read from Stripe. Stripe's test cards are issued in no sanctioned country,
so the refusal of one is proved by the shared rule, not by a card.

Co-authored-by: Hanzo Dev <[email protected]>

* payment: one claim per intent, and a refunded intent is not money in hand

From the third red review:

- completeIntent refuses a PaymentIntent whose charge was refunded in whole or
  part, or not received in full, and fails closed when the card cannot be read.
  An intent the reconciler refunded no longer reads as redeemable.
- ONE claim (`billing-intent`, system namespace) per intent across the webhook,
  the reconciler, the browser's top-up and a sale: whoever holds it credits, the
  others verify read-only and answer the credit that is there. The reconciler's
  refund takes the claim and completes it, so a refunded intent can never be
  redeemed. A claim is given back when its holder fails to credit.
- A sale is finished only by an intent registered for THIS sale (a plan's, this
  buyer's, this amount); a plan's registered intent cannot be a top-up, and a
  top-up's cannot buy a plan. A saved card's plan purchase may finish from an
  intent too.
- A buyer may have five unfinished bank steps at once; the reconciler does at
  most fifty Stripe calls a sweep and reads orgs with a plain Get.

Tests, against Stripe's real test mode: a refunded intent redeemed as a top-up and
as a sale, one intent one use, the browser then the webhook credits once, and the
cap.

Co-authored-by: Hanzo Dev <[email protected]>

* payment: close pending rows on every path, answer a replay with its receipt, credit only sound charges

From the fourth red review:

- A top-up finished in the browser, a webhook for an intent already accounted for,
  and the reconciler's sweep all close the intent's pending row, so the buyer's
  cap and the reconciler are not held by money already credited. Open lists the
  oldest first.
- A replayed intent answers the credit's own receipt id (the row stamped with the
  charge), or 409 while its holder is mid-credit: never a 200 with no receipt,
  which the host reads as a permanent failure.
- The webhook that finds the intent's claim held by a path still crediting answers
  a retry, so a holder that gives the claim back is not left with nothing to
  credit it.
- The webhook and the reconciler credit only a SOUND charge — captured in full,
  not refunded, not disputed — and completeIntent asks the same (Provider.
  ChargeSound).
- A saved card's plan purchase may name the card beside the finished intent.

Tests against Stripe's real test mode: a finished top-up closes its row and its
replay answers the receipt, a charge refunded before any credit is credited by
neither the webhook nor the reconciler, and a saved card's plan from its intent.

Co-authored-by: Hanzo Dev <[email protected]>

* payment: a webhook never closes a plan's row; the reconciler pages, backs off and alarms; renewals move to Stripe

From the independent red review of f68f03d98:

- CRITICAL: the webhook closed a 3-D Secure SALE's pending row, so an abandoned plan
  purchase was charged with no plan, no refund and no alarm. settleWallet closes
  only a wallet's row; a plan's or an invoice's is closed only by the sale (or the
  payment) finishing, or by the reconciler's refund. TestRed_SaleWebhookClosesRow
  SoReconcilerNeverRefunds.
- The reconciler reads ALL due rows, round-robin across orgs (twenty an org, four
  hundred a sweep), backs a row that errors off (5 minutes doubling to 6 hours),
  closes one that fails twelve sweeps with an alarm naming the money it may hold,
  and cancels at Stripe an intent abandoned for 48 hours.
- A Stripe card saved, or made the default, moves the subscriptions that renew on a
  card of another processor onto it; a card removed hands its renewals to the
  subject's default (Stripe first) card. "Renew on Square until a Stripe card is
  saved" is now both halves.
- A past-due invoice is paid on-session: the buyer's press of "pay" charges with
  the buyer present, so a bank that wants them is answered as the step, the intent
  is recorded for the invoice, and the next press finishes it. The off-session
  renewal still goes past due rather than lapsing.
- charge.refunded is read: the refunds on the charge are listed from Stripe and each
  taken back once by its own id, beside refund.created/updated. StripeWebhookEvents
  pins the endpoint's event list, which universe registers.
- Stripe-only is the default only where Stripe is keyed: with no policy and no
  Stripe key every configured processor keeps taking payments, with an alarm — a
  crash-looping host or a site that takes no payment is worse than the processors it
  did configure.
- Top-ups accept only intents commerce registered for a wallet and for that buyer;
  the webhook's receipt is deduped in the payer's org; the soundness check is never
  skipped and uses the recorded org's keys, and an unsound charge raises an alarm;
  customerIDOf prefers squareCustomerId for Square rows.

Tests, against Stripe's real test mode: the sale webhook leaves the row so the
reconciler refunds, charge.refunded alone claws back once, a flood in one org does
not hold another's good row and backs off and closes, plus the renewal re-pointing
and the policy fallback.

Co-authored-by: Hanzo Dev <[email protected]>

* payment: an invoice's recorded intent is settled from, never charged beside

From the re-review of 33b90066e:

- The off-session collector (the cron's first collection and dunning's retries)
  checks the invoice's recorded intent first. If the buyer finished their bank's
  step it settles the invoice from that payment and charges nothing more; if the
  buyer has not, it leaves the invoice waiting (no second charge); the buyer's own
  press of "pay" is answered the same step again, not a new charge.
- An invoice intent that no longer matches what is owed (a part-payment landed
  since) is finished for what is owed: the excess is refunded after the charge is
  verified, and an intent that took less than is owed is refunded in full and the
  buyer asked again.
- A row that is only waiting on its buyer is not looked at again before its 48
  hours are up; a row whose Stripe amount does not match what was registered backs
  off and closes after the same strikes as any other failure, instead of alarming
  every sweep.
- A card's detach and the renewal re-pointing use the card's owner (the caller's
  subject, or for staff the subject the card is filed under) and refuse an empty
  one, which would have listed every subject's subscriptions.

Tests against Stripe's real test mode: the buyer authenticates and the dunning
retry runs with exactly one charge; the retry leaves a waiting invoice alone and
"pay" answers the step again; the buyer authenticates, a part-payment lands, they
press pay, and it finishes with the excess returned.

Co-authored-by: Hanzo Dev <[email protected]>

* payment: the excess refund of an invoice intent is not a refund of the invoice

The refund commerce makes to return what an invoice intent took beyond what was
owed is tagged (metadata hanzo_excess). The invoice is paid in full, so the
webhook's refund event neither records it against the invoice nor claws back nor
stops the buyer's auto-reload; charge.refunded skips it too. A live test covers it:
invoice paid, 500 excess refunded, Refunded() 0 and the reload still on (it fails
without the tag).

The policy's comments no longer say it "defaults to stripe": production and the
test networks say so explicitly; unset is Stripe alone only where Stripe is keyed.

Co-authored-by: Hanzo Dev <[email protected]>

* ci: the stripe-test-mode gate reads its keys from KMS /deploy

STRIPE_TEST_SECRET_KEY and STRIPE_TEST_PUBLISHABLE_KEY (test mode only) come from KMS
org hanzo, path /deploy, env prod, with the bearer the job's KMS login minted, by the
same routes hanzoai/ci's get uses; both are masked, either missing fails the gate
loudly, and a key that is not test-mode is refused.

Co-authored-by: Hanzo Dev <[email protected]>

* ci: go-unit leaves the Stripe test-mode tests to their own gate

They need Stripe's test keys and fail without them by design.

Co-authored-by: Hanzo Dev <[email protected]>

* ci: the stripe-test-mode script parses

An apostrophe inside the ${VAR:?message} word opened a quote.

Co-authored-by: Hanzo Dev <[email protected]>

* ci: stripe-test-mode asks the endpoint ci asks, and logs what KMS answered

Co-authored-by: Hanzo Dev <[email protected]>

* ci: stripe-test-mode names the identity KMS refuses

Co-authored-by: Hanzo Dev <[email protected]>

* ci: stripe-test-mode does not re-vendor plans; builds compile the vendored bytes

Co-authored-by: Hanzo Dev <[email protected]>

---------

Co-authored-by: Hanzo Dev <[email protected]>
2026-11-12 17:47:27 -08:00

460 lines
19 KiB
Go

// Package checkout — OrgResolver is the canonical org resolver: the IAM org
// IS the org. There is no separate commerce-org registry to seed or drift.
//
// Resolution is host → brand → IAM org slug → Organization → public Org:
// - brandForHost maps a request host to its brand + IAM app (pay.hanzo.ai →
// hanzo, pay.lux.network → lux, …). Unknown hosts fall back to the
// deployment's default org (COMMERCE_DEFAULT_ORG, default "hanzo").
// - the org's public Square config (application id + location + environment)
// is resolved by the SAME authority as the charge path
// (payment.SquarePublicConfig) and projected into the org JSON, so the
// pay SPA's card iframe initializes with the exact application commerce
// will charge — no build-time VITE_* env, no per-host seed row.
//
// Resolution never 404s for a well-formed host: a missing org row degrades to
// the brand defaults + env Square config, so "add credits" always renders.
package checkout
import (
"cmp"
"os"
"strings"
"sync"
"github.com/hanzoai/commerce/models/organization"
"github.com/hanzoai/commerce/payment"
"github.com/hanzoai/commerce/payment/processor"
)
// OrgLoader loads an Organization by its IAM slug (read-only). It is injected
// by the binary so this package stays decoupled from datastore wiring; a nil
// loader (or a miss) degrades to a brand-default synthetic org whose Square
// config resolves from the deployment's per-brand env (the cloud-org path).
//
// WARNING: Resolve runs on /v1/commerce/org — a PUBLIC, unauthenticated
// endpoint the pay SPA hits on every boot. Any real loader wired here MUST be
// cached AND deadline-bounded. A naive per-request DB query under an unbounded
// context blocks and can exhaust the connection pool (regression at 1.42.44).
// nil is the correct default: pure host→brand→env, no I/O, no hang.
type OrgLoader func(slug string) (*organization.Organization, bool)
// OrgResolver implements Resolver by mapping the Host header to an IAM org and
// projecting that org into a public Org.
type OrgResolver struct {
load OrgLoader
}
// NewOrgResolver returns a Resolver backed by the IAM org model. load may be
// nil (every host resolves to a brand-default synthetic org + env Square).
func NewOrgResolver(load OrgLoader) *OrgResolver {
return &OrgResolver{load: load}
}
// Resolve maps host → brand → org and projects a public Org. It returns
// ErrUnknownOrg only for a malformed Host (empty / control bytes); every
// well-formed host resolves (known brand or the deployment default).
func (r *OrgResolver) Resolve(host string) (Org, error) {
h := normalizeHost(host)
if h == "" {
return Org{}, ErrUnknownOrg
}
b := brandForHost(h)
var org *organization.Organization
if r.load != nil {
if o, ok := r.load(b.slug); ok && o != nil {
org = o
}
}
if org == nil {
// No org row yet — the brand's env-backed Square config still resolves.
org = &organization.Organization{}
org.Name = b.slug
}
// The deployment's Square and PayPal credentials belong to its default brand's
// accounts. Any other brand takes cards/PayPal only with an account of its own;
// resolved onto the default's, its buyers would pay that merchant under this
// brand's name.
card := (b.slug == defaultBrand().slug || payment.SquareOwned(org)) && !processor.DisabledByPolicy(processor.Square)
var sq payment.SquarePublic
if card {
sq = payment.SquarePublicConfig(org)
}
paypalAllowed := (b.slug == defaultBrand().slug || payment.PayPalOwned(org)) && !processor.DisabledByPolicy(processor.PayPal)
var pp payment.PayPalPublic
if paypalAllowed {
pp = payment.PayPalPublicConfig(org)
}
hasPayPal := paypalAllowed && pp.ClientID != ""
// Stripe is shown on the same terms as Square: the deployment's own brand, or
// a brand with an account of its own — and only with a publishable key, the
// one thing its card form cannot mount without.
var st payment.StripePublic
if b.slug == defaultBrand().slug || payment.StripeOwned(org) {
st = payment.StripePublicConfig(org)
}
// The processors the selection rule may choose between for this brand: the
// org's, less any this brand may not show. Cards (applyCountryPolicy) is the
// rule's answer over exactly these, so the form the page mounts is the
// processor the charge will use.
reg := payment.ProcessorsForOrg(org)
if !card {
reg.Unregister(processor.Square)
}
if st.PublishableKey == "" {
reg.Unregister(processor.Stripe)
}
return Org{
Name: b.slug,
Brand: Brand{
DisplayName: b.displayName,
LogoURL: b.logoURL,
PrimaryColor: b.primaryColor,
LegalName: cmp.Or(b.legalName, b.displayName),
TermsURL: b.termsURL,
PrivacyURL: b.privacyURL,
},
IAM: IAMConfig{
Issuer: b.iamIssuer,
ClientID: b.iamClientID,
},
Providers: enabledProviders(card, hasPayPal, st.PublishableKey != ""),
ReturnURLAllowlist: returnHostsFor(b.slug),
Square: SquarePublic{
ApplicationID: sq.ApplicationID,
LocationID: sq.LocationID,
Environment: sq.Environment,
},
PayPal: PayPalPublic{
ClientID: pp.ClientID,
Environment: pp.Environment,
},
Stripe: StripePublic{
PublishableKey: st.PublishableKey,
Environment: st.Environment,
},
reg: reg,
}, nil
}
// returnHostsFor is the per-brand allowlist of first-party app hosts the pay
// SPA may bounce ?return= back to after checkout/onboarding. The pay matcher
// (isAllowedReturnUrl) requires an EXACT https hostname match, so these are
// full origins, not wildcards — every entry is a brand-controlled app host.
// Bounding ?return= to them keeps open-redirect phishing off the table while
// letting a user return to the app that sent them here (e.g. the playground
// flow: playground.hanzo.bot → pay.hanzo.ai/onboard → back to playground).
//
// This is intentionally a static first-party list, not org-model data: the
// resolver runs nil-loader on the PUBLIC /v1/commerce/org path (no
// per-request DB read — see the OrgLoader warning above), and these hosts are
// deploy-stable. Add a host here when a new first-party app must round-trip
// through pay.
func returnHostsFor(slug string) []string {
switch slug {
case "hanzo":
return []string{
"https://playground.hanzo.bot",
"https://hanzo.bot",
"https://console.hanzo.ai",
"https://cloud.hanzo.ai",
// hanzo.app — the builder. Its /billing and /pricing pages send the
// customer to pay.hanzo.ai for a card top-up or a plan and expect to
// get them back on /billing afterwards. Without this entry that
// returnUrl fails the allowlist and the buyer is stranded on pay.
"https://hanzo.app",
"https://chat.hanzo.ai",
"https://hanzo.chat",
"https://analytics.hanzo.ai",
"https://platform.hanzo.ai",
"https://bot.hanzo.ai",
"https://billing.hanzo.ai",
"https://s3.hanzo.ai",
"https://hanzo.ai",
"https://www.hanzo.ai",
// hanzo.id — sign-up onboarding. Its plan step sends a new customer
// here and completes only when checkout returns them to /onboarding
// paid.
"https://hanzo.id",
// hanzo.agency — the agency marketing/onboarding site. Its
// onboarding checkout mints a real Square link via the authed
// storefront BFF and bounces the buyer to
// https://hanzo.agency/onboarding-success on success. A distinct
// registrable domain, so it belongs in the brand's first-party
// host list (returnHostsFor), not brandDomains.
"https://hanzo.agency",
"https://www.hanzo.agency",
// hanzo.team — the Team workspace. Its /start sells the per-seat
// Team plan here and asks to come back to the workspace once paid.
"https://hanzo.team",
}
case "lux":
return []string{
"https://lux.network",
"https://lux.id",
"https://lux.finance",
"https://console.lux.network",
// Lux Tel — its site and console send the customer to pay.lux.tel
// for a top-up or a plan and expect them back afterwards.
"https://lux.tel",
"https://www.lux.tel",
"https://console.lux.tel",
// lux.cloud — the Lux console (hanzoai/console brand lux, home
// lux.cloud). Its top-ups and plans send the customer to
// pay.lux.cloud with returnUrl = the console page they left.
"https://lux.cloud",
"https://console.lux.cloud",
"https://cloud.lux.cloud",
}
case "zoo":
return []string{
"https://zoo.ngo",
"https://zoo.network",
// zoolabs.id — Zoo's identity origin (brandZoo.iamIssuer), where
// sign-up sends a new customer here and expects them back.
"https://zoolabs.id",
// zoo.cloud — the Zoo console (hanzoai/console brand zoo, home
// zoo.cloud), which returns its buyers the same way.
"https://zoo.cloud",
"https://console.zoo.cloud",
}
case "pars":
return []string{
"https://pars.network",
"https://pars.id",
"https://pars.vote",
}
default:
return nil
}
}
// enabledProviders is the payment-method surface the pay SPA renders, honoring
// the deploy-wide disabled policy. Square is surfaced where the brand has a
// card account (`card`), Stripe where it has a Stripe account (`stripe`), and
// PayPal when configured (`paypal`); applyCountryPolicy then turns each card
// processor on only where the selection rule chooses it. Crypto (MPC) and bank
// wire are always available.
func enabledProviders(card, paypal, stripe bool) []Provider {
out := make([]Provider, 0, 5)
if card && !processor.DisabledByPolicy(processor.Square) {
out = append(out, Provider{Name: "square", Enabled: true})
}
if stripe && !processor.DisabledByPolicy(processor.Stripe) {
out = append(out, Provider{Name: "stripe", Enabled: true})
}
if paypal && !processor.DisabledByPolicy(processor.PayPal) {
out = append(out, Provider{Name: "paypal", Enabled: true})
}
if !processor.DisabledByPolicy(processor.MPC) {
out = append(out, Provider{Name: "crypto", Enabled: true})
}
if !processor.DisabledByPolicy(processor.Wire) {
out = append(out, Provider{Name: "wire", Enabled: true})
}
return out
}
// ─── Brand map (ONE place) ───────────────────────────────────────────────────
// brand is the per-brand org defaults: the IAM org slug, display branding,
// and the IAM app the SPA signs in against. These mirror the commerce
// deployment's IAM_ISSUER / IAM_ACCEPTED_ISSUERS / IAM_ACCEPTED_AUDIENCES.
type brand struct {
slug string
displayName string
logoURL string
primaryColor string
iamIssuer string
iamClientID string
// legalName is the entity that takes the money — the name a receipt and a
// footer must carry, which is not the same string as the product's. "Hanzo"
// is a brand; "Hanzo Industries Inc." is who the customer is contracting
// with, and a checkout that never says so is a checkout that never says who
// it is. Empty falls back to displayName.
legalName string
// termsURL and privacyURL are the policies THIS brand publishes. Empty
// renders no link rather than a guess: a 404 in a footer is worse than an
// absence, and inventing a path on a brand's domain is how that happens.
termsURL string
privacyURL string
}
// brandDomains maps a registrable brand domain to its brand. Matching is
// exact-suffix (host == domain OR host endsWith "."+domain) so a spoof host
// like "pay.hanzo.ai.evil.com" can never match "hanzo.ai".
type domainBrand struct {
domain string
brand brand
}
var brandDomains = []domainBrand{
{"hanzo.ai", brandHanzo},
{"hanzo.id", brandHanzo},
{"hanzo.network", brandHanzo},
{"hanzo.chat", brandHanzo},
{"hanzo.computer", brandHanzo},
{"lux.network", brandLux},
{"lux.id", brandLux},
{"lux.finance", brandLux},
// The .cloud hosts are where these brands TAKE MONEY (pay.lux.cloud,
// pay.zoo.cloud). Absent here they fell to defaultBrand() — hanzo — so a Lux
// customer met Hanzo's brand, IAM app and Square merchant. The fallback is
// right for an unknown host; the bug was that these were unknown.
{"lux.cloud", brandLux},
// lux.tel is the same case one domain later: pay.lux.tel answered with Hanzo's
// name, Hanzo's logo and Hanzo's IAM app, because it was unknown here and the
// fallback is hanzo. Every host a brand TAKES MONEY on has to be listed, and
// the list is the only thing that knows.
{"lux.tel", brandLux},
{"zoo.ngo", brandZoo},
{"zoo.network", brandZoo},
{"zoolabs.id", brandZoo},
{"zoo.cloud", brandZoo},
{"pars.network", brandPars},
{"pars.id", brandPars},
{"pars.vote", brandPars},
}
// A brand carries a logoURL only when it HAS one. The checkout header already
// renders the displayName as a wordmark when this is empty, so a brand without
// a mark reads as itself rather than as a broken image — and, more to the point,
// never as somebody else. Filling these in by pattern would be the way a Hanzo
// logo ends up on a Lux page.
//
// Each was fetched before it was written here, and re-fetched 2026-08-11.
// Hanzo and Lux both answer with an actual image (200, image/svg+xml) and are
// different files — Hanzo's is the 67x67 square mark, Lux's the 63x17 wordmark —
// so the Lux entry is Lux's own asset and not Hanzo's served from a Lux host,
// which is the failure worth checking for rather than assuming. cdn.lux.network
// 404'd when this comment was first written; the asset was published since, so
// re-measure before trusting a "none exists" note.
//
// Zoo and Pars still have none: cdn.zoo.ngo and cdn.pars.network answer 522, and
// cdn.zoo.network / cdn.zoo.cloud / cdn.zoolabs.org do not resolve at all. They
// stay empty, which renders the displayName as a wordmark. Publishing those two
// assets is the remaining work, and it is a content task, not a config one.
//
// lux.network/logo-white.svg looks like a hit at 200 until you read the type —
// it is 112KB of text/html, the SPA's catch-all serving index.html, which the
// browser would take for an image and fail to draw.
var (
// #ffffff, like every other brand here. It was #808000 — CSS "olive" — and
// it painted the one control on the checkout that matters: pay renders the
// primary CTA from this value (accent() accepts it because olive does clear
// 3:1 on black), so "Continue to payment" shipped as a mustard slab and the
// selected plan wore a mustard edge. Hanzo's design system is monochrome by
// construction — "one hue rendered through an opacity ladder", with the only
// permitted hues being error/success state — so a brand hue here was never a
// value this system has. Lux and Zoo were already #ffffff; Hanzo was the odd
// one out, which is the shape of a placeholder that shipped.
brandHanzo = brand{slug: "hanzo", displayName: "Hanzo", logoURL: "https://cdn.hanzo.ai/img/logo-white.svg", primaryColor: "#ffffff", iamIssuer: "https://hanzo.id", iamClientID: "hanzo-app", legalName: "Hanzo Industries Inc.", termsURL: "https://hanzo.ai/terms", privacyURL: "https://hanzo.ai/privacy"}
brandLux = brand{slug: "lux", displayName: "Lux", logoURL: "https://cdn.lux.network/img/logo-white.svg", primaryColor: "#ffffff", iamIssuer: "https://lux.id", iamClientID: "lux-app"}
brandZoo = brand{slug: "zoo", displayName: "Zoo", primaryColor: "#ffffff", iamIssuer: "https://zoolabs.id", iamClientID: "zoo-app"}
brandPars = brand{slug: "pars", displayName: "Pars", primaryColor: "#ffffff", iamIssuer: "https://pars.id", iamClientID: "pars-app"}
)
// brandForHost resolves a normalized host to its brand. Unknown hosts fall back
// to the deployment default org (COMMERCE_DEFAULT_ORG, default "hanzo") so a
// same-cluster host that isn't a public brand domain still resolves to the org
// this commerce serves.
func brandForHost(host string) brand {
for _, bd := range configuredDomains() {
if host == bd.domain || strings.HasSuffix(host, "."+bd.domain) {
return bd.brand
}
}
return defaultBrand()
}
// COMMERCE_BRAND_DOMAINS adds paying hosts WITHOUT a release.
//
// The table above is the only thing that knows which hosts a brand takes money on,
// and it is compiled in — so every new one cost a module tag, a dependency bump in
// the host binary, an image build and a pin, to add one line. Meanwhile the host
// answered with the fallback brand, which is somebody else's name and mark on a
// checkout. That price is why lux.cloud and then lux.tel each shipped wrong first.
//
// The form is `domain=brand`, comma or space separated:
//
// COMMERCE_BRAND_DOMAINS="lux.tel=lux, pay.example.coop=zoo"
//
// Entries are prepended, so configuration BEATS the compiled default and a
// mistake in the table is correctable without a release too. An unknown brand is
// skipped rather than guessed — naming a brand that does not exist should not
// silently mint one.
//
// Read once. This runs on a PUBLIC unauthenticated path (see OrgLoader's warning),
// so it must never do I/O or take a lock per request; parsing an env var at first
// use does neither, and the value cannot change without a restart anyway.
var configuredDomains = sync.OnceValue(func() []domainBrand {
return append(parseBrandDomains(os.Getenv("COMMERCE_BRAND_DOMAINS")), brandDomains...)
})
// parseBrandDomains reads the `domain=brand` list. Split out so it is testable:
// configuredDomains reads the env exactly once by design, so a test cannot set it.
func parseBrandDomains(raw string) []domainBrand {
raw = strings.TrimSpace(raw)
if raw == "" {
return nil
}
known := map[string]brand{
brandHanzo.slug: brandHanzo,
brandLux.slug: brandLux,
brandZoo.slug: brandZoo,
brandPars.slug: brandPars,
}
extra := make([]domainBrand, 0, 4)
for _, pair := range strings.FieldsFunc(raw, func(r rune) bool { return r == ',' || r == ' ' || r == '\n' }) {
d, b, ok := strings.Cut(pair, "=")
if !ok {
continue
}
d = strings.ToLower(strings.TrimSpace(strings.TrimPrefix(d, ".")))
br, isKnown := known[strings.ToLower(strings.TrimSpace(b))]
if d == "" || !isKnown {
continue
}
extra = append(extra, domainBrand{d, br})
}
return extra
}
// BrandSlugForHost resolves a customer-facing host to the serving brand's org
// slug — the RECEIVING side of a deposit (whose bank account, whose KMS wire
// path, whose custody vault) and the SELLING side of the plan catalog.
// Exported for the /v1/billing surface, which shares this one host→brand table
// with the org endpoint rather than growing a second.
//
// It takes the host as a request carries it: port and case are dropped exactly
// as Resolve drops them, so "pay.lux.cloud:443" is Lux here as it is on the org
// endpoint, rather than an unknown host that falls to the default brand.
func BrandSlugForHost(host string) string {
return brandForHost(normalizeHost(host)).slug
}
// DefaultBrandSlug is the deployment's own brand: the org its own processor
// accounts belong to.
func DefaultBrandSlug() string { return defaultBrand().slug }
// defaultBrand is the deployment's fallback org. It is brandHanzo unless
// COMMERCE_DEFAULT_ORG names another known brand (so a lux/zoo/pars-only
// commerce deploy can flip its default without code changes).
func defaultBrand() brand {
switch strings.ToLower(strings.TrimSpace(os.Getenv("COMMERCE_DEFAULT_ORG"))) {
case "lux":
return brandLux
case "zoo":
return brandZoo
case "pars":
return brandPars
default:
return brandHanzo
}
}