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.

fix(api): give the pinning, premium and launch-og handlers real error envelopes

nirholas3f1a7df83027
diff --git a/api/pinning/[action].js b/api/pinning/[action].js
index 94f8329e9..0b2ac43ab 100644
--- a/api/pinning/[action].js
+++ b/api/pinning/[action].js
@@ -2,72 +2,166 @@ import { sql } from '../_lib/db.js';
import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';
import { cors, json, method, readJson, wrap, error, rateLimited } from '../_lib/http.js';
import { limits, clientIp } from '../_lib/rate-limit.js';
+import {
+ IPFS_READ_GATEWAYS,
+ ipfsGatewayUrl,
+ ipfsPinningConfigured,
+ pinToIPFS,
+} from '../_lib/ipfs-pin.js';
const MAX_R2_BYTES = 50 * 1024 * 1024;
const MAX_DATA_URL_BYTES = 10 * 1024 * 1024;
-const CID_RE = /^[a-zA-Z0-9]+$/;
+
+// A CID is base58btc (v0, 46 chars) or base32 (v1, 59+), so the ceiling only has
+// to exclude the pathological. Unbounded, a 5000-character "cid" was accepted:
+// echoed back inside every gateway URL and forwarded into the provider's API on
+// each status call, turning one request into a much larger one for free.
+const CID_RE = /^[a-zA-Z0-9]{16,128}$/;
function isOwnedR2Url(url) {
const domain = process.env.S3_PUBLIC_DOMAIN;
if (!domain) return false;
- try {
- const trimmed = domain.replace(/\/$/, '');
- return url.startsWith(trimmed + '/');
- } catch {
- return false;
- }
+ const trimmed = domain.replace(/\/$/, '');
+ return url.startsWith(trimmed + '/');
+}
+
+/** Every gateway worth handing a caller, from the one tested read list. */
+function gatewayUrlsFor(cid) {
+ return IPFS_READ_GATEWAYS.map((gateway) => `${gateway}${cid}`);
}
-async function pinViaPinata(buf, filename) {
- const form = new FormData();
- form.append('file', new Blob([buf]), filename);
- const resp = await fetch('https://api.pinata.cloud/pinning/pinFileToIPFS', {
- method: 'POST',
- headers: { Authorization: `Bearer ${process.env.PINATA_JWT}` },
- body: form,
- signal: AbortSignal.timeout(25000),
- });
- if (!resp.ok) {
- const detail = await resp.text().catch(() => '');
- throw Object.assign(new Error(`Pinata error ${resp.status}`), { status: 502, detail });
+function tooLarge(message) {
+ return Object.assign(new Error(message), { status: 413, code: 'payload_too_large' });
+}
+
+/**
+ * Buffer a response body, refusing to hold more than `maxBytes` at any point.
+ *
+ * A content-length pre-check alone is not a limit: the header is optional and
+ * a source that omits or understates it gets an unbounded read, because the
+ * whole body lands in memory before any post-hoc size check can run. Reading
+ * incrementally and cancelling the moment the running total crosses the cap
+ * keeps peak memory bounded whatever the source sends.
+ */
+async function readCappedBody(resp, maxBytes) {
+ if (Number(resp.headers.get('content-length') || 0) > maxBytes) {
+ throw tooLarge(`source exceeds ${Math.round(maxBytes / (1024 * 1024))} MB limit`);
+ }
+ const reader = resp.body?.getReader();
+ if (!reader) {
+ const buf = Buffer.from(await resp.arrayBuffer());
+ if (buf.byteLength > maxBytes) {
+ throw tooLarge(`source exceeds ${Math.round(maxBytes / (1024 * 1024))} MB limit`);
+ }
+ return buf;
}
- const data = await resp.json();
- return { cid: data.IpfsHash, provider: 'pinata' };
+ const chunks = [];
+ let total = 0;
+ for (;;) {
+ const { done, value } = await reader.read();
+ if (done) break;
+ total += value.byteLength;
+ if (total > maxBytes) {
+ await reader.cancel().catch(() => {});
+ throw tooLarge(`source exceeds ${Math.round(maxBytes / (1024 * 1024))} MB limit`);
+ }
+ chunks.push(value);
+ }
+ return Buffer.concat(chunks);
+}
+
+/**
+ * The name handed to the pinning provider. On the web3.storage lane it rides an
+ * HTTP header (`X-NAME`), so anything outside a conservative set is dropped
+ * rather than forwarded, and an entirely unusable name falls back to the kind's
+ * default instead of reaching the provider empty.
+ */
+function safeFilename(name, fallback) {
+ const cleaned = String(name || '')
+ .replace(/[^A-Za-z0-9._-]/g, '')
+ .slice(0, 128);
+ return cleaned || fallback;
}
-async function pinViaWeb3Storage(buf, filename) {
- const resp = await fetch('https://api.web3.storage/upload', {
- method: 'POST',
- headers: {
- Authorization: `Bearer ${process.env.WEB3_STORAGE_TOKEN}`,
- 'X-NAME': filename,
- },
- body: buf,
- signal: AbortSignal.timeout(25000),
- });
- if (!resp.ok) {
- const detail = await resp.text().catch(() => '');
- throw Object.assign(new Error(`Web3.Storage error ${resp.status}`), {
- status: 502,
- detail,
+/**
+ * What gets recorded as the pin's origin.
+ *
+ * A data: URL carries the entire payload, up to 10 MB of it. Persisting that
+ * verbatim would store a second copy of every inline pin in Postgres, in a
+ * column whose only job is to say where the bytes came from, and the database
+ * is the one resource here with a hard storage cap.
+ */
+function sourceUrlForRecord(sourceUrl, byteLength) {
+ if (!sourceUrl.startsWith('data:')) return sourceUrl;
+ const commaIdx = sourceUrl.indexOf(',');
+ return `${sourceUrl.slice(0, commaIdx)},<${byteLength} bytes inline>`;
+}
+
+let pinsTableReady = null;
+
+/**
+ * `create table if not exists` is a no-op after the first call but still costs a
+ * round trip, so it ran on the request path of every single pin. Once per
+ * process is enough; a failure clears the latch so the next request retries.
+ */
+function ensurePinsTable() {
+ if (!pinsTableReady) {
+ pinsTableReady = sql`
+ create table if not exists pins (
+ id bigserial primary key,
+ user_id text not null,
+ source_url text not null,
+ cid text not null,
+ provider text not null,
+ kind text not null,
+ created_at timestamptz not null default now()
+ )
+ `.catch((err) => {
+ pinsTableReady = null;
+ throw err;
});
}
- const data = await resp.json();
- return { cid: data.cid, provider: 'web3.storage' };
+ return pinsTableReady;
}
-async function ensurePinsTable() {
- await sql`
- create table if not exists pins (
- id bigserial primary key,
- user_id text not null,
- source_url text not null,
- cid text not null,
- provider text not null,
- kind text not null,
- created_at timestamptz not null default now()
- )
- `;
+/** Ask each configured provider whether it is holding this CID. */
+async function checkProviders(cid) {
+ const pinataJwt = process.env.PINATA_JWT;
+ const w3sToken = process.env.WEB3_STORAGE_TOKEN;
+ const checks = [];
+
+ if (pinataJwt) {
+ checks.push(
+ fetch(
+ `https://api.pinata.cloud/data/pinList?hashContains=${encodeURIComponent(cid)}&status=pinned`,
+ { headers: { Authorization: `Bearer ${pinataJwt}` }, signal: AbortSignal.timeout(10000) },
+ )
+ .then(async (r) => {
+ if (!r.ok) return null;
+ const data = await r.json();
+ const pinned = (data.rows || []).some((row) => row.ipfs_pin_hash === cid);
+ return pinned ? 'pinata' : null;
+ })
+ .catch(() => null),
+ );
+ }
+
+ if (w3sToken) {
+ checks.push(
+ fetch(`https://api.web3.storage/status/${encodeURIComponent(cid)}`, {
+ headers: { Authorization: `Bearer ${w3sToken}` },
+ signal: AbortSignal.timeout(10000),
+ })
+ .then(async (r) => {
+ if (!r.ok) return null;
+ const data = await r.json();
+ return data.cid === cid ? 'web3.storage' : null;
+ })
+ .catch(() => null),
+ );
+ }
+
+ return (await Promise.all(checks)).filter(Boolean);
}
export default wrap(async (req, res) => {
@@ -96,9 +190,7 @@ export default wrap(async (req, res) => {
return error(res, 400, 'validation_error', 'kind must be "manifest" or "glb"');
}
- const pinataJwt = process.env.PINATA_JWT;
- const w3sToken = process.env.WEB3_STORAGE_TOKEN;
- if (!pinataJwt && !w3sToken) {
+ if (!ipfsPinningConfigured()) {
return error(
res,
503,
@@ -107,8 +199,9 @@ export default wrap(async (req, res) => {
);
}
+ const defaultName = kind === 'glb' ? 'avatar.glb' : 'manifest.json';
let buf;
- let filename = kind === 'glb' ? 'avatar.glb' : 'manifest.json';
+ let filename = defaultName;
if (sourceUrl.startsWith('data:')) {
const commaIdx = sourceUrl.indexOf(',');
@@ -136,13 +229,12 @@ export default wrap(async (req, res) => {
signal: AbortSignal.timeout(8000),
});
if (!head.ok) return error(res, 400, 'validation_error', 'source URL is not accessible');
- const contentLength = parseInt(head.headers.get('content-length') || '0', 10);
- if (contentLength > MAX_R2_BYTES) {
+ if (Number(head.headers.get('content-length') || 0) > MAX_R2_BYTES) {
return error(res, 413, 'payload_too_large', 'source exceeds 50 MB limit');
}
- // redirect: 'manual' — the source is prefix-locked to our own R2 domain
- // and R2 public buckets do not 302; refusing to follow any redirect keeps
- // a future CDN/front-end change from silently widening the fetch target.
+ // The source is prefix-locked to our own R2 domain and R2 public buckets
+ // do not 302, so refusing to follow any redirect keeps a future CDN or
+ // front-end change from silently widening the fetch target.
const fetched = await fetch(sourceUrl, {
redirect: 'manual',
signal: AbortSignal.timeout(20000),
@@ -151,25 +243,24 @@ export default wrap(async (req, res) => {
return error(res, 502, 'fetch_failed', 'source URL returned an unexpected redirect');
}
if (!fetched.ok) return error(res, 502, 'fetch_failed', 'failed to fetch source URL');
- buf = Buffer.from(await fetched.arrayBuffer());
- const urlPath = new URL(sourceUrl).pathname;
- filename = urlPath.split('/').pop() || filename;
+ buf = await readCappedBody(fetched, MAX_R2_BYTES);
+ filename = safeFilename(new URL(sourceUrl).pathname.split('/').pop(), defaultName);
}
- const { cid, provider } = pinataJwt
- ? await pinViaPinata(buf, filename)
- : await pinViaWeb3Storage(buf, filename);
+ const pinned = await pinToIPFS(buf, filename);
+ const { cid, provider } = pinned;
await ensurePinsTable();
await sql`
insert into pins (user_id, source_url, cid, provider, kind)
- values (${userId}, ${sourceUrl}, ${cid}, ${provider}, ${kind})
+ values (${userId}, ${sourceUrlForRecord(sourceUrl, buf.byteLength)}, ${cid}, ${provider}, ${kind})
`;
return json(res, 200, {
ok: true,
cid,
- gatewayUrl: `https://ipfs.io/ipfs/${cid}`,
+ gatewayUrl: ipfsGatewayUrl(cid),
+ gatewayUrls: gatewayUrlsFor(cid),
provider,
});
}
@@ -188,59 +279,37 @@ export default wrap(async (req, res) => {
res,
400,
'validation_error',
- 'cid query parameter is required and must be alphanumeric',
+ 'cid query parameter is required and must be 16 to 128 alphanumeric characters',
);
}
- const pinataJwt = process.env.PINATA_JWT;
- const w3sToken = process.env.WEB3_STORAGE_TOKEN;
- const checks = [];
-
- if (pinataJwt) {
- checks.push(
- fetch(
- `https://api.pinata.cloud/data/pinList?hashContains=${encodeURIComponent(cid)}&status=pinned`,
- { headers: { Authorization: `Bearer ${pinataJwt}` } },
- )
- .then(async (r) => {
- if (!r.ok) return null;
- const data = await r.json();
- const pinned = (data.rows || []).some((row) => row.ipfs_pin_hash === cid);
- return pinned ? 'pinata' : null;
- })
- .catch(() => null),
- );
- }
-
- if (w3sToken) {
- checks.push(
- fetch(`https://api.web3.storage/status/${encodeURIComponent(cid)}`, {
- headers: { Authorization: `Bearer ${w3sToken}` },
- })
- .then(async (r) => {
- if (!r.ok) return null;
- const data = await r.json();
- return data.cid === cid ? 'web3.storage' : null;
- })
- .catch(() => null),
+ // With no provider configured there is nothing to ask, and answering
+ // `pinned: false` would state as fact something this deployment cannot
+ // know: an unconfigured checker and a genuinely unpinned CID are not the
+ // same answer, and a caller that acts on the second (re-pin, warn the
+ // user, fail a manifest attestation) must not be handed the first.
+ if (!ipfsPinningConfigured()) {
+ return error(
+ res,
+ 503,
+ 'pinning_unconfigured',
+ 'no pinning provider configured; set PINATA_JWT or WEB3_STORAGE_TOKEN',
);
}
- const providerResults = await Promise.all(checks);
- const activeProviders = providerResults.filter(Boolean);
- const pinned = activeProviders.length > 0;
+ const activeProviders = await checkProviders(cid);
return json(res, 200, {
cid,
- pinned,
+ pinned: activeProviders.length > 0,
provider: activeProviders[0] || null,
- gatewayUrls: [
- `https://ipfs.io/ipfs/${cid}`,
- `https://flk-ipfs.xyz/ipfs/${cid}`,
- `https://dweb.link/ipfs/${cid}`,
- ],
+ gatewayUrls: gatewayUrlsFor(cid),
});
}
+ // CORS before the 404 so a browser caller reads the error envelope instead of
+ // an opaque network failure, and so a preflight for a mistyped action fails
+ // with a message rather than silence.
+ if (cors(req, res, { methods: 'GET,POST,OPTIONS', credentials: true })) return;
return error(res, 404, 'not_found', 'unknown pinning action');
});
diff --git a/api/premium/plans.js b/api/premium/plans.js
index ae2b6717e..c405822c7 100644
--- a/api/premium/plans.js
+++ b/api/premium/plans.js
@@ -1,10 +1,10 @@
-// GET /api/premium/plans — every premium tier, priced live in every accepted asset.
+// GET /api/premium/plans: every premium tier, priced live in every accepted asset.
//
// Public and cacheable (60 s): the dashboard's pricing cards render from this.
// Three self-serve tiers (developer / pro / enterprise) differ on the enforced
// per-key rate limit and licensing; every tier is payable in $THREE (at the
// platform discount), SOL, or USDC on Solana. Each asset is priced
-// independently and a down oracle marks only that asset unavailable — USDC is
+// independently and a down oracle marks only that asset unavailable. USDC is
// parity and can never fail, so there is always at least one payable rail.
import { cors, json, method, wrap } from '../_lib/http.js';
@@ -61,7 +61,7 @@ export default wrap(async (req, res) => {
resources: PREMIUM_RESOURCES,
summary:
'Unmetered news-archive search at your tier’s rate limit via an x402_live_ API key ' +
- 'or a wallet signature (SIWX) — no per-call payments while the pass is active. ' +
+ 'or a wallet signature (SIWX), with no per-call payments while the pass is active. ' +
'Pro and Enterprise include commercial use; Enterprise includes priority support ' +
'and bulk corpus arrangements.',
},
diff --git a/api/premium/quote.js b/api/premium/quote.js
index af4f67466..1c87d1162 100644
--- a/api/premium/quote.js
+++ b/api/premium/quote.js
@@ -1,4 +1,4 @@
-// POST /api/premium/quote — lock a price and get the unsigned payment tx.
+// POST /api/premium/quote: lock a price and get the unsigned payment tx.
//
// body: { asset: 'THREE' | 'SOL' | 'USDC', wallet: '<base58>',
// plan?: 'developer' | 'pro' | 'enterprise' } (default developer)
@@ -29,7 +29,7 @@ export default wrap(async (req, res) => {
return error(res, 400, 'bad_asset', 'asset must be THREE, SOL, or USDC');
}
- // Session is optional — a raw-API buyer quotes with just a wallet; a
+ // Session is optional: a raw-API buyer quotes with just a wallet; a
// dashboard buyer gets the pass linked to their account for key management.
let userId = null;
try {
diff --git a/api/premium/status.js b/api/premium/status.js
index b0665e6d6..cb45bffa5 100644
--- a/api/premium/status.js
+++ b/api/premium/status.js
@@ -5,11 +5,11 @@
// purchase history), so it is gated behind wallet-ownership proof: the caller
// signs `three.ws premium status\nWallet: <wallet>\nIssued At: <iso>` with the
// wallet's key (SIWS/ed25519), same class of check the sibling
-// /api/x402/my-receipts uses. Key prefixes and usage counts only — the
+// /api/x402/my-receipts uses. Key prefixes and usage counts only: the
// plaintext key is never re-derivable.
//
// Unauthenticated callers (no/invalid signature) get only the boolean pass
-// state { active, pass } — wallet addresses are public, so the sensitive
+// state { active, pass }. Wallet addresses are public, so the sensitive
// fields must not leak to anyone who can name a wallet.
import { cors, json, error, method, wrap, rateLimited } from '../_lib/http.js';
diff --git a/api/pump/launch-og.js b/api/pump/launch-og.js
index 01a8e5dbf..4edfc912b 100644
--- a/api/pump/launch-og.js
+++ b/api/pump/launch-og.js
@@ -21,7 +21,7 @@
* footer — three.ws branding
*/
-import { cors, wrap } from '../_lib/http.js';
+import { cors, method, wrap } from '../_lib/http.js';
import { sql } from '../_lib/db.js';
const MINT_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;
@@ -57,6 +57,16 @@ function fmtNum(v) {
return `$${n.toFixed(4)}`;
}
+// pump_coin_intel stores organic_score and bundle_score as 0..1 fractions (the
+// enrichment writes ratios, e.g. 0.4279), while the card draws them as percent
+// bars. Convert once, here, so a 43% organic launch renders a 43% bar instead of
+// the 0%/1px sliver it drew when the raw fraction was fed straight to the gauge.
+function scoreToPercent(v) {
+ const n = Number(v);
+ if (!Number.isFinite(n) || n <= 0) return 0;
+ return Math.min(100, n * 100);
+}
+
function qualityColor(score) {
if (score == null) return '#6b7280';
if (score >= 70) return '#22c55e';
@@ -119,30 +129,41 @@ async function buildCardData(mint) {
const category = intel?.category || '';
const isThreeWsLaunch = !!reg;
- // Fetch live price from pump.fun if no outcome (coin is still active).
- let livePrice = null;
- let liveMcap = null;
- if (!outcome?.graduated && !outcome?.rugged) {
- try {
- const r = await fetch(`${PUMP_FRONTEND_V3}/coins-v2/${mint}`, {
- headers: { accept: 'application/json' },
- signal: AbortSignal.timeout(3000),
- });
- if (r.ok) {
- const d = await r.json();
- livePrice = d?.price_in_usd ?? d?.market_cap_in_usd ? null : null;
- liveMcap = d?.market_cap_in_usd ?? null;
- }
- } catch { /* non-fatal */ }
- }
+ // Live USD market cap from pump.fun, but only while the coin is still active:
+ // a graduated or rugged coin reads its number off the recorded outcome instead.
+ // The field is `usd_market_cap` (with `market_cap_usd` as the v2 alias); the
+ // card previously asked for a `market_cap_in_usd` key pump.fun does not emit,
+ // so MKT CAP silently never rendered for a live coin.
+ const wantsLiveMcap = !outcome?.graduated && !outcome?.rugged;
+
+ // Genuinely concurrent: the logo fetch and the market-cap lookup are two
+ // independent 3s-bounded round-trips, so the card costs one of them, not both.
+ const [logoBase64, liveMcap] = await Promise.all([
+ fetchLogoBase64(imageUri),
+ wantsLiveMcap ? fetchLiveMarketCap(mint) : Promise.resolve(null),
+ ]);
- // Fetch logo in parallel with the live price lookup.
- const [logoBase64] = await Promise.all([fetchLogoBase64(imageUri)]);
+ return { name, symbol, imageUri, logoBase64, qualityScore, category, isThreeWsLaunch, intel, outcome, liveMcap };
+}
- return { name, symbol, imageUri, logoBase64, qualityScore, category, isThreeWsLaunch, intel, outcome, livePrice, liveMcap };
+// Live USD market cap for a coin still on the curve. Any failure returns null and
+// the card falls back to the recorded outcome numbers, or omits the block.
+async function fetchLiveMarketCap(mint) {
+ try {
+ const r = await fetch(`${PUMP_FRONTEND_V3}/coins-v2/${mint}`, {
+ headers: { accept: 'application/json' },
+ signal: AbortSignal.timeout(3000),
+ });
+ if (!r.ok) return null;
+ const d = await r.json();
+ const mcap = Number(d?.usd_market_cap ?? d?.market_cap_usd);
+ return Number.isFinite(mcap) && mcap > 0 ? mcap : null;
+ } catch {
+ return null;
+ }
}
-function renderCard(mint, d) {
+export function renderCard(mint, d) {
const { name, symbol, logoBase64, qualityScore, category, isThreeWsLaunch, intel, outcome, liveMcap } = d;
const displayName = trunc(name || 'Unknown coin', 36);
const displaySym = symbol ? `$${symbol.toUpperCase()}` : '';
@@ -166,11 +187,12 @@ function renderCard(mint, d) {
<text x="908" y="552" fill="#22c55e" font-size="20" font-weight="500">LIVE</text>`;
}
- // Organic vs bundle gauge bar (230 px wide).
- const organic = Number(intel?.organic_score ?? 0);
+ // Organic vs bundle gauge bar (230 px wide, so 2.3 px per percentage point).
+ const organic = scoreToPercent(intel?.organic_score);
const organicW = Math.round(organic * 2.3);
- const bundle = Number(intel?.bundle_score ?? 0);
- const bundleColor = bundle > 0.3 ? '#ef4444' : '#f59e0b';
+ const bundle = scoreToPercent(intel?.bundle_score);
+ // 0.3 is the coordinated-launch threshold api/_lib/market-realness.js uses.
+ const bundleColor = bundle > 30 ? '#ef4444' : '#f59e0b';
// Horizontal divider y-position.
const imgBlock = logoBase64
@@ -273,6 +295,10 @@ function renderCard(mint, d) {
export default wrap(async (req, res) => {
if (cors(req, res, { methods: 'GET,OPTIONS' })) return;
+ // Crawlers fetch og:image with GET, and several (Slack, iMessage) HEAD it
+ // first; nothing else should be able to spend a DB read plus two upstream
+ // round-trips on this route.
+ if (!method(req, res, ['GET'])) return;
const url = new URL(req.url, 'http://x');
const mint = (url.searchParams.get('mint') || '').trim();
@@ -289,7 +315,7 @@ export default wrap(async (req, res) => {
data = await buildCardData(mint);
} catch {
// Hard DB failure — serve a branded fallback card rather than 500.
- data = { name: '', symbol: '', logoBase64: null, qualityScore: null, category: '', isThreeWsLaunch: false, intel: null, outcome: null, livePrice: null, liveMcap: null };
+ data = { name: '', symbol: '', logoBase64: null, qualityScore: null, category: '', isThreeWsLaunch: false, intel: null, outcome: null, liveMcap: null };
}
const svg = renderCard(mint, data);