From 6ca5339db90c8ea163f9edd6b6da6e2f13c3bf2c Mon Sep 17 00:00:00 2001 From: eazeeshow Date: Sat, 21 Nov 2026 16:22:07 +0100 Subject: [PATCH 1/4] fix(backend): single-writer top-ups and one error envelope #1848 - depositedAmount had two writers applying the same top-up: the API handler incremented and the Soroban indexer wrote the absolute on-chain value, with nothing joining them. Both now run inside one transaction, take the stream's row lock, and key on the same (transactionHash, TOPPED_UP) marker, so whichever commits second leaves the amount alone. The API's marker records ledgerSequence 0, which the indexer treats as "never confirmed" and reconciles against the event instead of skipping, so chain state stays authoritative in both arrival orders. endTime is projected by one shared helper on both paths, and backend/docs/TOP_UP_DEPOSITED_AMOUNT_REPAIR.md documents how to audit and repair the rows the old race already drifted. #1850 - topUpStreamHandler wrapped the chain call, the row lock and the bookkeeping in one catch that answered 400 TOP_UP_FAILED for all of them. Chain failures keep the 4xx; database and unexpected failures now surface as their own status (Prisma-mapped or 500 INTERNAL_SERVER_ERROR), and the `updatedStream!` assertion is gone because the writer returns the amount. #1851 - two ApiError classes with swapped constructor arguments plus five response shapes meant a caller could silently swap code and message. One ApiError(statusCode, code, message, details?) and one {error:{code,message, details?}} envelope remain; the unused RFC 7807 schema-validator middleware and its tests are deleted. BREAKING for API consumers: every 4xx/5xx body, including 429 rate limits and the CORS rejection, now uses that envelope. Also: stream-lifecycle and cancel-status-filter wiped the whole Stream table in their fixtures. Both files run in parallel against one database, so each deleted the other's rows mid-assertion; their cleanup is now scoped to the streams they own. --- .../docs/TOP_UP_DEPOSITED_AMOUNT_REPAIR.md | 238 ++++++++++ backend/src/app.ts | 3 +- backend/src/controllers/admin.controller.ts | 65 +-- .../src/controllers/analytics.controller.ts | 2 +- backend/src/controllers/sse.controller.ts | 25 +- backend/src/controllers/stream.controller.ts | 74 ++-- backend/src/controllers/stream/cancel.ts | 2 +- backend/src/controllers/stream/simulate.ts | 25 +- backend/src/controllers/token.controller.ts | 2 +- backend/src/controllers/user.controller.ts | 6 +- backend/src/controllers/webhook.controller.ts | 65 ++- backend/src/lib/api-error.ts | 134 +++--- .../src/middleware/api-version.middleware.ts | 13 +- backend/src/middleware/auth.ts | 21 +- .../src/middleware/compliance.middleware.ts | 24 +- backend/src/middleware/error.middleware.ts | 87 ++-- .../src/middleware/rate-limiter.middleware.ts | 38 +- backend/src/middleware/sandbox.middleware.ts | 26 +- .../middleware/schema-validator.middleware.ts | 94 ---- .../stream-rate-limiter.middleware.ts | 10 +- backend/src/routes/metrics.routes.ts | 7 +- backend/src/routes/v1/admin.routes.ts | 13 +- backend/src/routes/v1/compliance.routes.ts | 2 +- backend/src/routes/v1/events.routes.ts | 9 +- backend/src/routes/v1/notifications.routes.ts | 11 +- backend/src/routes/v1/streams/withdraw.ts | 2 +- backend/src/routes/v1/token.routes.ts | 2 +- backend/src/services/export.service.ts | 5 +- backend/src/services/sorobanService.ts | 26 +- .../src/services/token-registry.service.ts | 2 +- backend/src/services/top-up-projection.ts | 43 ++ backend/src/services/top-up-writer.ts | 187 ++++++++ backend/src/types/api-error.ts | 33 -- backend/src/workers/soroban-event-worker.ts | 78 +--- backend/tests/api-error.test.ts | 48 +-- backend/tests/auth.test.ts | 20 +- backend/tests/compliance.test.ts | 8 +- backend/tests/cors.test.ts | 6 +- backend/tests/error.middleware.test.ts | 4 +- .../integration/admin-dead-letter.test.ts | 22 +- .../tests/integration/admin-metrics.test.ts | 16 +- .../integration/cancel-status-filter.test.ts | 10 +- backend/tests/integration/events-list.test.ts | 4 +- .../tests/integration/sse-subscribe.test.ts | 4 +- .../tests/integration/stream-actions.test.ts | 3 +- .../integration/stream-lifecycle.test.ts | 23 +- backend/tests/integration/top-up.test.ts | 407 ++++++++++++------ backend/tests/soroban-event-worker.test.ts | 8 +- backend/tests/sse.controller.test.ts | 12 +- backend/tests/stream-rate-limiter.test.ts | 12 +- backend/tests/stream-simulation.test.ts | 22 +- backend/tests/unit/validation.test.ts | 82 ---- frontend/src/lib/api/webhooks.test.ts | 2 +- frontend/src/lib/api/webhooks.ts | 6 +- 54 files changed, 1309 insertions(+), 784 deletions(-) create mode 100644 backend/docs/TOP_UP_DEPOSITED_AMOUNT_REPAIR.md delete mode 100644 backend/src/middleware/schema-validator.middleware.ts create mode 100644 backend/src/services/top-up-projection.ts create mode 100644 backend/src/services/top-up-writer.ts delete mode 100644 backend/src/types/api-error.ts diff --git a/backend/docs/TOP_UP_DEPOSITED_AMOUNT_REPAIR.md b/backend/docs/TOP_UP_DEPOSITED_AMOUNT_REPAIR.md new file mode 100644 index 00000000..e8fa37e5 --- /dev/null +++ b/backend/docs/TOP_UP_DEPOSITED_AMOUNT_REPAIR.md @@ -0,0 +1,238 @@ +# Repairing Overcounted `depositedAmount` (Issue #1848) + +## Background + +`depositedAmount` had two independent writers applying the same top-up: + +| Writer | Location | Semantics | +| --- | --- | --- | +| API handler | `backend/src/controllers/stream.controller.ts` (`topUpStreamHandler`) | relative: `depositedAmount + amount` | +| Event indexer | `backend/src/workers/soroban-event-worker.ts` (`handleStreamToppedUp`) | absolute: `new_deposited_amount` from the `StreamToppedUp` event | + +The handler wrote no `TOPPED_UP` row, so the indexer's dedup key +(`@@unique([transactionHash, eventType])`) never covered it. `topUpStream` awaits +`pollTransactionStatus`, which confirms the transaction on-chain — so the indexer +could commit its absolute value first and the handler would then add the same +amount a second time. The stream ends up permanently overcounted, and `endTime` — +which both writers project as `startTime + depositedAmount / ratePerSecond + +totalPausedDuration` — drifts later by the same amount. + +The fix makes the handler write inside one transaction that takes a `FOR UPDATE` +lock on the `Stream` row and records the same `TOPPED_UP` marker the indexer keys +on, so exactly one of the two writers moves `depositedAmount` in either arrival +order. This document covers the rows that were already wrong before the fix +shipped. + +## What the event log can and cannot prove + +`StreamEvent` is the ledger of record for deposits: + +- one `CREATED` row per stream, whose `amount` is the initial deposit + (`deposited_amount` from the on-chain `StreamCreated` event); +- one `TOPPED_UP` row per top-up transaction hash, whose `amount` is that + top-up. + +Because the contract's `new_deposited_amount` is the running sum of exactly those +events, the authoritative value for a stream is: + +``` +expected = CREATED.amount + Σ TOPPED_UP.amount +``` + +Two caveats decide when that is safe to write back: + +1. **The indexer must have caught up.** A top-up whose transaction landed + seconds ago legitimately has `depositedAmount > expected` — the handler + applied it and the event has not been indexed yet. Re-derive only after the + indexer has reached a ledger at or beyond that transaction. +2. **Negative deltas mean the log is incomplete, not that the row is low.** If + the event index is missing a `TOPPED_UP` (a stream created before the event + backfill, or a pruned row), the repair would *reduce* a correct balance. + Never apply a downward-only shortcut; reconcile against the on-chain value + instead (see "Escalation"). + +## Step 1 — Audit (read-only) + +Run against a replica first. `depositedAmount` and `amount` are `text` columns +holding i128 values, so aggregate in `numeric`, not `bigint` — `bigint` overflows +above ~9.2e18, which is exactly the range an i128 token amount can reach. + +```sql +WITH ledger AS ( + SELECT + "streamId", + SUM( + CASE WHEN "eventType" = 'CREATED' THEN COALESCE("amount", '0')::numeric ELSE 0 END + ) AS initial_deposit, + SUM( + CASE WHEN "eventType" = 'TOPPED_UP' THEN COALESCE("amount", '0')::numeric ELSE 0 END + ) AS topped_up + FROM "StreamEvent" + WHERE "eventType" IN ('CREATED', 'TOPPED_UP') + GROUP BY "streamId" +) +SELECT + s."streamId", + s."depositedAmount"::numeric AS stored, + l.initial_deposit + l.topped_up AS expected, + s."depositedAmount"::numeric - (l.initial_deposit + l.topped_up) AS drift, + s."ratePerSecond"::numeric, + s."endTime", + s."isActive", + s."isPaused", + (SELECT MAX("ledgerSequence") FROM "StreamEvent" WHERE "streamId" = s."streamId") AS last_event_ledger +FROM "Stream" s +JOIN ledger l ON l."streamId" = s."streamId" +WHERE s."depositedAmount"::numeric <> l.initial_deposit + l.topped_up +ORDER BY abs(s."depositedAmount"::numeric - (l.initial_deposit + l.topped_up)) DESC; +``` + +Read the result three ways: + +- `drift > 0` and the stream's `last_event_ledger` is behind the indexer's + current position → **in-flight top-up**, not a bug. Re-check after the next + indexer run. +- `drift > 0` with no in-flight top-up → **double-counted by this bug**. +- `drift < 0` → **the event log is incomplete**; escalate, do not write. + +Compare `IndexerState.lastLedger` against each row's `last_event_ledger` before +concluding anything. + +## Step 2 — Repair + +Wrap the whole repair in a transaction and take the same row lock the writers +take, so a live top-up cannot interleave with it. Capture the pre-repair values +first; the audit is not reproducible once the rows are overwritten. + +The script writes every row it touches into this table before and after the +change, so the run is auditable and reversible one stream at a time. + +```sql +CREATE TABLE IF NOT EXISTS "TopUpRepairAudit_1848" ( + "streamId" BIGINT NOT NULL, + "before" TEXT NOT NULL, + "after" TEXT NOT NULL, + "drift" NUMERIC NOT NULL, + "repairedAt" TIMESTAMPTZ NOT NULL DEFAULT now() +); +``` + +Per stream, in one transaction (repeat for every `drift > 0` row from Step 1). +`:streamId` is the only input; the script captures each result and feeds it to +the next statement, which is what makes the run reversible one stream at a time. + +```sql +BEGIN; + +-- 1. Take the same row lock the API handler and the indexer take, so a live +-- top-up cannot interleave with the repair. Keep the value: it becomes the +-- audit row's `before`. If this blocks, a top-up is in flight for this +-- stream - skip it and re-audit later. +SELECT "depositedAmount" + FROM "Stream" + WHERE "streamId" = :streamId + FOR UPDATE; + +-- 2. Re-derive from the event log and write. Guarded so it can only lower a +-- balance this bug raised, and so it no-ops if the row is already correct. +WITH ledger AS ( + SELECT COALESCE(SUM(CASE WHEN "eventType" = 'CREATED' + THEN COALESCE("amount", '0')::numeric END), 0) + + COALESCE(SUM(CASE WHEN "eventType" = 'TOPPED_UP' + THEN COALESCE("amount", '0')::numeric END), 0) AS expected + FROM "StreamEvent" + WHERE "streamId" = :streamId + AND "eventType" IN ('CREATED', 'TOPPED_UP') +) +UPDATE "Stream" s + SET "depositedAmount" = l.expected::text, + "endTime" = CASE + WHEN s."ratePerSecond"::numeric = 0 THEN s."endTime" + ELSE s."startTime" + + div(l.expected, s."ratePerSecond"::numeric)::bigint + + s."totalPausedDuration"::bigint + END + FROM ledger l + WHERE s."streamId" = :streamId + AND l.expected > 0 + AND s."depositedAmount"::numeric > l.expected +RETURNING "depositedAmount"; + +-- 3. Record the pair. Zero rows from step 2 means nothing changed; do not write +-- an audit row for it. +INSERT INTO "TopUpRepairAudit_1848" ("streamId", "before", "after", "drift") +VALUES (:streamId, :before, :after, :before::numeric - :after::numeric); + +COMMIT; +``` + +Three deliberate constraints: + +- **`div(numeric, numeric)`, not `/` then `::bigint`.** `div` truncates toward + zero, which is exactly the `BigInt` division in `projectedEndTime` + (`backend/src/services/top-up-projection.ts`). Casting a `numeric` quotient to + `bigint` *rounds*, and a one-second difference here re-creates the drift this + repair exists to remove. +- **`AND s."depositedAmount" > l.expected` — the repair only lowers balances.** + This bug could only raise them. A row with the opposite sign is an indexer gap + and belongs in Escalation, not here. +- **One stream per transaction.** A single bad row rolls back one stream instead + of the batch, and the `FOR UPDATE` hold stays short. + +`endTime` is rewritten in the same statement because both writers projected it +from the overcounted value. + +## Step 3 — Verify + +```sql +-- 1. No positive drift remains outside the indexer-lag window. +SELECT count(*) FROM "Stream" s +JOIN ( + SELECT "streamId", + SUM(COALESCE("amount", '0')::numeric) AS expected + FROM "StreamEvent" + WHERE "eventType" IN ('CREATED', 'TOPPED_UP') + GROUP BY "streamId" +) l ON l."streamId" = s."streamId" +WHERE s."depositedAmount"::numeric > l.expected; + +-- 2. `endTime` agrees with the projection for every non-zero-rate stream. +SELECT s."streamId", s."endTime", + s."startTime" + (s."depositedAmount"::bigint / s."ratePerSecond"::bigint) + + s."totalPausedDuration"::bigint AS projected +FROM "Stream" s +WHERE s."ratePerSecond"::numeric <> '0' + AND s."endTime" IS DISTINCT FROM + s."startTime" + (s."depositedAmount"::bigint / s."ratePerSecond"::bigint) + + s."totalPausedDuration"::bigint; +``` + +Query 2 uses `::bigint` and so is a spot-check, not a proof, for streams whose +amounts exceed bigint range; for those, compute the projection in the script with +`BigInt` and compare in application code. + +Then confirm on chain that `get_stream(streamId).deposited_amount` equals the +repaired `depositedAmount` for every row in the audit table. The chain is the +only witness the indexer's absolute write trusts, so it is the only acceptable +final check. + +## Escalation: negative drift + +`depositedAmount < expected` means the event log holds a top-up the row never +received, or a row is missing a `CREATED` event. Both are indexer gaps, not this +bug, and re-deriving from the log would corrupt a balance that the chain says is +right. For those streams: + +1. read `deposited_amount` from the contract with `getStreamFromChain`, +2. write that value plus the projected `endTime` by hand, +3. file a separate issue — do not fold the fix into this repair. + +## Timing + +Run the audit read-only first and share the row count. Apply during a window +where the indexer is paused, or the set of "in-flight" false positives keeps +moving and the run is not reproducible. To pause it, stop +`soroban-event-worker`; the API is unaffected apart from stream projections +lagging. Restart it after the repair and re-run Step 3 — the absolute writes are +idempotent per event hash, so the indexer cannot reintroduce the double count +once the fix is deployed. diff --git a/backend/src/app.ts b/backend/src/app.ts index 24fc8261..89aa52ce 100644 --- a/backend/src/app.ts +++ b/backend/src/app.ts @@ -17,6 +17,7 @@ import { requestIdMiddleware } from "./middleware/requestId.js"; import { buildCorsOptions, CorsError } from "./config/cors.js"; import logger from "./logger.js"; import { bigIntSafeJsonMiddleware } from "./lib/serialize.js"; +import { sendApiError } from "./lib/api-error.js"; import v1Routes from "./routes/v1/index.js"; import healthRoutes from "./routes/health.routes.js"; import metricsRoutes from "./routes/metrics.routes.js"; @@ -77,7 +78,7 @@ app.use((err: unknown, req: Request, res: Response, next: NextFunction) => { method: req.method, path: req.path, }); - res.status(err.statusCode).json({ error: err.message }); + sendApiError(res, err.statusCode, "FORBIDDEN", err.message); return; } next(err); diff --git a/backend/src/controllers/admin.controller.ts b/backend/src/controllers/admin.controller.ts index 333f7309..6ed60450 100644 --- a/backend/src/controllers/admin.controller.ts +++ b/backend/src/controllers/admin.controller.ts @@ -14,6 +14,7 @@ import { isSentinelSeverity, } from '../services/sentinel.service.js'; import logger from '../logger.js'; +import { sendApiError } from '../lib/api-error.js'; /** Parse an optional positive-integer query param. */ function parseOptionalInt(raw: unknown): number | undefined { @@ -53,9 +54,12 @@ export const listSentinelAlertsHandler = async (req: Request, res: Response) => const severity = rawSeverity && isSentinelSeverity(rawSeverity) ? rawSeverity : undefined; if (rawSeverity && !severity) { - return res.status(400).json({ - error: 'severity must be one of LOW, MEDIUM, HIGH, CRITICAL', - }); + return sendApiError( + res, + 400, + 'BAD_REQUEST', + 'severity must be one of LOW, MEDIUM, HIGH, CRITICAL', + ); } const limit = parseOptionalInt(readSingleQueryParam(req.query.limit)); @@ -78,7 +82,7 @@ export const listSentinelAlertsHandler = async (req: Request, res: Response) => }); } catch (err) { logger.error('[AdminController] Failed to list sentinel alerts:', err); - return res.status(500).json({ error: 'Failed to list sentinel alerts' }); + return sendApiError(res, 500, 'INTERNAL_SERVER_ERROR', 'Failed to list sentinel alerts'); } }; @@ -95,12 +99,12 @@ export const acknowledgeSentinelAlertHandler = async ( const rawId = req.params.id; const id = Array.isArray(rawId) ? rawId[0] : rawId; if (!id) { - return res.status(400).json({ error: 'id is required' }); + return sendApiError(res, 400, 'BAD_REQUEST', 'id is required'); } const acknowledged = getSentinelService().acknowledgeAlert(id); if (!acknowledged) { - return res.status(404).json({ error: 'Sentinel incident not found' }); + return sendApiError(res, 404, 'NOT_FOUND', 'Sentinel incident not found'); } return res.status(200).json({ ok: true, id, acknowledged: true }); }; @@ -123,7 +127,7 @@ export const listDeadLetterHandler = async (req: Request, res: Response) => { 'startDate', ); if (startDate.error) { - return res.status(400).json({ error: startDate.error }); + return sendApiError(res, 400, 'BAD_REQUEST', startDate.error); } const endDate = parseOptionalDate( @@ -131,11 +135,11 @@ export const listDeadLetterHandler = async (req: Request, res: Response) => { 'endDate', ); if (endDate.error) { - return res.status(400).json({ error: endDate.error }); + return sendApiError(res, 400, 'BAD_REQUEST', endDate.error); } if (startDate.value && endDate.value && startDate.value > endDate.value) { - return res.status(400).json({ error: 'startDate must be before endDate' }); + return sendApiError(res, 400, 'BAD_REQUEST', 'startDate must be before endDate'); } try { @@ -156,7 +160,7 @@ export const listDeadLetterHandler = async (req: Request, res: Response) => { return res.status(200).json(result); } catch (err) { logger.error('[AdminController] Failed to list dead-letter events:', err); - return res.status(500).json({ error: 'Failed to list dead-letter events' }); + return sendApiError(res, 500, 'INTERNAL_SERVER_ERROR', 'Failed to list dead-letter events'); } }; @@ -171,33 +175,34 @@ export const replayDeadLetterHandler = async (req: Request, res: Response) => { const rawId = req.params.id; const id = Array.isArray(rawId) ? rawId[0] : rawId; if (!id) { - return res.status(400).json({ error: 'id is required' }); + return sendApiError(res, 400, 'BAD_REQUEST', 'id is required'); } try { const result = await replayDeadLetterEvent(id); if (result.outcome === 'not_found') { - return res.status(404).json({ error: 'Dead-letter event not found' }); + return sendApiError(res, 404, 'DEAD_LETTER_NOT_FOUND', 'Dead-letter event not found'); } if (result.outcome === 'undecodable') { - return res.status(422).json({ - error: 'Dead-letter payload could not be decoded', - code: 'undecodable_payload', - id, - errorMessage: result.errorMessage, - }); + return sendApiError( + res, + 422, + 'undecodable_payload', + 'Dead-letter payload could not be decoded', + { id, errorMessage: result.errorMessage }, + ); } if (result.outcome === 'failed') { - return res.status(422).json({ - error: 'Replay failed; the event remains quarantined', - code: 'replay_failed', - id, - attempts: result.attempts, - errorMessage: result.errorMessage, - }); + return sendApiError( + res, + 422, + 'replay_failed', + 'Replay failed; the event remains quarantined', + { id, attempts: result.attempts, errorMessage: result.errorMessage }, + ); } return res.status(200).json({ @@ -208,7 +213,7 @@ export const replayDeadLetterHandler = async (req: Request, res: Response) => { }); } catch (err) { logger.error(`[AdminController] Replay of dead-letter ${id} threw:`, err); - return res.status(500).json({ error: 'Replay failed' }); + return sendApiError(res, 500, 'INTERNAL_SERVER_ERROR', 'Replay failed'); } }; @@ -223,7 +228,7 @@ export const replayAllDeadLetterHandler = async (_req: Request, res: Response) = return res.status(200).json({ ok: true, ...summary }); } catch (err) { logger.error('[AdminController] Dead-letter replay-all threw:', err); - return res.status(500).json({ error: 'Replay-all failed' }); + return sendApiError(res, 500, 'INTERNAL_SERVER_ERROR', 'Replay-all failed'); } }; @@ -237,16 +242,16 @@ export const discardDeadLetterHandler = async (req: Request, res: Response) => { const rawId = req.params.id; const id = Array.isArray(rawId) ? rawId[0] : rawId; if (!id) { - return res.status(400).json({ error: 'id is required' }); + return sendApiError(res, 400, 'BAD_REQUEST', 'id is required'); } const discardedBy = (req as AuthenticatedRequest).user?.publicKey ?? 'unknown'; try { const discarded = await discardDeadLetterEvent(id, discardedBy); return res.status(200).json({ ok: true, discarded }); } catch (err) { if (err instanceof DeadLetterNotFoundError) { - return res.status(404).json({ error: 'Dead-letter event not found' }); + return sendApiError(res, 404, 'DEAD_LETTER_NOT_FOUND', 'Dead-letter event not found'); } logger.error(`[AdminController] Discard of dead-letter ${id} threw:`, err); - return res.status(500).json({ error: 'Discard failed' }); + return sendApiError(res, 500, 'INTERNAL_SERVER_ERROR', 'Discard failed'); } }; diff --git a/backend/src/controllers/analytics.controller.ts b/backend/src/controllers/analytics.controller.ts index 96dfbb88..2dad9e52 100644 --- a/backend/src/controllers/analytics.controller.ts +++ b/backend/src/controllers/analytics.controller.ts @@ -14,7 +14,7 @@ import { type AnalyticsInterval, type AnalyticsPeriod, } from "../services/analytics.service.js"; -import { sendApiError } from "../types/api-error.js"; +import { sendApiError } from "../lib/api-error.js"; import logger from "../logger.js"; const VALID_PERIODS: AnalyticsPeriod[] = ["7d", "30d", "90d", "1y"]; diff --git a/backend/src/controllers/sse.controller.ts b/backend/src/controllers/sse.controller.ts index fcc813d1..4ff5aaeb 100644 --- a/backend/src/controllers/sse.controller.ts +++ b/backend/src/controllers/sse.controller.ts @@ -5,6 +5,7 @@ import { prisma } from '../lib/prisma.js'; import { requestContext } from '../logger.js'; import type { AuthenticatedRequest } from '../types/auth.types.js'; import { isSandboxRequest } from '../middleware/sandbox.middleware.js'; +import { sendApiError } from '../lib/api-error.js'; import { z } from 'zod'; const subscribeSchema = z.object({ @@ -36,7 +37,7 @@ function getClientIp(req: Request): string { } export const subscribe = async (req: Request, res: Response) => { if (sseService.isShuttingDown()) { - return res.status(503).json({ message: 'Server is shutting down, please reconnect shortly.' }); + return sendApiError(res, 503, 'SERVICE_UNAVAILABLE', 'Server is shutting down, please reconnect shortly.'); } try { @@ -47,9 +48,12 @@ export const subscribe = async (req: Request, res: Response) => { if (capacity.retryAfterSeconds) { res.setHeader('Retry-After', String(capacity.retryAfterSeconds)); } - return res.status(capacity.status ?? 503).json({ - message: capacity.message ?? 'SSE connection rejected', - }); + return sendApiError( + res, + capacity.status ?? 503, + 'SSE_CONNECTION_REJECTED', + capacity.message ?? 'SSE connection rejected', + ); } const { publicKey } = (req as AuthenticatedRequest).user; @@ -116,11 +120,14 @@ export const subscribe = async (req: Request, res: Response) => { return; } catch (error: unknown) { if (error instanceof z.ZodError) { - return res.status(400).json({ - message: 'Invalid subscription parameters', - errors: error.issues, - }); + return sendApiError( + res, + 400, + 'VALIDATION_ERROR', + 'Invalid subscription parameters', + error.issues, + ); } - return res.status(500).json({ message: 'Internal server error' }); + return sendApiError(res, 500, 'INTERNAL_SERVER_ERROR', 'Internal server error'); } }; diff --git a/backend/src/controllers/stream.controller.ts b/backend/src/controllers/stream.controller.ts index 8ec104ed..389beafc 100644 --- a/backend/src/controllers/stream.controller.ts +++ b/backend/src/controllers/stream.controller.ts @@ -14,13 +14,14 @@ import { } from "../services/sorobanService.js"; import type { AuthenticatedRequest } from "../types/auth.types.js"; import { parseStreamId } from "../lib/stream-id.js"; +import { applyTopUpOnce } from "../services/top-up-writer.js"; import { createStreamSchema, parsePagination } from "../validators/stream.validator.js"; import { DEFAULT_EVENTS_PAGE_SIZE, MAX_EVENTS_PAGE_SIZE, } from "../repositories/streamEvent.repository.js"; import { findStreams } from "../repositories/stream.repository.js"; -import { sendApiError } from "../types/api-error.js"; +import { ApiError, fromPrismaError, sendApiError } from "../lib/api-error.js"; const DEFAULT_STREAM_PAGE_SIZE = 20; const MAX_STREAM_PAGE_SIZE = 100; @@ -132,10 +133,13 @@ export const createStream = async (req: Request, res: Response) => { const chainStream = await getStreamFromChain(parsedStreamId); if (!chainStream) { - return res.status(409).json({ - error: "Stream has not been confirmed on-chain", - message: "Submit the stream creation transaction and retry after confirmation.", - }); + return sendApiError( + res, + 409, + "STREAM_NOT_CONFIRMED", + "Stream has not been confirmed on-chain", + { hint: "Submit the stream creation transaction and retry after confirmation." }, + ); } if ( @@ -146,9 +150,12 @@ export const createStream = async (req: Request, res: Response) => { chainStream.depositedAmount !== parsedDepositedAmount.toString() || chainStream.startTime !== parsedStartTime ) { - return res.status(409).json({ - error: "Stream request does not match on-chain state", - }); + return sendApiError( + res, + 409, + "STREAM_STATE_MISMATCH", + "Stream request does not match on-chain state", + ); } const endTime = @@ -706,29 +713,44 @@ export const topUpStreamHandler = async (req: Request, res: Response) => { return sendApiError(res, 409, "CONFLICT", "Cannot top up a paused stream"); } - const txHash = await topUpStream(streamId, amount, callerAddress); - - // Use raw SQL atomic increment to prevent concurrent top-ups from - // overwriting each other's updates (Issue #1217 — read-compute-write race). - // Prisma's built-in { increment } is unavailable on String-typed columns, - // so we perform SET deposited_amount = deposited_amount + $1::bigint - // directly in a single SQL statement. - const now = BigInt(Math.floor(Date.now() / 1000)); - await prisma.$executeRawUnsafe( - `UPDATE "Stream" SET "depositedAmount" = ("depositedAmount"::bigint + $1::bigint)::text, "lastUpdateTime" = $2 WHERE "streamId" = $3`, - amount.toString(), - now, - streamId, + let txHash: string; + try { + txHash = await topUpStream(streamId, amount, callerAddress); + } catch (chainError) { + // A failure here is the caller's transaction not landing: a reverted + // contract call, a missing trustline, insufficient balance. Nothing was + // written, so a 4xx is the honest answer. + logger.error(`[topUp] stream=${streamId} on-chain call failed:`, chainError); + return sendApiError(res, 400, "TOP_UP_FAILED", "Failed to top up stream on chain"); + } + + // #1848: the indexer's `handleStreamToppedUp` writes the same top-up from + // the on-chain event, so this write is conditional on that event row not + // existing yet and holds the stream's row lock while it decides. Exactly + // one of the two writers moves `depositedAmount`, in either arrival order. + const depositedAmount = await prisma.$transaction((tx) => + applyTopUpOnce(tx, { streamId, txHash, amount }), ); - const updatedStream = await prisma.stream.findUnique({ where: { streamId } }); logger.info(`[topUp] stream=${streamId} amount=${amount} txHash=${txHash}`); return res .status(200) - .json({ streamId, txHash, depositedAmount: updatedStream!.depositedAmount }); - } catch (error: any) { - logger.error(`[topUp] stream=${streamId} error:`, error); - return sendApiError(res, 400, "TOP_UP_FAILED", "Failed to top up stream on chain"); + .json({ streamId, txHash, depositedAmount: depositedAmount.toString() }); + } catch (error) { + // Reaching this catch means the top-up question is already settled — the + // chain call either failed (handled above) or succeeded and this is the + // bookkeeping. A database outage is not the client's error, so it must not + // be reported as TOP_UP_FAILED: they would retry and pay twice. The + // indexer reconciles the row from the confirmed event. + logger.error(`[topUp] stream=${streamId} database update failed:`, error); + if (error instanceof ApiError) { + return sendApiError(res, error.statusCode, error.code, error.message, error.details); + } + const mapped = fromPrismaError(error); + if (mapped) { + return sendApiError(res, mapped.statusCode, mapped.code, mapped.message); + } + return sendApiError(res, 500, "INTERNAL_SERVER_ERROR", "A technical error occurred. Please try again later."); } }; diff --git a/backend/src/controllers/stream/cancel.ts b/backend/src/controllers/stream/cancel.ts index 8fd7cbb3..e8324504 100644 --- a/backend/src/controllers/stream/cancel.ts +++ b/backend/src/controllers/stream/cancel.ts @@ -5,7 +5,7 @@ import * as sorobanService from '../../services/sorobanService.js'; import type { AuthenticatedRequest } from '../../types/auth.types.js'; import * as streamRepository from '../../repositories/stream.repository.js'; import { parseStreamId } from '../../lib/stream-id.js'; -import { sendApiError } from '../../types/api-error.js'; +import { sendApiError } from '../../lib/api-error.js'; /** * @openapi diff --git a/backend/src/controllers/stream/simulate.ts b/backend/src/controllers/stream/simulate.ts index efc78abb..cda637da 100644 --- a/backend/src/controllers/stream/simulate.ts +++ b/backend/src/controllers/stream/simulate.ts @@ -1,6 +1,6 @@ import type { Request, Response } from 'express'; import { z } from 'zod'; -import { ApiError } from '../../lib/api-error.js'; +import { ApiError, sendApiError } from '../../lib/api-error.js'; import logger from '../../logger.js'; import { simulateStreamAction, type StreamAction } from '../../services/sorobanService.js'; @@ -65,11 +65,13 @@ const simulateBodySchema = z.object({ export const simulateStreamHandler = async (req: Request, res: Response) => { const parsed = simulateBodySchema.safeParse(req.body); if (!parsed.success) { - return res.status(400).json({ - error: 'Validation error', - code: 'invalid_params', - details: parsed.error.issues, - }); + return sendApiError( + res, + 400, + 'invalid_params', + 'Validation error', + parsed.error.issues, + ); } const { action, senderPublicKey, params } = parsed.data; @@ -79,17 +81,10 @@ export const simulateStreamHandler = async (req: Request, res: Response) => { return res.status(200).json({ success: true, data }); } catch (err) { if (err instanceof ApiError) { - return res.status(err.status).json({ - error: err.message, - code: err.code, - ...(err.details ? { details: err.details } : {}), - }); + return sendApiError(res, err.statusCode, err.code, err.message, err.details); } logger.error(`[simulate] Unexpected failure for action ${action}:`, err); - return res.status(500).json({ - error: 'Simulation failed', - code: 'simulation_error', - }); + return sendApiError(res, 500, 'simulation_error', 'Simulation failed'); } }; diff --git a/backend/src/controllers/token.controller.ts b/backend/src/controllers/token.controller.ts index fe00789d..dcfe59e7 100644 --- a/backend/src/controllers/token.controller.ts +++ b/backend/src/controllers/token.controller.ts @@ -1,6 +1,6 @@ import type { Request, Response } from 'express'; import { getTokenMetadata, listVerifiedTokens } from '../services/token-registry.service.js'; -import { sendApiError } from '../types/api-error.js'; +import { sendApiError } from '../lib/api-error.js'; import type { TokenMetadata as RegistryTokenMetadata } from '../services/token-registry.service.js'; export function toPublicTokenMetadata(token: RegistryTokenMetadata) { diff --git a/backend/src/controllers/user.controller.ts b/backend/src/controllers/user.controller.ts index 15c79d8b..eb0d64cb 100644 --- a/backend/src/controllers/user.controller.ts +++ b/backend/src/controllers/user.controller.ts @@ -13,7 +13,7 @@ import { resolveEventsPageSize, } from "../repositories/streamEvent.repository.js"; import * as exportService from "../services/export.service.js"; -import { sendApiError } from "../types/api-error.js"; +import { sendApiError } from "../lib/api-error.js"; /** * Public shape of a Stream, used when embedding streams inside a public @@ -177,9 +177,7 @@ export const getUserEvents = async ( const { requested, types } = parseEventTypeFilter(req.query["type"]); if (requested.length > 0 && types.length === 0) { - return res - .status(400) - .json({ error: "No valid event types in `type` filter" }); + return sendApiError(res, 400, "BAD_REQUEST", "No valid event types in `type` filter"); } const limit = resolveEventsPageSize(req.query["limit"]); diff --git a/backend/src/controllers/webhook.controller.ts b/backend/src/controllers/webhook.controller.ts index 7af0d37e..7637314a 100644 --- a/backend/src/controllers/webhook.controller.ts +++ b/backend/src/controllers/webhook.controller.ts @@ -4,6 +4,7 @@ import type { Request, Response } from "express"; import * as webhookService from "../services/webhook.service.js"; import logger from "../logger.js"; +import { sendApiError } from "../lib/api-error.js"; export async function createWebhook( req: Request, @@ -13,9 +14,12 @@ export async function createWebhook( const { userAddress, targetUrl, eventTypes } = req.body; if (!userAddress || !targetUrl || !Array.isArray(eventTypes)) { - res.status(400).json({ - error: "Missing required fields: userAddress, targetUrl, eventTypes", - }); + sendApiError( + res, + 400, + "WEBHOOK_INVALID_REQUEST", + "Missing required fields: userAddress, targetUrl, eventTypes", + ); return; } @@ -35,9 +39,12 @@ export async function createWebhook( }); } catch (error: any) { logger.error("[Webhook Controller] Create error:", error); - res - .status(500) - .json({ error: error.message || "Failed to create webhook" }); + sendApiError( + res, + 500, + "INTERNAL_SERVER_ERROR", + error.message || "Failed to create webhook", + ); } } @@ -46,7 +53,7 @@ export async function listWebhooks(req: Request, res: Response): Promise { const { userAddress } = req.query; if (!userAddress || typeof userAddress !== "string") { - res.status(400).json({ error: "userAddress query parameter required" }); + sendApiError(res, 400, "WEBHOOK_INVALID_REQUEST", "userAddress query parameter required"); return; } @@ -61,7 +68,7 @@ export async function listWebhooks(req: Request, res: Response): Promise { res.json({ subscriptions: safeSubscriptions }); } catch (error: any) { logger.error("[Webhook Controller] List error:", error); - res.status(500).json({ error: "Failed to list webhooks" }); + sendApiError(res, 500, "INTERNAL_SERVER_ERROR", "Failed to list webhooks"); } } @@ -75,7 +82,7 @@ export async function deleteWebhook( const { userAddress } = req.query; if (!id || !userAddress || typeof userAddress !== "string") { - res.status(400).json({ error: "Invalid id or userAddress required" }); + sendApiError(res, 400, "WEBHOOK_INVALID_REQUEST", "Invalid id or userAddress required"); return; } @@ -84,7 +91,7 @@ export async function deleteWebhook( res.status(204).send(); } catch (error: any) { logger.error("[Webhook Controller] Delete error:", error); - res.status(500).json({ error: "Failed to delete webhook" }); + sendApiError(res, 500, "INTERNAL_SERVER_ERROR", "Failed to delete webhook"); } } @@ -93,13 +100,18 @@ export async function updateWebhook(req: Request, res: Response): Promise const id = Array.isArray(req.params.id) ? req.params.id[0] : req.params.id; const { userAddress } = req.query; if (!id || typeof userAddress !== "string") { - res.status(400).json({ error: "id and userAddress are required" }); + sendApiError(res, 400, "WEBHOOK_INVALID_REQUEST", "id and userAddress are required"); return; } const subscription = await webhookService.updateWebhookSubscription(id, userAddress, req.body); res.json(subscription); } catch (error: any) { - res.status(400).json({ error: error.message || "Failed to update webhook" }); + sendApiError( + res, + 400, + "WEBHOOK_INVALID_REQUEST", + error.message || "Failed to update webhook", + ); } } @@ -108,12 +120,17 @@ export async function listDeliveries(req: Request, res: Response): Promise const id = Array.isArray(req.params.id) ? req.params.id[0] : req.params.id; const { userAddress, page = "1", limit = "20" } = req.query; if (!id || typeof userAddress !== "string") { - res.status(400).json({ error: "id and userAddress are required" }); + sendApiError(res, 400, "WEBHOOK_INVALID_REQUEST", "id and userAddress are required"); return; } res.json(await webhookService.listWebhookDeliveries(id, userAddress, Number(page), Number(limit))); } catch (error: any) { - res.status(400).json({ error: error.message || "Failed to list webhook deliveries" }); + sendApiError( + res, + 400, + "WEBHOOK_INVALID_REQUEST", + error.message || "Failed to list webhook deliveries", + ); } } @@ -122,12 +139,17 @@ export async function regenerateSecret(req: Request, res: Response): Promise { const { userAddress } = req.body; if (!id || !userAddress) { - res.status(400).json({ error: "id and userAddress required" }); + sendApiError(res, 400, "WEBHOOK_INVALID_REQUEST", "id and userAddress required"); return; } @@ -150,8 +172,11 @@ export async function testWebhook(req: Request, res: Response): Promise { }); } catch (error: any) { logger.error("[Webhook Controller] Test error:", error); - res - .status(500) - .json({ error: error.message || "Failed to send test webhook" }); + sendApiError( + res, + 500, + "INTERNAL_SERVER_ERROR", + error.message || "Failed to send test webhook", + ); } } diff --git a/backend/src/lib/api-error.ts b/backend/src/lib/api-error.ts index df619367..0665ee12 100644 --- a/backend/src/lib/api-error.ts +++ b/backend/src/lib/api-error.ts @@ -1,34 +1,48 @@ +import type { Response } from 'express'; import { Prisma } from '../generated/prisma/index.js'; +/** + * The one error envelope every API response uses: + * + * ```json + * { "error": { "code": "STRING_CODE", "message": "human text", "details": ... } } + * ``` + */ +export interface ApiErrorBody { + code: string; + message: string; + details?: unknown; +} + /** * Typed application error carrying an HTTP status and optional machine-readable * remediation hints. * - * `errorHandler` reads `err.status`, so throwing an `ApiError` from anywhere in - * a handler chain produces the right status code without a try/catch at every - * call site. The optional `code` lets clients branch on the failure class rather - * than string-matching a message. + * The constructor order — `(statusCode, code, message, details)` — is identical + * to `sendApiError`, so a call site can move between throwing and responding + * without reordering arguments. `code` precedes `message` because `code` is what + * clients branch on and `message` is display text. + * + * `errorHandler` reads `err.statusCode`, so throwing an `ApiError` from anywhere + * in a handler chain produces the right status code without a try/catch at every + * call site. */ export class ApiError extends Error { - readonly status: number; + readonly statusCode: number; readonly code: string; - readonly details?: Record; + readonly details?: unknown; constructor( - status: number, + statusCode: number, + code: string, message: string, - code = 'api_error', - details?: Record, + details?: unknown, ) { super(message); this.name = 'ApiError'; - this.status = status; + this.statusCode = statusCode; this.code = code; - if (details !== undefined) this.details = details; - } - - get statusCode(): number { - return this.status; + this.details = details; } static fromPrismaError(err: unknown): ApiError | null { @@ -36,32 +50,48 @@ export class ApiError extends Error { } } -export const badRequest = (message: string, code = 'BAD_REQUEST', details?: Record) => - new ApiError(400, message, code, details); +/** + * Writes the standard error envelope. Every non-2xx REST response goes through + * this function so clients never have to branch on the shape of a failure. + */ +export function sendApiError( + res: Response, + statusCode: number, + code: string, + message: string, + details?: unknown, +) { + const error: ApiErrorBody = { code, message }; + if (details !== undefined) error.details = details; + return res.status(statusCode).json({ error }); +} + +export const badRequest = (message: string, code = 'BAD_REQUEST', details?: unknown) => + new ApiError(400, code, message, details); export const duplicateEntry = ( message = 'A record with this unique value already exists.', code = 'DUPLICATE_ENTRY', - details?: Record, -) => new ApiError(409, message, code, details); + details?: unknown, +) => new ApiError(409, code, message, details); export const resourceNotFound = ( message = 'The requested record was not found.', code = 'RESOURCE_NOT_FOUND', - details?: Record, -) => new ApiError(404, message, code, details); + details?: unknown, +) => new ApiError(404, code, message, details); export const foreignKeyViolation = ( message = 'Related resource constraint violation.', code = 'FOREIGN_KEY_VIOLATION', - details?: Record, -) => new ApiError(409, message, code, details); + details?: unknown, +) => new ApiError(409, code, message, details); export const internal = ( message = 'A technical error occurred. Please try again later.', code = 'INTERNAL_SERVER_ERROR', - details?: Record, -) => new ApiError(500, message, code, details); + details?: unknown, +) => new ApiError(500, code, message, details); /** * Check if an error appears to be an error originating from Prisma. @@ -119,45 +149,33 @@ export function fromPrismaError(err: unknown): ApiError | null { switch (code) { case 'P2002': // Unique constraint violation - NEVER leak meta.target, column names, or table names - return new ApiError( - 409, - 'A record with this unique value already exists.', - 'DUPLICATE_ENTRY', - ); + return duplicateEntry(); case 'P2001': case 'P2015': case 'P2018': case 'P2025': // Record not found - NEVER leak model name or search condition - return new ApiError( - 404, - 'The requested record was not found.', - 'RESOURCE_NOT_FOUND', - ); + return resourceNotFound(); case 'P2003': // Foreign key violation - NEVER leak meta.field_name or relation - return new ApiError( - 409, - 'Related resource constraint violation.', - 'FOREIGN_KEY_VIOLATION', - ); + return foreignKeyViolation(); case 'P2000': // Value too long for column return new ApiError( 400, - 'A provided value exceeds the allowable limit.', 'VALUE_OUT_OF_RANGE', + 'A provided value exceeds the allowable limit.', ); case 'P2004': // Database constraint failed return new ApiError( 400, - 'A database constraint was violated.', 'CONSTRAINT_FAILED', + 'A database constraint was violated.', ); case 'P2005': @@ -165,8 +183,8 @@ export function fromPrismaError(err: unknown): ApiError | null { // Invalid data for field type return new ApiError( 400, - 'Invalid data provided for one or more fields.', 'INVALID_INPUT', + 'Invalid data provided for one or more fields.', ); case 'P2011': @@ -175,8 +193,8 @@ export function fromPrismaError(err: unknown): ApiError | null { // Null or missing required field return new ApiError( 400, - 'A required field was not provided.', 'MISSING_REQUIRED_FIELD', + 'A required field was not provided.', ); case 'P2014': @@ -184,34 +202,22 @@ export function fromPrismaError(err: unknown): ApiError | null { // Relation violation return new ApiError( 409, - 'The requested operation violates a relation constraint.', 'RELATION_VIOLATION', + 'The requested operation violates a relation constraint.', ); case 'P2016': // Query interpretation error - return new ApiError( - 400, - 'Invalid query parameters.', - 'INVALID_QUERY', - ); + return new ApiError(400, 'INVALID_QUERY', 'Invalid query parameters.'); case 'P2021': case 'P2022': // Table or column does not exist - return new ApiError( - 500, - 'A technical error occurred. Please try again later.', - 'INTERNAL_SERVER_ERROR', - ); + return internal(); default: // Any other Prisma request errors (P2xxx, etc.) - return new ApiError( - 400, - 'A database error occurred.', - 'DATABASE_ERROR', - ); + return new ApiError(400, 'DATABASE_ERROR', 'A database error occurred.'); } } @@ -220,7 +226,7 @@ export function fromPrismaError(err: unknown): ApiError | null { err instanceof Prisma.PrismaClientValidationError || (err instanceof Error && err.name === 'PrismaClientValidationError') ) { - return new ApiError(400, 'Invalid request data.', 'VALIDATION_ERROR'); + return new ApiError(400, 'VALIDATION_ERROR', 'Invalid request data.'); } // Handle PrismaClientUnknownRequestError, RustPanic, InitializationError @@ -233,11 +239,7 @@ export function fromPrismaError(err: unknown): ApiError | null { err.name === 'PrismaClientRustPanicError' || err.name === 'PrismaClientInitializationError')) ) { - return new ApiError( - 500, - 'A technical error occurred. Please try again later.', - 'INTERNAL_SERVER_ERROR', - ); + return internal(); } return null; diff --git a/backend/src/middleware/api-version.middleware.ts b/backend/src/middleware/api-version.middleware.ts index 675aa852..937e848b 100644 --- a/backend/src/middleware/api-version.middleware.ts +++ b/backend/src/middleware/api-version.middleware.ts @@ -1,4 +1,5 @@ import type { Request, Response, NextFunction } from 'express'; +import { sendApiError } from '../lib/api-error.js'; /** * API Version middleware @@ -46,11 +47,13 @@ export function apiVersionMiddleware( req.url = newPath + (queryString ? '?' + queryString : ''); // Note: req.path is read-only, but req.url modification affects routing } else { - res.status(400).json({ - error: 'Unsupported API version', - message: `API version '${versionString}' is not supported. Supported versions: ${SUPPORTED_VERSIONS.join(', ')}`, - supportedVersions: SUPPORTED_VERSIONS, - }); + sendApiError( + res, + 400, + 'UNSUPPORTED_API_VERSION', + `API version '${versionString}' is not supported. Supported versions: ${SUPPORTED_VERSIONS.join(', ')}`, + { supportedVersions: SUPPORTED_VERSIONS }, + ); return; } } diff --git a/backend/src/middleware/auth.ts b/backend/src/middleware/auth.ts index ae519e89..feb31430 100644 --- a/backend/src/middleware/auth.ts +++ b/backend/src/middleware/auth.ts @@ -3,6 +3,7 @@ import * as crypto from 'crypto'; import * as StellarSdk from '@stellar/stellar-sdk'; import type { AuthenticatedRequest } from '../types/auth.types.js'; import logger from '../logger.js'; +import { sendApiError } from '../lib/api-error.js'; const isProduction = process.env.NODE_ENV === 'production'; const rawJwtSecret = process.env.JWT_SECRET; @@ -149,7 +150,7 @@ export function verifyJwt(token: string): { publicKey: string } | null { export function issueChallenge(req: Request, res: Response): void { const { publicKey } = req.body as { publicKey?: string }; if (!publicKey || !StellarSdk.StrKey.isValidEd25519PublicKey(publicKey)) { - res.status(400).json({ error: 'Invalid publicKey' }); + sendApiError(res, 400, 'BAD_REQUEST', 'Invalid publicKey'); return; } const nonce = crypto.randomBytes(32).toString('hex'); @@ -171,13 +172,13 @@ export function verifyChallenge(req: Request, res: Response): void { }; if (!publicKey || !signedTransaction) { - res.status(400).json({ error: 'publicKey and signedTransaction required' }); + sendApiError(res, 400, 'BAD_REQUEST', 'publicKey and signedTransaction required'); return; } const challenge = challenges.get(publicKey); if (!challenge || challenge.expiresAt < Date.now()) { - res.status(401).json({ error: 'Challenge expired or not found' }); + sendApiError(res, 401, 'UNAUTHORIZED', 'Challenge expired or not found'); return; } @@ -188,14 +189,14 @@ export function verifyChallenge(req: Request, res: Response): void { ) as StellarSdk.Transaction; if (tx.source !== publicKey) { - res.status(401).json({ error: 'Transaction source does not match publicKey' }); + sendApiError(res, 401, 'UNAUTHORIZED', 'Transaction source does not match publicKey'); return; } // Verify the manage_data op contains our nonce const op = tx.operations[0] as StellarSdk.Operation.ManageData | undefined; if (!op || op.type !== 'manageData' || Buffer.from(op.value ?? new Uint8Array()).toString('hex') !== challenge.nonce) { - res.status(401).json({ error: 'Invalid challenge nonce in transaction' }); + sendApiError(res, 401, 'UNAUTHORIZED', 'Invalid challenge nonce in transaction'); return; } @@ -206,7 +207,7 @@ export function verifyChallenge(req: Request, res: Response): void { }); if (!valid) { - res.status(401).json({ error: 'Invalid signature' }); + sendApiError(res, 401, 'UNAUTHORIZED', 'Invalid signature'); return; } @@ -217,7 +218,7 @@ export function verifyChallenge(req: Request, res: Response): void { res.json({ token, expiresIn: JWT_EXPIRY_SECONDS }); } catch (err) { logger.error('[Auth] verifyChallenge error:', err); - res.status(401).json({ error: 'Invalid signed transaction' }); + sendApiError(res, 401, 'UNAUTHORIZED', 'Invalid signed transaction'); } } @@ -226,12 +227,12 @@ export function verifyChallenge(req: Request, res: Response): void { export function requireAuth(req: Request, res: Response, next: NextFunction): void { const header = req.headers.authorization; if (!header?.startsWith('Bearer ')) { - res.status(401).json({ error: 'Unauthorized', message: 'Missing Bearer token' }); + sendApiError(res, 401, 'UNAUTHORIZED', 'Missing Bearer token'); return; } const payload = verifyJwt(header.slice(7)); if (!payload) { - res.status(401).json({ error: 'Unauthorized', message: 'Invalid or expired token' }); + sendApiError(res, 401, 'UNAUTHORIZED', 'Invalid or expired token'); return; } (req as AuthenticatedRequest).user = { publicKey: payload.publicKey }; @@ -243,7 +244,7 @@ export function requireAdmin(req: Request, res: Response, next: NextFunction): v const user = (req as AuthenticatedRequest).user; const adminKey = process.env.ADMIN_PUBLIC_KEY; if (!adminKey || user.publicKey !== adminKey) { - res.status(403).json({ error: 'Forbidden', message: 'Admin access required' }); + sendApiError(res, 403, 'FORBIDDEN', 'Admin access required'); return; } next(); diff --git a/backend/src/middleware/compliance.middleware.ts b/backend/src/middleware/compliance.middleware.ts index c952f747..028014ae 100644 --- a/backend/src/middleware/compliance.middleware.ts +++ b/backend/src/middleware/compliance.middleware.ts @@ -12,6 +12,7 @@ */ import type { NextFunction, Request, RequestHandler, Response } from 'express'; import logger from '../logger.js'; +import { sendApiError } from '../lib/api-error.js'; import { getComplianceConfig, type ComplianceConfig } from '../config/compliance.config.js'; import { ComplianceScreeningError, @@ -167,11 +168,12 @@ export function complianceScreening(options: ComplianceMiddlewareOptions): Reque }); if (config.failureMode === 'fail-closed') { - res.status(503).json({ - error: 'COMPLIANCE_SCREENING_UNAVAILABLE', - message: - 'Compliance screening is temporarily unavailable. Please try again later.', - }); + sendApiError( + res, + 503, + 'COMPLIANCE_SCREENING_UNAVAILABLE', + 'Compliance screening is temporarily unavailable. Please try again later.', + ); return; } @@ -198,16 +200,18 @@ export function complianceScreening(options: ComplianceMiddlewareOptions): Reque ), ); - res.status(403).json({ - error: 'COMPLIANCE_RESTRICTION', - message: 'Address restricted under compliance policy', - details: blocked.map((result) => ({ + sendApiError( + res, + 403, + 'COMPLIANCE_RESTRICTION', + 'Address restricted under compliance policy', + blocked.map((result) => ({ address: result.address, riskScore: result.riskScore, tags: result.tags, isSanctioned: result.isSanctioned, })), - }); + ); return; } diff --git a/backend/src/middleware/error.middleware.ts b/backend/src/middleware/error.middleware.ts index a1e95a16..9e313d0d 100644 --- a/backend/src/middleware/error.middleware.ts +++ b/backend/src/middleware/error.middleware.ts @@ -1,8 +1,33 @@ import type { Request, Response, NextFunction } from 'express'; import { ZodError, type ZodIssue } from 'zod'; import logger from '../logger.js'; -import { ApiError as TypeApiError, sendApiError } from '../types/api-error.js'; -import { ApiError as LibApiError, fromPrismaError, sanitizeDatabaseErrorMessage } from '../lib/api-error.js'; +import { + ApiError, + fromPrismaError, + sanitizeDatabaseErrorMessage, + sendApiError, +} from '../lib/api-error.js'; + +/** + * Shape of the third-party errors that reach this handler. `express`, + * `body-parser` and the auth libraries attach a status (and sometimes a machine + * code) to a plain `Error`, so the handler reads those fields through this + * interface instead of through `any`. + */ +interface StatusedError extends Error { + status?: number; + statusCode?: number; + code?: string; + type?: string; + details?: unknown; +} + +const asStatusedError = (err: unknown): StatusedError | null => + err instanceof Error ? err : null; + +/** The status an error asks to be answered with, or 500 when it says nothing. */ +const statusOf = (err: StatusedError): number => + err.statusCode ?? err.status ?? 500; /** * Global error handler middleware @@ -19,12 +44,12 @@ export const errorHandler = ( return next(err); } + const statused = asStatusedError(err); + // body-parser signals an over-limit body with `type: 'entity.too.large'` // (and status 413). Translate it to the API's standard JSON error envelope // instead of leaking the raw parser message. - const maybeStatus = (err as { status?: number; statusCode?: number })?.status - ?? (err as { statusCode?: number })?.statusCode; - if ((err as { type?: string })?.type === 'entity.too.large' || maybeStatus === 413) { + if (statused?.type === 'entity.too.large' || (statused !== null && statusOf(statused) === 413)) { return sendApiError( res, 413, @@ -44,27 +69,41 @@ export const errorHandler = ( // Intercept Prisma database errors to prevent schema disclosure const prismaError = fromPrismaError(err); if (prismaError) { - return sendApiError(res, prismaError.status, prismaError.code, prismaError.message); + return sendApiError(res, prismaError.statusCode, prismaError.code, prismaError.message); } - if ( - err instanceof TypeApiError || - err instanceof LibApiError || - (err instanceof Error && 'statusCode' in err && 'code' in err) || - (err instanceof Error && 'status' in err && 'code' in err) - ) { - const statusCode = (err as any).statusCode ?? (err as any).status ?? 500; - const code = (err as any).code || (statusCode === 500 ? 'INTERNAL_SERVER_ERROR' : 'REQUEST_ERROR'); - let message = (err as any).message || 'Request failed'; - message = sanitizeDatabaseErrorMessage(message, statusCode); - return sendApiError(res, statusCode, code, message, (err as any).details); + // The application's own error type: the thrower already chose the status, + // the code and any details, so only the message needs sanitising. + if (err instanceof ApiError) { + return sendApiError( + res, + err.statusCode, + err.code, + sanitizeDatabaseErrorMessage(err.message, err.statusCode), + err.details, + ); } - // Default Error - const statusCode = (err instanceof Error && (err as any).status) || (err instanceof Error && (err as any).statusCode) || 500; - let message = statusCode === 500 ? 'A technical error occurred. Please try again later.' : (err instanceof Error ? err.message : 'Request failed'); - message = sanitizeDatabaseErrorMessage(message, statusCode); - const code = statusCode === 500 ? 'INTERNAL_SERVER_ERROR' : 'REQUEST_ERROR'; - return sendApiError(res, statusCode, code, message); -}; + if (statused) { + const statusCode = statusOf(statused); + const rawMessage = statusCode === 500 + ? 'A technical error occurred. Please try again later.' + : (statused.message || 'Request failed'); + return sendApiError( + res, + statusCode, + statused.code || (statusCode === 500 ? 'INTERNAL_SERVER_ERROR' : 'REQUEST_ERROR'), + sanitizeDatabaseErrorMessage(rawMessage, statusCode), + statused.details, + ); + } + // A thrown non-Error (a string, an object literal): report a generic 500 + // rather than echoing an unknown payload back to the caller. + return sendApiError( + res, + 500, + 'INTERNAL_SERVER_ERROR', + 'A technical error occurred. Please try again later.', + ); +}; diff --git a/backend/src/middleware/rate-limiter.middleware.ts b/backend/src/middleware/rate-limiter.middleware.ts index 67ae7f1a..59101744 100644 --- a/backend/src/middleware/rate-limiter.middleware.ts +++ b/backend/src/middleware/rate-limiter.middleware.ts @@ -1,4 +1,30 @@ +import type { NextFunction, Request, Response } from 'express'; import { rateLimit, type Options } from 'express-rate-limit'; +import { sendApiError } from '../lib/api-error.js'; + +/** + * Answers a throttled request in the shared error envelope (issue #1851). + * + * express-rate-limit's default handler sends its `message` option verbatim, so + * leaving it unset would keep 429s in a `{ message, status }` shape no other + * error response uses. `message` therefore stays a plain string here and this + * handler supplies the code. + */ +export function rateLimitHandler( + _req: Request, + res: Response, + _next: NextFunction, + options: { statusCode?: number; message?: unknown }, +): void { + sendApiError( + res, + options.statusCode ?? 429, + 'RATE_LIMITED', + typeof options.message === 'string' + ? options.message + : 'Too many requests, please try again later.', + ); +} /** * Shared factory to create an express-rate-limit instance with common configuration. @@ -23,10 +49,8 @@ export const globalRateLimiter = createRateLimiter({ // Prometheus mark the target down and blind the whole alerting pipeline. // It is protected by its own network/token guard instead. skip: (req) => req.path === '/metrics' || req.path.startsWith('/metrics/'), - message: { - message: 'Too many requests, please try again later.', - status: 429, - }, + message: 'Too many requests, please try again later.', + handler: rateLimitHandler, }); /** * Dedicated limiter for `/health` (issue #1511). @@ -40,8 +64,6 @@ export const globalRateLimiter = createRateLimiter({ export const healthRateLimiter = createRateLimiter({ windowMs: 60 * 1000, max: 60, - message: { - message: 'Too many health check requests, please try again later.', - status: 429, - }, + message: 'Too many health check requests, please try again later.', + handler: rateLimitHandler, }); diff --git a/backend/src/middleware/sandbox.middleware.ts b/backend/src/middleware/sandbox.middleware.ts index 5805da05..77478bca 100644 --- a/backend/src/middleware/sandbox.middleware.ts +++ b/backend/src/middleware/sandbox.middleware.ts @@ -1,5 +1,6 @@ import type { Request, Response, NextFunction } from 'express'; import { getSandboxConfig, isSandboxModeEnabled } from '../config/sandbox.js'; +import { sendApiError } from '../lib/api-error.js'; /** * Extended Request interface with sandbox flag @@ -80,22 +81,23 @@ export function requireSandbox( next: NextFunction ): void { if (!isSandboxModeEnabled()) { - res.status(503).json({ - error: 'Sandbox mode not available', - message: 'Sandbox mode is not enabled on this server.', - }); + sendApiError( + res, + 503, + 'SANDBOX_MODE_NOT_AVAILABLE', + 'Sandbox mode is not enabled on this server.', + ); return; } if (!isSandboxRequest(req)) { - res.status(400).json({ - error: 'Sandbox mode required', - message: 'This endpoint requires sandbox mode. Add X-Sandbox-Mode: true header or ?sandbox=true query parameter.', - hint: { - header: 'X-Sandbox-Mode: true', - queryParam: '?sandbox=true', - }, - }); + sendApiError( + res, + 400, + 'SANDBOX_MODE_REQUIRED', + 'This endpoint requires sandbox mode. Add X-Sandbox-Mode: true header or ?sandbox=true query parameter.', + { hint: { header: 'X-Sandbox-Mode: true', queryParam: '?sandbox=true' } }, + ); return; } diff --git a/backend/src/middleware/schema-validator.middleware.ts b/backend/src/middleware/schema-validator.middleware.ts deleted file mode 100644 index 3a08ed8a..00000000 --- a/backend/src/middleware/schema-validator.middleware.ts +++ /dev/null @@ -1,94 +0,0 @@ -import type { NextFunction, Request, Response } from "express"; -import { z } from "zod"; - -/** - * Zod-backed request validation that mirrors the OpenAPI contract. - * - * Attach per route: `router.post("/x", validateRequest({ body: schema }), handler)`. - * Invalid requests never reach the controller; they get a single RFC 7807 - * Problem Details response. Parsed (coerced) values are exposed on - * `res.locals.validated` so controllers stop re-parsing input. - */ - -export const INVALID_PARAMETERS_TYPE = "https://flowfi.org/errors/invalid-parameters"; - -export interface InvalidParam { - name: string; - reason: string; -} - -export interface ProblemDetails { - type: string; - title: string; - status: number; - detail: string; - invalidParams: InvalidParam[]; -} - -export interface RequestSchemas { - params?: z.ZodType; - query?: z.ZodType; - body?: z.ZodType; - headers?: z.ZodType; -} - -export type ValidatedRequest = Partial>; - -const SOURCES: (keyof RequestSchemas)[] = ["headers", "params", "query", "body"]; - -function toInvalidParams(error: z.ZodError): InvalidParam[] { - return error.issues.map((issue) => ({ - name: issue.path.length ? issue.path.join(".") : "(root)", - reason: issue.message, - })); -} - -export function invalidParametersProblem(invalidParams: InvalidParam[]): ProblemDetails { - const first = invalidParams[0]; - return { - type: INVALID_PARAMETERS_TYPE, - title: "Invalid Request Parameters", - status: 400, - detail: first ? `Invalid parameter '${first.name}': ${first.reason}` : "Invalid request", - invalidParams, - }; -} - -export function validateRequest(schemas: RequestSchemas) { - return (req: Request, res: Response, next: NextFunction) => { - const invalidParams: InvalidParam[] = []; - const validated: ValidatedRequest = {}; - - for (const source of SOURCES) { - const schema = schemas[source]; - if (!schema) continue; - const result = schema.safeParse(req[source] ?? {}); - if (result.success) { - validated[source] = result.data; - } else { - invalidParams.push(...toInvalidParams(result.error)); - } - } - - if (invalidParams.length > 0) { - res.status(400).type("application/problem+json").json(invalidParametersProblem(invalidParams)); - return; - } - - res.locals.validated = validated; - next(); - }; -} - -/** - * Test helper: asserts a controller response matches its documented schema, - * so contract drift fails the test suite. Throws with the offending fields. - */ -export function assertResponseMatches(schema: z.ZodType, payload: unknown): T { - const result = schema.safeParse(payload); - if (!result.success) { - const fields = toInvalidParams(result.error).map((p) => `${p.name}: ${p.reason}`); - throw new Error(`Response does not match schema — ${fields.join("; ")}`); - } - return result.data; -} diff --git a/backend/src/middleware/stream-rate-limiter.middleware.ts b/backend/src/middleware/stream-rate-limiter.middleware.ts index 4b551a30..1d8a1fef 100644 --- a/backend/src/middleware/stream-rate-limiter.middleware.ts +++ b/backend/src/middleware/stream-rate-limiter.middleware.ts @@ -1,4 +1,4 @@ -import { createRateLimiter } from './rate-limiter.middleware.js'; +import { createRateLimiter, rateLimitHandler } from './rate-limiter.middleware.js'; import { type Request, type Response, type NextFunction } from 'express'; import type { AuthenticatedRequest } from '../types/auth.types.js'; import logger from '../logger.js'; @@ -25,11 +25,7 @@ export function createStreamRateLimiter( return createRateLimiter({ windowMs, max, - message: { - error: 'Too many stream creation requests - rate limit exceeded', - message: 'You have exceeded the rate limit for stream creation. Please try again later.', - status: 429, - }, + message: 'You have exceeded the rate limit for stream creation. Please try again later.', /** * KeyGenerator: Use wallet address as the rate limit key * For authenticated requests, use the wallet's public key @@ -56,7 +52,7 @@ export function createStreamRateLimiter( `Rate limit exceeded for wallet: ${authReq.user?.publicKey || 'unknown'}`, { endpoint: req.path, method: req.method } ); - res.status(options.statusCode).json(options.message); + rateLimitHandler(req, res, next, options); }, }); } diff --git a/backend/src/routes/metrics.routes.ts b/backend/src/routes/metrics.routes.ts index 1f687388..3c90ceb1 100644 --- a/backend/src/routes/metrics.routes.ts +++ b/backend/src/routes/metrics.routes.ts @@ -1,6 +1,7 @@ import { Router, type Request, type Response } from 'express'; import net from 'node:net'; import { getMetricsRegistry, metricsContentType } from '../lib/metrics.js'; +import { sendApiError } from '../lib/api-error.js'; import logger from '../logger.js'; const router = Router(); @@ -108,12 +109,12 @@ function hasValidToken(req: Request): boolean { */ router.get('/', (req: Request, res: Response) => { if (!metricsEnabled()) { - res.status(404).json({ error: 'Not found' }); + sendApiError(res, 404, 'NOT_FOUND', 'Not found'); return; } if (!isAllowedIp(clientIp(req)) || !hasValidToken(req)) { - res.status(403).json({ error: 'Forbidden', message: 'Metrics access denied' }); + sendApiError(res, 403, 'FORBIDDEN', 'Metrics access denied'); return; } @@ -126,7 +127,7 @@ router.get('/', (req: Request, res: Response) => { .catch((err: unknown) => { logger.error('[Metrics] Failed to render registry:', err); if (!res.headersSent) { - res.status(500).json({ error: 'Failed to render metrics' }); + sendApiError(res, 500, 'INTERNAL_SERVER_ERROR', 'Failed to render metrics'); } }); }); diff --git a/backend/src/routes/v1/admin.routes.ts b/backend/src/routes/v1/admin.routes.ts index b28581f1..fd9cd935 100644 --- a/backend/src/routes/v1/admin.routes.ts +++ b/backend/src/routes/v1/admin.routes.ts @@ -25,6 +25,7 @@ import { sseService } from '../../services/sse.service.js'; import { cache } from '../../lib/redis.js'; import logger from '../../logger.js'; import { sorobanEventWorker } from '../../workers/soroban-event-worker.js'; +import { sendApiError } from '../../lib/api-error.js'; const router = Router(); @@ -302,7 +303,7 @@ router.get('/metrics', async (_req: Request, res: Response) => { res.json(withCalculatedAt(payload)); } catch (err) { logger.error('Error fetching admin metrics:', err); - res.status(500).json({ error: 'Internal server error' }); + sendApiError(res, 500, 'INTERNAL_SERVER_ERROR', 'Internal server error'); } }); @@ -345,7 +346,7 @@ router.get('/indexer/status', async (req: Request, res: Response) => { const status = await getIndexerStatus(); res.json(status); } catch (err) { - res.status(500).json({ error: 'Failed to fetch indexer status' }); + sendApiError(res, 500, 'INTERNAL_SERVER_ERROR', 'Failed to fetch indexer status'); } }); @@ -411,7 +412,7 @@ router.get('/indexer/status', async (req: Request, res: Response) => { router.post('/indexer/reset', async (req: Request, res: Response) => { const ledger = Number(req.body?.ledger); if (!Number.isInteger(ledger) || ledger < 0) { - res.status(400).json({ error: 'ledger must be a non-negative integer' }); + sendApiError(res, 400, 'BAD_REQUEST', 'ledger must be a non-negative integer'); return; } @@ -426,7 +427,7 @@ router.post('/indexer/reset', async (req: Request, res: Response) => { await resetIndexer(ledger); res.json({ ok: true, lastLedger: ledger }); } catch (err) { - res.status(500).json({ error: 'Reset failed' }); + sendApiError(res, 500, 'INTERNAL_SERVER_ERROR', 'Reset failed'); } }); @@ -490,7 +491,7 @@ router.post('/indexer/reset', async (req: Request, res: Response) => { router.post('/indexer/replay', async (req: Request, res: Response) => { const fromLedger = Number(req.query.from_ledger); if (!Number.isInteger(fromLedger) || fromLedger < 0) { - res.status(400).json({ error: 'from_ledger must be a non-negative integer' }); + sendApiError(res, 400, 'BAD_REQUEST', 'from_ledger must be a non-negative integer'); return; } @@ -505,7 +506,7 @@ router.post('/indexer/replay', async (req: Request, res: Response) => { const requestId = await replayFromLedger(fromLedger); res.status(202).json({ ok: true, replayingFrom: fromLedger, requestId }); } catch (err) { - res.status(500).json({ error: 'Replay failed' }); + sendApiError(res, 500, 'INTERNAL_SERVER_ERROR', 'Replay failed'); } }); diff --git a/backend/src/routes/v1/compliance.routes.ts b/backend/src/routes/v1/compliance.routes.ts index 267d7e3d..149b5424 100644 --- a/backend/src/routes/v1/compliance.routes.ts +++ b/backend/src/routes/v1/compliance.routes.ts @@ -4,7 +4,7 @@ import { requireAuth } from '../../middleware/auth.js'; import { complianceService } from '../../services/compliance.service.js'; import { getComplianceConfig } from '../../config/compliance.config.js'; import type { AuthenticatedRequest } from '../../types/auth.types.js'; -import { sendApiError } from '../../types/api-error.js'; +import { sendApiError } from '../../lib/api-error.js'; import logger from '../../logger.js'; const router = Router(); diff --git a/backend/src/routes/v1/events.routes.ts b/backend/src/routes/v1/events.routes.ts index c3945d34..86f180aa 100644 --- a/backend/src/routes/v1/events.routes.ts +++ b/backend/src/routes/v1/events.routes.ts @@ -5,6 +5,7 @@ import { sseService } from '../../services/sse.service.js'; import { requireAdmin, requireAuth } from '../../middleware/auth.js'; import type { AuthenticatedRequest } from '../../types/auth.types.js'; import logger from '../../logger.js'; +import { sendApiError } from '../../lib/api-error.js'; import { DEFAULT_EVENTS_PAGE_SIZE, MAX_EVENTS_PAGE_SIZE, @@ -95,19 +96,19 @@ router.get('/', requireAuth, async (req: Request, res: Response, next: NextFunct const { publicKey } = (req as AuthenticatedRequest).user; const address = typeof req.query.address === 'string' ? req.query.address.trim() : ''; if (!address) { - res.status(400).json({ error: 'address query parameter is required' }); + sendApiError(res, 400, 'BAD_REQUEST', 'address query parameter is required'); return; } // Aligned with SSE security: history queries require authentication and are scoped to the caller. if (address !== publicKey) { - res.status(403).json({ error: 'Forbidden', message: 'You can only view your own event history' }); + sendApiError(res, 403, 'FORBIDDEN', 'You can only view your own event history'); return; } const { requested, types } = parseEventTypeFilter(req.query.type); if (requested.length > 0 && types.length === 0) { - res.status(400).json({ error: 'No valid event types in `type` filter' }); + sendApiError(res, 400, 'BAD_REQUEST', 'No valid event types in `type` filter'); return; } @@ -116,7 +117,7 @@ router.get('/', requireAuth, async (req: Request, res: Response, next: NextFunct maxLimit: MAX_EVENTS_PAGE_SIZE, }); if (!pagination.ok) { - res.status(400).json({ error: pagination.message }); + sendApiError(res, 400, 'BAD_REQUEST', pagination.message); return; } const { limit, offset } = pagination; diff --git a/backend/src/routes/v1/notifications.routes.ts b/backend/src/routes/v1/notifications.routes.ts index e428922a..4141d548 100644 --- a/backend/src/routes/v1/notifications.routes.ts +++ b/backend/src/routes/v1/notifications.routes.ts @@ -1,5 +1,6 @@ import { Router } from 'express'; import { notificationService } from '../../services/notification.service.js'; +import { sendApiError } from '../../lib/api-error.js'; export const notificationsRouter = Router(); @@ -8,7 +9,7 @@ notificationsRouter.post('/subscribe', async (req, res) => { const result = await notificationService.subscribeWebPush(req.body); res.status(201).json(result); } catch (err) { - res.status(400).json({ error: err instanceof Error ? err.message : 'Bad request' }); + sendApiError(res, 400, 'BAD_REQUEST', err instanceof Error ? err.message : 'Bad request'); } }); @@ -17,7 +18,7 @@ notificationsRouter.post('/unsubscribe', async (req, res) => { await notificationService.unsubscribeWebPush(req.body.address, req.body.endpoint); res.json({ ok: true }); } catch (err) { - res.status(400).json({ error: err instanceof Error ? err.message : 'Bad request' }); + sendApiError(res, 400, 'BAD_REQUEST', err instanceof Error ? err.message : 'Bad request'); } }); @@ -26,7 +27,7 @@ notificationsRouter.post('/link-code', async (req, res) => { const result = await notificationService.generateLinkCode(req.body.address); res.json(result); } catch (err) { - res.status(400).json({ error: err instanceof Error ? err.message : 'Bad request' }); + sendApiError(res, 400, 'BAD_REQUEST', err instanceof Error ? err.message : 'Bad request'); } }); @@ -35,7 +36,7 @@ notificationsRouter.post('/telegram/link', async (req, res) => { const result = await notificationService.linkTelegram(req.body.code, req.body.chatId); res.json(result); } catch (err) { - res.status(400).json({ error: err instanceof Error ? err.message : 'Bad request' }); + sendApiError(res, 400, 'BAD_REQUEST', err instanceof Error ? err.message : 'Bad request'); } }); @@ -47,6 +48,6 @@ notificationsRouter.post('/discord', async (req, res) => { ); res.json(result); } catch (err) { - res.status(400).json({ error: err instanceof Error ? err.message : 'Bad request' }); + sendApiError(res, 400, 'BAD_REQUEST', err instanceof Error ? err.message : 'Bad request'); } }); diff --git a/backend/src/routes/v1/streams/withdraw.ts b/backend/src/routes/v1/streams/withdraw.ts index 8c123a20..b7d78969 100644 --- a/backend/src/routes/v1/streams/withdraw.ts +++ b/backend/src/routes/v1/streams/withdraw.ts @@ -5,7 +5,7 @@ import { claimableAmountService } from '../../../services/claimable.service.js'; import { withdraw as sorobanWithdraw } from '../../../services/sorobanService.js'; import type { AuthenticatedRequest } from '../../../types/auth.types.js'; import { parseStreamId } from '../../../lib/stream-id.js'; -import { sendApiError } from '../../../types/api-error.js'; +import { sendApiError } from '../../../lib/api-error.js'; /** * @openapi diff --git a/backend/src/routes/v1/token.routes.ts b/backend/src/routes/v1/token.routes.ts index 1531a431..0f63e260 100644 --- a/backend/src/routes/v1/token.routes.ts +++ b/backend/src/routes/v1/token.routes.ts @@ -2,7 +2,7 @@ import { Router, type Request, type Response } from 'express'; import { getToken, toPublicTokenMetadata } from '../../controllers/token.controller.js'; import { createHash } from 'node:crypto'; import { listVerifiedTokens } from '../../services/token-registry.service.js'; -import { sendApiError } from '../../types/api-error.js'; +import { sendApiError } from '../../lib/api-error.js'; const router = Router(); diff --git a/backend/src/services/export.service.ts b/backend/src/services/export.service.ts index 05f6f6b8..2e3e02df 100644 --- a/backend/src/services/export.service.ts +++ b/backend/src/services/export.service.ts @@ -5,6 +5,7 @@ import type { Response } from "express"; import { prisma } from "../lib/prisma.js"; import logger from "../logger.js"; +import { sendApiError } from "../lib/api-error.js"; export interface ExportOptions { format: "csv" | "json"; @@ -257,7 +258,7 @@ export async function streamTransactionCSV( } catch (error) { logger.error("[Export] CSV streaming error:", error); if (!res.headersSent) { - res.status(500).json({ error: "Export failed" }); + sendApiError(res, 500, "INTERNAL_SERVER_ERROR", "Export failed"); } else { if (typeof res.destroy === "function") { res.destroy(error as Error); @@ -373,7 +374,7 @@ export async function streamTransactionJSON( } catch (error) { logger.error("[Export] JSON streaming error:", error); if (!res.headersSent) { - res.status(500).json({ error: "Export failed" }); + sendApiError(res, 500, "INTERNAL_SERVER_ERROR", "Export failed"); } else { if (typeof res.destroy === "function") { res.destroy(error as Error); diff --git a/backend/src/services/sorobanService.ts b/backend/src/services/sorobanService.ts index 4746300b..16af2d7a 100644 --- a/backend/src/services/sorobanService.ts +++ b/backend/src/services/sorobanService.ts @@ -713,7 +713,7 @@ export function toSimulationApiError( ? known.message : `Simulation of "${action}" failed: ${rawError}`; - return new ApiError(400, message, 'simulation_failed', { + return new ApiError(400, 'simulation_failed', message, { action, reason: rawError, ...(code !== null ? { contractErrorCode: code } : {}), @@ -723,36 +723,36 @@ export function toSimulationApiError( function toStreamId(raw: string | undefined, field: string): bigint { if (raw === undefined || raw === null || raw === '') { - throw new ApiError(400, `${field} is required`, 'invalid_params'); + throw new ApiError(400, 'invalid_params', `${field} is required`); } if (!/^\d+$/.test(raw)) { - throw new ApiError(400, `${field} must be a non-negative integer string`, 'invalid_params'); + throw new ApiError(400, 'invalid_params', `${field} must be a non-negative integer string`); } return BigInt(raw); } function toPositiveI128(raw: string | undefined, field: string): bigint { if (raw === undefined || raw === null || raw === '') { - throw new ApiError(400, `${field} is required`, 'invalid_params'); + throw new ApiError(400, 'invalid_params', `${field} is required`); } if (!/^\d+$/.test(raw)) { - throw new ApiError(400, `${field} must be a positive integer string`, 'invalid_params'); + throw new ApiError(400, 'invalid_params', `${field} must be a positive integer string`); } const value = BigInt(raw); if (value <= 0n) { - throw new ApiError(400, `${field} must be greater than zero`, 'invalid_params'); + throw new ApiError(400, 'invalid_params', `${field} must be greater than zero`); } return value; } function toAddress(raw: string | undefined, field: string): Address { if (!raw) { - throw new ApiError(400, `${field} is required`, 'invalid_params'); + throw new ApiError(400, 'invalid_params', `${field} is required`); } try { return new Address(raw); } catch { - throw new ApiError(400, `${field} is not a valid Stellar address`, 'invalid_params'); + throw new ApiError(400, 'invalid_params', `${field} is not a valid Stellar address`); } } @@ -778,8 +778,8 @@ function buildInvocations( if (params.duration === undefined || !Number.isInteger(params.duration) || params.duration <= 0) { throw new ApiError( 400, - 'params.duration must be a positive integer (seconds)', 'invalid_params', + 'params.duration must be a positive integer (seconds)', ); } @@ -839,15 +839,15 @@ function buildInvocations( if (!ids || ids.length === 0) { throw new ApiError( 400, - 'params.streamIds is required for batch_withdraw', 'invalid_params', + 'params.streamIds is required for batch_withdraw', ); } if (ids.length > MAX_BATCH_WITHDRAW) { throw new ApiError( 400, - `batch_withdraw accepts at most ${MAX_BATCH_WITHDRAW} streams per transaction`, 'invalid_params', + `batch_withdraw accepts at most ${MAX_BATCH_WITHDRAW} streams per transaction`, ); } // The contract has no batch entrypoint, so each stream becomes its own @@ -861,7 +861,7 @@ function buildInvocations( default: { const exhaustive: never = action; - throw new ApiError(400, `Unsupported action: ${String(exhaustive)}`, 'invalid_params'); + throw new ApiError(400, 'invalid_params', `Unsupported action: ${String(exhaustive)}`); } } } @@ -950,7 +950,7 @@ export async function simulateStreamAction( ): Promise { const contractId = getContractId(); if (!contractId) { - throw new ApiError(503, 'Stream contract is not configured', 'contract_not_configured'); + throw new ApiError(503, 'contract_not_configured', 'Stream contract is not configured'); } const sender = toAddress(senderPublicKey, 'senderPublicKey'); diff --git a/backend/src/services/token-registry.service.ts b/backend/src/services/token-registry.service.ts index 144b8cb0..6e387252 100644 --- a/backend/src/services/token-registry.service.ts +++ b/backend/src/services/token-registry.service.ts @@ -2,7 +2,7 @@ import { Account, Asset, Contract, Keypair, Networks, rpc, scValToNative, StrKey import { prisma } from '../lib/prisma.js'; import { getPublisher } from '../lib/redis.js'; import { rpcPool } from '../lib/rpc-pool.js'; -import { ApiError } from '../types/api-error.js'; +import { ApiError } from '../lib/api-error.js'; const CACHE_TTL_SECONDS = 24 * 60 * 60; const CACHE_PREFIX = 'token-registry:v1'; diff --git a/backend/src/services/top-up-projection.ts b/backend/src/services/top-up-projection.ts new file mode 100644 index 00000000..7fddcf8d --- /dev/null +++ b/backend/src/services/top-up-projection.ts @@ -0,0 +1,43 @@ +import type { Prisma } from '../generated/prisma/index.js'; + +/** The fields `endTime` is derived from, as stored on a `Stream` row. */ +export interface StreamTiming { + ratePerSecond: string | bigint; + startTime: bigint; + totalPausedDuration: number | bigint; +} + +/** + * The wall-clock time a stream runs out of deposit. + * + * Both writers of `depositedAmount` — the top-up API handler and the Soroban + * event indexer — must extend `endTime` with this same formula, otherwise the + * two paths disagree about when a stream ends depending on which one committed. + * A zero rate means the deposit buys no runway, so the projection is unknown + * rather than a division by zero. + */ +export function projectedEndTime( + depositedAmount: bigint, + stream: StreamTiming, +): bigint | null { + const ratePerSecond = BigInt(stream.ratePerSecond); + if (ratePerSecond === 0n) return null; + return ( + stream.startTime + + depositedAmount / ratePerSecond + + BigInt(stream.totalPausedDuration) + ); +} + +/** + * Takes the `FOR UPDATE` row lock on one stream for the surrounding + * transaction, so that concurrent writers of its amounts serialise instead of + * interleaving a read-compute-write. Returns false when no such row exists. + */ +export async function lockStreamForUpdate( + tx: Prisma.TransactionClient, + streamId: bigint, +): Promise { + const locked = await tx.$executeRaw`SELECT 1 FROM "Stream" WHERE "streamId" = ${streamId} FOR UPDATE`; + return locked > 0; +} diff --git a/backend/src/services/top-up-writer.ts b/backend/src/services/top-up-writer.ts new file mode 100644 index 00000000..4df1fc56 --- /dev/null +++ b/backend/src/services/top-up-writer.ts @@ -0,0 +1,187 @@ +import type { Prisma } from '../generated/prisma/index.js'; +import logger from '../logger.js'; +import { resourceNotFound } from '../lib/api-error.js'; +import { lockStreamForUpdate, projectedEndTime } from './top-up-projection.js'; + +/** The dedup key both top-up writers share. */ +const TOPPED_UP = 'TOPPED_UP'; + +/** + * `StreamEvent.ledgerSequence` written by the API writer, which has no ledger + * position. The indexer treats a marker carrying it as chain-unconfirmed and + * reconciles it against the event it is processing. + */ +const UNINDEXED_MARKER = 0; + +/** + * The API writer: applies a top-up this process just confirmed on chain. + * + * `depositedAmount` has two independent writers — this handler (which knows the + * delta it sent) and the Soroban indexer (which knows the absolute value the + * contract reported). Both take the stream's row lock and both key their + * bookkeeping on the same `StreamEvent` `(transactionHash, "TOPPED_UP")` row, so + * whichever commits second finds the marker and leaves the amount alone. Without + * the marker the handler used to add the amount on top of the indexer's absolute + * write, permanently overcounting the stream. + * + * Returns the stream's authoritative `depositedAmount` afterwards, whether or not + * this call is the one that applied it. + */ +export async function applyTopUpOnce( + tx: Prisma.TransactionClient, + input: { streamId: bigint; txHash: string; amount: bigint }, +): Promise { + if (!(await lockStreamForUpdate(tx, input.streamId))) { + // Same code the handler's pre-flight read uses, so a caller cannot tell + // which of the two lookups found nothing. + throw resourceNotFound('Stream not found', 'NOT_FOUND'); + } + + const recorded = await tx.streamEvent.findUnique({ + where: { + transactionHash_eventType: { + transactionHash: input.txHash, + eventType: TOPPED_UP, + }, + }, + select: { id: true }, + }); + + const stream = await tx.stream.findUniqueOrThrow({ + where: { streamId: input.streamId }, + select: { + depositedAmount: true, + ratePerSecond: true, + startTime: true, + totalPausedDuration: true, + }, + }); + + if (recorded) { + logger.info( + `[topUp] stream=${input.streamId} txHash=${input.txHash} already applied by the indexer, skipping`, + ); + return BigInt(stream.depositedAmount); + } + + const depositedAmount = BigInt(stream.depositedAmount) + input.amount; + const timestamp = BigInt(Math.floor(Date.now() / 1000)); + + await tx.stream.update({ + where: { streamId: input.streamId }, + data: { + depositedAmount: depositedAmount.toString(), + endTime: projectedEndTime(depositedAmount, stream), + lastUpdateTime: timestamp, + }, + }); + + await tx.streamEvent.create({ + data: { + streamId: input.streamId, + eventType: TOPPED_UP, + amount: input.amount.toString(), + transactionHash: input.txHash, + // The API writer has no ledger position; the indexer records the real + // sequence for every event it reads from the chain. + ledgerSequence: UNINDEXED_MARKER, + timestamp, + metadata: JSON.stringify({ newDepositedAmount: depositedAmount.toString() }), + }, + }); + + return depositedAmount; +} + +/** + * The indexer writer: applies a `StreamToppedUp` event read off the chain. + * + * Chain state is authoritative, so this path writes the absolute + * `newDepositedAmount` rather than an increment. An event the indexer has + * already processed is skipped outright — replaying an older top-up would + * otherwise roll the row back to that event's (now stale) absolute value. + * + * A marker with `ledgerSequence === 0` was written by the API writer, which + * incremented from whatever the row happened to hold. That value has never been + * checked against the chain, so this event is its first confirmation and the + * absolute write is applied as a reconciliation. Skipping it instead would make + * the API's guess permanent: the dedup marker would block the only writer that + * knows the true `new_deposited_amount`. + */ +export async function applyToppedUpEvent( + tx: Prisma.TransactionClient, + input: { + streamId: bigint; + txHash: string; + amount: string; + newDepositedAmount: string; + ledgerSequence: number; + timestamp: number; + }, +): Promise { + await lockStreamForUpdate(tx, input.streamId); + + // Check for a duplicate BEFORE mutating any Stream fields so that a + // replayed event never re-applies the top-up. + const existingEvent = await tx.streamEvent.findUnique({ + where: { + transactionHash_eventType: { + transactionHash: input.txHash, + eventType: TOPPED_UP, + }, + }, + select: { id: true, ledgerSequence: true }, + }); + if (existingEvent && existingEvent.ledgerSequence !== UNINDEXED_MARKER) { + logger.warn( + `[SorobanWorker] Duplicate StreamEvent skipped: txHash=${input.txHash} type=${TOPPED_UP}`, + ); + return; + } + if (existingEvent) { + logger.info( + `[SorobanWorker] Reconciling API-applied top-up against chain: txHash=${input.txHash} ` + + `chainDeposited=${input.newDepositedAmount}`, + ); + } + + const stream = await tx.stream.findUniqueOrThrow({ + where: { streamId: input.streamId }, + select: { + ratePerSecond: true, + startTime: true, + totalPausedDuration: true, + }, + }); + + await tx.stream.update({ + where: { streamId: input.streamId }, + data: { + depositedAmount: input.newDepositedAmount, + endTime: projectedEndTime(BigInt(input.newDepositedAmount), stream), + lastUpdateTime: input.timestamp, + }, + }); + + await tx.streamEvent.upsert({ + where: { + transactionHash_eventType: { + transactionHash: input.txHash, + eventType: TOPPED_UP, + }, + }, + create: { + streamId: input.streamId, + eventType: TOPPED_UP, + amount: input.amount, + transactionHash: input.txHash, + ledgerSequence: input.ledgerSequence, + timestamp: BigInt(input.timestamp), + metadata: JSON.stringify({ newDepositedAmount: input.newDepositedAmount }), + }, + update: { + ledgerSequence: input.ledgerSequence, + timestamp: BigInt(input.timestamp), + }, + }); +} diff --git a/backend/src/types/api-error.ts b/backend/src/types/api-error.ts deleted file mode 100644 index d7cf3334..00000000 --- a/backend/src/types/api-error.ts +++ /dev/null @@ -1,33 +0,0 @@ -import type { Response } from "express"; - -export interface ApiErrorBody { - code: string; - message: string; - details?: unknown; -} - -export class ApiError extends Error { - readonly statusCode: number; - readonly code: string; - readonly details?: unknown; - - constructor(statusCode: number, code: string, message: string, details?: unknown) { - super(message); - this.name = "ApiError"; - this.statusCode = statusCode; - this.code = code; - this.details = details; - } -} - -export function sendApiError( - res: Response, - statusCode: number, - code: string, - message: string, - details?: unknown, -) { - const error: ApiErrorBody = { code, message }; - if (details !== undefined) error.details = details; - return res.status(statusCode).json({ error }); -} \ No newline at end of file diff --git a/backend/src/workers/soroban-event-worker.ts b/backend/src/workers/soroban-event-worker.ts index 3833cb0c..6215b4f5 100644 --- a/backend/src/workers/soroban-event-worker.ts +++ b/backend/src/workers/soroban-event-worker.ts @@ -5,6 +5,7 @@ import { INDEXER_STATE_ID, ensureIndexerState } from "../lib/indexer-state.js"; import { sseService } from "../services/sse.service.js"; import { sentinelService } from "../services/sentinel.service.js"; import { publishIndexerLag, quarantineEvent } from "../services/indexerService.js"; +import { applyToppedUpEvent } from "../services/top-up-writer.js"; import { indexerEventsProcessedTotal, indexerPollsTotal, @@ -937,73 +938,16 @@ export class SorobanEventWorker { const newDepositedAmount = decodeI128(body["new_deposited_amount"]); const timestamp = Math.floor(Date.now() / 1000); - await prisma.$transaction(async (tx: Prisma.TransactionClient) => { - // Check for a duplicate BEFORE mutating any Stream fields so that a - // replayed event never re-applies the top-up. - const existingEvent = await tx.streamEvent.findUnique({ - where: { - transactionHash_eventType: { - transactionHash: event.txHash, - eventType: "TOPPED_UP", - }, - }, - select: { id: true }, - }); - if (existingEvent) { - logger.warn( - `[SorobanWorker] Duplicate StreamEvent skipped: txHash=${event.txHash} type=TOPPED_UP`, - ); - return; - } - - const stream = await tx.stream.findUniqueOrThrow({ - where: { streamId }, - select: { - ratePerSecond: true, - startTime: true, - totalPausedDuration: true, - }, - }); - - const ratePerSecondBigInt = BigInt(stream.ratePerSecond); - const newEndTime = - ratePerSecondBigInt === 0n - ? null - : BigInt(stream.startTime) + - BigInt(newDepositedAmount) / ratePerSecondBigInt + - BigInt(stream.totalPausedDuration); - - await tx.stream.update({ - where: { streamId }, - data: { - depositedAmount: newDepositedAmount, - endTime: newEndTime, - lastUpdateTime: timestamp, - }, - }); - - await tx.streamEvent.upsert({ - where: { - transactionHash_eventType: { - transactionHash: event.txHash, - eventType: "TOPPED_UP", - }, - }, - create: { - streamId, - eventType: "TOPPED_UP", - amount, - transactionHash: event.txHash, - ledgerSequence: event.ledger, - timestamp, - metadata: JSON.stringify({ newDepositedAmount }), - }, - update: { - ledgerSequence: event.ledger, - timestamp, - }, - }); - }); + await prisma.$transaction(async (tx: Prisma.TransactionClient) => + applyToppedUpEvent(tx, { + streamId, + txHash: event.txHash, + amount, + newDepositedAmount, + ledgerSequence: event.ledger, + timestamp, + }), + ); sseService.broadcastToStream(String(streamId), "stream.topped_up", { streamId, diff --git a/backend/tests/api-error.test.ts b/backend/tests/api-error.test.ts index 2aad43ff..ced27f9f 100644 --- a/backend/tests/api-error.test.ts +++ b/backend/tests/api-error.test.ts @@ -15,22 +15,22 @@ import { describe('ApiError and Prisma error sanitization', () => { describe('ApiError class and factory functions', () => { - it('creates ApiError with default code and optional details', () => { - const err = new ApiError(400, 'Invalid request'); - expect(err.status).toBe(400); + it('takes status, code and message positionally, with optional details', () => { + const err = new ApiError(400, 'INVALID_REQUEST', 'Invalid request'); expect(err.statusCode).toBe(400); - expect(err.code).toBe('api_error'); + expect(err.code).toBe('INVALID_REQUEST'); expect(err.message).toBe('Invalid request'); expect(err.details).toBeUndefined(); - const errWithDetails = new ApiError(422, 'Unprocessable', 'UNPROCESSABLE', { foo: 'bar' }); + const errWithDetails = new ApiError(422, 'UNPROCESSABLE', 'Unprocessable', { foo: 'bar' }); expect(errWithDetails.details).toEqual({ foo: 'bar' }); expect(errWithDetails.code).toBe('UNPROCESSABLE'); + expect(errWithDetails.message).toBe('Unprocessable'); }); it('creates badRequest error', () => { const err = badRequest('Bad input', 'INVALID_PARAM'); - expect(err.status).toBe(400); + expect(err.statusCode).toBe(400); expect(err.statusCode).toBe(400); expect(err.code).toBe('INVALID_PARAM'); expect(err.message).toBe('Bad input'); @@ -38,28 +38,28 @@ describe('ApiError and Prisma error sanitization', () => { it('creates duplicateEntry error', () => { const err = duplicateEntry(); - expect(err.status).toBe(409); + expect(err.statusCode).toBe(409); expect(err.code).toBe('DUPLICATE_ENTRY'); expect(err.message).toBe('A record with this unique value already exists.'); }); it('creates resourceNotFound error', () => { const err = resourceNotFound(); - expect(err.status).toBe(404); + expect(err.statusCode).toBe(404); expect(err.code).toBe('RESOURCE_NOT_FOUND'); expect(err.message).toBe('The requested record was not found.'); }); it('creates foreignKeyViolation error', () => { const err = foreignKeyViolation(); - expect(err.status).toBe(409); + expect(err.statusCode).toBe(409); expect(err.code).toBe('FOREIGN_KEY_VIOLATION'); expect(err.message).toBe('Related resource constraint violation.'); }); it('creates internal error', () => { const err = internal(); - expect(err.status).toBe(500); + expect(err.statusCode).toBe(500); expect(err.code).toBe('INTERNAL_SERVER_ERROR'); expect(err.message).toBe('A technical error occurred. Please try again later.'); }); @@ -123,7 +123,7 @@ describe('ApiError and Prisma error sanitization', () => { const apiErr = fromPrismaError(err); expect(apiErr).not.toBeNull(); - expect(apiErr?.status).toBe(409); + expect(apiErr?.statusCode).toBe(409); expect(apiErr?.code).toBe('DUPLICATE_ENTRY'); expect(apiErr?.message).toBe('A record with this unique value already exists.'); expect(apiErr?.message).not.toContain('User'); @@ -142,7 +142,7 @@ describe('ApiError and Prisma error sanitization', () => { ); const apiErr2025 = fromPrismaError(err2025); - expect(apiErr2025?.status).toBe(404); + expect(apiErr2025?.statusCode).toBe(404); expect(apiErr2025?.code).toBe('RESOURCE_NOT_FOUND'); expect(apiErr2025?.message).toBe('The requested record was not found.'); expect(apiErr2025?.message).not.toContain('Stream'); @@ -152,7 +152,7 @@ describe('ApiError and Prisma error sanitization', () => { { code: 'P2001', clientVersion: '1.0' }, ); const apiErr2001 = fromPrismaError(err2001); - expect(apiErr2001?.status).toBe(404); + expect(apiErr2001?.statusCode).toBe(404); expect(apiErr2001?.code).toBe('RESOURCE_NOT_FOUND'); }); @@ -167,7 +167,7 @@ describe('ApiError and Prisma error sanitization', () => { ); const apiErr = fromPrismaError(err); - expect(apiErr?.status).toBe(409); + expect(apiErr?.statusCode).toBe(409); expect(apiErr?.code).toBe('FOREIGN_KEY_VIOLATION'); expect(apiErr?.message).toBe('Related resource constraint violation.'); expect(apiErr?.message).not.toContain('userId'); @@ -180,7 +180,7 @@ describe('ApiError and Prisma error sanitization', () => { clientVersion: '1.0', }); const apiErr = fromPrismaError(err); - expect(apiErr?.status).toBe(400); + expect(apiErr?.statusCode).toBe(400); expect(apiErr?.code).toBe('VALUE_OUT_OF_RANGE'); }); @@ -190,7 +190,7 @@ describe('ApiError and Prisma error sanitization', () => { clientVersion: '1.0', }); const apiErr = fromPrismaError(err); - expect(apiErr?.status).toBe(400); + expect(apiErr?.statusCode).toBe(400); expect(apiErr?.code).toBe('CONSTRAINT_FAILED'); }); @@ -200,7 +200,7 @@ describe('ApiError and Prisma error sanitization', () => { clientVersion: '1.0', }); const apiErr = fromPrismaError(err); - expect(apiErr?.status).toBe(400); + expect(apiErr?.statusCode).toBe(400); expect(apiErr?.code).toBe('INVALID_INPUT'); }); @@ -210,7 +210,7 @@ describe('ApiError and Prisma error sanitization', () => { clientVersion: '1.0', }); const apiErr = fromPrismaError(err); - expect(apiErr?.status).toBe(400); + expect(apiErr?.statusCode).toBe(400); expect(apiErr?.code).toBe('MISSING_REQUIRED_FIELD'); }); @@ -220,7 +220,7 @@ describe('ApiError and Prisma error sanitization', () => { clientVersion: '1.0', }); const apiErr = fromPrismaError(err); - expect(apiErr?.status).toBe(409); + expect(apiErr?.statusCode).toBe(409); expect(apiErr?.code).toBe('RELATION_VIOLATION'); }); @@ -230,7 +230,7 @@ describe('ApiError and Prisma error sanitization', () => { clientVersion: '1.0', }); const apiErr = fromPrismaError(err); - expect(apiErr?.status).toBe(400); + expect(apiErr?.statusCode).toBe(400); expect(apiErr?.code).toBe('INVALID_QUERY'); }); @@ -240,7 +240,7 @@ describe('ApiError and Prisma error sanitization', () => { clientVersion: '1.0', }); const apiErr = fromPrismaError(err); - expect(apiErr?.status).toBe(500); + expect(apiErr?.statusCode).toBe(500); expect(apiErr?.code).toBe('INTERNAL_SERVER_ERROR'); expect(apiErr?.message).toBe('A technical error occurred. Please try again later.'); }); @@ -251,7 +251,7 @@ describe('ApiError and Prisma error sanitization', () => { clientVersion: '1.0', }); const apiErr = fromPrismaError(err); - expect(apiErr?.status).toBe(400); + expect(apiErr?.statusCode).toBe(400); expect(apiErr?.code).toBe('DATABASE_ERROR'); expect(apiErr?.message).toBe('A database error occurred.'); }); @@ -262,7 +262,7 @@ describe('ApiError and Prisma error sanitization', () => { { clientVersion: '1.0' }, ); const apiErr = fromPrismaError(err); - expect(apiErr?.status).toBe(400); + expect(apiErr?.statusCode).toBe(400); expect(apiErr?.code).toBe('VALIDATION_ERROR'); expect(apiErr?.message).toBe('Invalid request data.'); expect(apiErr?.message).not.toContain('findMany'); @@ -275,7 +275,7 @@ describe('ApiError and Prisma error sanitization', () => { { clientVersion: '1.0' }, ); const apiErr = fromPrismaError(err); - expect(apiErr?.status).toBe(500); + expect(apiErr?.statusCode).toBe(500); expect(apiErr?.code).toBe('INTERNAL_SERVER_ERROR'); expect(apiErr?.message).toBe('A technical error occurred. Please try again later.'); expect(apiErr?.message).not.toContain('SELECT'); diff --git a/backend/tests/auth.test.ts b/backend/tests/auth.test.ts index dd2bf363..f5d92050 100644 --- a/backend/tests/auth.test.ts +++ b/backend/tests/auth.test.ts @@ -178,7 +178,7 @@ describe('Authentication & Middleware Tests', () => { .send({ publicKey: keypair.publicKey(), signedTransaction }); expect(res.status).toBe(401); - expect(res.body.error).toMatch(/Challenge expired or not found/i); + expect(res.body.error.message).toMatch(/Challenge expired or not found/i); }); it('test_verify_invalid_signature_returns_401', async () => { @@ -199,7 +199,7 @@ describe('Authentication & Middleware Tests', () => { .send({ publicKey: keypair.publicKey(), signedTransaction }); expect(res.status).toBe(401); - expect(res.body.error).toMatch(/Invalid signature/i); + expect(res.body.error.message).toMatch(/Invalid signature/i); }); it('test_verify_wrong_address_returns_401', async () => { @@ -220,7 +220,7 @@ describe('Authentication & Middleware Tests', () => { .send({ publicKey: keypair.publicKey(), signedTransaction }); expect(res.status).toBe(401); - expect(res.body.error).toMatch(/Transaction source does not match publicKey/i); + expect(res.body.error.message).toMatch(/Transaction source does not match publicKey/i); }); }); @@ -265,13 +265,13 @@ describe('Authentication & Middleware Tests', () => { .set('Authorization', `Bearer ${fakeJwt}`); expect(res.status).toBe(401); - expect(res.body.message).toMatch(/Invalid or expired token/i); + expect(res.body.error.message).toMatch(/Invalid or expired token/i); }); it('test_auth_middleware_rejects_missing_header', async () => { const res = await request(app).get('/v1/events/subscribe'); expect(res.status).toBe(401); - expect(res.body.message).toMatch(/Missing Bearer token/i); + expect(res.body.error.message).toMatch(/Missing Bearer token/i); }); it('test_sse_subscribe_without_token_returns_401', async () => { @@ -326,8 +326,8 @@ describe('Authentication & Middleware Tests', () => { .set('Authorization', `Bearer ${token}`); expect(res.status).toBe(403); - expect(res.body.error).toBe('Forbidden'); - expect(res.body.message).toMatch(/Admin access required/i); + expect(res.body.error.code).toBe('FORBIDDEN'); + expect(res.body.error.message).toMatch(/Admin access required/i); }); it('test_admin_middleware_accepts_admin_token', async () => { @@ -370,8 +370,8 @@ describe('Authentication & Middleware Tests', () => { .set('Authorization', `Bearer ${token}`); expect(res.status).toBe(403); - expect(res.body.error).toBe('Forbidden'); - expect(res.body.message).toMatch(/Admin access required/i); + expect(res.body.error.code).toBe('FORBIDDEN'); + expect(res.body.error.message).toMatch(/Admin access required/i); }); }); @@ -421,7 +421,7 @@ describe('Authentication & Middleware Tests', () => { .set('Authorization', `Bearer ${token}`); expect(res.status).toBe(403); - expect(res.body.error).toBe('Forbidden'); + expect(res.body.error.code).toBe('FORBIDDEN'); }); }); }); diff --git a/backend/tests/compliance.test.ts b/backend/tests/compliance.test.ts index 7bfa92de..0b3af182 100644 --- a/backend/tests/compliance.test.ts +++ b/backend/tests/compliance.test.ts @@ -412,8 +412,8 @@ describe('Compliance screening middleware', () => { const res = await request(app).post('/streams').send({ sender: USER, recipient: MW_SANCTIONED }); expect(res.status).toBe(403); - expect(res.body.error).toBe('COMPLIANCE_RESTRICTION'); - expect(res.body.message).toBe('Address restricted under compliance policy'); + expect(res.body.error.code).toBe('COMPLIANCE_RESTRICTION'); + expect(res.body.error.message).toBe('Address restricted under compliance policy'); expect(prisma.complianceAuditLog.create).toHaveBeenCalledWith( expect.objectContaining({ data: expect.objectContaining({ eventType: 'SCREENING_BLOCKED', isSanctioned: true }), @@ -438,7 +438,7 @@ describe('Compliance screening middleware', () => { const res = await request(app).post('/streams').send({ sender: USER, recipient: CLEAN }); expect(res.status).toBe(403); - expect(res.body.error).toBe('COMPLIANCE_RESTRICTION'); + expect(res.body.error.code).toBe('COMPLIANCE_RESTRICTION'); }); it('allows an address whose risk score equals the threshold', async () => { @@ -469,7 +469,7 @@ describe('Compliance screening middleware', () => { const res = await request(app).post('/streams').send({ sender: USER, recipient: CLEAN }); expect(res.status).toBe(503); - expect(res.body.error).toBe('COMPLIANCE_SCREENING_UNAVAILABLE'); + expect(res.body.error.code).toBe('COMPLIANCE_SCREENING_UNAVAILABLE'); expect(service.writeAuditLog).toHaveBeenCalledWith( expect.objectContaining({ eventType: 'SCREENING_ERROR' }), ); diff --git a/backend/tests/cors.test.ts b/backend/tests/cors.test.ts index b8a5c771..ce218c4d 100644 --- a/backend/tests/cors.test.ts +++ b/backend/tests/cors.test.ts @@ -11,7 +11,7 @@ describe('CORS middleware', () => { .set('Accept', 'text/plain'); expect(response.status).toBe(403); - expect(response.body.error).toBe('CORS origin not allowed'); + expect(response.body.error.message).toBe('CORS origin not allowed'); }); }); @@ -77,7 +77,9 @@ describe('CORS policy', () => { expect(response.status).toBe(403); expect(response.headers['content-type']).toMatch(/application\/json/); - expect(response.body).toEqual({ error: 'CORS origin not allowed' }); + expect(response.body).toEqual({ + error: { code: 'FORBIDDEN', message: 'CORS origin not allowed' }, + }); expect(response.headers['access-control-allow-origin']).toBeUndefined(); expect(warn).toHaveBeenCalledWith( 'CORS origin rejected', diff --git a/backend/tests/error.middleware.test.ts b/backend/tests/error.middleware.test.ts index f4a5fd2e..b973b457 100644 --- a/backend/tests/error.middleware.test.ts +++ b/backend/tests/error.middleware.test.ts @@ -193,7 +193,7 @@ describe('Error Middleware', () => { }); it('should handle ApiError instances and preserve code/details', () => { - const error = new ApiError(403, 'Forbidden action', 'FORBIDDEN_ACTION', { reason: 'denied' }); + const error = new ApiError(403, 'FORBIDDEN_ACTION', 'Forbidden action', { reason: 'denied' }); errorHandler(error, req as Request, res as Response, next); expect(res.status).toHaveBeenCalledWith(403); expect(res.json).toHaveBeenCalledWith({ @@ -206,7 +206,7 @@ describe('Error Middleware', () => { }); it('should sanitize ApiError instances if message contains raw database details', () => { - const error = new ApiError(400, 'Error in table "users": syntax error at or near "SELECT"', 'BAD_INPUT'); + const error = new ApiError(400, 'BAD_INPUT', 'Error in table "users": syntax error at or near "SELECT"'); errorHandler(error, req as Request, res as Response, next); expect(res.status).toHaveBeenCalledWith(400); const jsonCall = (res.json as ReturnType).mock.calls[0]![0]; diff --git a/backend/tests/integration/admin-dead-letter.test.ts b/backend/tests/integration/admin-dead-letter.test.ts index e9cc7bbd..a30cda8e 100644 --- a/backend/tests/integration/admin-dead-letter.test.ts +++ b/backend/tests/integration/admin-dead-letter.test.ts @@ -166,7 +166,7 @@ describe('dead-letter auth', () => { .set('Authorization', `Bearer ${userToken()}`); expect(res.status).toBe(403); - expect(res.body.message).toMatch(/Admin access required/i); + expect(res.body.error.message).toMatch(/Admin access required/i); }); it.each([ @@ -252,7 +252,7 @@ describe('GET /v1/admin/indexer/dead-letter', () => { .set('Authorization', `Bearer ${adminToken()}`); expect(res.status).toBe(400); - expect(res.body.error).toMatch(/startDate must be a valid ISO-8601 date/); + expect(res.body.error.message).toMatch(/startDate must be a valid ISO-8601 date/); expect(mocks.prisma.indexerDeadLetterEvent.findMany).not.toHaveBeenCalled(); }); @@ -262,7 +262,7 @@ describe('GET /v1/admin/indexer/dead-letter', () => { .set('Authorization', `Bearer ${adminToken()}`); expect(res.status).toBe(400); - expect(res.body.error).toMatch(/startDate must be before endDate/); + expect(res.body.error.message).toMatch(/startDate must be before endDate/); }); it('answers 500 when the table read fails', async () => { @@ -275,7 +275,7 @@ describe('GET /v1/admin/indexer/dead-letter', () => { .set('Authorization', `Bearer ${adminToken()}`); expect(res.status).toBe(500); - expect(res.body.error).toMatch(/Failed to list dead-letter events/); + expect(res.body.error.message).toMatch(/Failed to list dead-letter events/); }); }); @@ -325,10 +325,14 @@ describe('POST /v1/admin/indexer/dead-letter/:id/replay', () => { expect(res.status).toBe(422); expect(res.body).toMatchObject({ - code: 'replay_failed', - id: 'row-1', - attempts: 2, - errorMessage: 'handler still throws', + error: { + code: 'replay_failed', + details: { + id: 'row-1', + attempts: 2, + errorMessage: 'handler still throws', + }, + }, }); expect(mocks.prisma.indexerDeadLetterEvent.delete).not.toHaveBeenCalled(); }); @@ -344,7 +348,7 @@ describe('POST /v1/admin/indexer/dead-letter/:id/replay', () => { .set('Authorization', `Bearer ${adminToken()}`); expect(res.status).toBe(422); - expect(res.body.code).toBe('undecodable_payload'); + expect(res.body.error.code).toBe('undecodable_payload'); expect(mocks.processEvent).not.toHaveBeenCalled(); }); }); diff --git a/backend/tests/integration/admin-metrics.test.ts b/backend/tests/integration/admin-metrics.test.ts index c96d596b..70c8ef6d 100644 --- a/backend/tests/integration/admin-metrics.test.ts +++ b/backend/tests/integration/admin-metrics.test.ts @@ -469,7 +469,7 @@ describe('GET /v1/admin/indexer/status', () => { .get('/v1/admin/indexer/status') .set('Authorization', `Bearer ${createToken(NON_ADMIN_PUBLIC_KEY)}`); expect(nonAdminRes.status).toBe(403); - expect(nonAdminRes.body.error).toBe('Forbidden'); + expect(nonAdminRes.body.error.code).toBe('FORBIDDEN'); }); it('returns status 200 with indexer status data for admin', async () => { @@ -498,7 +498,7 @@ describe('GET /v1/admin/indexer/status', () => { .set('Authorization', `Bearer ${createToken()}`); expect(res.status).toBe(500); - expect(res.body).toEqual({ error: 'Failed to fetch indexer status' }); + expect(res.body).toEqual({ error: { code: 'INTERNAL_SERVER_ERROR', message: 'Failed to fetch indexer status' } }); }); }); @@ -538,7 +538,7 @@ describe('POST /v1/admin/indexer/reset', () => { .send(body); expect(res.status).toBe(400); - expect(res.body).toEqual({ error: 'ledger must be a non-negative integer' }); + expect(res.body).toEqual({ error: { code: 'BAD_REQUEST', message: 'ledger must be a non-negative integer' } }); } expect(resetIndexer).not.toHaveBeenCalled(); @@ -572,7 +572,7 @@ describe('POST /v1/admin/indexer/reset', () => { .send({ ledger: 100 }); expect(res.status).toBe(500); - expect(res.body).toEqual({ error: 'Reset failed' }); + expect(res.body).toEqual({ error: { code: 'INTERNAL_SERVER_ERROR', message: 'Reset failed' } }); }); it('returns a dry-run preview without calling resetIndexer when dryRun=true', async () => { @@ -615,7 +615,7 @@ describe('POST /v1/admin/indexer/reset', () => { .send({ ledger: 500 }); expect(res.status).toBe(500); - expect(res.body).toEqual({ error: 'Reset failed' }); + expect(res.body).toEqual({ error: { code: 'INTERNAL_SERVER_ERROR', message: 'Reset failed' } }); expect(resetIndexer).not.toHaveBeenCalled(); }); }); @@ -652,7 +652,7 @@ describe('POST /v1/admin/indexer/replay', () => { .set('Authorization', `Bearer ${createToken()}`); expect(res.status).toBe(400); - expect(res.body).toEqual({ error: 'from_ledger must be a non-negative integer' }); + expect(res.body).toEqual({ error: { code: 'BAD_REQUEST', message: 'from_ledger must be a non-negative integer' } }); } expect(replayFromLedger).not.toHaveBeenCalled(); @@ -683,7 +683,7 @@ describe('POST /v1/admin/indexer/replay', () => { .set('Authorization', `Bearer ${createToken()}`); expect(res.status).toBe(500); - expect(res.body).toEqual({ error: 'Replay failed' }); + expect(res.body).toEqual({ error: { code: 'INTERNAL_SERVER_ERROR', message: 'Replay failed' } }); }); it('returns a dry-run preview without triggering a replay when dryRun=true', async () => { @@ -726,7 +726,7 @@ describe('POST /v1/admin/indexer/replay', () => { .set('Authorization', `Bearer ${createToken()}`); expect(res.status).toBe(500); - expect(res.body).toEqual({ error: 'Replay failed' }); + expect(res.body).toEqual({ error: { code: 'INTERNAL_SERVER_ERROR', message: 'Replay failed' } }); expect(replayFromLedger).not.toHaveBeenCalled(); }); }); diff --git a/backend/tests/integration/cancel-status-filter.test.ts b/backend/tests/integration/cancel-status-filter.test.ts index 94d0b824..a7474c1b 100644 --- a/backend/tests/integration/cancel-status-filter.test.ts +++ b/backend/tests/integration/cancel-status-filter.test.ts @@ -114,10 +114,14 @@ function createStreamCancelledEvent( } async function cleanupDatabase() { + // Scoped to this file's fixtures: vitest runs each test file in its own process + // against one shared database, and a whole-table `deleteMany` deleted the rows + // another file had just seeded. const db = getDb(); - await db.streamEvent.deleteMany(); - await db.stream.deleteMany(); - await db.user.deleteMany(); + const streamId = BigInt(STREAM_ID); + await db.streamEvent.deleteMany({ where: { streamId } }); + await db.stream.deleteMany({ where: { streamId } }); + await db.user.deleteMany({ where: { publicKey: { in: [SENDER, RECIPIENT] } } }); } const STREAM_ID = 900; diff --git a/backend/tests/integration/events-list.test.ts b/backend/tests/integration/events-list.test.ts index 77c2d7e1..ee58bde9 100644 --- a/backend/tests/integration/events-list.test.ts +++ b/backend/tests/integration/events-list.test.ts @@ -94,7 +94,7 @@ describe('GET /v1/events', () => { .get('/v1/events') .set('Authorization', `Bearer ${token}`); expect(res.status).toBe(400); - expect(res.body.error).toMatch(/address/i); + expect(res.body.error.message).toMatch(/address/i); expect(mocks.prisma.streamEvent.findMany).not.toHaveBeenCalled(); }); @@ -111,7 +111,7 @@ describe('GET /v1/events', () => { .get(`/v1/events?address=${ADDR}`) .set('Authorization', `Bearer ${otherToken}`); expect(res.status).toBe(403); - expect(res.body.error).toBe('Forbidden'); + expect(res.body.error.code).toBe('FORBIDDEN'); }); it('returns the paged event list for the wallet', async () => { diff --git a/backend/tests/integration/sse-subscribe.test.ts b/backend/tests/integration/sse-subscribe.test.ts index 8944386c..55faeb3b 100644 --- a/backend/tests/integration/sse-subscribe.test.ts +++ b/backend/tests/integration/sse-subscribe.test.ts @@ -73,8 +73,8 @@ describe('GET /v1/events/subscribe', () => { .set('Authorization', `Bearer ${token}`); expect(res.status).toBe(400); - expect(res.body.message).toBe('Invalid subscription parameters'); - expect(res.body.errors).toBeDefined(); + expect(res.body.error.message).toBe('Invalid subscription parameters'); + expect(res.body.error.details).toBeDefined(); }); it('rejects requests missing authentication', async () => { diff --git a/backend/tests/integration/stream-actions.test.ts b/backend/tests/integration/stream-actions.test.ts index e908b183..52835692 100644 --- a/backend/tests/integration/stream-actions.test.ts +++ b/backend/tests/integration/stream-actions.test.ts @@ -146,8 +146,7 @@ describe('stream action routes', () => { expect(response.status).toBe(401); expect(response.body).toMatchObject({ - error: 'Unauthorized', - message: 'Invalid or expired token', + error: { code: 'UNAUTHORIZED', message: 'Invalid or expired token' }, }); }); diff --git a/backend/tests/integration/stream-lifecycle.test.ts b/backend/tests/integration/stream-lifecycle.test.ts index 62a2029f..2e78f17f 100644 --- a/backend/tests/integration/stream-lifecycle.test.ts +++ b/backend/tests/integration/stream-lifecycle.test.ts @@ -214,12 +214,27 @@ function createStreamCancelledEvent( }; } +/** Every on-chain stream id this file seeds, whether by hand or via the worker. */ +const OWNED_STREAM_IDS = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 100].map( + (id) => BigInt(id), +); + async function cleanupDatabase() { - // Clean up in order to respect foreign key constraints + // Delete in order to respect foreign key constraints, and only what this file + // owns: vitest runs each test file in its own process against one shared + // database, so a whole-table `deleteMany` here removed another file's fixtures + // while it was mid-assertion. `sender` catches rows a previous aborted run left + // behind; the keypair is regenerated per process, so it never matches another + // file's wallet. const db = getDb(); - await db.streamEvent.deleteMany(); - await db.stream.deleteMany(); - await db.user.deleteMany(); + const streams = { + OR: [{ streamId: { in: OWNED_STREAM_IDS } }, { sender: SENDER }], + }; + await db.streamEvent.deleteMany({ + where: { OR: [{ streamId: { in: OWNED_STREAM_IDS } }, { stream: streams }] }, + }); + await db.stream.deleteMany({ where: streams }); + await db.user.deleteMany({ where: { publicKey: { in: [SENDER, RECIPIENT] } } }); await db.indexerState.deleteMany(); } diff --git a/backend/tests/integration/top-up.test.ts b/backend/tests/integration/top-up.test.ts index 2f47d2e5..73705f6c 100644 --- a/backend/tests/integration/top-up.test.ts +++ b/backend/tests/integration/top-up.test.ts @@ -4,23 +4,111 @@ import request from 'supertest'; const SENDER = 'GABC123XYZ456DEF789GHI012JKL345MNO678PQR901STU234VWX567YZA'; const OTHER = 'GDEF456ABC789GHI012JKL345MNO678PQR901STU234VWX567YZA123BCD'; -const mockStream = { +const STREAM_ID = 42n; +const START_TIME = 1700000000n; +const RATE = 100n; +const INITIAL_DEPOSIT = 86400n; + +const streamRow = () => ({ id: 'uuid-1', - streamId: 42, + streamId: STREAM_ID, sender: SENDER, recipient: OTHER, tokenAddress: 'CBCD789EFG012HIJ345KLM678NOP901QRS234TUV567WXY890ZAB123CDE', - ratePerSecond: '100', - depositedAmount: '86400', + ratePerSecond: RATE.toString(), + depositedAmount: INITIAL_DEPOSIT.toString(), withdrawnAmount: '0', - startTime: 1700000000, + startTime: START_TIME, endTime: null, - lastUpdateTime: 1700000000, + lastUpdateTime: START_TIME, isPaused: false, pausedAt: null, totalPausedDuration: 0, isActive: true, -}; +}); + +/** + * A stream table small enough to hold in memory, with the two things the + * top-up writers actually depend on: the `(transactionHash, eventType)` unique + * key, and a `FOR UPDATE` row lock that a writer must hold while it decides + * whether it is the one that applies a top-up. + */ +class FakeStreams { + rows = new Map>(); + events = new Map>(); + locksHeld = 0; + + reset() { + this.rows.clear(); + this.events.clear(); + this.locksHeld = 0; + this.rows.set(STREAM_ID.toString(), streamRow() as unknown as Record); + } + + deposited(): bigint { + return BigInt(this.rows.get(STREAM_ID.toString())!.depositedAmount as string); + } + + eventCount(): number { + return this.events.size; + } + + /** Mirrors `SELECT ... FROM "Stream" WHERE "streamId" = $1 FOR UPDATE`. */ + lock(streamId: bigint): number { + this.locksHeld += 1; + return this.rows.has(streamId.toString()) ? 1 : 0; + } + + /** The writer must hold the row lock, exactly as Postgres would enforce. */ + private assertLocked() { + if (this.locksHeld === 0) { + throw new Error('top-up written without holding the stream row lock'); + } + } + + tx(): any { + const self = this; + return { + $executeRaw: async (_chunks: unknown, ...values: unknown[]) => + self.lock(values[0] as bigint), + stream: { + findUniqueOrThrow: async ({ where }: any) => ({ ...self.rows.get(String(where.streamId)) }), + update: async ({ where, data }: any) => { + self.assertLocked(); + const row = self.rows.get(String(where.streamId))!; + Object.assign(row, data); + return row; + }, + }, + streamEvent: { + findUnique: async ({ where }: any) => { + const { transactionHash, eventType } = where.transactionHash_eventType; + return self.events.get(`${transactionHash}|${eventType}`) ?? null; + }, + create: async ({ data }: any) => { + self.assertLocked(); + self.events.set(`${data.transactionHash}|${data.eventType}`, { ...data }); + return data; + }, + upsert: async ({ where, create, update }: any) => { + self.assertLocked(); + const { transactionHash, eventType } = where.transactionHash_eventType; + const key = `${transactionHash}|${eventType}`; + const existing = self.events.get(key); + if (existing) { + Object.assign(existing, update); + return existing; + } + const row = { ...create }; + self.events.set(key, row); + return row; + }, + }, + }; + } +} + +const store = new FakeStreams(); const { mockPrisma } = vi.hoisted(() => ({ mockPrisma: { @@ -36,8 +124,8 @@ const { mockPrisma } = vi.hoisted(() => ({ count: vi.fn().mockResolvedValue(0), }, $queryRaw: vi.fn().mockResolvedValue([{ '?column?': 1n }]), - $executeRawUnsafe: vi.fn().mockResolvedValue(undefined), - $transaction: vi.fn(async (fn: any) => fn(mockPrisma)), + $executeRaw: vi.fn(), + $transaction: vi.fn(), $disconnect: vi.fn(), }, })); @@ -72,7 +160,7 @@ vi.mock('../../src/middleware/auth.js', async (importOriginal) => { next(); }), requireAdmin: vi.fn((_req: any, res: any, _next: any) => { - res.status(403).json({ error: 'Forbidden' }); + res.status(403).json({ error: { code: 'FORBIDDEN', message: 'Forbidden' } }); }), }; }); @@ -81,21 +169,39 @@ vi.mock('../../src/middleware/auth.js', async (importOriginal) => { import app from '../../src/app.js'; import { topUpStream } from '../../src/services/sorobanService.js'; import { swaggerSpec } from '../../src/config/swagger.js'; +import { applyToppedUpEvent } from '../../src/services/top-up-writer.js'; + +const postTopUp = (amount = '1000', streamId = '42') => + request(app) + .post(`/v1/streams/${streamId}/top-up`) + .set('Authorization', 'Bearer dummy') + .send({ amount }); + +/** What the indexer would write for the same transaction the API just sent. */ +const indexTopUpEvent = (txHash = 'abc123txhash', absoluteDeposited = '87400') => + mockPrisma.$transaction((tx: any) => + applyToppedUpEvent(tx, { + streamId: STREAM_ID, + txHash, + amount: '1000', + newDepositedAmount: absoluteDeposited, + ledgerSequence: 5_112_233, + timestamp: 1700000600, + }), + ); // ── Tests ───────────────────────────────────────────────────────────────────── describe('POST /v1/streams/:streamId/top-up', () => { beforeEach(() => { vi.clearAllMocks(); - vi.mocked(mockPrisma.stream.findUnique).mockResolvedValue(mockStream as any); - vi.mocked(mockPrisma.stream.update).mockResolvedValue({ ...mockStream, depositedAmount: '87400' } as any); + store.reset(); + vi.mocked(mockPrisma.stream.findUnique).mockResolvedValue(streamRow() as any); + mockPrisma.$transaction.mockImplementation(async (fn: any) => fn(store.tx())); }); it('returns 200 with txHash on valid request', async () => { - const res = await request(app) - .post('/v1/streams/42/top-up') - .set('Authorization', 'Bearer dummy') - .send({ amount: '1000' }); + const res = await postTopUp(); expect(res.status).toBe(200); expect(res.body.txHash).toBe('abc123txhash'); @@ -104,10 +210,7 @@ describe('POST /v1/streams/:streamId/top-up', () => { }); it('documented TopUpResponse schema matches the actual controller response keys (issue #1536)', async () => { - const res = await request(app) - .post('/v1/streams/42/top-up') - .set('Authorization', 'Bearer dummy') - .send({ amount: '1000' }); + const res = await postTopUp(); expect(res.status).toBe(200); expect(Object.keys(res.body).sort()).toEqual(['depositedAmount', 'streamId', 'txHash']); @@ -116,9 +219,7 @@ describe('POST /v1/streams/:streamId/top-up', () => { const schema = (swaggerSpec as any)?.components?.schemas?.TopUpResponse; expect(schema).toBeDefined(); - expect(Object.keys(schema.properties).sort()).toEqual( - Object.keys(res.body).sort(), - ); + expect(Object.keys(schema.properties).sort()).toEqual(Object.keys(res.body).sort()); expect(schema.required.sort()).toEqual(Object.keys(res.body).sort()); }); @@ -132,28 +233,19 @@ describe('POST /v1/streams/:streamId/top-up', () => { }); it('returns 400 when amount is not a positive integer string', async () => { - const res = await request(app) - .post('/v1/streams/42/top-up') - .set('Authorization', 'Bearer dummy') - .send({ amount: '-50' }); + const res = await postTopUp('-50'); expect(res.status).toBe(400); }); it('returns 400 when amount is a float string', async () => { - const res = await request(app) - .post('/v1/streams/42/top-up') - .set('Authorization', 'Bearer dummy') - .send({ amount: '1.5' }); + const res = await postTopUp('1.5'); expect(res.status).toBe(400); }); it('returns 400 when amount exceeds the maximum allowed length', async () => { - const res = await request(app) - .post('/v1/streams/42/top-up') - .set('Authorization', 'Bearer dummy') - .send({ amount: '1'.repeat(10000) }); + const res = await postTopUp('1'.repeat(10000)); expect(res.status).toBe(400); expect(topUpStream).not.toHaveBeenCalled(); @@ -162,10 +254,7 @@ describe('POST /v1/streams/:streamId/top-up', () => { it('returns 404 when stream does not exist', async () => { vi.mocked(mockPrisma.stream.findUnique).mockResolvedValue(null); - const res = await request(app) - .post('/v1/streams/99/top-up') - .set('Authorization', 'Bearer dummy') - .send({ amount: '1000' }); + const res = await postTopUp('1000', '99'); expect(res.status).toBe(404); }); @@ -180,114 +269,184 @@ describe('POST /v1/streams/:streamId/top-up', () => { expect(res.status).toBe(403); }); - it('updates depositedAmount in DB on success', async () => { - // After $executeRawUnsafe, findUnique returns the updated stream - vi.mocked(mockPrisma.stream.findUnique).mockResolvedValue({ ...mockStream, depositedAmount: '87400' } as any); - - await request(app) - .post('/v1/streams/42/top-up') - .set('Authorization', 'Bearer dummy') - .send({ amount: '1000' }); - - // Verify the atomic SQL increment was called - expect(mockPrisma.$executeRawUnsafe).toHaveBeenCalled(); - }); - it('returns 409 when stream is inactive', async () => { - vi.mocked(mockPrisma.stream.findUnique).mockResolvedValue({ ...mockStream, isActive: false } as any); + vi.mocked(mockPrisma.stream.findUnique).mockResolvedValue({ ...streamRow(), isActive: false } as any); - const res = await request(app) - .post('/v1/streams/42/top-up') - .set('Authorization', 'Bearer dummy') - .send({ amount: '1000' }); + const res = await postTopUp(); expect(res.status).toBe(409); expect(res.body.error.message).toMatch(/inactive stream/); }); it('returns 409 when stream is paused', async () => { - vi.mocked(mockPrisma.stream.findUnique).mockResolvedValue({ ...mockStream, isPaused: true } as any); + vi.mocked(mockPrisma.stream.findUnique).mockResolvedValue({ ...streamRow(), isPaused: true } as any); - const res = await request(app) - .post('/v1/streams/42/top-up') - .set('Authorization', 'Bearer dummy') - .send({ amount: '1000' }); + const res = await postTopUp(); expect(res.status).toBe(409); expect(res.body.error.message).toMatch(/paused stream/); }); +}); - it('leaves DB unchanged when topUpStream fails on-chain', async () => { +describe('top-up single-writer race (issue #1848)', () => { + beforeEach(() => { + vi.clearAllMocks(); + store.reset(); + vi.mocked(mockPrisma.stream.findUnique).mockResolvedValue(streamRow() as any); + mockPrisma.$transaction.mockImplementation(async (fn: any) => fn(store.tx())); + }); + + it('writes the amount and its TOPPED_UP marker in one pass', async () => { + const res = await postTopUp('1000'); + + expect(res.status).toBe(200); + expect(store.deposited()).toBe(87400n); + expect(store.eventCount()).toBe(1); + // Extending the deposit must extend the runway, or the stream still ends on + // the old schedule and the recipient cannot claim what was topped up. + expect(store.rows.get('42')!.endTime).toBe(START_TIME + 874n); + }); + + it('does not double-count when the indexer commits first', async () => { + await indexTopUpEvent(); + + const res = await postTopUp('1000'); + + expect(res.status).toBe(200); + expect(res.body.depositedAmount).toBe('87400'); + expect(store.deposited()).toBe(87400n); + expect(store.eventCount()).toBe(1); + }); + + it('does not double-count when the API commits first', async () => { + const res = await postTopUp('1000'); + expect(res.body.depositedAmount).toBe('87400'); + + await indexTopUpEvent(); + + expect(store.deposited()).toBe(87400n); + expect(store.eventCount()).toBe(1); + }); + + it('reconciles the row to the chain value when the API incremented from a stale row', async () => { + // The API only knows `row + amount`. If the row was already behind the + // chain, that sum is wrong, and the marker must not lock the error in: + // the chain's absolute value has to be able to correct it once. + const res = await postTopUp('1000'); + expect(res.body.depositedAmount).toBe('87400'); + + await indexTopUpEvent('abc123txhash', '88400'); + + expect(store.deposited()).toBe(88400n); + expect(store.rows.get('42')!.endTime).toBe(START_TIME + 884n); + expect(store.eventCount()).toBe(1); + // Claiming the real ledger position is what retires the marker: a third + // writer for the same hash is now a replay, not a confirmation. + expect(store.events.get('abc123txhash|TOPPED_UP')!.ledgerSequence).toBe(5_112_233); + }); + + it('ignores a replay of an event the indexer already reconciled', async () => { + await indexTopUpEvent('abc123txhash', '87400'); + + // A re-read of an older ledger must not roll the absolute value backwards. + await indexTopUpEvent('abc123txhash', '86400'); + + expect(store.deposited()).toBe(87400n); + expect(store.eventCount()).toBe(1); + }); + + it('reports the indexer amount to the caller whichever writer wins', async () => { + await indexTopUpEvent('abc123txhash', '87400'); + const viaIndexer = await postTopUp('1000'); + store.reset(); + const viaApi = await postTopUp('1000'); + + expect(viaIndexer.body.depositedAmount).toBe(viaApi.body.depositedAmount); + }); + + it('applies two concurrent top-ups of different transactions without losing either', async () => { + vi.mocked(topUpStream).mockImplementation(async (_id, amount) => { + await new Promise((resolve) => setTimeout(resolve, 10)); + return `tx-${amount}`; + }); + + const [res1, res2] = await Promise.all([postTopUp('1000'), postTopUp('2000')]); + + expect([res1.status, res2.status]).toEqual([200, 200]); + expect(store.deposited()).toBe(89400n); + expect(store.eventCount()).toBe(2); + expect(Math.max(Number(res1.body.depositedAmount), Number(res2.body.depositedAmount))).toBe(89400); + }); + + it('refuses to write for a stream row that disappeared mid-transaction', async () => { + mockPrisma.$transaction.mockImplementation(async (fn: any) => { + store.rows.delete(STREAM_ID.toString()); + return fn(store.tx()); + }); + + const res = await postTopUp(); + + expect(res.status).toBe(404); + expect(res.body.error.code).toBe('NOT_FOUND'); + expect(store.events.size).toBe(0); + }); +}); + +describe('top-up error codes (issue #1850)', () => { + beforeEach(() => { + vi.clearAllMocks(); + store.reset(); + vi.mocked(mockPrisma.stream.findUnique).mockResolvedValue(streamRow() as any); + mockPrisma.$transaction.mockImplementation(async (fn: any) => fn(store.tx())); + }); + + it('leaves the DB untouched and answers 400 TOP_UP_FAILED when the chain call fails', async () => { vi.mocked(topUpStream).mockRejectedValueOnce( - new Error('Transaction failed on-chain: tx_fail_post_submission') + new Error('Transaction failed on-chain: tx_fail_post_submission'), ); + const before = store.deposited(); - const res = await request(app) - .post('/v1/streams/42/top-up') - .set('Authorization', 'Bearer dummy') - .send({ amount: '1000' }); + const res = await postTopUp(); expect(res.status).toBe(400); - expect(mockPrisma.stream.update).not.toHaveBeenCalled(); + expect(res.body.error.code).toBe('TOP_UP_FAILED'); + expect(store.deposited()).toBe(before); + expect(store.eventCount()).toBe(0); }); - it('handles concurrent top-ups correctly without lost updates', async () => { - // Both requests read the same initial state - vi.mocked(mockPrisma.stream.findUnique).mockResolvedValue(mockStream as any); - - // Simulate some delay in the on-chain transaction - vi.mocked(topUpStream).mockImplementation(async () => { - await new Promise((resolve) => setTimeout(resolve, 50)); - return 'txhash-mock'; - }); - - // We also need to implement $executeRaw to mock the atomic DB update - // because that's what we will change the implementation to use. - // However, if it's the OLD implementation, it calls update(). - // We should make the mocked executeRaw update a local variable and - // also make update() do the same, so we can test both the failure and success. - - let currentDeposited = BigInt(mockStream.depositedAmount); - - vi.mocked(mockPrisma.$executeRawUnsafe).mockImplementation(async (query: any, ...values: any[]) => { - const amountToAdd = BigInt(values[0]); - currentDeposited += amountToAdd; - return 1 as any; - }); + it('answers 5xx when the database fails after the top-up landed on chain', async () => { + mockPrisma.$transaction.mockRejectedValue(new Error('connection terminated unexpectedly')); - vi.mocked(mockPrisma.stream.findUnique).mockImplementation(async () => { - return { ...mockStream, depositedAmount: currentDeposited.toString() } as any; - }); + const res = await postTopUp(); - // Actually, to make the test pass after the fix, the best way to do atomic update is to do a transaction where we re-fetch the stream. - // Let's first just test if it works with the old implementation (should fail). - - const req1 = request(app) - .post('/v1/streams/42/top-up') - .set('Authorization', 'Bearer dummy') - .send({ amount: '1000' }); - - const req2 = request(app) - .post('/v1/streams/42/top-up') - .set('Authorization', 'Bearer dummy') - .send({ amount: '2000' }); - - const [res1, res2] = await Promise.all([req1, req2]); - - expect(res1.status).toBe(200); - expect(res2.status).toBe(200); - - // The initial amount is 86400. We add 1000 and 2000. - // 86400 + 1000 + 2000 = 89400. - // Because we mock Prisma in vitest, the controller's Prisma calls will hit our mock. - // We will assert on the final 'depositedAmount' returned in the response, or what was sent to Prisma. - // Since the API returns depositedAmount, let's just check the response body. - - // If it lost update, one response will be 87400 and the other 88400. - // If it didn't lose update, the second one should be 89400. - const amt1 = parseInt(res1.body.depositedAmount); - const amt2 = parseInt(res2.body.depositedAmount); - expect(Math.max(amt1, amt2)).toBe(89400); + expect(res.status).toBe(500); + expect(res.body.error.code).toBe('INTERNAL_SERVER_ERROR'); + expect(res.body.error.code).not.toBe('TOP_UP_FAILED'); + // The caller must not be told this is their transaction's fault, or they + // retry and pay for the top-up twice. + expect(res.body.error.message).not.toMatch(/on chain/); }); + it('answers 5xx, not 4xx, when the guard read fails', async () => { + vi.mocked(mockPrisma.stream.findUnique).mockRejectedValue(new Error('connection pool exhausted')); + + const res = await postTopUp(); + + expect(res.status).toBe(500); + expect(topUpStream).not.toHaveBeenCalled(); + }); + + it('maps a known Prisma failure to its sanitized code', async () => { + const constraintError = Object.assign(new Error('Unique constraint failed'), { + name: 'PrismaClientKnownRequestError', + code: 'P2002', + }); + mockPrisma.$transaction.mockRejectedValue(constraintError); + + const res = await postTopUp(); + + expect(res.status).toBe(409); + expect(res.body.error.code).toBe('DUPLICATE_ENTRY'); + expect(JSON.stringify(res.body)).not.toMatch(/Unique constraint failed/); + }); }); diff --git a/backend/tests/soroban-event-worker.test.ts b/backend/tests/soroban-event-worker.test.ts index 869a9a94..ef759ce0 100644 --- a/backend/tests/soroban-event-worker.test.ts +++ b/backend/tests/soroban-event-worker.test.ts @@ -546,10 +546,12 @@ describe('SorobanEventWorker', () => { }; const mockTx = { + $executeRaw: vi.fn().mockResolvedValue(1), stream: { findUniqueOrThrow: vi.fn().mockResolvedValue({ ratePerSecond: '10', - startTime: 1700000000, + // `Stream.startTime` is a BigInt column, so Prisma hands back a bigint. + startTime: 1700000000n, totalPausedDuration: 0, }), update: vi.fn().mockResolvedValue({}), @@ -577,7 +579,9 @@ describe('SorobanEventWorker', () => { // Second processing (replay of same txHash): the event now exists, so // depositedAmount/endTime must NOT be re-applied. - mockTx.streamEvent.findUnique.mockResolvedValueOnce({ id: 'topup-event-row' }); + // Second processing (replay of same txHash): the event now exists with the + // ledger this worker wrote, so it is a real replay, not an API marker. + mockTx.streamEvent.findUnique.mockResolvedValueOnce({ id: 'topup-event-row', ledgerSequence: 4001 }); await expect((worker as any).handleStreamToppedUp(mockEvent, mockEvent.topic![1])).resolves.not.toThrow(); expect(mockTx.stream.update).not.toHaveBeenCalled(); expect(mockTx.streamEvent.upsert).not.toHaveBeenCalled(); diff --git a/backend/tests/sse.controller.test.ts b/backend/tests/sse.controller.test.ts index 69299a14..59743d91 100644 --- a/backend/tests/sse.controller.test.ts +++ b/backend/tests/sse.controller.test.ts @@ -56,7 +56,11 @@ describe('SSE Controller', () => { await subscribe(req as Request, res as Response); expect(res.status).toHaveBeenCalledWith(503); - expect(res.json).toHaveBeenCalledWith(expect.objectContaining({ message: 'Too many connections' })); + expect(res.json).toHaveBeenCalledWith( + expect.objectContaining({ + error: expect.objectContaining({ message: 'Too many connections' }), + }), + ); }); it('should subscribe and add client to sseService', async () => { @@ -119,8 +123,10 @@ describe('SSE Controller', () => { expect(res.status).toHaveBeenCalledWith(400); expect(res.json).toHaveBeenCalledWith( expect.objectContaining({ - message: 'Invalid subscription parameters', - errors: expect.arrayContaining([expect.objectContaining({ code: expect.any(String) })]), + error: expect.objectContaining({ + message: 'Invalid subscription parameters', + details: expect.arrayContaining([expect.objectContaining({ code: expect.any(String) })]), + }), }), ); }); diff --git a/backend/tests/stream-rate-limiter.test.ts b/backend/tests/stream-rate-limiter.test.ts index bc0724c2..82a7c0c5 100644 --- a/backend/tests/stream-rate-limiter.test.ts +++ b/backend/tests/stream-rate-limiter.test.ts @@ -84,8 +84,8 @@ describe('Stream Creation Rate Limiter Middleware', () => { .set('Content-Type', 'application/json'); expect(res.status).toBe(429); - expect(res.body).toHaveProperty('error'); - expect(res.body.error).toContain('rate limit'); + expect(res.body.error.code).toBe('RATE_LIMITED'); + expect(res.body.error.message).toContain('rate limit'); }); it('should include Retry-After header in rate limit response', async () => { @@ -342,10 +342,10 @@ describe('Stream Creation Rate Limiter Middleware', () => { .set('Content-Type', 'application/json'); expect(res.status).toBe(429); - expect(res.body).toHaveProperty('error'); - expect(res.body).toHaveProperty('message'); - expect(typeof res.body.message).toBe('string'); - expect(res.body.message.toLowerCase()).toContain('rate limit'); + expect(Object.keys(res.body)).toEqual(['error']); + expect(res.body.error.code).toBe('RATE_LIMITED'); + expect(typeof res.body.error.message).toBe('string'); + expect(res.body.error.message.toLowerCase()).toContain('rate limit'); }); it('should include rate limit information in response headers', async () => { diff --git a/backend/tests/stream-simulation.test.ts b/backend/tests/stream-simulation.test.ts index d57bb60e..719ec5c7 100644 --- a/backend/tests/stream-simulation.test.ts +++ b/backend/tests/stream-simulation.test.ts @@ -164,7 +164,7 @@ describe('simulateStreamAction', () => { try { await expect( service.simulateStreamAction('cancel', senderKp.publicKey(), { streamId: '1' }), - ).rejects.toMatchObject({ status: 503, code: 'contract_not_configured' }); + ).rejects.toMatchObject({ statusCode: 503, code: 'contract_not_configured' }); } finally { process.env.STREAM_CONTRACT_ID = contractId; } @@ -209,7 +209,7 @@ describe('simulateStreamAction', () => { amount: '100', duration: 60, }), - ).rejects.toMatchObject({ status: 400, code: 'invalid_params' }); + ).rejects.toMatchObject({ statusCode: 400, code: 'invalid_params' }); }); it('rejects a zero amount', async () => { @@ -219,7 +219,7 @@ describe('simulateStreamAction', () => { amount: '0', duration: 60, }), - ).rejects.toMatchObject({ status: 400, code: 'invalid_params' }); + ).rejects.toMatchObject({ statusCode: 400, code: 'invalid_params' }); }); it('rejects a non-positive or fractional duration', async () => { @@ -230,7 +230,7 @@ describe('simulateStreamAction', () => { amount: '100', duration, }), - ).rejects.toMatchObject({ status: 400, code: 'invalid_params' }); + ).rejects.toMatchObject({ statusCode: 400, code: 'invalid_params' }); } }); }); @@ -270,13 +270,13 @@ describe('simulateStreamAction', () => { it('rejects a non-numeric streamId', async () => { await expect( service.simulateStreamAction('cancel', senderKp.publicKey(), { streamId: '12abc' }), - ).rejects.toMatchObject({ status: 400, code: 'invalid_params' }); + ).rejects.toMatchObject({ statusCode: 400, code: 'invalid_params' }); }); it('rejects a missing streamId', async () => { await expect( service.simulateStreamAction('cancel', senderKp.publicKey(), {}), - ).rejects.toMatchObject({ status: 400, code: 'invalid_params' }); + ).rejects.toMatchObject({ statusCode: 400, code: 'invalid_params' }); }); }); @@ -296,13 +296,13 @@ describe('simulateStreamAction', () => { const streamIds = Array.from({ length: 11 }, (_, i) => String(i + 1)); await expect( service.simulateStreamAction('batch_withdraw', recipientKp.publicKey(), { streamIds }), - ).rejects.toMatchObject({ status: 400, code: 'invalid_params' }); + ).rejects.toMatchObject({ statusCode: 400, code: 'invalid_params' }); }); it('rejects an empty batch', async () => { await expect( service.simulateStreamAction('batch_withdraw', recipientKp.publicKey(), { streamIds: [] }), - ).rejects.toMatchObject({ status: 400, code: 'invalid_params' }); + ).rejects.toMatchObject({ statusCode: 400, code: 'invalid_params' }); }); }); @@ -448,15 +448,15 @@ describe('simulateStreamAction', () => { expect(err).toBeInstanceOf(ApiError); expect(err).toMatchObject({ - status: 400, + statusCode: 400, code: 'simulation_failed', message: 'Stream not found', }); expect((err as InstanceType).details).toMatchObject({ action: 'cancel', contractErrorCode: 2, + hint: expect.any(String), }); - expect((err as InstanceType).details?.hint).toBeTruthy(); }); it('passes through an unrecognised reason when no code can be parsed', async () => { @@ -467,7 +467,7 @@ describe('simulateStreamAction', () => { await expect( service.simulateStreamAction('withdraw', recipientKp.publicKey(), { streamId: '1' }), ).rejects.toMatchObject({ - status: 400, + statusCode: 400, code: 'simulation_failed', message: 'Simulation of "withdraw" failed: Host function failed: panic', }); diff --git a/backend/tests/unit/validation.test.ts b/backend/tests/unit/validation.test.ts index 91e561bf..8353c2bf 100644 --- a/backend/tests/unit/validation.test.ts +++ b/backend/tests/unit/validation.test.ts @@ -1,90 +1,8 @@ import express from "express"; import request from "supertest"; import { describe, expect, it } from "vitest"; -import { z } from "zod"; -import { - INVALID_PARAMETERS_TYPE, - assertResponseMatches, - validateRequest, -} from "../../src/middleware/schema-validator.middleware.js"; import { parsePagination } from "../../src/validators/stream.validator.js"; -const streamResponse = z.object({ id: z.string(), duration: z.number().int().positive() }); - -function buildApp() { - const app = express(); - app.use(express.json()); - app.post( - "/streams/:id", - validateRequest({ - params: z.object({ id: z.string().regex(/^\d+$/, "Expected numeric id") }), - query: z.object({ dryRun: z.enum(["true", "false"]).optional() }).strict(), - headers: z.object({ "x-client": z.string().min(1, "Header is required") }), - body: z.object({ - duration: z.number().int("Expected positive integer").positive("must be greater than 0"), - }), - }), - (req, res) => { - const { params, body } = res.locals.validated; - res.json({ id: params.id, duration: body.duration }); - }, - ); - return app; -} - -describe("schema validator middleware", () => { - it("passes valid requests with parsed values to the controller", async () => { - const res = await request(buildApp()) - .post("/streams/42?dryRun=true") - .set("x-client", "web") - .send({ duration: 3600 }); - - expect(res.status).toBe(200); - expect(assertResponseMatches(streamResponse, res.body)).toEqual({ id: "42", duration: 3600 }); - }); - - it("rejects an invalid body with RFC 7807 problem details", async () => { - const res = await request(buildApp()).post("/streams/42").set("x-client", "web").send({ duration: 0 }); - - expect(res.status).toBe(400); - expect(res.headers["content-type"]).toMatch(/application\/problem\+json/); - expect(res.body).toEqual({ - type: INVALID_PARAMETERS_TYPE, - title: "Invalid Request Parameters", - status: 400, - detail: "Invalid parameter 'duration': must be greater than 0", - invalidParams: [{ name: "duration", reason: "must be greater than 0" }], - }); - }); - - it("rejects undocumented query parameters", async () => { - const res = await request(buildApp()) - .post("/streams/42?debug=1") - .set("x-client", "web") - .send({ duration: 10 }); - - expect(res.status).toBe(400); - expect(res.body.invalidParams[0].reason).toMatch(/debug/); - }); - - it("rejects invalid path params and missing headers together", async () => { - const res = await request(buildApp()).post("/streams/abc").send({ duration: 10 }); - - expect(res.status).toBe(400); - const names = res.body.invalidParams.map((p: { name: string }) => p.name); - expect(names).toEqual(expect.arrayContaining(["x-client", "id"])); - }); - - it("does not coerce string numbers in the body", async () => { - const res = await request(buildApp()).post("/streams/42").set("x-client", "web").send({ duration: "10" }); - expect(res.status).toBe(400); - }); - - it("assertResponseMatches flags contract drift", () => { - expect(() => assertResponseMatches(streamResponse, { id: "1", duration: "10" })).toThrow(/duration/); - }); -}); - describe("parsePagination (#1644)", () => { function paginationApp() { const app = express(); diff --git a/frontend/src/lib/api/webhooks.test.ts b/frontend/src/lib/api/webhooks.test.ts index 90e8e5f3..85a0adad 100644 --- a/frontend/src/lib/api/webhooks.test.ts +++ b/frontend/src/lib/api/webhooks.test.ts @@ -72,7 +72,7 @@ describe("webhooks api", () => { vi.mocked(shared.fetchWithTimeout).mockResolvedValueOnce({ ok: false, status: 400, - json: async () => ({ error: "Bad Request" }), + json: async () => ({ error: { code: "WEBHOOK_INVALID_REQUEST", message: "Bad Request" } }), } as unknown as Response); await expect(listWebhooks("address")).rejects.toThrow("Bad Request"); }); diff --git a/frontend/src/lib/api/webhooks.ts b/frontend/src/lib/api/webhooks.ts index 52988ca1..14781d8d 100644 --- a/frontend/src/lib/api/webhooks.ts +++ b/frontend/src/lib/api/webhooks.ts @@ -51,8 +51,10 @@ async function request(path: string, init?: RequestInit): Promise { ...init, }); if (!response.ok) { - const body = (await response.json().catch(() => null)) as { error?: string } | null; - throw new Error(body?.error ?? `Webhook request failed (${response.status})`); + const body = (await response.json().catch(() => null)) as { + error?: { message?: string }; + } | null; + throw new Error(body?.error?.message ?? `Webhook request failed (${response.status})`); } if (response.status === 204) return undefined as T; return (await response.json()) as T; From 5ae876b0fe37b4e7f9a75f9a06a6168e911c17dc Mon Sep 17 00:00:00 2001 From: eazeeshow Date: Sat, 21 Nov 2026 16:28:20 +0100 Subject: [PATCH 2/4] test(backend): pin SSE rejection responses to the unified envelope #1747's new subscribe tests asserted the flat `{ message }` and `{ message, errors }` bodies that #1851 replaces with `{ error: { code, message, details } }`. Statuses, messages, the Retry-After header and the "no SSE headers committed" checks are unchanged. --- backend/tests/sse-auth-cleanup.test.ts | 28 +++++++++++++++++++------- 1 file changed, 21 insertions(+), 7 deletions(-) diff --git a/backend/tests/sse-auth-cleanup.test.ts b/backend/tests/sse-auth-cleanup.test.ts index 0665addd..add599f1 100644 --- a/backend/tests/sse-auth-cleanup.test.ts +++ b/backend/tests/sse-auth-cleanup.test.ts @@ -93,7 +93,10 @@ describe('SSE subscribe authorization and rejection paths (#1747)', () => { expect(res.status).toHaveBeenCalledWith(503); expect(res.json).toHaveBeenCalledWith({ - message: 'Server is shutting down, please reconnect shortly.', + error: { + code: 'SERVICE_UNAVAILABLE', + message: 'Server is shutting down, please reconnect shortly.', + }, }); expect(mocks.checkCapacity).not.toHaveBeenCalled(); expect(mocks.findMany).not.toHaveBeenCalled(); @@ -114,7 +117,9 @@ describe('SSE subscribe authorization and rejection paths (#1747)', () => { expect(res.setHeader).toHaveBeenCalledWith('Retry-After', '60'); expect(res.status).toHaveBeenCalledWith(429); - expect(res.json).toHaveBeenCalledWith({ message: 'Too many SSE connections from this IP. Max 5.' }); + expect(res.json).toHaveBeenCalledWith({ + error: { code: 'SSE_CONNECTION_REJECTED', message: 'Too many SSE connections from this IP. Max 5.' }, + }); expect(res.writeHead).not.toHaveBeenCalled(); expect(res.write).not.toHaveBeenCalled(); expect(mocks.addClient).not.toHaveBeenCalled(); @@ -130,7 +135,9 @@ describe('SSE subscribe authorization and rejection paths (#1747)', () => { expect(res.setHeader).not.toHaveBeenCalledWith('Retry-After', expect.anything()); expect(res.status).toHaveBeenCalledWith(503); - expect(res.json).toHaveBeenCalledWith({ message: 'SSE capacity reached.' }); + expect(res.json).toHaveBeenCalledWith({ + error: { code: 'SSE_CONNECTION_REJECTED', message: 'SSE capacity reached.' }, + }); }); it('honours an explicit 503 rejection without inventing a Retry-After hint', async () => { @@ -151,7 +158,9 @@ describe('SSE subscribe authorization and rejection paths (#1747)', () => { await runSubscribe(makeReq({ user: undefined }), res); expect(res.statusCode).toBe(500); - expect(res.json).toHaveBeenCalledWith({ message: 'Internal server error' }); + expect(res.json).toHaveBeenCalledWith({ + error: { code: 'INTERNAL_SERVER_ERROR', message: 'Internal server error' }, + }); expect(res.writeHead).not.toHaveBeenCalled(); expect(res.write).not.toHaveBeenCalled(); expect(mocks.addClient).not.toHaveBeenCalled(); @@ -165,7 +174,9 @@ describe('SSE subscribe authorization and rejection paths (#1747)', () => { await runSubscribe(makeReq(), res); expect(res.statusCode).toBe(500); - expect(res.json).toHaveBeenCalledWith({ message: 'Internal server error' }); + expect(res.json).toHaveBeenCalledWith({ + error: { code: 'INTERNAL_SERVER_ERROR', message: 'Internal server error' }, + }); expect(res.writeHead).not.toHaveBeenCalled(); expect(mocks.addClient).not.toHaveBeenCalled(); }); @@ -179,8 +190,11 @@ describe('SSE subscribe authorization and rejection paths (#1747)', () => { expect(res.statusCode).toBe(400); expect(res.json).toHaveBeenCalledWith( expect.objectContaining({ - message: 'Invalid subscription parameters', - errors: expect.arrayContaining([expect.objectContaining({ code: expect.any(String) })]), + error: expect.objectContaining({ + code: 'VALIDATION_ERROR', + message: 'Invalid subscription parameters', + details: expect.arrayContaining([expect.objectContaining({ code: expect.any(String) })]), + }), }), ); expect(res.writeHead).not.toHaveBeenCalled(); From 745c15e01e993891bcfbb1c1fb2c69f282db4b9a Mon Sep 17 00:00:00 2001 From: eazeeshow Date: Sat, 21 Nov 2026 16:39:09 +0100 Subject: [PATCH 3/4] docs(backend): describe the error envelope the API actually returns #1851 leaves exactly one envelope, so the prose has to stop advertising the shapes it replaced. AUTHENTICATION, SANDBOX_MODE, API_VERSIONING, DEPRECATION_POLICY and the backend README now show `{error:{code,message,details}}` with the codes the middleware really sends, and the sunset example is marked unimplemented instead of implying a 410 no route produces. --- backend/README.md | 20 +++++++++++++++++- backend/docs/API_VERSIONING.md | 33 ++++++++++++++++++++---------- backend/docs/AUTHENTICATION.md | 24 ++++++++++++++++++---- backend/docs/DEPRECATION_POLICY.md | 24 ++++++++++++++-------- backend/docs/SANDBOX_MODE.md | 14 ++++++++----- 5 files changed, 86 insertions(+), 29 deletions(-) diff --git a/backend/README.md b/backend/README.md index e8a4fb16..c5e2676f 100644 --- a/backend/README.md +++ b/backend/README.md @@ -41,7 +41,7 @@ The CORS policy is built in `src/config/cors.ts` when the app starts and depends - **`FRONTEND_URL` is required in production.** Set it to the frontend origin, e.g. `FRONTEND_URL=https://app.flowfi.xyz`. Comma-separate several origins (e.g. preview domains). Each entry is normalised to its origin, so `https://app.flowfi.xyz/` works too. If no valid origin is configured, or any entry is not an absolute `http(s)` URL (including `*`), the server throws at startup instead of running with an open policy. - **Set `NODE_ENV=production` in every deployed environment.** Otherwise the development policy applies (headers and methods unrestricted). The server logs a warning at startup when `NODE_ENV` is unset. -- Browser requests from any other origin get `403 {"error": "CORS origin not allowed"}` and no `Access-Control-Allow-Origin` header. The rejected origin is logged at `warn` level. +- Browser requests from any other origin get `403 {"error": {"code": "FORBIDDEN", "message": "CORS origin not allowed"}}` and no `Access-Control-Allow-Origin` header. The rejected origin is logged at `warn` level. - Requests without an `Origin` header (health checks, webhooks, curl, server-to-server calls) are not affected. ## Prisma Database @@ -99,6 +99,24 @@ If a `prisma generate` / `prisma migrate` command misbehaves, check `prisma.conf All REST API endpoints are prefixed with `/v1`. Refer to the API Documentation in the root `README.md` and the `docs/` folder for versioning and authentication details. +### Error envelope + +Every non-2xx JSON response has the same body, produced only by `sendApiError` (`src/lib/api-error.ts`) and by `ApiError` → `errorHandler` for thrown errors: + +```json +{ + "error": { + "code": "VALIDATION_ERROR", + "message": "Request validation failed", + "details": [{ "path": "sender", "message": "Sender address is required", "code": "too_small" }] + } +} +``` + +- `code` is stable and machine-readable — branch on it. `message` is display text and may change. +- `details` is present only when there is something to report and its type depends on `code` (an array of zod issues for `VALIDATION_ERROR`, an object of remediation hints elsewhere). +- This covers 4xx and 5xx from every layer, including the rate limiter's `429 RATE_LIMITED`, the body-size `413 PAYLOAD_TOO_LARGE` and the CORS `403 FORBIDDEN`. The spec's `components.schemas.Error` in `swagger/flowfi.openapi.json` is the generated contract. + ## Server-Sent Events (SSE) The backend exposes an SSE endpoint (`/v1/streams/events`) to stream real-time updates to the frontend whenever on-chain stream events are indexed. diff --git a/backend/docs/API_VERSIONING.md b/backend/docs/API_VERSIONING.md index 1469d6a4..8a836f28 100644 --- a/backend/docs/API_VERSIONING.md +++ b/backend/docs/API_VERSIONING.md @@ -104,16 +104,23 @@ X-API-Migration-Path: /v1/streams ### Example Deprecated Response +Sunset responses use the same envelope as every other error; see +[DEPRECATION_POLICY.md](./DEPRECATION_POLICY.md) for the contract and for the fact +that no endpoint emits it yet. + ```json { - "error": "Deprecated endpoint", - "message": "This endpoint has been deprecated. Please use /v1/streams instead.", - "deprecated": true, - "migration": { - "old": "/streams", - "new": "/v1/streams" - }, - "sunsetDate": "2024-12-31" + "error": { + "code": "ENDPOINT_DEPRECATED", + "message": "This endpoint has been deprecated. Please use /v1/streams instead.", + "details": { + "migration": { + "old": "/streams", + "new": "/v1/streams" + }, + "sunsetDate": "2024-12-31" + } + } } ``` @@ -221,9 +228,13 @@ GET /v2/streams Response: ```json { - "error": "Unsupported API version", - "message": "API version 'v2' is not supported. Supported versions: v1", - "supportedVersions": ["v1"] + "error": { + "code": "UNSUPPORTED_API_VERSION", + "message": "API version 'v2' is not supported. Supported versions: v1", + "details": { + "supportedVersions": ["v1"] + } + } } ``` diff --git a/backend/docs/AUTHENTICATION.md b/backend/docs/AUTHENTICATION.md index 984cf617..713caf1e 100644 --- a/backend/docs/AUTHENTICATION.md +++ b/backend/docs/AUTHENTICATION.md @@ -105,12 +105,26 @@ const response = await fetch('http://localhost:3001/v1/users/me', { ## Error Responses +Every non-2xx response, including the two 401s below, uses the shared error envelope: + +```json +{ + "error": { + "code": "STRING_CODE", + "message": "human readable text", + "details": "optional; omitted when there is nothing to report" + } +} +``` + ### 401 Unauthorized - Missing Token ```json { - "error": "Unauthorized", - "message": "Missing or invalid Authorization header. Expected format: Bearer " + "error": { + "code": "UNAUTHORIZED", + "message": "Missing Bearer token" + } } ``` @@ -118,8 +132,10 @@ const response = await fetch('http://localhost:3001/v1/users/me', { ```json { - "error": "Unauthorized", - "message": "Invalid or expired signature" + "error": { + "code": "UNAUTHORIZED", + "message": "Invalid or expired token" + } } ``` diff --git a/backend/docs/DEPRECATION_POLICY.md b/backend/docs/DEPRECATION_POLICY.md index b9e0dd7f..5418b94d 100644 --- a/backend/docs/DEPRECATION_POLICY.md +++ b/backend/docs/DEPRECATION_POLICY.md @@ -88,16 +88,24 @@ X-API-Migration-Path: /v1/streams ``` **Body:** + +> Not yet implemented — no endpoint in `src/` returns `410` or sets the +> `X-API-*` headers. This is the shape such a response must use once it exists, +> written against the envelope every other error already returns. + ```json { - "error": "Deprecated endpoint", - "message": "This endpoint has been deprecated. Please use /v1/streams instead.", - "deprecated": true, - "migration": { - "old": "/streams", - "new": "/v1/streams" - }, - "sunsetDate": "2024-12-31" + "error": { + "code": "ENDPOINT_DEPRECATED", + "message": "This endpoint has been deprecated. Please use /v1/streams instead.", + "details": { + "migration": { + "old": "/streams", + "new": "/v1/streams" + }, + "sunsetDate": "2024-12-31" + } + } } ``` diff --git a/backend/docs/SANDBOX_MODE.md b/backend/docs/SANDBOX_MODE.md index fbac64f4..2b547986 100644 --- a/backend/docs/SANDBOX_MODE.md +++ b/backend/docs/SANDBOX_MODE.md @@ -148,11 +148,15 @@ If an endpoint requires sandbox mode and the request is not sandboxed: ```json { - "error": "Sandbox mode required", - "message": "This endpoint requires sandbox mode.", - "hint": { - "header": "X-Sandbox-Mode: true", - "queryParam": "?sandbox=true" + "error": { + "code": "SANDBOX_MODE_REQUIRED", + "message": "This endpoint requires sandbox mode. Add X-Sandbox-Mode: true header or ?sandbox=true query parameter.", + "details": { + "hint": { + "header": "X-Sandbox-Mode: true", + "queryParam": "?sandbox=true" + } + } } } ``` From a1356534738597839a2de83b7188c242219b562d Mon Sep 17 00:00:00 2001 From: eazeeshow Date: Sat, 21 Nov 2026 16:45:30 +0100 Subject: [PATCH 4/4] docs(backend): show validation details in the shape most sites emit --- backend/README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/backend/README.md b/backend/README.md index c5e2676f..939733ee 100644 --- a/backend/README.md +++ b/backend/README.md @@ -108,13 +108,13 @@ Every non-2xx JSON response has the same body, produced only by `sendApiError` ( "error": { "code": "VALIDATION_ERROR", "message": "Request validation failed", - "details": [{ "path": "sender", "message": "Sender address is required", "code": "too_small" }] + "details": [{ "path": ["sender"], "message": "Sender address is required", "code": "too_small" }] } } ``` - `code` is stable and machine-readable — branch on it. `message` is display text and may change. -- `details` is present only when there is something to report and its type depends on `code` (an array of zod issues for `VALIDATION_ERROR`, an object of remediation hints elsewhere). +- `details` is present only when there is something to report and its shape depends on `code`: the failing zod issues for `VALIDATION_ERROR`, an object of remediation hints elsewhere. - This covers 4xx and 5xx from every layer, including the rate limiter's `429 RATE_LIMITED`, the body-size `413 PAYLOAD_TOO_LARGE` and the CORS `403 FORBIDDEN`. The spec's `components.schemas.Error` in `swagger/flowfi.openapi.json` is the generated contract. ## Server-Sent Events (SSE)