Skip to content

feat(billing): let providers change their payout bank account themselves - #594

Merged
Gajesh2007 merged 4 commits into
masterfrom
feat/stripe-express-dashboard-link
Aug 3, 2026
Merged

Gajesh2007 merged 4 commits into
masterfrom
feat/stripe-express-dashboard-link

Conversation

@Gajesh2007

@Gajesh2007 Gajesh2007 commented Jul 27, 2026 •

Copy link
Copy Markdown
Member

What prompted this

A provider asked support:

can you please send me the Stripe Express payout-bank update link for my existing Darkbloom provider connected account? I need to replace the current bank account with my business bank account.

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:

Path Why it fails
POST /v1/billing/stripe/onboard Mints an account_links link of type account_onboarding, which only collects outstanding requirements. A ready account has none, so Stripe bounces the user straight to return_url.
Switching that link to account_update Stripe forbids it for any account with a Stripe-hosted dashboard — which every Express account has.
POST /v1/accounts/{id}/external_accounts Requires controller.requirement_collection = application; Express is stripe.
DELETE /v1/billing/stripe/account then re-onboard Creates a brand-new connected account and discards completed KYC.

The 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
  end
Loading
flowchart 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"]
  end
Loading

Before / 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"]
  end
Loading
flowchart 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"]
  end
Loading

Security

The returned URL is a credential for a session that can redirect where a provider's money is paid, so:

  • Wired behind requirePrivyAuth, not requireAuth. This matters more than it looks: requireAuth also populates the user context for account-bound API keys and provider device-login tokens, so the in-handler requirePrivyUser is not a second line of defense — the route-level middleware is the only gate. TestStripeDashboardLinkRouteRejectsAPIKey drives the real mux so flipping that one line can't pass CI.
  • The account ID comes solely from the verified Privy JWT. No body, query, or path parameter — one user cannot mint a link for another's account. validAccountID additionally regex-gates it before interpolation into the Stripe path.
  • The link is never logged, persisted, or cached. Only issuance is logged.
  • The frontend disowns the pre-opened tab (opener = null) before it points at Stripe, and every navigation uses replace() so the credential never enters session history.

Edge cases handled

  • Not onboarded ("" / pending): 409 not_onboarded. Stripe has no dashboard for these, and the raw error told the user to retry something that can never work. restricted and rejected accounts do have a dashboard — that's where Stripe explains what's wrong — so they still get through.
  • Account closed on Stripe: unlinked locally + 409, mirroring the refresh=1 self-heal in handleStripeStatus. Returns 500 instead if the unlink didn't persist, rather than telling the user we unlinked something we didn't.
  • Transient Stripe 5xx: 502, account explicitly left intact.
  • Popup blocked, or user closes the pre-opened tab mid-flight: falls back to the current tab instead of burning a single-use link.
  • Response without a url: rejected before navigating, so no tab goes to /undefined.

Modularity

Extracted PayoutDestinationRow, which takes StripePayoutsCard'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 -l clean
  • go test ./api/... ./billing/... — pass
  • 6 new client tests (TestCreateLoginLink*): path, method, malformed-ID rejection, empty-url rejection, error propagation, mock mode
  • 7 new handler tests (TestStripeDashboardLink*): auth, no account, status gate across all five states, route-level API-key rejection, happy path, account-gone unlink, transient error leaves account intact
  • npx eslint src/ __tests__/ — 0 errors
  • npm test — 488 passed (was 481)
  • 12 new frontend tests: classifyDashboardError codes, and openDashboard navigation paths (tab reuse, popup blocked, closed tab, error cleanup, malformed body) plus card rendering
  • npm run build — /api/payments/stripe/dashboard registered
  • Manual: click Change in Stripe on /billing and /providers/earnings against a real Express account, confirm the dashboard opens and a bank change round-trips via account.updated

Note 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.


View with [code]smith Autofix with [code]smith
Need help on this PR? Tag @codesmith-bot with what you need. Autofix is disabled.

Gajesh2007 and others added 2 commits July 27, 2026 15:08
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>
Copilot AI review requested due to automatic review settings July 27, 2026 22:22
@vercel

vercel Bot commented Jul 27, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
d-inference Ready Ready Preview Aug 3, 2026 4:41am
d-inference-console-ui-dev Ready Ready Preview Aug 3, 2026 4:41am
d-inference-landing Ready Ready Preview Aug 3, 2026 4:41am

Request Review

@github-actions

Copy link
Copy Markdown
Contributor

This PR adds a Stripe Express Dashboard login-link endpoint and gates it correctly behind requirePrivyAuth; the security posture is neutral-to-positive with one new surface item worth tracking.


Trust boundaries touched

  • TB-001 — Consumer → Coordinator API (new authenticated route)
  • TB-008 — Coordinator → Payments (new Stripe Connect API call)
  • TB-006 — Admin/account-management scope enforcement (auth middleware choice)

Per-threat assessment

