Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -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=

Expand Down
4 changes: 4 additions & 0 deletions src/config.schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,

Expand Down
1 change: 1 addition & 0 deletions src/constants/error.constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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];
100 changes: 72 additions & 28 deletions src/middlewares/stellar-signature.middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import { ErrorCode } from '../constants/error.constants';
import { logger } from '../utils/logger.utils';
import {
validateSignedActionNonce,
verifyAndConsumeTradeNonce,
NonceAlreadyConsumedError,
NonceMismatchError,
} from '../modules/nonce';
Expand All @@ -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
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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;
}
}
}

Expand Down
4 changes: 4 additions & 0 deletions src/modules/creator/buy.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<typeof buySchema>;
Expand Down
4 changes: 4 additions & 0 deletions src/modules/creator/sell.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<typeof sellSchema>;
Expand Down
75 changes: 75 additions & 0 deletions src/modules/creator/transfer.controller.ts
Original file line number Diff line number Diff line change
@@ -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<typeof transferSchema>;

export async function httpTransferCreatorKey(
req: StellarSignedRequest,
res: Response
): Promise<void> {
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;
}
}
25 changes: 23 additions & 2 deletions src/modules/creators/creators.routes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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(),
Expand All @@ -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(
Expand Down
22 changes: 22 additions & 0 deletions src/modules/keys/keys.routes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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;
Loading
Loading