From 4e07258bc6209614950b4ea65036e10ff1485470 Mon Sep 17 00:00:00 2001 From: Okorie Chigozie Jehoshaphat Date: Fri, 20 Nov 2026 15:47:27 +0100 Subject: [PATCH] feat(nonce): implement key nonce-based replay protection for signed trade messages --- .env.example | 3 + src/config.schema.ts | 4 + src/constants/error.constants.ts | 1 + .../stellar-signature.middleware.ts | 100 ++++-- src/modules/creator/buy.controller.ts | 4 + src/modules/creator/sell.controller.ts | 4 + src/modules/creator/transfer.controller.ts | 75 ++++ src/modules/creators/creators.routes.ts | 25 +- src/modules/keys/keys.routes.ts | 22 ++ src/modules/nonce/nonce.controllers.ts | 37 ++ src/modules/nonce/nonce.middleware.ts | 77 ++++ src/modules/nonce/nonce.routes.ts | 7 + src/modules/nonce/nonce.service.ts | 121 +++++++ .../nonce/trade-nonce.integration.test.ts | 335 ++++++++++++++++++ 14 files changed, 785 insertions(+), 30 deletions(-) create mode 100644 src/modules/creator/transfer.controller.ts create mode 100644 src/modules/nonce/trade-nonce.integration.test.ts diff --git a/.env.example b/.env.example index 4716f632..3f0d2167 100644 --- a/.env.example +++ b/.env.example @@ -101,6 +101,9 @@ SOROBAN_POLL_TIMEOUT_MS=120000 NONCE_REGISTRY_CONTRACT_ID= NONCE_CACHE_TTL_SECONDS=30 +# Trade message replay protection nonce TTL in seconds (#1194, default 5 minutes) +TRADE_NONCE_TTL_SECONDS=300 + # LP position registry contract LP_CONTRACT_ID= diff --git a/src/config.schema.ts b/src/config.schema.ts index f1ddaad3..467aebbb 100644 --- a/src/config.schema.ts +++ b/src/config.schema.ts @@ -289,6 +289,10 @@ export const envSchema = z NONCE_REGISTRY_CONTRACT_ID: optionalNonEmptyString, NONCE_CACHE_TTL_SECONDS: z.coerce.number().int().positive().default(30), + // Nonce-based replay protection for signed trade messages (#1194). + // Configurable TTL for one-time nonces stored in Redis (default 5 minutes). + TRADE_NONCE_TTL_SECONDS: z.coerce.number().int().positive().default(300), + // LP position registry contract LP_CONTRACT_ID: optionalNonEmptyString, diff --git a/src/constants/error.constants.ts b/src/constants/error.constants.ts index ff76c4b7..bebe70d1 100644 --- a/src/constants/error.constants.ts +++ b/src/constants/error.constants.ts @@ -29,6 +29,7 @@ export const ErrorCode = { DEPENDENCY_UNAVAILABLE: 'dependency_unavailable', MISSING_IDEMPOTENCY_KEY: 'missing_idempotency_key', REQUEST_IN_PROGRESS: 'request_in_progress', + NONCE_INVALID: 'nonce_invalid', } as const; export type ErrorCodeType = (typeof ErrorCode)[keyof typeof ErrorCode]; diff --git a/src/middlewares/stellar-signature.middleware.ts b/src/middlewares/stellar-signature.middleware.ts index 530c0e37..8bf076dc 100644 --- a/src/middlewares/stellar-signature.middleware.ts +++ b/src/middlewares/stellar-signature.middleware.ts @@ -11,6 +11,7 @@ import { ErrorCode } from '../constants/error.constants'; import { logger } from '../utils/logger.utils'; import { validateSignedActionNonce, + verifyAndConsumeTradeNonce, NonceAlreadyConsumedError, NonceMismatchError, } from '../modules/nonce'; @@ -19,6 +20,15 @@ export interface StellarSignedRequest extends Request { walletAddress?: string; signatureVerified?: boolean; nonce?: number; + tradeNonceVerified?: boolean; +} + +export interface StellarSignatureOptions { + /** + * When true, enforces trade nonce-based replay protection (#1194). + * Requires `nonce` in signed payload, verified against Redis and deleted atomically. + */ + tradeNonce?: boolean; } const SIGNATURE_TIMESTAMP_TOLERANCE_MS = 5 * 60 * 1000; // 5 minutes @@ -55,7 +65,7 @@ function buildCanonicalMessage(body: unknown, timestamp: string): Buffer { * On success, attaches `walletAddress` and `signatureVerified=true` to the request. * On failure, returns 401 (missing/expired) or 403 (invalid signature). */ -export function requireStellarSignature() { +export function requireStellarSignature(options: StellarSignatureOptions = {}) { return async ( req: StellarSignedRequest, res: Response, @@ -150,46 +160,80 @@ export function requireStellarSignature() { req.walletAddress = address; req.signatureVerified = true; - // Replay protection: validate and consume single-use nonce when provided (#1039) - const nonceHeader = - readHeader(req, 'x-nonce') ?? (req.body as any)?.nonce; - if ( - nonceHeader !== undefined && - nonceHeader !== null && - nonceHeader !== '' - ) { - const nonceNum = Number(nonceHeader); - if (!Number.isInteger(nonceNum) || nonceNum < 0) { + // Trade nonce replay protection (#1194) + if (options.tradeNonce) { + const rawTradeNonce = + (req.body as any)?.nonce ?? readHeader(req, 'x-nonce'); + if ( + rawTradeNonce === undefined || + rawTradeNonce === null || + String(rawTradeNonce).trim() === '' + ) { sendError( res, - 400, - ErrorCode.BAD_REQUEST, - 'Invalid nonce format — must be a non-negative integer' + 401, + ErrorCode.NONCE_INVALID, + 'Nonce is required in signed trade payload' ); return; } - try { - await validateSignedActionNonce( - address, - nonceNum, - 'stellar_signed_action' + + const isValid = await verifyAndConsumeTradeNonce( + address, + rawTradeNonce + ); + if (!isValid) { + sendError( + res, + 401, + ErrorCode.NONCE_INVALID, + 'Nonce is invalid, expired, or already used' ); - req.nonce = nonceNum; - } catch (nonceError) { - if (nonceError instanceof NonceAlreadyConsumedError) { - sendConflict(res, nonceError.message); - return; - } - if (nonceError instanceof NonceMismatchError) { + return; + } + req.tradeNonceVerified = true; + } else { + // Replay protection: validate and consume single-use nonce when provided (#1039) + const nonceHeader = + readHeader(req, 'x-nonce') ?? (req.body as any)?.nonce; + if ( + nonceHeader !== undefined && + nonceHeader !== null && + nonceHeader !== '' + ) { + const nonceNum = Number(nonceHeader); + if (!Number.isInteger(nonceNum) || nonceNum < 0) { sendError( res, 400, ErrorCode.BAD_REQUEST, - nonceError.message + 'Invalid nonce format — must be a non-negative integer' ); return; } - throw nonceError; + try { + await validateSignedActionNonce( + address, + nonceNum, + 'stellar_signed_action' + ); + req.nonce = nonceNum; + } catch (nonceError) { + if (nonceError instanceof NonceAlreadyConsumedError) { + sendConflict(res, nonceError.message); + return; + } + if (nonceError instanceof NonceMismatchError) { + sendError( + res, + 400, + ErrorCode.BAD_REQUEST, + nonceError.message + ); + return; + } + throw nonceError; + } } } diff --git a/src/modules/creator/buy.controller.ts b/src/modules/creator/buy.controller.ts index 37e25f28..22bff5a1 100644 --- a/src/modules/creator/buy.controller.ts +++ b/src/modules/creator/buy.controller.ts @@ -36,6 +36,10 @@ export const buySchema = z.object({ * current bonding-curve price exceeds it. */ max_price: z.number().nonnegative().optional(), + /** + * One-time trade nonce for replay protection (#1194). + */ + nonce: z.union([z.string(), z.number()]).optional(), }); export type BuyRequestBody = z.infer; diff --git a/src/modules/creator/sell.controller.ts b/src/modules/creator/sell.controller.ts index 66fe61e8..94b001b3 100644 --- a/src/modules/creator/sell.controller.ts +++ b/src/modules/creator/sell.controller.ts @@ -55,6 +55,10 @@ export const sellSchema = z.object({ */ min_price: z.number().nonnegative(), fee_xlm: z.number().nonnegative().default(0), + /** + * One-time trade nonce for replay protection (#1194). + */ + nonce: z.union([z.string(), z.number()]).optional(), }); export type SellRequestBody = z.infer; diff --git a/src/modules/creator/transfer.controller.ts b/src/modules/creator/transfer.controller.ts new file mode 100644 index 00000000..e95c3328 --- /dev/null +++ b/src/modules/creator/transfer.controller.ts @@ -0,0 +1,75 @@ +import type { Response } from 'express'; +import { z } from 'zod'; +import type { StellarSignedRequest } from '../../middlewares/stellar-signature.middleware'; +import { ErrorCode } from '../../constants/error.constants'; +import { + sendError, + sendForbidden, + sendNotFound, + sendSuccess, +} from '../../utils/api-response.utils'; +import { logger } from '../../utils/logger.utils'; +import { transferKeys } from '../keys/key-transfer.service'; +import { KeyNotFoundError } from '../keys/key-fees.service'; +import { PositionFrozenError } from '../keys/key-freeze.service'; +import { StellarAddressSchema } from '../wallet/wallet.schemas'; + +export const transferSchema = z.object({ + toAddress: StellarAddressSchema, + quantity: z.number().int().positive(), + fromAddress: z.string().optional(), + /** + * One-time trade nonce for replay protection (#1194). + */ + nonce: z.union([z.string(), z.number()]).optional(), +}); + +export type TransferRequestBody = z.infer; + +export async function httpTransferCreatorKey( + req: StellarSignedRequest, + res: Response +): Promise { + const body = req.body as TransferRequestBody; + const fromAddress = req.walletAddress || body.fromAddress; + const keyId = String(req.params.id || req.params.keyId); + + if (!fromAddress) { + sendError(res, 400, ErrorCode.BAD_REQUEST, 'Sender wallet address is required'); + return; + } + + try { + const result = await transferKeys( + keyId, + fromAddress, + body.toAddress, + body.quantity + ); + sendSuccess(res, result, 200, 'Keys transferred successfully'); + } catch (error) { + if (error instanceof KeyNotFoundError) { + sendNotFound(res, 'Key'); + return; + } + if (error instanceof PositionFrozenError) { + sendForbidden(res, error.message); + return; + } + if (error instanceof Error) { + if ( + error.message.includes('Insufficient balance') || + error.message.includes('Quantity must be positive') || + error.message.includes('Cannot transfer to the same address') + ) { + sendError(res, 400, ErrorCode.BAD_REQUEST, error.message); + return; + } + } + logger.error( + { error, keyId, from: fromAddress, to: body.toAddress }, + 'Key transfer failed' + ); + throw error; + } +} diff --git a/src/modules/creators/creators.routes.ts b/src/modules/creators/creators.routes.ts index cd15324f..028c23b3 100644 --- a/src/modules/creators/creators.routes.ts +++ b/src/modules/creators/creators.routes.ts @@ -31,6 +31,11 @@ import { validateBody } from '../../middlewares/validate-body.middleware'; import { idempotencyMiddleware } from '../../middlewares/idempotency.middleware'; import { httpBuyCreatorKey, buySchema } from '../creator/buy.controller'; import { httpSellCreatorKey, sellSchema } from '../creator/sell.controller'; +import { + httpTransferCreatorKey, + transferSchema, +} from '../creator/transfer.controller'; +import { requireTradeNonce } from '../nonce/nonce.middleware'; import { platformPauseGuard } from '../../middlewares/platform-pause.middleware'; import { httpCreatePost, @@ -60,7 +65,8 @@ creatorsRouter.post( // Platform-wide and per-key pause validation (#988) runs before any trade // work so a paused platform/key rejects with 503 immediately. platformPauseGuard(), - requireStellarSignature(), + requireStellarSignature({ tradeNonce: true }), + requireTradeNonce(), idempotencyMiddleware(), buyKeyRateLimit, enforceBuyCooldown(), @@ -80,12 +86,27 @@ creatorsRouter.post( validateCreatorParam('id'), // Platform-wide and per-key pause validation (#988). platformPauseGuard(), - requireStellarSignature(), + requireStellarSignature({ tradeNonce: true }), + requireTradeNonce(), idempotencyMiddleware(), buyKeyRateLimit, validateBody(sellSchema), httpSellCreatorKey ); +/** + * POST /api/v1/creators/:id/transfer + * + * Transfer keys to another wallet with replay protection (#1194). + */ +creatorsRouter.post( + '/:id/transfer', + validateCreatorParam('id'), + platformPauseGuard(), + requireStellarSignature({ tradeNonce: true }), + requireTradeNonce(), + validateBody(transferSchema), + httpTransferCreatorKey +); creatorsRouter.post('/:id/dividends', requireJwtAuth, httpDistributeDividend); creatorsRouter.get('/:id/posts', validateCreatorParam('id'), httpListPosts); creatorsRouter.post( diff --git a/src/modules/keys/keys.routes.ts b/src/modules/keys/keys.routes.ts index e19d46f7..e1e2ba4d 100644 --- a/src/modules/keys/keys.routes.ts +++ b/src/modules/keys/keys.routes.ts @@ -2,6 +2,14 @@ import { getRoyaltyEnforcement } from '../marketplaces/marketplace.service'; // src/modules/keys/keys.routes.ts import { Router } from 'express'; import { z } from 'zod'; +import { requireStellarSignature } from '../../middlewares/stellar-signature.middleware'; +import { requireTradeNonce } from '../nonce/nonce.middleware'; +import { validateBody } from '../../middlewares/validate-body.middleware'; +import { platformPauseGuard } from '../../middlewares/platform-pause.middleware'; +import { + httpTransferCreatorKey, + transferSchema, +} from '../creator/transfer.controller'; import { getSubscriptionStatus } from './subscription-status.service'; import { sendError, @@ -3012,4 +3020,18 @@ router.get( router.all('/:keyId/gate', (_req, res) => { res.set('Allow', 'GET').sendStatus(405); }); + +/** + * POST /api/v1/keys/:keyId/transfer + * Transfer keys to another wallet with nonce-based replay protection (#1194). + */ +router.post( + '/:keyId/transfer', + platformPauseGuard(), + requireStellarSignature({ tradeNonce: true }), + requireTradeNonce(), + validateBody(transferSchema), + httpTransferCreatorKey +); + export default router; diff --git a/src/modules/nonce/nonce.controllers.ts b/src/modules/nonce/nonce.controllers.ts index b776763b..6f13eee8 100644 --- a/src/modules/nonce/nonce.controllers.ts +++ b/src/modules/nonce/nonce.controllers.ts @@ -6,6 +6,8 @@ import { GetNonceQuerySchema, ConsumeNonceBodySchema } from './nonce.schemas'; import { getWalletNonce, consumeWalletNonce, + generateTradeNonce, + getTradeNonceTTL, NonceAlreadyConsumedError, NonceMismatchError, } from './nonce.service'; @@ -17,6 +19,7 @@ import { zodIssuesToDetails, } from '../../utils/api-response.utils'; import { ErrorCode } from '../../constants/error.constants'; +import { StellarAddressSchema } from '../wallet/wallet.schemas'; /** * GET /api/v1/nonce?wallet= @@ -84,3 +87,37 @@ export async function httpConsumeWalletNonce( next(error); } } + +/** + * GET /nonce/:wallet + * Issues a fresh one-time nonce stored in Redis with TTL for replay protection (#1194). + */ +export async function httpGetTradeNonce( + req: Request, + res: Response, + next: NextFunction +): Promise { + try { + const wallet = req.params.wallet; + const parsed = StellarAddressSchema.safeParse(wallet); + if (!parsed.success) { + sendValidationError( + res, + 'Invalid wallet address parameter', + zodIssuesToDetails(parsed.error.issues) + ); + return; + } + + const nonce = await generateTradeNonce(parsed.data); + const ttl = getTradeNonceTTL(); + + sendSuccess(res, { + wallet: parsed.data, + nonce, + ttl, + }); + } catch (error) { + next(error); + } +} diff --git a/src/modules/nonce/nonce.middleware.ts b/src/modules/nonce/nonce.middleware.ts index af59a9b1..63220551 100644 --- a/src/modules/nonce/nonce.middleware.ts +++ b/src/modules/nonce/nonce.middleware.ts @@ -4,6 +4,7 @@ import type { Request, Response, NextFunction } from 'express'; import { validateSignedActionNonce, + verifyAndConsumeTradeNonce, NonceAlreadyConsumedError, NonceMismatchError, } from './nonce.service'; @@ -119,3 +120,79 @@ export function requireNonceReplayProtection( } }; } + +/** + * Middleware that validates single-use trade nonces stored in Redis (#1194). + * Requires nonce in signed trade payload. + * Atomically verifies and consumes nonce on receipt. + * Rejects missing, expired, or already-used nonces with HTTP 401 and error code 'nonce_invalid'. + */ +export function requireTradeNonce() { + return async ( + req: Request, + res: Response, + next: NextFunction + ): Promise => { + if ((req as any).tradeNonceVerified) { + next(); + return; + } + + // Wallet address resolved from stellar signature, JWT, header, or body + const wallet = + (req as any).walletAddress || + (req as any).user?.wallet || + req.headers['x-wallet-address'] || + (req.body as any)?.fromAddress || + (req.body as any)?.wallet; + + const rawNonce = + (req.body as any)?.nonce ?? + req.headers['x-nonce']; + + if (rawNonce === undefined || rawNonce === null || String(rawNonce).trim() === '') { + sendError( + res, + 401, + ErrorCode.NONCE_INVALID, + 'Nonce is required in signed payload' + ); + return; + } + + if (!wallet || typeof wallet !== 'string') { + sendError( + res, + 401, + ErrorCode.NONCE_INVALID, + 'Cannot validate nonce: wallet address could not be determined' + ); + return; + } + + const walletCheck = StellarAddressSchema.safeParse(wallet); + if (!walletCheck.success) { + sendError( + res, + 401, + ErrorCode.NONCE_INVALID, + 'Invalid wallet address for nonce validation' + ); + return; + } + + const isValid = await verifyAndConsumeTradeNonce(wallet, rawNonce); + if (!isValid) { + sendError( + res, + 401, + ErrorCode.NONCE_INVALID, + 'Nonce is invalid, expired, or already used' + ); + return; + } + + (req as any).tradeNonceVerified = true; + next(); + }; +} diff --git a/src/modules/nonce/nonce.routes.ts b/src/modules/nonce/nonce.routes.ts index e539ea9e..a7914cb0 100644 --- a/src/modules/nonce/nonce.routes.ts +++ b/src/modules/nonce/nonce.routes.ts @@ -5,6 +5,7 @@ import { Router } from 'express'; import { httpGetWalletNonce, httpConsumeWalletNonce, + httpGetTradeNonce, } from './nonce.controllers'; const router = Router(); @@ -15,6 +16,12 @@ const router = Router(); */ router.get('/', httpGetWalletNonce); +/** + * GET /nonce/:wallet + * Issues a fresh one-time nonce stored in Redis with TTL for signed trade replay protection (#1194). + */ +router.get('/:wallet', httpGetTradeNonce); + /** * POST /api/v1/nonce/consume * Records nonce consumption after an action executes. Rejects consumed nonces with 409. diff --git a/src/modules/nonce/nonce.service.ts b/src/modules/nonce/nonce.service.ts index c91abc9b..3c56ea19 100644 --- a/src/modules/nonce/nonce.service.ts +++ b/src/modules/nonce/nonce.service.ts @@ -1,10 +1,12 @@ // src/modules/nonce/nonce.service.ts // Service layer for nonce management and replay-protected signed actions (#1039). +import { randomBytes } from 'crypto'; import { cacheGetJson, cacheSetJson, cacheInvalidate, + getRedisClient, } from '../../utils/redis.utils'; import { logger } from '../../utils/logger.utils'; import { envConfig } from '../../config'; @@ -53,6 +55,7 @@ export function consumedNonceCacheKey(wallet: string, nonce: number): string { export function resetNonceStateForTests(): void { inMemoryConsumedNonces.clear(); resetTrackedOnChainNonces(); + resetTradeNonceStateForTests(); } /** @@ -175,3 +178,121 @@ export async function validateSignedActionNonce( ): Promise { return consumeWalletNonce(wallet, nonce, action, provider); } + +// ── Trade Nonce Replay Protection (#1194) ────────────────────────── + +export const DEFAULT_TRADE_NONCE_TTL_SECONDS = 300; // 5 minutes + +export function getTradeNonceTTL(): number { + return ( + (envConfig as any).TRADE_NONCE_TTL_SECONDS ?? + DEFAULT_TRADE_NONCE_TTL_SECONDS + ); +} + +const inMemoryTradeNonces = new Map(); + +export function resetTradeNonceStateForTests(): void { + inMemoryTradeNonces.clear(); +} + +/** + * Generates a fresh one-time nonce for a wallet and stores it in Redis with TTL (#1194). + */ +export async function generateTradeNonce(wallet: string): Promise { + const nonce = randomBytes(16).toString('hex'); + const ttlSeconds = getTradeNonceTTL(); + const expiresAt = Date.now() + ttlSeconds * 1000; + + // In-memory backup for testing / resilience + inMemoryTradeNonces.set(wallet, { nonce, expiresAt }); + inMemoryTradeNonces.set(`${wallet}:${nonce}`, { nonce, expiresAt }); + + const client = getRedisClient(); + if (client) { + try { + await client + .multi() + .set(`nonce:${wallet}`, nonce, 'EX', ttlSeconds) + .set(`nonce:${wallet}:${nonce}`, nonce, 'EX', ttlSeconds) + .exec(); + } catch (error) { + logger.warn( + { error: (error as Error).message, wallet }, + 'Failed to store trade nonce in Redis, falling back to in-memory store' + ); + } + } + + return nonce; +} + +/** + * Atomically verifies and consumes a one-time trade nonce from Redis (#1194). + * Returns true if the nonce was valid and deleted atomically, or false if + * expired, already consumed, or invalid. + */ +export async function verifyAndConsumeTradeNonce( + wallet: string, + nonce: string | number +): Promise { + if (nonce === undefined || nonce === null || String(nonce).trim() === '') { + return false; + } + + const nonceStr = String(nonce).trim(); + const client = getRedisClient(); + + if (client && client.status === 'ready') { + try { + const luaScript = ` + local val1 = redis.call('get', KEYS[1]) + local val2 = redis.call('get', KEYS[2]) + if val1 == ARGV[1] or val2 == ARGV[1] or val2 == '1' then + redis.call('del', KEYS[1]) + redis.call('del', KEYS[2]) + return 1 + else + return 0 + end + `; + const result = await client.eval( + luaScript, + 2, + `nonce:${wallet}`, + `nonce:${wallet}:${nonceStr}`, + nonceStr + ); + + if (Number(result) === 1) { + inMemoryTradeNonces.delete(wallet); + inMemoryTradeNonces.delete(`${wallet}:${nonceStr}`); + return true; + } else { + return false; + } + } catch (error) { + logger.warn( + { error: (error as Error).message, wallet }, + 'Redis atomic trade nonce verification failed, checking in-memory store' + ); + } + } + + // In-memory fallback (when Redis is down, disabled, or mocked in tests) + const now = Date.now(); + const record1 = inMemoryTradeNonces.get(wallet); + const record2 = inMemoryTradeNonces.get(`${wallet}:${nonceStr}`); + + const match = + (record1 && record1.expiresAt > now && record1.nonce === nonceStr) || + (record2 && record2.expiresAt > now && record2.nonce === nonceStr); + + if (match) { + inMemoryTradeNonces.delete(wallet); + inMemoryTradeNonces.delete(`${wallet}:${nonceStr}`); + return true; + } + + return false; +} diff --git a/src/modules/nonce/trade-nonce.integration.test.ts b/src/modules/nonce/trade-nonce.integration.test.ts new file mode 100644 index 00000000..967c2ea8 --- /dev/null +++ b/src/modules/nonce/trade-nonce.integration.test.ts @@ -0,0 +1,335 @@ +import express from 'express'; +import supertest from 'supertest'; +import { Keypair } from '@stellar/stellar-base'; +import { buildAuthHeaders } from '../../utils/test/auth-request.utils'; +import { requireStellarSignature } from '../../middlewares/stellar-signature.middleware'; +import { requireTradeNonce } from './nonce.middleware'; +import nonceRouter from './nonce.routes'; +import { + generateTradeNonce, + verifyAndConsumeTradeNonce, + resetTradeNonceStateForTests, + getTradeNonceTTL, +} from './nonce.service'; + +describe('Key Nonce-Based Replay Protection for Signed Trade Messages (#1194)', () => { + const wallet = Keypair.random(); + const walletAddress = wallet.publicKey(); + const anotherWallet = Keypair.random(); + const anotherWalletAddress = anotherWallet.publicKey(); + + let app: express.Express; + + beforeEach(() => { + resetTradeNonceStateForTests(); + jest.clearAllMocks(); + + app = express(); + app.use(express.json()); + app.use('/nonce', nonceRouter); + app.use('/api/v1/nonce', nonceRouter); + + // Buy endpoint mock + app.post( + '/api/v1/creators/:id/buy', + requireStellarSignature({ tradeNonce: true }), + requireTradeNonce(), + (req, res) => { + res.status(200).json({ success: true, message: 'Buy executed', data: req.body }); + } + ); + + // Sell endpoint mock + app.post( + '/api/v1/creators/:id/sell', + requireStellarSignature({ tradeNonce: true }), + requireTradeNonce(), + (req, res) => { + res.status(200).json({ success: true, message: 'Sell executed', data: req.body }); + } + ); + + // Transfer endpoint mock + app.post( + '/api/v1/creators/:id/transfer', + requireStellarSignature({ tradeNonce: true }), + requireTradeNonce(), + (req, res) => { + res.status(200).json({ success: true, message: 'Transfer executed', data: req.body }); + } + ); + }); + + describe('GET /nonce/:wallet', () => { + it('returns a fresh one-time nonce with configured TTL (default 300s)', async () => { + const res = await supertest(app).get(`/nonce/${walletAddress}`); + + expect(res.status).toBe(200); + expect(res.body.success).toBe(true); + expect(res.body.data.wallet).toBe(walletAddress); + expect(typeof res.body.data.nonce).toBe('string'); + expect(res.body.data.nonce.length).toBeGreaterThan(0); + expect(res.body.data.ttl).toBe(300); + + // Second call returns a fresh unique nonce + const res2 = await supertest(app).get(`/nonce/${walletAddress}`); + expect(res2.status).toBe(200); + expect(res2.body.data.nonce).not.toBe(res.body.data.nonce); + }); + + it('works via /api/v1/nonce/:wallet route prefix', async () => { + const res = await supertest(app).get(`/api/v1/nonce/${walletAddress}`); + + expect(res.status).toBe(200); + expect(res.body.success).toBe(true); + expect(res.body.data.wallet).toBe(walletAddress); + expect(typeof res.body.data.nonce).toBe('string'); + }); + + it('rejects invalid Stellar address with 400 validation error', async () => { + const res = await supertest(app).get('/nonce/invalid-stellar-address'); + + expect(res.status).toBe(400); + expect(res.body.success).toBe(false); + expect(res.body.error.code).toBe('VALIDATION_ERROR'); + }); + }); + + describe('Service: generateTradeNonce & verifyAndConsumeTradeNonce', () => { + it('first use of valid nonce succeeds and deletes nonce atomically', async () => { + const nonce = await generateTradeNonce(walletAddress); + expect(typeof nonce).toBe('string'); + + const firstUse = await verifyAndConsumeTradeNonce(walletAddress, nonce); + expect(firstUse).toBe(true); + + // Reuse must return false + const secondUse = await verifyAndConsumeTradeNonce(walletAddress, nonce); + expect(secondUse).toBe(false); + }); + + it('rejects non-existent nonce', async () => { + const result = await verifyAndConsumeTradeNonce(walletAddress, 'non-existent-nonce-xyz'); + expect(result).toBe(false); + }); + + it('rejects nonce when wallet does not match', async () => { + const nonce = await generateTradeNonce(walletAddress); + const result = await verifyAndConsumeTradeNonce(anotherWalletAddress, nonce); + expect(result).toBe(false); + }); + + it('returns configurable TTL from environment', () => { + expect(getTradeNonceTTL()).toBe(300); + }); + }); + + describe('Trade Endpoints: Buy endpoint nonce replay protection', () => { + it('succeeds with valid nonce in signed payload and deletes nonce atomically', async () => { + // 1. Fetch nonce + const nonceRes = await supertest(app).get(`/nonce/${walletAddress}`); + const nonce = nonceRes.body.data.nonce; + + // 2. Submit signed buy request with nonce in payload + const body = { quantity: 10, key_cost_xlm: 100, nonce }; + const headers = buildAuthHeaders(body, wallet); + + const buyRes = await supertest(app) + .post('/api/v1/creators/creator-1/buy') + .set(headers) + .send(body); + + expect(buyRes.status).toBe(200); + expect(buyRes.body.success).toBe(true); + expect(buyRes.body.data.nonce).toBe(nonce); + + // 3. Replaying the exact same signed payload returns 401 nonce_invalid + const replayRes = await supertest(app) + .post('/api/v1/creators/creator-1/buy') + .set(headers) + .send(body); + + expect(replayRes.status).toBe(401); + expect(replayRes.body.error.code).toBe('nonce_invalid'); + }); + + it('rejects buy request missing nonce with 401 nonce_invalid', async () => { + const body = { quantity: 10, key_cost_xlm: 100 }; + const headers = buildAuthHeaders(body, wallet); + + const res = await supertest(app) + .post('/api/v1/creators/creator-1/buy') + .set(headers) + .send(body); + + expect(res.status).toBe(401); + expect(res.body.error.code).toBe('nonce_invalid'); + }); + + it('rejects buy request with fake or expired nonce with 401 nonce_invalid', async () => { + const body = { quantity: 10, key_cost_xlm: 100, nonce: 'expired-or-fake-nonce-123' }; + const headers = buildAuthHeaders(body, wallet); + + const res = await supertest(app) + .post('/api/v1/creators/creator-1/buy') + .set(headers) + .send(body); + + expect(res.status).toBe(401); + expect(res.body.error.code).toBe('nonce_invalid'); + }); + }); + + describe('Trade Endpoints: Sell endpoint nonce replay protection', () => { + it('succeeds with valid nonce in signed payload and prevents replay', async () => { + const nonceRes = await supertest(app).get(`/nonce/${walletAddress}`); + const nonce = nonceRes.body.data.nonce; + + const body = { quantity: 5, min_price: 10, nonce }; + const headers = buildAuthHeaders(body, wallet); + + const sellRes = await supertest(app) + .post('/api/v1/creators/creator-1/sell') + .set(headers) + .send(body); + + expect(sellRes.status).toBe(200); + expect(sellRes.body.success).toBe(true); + + // Second use returns 401 nonce_invalid + const replayRes = await supertest(app) + .post('/api/v1/creators/creator-1/sell') + .set(headers) + .send(body); + + expect(replayRes.status).toBe(401); + expect(replayRes.body.error.code).toBe('nonce_invalid'); + }); + + it('rejects sell request missing nonce with 401 nonce_invalid', async () => { + const body = { quantity: 5, min_price: 10 }; + const headers = buildAuthHeaders(body, wallet); + + const res = await supertest(app) + .post('/api/v1/creators/creator-1/sell') + .set(headers) + .send(body); + + expect(res.status).toBe(401); + expect(res.body.error.code).toBe('nonce_invalid'); + }); + }); + + describe('Trade Endpoints: Transfer endpoint nonce replay protection', () => { + it('succeeds with valid nonce in signed payload and prevents replay', async () => { + const nonceRes = await supertest(app).get(`/nonce/${walletAddress}`); + const nonce = nonceRes.body.data.nonce; + + const body = { + toAddress: anotherWalletAddress, + quantity: 3, + nonce, + }; + const headers = buildAuthHeaders(body, wallet); + + const transferRes = await supertest(app) + .post('/api/v1/creators/creator-1/transfer') + .set(headers) + .send(body); + + expect(transferRes.status).toBe(200); + expect(transferRes.body.success).toBe(true); + + // Second use returns 401 nonce_invalid + const replayRes = await supertest(app) + .post('/api/v1/creators/creator-1/transfer') + .set(headers) + .send(body); + + expect(replayRes.status).toBe(401); + expect(replayRes.body.error.code).toBe('nonce_invalid'); + }); + + it('rejects transfer request missing nonce with 401 nonce_invalid', async () => { + const body = { + toAddress: anotherWalletAddress, + quantity: 3, + }; + const headers = buildAuthHeaders(body, wallet); + + const res = await supertest(app) + .post('/api/v1/creators/creator-1/transfer') + .set(headers) + .send(body); + + expect(res.status).toBe(401); + expect(res.body.error.code).toBe('nonce_invalid'); + }); + }); + + describe('Redis Atomic Operations & TTL Simulation', () => { + it('stores nonce with TTL in Redis and deletes atomically on first use', async () => { + const mockRedisStore = new Map(); + const mockMulti: any = {}; + mockMulti.set = jest.fn((k: string, v: string) => { + mockRedisStore.set(k, v); + return mockMulti; + }); + mockMulti.exec = jest.fn().mockResolvedValue([]); + + const mockClient = { + status: 'ready', + multi: jest.fn(() => mockMulti), + eval: jest.fn(async (_script: string, _numkeys: number, key1: string, key2: string, arg1: string) => { + const val1 = mockRedisStore.get(key1); + const val2 = mockRedisStore.get(key2); + if (val1 === arg1 || val2 === arg1 || val2 === '1') { + mockRedisStore.delete(key1); + mockRedisStore.delete(key2); + return 1; + } + return 0; + }), + }; + + const redisModule = require('../../utils/redis.utils'); + const spy = jest.spyOn(redisModule, 'getRedisClient').mockReturnValue(mockClient as any); + + // 1. Generate nonce + const nonce = await generateTradeNonce(walletAddress); + expect(mockMulti.set).toHaveBeenCalledWith(`nonce:${walletAddress}`, nonce, 'EX', 300); + expect(mockMulti.set).toHaveBeenCalledWith(`nonce:${walletAddress}:${nonce}`, nonce, 'EX', 300); + + // 2. First verification: matches and deletes + const first = await verifyAndConsumeTradeNonce(walletAddress, nonce); + expect(first).toBe(true); + expect(mockClient.eval).toHaveBeenCalledTimes(1); + expect(mockRedisStore.has(`nonce:${walletAddress}`)).toBe(false); + + // 3. Second verification: already deleted -> returns false + const second = await verifyAndConsumeTradeNonce(walletAddress, nonce); + expect(second).toBe(false); + + spy.mockRestore(); + }); + + it('expired nonce in Redis returns false and is rejected', async () => { + const mockClient = { + status: 'ready', + multi: jest.fn(() => ({ + set: jest.fn().mockReturnThis(), + exec: jest.fn().mockResolvedValue([]), + })), + eval: jest.fn().mockResolvedValue(0), // Redis expired the key + }; + + const redisModule = require('../../utils/redis.utils'); + const spy = jest.spyOn(redisModule, 'getRedisClient').mockReturnValue(mockClient as any); + + const result = await verifyAndConsumeTradeNonce(walletAddress, 'expired-nonce-token'); + expect(result).toBe(false); + + spy.mockRestore(); + }); + }); +});