fix: round-2 loop-A fresh review (503c326 baseline) — B1 replay cap, A6 discount record, 2FA reissue+cooldown, notification flood, lockout saturation, VAT/refund-status consolidation

Round 2 Loop A fresh money/security/dup-mod review. 23 findings fixed:

MONEY:
- CRITICAL: B1 duplicate auto-refund gains an attempt cap (b1_attempts col, cap 3) —
  a rejected auto-refund no longer re-replays the expired key every sweep run
  (which minted a stacking unauthorized charge each time); FAILED-webhook
  demotion respects the cap; never re-replay a key whose B1 refund failed
- HIGH: A6 deposit_covered_by_discount skip path now APPLIES the eligible
  campaign discount rows immediately (capped) instead of skipping with no
  discount recorded — no more promised-discount-not-recorded overcharge
- MEDIUM: 2FA code burned by the SAVE gate is re-issued on failed
  new-card+save_card charges (re-issue guard now covers req.SaveCard)
- LOW: GetBookingPaymentSummary excludes tip rows from paidAmount (remaining
  now matches the authoritative tip-excluded balance)

SECURITY:
- MEDIUM: unacknowledged CRITICAL admin-notification flood capped (global cap
  on critical_payment_log + refresh_token_reuse rows)
- MEDIUM: 2FA reissue no longer bypasses the mint cooldown (Check no longer
  clears LastMintAt on gate-verify; cleared on terminal charge success)
- MEDIUM: twofa.StateFor map-saturation returns a shared permanently-locked
  state instead of a fresh 5-guess budget per request
- MEDIUM: ProgressiveRateLimit rejects 429 past maxProgressiveSleepDelayMs
  instead of sleeping unboundedly; login bcrypt concurrency semaphore added
- LOW: loginInProgress 409->429; webhook key-set/URL-unset startup check;
  email-verification per-user attempt counter

DUP/MOD:
- formatCurrency single source (frontend format.ts, 7 files consolidated);
  SquareRefundStatusToLocal single source (errors.go, all sites); admin
  audit-log helper dedup; SCA retry model unified (proactive on all 6
  surfaces); buyDailyTotal/daily-cap mirror via backend; lock TTL from
  backend; generateUUID at all card-form sites; magic numbers named
  (defaultPostgresHost, epsilon, fee constants); admin CASH + gift-card
  terminal charges now audited; DAV_SKIP_INIT documented in manuals

Verified: 26/26 dev + 24/24 prod (GO_TESTING=1, the CI condition), both vet
tags, frontend tests+build, env-docs 42/42.
This commit is contained in:
2026-08-22 00:34:50 +01:00
parent 4e64e32f09
commit 3866cc5963
36 changed files with 2032 additions and 719 deletions
+12 -21
View File
@@ -232,6 +232,15 @@ func HandleSquareWebhook(w http.ResponseWriter, r *http.Request) {
signingKey := os.Getenv("SQUARE_WEBHOOK_SIGNATURE_KEY")
notificationURL := os.Getenv("SQUARE_WEBHOOK_NOTIFICATION_URL")
if notificationURL == "" {
// Fail-closed fallback (Round 2 Loop A finding 6): an unset URL falls
// back to the public dev default so the handler always has a string to
// HMAC against. The subscription is fail-closed — the key AND the URL
// must exactly match the Square Dashboard configuration, so with the
// URL unset every GENUINE Square event fails signature verification
// here (403) and no event is ever processed; only the operator can fix
// the config. main.go's startup check (checkWebhookSignatureKey) warns
// when the key is set but the URL is unset — the reverse
// misconfiguration — so the breakage is visible at boot, not silent.
notificationURL = "http://localhost:8080/webhooks/square"
}
if signingKey == "" {
@@ -551,26 +560,6 @@ func squarePaymentStatusToLocal(status string) (string, bool) {
}
}
// squareRefundStatusToLocal maps Square's refund status to the local
// payment_status enum. Square's PaymentRefund states are PENDING, APPROVED,
// COMPLETED, CANCELED, FAILED and REJECTED (developer.squareup.com/reference/
// square/objects/PaymentRefund). COMPLETED/FAILED/REJECTED are TERMINAL —
// REJECTED (Square declined the refund) is a definitive failure and must be
// surfaced as local 'failed' instead of leaving the row pending until the slow
// sweep; PENDING and APPROVED are NON-terminal (the refund may still complete
// or be rejected) and map to a zero local status so the caller leaves the row
// untouched.
func squareRefundStatusToLocal(status string) (string, bool) {
switch status {
case "COMPLETED":
return "completed", true
case "FAILED", "REJECTED":
return "failed", true
default:
return "", false
}
}
// squareDisputeStateToLocal maps Square's dispute state to the local
// disputes.status. Only the terminal resolutions move the row to won/lost;
// ACCEPTED (seller accepted the dispute) is a loss — the money is gone.
@@ -1159,7 +1148,9 @@ func handleRefundUpdated(data json.RawMessage) error {
// A refund object is present but unusable: cannot apply money state — retry.
return fmt.Errorf("refund.updated payload for data.id=%q missing/invalid refund object (id=%q status=%q): %w", env.ID, refund.ID, refund.Status, errWebhookParseFailure)
}
localStatus, terminal := squareRefundStatusToLocal(refund.Status)
// Single shared Square → local refund-status mapping (payments package) so
// the webhook and the synchronous refund handlers can never drift.
localStatus, terminal := payments.SquareRefundStatusToLocal(refund.Status)
if !terminal {
log.Printf("[SQUARE-WEBHOOK] refund.updated: square refund %s status %q is non-terminal — no local state change", refund.ID, refund.Status)
return nil