T-004 (Elevation of Privilege — consumer key used for admin-scoped operations)
✅ Strengthens mitigation.
server.go line 1813: POST /v1/billing/stripe/dashboard is registered under requirePrivyAuth, not requireAuth. The inline comment explicitly states why: a leaked inference API key must not be able to mint a dashboard session that redirects earnings to an attacker-controlled bank account. This is the correct and more restrictive gate — consistent with the existing DELETE /v1/billing/stripe/account treatment.

T-021 (Unauthenticated MDM webhook injection)
ℹ️ Neutral — server.go changes are in the billing route block only; MDM webhook registration is untouched.

T-024 (Admin API key compromise — release/trust manipulation)
ℹ️ Neutral — no changes to admin key validation or release handlers.

T-040 (Host header injection influences generated URLs)
ℹ️ Neutral — no changes to URL generation paths.

T-032 (Coordinator encryption mnemonic / secrets exfiltration)
ℹ️ Neutral in direct terms, but note the new CreateLoginLink return value is a bearer credential for the account holder's Stripe dashboard session. The doc comment at stripe_connect.go:339 correctly flags this: "never email, message, or log it." The coordinator runs in a GCP AMD SEV-SNP VM and the mnemonic protections apply equally here, but the login link URL is a new short-lived secret that must not appear in coordinator logs. There is no evidence it is logged in the diff, and no direct threat entry covers it — see new surface note below.


New attack surface not covered by an existing threat

Login link URL as a bearer credential (no existing threat entry)

CreateLoginLink returns a single-use Stripe URL that grants full Express Dashboard access (change bank account, view balance, initiate payouts). Observations:

  1. URL is returned to the caller and must reach the browser over a secure redirect, not be stored. The diff does not show the handler (handleStripeDashboardLink in coordinator/api/stripe_payouts.go, not included in diff). It is not possible from this diff to confirm whether the returned URL is: (a) returned as a JSON field vs an immediate 302 redirect, (b) ever written to the database or a cache, or (c) included in coordinator access logs at the INFO level. A 302 redirect is strongly preferable to returning the URL as a JSON body, since it limits the window during which the link is available to an attacker who has read access to response bodies or logs.

  2. validAccountID path-injection check is present and tested (stripe_connect_test.go:209–221): acct_x/../../v1/payouts, cus_123, and acct_x?foo=1 are all rejected before the Stripe HTTP call. This closes the obvious URL-reshaping vector.

  3. Mock mode returns a predictable URL embedding the account ID (stripe_connect.go:344). This is test-only and gated on c.mockMode; confirm mock mode is not reachable in production (i.e., NewStripeConnect is called with mockMode=false when STRIPE_SECRET_KEY is set).

Recommended action: Confirm in handleStripeDashboardLink (not diffed) that (a) the link is issued as an immediate 302 Found or equivalent one-shot redirect rather than stored or returned as a persistent JSON field, and (b) the URL is not emitted at any log level. If it is returned as JSON, it should have a very short client-side lifetime and the handler should document the rationale.


SEC-* findings resolved by this PR

None explicitly resolved. The requirePrivyAuth gate on the dashboard route is a positive incremental hardening step aligned with TB-001 / T-004 but does not close any open finding by itself.


🔐 Threat model: docs/threat-model.yaml · Updates on each push to this PR

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.CreateLoginLink and a new Privy-only endpoint POST /v1/billing/stripe/dashboard that 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.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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".

