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
refactor(api): standardize 429 responses with rateLimited helper
nirholas2a1b43ce6a1c
diff --git a/api/_lib/http.js b/api/_lib/http.jsindex ec3b79d3c..34a701a10 100644--- a/api/_lib/http.js+++ b/api/_lib/http.js@@ -70,6 +70,35 @@ export function respondError(res, status, code, err, extra = {}) {return serverError(res, status, code, err, extra);}+// Advertise the limiter budget on the response using the conventional+// `RateLimit-*` headers (the shape GitHub/Stripe and the IETF+// draft-ietf-httpapi-ratelimit-headers converge on). `result` is the object+// returned by api/_lib/rate-limit.js limiters: { success, limit, remaining,+// reset } where `reset` is an absolute epoch-ms timestamp. Returns the+// seconds-until-reset so callers can reuse it for Retry-After.+export function setRateLimitHeaders(res, result) {+ if (!result) return 0;+ const now = Date.now();+ const resetSec = Math.max(0, Math.ceil(((result.reset ?? now) - now) / 1000));+ if (Number.isFinite(result.limit)) res.setHeader('ratelimit-limit', String(result.limit));+ if (Number.isFinite(result.remaining)) {+ res.setHeader('ratelimit-remaining', String(Math.max(0, result.remaining)));+ }+ res.setHeader('ratelimit-reset', String(resetSec));+ return resetSec;+}++// Standard 429 response. Given a limiter result, set the RateLimit-* budget+// headers plus Retry-After (RFC 9110 §10.2.3) so well-behaved clients — and the+// paying agents this platform is built for — back off by the exact window+// instead of hammering or giving up blind. `retry_after` is mirrored into the+// JSON body for clients that read the envelope rather than headers.+export function rateLimited(res, result, message = 'too many requests', extra = {}) {+ const retryAfter = Math.max(1, setRateLimitHeaders(res, result));+ res.setHeader('retry-after', String(retryAfter));+ return error(res, 429, 'rate_limited', message, { retry_after: retryAfter, ...extra });+}+// Response shape used for zod validation errors so clients can render// field-level feedback. Mirrors RFC 9457-style problem details (lite).export function validationError(res, err) {diff --git a/api/agenc/[action].js b/api/agenc/[action].jsindex 334dfc954..80df589e0 100644--- a/api/agenc/[action].js+++ b/api/agenc/[action].js@@ -32,7 +32,7 @@ import { PublicKey } from '@solana/web3.js';import { createHash } from 'node:crypto';import { getTask, getTaskLifecycleSummary, getTasksByCreator, getAgent, deriveTaskPda, deriveAgentPda } from '@tetsuo-ai/sdk';-import { cors, json, method, readJson, wrap, error } from '../_lib/http.js';+import { cors, json, method, readJson, wrap, error, rateLimited } from '../_lib/http.js';import { limits, clientIp } from '../_lib/rate-limit.js';import { Bazaar, filterByExtension, filterByMaxPrice, filterByNetwork } from '../_lib/x402/bazaar-client.js';import {@@ -414,7 +414,7 @@ export default wrap(async (req, res) => {if (!method(req, res, route.methods)) return;const rl = await limits.publicIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);try {return await route.fn(req, res);diff --git a/api/agent-delegate.js b/api/agent-delegate.jsindex 5faf155d0..547488490 100644--- a/api/agent-delegate.js+++ b/api/agent-delegate.js@@ -1,5 +1,5 @@import { authenticateBearer, extractBearer, getSessionUser } from './_lib/auth.js';-import { cors, json, method, wrap, error, readJson } from './_lib/http.js';+import { cors, json, method, wrap, error, readJson, rateLimited } from './_lib/http.js';import { limits } from './_lib/rate-limit.js';import { LlmUnavailableError } from './_lib/llm.js';import { runAgentDelegation, AgentNotFoundError } from './_lib/agent-delegate.js';@@ -27,7 +27,7 @@ export default wrap(async (req, res) => {// Rate limit per calling agent (or user session as fallback)const rl = await limits.agentDelegate(fromAgentId || userId || 'anon');- if (!rl.success) return error(res, 429, 'rate_limited', 'delegate rate limit exceeded');+ if (!rl.success) return rateLimited(res, rl, 'delegate rate limit exceeded');try {const out = await runAgentDelegation({ toAgentId, message });diff --git a/api/agent-economy/transact.js b/api/agent-economy/transact.jsindex 061add90f..d283a1ac9 100644--- a/api/agent-economy/transact.js+++ b/api/agent-economy/transact.js@@ -17,7 +17,7 @@// The caller UI degrades gracefully: it shows the conversation without the tx.import { z } from 'zod';-import { cors, json, method, readJson, wrap, error } from '../_lib/http.js';+import { cors, json, method, readJson, wrap, error, rateLimited } from '../_lib/http.js';import { parse } from '../_lib/validate.js';import { limits, clientIp } from '../_lib/rate-limit.js';import {@@ -80,7 +80,7 @@ export default wrap(async (req, res) => {if (!method(req, res, ['POST'])) return;const rl = await limits.agentEconomyIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const body = parse(bodySchema, await readJson(req));const svc = SERVICES[body.service];diff --git a/api/agent-skill-price.js b/api/agent-skill-price.jsindex 96292b440..9b6b38287 100644--- a/api/agent-skill-price.js+++ b/api/agent-skill-price.js@@ -6,7 +6,7 @@*/import { sql } from './_lib/db.js';import { authenticateBearer, extractBearer, getSessionUser } from './_lib/auth.js';-import { cors, error, json, method, readJson, wrap } from './_lib/http.js';+import { cors, error, json, method, readJson, wrap, rateLimited } from './_lib/http.js';import { clientIp, limits } from './_lib/rate-limit.js';import { z } from 'zod';@@ -35,7 +35,7 @@ export default wrap(async (req, res) => {if (!auth) return error(res, 401, 'unauthorized', 'sign in required');const rl = await limits.authIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const url = new URL(req.url, 'http://x');const agentId = url.searchParams.get('agentId');diff --git a/api/agent-skills.js b/api/agent-skills.jsindex 86bb1a649..09bb9968b 100644--- a/api/agent-skills.js+++ b/api/agent-skills.js@@ -5,7 +5,7 @@*/import { sql } from './_lib/db.js';import { authenticateBearer, extractBearer, getSessionUser } from './_lib/auth.js';-import { cors, error, json, method, readJson, wrap } from './_lib/http.js';+import { cors, error, json, method, readJson, wrap, rateLimited } from './_lib/http.js';import { clientIp, limits } from './_lib/rate-limit.js';import { z } from 'zod';@@ -34,7 +34,7 @@ async function handleSetPrice(req, res, agentId) {if (!auth) return error(res, 401, 'unauthorized', 'sign in required');const rl = await limits.authIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);if (!agentId) return error(res, 400, 'validation_error', 'agentId required');diff --git a/api/agent-strategy.js b/api/agent-strategy.jsindex cde0a201e..02022438a 100644--- a/api/agent-strategy.js+++ b/api/agent-strategy.js@@ -9,7 +9,7 @@*/import { sql } from './_lib/db.js';import { authenticateBearer, extractBearer, getSessionUser } from './_lib/auth.js';-import { cors, error, json, method, readJson, wrap } from './_lib/http.js';+import { cors, error, json, method, readJson, wrap, rateLimited } from './_lib/http.js';import { clientIp, limits } from './_lib/rate-limit.js';async function resolveAuth(req) {@@ -40,7 +40,7 @@ export default wrap(async (req, res) => {if (req.method === 'GET') {const rl = await limits.widgetRead(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);// "no strategy set" is a valid empty state, not an error — return null with// 200 so owners viewing an un-configured agent don't generate console 404s.@@ -50,7 +50,7 @@ export default wrap(async (req, res) => {// POST / PUT — replaceconst rl = await limits.authIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const body = await readJson(req).catch(() => null);if (!body || body.strategy === undefined) {diff --git a/api/agent-trade/demo.js b/api/agent-trade/demo.jsindex 230f71968..5a04d8ae6 100644--- a/api/agent-trade/demo.js+++ b/api/agent-trade/demo.js@@ -26,7 +26,7 @@ import {LAMPORTS_PER_SOL,} from '../_lib/avatar-wallet.js';import { watsonxConfig, watsonxChatComplete } from '../_lib/watsonx.js';-import { cors, method, json, error, wrap } from '../_lib/http.js';+import { cors, method, json, error, wrap, rateLimited } from '../_lib/http.js';import { limits, clientIp } from '../_lib/rate-limit.js';const DEFAULT_PRICE_SOL = 0.001;@@ -126,7 +126,7 @@ export default wrap(async (req, res) => {// Rate-limit the live demo (it moves real SOL).const rl = await limits.authIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many demo requests');+ if (!rl.success) return rateLimited(res, rl, 'too many demo requests');const topic = (url.searchParams.get('topic') || 'crypto markets').trim().slice(0, 200);diff --git a/api/agent-trade/skill.js b/api/agent-trade/skill.jsindex 0bc665324..ad30af14a 100644--- a/api/agent-trade/skill.js+++ b/api/agent-trade/skill.js@@ -15,7 +15,7 @@ import {LAMPORTS_PER_SOL,} from '../_lib/avatar-wallet.js';import { watsonxConfig, watsonxChatComplete } from '../_lib/watsonx.js';-import { cors, method, json, error, wrap } from '../_lib/http.js';+import { cors, method, json, error, wrap, rateLimited } from '../_lib/http.js';import { limits, clientIp } from '../_lib/rate-limit.js';const DEFAULT_PRICE_SOL = 0.001;@@ -157,7 +157,7 @@ export default wrap(async (req, res) => {if (!method(req, res, ['GET'])) return;const rl = await limits.publicIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const cfg = skillConfig();if (!cfg.configured) {diff --git a/api/agent/send-sol.js b/api/agent/send-sol.jsindex 1dd8572ea..9b0cb7eb8 100644--- a/api/agent/send-sol.js+++ b/api/agent/send-sol.js@@ -13,7 +13,7 @@// IP rate-limit, optional shared-secret header (AVATAR_DEMO_TOKEN).import { z } from 'zod';-import { cors, json, method, readJson, wrap, error } from '../_lib/http.js';+import { cors, json, method, readJson, wrap, error, rateLimited } from '../_lib/http.js';import { parse } from '../_lib/validate.js';import { limits, clientIp } from '../_lib/rate-limit.js';import {@@ -67,7 +67,7 @@ export default wrap(async (req, res) => {}const rl = await limits.authIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many payout requests, try again shortly');+ if (!rl.success) return rateLimited(res, rl, 'too many payout requests, try again shortly');const body = parse(bodySchema, await readJson(req));diff --git a/api/agents.js b/api/agents.jsindex bc47ad865..63b004e7d 100644--- a/api/agents.js+++ b/api/agents.js@@ -13,7 +13,7 @@import { getSessionUser, authenticateBearer, extractBearer, hasScope } from './_lib/auth.js';import { sql } from './_lib/db.js';-import { cors, json, method, readJson, wrap, error } from './_lib/http.js';+import { cors, json, method, readJson, wrap, error, rateLimited } from './_lib/http.js';import { requireCsrf } from './_lib/csrf.js';import { limits, clientIp } from './_lib/rate-limit.js';import { generateAgentWallet, generateSolanaAgentWallet } from './_lib/agent-wallet.js';@@ -311,7 +311,7 @@ export async function handleGetOne(req, res, id) {if (req.method === 'GET') {const rl = await limits.publicIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);// Single roundtrip: pull skill_prices as a JSON-aggregated subquery// instead of a follow-up SELECT. Saves a second DB hop per GET ondiff --git a/api/agents/[id]/memory-seed-x.js b/api/agents/[id]/memory-seed-x.jsindex 2e6009e4a..344b47c32 100644--- a/api/agents/[id]/memory-seed-x.js+++ b/api/agents/[id]/memory-seed-x.js@@ -6,7 +6,7 @@import { sql } from '../../_lib/db.js';import { getSessionUser } from '../../_lib/auth.js';-import { cors, json, method, wrap, error } from '../../_lib/http.js';+import { cors, json, method, wrap, error, rateLimited } from '../../_lib/http.js';import { limits, clientIp } from '../../_lib/rate-limit.js';import { env } from '../../_lib/env.js';import { llmComplete } from '../../_lib/llm.js';@@ -124,7 +124,7 @@ async function handlePost(req, res, agentId) {if (!user) return error(res, 401, 'unauthorized', 'sign in required');const rl = await limits.xSeed(agentId);- if (!rl.success) return error(res, 429, 'rate_limited', 'agent can only be re-seeded every 6 hours');+ if (!rl.success) return rateLimited(res, rl, 'agent can only be re-seeded every 6 hours');const [agent] = await sql`SELECT id, user_id FROM agent_identities WHERE id = ${agentId} AND deleted_at IS NULLdiff --git a/api/agents/[id]/skill-access.js b/api/agents/[id]/skill-access.jsindex 2d3a83cd0..4bd9dc3ee 100644--- a/api/agents/[id]/skill-access.js+++ b/api/agents/[id]/skill-access.js@@ -19,7 +19,7 @@import { sql } from '../../_lib/db.js';import { authenticateBearer, extractBearer, getSessionUser } from '../../_lib/auth.js';-import { cors, error, json, method, wrap } from '../../_lib/http.js';+import { cors, error, json, method, wrap, rateLimited } from '../../_lib/http.js';import { clientIp, limits } from '../../_lib/rate-limit.js';const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;@@ -37,7 +37,7 @@ export default wrap(async (req, res) => {if (!method(req, res, ['GET'])) return;const rl = await limits.widgetRead(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const url = new URL(req.url, 'http://x');const id = url.searchParams.get('id') || url.pathname.split('/').filter(Boolean)[2];diff --git a/api/agents/[id]/skill-prices.js b/api/agents/[id]/skill-prices.jsindex 651c578f1..02b2d83b6 100644--- a/api/agents/[id]/skill-prices.js+++ b/api/agents/[id]/skill-prices.js@@ -10,7 +10,7 @@import { sql } from '../../_lib/db.js';import { authenticateBearer, extractBearer, getSessionUser } from '../../_lib/auth.js';-import { cors, error, json, method, readJson, wrap } from '../../_lib/http.js';+import { cors, error, json, method, readJson, wrap, rateLimited } from '../../_lib/http.js';import { clientIp, limits } from '../../_lib/rate-limit.js';import { z } from 'zod';@@ -46,7 +46,7 @@ export default wrap(async (req, res) => {if (!auth) return error(res, 401, 'unauthorized', 'sign in required');const rl = await limits.authIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const url = new URL(req.url, 'http://x');const parts = url.pathname.split('/').filter(Boolean);diff --git a/api/agents/_id/_sub.js b/api/agents/_id/_sub.jsindex 61b1532c6..94d91e6af 100644--- a/api/agents/_id/_sub.js+++ b/api/agents/_id/_sub.js@@ -6,7 +6,7 @@ import { Wallet } from 'ethers';import { z } from 'zod';import { sql } from '../../_lib/db.js';import { getSessionUser, authenticateBearer, extractBearer } from '../../_lib/auth.js';-import { cors, json, method, readJson, wrap, error } from '../../_lib/http.js';+import { cors, json, method, readJson, wrap, error, rateLimited } from '../../_lib/http.js';import { limits, clientIp } from '../../_lib/rate-limit.js';import { parse } from '../../_lib/validate.js';import { recoverAgentKey } from '../../_lib/agent-wallet.js';@@ -281,7 +281,7 @@ export const handleSign = wrap(async (req, res, id) => {if (!auth) return error(res, 401, 'unauthorized', 'sign in required');const rl = await limits.authIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many sign requests');+ if (!rl.success) return rateLimited(res, rl, 'too many sign requests');const [row] = await sql`SELECT id, user_id, wallet_address, meta FROM agent_identities WHERE id = ${id} AND deleted_at IS NULL LIMIT 1`;if (!row) return error(res, 404, 'not_found', 'agent not found');@@ -375,7 +375,7 @@ export const handleMemories = wrap(async (req, res, id, memoryId) => {// POSTconst rl = await limits.authIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const body = parse(memoryBodySchema, await readJson(req));const [row] = await sql`diff --git a/api/agents/_id/embed.js b/api/agents/_id/embed.jsindex d3d9d9d07..c00ea3bf9 100644--- a/api/agents/_id/embed.js+++ b/api/agents/_id/embed.js@@ -3,7 +3,7 @@// Used by AgentMemory.recall() for semantic similarity search.import { getSessionUser, authenticateBearer, extractBearer, hasScope } from '../../_lib/auth.js';-import { cors, json, method, readJson, error } from '../../_lib/http.js';+import { cors, json, method, readJson, error, rateLimited } from '../../_lib/http.js';import { limits } from '../../_lib/rate-limit.js';import { sql } from '../../_lib/db.js';import { env } from '../../_lib/env.js';@@ -35,7 +35,7 @@ export async function handleEmbed(req, res, id) {if (!agent) return error(res, 404, 'not_found', 'agent not found');const rl = await limits.embedUser(userId);- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const body = await readJson(req);const text = body?.text;diff --git a/api/agents/_id/memory-seed-farcaster.js b/api/agents/_id/memory-seed-farcaster.jsindex aedacfc37..9bf4a04c6 100644--- a/api/agents/_id/memory-seed-farcaster.js+++ b/api/agents/_id/memory-seed-farcaster.js@@ -4,7 +4,7 @@import { z } from 'zod';import { sql } from '../../_lib/db.js';import { getSessionUser, authenticateBearer, extractBearer } from '../../_lib/auth.js';-import { cors, json, method, readJson, wrap, error } from '../../_lib/http.js';+import { cors, json, method, readJson, wrap, error, rateLimited } from '../../_lib/http.js';import { limits, clientIp } from '../../_lib/rate-limit.js';import { parse } from '../../_lib/validate.js';import { env } from '../../_lib/env.js';@@ -103,12 +103,12 @@ export default wrap(async (req, res) => {// POSTconst rl = await limits.authIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);if (agent.farcaster_seeded_at) {const elapsed = Date.now() - new Date(agent.farcaster_seeded_at).getTime();if (elapsed < SEED_COOLDOWN_MS)- return error(res, 429, 'rate_limited', 'farcaster seed cooldown: try again in 6 hours');+ return rateLimited(res, rl, 'farcaster seed cooldown: try again in 6 hours');}const body = parse(bodySchema, await readJson(req));diff --git a/api/agents/_id/memory-seed-x.js b/api/agents/_id/memory-seed-x.jsindex 3c13dcaaf..0d5e53eb5 100644--- a/api/agents/_id/memory-seed-x.js+++ b/api/agents/_id/memory-seed-x.js@@ -11,7 +11,7 @@ import { webcrypto } from 'node:crypto';import { TwitterApi } from 'twitter-api-v2';import { sql } from '../../_lib/db.js';import { getSessionUser, authenticateBearer, extractBearer } from '../../_lib/auth.js';-import { cors, json, method, error } from '../../_lib/http.js';+import { cors, json, method, error, rateLimited } from '../../_lib/http.js';import { env } from '../../_lib/env.js';import { llmComplete } from '../../_lib/llm.js';import { limits } from '../../_lib/rate-limit.js';@@ -158,7 +158,7 @@ export default async function handleMemorySeedX(req, res, agentId) {// Rate limit: 1 seed per agent per 24 hoursconst rl = await limits.memorySeed(agentId);if (!rl.success) {- return error(res, 429, 'rate_limited', 'memory seeding is limited to once per 24 hours');+ return rateLimited(res, rl, 'memory seeding is limited to once per 24 hours');}let accessToken;diff --git a/api/agents/_id/memory-seed.js b/api/agents/_id/memory-seed.jsindex 51d657ed7..37c2d0550 100644--- a/api/agents/_id/memory-seed.js+++ b/api/agents/_id/memory-seed.js@@ -6,7 +6,7 @@import { webcrypto } from 'node:crypto';import { sql } from '../../_lib/db.js';import { getSessionUser, authenticateBearer, extractBearer } from '../../_lib/auth.js';-import { cors, json, method, error } from '../../_lib/http.js';+import { cors, json, method, error, rateLimited } from '../../_lib/http.js';import { env } from '../../_lib/env.js';import { llmComplete } from '../../_lib/llm.js';import { limits } from '../../_lib/rate-limit.js';@@ -147,7 +147,7 @@ export default async function handleMemorySeed(req, res, agentId) {// Rate limit: 1 seed per agent per 24 hoursconst rl = await limits.memorySeed(agentId);if (!rl.success) {- return error(res, 429, 'rate_limited', 'memory seeding is limited to once per 24 hours');+ return rateLimited(res, rl, 'memory seeding is limited to once per 24 hours');}let accessToken;diff --git a/api/agents/_id/memory/[cid].js b/api/agents/_id/memory/[cid].jsindex 5326f005e..766160208 100644--- a/api/agents/_id/memory/[cid].js+++ b/api/agents/_id/memory/[cid].js@@ -1,6 +1,6 @@import { sql } from '../../../_lib/db.js';import { getSessionUser, authenticateBearer, extractBearer } from '../../../_lib/auth.js';-import { cors, method, wrap, error } from '../../../_lib/http.js';+import { cors, method, wrap, error, rateLimited } from '../../../_lib/http.js';import { limits, clientIp } from '../../../_lib/rate-limit.js';const IPFS_GATEWAYS = [@@ -55,7 +55,7 @@ export default wrap(async (req, res) => {if (!agent) return error(res, 404, 'not_found', 'agent not found');const rl = await limits.authIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);// Bind the CID to this agent's own pinned set. Owning the agent is not enough// — without this the route is a generic authenticated IPFS fetch proxy for anydiff --git a/api/agents/_id/memory/pin.js b/api/agents/_id/memory/pin.jsindex 175c50a49..c51b6a1dd 100644--- a/api/agents/_id/memory/pin.js+++ b/api/agents/_id/memory/pin.js@@ -1,7 +1,7 @@import { z } from 'zod';import { sql } from '../../../_lib/db.js';import { getSessionUser, authenticateBearer, extractBearer } from '../../../_lib/auth.js';-import { cors, json, method, readJson, wrap, error } from '../../../_lib/http.js';+import { cors, json, method, readJson, wrap, error, rateLimited } from '../../../_lib/http.js';import { limits, clientIp } from '../../../_lib/rate-limit.js';import { parse } from '../../../_lib/validate.js';@@ -54,7 +54,7 @@ export default wrap(async (req, res) => {if (!agent) return error(res, 404, 'not_found', 'agent not found');const rl = await limits.upload(userId);- if (!rl.success) return error(res, 429, 'rate_limited', 'upload rate exceeded');+ if (!rl.success) return rateLimited(res, rl, 'upload rate exceeded');const body = parse(bodySchema, await readJson(req));diff --git a/api/agents/_id/payments.js b/api/agents/_id/payments.jsindex 575e4f5c6..3b684dbf5 100644--- a/api/agents/_id/payments.js+++ b/api/agents/_id/payments.js@@ -1,6 +1,6 @@import { sql } from '../../_lib/db.js';import { getSessionUser, authenticateBearer, extractBearer } from '../../_lib/auth.js';-import { cors, json, method, wrap, error } from '../../_lib/http.js';+import { cors, json, method, wrap, error, rateLimited } from '../../_lib/http.js';import { limits, clientIp } from '../../_lib/rate-limit.js';async function resolveAuth(req) {@@ -19,7 +19,7 @@ export const handlePayments = wrap(async (req, res, id) => {if (!auth) return error(res, 401, 'unauthorized', 'sign in required');const rl = await limits.authIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const [agent] = await sql`select id, user_id from agent_identitiesdiff --git a/api/agents/_id/persona.js b/api/agents/_id/persona.jsindex afc3fba0c..dc267d1ad 100644--- a/api/agents/_id/persona.js+++ b/api/agents/_id/persona.js@@ -4,7 +4,7 @@import { createHash, createHmac } from 'node:crypto';import { sql } from '../../_lib/db.js';import { getSessionUser, authenticateBearer, extractBearer } from '../../_lib/auth.js';-import { cors, json, method, readJson, wrap, error } from '../../_lib/http.js';+import { cors, json, method, readJson, wrap, error, rateLimited } from '../../_lib/http.js';import { limits } from '../../_lib/rate-limit.js';import { env } from '../../_lib/env.js';import { llmComplete, LlmUnavailableError } from '../../_lib/llm.js';@@ -56,7 +56,7 @@ export const handlePersona = wrap(async (req, res, id, action) => {if (req.method === 'POST' && action === 'extract') {const rl = await limits.personaExtract(auth.userId);if (!rl.success)- return error(res, 429, 'rate_limited', 'persona extraction limit reached (5 per day)');+ return rateLimited(res, rl, 'persona extraction limit reached (5 per day)');const body = parse(extractBody, await readJson(req));const { answers } = body;diff --git a/api/agents/_id/pricing/[skill].js b/api/agents/_id/pricing/[skill].jsindex 6b4cc4fb6..3aab48f7f 100644--- a/api/agents/_id/pricing/[skill].js+++ b/api/agents/_id/pricing/[skill].js@@ -1,7 +1,7 @@import { z } from 'zod';import { sql } from '../../../_lib/db.js';import { getSessionUser, authenticateBearer, extractBearer } from '../../../_lib/auth.js';-import { cors, json, method, readJson, wrap, error } from '../../../_lib/http.js';+import { cors, json, method, readJson, wrap, error, rateLimited } from '../../../_lib/http.js';import { parse } from '../../../_lib/validate.js';import { limits, clientIp } from '../../../_lib/rate-limit.js';import { requireCsrf } from '../../../_lib/csrf.js';@@ -46,7 +46,7 @@ export default wrap(async (req, res) => {if (!(await requireCsrf(req, res, userId))) return;const rl = await limits.authIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const [agent] = await sql`SELECT id, user_id FROM agent_identities WHERE id = ${id} AND deleted_at IS NULLdiff --git a/api/agents/_id/pricing/index.js b/api/agents/_id/pricing/index.jsindex d332a5bd3..4836d20fb 100644--- a/api/agents/_id/pricing/index.js+++ b/api/agents/_id/pricing/index.js@@ -1,5 +1,5 @@import { sql } from '../../../_lib/db.js';-import { cors, json, method, wrap, error } from '../../../_lib/http.js';+import { cors, json, method, wrap, error, rateLimited } from '../../../_lib/http.js';import { limits, clientIp } from '../../../_lib/rate-limit.js';// GET /api/agents/:id/pricing — public for all agents (x402 manifest reads this)@@ -12,7 +12,7 @@ export default wrap(async (req, res) => {if (!id) return error(res, 400, 'bad_request', 'missing agent id');const rl = await limits.pricingPerIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const [agent] = await sql`SELECT id FROM agent_identities WHERE id = ${id} AND deleted_at IS NULLdiff --git a/api/agents/_id/reputation.js b/api/agents/_id/reputation.jsindex 93b2d1f47..9a747e0ae 100644--- a/api/agents/_id/reputation.js+++ b/api/agents/_id/reputation.js@@ -1,5 +1,5 @@import { sql } from '../../_lib/db.js';-import { cors, json, error, method, wrap } from '../../_lib/http.js';+import { cors, json, error, method, wrap, rateLimited } from '../../_lib/http.js';import { limits, clientIp } from '../../_lib/rate-limit.js';import { env } from '../../_lib/env.js';@@ -32,7 +32,7 @@ export const handleReputation = wrap(async (req, res, agentId) => {if (!method(req, res, ['GET'])) return;const rl = await limits.publicIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const [agent] = await sql`SELECT erc8004_agent_id, chain_iddiff --git a/api/agents/_id/voice.js b/api/agents/_id/voice.jsindex 722610f6f..0d8616681 100644--- a/api/agents/_id/voice.js+++ b/api/agents/_id/voice.js@@ -8,7 +8,7 @@import { sql } from '../../_lib/db.js';import { getSessionUser, authenticateBearer, extractBearer } from '../../_lib/auth.js';-import { cors, json, method, wrap, error, readJson } from '../../_lib/http.js';+import { cors, json, method, wrap, error, readJson, rateLimited } from '../../_lib/http.js';import { limits } from '../../_lib/rate-limit.js';import {isConfigured,@@ -224,7 +224,7 @@ export const handleVoice = wrap(async (req, res, id, action) => {// Rate limit: 3 clones per user per day.const rl = await limits.voiceClone(auth.userId);if (!rl.success)- return error(res, 429, 'rate_limited', 'voice clone limit reached (3 per day)');+ return rateLimited(res, rl, 'voice clone limit reached (3 per day)');// Client can send recording duration in seconds so we can reject short clips// without decoding the audio.diff --git a/api/agents/by-address/[addr].js b/api/agents/by-address/[addr].jsindex 673773690..f8521e275 100644--- a/api/agents/by-address/[addr].js+++ b/api/agents/by-address/[addr].js@@ -5,7 +5,7 @@import { Contract } from 'ethers';import { evmFallbackProvider } from '../../_lib/evm/rpc.js';import { sql } from '../../_lib/db.js';-import { cors, error, json, method, wrap } from '../../_lib/http.js';+import { cors, error, json, method, wrap, rateLimited } from '../../_lib/http.js';import { limits, clientIp } from '../../_lib/rate-limit.js';import { SERVER_CHAIN_META, resolveURI } from '../../_lib/onchain.js';@@ -110,7 +110,7 @@ export default wrap(async (req, res) => {if (!method(req, res, ['GET'])) return;const rl = await limits.agentByAddress(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const raw = (req.query?.addr || '').trim().toLowerCase();if (!/^0x[a-f0-9]{40}$/.test(raw)) {diff --git a/api/agents/by-wallet.js b/api/agents/by-wallet.jsindex 51569a277..00c95eb4d 100644--- a/api/agents/by-wallet.js+++ b/api/agents/by-wallet.js@@ -8,7 +8,7 @@*/import { sql } from '../_lib/db.js';-import { cors, error, json, method, wrap } from '../_lib/http.js';+import { cors, error, json, method, wrap, rateLimited } from '../_lib/http.js';import { limits, clientIp } from '../_lib/rate-limit.js';export default wrap(async (req, res) => {@@ -16,7 +16,7 @@ export default wrap(async (req, res) => {if (!method(req, res, ['GET'])) return;const rl = await limits.authIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const url = new URL(req.url, 'http://x');const raw = (url.searchParams.get('address') || '').trim();diff --git a/api/agents/check-name.js b/api/agents/check-name.jsindex 2c6604490..28ad959bd 100644--- a/api/agents/check-name.js+++ b/api/agents/check-name.js@@ -3,7 +3,7 @@import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';import { sql } from '../_lib/db.js';-import { cors, json, method, wrap, error } from '../_lib/http.js';+import { cors, json, method, wrap, error, rateLimited } from '../_lib/http.js';import { limits, clientIp } from '../_lib/rate-limit.js';const NAME_RE = /^[a-zA-Z0-9_-]{3,32}$/;@@ -30,7 +30,7 @@ export default wrap(async (req, res) => {const userId = session?.id ?? bearer.userId;const rl = await limits.checkName(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const url = new URL(req.url, 'http://x');const name = (url.searchParams.get('name') || '').trim();diff --git a/api/agents/ens/[name].js b/api/agents/ens/[name].jsindex 7471ec4ed..8db8c0e62 100644--- a/api/agents/ens/[name].js+++ b/api/agents/ens/[name].js@@ -4,7 +4,7 @@import { evmFallbackProvider } from '../../_lib/evm/rpc.js';import { sql } from '../../_lib/db.js';-import { cors, error, json, method, wrap } from '../../_lib/http.js';+import { cors, error, json, method, wrap, rateLimited } from '../../_lib/http.js';import { limits, clientIp } from '../../_lib/rate-limit.js';import { env } from '../../_lib/env.js';@@ -72,7 +72,7 @@ export default wrap(async (req, res) => {if (!method(req, res, ['GET'])) return;const rl = await limits.ensResolve(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const name = (req.query?.name || '').trim().toLowerCase();diff --git a/api/agents/eth-vanity.js b/api/agents/eth-vanity.jsindex 24de664c6..1d084f80a 100644--- a/api/agents/eth-vanity.js+++ b/api/agents/eth-vanity.js@@ -30,7 +30,7 @@import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';import { sql } from '../_lib/db.js';-import { cors, json, method, error, readJson } from '../_lib/http.js';+import { cors, json, method, error, readJson, rateLimited } from '../_lib/http.js';import { limits, clientIp } from '../_lib/rate-limit.js';import { keccak_256 } from '@noble/hashes/sha3';@@ -133,7 +133,7 @@ export default async function handler(req, res, id, action) {const rl = req.method === 'GET'? await limits.walletRead(auth.userId): await limits.authIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const [row] = await sql`SELECT id, user_id, meta FROM agent_identities WHERE id = ${id} AND deleted_at IS NULL`;if (!row) return error(res, 404, 'not_found', 'agent not found');diff --git a/api/agents/featured.js b/api/agents/featured.jsindex 61bb282ec..354d919d8 100644--- a/api/agents/featured.js+++ b/api/agents/featured.js@@ -13,7 +13,7 @@// or 404 when there are zero eligible agents.import { sql } from '../_lib/db.js';-import { cors, json, method, wrap, error } from '../_lib/http.js';+import { cors, json, method, wrap, error, rateLimited } from '../_lib/http.js';import { limits, clientIp } from '../_lib/rate-limit.js';import { publicUrl } from '../_lib/r2.js';@@ -22,7 +22,7 @@ export default wrap(async (req, res) => {if (!method(req, res, ['GET'])) return;const rl = await limits.publicIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const [row] = await sql`WITH revenue AS (diff --git a/api/agents/gmgn.js b/api/agents/gmgn.jsindex e19ef586e..4be69fc97 100644--- a/api/agents/gmgn.js+++ b/api/agents/gmgn.js@@ -8,7 +8,7 @@* minSmartBuys number (default: 2)*/-import { cors, method, error } from '../_lib/http.js';+import { cors, method, error, rateLimited } from '../_lib/http.js';import { limits, clientIp } from '../_lib/rate-limit.js';import { connectGmgnFeed, recentGmgnBuffered } from '../_lib/gmgn-feed.js';@@ -28,7 +28,7 @@ async function handleFeed(req, res) {if (!method(req, res, ['GET'])) return;const rl = await limits.mcpIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many feed connections');+ if (!rl.success) return rateLimited(res, rl, 'too many feed connections');const url = new URL(req.url, 'http://x');const chain = url.searchParams.get('chain') || 'sol';diff --git a/api/agents/identity-check.js b/api/agents/identity-check.jsindex 270de7ccc..ebee0b3a5 100644--- a/api/agents/identity-check.js+++ b/api/agents/identity-check.js@@ -12,7 +12,7 @@// status:'unavailable' } and the client treats the identity as allowed.import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';-import { cors, json, method, wrap, error, readJson } from '../_lib/http.js';+import { cors, json, method, wrap, error, readJson, rateLimited } from '../_lib/http.js';import { limits, clientIp } from '../_lib/rate-limit.js';import { checkIdentityIntegrity } from '../_lib/identity-integrity.js';@@ -36,7 +36,7 @@ export default wrap(async (req, res) => {limits.identityCheckGlobal(),]);if (!ipRl.success || !globalRl.success) {- return error(res, 429, 'rate_limited', 'too many identity checks; try again shortly');+ return rateLimited(res, ipRl, 'too many identity checks; try again shortly');}let body;diff --git a/api/agents/nfts.js b/api/agents/nfts.jsindex 6dd319b35..231823f8c 100644--- a/api/agents/nfts.js+++ b/api/agents/nfts.js@@ -13,7 +13,7 @@* Requires HELIUS_API_KEY env var.*/-import { cors, json, method, error, wrap } from '../_lib/http.js';+import { cors, json, method, error, wrap, rateLimited } from '../_lib/http.js';import { limits, clientIp } from '../_lib/rate-limit.js';import { getSessionUser, authenticateBearer, extractBearer, hasScope } from '../_lib/auth.js';@@ -40,7 +40,7 @@ export default wrap(async (req, res) => {}const rl = await limits.authIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const op = req.query.op || 'portfolio';diff --git a/api/agents/onchain/[action].js b/api/agents/onchain/[action].jsindex e5260c623..b9f5e5e47 100644--- a/api/agents/onchain/[action].js+++ b/api/agents/onchain/[action].js@@ -22,7 +22,7 @@ import * as raw from 'multiformats/codecs/raw';import { sha256 } from 'multiformats/hashes/sha2';import { sql } from '../../_lib/db.js';import { getSessionUser } from '../../_lib/auth.js';-import { cors, json, method, readJson, wrap, error } from '../../_lib/http.js';+import { cors, json, method, readJson, wrap, error, rateLimited } from '../../_lib/http.js';import { limits, clientIp } from '../../_lib/rate-limit.js';import { parse } from '../../_lib/validate.js';import { randomToken } from '../../_lib/crypto.js';@@ -292,7 +292,7 @@ async function handlePrep(req, res) {if (!user) return error(res, 401, 'unauthorized', 'sign in required');const rl = await limits.authIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const body = parse(prepBodySchema, await readJson(req));@@ -504,7 +504,7 @@ async function handleConfirm(req, res) {if (!user) return error(res, 401, 'unauthorized', 'sign in required');const rl = await limits.authIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const body = parse(confirmBodySchema, await readJson(req));diff --git a/api/agents/payments/[action].js b/api/agents/payments/[action].jsindex dad6780c7..a2bdb4ef7 100644--- a/api/agents/payments/[action].js+++ b/api/agents/payments/[action].js@@ -29,7 +29,7 @@ import { OnlinePumpSdk } from '@pump-fun/pump-sdk';import BN from 'bn.js';import { sql } from '../../_lib/db.js';import { getSessionUser } from '../../_lib/auth.js';-import { cors, json, method, readJson, wrap, error } from '../../_lib/http.js';+import { cors, json, method, readJson, wrap, error, rateLimited } from '../../_lib/http.js';import { limits, clientIp } from '../../_lib/rate-limit.js';import { parse } from '../../_lib/validate.js';import { randomToken } from '../../_lib/crypto.js';@@ -85,7 +85,7 @@ async function handleCreatePrep(req, res) {if (!user) return error(res, 401, 'unauthorized', 'sign in required');const rl = await limits.authIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const body = parse(createPrepSchema, await readJson(req));@@ -183,7 +183,7 @@ async function handleCreateConfirm(req, res) {if (!user) return error(res, 401, 'unauthorized', 'sign in required');const rl = await limits.authIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const body = parse(createConfirmSchema, await readJson(req));@@ -272,7 +272,7 @@ async function handlePayPrep(req, res) {if (!user) return error(res, 401, 'unauthorized', 'sign in required');const rl = await limits.authIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const body = parse(payPrepSchema, await readJson(req));@@ -366,7 +366,7 @@ async function handlePayConfirm(req, res) {if (!user) return error(res, 401, 'unauthorized', 'sign in required');const rl = await limits.authIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const body = parse(payConfirmSchema, await readJson(req));diff --git a/api/agents/pricing.js b/api/agents/pricing.jsindex 505a43890..d3ac337ea 100644--- a/api/agents/pricing.js+++ b/api/agents/pricing.js@@ -6,7 +6,7 @@*/import { sql } from '../_lib/db.js';import { authenticateBearer, extractBearer, getSessionUser } from '../_lib/auth.js';-import { cors, error, json, method, readJson, wrap } from '../_lib/http.js';+import { cors, error, json, method, readJson, wrap, rateLimited } from '../_lib/http.js';import { clientIp, limits } from '../_lib/rate-limit.js';import { z } from 'zod';@@ -33,7 +33,7 @@ export default wrap(async (req, res) => {if (!auth) return error(res, 401, 'unauthorized', 'sign in required');const rl = await limits.authIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const url = new URL(req.url, 'http://x');const parts = url.pathname.split('/').filter(Boolean);diff --git a/api/agents/pumpfun.js b/api/agents/pumpfun.jsindex 5f94a3067..2bf0a1fa9 100644--- a/api/agents/pumpfun.js+++ b/api/agents/pumpfun.js@@ -17,7 +17,7 @@*/import { getSessionUser, authenticateBearer, extractBearer, hasScope } from '../_lib/auth.js';-import { cors, json, method, error, wrap } from '../_lib/http.js';+import { cors, json, method, error, wrap, rateLimited } from '../_lib/http.js';import { limits, clientIp } from '../_lib/rate-limit.js';import { pumpfunMcp, pumpfunBotEnabled } from '../_lib/pumpfun-mcp.js';@@ -39,7 +39,7 @@ export default wrap(async (req, res) => {const userId = session?.id ?? bearer.userId;const rl = await limits.mcpUser(String(userId));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const url = new URL(req.url, 'http://x');const op = url.searchParams.get('op') || 'claims';@@ -97,7 +97,7 @@ async function handleFeed(req, res) {if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;if (!method(req, res, ['GET'])) return;const rl = await limits.mcpIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many feed connections');+ if (!rl.success) return rateLimited(res, rl, 'too many feed connections');const url = new URL(req.url, 'http://x');const kind = url.searchParams.get('kind') || 'all';const mintParam = url.searchParams.get('mint');diff --git a/api/agents/pumpfun/[action].js b/api/agents/pumpfun/[action].jsindex 75b16261d..5bc53b6c5 100644--- a/api/agents/pumpfun/[action].js+++ b/api/agents/pumpfun/[action].js@@ -13,7 +13,7 @@*/import { getSessionUser, authenticateBearer, extractBearer } from '../../_lib/auth.js';-import { cors, json, method, readJson, wrap, error } from '../../_lib/http.js';+import { cors, json, method, readJson, wrap, error, rateLimited } from '../../_lib/http.js';import { limits, clientIp } from '../../_lib/rate-limit.js';import { loadAgentForSigning, solanaConnection } from '../../_lib/agent-pumpfun.js';import { checkBuyAllowed } from '../../_lib/agent-spend-policy.js';@@ -77,7 +77,7 @@ async function handleBuy(req, res, id) {const auth = await resolveAuth(req);if (!auth) return error(res, 401, 'unauthorized', 'sign in required');const rl = await limits.authIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);let body;try {@@ -227,7 +227,7 @@ async function handleLaunch(req, res, id) {const auth = await resolveAuth(req);if (!auth) return error(res, 401, 'unauthorized', 'sign in required');const rl = await limits.authIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);let body;try {@@ -417,7 +417,7 @@ async function handlePay(req, res, id) {const auth = await resolveAuth(req);if (!auth) return error(res, 401, 'unauthorized', 'sign in required');const rl = await limits.authIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);let body;try {@@ -622,7 +622,7 @@ async function handlePortfolio(req, res, id) {const auth = await resolveAuth(req);if (!auth) return error(res, 401, 'unauthorized', 'sign in required');const rl = await limits.authIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const url = new URL(req.url, 'http://x');const network = url.searchParams.get('network') === 'devnet' ? 'devnet' : 'mainnet';@@ -803,7 +803,7 @@ async function handleSell(req, res, id) {const auth = await resolveAuth(req);if (!auth) return error(res, 401, 'unauthorized', 'sign in required');const rl = await limits.authIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);let body;try {@@ -941,7 +941,7 @@ async function handleSwap(req, res, id) {const auth = await resolveAuth(req);if (!auth) return error(res, 401, 'unauthorized', 'sign in required');const rl = await limits.authIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);let body;try {diff --git a/api/agents/register/[action].js b/api/agents/register/[action].jsindex 1e8bd548f..5aee0e79d 100644--- a/api/agents/register/[action].js+++ b/api/agents/register/[action].js@@ -4,7 +4,7 @@import { sql } from '../../_lib/db.js';import { getSessionUser } from '../../_lib/auth.js';-import { cors, json, method, wrap, error, readJson } from '../../_lib/http.js';+import { cors, json, method, wrap, error, readJson, rateLimited } from '../../_lib/http.js';import { parse } from '../../_lib/validate.js';import { limits, clientIp } from '../../_lib/rate-limit.js';import { env } from '../../_lib/env.js';@@ -91,7 +91,7 @@ async function handlePrep(req, res) {const session = await getSessionUser(req);if (!session) return error(res, 401, 'unauthorized', 'sign in required');const rl = await limits.authIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const body = parse(prepSchema, await readJson(req));const [avatar] = await sql`select id from avatars where id = ${body.avatarId} and owner_id = ${session.id} and deleted_at is null limit 1`;if (!avatar) return error(res, 404, 'not_found', 'avatar not found');@@ -145,7 +145,7 @@ async function handleConfirm(req, res) {const session = await getSessionUser(req);if (!session) return error(res, 401, 'unauthorized', 'sign in required');const rl = await limits.authIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const body = parse(confirmSchema, await readJson(req));const chainMeta = SERVER_CHAIN_META[body.chainId];if (!chainMeta) return error(res, 400, 'bad_request', `unsupported chain ${body.chainId}`);diff --git a/api/agents/sas/[action].js b/api/agents/sas/[action].jsindex 95362209b..52e017914 100644--- a/api/agents/sas/[action].js+++ b/api/agents/sas/[action].js@@ -1,7 +1,7 @@// Consolidated SAS credential endpoints (credentials + issue-credential).import { sql } from '../../_lib/db.js';-import { cors, json, method, readJson, wrap, error } from '../../_lib/http.js';+import { cors, json, method, readJson, wrap, error, rateLimited } from '../../_lib/http.js';import { parse } from '../../_lib/validate.js';import { limits, clientIp } from '../../_lib/rate-limit.js';import { requireAdmin } from '../../_lib/admin.js';@@ -15,7 +15,7 @@ async function handleCredentials(req, res) {if (!method(req, res, ['GET'])) return;const rl = await limits.authIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const url = new URL(req.url, `http://${req.headers.host}`);const subject = url.searchParams.get('subject');@@ -52,7 +52,7 @@ async function handleIssueCredential(req, res) {if (!admin) return;const rl = await limits.authIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const body = parse(issueSchema, await readJson(req));const def = SAS_CONFIG.schemas[body.kind];diff --git a/api/agents/sns.js b/api/agents/sns.jsindex b497838d5..93b375cdd 100644--- a/api/agents/sns.js+++ b/api/agents/sns.js@@ -26,7 +26,7 @@import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';import { sql } from '../_lib/db.js';-import { cors, json, method, error, readJson } from '../_lib/http.js';+import { cors, json, method, error, readJson, rateLimited } from '../_lib/http.js';import { limits, clientIp } from '../_lib/rate-limit.js';import { env } from '../_lib/env.js';import { loadAgentForSigning, solanaConnection } from '../_lib/agent-pumpfun.js';@@ -283,7 +283,7 @@ export default async function handler(req, res, id, action) {if (!auth) return error(res, 401, 'unauthorized', 'sign in required');const rl = await limits.authIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);if (action === 'check') return handleCheck(req, res);if (action === 'register') return handleRegisterAgent(req, res, id, auth);diff --git a/api/agents/solana-airdrop.js b/api/agents/solana-airdrop.jsindex 91ddbef40..716a05b46 100644--- a/api/agents/solana-airdrop.js+++ b/api/agents/solana-airdrop.js@@ -1,6 +1,6 @@import { getSessionUser } from '../_lib/auth.js';import { sql } from '../_lib/db.js';-import { cors, error, json, method, wrap } from '../_lib/http.js';+import { cors, error, json, method, wrap, rateLimited } from '../_lib/http.js';import { limits, clientIp } from '../_lib/rate-limit.js';import { recordEvent } from '../_lib/usage.js';import { solanaConnection } from '../_lib/agent-pumpfun.js';@@ -14,7 +14,7 @@ export default wrap(async (req, res) => {if (!user) return error(res, 401, 'unauthorized', 'sign in required');const rl = await limits.authIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const url = new URL(req.url, 'http://x');const agentId = url.searchParams.get('id') || req.query?.id;diff --git a/api/agents/solana-wallet.js b/api/agents/solana-wallet.jsindex 3a49bd2c6..c44c4131c 100644--- a/api/agents/solana-wallet.js+++ b/api/agents/solana-wallet.js@@ -3,7 +3,7 @@import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';import { sql } from '../_lib/db.js';-import { cors, json, method, error, readJson } from '../_lib/http.js';+import { cors, json, method, error, readJson, rateLimited } from '../_lib/http.js';import { limits, clientIp } from '../_lib/rate-limit.js';import { generateSolanaAgentWallet } from '../_lib/agent-wallet.js';import { solanaConnection, solanaPublicConnection } from '../_lib/agent-pumpfun.js';@@ -126,7 +126,7 @@ async function handleActivity(req, res, id) {if (!auth) return error(res, 401, 'unauthorized', 'sign in required');const rl = await limits.walletRead(auth.userId);- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const [row] = await sql`SELECT id, user_id, meta FROM agent_identities WHERE id = ${id} AND deleted_at IS NULL`;if (!row) return error(res, 404, 'not_found', 'agent not found');@@ -222,7 +222,7 @@ async function handleAirdrop(req, res, id) {if (!auth) return error(res, 401, 'unauthorized', 'sign in required');const rl = await limits.authIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const [row] = await sql`SELECT id, user_id, meta FROM agent_identities WHERE id = ${id} AND deleted_at IS NULL`;if (!row) return error(res, 404, 'not_found', 'agent not found');@@ -326,7 +326,7 @@ async function handleWallet(req, res, id) {const rl = req.method === 'GET'? await limits.walletRead(auth.userId): await limits.authIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const [row] = await sql`SELECT id, user_id, meta FROM agent_identities WHERE id = ${id} AND deleted_at IS NULL`;if (!row) return error(res, 404, 'not_found', 'agent not found');diff --git a/api/agents/solana/_handlers.js b/api/agents/solana/_handlers.jsindex 659a3f6d3..ecd087b4f 100644--- a/api/agents/solana/_handlers.js+++ b/api/agents/solana/_handlers.js@@ -8,7 +8,7 @@ import { z } from 'zod';import { PublicKey } from '@solana/web3.js';import { solanaConnection } from '../../_lib/solana/connection.js';import { sql } from '../../_lib/db.js';-import { cors, json, method, wrap, error, readJson } from '../../_lib/http.js';+import { cors, json, method, wrap, error, readJson, rateLimited } from '../../_lib/http.js';import { limits, clientIp } from '../../_lib/rate-limit.js';import { getSessionUser } from '../../_lib/auth.js';import { parse } from '../../_lib/validate.js';@@ -57,7 +57,7 @@ export const handleAttestations = wrap(async (req, res) => {if (!method(req, res, ['GET'])) return;const rl = await limits.authIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const url = new URL(req.url, `http://${req.headers.host}`);const asset = url.searchParams.get('asset');@@ -116,7 +116,7 @@ export const handleAttestEvent = wrap(async (req, res) => {const startedAt = Date.now();const rl = await limits.authIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const secret = process.env.PUMPKIT_WEBHOOK_SECRET;if (!secret) return error(res, 500, 'internal', 'webhook secret not configured');@@ -344,7 +344,7 @@ export const handleRegisterPrep = wrap(async (req, res) => {if (!user) return error(res, 401, 'unauthorized', 'sign in required');const rl = await limits.authIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const body = parse(registerPrepSchema, await readJson(req));const { name, description, avatar_id, wallet_address, network, asset_pubkey, vanity_prefix } = body;@@ -499,7 +499,7 @@ export const handleRegisterConfirm = wrap(async (req, res) => {if (!user) return error(res, 401, 'unauthorized', 'sign in required');const rl = await limits.authIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const body = parse(registerConfirmSchema, await readJson(req));const { tx_signature, asset_pubkey, wallet_address, network } = body;@@ -601,7 +601,7 @@ export const handleEdit = wrap(async (req, res) => {if (!user) return error(res, 401, 'unauthorized', 'sign in required');const rl = await limits.authIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const body = parse(editSchema, await readJson(req));const { asset_pubkey, network } = body;@@ -711,7 +711,7 @@ export const handleReputation = wrap(async (req, res) => {if (!method(req, res, ['GET'])) return;const rl = await limits.authIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const url = new URL(req.url, `http://${req.headers.host}`);const asset = url.searchParams.get('asset');@@ -832,7 +832,7 @@ export const handleReputationHistory = wrap(async (req, res) => {if (!method(req, res, ['GET'])) return;const rl = await limits.authIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const url = new URL(req.url, `http://${req.headers.host}`);const asset = url.searchParams.get('asset');diff --git a/api/agents/suggest.js b/api/agents/suggest.jsindex c83b23dec..bf0d8f076 100644--- a/api/agents/suggest.js+++ b/api/agents/suggest.js@@ -3,7 +3,7 @@import { sql } from '../_lib/db.js';import { publicUrl } from '../_lib/r2.js';-import { cors, json, method, wrap, error } from '../_lib/http.js';+import { cors, json, method, wrap, error, rateLimited } from '../_lib/http.js';import { limits, clientIp } from '../_lib/rate-limit.js';const Q_RE = /[^a-zA-Z0-9_-]/g;@@ -13,7 +13,7 @@ export default wrap(async (req, res) => {if (!method(req, res, ['GET'])) return;const rl = await limits.agentSuggest(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const url = new URL(req.url, 'http://x');const raw = (url.searchParams.get('q') || '').trim();diff --git a/api/agents/talk.js b/api/agents/talk.jsindex e65c4c475..bf4a904a8 100644--- a/api/agents/talk.js+++ b/api/agents/talk.js@@ -17,7 +17,7 @@import { z } from 'zod';import { sql } from '../_lib/db.js';-import { cors, error, json, method, readJson, wrap } from '../_lib/http.js';+import { cors, error, json, method, readJson, wrap, rateLimited } from '../_lib/http.js';import { limits, clientIp } from '../_lib/rate-limit.js';import { normalizeLegacyPolicy } from '../_lib/embed-policy.js';import { llmComplete, LlmUnavailableError } from '../_lib/llm.js';@@ -45,7 +45,7 @@ export default wrap(async (req, res) => {}const rl = await limits.agentDelegate(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'agent delegate rate limit');+ if (!rl.success) return rateLimited(res, rl, 'agent delegate rate limit');let raw;try {diff --git a/api/agents/tokens/[action].js b/api/agents/tokens/[action].jsindex 6131a8ca4..0254a994d 100644--- a/api/agents/tokens/[action].js+++ b/api/agents/tokens/[action].js@@ -16,7 +16,7 @@ import { createHash } from 'crypto';import { sql } from '../../_lib/db.js';import { getSessionUser } from '../../_lib/auth.js';-import { cors, json, method, readJson, wrap, error } from '../../_lib/http.js';+import { cors, json, method, readJson, wrap, error, rateLimited } from '../../_lib/http.js';import { limits, clientIp } from '../../_lib/rate-limit.js';import { parse } from '../../_lib/validate.js';import { randomToken } from '../../_lib/crypto.js';@@ -136,7 +136,7 @@ async function handleLaunchPrep(req, res) {if (!user) return error(res, 401, 'unauthorized', 'sign in required');const rl = await limits.authIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const body = parse(launchPrepSchema, await readJson(req));@@ -328,7 +328,7 @@ async function handleLaunchConfirm(req, res) {if (!user) return error(res, 401, 'unauthorized', 'sign in required');const rl = await limits.authIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const body = parse(launchConfirmSchema, await readJson(req));@@ -450,7 +450,7 @@ async function handleLaunchQuote(req, res) {if (!user) return error(res, 401, 'unauthorized', 'sign in required');const rl = await limits.authIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const url = new URL(req.url, 'http://x');const q = parse(launchQuoteSchema, {diff --git a/api/agents/x402/[action].js b/api/agents/x402/[action].jsindex c25986c9f..df9dea419 100644--- a/api/agents/x402/[action].js+++ b/api/agents/x402/[action].js@@ -3,7 +3,7 @@import { z } from 'zod';import { sql } from '../../_lib/db.js';import { getSessionUser, authenticateBearer, extractBearer } from '../../_lib/auth.js';-import { cors, json, method, readJson, wrap, error } from '../../_lib/http.js';+import { cors, json, method, readJson, wrap, error, rateLimited } from '../../_lib/http.js';import { limits, clientIp } from '../../_lib/rate-limit.js';import { parse, isUuid } from '../../_lib/validate.js';import { emit402, verifyPaid, consumeIntent, manifestOnly } from '../../_lib/x402.js';@@ -53,7 +53,7 @@ async function handleInvoke(req, res) {if (!auth) return error(res, 401, 'unauthorized', 'sign in or provide a bearer token');const rl = await limits.authIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const body = parse(invokeSchema, await readJson(req));if (!isUuid(body.agent_id)) return error(res, 404, 'not_found', 'agent not found');@@ -115,7 +115,7 @@ async function handleManifest(req, res) {if (!method(req, res, ['GET'])) return;const rl = await limits.publicIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const url = new URL(req.url, 'http://x');const agent_id = url.searchParams.get('agent_id');diff --git a/api/aixbt/chat.js b/api/aixbt/chat.jsindex c6908093d..4bae5b097 100644--- a/api/aixbt/chat.js+++ b/api/aixbt/chat.js@@ -6,7 +6,7 @@// Body: { messages: [{ role, content }], ... } OR { message: "..." }// Response: { reply, source } | { error, error_description }-import { wrap, cors, method, json, error, readJson } from '../_lib/http.js';+import { wrap, cors, method, json, error, readJson, rateLimited } from '../_lib/http.js';import { limits, clientIp } from '../_lib/rate-limit.js';import { chatIndigo } from '../_lib/aixbt.js';import { respondAixbtError } from './_shared.js';@@ -35,7 +35,7 @@ export default wrap(async (req, res) => {if (!method(req, res, ['POST'])) return;const rl = await limits.aixbtIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const body = await readJson(req).catch(() => null);const messages = normalizeMessages(body);diff --git a/api/aixbt/grounding.js b/api/aixbt/grounding.jsindex d04d0c235..09f75def3 100644--- a/api/aixbt/grounding.js+++ b/api/aixbt/grounding.js@@ -5,7 +5,7 @@//// Response: { grounding, source } | { error, error_description }-import { wrap, cors, method, json, error } from '../_lib/http.js';+import { wrap, cors, method, json, error, rateLimited } from '../_lib/http.js';import { limits, clientIp } from '../_lib/rate-limit.js';import { getGrounding } from '../_lib/aixbt.js';import { respondAixbtError } from './_shared.js';@@ -15,7 +15,7 @@ export default wrap(async (req, res) => {if (!method(req, res, ['GET'])) return;const rl = await limits.aixbtIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);try {const result = await getGrounding();diff --git a/api/aixbt/intel.js b/api/aixbt/intel.jsindex 62acecb5e..73f17ebde 100644--- a/api/aixbt/intel.js+++ b/api/aixbt/intel.js@@ -7,7 +7,7 @@// Query: ?limit=20&category=<cat>&chain=<chain>// Response: { intel: [...], pagination } | { error, error_description, setup? }-import { wrap, cors, method, json, error } from '../_lib/http.js';+import { wrap, cors, method, json, error, rateLimited } from '../_lib/http.js';import { limits, clientIp } from '../_lib/rate-limit.js';import { getIntel } from '../_lib/aixbt.js';import { respondAixbtError } from './_shared.js';@@ -17,7 +17,7 @@ export default wrap(async (req, res) => {if (!method(req, res, ['GET'])) return;const rl = await limits.aixbtIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const url = new URL(req.url, 'http://x');const limit = Number(url.searchParams.get('limit')) || 20;diff --git a/api/aixbt/projects.js b/api/aixbt/projects.jsindex f0fe9c95d..a8d484a36 100644--- a/api/aixbt/projects.js+++ b/api/aixbt/projects.js@@ -5,7 +5,7 @@// Query: ?limit=20&page=1&names=<comma list>&chain=<chain>// Response: { projects: [...], pagination } | { error, error_description }-import { wrap, cors, method, json, error } from '../_lib/http.js';+import { wrap, cors, method, json, error, rateLimited } from '../_lib/http.js';import { limits, clientIp } from '../_lib/rate-limit.js';import { getProjects } from '../_lib/aixbt.js';import { respondAixbtError } from './_shared.js';@@ -15,7 +15,7 @@ export default wrap(async (req, res) => {if (!method(req, res, ['GET'])) return;const rl = await limits.aixbtIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const url = new URL(req.url, 'http://x');const limit = Number(url.searchParams.get('limit')) || 20;diff --git a/api/alerts/config.js b/api/alerts/config.jsindex 9f1f12a03..1c88e7c51 100644--- a/api/alerts/config.js+++ b/api/alerts/config.js@@ -7,7 +7,7 @@import { sql } from '../_lib/db.js';import { getSessionUser } from '../_lib/auth.js';-import { cors, json, method, wrap, error, readJson } from '../_lib/http.js';+import { cors, json, method, wrap, error, readJson, rateLimited } from '../_lib/http.js';import { requireCsrf } from '../_lib/csrf.js';import { limits, clientIp } from '../_lib/rate-limit.js';import { parse } from '../_lib/validate.js';@@ -66,7 +66,7 @@ export default wrap(async (req, res) => {if (!user) return error(res, 401, 'unauthorized', 'sign in required');const rl = await limits.prefsWrite(user.id);- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);if (req.method === 'GET') {const [row] = await sql`diff --git a/api/animations/clips.js b/api/animations/clips.jsindex 7f2fe8e16..1ed00ffd1 100644--- a/api/animations/clips.js+++ b/api/animations/clips.js@@ -11,7 +11,7 @@import { getSessionUser, authenticateBearer, extractBearer, hasScope } from '../_lib/auth.js';import { sql } from '../_lib/db.js';-import { cors, json, method, readJson, wrap, error } from '../_lib/http.js';+import { cors, json, method, readJson, wrap, error, rateLimited } from '../_lib/http.js';import { putObject, publicUrl } from '../_lib/r2.js';import { limits } from '../_lib/rate-limit.js';import { z } from 'zod';@@ -155,7 +155,7 @@ async function handleList(req, res, auth) {async function handleCreate(req, res, auth) {const rl = await limits.avatarPatch(auth.userId);- if (!rl.success) return error(res, 429, 'rate_limited', 'too many animation saves');+ if (!rl.success) return rateLimited(res, rl, 'too many animation saves');const body = await readJson(req);if (!body) return error(res, 400, 'invalid_request', 'body required');diff --git a/api/animations/presign.js b/api/animations/presign.jsindex 939df9a2e..1ed07e449 100644--- a/api/animations/presign.js+++ b/api/animations/presign.js@@ -5,7 +5,7 @@import { getSessionUser, authenticateBearer, extractBearer, hasScope } from '../_lib/auth.js';import { presignUpload } from '../_lib/r2.js';-import { cors, json, method, readJson, wrap, error } from '../_lib/http.js';+import { cors, json, method, readJson, wrap, error, rateLimited } from '../_lib/http.js';import { limits, clientIp } from '../_lib/rate-limit.js';import { z } from 'zod';@@ -37,7 +37,7 @@ export default wrap(async (req, res) => {if (!userId) return error(res, 401, 'unauthorized', 'sign in or provide a valid bearer token');const rl = await limits.upload(userId);- if (!rl.success) return error(res, 429, 'rate_limited', 'upload rate exceeded');+ if (!rl.success) return rateLimited(res, rl, 'upload rate exceeded');const raw = await readJson(req);const parsed = bodySchema.safeParse(raw);diff --git a/api/animations/thumbnail.js b/api/animations/thumbnail.jsindex 47f2f17b8..e259f7026 100644--- a/api/animations/thumbnail.js+++ b/api/animations/thumbnail.js@@ -6,7 +6,7 @@import { sql } from '../_lib/db.js';import { getSessionUser, authenticateBearer, extractBearer, hasScope } from '../_lib/auth.js';import { putObject, deleteObject, publicUrl } from '../_lib/r2.js';-import { cors, error, json, method, readJson, wrap } from '../_lib/http.js';+import { cors, error, json, method, readJson, wrap, rateLimited } from '../_lib/http.js';import { limits } from '../_lib/rate-limit.js';const MAX_PNG_BYTES = 1_500_000;@@ -20,7 +20,7 @@ export default wrap(async (req, res) => {if (!auth) return error(res, 401, 'unauthorized', 'sign in or provide a valid bearer token');const rl = await limits.upload(auth.userId);- if (!rl.success) return error(res, 429, 'rate_limited', 'thumbnail upload rate exceeded');+ if (!rl.success) return rateLimited(res, rl, 'thumbnail upload rate exceeded');const body = await readJson(req).catch(() => null);const id = body?.id;diff --git a/api/api-keys.js b/api/api-keys.jsindex 968384c6b..4b56b47df 100644--- a/api/api-keys.js+++ b/api/api-keys.js@@ -1,7 +1,7 @@import { randomToken, sha256 } from './_lib/crypto.js';import { sql } from './_lib/db.js';import { getSessionUser, authenticateBearer, extractBearer, hasScope } from './_lib/auth.js';-import { cors, json, error, wrap, method, readJson } from './_lib/http.js';+import { cors, json, error, wrap, method, readJson, rateLimited } from './_lib/http.js';import { limits, clientIp } from './_lib/rate-limit.js';import { requireCsrf } from './_lib/csrf.js';import { parse } from './_lib/validate.js';@@ -31,7 +31,7 @@ export default wrap(async (req, res) => {const userId = session?.id ?? bearer.userId;const rl = await limits.authIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);if (req.method === 'GET') {const rows = await sql`diff --git a/api/api-keys/[id].js b/api/api-keys/[id].jsindex 571c144fb..78e336dd6 100644--- a/api/api-keys/[id].js+++ b/api/api-keys/[id].js@@ -1,7 +1,7 @@import { sql } from '../_lib/db.js';import { getSessionUser, authenticateBearer, extractBearer, hasScope } from '../_lib/auth.js';import { logAudit } from '../_lib/audit.js';-import { cors, json, error, wrap, method } from '../_lib/http.js';+import { cors, json, error, wrap, method, rateLimited } from '../_lib/http.js';import { limits, clientIp } from '../_lib/rate-limit.js';export default wrap(async (req, res) => {@@ -16,7 +16,7 @@ export default wrap(async (req, res) => {const userId = session?.id ?? bearer.userId;const rl = await limits.authIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const { id } = req.query;diff --git a/api/artifact.js b/api/artifact.jsindex 0f82d4830..70d8b6230 100644--- a/api/artifact.js+++ b/api/artifact.js@@ -13,7 +13,7 @@ import { readFileSync } from 'node:fs';import { fileURLToPath } from 'node:url';import { dirname, resolve as pathResolve } from 'node:path';import { sql } from './_lib/db.js';-import { error, wrap } from './_lib/http.js';+import { error, wrap, rateLimited } from './_lib/http.js';import { limits, clientIp } from './_lib/rate-limit.js';import { getObjectBuffer } from './_lib/r2.js';import { assertSafePublicUrl } from './_lib/ssrf-guard.js';@@ -213,7 +213,7 @@ export default wrap(async (req, res) => {const ip = clientIp(req);const rl = await limits.widgetRead(ip);- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const params = new URL(req.url, 'http://x').searchParams;const agentId = params.get('agent');diff --git a/api/audit-log.js b/api/audit-log.jsindex 5d5d9cc66..2f14c1c00 100644--- a/api/audit-log.js+++ b/api/audit-log.js@@ -15,7 +15,7 @@import { sql } from './_lib/db.js';import { getSessionUser } from './_lib/auth.js';-import { cors, error, json, method, wrap } from './_lib/http.js';+import { cors, error, json, method, wrap, rateLimited } from './_lib/http.js';import { limits } from './_lib/rate-limit.js';const DEFAULT_LIMIT = 50;@@ -58,7 +58,7 @@ export default wrap(async (req, res) => {if (!session) return error(res, 401, 'unauthorized', 'sign in required');const rl = await limits.auditLogRead(session.id);- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const url = new URL(req.url, 'http://x');const format = (url.searchParams.get('format') || '').toLowerCase();diff --git a/api/auth/[action].js b/api/auth/[action].jsindex 1e929e286..a668e4448 100644--- a/api/auth/[action].js+++ b/api/auth/[action].js@@ -10,7 +10,7 @@ import {getSessionUser, hasSessionCookie, revokeRefreshToken,} from '../_lib/auth.js';import { randomToken, sha256 } from '../_lib/crypto.js';-import { cors, json, method, readJson, wrap, error } from '../_lib/http.js';+import { cors, json, method, readJson, wrap, error, rateLimited } from '../_lib/http.js';import { limits, clientIp } from '../_lib/rate-limit.js';import { parse, loginBody, registerBody, usernameRegisterBody, username as usernameValidator, displayName, email, password } from '../_lib/validate.js';import { sendPasswordResetEmail, sendVerificationEmail } from '../_lib/email.js';@@ -33,7 +33,7 @@ async function handleLogin(req, res) {if (!method(req, res, ['POST'])) return;const ip = clientIp(req);const rl = await limits.authIp(ip);- if (!rl.success) return error(res, 429, 'rate_limited', 'too many attempts; try again later');+ if (!rl.success) return rateLimited(res, rl, 'too many attempts; try again later');const body = parse(loginBody, await readJson(req));const isEmail = body.email.includes('@');const rows = isEmail@@ -76,7 +76,7 @@ async function handleLogoutEverywhere(req, res) {const user = await getSessionUser(req);if (!user) return error(res, 401, 'unauthenticated', 'not signed in');const rl = await limits.authIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const sessionResult = await sql`update sessions set revoked_at = now() where user_id = ${user.id} and revoked_at is null`;await sql`update oauth_refresh_tokens set revoked_at = now() where user_id = ${user.id} and revoked_at is null`;const clearCookies = sessionCookie('', { clear: true });@@ -118,7 +118,7 @@ async function handleRegister(req, res) {if (!method(req, res, ['POST'])) return;const ip = clientIp(req);const rl = await limits.registerIp(ip);- if (!rl.success) return error(res, 429, 'rate_limited', 'too many signups from this IP');+ if (!rl.success) return rateLimited(res, rl, 'too many signups from this IP');const raw = await readJson(req);let email_val, displayName_val, passwordVal, referralCode;if (raw.username && !raw.email) {@@ -193,7 +193,7 @@ async function handleProfile(req, res) {const user = await getSessionUser(req);if (!user) return error(res, 401, 'unauthenticated', 'not signed in');const rl = await limits.authIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const body = parse(profileSchema, await readJson(req));if (body.username) {const taken = await sql`select id from users where lower(username) = ${body.username.toLowerCase()} and id != ${user.id} and deleted_at is null limit 1`;@@ -243,7 +243,7 @@ async function handleResetPassword(req, res) {if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;if (!method(req, res, ['POST'])) return;const rl = await limits.authIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many attempts; try again later');+ if (!rl.success) return rateLimited(res, rl, 'too many attempts; try again later');const body = parse(resetSchema, await readJson(req));const tokenHash = await sha256(body.token);const rows = await sql`select r.id, r.user_id from password_resets r join users u on u.id = r.user_id where r.token_hash = ${tokenHash} and r.consumed_at is null and r.expires_at > now() and u.deleted_at is null limit 1`;@@ -263,7 +263,7 @@ async function handleVerifyEmail(req, res) {if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;if (!method(req, res, ['POST'])) return;const rl = await limits.verifyEmailIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many attempts; try again later');+ if (!rl.success) return rateLimited(res, rl, 'too many attempts; try again later');const body = parse(verifyEmailSchema, await readJson(req));const codeHash = await sha256(body.code);const rows = await sql`select v.id, v.user_id from email_verifications v join users u on u.id = v.user_id where v.code_hash = ${codeHash} and v.consumed_at is null and v.expires_at > now() and u.deleted_at is null limit 1`;@@ -281,7 +281,7 @@ async function handleResendVerification(req, res) {const session = await getSessionUser(req);if (!session) return error(res, 401, 'unauthorized', 'sign in required');const rl = await limits.resendVerifyUser(session.id);- if (!rl.success) return error(res, 429, 'rate_limited', 'please wait before requesting again');+ if (!rl.success) return rateLimited(res, rl, 'please wait before requesting again');const rows = await sql`select email, email_verified from users where id = ${session.id} and deleted_at is null limit 1`;if (!rows[0]) return error(res, 401, 'unauthorized', 'sign in required');if (rows[0].email_verified) return json(res, 200, { success: true, already_verified: true });diff --git a/api/auth/privy/verify.js b/api/auth/privy/verify.jsindex cb1b0eaa0..33782bde2 100644--- a/api/auth/privy/verify.js+++ b/api/auth/privy/verify.js@@ -17,7 +17,7 @@ import {} from '../../_lib/auth.js';import { fetchPrivyWallets, extractIdentity } from '../../_lib/privy.js';import { env } from '../../_lib/env.js';-import { cors, json, method, readJson, wrap, error } from '../../_lib/http.js';+import { cors, json, method, readJson, wrap, error, rateLimited } from '../../_lib/http.js';import { limits, clientIp } from '../../_lib/rate-limit.js';import { parse } from '../../_lib/validate.js';import { seedDefaultAgent } from '../../_lib/seed-default-agent.js';@@ -33,7 +33,7 @@ export default wrap(async (req, res) => {const ip = clientIp(req);const rl = await limits.authIp(ip);- if (!rl.success) return error(res, 429, 'rate_limited', 'too many attempts');+ if (!rl.success) return rateLimited(res, rl, 'too many attempts');if (!env.PRIVY_APP_ID) return error(res, 503, 'not_configured', 'Privy is not configured on this server');diff --git a/api/auth/sessions/[action].js b/api/auth/sessions/[action].jsindex 8c296948b..59c16f28b 100644--- a/api/auth/sessions/[action].js+++ b/api/auth/sessions/[action].js@@ -9,7 +9,7 @@import { sql } from '../../_lib/db.js';import { getSessionUser, rotateSession, sessionCookie } from '../../_lib/auth.js';-import { cors, json, method, wrap, error } from '../../_lib/http.js';+import { cors, json, method, wrap, error, rateLimited } from '../../_lib/http.js';import { limits, clientIp } from '../../_lib/rate-limit.js';const UUID_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;@@ -35,7 +35,7 @@ async function handleIndex(req, res) {const ip = clientIp(req);const rl = await limits.authIp(ip);- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);if (req.method === 'GET') {const rows = await sql`diff --git a/api/auth/siwe/[action].js b/api/auth/siwe/[action].jsindex 2d7d571b2..57a11a595 100644--- a/api/auth/siwe/[action].js+++ b/api/auth/siwe/[action].js@@ -6,7 +6,7 @@ import { verifyMessage, getAddress } from 'ethers';import { z } from 'zod';import { sql } from '../../_lib/db.js';import { createSession, sessionCookie, destroySession } from '../../_lib/auth.js';-import { cors, json, method, readJson, wrap, error } from '../../_lib/http.js';+import { cors, json, method, readJson, wrap, error, rateLimited } from '../../_lib/http.js';import { limits, clientIp } from '../../_lib/rate-limit.js';import { randomToken, hmacSha256, constantTimeEquals } from '../../_lib/crypto.js';import { env } from '../../_lib/env.js';@@ -38,7 +38,7 @@ async function handleNonce(req, res) {const ip = clientIp(req);const rl = await limits.authIp(ip);- if (!rl.success) return error(res, 429, 'rate_limited', 'too many nonce requests');+ if (!rl.success) return rateLimited(res, rl, 'too many nonce requests');// EIP-4361 requires ≥8 alphanumeric chars. Strip base64url's - and _.// 22 chars ≈ 131 bits of entropy (log2(62^22) ≈ 131).@@ -106,7 +106,7 @@ async function handleVerify(req, res) {const ip = clientIp(req);const rl = await limits.authIp(ip);- if (!rl.success) return error(res, 429, 'rate_limited', 'too many attempts');+ if (!rl.success) return rateLimited(res, rl, 'too many attempts');const body = parse(verifyBody, await readJson(req));diff --git a/api/auth/siws/[action].js b/api/auth/siws/[action].jsindex e6e543f58..9dc9827f2 100644--- a/api/auth/siws/[action].js+++ b/api/auth/siws/[action].js@@ -5,7 +5,7 @@import { z } from 'zod';import { sql } from '../../_lib/db.js';import { createSession, sessionCookie, destroySession } from '../../_lib/auth.js';-import { cors, json, method, readJson, wrap, error } from '../../_lib/http.js';+import { cors, json, method, readJson, wrap, error, rateLimited } from '../../_lib/http.js';import { limits, clientIp } from '../../_lib/rate-limit.js';import { env } from '../../_lib/env.js';import { parse } from '../../_lib/validate.js';@@ -40,7 +40,7 @@ async function handleNonce(req, res) {const ip = clientIp(req);const rl = await limits.authIp(ip);- if (!rl.success) return error(res, 429, 'rate_limited', 'too many nonce requests');+ if (!rl.success) return rateLimited(res, rl, 'too many nonce requests');// 22 alphanumeric chars ≈ 131 bits of entropy.let nonce = '';@@ -107,7 +107,7 @@ async function handleVerify(req, res) {const ip = clientIp(req);const rl = await limits.authIp(ip);- if (!rl.success) return error(res, 429, 'rate_limited', 'too many attempts');+ if (!rl.success) return rateLimited(res, rl, 'too many attempts');const body = parse(verifyBody, await readJson(req));diff --git a/api/auth/x/[action].js b/api/auth/x/[action].jsindex 606cecac8..7688a49eb 100644--- a/api/auth/x/[action].js+++ b/api/auth/x/[action].js@@ -16,7 +16,7 @@ import {hmacSha256,constantTimeEquals,} from '../../_lib/crypto.js';-import { cors, method, wrap, error, redirect } from '../../_lib/http.js';+import { cors, method, wrap, error, redirect, rateLimited } from '../../_lib/http.js';import { limits, clientIp } from '../../_lib/rate-limit.js';import { env } from '../../_lib/env.js';@@ -118,7 +118,7 @@ async function handleConnect(req, res) {}const rl = await limits.authIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const user = await getSessionUser(req);if (!user) return error(res, 401, 'unauthorized', 'sign in required');diff --git a/api/avatar/presign-glb.js b/api/avatar/presign-glb.jsindex 450844059..b7fc80f41 100644--- a/api/avatar/presign-glb.js+++ b/api/avatar/presign-glb.js@@ -21,7 +21,7 @@// storage_key: string, // R2 key, for reference// }-import { cors, error, json, wrap } from '../_lib/http.js';+import { cors, error, json, wrap, rateLimited } from '../_lib/http.js';import { getSessionUser } from '../_lib/auth.js';import { presignUpload, publicUrl } from '../_lib/r2.js';import { limits, clientIp } from '../_lib/rate-limit.js';@@ -53,7 +53,7 @@ export default wrap(async (req, res) => {const rl = userId === 'anon'? await limits.publicIp(clientIp(req)): await limits.upload(userId);- if (!rl.success) return error(res, 429, 'rate_limited', 'too many upload requests');+ if (!rl.success) return rateLimited(res, rl, 'too many upload requests');const body = req.body || {};const contentType = (body.content_type || 'model/gltf-binary').toLowerCase().trim();diff --git a/api/avatar/render.js b/api/avatar/render.jsindex 016c45006..6f6f729df 100644--- a/api/avatar/render.js+++ b/api/avatar/render.js@@ -25,7 +25,7 @@ import { createHash } from 'node:crypto';// puppeteer-core + @sparticuz/chromium-min are loaded lazily inside getBrowser()// so Vercel's NFT does not statically trace the chromium binary tree on every// route in this function package — that trace was the 45-min build timeout.-import { cors, error, json, wrap } from '../_lib/http.js';+import { cors, error, json, wrap, rateLimited } from '../_lib/http.js';import { env } from '../_lib/env.js';import { getAvatar } from '../_lib/avatars.js';import { publicUrl, putObject, headObject } from '../_lib/r2.js';@@ -54,12 +54,13 @@ const FORMAT_TYPES = {const rateMap = new Map();function rateCheck(ip) {- if (!ip) return true;const now = Date.now();+ if (!ip)+ return { success: true, limit: RATE_LIMIT_MAX, remaining: RATE_LIMIT_MAX, reset: now + RATE_LIMIT_WINDOW_MS };const arr = (rateMap.get(ip) || []).filter((t) => now - t < RATE_LIMIT_WINDOW_MS);if (arr.length >= RATE_LIMIT_MAX) {rateMap.set(ip, arr);- return false;+ return { success: false, limit: RATE_LIMIT_MAX, remaining: 0, reset: arr[0] + RATE_LIMIT_WINDOW_MS };}arr.push(now);rateMap.set(ip, arr);@@ -68,7 +69,7 @@ function rateCheck(ip) {if (v.every((t) => now - t >= RATE_LIMIT_WINDOW_MS)) rateMap.delete(k);}}- return true;+ return { success: true, limit: RATE_LIMIT_MAX, remaining: RATE_LIMIT_MAX - arr.length, reset: now + RATE_LIMIT_WINDOW_MS };}function cacheKey(avatarId, paramsHash, format) {@@ -88,8 +89,9 @@ export default wrap(async function handler(req, res) {}const ip = (req.headers['x-forwarded-for'] || '').split(',')[0].trim() || req.socket?.remoteAddress;- if (!rateCheck(ip)) {- return error(res, 429, 'rate_limited', `Limit: ${RATE_LIMIT_MAX} renders per ${RATE_LIMIT_WINDOW_MS / 60000}m`);+ const rl = rateCheck(ip);+ if (!rl.success) {+ return rateLimited(res, rl, `Limit: ${RATE_LIMIT_MAX} renders per ${RATE_LIMIT_WINDOW_MS / 60000}m`);}const url = new URL(req.url, 'http://x');diff --git a/api/avatars/[id].js b/api/avatars/[id].jsindex c820d6c0f..c9a2531b6 100644--- a/api/avatars/[id].js+++ b/api/avatars/[id].js@@ -14,7 +14,7 @@ import {import { bakeAndUploadAppearance, isBakeable } from '../_lib/bake.js';import { sql } from '../_lib/db.js';import { logAudit } from '../_lib/audit.js';-import { cors, json, method, readJson, wrap, error } from '../_lib/http.js';+import { cors, json, method, readJson, wrap, error, rateLimited } from '../_lib/http.js';import { headObject } from '../_lib/r2.js';import { limits } from '../_lib/rate-limit.js';import { recordEvent } from '../_lib/usage.js';@@ -222,7 +222,7 @@ const VALID_GLB_TYPES = new Set(['model/gltf-binary', 'application/octet-stream'async function handleGlbPatch(res, auth, id, glbUrl) {const rl = await limits.avatarPatch(auth.userId);- if (!rl.success) return error(res, 429, 'rate_limited', 'too many patch requests');+ if (!rl.success) return rateLimited(res, rl, 'too many patch requests');if (!/^u\/[^/]+\/.+\.glb$/.test(glbUrl)) {return error(diff --git a/api/avatars/[id]/[action].js b/api/avatars/[id]/[action].jsindex 377912aff..637074a60 100644--- a/api/avatars/[id]/[action].js+++ b/api/avatars/[id]/[action].js@@ -13,7 +13,7 @@ import {hasScope,} from '../../_lib/auth.js';import { sql } from '../../_lib/db.js';-import { cors, json, method, readJson, wrap, error } from '../../_lib/http.js';+import { cors, json, method, readJson, wrap, error, rateLimited } from '../../_lib/http.js';import { limits, clientIp } from '../../_lib/rate-limit.js';import { parse, isUuid } from '../../_lib/validate.js';import {@@ -84,7 +84,7 @@ async function handleAgentsByAvatar(req, res) {if (!id) return error(res, 400, 'invalid_request', 'id required');const rl = await limits.publicIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);if (String(id).startsWith('avatar_demo_')) {return json(res, 200, { agents: [] });@@ -259,7 +259,7 @@ async function handleRollback(req, res) {const userId = session?.id ?? bearer.userId;const rl = await limits.avatarRollback(userId);- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const { versionId } = parse(rollbackBodySchema, await readJson(req));@@ -311,7 +311,7 @@ async function handleSession(req, res) {if (!auth) return error(res, 401, 'unauthorized', 'sign in required');const rl = await limits.upload(auth.userId);- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests, try again later');+ if (!rl.success) return rateLimited(res, rl, 'too many requests, try again later');// 404 (not 403) when not found or not owned — mirrors [id].js.const avatar = await getAvatar({ id, requesterId: auth.userId });diff --git a/api/avatars/_actions.js b/api/avatars/_actions.jsindex 814adc977..32618be4e 100644--- a/api/avatars/_actions.js+++ b/api/avatars/_actions.js@@ -7,7 +7,7 @@ import { storageKeyFor, enforceQuotas, searchPublicAvatars, stripOwnerFor } fromimport { listAvatars } from '../_lib/avatars.js';import { env } from '../_lib/env.js';import { sql } from '../_lib/db.js';-import { cors, json, method, readJson, wrap, error } from '../_lib/http.js';+import { cors, json, method, readJson, wrap, error, rateLimited } from '../_lib/http.js';import { parse, presignUploadBody, slug as slugSchema, createAvatarBody } from '../_lib/validate.js';import { recordEvent } from '../_lib/usage.js';import { limits, clientIp } from '../_lib/rate-limit.js';@@ -35,7 +35,7 @@ const handlePresign = wrap(async (req, res) => {const userId = await resolvePresignUser(req, 'avatars:write');if (!userId) return error(res, 401, 'unauthorized', 'sign in or provide a valid bearer token');const rl = await limits.upload(userId);- if (!rl.success) return error(res, 429, 'rate_limited', 'upload rate exceeded');+ if (!rl.success) return rateLimited(res, rl, 'upload rate exceeded');const body = parse(presignUploadBody, await readJson(req));try { await enforceQuotas(userId, body.size_bytes); }catch (err) { return error(res, err.status || 402, err.code || 'plan_limit', err.message); }@@ -74,7 +74,7 @@ const handleUpload = wrap(async (req, res) => {if (!userId) return error(res, 401, 'unauthorized', 'sign in or provide a valid bearer token');if (!(await requireCsrf(req, res, userId))) return;const rl = await limits.upload(userId);- if (!rl.success) return error(res, 429, 'rate_limited', 'upload rate exceeded');+ if (!rl.success) return rateLimited(res, rl, 'upload rate exceeded');const url = new URL(req.url, 'http://x');const rawContentType = url.searchParams.get('content_type') || req.headers['content-type'] || 'model/gltf-binary';@@ -347,7 +347,7 @@ const handleRegenerate = wrap(async (req, res) => {const userId = await resolveRegenUser(req);if (!userId) return error(res, 401, 'unauthorized', 'sign in or provide a valid bearer token');const rl = await limits.upload(userId);- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const body = parse(regenerateSchema, await readJson(req));const rows = await sql`select id, name, storage_key from avatars where id = ${body.sourceAvatarId} and owner_id = ${userId} and deleted_at is null limit 1`;if (!rows[0]) return error(res, 404, 'not_found', 'source avatar not found or not owned');@@ -828,7 +828,7 @@ const handleReconstruct = wrap(async (req, res) => {const userId = await resolveRegenUser(req);if (!userId) return error(res, 401, 'unauthorized', 'sign in or provide a valid bearer token');const rl = await limits.upload(userId);- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const body = parse(reconstructSchema, await readJson(req));let provider;diff --git a/api/avatars/thumbnail.js b/api/avatars/thumbnail.jsindex a5d16f9b9..57688ee41 100644--- a/api/avatars/thumbnail.js+++ b/api/avatars/thumbnail.js@@ -9,7 +9,7 @@import { sql } from '../_lib/db.js';import { getSessionUser, authenticateBearer, extractBearer, hasScope } from '../_lib/auth.js';import { putObject, deleteObject, publicUrl } from '../_lib/r2.js';-import { cors, error, json, method, readJson, wrap } from '../_lib/http.js';+import { cors, error, json, method, readJson, wrap, rateLimited } from '../_lib/http.js';import { limits, clientIp } from '../_lib/rate-limit.js';const MAX_PNG_BYTES = 1_500_000; // 1.5 MB max — generous for 1024² posters.@@ -23,7 +23,7 @@ export default wrap(async (req, res) => {if (!auth) return error(res, 401, 'unauthorized', 'sign in or provide a valid bearer token');const rl = await limits.upload(auth.userId);- if (!rl.success) return error(res, 429, 'rate_limited', 'thumbnail upload rate exceeded');+ if (!rl.success) return rateLimited(res, rl, 'thumbnail upload rate exceeded');const body = await readJson(req).catch(() => null);const avatarId = body?.avatar_id;diff --git a/api/billing/payout-wallets/[id].js b/api/billing/payout-wallets/[id].jsindex ac7e7cccf..515335a1f 100644--- a/api/billing/payout-wallets/[id].js+++ b/api/billing/payout-wallets/[id].js@@ -1,6 +1,6 @@import { sql } from '../../_lib/db.js';import { getSessionUser } from '../../_lib/auth.js';-import { cors, json, method, wrap, error } from '../../_lib/http.js';+import { cors, json, method, wrap, error, rateLimited } from '../../_lib/http.js';import { limits, clientIp } from '../../_lib/rate-limit.js';export default wrap(async (req, res) => {@@ -11,7 +11,7 @@ export default wrap(async (req, res) => {if (!user) return error(res, 401, 'unauthorized', 'sign in required');const rl = await limits.authIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const { id } = req.query;const [deleted] = await sql`diff --git a/api/billing/payout-wallets/index.js b/api/billing/payout-wallets/index.jsindex 947f84322..165375ee5 100644--- a/api/billing/payout-wallets/index.js+++ b/api/billing/payout-wallets/index.js@@ -1,6 +1,6 @@import { sql } from '../../_lib/db.js';import { getSessionUser } from '../../_lib/auth.js';-import { cors, json, method, wrap, error, readJson } from '../../_lib/http.js';+import { cors, json, method, wrap, error, readJson, rateLimited } from '../../_lib/http.js';import { parse, isValidSolanaAddress, isValidEvmAddress } from '../../_lib/validate.js';import { limits, clientIp } from '../../_lib/rate-limit.js';import { requireCsrf } from '../../_lib/csrf.js';@@ -21,7 +21,7 @@ export default wrap(async (req, res) => {if (!user) return error(res, 401, 'unauthorized', 'sign in required');const rl = await limits.authIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);if (req.method === 'GET') {const wallets = await sql`diff --git a/api/billing/receipts.js b/api/billing/receipts.jsindex c5309617f..82cbd46f4 100644--- a/api/billing/receipts.js+++ b/api/billing/receipts.js@@ -5,7 +5,7 @@import { sql } from '../_lib/db.js';import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';-import { cors, error, json, method, wrap } from '../_lib/http.js';+import { cors, error, json, method, wrap, rateLimited } from '../_lib/http.js';import { clientIp, limits } from '../_lib/rate-limit.js';export default wrap(async (req, res) => {@@ -18,7 +18,7 @@ export default wrap(async (req, res) => {if (!userId) return error(res, 401, 'unauthorized', 'sign in required');const rl = await limits.widgetRead(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const params = new URL(req.url, 'http://x').searchParams;const purchaseId = params.get('purchase_id');diff --git a/api/billing/withdrawals/[id].js b/api/billing/withdrawals/[id].jsindex 1e3c5d1f9..23045241b 100644--- a/api/billing/withdrawals/[id].js+++ b/api/billing/withdrawals/[id].js@@ -2,7 +2,7 @@import { sql } from '../../_lib/db.js';import { getSessionUser } from '../../_lib/auth.js';-import { cors, json, method, wrap, error } from '../../_lib/http.js';+import { cors, json, method, wrap, error, rateLimited } from '../../_lib/http.js';import { limits, clientIp } from '../../_lib/rate-limit.js';export default wrap(async (req, res) => {@@ -13,7 +13,7 @@ export default wrap(async (req, res) => {if (!user) return error(res, 401, 'unauthorized', 'sign in required');const rl = await limits.authIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const id = req.query?.id;diff --git a/api/billing/withdrawals/index.js b/api/billing/withdrawals/index.jsindex 1aa8907df..96575e99b 100644--- a/api/billing/withdrawals/index.js+++ b/api/billing/withdrawals/index.js@@ -4,7 +4,7 @@import { z } from 'zod';import { sql } from '../../_lib/db.js';import { getSessionUser } from '../../_lib/auth.js';-import { cors, json, method, wrap, error, readJson } from '../../_lib/http.js';+import { cors, json, method, wrap, error, readJson, rateLimited } from '../../_lib/http.js';import { parse } from '../../_lib/validate.js';import { limits, clientIp } from '../../_lib/rate-limit.js';import { requireCsrf } from '../../_lib/csrf.js';@@ -25,7 +25,7 @@ export default wrap(async (req, res) => {if (!user) return error(res, 401, 'unauthorized', 'sign in required');const rl = await limits.authIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);if (req.method === 'GET') {const params = new URL(req.url, 'http://x').searchParams;@@ -74,7 +74,7 @@ export default wrap(async (req, res) => {if (!csrfOk) return;const rlUser = await limits.withdrawalPerUser(user.id);- if (!rlUser.success) return error(res, 429, 'rate_limited', 'too many withdrawal requests');+ if (!rlUser.success) return rateLimited(res, rlUser, 'too many withdrawal requests');const body = parse(postBody, await readJson(req));const { amount, currency_mint, chain, to_address, agent_id = null } = body;diff --git a/api/bounties/[id]/judge.js b/api/bounties/[id]/judge.jsindex 12232ef45..1daf63bb1 100644--- a/api/bounties/[id]/judge.js+++ b/api/bounties/[id]/judge.js@@ -11,7 +11,7 @@// caps worst-case spend.import { sql } from '../../_lib/db.js';-import { cors, json, error, wrap, method } from '../../_lib/http.js';+import { cors, json, error, wrap, method, rateLimited } from '../../_lib/http.js';import { getSessionUser } from '../../_lib/auth.js';import { isUuid } from '../../_lib/validate.js';import { llmComplete, LlmUnavailableError } from '../../_lib/llm.js';@@ -35,7 +35,7 @@ export default wrap(async (req, res) => {const rl = await limits.bountyJudge(user.id);if (!rl.success)- return error(res, 429, 'rate_limited', 'AI judge limit reached — try again later');+ return rateLimited(res, rl, 'AI judge limit reached — try again later');const [bounty] = await sql`SELECT id, user_id, title, description, statusdiff --git a/api/characters.js b/api/characters.jsindex f37ff7e7f..1419b0e95 100644--- a/api/characters.js+++ b/api/characters.js@@ -9,7 +9,7 @@*/import { sql } from './_lib/db.js';-import { cors, json, method, wrap, error } from './_lib/http.js';+import { cors, json, method, wrap, error, rateLimited } from './_lib/http.js';import { limits, clientIp } from './_lib/rate-limit.js';import { publicUrl } from './_lib/r2.js';@@ -18,7 +18,7 @@ export default wrap(async (req, res) => {if (!method(req, res, ['GET'])) return;const rl = await limits.publicIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const url = new URL(req.url, 'http://x');const limit = Math.min(Math.max(parseInt(url.searchParams.get('limit') || '24', 10), 1), 60);diff --git a/api/chat-plugin/[tool].js b/api/chat-plugin/[tool].jsindex 6a9cb3ba2..16d24eed4 100644--- a/api/chat-plugin/[tool].js+++ b/api/chat-plugin/[tool].js@@ -11,7 +11,7 @@// speak → /api/chat-plugin/speak// gesture → /api/chat-plugin/gesture// emote → /api/chat-plugin/emote-import { cors, error, json, method, readJson, wrap } from '../_lib/http.js';+import { cors, error, json, method, readJson, wrap, rateLimited } from '../_lib/http.js';import { clientIp, limits } from '../_lib/rate-limit.js';const GESTURES = ['wave', 'nod', 'point', 'shrug'];@@ -51,7 +51,7 @@ export default wrap(async (req, res) => {if (!method(req, res, ['POST'])) return;const rl = await limits.widgetRead(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const tool = String(req.query?.tool || '').toLowerCase();const args = readArgs(await readJson(req, 64_000));diff --git a/api/chat.js b/api/chat.jsindex 63c543fae..79f839085 100644--- a/api/chat.js+++ b/api/chat.js@@ -21,7 +21,7 @@// OpenAI stream reader handles them verbatim.import { getSessionUser, authenticateBearer, extractBearer } from './_lib/auth.js';-import { cors, json, method, readJson, wrap, error } from './_lib/http.js';+import { cors, json, method, readJson, wrap, error, rateLimited } from './_lib/http.js';import { parse } from './_lib/validate.js';import { recordEvent } from './_lib/usage.js';import { captureException } from './_lib/sentry.js';@@ -324,7 +324,7 @@ export default wrap(async (req, res) => {const ip = clientIp(req);const rl = await limits.chatIp(ip);if (!rl.success) {- return error(res, 429, 'rate_limited', 'too many anonymous chat requests, try again shortly');+ return rateLimited(res, rl, 'too many anonymous chat requests, try again shortly');}const hasOpenRouter = !!process.env.OPENROUTER_API_KEY;const hasGroq = !!process.env.GROQ_API_KEY;diff --git a/api/chat/proxy.js b/api/chat/proxy.jsindex 03b663402..6851c1c00 100644--- a/api/chat/proxy.js+++ b/api/chat/proxy.js@@ -1,5 +1,5 @@import { env } from '../_lib/env.js';-import { cors, error, json, method, wrap, readJson } from '../_lib/http.js';+import { cors, error, json, method, wrap, readJson, rateLimited } from '../_lib/http.js';import { limits, clientIp } from '../_lib/rate-limit.js';const UPGRADE_URL = `${env.APP_ORIGIN}/pricing`;@@ -18,7 +18,7 @@ export default wrap(async (req, res) => {const rl = await limits.chatIp(ip);if (!rl.success) {res.setHeader('retry-after', '60');- return error(res, 429, 'rate_limited', 'too many requests');+ return rateLimited(res, rl);}let body;diff --git a/api/community/auth/url.js b/api/community/auth/url.jsindex 46861d048..1cf803f71 100644--- a/api/community/auth/url.js+++ b/api/community/auth/url.js@@ -3,7 +3,7 @@// CoinCommunities. The redirect lands on our same-origin callback, which// completes the exchange and sets the session cookie. The redirect URL must be// whitelisted in the CoinCommunities dashboard.-import { cors, error, json, method, wrap } from '../../_lib/http.js';+import { cors, error, json, method, wrap, rateLimited } from '../../_lib/http.js';import { clientIp, limits } from '../../_lib/rate-limit.js';import { env } from '../../_lib/env.js';import { cc, UnconfiguredError } from '../../_lib/coin-communities.js';@@ -13,7 +13,7 @@ export default wrap(async (req, res) => {if (!method(req, res, ['GET'])) return;const rl = await limits.publicIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);let api;try {diff --git a/api/community/holder-pass.js b/api/community/holder-pass.jsindex 41a42c0ba..d86a6a0cb 100644--- a/api/community/holder-pass.js+++ b/api/community/holder-pass.js@@ -17,7 +17,7 @@// Auth/wallet problems are real errors the gate UI routes on:// 401 auth_required — not signed in to CoinCommunities// 403 wallet_required — signed in but no linked Solana wallet-import { cors, error, json, method, wrap } from '../_lib/http.js';+import { cors, error, json, method, wrap, rateLimited } from '../_lib/http.js';import { clientIp, limits } from '../_lib/rate-limit.js';import { cc, userAuthHeaders, isValidToken, UnconfiguredError } from '../_lib/coin-communities.js';import { getBalances, solanaMintUsdPrice } from '../_lib/balances.js';@@ -37,7 +37,7 @@ export default wrap(async (req, res) => {res.setHeader('cache-control', 'no-store');const rl = await limits.authIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const token = new URL(req.url, 'http://x').searchParams.get('token');if (!isValidToken(token)) {diff --git a/api/community/messages.js b/api/community/messages.jsindex d4940201e..301a0ec74 100644--- a/api/community/messages.js+++ b/api/community/messages.js@@ -8,7 +8,7 @@// Neither available → 403 posting_locked, which the composer renders// as its designed locked state rather than a broken submit.import { z } from 'zod';-import { cors, error, json, method, readJson, wrap } from '../_lib/http.js';+import { cors, error, json, method, readJson, wrap, rateLimited } from '../_lib/http.js';import { clientIp, limits } from '../_lib/rate-limit.js';import {cc,@@ -43,7 +43,7 @@ function getApi(res) {async function handleGet(req, res, token) {const rl = await limits.publicIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const api = getApi(res);if (!api) return;@@ -67,7 +67,7 @@ async function handleGet(req, res, token) {async function handlePost(req, res, token) {const rl = await limits.authIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const userHeaders = userAuthHeaders(req);if (!userHeaders && !canPostServer()) {diff --git a/api/community/wallet/challenge.js b/api/community/wallet/challenge.jsindex 3d5662580..d3de5ea56 100644--- a/api/community/wallet/challenge.js+++ b/api/community/wallet/challenge.js@@ -2,7 +2,7 @@// Requests a sign-in challenge to link a Solana wallet (chainType 'svm') to the// signed-in CoinCommunities user. Returns the message the wallet must sign.import { z } from 'zod';-import { cors, error, json, method, readJson, wrap } from '../../_lib/http.js';+import { cors, error, json, method, readJson, wrap, rateLimited } from '../../_lib/http.js';import { clientIp, limits } from '../../_lib/rate-limit.js';import { cc, userAuthHeaders, UnconfiguredError } from '../../_lib/coin-communities.js';@@ -13,7 +13,7 @@ export default wrap(async (req, res) => {if (!method(req, res, ['POST'])) return;const rl = await limits.authIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const headers = userAuthHeaders(req);if (!headers) return error(res, 401, 'unauthorized', 'sign in with X first');diff --git a/api/community/wallet/link.js b/api/community/wallet/link.jsindex 4c4016aa3..229991be4 100644--- a/api/community/wallet/link.js+++ b/api/community/wallet/link.js@@ -3,7 +3,7 @@// signature over the message from /wallet/challenge. Lets the user post from// that wallet (subject to the community's token-balance gate).import { z } from 'zod';-import { cors, error, json, method, readJson, wrap } from '../../_lib/http.js';+import { cors, error, json, method, readJson, wrap, rateLimited } from '../../_lib/http.js';import { clientIp, limits } from '../../_lib/rate-limit.js';import { cc, userAuthHeaders, UnconfiguredError } from '../../_lib/coin-communities.js';@@ -17,7 +17,7 @@ export default wrap(async (req, res) => {if (!method(req, res, ['POST'])) return;const rl = await limits.authIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const headers = userAuthHeaders(req);if (!headers) return error(res, 401, 'unauthorized', 'sign in with X first');diff --git a/api/community/wallet/unlink.js b/api/community/wallet/unlink.jsindex 3de4a5242..7853e1317 100644--- a/api/community/wallet/unlink.js+++ b/api/community/wallet/unlink.js@@ -4,7 +4,7 @@// and they need to switch to the one that does. Idempotent: succeeds (unlinked:0)// when nothing is linked, so the gate's "use a different wallet" path is safe to// call from any state.-import { cors, error, json, method, wrap } from '../../_lib/http.js';+import { cors, error, json, method, wrap, rateLimited } from '../../_lib/http.js';import { clientIp, limits } from '../../_lib/rate-limit.js';import { cc, userAuthHeaders, UnconfiguredError } from '../../_lib/coin-communities.js';@@ -13,7 +13,7 @@ export default wrap(async (req, res) => {if (!method(req, res, ['POST'])) return;const rl = await limits.authIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const headers = userAuthHeaders(req);if (!headers) return error(res, 401, 'unauthorized', 'sign in with X first');diff --git a/api/community/world-gate.js b/api/community/world-gate.jsindex 22ca9c1c8..cc6cf725b 100644--- a/api/community/world-gate.js+++ b/api/community/world-gate.js@@ -16,7 +16,7 @@// 401 auth_required — POST without a CoinCommunities session// 403 not_creator — signed in, but not this coin's creator// 403 wallet_required — signed in, but no linked Solana wallet to match-import { cors, error, json, method, readJson, wrap } from '../_lib/http.js';+import { cors, error, json, method, readJson, wrap, rateLimited } from '../_lib/http.js';import { clientIp, limits } from '../_lib/rate-limit.js';import { cc, userAuthHeaders, isValidToken, UnconfiguredError } from '../_lib/coin-communities.js';import { readWorldGate, writeWorldGate, normalizeMinTokens } from '../_lib/world-gate.js';@@ -59,7 +59,7 @@ export default wrap(async (req, res) => {res.setHeader('cache-control', 'no-store');const rl = await limits.authIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const mint = new URL(req.url, 'http://x').searchParams.get('token');if (!isValidToken(mint)) {diff --git a/api/community/worlds.js b/api/community/worlds.jsindex ec5a5e375..f68272767 100644--- a/api/community/worlds.js+++ b/api/community/worlds.js@@ -1,7 +1,7 @@// GET /api/community/worlds// The lobby of live coin-worlds. Each TopCommunity becomes an enterable 3D// world on /walk?coin=<token>. Real data — most active communities first.-import { cors, error, json, method, wrap } from '../_lib/http.js';+import { cors, error, json, method, wrap, rateLimited } from '../_lib/http.js';import { clientIp, limits } from '../_lib/rate-limit.js';import { cc, toWorldCard, UnconfiguredError } from '../_lib/coin-communities.js';@@ -10,7 +10,7 @@ export default wrap(async (req, res) => {if (!method(req, res, ['GET'])) return;const rl = await limits.publicIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);let api;try {diff --git a/api/community/ws-ticket.js b/api/community/ws-ticket.jsindex d46e2b332..56ccb5306 100644--- a/api/community/ws-ticket.js+++ b/api/community/ws-ticket.js@@ -3,7 +3,7 @@// then opens the realtime socket to CoinCommunities directly with this ticket// (the API key never leaves the server). Returns the CC origin too so the// client knows where to connect.-import { cors, error, json, method, wrap } from '../_lib/http.js';+import { cors, error, json, method, wrap, rateLimited } from '../_lib/http.js';import { clientIp, limits } from '../_lib/rate-limit.js';import { cc, ccBaseUrl, isValidToken, UnconfiguredError } from '../_lib/coin-communities.js';@@ -12,7 +12,7 @@ export default wrap(async (req, res) => {if (!method(req, res, ['POST'])) return;const rl = await limits.publicIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const token = new URL(req.url, 'http://x').searchParams.get('token');if (!isValidToken(token)) {diff --git a/api/cosmetics/catalog.js b/api/cosmetics/catalog.jsindex 8450787da..e5d846fc3 100644--- a/api/cosmetics/catalog.js+++ b/api/cosmetics/catalog.js@@ -13,7 +13,7 @@* this account has purchased read as owned.*/-import { cors, json, method, wrap, error } from '../_lib/http.js';+import { cors, json, method, wrap, error, rateLimited } from '../_lib/http.js';import { limits, clientIp } from '../_lib/rate-limit.js';import { buildCatalog, RARITIES } from '../_lib/cosmetics.js';import { readOwnedCosmetics, normalizeAccountId } from '../_lib/cosmetics-ownership.js';@@ -23,7 +23,7 @@ export default wrap(async (req, res) => {if (!method(req, res, ['GET'])) return;const rl = await limits.publicIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const url = new URL(req.url, 'http://x');const rarity = url.searchParams.get('rarity');diff --git a/api/cosmetics/earnings.js b/api/cosmetics/earnings.jsindex c8304c1f4..45fb98eb3 100644--- a/api/cosmetics/earnings.js+++ b/api/cosmetics/earnings.js@@ -6,7 +6,7 @@// earnings view in the dashboard. Public read keyed on the wallet (the numbers are// derived from public on-chain settlements); no secrets are exposed.-import { cors, json, method, wrap, error } from '../_lib/http.js';+import { cors, json, method, wrap, error, rateLimited } from '../_lib/http.js';import { limits, clientIp } from '../_lib/rate-limit.js';import { creatorEarnings, isWallet } from '../_lib/cosmetics-economy.js';@@ -15,7 +15,7 @@ export default wrap(async (req, res) => {if (!method(req, res, ['GET'])) return;const rl = await limits.publicIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const url = new URL(req.url, 'http://x');const creator = String(url.searchParams.get('creator') || '').trim();diff --git a/api/cosmetics/leaderboard.js b/api/cosmetics/leaderboard.jsindex b15370396..1309ea595 100644--- a/api/cosmetics/leaderboard.js+++ b/api/cosmetics/leaderboard.js@@ -6,7 +6,7 @@// number is read straight from the settled-sale ledger — nothing simulated. Public// + briefly cached so the /play flex panel and any embed can poll it cheaply.-import { cors, json, method, wrap, error } from '../_lib/http.js';+import { cors, json, method, wrap, error, rateLimited } from '../_lib/http.js';import { limits, clientIp } from '../_lib/rate-limit.js';import { cosmeticsLeaderboard } from '../_lib/cosmetics-economy.js';@@ -15,7 +15,7 @@ export default wrap(async (req, res) => {if (!method(req, res, ['GET'])) return;const rl = await limits.publicIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const url = new URL(req.url, 'http://x');const limit = Math.max(1, Math.min(50, Number(url.searchParams.get('limit')) || 12));diff --git a/api/cosmetics/owned.js b/api/cosmetics/owned.jsindex 7391d1061..a1868b0f1 100644--- a/api/cosmetics/owned.js+++ b/api/cosmetics/owned.js@@ -12,7 +12,7 @@* account (required) — a Solana wallet address or a guest id (g_…).*/-import { cors, json, method, wrap, error } from '../_lib/http.js';+import { cors, json, method, wrap, error, rateLimited } from '../_lib/http.js';import { limits, clientIp } from '../_lib/rate-limit.js';import { getCosmetic, priceOf, priceUsdcAtomicsOf, priceUsdcDisplayOf } from '../_lib/cosmetics.js';import { readOwnedCosmetics, normalizeAccountId } from '../_lib/cosmetics-ownership.js';@@ -22,7 +22,7 @@ export default wrap(async (req, res) => {if (!method(req, res, ['GET'])) return;const rl = await limits.publicIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const url = new URL(req.url, 'http://x');const account = normalizeAccountId(url.searchParams.get('account'));diff --git a/api/cosmetics/split.js b/api/cosmetics/split.jsindex 1d8bca218..0555100da 100644--- a/api/cosmetics/split.js+++ b/api/cosmetics/split.js@@ -13,7 +13,7 @@// from launch records / on-chain — only HOW MUCH of each sale they take, up to the// cap. So a config write can't redirect another coin's revenue.-import { cors, json, method, wrap, error, readJson } from '../_lib/http.js';+import { cors, json, method, wrap, error, readJson, rateLimited } from '../_lib/http.js';import { limits, clientIp } from '../_lib/rate-limit.js';import { getSplitConfig, setSplitConfig, splitConfigMessage, isMint, MAX_CREATOR_BPS } from '../_lib/cosmetics-economy.js';@@ -23,7 +23,7 @@ export default wrap(async (req, res) => {if (req.method === 'GET') {if (!method(req, res, ['GET'])) return;const rl = await limits.publicIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const url = new URL(req.url, 'http://x');const mint = String(url.searchParams.get('mint') || '').trim();@@ -47,7 +47,7 @@ export default wrap(async (req, res) => {if (!method(req, res, ['POST'])) return;const rl = await limits.authIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests — slow down');+ if (!rl.success) return rateLimited(res, rl, 'too many requests — slow down');let body;try { body = await readJson(req); } catch { return error(res, 400, 'bad_json', 'invalid request body'); }diff --git a/api/creators/[id].js b/api/creators/[id].jsindex de95df4e9..9e3ff6e90 100644--- a/api/creators/[id].js+++ b/api/creators/[id].js@@ -10,7 +10,7 @@*/import { sql } from '../_lib/db.js';-import { cors, error, json, method, wrap } from '../_lib/http.js';+import { cors, error, json, method, wrap, rateLimited } from '../_lib/http.js';import { publicUrl } from '../_lib/r2.js';import { clientIp, limits } from '../_lib/rate-limit.js';@@ -24,7 +24,7 @@ export default wrap(async (req, res) => {if (!UUID_RE.test(id)) return error(res, 404, 'not_found', 'creator not found');const rl = await limits.publicIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const [user] = await sql`SELECT id, display_name, username, avatar_url, created_atdiff --git a/api/crews/[tag].js b/api/crews/[tag].jsindex 342173290..be0e01e30 100644--- a/api/crews/[tag].js+++ b/api/crews/[tag].js@@ -4,7 +4,7 @@// landing surface. Auth-optional — a crew roster is public, like the agent// gallery, but never leaks private member state (handled in crews-store).-import { cors, error, json, method, wrap } from '../_lib/http.js';+import { cors, error, json, method, wrap, rateLimited } from '../_lib/http.js';import { clientIp, limits } from '../_lib/rate-limit.js';import { readPresence } from '../_lib/presence-store.js';import { getCrewByTag, normalizeTag } from '../_lib/crews-store.js';@@ -14,7 +14,7 @@ export default wrap(async (req, res) => {if (!method(req, res, ['GET'])) return;const rl = await limits.publicIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const url = new URL(req.url, 'http://x');const raw = url.searchParams.get('tag') || url.pathname.split('/').pop() || '';diff --git a/api/crews/index.js b/api/crews/index.jsindex 5059d592b..1540e5857 100644--- a/api/crews/index.js+++ b/api/crews/index.js@@ -13,7 +13,7 @@// guards self-invite, duplicates, one-crew-per-account, and ownership. Rate-// limited per account. Mirrors api/friends/index.js.-import { cors, error, json, method, readJson, wrap } from '../_lib/http.js';+import { cors, error, json, method, readJson, wrap, rateLimited } from '../_lib/http.js';import { clientIp, limits } from '../_lib/rate-limit.js';import { resolveAccount } from '../_lib/account-auth.js';import { readPresence, notifyMultiplayer } from '../_lib/presence-store.js';@@ -45,13 +45,13 @@ export default wrap(async (req, res) => {if (req.method === 'GET') {const rl = await limits.publicIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);return json(res, 200, { data: await crewWithPresence(me) });}// POST — a crew mutation. 40 actions/min per account (shared chat limiter).const rl = await limits.chatUser(me);- if (!rl.success) return error(res, 429, 'rate_limited', 'slow down');+ if (!rl.success) return rateLimited(res, rl, 'slow down');const body = await readJson(req).catch(() => ({}));const action = String(body.action || '');diff --git a/api/cz/claim.js b/api/cz/claim.jsindex 9564a52ae..2f8774b5e 100644--- a/api/cz/claim.js+++ b/api/cz/claim.js@@ -14,7 +14,7 @@import { randomBytes } from 'crypto';import { verifyMessage, Interface } from 'ethers';import { sql } from '../_lib/db.js';-import { cors, json, error, wrap, readJson } from '../_lib/http.js';+import { cors, json, error, wrap, readJson, rateLimited } from '../_lib/http.js';import { clientIp } from '../_lib/rate-limit.js';import { env } from '../_lib/env.js';@@ -36,10 +36,10 @@ function checkRate(ip) {const now = Date.now();const window = 60 * 60 * 1000;const kept = (_buckets.get(ip) || []).filter((t) => t > now - window);- if (kept.length >= 5) return false;+ if (kept.length >= 5) return { success: false, limit: 5, remaining: 0, reset: kept[0] + window };kept.push(now);_buckets.set(ip, kept);- return true;+ return { success: true, limit: 5, remaining: 5 - kept.length, reset: now + window };}function claimMessage(nonce) {@@ -62,8 +62,9 @@ export default wrap(async (req, res) => {'address must be a 0x-prefixed Ethereum address',);- if (!checkRate(ip))- return error(res, 429, 'rate_limited', 'too many requests — try again in an hour');+ const rl = checkRate(ip);+ if (!rl.success)+ return rateLimited(res, rl, 'too many requests — try again in an hour');const nonce = randomBytes(16).toString('hex');await sql`@@ -93,8 +94,9 @@ export default wrap(async (req, res) => {if (!/^0x[0-9a-fA-F]{40}$/.test(signerAddress))return error(res, 400, 'validation_error', 'invalid signerAddress format');- if (!checkRate(ip))- return error(res, 429, 'rate_limited', 'too many requests — try again in an hour');+ const rl = checkRate(ip);+ if (!rl.success)+ return rateLimited(res, rl, 'too many requests — try again in an hour');const rows = await sql`select id, address, status from cz_claims where nonce = ${nonce} limit 1diff --git a/api/dashboard/prefs.js b/api/dashboard/prefs.jsindex 6a922a735..8b26ff39c 100644--- a/api/dashboard/prefs.js+++ b/api/dashboard/prefs.js@@ -12,7 +12,7 @@import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';import { sql } from '../_lib/db.js';-import { cors, json, method, readJson, wrap, error } from '../_lib/http.js';+import { cors, json, method, readJson, wrap, error, rateLimited } from '../_lib/http.js';import { limits } from '../_lib/rate-limit.js';import { parse } from '../_lib/validate.js';import { z } from 'zod';@@ -41,7 +41,7 @@ export default wrap(async (req, res) => {}const rl = await limits.prefsWrite(auth.userId);- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const { prefs: incoming } = parse(prefsBody, await readJson(req));diff --git a/api/dca-strategies.js b/api/dca-strategies.jsindex 2207ad04b..db8cc9322 100644--- a/api/dca-strategies.js+++ b/api/dca-strategies.js@@ -4,7 +4,7 @@import { z } from 'zod';import { sql } from './_lib/db.js';import { getSessionUser } from './_lib/auth.js';-import { cors, json, error, wrap, readJson, method } from './_lib/http.js';+import { cors, json, error, wrap, readJson, method, rateLimited } from './_lib/http.js';import { parse } from './_lib/validate.js';import { limits, clientIp } from './_lib/rate-limit.js';@@ -56,7 +56,7 @@ export default wrap(async (req, res) => {const ip = clientIp(req);const rl = await limits.authIp(ip);- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);// Verify ownership via agent_id → user_id chainconst [row] = await sql`@@ -88,7 +88,7 @@ export default wrap(async (req, res) => {const ip = clientIp(req);const rl = await limits.authIp(ip);- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);// Confirm session user owns this agentconst [agent] = await sql`@@ -128,7 +128,7 @@ export default wrap(async (req, res) => {const ip = clientIp(req);const rl = await limits.authIp(ip);- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);let body;try {diff --git a/api/demo/coin/[action].js b/api/demo/coin/[action].jsindex 604cab116..97fb6b71d 100644--- a/api/demo/coin/[action].js+++ b/api/demo/coin/[action].js@@ -17,7 +17,7 @@// the JSON wire (Number can't safely represent values > 2^53).import { sql } from '../../_lib/db.js';-import { cors, error, json, method, wrap } from '../../_lib/http.js';+import { cors, error, json, method, wrap, rateLimited } from '../../_lib/http.js';import { limits, clientIp } from '../../_lib/rate-limit.js';import { listActiveCoins, loadCoinByMint } from '../../_lib/coin/index.js';@@ -362,12 +362,7 @@ export default wrap(async (req, res) => {// share-bot calling /og also needs.const rl = await limits.publicIp(clientIp(req));if (!rl.success) {- res.setHeader('retry-after', Math.ceil((rl.reset - Date.now()) / 1000));- return error(res, 429, 'rate_limited', 'too many requests', {- limit: rl.limit,- remaining: rl.remaining,- reset: rl.reset,- });+ return rateLimited(res, rl);}const action = req.query?.action;diff --git a/api/embed/resolve.js b/api/embed/resolve.jsindex 4804072f1..b3f83490f 100644--- a/api/embed/resolve.js+++ b/api/embed/resolve.js@@ -14,7 +14,7 @@*/import { sql } from '../_lib/db.js';-import { cors, method, wrap, error } from '../_lib/http.js';+import { cors, method, wrap, error, rateLimited } from '../_lib/http.js';import { limits, clientIp } from '../_lib/rate-limit.js';import { CHAIN_BY_ID } from '../_lib/erc8004-chains.js';import { publicUrl } from '../_lib/r2.js';@@ -28,7 +28,7 @@ export default wrap(async (req, res) => {if (!method(req, res, ['GET'])) return;const rl = await limits.publicIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const url = new URL(req.url, 'http://x');const id = (url.searchParams.get('id') || '').trim();diff --git a/api/erc8004/[action].js b/api/erc8004/[action].jsindex b8167a869..341ff909c 100644--- a/api/erc8004/[action].js+++ b/api/erc8004/[action].js@@ -13,7 +13,7 @@ import { z } from 'zod';import { sql } from '../_lib/db.js';import { getSessionUser } from '../_lib/auth.js';-import { cors, json, method, wrap, error, readJson } from '../_lib/http.js';+import { cors, json, method, wrap, error, readJson, rateLimited } from '../_lib/http.js';import { parse } from '../_lib/validate.js';import { limits, clientIp } from '../_lib/rate-limit.js';import { resolveOnChainAgent, SERVER_CHAIN_META } from '../_lib/onchain.js';@@ -46,7 +46,7 @@ async function handleHydrate(req, res) {const ip = clientIp(req);const rl = await limits.authIp(ip);- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);// Get user's linked wallets.const wallets = await sql`@@ -118,7 +118,7 @@ async function handleImport(req, res) {const ip = clientIp(req);const rl = await limits.authIp(ip);- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const body = parse(importBodySchema, await readJson(req));const chainMeta = SERVER_CHAIN_META[body.chainId];@@ -234,7 +234,7 @@ async function handlePin(req, res) {const ip = clientIp(req);const rl = await limits.authIp(ip);- if (!rl.success) return error(res, 429, 'rate_limited', 'too many uploads');+ if (!rl.success) return rateLimited(res, rl, 'too many uploads');const ct = (req.headers['content-type'] || 'application/octet-stream').split(';')[0].trim();if (!ALLOWED.has(ct))diff --git a/api/erc8004/register-confirm.js b/api/erc8004/register-confirm.jsindex 5bd14072a..c03c83a59 100644--- a/api/erc8004/register-confirm.js+++ b/api/erc8004/register-confirm.js@@ -2,7 +2,7 @@ import { id as keccakId, getAddress } from 'ethers';import { z } from 'zod';import { sql } from '../_lib/db.js';import { getSessionUser, authenticateBearer, extractBearer, hasScope } from '../_lib/auth.js';-import { cors, json, method, wrap, error, readJson } from '../_lib/http.js';+import { cors, json, method, wrap, error, readJson, rateLimited } from '../_lib/http.js';import { parse } from '../_lib/validate.js';import { limits, clientIp } from '../_lib/rate-limit.js';import { CHAIN_BY_ID } from '../_lib/erc8004-chains.js';@@ -26,7 +26,7 @@ export default wrap(async (req, res) => {if (bearer && !hasScope(bearer.scope, 'avatars:write'))return error(res, 403, 'insufficient_scope', 'avatars:write scope required');const rl = await limits.registerIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const body = parse(bodySchema, await readJson(req));const chain = CHAIN_BY_ID[body.chainId];if (!chain) return error(res, 400, 'bad_request', `unsupported chain ${body.chainId}`);diff --git a/api/explore-item.js b/api/explore-item.jsindex 6f8fc63a9..9f48491ca 100644--- a/api/explore-item.js+++ b/api/explore-item.js@@ -7,7 +7,7 @@*/import { sql } from './_lib/db.js';-import { cors, json, method, wrap, error } from './_lib/http.js';+import { cors, json, method, wrap, error, rateLimited } from './_lib/http.js';import { limits, clientIp } from './_lib/rate-limit.js';import { CHAIN_BY_ID, tokenExplorerUrl, addressExplorerUrl } from './_lib/erc8004-chains.js';import { publicUrl } from './_lib/r2.js';@@ -18,7 +18,7 @@ export default wrap(async (req, res) => {if (!method(req, res, ['GET'])) return;const rl = await limits.publicIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const url = new URL(req.url, 'http://x');const kind = url.searchParams.get('kind');diff --git a/api/explore.js b/api/explore.jsindex 619d72b92..508c565e2 100644--- a/api/explore.js+++ b/api/explore.js@@ -25,7 +25,7 @@ function isAutoNamed(name) {}import { sql } from './_lib/db.js';-import { cors, json, method, wrap, error } from './_lib/http.js';+import { cors, json, method, wrap, error, rateLimited } from './_lib/http.js';import { limits, clientIp } from './_lib/rate-limit.js';import { CHAIN_BY_ID, tokenExplorerUrl, addressExplorerUrl } from './_lib/erc8004-chains.js';import { publicUrl } from './_lib/r2.js';@@ -36,7 +36,7 @@ export default wrap(async (req, res) => {if (!method(req, res, ['GET'])) return;const rl = await limits.publicIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const url = new URL(req.url, 'http://x');const only3d = url.searchParams.get('only3d') === '1';diff --git a/api/friends/index.js b/api/friends/index.jsindex 0ab023f46..f8efd404a 100644--- a/api/friends/index.js+++ b/api/friends/index.js@@ -12,7 +12,7 @@// Validates the caller owns the account (session or bearer). Guards self-add,// duplicates, and unknown targets in the store layer; rate-limited per account.-import { cors, error, json, method, readJson, wrap } from '../_lib/http.js';+import { cors, error, json, method, readJson, wrap, rateLimited } from '../_lib/http.js';import { clientIp, limits } from '../_lib/rate-limit.js';import { resolveAccount } from '../_lib/account-auth.js';import { readPresence, notifyMultiplayer } from '../_lib/presence-store.js';@@ -40,13 +40,13 @@ export default wrap(async (req, res) => {if (req.method === 'GET') {const rl = await limits.publicIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);return json(res, 200, { data: await graphWithPresence(me) });}// POST — a graph mutation. Tighter limit: 60 actions/min per account.const rl = await limits.chatUser(me);- if (!rl.success) return error(res, 429, 'rate_limited', 'slow down');+ if (!rl.success) return rateLimited(res, rl, 'slow down');const body = await readJson(req).catch(() => ({}));const action = String(body.action || '');diff --git a/api/friends/messages.js b/api/friends/messages.jsindex 019e1800e..0aa4b4147 100644--- a/api/friends/messages.js+++ b/api/friends/messages.js@@ -8,7 +8,7 @@// them on next login. If the recipient has muted the sender the message is// silently dropped (Task 14). Rate-limited and length-capped like world chat.-import { cors, error, json, method, readJson, wrap } from '../_lib/http.js';+import { cors, error, json, method, readJson, wrap, rateLimited } from '../_lib/http.js';import { clientIp, limits } from '../_lib/rate-limit.js';import { resolveAccount } from '../_lib/account-auth.js';import { notifyMultiplayer } from '../_lib/presence-store.js';@@ -36,7 +36,7 @@ export default wrap(async (req, res) => {if (req.method === 'GET') {const rl = await limits.publicIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const url = new URL(req.url, 'http://x');const other = url.searchParams.get('with');@@ -55,7 +55,7 @@ export default wrap(async (req, res) => {// POST — send a DM.const rl = await limits.dmSend(me);- if (!rl.success) return error(res, 429, 'rate_limited', 'you are sending messages too fast');+ if (!rl.success) return rateLimited(res, rl, 'you are sending messages too fast');const payload = await readJson(req).catch(() => ({}));const to = payload.to;diff --git a/api/friends/presence-ticket.js b/api/friends/presence-ticket.jsindex d89f9cc8e..6c85d1cc9 100644--- a/api/friends/presence-ticket.js+++ b/api/friends/presence-ticket.js@@ -4,7 +4,7 @@// publishes the bearer's presence — so a client can never claim to be online as// another account. The client refreshes the ticket before it expires.-import { cors, error, json, method, wrap } from '../_lib/http.js';+import { cors, error, json, method, wrap, rateLimited } from '../_lib/http.js';import { clientIp, limits } from '../_lib/rate-limit.js';import { resolveAccount } from '../_lib/account-auth.js';import { signPresenceTicket } from '../_lib/presence-store.js';@@ -14,7 +14,7 @@ export default wrap(async (req, res) => {if (!method(req, res, ['GET'])) return;const rl = await limits.authIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const auth = await resolveAccount(req, res);if (!auth) return error(res, 401, 'unauthorized', 'sign in required');diff --git a/api/friends/search.js b/api/friends/search.jsindex 5d7c5f0a2..6cab3b4d9 100644--- a/api/friends/search.js+++ b/api/friends/search.js@@ -3,7 +3,7 @@// annotated with the caller's existing relationship so the UI renders the right// action inline (Add / Pending / Friends).-import { cors, error, json, method, wrap } from '../_lib/http.js';+import { cors, error, json, method, wrap, rateLimited } from '../_lib/http.js';import { clientIp, limits } from '../_lib/rate-limit.js';import { resolveAccount } from '../_lib/account-auth.js';import { searchUsers } from '../_lib/friends-store.js';@@ -13,7 +13,7 @@ export default wrap(async (req, res) => {if (!method(req, res, ['GET'])) return;const rl = await limits.publicIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const auth = await resolveAccount(req, res);if (!auth) return error(res, 401, 'unauthorized', 'sign in required');diff --git a/api/galaxy.js b/api/galaxy.jsindex a689a2065..f66f2201c 100644--- a/api/galaxy.js+++ b/api/galaxy.js@@ -19,7 +19,7 @@*/import { sql } from './_lib/db.js';-import { cors, json, method, readJson, wrap, error } from './_lib/http.js';+import { cors, json, method, readJson, wrap, error, rateLimited } from './_lib/http.js';import { limits, clientIp } from './_lib/rate-limit.js';import { publicUrl } from './_lib/r2.js';import { watsonxConfig, watsonxEmbed, watsonxChatComplete } from './_lib/watsonx.js';@@ -60,7 +60,7 @@ export default wrap(async (req, res) => {if (!method(req, res, ['GET', 'POST'])) return;const rl = await limits.publicIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const cfg = watsonxConfig();if (!cfg.configured) {diff --git a/api/guardian/assess.js b/api/guardian/assess.jsindex afd72f857..25c4b745a 100644--- a/api/guardian/assess.js+++ b/api/guardian/assess.js@@ -21,7 +21,7 @@// `guardian_unconfigured` so the caller renders an honest state instead of a// fabricated verdict. Every score is a real Granite Guardian classifier pass.-import { cors, method, readJson, error, json, wrap } from '../_lib/http.js';+import { cors, method, readJson, error, json, wrap, rateLimited } from '../_lib/http.js';import { limits, clientIp } from '../_lib/rate-limit.js';import { recordEvent } from '../_lib/usage.js';import {@@ -102,13 +102,11 @@ export default wrap(async function handler(req, res) {const ip = clientIp(req);const perIp = await limits.guardianIp(ip);if (!perIp.success) {- return error(res, 429, 'rate_limited', 'too many governance requests — slow down', {- retryAfter: Math.ceil((perIp.reset - Date.now()) / 1000),- });+ return rateLimited(res, perIp, 'too many governance requests — slow down');}const globalLimit = await limits.guardianGlobal();if (!globalLimit.success) {- return error(res, 429, 'rate_limited', 'governance capacity reached — try again shortly');+ return rateLimited(res, globalLimit, 'governance capacity reached — try again shortly');}let body;diff --git a/api/ibm/attest.js b/api/ibm/attest.jsindex 269789d47..b968be492 100644--- a/api/ibm/attest.js+++ b/api/ibm/attest.js@@ -21,7 +21,7 @@// proof fields appear only when those services are reachable.import { createHash } from 'node:crypto';-import { cors, json, method, wrap, error, readJson } from '../_lib/http.js';+import { cors, json, method, wrap, error, readJson, rateLimited } from '../_lib/http.js';import { limits, clientIp } from '../_lib/rate-limit.js';import { watsonxConfig, watsonxChatComplete } from '../_lib/watsonx.js';import { watsonxForecast, forecastModelFor } from '../_lib/watsonx-forecast.js';@@ -329,7 +329,7 @@ export default wrap(async (req, res) => {if (!method(req, res, ['GET', 'POST'])) return;const rl = await limits.publicIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const url = new URL(req.url, 'http://x');const wallet = avatarWalletConfig();diff --git a/api/ibm/galaxy.js b/api/ibm/galaxy.jsindex e9ab9d885..4ece58d5a 100644--- a/api/ibm/galaxy.js+++ b/api/ibm/galaxy.js@@ -16,7 +16,7 @@// happens when agents are added or edited.import { sql } from '../_lib/db.js';-import { cors, method, readJson, error, json, wrap } from '../_lib/http.js';+import { cors, method, readJson, error, json, wrap, rateLimited } from '../_lib/http.js';import { limits, clientIp } from '../_lib/rate-limit.js';import { publicUrl } from '../_lib/r2.js';import { watsonxConfig, watsonxEmbed, watsonxChatComplete } from '../_lib/watsonx.js';@@ -394,7 +394,7 @@ export default wrap(async (req, res) => {if (!method(req, res, ['GET', 'POST'])) return;const rl = await limits.publicIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);if (req.method === 'POST') return handleSearch(req, res);return handleGet(req, res);diff --git a/api/ibm/oracle.js b/api/ibm/oracle.jsindex 1aceb52e0..273aa6441 100644--- a/api/ibm/oracle.js+++ b/api/ibm/oracle.js@@ -8,7 +8,7 @@// Candles come keyless from GeckoTerminal and are ALWAYS returned, so the 3D// chart renders real history even when watsonx is not configured; the forecast,// narration, and governance fields appear only when Granite is reachable.-import { cors, json, method, wrap, error } from '../_lib/http.js';+import { cors, json, method, wrap, error, rateLimited } from '../_lib/http.js';import { limits, clientIp } from '../_lib/rate-limit.js';import { watsonxConfig, watsonxChatComplete } from '../_lib/watsonx.js';import { watsonxForecast, forecastModelFor } from '../_lib/watsonx-forecast.js';@@ -70,7 +70,7 @@ export default wrap(async (req, res) => {if (!method(req, res, ['GET'])) return;const rl = await limits.publicIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const params = new URL(req.url, 'http://x').searchParams;diff --git a/api/ibm/twin.js b/api/ibm/twin.jsindex ee87e181b..c144f0eb6 100644--- a/api/ibm/twin.js+++ b/api/ibm/twin.js@@ -15,7 +15,7 @@// governance appear only when watsonx.ai is reachable. There is no mock path: a// scenario forecast is the real Granite model evaluating a transformed-but-real// input series, clearly labelled as a counterfactual.-import { cors, json, method, wrap, error, readJson } from '../_lib/http.js';+import { cors, json, method, wrap, error, readJson, rateLimited } from '../_lib/http.js';import { limits, clientIp } from '../_lib/rate-limit.js';import { watsonxConfig, watsonxChatComplete } from '../_lib/watsonx.js';import { watsonxForecast, forecastModelFor } from '../_lib/watsonx-forecast.js';@@ -504,7 +504,7 @@ export default wrap(async (req, res) => {if (!method(req, res, ['GET', 'POST'])) return;const rl = await limits.publicIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);if (req.method === 'POST') return handlePost(req, res);return handleGet(req, res);diff --git a/api/ibm/vision.js b/api/ibm/vision.jsindex dada3a2db..d0faf537a 100644--- a/api/ibm/vision.js+++ b/api/ibm/vision.js@@ -19,7 +19,7 @@// unconfigured the endpoint says so (503) instead of inventing a description.import { sql } from '../_lib/db.js';-import { cors, method, readJson, error, json, wrap } from '../_lib/http.js';+import { cors, method, readJson, error, json, wrap, rateLimited } from '../_lib/http.js';import { limits, clientIp } from '../_lib/rate-limit.js';import { publicUrl } from '../_lib/r2.js';import { watsonxConfig, watsonxChatComplete } from '../_lib/watsonx.js';@@ -91,7 +91,7 @@ export default wrap(async (req, res) => {if (!method(req, res, ['GET', 'POST'])) return;const rl = await limits.publicIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);if (req.method === 'GET') return handleSubjects(req, res);return handleVision(req, res);diff --git a/api/keys/[id].js b/api/keys/[id].jsindex 5cadaa93d..aefde28cc 100644--- a/api/keys/[id].js+++ b/api/keys/[id].js@@ -3,7 +3,7 @@import { sql } from '../_lib/db.js';import { getSessionUser } from '../_lib/auth.js';import { logAudit } from '../_lib/audit.js';-import { cors, json, method, wrap, error } from '../_lib/http.js';+import { cors, json, method, wrap, error, rateLimited } from '../_lib/http.js';import { requireCsrf } from '../_lib/csrf.js';import { limits } from '../_lib/rate-limit.js';@@ -17,7 +17,7 @@ export default wrap(async (req, res) => {if (!(await requireCsrf(req, res, user.id))) return;const rl = await limits.apiKeyManage(user.id);- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const id = req.query?.id || new URL(req.url, 'http://x').pathname.split('/').pop();const rows = await sql`diff --git a/api/keys/index.js b/api/keys/index.jsindex 1142f69e7..c870b654b 100644--- a/api/keys/index.js+++ b/api/keys/index.js@@ -5,7 +5,7 @@import { sql } from '../_lib/db.js';import { getSessionUser } from '../_lib/auth.js';import { randomToken, sha256 } from '../_lib/crypto.js';-import { cors, json, method, readJson, wrap, error } from '../_lib/http.js';+import { cors, json, method, readJson, wrap, error, rateLimited } from '../_lib/http.js';import { requireCsrf } from '../_lib/csrf.js';import { limits } from '../_lib/rate-limit.js';import { parse } from '../_lib/validate.js';@@ -32,7 +32,7 @@ export default wrap(async (req, res) => {if (!user) return error(res, 401, 'unauthorized', 'sign in to manage API keys');const rl = await limits.apiKeyManage(user.id);- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);if (req.method === 'GET') {const rows = await sql`diff --git a/api/kol/[action].js b/api/kol/[action].jsindex 8eef0fceb..8ba795062 100644--- a/api/kol/[action].js+++ b/api/kol/[action].js@@ -3,7 +3,7 @@import { readFile, writeFile } from 'node:fs/promises';import path from 'node:path';import { fileURLToPath } from 'node:url';-import { cors, json, method, readJson, wrap, error } from '../_lib/http.js';+import { cors, json, method, readJson, wrap, error, rateLimited } from '../_lib/http.js';import { limits, clientIp } from '../_lib/rate-limit.js';// ── wallets (Birdeye P&L proxy) ───────────────────────────────────────────────@@ -71,7 +71,7 @@ async function handleWallets(req, res) {if (!apiKey) return error(res, 503, 'birdeye_not_configured', 'Birdeye API key not configured');const rl = await limits.mcpIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const url = new URL(req.url, `http://${req.headers.host}`);const addresses = (url.searchParams.get('addresses') ?? '')@@ -122,7 +122,7 @@ async function handleImportGmgn(req, res) {if (cors(req, res, { methods: 'POST,OPTIONS', origins: '*' })) return;if (!method(req, res, ['POST'])) return;const rl = await limits.mcpIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const body = await readJson(req);if (!body || body.rawJson == null)return error(res, 400, 'validation_error', 'body.rawJson is required');@@ -147,7 +147,7 @@ async function handleLeaderboard(req, res) {if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;if (!method(req, res, ['GET'])) return;const rl = await limits.mcpIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const url = new URL(req.url, `http://${req.headers.host}`);const window = url.searchParams.get('window') || '7d';const limitRaw = url.searchParams.get('limit');diff --git a/api/launchpad/publish.js b/api/launchpad/publish.jsindex cbeab4006..eaafe05d5 100644--- a/api/launchpad/publish.js+++ b/api/launchpad/publish.js@@ -22,7 +22,7 @@import { createHash, randomBytes } from 'node:crypto';import { sql } from '../_lib/db.js';import { authenticateBearer, extractBearer, getSessionUser } from '../_lib/auth.js';-import { cors, error, json, method, readJson, wrap } from '../_lib/http.js';+import { cors, error, json, method, readJson, wrap, rateLimited } from '../_lib/http.js';import { clientIp, limits } from '../_lib/rate-limit.js';import { z } from 'zod';@@ -109,7 +109,7 @@ export default wrap(async (req, res) => {if (!method(req, res, ['POST'])) return;const rl = await limits.authIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many publish attempts — try again soon');+ if (!rl.success) return rateLimited(res, rl, 'too many publish attempts — try again soon');const body = await readJson(req).catch(() => null);if (!body) return error(res, 400, 'validation_error', 'request body required');diff --git a/api/llm/anthropic.js b/api/llm/anthropic.jsindex c9731afbe..0844c0787 100644--- a/api/llm/anthropic.js+++ b/api/llm/anthropic.js@@ -13,7 +13,7 @@import { z } from 'zod';import { Redis } from '@upstash/redis';import { env } from '../_lib/env.js';-import { cors, error, method, wrap, readJson, json } from '../_lib/http.js';+import { cors, error, method, wrap, readJson, json, rateLimited } from '../_lib/http.js';import { parse } from '../_lib/validate.js';import { limits, clientIp } from '../_lib/rate-limit.js';import { recordEvent, logger } from '../_lib/usage.js';@@ -242,12 +242,12 @@ export default wrap(async (req, res) => {}const ipRl = await limits.embedLlmIp(clientIp(req));- if (!ipRl.success) return error(res, 429, 'rate_limited', 'too many requests from this IP');+ if (!ipRl.success) return rateLimited(res, ipRl, 'too many requests from this IP');const perMin = policy.brain?.rate_limit_per_min;if (perMin && perMin > 0) {const agentRl = await limits.embedLlmAgent(agentId, perMin);- if (!agentRl.success) return error(res, 429, 'rate_limited', 'agent rate limit exceeded');+ if (!agentRl.success) return rateLimited(res, agentRl, 'agent rate limit exceeded');}const quota = policy.brain?.monthly_quota;diff --git a/api/lobehub/[action].js b/api/lobehub/[action].jsindex b6c09f75a..e2468b9bd 100644--- a/api/lobehub/[action].js+++ b/api/lobehub/[action].js@@ -1,7 +1,7 @@import { readFileSync } from 'node:fs';import { join } from 'node:path';import { sql } from '../_lib/db.js';-import { cors, error, json, method, readJson, wrap } from '../_lib/http.js';+import { cors, error, json, method, readJson, wrap, rateLimited } from '../_lib/http.js';import { clientIp, limits } from '../_lib/rate-limit.js';let pluginManifest;@@ -50,7 +50,7 @@ export default wrap(async (req, res) => {if (!method(req, res, ['POST'])) return;const rl = await limits.widgetRead(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const body = await readJson(req);const agentId = body?.agentId;diff --git a/api/marketplace/[action].js b/api/marketplace/[action].jsindex 7b15b9175..e4d757fd9 100644--- a/api/marketplace/[action].js+++ b/api/marketplace/[action].js@@ -19,7 +19,7 @@import { sql } from '../_lib/db.js';import { authenticateBearer, extractBearer, getSessionUser } from '../_lib/auth.js';-import { cors, error, json, method, readJson, wrap } from '../_lib/http.js';+import { cors, error, json, method, readJson, wrap, rateLimited } from '../_lib/http.js';import { publicUrl } from '../_lib/r2.js';import { clientIp, limits } from '../_lib/rate-limit.js';import { markProviderCooldown } from '../_lib/provider-health.js';@@ -131,7 +131,7 @@ async function handleCategories(req, res) {if (!method(req, res, ['GET'])) return;const rl = await limits.widgetRead(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const rows = await sql`SELECT category, count(*)::int AS count@@ -175,7 +175,7 @@ async function handleTheme(req, res) {if (!method(req, res, ['GET'])) return;const rl = await limits.widgetRead(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const weekNum = Math.floor(Date.now() / (7 * 24 * 3600 * 1000));const cat = THEME_CATEGORIES[weekNum % THEME_CATEGORIES.length];@@ -292,7 +292,7 @@ async function handleCreate(req, res) {if (!auth) return error(res, 401, 'unauthorized', 'sign in required');const rl = await limits.authIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);let body = await readJson(req).catch(() => null);if (!body) return error(res, 400, 'validation_error', 'request body required');@@ -376,7 +376,7 @@ async function handleMine(req, res) {if (!auth) return error(res, 401, 'unauthorized', 'sign in required');const rl = await limits.widgetRead(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const rows = await sql`SELECT ai.id, ai.name, ai.description, ai.category, ai.tags, ai.avatar_id, ai.user_id,@@ -411,7 +411,7 @@ async function handleList(req, res, url) {if (!method(req, res, ['GET'])) return;const rl = await limits.widgetRead(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const category = url.searchParams.get('category') || null;const q = (url.searchParams.get('q') || '').trim().slice(0, 80);@@ -555,7 +555,7 @@ async function handleDetail(req, res, id) {if (!method(req, res, ['GET'])) return;const rl = await limits.widgetRead(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);let row;try {@@ -731,9 +731,9 @@ async function handlePreview(req, res, id) {const ip = clientIp(req);const ipRl = await limits.previewIp(ip);- if (!ipRl.success) return error(res, 429, 'rate_limited', 'too many preview messages — try again later');+ if (!ipRl.success) return rateLimited(res, ipRl, 'too many preview messages — try again later');const agentRl = await limits.previewAgent(id);- if (!agentRl.success) return error(res, 429, 'rate_limited', 'this agent is at capacity right now');+ if (!agentRl.success) return rateLimited(res, agentRl, 'this agent is at capacity right now');const raw = await readJson(req).catch(() => null);if (!raw) return error(res, 400, 'validation_error', 'request body required');@@ -991,7 +991,7 @@ async function handleVersions(req, res, id) {if (!method(req, res, ['GET'])) return;const rl = await limits.widgetRead(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const rows = await sql`SELECT id, version, changelog, category, tags, created_at@@ -1010,7 +1010,7 @@ async function handleSimilar(req, res, id) {if (!method(req, res, ['GET'])) return;const rl = await limits.widgetRead(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const [base] = await sql`SELECT id, name, description, category, tags FROM agent_identities@@ -1051,7 +1051,7 @@ async function handleFork(req, res, id) {if (!auth) return error(res, 401, 'unauthorized', 'sign in required');const rl = await limits.authIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const [src] = await sql`SELECT * FROM agent_identities@@ -1097,7 +1097,7 @@ async function handleBookmark(req, res, id) {if (!auth) return error(res, 401, 'unauthorized', 'sign in required');const rl = await limits.authIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);if (req.method === 'DELETE') {await sql`DELETE FROM agent_bookmarks WHERE user_id = ${auth.userId} AND agent_id = ${id}`;@@ -1122,7 +1122,7 @@ async function handlePublish(req, res, id) {if (!auth) return error(res, 401, 'unauthorized', 'sign in required');const rl = await limits.authIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const body = await readJson(req).catch(() => ({}));diff --git a/api/marketplace/asset-price.js b/api/marketplace/asset-price.jsindex f2d39cbcb..68f47508c 100644--- a/api/marketplace/asset-price.js+++ b/api/marketplace/asset-price.js@@ -15,7 +15,7 @@import { sql } from '../_lib/db.js';import { authenticateBearer, extractBearer, getSessionUser } from '../_lib/auth.js';-import { cors, error, json, method, readJson, wrap } from '../_lib/http.js';+import { cors, error, json, method, readJson, wrap, rateLimited } from '../_lib/http.js';import { clientIp, limits } from '../_lib/rate-limit.js';import { z } from 'zod';@@ -73,7 +73,7 @@ async function handleGet(req, res) {}const rl = await limits.widgetRead(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const [row] = await sql`SELECT ap.amount, ap.currency_mint, ap.chain, ap.mint_decimals, ap.owner_user_id, ap.updated_at,@@ -107,7 +107,7 @@ async function handleSet(req, res) {if (!auth) return error(res, 401, 'unauthorized', 'sign in required');const rl = await limits.authIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const body = await readJson(req).catch(() => null);if (!body) return error(res, 400, 'validation_error', 'request body required');diff --git a/api/marketplace/buy-asset.js b/api/marketplace/buy-asset.jsindex fcb0bdc05..789ea47f2 100644--- a/api/marketplace/buy-asset.js+++ b/api/marketplace/buy-asset.js@@ -22,7 +22,7 @@ import crypto from 'node:crypto';import { sql } from '../_lib/db.js';import { authenticateBearer, extractBearer, getSessionUser } from '../_lib/auth.js';-import { cors, error, json, method, readJson, wrap } from '../_lib/http.js';+import { cors, error, json, method, readJson, wrap, rateLimited } from '../_lib/http.js';import { clientIp, limits } from '../_lib/rate-limit.js';import { requireCsrf } from '../_lib/csrf.js';import { rpcFallbackFromEnv } from '../_lib/solana/rpc-fallback.js';@@ -107,7 +107,7 @@ async function handleCreate(req, res) {if (!(await requireCsrf(req, res, auth.userId))) return;const rl = await limits.authIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const body = await readJson(req).catch(() => null);const itemType = String(body?.item_type || '').trim();@@ -209,7 +209,7 @@ async function handleStatus(req, res, reference) {if (!auth) return error(res, 401, 'unauthorized', 'sign in required');const rl = await limits.widgetRead(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const [row] = await sql`SELECT reference, item_type, item_id, status, tx_signature, confirmed_at,@@ -232,7 +232,7 @@ async function handleConfirm(req, res, reference) {if (!(await requireCsrf(req, res, auth.userId))) return;const rl = await limits.authIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const [pur] = await sql`SELECT id, buyer_user_id, item_type, item_id, seller_user_id, status,diff --git a/api/marketplace/check-skill-access.js b/api/marketplace/check-skill-access.jsindex 687647928..f4a5710e9 100644--- a/api/marketplace/check-skill-access.js+++ b/api/marketplace/check-skill-access.js@@ -5,7 +5,7 @@import { sql } from '../_lib/db.js';import { authenticateBearer, extractBearer, getSessionUser } from '../_lib/auth.js';-import { cors, error, json, method, wrap } from '../_lib/http.js';+import { cors, error, json, method, wrap, rateLimited } from '../_lib/http.js';import { clientIp, limits } from '../_lib/rate-limit.js';export default wrap(async (req, res) => {@@ -18,7 +18,7 @@ export default wrap(async (req, res) => {if (!userId) return error(res, 401, 'unauthorized', 'sign in required');const rl = await limits.widgetRead(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const url = new URL(req.url, 'http://x');const agentId = url.searchParams.get('agent_id');diff --git a/api/marketplace/purchase-as-agent.js b/api/marketplace/purchase-as-agent.jsindex 2538d5a6a..d66c58e1f 100644--- a/api/marketplace/purchase-as-agent.js+++ b/api/marketplace/purchase-as-agent.js@@ -28,7 +28,7 @@ import {import { sql } from '../_lib/db.js';import { authenticateBearer, extractBearer, getSessionUser } from '../_lib/auth.js';-import { cors, error, json, method, readJson, wrap } from '../_lib/http.js';+import { cors, error, json, method, readJson, wrap, rateLimited } from '../_lib/http.js';import { clientIp, limits } from '../_lib/rate-limit.js';import { recoverSolanaAgentKeypair } from '../_lib/agent-wallet.js';import { confirmSkillPurchase, resolvePayoutAddress, logEvent } from '../_lib/purchase-confirm.js';@@ -64,7 +64,7 @@ export default wrap(async (req, res) => {// Per-IP rate limit (coarse gate)const rlIp = await limits.authIp(clientIp(req));- if (!rlIp.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rlIp.success) return rateLimited(res, rlIp);const body = await readJson(req).catch(() => null);const parsed = bodySchema.safeParse(body);@@ -81,7 +81,7 @@ export default wrap(async (req, res) => {const rlAgent = await limits.agentBuy(buyer_agent_id);if (!rlAgent.success) {log('purchase_as_agent.rate_limited', { buyer_agent_id, seller_agent_id, skill });- return error(res, 429, 'rate_limited', 'too many autonomous purchases — try again later');+ return rateLimited(res, rlAgent, 'too many autonomous purchases — try again later');}// Verify caller owns the buyer agentdiff --git a/api/marketplace/purchase.js b/api/marketplace/purchase.jsindex 9af80e204..c0f86ae8b 100644--- a/api/marketplace/purchase.js+++ b/api/marketplace/purchase.js@@ -20,7 +20,7 @@ import { Keypair } from '@solana/web3.js';import { sql } from '../_lib/db.js';import { authenticateBearer, extractBearer, getSessionUser } from '../_lib/auth.js';-import { cors, error, json, method, readJson, wrap } from '../_lib/http.js';+import { cors, error, json, method, readJson, wrap, rateLimited } from '../_lib/http.js';import { clientIp, limits } from '../_lib/rate-limit.js';import { confirmSkillPurchase, logEvent, resolvePayoutAddress } from '../_lib/purchase-confirm.js';import { requireCsrf } from '../_lib/csrf.js';@@ -69,7 +69,7 @@ async function handleCreate(req, res) {if (!(await requireCsrf(req, res, auth.userId))) return;const rl = await limits.authIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const body = await readJson(req).catch(() => null);const agentId = body?.agent_id;@@ -211,7 +211,7 @@ async function handleStatus(req, res, reference) {if (!auth) return error(res, 401, 'unauthorized', 'sign in required');const rl = await limits.widgetRead(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const [row] = await sql`SELECT reference, agent_id, skill, status, tx_signature, confirmed_at,@@ -236,7 +236,7 @@ async function handleConfirm(req, res, reference) {if (!(await requireCsrf(req, res, auth.userId))) return;const rl = await limits.authIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const [pur] = await sql`SELECT sp.id, sp.user_id, sp.agent_id, sp.skill, sp.status,diff --git a/api/marketplace/reviews.js b/api/marketplace/reviews.jsindex 12495a0d5..9572e4cb2 100644--- a/api/marketplace/reviews.js+++ b/api/marketplace/reviews.js@@ -16,7 +16,7 @@ import { z } from 'zod';import { sql } from '../_lib/db.js';import { authenticateBearer, extractBearer, getSessionUser } from '../_lib/auth.js';-import { cors, error, json, method, readJson, wrap } from '../_lib/http.js';+import { cors, error, json, method, readJson, wrap, rateLimited } from '../_lib/http.js';import { clientIp, limits } from '../_lib/rate-limit.js';import { requireCsrf } from '../_lib/csrf.js';@@ -63,7 +63,7 @@ async function handleList(req, res, agentId) {if (!method(req, res, ['GET'])) return;const rl = await limits.widgetRead(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const [agent] = await sql`SELECT id FROM agent_identities WHERE id = ${agentId} AND deleted_at IS NULL@@ -146,7 +146,7 @@ async function handleUpsert(req, res, agentId) {if (!(await requireCsrf(req, res, auth.userId))) return;const rl = await limits.authIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const [agent] = await sql`SELECT id, user_id FROM agent_identities@@ -202,7 +202,7 @@ async function handleDelete(req, res, agentId) {if (!(await requireCsrf(req, res, auth.userId))) return;const rl = await limits.authIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);await sql`DELETE FROM agent_reviews WHERE agent_id = ${agentId} AND user_id = ${auth.userId}`;return json(res, 200, { data: { deleted: true } });diff --git a/api/marketplace/set-skill-price.js b/api/marketplace/set-skill-price.jsindex 7b12c6989..19bd01a8e 100644--- a/api/marketplace/set-skill-price.js+++ b/api/marketplace/set-skill-price.js@@ -6,7 +6,7 @@*/import { sql } from '../_lib/db.js';import { authenticateBearer, extractBearer, getSessionUser } from '../_lib/auth.js';-import { cors, error, json, method, readJson, wrap } from '../_lib/http.js';+import { cors, error, json, method, readJson, wrap, rateLimited } from '../_lib/http.js';import { clientIp, limits } from '../_lib/rate-limit.js';import { z } from 'zod';@@ -34,7 +34,7 @@ export default wrap(async (req, res) => {if (!auth) return error(res, 401, 'unauthorized', 'sign in required');const rl = await limits.authIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const body = await readJson(req).catch(() => null);if (!body) return error(res, 400, 'validation_error', 'request body required');diff --git a/api/marketplace/start-trial.js b/api/marketplace/start-trial.jsindex a21241fdc..104b34bee 100644--- a/api/marketplace/start-trial.js+++ b/api/marketplace/start-trial.js@@ -11,7 +11,7 @@ import { z } from 'zod';import crypto from 'node:crypto';import { sql } from '../_lib/db.js';import { getSessionUser } from '../_lib/auth.js';-import { cors, json, method, wrap, error, readJson } from '../_lib/http.js';+import { cors, json, method, wrap, error, readJson, rateLimited } from '../_lib/http.js';import { parse } from '../_lib/validate.js';import { limits, clientIp } from '../_lib/rate-limit.js';import { requireCsrf } from '../_lib/csrf.js';@@ -32,7 +32,7 @@ export default wrap(async (req, res) => {if (!csrfOk) return;const rl = await limits.authIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const body = parse(bodySchema, await readJson(req));const { agent_id, skill } = body;diff --git a/api/mocap/clips.js b/api/mocap/clips.jsindex 75fc598a5..c6126205e 100644--- a/api/mocap/clips.js+++ b/api/mocap/clips.js@@ -7,7 +7,7 @@import { getSessionUser, authenticateBearer, extractBearer, hasScope } from '../_lib/auth.js';import { sql } from '../_lib/db.js';-import { cors, json, method, readJson, wrap, error } from '../_lib/http.js';+import { cors, json, method, readJson, wrap, error, rateLimited } from '../_lib/http.js';import { limits } from '../_lib/rate-limit.js';import { z } from 'zod';@@ -147,7 +147,7 @@ async function handleList(req, res, auth) {async function handleCreate(req, res, auth) {const rl = await limits.avatarPatch(auth.userId);- if (!rl.success) return error(res, 429, 'rate_limited', 'too many mocap saves');+ if (!rl.success) return rateLimited(res, rl, 'too many mocap saves');const body = await readJson(req);if (!body) return error(res, 400, 'invalid_request', 'body required');diff --git a/api/monetization/prices.js b/api/monetization/prices.jsindex a5ff46468..03fc2a87e 100644--- a/api/monetization/prices.js+++ b/api/monetization/prices.js@@ -8,7 +8,7 @@import { z } from 'zod';import { sql } from '../_lib/db.js';import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';-import { cors, json, method, wrap, error, readJson } from '../_lib/http.js';+import { cors, json, method, wrap, error, readJson, rateLimited } from '../_lib/http.js';import { parse } from '../_lib/validate.js';import { limits, clientIp } from '../_lib/rate-limit.js';import { requireCsrf } from '../_lib/csrf.js';@@ -58,7 +58,7 @@ export default wrap(async (req, res) => {// GET is public for listed agentsif (req.method === 'GET') {const rl = await limits.pricingPerIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const params = new URL(req.url, 'http://x').searchParams;const agentId = params.get('agent_id');@@ -92,7 +92,7 @@ export default wrap(async (req, res) => {if (!(await requireCsrf(req, res, userId))) return;const rl = await limits.authIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);if (req.method === 'PUT') {const body = parse(putBody, await readJson(req));diff --git a/api/monetization/revenue.js b/api/monetization/revenue.jsindex 2b4c1c62a..91f95cd20 100644--- a/api/monetization/revenue.js+++ b/api/monetization/revenue.js@@ -8,7 +8,7 @@import { sql } from '../_lib/db.js';import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';-import { cors, json, method, wrap, error } from '../_lib/http.js';+import { cors, json, method, wrap, error, rateLimited } from '../_lib/http.js';import { limits, clientIp } from '../_lib/rate-limit.js';const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;@@ -37,7 +37,7 @@ export default wrap(async (req, res) => {if (!userId) return error(res, 401, 'unauthorized', 'Sign in required');const rl = await limits.authIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const params = new URL(req.url, 'http://x').searchParams;diff --git a/api/monetization/wallet.js b/api/monetization/wallet.jsindex 09adc8a59..015161e39 100644--- a/api/monetization/wallet.js+++ b/api/monetization/wallet.js@@ -6,7 +6,7 @@import { z } from 'zod';import { sql } from '../_lib/db.js';import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';-import { cors, json, method, wrap, error, readJson } from '../_lib/http.js';+import { cors, json, method, wrap, error, readJson, rateLimited } from '../_lib/http.js';import { parse, isValidSolanaAddress, isValidEvmAddress } from '../_lib/validate.js';import { limits, clientIp } from '../_lib/rate-limit.js';@@ -35,7 +35,7 @@ export default wrap(async (req, res) => {if (!userId) return error(res, 401, 'unauthorized', 'Sign in required');const rl = await limits.authIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);if (req.method === 'GET') {const params = new URL(req.url, 'http://x').searchParams;diff --git a/api/monetization/withdrawals.js b/api/monetization/withdrawals.jsindex fe1633c62..31fbe4c5c 100644--- a/api/monetization/withdrawals.js+++ b/api/monetization/withdrawals.js@@ -7,7 +7,7 @@import { z } from 'zod';import { sql } from '../_lib/db.js';import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';-import { cors, json, method, wrap, error, readJson } from '../_lib/http.js';+import { cors, json, method, wrap, error, readJson, rateLimited } from '../_lib/http.js';import { parse, isValidSolanaAddress, isValidEvmAddress } from '../_lib/validate.js';import { limits, clientIp } from '../_lib/rate-limit.js';import { requireCsrf } from '../_lib/csrf.js';@@ -40,7 +40,7 @@ export default wrap(async (req, res) => {const { userId } = auth;const rl = await limits.authIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);if (req.method === 'GET') {const params = new URL(req.url, 'http://x').searchParams;@@ -122,7 +122,7 @@ export default wrap(async (req, res) => {if (!csrfOk) return;const rlUser = await limits.withdrawalPerUser(userId);- if (!rlUser.success) return error(res, 429, 'rate_limited', 'too many withdrawal requests');+ if (!rlUser.success) return rateLimited(res, rlUser, 'too many withdrawal requests');const body = parse(postBody, await readJson(req));const { agent_id, amount_usdc } = body;diff --git a/api/newsletter-subscribe.js b/api/newsletter-subscribe.jsindex 402c59da5..99bb91e37 100644--- a/api/newsletter-subscribe.js+++ b/api/newsletter-subscribe.js@@ -1,6 +1,6 @@import { Resend } from 'resend';import { z } from 'zod';-import { cors, json, method, wrap, error, readJson } from './_lib/http.js';+import { cors, json, method, wrap, error, readJson, rateLimited } from './_lib/http.js';import { parse } from './_lib/validate.js';import { limits, clientIp } from './_lib/rate-limit.js';import { captureException } from './_lib/sentry.js';@@ -20,7 +20,7 @@ export default wrap(async (req, res) => {if (!method(req, res, ['POST'])) return;const rl = await limits.newsletterIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const { email } = parse(bodySchema, await readJson(req));diff --git a/api/nft/mint-scene-confirm.js b/api/nft/mint-scene-confirm.jsindex 856ca1adf..7944e1247 100644--- a/api/nft/mint-scene-confirm.js+++ b/api/nft/mint-scene-confirm.js@@ -1,5 +1,5 @@import { env } from '../_lib/env.js';-import { wrap, cors, error, json, readJson, method } from '../_lib/http.js';+import { wrap, cors, error, json, readJson, method, rateLimited } from '../_lib/http.js';import { limits, clientIp } from '../_lib/rate-limit.js';import { solanaConnection } from '../_lib/solana/connection.js';@@ -8,7 +8,7 @@ export default wrap(async (req, res) => {if (!method(req, res, ['POST'])) return;const rl = await limits.authIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const body = await readJson(req);const { signedTxBase64 } = body || {};diff --git a/api/nft/mint-scene.js b/api/nft/mint-scene.jsindex db5e7314d..247153d5d 100644--- a/api/nft/mint-scene.js+++ b/api/nft/mint-scene.js@@ -1,5 +1,5 @@import { env } from '../_lib/env.js';-import { wrap, cors, error, json, readJson, method } from '../_lib/http.js';+import { wrap, cors, error, json, readJson, method, rateLimited } from '../_lib/http.js';import { limits, clientIp } from '../_lib/rate-limit.js';import { createUmi } from '@metaplex-foundation/umi-bundle-defaults';import { mplCore, createV1 } from '@metaplex-foundation/mpl-core';@@ -39,7 +39,7 @@ export default wrap(async (req, res) => {return error(res, 503, 'not_configured', 'NFT_STORAGE_TOKEN not configured');const rl = await limits.authIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const body = await readJson(req);const { ownerPubkey, glbBase64, thumbnailBase64, name, description } = body || {};diff --git a/api/nft/resolve.js b/api/nft/resolve.jsindex 95af2c74b..44d4a0486 100644--- a/api/nft/resolve.js+++ b/api/nft/resolve.js@@ -1,5 +1,5 @@import { env } from '../_lib/env.js';-import { wrap, cors, error, json, readJson, method } from '../_lib/http.js';+import { wrap, cors, error, json, readJson, method, rateLimited } from '../_lib/http.js';import { limits, clientIp } from '../_lib/rate-limit.js';export default wrap(async (req, res) => {@@ -7,7 +7,7 @@ export default wrap(async (req, res) => {if (!method(req, res, ['POST'])) return;const rl = await limits.authIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const body = await readJson(req);const chain = String(body.chain || '').toLowerCase();diff --git a/api/notifications/index.js b/api/notifications/index.jsindex c260908a4..c23046f5a 100644--- a/api/notifications/index.js+++ b/api/notifications/index.js@@ -2,7 +2,7 @@import { sql } from '../_lib/db.js';import { getSessionUser } from '../_lib/auth.js';-import { cors, json, method, wrap, error } from '../_lib/http.js';+import { cors, json, method, wrap, error, rateLimited } from '../_lib/http.js';import { limits } from '../_lib/rate-limit.js';export default wrap(async (req, res) => {@@ -13,7 +13,7 @@ export default wrap(async (req, res) => {if (!user) return error(res, 401, 'unauthorized', 'sign in required');const rl = await limits.notificationsRead(user.id);- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const params = new URL(req.url, 'http://x').searchParams;const limit = Math.min(50, Math.max(1, parseInt(params.get('limit') || '20', 10)));diff --git a/api/oauth/[action].js b/api/oauth/[action].jsindex c84cef0f4..e223bc4d9 100644--- a/api/oauth/[action].js+++ b/api/oauth/[action].js@@ -9,7 +9,7 @@ import {revokeRefreshToken, authenticateBearer, verifyAccessToken,} from '../_lib/auth.js';import { randomToken, sha256, sha256Base64Url, constantTimeEquals } from '../_lib/crypto.js';-import { cors, method, wrap, error, redirect, readForm, readJson, json } from '../_lib/http.js';+import { cors, method, wrap, error, redirect, readForm, readJson, json, rateLimited } from '../_lib/http.js';import { limits, clientIp } from '../_lib/rate-limit.js';import { env } from '../_lib/env.js';import { z } from 'zod';@@ -134,7 +134,7 @@ async function handleToken(req, res) {const clientId = form.client_id || basicAuthUser(req);if (!clientId) return error(res, 400, 'invalid_client', 'client_id required');const rl = await limits.oauthToken(clientId);- if (!rl.success) return error(res, 429, 'rate_limited', 'too many token requests');+ if (!rl.success) return rateLimited(res, rl, 'too many token requests');const rows = await sql`select * from oauth_clients where client_id = ${clientId} limit 1`;const client = rows[0];if (!client) return error(res, 400, 'invalid_client', 'unknown client');@@ -196,7 +196,7 @@ async function handleRegister(req, res) {if (cors(req, res, { methods: 'POST,OPTIONS' })) return;if (!method(req, res, ['POST'])) return;const rl = await limits.oauthRegisterIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many registrations from this IP');+ if (!rl.success) return rateLimited(res, rl, 'too many registrations from this IP');const body = parse(registerSchema, await readJson(req));for (const uri of body.redirect_uris) {const u = new URL(uri);diff --git a/api/onboarding/[action].js b/api/onboarding/[action].jsindex 1f41fd496..d96749f0a 100644--- a/api/onboarding/[action].js+++ b/api/onboarding/[action].js@@ -3,7 +3,7 @@import { z } from 'zod';import { sql } from '../_lib/db.js';import { getSessionUser, authenticateBearer, extractBearer, hasScope } from '../_lib/auth.js';-import { cors, json, method, readJson, wrap, error } from '../_lib/http.js';+import { cors, json, method, readJson, wrap, error, rateLimited } from '../_lib/http.js';import { limits, clientIp } from '../_lib/rate-limit.js';import { parse } from '../_lib/validate.js';import { env } from '../_lib/env.js';@@ -31,9 +31,9 @@ async function handleAvaturnSession(req, res) {const userId = await resolveAvaturnUser(req);if (!userId) return error(res, 401, 'unauthorized', 'sign in to create an avatar');const rlUser = await limits.upload(userId);- if (!rlUser.success) return error(res, 429, 'rate_limited', 'too many avatar attempts, try again later');+ if (!rlUser.success) return rateLimited(res, rlUser, 'too many avatar attempts, try again later');const rlIp = await limits.authIp(clientIp(req));- if (!rlIp.success) return error(res, 429, 'rate_limited', 'too many requests from this network');+ if (!rlIp.success) return rateLimited(res, rlIp, 'too many requests from this network');if (!env.AVATURN_API_KEY) return error(res, 501, 'not_configured', 'Avatar editor is not available right now. Please try again later.');const body = parse(avaturnSchema, await readJson(req, 8_000_000));try {diff --git a/api/pay/deal.js b/api/pay/deal.jsindex c7d4c4ab4..f7dbb057f 100644--- a/api/pay/deal.js+++ b/api/pay/deal.js@@ -17,7 +17,7 @@// event: done data: {}//// No mock paths. Every run executes a real on-chain SOL transfer.-import { cors, method, wrap, error } from '../_lib/http.js';+import { cors, method, wrap, error, rateLimited } from '../_lib/http.js';import { limits, clientIp } from '../_lib/rate-limit.js';import {avatarWalletConfig,@@ -158,7 +158,7 @@ export default wrap(async (req, res) => {if (!method(req, res, ['GET'])) return;const rl = await limits.publicIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);// Wallet Aconst cfg = avatarWalletConfig();diff --git a/api/payments/evm/[action].js b/api/payments/evm/[action].jsindex 60dcdb214..108efc4d2 100644--- a/api/payments/evm/[action].js+++ b/api/payments/evm/[action].js@@ -3,7 +3,7 @@import { z } from 'zod';import { sql } from '../../_lib/db.js';import { getSessionUser } from '../../_lib/auth.js';-import { cors, json, method, readJson, wrap, error } from '../../_lib/http.js';+import { cors, json, method, readJson, wrap, error, rateLimited } from '../../_lib/http.js';import { limits, clientIp } from '../../_lib/rate-limit.js';import { parse } from '../../_lib/validate.js';import { randomToken } from '../../_lib/crypto.js';@@ -23,7 +23,7 @@ async function handleCheckout(req, res) {const user = await getSessionUser(req);if (!user) return error(res, 401, 'unauthorized', 'sign in required');const rl = await limits.authIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const body = parse(checkoutSchema, await readJson(req));const { plan, chain_id } = body;if (!EVM_USDC[chain_id]) return error(res, 400, 'unsupported_chain', `chain ${chain_id} is not supported for payments`);@@ -57,7 +57,7 @@ async function handleConfirm(req, res) {const user = await getSessionUser(req);if (!user) return error(res, 401, 'unauthorized', 'sign in required');const rl = await limits.authIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const body = parse(confirmSchema, await readJson(req));const { intent_id, tx_hash } = body;const [intent] = await sql`select * from plan_payment_intents where id = ${intent_id} and user_id = ${user.id} limit 1`;diff --git a/api/payments/intent.js b/api/payments/intent.jsindex 7dadb0783..1ad7c3069 100644--- a/api/payments/intent.js+++ b/api/payments/intent.js@@ -8,7 +8,7 @@*/import { sql } from '../_lib/db.js';import { getSessionUser } from '../_lib/auth.js';-import { cors, json, method, readJson, wrap, error } from '../_lib/http.js';+import { cors, json, method, readJson, wrap, error, rateLimited } from '../_lib/http.js';import { clientIp, limits } from '../_lib/rate-limit.js';import { nanoid } from 'nanoid';@@ -22,7 +22,7 @@ export default wrap(async (req, res) => {if (!user) return error(res, 401, 'unauthorized', 'sign in required');const rl = await limits.authIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const body = await readJson(req).catch(() => null);const agent_id = body?.agent_id;diff --git a/api/payments/prepare-skill-purchase.js b/api/payments/prepare-skill-purchase.jsindex 7aafa85c8..7f2f2fe21 100644--- a/api/payments/prepare-skill-purchase.js+++ b/api/payments/prepare-skill-purchase.js@@ -13,7 +13,7 @@ import { getAssociatedTokenAddressSync, createTransferCheckedInstruction, getMinimport { sql } from '../_lib/db.js';import { authenticateBearer, extractBearer, getSessionUser } from '../_lib/auth.js';-import { cors, error, json, method, readJson, wrap } from '../_lib/http.js';+import { cors, error, json, method, readJson, wrap, rateLimited } from '../_lib/http.js';import { clientIp, limits } from '../_lib/rate-limit.js';import { z } from 'zod';@@ -43,7 +43,7 @@ export default wrap(async (req, res) => {if (!auth) return error(res, 401, 'unauthorized', 'sign in required');const rl = await limits.authIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const body = await readJson(req).catch(() => null);const parsed = bodySchema.safeParse(body);diff --git a/api/payments/purchase-skill.js b/api/payments/purchase-skill.jsindex 4e91ae074..978c39044 100644--- a/api/payments/purchase-skill.js+++ b/api/payments/purchase-skill.js@@ -8,7 +8,7 @@ import { Keypair } from '@solana/web3.js';import { sql } from '../_lib/db.js';import { authenticateBearer, extractBearer, getSessionUser } from '../_lib/auth.js';-import { cors, error, json, method, readJson, wrap } from '../_lib/http.js';+import { cors, error, json, method, readJson, wrap, rateLimited } from '../_lib/http.js';import { clientIp, limits } from '../_lib/rate-limit.js';import { z } from 'zod';@@ -33,7 +33,7 @@ export default wrap(async (req, res) => {if (!auth) return error(res, 401, 'unauthorized', 'sign in required');const rl = await limits.authIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const body = await readJson(req).catch(() => null);const parsed = bodySchema.safeParse(body);diff --git a/api/payments/solana/[action].js b/api/payments/solana/[action].jsindex 3840bfed1..768e41dd3 100644--- a/api/payments/solana/[action].js+++ b/api/payments/solana/[action].js@@ -4,7 +4,7 @@ import { z } from 'zod';import { solanaConnection } from '../../_lib/solana/connection.js';import { sql } from '../../_lib/db.js';import { getSessionUser } from '../../_lib/auth.js';-import { cors, json, method, readJson, wrap, error } from '../../_lib/http.js';+import { cors, json, method, readJson, wrap, error, rateLimited } from '../../_lib/http.js';import { limits, clientIp } from '../../_lib/rate-limit.js';import { parse } from '../../_lib/validate.js';import { randomToken } from '../../_lib/crypto.js';@@ -27,7 +27,7 @@ async function handleCheckout(req, res) {const user = await getSessionUser(req);if (!user) return error(res, 401, 'unauthorized', 'sign in required');const rl = await limits.authIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const body = parse(checkoutSchema, await readJson(req));const { plan, network } = body;const recipient = getSolanaRecipient();@@ -61,7 +61,7 @@ async function handleConfirm(req, res) {const user = await getSessionUser(req);if (!user) return error(res, 401, 'unauthorized', 'sign in required');const rl = await limits.authIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const body = parse(confirmSchema, await readJson(req));const { intent_id, tx_signature, network } = body;const [intent] = await sql`select * from plan_payment_intents where id = ${intent_id} and user_id = ${user.id} and chain_type = 'solana' limit 1`;diff --git a/api/permissions/[action].js b/api/permissions/[action].jsindex 9c9b61339..4c83ec561 100644--- a/api/permissions/[action].js+++ b/api/permissions/[action].js@@ -18,7 +18,7 @@ import { evmFallbackProvider } from '../_lib/evm/rpc.js';import { sql } from '../_lib/db.js';import { getSessionUser, authenticateBearer, extractBearer, hasScope } from '../_lib/auth.js';-import { cors, json, method, readJson, wrap, error } from '../_lib/http.js';+import { cors, json, method, readJson, wrap, error, rateLimited } from '../_lib/http.js';import { limits, clientIp } from '../_lib/rate-limit.js';import { parse } from '../_lib/validate.js';import { env } from '../_lib/env.js';@@ -109,7 +109,7 @@ async function handleGrant(req, res) {if (!user) return error(res, 401, 'unauthorized', 'sign in required');const rl = await limits.permissionsGrant(user.id);- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const raw = await readJson(req);const parsed = grantBodySchema.safeParse(raw);@@ -317,7 +317,7 @@ async function handleList(req, res) {}const rl = await limits.read(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const url = new URL(req.url, 'http://x');const agentId = url.searchParams.get('agentId') || null;@@ -489,7 +489,7 @@ async function handleMetadata(req, res) {}const rl = await limits.read(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const url = new URL(req.url, 'http://x');const agentId = url.searchParams.get('agentId');@@ -688,7 +688,7 @@ async function handleRedeem(req, res) {// Rate limit — strict bucket since each request costs gasconst ip = clientIp(req);const rl = await limits.strict(ip);- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);// Auth — agent bearer only (no user sessions on this machine endpoint)const token = extractBearer(req);@@ -973,7 +973,7 @@ async function handleRevoke(req, res) {if (!user) return error(res, 401, 'unauthorized', 'sign in required');const rl = await limits.permissionsRevoke(user.id);- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const raw = await readJson(req);const parsed = revokeBodySchema.safeParse(raw);@@ -1116,7 +1116,7 @@ async function handleVerify(req, res) {}const rl = await limits.read(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const url = new URL(req.url, 'http://x');const hash = url.searchParams.get('hash');diff --git a/api/pinning/[action].js b/api/pinning/[action].jsindex d1470c150..70b7a99e4 100644--- a/api/pinning/[action].js+++ b/api/pinning/[action].js@@ -1,6 +1,6 @@import { sql } from '../_lib/db.js';import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';-import { cors, json, method, readJson, wrap, error } from '../_lib/http.js';+import { cors, json, method, readJson, wrap, error, rateLimited } from '../_lib/http.js';import { limits, clientIp } from '../_lib/rate-limit.js';const MAX_R2_BYTES = 50 * 1024 * 1024;@@ -82,7 +82,7 @@ export default wrap(async (req, res) => {const userId = session?.id ?? bearer.userId;const rl = await limits.pinUser(userId);- if (!rl.success) return error(res, 429, 'rate_limited', 'pinning rate exceeded (30/hour)');+ if (!rl.success) return rateLimited(res, rl, 'pinning rate exceeded (30/hour)');const body = await readJson(req);const { sourceUrl, kind } = body || {};@@ -165,7 +165,7 @@ export default wrap(async (req, res) => {const ip = clientIp(req);const rl = await limits.pinStatusIp(ip);- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const cid = req.query?.cid || new URL(req.url, 'http://x').searchParams.get('cid');if (!cid || !CID_RE.test(cid)) {diff --git a/api/play/builds.js b/api/play/builds.jsindex 9a48db7bd..ab9bef884 100644--- a/api/play/builds.js+++ b/api/play/builds.js@@ -9,7 +9,7 @@// lives in the /play client (coincommunities-ui.js); each card links back into// the coin's world.import { z } from 'zod';-import { cors, error, json, method, readJson, wrap } from '../_lib/http.js';+import { cors, error, json, method, readJson, wrap, rateLimited } from '../_lib/http.js';import { clientIp, limits } from '../_lib/rate-limit.js';import { listBuilds, publishBuild } from '../_lib/builds-store.js';@@ -38,7 +38,7 @@ export default wrap(async (req, res) => {if (req.method === 'GET') {res.setHeader('cache-control', 'public, max-age=15, stale-while-revalidate=60');const rl = await limits.publicIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const mint = String(req.query?.mint || '').trim();if (!mint || mint.length < 32 || mint.length > 64) {return error(res, 400, 'bad_mint', 'a valid coin mint is required');@@ -55,7 +55,7 @@ export default wrap(async (req, res) => {// POST — publish a build.res.setHeader('cache-control', 'no-store');const rl = await limits.buildPublishIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'sharing too fast — try again shortly');+ if (!rl.success) return rateLimited(res, rl, 'sharing too fast — try again shortly');// Read a little past the thumb cap so a modestly-oversized screenshot is// rejected by the schema (a clean 413) rather than the raw byte limit, whilediff --git a/api/play/nonce.js b/api/play/nonce.jsindex 59afb1440..ec3f14601 100644--- a/api/play/nonce.js+++ b/api/play/nonce.js@@ -5,7 +5,7 @@// active (required) and what it demands (mint + minBalance) so the gate UI can// state the exact requirement and skip the whole flow when the platform hasn't// pinned a game token yet.-import { cors, error, json, method, wrap } from '../_lib/http.js';+import { cors, error, json, method, wrap, rateLimited } from '../_lib/http.js';import { clientIp, limits } from '../_lib/rate-limit.js';import { issueNonce, PLAY_GATE_MINT, PLAY_GATE_MIN, PLAY_GATE_SYMBOL } from '../_lib/play-pass.js';@@ -15,7 +15,7 @@ export default wrap(async (req, res) => {res.setHeader('cache-control', 'no-store');const rl = await limits.authIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const { nonce, exp } = issueNonce();return json(res, 200, {diff --git a/api/play/refresh.js b/api/play/refresh.jsindex 189a8a045..a9f5b6d53 100644--- a/api/play/refresh.js+++ b/api/play/refresh.js@@ -17,7 +17,7 @@// 401 pass_invalid — missing/expired/forged pass → fall back to a full sign-in// 502 balance_unavailable — RPC/price feed downimport { z } from 'zod';-import { cors, error, json, method, readJson, wrap } from '../_lib/http.js';+import { cors, error, json, method, readJson, wrap, rateLimited } from '../_lib/http.js';import { clientIp, limits } from '../_lib/rate-limit.js';import { getBalances } from '../_lib/balances.js';import { verifyPlayPass, signPlayPass, PLAY_GATE_MINT, PLAY_GATE_MIN } from '../_lib/play-pass.js';@@ -34,7 +34,7 @@ export default wrap(async (req, res) => {res.setHeader('cache-control', 'no-store');const rl = await limits.authIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);if (!PLAY_GATE_MINT) {return error(res, 400, 'gate_disabled', 'the token gate is not active');diff --git a/api/play/verify.js b/api/play/verify.jsindex daf88441b..dcf84831d 100644--- a/api/play/verify.js+++ b/api/play/verify.js@@ -21,7 +21,7 @@import { ed25519 } from '@noble/curves/ed25519.js';import bs58mod from 'bs58';import { z } from 'zod';-import { cors, error, json, method, readJson, wrap } from '../_lib/http.js';+import { cors, error, json, method, readJson, wrap, rateLimited } from '../_lib/http.js';import { clientIp, limits } from '../_lib/rate-limit.js';import { getBalances } from '../_lib/balances.js';import { cacheGet, cacheSet } from '../_lib/cache.js';@@ -56,7 +56,7 @@ export default wrap(async (req, res) => {res.setHeader('cache-control', 'no-store');const rl = await limits.authIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);if (!PLAY_GATE_MINT) {return error(res, 400, 'gate_disabled', 'the token gate is not active');diff --git a/api/plugins/[action].js b/api/plugins/[action].jsindex d62e2ade1..4efb59129 100644--- a/api/plugins/[action].js+++ b/api/plugins/[action].js@@ -4,7 +4,7 @@* GET /api/plugins/categories* GET /api/plugins/list ?category=&q=&sort=&cursor=&limit=* GET /api/plugins/:id- * POST /api/plugins/import { manifest_url } — fetch + validate + optionally save+ * POST /api/plugins/import { manifest_url } — fetch + validate + optionally save* POST /api/plugins/publish { manifest_json } — publish plugin to marketplace* POST /api/plugins/:id/install — increment install_count (called client-side on install)*/@@ -12,7 +12,7 @@import { z } from 'zod';import { sql } from '../_lib/db.js';import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';-import { cors, error, json, method, readJson, wrap } from '../_lib/http.js';+import { cors, error, json, method, readJson, wrap, rateLimited } from '../_lib/http.js';import { limits, clientIp } from '../_lib/rate-limit.js';const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;@@ -109,7 +109,7 @@ async function handleCategories(req, res) {if (!method(req, res, ['GET'])) return;const rl = await limits.widgetRead(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const rows = await sql`SELECT category, count(*)::int AS count@@ -135,7 +135,7 @@ async function handleList(req, res, url) {if (!method(req, res, ['GET'])) return;const rl = await limits.widgetRead(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const q = (url.searchParams.get('q') || '').trim().slice(0, 80) || null;const category = url.searchParams.get('category') || null;@@ -185,7 +185,7 @@ async function handleDetail(req, res, id) {if (!method(req, res, ['GET'])) return;const rl = await limits.widgetRead(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const [row] = await sql`SELECT p.*, u.display_name AS author_display_name,@@ -211,7 +211,7 @@ async function handleImport(req, res) {if (!method(req, res, ['POST'])) return;const rl = await limits.widgetRead(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const body = await readJson(req);const manifestUrl = (body?.manifest_url || '').trim();@@ -272,7 +272,7 @@ async function handlePublish(req, res) {if (!auth) return error(res, 401, 'unauthorized', 'authentication required');const rl = await limits.widgetRead(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const raw = await readJson(req);let body;@@ -332,7 +332,7 @@ async function handleInstall(req, res, id) {if (!method(req, res, ['POST'])) return;const rl = await limits.widgetRead(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);await sql`UPDATE plugins SET install_count = install_count + 1 WHERE id = ${id} AND deleted_at IS NULLdiff --git a/api/portfolio/[action].js b/api/portfolio/[action].jsindex eacdcc598..babb35131 100644--- a/api/portfolio/[action].js+++ b/api/portfolio/[action].js@@ -9,7 +9,7 @@// memoized for 60s in-process to shield Helius/Alchemy/CoinGecko from// per-page-load fan-out.-import { cors, json, method, readJson, wrap, error, validationError } from '../_lib/http.js';+import { cors, json, method, readJson, wrap, error, validationError, rateLimited } from '../_lib/http.js';import { solanaConnection } from '../_lib/solana/connection.js';import { evmFallbackProvider } from '../_lib/evm/rpc.js';import { limits, clientIp } from '../_lib/rate-limit.js';@@ -101,7 +101,7 @@ async function handleSummary(req, res) {if (!user) return error(res, 401, 'unauthorized', 'sign in required');const rl = await limits.walletRead(user.id);- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const url = new URL(req.url, 'http://localhost');const wantSnapshot = url.searchParams.get('snapshot') === '1';@@ -185,7 +185,7 @@ async function handleHistory(req, res) {if (!user) return error(res, 401, 'unauthorized', 'sign in required');const rl = await limits.walletRead(user.id);- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const url = new URL(req.url, 'http://localhost');const days = Math.min(365, Math.max(1, parseInt(url.searchParams.get('days') || '90', 10)));@@ -361,7 +361,7 @@ async function handleSend(req, res) {if (!(await requireCsrf(req, res, user.id))) return;const rl = await limits.strict(`portfolio:send:${user.id}`);- if (!rl.success) return error(res, 429, 'rate_limited', 'too many sends');+ if (!rl.success) return rateLimited(res, rl, 'too many sends');let body;try {@@ -438,7 +438,7 @@ async function handleAsset(req, res) {if (!user) return error(res, 401, 'unauthorized', 'sign in required');const rl = await limits.walletRead(user.id);- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const url = new URL(req.url, 'http://localhost');const chain = String(url.searchParams.get('chain') || '').toLowerCase();diff --git a/api/pump-fun-mcp.js b/api/pump-fun-mcp.jsindex 6cfe642fd..cfc219c0f 100644--- a/api/pump-fun-mcp.js+++ b/api/pump-fun-mcp.js@@ -16,7 +16,7 @@// Methods: initialize, tools/list, tools/call. CORS open (read-only data).// Rate-limited by IP via limits.mcpIp.-import { cors, json, method, wrap, readJson, error } from './_lib/http.js';+import { cors, json, method, wrap, readJson, error, rateLimited } from './_lib/http.js';import { limits, clientIp } from './_lib/rate-limit.js';import { extractBearer, authenticateBearer } from './_lib/auth.js';import { verifyPayment, resolveResourceUrl, paymentRequirements } from './_lib/x402-spec.js';@@ -764,7 +764,7 @@ export default wrap(async (req, res) => {if (!method(req, res, ['POST'])) return;const rl = await limits.mcpIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);let body;try {diff --git a/api/pump/[action].js b/api/pump/[action].jsindex 69b07059e..106ae325c 100644--- a/api/pump/[action].js+++ b/api/pump/[action].js@@ -54,7 +54,7 @@ import { z } from 'zod';import { Keypair, PublicKey, LAMPORTS_PER_SOL } from '@solana/web3.js';import { sql } from '../_lib/db.js';import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';-import { cors, json, method, readJson, wrap, error } from '../_lib/http.js';+import { cors, json, method, readJson, wrap, error, rateLimited } from '../_lib/http.js';import { putObject, publicUrl as r2PublicUrl } from '../_lib/r2.js';import { env } from '../_lib/env.js';import { limits, clientIp } from '../_lib/rate-limit.js';@@ -177,7 +177,7 @@ async function handleBalances(req, res) {if (!method(req, res, ['GET'])) return;const rl = await limits.authIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const url = new URL(req.url, `http://${req.headers.host}`);const mintStr = url.searchParams.get('mint');@@ -244,7 +244,7 @@ async function handleBuyPrep(req, res) {if (!user) return error(res, 401, 'unauthorized', 'sign in required');const rl = await limits.authIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const body = parse(buyPrepSchema, await readJson(req));const userPk = solanaPubkey(body.wallet_address);@@ -406,7 +406,7 @@ async function handleBuyConfirm(req, res) {if (!user) return error(res, 401, 'unauthorized', 'sign in required');const rl = await limits.authIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const body = parse(buyConfirmSchema, await readJson(req));@@ -491,7 +491,7 @@ async function handleSellPrep(req, res) {if (!user) return error(res, 401, 'unauthorized', 'sign in required');const rl = await limits.authIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const body = parse(sellPrepSchema, await readJson(req));const userPk = solanaPubkey(body.wallet_address);@@ -615,7 +615,7 @@ async function handleSellConfirm(req, res) {if (!user) return error(res, 401, 'unauthorized', 'sign in required');const rl = await limits.authIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const body = parse(sellConfirmSchema, await readJson(req));@@ -680,7 +680,7 @@ async function handleBuildMetadata(req, res) {if (!user) return error(res, 401, 'unauthorized', 'sign in required');const rl = await limits.pumpMetaIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);let body;try {@@ -987,7 +987,7 @@ async function handleLaunchPrep(req, res) {if (!user) return error(res, 401, 'unauthorized', 'sign in required');const rl = await limits.authIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const body = parse(launchPrepSchema, await readJson(req));const signer = solanaPubkey(body.wallet_address);@@ -1175,7 +1175,7 @@ async function handleLaunchConfirm(req, res) {if (!user) return error(res, 401, 'unauthorized', 'sign in required');const rl = await limits.authIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const body = parse(launchConfirmSchema, await readJson(req));@@ -1270,7 +1270,7 @@ async function handleAgentWallet(req, res) {if (!user) return error(res, 401, 'unauthorized', 'sign in required');const rl = await limits.authIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const body = parse(agentWalletSchema, await readJson(req));@@ -1352,7 +1352,7 @@ async function handleLaunchAgent(req, res) {if (!user) return error(res, 401, 'unauthorized', 'sign in required');const rl = await limits.authIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const body = parse(launchAgentSchema, await readJson(req));@@ -1631,7 +1631,7 @@ async function handleAcceptPaymentPrep(req, res) {const userId = session?.id ?? bearer?.userId ?? null;const rl = await limits.authIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const body = parse(acceptPaymentPrepSchema, await readJson(req));const payer = solanaPubkey(body.payer_wallet);@@ -1731,7 +1731,7 @@ async function handleAcceptPaymentConfirm(req, res) {if (!session && !bearer) return error(res, 401, 'unauthorized', 'auth required');const rl = await limits.authIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const body = parse(acceptPaymentConfirmSchema, await readJson(req));const [payment] = await sql`@@ -1825,7 +1825,7 @@ async function handlePaymentsList(req, res) {if (!method(req, res, ['GET'])) return;const rl = await limits.authIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const url = new URL(req.url, `http://${req.headers.host}`);const mint = url.searchParams.get('mint');@@ -1912,7 +1912,7 @@ async function handlePortfolio(req, res) {if (!auth) return error(res, 401, 'unauthorized', 'sign in required');const rl = await limits.authIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const url = new URL(req.url, `http://${req.headers.host}`);const agentId = url.searchParams.get('agentId');@@ -2013,7 +2013,7 @@ async function handleByAgent(req, res) {if (!method(req, res, ['GET'])) return;const rl = await limits.authIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const url = new URL(req.url, `http://${req.headers.host}`);const agentId = url.searchParams.get('agent_id');@@ -2091,7 +2091,7 @@ async function handleQuote(req, res) {if (!method(req, res, ['GET'])) return;const rl = await limits.authIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const url = new URL(req.url, `http://${req.headers.host}`);const mintStr = url.searchParams.get('mint');@@ -2296,7 +2296,7 @@ async function handleGovernancePrep(req, res) {if (!user) return error(res, 401, 'unauthorized', 'sign in required');const rl = await limits.authIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const body = parse(governancePrepSchema, await readJson(req));const authority = solanaPubkey(body.authority_wallet);@@ -2353,7 +2353,7 @@ async function handleWithdrawPrep(req, res) {if (!user) return error(res, 401, 'unauthorized', 'sign in required');const rl = await limits.authIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const body = parse(withdrawPrepSchema, await readJson(req));const authority = solanaPubkey(body.authority_wallet);@@ -2423,7 +2423,7 @@ async function handleWithdrawConfirm(req, res) {if (!user) return error(res, 401, 'unauthorized', 'sign in required');const rl = await limits.authIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const body = parse(withdrawConfirmSchema, await readJson(req));@@ -2477,7 +2477,7 @@ async function handleStrategyBacktest(req, res) {if (!method(req, res, ['POST'])) return;const rl = await limits.authIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const body = await readJson(req);if (!body?.strategy) return error(res, 400, 'validation_error', 'strategy required');@@ -2510,7 +2510,7 @@ async function handleStrategyCloseAll(req, res) {if (!auth) return error(res, 401, 'unauthorized', 'sign in required');const rl = await limits.authIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const body = await readJson(req);if (!body?.agentId) return error(res, 400, 'validation_error', 'agentId required');@@ -2566,7 +2566,7 @@ async function handleStrategyRun(req, res) {if (!method(req, res, ['POST'])) return;const rl = await limits.authIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);let body;try { body = await readJson(req); }@@ -2666,7 +2666,7 @@ async function handleLiveStream(req, res) {if (!method(req, res, ['GET'])) return;const rl = await limits.mcpIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const url = new URL(req.url, `http://${req.headers.host}`);let kind;@@ -2729,7 +2729,7 @@ async function handleStrategyValidate(req, res) {if (!method(req, res, ['POST'])) return;const rl = await limits.authIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const body = await readJson(req);if (!body?.strategy || typeof body.strategy !== 'object') {@@ -2748,7 +2748,7 @@ async function handleChannelFeed(req, res) {if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;if (!method(req, res, ['GET'])) return;const rl = await limits.mcpIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const url = new URL(req.url, `http://${req.headers.host}`);const limit = Math.min(Math.max(1, Number(url.searchParams.get('limit') || 50)), 200);const kinds = url.searchParams.get('kinds') || null;@@ -2783,7 +2783,7 @@ async function handleTrending(req, res) {if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;if (!method(req, res, ['GET'])) return;const rl = await limits.mcpIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const now = Date.now();if (TRENDING_CACHE.body && now - TRENDING_CACHE.at < TRENDING_TTL_MS) {res.setHeader('cache-control', 'public, max-age=15');@@ -2820,7 +2820,7 @@ async function handleCoin(req, res) {if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;if (!method(req, res, ['GET'])) return;const rl = await limits.mcpIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const url = new URL(req.url, `http://${req.headers.host}`);const mint = (url.searchParams.get('mint') || '').trim();if (!MINT_RE.test(mint)) return error(res, 400, 'invalid_mint', 'mint must be a base58 address');@@ -2872,7 +2872,7 @@ async function handleCoinTrades(req, res) {if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;if (!method(req, res, ['GET'])) return;const rl = await limits.mcpIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const url = new URL(req.url, `http://${req.headers.host}`);const mint = (url.searchParams.get('mint') || '').trim();if (!MINT_RE.test(mint)) return error(res, 400, 'invalid_mint', 'mint must be a base58 address');@@ -2909,7 +2909,7 @@ async function handleSearch(req, res) {if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;if (!method(req, res, ['GET'])) return;const rl = await limits.mcpIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const url = new URL(req.url, `http://${req.headers.host}`);const q = (url.searchParams.get('q') || '').trim();if (!q) return json(res, 200, []);@@ -2974,7 +2974,7 @@ async function handleRecentGraduations(req, res) {if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;if (!method(req, res, ['GET'])) return;const rl = await limits.mcpIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const url = new URL(req.url, 'http://x');const limit = Math.max(1, Math.min(100, Number(url.searchParams.get('limit')) || 20));try {@@ -2991,7 +2991,7 @@ async function handleFirstClaims(req, res) {if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;if (!method(req, res, ['GET'])) return;const rl = await limits.mcpIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const url = new URL(req.url, 'http://x');const limit = Math.max(1, Math.min(50, Number(url.searchParams.get('limit')) || 50));let sinceTs;@@ -3079,7 +3079,7 @@ async function handleVanityKeygen(req, res) {if (cors(req, res, { methods: 'POST,OPTIONS', origins: '*' })) return;if (req.method !== 'POST') { res.setHeader('allow', 'POST'); return error(res, 405, 'method_not_allowed', 'method POST required'); }const rl = await limits.mcpIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);let body;try { body = await readJson(req); } catch (e) { return error(res, e.status || 400, 'bad_request', e.message); }const { suffix = '', prefix = '', caseSensitive = false, maxAttempts = 5_000_000 } = body || {};@@ -3127,7 +3127,7 @@ async function handleCollectCreatorFeePrep(req, res) {if (!user) return error(res, 401, 'unauthorized', 'sign in required');const rl = await limits.authIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const body = parse(collectCreatorFeePrepSchema, await readJson(req));const creatorPk = solanaPubkey(body.creator_address);@@ -3183,7 +3183,7 @@ async function handleDistributeCreatorFeesPrep(req, res) {if (!user) return error(res, 401, 'unauthorized', 'sign in required');const rl = await limits.authIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const body = parse(distributeCreatorFeesPrepSchema, await readJson(req));const mintPk = solanaPubkey(body.mint);@@ -3258,7 +3258,7 @@ async function handleUpdateFeeSharesPrep(req, res) {if (!user) return error(res, 401, 'unauthorized', 'sign in required');const rl = await limits.authIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const body = parse(updateFeeSharesSchema, await readJson(req));const mintPk = solanaPubkey(body.mint);@@ -3339,7 +3339,7 @@ async function handleCreateFeeSharingPrep(req, res) {if (!user) return error(res, 401, 'unauthorized', 'sign in required');const rl = await limits.authIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const body = parse(createFeeSharingPrepSchema, await readJson(req));const mintPk = solanaPubkey(body.mint);@@ -3435,7 +3435,7 @@ async function handleResolveGithubShareholder(req, res) {if (!user) return error(res, 401, 'unauthorized', 'sign in required');const rl = await limits.authIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const body = parse(resolveGithubShareholderSchema, await readJson(req));const login = body.github_username ? body.github_username.replace(/^@/, '') : null;@@ -3525,7 +3525,7 @@ async function handleCreateSocialFeePdaPrep(req, res) {if (!user) return error(res, 401, 'unauthorized', 'sign in required');const rl = await limits.authIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const body = parse(createSocialFeePdaPrepSchema, await readJson(req));const payerPk = solanaPubkey(body.wallet_address);@@ -3578,7 +3578,7 @@ async function handleFeeInfo(req, res) {if (!method(req, res, ['GET'])) return;const rl = await limits.authIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const url = new URL(req.url, `http://${req.headers.host}`);const mintStr = url.searchParams.get('mint');@@ -3763,7 +3763,7 @@ async function handleCollectCreatorFeeAgent(req, res) {if (!method(req, res, ['POST'])) return;const rl = await limits.authIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const body = parse(collectFeeAgentSchema, await readJson(req));const ctx = await resolveAgentFeeContext(req, res, body);@@ -3805,7 +3805,7 @@ async function handleDistributeCreatorFeesAgent(req, res) {if (!method(req, res, ['POST'])) return;const rl = await limits.authIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const body = parse(collectFeeAgentSchema, await readJson(req));const ctx = await resolveAgentFeeContext(req, res, body);@@ -3861,7 +3861,7 @@ async function handleFeeSharingAgent(req, res) {if (!method(req, res, ['POST'])) return;const rl = await limits.authIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const body = parse(feeSharingAgentSchema, await readJson(req));const ctx = await resolveAgentFeeContext(req, res, body);@@ -3968,7 +3968,7 @@ async function handleGithubResolve(req, res) {if (!method(req, res, ['GET'])) return;const rl = await limits.authIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const url = new URL(req.url, `http://${req.headers.host}`);const handle = (url.searchParams.get('handle') || '').replace(/^@/, '').trim();@@ -4028,7 +4028,7 @@ async function handleSocialFeeClaimStatus(req, res) {if (!method(req, res, ['GET'])) return;const rl = await limits.authIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const url = new URL(req.url, `http://${req.headers.host}`);const userId = (url.searchParams.get('user_id') || '').trim();diff --git a/api/pump/channel-feed.js b/api/pump/channel-feed.jsindex 61827e966..c979cc7ce 100644--- a/api/pump/channel-feed.js+++ b/api/pump/channel-feed.js@@ -1,4 +1,4 @@-import { cors, error, json, method, wrap } from '../_lib/http.js';+import { cors, error, json, method, wrap, rateLimited } from '../_lib/http.js';import { limits, clientIp } from '../_lib/rate-limit.js';import { getMints, getWhales, getClaims } from '../_lib/channel-feed-sources.js';@@ -7,7 +7,7 @@ export default wrap(async (req, res) => {if (!method(req, res, ['GET'])) return;const rl = await limits.mcpIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const url = new URL(req.url, 'http://x');const kindsParam = url.searchParams.get('kinds');diff --git a/api/pump/deliver-telegram.js b/api/pump/deliver-telegram.jsindex c4d1d49c4..92c3e8af7 100644--- a/api/pump/deliver-telegram.js+++ b/api/pump/deliver-telegram.js@@ -6,7 +6,7 @@// without that, anyone on the internet could turn the bot into a spam/phishing// relay (a direct server-to-server POST is not subject to browser CORS).-import { cors, error, json, method, readJson, wrap } from '../_lib/http.js';+import { cors, error, json, method, readJson, wrap, rateLimited } from '../_lib/http.js';import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';import { limits, clientIp } from '../_lib/rate-limit.js';import { z } from 'zod';@@ -60,7 +60,7 @@ export default wrap(async (req, res) => {if (!authed) return error(res, 401, 'unauthorized', 'sign in or provide a valid bearer token');const rl = await limits.authIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many delivery requests');+ if (!rl.success) return rateLimited(res, rl, 'too many delivery requests');const token = process.env.TELEGRAM_BOT_TOKEN;if (!token) return error(res, 500, 'misconfigured', 'TELEGRAM_BOT_TOKEN is not set');diff --git a/api/pump/price-history.js b/api/pump/price-history.jsindex 97347b923..03882d14b 100644--- a/api/pump/price-history.js+++ b/api/pump/price-history.js@@ -5,7 +5,7 @@//// Response: { data: [ { t, o, h, l, c, v }, ... ] } (t = unix seconds)-import { cors, json, method, wrap, error } from '../_lib/http.js';+import { cors, json, method, wrap, error, rateLimited } from '../_lib/http.js';import { limits, clientIp } from '../_lib/rate-limit.js';import { fetchBirdeyeOhlcv, birdeyeConfigured } from '../_lib/birdeye.js';@@ -58,7 +58,7 @@ export default wrap(async (req, res) => {if (!method(req, res, ['GET'])) return;const rl = await limits.publicIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const params = new URL(req.url, 'http://x').searchParams;const mint = (params.get('mint') || '').trim();diff --git a/api/pump/search.js b/api/pump/search.jsindex c770f53a2..cb5495860 100644--- a/api/pump/search.js+++ b/api/pump/search.js@@ -13,7 +13,7 @@//// Response: { data: [ { mint, symbol, name, logo, price_usd, rank } ] }-import { cors, json, method, wrap, error } from '../_lib/http.js';+import { cors, json, method, wrap, error, rateLimited } from '../_lib/http.js';import { limits, clientIp } from '../_lib/rate-limit.js';import { normalizeGatewayURL } from '../../src/ipfs.js';@@ -102,7 +102,7 @@ export default wrap(async (req, res) => {if (!method(req, res, ['GET'])) return;const rl = await limits.publicIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const params = new URL(req.url, 'http://x').searchParams;const q = (params.get('q') || '').trim().slice(0, 64);diff --git a/api/pump/trending.js b/api/pump/trending.jsindex 8553a6f8a..63a8c8f4b 100644--- a/api/pump/trending.js+++ b/api/pump/trending.js@@ -10,7 +10,7 @@//// Response: { data: [ { mint, symbol, name, logo, price_usd, rank } ] }-import { cors, json, method, wrap, error } from '../_lib/http.js';+import { cors, json, method, wrap, error, rateLimited } from '../_lib/http.js';import { limits, clientIp } from '../_lib/rate-limit.js';import { normalizeGatewayURL } from '../../src/ipfs.js';@@ -93,7 +93,7 @@ export default wrap(async (req, res) => {if (!method(req, res, ['GET'])) return;const rl = await limits.publicIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const raw = Number(new URL(req.url, 'http://x').searchParams.get('limit') || '25');const limit = Math.min(50, Math.max(1, Number.isFinite(raw) ? Math.floor(raw) : 25));diff --git a/api/render/avatar-clip.js b/api/render/avatar-clip.jsindex 14d32c56b..8d7afa1f4 100644--- a/api/render/avatar-clip.js+++ b/api/render/avatar-clip.js@@ -11,7 +11,7 @@// expression: { jawOpen: 0.4, mouthSmileLeft: 0.6, ... } // ARKit-52 morphs// }-import { cors, error, json, method, readJson, wrap } from '../_lib/http.js';+import { cors, error, json, method, readJson, wrap, rateLimited } from '../_lib/http.js';import { renderClip } from '../_lib/render-clip.js';import { PRESETS } from '../../src/pose-presets.js';import { assertSafePublicUrl, SsrfBlockedError } from '../_lib/ssrf-guard.js';@@ -27,16 +27,17 @@ const RATE_LIMIT_MAX = 60;const rateMap = new Map();function rateCheck(ip) {- if (!ip) return true;const now = Date.now();+ if (!ip)+ return { success: true, limit: RATE_LIMIT_MAX, remaining: RATE_LIMIT_MAX, reset: now + RATE_LIMIT_WINDOW_MS };const arr = (rateMap.get(ip) || []).filter((t) => now - t < RATE_LIMIT_WINDOW_MS);if (arr.length >= RATE_LIMIT_MAX) {rateMap.set(ip, arr);- return false;+ return { success: false, limit: RATE_LIMIT_MAX, remaining: 0, reset: arr[0] + RATE_LIMIT_WINDOW_MS };}arr.push(now);rateMap.set(ip, arr);- return true;+ return { success: true, limit: RATE_LIMIT_MAX, remaining: RATE_LIMIT_MAX - arr.length, reset: now + RATE_LIMIT_WINDOW_MS };}async function preflightSize(url) {@@ -70,8 +71,9 @@ export default wrap(async function handler(req, res) {if (!method(req, res, ['POST'])) return;const ip = clientIp(req);- if (!rateCheck(ip)) {- return error(res, 429, 'rate_limited', `Too many render requests. Limit: ${RATE_LIMIT_MAX} per ${RATE_LIMIT_WINDOW_MS / 60000}m.`);+ const rl = rateCheck(ip);+ if (!rl.success) {+ return rateLimited(res, rl, `Too many render requests. Limit: ${RATE_LIMIT_MAX} per ${RATE_LIMIT_WINDOW_MS / 60000}m.`);}let body;diff --git a/api/render/glb.js b/api/render/glb.jsindex 5a3223a9b..8fc2304bd 100644--- a/api/render/glb.js+++ b/api/render/glb.js@@ -18,7 +18,7 @@// - In-memory IP rate limit (60 renders / 10 min / IP) to keep chromium// warm-up costs bounded under abuse.-import { cors, error, method, readJson, wrap } from '../_lib/http.js';+import { cors, error, method, readJson, wrap, rateLimited } from '../_lib/http.js';import { renderGlbToPng } from '../_lib/render-glb.js';import { assertSafePublicUrl, SsrfBlockedError } from '../_lib/ssrf-guard.js';import { clientIp } from '../_lib/rate-limit.js';@@ -33,16 +33,17 @@ const RATE_LIMIT_MAX = 60;const rateMap = new Map();function rateCheck(ip) {- if (!ip) return true;const now = Date.now();+ const full = { limit: RATE_LIMIT_MAX, remaining: RATE_LIMIT_MAX, reset: now + RATE_LIMIT_WINDOW_MS };+ if (!ip) return { success: true, ...full };const arr = (rateMap.get(ip) || []).filter((t) => now - t < RATE_LIMIT_WINDOW_MS);if (arr.length >= RATE_LIMIT_MAX) {rateMap.set(ip, arr);- return false;+ return { success: false, limit: RATE_LIMIT_MAX, remaining: 0, reset: arr[0] + RATE_LIMIT_WINDOW_MS };}arr.push(now);rateMap.set(ip, arr);- return true;+ return { success: true, limit: RATE_LIMIT_MAX, remaining: RATE_LIMIT_MAX - arr.length, reset: now + RATE_LIMIT_WINDOW_MS };}async function preflightSize(url) {@@ -67,8 +68,9 @@ export default wrap(async function handler(req, res) {if (!method(req, res, ['POST'])) return;const ip = clientIp(req);- if (!rateCheck(ip)) {- return error(res, 429, 'rate_limited', `Too many render requests. Limit: ${RATE_LIMIT_MAX} per ${RATE_LIMIT_WINDOW_MS / 60000}m.`);+ const rl = rateCheck(ip);+ if (!rl.success) {+ return rateLimited(res, rl, `Too many render requests. Limit: ${RATE_LIMIT_MAX} per ${RATE_LIMIT_WINDOW_MS / 60000}m.`);}let body;diff --git a/api/rider/check.js b/api/rider/check.jsindex 05d374834..4b6d50c8d 100644--- a/api/rider/check.js+++ b/api/rider/check.js@@ -1,6 +1,6 @@import { PublicKey } from '@solana/web3.js';import { solanaConnection } from '../_lib/solana/connection.js';-import { cors, json, method, wrap, error } from '../_lib/http.js';+import { cors, json, method, wrap, error, rateLimited } from '../_lib/http.js';import { limits, clientIp } from '../_lib/rate-limit.js';import { TOKEN_MINT as THREE_MINT } from '../_lib/token/config.js';const TOKEN_PROGRAM = new PublicKey('TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA');@@ -11,7 +11,7 @@ export default wrap(async (req, res) => {if (!method(req, res, ['GET'])) return;const rl = await limits.authIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const address = req.query?.address?.trim();if (!address) return error(res, 400, 'validation_error', 'address required');diff --git a/api/scene/gate-check.js b/api/scene/gate-check.jsindex 68024b520..aebfa70cf 100644--- a/api/scene/gate-check.js+++ b/api/scene/gate-check.js@@ -1,7 +1,7 @@import { z } from 'zod';import { verifyMessage } from 'ethers';import { sql } from '../_lib/db.js';-import { cors, json, method, readJson, wrap, error } from '../_lib/http.js';+import { cors, json, method, readJson, wrap, error, rateLimited } from '../_lib/http.js';import { limits, clientIp } from '../_lib/rate-limit.js';import { randomToken } from '../_lib/crypto.js';import { verifySiwsSignature } from '../_lib/siws.js';@@ -26,7 +26,7 @@ export default wrap(async (req, res) => {if (!method(req, res, ['POST'])) return;const rl = await limits.authIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const raw = await readJson(req);diff --git a/api/scene/gate-create.js b/api/scene/gate-create.jsindex 303f5df5f..f46c1d37b 100644--- a/api/scene/gate-create.js+++ b/api/scene/gate-create.js@@ -1,7 +1,7 @@import { z } from 'zod';import { sql } from '../_lib/db.js';import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';-import { cors, json, method, readJson, wrap, error } from '../_lib/http.js';+import { cors, json, method, readJson, wrap, error, rateLimited } from '../_lib/http.js';import { limits, clientIp } from '../_lib/rate-limit.js';import { env } from '../_lib/env.js';import { parse } from '../_lib/validate.js';@@ -27,7 +27,7 @@ export default wrap(async (req, res) => {const userId = session?.id ?? bearer.userId;const rl = await limits.authIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const body = parse(bodySchema, await readJson(req));diff --git a/api/seed/synthesize.js b/api/seed/synthesize.jsindex 3788a68f8..ac8c7f10a 100644--- a/api/seed/synthesize.js+++ b/api/seed/synthesize.js@@ -10,7 +10,7 @@// handleAutoTag for the Anthropic call.import { z } from 'zod';-import { cors, json, method, readJson, wrap, error } from '../_lib/http.js';+import { cors, json, method, readJson, wrap, error, rateLimited } from '../_lib/http.js';import { parse } from '../_lib/validate.js';import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';import { llmComplete, LlmUnavailableError } from '../_lib/llm.js';@@ -104,7 +104,7 @@ export default wrap(async (req, res) => {return error(res, 401, 'unauthorized', 'sign in or provide a valid bearer token');const rl = await limits.authIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many synthesis requests');+ if (!rl.success) return rateLimited(res, rl, 'too many synthesis requests');const body = parse(bodySchema, await readJson(req));diff --git a/api/sentiment.js b/api/sentiment.jsindex c20b2544b..0050cfb2f 100644--- a/api/sentiment.js+++ b/api/sentiment.js@@ -4,7 +4,7 @@// Backs the analyze-sentiment skill in src/agent-skills-sentiment.js.// Deterministic lexicon scorer — same one used by /api/social/sentiment.-import { cors, json, method, readJson, wrap, error } from './_lib/http.js';+import { cors, json, method, readJson, wrap, error, rateLimited } from './_lib/http.js';import { limits, clientIp } from './_lib/rate-limit.js';import { scoreSentiment } from '../src/social/sentiment.js';@@ -13,7 +13,7 @@ export default wrap(async (req, res) => {if (!method(req, res, ['POST'])) return;const rl = await limits.publicIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);let body;try {diff --git a/api/showcase.js b/api/showcase.jsindex 7f7f69223..4c3b283c3 100644--- a/api/showcase.js+++ b/api/showcase.js@@ -5,7 +5,7 @@// concurrent inserts and backed by the `erc8004_agents_has3d_time` index.import { sql } from './_lib/db.js';-import { cors, error, json, method, wrap } from './_lib/http.js';+import { cors, error, json, method, wrap, rateLimited } from './_lib/http.js';import { limits, clientIp } from './_lib/rate-limit.js';import { CHAIN_BY_ID, tokenExplorerUrl, addressExplorerUrl } from './_lib/erc8004-chains.js';@@ -17,7 +17,7 @@ export default wrap(async (req, res) => {if (!method(req, res, ['GET'])) return;const rl = await limits.publicIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const url = new URL(req.url, 'http://x');const params = parseParams(url.searchParams);diff --git a/api/skills/[id].js b/api/skills/[id].jsindex 7cdb31af4..c11f44a9a 100644--- a/api/skills/[id].js+++ b/api/skills/[id].js@@ -1,7 +1,7 @@import { z } from 'zod';import { sql } from '../_lib/db.js';import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';-import { cors, json, error, method, readJson, wrap } from '../_lib/http.js';+import { cors, json, error, method, readJson, wrap, rateLimited } from '../_lib/http.js';import { limits, clientIp } from '../_lib/rate-limit.js';import { parse } from '../_lib/validate.js';@@ -71,7 +71,7 @@ function toSkill(row, { includeInstalled = false } = {}) {async function handleGet(req, res, id) {const rl = await limits.publicIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const auth = await resolveOptionalAuth(req);const userId = auth?.userId ?? null;@@ -105,7 +105,7 @@ async function handleUpdate(req, res, id) {if (!auth) return error(res, 401, 'unauthorized', 'sign in required');const rl = await limits.chatUser(auth.userId);- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const [skill] = await sql`SELECT id, author_id FROM marketplace_skills WHERE id = ${id}@@ -174,7 +174,7 @@ async function handleDelete(req, res, id) {if (!auth) return error(res, 401, 'unauthorized', 'sign in required');const rl = await limits.chatUser(auth.userId);- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const [skill] = await sql`SELECT id, author_id FROM marketplace_skills WHERE id = ${id}diff --git a/api/skills/[id]/install.js b/api/skills/[id]/install.jsindex e571e3b1b..b0347a96a 100644--- a/api/skills/[id]/install.js+++ b/api/skills/[id]/install.js@@ -1,6 +1,6 @@import { sql } from '../../_lib/db.js';import { getSessionUser, authenticateBearer, extractBearer } from '../../_lib/auth.js';-import { cors, json, error, method, wrap } from '../../_lib/http.js';+import { cors, json, error, method, wrap, rateLimited } from '../../_lib/http.js';import { limits } from '../../_lib/rate-limit.js';const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;@@ -18,7 +18,7 @@ export default wrap(async (req, res) => {const userId = session?.id ?? bearer.userId;const rl = await limits.chatUser(userId);- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const [skill] = await sql`SELECT id, schema_json, content FROM marketplace_skills WHERE id = ${id} AND is_public = true`;if (!skill) return error(res, 404, 'not_found', 'skill not found');diff --git a/api/skills/[id]/rate.js b/api/skills/[id]/rate.jsindex 684a518b8..d324c8644 100644--- a/api/skills/[id]/rate.js+++ b/api/skills/[id]/rate.js@@ -1,7 +1,7 @@import { z } from 'zod';import { sql } from '../../_lib/db.js';import { getSessionUser, authenticateBearer, extractBearer } from '../../_lib/auth.js';-import { cors, json, error, method, readJson, wrap } from '../../_lib/http.js';+import { cors, json, error, method, readJson, wrap, rateLimited } from '../../_lib/http.js';import { limits } from '../../_lib/rate-limit.js';import { parse } from '../../_lib/validate.js';@@ -24,7 +24,7 @@ export default wrap(async (req, res) => {const userId = session?.id ?? bearer.userId;const rl = await limits.chatUser(userId);- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const [skill] = await sql`SELECT id FROM marketplace_skills WHERE id = ${id} AND is_public = true`;if (!skill) return error(res, 404, 'not_found', 'skill not found');diff --git a/api/skills/index.js b/api/skills/index.jsindex 621fc8c8b..0bb537492 100644--- a/api/skills/index.js+++ b/api/skills/index.js@@ -1,7 +1,7 @@import { z } from 'zod';import { sql } from '../_lib/db.js';import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';-import { cors, json, error, method, readJson, wrap } from '../_lib/http.js';+import { cors, json, error, method, readJson, wrap, rateLimited } from '../_lib/http.js';import { limits, clientIp } from '../_lib/rate-limit.js';import { parse } from '../_lib/validate.js';@@ -116,7 +116,7 @@ async function handleList(req, res) {}const rl = await limits.skillsBrowse(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const auth = await resolveOptionalAuth(req);const userId = auth?.userId ?? null;@@ -327,7 +327,7 @@ async function handlePublish(req, res) {if (!auth) return error(res, 401, 'unauthorized', 'sign in required');const rl = await limits.chatUser(auth.userId);- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const body = parse(publishSchema, await readJson(req));diff --git a/api/sns-subdomain.js b/api/sns-subdomain.jsindex d1678330d..18f8d1b87 100644--- a/api/sns-subdomain.js+++ b/api/sns-subdomain.js@@ -26,7 +26,7 @@import { getSessionUser, authenticateBearer, extractBearer } from './_lib/auth.js';import { sql } from './_lib/db.js';-import { cors, json, method, error, readJson, wrap } from './_lib/http.js';+import { cors, json, method, error, readJson, wrap, rateLimited } from './_lib/http.js';import { limits, clientIp } from './_lib/rate-limit.js';import {PARENT_LABEL,@@ -59,7 +59,7 @@ function slugifyName(name) {async function handleCheck(req, res) {const rl = await limits.snsResolve(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const url = new URL(req.url, 'http://x');const label = normalizeLabel(url.searchParams.get('label'));@@ -181,7 +181,7 @@ export default wrap(async (req, res) => {if (!auth) return error(res, 401, 'unauthorized', 'sign in or provide a bearer token');const rl = await limits.authIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);return handleMint(req, res, auth);});diff --git a/api/sns.js b/api/sns.jsindex 771f6dfe1..6ee41463c 100644--- a/api/sns.js+++ b/api/sns.js@@ -12,7 +12,7 @@// 5 minutes (negative results for 60s) so repeated UX previews don't hammer// the Bonfida RPC pool. Mainnet only — SNS is not deployed on devnet.-import { cors, error, json, method, wrap } from './_lib/http.js';+import { cors, error, json, method, wrap, rateLimited } from './_lib/http.js';import { limits, clientIp } from './_lib/rate-limit.js';import { resolveSnsName, reverseLookupAddress } from '../src/solana/sns.js';@@ -56,7 +56,7 @@ export default wrap(async (req, res) => {if (!method(req, res, ['GET'])) return;const rl = await limits.snsResolve(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const url = new URL(req.url, 'http://x');const rawName = url.searchParams.get('name');diff --git a/api/social/sentiment-pulse.js b/api/social/sentiment-pulse.jsindex 752730ef2..abc8a5501 100644--- a/api/social/sentiment-pulse.js+++ b/api/social/sentiment-pulse.js@@ -28,7 +28,7 @@// }import { z } from 'zod';-import { cors, error, json, method, readJson, wrap } from '../_lib/http.js';+import { cors, error, json, method, readJson, wrap, rateLimited } from '../_lib/http.js';import { limits, clientIp } from '../_lib/rate-limit.js';const PUMPFUN_BASE = 'https://frontend-api-v3.pump.fun';@@ -76,7 +76,7 @@ export default wrap(async (req, res) => {if (!method(req, res, ['POST'])) return;const rl = await limits.mcpIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);let raw;try {diff --git a/api/social/sentiment.js b/api/social/sentiment.jsindex a57957b87..6e14e89b4 100644--- a/api/social/sentiment.js+++ b/api/social/sentiment.js@@ -3,7 +3,7 @@// → { score, posPct, negPct, neuPct, count, examples }// No auth required. Rate-limited by IP.-import { cors, json, method, readJson, wrap, error } from '../_lib/http.js';+import { cors, json, method, readJson, wrap, error, rateLimited } from '../_lib/http.js';import { limits, clientIp } from '../_lib/rate-limit.js';import { z } from 'zod';@@ -23,7 +23,7 @@ export default wrap(async (req, res) => {if (!method(req, res, ['POST'])) return;const rl = await limits.mcpIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);let raw;try {diff --git a/api/solana-rpc.js b/api/solana-rpc.jsindex e13277364..46264154e 100644--- a/api/solana-rpc.js+++ b/api/solana-rpc.js@@ -16,7 +16,7 @@// (getProgramAccounts, getBlock*) that would let an anonymous caller drain the// upstream quota.-import { cors, method, wrap, readJson, error } from './_lib/http.js';+import { cors, method, wrap, readJson, error, rateLimited } from './_lib/http.js';import { limits, clientIp } from './_lib/rate-limit.js';const PUBLIC_MAINNET = 'https://api.mainnet-beta.solana.com';@@ -83,7 +83,7 @@ export default wrap(async function handler(req, res) {const ip = clientIp(req);const [ipRl, globalRl] = await Promise.all([limits.solanaRpcIp(ip), limits.solanaRpcGlobal()]);if (!ipRl.success || !globalRl.success) {- return error(res, 429, 'rate_limited', 'too many RPC requests');+ return rateLimited(res, ipRl, 'too many RPC requests');}const url = new URL(req.url, 'http://x');diff --git a/api/studio/retexture-region.js b/api/studio/retexture-region.jsindex bf9f81d70..41a4a9e1e 100644--- a/api/studio/retexture-region.js+++ b/api/studio/retexture-region.js@@ -14,7 +14,7 @@// we actually configured before polling — so a forged token can never steer the// server's fetch at an attacker-chosen host (no SSRF, no DB row needed).-import { cors, json, method, readJson, wrap, error } from '../_lib/http.js';+import { cors, json, method, readJson, wrap, error, rateLimited } from '../_lib/http.js';import { getSessionUser, authenticateBearer, extractBearer, hasScope } from '../_lib/auth.js';import { limits } from '../_lib/rate-limit.js';import { assertSafePublicUrl } from '../_lib/ssrf-guard.js';@@ -93,7 +93,7 @@ async function handleSubmit(req, res) {if (!userId) return error(res, 401, 'unauthorized', 'sign in or provide a valid bearer token');const rl = await limits.upload(userId);- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests — try again shortly');+ if (!rl.success) return rateLimited(res, rl, 'too many requests — try again shortly');const body = parse(submitSchema, await readJson(req, 12 * 1024 * 1024));diff --git a/api/subscriptions.js b/api/subscriptions.jsindex 0bf4f139b..648c7b360 100644--- a/api/subscriptions.js+++ b/api/subscriptions.js@@ -8,7 +8,7 @@import { sql } from './_lib/db.js';import { getSessionUser, authenticateBearer, extractBearer } from './_lib/auth.js';-import { cors, json, method, wrap, error, readJson } from './_lib/http.js';+import { cors, json, method, wrap, error, readJson, rateLimited } from './_lib/http.js';import { limits, clientIp } from './_lib/rate-limit.js';import { z } from 'zod';import { parse } from './_lib/validate.js';@@ -32,7 +32,7 @@ export default wrap(async (req, res) => {const userId = session?.id ?? bearer.userId;const rl = await limits.authIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);// ── POST: create subscription ─────────────────────────────────────────────diff --git a/api/subscriptions/index.js b/api/subscriptions/index.jsindex 7034a8de1..abc8c1bc9 100644--- a/api/subscriptions/index.js+++ b/api/subscriptions/index.js@@ -11,7 +11,7 @@import { z } from 'zod';import { sql } from '../_lib/db.js';import { getSessionUser } from '../_lib/auth.js';-import { cors, json, method, wrap, error, readJson } from '../_lib/http.js';+import { cors, json, method, wrap, error, readJson, rateLimited } from '../_lib/http.js';import { parse } from '../_lib/validate.js';import { limits, clientIp } from '../_lib/rate-limit.js';import { chargeSubscription } from '../_lib/subscription-billing.js';@@ -42,7 +42,7 @@ async function handleMine(req, res) {const ip = clientIp(req);const rl = await limits.publicIp(ip);- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const rows = await sql`SELECT@@ -66,7 +66,7 @@ async function handleSubscribe(req, res) {const ip = clientIp(req);const rl = await limits.publicIp(ip);- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const body = parse(subscribeSchema, await readJson(req));diff --git a/api/subscriptions/plans.js b/api/subscriptions/plans.jsindex 5cdad4870..5347ab29e 100644--- a/api/subscriptions/plans.js+++ b/api/subscriptions/plans.js@@ -11,7 +11,7 @@import { z } from 'zod';import { sql } from '../_lib/db.js';import { getSessionUser } from '../_lib/auth.js';-import { cors, json, method, wrap, error, readJson } from '../_lib/http.js';+import { cors, json, method, wrap, error, readJson, rateLimited } from '../_lib/http.js';import { parse } from '../_lib/validate.js';import { limits, clientIp } from '../_lib/rate-limit.js';@@ -49,7 +49,7 @@ export default wrap(async (req, res) => {async function handleList(req, res) {const ip = clientIp(req);const rl = await limits.publicIp(ip);- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const params = new URL(req.url, 'http://x').searchParams;const creatorId = params.get('creator_id');@@ -95,7 +95,7 @@ async function handleCreate(req, res) {const ip = clientIp(req);const rl = await limits.publicIp(ip);- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const body = parse(planSchema, await readJson(req));diff --git a/api/threews/me.js b/api/threews/me.jsindex 2bde77939..2e690a69e 100644--- a/api/threews/me.js+++ b/api/threews/me.js@@ -6,7 +6,7 @@import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';import { sql } from '../_lib/db.js';-import { cors, error, json, method, wrap } from '../_lib/http.js';+import { cors, error, json, method, wrap, rateLimited } from '../_lib/http.js';import { limits, clientIp } from '../_lib/rate-limit.js';import { env } from '../_lib/env.js';import { PARENT_LABEL, fullDomain } from '../_lib/threews-sns.js';@@ -24,7 +24,7 @@ export default wrap(async (req, res) => {if (!method(req, res, ['GET'])) return;const rl = await limits.authIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const auth = await resolveAuth(req);if (!auth) return error(res, 401, 'unauthorized', 'sign in required');diff --git a/api/threews/subdomain.js b/api/threews/subdomain.jsindex fdc275cb2..e1c4f6ae0 100644--- a/api/threews/subdomain.js+++ b/api/threews/subdomain.js@@ -18,7 +18,7 @@import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';import { sql } from '../_lib/db.js';-import { cors, error, json, method, readJson, wrap } from '../_lib/http.js';+import { cors, error, json, method, readJson, wrap, rateLimited } from '../_lib/http.js';import { limits, clientIp } from '../_lib/rate-limit.js';import { env } from '../_lib/env.js';import {@@ -210,7 +210,7 @@ export default wrap(async (req, res) => {if (!method(req, res, ['GET', 'POST', 'DELETE'])) return;const rl = await limits.authIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);if (req.method === 'GET') return handleCheck(req, res);diff --git a/api/token/[action].js b/api/token/[action].jsindex 220d765ba..5e203c4ba 100644--- a/api/token/[action].js+++ b/api/token/[action].js@@ -14,7 +14,7 @@import { z } from 'zod';import { env } from '../_lib/env.js';import { getSessionUser } from '../_lib/auth.js';-import { cors, error, json, method, readJson, wrap } from '../_lib/http.js';+import { cors, error, json, method, readJson, wrap, rateLimited } from '../_lib/http.js';import { limits, clientIp } from '../_lib/rate-limit.js';import { parse } from '../_lib/validate.js';import { publicConfig } from '../_lib/token/config.js';@@ -52,7 +52,7 @@ async function handlePrice(req, res) {if (cors(req, res, { methods: 'GET,OPTIONS' })) return;if (!method(req, res, ['GET'])) return;const rl = await limits.tokenPriceIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const url = new URL(req.url, 'http://x');const price = await getTokenPriceUsd();const usdParam = url.searchParams.get('usd');@@ -87,7 +87,7 @@ async function handleQuote(req, res) {const user = await getSessionUser(req, res);if (!user) return error(res, 401, 'unauthorized', 'sign in required');const rl = await limits.tokenQuote(user.id);- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const body = parse(quoteSchema, await readJson(req));const purpose = PURPOSES[body.purpose];@@ -146,7 +146,7 @@ async function handleSettle(req, res) {const user = await getSessionUser(req, res);if (!user) return error(res, 401, 'unauthorized', 'sign in required');const rl = await limits.tokenSettle(user.id);- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const body = parse(settleSchema, await readJson(req));const result = await verifyAndSettlePayment({diff --git a/api/tts/edge.js b/api/tts/edge.jsindex 5a7fc9b9b..d5e570b18 100644--- a/api/tts/edge.js+++ b/api/tts/edge.js@@ -15,7 +15,7 @@import WebSocket from 'ws';import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';-import { cors, method, wrap, error, readJson } from '../_lib/http.js';+import { cors, method, wrap, error, readJson, rateLimited } from '../_lib/http.js';import { limits } from '../_lib/rate-limit.js';import { sha256 } from '../_lib/crypto.js';import { headObject, getObjectBuffer, putObject } from '../_lib/r2.js';@@ -142,7 +142,7 @@ export default wrap(async (req, res) => {if (!rl.success) {const retryAfter = Math.max(1, Math.ceil((rl.reset - Date.now()) / 1000));res.setHeader('retry-after', String(retryAfter));- return error(res, 429, 'rate_limited', 'Too many TTS requests', { retry_after: retryAfter });+ return rateLimited(res, rl, 'Too many TTS requests', { retry_after: retryAfter });}const body = await readJson(req);diff --git a/api/tx/explain.js b/api/tx/explain.jsindex fc0287377..423f80b69 100644--- a/api/tx/explain.js+++ b/api/tx/explain.js@@ -1,6 +1,6 @@import { Interface } from 'ethers';import { env } from '../_lib/env.js';-import { wrap, cors, error, json, readJson, method } from '../_lib/http.js';+import { wrap, cors, error, json, readJson, method, rateLimited } from '../_lib/http.js';import { limits, clientIp } from '../_lib/rate-limit.js';const ERC20_TRANSFER_TOPIC =@@ -14,7 +14,7 @@ export default wrap(async (req, res) => {if (!method(req, res, ['POST'])) return;const rl = await limits.authIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);let body;try {diff --git a/api/tx/solana/[action].js b/api/tx/solana/[action].jsindex 9abfe6af5..9f07c99b6 100644--- a/api/tx/solana/[action].js+++ b/api/tx/solana/[action].js@@ -8,7 +8,7 @@ import {createTransferInstruction, getMint, getAssociatedTokenAddress,createAssociatedTokenAccountInstruction,} from '@solana/spl-token';-import { cors, json, method, readJson, wrap, error } from '../../_lib/http.js';+import { cors, json, method, readJson, wrap, error, rateLimited } from '../../_lib/http.js';import { getSessionUser } from '../../_lib/auth.js';import { limits, clientIp } from '../../_lib/rate-limit.js';import { parse } from '../../_lib/validate.js';@@ -34,7 +34,7 @@ async function handleBuildTransfer(req, res) {const user = await getSessionUser(req);if (!user) return error(res, 401, 'unauthorized', 'sign in required');const rl = await limits.authIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const { sender, recipient, amount, token, memo, network } = parse(transferSchema, await readJson(req));@@ -104,7 +104,7 @@ async function handleBuildSwap(req, res) {const user = await getSessionUser(req);if (!user) return error(res, 401, 'unauthorized', 'sign in required');const rl = await limits.authIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const { sender, inputMint, outputMint, amount, slippageBps } = parse(swapSchema, await readJson(req));diff --git a/api/users/[username].js b/api/users/[username].jsindex 742840eb4..82f667eff 100644--- a/api/users/[username].js+++ b/api/users/[username].js@@ -1,5 +1,5 @@import { sql } from '../_lib/db.js';-import { cors, json, method, wrap, error } from '../_lib/http.js';+import { cors, json, method, wrap, error, rateLimited } from '../_lib/http.js';import { limits, clientIp } from '../_lib/rate-limit.js';import { publicUrl } from '../_lib/r2.js';@@ -13,7 +13,7 @@ export default wrap(async (req, res) => {}const rl = await limits.authIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const [user] = await sql`select id, display_name, username, created_at, referral_code, wallet_addressdiff --git a/api/users/[username]/avatar.js b/api/users/[username]/avatar.jsindex 44cbe48de..57d2c44a9 100644--- a/api/users/[username]/avatar.js+++ b/api/users/[username]/avatar.js@@ -27,7 +27,7 @@// Visage style) who want to render it themselves.import { sql } from '../../_lib/db.js';-import { cors, json, method, wrap, error } from '../../_lib/http.js';+import { cors, json, method, wrap, error, rateLimited } from '../../_lib/http.js';import { limits, clientIp } from '../../_lib/rate-limit.js';import { publicUrl } from '../../_lib/r2.js';import { env } from '../../_lib/env.js';@@ -61,7 +61,7 @@ export default wrap(async (req, res) => {}const rl = await limits.authIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const url = new URL(req.url, 'http://x');const lod = url.searchParams.get('lod');diff --git a/api/users/by-subdomain.js b/api/users/by-subdomain.jsindex 221cc023e..bf7d95d93 100644--- a/api/users/by-subdomain.js+++ b/api/users/by-subdomain.js@@ -5,7 +5,7 @@// when accessed via a SNS-resolved Brave URL.import { sql } from '../_lib/db.js';-import { cors, error, json, method, wrap } from '../_lib/http.js';+import { cors, error, json, method, wrap, rateLimited } from '../_lib/http.js';import { limits, clientIp } from '../_lib/rate-limit.js';import { PARENT_LABEL, normalizeLabel } from '../_lib/threews-sns.js';@@ -14,7 +14,7 @@ export default wrap(async (req, res) => {if (!method(req, res, ['GET'])) return;const rl = await limits.snsResolve(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const url = new URL(req.url, 'http://x');const label = normalizeLabel(url.searchParams.get('label'));diff --git a/api/users/earnings.js b/api/users/earnings.jsindex 46f5bdb89..8eba2f5be 100644--- a/api/users/earnings.js+++ b/api/users/earnings.js@@ -1,6 +1,6 @@import { sql } from '../_lib/db.js';import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';-import { cors, json, error, method, wrap } from '../_lib/http.js';+import { cors, json, error, method, wrap, rateLimited } from '../_lib/http.js';import { limits, clientIp } from '../_lib/rate-limit.js';export default wrap(async (req, res) => {@@ -13,7 +13,7 @@ export default wrap(async (req, res) => {const userId = session?.id ?? bearer.userId;const rl = await limits.authIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const rows = await sql`SELECTdiff --git a/api/users/me/bookmarks.js b/api/users/me/bookmarks.jsindex e8a214277..4bbfd2bba 100644--- a/api/users/me/bookmarks.js+++ b/api/users/me/bookmarks.js@@ -6,7 +6,7 @@import { sql } from '../../_lib/db.js';import { authenticateBearer, extractBearer, getSessionUser } from '../../_lib/auth.js';-import { cors, error, json, method, wrap } from '../../_lib/http.js';+import { cors, error, json, method, wrap, rateLimited } from '../../_lib/http.js';import { clientIp, limits } from '../../_lib/rate-limit.js';import { publicUrl } from '../../_lib/r2.js';@@ -20,7 +20,7 @@ export default wrap(async (req, res) => {if (!userId) return error(res, 401, 'unauthorized', 'sign in required');const rl = await limits.widgetRead(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const rows = await sql`SELECTdiff --git a/api/users/me/purchased-skills.js b/api/users/me/purchased-skills.jsindex ffb612e45..e746393a6 100644--- a/api/users/me/purchased-skills.js+++ b/api/users/me/purchased-skills.js@@ -5,7 +5,7 @@import { sql } from '../../_lib/db.js';import { authenticateBearer, extractBearer, getSessionUser } from '../../_lib/auth.js';-import { cors, error, json, method, wrap } from '../../_lib/http.js';+import { cors, error, json, method, wrap, rateLimited } from '../../_lib/http.js';import { clientIp, limits } from '../../_lib/rate-limit.js';export default wrap(async (req, res) => {@@ -18,7 +18,7 @@ export default wrap(async (req, res) => {if (!userId) return error(res, 401, 'unauthorized', 'sign in required');const rl = await limits.widgetRead(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const purchases = await sql`SELECTdiff --git a/api/users/referrals.js b/api/users/referrals.jsindex 0a5a6909e..7476fc290 100644--- a/api/users/referrals.js+++ b/api/users/referrals.js@@ -1,6 +1,6 @@import { sql } from '../_lib/db.js';import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';-import { cors, json, error, method, wrap } from '../_lib/http.js';+import { cors, json, error, method, wrap, rateLimited } from '../_lib/http.js';import { limits, clientIp } from '../_lib/rate-limit.js';export default wrap(async (req, res) => {@@ -13,7 +13,7 @@ export default wrap(async (req, res) => {const userId = session?.id ?? bearer.userId;const rl = await limits.authIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const [user] = await sql`SELECTdiff --git a/api/v1/agents/[caip].js b/api/v1/agents/[caip].jsindex 9d8ab0084..059368bf9 100644--- a/api/v1/agents/[caip].js+++ b/api/v1/agents/[caip].js@@ -25,7 +25,7 @@* Errors: 400 invalid_caip, 404 not_found, 502 upstream, 429 rate_limited.*/-import { wrap, cors, method, json, error } from '../../_lib/http.js';+import { wrap, cors, method, json, error, rateLimited } from '../../_lib/http.js';import { limits, clientIp } from '../../_lib/rate-limit.js';import { resolveOnChainAgent, resolveURI } from '../../_lib/onchain.js';@@ -40,7 +40,7 @@ export default wrap(async (req, res) => {if (!method(req, res, ['GET'])) return;const rl = await limits.mcpIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const raw = decodeURIComponent(req.query?.caip || '');const m = CAIP_RE.exec(raw);diff --git a/api/wallet/balances.js b/api/wallet/balances.jsindex e27391798..01470935d 100644--- a/api/wallet/balances.js+++ b/api/wallet/balances.js@@ -2,7 +2,7 @@// body: { chain: 'solana'|'evm', address: string }// → { chain, address, native: {symbol, amount, usd}, tokens: [{symbol, amount, usd, logo}] }-import { cors, json, method, readJson, wrap, error } from '../_lib/http.js';+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 { z } from 'zod';@@ -17,7 +17,7 @@ export default wrap(async (req, res) => {if (!method(req, res, ['POST'])) return;const rl = await limits.authIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);let body;try {diff --git a/api/watsonx/embed.js b/api/watsonx/embed.jsindex 9dba5f8f0..220147147 100644--- a/api/watsonx/embed.js+++ b/api/watsonx/embed.js@@ -14,7 +14,7 @@// instead of inventing vectors. Every successful vector is a real Granite call.import { createHash } from 'node:crypto';-import { cors, method, readJson, error, json, wrap } from '../_lib/http.js';+import { cors, method, readJson, error, json, wrap, rateLimited } from '../_lib/http.js';import { watsonxConfig, watsonxEmbed } from '../_lib/watsonx.js';import { limits, clientIp } from '../_lib/rate-limit.js';@@ -77,13 +77,11 @@ export default wrap(async function handler(req, res) {const ip = clientIp(req);const perIp = await limits.watsonxEmbedIp(ip);if (!perIp.success) {- return error(res, 429, 'rate_limited', 'too many embedding requests — slow down', {- retryAfter: Math.ceil((perIp.reset - Date.now()) / 1000),- });+ return rateLimited(res, perIp, 'too many embedding requests — slow down');}const global = await limits.watsonxEmbedGlobal();if (!global.success) {- return error(res, 429, 'rate_limited', 'embedding capacity reached — try again shortly');+ return rateLimited(res, global, 'embedding capacity reached — try again shortly');}let body;diff --git a/api/widgets/[id].js b/api/widgets/[id].jsindex cd90caf20..0745f846c 100644--- a/api/widgets/[id].js+++ b/api/widgets/[id].js@@ -15,7 +15,7 @@ import { z } from 'zod';import { sql } from '../_lib/db.js';import { getSessionUser, authenticateBearer, extractBearer, hasScope } from '../_lib/auth.js';-import { cors, json, method, readJson, wrap, error } from '../_lib/http.js';+import { cors, json, method, readJson, wrap, error, rateLimited } from '../_lib/http.js';import { parse } from '../_lib/validate.js';import { limits, clientIp } from '../_lib/rate-limit.js';import { decorate } from './index.js';@@ -41,7 +41,7 @@ export default wrap(async (req, res) => {if (req.method === 'GET') {const rl = await limits.widgetRead(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);// Public showcase fixtures — short-circuit DB lookup so the gallery// renders without seeded rows in any environment.@@ -84,7 +84,7 @@ export default wrap(async (req, res) => {}const rl = await limits.widgetWrite(auth.userId);- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);if (req.method === 'PATCH') {const patch = parse(patchSchema, await readJson(req));diff --git a/api/widgets/[id]/[action].js b/api/widgets/[id]/[action].jsindex 7999f9eab..31cedfd56 100644--- a/api/widgets/[id]/[action].js+++ b/api/widgets/[id]/[action].js@@ -9,7 +9,7 @@ import { z } from 'zod';import { sql } from '../../_lib/db.js';import { getSessionUser, authenticateBearer, extractBearer, hasScope } from '../../_lib/auth.js';-import { cors, json, method, readJson, wrap, error } from '../../_lib/http.js';+import { cors, json, method, readJson, wrap, error, rateLimited } from '../../_lib/http.js';import { parse } from '../../_lib/validate.js';import { limits, clientIp } from '../../_lib/rate-limit.js';import { captureException } from '../../_lib/sentry.js';@@ -194,11 +194,7 @@ async function handleChat(req, res) {const ip = clientIp(req);const rl = await limits.widgetChat({ ip, widgetId, perMinute });if (!rl.success) {- const retryAfter = Math.max(1, Math.ceil((rl.reset - Date.now()) / 1000));- res.setHeader('retry-after', String(retryAfter));- return error(res, 429, 'rate_limited', 'too many messages — slow down', {- retry_after: retryAfter,- });+ return rateLimited(res, rl, 'too many messages — slow down');}}@@ -848,7 +844,7 @@ async function handleDuplicate(req, res) {}const rl = await limits.widgetWrite(auth.userId);- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const [src] = await sql`select id, type, name, config, avatar_id, is_public@@ -1360,7 +1356,7 @@ async function handleKnowledge(req, res) {}const rl = await limits.upload(auth.userId);- if (!rl.success) return error(res, 429, 'rate_limited', 'too many uploads — try again later');+ if (!rl.success) return rateLimited(res, rl, 'too many uploads — try again later');let body;try {diff --git a/api/widgets/[id]/duplicate.js b/api/widgets/[id]/duplicate.jsindex 613d1db86..75deb3156 100644--- a/api/widgets/[id]/duplicate.js+++ b/api/widgets/[id]/duplicate.js@@ -1,6 +1,6 @@import { sql } from '../../_lib/db.js';import { getSessionUser } from '../../_lib/auth.js';-import { cors, error, json, method, wrap } from '../../_lib/http.js';+import { cors, error, json, method, wrap, rateLimited } from '../../_lib/http.js';import { limits, clientIp } from '../../_lib/rate-limit.js';export default wrap(async (req, res) => {@@ -11,7 +11,7 @@ export default wrap(async (req, res) => {if (!user) return error(res, 401, 'unauthorized', 'sign in required');const rl = await limits.widgetWrite(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const url = new URL(req.url, 'http://x');const parts = url.pathname.split('/').filter(Boolean);diff --git a/api/widgets/index.js b/api/widgets/index.jsindex d8d43068f..db3831e11 100644--- a/api/widgets/index.js+++ b/api/widgets/index.js@@ -13,7 +13,7 @@ import { z } from 'zod';import { sql } from '../_lib/db.js';import { getSessionUser, authenticateBearer, extractBearer, hasScope } from '../_lib/auth.js';-import { cors, json, method, readJson, wrap, error } from '../_lib/http.js';+import { cors, json, method, readJson, wrap, error, rateLimited } from '../_lib/http.js';import { parse } from '../_lib/validate.js';import { limits, clientIp } from '../_lib/rate-limit.js';import { publicUrl } from '../_lib/r2.js';@@ -36,7 +36,7 @@ export default wrap(async (req, res) => {if (req.method === 'GET') {const rl = await limits.widgetRead(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const rows = await sql`select w.id, w.user_id, w.avatar_id, w.type, w.name, w.config, w.is_public,@@ -54,7 +54,7 @@ export default wrap(async (req, res) => {// POSTconst rl = await limits.widgetWrite(auth.userId);- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const body = parse(createBody, await readJson(req));diff --git a/api/wk.js b/api/wk.jsindex b37696f00..89dcee381 100644--- a/api/wk.js+++ b/api/wk.js@@ -518,6 +518,14 @@ function handleX402Discovery(req, res) {serviceName: 'three.ws Pay-As-You-Learn Tutor',tags: ['tutor', 'education', 'llm', 'explain', 'pay-per-call'],}),+ cryptoIntel: withService({+ serviceName: 'three.ws Crypto Intel',+ tags: ['crypto', 'market', 'signal', 'agent-exchange', 'solana'],+ }),+ avatarShop: withService({+ serviceName: 'three.ws Avatar Shop',+ tags: ['3d', 'avatar', 'cosmetic', 'shop', 'wearable'],+ }),};// USE-13: per-tool MCP catalog entries. Each priced tool is its own@@ -1203,6 +1211,83 @@ function handleX402Discovery(req, res) {}),};})(),+ (() => {+ const url = `${origin}/api/x402/crypto-intel`;+ const accepts = acceptsForPrice('10000', url);+ return {+ path: '/api/x402/crypto-intel',+ url,+ method: 'POST',+ description:+ 'three.ws Crypto Intel — Agent-to-Agent crypto intelligence feed. Pay $0.01 USDC per call to receive a live market signal (bullish / bearish / neutral) with current price, 24 h change, and a two-sentence rationale. Powered by CoinGecko live prices. Powers the three.ws agent-exchange demo where two 3D avatars trade real intel for real USDC settled on-chain.',+ mimeType: 'application/json',+ serviceName: routeMeta.cryptoIntel.serviceName,+ tags: routeMeta.cryptoIntel.tags,+ iconUrl: routeMeta.cryptoIntel.iconUrl,+ accepts,+ extensions: extensionsForAccepts(accepts, {+ method: 'POST',+ discoverable: true,+ input: { topic: 'sol' },+ inputSchema: {+ type: 'object',+ properties: {+ topic: {+ type: 'string',+ description:+ 'Token ticker or CoinGecko id: btc, sol, eth, doge, …',+ default: 'sol',+ },+ },+ },+ }),+ };+ })(),+ (() => {+ // Avatar Shop pricing is per-rarity ($0.25 common → $3.00+ // legendary). The catalog advertises the rare tier ('500000' =+ // $0.50) as a representative price; the live 402 challenge always+ // quotes the exact USDC amount for the requested cosmetic id.+ const url = `${origin}/api/x402/cosmetic-purchase`;+ const accepts = acceptsForPrice('500000', url);+ return {+ path: '/api/x402/cosmetic-purchase',+ url,+ method: 'GET',+ description:+ 'three.ws Avatar Shop — pay once in USDC to unlock a premium avatar cosmetic (skin or emote) for an account. Pay on Base or Solana; the cosmetic is recorded to the buyer-specified account and is wearable across /play and /walk. Wallets that already purchased an item re-confirm for free by signing in with SIWX (CAIP-122). Price varies by rarity ($0.25–$3.00 USDC).',+ mimeType: 'application/json',+ serviceName: routeMeta.avatarShop.serviceName,+ tags: routeMeta.avatarShop.tags,+ iconUrl: routeMeta.avatarShop.iconUrl,+ accepts,+ extensions: extensionsForAccepts(accepts, {+ method: 'GET',+ discoverable: true,+ input: { id: 'skin-midnight', account: 'g_5f3c9a21b8' },+ inputSchema: {+ type: 'object',+ required: ['id', 'account'],+ properties: {+ id: {+ type: 'string',+ minLength: 1,+ maxLength: 64,+ description:+ 'Premium cosmetic id from /api/cosmetics/catalog.',+ },+ account: {+ type: 'string',+ minLength: 3,+ maxLength: 64,+ description:+ 'Account the cosmetic is granted to — a Solana wallet address or a guest id (g_…).',+ },+ },+ },+ }),+ };+ })(),// USE-13: one Bazaar catalog row per priced MCP tool. The shared// `/api/mcp` resource above is the transport entry; these are// the individual paid tools facilitators index by toolName.diff --git a/api/world/[action].js b/api/world/[action].jsindex c8a8c6fc3..148840f4a 100644--- a/api/world/[action].js+++ b/api/world/[action].js@@ -14,7 +14,7 @@//// Storage lives in api/_lib/world-store.js (Postgres index + R2 blob offload).-import { cors, json, method, wrap, error, readJson } from '../_lib/http.js';+import { cors, json, method, wrap, error, readJson, rateLimited } from '../_lib/http.js';import { limits, clientIp } from '../_lib/rate-limit.js';import { extractBearer } from '../_lib/auth.js';import { resolveAccount } from '../_lib/account-auth.js';@@ -50,7 +50,7 @@ async function handleLoad(req, res) {if (!method(req, res, ['GET'])) return;const rl = await limits.publicIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const worldId = new URL(req.url, 'http://x').searchParams.get('worldId') || '';if (!isValidWorldId(worldId)) return error(res, 400, 'validation_error', 'invalid or missing worldId');@@ -85,7 +85,7 @@ async function handleSave(req, res) {if (!account) return error(res, 401, 'unauthorized', 'authentication required to write a world');writer = account.userId;const rl = await limits.prefsWrite(account.userId);- if (!rl.success) return error(res, 429, 'rate_limited', 'too many world saves');+ if (!rl.success) return rateLimited(res, rl, 'too many world saves');}let body;diff --git a/api/x/post.js b/api/x/post.jsindex c8ce34a3d..04b19a942 100644--- a/api/x/post.js+++ b/api/x/post.js@@ -3,7 +3,7 @@// One of `text` (single tweet) or `thread_parts` (array → thread) is required.import { getSessionUser } from '../_lib/auth.js';-import { cors, method, wrap, error, readJson, json } from '../_lib/http.js';+import { cors, method, wrap, error, readJson, json, rateLimited } from '../_lib/http.js';import { requireCsrf } from '../_lib/csrf.js';import { limits, clientIp } from '../_lib/rate-limit.js';import { publishTweet, XPostError } from '../_lib/x-post.js';@@ -21,7 +21,7 @@ export default wrap(async (req, res) => {if (!(await requireCsrf(req, res, user.id))) return;const rl = await limits.authIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const body = await readJson(req);const text = typeof body?.text === 'string' ? body.text : '';diff --git a/api/x402-checkout.js b/api/x402-checkout.jsindex 55f219145..02c0e838c 100644--- a/api/x402-checkout.js+++ b/api/x402-checkout.js@@ -37,7 +37,7 @@ import {createTransferCheckedInstruction,getMint,} from '@solana/spl-token';-import { cors, json, method, readJson, wrap, error } from './_lib/http.js';+import { cors, json, method, readJson, wrap, error, rateLimited } from './_lib/http.js';import { parse } from './_lib/validate.js';import { limits, clientIp } from './_lib/rate-limit.js';import {@@ -140,7 +140,7 @@ async function handlePrepare(req, res) {// throttle anonymous callers to stop quota-drain / cost amplification against// the (potentially paid) upstream RPC.const rl = await limits.x402PayIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many prepare requests');+ if (!rl.success) return rateLimited(res, rl, 'too many prepare requests');const body = parse(prepareSchema, await readJson(req));const { accept, buyer } = body;diff --git a/api/x402-skus.js b/api/x402-skus.jsindex 5cabed49e..742e5074e 100644--- a/api/x402-skus.js+++ b/api/x402-skus.js@@ -14,7 +14,7 @@import { z } from 'zod';import { sql } from './_lib/db.js';import { getSessionUser } from './_lib/auth.js';-import { cors, json, readJson, wrap, error } from './_lib/http.js';+import { cors, json, readJson, wrap, error, rateLimited } from './_lib/http.js';import { parse } from './_lib/validate.js';import { clientIp, limits } from './_lib/rate-limit.js';@@ -124,7 +124,7 @@ async function handleCreate(req, res) {const user = await getSessionUser(req, res);if (!user) return error(res, 401, 'unauthorized', 'sign in required');const rl = await limits.authIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const body = parse(createSchema, await readJson(req));@@ -152,7 +152,7 @@ async function handleUpdate(req, res) {const user = await getSessionUser(req, res);if (!user) return error(res, 401, 'unauthorized', 'sign in required');const rl = await limits.authIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const id = req.query?.id;if (!id) return error(res, 400, 'missing_id', 'query param `id` required');diff --git a/api/x402/my-receipts.js b/api/x402/my-receipts.jsindex c7fb16518..d54afe15a 100644--- a/api/x402/my-receipts.js+++ b/api/x402/my-receipts.js@@ -19,7 +19,7 @@ import { createPublicClient } from 'viem';import { mainnet } from 'viem/chains';import { evmTransport } from '../_lib/evm/rpc.js';-import { cors, error, json, method } from '../_lib/http.js';+import { cors, error, json, method, rateLimited } from '../_lib/http.js';import { limits, clientIp } from '../_lib/rate-limit.js';import { listReceiptsForPayer } from '../_lib/x402/receipt-storage.js';import { verifySiwsSignature } from '../_lib/siws.js';@@ -65,7 +65,7 @@ export default async function handler(req, res) {if (!method(req, res, ['GET'])) return;const rl = await limits.publicIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);const url = new URL(req.url, 'http://x');const address = String(url.searchParams.get('address') || '').trim();diff --git a/api/x402/pay-by-name.js b/api/x402/pay-by-name.jsindex 6af1df4dd..73d7aee5b 100644--- a/api/x402/pay-by-name.js+++ b/api/x402/pay-by-name.js@@ -37,7 +37,7 @@ import {import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';import { sql } from '../_lib/db.js';-import { cors, error, json, method, readJson, wrap } from '../_lib/http.js';+import { cors, error, json, method, readJson, wrap, rateLimited } from '../_lib/http.js';import { limits, clientIp } from '../_lib/rate-limit.js';import { solanaConnection, loadAgentForSigning } from '../_lib/agent-pumpfun.js';import { PARENT_LABEL } from '../_lib/threews-sns.js';@@ -289,7 +289,7 @@ export default wrap(async (req, res) => {if (!method(req, res, ['GET', 'POST'])) return;const rl = await limits.authIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);if (req.method === 'GET') return handleResolve(req, res);diff --git a/api/x402/vanity.js b/api/x402/vanity.jsindex c0e1e4f20..2fa86ccad 100644--- a/api/x402/vanity.js+++ b/api/x402/vanity.js@@ -22,7 +22,7 @@// (USDC). verifyPayment / settlePayment in x402-spec.js route per network. The// Solana entry is omitted when X402_PAY_TO_SOLANA is unset so the 402 stays valid.-import { wrap, cors, error } from '../_lib/http.js';+import { wrap, cors, error, rateLimited } from '../_lib/http.js';import {NETWORK_BASE_MAINNET,NETWORK_SOLANA_MAINNET,@@ -277,7 +277,7 @@ export default wrap(async (req, res) => {// Light rate limit on the public (pre-payment) path so the 402 challenge// and parameter validation can't be hammered. The grind itself is paywalled.const rl = await limits.publicIp(clientIp(req));- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!rl.success) return rateLimited(res, rl);// Validate the pattern up front so a malformed request is rejected before we// ever quote a price. A pattern-free probe is allowed (combinedLength 0).diff --git a/mcp-server/README.md b/mcp-server/README.mdindex 04a95b376..cfaf0b890 100644--- a/mcp-server/README.md+++ b/mcp-server/README.md@@ -39,7 +39,7 @@ Restart Claude Desktop. The four tools appear immediately — no install step re| `get_pose_seed` | $0.001 | Deterministic seed + full Euler-rotation pose map (radians) for the three.ws pose-studio mannequin, matched from the in-repo preset library. Includes a `previewUrl` at `https://three.ws/pose?seed=…&preset=…`. || `pump_snapshot` | $0.005 | Live token snapshot — USD price (Jupiter), 24h volume + pair (Dexscreener), mint metadata + image (pump.fun frontend-api-v3), and on-chain top-holder distribution (Solana RPC). Adds Helius DAS data when `HELIUS_API_KEY` is set. || `agent_reputation` | $0.01 | ERC-8004 reputation: `getReputation`, `getTotalStake`, and the latest `ReputationSubmitted` / `ReputationStaked` events from the canonical ReputationRegistry on the requested chain (default Base). Resolves `agentId` from a wallet address automatically. |-| `vanity_grinder` | up to $0.50 | Solana keypair whose base58 address starts with `prefix` (and optionally ends with `suffix`). Returns the full base58 secret key — treat as a secret. Actual settled USDC scales with iterations: `$0.01 base + $0.0000001/attempt`, capped at $0.50. |+| `vanity_grinder` | $0.05 | Solana keypair whose base58 address starts with `prefix` (and optionally ends with `suffix`). Returns the full base58 secret key — treat as a secret. Flat `exact` price (override with `MCP_VANITY_PRICE_USD`); a difficulty guard rejects prefixes too long to mine within the iteration cap. |---@@ -175,7 +175,9 @@ The server is the x402 **resource server**. On each tool call:4. Client retries the `tools/call` with `_meta["x402/payment"]` attached.5. Server verifies + settles via the configured facilitator, runs the tool, and returns the result with `_meta["x402/payment-response"]`.-`vanity_grinder` uses the x402 `upto` scheme — the client authorizes up to $0.50 and the server settles the actual metered amount after mining completes.+Every tool settles in USDC on **Solana mainnet** with the `exact` scheme (`@x402/svm` ships no `upto`/metered scheme). Each tool quotes a fixed price; there is no post-hoc metering.++A successful result carries the tool's JSON in two forms: `content[0].text` (for text-only clients) and `structuredContent` (MCP 2025-06-18 structured output — a ready-to-use object). A tool-level error sets `isError: true`, and the x402 wrapper **cancels rather than settles** the payment, so failed calls do not bill the caller.---@@ -184,8 +186,8 @@ The server is the x402 **resource server**. On each tool call:```┌─────────────────┐ ┌─────────────────────┐ ┌──────────────────────┐│ Claude Desktop │────▶│ @3d-agent/mcp │────▶│ x402 facilitator │-│ / Cursor / │ │ (stdio transport) │ │ (CDP for Base, │-│ your agent │ │ │ │ PayAI for Solana) │+│ / Cursor / │ │ (stdio transport) │ │ (PayAI — Solana │+│ your agent │ │ │ │ USDC, exact) │└─────────────────┘ └─────────────────────┘ └──────────────────────┘```diff --git a/mcp-server/src/payments.js b/mcp-server/src/payments.jsindex 7b943d89c..c1731bb92 100644--- a/mcp-server/src/payments.js+++ b/mcp-server/src/payments.js@@ -222,10 +222,7 @@ export function paid(cfg, handler) {return wrap(async (args, context) => {const result = await handler(args, context);- const text = typeof result === 'string' ? result : JSON.stringify(result);- return {- content: [{ type: 'text', text }],- };+ return buildToolResult(result);});})();return wrapperPromise;@@ -239,6 +236,44 @@ export function paid(cfg, handler) {};}+/**+ * Build the MCP `CallToolResult` envelope from a handler's return value.+ *+ * This is the single place every paid tool's output is shaped, so all 15 tools+ * get the same modern MCP contract for free:+ *+ * - `content[0].text` — the JSON (or raw string) blob. Always present, so+ * pre-2025-06-18 clients that only read text keep working unchanged.+ * - `structuredContent` — the handler's object verbatim, surfaced as MCP+ * structured tool output (spec 2025-06-18). Clients that support it get a+ * ready-to-use object and skip the `JSON.parse(content[0].text)` dance.+ * Only emitted for plain objects (the spec requires an object, not an+ * array or scalar); string/array returns fall back to text-only.+ * - `isError: true` — set ONLY for the explicit `toolError()` envelope+ * (`ok === false`). This flags the failure to the LLM AND, via the x402+ * payment wrapper, cancels the payment instead of settling it — so a caller+ * is never charged for an invalid-input / provider / timeout error. It is+ * deliberately NOT set for partial-data successes (e.g. a snapshot whose+ * `price` sub-field carries `{ error }` but whose overall call succeeded),+ * which have no top-level `ok: false`.+ *+ * @param {unknown} result — whatever the tool handler returned+ * @returns {{ content: Array<{type:'text',text:string}>, structuredContent?: object, isError?: true }}+ */+export function buildToolResult(result) {+ const text = typeof result === 'string' ? result : JSON.stringify(result);+ const envelope = { content: [{ type: 'text', text }] };+ const isPlainObject =+ result !== null && typeof result === 'object' && !Array.isArray(result);+ if (isPlainObject) {+ envelope.structuredContent = result;+ if (result.ok === false) {+ envelope.isError = true;+ }+ }+ return envelope;+}+/*** Standard tool error envelope. Every tool's error path returns this shape so* MCP clients can branch on a stable `{ ok: false, error: <code>, message }`diff --git a/pages/dashboard-next/holders.html b/pages/dashboard-next/holders.htmlnew file mode 100644index 000000000..5f3ea17db--- /dev/null+++ b/pages/dashboard-next/holders.html@@ -0,0 +1,15 @@+<!doctype html>+<html lang="en">+ <head>+ <meta charset="utf-8" />+ <meta name="viewport" content="width=device-width,initial-scale=1" />+ <title>$THREE Holders · Dashboard · three.ws</title>+ <meta name="robots" content="noindex" />+ <link rel="icon" href="/favicon.ico" />+ <link rel="stylesheet" href="/fonts/fonts.css" />+ <link rel="stylesheet" href="/dashboard-next/shell.css" />+ </head>+ <body>+ <script type="module" src="/src/dashboard-next/pages/holders.js"></script>+ </body>+</html>diff --git a/scripts/codemod-rate-limit-headers.mjs b/scripts/codemod-rate-limit-headers.mjsnew file mode 100644index 000000000..69431c04e--- /dev/null+++ b/scripts/codemod-rate-limit-headers.mjs@@ -0,0 +1,106 @@+// One-off codemod: migrate hand-rolled 429 responses to the standard+// rateLimited() helper so every rate-limited response carries Retry-After ++// RateLimit-* headers. Idempotent — safe to re-run.+//+// node scripts/codemod-rate-limit-headers.mjs # apply+// node scripts/codemod-rate-limit-headers.mjs --dry # preview only+//+// Transforms single-line guards of the canonical shape:+// if (!VAR.success) return error(res, 429, 'rate_limited', MSG[, EXTRA]);+// return error(res, 429, 'rate_limited', MSG[, EXTRA]); // VAR inferred from nearest prior !X.success+// into rateLimited(res, VAR[, MSG][, EXTRA]) and ensures `rateLimited` is+// imported from the file's existing _lib/http.js import. Lines whose limiter+// variable cannot be resolved are left untouched and reported.++import { readFileSync, writeFileSync } from 'node:fs';+import { execSync } from 'node:child_process';++const DRY = process.argv.includes('--dry');++const files = execSync(`grep -rln "429, 'rate_limited'" api --include="*.js"`, {+ encoding: 'utf8',+})+ .trim()+ .split('\n')+ .filter(Boolean);++// Matches: error(res, 429, 'rate_limited', <msg>) with an optional 5th extra arg.+// <msg> is a single- or double-quoted or backtick string (no nested same-quote).+const CALL_RE =+ /error\(\s*res\s*,\s*429\s*,\s*'rate_limited'\s*,\s*('[^']*'|"[^"]*"|`[^`]*`)\s*(?:,\s*([\s\S]*?))?\)/;++let changedFiles = 0;+let changedLines = 0;+const skipped = [];++for (const file of files) {+ let src = readFileSync(file, 'utf8');+ const lines = src.split('\n');+ let touched = false;+ let lastVar = null;++ for (let i = 0; i < lines.length; i++) {+ const line = lines[i];++ // Track the most recent `!VAR.success` guard so a bare `return error(...)`+ // on its own line can resolve which limiter result to report.+ const guard = line.match(/!\s*([A-Za-z_$][\w$]*)\.success\b/);+ if (guard) lastVar = guard[1];++ if (!line.includes("429, 'rate_limited'")) continue;+ // Only single-line call sites; multi-line ones (trailing `, {` opening an+ // object across lines) are left for manual review.+ const m = line.match(CALL_RE);+ if (!m) {+ skipped.push(`${file}:${i + 1} (multi-line or unrecognized)`);+ continue;+ }++ const varOnLine = guard ? guard[1] : lastVar;+ if (!varOnLine) {+ skipped.push(`${file}:${i + 1} (no limiter variable in scope)`);+ continue;+ }++ const msg = m[1];+ const extra = m[2] ? m[2].trim() : null;+ // Drop the default message to keep call sites terse; keep custom ones.+ const isDefault = msg === "'too many requests'";+ const args = [`res`, varOnLine];+ if (!isDefault || extra) args.push(isDefault ? `'too many requests'` : msg);+ if (extra) args.push(extra);+ const replacement = `rateLimited(${args.join(', ')})`;++ lines[i] = line.slice(0, m.index) + replacement + line.slice(m.index + m[0].length);+ touched = true;+ changedLines++;+ }++ if (!touched) continue;++ src = lines.join('\n');++ // Ensure `rateLimited` is imported from the file's _lib/http.js import.+ if (!/\brateLimited\b/.test(src.split('\n').filter((l) => l.includes('import')).join('\n'))) {+ const importRe = /import\s*\{([\s\S]*?)\}\s*from\s*'([^']*_lib\/http\.js)'/;+ const im = src.match(importRe);+ if (im) {+ const names = im[1];+ const newNames = names.includes('rateLimited')+ ? names+ : names.replace(/\s*\}?\s*$/, '') + ', rateLimited';+ src = src.replace(importRe, `import {${newNames} } from '${im[2]}'`);+ } else {+ skipped.push(`${file} (uses rateLimited but no _lib/http.js import found to extend)`);+ }+ }++ if (!DRY) writeFileSync(file, src);+ changedFiles++;+}++console.log(`${DRY ? '[dry] ' : ''}rewrote ${changedLines} call sites across ${changedFiles} files`);+if (skipped.length) {+ console.log(`\nskipped ${skipped.length} site(s) for manual review:`);+ for (const s of skipped) console.log(' ' + s);+}diff --git a/src/dashboard-next/nav.js b/src/dashboard-next/nav.jsindex 91ced8495..b7eb849f6 100644--- a/src/dashboard-next/nav.js+++ b/src/dashboard-next/nav.js@@ -32,6 +32,7 @@ export const NAV = [// ── Monetize ────────────────────────────────────────────────────────{ path: '/dashboard/three-token', label: '$THREE', icon: 'three', group: 'Monetize', tags: ['token', 'utility', 'burn', 'revenue share', 'protocol', '$three', 'economy', 'holders'] },+ { path: '/dashboard/holders', label: 'Holders', icon: 'three', group: 'Monetize', tags: ['leaderboard', 'holders', 'rank', 'badge', '$three', 'whale', 'top holders', 'standing'] },{ path: '/dashboard/analytics', label: 'Analytics', icon: 'chart', group: 'Monetize', tags: ['revenue', 'charts', 'metrics', 'funnel', 'performance', 'views', 'engagement'] },{ path: '/dashboard/monetize', label: 'Monetize', icon: 'coin', group: 'Monetize', tags: ['revenue', 'payments', 'subscriptions', 'withdrawals', 'earnings', 'plan', 'billing'] },{ path: '/dashboard/tokens', label: 'Tokens', icon: 'token', group: 'Monetize', tags: ['pump.fun', 'launch', 'bonding curve', 'royalties', 'trade'] },diff --git a/src/dashboard-next/pages/holders.js b/src/dashboard-next/pages/holders.jsnew file mode 100644index 000000000..ff4baec4d--- /dev/null+++ b/src/dashboard-next/pages/holders.js@@ -0,0 +1,393 @@+// dashboard-next — $THREE Holders page.+//+// Public-facing holder leaderboard + the signed-in user's standing + a+// holder-gated, shareable badge. Three real data sources, all server-side:+// GET /api/three-token/leaderboard — ranked holders (Helius-backed, cached)+// the shared $THREE store — the viewer's own position (price/%/USD)+// The badge gate keys off the store's position, which is computed server-side+// from /api/wallet/balances — never a client-asserted balance.++import { mountShell } from '../shell.js';+import { requireUser, get, esc, ApiError } from '../api.js';+import { createThreeTokenData } from '../../pump/three-token-data.js';++const MONO = `'JetBrains Mono', ui-monospace, SFMono-Regular, Menlo, monospace`;+const PAGE_SIZE = 25;++// ── formatters ──────────────────────────────────────────────────────────────++function fmtCompact(n) {+ const v = Number(n);+ if (!Number.isFinite(v)) return '—';+ if (v >= 1_000_000) return `${(v / 1_000_000).toFixed(2)}M`;+ if (v >= 1_000) return `${(v / 1_000).toFixed(2)}K`;+ return v.toLocaleString('en-US', { maximumFractionDigits: 2 });+}+function fmtUsd(n) {+ const v = Number(n);+ if (!Number.isFinite(v)) return '—';+ return v.toLocaleString('en-US', { style: 'currency', currency: 'USD', maximumFractionDigits: v < 1 ? 6 : 2 });+}+function fmtPct(n) {+ const v = Number(n);+ if (!Number.isFinite(v)) return '—';+ return `${v.toFixed(v < 0.01 ? 4 : 2)}%`;+}++// Holder tier from share of supply — drives the badge styling/label.+function tierFor(pctOfSupply) {+ const p = Number(pctOfSupply);+ if (Number.isFinite(p)) {+ if (p >= 0.01) return { key: 'whale', label: 'Whale', accent: '#7CC4FF' };+ if (p >= 0.001) return { key: 'major', label: 'Major Holder', accent: '#A6E3A1' };+ }+ return { key: 'holder', label: 'Holder', accent: '#F5C518' };+}++// ── boot ──────────────────────────────────────────────────────────────────────++(async function boot() {+ try {+ const main = await mountShell();+ await requireUser();++ main.innerHTML = `+ <div style="margin-bottom:6px">+ <div style="display:flex;align-items:center;gap:12px;margin-bottom:4px">+ <div style="width:36px;height:36px;border-radius:10px;background:linear-gradient(135deg,#fff 0%,#888 100%);display:grid;place-items:center;font-weight:800;font-size:15px;color:#000;flex-shrink:0">$3</div>+ <div>+ <h1 class="dn-h1" style="margin:0">$THREE Holders</h1>+ <p class="dn-h1-sub" style="margin:0">The on-chain holder leaderboard for the protocol token</p>+ </div>+ </div>+ </div>+ <div data-slot="content" style="display:flex;flex-direction:column;gap:20px">+ <div class="dn-skeleton" style="height:150px;border-radius:12px"></div>+ <div class="dn-skeleton" style="height:420px;border-radius:12px"></div>+ </div>+ `;++ const host = main.querySelector('[data-slot="content"]');++ // Shared store gives the viewer's own position (server-derived balance).+ const store = createThreeTokenData({ pollMs: 60_000, anchorEl: host });++ host.innerHTML = '';+ const standing = renderStanding(store);+ const badge = renderBadge(store);+ const board = renderLeaderboard(store);+ host.appendChild(standing);+ host.appendChild(badge);+ host.appendChild(board.el);++ // First board load.+ board.load(0);+ } catch (err) {+ if (err instanceof ApiError && err.status === 401) {+ location.href = `/login?return=${encodeURIComponent(location.pathname)}`;+ } else throw err;+ }+})();++// ── Your standing (from the shared store position) ──────────────────────────────++function renderStanding(store) {+ const section = document.createElement('div');+ section.className = 'dn-panel';+ section.setAttribute('aria-label', 'Your $THREE standing');+ section.innerHTML = `+ <div style="font-size:11.5px;color:var(--nxt-ink-fade);text-transform:uppercase;letter-spacing:0.06em;margin-bottom:12px">Your Standing</div>+ <div data-slot="standing-body"></div>+ `;+ const body = section.querySelector('[data-slot="standing-body"]');++ const render = (state) => {+ const pos = state.position;+ const token = state.protocol.token || {};+ body.innerHTML = standingBody(pos, token);+ };+ const unsub = store.subscribe(render);++ new MutationObserver((_m, obs) => {+ if (!section.isConnected) { unsub(); obs.disconnect(); }+ }).observe(document.body, { childList: true, subtree: true });++ return section;+}++function standingBody(pos, token) {+ switch (pos.status) {+ case 'idle':+ case 'loading':+ return `<div class="dn-skeleton" style="height:60px;border-radius:10px" aria-busy="true"></div>`;+ case 'unauthenticated':+ return emptyRow('Sign in to see your standing.', 'Sign in', `/login?return=${encodeURIComponent(location.pathname)}`);+ case 'no_wallet':+ return emptyRow('Link a Solana wallet to appear on the leaderboard.', 'Link wallet', '/dashboard/account');+ case 'zero':+ return emptyRow('You don’t hold $THREE yet — acquire some to climb the board.', 'Get $THREE', `https://pump.fun/coin/${esc(token.mint || '')}`, true);+ case 'error':+ return `<span style="color:var(--nxt-ink-fade);font-size:13.5px">Couldn’t load your standing right now.</span>`;+ case 'ok': {+ const tier = tierFor(pos.pctOfSupply);+ const cells = [+ { label: 'Holding', value: `${fmtCompact(pos.amount)} <span style="font-size:12px;color:var(--nxt-ink-fade)">$THREE</span>` },+ { label: 'Value', value: pos.usd != null ? fmtUsd(pos.usd) : '—' },+ { label: 'Share of supply', value: pos.pctOfSupply != null ? fmtPct(pos.pctOfSupply * 100) : '—' },+ { label: 'Tier', value: `<span style="color:${tier.accent};font-weight:700">${tier.label}</span>` },+ ];+ return `<div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(130px,1fr));gap:12px">+ ${cells.map((c) => `<div>+ <div style="font-size:11px;color:var(--nxt-ink-fade);text-transform:uppercase;letter-spacing:0.05em;margin-bottom:4px">${esc(c.label)}</div>+ <div style="font-size:19px;font-weight:700;font-family:${MONO}">${c.value}</div>+ </div>`).join('')}+ </div>`;+ }+ default:+ return '';+ }+}++// ── Holder badge (gated, shareable) ─────────────────────────────────────────────++function renderBadge(store) {+ const section = document.createElement('div');+ section.className = 'dn-panel';+ section.setAttribute('aria-label', 'Your holder badge');+ section.innerHTML = `+ <div style="display:flex;align-items:center;justify-content:space-between;gap:12px;margin-bottom:12px">+ <div style="font-size:11.5px;color:var(--nxt-ink-fade);text-transform:uppercase;letter-spacing:0.06em">Holder Badge</div>+ <button data-action="download-badge" class="dn-btn" disabled style="font-size:12px;padding:4px 10px">Download PNG</button>+ </div>+ <div data-slot="badge-body"></div>+ `;+ const body = section.querySelector('[data-slot="badge-body"]');+ const dlBtn = section.querySelector('[data-action="download-badge"]');++ let current = null; // last { pos, token } when eligible, for export++ const render = (state) => {+ const pos = state.position;+ const token = state.protocol.token || {};+ if (pos.status === 'ok' && Number(pos.amount) > 0) {+ current = { pos, token };+ body.innerHTML = badgeSvg(pos, token);+ dlBtn.disabled = false;+ } else {+ current = null;+ dlBtn.disabled = true;+ body.innerHTML = badgeLocked(pos, token);+ }+ };+ const unsub = store.subscribe(render);++ dlBtn.addEventListener('click', () => {+ if (!current) return;+ dlBtn.disabled = true;+ downloadBadgePng(body.querySelector('svg'))+ .catch((e) => console.error('[holders] badge export failed', e))+ .finally(() => { dlBtn.disabled = false; });+ });++ new MutationObserver((_m, obs) => {+ if (!section.isConnected) { unsub(); obs.disconnect(); }+ }).observe(document.body, { childList: true, subtree: true });++ return section;+}++function badgeLocked(pos, token) {+ const msg = pos.status === 'unauthenticated'+ ? 'Sign in and hold $THREE to unlock your shareable holder badge.'+ : pos.status === 'no_wallet'+ ? 'Link a Solana wallet that holds $THREE to unlock your badge.'+ : 'Hold any amount of $THREE to unlock your shareable holder badge.';+ return `<div style="display:flex;align-items:center;gap:16px;flex-wrap:wrap">+ <div style="width:120px;height:68px;border-radius:10px;border:1px dashed var(--nxt-line);display:grid;place-items:center;color:var(--nxt-ink-fade);font-size:22px">🔒</div>+ <div style="flex:1;min-width:200px">+ <div style="font-size:13.5px;color:var(--nxt-ink-fade);margin-bottom:8px">${esc(msg)}</div>+ <a class="dn-btn" href="https://pump.fun/coin/${esc(token.mint || '')}" target="_blank" rel="noopener" style="font-size:12.5px">Get $THREE</a>+ </div>+ </div>`;+}++// A self-contained SVG badge — no external images, so it exports to PNG cleanly.+function badgeSvg(pos, token) {+ const tier = tierFor(pos.pctOfSupply);+ const amount = fmtCompact(pos.amount);+ const pct = pos.pctOfSupply != null ? fmtPct(pos.pctOfSupply * 100) : '—';+ const wallet = pos.wallet ? `${pos.wallet.slice(0, 4)}…${pos.wallet.slice(-4)}` : '';+ return `+ <svg viewBox="0 0 600 320" width="100%" style="max-width:480px;border-radius:14px;display:block" role="img" aria-label="$THREE ${esc(tier.label)} badge" xmlns="http://www.w3.org/2000/svg">+ <defs>+ <linearGradient id="bg" x1="0" y1="0" x2="1" y2="1">+ <stop offset="0" stop-color="#0b0b0f"/><stop offset="1" stop-color="#15151c"/>+ </linearGradient>+ <radialGradient id="glow" cx="0.8" cy="0.15" r="0.8">+ <stop offset="0" stop-color="${tier.accent}" stop-opacity="0.18"/><stop offset="1" stop-color="${tier.accent}" stop-opacity="0"/>+ </radialGradient>+ </defs>+ <rect width="600" height="320" rx="16" fill="url(#bg)"/>+ <rect width="600" height="320" rx="16" fill="url(#glow)"/>+ <rect x="1" y="1" width="598" height="318" rx="15" fill="none" stroke="${tier.accent}" stroke-opacity="0.35"/>+ <g font-family="${MONO}">+ <text x="36" y="58" fill="#ffffff" font-size="13" letter-spacing="3" opacity="0.7">THREE.WS · PROTOCOL TOKEN</text>+ <text x="36" y="120" fill="#ffffff" font-size="40" font-weight="800">$THREE ${esc(tier.label)}</text>+ <text x="36" y="186" fill="${tier.accent}" font-size="52" font-weight="800">${esc(amount)}</text>+ <text x="36" y="214" fill="#ffffff" font-size="15" opacity="0.7">$THREE held · ${esc(pct)} of supply</text>+ <text x="36" y="276" fill="#ffffff" font-size="14" opacity="0.55">${esc(wallet)}</text>+ <text x="430" y="276" fill="#ffffff" font-size="14" opacity="0.55">three.ws/holders</text>+ <circle cx="540" cy="64" r="26" fill="none" stroke="${tier.accent}" stroke-opacity="0.6"/>+ <text x="540" y="71" fill="#ffffff" font-size="22" font-weight="800" text-anchor="middle">$3</text>+ </g>+ </svg>`;+}++async function downloadBadgePng(svgEl) {+ if (!svgEl) return;+ const xml = new XMLSerializer().serializeToString(svgEl);+ const svg64 = `data:image/svg+xml;base64,${btoa(unescape(encodeURIComponent(xml)))}`;+ const img = new Image();+ img.crossOrigin = 'anonymous';+ await new Promise((res, rej) => { img.onload = res; img.onerror = rej; img.src = svg64; });+ const scale = 2; // retina+ const canvas = document.createElement('canvas');+ canvas.width = 600 * scale;+ canvas.height = 320 * scale;+ const ctx = canvas.getContext('2d');+ ctx.scale(scale, scale);+ ctx.drawImage(img, 0, 0, 600, 320);+ const url = canvas.toDataURL('image/png');+ const a = document.createElement('a');+ a.href = url;+ a.download = 'three-holder-badge.png';+ document.body.appendChild(a);+ a.click();+ a.remove();+}++// ── Leaderboard ─────────────────────────────────────────────────────────────────++function renderLeaderboard(store) {+ const section = document.createElement('div');+ section.className = 'dn-panel';+ section.setAttribute('aria-label', '$THREE holder leaderboard');+ section.innerHTML = `+ <div style="display:flex;align-items:center;justify-content:space-between;gap:12px;margin-bottom:12px">+ <div style="font-size:11.5px;color:var(--nxt-ink-fade);text-transform:uppercase;letter-spacing:0.06em">Leaderboard</div>+ <div data-slot="lb-meta" style="font-size:12px;color:var(--nxt-ink-fade)"></div>+ </div>+ <div data-slot="lb-body"></div>+ <div data-slot="lb-pager" style="display:flex;align-items:center;justify-content:space-between;gap:12px;margin-top:14px"></div>+ `;+ const body = section.querySelector('[data-slot="lb-body"]');+ const meta = section.querySelector('[data-slot="lb-meta"]');+ const pager = section.querySelector('[data-slot="lb-pager"]');++ let offset = 0;+ let total = 0;+ let loading = false;++ // Resolve the viewer's wallet from the store so we can highlight their row.+ const myWallet = () => store.getState().position.wallet || null;++ async function load(nextOffset) {+ if (loading) return;+ loading = true;+ offset = Math.max(0, nextOffset);+ body.innerHTML = `<div class="dn-skeleton" style="height:300px;border-radius:10px" aria-busy="true"></div>`;+ pager.innerHTML = '';+ try {+ const data = await get(`/api/three-token/leaderboard?limit=${PAGE_SIZE}&offset=${offset}`);+ total = Number(data?.total) || 0;+ const rows = Array.isArray(data?.holders) ? data.holders : [];+ if (!rows.length) {+ body.innerHTML = emptyBoard(offset);+ meta.textContent = total ? `${total.toLocaleString()} holders` : '';+ } else {+ body.innerHTML = boardTable(rows, myWallet());+ meta.textContent = `${total.toLocaleString()} holders`;+ }+ renderPager();+ } catch (err) {+ console.error('[holders] leaderboard load failed', err);+ body.innerHTML = `<div style="display:flex;align-items:center;justify-content:space-between;gap:12px;flex-wrap:wrap">+ <span style="color:var(--nxt-ink-fade);font-size:13.5px">Couldn’t load the leaderboard.</span>+ <button data-action="retry" class="dn-btn" style="font-size:12px;padding:4px 10px">Retry</button>+ </div>`;+ body.querySelector('[data-action="retry"]').addEventListener('click', () => load(offset));+ } finally {+ loading = false;+ }+ }++ function renderPager() {+ const page = Math.floor(offset / PAGE_SIZE) + 1;+ const pages = Math.max(1, Math.ceil(total / PAGE_SIZE));+ const hasPrev = offset > 0;+ const hasNext = offset + PAGE_SIZE < total;+ pager.innerHTML = `+ <button data-action="prev" class="dn-btn" ${hasPrev ? '' : 'disabled'} style="font-size:12px;padding:5px 12px">‹ Prev</button>+ <span style="font-size:12px;color:var(--nxt-ink-fade)">Page ${page} of ${pages}</span>+ <button data-action="next" class="dn-btn" ${hasNext ? '' : 'disabled'} style="font-size:12px;padding:5px 12px">Next ›</button>+ `;+ pager.querySelector('[data-action="prev"]').addEventListener('click', () => hasPrev && load(offset - PAGE_SIZE));+ pager.querySelector('[data-action="next"]').addEventListener('click', () => hasNext && load(offset + PAGE_SIZE));+ }++ // Re-highlight the viewer's row once their wallet resolves from the store.+ const unsub = store.subscribe(() => {+ const w = myWallet();+ if (!w) return;+ const rows = section.querySelectorAll('[data-wallet]');+ rows.forEach((r) => {+ const mine = r.getAttribute('data-wallet') === w;+ r.style.background = mine ? 'rgba(245,197,24,0.10)' : '';+ });+ });+ new MutationObserver((_m, obs) => {+ if (!section.isConnected) { unsub(); obs.disconnect(); }+ }).observe(document.body, { childList: true, subtree: true });++ return { el: section, load };+}++function boardTable(rows, myWallet) {+ const head = `+ <div style="display:grid;grid-template-columns:56px 1fr 120px 110px;gap:8px;padding:0 10px 8px;font-size:11px;color:var(--nxt-ink-fade);text-transform:uppercase;letter-spacing:0.05em">+ <div>Rank</div><div>Holder</div><div style="text-align:right">$THREE</div><div style="text-align:right">% Supply</div>+ </div>`;+ const body = rows.map((h) => {+ const mine = myWallet && h.wallet === myWallet;+ const medal = h.rank === 1 ? '🥇' : h.rank === 2 ? '🥈' : h.rank === 3 ? '🥉' : `#${h.rank}`;+ return `+ <div data-wallet="${esc(h.wallet)}" style="display:grid;grid-template-columns:56px 1fr 120px 110px;gap:8px;align-items:center;padding:9px 10px;border-radius:8px;${mine ? 'background:rgba(245,197,24,0.10);' : ''}font-size:13.5px">+ <div style="font-weight:700;font-family:${MONO}">${medal}</div>+ <div style="overflow:hidden;text-overflow:ellipsis;white-space:nowrap">+ <a href="https://solscan.io/account/${esc(h.wallet)}" target="_blank" rel="noopener" style="font-family:${MONO};color:inherit;text-decoration:none" title="${esc(h.wallet)}">${esc(h.wallet_short || h.wallet)}</a>+ ${mine ? '<span style="margin-left:8px;font-size:10.5px;color:#F5C518;font-weight:700">YOU</span>' : ''}+ </div>+ <div style="text-align:right;font-family:${MONO}">${fmtCompact(h.amount)}</div>+ <div style="text-align:right;font-family:${MONO};color:var(--nxt-ink-fade)">${h.pct_of_supply != null ? fmtPct(h.pct_of_supply * 100) : '—'}</div>+ </div>`;+ }).join('');+ return head + `<div style="display:flex;flex-direction:column;gap:2px">${body}</div>`;+}++function emptyBoard(offset) {+ if (offset > 0) {+ return `<div style="text-align:center;color:var(--nxt-ink-fade);font-size:13.5px;padding:40px 0">No more holders on this page.</div>`;+ }+ return `<div style="text-align:center;padding:48px 0">+ <div style="font-size:30px;margin-bottom:10px">🏆</div>+ <div style="color:var(--nxt-ink-fade);font-size:13.5px;margin-bottom:14px">No holders to show yet — be one of the first.</div>+ <a class="dn-btn" href="/dashboard/three-token" style="font-size:12.5px">View $THREE</a>+ </div>`;+}++function emptyRow(message, ctaLabel, href, external = false) {+ return `<div style="display:flex;align-items:center;justify-content:space-between;gap:12px;flex-wrap:wrap">+ <span style="color:var(--nxt-ink-fade);font-size:13.5px">${esc(message)}</span>+ <a class="dn-btn" href="${esc(href)}" ${external ? 'target="_blank" rel="noopener"' : ''} style="font-size:12.5px;white-space:nowrap">${esc(ctaLabel)}</a>+ </div>`;+}diff --git a/tests/mcp-tool-result.test.js b/tests/mcp-tool-result.test.jsnew file mode 100644index 000000000..03f0ec4e9--- /dev/null+++ b/tests/mcp-tool-result.test.js@@ -0,0 +1,97 @@+import { describe, it, expect } from 'vitest';++import { buildToolResult, toolError } from '../mcp-server/src/payments.js';+import { buildTools, buildServer } from '../mcp-server/src/index.js';++// Guards the MCP result envelope that EVERY paid tool funnels through+// (mcp-server/src/payments.js → buildToolResult). The contract:+// - text content is always present (back-compat for text-only clients)+// - plain-object returns are surfaced as MCP structuredContent (2025-06-18)+// - only the explicit toolError() envelope flips isError (which also tells the+// x402 wrapper to cancel — not settle — the payment, so failures don't bill)+describe('buildToolResult — MCP CallToolResult envelope', () => {+ it('surfaces a plain object as both text and structuredContent', () => {+ const out = { seed: 'abc', presetId: 'wave', match: { score: 3 } };+ const res = buildToolResult(out);++ expect(res.content).toEqual([{ type: 'text', text: JSON.stringify(out) }]);+ // Structured output: the exact object, not a re-parsed copy.+ expect(res.structuredContent).toBe(out);+ // A successful call must NOT be flagged as an error.+ expect(res.isError).toBeUndefined();+ });++ it('flags the toolError() envelope with isError so the payment is cancelled, not settled', () => {+ const err = toolError('invalid_mint', 'token must be a base58 Solana pubkey', {+ token: 'nope',+ });+ const res = buildToolResult(err);++ expect(res.isError).toBe(true);+ expect(res.structuredContent).toEqual({+ ok: false,+ error: 'invalid_mint',+ message: 'token must be a base58 Solana pubkey',+ token: 'nope',+ });+ // Text mirror still carries the full error envelope for text-only clients.+ expect(JSON.parse(res.content[0].text)).toEqual(res.structuredContent);+ });++ it('does NOT flag a partial-data success (embedded sub-field error, no top-level ok:false)', () => {+ // pump_snapshot returns this shape when one upstream (Jupiter) is down but+ // the overall call succeeded — the caller should still pay and not see isError.+ const partial = {+ token: 'HZ1JovNiVvGrGNiiYvEozEVgZ58xaU3RKwX8eACQBCt3',+ price: { error: 'jupiter timeout' },+ volume24h: { volume24hUsd: 1000 },+ };+ const res = buildToolResult(partial);++ expect(res.isError).toBeUndefined();+ expect(res.structuredContent).toBe(partial);+ });++ it('keeps string returns text-only (structuredContent must be an object)', () => {+ const res = buildToolResult('plain text result');+ expect(res.content).toEqual([{ type: 'text', text: 'plain text result' }]);+ expect(res.structuredContent).toBeUndefined();+ expect(res.isError).toBeUndefined();+ });++ it('does not promote arrays to structuredContent (spec requires an object)', () => {+ const arr = [{ a: 1 }, { b: 2 }];+ const res = buildToolResult(arr);+ expect(res.content).toEqual([{ type: 'text', text: JSON.stringify(arr) }]);+ expect(res.structuredContent).toBeUndefined();+ });+});++// The tool surface must be enumerable WITHOUT any payment env — tool+// registration is secret-free; only an actual paid invocation needs a pay-to.+describe('MCP tool surface', () => {+ it('builds every tool descriptor with a complete, unique contract', async () => {+ const tools = await buildTools();+ expect(tools.length).toBeGreaterThanOrEqual(15);++ const names = new Set();+ for (const t of tools) {+ expect(typeof t.name).toBe('string');+ expect(t.name).toMatch(/^[a-z][a-z0-9_]*$/);+ expect(typeof t.title).toBe('string');+ expect(t.title.length).toBeGreaterThan(0);+ expect(typeof t.description).toBe('string');+ // Every paid tool must quote its USDC price in its description.+ expect(t.description).toMatch(/\$[0-9]/);+ expect(t.inputSchema).toBeTypeOf('object');+ expect(t.handler).toBeTypeOf('function');+ expect(names.has(t.name)).toBe(false);+ names.add(t.name);+ }+ });++ it('constructs the MCP server with no payment env set', async () => {+ const server = await buildServer();+ expect(server).toBeTruthy();+ });+});diff --git a/vercel.json b/vercel.jsonindex d4da9fdfe..e38a1c2c9 100644--- a/vercel.json+++ b/vercel.json@@ -940,6 +940,10 @@"src": "/dashboard/three-token/?","dest": "/dashboard-next/three-token.html"},+ {+ "src": "/dashboard/holders/?",+ "dest": "/dashboard-next/holders.html"+ },{"src": "/dashboard/analytics/?","dest": "/dashboard-next/analytics.html"diff --git a/vite.config.js b/vite.config.jsindex 639bd9028..0d05574ef 100644--- a/vite.config.js+++ b/vite.config.js@@ -538,6 +538,10 @@ const appConfig = {'/dashboard/avatars/': resolve(root, 'pages/dashboard-next/avatars.html'),'/dashboard-next/avatars': resolve(root, 'pages/dashboard-next/avatars.html'),'/dashboard-next/avatars/': resolve(root, 'pages/dashboard-next/avatars.html'),+ '/dashboard/holders': resolve(root, 'pages/dashboard-next/holders.html'),+ '/dashboard/holders/': resolve(root, 'pages/dashboard-next/holders.html'),+ '/dashboard-next/holders': resolve(root, 'pages/dashboard-next/holders.html'),+ '/dashboard-next/holders/': resolve(root, 'pages/dashboard-next/holders.html'),'/studio': resolve(root, 'public/studio/index.html'),'/studio/': resolve(root, 'public/studio/index.html'),'/widgets': resolve(root, 'public/widgets-gallery/index.html'),