diff --git a/backend/src/__tests__/transactions-export.test.ts b/backend/src/__tests__/transactions-export.test.ts index 5bd6d0d4..8688b2dd 100644 --- a/backend/src/__tests__/transactions-export.test.ts +++ b/backend/src/__tests__/transactions-export.test.ts @@ -19,6 +19,7 @@ const mockRecords = [ const mockGetMany = vi.fn().mockResolvedValue(mockRecords); const mockGetManyAndCount = vi.fn().mockResolvedValue([mockRecords, mockRecords.length]); +const mockGetCount = vi.fn().mockResolvedValue(mockRecords.length); const mockQueryBuilder = { andWhere: vi.fn().mockReturnThis(), @@ -26,6 +27,7 @@ const mockQueryBuilder = { addOrderBy: vi.fn().mockReturnThis(), skip: vi.fn().mockReturnThis(), take: vi.fn().mockReturnThis(), + getCount: mockGetCount, getMany: mockGetMany, getManyAndCount: mockGetManyAndCount, }; @@ -50,6 +52,7 @@ vi.mock("../services/session-revocation.js", () => ({ import { app } from "../index.js"; import { signToken } from "../services/jwt.js"; +import { encodeTransactionCursor } from "../lib/keyset-cursor.js"; describe("GET /transactions/export", () => { it("rejects a request with no bearer token", async () => { @@ -72,7 +75,7 @@ describe("GET /transactions/export", () => { ); }); - it("returns a paginated JSON page for format=json", async () => { + it("returns a paginated JSON page with pagination metadata for format=json", async () => { const token = signToken(OWN_ADDRESS); const response = await request(app) .get("/transactions/export?format=json&limit=10&offset=0") @@ -83,6 +86,48 @@ describe("GET /transactions/export", () => { expect(response.body).toHaveProperty("total", mockRecords.length); expect(response.body).toHaveProperty("limit", 10); expect(response.body).toHaveProperty("offset", 0); + expect(response.body).toHaveProperty("hasMore", false); + expect(response.body).toHaveProperty("nextCursor", null); + // Verify financial precision is preserved + expect(typeof response.body.transactions[0].amount).toBe("string"); + expect(response.body.transactions[0].amount).toBe("1000"); + }); + + it("accepts a valid cursor for format=json pagination", async () => { + const token = signToken(OWN_ADDRESS); + const cursor = encodeTransactionCursor({ + timestamp: mockRecords[0].timestamp, + id: "11111111-1111-4111-8111-111111111111", + }); + const response = await request(app) + .get(`/transactions/export?format=json&cursor=${encodeURIComponent(cursor)}`) + .set("Authorization", `Bearer ${token}`); + + expect(response.status).toBe(200); + expect(response.body).toHaveProperty("transactions"); + expect(response.body).toHaveProperty("total"); + expect(response.body).toHaveProperty("hasMore"); + }); + + it("rejects an invalid cursor with 400 VALIDATION_ERROR", async () => { + const token = signToken(OWN_ADDRESS); + const response = await request(app) + .get("/transactions/export?format=json&cursor=invalid-cursor-token!") + .set("Authorization", `Bearer ${token}`); + + expect(response.status).toBe(400); + expect(response.body.code).toBe("VALIDATION_ERROR"); + expect(response.body.details).toEqual({ cursor: "invalid" }); + }); + + it("rejects limit above 100 with 400", async () => { + const token = signToken(OWN_ADDRESS); + const response = await request(app) + .get("/transactions/export?format=json&limit=101") + .set("Authorization", `Bearer ${token}`); + + expect(response.status).toBe(400); + expect(response.body.code).toBe("VALIDATION_ERROR"); }); it("streams a CSV by default with a header row and a downloadable filename", async () => { diff --git a/backend/src/__tests__/transactions-pagination.test.ts b/backend/src/__tests__/transactions-pagination.test.ts index 1d2c77de..c0b8fafc 100644 --- a/backend/src/__tests__/transactions-pagination.test.ts +++ b/backend/src/__tests__/transactions-pagination.test.ts @@ -85,11 +85,18 @@ vi.mock("../services/database.js", () => ({ closeDatabase: async () => {}, })); +vi.mock("../services/session-revocation.js", () => ({ + getSessionVersion: vi.fn(async () => 0), + getMaxSessionVersionForEmail: vi.fn(async () => 0), + revokeSessionsForEmail: vi.fn(async () => 1), +})); + import { transactionsRouter } from "../routes/transactions.js"; import { createPayoutHistoryService } from "../services/PayoutHistoryService.js"; import { errorHandler, notFoundHandler } from "../middleware/error.js"; import { requestIdMiddleware } from "../middleware/request-id.js"; import { encodeTransactionCursor } from "../lib/keyset-cursor.js"; +import { signToken } from "../services/jwt.js"; const WALLET = "GAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAWHF"; const OTHER_WALLET = "GBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB"; @@ -296,6 +303,125 @@ describe("GET /transactions/recipient/:walletAddress cursor pagination", () => { }); }); +describe("GET /transactions/export cursor pagination", () => { + it("scopes the page to the authenticated user from bearer token and returns pagination metadata", async () => { + enqueue([], 5); + enqueue([ROW_A, ROW_B, ROW_C]); + + const token = signToken(WALLET); + const res = await request(createApp()) + .get("/transactions/export?format=json&limit=2") + .set("Authorization", `Bearer ${token}`) + .expect(200); + + expect(res.body.total).toBe(5); + expect(res.body.limit).toBe(2); + expect(res.body.offset).toBe(0); + expect(res.body.hasMore).toBe(true); + expect(res.body.transactions.map((t: { id: string }) => t.id)).toEqual([ID_A, ID_B]); + expect(res.body.nextCursor).toBe( + encodeTransactionCursor({ timestamp: ROW_B.timestamp, id: ROW_B.id }) + ); + + const [countBuilder, pageBuilder] = h.builders; + expect(countBuilder.conditions[0].params).toEqual({ recipient: WALLET }); + expect(pageBuilder.conditions[0].params).toEqual({ recipient: WALLET }); + expect(pageBuilder.orders).toEqual([ + ["transaction.timestamp", "DESC"], + ["transaction.id", "DESC"], + ]); + expect(pageBuilder.takeValue).toBe(3); + expect(pageBuilder.skipValue).toBeUndefined(); + }); + + it("continues after the cursor with a keyset predicate, ignoring offset and client wallet param", async () => { + enqueue([], 5); + enqueue([ROW_C]); + + const token = signToken(WALLET); + const cursor = encodeTransactionCursor({ timestamp: ROW_B.timestamp, id: ROW_B.id }); + const res = await request(createApp()) + .get( + `/transactions/export?format=json&cursor=${encodeURIComponent(cursor)}&offset=99&walletAddress=${OTHER_WALLET}` + ) + .set("Authorization", `Bearer ${token}`) + .expect(200); + + expect(res.body.hasMore).toBe(false); + expect(res.body.nextCursor).toBeNull(); + expect(res.body.transactions).toHaveLength(1); + + const [countBuilder, pageBuilder] = h.builders; + expect(countBuilder.conditions[0].params).toEqual({ recipient: WALLET }); + expect(pageBuilder.conditions[0].params).toEqual({ recipient: WALLET }); + expect(pageBuilder.conditions[1].sql).toContain("transaction.timestamp < :cursorTimestamp"); + expect(pageBuilder.conditions[1].params).toEqual({ + cursorTimestamp: ROW_B.timestamp, + cursorId: ROW_B.id, + }); + expect(pageBuilder.skipValue).toBeUndefined(); + }); + + it("applies status and date filters alongside account scope", async () => { + enqueue([], 1); + enqueue([ROW_A]); + + const token = signToken(WALLET); + await request(createApp()) + .get("/transactions/export?format=json&status=completed&startDate=1&endDate=9999999999") + .set("Authorization", `Bearer ${token}`) + .expect(200); + + const [countBuilder, pageBuilder] = h.builders; + expect(countBuilder.conditions).toHaveLength(4); + expect(pageBuilder.conditions).toHaveLength(4); + }); + + it("rejects an unauthenticated request with 401", async () => { + const res = await request(createApp()).get("/transactions/export?format=json").expect(401); + expect(res.body.code).toBe("UNAUTHORIZED"); + expect(h.builders).toHaveLength(0); + }); + + it("rejects a malformed cursor with 400 and does not query the database", async () => { + const token = signToken(WALLET); + const res = await request(createApp()) + .get("/transactions/export?format=json&cursor=bad-cursor!!!") + .set("Authorization", `Bearer ${token}`) + .expect(400); + + expect(res.body.code).toBe("VALIDATION_ERROR"); + expect(res.body.details).toEqual({ cursor: "invalid" }); + expect(h.builders).toHaveLength(0); + }); + + it("rejects page size above 100 with 400", async () => { + const token = signToken(WALLET); + const res = await request(createApp()) + .get("/transactions/export?format=json&limit=101") + .set("Authorization", `Bearer ${token}`) + .expect(400); + + expect(res.body.code).toBe("VALIDATION_ERROR"); + expect(h.builders).toHaveLength(0); + }); + + it("allows maximum page size of 100", async () => { + enqueue([], 0); + enqueue([]); + + const token = signToken(WALLET); + const res = await request(createApp()) + .get("/transactions/export?format=json&limit=100") + .set("Authorization", `Bearer ${token}`) + .expect(200); + + expect(res.body.limit).toBe(100); + const [, pageBuilder] = h.builders; + expect(pageBuilder.takeValue).toBe(101); + }); +}); + describe("PayoutHistoryService.getPayoutsWithCount", () => { it("honours limit and offset and uses the same stable order", async () => { enqueue([ROW_B], 7); diff --git a/backend/src/openapi.ts b/backend/src/openapi.ts index 464f004d..f352e3d9 100644 --- a/backend/src/openapi.ts +++ b/backend/src/openapi.ts @@ -1324,7 +1324,9 @@ registry.registerPath({ path: "/transactions/export", summary: "Export the authenticated wallet's own transaction history", description: - "Always scoped to the authenticated wallet from the bearer token, never a request parameter. format=csv (default) streams an injection-safe CSV of the full matching result set, capped at 50,000 rows. format=json returns one limit/offset page.", + "Always scoped to the authenticated wallet from the bearer token, never a request parameter. " + + "format=csv (default) streams an injection-safe CSV of the full matching result set, capped at 50,000 rows. " + + "format=json returns paginated records with stable keyset cursor pagination matching /transactions/history.", tags: ["Transactions"], security: [{ bearerAuth: [] }], request: { query: transactionExportQuerySchema }, diff --git a/backend/src/routes/transactions.ts b/backend/src/routes/transactions.ts index 82b0cca5..1717d0dd 100644 --- a/backend/src/routes/transactions.ts +++ b/backend/src/routes/transactions.ts @@ -258,8 +258,8 @@ transactionsRouter.get("/history", async (req: Request, res: Response, next: Nex * wallet — a caller can never export another wallet's transactions, * regardless of query parameters. `format=csv` (default) streams the * full matching result set as an injection-safe CSV in fixed-size - * batches, capped at 50,000 rows. `format=json` returns one - * limit/offset page, matching /transactions/history's pagination. + * batches, capped at 50,000 rows. `format=json` returns paginated + * records with stable keyset cursor pagination, matching /transactions/history. * tags: [Transactions] */ transactionsRouter.get("/export", authJwtMiddleware, async (req: Request, res: Response, next: NextFunction) => { @@ -275,24 +275,39 @@ transactionsRouter.get("/export", authJwtMiddleware, async (req: Request, res: R ); } - const { format, startDate, endDate, status, limit, offset } = parsed.data; + const { format, startDate, endDate, status, limit, offset, cursor } = parsed.data; // Access control: the export is always scoped to the authenticated // caller's own wallet, taken from the verified token — never from a // request parameter — so one user cannot export another's transactions. const recipient = req.user!.walletAddress; + const decodedCursor = decodePageCursor(cursor); - logger.info("Exporting transaction history", { recipient, format, startDate, endDate, status }); + logger.info("Exporting transaction history", { + recipient, + format, + startDate, + endDate, + status, + limit, + offset, + cursor: decodedCursor ? "provided" : "none", + }); if (format === "json") { - const { records, total } = await payoutHistoryService.getPayoutsWithCount({ + const page = await payoutHistoryService.getPayoutsPage({ recipient, startDate, endDate, status, limit, offset, + cursor: decodedCursor, + }); + return res.status(200).json({ + transactions: page.records, + total: page.total, + ...buildPageMetadata(page, limit, offset), }); - return res.status(200).json({ transactions: records, total, limit, offset }); } // format === "csv": stream the full authorized result set. diff --git a/backend/src/schemas/transactions.schemas.ts b/backend/src/schemas/transactions.schemas.ts index 6f264870..75005153 100644 --- a/backend/src/schemas/transactions.schemas.ts +++ b/backend/src/schemas/transactions.schemas.ts @@ -77,8 +77,10 @@ export const transactionExportQuerySchema = z.object({ status: z.enum(["pending", "completed", "failed"]).optional(), // Only meaningful for format=json, which returns one page rather than // streaming the full result set. - limit: z.coerce.number().int().min(1).max(100).default(20), + limit: z.coerce.number().int().min(1).max(MAX_TRANSACTION_PAGE_SIZE).default(20), offset: z.coerce.number().int().min(0).default(0), + /** Opaque `(timestamp, id)` cursor returned as `nextCursor` by a prior page. */ + cursor: z.string().min(1).max(512).optional(), }); // Transaction record schema diff --git a/docs/api-surface-contracts.md b/docs/api-surface-contracts.md index 5f624dc6..55f1e9b5 100644 --- a/docs/api-surface-contracts.md +++ b/docs/api-surface-contracts.md @@ -102,7 +102,8 @@ the first registered deprecation. ## Transaction pagination contract -`GET /transactions/history` and `GET /transactions/recipient/:walletAddress` +`GET /transactions/history`, `GET /transactions/recipient/:walletAddress`, and +the authenticated account-scoped `GET /transactions/export` (`format=json`) share one pagination contract (#1259): - **Stable order.** Rows are ordered by `(timestamp DESC, id DESC)`. `timestamp` @@ -120,6 +121,9 @@ share one pagination contract (#1259): after the cursor. - **`hasMore`** is derived from a `limit + 1` probe, so a full last page is not reported as having a next page. +- **Account scope.** `GET /transactions/export` enforces account isolation via + the verified bearer token (`req.user.walletAddress`), rejecting unauthenticated + callers with `401 UNAUTHORIZED` and ignoring client-supplied wallet addresses. The response shape is documented in `docs/openapi.yaml`; the codec lives in `backend/src/lib/keyset-cursor.ts` and is pinned by diff --git a/docs/openapi.json b/docs/openapi.json index 941b0811..4cd87ced 100644 --- a/docs/openapi.json +++ b/docs/openapi.json @@ -3919,7 +3919,7 @@ }, "/transactions/export": { "get": { - "description": "Always scoped to the authenticated wallet from the bearer token, never a request parameter. format=csv (default) streams an injection-safe CSV of the full matching result set, capped at 50,000 rows. format=json returns one limit/offset page.", + "description": "Always scoped to the authenticated wallet from the bearer token, never a request parameter. format=csv (default) streams an injection-safe CSV of the full matching result set, capped at 50,000 rows. format=json returns paginated records with stable keyset cursor pagination matching /transactions/history.", "parameters": [ { "in": "query", @@ -3988,6 +3988,16 @@ "nullable": true, "type": "integer" } + }, + { + "in": "query", + "name": "cursor", + "required": false, + "schema": { + "maxLength": 512, + "minLength": 1, + "type": "string" + } } ], "responses": { diff --git a/docs/openapi.yaml b/docs/openapi.yaml index 754543af..9b8e0188 100644 --- a/docs/openapi.yaml +++ b/docs/openapi.yaml @@ -3258,7 +3258,8 @@ paths: description: Always scoped to the authenticated wallet from the bearer token, never a request parameter. format=csv (default) streams an injection-safe CSV of the full matching result set, capped at 50,000 - rows. format=json returns one limit/offset page. + rows. format=json returns paginated records with stable keyset cursor + pagination matching /transactions/history. tags: - Transactions security: @@ -3312,6 +3313,13 @@ paths: required: false name: offset in: query + - schema: + type: string + minLength: 1 + maxLength: 512 + required: false + name: cursor + in: query responses: "200": description: CSV file (format=csv) or a paginated JSON page (format=json)