TransferService.CreateTransfer signature changes from (...) error to
(...) (string, error) — the caller now captures the Stripe transfer
identifier and persists it on the SellerTransfer row. Pre-v1.0.7 the
stripe_transfer_id column was declared on the model and table but
never written to, which blocked the reversal worker (v1.0.7 item B)
from identifying which transfer to reverse on refund.
Changes:
* `TransferService` interface and `StripeConnectService.CreateTransfer`
both return the Stripe transfer id alongside the error.
* `processSellerTransfers` (marketplace service) persists the id on
success before `tx.Create(&st)` so a crash between Stripe ACK and
DB commit leaves no inconsistency.
* `TransferRetryWorker.retryOne` persists on retry success — a row
that failed on first attempt and succeeded via the worker is
reversal-ready all the same.
* `admin_transfer_handler.RetryTransfer` (manual retry) persists too.
* `SellerPayout.ExternalPayoutID` is populated by the Connect payout
flow (`payout.go`) — the field existed but was never written.
* Four test mocks updated; two tests assert the id is persisted on
the happy path, one on the failure path confirms we don't write a
fake id when the provider errors.
Migration `981_seller_transfers_stripe_reversal_id.sql`:
* Adds nullable `stripe_reversal_id` column for item B.
* Partial UNIQUE indexes on both stripe_transfer_id and
stripe_reversal_id (WHERE IS NOT NULL AND <> ''), mirroring the
v1.0.6.1 pattern for refunds.hyperswitch_refund_id.
* Logs a count of historical completed transfers that lack an id —
these are candidates for the backfill CLI follow-up task.
Backfill for historical rows is a separate follow-up (cmd/tools/
backfill_stripe_transfer_ids, calling Stripe's transfers.List with
Destination + Metadata[order_id]). Pre-v1.0.7 transfers without a
backfilled id cannot be auto-reversed on refund — document in P2.9
admin-recovery when it lands. Acceptable scope per v107-plan.
Migration number bumped 980 → 981 because v1.0.6.2 used 980 for the
unpaid-subscription cleanup; v107-plan updated with the note.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Closes a bypass surfaced by the 2026-04 audit probe (axis-1 Q2): any
authenticated user could POST /api/v1/subscriptions/subscribe on a paid
plan and receive 201 active without the payment provider ever being
invoked. The resulting row satisfied `checkEligibility()` in the
distribution service via `can_sell_on_marketplace=true` on the Creator
plan — effectively free access to /api/v1/distribution/submit, which
dispatches to external partners.
Fix is centralised in `GetUserSubscription` so there is no code path
that can grant subscription-gated access without routing through the
payment check. Effective-payment = free plan OR unexpired trial OR
invoice with non-empty hyperswitch_payment_id. Migration 980 sweeps
pre-existing fantôme rows into `expired`, preserving the tuple in a
dated audit table for support outreach.
Subscribe and subscribeToFreePlan treat the new ErrSubscriptionNoPayment
as equivalent to ErrNoActiveSubscription so re-subscription works
cleanly post-cleanup. GET /me/subscription surfaces needs_payment=true
with a support-contact message rather than a misleading "you're on
free" or an opaque 500. TODO(v1.0.7-item-G) annotation marks where the
`if s.paymentProvider != nil` short-circuit needs to become a mandatory
pending_payment state.
Probe script `scripts/probes/subscription-unpaid-activation.sh` kept as
a versioned regression test — dry-run by default, --destructive logs in
and attempts the exploit against a live backend with automatic cleanup.
8-case unit test matrix covers the full hasEffectivePayment predicate.
Smoke validated end-to-end against local v1.0.6.2: POST /subscribe
returns 201 (by design — item G closes the creation path), but
GET /me/subscription returns subscription=null + needs_payment=true,
distribution eligibility returns false.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Hotfix surfaced by the v1.0.6 refund smoke test. Migration 978's plain
UNIQUE constraint on hyperswitch_refund_id collided on empty strings
— two refunds in the same post-Phase-1 / pre-Phase-2 state (or a
previous Phase-2 failure leaving '') would violate the constraint at
INSERT time on the second attempt, even though the refunds were for
different orders.
* Migration 979_refunds_unique_partial.sql replaces the plain
UNIQUE with a partial index excluding empty and NULL values.
Idempotency for successful refunds is preserved — duplicate
Hyperswitch webhooks land on the same row because the PSP-
assigned refund_id is non-empty.
* No Go code change. The bug was purely in the DB constraint shape.
Smoke test that caught it — 5/5 scenarios re-verified end-to-end:
happy path, idempotent replay (succeeded_at + balance strictly
invariant), PSP error rollback, webhook refund.failed, double-submit.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Fourth item of the v1.0.6 backlog, and the structuring one — the pre-
v1.0.6 RefundOrder wrote `status='refunded'` to the DB and called
Hyperswitch synchronously in the same transaction, treating the API
ack as terminal confirmation. In reality Hyperswitch returns `pending`
and only finalizes via webhook. Customers could see "refunded" in the
UI while their bank was still uncredited, and the seller balance
stayed credited even on successful refunds.
v1.0.6 flow
Phase 1 — open a pending refund (short row-locked transaction):
* validate permissions + 14-day window + double-submit guard
* persist Refund{status=pending}
* flip order to `refund_pending` (not `refunded` — that's the
webhook's job)
Phase 2 — call PSP outside the transaction:
* Provider.CreateRefund returns (refund_id, status, err). The
refund_id is the unique idempotency key for the webhook.
* on PSP error: mark Refund{status=failed}, roll order back to
`completed` so the buyer can retry.
* on success: persist hyperswitch_refund_id, stay in `pending`
even if the sync status is "succeeded". The webhook is the only
authoritative signal. (Per customer guidance: "ne jamais flipper
à succeeded sur la réponse synchrone du POST".)
Phase 3 — webhook drives terminal state:
* ProcessRefundWebhook looks up by hyperswitch_refund_id (UNIQUE
constraint in the new `refunds` table guarantees idempotency).
* terminal-state short-circuit: IsTerminal() returns 200 without
mutating anything, so a Hyperswitch retry storm is safe.
* on refund.succeeded: flip refund + order to succeeded/refunded,
revoke licenses, debit seller balance, mark every SellerTransfer
for the order as `reversed`. All within a row-locked tx.
* on refund.failed: flip refund to failed, order back to
`completed`.
Seller-side reconciliation
* SellerBalance.DebitSellerBalance was using Postgres-only GREATEST,
which silently failed on SQLite tests. Ported to a portable
CASE WHEN that clamps at zero in both DBs.
* SellerTransfer.Status = "reversed" captures the refund event in
the ledger. The actual Stripe Connect Transfers:reversal call is
flagged TODO(v1.0.7) — requires wiring through TransferService
with connected-account context that the current transfer worker
doesn't expose. The internal balance is corrected here so the
buyer and seller views match as soon as the PSP confirms; the
missing piece is purely the money-movement round-trip at Stripe.
Webhook routing
* HyperswitchWebhookPayload extended with event_type + refund_id +
error_message, with flat and nested (object.*) shapes supported
(same tolerance as the existing payment fields).
* New IsRefundEvent() discriminator: matches any event_type
containing "refund" (case-insensitive) or presence of refund_id.
routes_webhooks.go peeks the payload once and dispatches to
ProcessRefundWebhook or ProcessPaymentWebhook.
* No signature-verification changes — the same HMAC-SHA512 check
protects both paths.
Handler response
* POST /marketplace/orders/:id/refund now returns
`{ refund: { id, status: "pending" }, message }` so the UI can
surface the in-flight state. A new ErrRefundAlreadyRequested maps
to 400 with a "already in progress" message instead of silently
creating a duplicate row (the double-submit guard checks order
status = `refund_pending` *before* the existing-row check so the
error is explicit).
Schema
* Migration 978_refunds_table.sql adds the `refunds` table with
UNIQUE(hyperswitch_refund_id). The uniqueness constraint is the
load-bearing idempotency guarantee — a duplicate PSP notification
lands on the same DB row, and the webhook handler's
FOR UPDATE + IsTerminal() check turns it into a no-op.
* hyperswitch_refund_id is nullable (NULL between Phase 1 and
Phase 2) so the UNIQUE index ignores rows that haven't been
assigned a PSP id yet.
Partial refunds
* The Provider.CreateRefund signature carries `amount *int64`
already (nil = full), but the service call-site passes nil. Full
refunds only for v1.0.6 — partial-refund UX needs a product
decision and is deferred to v1.0.7. Flagged in the ErrRefund*
section.
Tests (15 cases, all sqlite-in-memory + httptest-style mock provider)
* RefundOrder phase 1
- OpensPendingRefund: pending state, refund_id captured, order
→ refund_pending, licenses untouched
- PSPErrorRollsBack: failed state, order reverts to completed
- DoubleRequestRejected: second call returns
ErrRefundAlreadyRequested, not a generic ErrOrderNotRefundable
- NotCompleted / NoPaymentID / Forbidden / SellerCanRefund
- ExpiredRefundWindow / FallbackExpiredNoDeadline
* ProcessRefundWebhook
- SucceededFinalizesState: refund + order + licenses + seller
balance + seller transfer all reconciled in one tx
- FailedRollsOrderBack: order returns to completed for retry
- IsRefundEventIdempotentOnReplay: second webhook asserts
succeeded_at timestamp is *unchanged*, proving the second
invocation bailed out on IsTerminal (not re-ran)
- UnknownRefundIDReturnsOK: never-issued refund_id → 200 silent
(avoids a Hyperswitch retry storm on stale events)
- MissingRefundID: explicit 400 error
- NonTerminalStatusIgnored: pending/processing leave the row
alone
* HyperswitchWebhookPayload.IsRefundEvent: 6 dispatcher cases
(flat event_type, mixed case, payment event, refund_id alone,
empty, nested object.refund_id)
Backward compat
* hyperswitch.Provider still exposes the old Refund(ctx,...) error
method for any call-site that only cared about success/failure.
* Old mockRefundPaymentProvider replaced; external mocks need to
add CreateRefund — the interface is now (refundID, status, err).
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
First item of the v1.0.6 backlog surfaced by the v1.0.5 smoke test: a
brand-new account could register, verify email, and log in — but
attempting to upload hit a 403 because `role='user'` doesn't pass the
`RequireContentCreatorRole` middleware. The only way to get past that
gate was an admin DB update.
This commit wires the self-service path decided in the v1.0.6
specification:
* One-way flip from `role='user'` to `role='creator'`, gated strictly
on `is_verified=true` (the verification-email flow we restored in
Fix 2 of the hardening sprint).
* No KYC, no cooldown, no admin validation. The conscious click
already requires ownership of the email address.
* Downgrade is out of scope — a creator who wants back to `user`
opens a support ticket. Avoids the "my uploads orphaned" edge case.
Backend
* Migration `977_users_promoted_to_creator_at.sql`: nullable
`TIMESTAMPTZ` column, partial index for non-null values. NULL
preserves the semantic for users who never self-promoted
(out-of-band admin assignments stay distinguishable from organic
creators for audit/analytics).
* `models.User`: new `PromotedToCreatorAt *time.Time` field.
* `handlers.UpgradeToCreator(db, auditService, logger)`:
- 401 if no `user_id` in context (belt-and-braces — middleware
should catch this first)
- 404 if the user row is missing
- 403 `EMAIL_NOT_VERIFIED` when `is_verified=false`
- 200 idempotent with `already_elevated=true` when the caller is
already creator / premium / moderator / admin / artist /
producer / label (same set accepted by
`RequireContentCreatorRole`)
- 200 with the new role + `promoted_to_creator_at` on the happy
path. The UPDATE is scoped `WHERE role='user'` so a concurrent
admin assignment can't be silently overwritten; the zero-rows
case reloads and returns `already_elevated=true`.
- audit logs a `user.upgrade_creator` action with IP, UA, and
the role transition metadata. Non-fatal on failure — the
upgrade itself already committed.
* Route: `POST /api/v1/users/me/upgrade-creator` under the existing
protected users group (RequireAuth + CSRF).
Frontend
* `AccountSettingsCreatorCard`: new card in the Account tab of
`/settings`. Completely hidden for users already on a creator-tier
role (no "you're already a creator" clutter). Unverified users see
a disabled-but-explanatory state with a "Resend verification"
CTA to `/verify-email/resend`. Verified users see the "Become an
artist" button, which POSTs to `/users/me/upgrade-creator` and
refetches the user on success.
* `upgradeToCreator()` service in `features/settings/services/`.
* Copy is deliberately explicit that the change is one-way.
Tests
* 6 Go unit tests covering: happy path (role + timestamp), unverified
refused, already-creator idempotent (timestamp preserved),
admin-assigned idempotent (no timestamp overwrite), user-not-found,
no-auth-context.
* 7 Vitest tests covering: verified button visible, unverified state
shown, card hidden for creator, card hidden for admin, success +
refetch, idempotent message, server error via toast.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
The maintenance toggle lived in a package-level `bool` inside
`middleware/maintenance.go`. Flipping it via `PUT /admin/maintenance`
only updated the pod handling that request — the other N-1 pods stayed
open for traffic. In practice this meant deploys-in-progress or
incident playbooks silently failed to put the fleet into maintenance.
New storage:
* Migration `976_platform_settings.sql` adds a typed key/value table
(`value_bool` / `value_text` to avoid string parsing in the hot
path) and seeds `maintenance_mode=false`. Idempotent on re-run.
* `middleware/maintenance.go` rewritten around a `maintenanceState`
with a 10s TTL cache. `InitMaintenanceMode(db, logger)` primes the
cache at boot; `MaintenanceModeEnabled()` refreshes lazily when the
next request lands after the TTL. Startup `MAINTENANCE_MODE` env is
still honoured for fresh pods.
* `router.go` calls `InitMaintenanceMode` before applying the
`MaintenanceGin()` middleware so the first request sees DB truth.
* `PUT /api/v1/admin/maintenance` in `routes_core.go` now does an
`INSERT ... ON CONFLICT DO UPDATE` on the table *before* the
in-memory setter, so the flip survives restarts and propagates to
every pod within ~10s (one TTL window).
Tests: `TestMaintenanceGin_DBBacked` flips the DB row, waits past a
shrunk-for-test TTL, and asserts the cache picked up the change. All
four pre-existing tests preserved (`Disabled`, `Enabled_Returns503`,
`HealthExempt`, `AdminExempt`).
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
- Add PUT /users/me/password inline handler in routes_users.go
(the existing handler in internal/api/user/ was never registered)
- Create migration 975 adding two_factor_enabled, two_factor_secret,
and backup_codes columns to users table (fixes 500 on 2FA endpoints)
Fixes: Settings bugs #1 (password 404), #2/#4 (2FA 500)
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Update RabbitMQ config and eventbus. Improve secret filter logging.
Refine presence, cloud, and social services. Update announcement and
feature flag handlers. Add track_likes updated_at migration. Rebuild
seed binary.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
- Remove old apps/web/e2e/ test suite (replaced by tests/e2e/)
- Remove old playwright configs (smoke, storybook, visual, root)
- Move down migrations to veza-backend-api/migrations/rollback/
- Remove stale test results and playwright report artifacts
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Tables: courses, lessons, course_enrollments, lesson_progress,
certificates, course_reviews with proper indexes and constraints.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Add migration 950 with track_distributions, track_distribution_status_history,
and external_streaming_royalties tables for F501-F510.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Add migration 949 with subscription_plans, user_subscriptions,
and subscription_invoices tables. Includes default plan data
(Free, Creator $9.99/mo, Premium $19.99/mo with 14-day trial).
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
- seller_balances table for balance tracking
- seller_payouts table for payout scheduling
- commission_rate column on seller_transfers
- refund_deadline column on orders (14-day window)
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Add daily_track_stats, geographic_play_stats, track_discovery_sources tables.
Add source and country_code columns to track_plays.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
- Export: table data_exports, POST /me/export (202), GET /me/exports, messages+playback_history
- Notification email quand ZIP prêt, rate limit 3/jour
- Suppression: keep_public_tracks, anonymisation PII complète (users, user_profiles)
- HardDeleteWorker: final anonymization après 30 jours
- Frontend: POST export, checkbox keep_public_tracks
- MSW handlers pour Storybook
- PKCE (S256) in OAuth flow: code_verifier in oauth_states, code_challenge in auth URL
- CryptoService: AES-256-GCM encryption for OAuth provider tokens at rest
- OAuth redirect URL validated against OAUTH_ALLOWED_REDIRECT_DOMAINS
- CHAT_JWT_SECRET must differ from JWT_SECRET in production
- Migration script: cmd/tools/encrypt_oauth_tokens for existing tokens
- Fixes: VEZA-SEC-003, VEZA-SEC-004, VEZA-SEC-009, VEZA-SEC-010