apply_reversal() read the deposit_reversals row, computed a new
clawed_micros/status from it, then wrote it back with no lock held across
the gap -- the actual money movement (commit_redeem) is independently
idempotency-guarded, but the bookkeeping UPSERT was a blind
EXCLUDED.* overwrite. Two concurrent reversal applications for the same
deposit_ref (e.g. a provider's at-least-once webhook redelivery, or a
webhook racing an operator retry) could both read the same stale row;
whichever write landed last won, even if it came from the side that
burned nothing (idempotent replay). That could silently regress a fully
clawed-back reversal to "shortfall" -- and shortfalls are a designed-for
operator worklist item that gets retried, so the next retry would burn
the account a second time for money already recovered.
Same bug class as the Rago prepaid-wallet lost-update fix (f9d0a1b5):
make the merge commutative instead of last-write-wins. amount_micros/
clawed_micros/attempts only ever grow, so GREATEST() them in the
Postgres UPSERT (and mirror the merge in the in-memory store); derive
status from the post-merge totals, with written_off always sticky on
either side of a race.
Repro: added concurrent_reversal_upsert_does_not_lose_the_winning_write
and written_off_is_sticky_against_a_late_stale_reversal_write to
mint-store's memory tests -- both fail against the pre-fix blind
overwrite and pass after the fix. Also manually verified against a real
Postgres (docker postgres:16-alpine, migrations applied): same
before/after repro reproduces the regression pre-fix and confirms the
fix post-fix.
cargo build --workspace and cargo test --workspace (excluding the
DATABASE_URL-gated pg_live/pg_settlement_live suites) are green.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
GET /v1/accounts/:id/allowances (mint-server's `allowances` handler) calls
store.list_account_allowances, a second read path over the same
AllowanceRecord type as get_allowance/read_allowance. Commit 8e6a6671 fixed
the stale spent_micros/window_start_ms bug for GET /v1/allowances/:id by
projecting AllowanceRecord::as_of(now) onto the single-record read, but
never applied the same fix to this listing call site in either the
in-memory or Postgres store, so a caller polling an account's allowances
after a Rolling window elapsed but before the next spend would still see
the stale, too-low spent_micros.
Apply the same `.as_of(clock.now())` projection to each record returned by
list_account_allowances in both mint-store/src/memory.rs and
mint-store-postgres/src/store.rs. Add a ledger-level regression test
mirroring the existing read_allowance_reflects_rolling_reset test, but
exercising list_account_allowances instead; verified it fails with the
exact stale value (spent_micros 5_000_000 instead of 0) when the fix is
reverted, and passes with the fix applied.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Ledger::read_allowance (both InMemoryStore and the Postgres store) returned
the raw stored row, which only resets spent_micros/window_start_ms lazily
inside the next commit_allowance_spend call. A caller that reads an
allowance (GET /v1/allowances/:id) after a Rolling window has elapsed but
before the next spend saw the stale pre-reset spent_micros — in the worst
case a fully-reset allowance reporting itself as exhausted.
Real downstream impact: Abacus's GET /v1/budget (agent-facing) and GET
/v1/admin/overview both call Mint's get_allowance and compute
remaining_micros directly from this value (apps/abacus/crates/abacus-proxy/
src/admin.rs::allowance_remaining), so an allowance-funded agent could be
told it has no budget left when its window had already reset, blocking real
paid work that would in fact succeed.
Fix: AllowanceRecord::as_of(now_ms) projects the same elapsed-window reset
read-only (no store write, no API/schema change) and both get_allowance
impls apply it. Added a regression test
(read_allowance_reflects_rolling_reset_before_any_further_spend) proving a
plain read reflects the reset immediately. Full workspace suite still
green (cargo test --workspace --locked).
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
verify_webhook's RTDN re-confirmation call mapped EVERY lookup() failure
(network error, Google-side 5xx/429, a bad OAuth2 exchange -- all surfaced as
RampError::ProviderUnavailable) into WebhookError::Ignored. mint-server's
webhook dispatch acknowledges Ignored with 200, so Pub/Sub never redelivers:
a real paid purchase hitting a transient Play Developer API hiccup during
re-confirmation was silently and permanently dropped, never minted.
Distinguish ProviderUnavailable (transient, retryable) from the other
RampError variants (DepositNotFound/NotConfirmed -- a definitive non-paid
answer, correctly Ignored) by mapping it to WebhookError::Malformed instead,
which the same dispatch answers 503 so Pub/Sub retries until the lookup
succeeds. TDD: added transient_lookup_failure_is_retried_not_dropped (red on
the old mapping, green after), full mint-payments + mint workspace suites
(all 100+ tests, 20 crates) still pass with zero regressions.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Closes the other half of I31 ("Direct ASSN v2 and Play RTDN in Mint") —
Apple App Store Server Notifications v2 was already built; this adds the
matching direct (no-aggregator) integration for Google Play.
New ProviderId::PlayStore in mint-payments, mirroring the AppStore adapter's
shape but necessarily async: an RTDN notification carries neither a price
nor the Mint account to credit, so a mintable delivery is re-confirmed
against the Play Developer API (OAuth2 service-account JWT, RS256 via the
already-vendored `ring` crate — no new dependency) before it mints.
Key correctness decisions, documented in the module:
- deposit_ref is keyed on the Developer API's own order id, not the purchase
token (which Play keeps stable across a subscription's own renewals) — a
renewal mints again instead of idempotently replaying the original
purchase, covered by a dedicated regression test.
- USD price comes from a static PLAYSTORE_PRICES_JSON catalog: neither the
v3 ProductPurchase nor SubscriptionPurchaseV2 Developer API resource
carries a price field.
- voidedPurchaseNotification (Google's refund signal) reverses by its own
orderId with no second network call; REVOKED/CANCELED on the primary
notification types are deliberately Ignored in favor of that cleaner,
orderId-bearing signal.
- the Pub/Sub push auth token travels as a `?token=` query parameter (push
subscriptions can't attach a custom static header); mint-server's
deposits.rs bridges it into a synthetic header so mint-payments itself
stays axum/query-string-free.
18 new unit tests in playstore.rs (the OAuth2 path signs with a real
synthetic RSA test key, not a mocked signer) plus 4 in mint-server's
deposits.rs for the query->header bridge. Full existing suites re-run green
with zero regressions: mint-payments 112+13+6+6+3, mint-server
22+13+14+3+3+6+8. cargo clippy --all-targets: zero warnings in any touched
file.
Also closes the gap in scripts/parity/recount.mjs: new wave-s.mjs moves I31
MISSING -> DONE on real evidence; infra now 30/10/4 (was 29/10/5),
--self-test still exits 0, recount.test.mjs extended with a Wave S test.
Not deployed: PLAYSTORE_SERVICE_ACCOUNT_KEY / CLIENT_EMAIL / PACKAGE_NAME /
WEBHOOK_TOKEN / PRICES_JSON all need a real Google Play Console service
account and a Pub/Sub push subscription, which is an owner-only step.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Notifications and their transactions are Apple JWS verified against a
pinned root (Apple Root CA - G3 by SHA-256): x5c chain links, validity,
Apple's marker extensions and the ES256 signature. Bundle id and
environment must match; ONE_TIME_CHARGE, SUBSCRIBED and DID_RENEW mint
USD prices to the transaction's appAccountToken; REFUND and REVOKE
reverse. Re-confirmation calls the App Store Server API with an ES256
token from the app's key and refuses revoked or foreign transactions.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
When a seller disconnects our platform in their Stripe dashboard, Stripe
sends account.application.deauthorized; Mint ignored it, so the seller still
showed as connected and checkouts were attempted on a revoked account.
The Connect webhook now maps it (ConnectEvent.deauthorized) and the seller
store forgets the connection and the products made on that account (their
prices live there) in one transaction; entitlement history stays. A replay or
an unknown account is ignored.
Tests: stripe unit (mapping, no lookup on the revoked account), mint-server
seller (connected -> webhook -> not connected, products gone, replay ignored),
mint-store-postgres live (account and products removed, replay no-op).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The live suites used fixed idempotency keys (keys are global in the ledger),
so a second run on the same scratch database replayed the first run's keys
against new accounts (IdempotencyConflict, InsufficientFunds), and the
settlement tests asserted the global reserve unchanged while running in
parallel with tests that fund accounts. Keys now carry a per-run tag and the
reserve-sensitive tests run one at a time. 11/11 pass twice in a row.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Menivor's coupons (videogen processor.py MintDiscounts, apps/mint README
contract) PATCH /mint/v1/sellers/{seller}/discounts/{discount_id} to stop a
code (expires_at now) and to switch it back on with new terms on the same id.
- PATCH forwards a partial Dodo PATCH /discounts/{id} (code, name,
type+amount, currency_options or currency, expires_at incl. null to clear,
restricted_to as the seller's skus) with the seller's own key and answers
200 {discount:{discount_id, id, code, type, amount, expires_at}}.
A change to a percentage sends currency_options [] so an old flat row
never lingers as a percentage cap (Dodo replace-set semantics).
- Seller-scoped authz: Mint now records which seller of which product made
which processor discount id (mint_seller_discounts, migration 0015; memory
store too). Any other id, or a code deleted on the dashboard (Dodo 404),
is 404 unknown_discount; the seller error shape throughout.
- Validation before any call: id charset, type and amount together, flat
needs one currency row whose max_amount_possible is the amount, RFC 3339
dates, unknown fields refused (400 invalid_body).
- Idempotency: PATCH is naturally repeatable; a retried create of a known
code with the same terms answers 200 created:false (checked with GET on
the seller's account), other terms 409 code_in_use, a code gone from the
processor is made again. Create answers carry discount_id as the contract
says (id kept).
- HttpTransport gains patch_json (default refuses; ReqwestTransport sends).
- Verified against Dodo docs: currency_options rows are {currency,
max_amount_possible, is_default, minimum_subtotal?}; is_default is real and
a flat code needs a resolvable default, so the mapping stays.
- Discount handlers moved to mint-server/src/seller_discounts.rs (seller.rs
was over 800 lines).
Tests: cargo test -p mint-payments seller 11/11 (new stop/re-enable/404 and
validation case); cargo test -p mint-server --test seller 5/5 (new end to
end: stop, re-enable flat, clear expiry, re-code, retried create, conflict,
deleted on dashboard, other seller's id, 11 refusals with no processor
call). pg_seller_live extended (ignored without DATABASE_URL). Clippy: no
findings in touched files (pre-existing mint-store/main.rs findings untouched).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Menivor creator coupons (videogen wave-q-menivor 778634b5) need Mint to
make discounts on the creator's own processor so no seller key reaches
Menivor.
- POST /mint/v1/sellers/{seller}/discounts takes Dodo's POST /discounts
shape as Menivor sends it: {code, type percentage|flat, amount (basis
points, or the smallest unit for flat), expires_at?, name?,
currency_options? (or currency), restricted_to? (the seller's skus)}.
Mint maps skus to the seller's processor product ids, calls Dodo with the
seller's sealed key, stores nothing, and answers
201 {discount:{id, code, type, amount, currency, expires_at,
restricted_to}}. Refusals: 400 bad type/amount/currency/date/code,
404 unknown_sku, 401 without a product key, 409 not_connected or
discounts_unsupported (Stripe-connected sellers), 422 when the
processor refuses (a code in use).
- checkout-sessions takes discount_code (3-32 of A-Z 0-9 - _), sent to
Dodo as discount_codes [CODE] (the non-deprecated field); refused with
400 before any call when malformed, 409 for Stripe sellers.
- The ledger invariant holds: the seller module still has no ledger handle.
Tests: cargo test -p mint-payments seller 10/10 (new: discount body
shapes, seller's key, validation before any call, coded checkout);
cargo test -p mint-server --test seller 4/4 (new end-to-end case). Clippy
clean on the touched files (mint-store has pre-existing -D warnings
findings, not touched).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- A Dodo retry is signed with a fresh webhook-timestamp. Using it as
occurred_at let a grant retried after a refund look newer than the refund,
so the never-back-in-time upsert downstream re-granted a refunded buyer.
occurred_at now comes from the payload's own UTC timestamp (not trusted
beyond the signature tolerance), falling back to the delivery stamp.
- Dodo makes a webhook secret only when the endpoint is added, but the page
asked for the secret before showing the address. The address now sits
above the secret field, so the seller connects in one pass.
Tests: mint-payments 85, mint-server green (seller 3).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
VC6 and dispatch contract 5.5, Mint side:
- mint-payments/src/seller: the seller's own Dodo account (their key on
their account for products, checkouts and the payment lookup a refund or
dispute needs; their webhook secret verifies their events) and Stripe
Connect (OAuth, direct charges on the connected account with no fee and no
transfer; off until OD-9: all three MINT_STRIPE_CONNECT_* or nothing).
Credentials sealed with AES-256-GCM (ring, already in the lock), bound to
the seller so a sealed value cannot move to another row.
- mint-server/src/seller.rs: POST /mint/v1/sellers/{seller}/connect (a one-
time, 15-minute link), GET seller, products (create, list),
checkout-sessions, entitlements; the processor webhooks
(/mint/webhooks/seller/{product}/{seller}/dodo, /mint/webhooks/stripe-connect)
become entitlement.granted / entitlement.revoked (refund, dispute,
cancelled, expired), recorded once per provider event and delivered
Standard Webhooks signed to the calling product with backoff. Product keys
in MINT_SELLER_PRODUCTS_JSON keep callers apart; an event whose metadata
names another seller changes nothing.
- seller_page.rs: the connect page, the only place a key is typed; the
default screen has no key field (Stripe is a button, Dodo keys sit under
Advanced, closed); no scripts; strict CSP.
- Invariant: no ledger handle anywhere in seller payments; the test runs a
sale through the served router and finds no journal entry and no account.
- Storage: mint-store SellerStore + MemorySellerStore; Postgres PgSeller and
migration 0014_seller_payments (idempotent).
Tests: mint-payments 84 (seller 8), mint-server 18 lib + seller 3 + the rest
green, mint-store green, live PG seller + mirror 2/2 on a scratch cluster with
0001-0014 applied; clippy clean on the new files.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Mint side of PY1.5 (dispatch 5.3: a ledger entry per paid event, mirrored
from Dodo webhooks; Mint never initiates a payout of third-party funds).
- POST /v1/mirror/events: each product records what its payment provider
told it, with its own mirror key (MINT_MIRROR_KEYS_JSON); a replay of the
same provider event is a no-op (unique provider + event id);
GET /v1/mirror/events lists only the calling product's records.
- Records live beside the ledger (mint_mirror_events, migration 0013) and the
mirror module has no ledger handle: no balance, hold or payout can result.
- Outbound: every record is delivered to each configured endpoint
(MINT_EVENT_WEBHOOKS_JSON) as a Standard Webhooks signed mirror.recorded
event from an outbox, every 15 s, retried 30 s doubling to 6 h until a 2xx.
The signer lives in mint-payments (the only crate that talks HTTP) and
reproduces the Railyard bridge contract's signature vector.
- /metrics already exists (RY-MT1) and is scraped by the box-2 job.
Tests: mint workspace green; mint-server tests/mirror.rs 3/3 (idempotency,
product isolation, signed delivery with retry and backoff, config checks);
mint-payments outbound 1/1; mint-store-postgres pg_mirror_live and pg_live
against a scratch local cluster (DATABASE_URL, --ignored) 3/3; migration 0013
re-applied by hand without error.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- MINT_SHADOW=1 installs a ramp that refuses every deposit and every payout
(checked before any burn), so Mint can run on its production Postgres with no
money moving. Startup is refused in shadow mode when a payment provider or
MINT_DEV_FUNDING=1 is configured, so no hosted checkout can take money that
would never be credited.
- GET /metrics (Prometheus text): readiness, journal, reserve, open holds and
micros, hold-expiry sweep lag, pending payouts, and the full receipt hash-chain
plus signature verification (first scrape, then every 24 h in the background).
Bearer token via MINT_METRICS_TOKEN; without it, proxied requests get 404.
- Tests: shadow refuses mint and redeem with balances unchanged, ledger and
/readyz still serve, metrics gauges, chain verify 1 and 0, token and proxy
gating, sweep lag on an expired hold; ramp-choice unit tests.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
DodoRamp creates pay-what-you-want USD checkouts, re-confirms deposits,
verifies Standard Webhooks signatures (5 min window) and maps refunds and
disputes to reversals. Wired into registry, config, checkout and
reconciliation handlers.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- RevenueCat/Adapty deposits confirmed via subscriber lookup bound to the
account (confirm_deposit_for), fail closed on refunds, mint from USD price
- hold expiry written in the same transaction as the hold (memory + Postgres)
- Iyzico V3-signed merchant notifications mapped to refund/dispute reversals;
hosted checkout-form callback resolves the token server-side
- PayPal/Stripe payout webhooks drive ReserveLedger::apply_payout_update
- mint-sdk: typed HoldReceipt/HoldState, validated capture/release,
capture_hold_in_full
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A dev/test-only binary that runs the REAL mint-server router / handlers /
auth / ledger over a real TCP socket, backed by the in-memory store and a
deterministic auto-confirming funding ramp. Lets an out-of-process client
(the ReelForge Python wallet) drive the genuine HTTP money surface end to
end — create account -> fund -> reserve -> capture / release — with no
Postgres or live payment provider. Never for deployment (refuses no deposit,
never touches a DB); production runs the mint-server main.rs binary.
Mint's prod binary shipped a permissive `FakeKycGate::new(Basic, i64::MAX)`
and silently fell back to the in-memory dev `FakeRamp` whenever no payment
provider was configured — the top money-correctness gap before real dollars
move.
- Add `StrictKycGate` (mint-reserve): a deny-by-default `KycGate` that refuses
every redemption with `KycRequired`. It fails CLOSED (unlike `FakeKycGate`,
which trusts a caller-presented tier), and is the seam a real provider slots
behind. Exported from the crate root.
- Rewire `mint-server` to select gates from deployment mode (a configured
`DATABASE_URL` = production):
* KYC: production always installs `StrictKycGate`. The permissive
`FakeKycGate` is a dev-only escape hatch behind `MINT_DEV_KYC_ALLOW=1` and
is REFUSED (bail) in production, mirroring the existing signer hardening.
* Funding ramp: a configured provider is always used; the dev `FakeRamp`
fallback is refused in production unless `MINT_DEV_FUNDING=1` is explicitly
set, so it can't silently ship as the funding path.
- Selection logic extracted into pure `choose_kyc`/`choose_ramp` fns with unit
tests (deny-by-default, dev-fake-refused-in-prod), plus `StrictKycGate`
gate tests in mint-reserve.
Tests: mint-reserve (lib 3 new + 11 integration) and mint-server (8 new wiring
+ 11 api) green on rust 1.96.1; clippy clean.
The store's authoritative dedupe key is derived purely from the ramp
reference (mint:{deposit_ref} / redeem:{payout_ref}), but both mint()
and redeem() folded the caller-supplied req.idem_key into op_hash. A
legitimate retry that reused the same deposit_ref/payout_ref but supplied
a fresh per-attempt caller idem_key tripped IdempotencyConflict instead
of replaying cleanly, contradicting the documented retry-safety contracts.
Remove req.idem_key from both op_hash bodies so the hash depends only on
the authoritative dedupe inputs (op/to/amount/deposit_ref and
op/from/amount/payout_ref). Real conflicts (different to/from/amount
reusing the same ref) still mismatch on those fields. Add regression
tests for both mint and redeem.