diff --git a/backend/src/controllers/gasStationController.ts b/backend/src/controllers/gasStationController.ts index 3893ef01..3fd83651 100644 --- a/backend/src/controllers/gasStationController.ts +++ b/backend/src/controllers/gasStationController.ts @@ -7,6 +7,7 @@ import { ApiResponse } from '../utils/response.js'; const sponsorSchema = z.object({ innerTxXdr: z.string().min(10), + turnstileToken: z.string().min(1).optional(), }); export const gasStationController = { @@ -18,11 +19,19 @@ export const gasStationController = { } const user = req.user!; + const countryCode = + (req.headers['cf-ipcountry'] as string | undefined) || + (req.headers['x-vercel-ip-country'] as string | undefined) || + (req.headers['x-country-code'] as string | undefined); + try { const result = await gasStationService.sponsor({ studentId: user.id, studentPublicKey: user.walletAddress || '', innerTxXdr: parsed.data.innerTxXdr, + turnstileToken: parsed.data.turnstileToken, + clientIp: req.ip, + countryCode, }); return res.status(200).json(ApiResponse.success('Transaction sponsored', result)); } catch (err) { @@ -35,8 +44,13 @@ export const gasStationController = { // Today's sponsorship usage for the authenticated student getQuota: asyncHandler(async (req: Request, res: Response) => { - const usage = await getGasQuotaUsage(req.user!.id); - return res.status(200).json(ApiResponse.success('Gas quota retrieved', usage)); + const [usage, dailyTransactions] = await Promise.all([ + getGasQuotaUsage(req.user!.id), + gasStationService.getDailyTxCount(req.user!.id), + ]); + return res + .status(200) + .json(ApiResponse.success('Gas quota retrieved', { ...usage, dailyTransactions })); }), // Verified course contracts eligible for sponsorship diff --git a/backend/src/routes/gasStation.routes.ts b/backend/src/routes/gasStation.routes.ts index 75ea3489..07d9b382 100644 --- a/backend/src/routes/gasStation.routes.ts +++ b/backend/src/routes/gasStation.routes.ts @@ -1,12 +1,78 @@ -import { Router } from 'express'; +import { NextFunction, Request, Response, Router } from 'express'; import { authenticate } from '../auth/auth.middleware.js'; import { gasStationController } from '../controllers/gasStationController.js'; import { gasQuotaMiddleware } from '../middleware/gasQuotaMiddleware.js'; +import { GasStationError, gasStationService } from '../services/gasStationService.js'; +import { ApiResponse } from '../utils/response.js'; const router: ReturnType = Router(); +/** + * Early anti-drain guard on the gas station sponsor endpoint: + * - Enforces geofencing via proxy country headers (CF-IPCountry / X-Country-Code) + * - Rejects blacklisted linked wallets before quota or XDR work + * - Rejects students who have already exhausted their daily 50-tx cap + */ +const gasStationPolicyGuard = async ( + req: Request, + res: Response, + next: NextFunction +): Promise => { + const countryCode = + (req.headers['cf-ipcountry'] as string | undefined) || + (req.headers['x-vercel-ip-country'] as string | undefined) || + (req.headers['x-country-code'] as string | undefined); + + try { + gasStationService.validateGeofence(countryCode); + } catch (err) { + if (err instanceof GasStationError) { + res.status(err.statusCode).json(ApiResponse.error(err.message)); + return; + } + next(err); + return; + } + + const user = req.user; + if (!user?.id) { + res.status(401).json(ApiResponse.error('Authentication required')); + return; + } + + try { + if (user.walletAddress && (await gasStationService.isAddressBlacklisted(user.walletAddress))) { + res + .status(403) + .json( + ApiResponse.error('Address is temporarily blacklisted for 24 hours due to abusive activity') + ); + return; + } + + const txUsage = await gasStationService.getDailyTxCount(user.id); + if (txUsage.remaining <= 0) { + res + .status(429) + .json(ApiResponse.error(`Daily limit of ${txUsage.limit} sponsored transactions reached`)); + return; + } + } catch { + res.status(503).json(ApiResponse.error('Gas sponsorship is temporarily unavailable')); + return; + } + + next(); +}; + router.get('/contracts', gasStationController.getWhitelist); router.get('/quota', authenticate, gasStationController.getQuota); -router.post('/sponsor', authenticate, gasQuotaMiddleware, gasStationController.sponsor); +router.post( + '/sponsor', + authenticate, + gasStationPolicyGuard, + gasQuotaMiddleware, + gasStationController.sponsor +); export default router; diff --git a/backend/src/services/gasStationService.ts b/backend/src/services/gasStationService.ts index aa3a3469..39fbf2a6 100644 --- a/backend/src/services/gasStationService.ts +++ b/backend/src/services/gasStationService.ts @@ -18,21 +18,26 @@ import { getRedisClient } from '../utils/redis.js'; import { withLock } from '../utils/redlock.js'; /** - * Gas station relayer (#1593 / BE-021). + * Gas station relayer (#1593 / BE-021, hardened in BE-091). * - * Accepts student-signed inner transactions, checks that every operation only - * calls verified course contracts, wraps the transaction in a fee-bump - * envelope paid by the relayer account and submits it to Horizon. Fees are - * charged against the student's daily USD-denominated quota. + * Accepts student-signed inner transactions, enforces geofencing, Redis 24h + * abuse blacklisting, Turnstile CAPTCHA for unlinked wallets, strict verified + * course contract whitelisting (rejecting arbitrary fund transfers), a daily + * cap of 50 sponsored transactions per student, and a daily USD-denominated + * spending cap before wrapping in a fee-bump envelope and submitting to Horizon. */ -// Verified course contracts. Fails closed: with no whitelist, nothing is sponsored. -const WHITELISTED_CONTRACTS = new Set( - (process.env.GAS_STATION_WHITELISTED_CONTRACTS || process.env.RELAYER_WHITELISTED_CONTRACTS || '') - .split(',') - .map((c) => c.trim()) - .filter(Boolean) -); +const TURNSTILE_VERIFY_URL = 'https://challenges.cloudflare.com/turnstile/v0/siteverify'; + +// Functions that perform arbitrary token/fund transfers and must not be sponsored. +const BLOCKED_FUND_TRANSFER_FUNCTIONS = new Set([ + 'transfer', + 'transfer_from', + 'transfer_muxed', + 'clawback', + 'burn', + 'burn_from', +]); // Hard per-transaction ceiling on what the relayer will pay (default 0.1 XLM). const MAX_FEE_STROOPS = parseInt(process.env.GAS_STATION_MAX_FEE_STROOPS || '1000000', 10); @@ -40,6 +45,59 @@ const MIN_BASE_FEE_STROOPS = parseInt(process.env.GAS_STATION_BASE_FEE_STROOPS | const SUBMIT_LOCK_TTL_MS = 30_000; const REPLAY_TTL_SECONDS = 24 * 60 * 60; +// Anti-drain & budget cap defaults +export const DEFAULT_DAILY_TX_CAP = 50; +export const BLACKLIST_TTL_SECONDS = 24 * 60 * 60; // 24 hours +export const DEFAULT_ABUSE_THRESHOLD = 5; +export const DEFAULT_ABUSE_WINDOW_SECONDS = 10 * 60; // 10 minutes + +const RESERVE_TX_CAP_SCRIPT = ` +local count = tonumber(redis.call('GET', KEYS[1]) or '0') +local limit = tonumber(ARGV[1]) +if count + 1 > limit then + return -1 +end +local total = redis.call('INCR', KEYS[1]) +redis.call('EXPIRE', KEYS[1], tonumber(ARGV[2])) +return total +`; + +const RECORD_ABUSE_SCRIPT = ` +local count = redis.call('INCR', KEYS[1]) +if count == 1 then + redis.call('EXPIRE', KEYS[1], tonumber(ARGV[1])) +end +return count +`; + +function parseCsvSet(value?: string): Set { + return new Set( + (value || '') + .split(',') + .map((item) => item.trim()) + .filter(Boolean) + ); +} + +function secondsUntilMidnightUTC(): number { + const now = new Date(); + const midnight = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate() + 1)); + return Math.max(1, Math.ceil((midnight.getTime() - now.getTime()) / 1000)); +} + +function dailyTxCountKey(studentId: string): string { + const today = new Date().toISOString().slice(0, 10); + return `gas-station:tx-count:${studentId}:${today}`; +} + +function blacklistKey(address: string): string { + return `gas-station:blacklist:${address}`; +} + +function abuseKey(address: string): string { + return `gas-station:abuse:${address}`; +} + export class GasStationError extends Error { constructor( message: string, @@ -54,6 +112,9 @@ export interface SponsorRequest { studentId: string; studentPublicKey: string; innerTxXdr: string; + turnstileToken?: string; + clientIp?: string; + countryCode?: string; } export interface SponsorResult { @@ -63,6 +124,24 @@ export interface SponsorResult { innerHash: string; } +export interface DailyTxCapUsage { + used: number; + limit: number; + remaining: number; +} + +export interface GasStationOptions { + whitelistedContracts?: string[]; + dailyTxCap?: number; + abuseThreshold?: number; + abuseWindowSeconds?: number; + blacklistTtlSeconds?: number; + blockedCountries?: string[]; + allowedCountries?: string[]; + turnstileSecretKey?: string; + fetchFn?: typeof fetch; +} + function networkPassphrase(): string { const net = (process.env.STELLAR_NETWORK || 'testnet').toLowerCase(); return net === 'mainnet' || net === 'public' ? Networks.PUBLIC : Networks.TESTNET; @@ -115,13 +194,16 @@ export class RelayerSubmissionQueue { export class GasStationService { private signer?: KmsStellarSigner; private readonly passphrase = networkPassphrase(); + private readonly options: GasStationOptions; constructor( signer?: KmsStellarSigner, private queue = new RelayerSubmissionQueue(), - private horizon = new Horizon.Server(HORIZON_URL, { allowHttp: HORIZON_URL.startsWith('http://') }) + private horizon = new Horizon.Server(HORIZON_URL, { allowHttp: HORIZON_URL.startsWith('http://') }), + options: GasStationOptions = {} ) { this.signer = signer; + this.options = options; } private getSigner(): KmsStellarSigner { @@ -129,14 +211,218 @@ export class GasStationService { return this.signer; } + private getWhitelistedContractSet(): Set { + if (this.options.whitelistedContracts) { + return new Set(this.options.whitelistedContracts.map((c) => c.trim()).filter(Boolean)); + } + return parseCsvSet( + process.env.GAS_STATION_WHITELISTED_CONTRACTS || process.env.RELAYER_WHITELISTED_CONTRACTS + ); + } + + private getDailyTxCap(): number { + return ( + this.options.dailyTxCap ?? + parseInt(process.env.GAS_STATION_DAILY_TX_CAP || String(DEFAULT_DAILY_TX_CAP), 10) + ); + } + + private getAbuseThreshold(): number { + return ( + this.options.abuseThreshold ?? + parseInt(process.env.GAS_STATION_ABUSE_THRESHOLD || String(DEFAULT_ABUSE_THRESHOLD), 10) + ); + } + + private getAbuseWindowSeconds(): number { + return ( + this.options.abuseWindowSeconds ?? + parseInt( + process.env.GAS_STATION_ABUSE_WINDOW_SECONDS || String(DEFAULT_ABUSE_WINDOW_SECONDS), + 10 + ) + ); + } + + private getBlacklistTtlSeconds(): number { + return ( + this.options.blacklistTtlSeconds ?? + parseInt(process.env.GAS_STATION_BLACKLIST_TTL_SECONDS || String(BLACKLIST_TTL_SECONDS), 10) + ); + } + + private getBlockedCountries(): Set { + const list = this.options.blockedCountries + ? new Set(this.options.blockedCountries.map((c) => c.trim().toUpperCase()).filter(Boolean)) + : new Set( + [...parseCsvSet(process.env.GAS_STATION_BLOCKED_COUNTRIES)].map((c) => c.toUpperCase()) + ); + return list; + } + + private getAllowedCountries(): Set { + const list = this.options.allowedCountries + ? new Set(this.options.allowedCountries.map((c) => c.trim().toUpperCase()).filter(Boolean)) + : new Set( + [...parseCsvSet(process.env.GAS_STATION_ALLOWED_COUNTRIES)].map((c) => c.toUpperCase()) + ); + return list; + } + getWhitelist(): string[] { - return [...WHITELISTED_CONTRACTS]; + return [...this.getWhitelistedContractSet()]; } getRelayerPublicKey(): string { return this.getSigner().getPublicKey(); } + /** + * Enforce geofencing rules based on country code headers (e.g. CF-IPCountry). + */ + validateGeofence(countryCode?: string): void { + const normalized = countryCode?.trim().toUpperCase(); + const blocked = this.getBlockedCountries(); + if (normalized && blocked.has(normalized)) { + throw new GasStationError('Gas sponsorship is not available in your region', 403); + } + const allowed = this.getAllowedCountries(); + if (allowed.size > 0 && (!normalized || !allowed.has(normalized))) { + throw new GasStationError('Gas sponsorship is not available in your region', 403); + } + } + + /** + * Check whether a wallet address is currently blacklisted in Redis. + */ + async isAddressBlacklisted(address: string): Promise { + if (!address) return false; + const redis = getRedisClient(); + const entry = await redis.get(blacklistKey(address)); + return entry !== null; + } + + /** + * Blacklist an abusive address in Redis for 24 hours (default). + */ + async blacklistAddress( + address: string, + reason: string, + ttlSeconds = this.getBlacklistTtlSeconds() + ): Promise { + if (!address) return; + const redis = getRedisClient(); + await redis.set(blacklistKey(address), reason, 'EX', ttlSeconds); + logger.warn( + `Gas station blacklisted address ${address} for ${ttlSeconds}s: ${reason}` + ); + } + + /** + * Track abusive or policy-violating attempts for an address. Once the + * threshold is reached within the rolling window, automatically blacklist + * the address in Redis for 24 hours. + */ + async recordAbuseAttempt( + address: string, + reason: string + ): Promise<{ count: number; blacklisted: boolean }> { + if (!address) return { count: 0, blacklisted: false }; + try { + const redis = getRedisClient(); + const count = Number( + await redis.eval(RECORD_ABUSE_SCRIPT, 1, abuseKey(address), this.getAbuseWindowSeconds()) + ); + if (count >= this.getAbuseThreshold()) { + await this.blacklistAddress(address, reason); + return { count, blacklisted: true }; + } + return { count, blacklisted: false }; + } catch (err) { + logger.warn(`Failed to record gas station abuse attempt for ${address}:`, err); + return { count: 0, blacklisted: false }; + } + } + + /** + * Verify a Cloudflare Turnstile CAPTCHA token for unlinked wallets. + */ + async verifyTurnstileToken(token: string, clientIp?: string): Promise { + const secret = this.options.turnstileSecretKey ?? process.env.TURNSTILE_SECRET_KEY; + if (!secret) { + throw new GasStationError( + 'Turnstile CAPTCHA verification is not configured on the server', + 503 + ); + } + + const body = new URLSearchParams({ secret, response: token }); + if (clientIp) { + body.set('remoteip', clientIp); + } + + const fetchImpl = this.options.fetchFn ?? fetch; + try { + const response = await fetchImpl(TURNSTILE_VERIFY_URL, { + method: 'POST', + headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, + body: body.toString(), + }); + if (!response.ok) { + return false; + } + const data = (await response.json()) as { success?: boolean }; + return data.success === true; + } catch (err) { + logger.error('Turnstile CAPTCHA verification request failed:', err); + return false; + } + } + + /** + * Return the student's daily sponsored transaction count usage (cap: 50/day). + */ + async getDailyTxCount(studentId: string): Promise { + const limit = this.getDailyTxCap(); + const raw = await getRedisClient().get(dailyTxCountKey(studentId)); + const used = raw ? parseInt(raw, 10) : 0; + return { used, limit, remaining: Math.max(0, limit - used) }; + } + + /** + * Atomically reserve 1 slot from the student's daily sponsored transaction cap. + */ + async reserveDailyTxSlot(studentId: string): Promise { + const limit = this.getDailyTxCap(); + const result = Number( + await getRedisClient().eval( + RESERVE_TX_CAP_SCRIPT, + 1, + dailyTxCountKey(studentId), + limit, + secondsUntilMidnightUTC() + ) + ); + if (result < 0) { + throw new GasStationError( + `Daily limit of ${limit} sponsored transactions reached`, + 429 + ); + } + return result; + } + + /** + * Return a reserved daily transaction slot if submission fails. + */ + async refundDailyTxSlot(studentId: string): Promise { + try { + await getRedisClient().decr(dailyTxCountKey(studentId)); + } catch (err) { + logger.warn(`Gas station daily tx cap refund failed for ${studentId}:`, err); + } + } + parseInnerTransaction(innerTxXdr: string): Transaction { let parsed: Transaction | FeeBumpTransaction; try { @@ -150,16 +436,53 @@ export class GasStationService { return parsed; } + private validateAuthorizedInvocation( + invocation: xdr.SorobanAuthorizedInvocation, + whitelist: Set + ): void { + const fn = invocation.function(); + if (fn.switch() === xdr.SorobanAuthorizedFunctionType.sorobanAuthorizedFunctionTypeContractFn()) { + const contractFn = fn.contractFn(); + const authContract = contractOf(contractFn.contractAddress()); + if (!whitelist.has(authContract)) { + throw new GasStationError( + `Authorization for contract ${authContract} is not sponsorable`, + 403 + ); + } + const fnName = contractFn.functionName().toString().trim().toLowerCase(); + if (BLOCKED_FUND_TRANSFER_FUNCTIONS.has(fnName)) { + throw new GasStationError( + `Authorized function ${fnName} is not eligible for gas sponsorship`, + 403 + ); + } + } else { + throw new GasStationError('Contract deployment authorizations cannot be sponsored', 403); + } + + for (const sub of invocation.subInvocations() ?? []) { + this.validateAuthorizedInvocation(sub, whitelist); + } + } + /** * Policy checks that keep relayer funds from being spent on anything but * verified course contracts, submitted by the authenticated student. */ validateInnerTransaction(tx: Transaction, studentPublicKey: string): void { - if (WHITELISTED_CONTRACTS.size === 0) { - throw new GasStationError('Gas sponsorship is disabled: no verified course contracts configured', 503); + const whitelist = this.getWhitelistedContractSet(); + if (whitelist.size === 0) { + throw new GasStationError( + 'Gas sponsorship is disabled: no verified course contracts configured', + 503 + ); } if (!studentPublicKey) { - throw new GasStationError('Link a Stellar wallet to your account before requesting sponsorship', 403); + throw new GasStationError( + 'Link a Stellar wallet to your account before requesting sponsorship', + 403 + ); } if (tx.source !== studentPublicKey) { throw new GasStationError('Inner transaction source must be your linked wallet', 403); @@ -180,21 +503,25 @@ export class GasStationService { if (func.switch() !== xdr.HostFunctionType.hostFunctionTypeInvokeContract()) { throw new GasStationError('Only contract invocations can be sponsored', 403); } - const contractId = contractOf(func.invokeContract().contractAddress()); - if (!WHITELISTED_CONTRACTS.has(contractId)) { + const invokeArgs = func.invokeContract(); + const contractId = contractOf(invokeArgs.contractAddress()); + if (!whitelist.has(contractId)) { throw new GasStationError(`Contract ${contractId} is not a verified course contract`, 403); } + const fnName = invokeArgs.functionName().toString().trim().toLowerCase(); + if (!fnName) { + throw new GasStationError('Contract function name cannot be empty', 400); + } + if (BLOCKED_FUND_TRANSFER_FUNCTIONS.has(fnName)) { + throw new GasStationError( + `Function ${fnName} is not eligible for gas sponsorship (arbitrary fund transfers are prohibited)`, + 403 + ); + } + for (const entry of (op as Operation.InvokeHostFunction).auth ?? []) { - const root = entry.rootInvocation().function(); - if (root.switch() === xdr.SorobanAuthorizedFunctionType.sorobanAuthorizedFunctionTypeContractFn()) { - const authContract = contractOf(root.contractFn().contractAddress()); - if (!WHITELISTED_CONTRACTS.has(authContract)) { - throw new GasStationError(`Authorization for contract ${authContract} is not sponsorable`, 403); - } - } else { - throw new GasStationError('Contract deployment authorizations cannot be sponsored', 403); - } + this.validateAuthorizedInvocation(entry.rootInvocation(), whitelist); } } @@ -226,25 +553,84 @@ export class GasStationService { } async sponsor(req: SponsorRequest): Promise { + // 1. Geofencing check + this.validateGeofence(req.countryCode); + + // 2. Parse inner transaction so we know the source address const inner = this.parseInnerTransaction(req.innerTxXdr); - this.validateInnerTransaction(inner, req.studentPublicKey); + const sourceAddress = inner.source; + + // 3. Check 24h Redis blacklist for both linked wallet (if any) and tx source + if ( + (req.studentPublicKey && (await this.isAddressBlacklisted(req.studentPublicKey))) || + (await this.isAddressBlacklisted(sourceAddress)) + ) { + throw new GasStationError( + 'Address is temporarily blacklisted for 24 hours due to abusive activity', + 403 + ); + } + + // 4. Mandate Turnstile CAPTCHA verification for unlinked wallets + let effectivePublicKey = req.studentPublicKey; + if (!effectivePublicKey) { + if (!req.turnstileToken) { + await this.recordAbuseAttempt(sourceAddress, 'Missing Turnstile CAPTCHA for unlinked wallet'); + throw new GasStationError( + 'Turnstile CAPTCHA verification is required for unlinked wallets', + 403 + ); + } + const verified = await this.verifyTurnstileToken(req.turnstileToken, req.clientIp); + if (!verified) { + await this.recordAbuseAttempt(sourceAddress, 'Failed Turnstile CAPTCHA verification'); + throw new GasStationError('Turnstile CAPTCHA verification failed', 403); + } + effectivePublicKey = sourceAddress; + } + + // 5. Strict contract whitelist, anti-fund-transfer & signature validation + try { + this.validateInnerTransaction(inner, effectivePublicKey); + } catch (err) { + if (err instanceof GasStationError && err.statusCode !== 503) { + await this.recordAbuseAttempt(sourceAddress, err.message); + } + throw err; + } const { baseFee, totalFee } = this.computeFeeBump(inner); if (totalFee > MAX_FEE_STROOPS) { - throw new GasStationError(`Transaction fee ${totalFee} exceeds the sponsorship limit of ${MAX_FEE_STROOPS} stroops`); + await this.recordAbuseAttempt(sourceAddress, `Excessive fee requested: ${totalFee}`); + throw new GasStationError( + `Transaction fee ${totalFee} exceeds the sponsorship limit of ${MAX_FEE_STROOPS} stroops` + ); } const innerHash = inner.hash().toString('hex'); const replayKey = `gas-station:inner:${innerHash}`; const redis = getRedisClient(); if ((await redis.set(replayKey, req.studentId, 'EX', REPLAY_TTL_SECONDS, 'NX')) === null) { + await this.recordAbuseAttempt(sourceAddress, 'Duplicate transaction replay attempt'); throw new GasStationError('This transaction has already been submitted for sponsorship', 409); } + // 6. Enforce daily per-student transaction count cap (max 50/day) + try { + await this.reserveDailyTxSlot(req.studentId); + } catch (err) { + await redis.del(replayKey); + await this.recordAbuseAttempt(sourceAddress, 'Daily sponsored transaction cap exceeded'); + throw err; + } + + // 7. Enforce daily per-student USD/stroops spending cap try { await reserveGasQuota(req.studentId, totalFee); } catch (err) { + await this.refundDailyTxSlot(req.studentId); await redis.del(replayKey); + await this.recordAbuseAttempt(sourceAddress, 'Daily gas spending quota exceeded'); throw new GasStationError((err as Error).message, 429); } @@ -269,8 +655,9 @@ export class GasStationService { ); return { hash: result.hash, ledger: result.ledger, feeChargedStroops: totalFee, innerHash }; } catch (err: any) { - // Nothing landed on-chain, so give the quota and replay slot back. + // Nothing landed on-chain, so give the quota, daily tx slot, and replay slot back. await refundGasQuota(req.studentId, totalFee); + await this.refundDailyTxSlot(req.studentId); await redis.del(replayKey); const code = err?.response?.data?.extras?.result_codes?.transaction || err?.message || 'unknown'; logger.error(`Gas station submission failed for ${innerHash}: ${code}`); diff --git a/backend/tests/gasStationService.test.ts b/backend/tests/gasStationService.test.ts new file mode 100644 index 00000000..f9fd0bfe --- /dev/null +++ b/backend/tests/gasStationService.test.ts @@ -0,0 +1,366 @@ +import { + Account, + Address, + Asset, + Contract, + Keypair, + Networks, + Operation, + TransactionBuilder, + xdr, +} from '@stellar/stellar-sdk'; +import { + BLACKLIST_TTL_SECONDS, + GasStationError, + GasStationService, + RelayerSubmissionQueue, +} from '../src/services/gasStationService.js'; + +// In-memory Redis mock supporting get, set (with EX/NX), del, decr, and eval for Lua scripts +class InMemoryRedis { + private store = new Map(); + + async get(key: string): Promise { + return this.store.get(key)?.value ?? null; + } + + async set(key: string, value: string, ...args: any[]): Promise<'OK' | null> { + const hasNx = args.includes('NX'); + if (hasNx && this.store.has(key)) { + return null; + } + const exIdx = args.indexOf('EX'); + const ttl = exIdx >= 0 ? Number(args[exIdx + 1]) : undefined; + this.store.set(key, { value: String(value), ttl }); + return 'OK'; + } + + async del(key: string): Promise { + return this.store.delete(key) ? 1 : 0; + } + + async decr(key: string): Promise { + const cur = parseInt(this.store.get(key)?.value || '0', 10) - 1; + this.store.set(key, { value: String(cur), ttl: this.store.get(key)?.ttl }); + return cur; + } + + async decrby(key: string, amount: number): Promise { + const cur = parseInt(this.store.get(key)?.value || '0', 10) - amount; + this.store.set(key, { value: String(cur), ttl: this.store.get(key)?.ttl }); + return cur; + } + + async eval(script: string, _numKeys: number, key: string, ...argv: any[]): Promise { + if (script.includes('INCRBY')) { + // reserveGasQuota script + const used = parseInt(this.store.get(key)?.value || '0', 10); + const amount = Number(argv[0]); + const limit = Number(argv[1]); + const ttl = Number(argv[2]); + if (used + amount > limit) return -1; + const total = used + amount; + this.store.set(key, { value: String(total), ttl }); + return total; + } + if (script.includes('local limit = tonumber(ARGV[1])')) { + // RESERVE_TX_CAP_SCRIPT + const count = parseInt(this.store.get(key)?.value || '0', 10); + const limit = Number(argv[0]); + const ttl = Number(argv[1]); + if (count + 1 > limit) return -1; + const total = count + 1; + this.store.set(key, { value: String(total), ttl }); + return total; + } + // RECORD_ABUSE_SCRIPT + const count = parseInt(this.store.get(key)?.value || '0', 10) + 1; + const ttl = Number(argv[0]); + this.store.set(key, { value: String(count), ttl }); + return count; + } + + getTtl(key: string): number | undefined { + return this.store.get(key)?.ttl; + } + + clear(): void { + this.store.clear(); + } +} + +const mockRedis = new InMemoryRedis(); + +jest.mock('../src/utils/redis.js', () => ({ + getRedisClient: () => mockRedis, +})); + +jest.mock('../src/utils/logger.js', () => ({ + __esModule: true, + default: { + info: jest.fn(), + warn: jest.fn(), + error: jest.fn(), + }, +})); + +const WHITELISTED_CONTRACT = Address.contract(Buffer.alloc(32, 1)).toString(); +const UNAUTHORIZED_CONTRACT = Address.contract(Buffer.alloc(32, 2)).toString(); + +function buildContractTx( + signer: Keypair, + contractId: string, + fnName: string, + sequence = '100', + sign = true +): string { + const account = new Account(signer.publicKey(), sequence); + const contract = new Contract(contractId); + const tx = new TransactionBuilder(account, { + fee: '100', + networkPassphrase: Networks.TESTNET, + }) + .addOperation(contract.call(fnName)) + .setTimeout(30) + .build(); + if (sign) { + tx.sign(signer); + } + return tx.toXDR(); +} + +function buildPaymentTx(signer: Keypair, destination: string, sequence = '100'): string { + const account = new Account(signer.publicKey(), sequence); + const tx = new TransactionBuilder(account, { + fee: '100', + networkPassphrase: Networks.TESTNET, + }) + .addOperation( + Operation.payment({ + destination, + asset: Asset.native(), + amount: '10', + }) + ) + .setTimeout(30) + .build(); + tx.sign(signer); + return tx.toXDR(); +} + +describe('GasStationService (BE-091 anti-drain, caps, geofencing & Turnstile)', () => { + const studentKeypair = Keypair.random(); + const relayerKeypair = Keypair.random(); + let mockSigner: any; + let mockHorizon: any; + let queue: RelayerSubmissionQueue; + + beforeEach(() => { + mockRedis.clear(); + mockSigner = { + getPublicKey: () => relayerKeypair.publicKey(), + signTransaction: jest.fn().mockResolvedValue(undefined), + }; + mockHorizon = { + submitTransaction: jest.fn().mockResolvedValue({ hash: 'tx-hash-123', ledger: 42 }), + }; + queue = new RelayerSubmissionQueue(async (_key, _ttl, fn) => fn()); + }); + + it('sponsors a valid whitelisted course contract invocation', async () => { + const service = new GasStationService(mockSigner, queue, mockHorizon, { + whitelistedContracts: [WHITELISTED_CONTRACT], + }); + const xdrStr = buildContractTx(studentKeypair, WHITELISTED_CONTRACT, 'submit_lesson'); + + const result = await service.sponsor({ + studentId: 'student-1', + studentPublicKey: studentKeypair.publicKey(), + innerTxXdr: xdrStr, + }); + + expect(result.hash).toBe('tx-hash-123'); + expect(result.ledger).toBe(42); + expect(mockHorizon.submitTransaction).toHaveBeenCalledTimes(1); + const usage = await service.getDailyTxCount('student-1'); + expect(usage.used).toBe(1); + expect(usage.limit).toBe(50); + }); + + it('strictly rejects unauthorized contracts', async () => { + const service = new GasStationService(mockSigner, queue, mockHorizon, { + whitelistedContracts: [WHITELISTED_CONTRACT], + }); + const xdrStr = buildContractTx(studentKeypair, UNAUTHORIZED_CONTRACT, 'submit_lesson'); + + await expect( + service.sponsor({ + studentId: 'student-1', + studentPublicKey: studentKeypair.publicKey(), + innerTxXdr: xdrStr, + }) + ).rejects.toMatchObject({ + statusCode: 403, + message: expect.stringContaining('not a verified course contract'), + }); + expect(mockHorizon.submitTransaction).not.toHaveBeenCalled(); + }); + + it('strictly rejects arbitrary fund transfers (native payment and contract transfer)', async () => { + const service = new GasStationService(mockSigner, queue, mockHorizon, { + whitelistedContracts: [WHITELISTED_CONTRACT], + }); + + // 1. Native Stellar payment operation + const paymentXdr = buildPaymentTx(studentKeypair, Keypair.random().publicKey()); + await expect( + service.sponsor({ + studentId: 'student-1', + studentPublicKey: studentKeypair.publicKey(), + innerTxXdr: paymentXdr, + }) + ).rejects.toMatchObject({ + statusCode: 403, + message: expect.stringContaining('payment is not eligible for sponsorship'), + }); + + // 2. Soroban token transfer function on a contract + const transferXdr = buildContractTx(studentKeypair, WHITELISTED_CONTRACT, 'transfer'); + await expect( + service.sponsor({ + studentId: 'student-1', + studentPublicKey: studentKeypair.publicKey(), + innerTxXdr: transferXdr, + }) + ).rejects.toMatchObject({ + statusCode: 403, + message: expect.stringContaining('arbitrary fund transfers are prohibited'), + }); + }); + + it('enforces the daily cap of 50 sponsored transactions per student', async () => { + const service = new GasStationService(mockSigner, queue, mockHorizon, { + whitelistedContracts: [WHITELISTED_CONTRACT], + dailyTxCap: 2, + abuseThreshold: 100, + }); + + for (let i = 0; i < 2; i++) { + const xdrStr = buildContractTx(studentKeypair, WHITELISTED_CONTRACT, 'submit_lesson', String(100 + i)); + await service.sponsor({ + studentId: 'student-cap', + studentPublicKey: studentKeypair.publicKey(), + innerTxXdr: xdrStr, + }); + } + + const thirdXdr = buildContractTx(studentKeypair, WHITELISTED_CONTRACT, 'submit_lesson', '103'); + await expect( + service.sponsor({ + studentId: 'student-cap', + studentPublicKey: studentKeypair.publicKey(), + innerTxXdr: thirdXdr, + }) + ).rejects.toMatchObject({ + statusCode: 429, + message: expect.stringContaining('Daily limit of 2 sponsored transactions reached'), + }); + }); + + it('mandates Turnstile CAPTCHA verification for unlinked wallets', async () => { + const mockFetch = jest.fn().mockResolvedValue({ + ok: true, + json: async () => ({ success: true }), + }); + + const service = new GasStationService(mockSigner, queue, mockHorizon, { + whitelistedContracts: [WHITELISTED_CONTRACT], + turnstileSecretKey: 'test-secret', + fetchFn: mockFetch as any, + }); + + const xdrStr = buildContractTx(studentKeypair, WHITELISTED_CONTRACT, 'submit_lesson'); + + // Missing token -> rejected + await expect( + service.sponsor({ + studentId: 'student-unlinked', + studentPublicKey: '', + innerTxXdr: xdrStr, + }) + ).rejects.toMatchObject({ + statusCode: 403, + message: expect.stringContaining('Turnstile CAPTCHA verification is required'), + }); + + // Valid token -> succeeds + const result = await service.sponsor({ + studentId: 'student-unlinked', + studentPublicKey: '', + innerTxXdr: xdrStr, + turnstileToken: 'valid-turnstile-token', + clientIp: '203.0.113.10', + }); + + expect(result.hash).toBe('tx-hash-123'); + expect(mockFetch).toHaveBeenCalledTimes(1); + }); + + it('automatically blacklists abusive addresses in Redis for 24 hours', async () => { + const service = new GasStationService(mockSigner, queue, mockHorizon, { + whitelistedContracts: [WHITELISTED_CONTRACT], + abuseThreshold: 3, + blacklistTtlSeconds: BLACKLIST_TTL_SECONDS, + }); + + const badXdr = buildContractTx(studentKeypair, UNAUTHORIZED_CONTRACT, 'drain'); + + for (let i = 0; i < 3; i++) { + await expect( + service.sponsor({ + studentId: 'attacker-1', + studentPublicKey: studentKeypair.publicKey(), + innerTxXdr: badXdr, + }) + ).rejects.toBeInstanceOf(GasStationError); + } + + // Address should now be blacklisted in Redis with 24h TTL + const isBlacklisted = await service.isAddressBlacklisted(studentKeypair.publicKey()); + expect(isBlacklisted).toBe(true); + expect(mockRedis.getTtl(`gas-station:blacklist:${studentKeypair.publicKey()}`)).toBe(86400); + + // Even a valid transaction from this address is now immediately blocked + const validXdr = buildContractTx(studentKeypair, WHITELISTED_CONTRACT, 'submit_lesson', '200'); + await expect( + service.sponsor({ + studentId: 'attacker-1', + studentPublicKey: studentKeypair.publicKey(), + innerTxXdr: validXdr, + }) + ).rejects.toMatchObject({ + statusCode: 403, + message: expect.stringContaining('blacklisted for 24 hours'), + }); + }); + + it('enforces geofencing for blocked countries', async () => { + const service = new GasStationService(mockSigner, queue, mockHorizon, { + whitelistedContracts: [WHITELISTED_CONTRACT], + blockedCountries: ['KP', 'IR'], + }); + const xdrStr = buildContractTx(studentKeypair, WHITELISTED_CONTRACT, 'submit_lesson'); + + await expect( + service.sponsor({ + studentId: 'student-geo', + studentPublicKey: studentKeypair.publicKey(), + innerTxXdr: xdrStr, + countryCode: 'kp', + }) + ).rejects.toMatchObject({ + statusCode: 403, + message: expect.stringContaining('not available in your region'), + }); + }); +});