Skip to content

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.

feat: apply distributed rate limiting across forge, explore, and oracle endpoints

nirholas69fc8d676498
diff --git a/api/_lib/rate-limit.js b/api/_lib/rate-limit.js
index 10fe9f7e5..7d2cfc733 100644
--- a/api/_lib/rate-limit.js
+++ b/api/_lib/rate-limit.js
@@ -347,6 +347,24 @@ export const limits = {
// keep that egress bounded. Non-critical: a Redis outage must never block a
// rewrite (the enhancer degrades gracefully to the original prompt anyway).
forgeEnhance: (key) => getLimiter('forge:enhance', { limit: 40, window: '1 h' }).limit(key),
+ // Diorama composer (api/diorama action:compose) — one free-first LLM
+ // completion per call that decomposes a sentence into a placed object set.
+ // Paid upstream egress, so cap per IP and add a global hourly circuit breaker.
+ // Critical: a Redis outage in prod fails closed rather than handing out
+ // unbounded paid inference (the same posture as the chat/brain buckets).
+ dioramaComposeIp: (ip) =>
+ getLimiter('diorama:compose:ip', { limit: 20, window: '10 m', critical: true }).limit(ip),
+ dioramaComposeGlobal: () =>
+ getLimiter('diorama:compose:global', {
+ limit: Math.max(120, Number(process.env.DIORAMA_COMPOSE_GLOBAL_HOURLY) || 600),
+ window: '1 h',
+ critical: true,
+ }).limit('global'),
+ // Diorama save (api/diorama action:save) — persists a forged world to the
+ // public gallery table. Anonymous write, so cap per IP to stop one caller
+ // carpeting the gallery; non-critical so an infra hiccup never blocks a save.
+ dioramaSaveIp: (ip) =>
+ getLimiter('diorama:save:ip', { limit: 30, window: '10 m' }).limit(ip),
// x402 Bazaar MCP. Discovery calls fan out to external facilitators, so cap
// per principal to keep that egress bounded without throttling normal use.
mcpBazaar: (key) =>
diff --git a/api/characters.js b/api/characters.js
index 6c38e49f7..35f87375d 100644
--- a/api/characters.js
+++ b/api/characters.js
@@ -121,5 +121,13 @@ export default wrap(async (req, res) => {
const nextCursor = hasMore ? items[items.length - 1].created_at : null;
- return json(res, 200, { characters: items, next_cursor: nextCursor });
+ // Public, non-personalized published-agents feed. CDN-cache so a traffic surge
+ // is absorbed at the edge instead of re-running the per-row chat_count aggregate
+ // on every request; stale-while-revalidate keeps it warm across refreshes.
+ return json(
+ res,
+ 200,
+ { characters: items, next_cursor: nextCursor },
+ { 'cache-control': 'public, s-maxage=60, stale-while-revalidate=300' },
+ );
});
diff --git a/api/diorama.js b/api/diorama.js
index f07f305fd..3f15122dd 100644
--- a/api/diorama.js
+++ b/api/diorama.js
@@ -17,7 +17,8 @@
* 503 and the page renders a designed retry state — it never fabricates a world.
*/
-import { cors, json, method, readJson, wrap } from './_lib/http.js';
+import { cors, json, method, readJson, wrap, rateLimited } from './_lib/http.js';
+import { limits, clientIp } from './_lib/rate-limit.js';
import { llmComplete, llmConfigured } from './_lib/llm.js';
import { saveDiorama, getDiorama, listDioramas, bumpViews, dioramaStoreEnabled } from './_lib/diorama-store.js';
import {
@@ -106,6 +107,19 @@ async function handleCompose(req, res, body) {
});
}
+ // Compose runs a paid LLM completion — gate per IP and behind a global hourly
+ // circuit breaker so one caller (or an influx) can't drive unbounded inference
+ // spend. The global bucket only trips under a genuine surge or distributed abuse.
+ const ip = clientIp(req);
+ const rl = await limits.dioramaComposeIp(ip);
+ if (!rl.success) {
+ return rateLimited(res, rl, 'World composer limit reached. Try again shortly.');
+ }
+ const globalRl = await limits.dioramaComposeGlobal();
+ if (!globalRl.success) {
+ return rateLimited(res, globalRl, 'The world composer is at capacity. Try again shortly.');
+ }
+
let completion;
try {
completion = await llmComplete({
@@ -159,6 +173,12 @@ async function handleSave(req, res, body) {
message: 'Sharing is not configured on this deployment.',
});
}
+ // Persisting a world is an anonymous public write — bound per IP so one caller
+ // can't carpet the gallery table.
+ const saveRl = await limits.dioramaSaveIp(clientIp(req));
+ if (!saveRl.success) {
+ return rateLimited(res, saveRl, 'Saving too fast. Try again in a moment.');
+ }
let saved;
try {
saved = await saveDiorama({
diff --git a/api/explore.js b/api/explore.js
index 46642f096..23c556f7a 100644
--- a/api/explore.js
+++ b/api/explore.js
@@ -292,17 +292,25 @@ export default wrap(async (req, res) => {
const allTotal = Number(onchainTotal) + solCount + avatarCount;
const threeDTotal = Number(onchain3d) + avatarCount;
- return json(res, 200, {
- items,
- nextCursor,
- totals: {
- all: allTotal,
- threeD: threeDTotal,
- onchain: Number(onchainTotal),
- solana: solCount,
- avatars: avatarCount,
+ return json(
+ res,
+ 200,
+ {
+ items,
+ nextCursor,
+ totals: {
+ all: allTotal,
+ threeD: threeDTotal,
+ onchain: Number(onchainTotal),
+ solana: solCount,
+ avatars: avatarCount,
+ },
},
- });
+ // Public, non-personalized discover feed (incl. the leading-wildcard search
+ // scan). CDN-cache by full URL so repeated queries and the firehose of new
+ // visitors are served from the edge instead of re-scanning on every hit.
+ { 'cache-control': 'public, s-maxage=30, stale-while-revalidate=120' },
+ );
});
function shortAddr(a) {
diff --git a/api/oracle/social.js b/api/oracle/social.js
index 3c35df1e5..f9504d824 100644
--- a/api/oracle/social.js
+++ b/api/oracle/social.js
@@ -22,7 +22,7 @@
import { cors, json, method, readJson, wrap, error, rateLimited } from '../_lib/http.js';
import { limits, clientIp } from '../_lib/rate-limit.js';
-import { sql } from '../_lib/db.js';
+import { sql, sqlValues } from '../_lib/db.js';
const NETWORK = 'mainnet';
@@ -116,23 +116,25 @@ export default wrap(async (req, res) => {
updates.push({ mint, network, virality: data.maxVirality, tweetCount: data.tweetCount });
}
- let mints_updated = 0;
- for (const u of updates) {
- await sql`
- insert into oracle_narrative (mint, network, virality, confidence, source, classified_at)
- values (${u.mint}, ${u.network}, ${u.virality}, 0.4, 'heuristic', now())
- on conflict (mint, network) do update set
- virality = case
- when oracle_narrative.source = 'llm' then oracle_narrative.virality
- else least(100, greatest(oracle_narrative.virality, excluded.virality))
- end,
- classified_at = case
- when oracle_narrative.source = 'llm' then oracle_narrative.classified_at
- else now()
- end
- `.catch(() => null);
- mints_updated++;
- }
+ // Single multi-row upsert instead of one round-trip per symbol — a batch of up
+ // to 500 tweets can mention dozens of known mints, and N sequential INSERTs
+ // would serialize the whole request behind DB latency. classified_at is bound
+ // per row; the ON CONFLICT branch still uses now() for the update path.
+ const rows = updates.map((u) => [u.mint, u.network, u.virality, 0.4, 'heuristic', new Date()]);
+ const upserted = await sql`
+ insert into oracle_narrative (mint, network, virality, confidence, source, classified_at)
+ values ${sqlValues(rows)}
+ on conflict (mint, network) do update set
+ virality = case
+ when oracle_narrative.source = 'llm' then oracle_narrative.virality
+ else least(100, greatest(oracle_narrative.virality, excluded.virality))
+ end,
+ classified_at = case
+ when oracle_narrative.source = 'llm' then oracle_narrative.classified_at
+ else now()
+ end
+ `.catch(() => null);
+ const mints_updated = upserted === null ? 0 : updates.length;
return json(res, 200, {
ok: true,
diff --git a/api/wk.js b/api/wk.js
index 083408afe..1455675e7 100644
--- a/api/wk.js
+++ b/api/wk.js
@@ -642,6 +642,10 @@ async function handleX402Discovery(req, res) {
serviceName: 'three.ws Vanity Grinder',
tags: ['solana', 'vanity', 'keypair', 'wallet', 'address'],
}),
+ vanityVerifiable: withService({
+ serviceName: 'three.ws Provably-Fair Vanity Grinder',
+ tags: ['solana', 'vanity', 'keypair', 'wallet', 'verifiable', 'commit-reveal'],
+ }),
permit2Demo: withService({
serviceName: 'three.ws Permit2 Demo',
tags: ['x402', 'permit2', 'eip2612', 'gasless', 'demo'],
@@ -1175,6 +1179,60 @@ async function handleX402Discovery(req, res) {
}),
};
})(),
+ (() => {
+ // Provably-fair vanity grind: same difficulty tiers as /vanity with a
+ // small premium for the deterministic derivation + signed receipt. The
+ // catalog advertises the 1-char entry tier ('20000' = $0.02); the live
+ // 402 quotes the exact price for the requested pattern length.
+ const url = `${origin}/api/x402/vanity-verifiable`;
+ const accepts = acceptsForPrice('20000', url);
+ return {
+ path: '/api/x402/vanity-verifiable',
+ url,
+ method: 'GET',
+ description:
+ 'Provably-Fair Vanity Grinder — generate a brand-new Solana keypair whose Base58 address starts with a chosen prefix and/or ends with a chosen suffix, with a SIGNED receipt that proves the key was ground fresh and never kept. The server commits to a random 32-byte seed (commitment = SHA-256(serverSeed)) BEFORE grinding, mixes in your optional clientSeed, derives each candidate deterministically (HMAC-SHA256 → Ed25519), and signs the receipt with its long-lived service key (published at /.well-known/three-vanity.json). Pass sealTo=<X25519 public key> and the secret is ECIES-sealed to you — plaintext never appears in the response or any log. Verify entirely client-side with @three-ws/solana-agent verifyVanityReceipt(), the CLI, or three.ws/vanity/verify. Combined pattern capped at 3 Base58 chars, priced $0.02–$0.40; settlement runs only after a successful grind, so an exhausted budget costs nothing.',
+ mimeType: 'application/json',
+ serviceName: routeMeta.vanityVerifiable.serviceName,
+ tags: routeMeta.vanityVerifiable.tags,
+ iconUrl: routeMeta.vanityVerifiable.iconUrl,
+ accepts,
+ extensions: extensionsForAccepts(accepts, {
+ method: 'GET',
+ discoverable: true,
+ input: { prefix: 'So', suffix: '', ignoreCase: '0', sealTo: '' },
+ inputSchema: {
+ type: 'object',
+ anyOf: [{ required: ['prefix'] }, { required: ['suffix'] }],
+ properties: {
+ prefix: {
+ type: 'string',
+ maxLength: 3,
+ description:
+ 'Base58 characters the address must start with (excludes 0, O, I, l). Combined with suffix, max 3.',
+ },
+ suffix: {
+ type: 'string',
+ maxLength: 3,
+ description:
+ 'Base58 characters the address must end with. Combined with prefix, max 3.',
+ },
+ ignoreCase: {
+ type: 'string',
+ enum: ['0', '1', 'true', 'false'],
+ description:
+ 'When 1/true, match case-insensitively (faster, less specific).',
+ },
+ sealTo: {
+ type: 'string',
+ description:
+ 'Recommended. Your 32-byte X25519 public key (Base58/Base64url/hex). When set, the secret is ECIES-sealed to it and omitted from the response.',
+ },
+ },
+ },
+ }),
+ };
+ })(),
(() => {
// Permit2-only demo: skip the EIP-3009 entry that acceptsForPrice
// would push first, so SDK clients are forced through the gasless