Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
fix(wallet): validate caller addresses and clamp the history limit before the RPC sees them
nirholasd84d8768bd16
diff --git a/api/user/wallet/fund-agent.js b/api/user/wallet/fund-agent.jsindex e31c77515..9387e998f 100644--- a/api/user/wallet/fund-agent.js+++ b/api/user/wallet/fund-agent.js@@ -77,7 +77,17 @@ export default wrap(async (req, res) => {if (!agent) return error(res, 403, 'forbidden', 'agent not found or not yours');const agentSolAddr = agent.meta?.solana_address;- if (!agentSolAddr) return error(res, 400, 'no_agent_wallet', 'agent has no Solana wallet — provision one first');+ if (!agentSolAddr) return error(res, 400, 'no_agent_wallet', 'agent has no Solana wallet, provision one first');++ // agent_identities.meta is JSON written by several provisioning paths, so the+ // address stored there is not guaranteed to be a decodable pubkey. Handing an+ // unchecked string to `new PublicKey()` threw past every boundary and surfaced+ // as an opaque 500; validating it names the fault and keeps the destination+ // check identical to the one send.js applies to a user-supplied address.+ const agentDest = validateSolanaAddress(agentSolAddr);+ if (!agentDest.valid || !agentDest.onCurve) {+ return error(res, 422, 'agent_wallet_invalid', 'this agent\'s stored wallet address is not a valid Solana account; re-provision its wallet');+ }const asset = body.asset === 'SOL' ? 'SOL' : 'USDC';const isMax = body.amount === 'max' || body.amount === 'MAX';@@ -88,7 +98,7 @@ export default wrap(async (req, res) => {const conn = solanaConnection('mainnet');const fromPk = new PublicKey(mw.solana_address);- const destPk = new PublicKey(agentSolAddr);+ const destPk = agentDest.pubkey;const mintPk = new PublicKey(USDC_MINT);let balanceLamports;diff --git a/api/user/wallet/history.js b/api/user/wallet/history.jsindex 88abad5c8..d1f83c31c 100644--- a/api/user/wallet/history.js+++ b/api/user/wallet/history.js@@ -40,7 +40,10 @@ export default wrap(async (req, res) => {const url = new URL(req.url, 'http://x');const network = url.searchParams.get('network') === 'devnet' ? 'devnet' : 'mainnet';- const limit = Math.min(parseInt(url.searchParams.get('limit') || '20', 10) || 20, 50);+ // Clamp on BOTH ends. Only the upper bound was enforced, so `?limit=-5`+ // passed straight through to getSignaturesForAddress, which rejects it and+ // turned plainly malformed input into a 502 blamed on the RPC.+ const limit = Math.max(1, Math.min(parseInt(url.searchParams.get('limit') || '20', 10) || 20, 50));const address = row.solana_address;const cacheKey = `mw:sigs:${address}:${network}:${limit}`;diff --git a/api/user/wallet/send.js b/api/user/wallet/send.jsindex d5868d011..950b908b2 100644--- a/api/user/wallet/send.js+++ b/api/user/wallet/send.js@@ -12,8 +12,7 @@ import { solanaConnection } from '../../_lib/agent-pumpfun.js';import { validateSolanaAddress, lamportsToUsd } from '../../_lib/agent-trade-guards.js';import { recordEvent } from '../../_lib/usage.js';import {- Keypair, PublicKey, LAMPORTS_PER_SOL, SystemProgram,- TransactionMessage, VersionedTransaction,+ PublicKey, SystemProgram, TransactionMessage, VersionedTransaction,} from '@solana/web3.js';import {getAssociatedTokenAddressSync, createTransferCheckedInstruction,diff --git a/api/wallet/balances.js b/api/wallet/balances.jsindex 37b661d6d..b5019e990 100644--- a/api/wallet/balances.js+++ b/api/wallet/balances.js@@ -5,12 +5,31 @@import { cors, json, method, readJson, wrap, error, rateLimited } from '../_lib/http.js';import { limits, clientIp } from '../_lib/rate-limit.js';import { getBalances } from '../_lib/balances.js';+import { isValidSolanaAddress, isValidEvmAddress } from '../_lib/validate.js';import { z } from 'zod';-const bodySchema = z.object({- chain: z.enum(['solana', 'evm']),- address: z.string().trim().min(1),-});+// The address is caller-supplied, so its shape is checked here rather than left+// to the upstream RPC. Without this, a string that cannot be an address reads as+// a real empty wallet: Helius/DAS answers "no assets" for base58 garbage and the+// caller gets a 200 with zero balances instead of being told the input is wrong.+// It also stops arbitrary-length junk from costing an upstream round trip.+const bodySchema = z+ .object({+ chain: z.enum(['solana', 'evm']),+ address: z.string().trim().min(1),+ })+ .superRefine((body, ctx) => {+ const ok = body.chain === 'solana' ? isValidSolanaAddress : isValidEvmAddress;+ if (ok(body.address)) return;+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ path: ['address'],+ message:+ body.chain === 'solana'+ ? 'must be a base58 Solana address (32-44 chars)'+ : 'must be a 0x-prefixed 40-character hex address',+ });+ });export default wrap(async (req, res) => {if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;diff --git a/tests/api-wallet-balances-handler.test.js b/tests/api-wallet-balances-handler.test.jsnew file mode 100644index 000000000..fe860744d--- /dev/null+++ b/tests/api-wallet-balances-handler.test.js@@ -0,0 +1,160 @@+// Route-handler tests for api/wallet/balances.js (POST /api/wallet/balances).+//+// This is the one balance reader whose address comes straight off the wire+// (every other getBalances() caller reads a wallet out of our own DB), so the+// HTTP boundary is the only thing standing between caller junk and an upstream+// RPC call. What is covered here:+//+// 1. Address shape is enforced per chain BEFORE any upstream work. Helius/DAS+// answers "no assets" for base58-shaped garbage, so an unvalidated bad+// address used to come back as a 200 with a native amount of 0 and an empty+// token list: indistinguishable from a real empty wallet, and a free+// arbitrary-length round trip against our RPC quota.+// 2. The success path passes the trimmed address through and returns the+// reader's payload verbatim.+// 3. The two upstream failure shapes getBalances() raises stay mapped to+// their intended statuses (503 not_configured with the missing key named,+// 502 for a bad upstream) rather than collapsing into a 500.++import { Readable } from 'node:stream';+import { describe, it, expect, beforeEach, vi } from 'vitest';++// A clearly-synthetic wallet: these cases assert routing and validation only, so+// a real mainnet address would add nothing but a claim we do not mean.+const WALLET = 'THREEsynthetic1111111111111111111111111111';+const EVM_WALLET = '0x1111111111111111111111111111111111111111';++const balancesState = { result: null, error: null, calls: [] };++vi.mock('../api/_lib/balances.js', () => ({+ getBalances: vi.fn(async (args) => {+ balancesState.calls.push(args);+ if (balancesState.error) throw balancesState.error;+ return balancesState.result;+ }),+}));++vi.mock('../api/_lib/rate-limit.js', () => ({+ limits: { authedReadIp: vi.fn(async () => ({ success: true })) },+ clientIp: vi.fn(() => '127.0.0.1'),+}));++const handler = (await import('../api/wallet/balances.js')).default;++function makeReq({ method = 'POST', rawBody = null } = {}) {+ const req = Readable.from(rawBody == null ? [] : [Buffer.from(rawBody)]);+ req.method = method;+ req.url = '/api/wallet/balances';+ req.headers = {+ host: 'localhost',+ ...(rawBody == null ? {} : { 'content-type': 'application/json' }),+ };+ return req;+}++function makeRes() {+ return {+ statusCode: 200,+ headers: {},+ body: '',+ writableEnded: false,+ setHeader(k, v) {+ this.headers[k.toLowerCase()] = v;+ },+ end(chunk) {+ if (chunk !== undefined) this.body += chunk;+ this.writableEnded = true;+ },+ };+}++async function call(body, { method = 'POST' } = {}) {+ const rawBody = body === undefined ? null : JSON.stringify(body);+ const res = makeRes();+ await handler(makeReq({ method, rawBody }), res);+ return { status: res.statusCode, body: res.body ? JSON.parse(res.body) : null };+}++beforeEach(() => {+ balancesState.calls = [];+ balancesState.error = null;+ balancesState.result = {+ chain: 'solana',+ address: WALLET,+ native: { symbol: 'SOL', name: 'Solana', amount: 1.5, price: 100, change24h: null, usd: 150 },+ tokens: [],+ };+});++describe('wallet balances: address validation', () => {+ it('rejects a Solana address that is not base58, without calling upstream', async () => {+ const { status, body } = await call({ chain: 'solana', address: 'not-a-real-address' });+ expect(status).toBe(400);+ expect(body.error).toBe('validation_error');+ expect(body.error_description).toContain('base58');+ expect(balancesState.calls).toHaveLength(0);+ });++ it('rejects an over-long address instead of paying for the RPC round trip', async () => {+ const { status } = await call({ chain: 'solana', address: 'A'.repeat(5000) });+ expect(status).toBe(400);+ expect(balancesState.calls).toHaveLength(0);+ });++ it('rejects a Solana-shaped address on the evm chain', async () => {+ const { status, body } = await call({ chain: 'evm', address: WALLET });+ expect(status).toBe(400);+ expect(body.error_description).toContain('0x-prefixed');+ expect(balancesState.calls).toHaveLength(0);+ });++ it('rejects an unknown chain', async () => {+ const { status, body } = await call({ chain: 'bitcoin', address: WALLET });+ expect(status).toBe(400);+ expect(body.error).toBe('validation_error');+ expect(balancesState.calls).toHaveLength(0);+ });++ it('accepts an evm address on the evm chain', async () => {+ balancesState.result = { chain: 'evm', address: EVM_WALLET, native: null, tokens: [] };+ const { status } = await call({ chain: 'evm', address: EVM_WALLET });+ expect(status).toBe(200);+ expect(balancesState.calls[0]).toEqual({ chain: 'evm', address: EVM_WALLET });+ });+});++describe('wallet balances: success path', () => {+ it('returns the reader payload and passes the trimmed address through', async () => {+ const { status, body } = await call({ chain: 'solana', address: ` ${WALLET} ` });+ expect(status).toBe(200);+ expect(balancesState.calls[0]).toEqual({ chain: 'solana', address: WALLET });+ expect(body.native.amount).toBe(1.5);+ expect(body.tokens).toEqual([]);+ });++ it('answers a wrong method with 405 rather than running the reader', async () => {+ const { status } = await call(undefined, { method: 'GET' });+ expect(status).toBe(405);+ expect(balancesState.calls).toHaveLength(0);+ });+});++describe('wallet balances: upstream failures', () => {+ it('maps a missing provider key to 503 and names the key', async () => {+ balancesState.error = Object.assign(new Error('not_configured: ALCHEMY_API_KEY'), {+ code: 'not_configured',+ missing: 'ALCHEMY_API_KEY',+ });+ const { status, body } = await call({ chain: 'evm', address: EVM_WALLET });+ expect(status).toBe(503);+ expect(body.error).toBe('not_configured');+ expect(body.missing_key).toBe('ALCHEMY_API_KEY');+ });++ it('maps a bad upstream response to 502', async () => {+ balancesState.error = Object.assign(new Error('upstream 500: boom'), { status: 502 });+ const { status, body } = await call({ chain: 'solana', address: WALLET });+ expect(status).toBe(502);+ expect(body.error).toBe('upstream_error');+ });+});