Repository navigation
feat(billing): let providers change their payout bank account themselves - #594
Conversation
Providers with a fully onboarded Stripe Express account had no way to change the bank account their earnings land in. The onboarding link we already expose only collects outstanding requirements, and a `ready` account has none, so it bounces straight back to the return URL; Stripe forbids `account_update` links for any account with a Stripe-hosted dashboard, which every Express account has. The only remaining option was unlinking and re-onboarding a brand new connected account, throwing away completed KYC — so the request arrived as a support ticket instead. Add the Express Dashboard login link, which is exactly the supported path for this. `POST /v1/billing/stripe/dashboard` mints a single-use URL and the ready-state payout card gains a "Change in Stripe" action next to the destination chip. Gated on requirePrivyAuth rather than requireAuth: the URL is a bearer credential for a session that can redirect a user's earnings to another bank account, so an inference API key must not be able to mint one. Co-authored-by: Cursor <cursoragent@cursor.com>
Two independent reviews of the previous commit found one must-fix and a set of real edge cases. The must-fix: nothing tested that the new route rejects API keys. Since requireAuth also populates the user context for account-bound keys and provider device tokens, the in-handler requirePrivyUser is not a second line of defense — the route-level middleware is the only gate, and swapping that one line would have left the whole suite green while letting a leaked inference key mint a session that redirects a provider's earnings. Now driven through the real mux, mirroring TestStripeUnlinkRouteRejectsAPIKey. Also: - Reuse the existing error vocabulary (not_onboarded, stripe_account_gone) instead of coining parallel spellings the frontend classifier wouldn't have matched. - Reject accounts that haven't submitted details. Stripe has no Express Dashboard for them, and the raw error told the user to retry something that can never work. Restricted and rejected accounts do have a dashboard, so they still get through. - Return 500 rather than claiming an unlink when persisting it failed. - Don't burn the single-use link when the pre-opened tab was closed, or when the response arrives without a url; navigate with replace() so the credential never enters session history. - Extract PayoutDestinationRow, taking the card's cognitive complexity to 24 — below its pre-existing baseline of 30. Co-authored-by: Cursor <cursoragent@cursor.com>
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
|
This PR adds a Stripe Express Dashboard login-link endpoint and gates it correctly behind Trust boundaries touched
Per-threat assessmentT-004 (Elevation of Privilege — consumer key used for admin-scoped operations) T-021 (Unauthenticated MDM webhook injection) T-024 (Admin API key compromise — release/trust manipulation) T-040 (Host header injection influences generated URLs) T-032 (Coordinator encryption mnemonic / secrets exfiltration) New attack surface not covered by an existing threatLogin link URL as a bearer credential (no existing threat entry)
Recommended action: Confirm in SEC-* findings resolved by this PRNone explicitly resolved. The 🔐 Threat model: |
There was a problem hiding this comment.
Pull request overview
Adds a self-serve way for providers with Stripe Connect Express accounts to open the Stripe Express Dashboard (via single-use login_links) so they can change their payout bank account/debit card without support intervention, while keeping the operation gated to Privy-authenticated user sessions.
Changes:
- Coordinator: adds
StripeConnect.CreateLoginLinkand a new Privy-only endpointPOST /v1/billing/stripe/dashboardthat returns a single-use Express Dashboard URL (with account-gone self-heal and clear status gating). - Console UI: adds a “Change in Stripe” action in the payouts card and a new proxy route
/api/payments/stripe/dashboard+ API client method to mint and immediately navigate to the login link safely (replace(),opener=null, popup-blocker fallback). - Tests: adds targeted Go + UI tests for login-link creation, auth enforcement (including API key rejection at the mux), status gating, and client navigation/error classification.
Reviewed changes
Copilot reviewed 18 out of 18 changed files in this pull request and generated no comments.
Show a summary per file
| File | Description |
|---|---|
| coordinator/billing/stripe_connect.go | Add CreateLoginLink wrapper for Stripe login_links.create with validation and parsing. |
| coordinator/billing/stripe_connect_test.go | Unit tests for login link path/method, malformed IDs, empty URL, Stripe error propagation, and mock mode. |
| coordinator/api/stripe_payouts.go | Add handleStripeDashboardLink endpoint and stripeDashboardAvailable gate; account-gone unlink behavior. |
| coordinator/api/stripe_payouts_test.go | Handler + mux tests for auth, status gating, API-key rejection, happy path, account-gone unlink, transient error behavior. |
| coordinator/api/server.go | Wire POST /v1/billing/stripe/dashboard behind requirePrivyAuth. |
| console-ui/src/lib/api/types.ts | Add StripeDashboardLinkResponse type. |
| console-ui/src/lib/api/index.ts | Export createStripeDashboardLink. |
| console-ui/src/lib/api/billing.ts | Add createStripeDashboardLink() client method via /api/payments/stripe/dashboard. |
| console-ui/src/components/payouts/useStripePayouts.ts | Add openDashboard() flow + loading state with safe navigation semantics. |
| console-ui/src/components/payouts/StripePayoutsCard.tsx | Render destination row using extracted component and wire “Change in Stripe” action in ready state. |
| console-ui/src/components/payouts/PayoutDestinationRow.tsx | New component for destination display + dashboard action button. |
| console-ui/src/components/payouts/payout-copy.ts | Add classifyDashboardError and unify closed-account messaging constant. |
| console-ui/src/components/payouts/payout-copy.test.ts | Tests for dashboard error classification behavior. |
| console-ui/src/components/payouts/index.ts | Export PayoutDestinationRow. |
| console-ui/src/app/providers/earnings/EarningsContent.tsx | Wire dashboard open action into payouts card on earnings page. |
| console-ui/src/app/billing/BillingContent.tsx | Wire dashboard open action into payouts card on billing page. |
| console-ui/src/app/api/payments/stripe/dashboard/route.ts | New Next.js proxy route to coordinator POST /v1/billing/stripe/dashboard (Privy-only upstream). |
| console-ui/tests/payouts.test.tsx | UI tests for openDashboard() navigation paths + card rendering of “Change in Stripe”. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: b56da6ad9c
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| if (tab && !tab.closed) { | ||
| tab.location.replace(url); | ||
| } else { | ||
| window.location.replace(url); |
There was a problem hiding this comment.
Refresh the payout destination after returning from Stripe
When the dashboard opens in a new tab and the user changes their bank account or debit card, this success path never refreshes Stripe status in the original tab. Consequently, status.destination_last4 and status.instant_eligible remain at their pre-change values, so the page continues showing the old destination and can select the wrong default withdrawal method until a manual reload. Register a focus/visibility return handler that calls reload(true) after navigating the dashboard tab.
Useful? React with 👍 / 👎.
| if user.StripeAccountID == "" || !stripeDashboardAvailable(user.StripeAccountStatus) { | ||
| writeJSON(w, http.StatusConflict, errorResponse("not_onboarded", | ||
| "finish your payout setup first, then you can manage the account in Stripe")) | ||
| return |
There was a problem hiding this comment.
Distinguish pending verification from unfinished onboarding
For an account with DetailsSubmitted=true, PayoutsEnabled=false, and no CurrentlyDue requirements—such as one awaiting Stripe verification—stripeStatusForAccount returns pending, so this gate rejects the dashboard link as not_onboarded. That contradicts the stated prerequisite of having submitted details and blocks a completed account from accessing its Express Dashboard. Persist the submitted-details state or fetch the account before deciding whether a login link is available.
Useful? React with 👍 / 👎.
| // operations — a leaked inference API key must not be able to detach the | ||
| // user's payout account, nor mint a dashboard session that can point their | ||
| // earnings at a different bank account. | ||
| s.mux.HandleFunc("POST /v1/billing/stripe/dashboard", s.requirePrivyAuth(s.handleStripeDashboardLink)) |
There was a problem hiding this comment.
Rate-limit dashboard login-link creation
This new account-management endpoint performs a Stripe POST and mints a live dashboard credential on every request, but unlike nearby sensitive mutations and Stripe session creation it is not wrapped in rateLimitFinancial. Any caller with a valid Privy session can therefore loop this route and consume the platform's Stripe request capacity, degrading dashboard-link creation and potentially other billing operations. Apply the financial limiter outside the authentication middleware.
Useful? React with 👍 / 👎.
| return | ||
| } | ||
|
|
||
| link, err := s.billing.StripeConnect().CreateLoginLink(user.StripeAccountID) |
There was a problem hiding this comment.
Reconcile payouts initiated from the newly exposed dashboard
When a provider uses the Express Dashboard reached through this login link to initiate a payout of their connected balance, Stripe reports a non-automatic payout. reconcileUnmatchedPayout explicitly ignores every unmatched payout with Automatic=false, and the existing test pins the associated withdrawal row in transferred; now that providers can initiate these dashboard payouts themselves, a successfully delivered withdrawal can remain nonterminal forever and trigger false stuck-withdrawal incidents. Either disable user-initiated dashboard payouts or safely attribute these events to eligible withdrawal rows.
Useful? React with 👍 / 👎.
|
Found 1 test failure on Blacksmith runners: Failure
|
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: b0e3f73ae3
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| <PayoutDestinationRow | ||
| status={status} | ||
| onOpenDashboard={onOpenDashboard} | ||
| dashboardLoading={dashboardLoading} | ||
| /> |
There was a problem hiding this comment.
Show the dashboard action for restricted accounts
When status is restricted or rejected, this ready-only branch is skipped and the fallback UI exposes only onboarding and unlinking, so neither page provides any way to call openDashboard. This conflicts with stripeDashboardAvailable, which explicitly permits both states because the Express Dashboard is where these users can inspect and fix the account problem; render a dashboard action for those onboarded states as well.
Useful? React with 👍 / 👎.
…on on return Two of the four Codex review findings on #594 were real. This addresses both. Rate limit (P2 #3). POST /v1/billing/stripe/dashboard was the only Stripe-POST billing route without rateLimitFinancial — create-session has it — so a valid Privy session could loop the route and burn the platform's Stripe request capacity while minting live credentials. Chained INSIDE requirePrivyAuth, not outside as the review suggested: rateLimitWithTier keys on consumerKeyFromContext, which only the auth middleware populates, so an outer limiter would collapse every caller into one empty-string bucket. This matches all ten sibling financial routes and rateLimitFinancial's own doc comment. Stale destination (P2 #1). The dashboard opens in another tab, so the original kept rendering the pre-change destination_last4 and — worse — openWithdraw seeds withdrawMethod from the same stale instant_eligible. stripe_withdraw.go admits instant when EITHER the fresh account or the stored flag says eligible, so a card -> bank switch got an instant payout accepted, rejected by Stripe, and the fee charged then refunded before falling back to the daily sweep. A one-shot visibilitychange handler now pulls refresh=1 on return (not the cached read: account.updated may not have landed yet). It lives in an effect so it is torn down if the page unmounts before the user comes back. Not addressed, deliberately: P2 #2 (pending vs awaiting-verification) is correct — an account with details_submitted=true, payouts_enabled=false and no currently_due maps to "pending" and gets 409'd despite having a Stripe dashboard — but PayoutDestinationRow renders only in the ready branch, so no UI path reaches it. Adding a Stripe round-trip to unblock a dead path is not worth it. P2 #4 (dashboard-initiated payouts never reconcile) is real but pre-existing: live-mode Express holders already self-serve at connect.stripe.com/express_login with email + OTP, no platform link required, so reconcileUnmatchedPayout's !pe.Automatic early return already strands those rows today. Attributing non-automatic payouts to withdrawal rows is a separate change to the webhook state machine. Tests: both fixes negative-controlled (reverted each, confirmed its test fails, restored). gofmt/go vet clean; go test ./api/... ./billing/... pass; eslint 0 errors; vitest 499 passed.
|
@codex — went through all four findings. Two were real and are fixed in 06f880e; two I'm declining, with reasoning below. FixedP2 #3 — rate-limit dashboard login-link creation. Correct, and One correction to the suggestion: you said "apply the financial limiter outside the authentication middleware." That would break it. Pinned by P2 #1 — refresh the payout destination after returning from Stripe. Correct, and worse than the cosmetic staleness you described. if method == "instant" && !acct.InstantEligible && !user.StripeInstantEligible {So after a card → bank switch in the other tab, the stale stored flag lets an instant payout through, Stripe rejects it, and the instant fee is charged then refunded before falling back to the daily sweep. Implemented as a one-shot DecliningP2 #2 — distinguish pending verification from unfinished onboarding. The analysis is right: P2 #4 — reconcile payouts initiated from the dashboard. Real gap, but this PR doesn't create it. Live-mode Express account holders can already sign in at Unrelated: this PR cannot go green yet
That's a master breakage inherited via the merge commit —
For the threat-model reviewer's two open questions
Verification for this commit: |
Summary
Testing
|
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 19 out of 19 changed files in this pull request and generated no new comments.
Suppressed comments (2)
console-ui/src/app/api/payments/stripe/dashboard/route.ts:20
- This route returns a single-use Stripe dashboard URL (a bearer credential). Add
Cache-Control: no-storeto both success and error responses so the link isn’t cached by proxies or the browser.
if (!res.ok) {
const text = await res.text();
return NextResponse.json({ error: text }, { status: res.status });
}
return NextResponse.json(await res.json().catch(() => ({})));
coordinator/api/stripe_payouts.go:356
- The dashboard login link is a bearer credential; responses should be explicitly marked non-cacheable to avoid accidental caching by browsers/intermediaries. Consider setting
Cache-Control: no-storefor all responses from this handler before writing JSON.
func (s *Server) handleStripeDashboardLink(w http.ResponseWriter, r *http.Request) {
user := s.requirePrivyUser(w, r)
if user == nil {
return
}
![Fix with [code]smith](https://pr-comments-assets.blacksmith.sh/codesmith/fix-with-codesmith-light.png)
What prompted this
A provider asked support:
We had no way to do that. This adds one.
Why the existing endpoints couldn't do it
Our connected accounts are Stripe Express (
form.Set("type", "express"),coordinator/billing/stripe_connect.go). For an account that has finished onboarding, every path we already had is a dead end:POST /v1/billing/stripe/onboardaccount_linkslink of typeaccount_onboarding, which only collects outstanding requirements. Areadyaccount has none, so Stripe bounces the user straight toreturn_url.account_updatePOST /v1/accounts/{id}/external_accountscontroller.requirement_collection = application; Express isstripe.DELETE /v1/billing/stripe/accountthen re-onboardThe supported mechanism is the Express Dashboard login link,
POST /v1/accounts/{id}/login_links. That dashboard is where Stripe lets the account holder change their payout bank account or debit card. We never see or store bank details, which is why we don't rebuild this ourselves.Before / After — behavior
flowchart TB subgraph Before["BEFORE - no way to change the bank"] direction TB B1["Provider: 'change my bank account'"] --> B2{"Payouts card, status = ready"} B2 --> B3["Only action: Withdraw"] B2 -. "no affordance" .-> B4["Unlink is hidden<br/>renders only when NOT ready"] B3 --> B5["Support ticket"] B6["If they force onboarding anyway"] --> B7["account_onboarding link"] B7 --> B8["No requirements due<br/>redirect to return_url"] B8 --> B5 endflowchart TB subgraph After["AFTER - self-serve"] direction TB A1["Provider clicks 'Change in Stripe'"] --> A2["POST /v1/billing/stripe/dashboard"] A2 --> A3{"Privy session?"} A3 -- "API key / device token" --> A4["403"] A3 -- yes --> A5{"Account submitted details?<br/>ready / restricted / rejected"} A5 -- no --> A6["409 not_onboarded<br/>'Finish your payout setup first'"] A5 -- yes --> A7["Stripe: POST /v1/accounts/id/login_links"] A7 -- "account_invalid" --> A8["Unlink + 409 stripe_account_gone<br/>500 if the unlink did not persist"] A7 -- "5xx / transport" --> A9["502 stripe_error<br/>account left intact"] A7 -- ok --> A10["200 with url"] A10 --> A11["New tab to Express Dashboard"] A11 --> A12["Provider changes their bank account"] A12 --> A13["account.updated webhook<br/>refreshes destination_last4"] endBefore / After — code
flowchart LR subgraph BeforeCode["BEFORE"] direction TB C1["StripePayoutsCard<br/>ready branch"] --> C2["destination chip + Withdraw<br/>inline, complexity 30"] C3["useStripePayouts"] --> C4["onboard / withdraw / unlink"] C5["server.go routes"] --> C6["onboard, status, withdraw,<br/>withdrawals, account, webhook"] C7["StripeConnect"] --> C8["CreateExpressAccount<br/>CreateAccountLink<br/>GetAccount / Transfer / Payout"] endflowchart LR subgraph AfterCode["AFTER - new nodes marked NEW"] direction TB D1["StripePayoutsCard<br/>complexity 24"] --> D2["NEW PayoutDestinationRow<br/>chip + 'Change in Stripe'"] D1 --> D3["Withdraw"] D2 --> D4["NEW useStripePayouts.openDashboard"] D4 --> D5["NEW createStripeDashboardLink"] D5 --> D6["NEW /api/payments/stripe/dashboard<br/>Next proxy"] D6 --> D7["NEW POST /v1/billing/stripe/dashboard<br/>requirePrivyAuth"] D7 --> D8["NEW handleStripeDashboardLink"] D8 --> D9["NEW StripeConnect.CreateLoginLink"] D9 --> D10["Stripe /v1/accounts/id/login_links"] D4 -. on error .-> D11["NEW classifyDashboardError"] endSecurity
The returned URL is a credential for a session that can redirect where a provider's money is paid, so:
requirePrivyAuth, notrequireAuth. This matters more than it looks:requireAuthalso populates the user context for account-bound API keys and provider device-login tokens, so the in-handlerrequirePrivyUseris not a second line of defense — the route-level middleware is the only gate.TestStripeDashboardLinkRouteRejectsAPIKeydrives the real mux so flipping that one line can't pass CI.validAccountIDadditionally regex-gates it before interpolation into the Stripe path.opener = null) before it points at Stripe, and every navigation usesreplace()so the credential never enters session history.Edge cases handled
""/pending): 409not_onboarded. Stripe has no dashboard for these, and the raw error told the user to retry something that can never work.restrictedandrejectedaccounts do have a dashboard — that's where Stripe explains what's wrong — so they still get through.refresh=1self-heal inhandleStripeStatus. Returns 500 instead if the unlink didn't persist, rather than telling the user we unlinked something we didn't.url: rejected before navigating, so no tab goes to/undefined.Modularity
Extracted
PayoutDestinationRow, which takesStripePayoutsCard's cognitive complexity to 24 — below its pre-existing baseline of 30, despite adding a feature.Test plan
go build ./...,go vet ./api/... ./billing/...,gofmt -lcleango test ./api/... ./billing/...— passTestCreateLoginLink*): path, method, malformed-ID rejection, empty-url rejection, error propagation, mock modeTestStripeDashboardLink*): auth, no account, status gate across all five states, route-level API-key rejection, happy path, account-gone unlink, transient error leaves account intactnpx eslint src/ __tests__/— 0 errorsnpm test— 488 passed (was 481)classifyDashboardErrorcodes, andopenDashboardnavigation paths (tab reuse, popup blocked, closed tab, error cleanup, malformed body) plus card renderingnpm run build—/api/payments/stripe/dashboardregistered/billingand/providers/earningsagainst a real Express account, confirm the dashboard opens and a bank change round-trips viaaccount.updatedNote for the provider who asked
Their account is created with
business_type=individual. If the business bank account is held by a legal entity rather than by them personally, the receiving bank can reject the deposit on a name mismatch — worth checking with them before they switch.Need help on this PR? Tag
@codesmith-botwith what you need. Autofix is disabled.