Comment on lines +177 to +180
if (tab && !tab.closed) {
tab.location.replace(url);
} else {
window.location.replace(url);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

Comment on lines +360 to +363
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

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

Comment thread coordinator/api/server.go Outdated
// 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))

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

@blacksmith-sh

blacksmith-sh Bot commented Jul 27, 2026

Copy link
Copy Markdown
Contributor

Found 1 test failure on Blacksmith runners:

Failure

Test View Logs
github.com/eigeninference/d-inference/e2e/TestIntegrationExactCacheRouting View Logs

Fix with [code]smith
Need help on this PR? Tag @codesmith-bot with what you need.

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 18 out of 18 changed files in this pull request and generated no new comments.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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".

Comment on lines +116 to +120
<PayoutDestinationRow
status={status}
onOpenDashboard={onOpenDashboard}
dashboardLoading={dashboardLoading}
/>

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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.
@Gajesh2007

Copy link
Copy Markdown
Member Author

@codex — went through all four findings. Two were real and are fixed in 06f880e; two I'm declining, with reasoning below.

Fixed

P2 #3 — rate-limit dashboard login-link creation. Correct, and POST /v1/billing/stripe/dashboard was the only Stripe-POST billing route missing the limiter (create-session has it). Now requirePrivyAuth(rateLimitFinancial(handleStripeDashboardLink)).

One correction to the suggestion: you said "apply the financial limiter outside the authentication middleware." That would break it. rateLimitWithTier keys on consumerKeyFromContext(r.Context()), which only the auth middleware populates — outside requirePrivyAuth every caller collapses into one empty-string bucket, so the first anonymous request would consume the shared token and throttle everyone else. rateLimitFinancial's own doc comment says "Chain inside requireAuth," and all ten sibling financial routes do exactly that. Chained inside.

Pinned by TestStripeDashboardLinkRouteIsRateLimited, which drives the real mux with a signed Privy JWT (new privySession harness — the existing withPrivyUser only stuffs context and can't traverse route middleware). Negative-controlled: with the limiter removed the second call returns 409 instead of 429 and the test fails.

P2 #1 — refresh the payout destination after returning from Stripe. Correct, and worse than the cosmetic staleness you described. openWithdraw seeds withdrawMethod from the stale status.instant_eligible, and stripe_withdraw.go:143 admits instant when either the freshly fetched account or the stored flag says eligible:

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 visibilitychange handler that fires reload(true) — refresh=1, not the cached read, since account.updated may not have landed yet. It lives in a useEffect rather than inside openDashboard so it's torn down if the page unmounts before the user ever comes back, and the flag is only armed on the new-tab branch (the popup-blocked fallback unloads this page anyway). Two tests: the refresh fires once on return, and tab focus without a dashboard link never triggers it. Negative-controlled.

Declining

P2 #2 — distinguish pending verification from unfinished onboarding. The analysis is right: stripeStatusForAccount maps DetailsSubmitted=true, PayoutsEnabled=false, CurrentlyDue=[] to pending via the default arm, and Stripe does issue login links for that state. But PayoutDestinationRow renders only in the ready branch of StripePayoutsCard (line 114), so no UI path can reach the 409 — only a direct API caller. Adding a Stripe round-trip on every pending request to unblock a path nothing walks isn't worth it. If we later surface the button for restricted/rejected (which the backend gate already allows) this becomes worth revisiting.

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 connect.stripe.com/express_login with their email and an OTP, no platform-issued link required — per Stripe's Express Dashboard docs. So reconcileUnmatchedPayout's !pe.Automatic early return already strands dashboard-initiated payouts in transferred today; this PR only makes the door more discoverable. Attributing non-automatic payouts to withdrawal rows means changing the webhook state machine's matching rules, which deserves its own PR and its own reasoning about over-claiming — the exact hazard the current early return exists to avoid. Filing a follow-up rather than bolting it on here.

Unrelated: this PR cannot go green yet

Coordinator Lint fails with:

coordinator/api/toolschema.go:722:6: func typelessAssertionFamiliesAmbiguous is unused (unused)

That's a master breakage inherited via the merge commit — master at fde284903 (#603) is red on the same job. Please don't "fix" it by deleting the function: its doc comment says "Callers reject these before normalization" and nothing calls it, so inferredType silently falls through to "string" for {"minimum":5,"minLength":2} and {"not":{"type":"string"}}. That's a live behavior gap in #603, not dead code. Needs a fix on master.

Threat Model Review is also failing, on infra rather than code: anthropic.AuthenticationError: 401 - API key is invalid.

For the threat-model reviewer's two open questions

  • Is the URL logged or persisted? No. stripe_payouts.go:393-396 logs a truncated account ID and the Stripe account ID at issuance; the link itself is never logged, stored, or cached. On the JSON-vs-302 point: a redirect can't work here — the frontend opens a tab synchronously inside the click gesture to survive the popup blocker, then navigates it once the link arrives, so the URL has to come back as data.
  • Is mock mode reachable in production? No. BillingConfig.Validate() (billing/config.go:74-76) refuses to boot when MockMode and a real StripeSecretKey are both set.

Verification for this commit: gofmt -l clean · go vet ./api/... ./billing/... clean · go test ./api/... ./billing/... pass · eslint src/ __tests__/ 0 errors · vitest 499 passed.

@chatgpt-codex-connector

Copy link
Copy Markdown

Summary

Testing

  • ✅ git diff --check
  • ✅ git status --porcelain
  • ⚠️ npm test -- --run __tests__/payouts.test.tsx (Node.js was unavailable, and mise could not download the pinned toolchain because outbound network access failed.)
  • ⚠️ npx eslint src/ __tests__/ (Node.js was unavailable for the same environment limitation.)
  • ⚠️ Screenshot capture was not possible because the local web application could not be started without the Node.js toolchain.

View task →

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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-store to 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-store for 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
	}

@Gajesh2007
Gajesh2007 merged commit 77c99fb into master Aug 3, 2026
12 of 15 checks passed
@Gajesh2007
Gajesh2007 deleted the feat/stripe-express-dashboard-link branch August 3, 2026 18:46

This branch had an error being deployed

1 failed and 3 active deployments
Preview – d-inference — 06f880e6 Deployed Aug 3, 2026 by vercel[bot]
Preview – d-inference-console-ui-dev — 06f880e6 Deployed Aug 3, 2026 by vercel[bot]
Preview – d-inference-landing — 06f880e6 Deployed Aug 3, 2026 by vercel[bot]
benchmarks — 06f880e6 Deployed Aug 3, 2026 by Gajesh2007 via E2E Benchmarks #29
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants