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(api): SDP relay endpoint + client, render/cron/oauth/permissions hardening

nirholas8de3a0c75700
diff --git a/.env.example b/.env.example
index 55f8f21a2..4afedd5d4 100644
--- a/.env.example
+++ b/.env.example
@@ -290,6 +290,21 @@ HELIUS_WEBHOOK_AUTH=
SOLANA_RPC_URL=
SOLANA_RPC_URL_DEVNET=
+# ── Solana Developer Platform (SDP) — custodial wallets, SPL issuance, ───────
+# payments, and compliance screening via the Solana Foundation's enterprise API
+# (https://platform.solana.com). Used by the same-origin proxy at /api/sdp/* and
+# the helpers in api/_lib/sdp.js.
+# When set, /api/sdp/v1/{wallets,issuance,payments,compliance,...} go live under
+# our origin (the key stays server-side, never reaches the browser). Without it,
+# authenticated routes return a designed "not configured" 503 — never fake data;
+# the unauthenticated /api/sdp/health probe still works.
+# Get a project-scoped key from https://platform.solana.com (sandbox keys hit
+# the same wire surface — swap the key to go to production).
+SDP_API_KEY=
+# Optional override for the SDP API host. Defaults to the production API; point
+# at the sandbox or a self-hosted Worker deployment if needed.
+SDP_API_BASE=https://api.solana.com
+
# ── x402 micropayments (POST /api/mcp) ─────────────────────────────────────
# Per-network payTo wallets that receive USDC for paid MCP calls.
X402_PAY_TO_SOLANA=BUrwd1nK6tFeeJMyzRHDo6AuVbnSfUULfvwq21X93nSN
diff --git a/api/_lib/rate-limit.js b/api/_lib/rate-limit.js
index 8d9804178..164a225e1 100644
--- a/api/_lib/rate-limit.js
+++ b/api/_lib/rate-limit.js
@@ -179,6 +179,12 @@ export const limits = {
// caller can't drain the shared key's budget. Reads are cached, so this is
// generous enough for an interactive feed.
aixbtIp: (ip) => getLimiter('aixbt:ip', { limit: 90, window: '1 m' }).limit(ip),
+ // Solana Developer Platform proxy (api/sdp/*). Each call fronts the SDP API
+ // under our server-side key, and writes (wallet create / issuance / payment)
+ // move real value, so cap per IP to keep that egress bounded and prevent the
+ // shared key's quota from being drained by one caller. Generous enough for an
+ // interactive dashboard; reads are not cached so this gates every origin hit.
+ sdpIp: (ip) => getLimiter('sdp:ip', { limit: 60, window: '1 m' }).limit(ip),
mcpUser: (userId) => getLimiter('mcp:user', { limit: 1200, window: '1 m' }).limit(userId),
mcpIp: (ip) => getLimiter('mcp:ip', { limit: 600, window: '1 m' }).limit(ip),
// Paid MCP tools — each call runs real compute (glTF validation / inspection
diff --git a/api/_lib/render-clip.js b/api/_lib/render-clip.js
index 3769fa09c..e19463da5 100644
--- a/api/_lib/render-clip.js
+++ b/api/_lib/render-clip.js
@@ -18,8 +18,12 @@
// so Vercel's NFT doesn't statically trace the chromium tree for every route
// that transitively imports this module — that trace caused 45-min build hangs.
import { env } from './env.js';
+import { fetchModel } from './fetch-model.js';
import { PRESETS } from '../../src/pose-presets.js';
+// Cap on GLB bytes pulled into the renderer (OOM / render-budget guard).
+const DEFAULT_MAX_GLB_BYTES = 25 * 1024 * 1024;
+
const DEFAULT_CHROMIUM_PACK =
'https://github.com/Sparticuz/chromium/releases/download/v148.0.0/chromium-v148.0.0-pack.x64.tar';
const CHROMIUM_PACK = env.CHROMIUM_PACK_URL || DEFAULT_CHROMIUM_PACK;
@@ -53,7 +57,7 @@ function poseById(id) {
return found ? { id: found.id, label: found.label, pose: found.pose } : null;
}
-function viewerHtml({ glbUrl, width, height, background, pose, cameraOrbit, expression }) {
+function viewerHtml({ glbBase64, width, height, background, pose, cameraOrbit, expression }) {
const bg = background === 'transparent' ? 'null' : JSON.stringify(background || '#0a0a0a');
const poseJson = pose ? JSON.stringify(pose.pose) : 'null';
const orbitJson = JSON.stringify(cameraOrbit || { theta: 0, phi: 80, radius: null });
@@ -63,6 +67,7 @@ function viewerHtml({ glbUrl, width, height, background, pose, cameraOrbit, expr
<style>html,body{margin:0;padding:0;background:transparent;overflow:hidden}</style>
</head><body>
<canvas id="c" width="${width}" height="${height}" style="display:block;width:${width}px;height:${height}px"></canvas>
+<script>window.__GLB_B64=${JSON.stringify(glbBase64)};</script>
<script type="importmap">{ "imports": {
"three": "https://unpkg.com/three@${THREE_VERSION}/build/three.module.js",
"three/addons/": "https://unpkg.com/three@${THREE_VERSION}/examples/jsm/"
@@ -179,7 +184,10 @@ loader.setDRACOLoader(dracoLoader);
loader.setKTX2Loader(ktx2Loader);
loader.setMeshoptDecoder(MeshoptDecoder);
-loader.load(${JSON.stringify(glbUrl)}, (gltf) => {
+// GLB bytes are fetched server-side via the SSRF-pinned fetchModel path and
+// embedded as base64, so chromium never fetches the user-supplied URL (no
+// DNS-rebinding / redirect-to-internal SSRF).
+function onLoaded(gltf) {
try {
const root = gltf.scene;
scene.add(root);
@@ -194,9 +202,18 @@ loader.load(${JSON.stringify(glbUrl)}, (gltf) => {
} catch (err) {
window.__renderError = err.message || String(err);
}
-}, undefined, (err) => {
- window.__renderError = 'glb load failed: ' + (err?.message || err);
-});
+}
+
+(async () => {
+ try {
+ const buf = await (await fetch('data:application/octet-stream;base64,' + window.__GLB_B64)).arrayBuffer();
+ loader.parse(buf, '', onLoaded, (err) => {
+ window.__renderError = 'glb parse failed: ' + (err?.message || err);
+ });
+ } catch (err) {
+ window.__renderError = 'glb decode failed: ' + (err?.message || String(err));
+ }
+})();
</script></body></html>`;
}
@@ -221,6 +238,7 @@ export async function renderClip({
posePresetId = null,
cameraOrbit = null,
expression = null,
+ maxBytes = DEFAULT_MAX_GLB_BYTES,
} = {}) {
if (!glbUrl || typeof glbUrl !== 'string') {
throw Object.assign(new Error('glbUrl required'), { status: 400, code: 'invalid_args' });
@@ -228,11 +246,23 @@ export async function renderClip({
const W = Math.max(64, Math.min(2048, Number(width) || 1024));
const H = Math.max(64, Math.min(2048, Number(height) || 1024));
const pose = poseById(posePresetId);
+ // Pull the GLB through the SSRF-pinned fetcher (DNS-pinned per hop, redirects
+ // re-validated, byte cap enforced) so chromium never fetches the untrusted URL.
+ let glbBase64;
+ try {
+ const { bytes } = await fetchModel(glbUrl, { maxBytes });
+ glbBase64 = Buffer.from(bytes).toString('base64');
+ } catch (err) {
+ throw Object.assign(new Error(`glb fetch failed: ${err?.message || err}`), {
+ status: err?.code === 'file_too_large' ? 413 : 400,
+ code: err?.code || 'glb_fetch_failed',
+ });
+ }
const browser = await getBrowser();
const page = await browser.newPage();
try {
await page.setViewport({ width: W, height: H, deviceScaleFactor: 1 });
- const html = viewerHtml({ glbUrl, width: W, height: H, background, pose, cameraOrbit, expression });
+ const html = viewerHtml({ glbBase64, width: W, height: H, background, pose, cameraOrbit, expression });
await page.setContent(html, { waitUntil: 'domcontentloaded' });
await page.waitForFunction(
'window.__renderDone === true || window.__renderError !== null',
diff --git a/api/_lib/render-glb.js b/api/_lib/render-glb.js
index 933e07e0b..25133ce41 100644
--- a/api/_lib/render-glb.js
+++ b/api/_lib/render-glb.js
@@ -13,6 +13,11 @@
// so Vercel's NFT doesn't statically trace the chromium tree for every route
// that transitively imports this module — that trace caused 45-min build hangs.
import { env } from './env.js';
+import { fetchModel } from './fetch-model.js';
+
+// Cap on GLB bytes pulled into the renderer. Anything larger risks OOM /
+// blowing the render budget; callers may tighten this via `maxBytes`.
+const DEFAULT_MAX_GLB_BYTES = 25 * 1024 * 1024;
// The "-min" build of @sparticuz/chromium ships without the chromium binary
// to keep the function bundle small. The binary is downloaded on first use
@@ -58,13 +63,14 @@ async function getBrowser() {
// Inline viewer HTML — bundled into the function so the renderer needs no
// extra static assets. three.js + GLTFLoader load from unpkg pinned to the
// installed version. window.__renderDone signals readiness to puppeteer.
-function viewerHtml({ glbUrl, width, height, background }) {
+function viewerHtml({ glbBase64, width, height, background }) {
const bg = background === 'transparent' ? 'null' : JSON.stringify(background || '#0a0a0a');
return `<!doctype html>
<html><head><meta charset="utf-8" />
<style>html,body{margin:0;padding:0;background:transparent;overflow:hidden}</style>
</head><body>
<canvas id="c" width="${width}" height="${height}" style="display:block;width:${width}px;height:${height}px"></canvas>
+<script>window.__GLB_B64=${JSON.stringify(glbBase64)};</script>
<script type="importmap">{ "imports": {
"three": "https://unpkg.com/three@${THREE_VERSION}/build/three.module.js",
"three/addons/": "https://unpkg.com/three@${THREE_VERSION}/examples/jsm/"
@@ -114,7 +120,10 @@ loader.setDRACOLoader(dracoLoader);
loader.setKTX2Loader(ktx2Loader);
loader.setMeshoptDecoder(MeshoptDecoder);
-loader.load(${JSON.stringify(glbUrl)}, (gltf) => {
+// The GLB bytes are fetched server-side through the SSRF-pinned fetchModel
+// path and embedded here as base64, so chromium never makes a network
+// request for the user-supplied URL (no DNS-rebinding / redirect SSRF).
+function onLoaded(gltf) {
try {
const root = gltf.scene;
scene.add(root);
@@ -140,9 +149,18 @@ loader.load(${JSON.stringify(glbUrl)}, (gltf) => {
} catch (err) {
window.__renderError = err.message || String(err);
}
-}, undefined, (err) => {
- window.__renderError = 'glb load failed: ' + (err?.message || err);
-});
+}
+
+(async () => {
+ try {
+ const buf = await (await fetch('data:application/octet-stream;base64,' + window.__GLB_B64)).arrayBuffer();
+ loader.parse(buf, '', onLoaded, (err) => {
+ window.__renderError = 'glb parse failed: ' + (err?.message || err);
+ });
+ } catch (err) {
+ window.__renderError = 'glb decode failed: ' + (err?.message || String(err));
+ }
+})();
</script></body></html>`;
}
@@ -156,15 +174,29 @@ loader.load(${JSON.stringify(glbUrl)}, (gltf) => {
* @param {string} [opts.background='#0a0a0a'] - 'transparent' or hex color
* @returns {Promise<Buffer>} PNG buffer
*/
-export async function renderGlbToPng({ glbUrl, width = 1200, height = 630, background = '#0a0a0a' } = {}) {
+export async function renderGlbToPng({ glbUrl, width = 1200, height = 630, background = '#0a0a0a', maxBytes = DEFAULT_MAX_GLB_BYTES } = {}) {
if (!glbUrl || typeof glbUrl !== 'string') {
throw Object.assign(new Error('glbUrl required'), { status: 400, code: 'invalid_args' });
}
+ // Pull the GLB through the SSRF-pinned fetcher (DNS-pinned per hop, redirects
+ // re-validated, byte cap enforced during download) so chromium never fetches
+ // the untrusted URL itself. This is the single boundary where the user URL
+ // touches the network — defeating DNS-rebinding and redirect-to-internal SSRF.
+ let glbBase64;
+ try {
+ const { bytes } = await fetchModel(glbUrl, { maxBytes });
+ glbBase64 = Buffer.from(bytes).toString('base64');
+ } catch (err) {
+ throw Object.assign(new Error(`glb fetch failed: ${err?.message || err}`), {
+ status: err?.code === 'file_too_large' ? 413 : 400,
+ code: err?.code || 'glb_fetch_failed',
+ });
+ }
const browser = await getBrowser();
const page = await browser.newPage();
try {
await page.setViewport({ width, height, deviceScaleFactor: 1 });
- const html = viewerHtml({ glbUrl, width, height, background });
+ const html = viewerHtml({ glbBase64, width, height, background });
// data: URL avoids needing a network fetch for the bootstrap page itself.
// importmap dependencies (three, GLTFLoader) still come from unpkg.
await page.setContent(html, { waitUntil: 'domcontentloaded' });
diff --git a/api/_lib/sdp.js b/api/_lib/sdp.js
new file mode 100644
index 000000000..9a7314ec6
--- /dev/null
+++ b/api/_lib/sdp.js
@@ -0,0 +1,210 @@
+// Shared client for the Solana Developer Platform (SDP) — the Solana
+// Foundation's enterprise API for custodial wallets, SPL token issuance,
+// payments, and compliance screening (https://platform.solana.com).
+//
+// Keeps SDP_API_KEY server-side and returns parsed JSON. Throws an Error
+// tagged with { status, code, detail } so proxy/handlers map upstream
+// failures to the right HTTP code without leaking the key. Never fabricates
+// data — upstream errors surface verbatim.
+//
+// Auth: project-scoped API key in the Authorization header (Bearer). The
+// `/health` and `/openapi.json` surfaces need no key, so health checks work
+// even on a deployment that hasn't been wired with credentials yet.
+
+// Production API host. Override with SDP_API_BASE to point at the sandbox or a
+// self-hosted deployment (the SDP API is a Cloudflare Worker — see
+// solana-foundation/solana-developer-platform). Sandbox vs. production is
+// otherwise selected by which API key you use; the wire surface is identical.
+const DEFAULT_BASE = 'https://api.solana.com';
+
+// Versioned API segments the proxy is willing to forward (everything under
+// `/v1`). The list mirrors the SDP Hono router's v1 mounts so we never forward
+// to a path the upstream doesn't serve — and so this can't be turned into an
+// open proxy to arbitrary hosts/paths. Keep in sync with the upstream
+// `apps/sdp-api/src/app.ts` router.
+export const SDP_V1_RESOURCES = Object.freeze([
+ 'organizations',
+ 'api-keys',
+ 'counterparties',
+ 'members',
+ 'auth',
+ 'projects',
+ 'rpc',
+ 'issuance',
+ 'wallets',
+ 'onboarding',
+ 'payments',
+ 'compliance',
+]);
+
+// Top-level (un-versioned) paths the upstream serves directly. `health` and
+// `openapi.json` are unauthenticated; `llms.txt` is the machine-readable doc.
+export const SDP_TOP_LEVEL = Object.freeze(['health', 'openapi.json', 'llms.txt']);
+
+export function sdpConfigured() {
+ return !!process.env.SDP_API_KEY;
+}
+
+export function sdpBase() {
+ const raw = process.env.SDP_API_BASE || DEFAULT_BASE;
+ return raw.replace(/\/+$/, '');
+}
+
+// True when `path` (no leading slash, no query) is a surface the upstream
+// actually serves. Used by the proxy allowlist.
+export function isSdpAllowedPath(path) {
+ const clean = String(path || '').replace(/^\/+/, '');
+ if (!clean || clean.includes('..')) return false;
+ if (SDP_TOP_LEVEL.includes(clean)) return true;
+ if (clean === 'health/ready') return true;
+ if (clean.startsWith('v1/')) {
+ const resource = clean.slice(3).split('/')[0];
+ return SDP_V1_RESOURCES.includes(resource);
+ }
+ return false;
+}
+
+// Whether a given SDP path requires our server-side API key. Health and the
+// public doc/spec surfaces don't, so they stay reachable on an unconfigured
+// deployment (returning the upstream's real status rather than a fake 503).
+export function sdpPathNeedsKey(path) {
+ const clean = String(path || '').replace(/^\/+/, '');
+ if (clean === 'health' || clean === 'health/ready') return false;
+ if (clean === 'openapi.json' || clean === 'llms.txt') return false;
+ return true;
+}
+
+// Core request. Returns { status, headers, body } where body is parsed JSON
+// when the upstream sends JSON, otherwise the raw text. Throws (tagged with
+// { status }) only on transport failure or missing-credential — HTTP error
+// statuses from the upstream are returned, not thrown, so the proxy can relay
+// the upstream's own error envelope and status code faithfully.
+export async function sdpRequest(
+ path,
+ { method = 'GET', query, body, headers = {}, timeoutMs = 15_000 } = {},
+) {
+ const clean = String(path || '').replace(/^\/+/, '');
+ if (!isSdpAllowedPath(clean)) {
+ throw Object.assign(new Error(`SDP path not allowed: ${clean}`), { status: 404 });
+ }
+
+ const needsKey = sdpPathNeedsKey(clean);
+ const apiKey = process.env.SDP_API_KEY;
+ if (needsKey && !apiKey) {
+ throw Object.assign(
+ new Error('Solana Developer Platform is not configured (set SDP_API_KEY)'),
+ { status: 503 },
+ );
+ }
+
+ let url = `${sdpBase()}/${clean}`;
+ if (query && typeof query === 'object') {
+ const qs = new URLSearchParams();
+ for (const [k, v] of Object.entries(query)) {
+ if (v != null && v !== '') qs.set(k, String(v));
+ }
+ const s = qs.toString();
+ if (s) url += `?${s}`;
+ }
+
+ const reqHeaders = { accept: 'application/json', ...headers };
+ if (apiKey) reqHeaders.authorization = `Bearer ${apiKey}`;
+
+ const init = { method, headers: reqHeaders, signal: AbortSignal.timeout(timeoutMs) };
+ if (body != null && method !== 'GET' && method !== 'HEAD') {
+ init.body = typeof body === 'string' ? body : JSON.stringify(body);
+ reqHeaders['content-type'] = 'application/json';
+ }
+
+ let upstream;
+ try {
+ upstream = await fetch(url, init);
+ } catch (e) {
+ const reason = e?.name === 'TimeoutError' ? 'timed out' : e?.message || 'unreachable';
+ throw Object.assign(new Error(`Solana Developer Platform ${reason}`), { status: 504 });
+ }
+
+ const ct = upstream.headers.get('content-type') || '';
+ const raw = await upstream.text();
+ let parsed = raw;
+ if (ct.includes('application/json') && raw) {
+ try {
+ parsed = JSON.parse(raw);
+ } catch {
+ parsed = raw;
+ }
+ }
+
+ return {
+ status: upstream.status,
+ contentType: ct,
+ traceId: upstream.headers.get('x-sdp-trace-id') || null,
+ body: parsed,
+ };
+}
+
+// Convenience wrapper that throws on any non-2xx, surfacing the upstream's
+// structured error ({ error: { code, message } }). Use from server-side code
+// that wants a value-or-throw contract rather than the raw envelope.
+export async function sdpCall(path, opts = {}) {
+ const res = await sdpRequest(path, opts);
+ if (res.status >= 200 && res.status < 300) return res.body;
+ const err = res.body?.error;
+ const message = err?.message || (typeof res.body === 'string' ? res.body : 'request failed');
+ throw Object.assign(new Error(`SDP ${res.status}: ${String(message).slice(0, 300)}`), {
+ status: res.status,
+ code: err?.code || 'sdp_error',
+ traceId: res.traceId,
+ });
+}
+
+// ── Typed helpers for the common surfaces ────────────────────────────────────
+
+export function sdpHealth() {
+ return sdpCall('health');
+}
+
+export function sdpListWallets(query) {
+ return sdpCall('v1/wallets', { query });
+}
+
+export function sdpGetWallet(walletId) {
+ return sdpCall(`v1/wallets/${encodeURIComponent(walletId)}`);
+}
+
+export function sdpCreateWallet(payload, idempotencyKey) {
+ return sdpCall('v1/wallets', {
+ method: 'POST',
+ body: payload,
+ headers: idempotencyKey ? { 'idempotency-key': idempotencyKey } : {},
+ });
+}
+
+export function sdpListIssuances(query) {
+ return sdpCall('v1/issuance', { query });
+}
+
+export function sdpCreateIssuance(payload, idempotencyKey) {
+ return sdpCall('v1/issuance', {
+ method: 'POST',
+ body: payload,
+ headers: idempotencyKey ? { 'idempotency-key': idempotencyKey } : {},
+ });
+}
+
+export function sdpListPayments(query) {
+ return sdpCall('v1/payments', { query });
+}
+
+export function sdpCreatePayment(payload, idempotencyKey) {
+ return sdpCall('v1/payments', {
+ method: 'POST',
+ body: payload,
+ headers: idempotencyKey ? { 'idempotency-key': idempotencyKey } : {},
+ });
+}
+
+// Screen an address or transaction against the SDP compliance providers.
+export function sdpScreenCompliance(payload) {
+ return sdpCall('v1/compliance/screen', { method: 'POST', body: payload });
+}
diff --git a/api/admin/pump-cron-health.js b/api/admin/pump-cron-health.js
index f1600e72a..399199fd9 100644
--- a/api/admin/pump-cron-health.js
+++ b/api/admin/pump-cron-health.js
@@ -8,6 +8,7 @@ import { sql } from '../_lib/db.js';
import { requireAdmin } from '../_lib/admin.js';
import { cors, json, method, wrap } from '../_lib/http.js';
import { env } from '../_lib/env.js';
+import { constantTimeEquals } from '../_lib/crypto.js';
export default wrap(async (req, res) => {
if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;
@@ -17,7 +18,8 @@ export default wrap(async (req, res) => {
// be a real admin. The previous `user.plan === 'admin'` check was dead — there
// is no 'admin' plan (free|pro|team|enterprise) — so it rejected every admin.
const auth = req.headers.authorization || '';
- const isCron = env.CRON_SECRET && auth === `Bearer ${env.CRON_SECRET}`;
+ const bearer = auth.toLowerCase().startsWith('bearer ') ? auth.slice(7).trim() : '';
+ const isCron = !!env.CRON_SECRET && constantTimeEquals(bearer, env.CRON_SECRET);
if (!isCron) {
const admin = await requireAdmin(req, res);
if (!admin) return;
diff --git a/api/agent/send-sol.js b/api/agent/send-sol.js
index 9b0cb7eb8..21d499014 100644
--- a/api/agent/send-sol.js
+++ b/api/agent/send-sol.js
@@ -80,6 +80,19 @@ export default wrap(async (req, res) => {
}
recipient = cfg.defaultRecipient;
} else {
+ // Sending to a client-supplied address that isn't the configured default is
+ // the drain vector: without a gate, anyone (rotating IPs past the per-IP
+ // limit) can repeatedly pay themselves up to the per-send cap until the
+ // wallet is empty. Require the demo-token gate to be configured before
+ // honoring an arbitrary `to`; otherwise the wallet can only pay its default.
+ if (body.to && body.to !== cfg.defaultRecipient && !cfg.demoToken) {
+ return error(
+ res,
+ 403,
+ 'recipient_not_allowed',
+ 'sends to arbitrary recipients require AVATAR_DEMO_TOKEN; otherwise set AVATAR_LOCK_RECIPIENT to pin payouts to AVATAR_DEFAULT_RECIPIENT',
+ );
+ }
recipient = body.to || cfg.defaultRecipient;
}
if (!recipient) {
diff --git a/api/agents/solana/_handlers.js b/api/agents/solana/_handlers.js
index ecd087b4f..f1dc52889 100644
--- a/api/agents/solana/_handlers.js
+++ b/api/agents/solana/_handlers.js
@@ -201,6 +201,15 @@ export const handleMetadata = wrap(async (req, res) => {
}
}
+ // Prep bakes the resolved avatar media into the mint URI (img/anim) so the
+ // manifest is complete on the FIRST fetch — before the agent row above
+ // exists. The live DB values (when present) win; these are the fallback.
+ // Only http(s)/ipfs URLs are honoured: they are echoed into JSON, never
+ // fetched server-side, so this can't be turned into an SSRF vector.
+ const SAFE_MEDIA = /^(https?:|ipfs:)/i;
+ if (!image) { const q = url.searchParams.get('img'); if (q && SAFE_MEDIA.test(q)) image = q; }
+ if (!animationUrl) { const q = url.searchParams.get('anim'); if (q && SAFE_MEDIA.test(q)) animationUrl = q; }
+
const manifest = buildAgentManifest({
name,
description,
@@ -352,9 +361,18 @@ export const handleRegisterPrep = wrap(async (req, res) => {
const [walletRow] = await sql`select id from user_wallets where user_id = ${user.id} and address = ${wallet_address} and chain_type = 'solana' limit 1`;
if (!walletRow) return error(res, 403, 'forbidden', 'wallet not linked to your account');
+ // Resolve the avatar's media up front so it can be baked into the metadata
+ // URI as query-param fallbacks (img/anim). This makes the off-chain JSON
+ // complete from the very FIRST indexer fetch — before solana-register-confirm
+ // writes the agent row that handleMetadata normally joins against — closing
+ // the race where a DAS provider caches a body-less, image-less manifest.
+ let avatarImg = null;
+ let avatarAnim = null;
if (avatar_id) {
- const [av] = await sql`select id from avatars where id=${avatar_id} and owner_id=${user.id} and deleted_at is null limit 1`;
+ const [av] = await sql`select id, storage_key, thumbnail_key from avatars where id=${avatar_id} and owner_id=${user.id} and deleted_at is null limit 1`;
if (!av) return error(res, 404, 'not_found', 'avatar not found');
+ if (av.thumbnail_key) avatarImg = publicUrl(av.thumbnail_key);
+ if (av.storage_key) avatarAnim = publicUrl(av.storage_key);
}
if (vanity_prefix && !asset_pubkey) return error(res, 400, 'validation_error', 'vanity_prefix requires asset_pubkey');
@@ -391,7 +409,10 @@ export const handleRegisterPrep = wrap(async (req, res) => {
const passportUrl = `${appOrigin}/agent-passport.html?asset=${assetPubkey}&network=${network}`;
const metadataUri = body.metadata_uri
- || `${appOrigin}/api/agents/solana-metadata?asset=${assetPubkey}&network=${network}&name=${encodeURIComponent(name)}&desc=${encodeURIComponent(description)}`;
+ || `${appOrigin}/api/agents/solana-metadata?asset=${assetPubkey}&network=${network}`
+ + `&name=${encodeURIComponent(name)}&desc=${encodeURIComponent(description)}`
+ + (avatarImg ? `&img=${encodeURIComponent(avatarImg)}` : '')
+ + (avatarAnim ? `&anim=${encodeURIComponent(avatarAnim)}` : '');
// On-chain brand written into the asset account itself: three.ws identity,
// our links, and the $THREE mint (Attributes plugin) + an enforced 5%
diff --git a/api/cron/[name].js b/api/cron/[name].js
index 79bc1bfdb..e282a30c8 100644
--- a/api/cron/[name].js
+++ b/api/cron/[name].js
@@ -49,6 +49,31 @@ import { SOLANA_USDC_MINT, SOLANA_USDC_MINT_DEVNET } from '../payments/_config.j
import { chargeSubscription, failPayment } from '../_lib/subscription-billing.js';
import { sendEmail } from '../_lib/email.js';
import { fetchSafePublicUrl } from '../_lib/ssrf-guard.js';
+import { constantTimeEquals } from '../_lib/crypto.js';
+
+// ─── Cron auth ───────────────────────────────────────────────────────────────
+//
+// Every cron handler is privileged (some move funds). Vercel's scheduler always
+// sends `Authorization: Bearer $CRON_SECRET` on its invocations, so we require a
+// valid secret UNCONDITIONALLY and compare it constant-time. The presence of the
+// `x-vercel-cron` header is NOT trusted as authorization on its own — an inbound
+// request header is spoofable if it ever reaches the function unstripped, and
+// must never be allowed to skip the secret. Returns true on success; on failure
+// it writes the response and returns false (caller must `return`).
+function requireCron(req, res) {
+ const secret = process.env.CRON_SECRET || env.CRON_SECRET;
+ if (!secret) {
+ error(res, 503, 'not_configured', 'CRON_SECRET unset');
+ return false;
+ }
+ const auth = req.headers['authorization'] || '';
+ const token = auth.toLowerCase().startsWith('bearer ') ? auth.slice(7).trim() : '';
+ if (!constantTimeEquals(token, secret)) {
+ error(res, 401, 'unauthorized', 'cron secret required');
+ return false;
+ }
+ return true;
+}
// ─── Dispatcher ──────────────────────────────────────────────────────────────
@@ -120,12 +145,7 @@ const CRAWL_BUDGET_MS = 240_000;
async function handleErc8004Crawl(req, res) {
if (cors(req, res, { methods: 'GET,POST,OPTIONS' })) return;
- const auth = req.headers['authorization'] || '';
- const expected = process.env.CRON_SECRET ? `Bearer ${process.env.CRON_SECRET}` : null;
- const fromCron = req.headers['x-vercel-cron'] === '1';
- if (!fromCron && (!expected || auth !== expected)) {
- return error(res, 401, 'unauthorized', 'cron secret required');
- }
+ if (!requireCron(req, res)) return;
const crawlStart = Date.now();
const report = { chains: [], enriched: 0, errors: [] };
@@ -450,12 +470,7 @@ function idxRpcUrls(chainId) {
async function handleIndexDelegations(req, res) {
if (cors(req, res, { methods: 'GET,POST,OPTIONS' })) return;
- const auth = req.headers['authorization'] || '';
- const expected = env.CRON_SECRET ? `Bearer ${env.CRON_SECRET}` : null;
- const fromCron = req.headers['x-vercel-cron'] === '1';
- if (!fromCron && (!expected || auth !== expected)) {
- return error(res, 401, 'unauthorized', 'cron secret required');
- }
+ if (!requireCron(req, res)) return;
const started = Date.now();
const report = { chains: [], expiredSwept: 0, errors: [] };
@@ -748,13 +763,7 @@ async function handlePumpAgentStats(req, res) {
if (cors(req, res, { methods: 'GET,POST,OPTIONS' })) return;
if (!method(req, res, ['GET', 'POST'])) return;
- const auth = req.headers.authorization || '';
- const fromCron = req.headers['x-vercel-cron'] === '1';
- if (!fromCron) {
- if (!env.CRON_SECRET) return error(res, 503, 'not_configured', 'CRON_SECRET unset');
- if (auth !== `Bearer ${env.CRON_SECRET}`)
- return error(res, 401, 'unauthorized', 'cron auth required');
- }
+ if (!requireCron(req, res)) return;
const mints = await sql`
select id, mint, network from pump_agent_mints
@@ -993,12 +1002,7 @@ const WHALE_TRADE_USD_FLOOR = 1_000;
async function handlePumpfunMonitor(req, res) {
if (cors(req, res, { methods: 'GET,POST,OPTIONS' })) return;
- const auth = req.headers['authorization'] || '';
- const expected = process.env.CRON_SECRET ? `Bearer ${process.env.CRON_SECRET}` : null;
- const fromCron = req.headers['x-vercel-cron'] === '1';
- if (!fromCron && (!expected || auth !== expected)) {
- return error(res, 401, 'unauthorized', 'cron secret required');
- }
+ if (!requireCron(req, res)) return;
// Heartbeat + per-user alert evaluation run on every tick regardless of
// attester provisioning, so /api/healthz reports real bot status and the
@@ -1293,12 +1297,7 @@ const SIGNAL_WEIGHT = {
async function handlePumpfunSignals(req, res) {
if (cors(req, res, { methods: 'GET,POST,OPTIONS' })) return;
- const auth = req.headers['authorization'] || '';
- const expected = process.env.CRON_SECRET ? `Bearer ${process.env.CRON_SECRET}` : null;
- const fromCron = req.headers['x-vercel-cron'] === '1';
- if (!fromCron && (!expected || auth !== expected)) {
- return error(res, 401, 'unauthorized', 'cron secret required');
- }
+ if (!requireCron(req, res)) return;
if (!pumpfunBotEnabled()) {
return json(res, 200, { skipped: 'pumpfun bot not configured' });
@@ -1440,11 +1439,7 @@ async function handleRunBuyback(req, res) {
if (cors(req, res, { methods: 'GET,POST,OPTIONS', origins: '*' })) return;
if (!method(req, res, ['GET', 'POST'])) return;
- const auth = req.headers.authorization || '';
- if (!env.CRON_SECRET) return error(res, 503, 'not_configured', 'CRON_SECRET unset');
- if (auth !== `Bearer ${env.CRON_SECRET}`) {
- return error(res, 401, 'unauthorized', 'cron auth required');
- }
+ if (!requireCron(req, res)) return;
const relayer = await buybackLoadRelayer();
@@ -1867,13 +1862,7 @@ async function dcaOnPeriod(strategy) {
async function handleRunDca(req, res) {
// Vercel cron passes Authorization: Bearer $CRON_SECRET
- const cronSecret = env.CRON_SECRET;
- if (cronSecret) {
- const auth = req.headers.authorization || '';
- if (auth !== `Bearer ${cronSecret}`) {
- return error(res, 401, 'unauthorized', 'invalid cron secret');
- }
- }
+ if (!requireCron(req, res)) return;
const runId = globalThis.crypto?.randomUUID?.() ?? `run_${Date.now()}`;
dcaLog('info', 'tick_start', { run_id: runId });
@@ -2054,13 +2043,8 @@ async function handleRunDistributePayments(req, res) {
if (cors(req, res, { methods: 'GET,POST,OPTIONS', origins: '*' })) return;
if (!method(req, res, ['GET', 'POST'])) return;
- // Auth: cron secret OR admin bearer.
- const auth = req.headers.authorization || '';
- const cronSecret = env.CRON_SECRET;
- if (!cronSecret) return error(res, 503, 'not_configured', 'CRON_SECRET unset');
- if (auth !== `Bearer ${cronSecret}`) {
- return error(res, 401, 'unauthorized', 'cron auth required');
- }
+ // Auth: Vercel cron secret (constant-time, unconditional).
+ if (!requireCron(req, res)) return;
// Pick mints to consider: those with confirmed payments since last
// distribute run, or never run before.
@@ -2238,20 +2222,13 @@ function subWithTimeout(promise, ms, label) {
async function handleRunSubscriptions(req, res) {
if (cors(req, res, { methods: 'GET,POST,OPTIONS' })) return;
- // Auth: Vercel Cron header OR explicit Bearer $CRON_SECRET.
- // If neither is configured AND no Vercel cron header is present, reject.
- const auth = req.headers['authorization'] ?? '';
- const expected = env.CRON_SECRET ? `Bearer ${env.CRON_SECRET}` : null;
- const fromVercelCron = req.headers['x-vercel-cron'] === '1';
- if (!fromVercelCron) {
- if (!expected || auth !== expected) {
- return error(res, 401, 'unauthorized', 'cron secret required');
- }
- }
+ // Auth: Vercel cron secret (constant-time, unconditional — the scheduler
+ // always sends Authorization: Bearer $CRON_SECRET).
+ if (!requireCron(req, res)) return;
const runId = `sub-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
const runStart = Date.now();
- subLog('subscription_cron.start', { runId, fromVercelCron });
+ subLog('subscription_cron.start', { runId });
const origin = env.APP_ORIGIN;
const relayerToken = env.CRON_SECRET ?? '';
@@ -2523,12 +2500,7 @@ const STALE_AFTER_SECS = 60 * 60; // 1 hour
async function handleSolanaAttestEventCleanup(req, res) {
if (cors(req, res, { methods: 'GET,POST,OPTIONS' })) return;
- const auth = req.headers['authorization'] || '';
- const expected = process.env.CRON_SECRET ? `Bearer ${process.env.CRON_SECRET}` : null;
- const fromCron = req.headers['x-vercel-cron'] === '1';
- if (!fromCron && (!expected || auth !== expected)) {
- return error(res, 401, 'unauthorized', 'cron secret required');
- }
+ if (!requireCron(req, res)) return;
const result = await sql`
delete from solana_attest_event_claims
@@ -2553,12 +2525,7 @@ const SOL_ATTEST_PER_RUN_MAX = 50; // bound RPC fan-out per cron tick
async function handleSolanaAttestationsCrawl(req, res) {
if (cors(req, res, { methods: 'GET,POST,OPTIONS' })) return;
- const auth = req.headers['authorization'] || '';
- const expected = process.env.CRON_SECRET ? `Bearer ${process.env.CRON_SECRET}` : null;
- const fromCron = req.headers['x-vercel-cron'] === '1';
- if (!fromCron && (!expected || auth !== expected)) {
- return error(res, 401, 'unauthorized', 'cron secret required');
- }
+ if (!requireCron(req, res)) return;
// Pull Solana agents, oldest-cursor first.
const agents = await sql`
@@ -2601,12 +2568,7 @@ async function handleSolanaAttestationsCrawl(req, res) {
async function handleProcessSubscriptions(req, res) {
if (cors(req, res, { methods: 'GET,POST,OPTIONS' })) return;
- const auth = req.headers['authorization'] || '';
- const cronSecret = env.CRON_SECRET;
- const fromCron = req.headers['x-vercel-cron'] === '1';
- if (!fromCron && cronSecret && auth !== `Bearer ${cronSecret}`) {
- return error(res, 401, 'unauthorized', 'cron secret required');
- }
+ if (!requireCron(req, res)) return;
const runId = `psub-${Date.now()}`;
const report = {
@@ -2726,12 +2688,7 @@ async function handleProcessSubscriptions(req, res) {
async function handleSettleRoyalties(req, res) {
if (cors(req, res, { methods: 'GET,POST,OPTIONS' })) return;
- const auth = req.headers['authorization'] || '';
- const cronSecret = env.CRON_SECRET;
- const fromCron = req.headers['x-vercel-cron'] === '1';
- if (!fromCron && cronSecret && auth !== `Bearer ${cronSecret}`) {
- return error(res, 401, 'unauthorized', 'cron secret required');
- }
+ if (!requireCron(req, res)) return;
const { settleAllPendingRoyalties } = await import('../_lib/royalty.js');
const report = await settleAllPendingRoyalties();
@@ -2747,12 +2704,7 @@ const AUDIT_LOG_RETENTION_DAYS = 365;
async function handleAuditLogCleanup(req, res) {
if (cors(req, res, { methods: 'GET,POST,OPTIONS' })) return;
- const auth = req.headers['authorization'] || '';
- const cronSecret = env.CRON_SECRET;
- const fromCron = req.headers['x-vercel-cron'] === '1';
- if (!fromCron && cronSecret && auth !== `Bearer ${cronSecret}`) {
- return error(res, 401, 'unauthorized', 'cron secret required');
- }
+ if (!requireCron(req, res)) return;
const result = await sql`
delete from audit_log
@@ -2770,12 +2722,7 @@ async function handleAuditLogCleanup(req, res) {
async function handleExpirePendingPurchases(req, res) {
if (!method(req, res, ['GET'])) return;
- const auth = req.headers['authorization'] || '';
- const cronSecret = env.CRON_SECRET;
- const fromCron = req.headers['x-vercel-cron'] === '1';
- if (!fromCron && cronSecret && auth !== `Bearer ${cronSecret}`) {
- return error(res, 401, 'unauthorized', 'cron secret required');
- }
+ if (!requireCron(req, res)) return;
const result = await sql`
UPDATE skill_purchases
SET status = 'expired', updated_at = now()
@@ -2791,12 +2738,7 @@ async function handleExpirePendingPurchases(req, res) {
async function handleCleanupCsrfTokens(req, res) {
if (!method(req, res, ['GET'])) return;
- const auth = req.headers['authorization'] || '';
- const cronSecret = env.CRON_SECRET;
- const fromCron = req.headers['x-vercel-cron'] === '1';
- if (!fromCron && cronSecret && auth !== `Bearer ${cronSecret}`) {
- return error(res, 401, 'unauthorized', 'cron secret required');
- }
+ if (!requireCron(req, res)) return;
const result = await sql`DELETE FROM csrf_tokens WHERE expires_at < now() RETURNING token`;
return json(res, 200, { deleted: result.length });
}
@@ -2811,12 +2753,7 @@ async function handleCleanupCsrfTokens(req, res) {
async function handleSiwxGc(req, res) {
if (cors(req, res, { methods: 'GET,POST,OPTIONS' })) return;
- const auth = req.headers['authorization'] || '';
- const expected = env.CRON_SECRET ? `Bearer ${env.CRON_SECRET}` : null;
- const fromCron = req.headers['x-vercel-cron'] === '1';
- if (!fromCron && (!expected || auth !== expected)) {
- return error(res, 401, 'unauthorized', 'cron secret required');
- }
+ if (!requireCron(req, res)) return;
const { pruneOldNonces, pruneExpiredPayments } = await import('../_lib/siwx-storage.js');
@@ -2846,12 +2783,7 @@ const WITHDRAWALS_BATCH = 20;
async function handleProcessWithdrawals(req, res) {
if (cors(req, res, { methods: 'GET,POST,OPTIONS' })) return;
- const auth = req.headers['authorization'] || '';
- const cronSecret = env.CRON_SECRET;
- const fromCron = req.headers['x-vercel-cron'] === '1';
- if (!fromCron && cronSecret && auth !== `Bearer ${cronSecret}`) {
- return error(res, 401, 'unauthorized', 'cron secret required');
- }
+ if (!requireCron(req, res)) return;
const treasuryKeypair = process.env.TREASURY_KEYPAIR || process.env.PLATFORM_TREASURY_KEYPAIR;
const evmTreasuryKey = process.env.EVM_TREASURY_PRIVATE_KEY;
@@ -3020,12 +2952,7 @@ async function handleProcessWithdrawals(req, res) {
async function handleRunXScheduledPosts(req, res) {
if (cors(req, res, { methods: 'GET,POST,OPTIONS' })) return;
- const auth = req.headers['authorization'] || '';
- const expected = env.CRON_SECRET ? `Bearer ${env.CRON_SECRET}` : null;
- const fromCron = req.headers['x-vercel-cron'] === '1';
- if (!fromCron && (!expected || auth !== expected)) {
- return error(res, 401, 'unauthorized', 'cron secret required');
- }
+ if (!requireCron(req, res)) return;
const { publishTweet, XPostError } = await import('../_lib/x-post.js');
@@ -3088,12 +3015,7 @@ const SOL_USD_FALLBACK = 150;
async function handleRunXTriggers(req, res) {
if (cors(req, res, { methods: 'GET,POST,OPTIONS' })) return;
- const auth = req.headers['authorization'] || '';
- const expected = env.CRON_SECRET ? `Bearer ${env.CRON_SECRET}` : null;
- const fromCron = req.headers['x-vercel-cron'] === '1';
- if (!fromCron && (!expected || auth !== expected)) {
- return error(res, 401, 'unauthorized', 'cron secret required');
- }
+ if (!requireCron(req, res)) return;
const started = Date.now();
let rows;
@@ -3395,12 +3317,7 @@ async function evalPaymentReceived(t) {
async function handleFetchXMetrics(req, res) {
if (cors(req, res, { methods: 'GET,POST,OPTIONS' })) return;
- const auth = req.headers['authorization'] || '';
- const expected = env.CRON_SECRET ? `Bearer ${env.CRON_SECRET}` : null;
- const fromCron = req.headers['x-vercel-cron'] === '1';
- if (!fromCron && (!expected || auth !== expected)) {
- return error(res, 401, 'unauthorized', 'cron secret required');
- }
+ if (!requireCron(req, res)) return;
const { decryptToken } = await import('../auth/x/[action].js');
@@ -3482,12 +3399,7 @@ async function handleRunCoinCycle(req, res) {
if (cors(req, res, { methods: 'GET,POST,OPTIONS' })) return;
if (!method(req, res, ['GET', 'POST'])) return;
- const auth = req.headers['authorization'] || '';
- const expected = process.env.CRON_SECRET ? `Bearer ${process.env.CRON_SECRET}` : null;
- const fromCron = req.headers['x-vercel-cron'] === '1';
- if (!fromCron && (!expected || auth !== expected)) {
- return error(res, 401, 'unauthorized', 'cron secret required');
- }
+ if (!requireCron(req, res)) return;
// Demo gate: cron is wired in vercel.json but stays a no-op until the
// operator opts in by setting COIN_DEMO_ENABLED=true in env. Until then
@@ -3585,12 +3497,7 @@ async function handleRunCoinPayouts(req, res) {
if (cors(req, res, { methods: 'GET,POST,OPTIONS' })) return;
if (!method(req, res, ['GET', 'POST'])) return;
- const auth = req.headers['authorization'] || '';
- const expected = process.env.CRON_SECRET ? `Bearer ${process.env.CRON_SECRET}` : null;
- const fromCron = req.headers['x-vercel-cron'] === '1';
- if (!fromCron && (!expected || auth !== expected)) {
- return error(res, 401, 'unauthorized', 'cron secret required');
- }
+ if (!requireCron(req, res)) return;
// Demo gate — see handleRunCoinCycle. Until COIN_DEMO_ENABLED=true is set,
// the payout drainer cannot fire even if rows are pending.
@@ -3622,12 +3529,7 @@ async function handleClubPayouts(req, res) {
if (cors(req, res, { methods: 'GET,POST,OPTIONS' })) return;
if (!method(req, res, ['GET', 'POST'])) return;
- const auth = req.headers['authorization'] || '';
- const expected = process.env.CRON_SECRET ? `Bearer ${process.env.CRON_SECRET}` : null;
- const fromCron = req.headers['x-vercel-cron'] === '1';
- if (!fromCron && (!expected || auth !== expected)) {
- return error(res, 401, 'unauthorized', 'cron secret required');
- }
+ if (!requireCron(req, res)) return;
const { runClubPayoutSweep, expireStaleClaims } = await import('../_lib/club/sweep.js');
@@ -3651,12 +3553,7 @@ async function handleUnstoppableTick(req, res) {
if (cors(req, res, { methods: 'GET,POST,OPTIONS' })) return;
if (!method(req, res, ['GET', 'POST'])) return;
- const auth = req.headers['authorization'] || '';
- const expected = process.env.CRON_SECRET ? `Bearer ${process.env.CRON_SECRET}` : null;
- const fromCron = req.headers['x-vercel-cron'] === '1';
- if (!fromCron && (!expected || auth !== expected)) {
- return error(res, 401, 'unauthorized', 'cron secret required');
- }
+ if (!requireCron(req, res)) return;
try {
const { tick } = await import('../../agents/unstoppable/src/loop.js');
diff --git a/api/monetization/withdrawals.js b/api/monetization/withdrawals.js
index 31fbe4c5c..f146db06c 100644
--- a/api/monetization/withdrawals.js
+++ b/api/monetization/withdrawals.js
@@ -175,13 +175,47 @@ export default wrap(async (req, res) => {
return error(res, 422, 'insufficient_balance', `Insufficient balance for withdrawal. Available: ${(balance.available / 1_000_000).toFixed(6)} USDC`);
}
- const [withdrawal] = await sql`
- INSERT INTO agent_withdrawals
- (user_id, agent_id, amount, currency_mint, chain, to_address, status)
- VALUES
- (${userId}, ${agent_id}, ${amountAtomic}, ${currencyMint}, ${wallet.chain}, ${wallet.address}, 'pending')
- RETURNING id, agent_id, amount, currency_mint, chain, to_address, status, tx_signature, created_at, updated_at
- `;
+ // Reserve the withdrawal atomically. The available-balance check above is a
+ // fast/UX pre-check only — on its own it's a TOCTOU hole: N concurrent
+ // requests all read the same `available` and all insert, over-withdrawing
+ // past the real balance (the per-user rate limit admits several before any
+ // pending row is committed, so it can't guarantee integrity).
+ //
+ // pg_advisory_xact_lock serializes concurrent requests for the same
+ // (user, mint); the conditional INSERT…SELECT then re-derives available
+ // (earned − pending/processing/completed, mirroring getAvailableBalance)
+ // inside the locked transaction and refuses to insert when the amount
+ // exceeds it. Matches api/billing/withdrawals/index.js.
+ const lockKey = `withdrawal:${userId}:${currencyMint}`;
+ const [, inserted] = await sql.transaction([
+ sql`select pg_advisory_xact_lock(hashtextextended(${lockKey}, 0))`,
+ sql`
+ INSERT INTO agent_withdrawals
+ (user_id, agent_id, amount, currency_mint, chain, to_address, status)
+ SELECT ${userId}, ${agent_id}, ${amountAtomic}, ${currencyMint}, ${wallet.chain}, ${wallet.address}, 'pending'
+ WHERE ${amountAtomic} <= (
+ (
+ SELECT COALESCE(SUM(re.net_amount), 0)::bigint
+ FROM agent_revenue_events re
+ JOIN agent_identities ai ON ai.id = re.agent_id
+ WHERE ai.user_id = ${userId}
+ AND re.currency_mint = ${currencyMint}
+ ) - (
+ SELECT COALESCE(SUM(w2.amount), 0)::bigint
+ FROM agent_withdrawals w2
+ WHERE w2.user_id = ${userId}
+ AND w2.currency_mint = ${currencyMint}
+ AND w2.status IN ('pending', 'processing', 'completed')
+ )
+ )
+ RETURNING id, agent_id, amount, currency_mint, chain, to_address, status, tx_signature, created_at, updated_at
+ `,
+ ]);
+
+ const withdrawal = inserted?.[0];
+ if (!withdrawal) {
+ return error(res, 422, 'insufficient_balance', `Insufficient balance for withdrawal. Available: ${(balance.available / 1_000_000).toFixed(6)} USDC`);
+ }
return json(res, 201, {
withdrawal: formatWithdrawal(withdrawal),
diff --git a/api/oauth/[action].js b/api/oauth/[action].js
index fb86fade2..99dbe2013 100644
--- a/api/oauth/[action].js
+++ b/api/oauth/[action].js
@@ -37,6 +37,20 @@ function intersectScopes(requested, allowed) {
return requested.split(/\s+/).filter((s) => a.has(s)).join(' ') || allowed;
}
+// Scopes a dynamically-registered client may request. Anything outside this set
+// (notably privileged scopes like `permissions:redeem`, which authorizes
+// gas-spending on-chain redemption) is silently dropped at registration so a
+// self-registering client can never mint a token carrying it.
+const REGISTERABLE_SCOPES = new Set([
+ 'avatars:read', 'avatars:write', 'avatars:delete', 'profile',
+ 'memory:read', 'memory:write', 'agents:read', 'agents:write', 'offline_access',
+]);
+
+function filterRegisterableScope(requested) {
+ const kept = String(requested || '').split(/\s+/).filter((s) => REGISTERABLE_SCOPES.has(s));
+ return kept.length ? kept.join(' ') : 'avatars:read';
+}
+
function scopeLabel(s) {
const labels = { 'avatars:read': 'Read your avatars', 'avatars:write': 'Create and update avatars', 'avatars:delete': 'Delete your avatars', profile: 'See your name and email', offline_access: 'Stay signed in across sessions', 'memory:read': 'Recall your agents’ memories', 'memory:write': 'Store and forget your agents’ memories', 'agents:read': 'Screen your agents’ identities', 'agents:write': 'Register your agents on-chain' };
return labels[s] || esc(s);
@@ -207,7 +221,7 @@ async function handleRegister(req, res) {
const clientId = `mcp_${randomToken(18)}`;
let clientSecret = null, secretHash = null;
if (clientType === 'confidential') { clientSecret = randomToken(32); secretHash = await sha256(clientSecret); }
- const scope = body.scope ?? 'avatars:read';
+ const scope = filterRegisterableScope(body.scope ?? 'avatars:read');
const grantTypes = body.grant_types ?? ['authorization_code', 'refresh_token'];
const responseTypes = body.response_types ?? ['code'];
await sql`insert into oauth_clients (client_id, client_secret_hash, client_type, name, logo_uri, client_uri, redirect_uris, grant_types, response_types, token_endpoint_auth, scope, software_id, software_version, dynamically_registered) values (${clientId}, ${secretHash}, ${clientType}, ${body.client_name ?? 'MCP Client'}, ${body.logo_uri ?? null}, ${body.client_uri ?? null}, ${body.redirect_uris}, ${grantTypes}, ${responseTypes}, ${authMethod}, ${scope}, ${body.software_id ?? null}, ${body.software_version ?? null}, true)`;
diff --git a/api/permissions/[action].js b/api/permissions/[action].js
index 4c83ec561..5e725acc0 100644
--- a/api/permissions/[action].js
+++ b/api/permissions/[action].js
@@ -731,6 +731,21 @@ async function handleRedeem(req, res) {
`;
if (!row) return error(res, 404, 'delegation_not_found', 'delegation not found');
+ // Ownership binding: the bearer principal must own the agent this delegation
+ // belongs to. Without this, any token carrying the `permissions:redeem` scope
+ // could force redemption of ANY delegation by id (enumerating UUIDs) — spending
+ // the platform relayer's gas and triggering transfers the delegator didn't
+ // initiate. Mirror the owner gate used by the grant path.
+ const [owner] = await sql`
+ SELECT user_id FROM agent_identities
+ WHERE id = ${row.agent_id} AND deleted_at IS NULL
+ LIMIT 1
+ `;
+ if (!owner || owner.user_id !== bearer.userId) {
+ // 404 (not 403) so a caller can't probe which delegation ids exist.
+ return error(res, 404, 'delegation_not_found', 'delegation not found');
+ }
+
// Check status
if (row.status === 'revoked') {
return error(res, 409, 'delegation_revoked', 'delegation has been revoked');
diff --git a/api/render/avatar-clip.js b/api/render/avatar-clip.js
index 8d7afa1f4..00e69f72b 100644
--- a/api/render/avatar-clip.js
+++ b/api/render/avatar-clip.js
@@ -40,21 +40,6 @@ function rateCheck(ip) {
return { success: true, limit: RATE_LIMIT_MAX, remaining: RATE_LIMIT_MAX - arr.length, reset: now + RATE_LIMIT_WINDOW_MS };
}
-async function preflightSize(url) {
- try {
- const r = await fetch(url, { method: 'HEAD' });
- const lenHeader = r.headers.get('content-length');
- if (!lenHeader) return { ok: true, size: null };
- const size = Number(lenHeader);
- if (Number.isFinite(size) && size > MAX_GLB_BYTES) {
- return { ok: false, code: 'glb_too_large', size, limit: MAX_GLB_BYTES };
- }
- return { ok: true, size };
- } catch {
- return { ok: true, size: null };
- }
-}
-
export default wrap(async function handler(req, res) {
if (cors(req, res, { methods: 'GET,POST,OPTIONS' })) return;
@@ -85,8 +70,8 @@ export default wrap(async function handler(req, res) {
const glbUrl = typeof body.glbUrl === 'string' ? body.glbUrl.trim() : '';
if (!glbUrl) return error(res, 400, 'bad_request', 'glbUrl is required');
- // DNS-resolving SSRF guard (see render/glb.js) — headless chromium loads this
- // URL inside the function, so a prefix denylist was bypassable.
+ // Fast pre-check before booting chromium. The authoritative SSRF boundary is
+ // renderClip → fetchModel (DNS-pinned per hop, redirects re-validated, capped).
try {
await assertSafePublicUrl(glbUrl, { allowHttp: true });
} catch (e) {
@@ -117,14 +102,9 @@ export default wrap(async function handler(req, res) {
const expression = body.expression && typeof body.expression === 'object' ? body.expression : null;
- const pre = await preflightSize(glbUrl);
- if (!pre.ok) {
- return error(res, 413, pre.code, `GLB is ${pre.size} bytes; limit is ${pre.limit}`, { size: pre.size, limit: pre.limit });
- }
-
let result;
try {
- result = await renderClip({ glbUrl, width, height, background, posePresetId, cameraOrbit, expression });
+ result = await renderClip({ glbUrl, width, height, background, posePresetId, cameraOrbit, expression, maxBytes: MAX_GLB_BYTES });
} catch (err) {
const status = err?.status || 502;
return error(res, status, err?.code || 'render_failed', err?.message || 'render failed');
diff --git a/api/render/glb.js b/api/render/glb.js
index 8fc2304bd..b2f1e60aa 100644
--- a/api/render/glb.js
+++ b/api/render/glb.js
@@ -46,23 +46,6 @@ function rateCheck(ip) {
return { success: true, limit: RATE_LIMIT_MAX, remaining: RATE_LIMIT_MAX - arr.length, reset: now + RATE_LIMIT_WINDOW_MS };
}
-async function preflightSize(url) {
- try {
- const r = await fetch(url, { method: 'HEAD' });
- const lenHeader = r.headers.get('content-length');
- if (!lenHeader) return { ok: true, size: null };
- const size = Number(lenHeader);
- if (Number.isFinite(size) && size > MAX_GLB_BYTES) {
- return { ok: false, code: 'glb_too_large', size, limit: MAX_GLB_BYTES };
- }
- return { ok: true, size };
- } catch {
- // Origins that don't support HEAD will still be filtered by chromium's
- // 15s render budget. Don't fail closed on a HEAD timeout.
- return { ok: true, size: null };
- }
-}
-
export default wrap(async function handler(req, res) {
if (cors(req, res, { methods: 'POST,OPTIONS' })) return;
if (!method(req, res, ['POST'])) return;
@@ -82,10 +65,10 @@ export default wrap(async function handler(req, res) {
const glbUrl = typeof body.glbUrl === 'string' ? body.glbUrl.trim() : '';
if (!glbUrl) return error(res, 400, 'bad_request', 'glbUrl is required');
- // DNS-resolving SSRF guard: rejects any host that resolves to a private,
- // loopback, link-local, or cloud-metadata range. The headless chromium that
- // loads this URL runs inside the function, so a naive prefix denylist (the
- // previous check) was bypassable via DNS rebinding, 172.16/12, IPv6, etc.
+ // Fast, cheap rejection before booting chromium. The authoritative SSRF
+ // boundary is renderGlbToPng → fetchModel, which pins DNS per hop and
+ // re-validates every redirect; this pre-check just avoids the chromium spin-up
+ // for an obviously-private host. allowHttp mirrors the renderer's fetcher.
try {
await assertSafePublicUrl(glbUrl, { allowHttp: true });
} catch (e) {
@@ -97,14 +80,9 @@ export default wrap(async function handler(req, res) {
const height = Math.max(MIN_DIM, Math.min(MAX_DIM, Number(body.height) || 1024));
const background = body.background === 'transparent' ? 'transparent' : (typeof body.background === 'string' && body.background ? body.background : '#0a0a0a');
- const pre = await preflightSize(glbUrl);
- if (!pre.ok) {
- return error(res, 413, pre.code, `GLB is ${pre.size} bytes; limit is ${pre.limit}`, { size: pre.size, limit: pre.limit });
- }
-
let png;
try {
- png = await renderGlbToPng({ glbUrl, width, height, background });
+ png = await renderGlbToPng({ glbUrl, width, height, background, maxBytes: MAX_GLB_BYTES });
} catch (err) {
const status = err?.status || 502;
return error(res, status, err?.code || 'render_failed', err?.message || 'render failed');
diff --git a/api/sdp/[...path].js b/api/sdp/[...path].js
new file mode 100644
index 000000000..45a5eb8d2
--- /dev/null
+++ b/api/sdp/[...path].js
@@ -0,0 +1,108 @@
+// Same-origin proxy for the Solana Developer Platform (SDP) API
+// (https://platform.solana.com). Fronts the SDP v1 surface — custodial
+// wallets, SPL token issuance, payments, and compliance screening — under our
+// own origin so the browser never sees the SDP_API_KEY and never hits a vendor
+// host directly.
+//
+// GET /api/sdp/health -> SDP /health (no key)
+// GET /api/sdp/v1/wallets -> SDP /v1/wallets
+// POST /api/sdp/v1/issuance -> SDP /v1/issuance
+// POST /api/sdp/v1/compliance/screen -> SDP /v1/compliance/screen
+// ...
+//
+// Only the upstream's real route surface is forwardable (see isSdpAllowedPath);
+// anything else 404s, so this can't be turned into an open proxy. The caller's
+// Authorization header is ignored — we always attach our server-side key — so
+// the key can never be impersonated or exfiltrated.
+//
+// Authorization: the SDP key grants org-level control over custodial wallets,
+// SPL issuance, and payments — capabilities that must never be exposed to the
+// open internet. The path allowlist and per-IP rate limit are NOT access
+// controls; they only constrain which upstream route is hit and how often. So
+// every forwarding path requires an authenticated admin. The only exception is
+// the unauthenticated public surface (health/openapi/llms.txt — see
+// sdpPathNeedsKey), which the upstream itself serves without a key and which
+// exposes no org data.
+
+import { requireAdmin } from '../_lib/admin.js';
+import { isSameSiteOrigin } from '../_lib/auth.js';
+import { cors, error, json, method as methodGuard, rateLimited, readJson, wrap } from '../_lib/http.js';
+import { clientIp, limits } from '../_lib/rate-limit.js';
+import { isSdpAllowedPath, sdpPathNeedsKey, sdpRequest } from '../_lib/sdp.js';
+
+export const config = { runtime: 'nodejs' };
+
+const ALLOWED_METHODS = ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'];
+
+// Upstream request headers we relay from the caller. Authorization is
+// deliberately NOT here — the client lib attaches our own key.
+const FORWARDABLE_HEADERS = ['idempotency-key'];
+
+function joinPath(parts) {
+ if (Array.isArray(parts)) return parts.join('/');
+ return String(parts || '');
+}
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,POST,PUT,PATCH,DELETE,OPTIONS', credentials: false })) return;
+ if (!methodGuard(req, res, ALLOWED_METHODS)) return;
+
+ const path = decodeURIComponent(joinPath(req.query?.path)).replace(/^\/+/, '');
+ if (!isSdpAllowedPath(path)) {
+ return error(res, 404, 'not_found', `unknown Solana Developer Platform route: ${path}`);
+ }
+
+ const rl = await limits.sdpIp(clientIp(req));
+ if (!rl.success) return rateLimited(res, rl, 'too many Solana Developer Platform requests');
+
+ // Gate every privileged (key-bearing) route behind an authenticated admin.
+ // requireAdmin writes the 401/403 response itself and returns null on failure.
+ // The public health/doc surfaces (sdpPathNeedsKey === false) stay open so an
+ // unconfigured deployment's health checks keep working.
+ if (sdpPathNeedsKey(path)) {
+ const admin = await requireAdmin(req, res);
+ if (!admin) return;
+
+ // Defense in depth atop the SameSite=Lax session cookie: reject any
+ // state-changing verb that didn't originate from our own origin, so a
+ // fund-moving call can never be driven cross-site even if a cookie leaks.
+ const mutating = req.method !== 'GET' && req.method !== 'HEAD' && req.method !== 'OPTIONS';
+ if (mutating && !isSameSiteOrigin(req)) {
+ return error(res, 403, 'forbidden', 'cross-site request blocked');
+ }
+ }
+
+ // Forward the caller's query string (Vercel folds the catch-all into
+ // `path`; everything else is a real upstream query param).
+ const query = {};
+ for (const [k, v] of Object.entries(req.query || {})) {
+ if (k !== 'path') query[k] = Array.isArray(v) ? v[0] : v;
+ }
+
+ const headers = {};
+ for (const h of FORWARDABLE_HEADERS) {
+ if (req.headers[h]) headers[h] = req.headers[h];
+ }
+
+ let body;
+ if (req.method !== 'GET' && req.method !== 'HEAD') {
+ // Empty body is valid for some POSTs (e.g. collect/refresh actions).
+ const cl = req.headers['content-length'];
+ if (cl && Number(cl) > 0) body = await readJson(req);
+ }
+
+ const upstream = await sdpRequest(path, { method: req.method, query, body, headers });
+
+ // Relay the upstream status + body verbatim so SDP's own error envelope
+ // ({ error: { code, message }, meta }) and success shapes reach the client
+ // unchanged. Surface the SDP trace id for support correlation.
+ const extra = upstream.traceId ? { 'x-sdp-trace-id': upstream.traceId } : {};
+ if (typeof upstream.body === 'string') {
+ res.statusCode = upstream.status;
+ res.setHeader('content-type', upstream.contentType || 'text/plain; charset=utf-8');
+ res.setHeader('cache-control', 'no-store');
+ for (const [k, v] of Object.entries(extra)) res.setHeader(k, v);
+ return res.end(upstream.body);
+ }
+ return json(res, upstream.status, upstream.body, extra);
+});
diff --git a/api/user/provider-keys.js b/api/user/provider-keys.js
index edbef6ee7..50de1509f 100644
--- a/api/user/provider-keys.js
+++ b/api/user/provider-keys.js
@@ -5,6 +5,7 @@
import { sql } from '../_lib/db.js';
import { getSessionUser } from '../_lib/auth.js';
+import { requireCsrf } from '../_lib/csrf.js';
import { cors, json, error, wrap, method, readJson } from '../_lib/http.js';
import { encryptProviderKey, BYOK_PROVIDERS } from '../_lib/provider-keys.js';
import { z } from 'zod';
@@ -34,7 +35,10 @@ export default wrap(async (req, res) => {
return json(res, 200, { keys: status });
}
- // PATCH
+ // PATCH — state-changing write of sensitive provider credentials; require a
+ // CSRF token bound to the session, matching the other session-auth writers.
+ if (!(await requireCsrf(req, res, session.id))) return;
+
const body = parse(patchSchema, await readJson(req));
const [row] = await sql`SELECT provider_keys FROM users WHERE id = ${session.id}`;
diff --git a/blog/index.html b/blog/index.html
index 8f19c2966..00ab4fcb4 100644
--- a/blog/index.html
+++ b/blog/index.html
@@ -387,6 +387,11 @@
<span class="bl-press-title">IBM Extends AI Narrative with three.ws Partnership</span>
<span class="bl-press-arrow">↗</span>
</a>
+ <a class="bl-press-card" href="https://community.ibm.com/community/user/blogs/nich8/2026/06/08/3d-ai-web3-just-converge-threews-shipped-the-whole" target="_blank" rel="noopener">
+ <span class="bl-press-outlet">IBM Community</span>
+ <span class="bl-press-title">Embodied, Intelligent, and Self-Custodied: three.ws and the 3D AI Agent Stack</span>
+ <span class="bl-press-arrow">↗</span>
+ </a>
</div>
</section>
</main>
diff --git a/character-studio/.gitignore b/character-studio/.gitignore
index e3551b436..d07eb1f6c 100644
--- a/character-studio/.gitignore
+++ b/character-studio/.gitignore
@@ -289,3 +289,6 @@ lerna-debug.log
# Docusaurus build output
.docusaurus/
+
+# TLS material — never commit; generate locally at dev time
+*.pem
diff --git a/character-studio/cert.pem b/character-studio/cert.pem
deleted file mode 100644
index 9836c513f..000000000
--- a/character-studio/cert.pem
+++ /dev/null
@@ -1,93 +0,0 @@
------BEGIN CERTIFICATE-----
-MIIFijCCBHKgAwIBAgISAy9/eUHWrNKg+r3NvMO2dLfOMA0GCSqGSIb3DQEBCwUA
-MDIxCzAJBgNVBAYTAlVTMRYwFAYDVQQKEw1MZXQncyBFbmNyeXB0MQswCQYDVQQD
-EwJSMzAeFw0yMjEwMTAyMjQ0MTNaFw0yMzAxMDgyMjQ0MTJaMB4xHDAaBgNVBAMT
-E2xvY2FsLndlYmF2ZXJzZS5jb20wggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEK
-AoIBAQDE6IZDH3Rdf4R42yy+fGbNDDHmywUREBSHOSpS0a6kjDoiv6t9SKJ3su6M
-1g39GuJUhRBAGrW8bHDdSHrPcGyQzrg4ED04ZWl697/RIDZ9SLz/g+DsFPv6/TId
-jHBt3e9+CRX/LH+8kTYc4yu1kBqKM4QRWz0oWzsWJDTSZRwjJXk1p6G5jlsGbk9R
-uttufBn/N57iqxBDVOXVTmZIwgVj/GiSbrhyWjzt3PG3Ai6jdd24XUOzpXAPdv7p
-1WMNNyR1yiiw6INwn5FhRN1L9aqFIJr2XDIuWcImvl02uSYt0jOrJuP/igjHlMn+
-oF4i9Kb2d7zSAAorSoaZGhWRlzSlAgMBAAGjggKsMIICqDAOBgNVHQ8BAf8EBAMC
-BaAwHQYDVR0lBBYwFAYIKwYBBQUHAwEGCCsGAQUFBwMCMAwGA1UdEwEB/wQCMAAw
-HQYDVR0OBBYEFIQt7P2IwGCymrmNNZx4RfSHHivqMB8GA1UdIwQYMBaAFBQusxe3
-WFbLrlAJQOYfr52LFMLGMFUGCCsGAQUFBwEBBEkwRzAhBggrBgEFBQcwAYYVaHR0
-cDovL3IzLm8ubGVuY3Iub3JnMCIGCCsGAQUFBzAChhZodHRwOi8vcjMuaS5sZW5j
-ci5vcmcvMHwGA1UdEQR1MHOCEGFpLndlYmF2ZXJzZS5jb22CHGxvY2FsLWNvbXBp
-bGVyLndlYmF2ZXJzZS5jb22CE2xvY2FsLndlYmF2ZXJzZS5jb22CFGxvY2FsLndl
-YmF2ZXJzZS5saXZlghZsb2NhbC53ZWJhdmVyc2Uub25saW5lMEwGA1UdIARFMEMw
-CAYGZ4EMAQIBMDcGCysGAQQBgt8TAQEBMCgwJgYIKwYBBQUHAgEWGmh0dHA6Ly9j
-cHMubGV0c2VuY3J5cHQub3JnMIIBBAYKKwYBBAHWeQIEAgSB9QSB8gDwAHYAejKM
-VNi3LbYg6jjgUh7phBZwMhOFTTvSK8E6V6NS61IAAAGDxEjfJAAABAMARzBFAiEA
-3LGabGCXXpT9E4DZq+6KcQC23XUbMPL4Box0oKb6Rf0CIETJxDvR7SaKgrEavyi1
-/Eb1DjxaF7ke0lcFVCSaLTWNAHYAtz77JN+cTbp18jnFulj0bF38Qs96nzXEnh0J
-gSXttJkAAAGDxEjfFAAABAMARzBFAiEA5/V8jb0B/pzvhhDy3AOAdBOJDGxkTGPi
-a59g6up7t/4CIDEzIZqruAMsFtCd0HGyvnkuxTP03dHe08aK2TcCjrVtMA0GCSqG
-SIb3DQEBCwUAA4IBAQBBxEXv/3rjRm6LzX/J2gGWf32VLqkRx5KAx/EuMTpF/uop
-npNYOSdsxPqvQzqc943zkHIp9CdktIIoqVDJUgfegbM+ZqbrY3Pzdx2is9uavCn2
-pN1w5PZaM2w4QYXVq90c9GW8hDBSMexEVrC4P8o6ZIdhRPOzHGgzQgAmUEu3BITX
-jGb/tgpRe19AkSDrzNQpZ4clAdLPKSTlXs/AScME/anS7qLeJV3C5gHLZOA/RGh1
-vTp/1yGlT2i2AFpQxX4LYRl/dWnsLctA+Sy0aymuHhyj+5y80gM7um1B1bv6L+X0
-lucdOyVe+rXn8kNeyr1JpeVXfKufZU0sCsGyQMY2
------END CERTIFICATE-----
------BEGIN CERTIFICATE-----
-MIIFFjCCAv6gAwIBAgIRAJErCErPDBinU/bWLiWnX1owDQYJKoZIhvcNAQELBQAw
-TzELMAkGA1UEBhMCVVMxKTAnBgNVBAoTIEludGVybmV0IFNlY3VyaXR5IFJlc2Vh
-cmNoIEdyb3VwMRUwEwYDVQQDEwxJU1JHIFJvb3QgWDEwHhcNMjAwOTA0MDAwMDAw
-WhcNMjUwOTE1MTYwMDAwWjAyMQswCQYDVQQGEwJVUzEWMBQGA1UEChMNTGV0J3Mg
-RW5jcnlwdDELMAkGA1UEAxMCUjMwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEK
-AoIBAQC7AhUozPaglNMPEuyNVZLD+ILxmaZ6QoinXSaqtSu5xUyxr45r+XXIo9cP
-R5QUVTVXjJ6oojkZ9YI8QqlObvU7wy7bjcCwXPNZOOftz2nwWgsbvsCUJCWH+jdx
-sxPnHKzhm+/b5DtFUkWWqcFTzjTIUu61ru2P3mBw4qVUq7ZtDpelQDRrK9O8Zutm
-NHz6a4uPVymZ+DAXXbpyb/uBxa3Shlg9F8fnCbvxK/eG3MHacV3URuPMrSXBiLxg
-Z3Vms/EY96Jc5lP/Ooi2R6X/ExjqmAl3P51T+c8B5fWmcBcUr2Ok/5mzk53cU6cG
-/kiFHaFpriV1uxPMUgP17VGhi9sVAgMBAAGjggEIMIIBBDAOBgNVHQ8BAf8EBAMC
-AYYwHQYDVR0lBBYwFAYIKwYBBQUHAwIGCCsGAQUFBwMBMBIGA1UdEwEB/wQIMAYB
-Af8CAQAwHQYDVR0OBBYEFBQusxe3WFbLrlAJQOYfr52LFMLGMB8GA1UdIwQYMBaA
-FHm0WeZ7tuXkAXOACIjIGlj26ZtuMDIGCCsGAQUFBwEBBCYwJDAiBggrBgEFBQcw
-AoYWaHR0cDovL3gxLmkubGVuY3Iub3JnLzAnBgNVHR8EIDAeMBygGqAYhhZodHRw
-Oi8veDEuYy5sZW5jci5vcmcvMCIGA1UdIAQbMBkwCAYGZ4EMAQIBMA0GCysGAQQB
-gt8TAQEBMA0GCSqGSIb3DQEBCwUAA4ICAQCFyk5HPqP3hUSFvNVneLKYY611TR6W
-PTNlclQtgaDqw+34IL9fzLdwALduO/ZelN7kIJ+m74uyA+eitRY8kc607TkC53wl
-ikfmZW4/RvTZ8M6UK+5UzhK8jCdLuMGYL6KvzXGRSgi3yLgjewQtCPkIVz6D2QQz
-CkcheAmCJ8MqyJu5zlzyZMjAvnnAT45tRAxekrsu94sQ4egdRCnbWSDtY7kh+BIm
-lJNXoB1lBMEKIq4QDUOXoRgffuDghje1WrG9ML+Hbisq/yFOGwXD9RiX8F6sw6W4
-avAuvDszue5L3sz85K+EC4Y/wFVDNvZo4TYXao6Z0f+lQKc0t8DQYzk1OXVu8rp2
-yJMC6alLbBfODALZvYH7n7do1AZls4I9d1P4jnkDrQoxB3UqQ9hVl3LEKQ73xF1O
-yK5GhDDX8oVfGKF5u+decIsH4YaTw7mP3GFxJSqv3+0lUFJoi5Lc5da149p90Ids
-hCExroL1+7mryIkXPeFM5TgO9r0rvZaBFOvV2z0gp35Z0+L4WPlbuEjN/lxPFin+
-HlUjr8gRsI3qfJOQFy/9rKIJR0Y/8Omwt/8oTWgy1mdeHmmjk7j1nYsvC9JSQ6Zv
-MldlTTKB3zhThV1+XWYp6rjd5JW1zbVWEkLNxE7GJThEUG3szgBVGP7pSWTUTsqX
-nLRbwHOoq7hHwg==
------END CERTIFICATE-----
------BEGIN CERTIFICATE-----
-MIIFYDCCBEigAwIBAgIQQAF3ITfU6UK47naqPGQKtzANBgkqhkiG9w0BAQsFADA/
-MSQwIgYDVQQKExtEaWdpdGFsIFNpZ25hdHVyZSBUcnVzdCBDby4xFzAVBgNVBAMT
-DkRTVCBSb290IENBIFgzMB4XDTIxMDEyMDE5MTQwM1oXDTI0MDkzMDE4MTQwM1ow
-TzELMAkGA1UEBhMCVVMxKTAnBgNVBAoTIEludGVybmV0IFNlY3VyaXR5IFJlc2Vh
-cmNoIEdyb3VwMRUwEwYDVQQDEwxJU1JHIFJvb3QgWDEwggIiMA0GCSqGSIb3DQEB
-AQUAA4ICDwAwggIKAoICAQCt6CRz9BQ385ueK1coHIe+3LffOJCMbjzmV6B493XC
-ov71am72AE8o295ohmxEk7axY/0UEmu/H9LqMZshftEzPLpI9d1537O4/xLxIZpL
-wYqGcWlKZmZsj348cL+tKSIG8+TA5oCu4kuPt5l+lAOf00eXfJlII1PoOK5PCm+D
-LtFJV4yAdLbaL9A4jXsDcCEbdfIwPPqPrt3aY6vrFk/CjhFLfs8L6P+1dy70sntK
-4EwSJQxwjQMpoOFTJOwT2e4ZvxCzSow/iaNhUd6shweU9GNx7C7ib1uYgeGJXDR5
-bHbvO5BieebbpJovJsXQEOEO3tkQjhb7t/eo98flAgeYjzYIlefiN5YNNnWe+w5y
-sR2bvAP5SQXYgd0FtCrWQemsAXaVCg/Y39W9Eh81LygXbNKYwagJZHduRze6zqxZ
-Xmidf3LWicUGQSk+WT7dJvUkyRGnWqNMQB9GoZm1pzpRboY7nn1ypxIFeFntPlF4
-FQsDj43QLwWyPntKHEtzBRL8xurgUBN8Q5N0s8p0544fAQjQMNRbcTa0B7rBMDBc
-SLeCO5imfWCKoqMpgsy6vYMEG6KDA0Gh1gXxG8K28Kh8hjtGqEgqiNx2mna/H2ql
-PRmP6zjzZN7IKw0KKP/32+IVQtQi0Cdd4Xn+GOdwiK1O5tmLOsbdJ1Fu/7xk9TND
-TwIDAQABo4IBRjCCAUIwDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAQYw
-SwYIKwYBBQUHAQEEPzA9MDsGCCsGAQUFBzAChi9odHRwOi8vYXBwcy5pZGVudHJ1
-c3QuY29tL3Jvb3RzL2RzdHJvb3RjYXgzLnA3YzAfBgNVHSMEGDAWgBTEp7Gkeyxx
-+tvhS5B1/8QVYIWJEDBUBgNVHSAETTBLMAgGBmeBDAECATA/BgsrBgEEAYLfEwEB
-ATAwMC4GCCsGAQUFBwIBFiJodHRwOi8vY3BzLnJvb3QteDEubGV0c2VuY3J5cHQu
-b3JnMDwGA1UdHwQ1MDMwMaAvoC2GK2h0dHA6Ly9jcmwuaWRlbnRydXN0LmNvbS9E
-U1RST09UQ0FYM0NSTC5jcmwwHQYDVR0OBBYEFHm0WeZ7tuXkAXOACIjIGlj26Ztu
-MA0GCSqGSIb3DQEBCwUAA4IBAQAKcwBslm7/DlLQrt2M51oGrS+o44+/yQoDFVDC
-5WxCu2+b9LRPwkSICHXM6webFGJueN7sJ7o5XPWioW5WlHAQU7G75K/QosMrAdSW
-9MUgNTP52GE24HGNtLi1qoJFlcDyqSMo59ahy2cI2qBDLKobkx/J3vWraV0T9VuG
-WCLKTVXkcGdtwlfFRjlBz4pYg1htmf5X6DYO8A4jqv2Il9DjXA6USbW1FzXSLr9O
-he8Y4IWS6wY7bCkjCWDcRQJMEhg76fsO3txE+FiYruq9RUWhiF1myv4Q6W+CyBFC
-Dfvp7OOGAN6dEOM4+qR9sdjoSYKEBpsr6GtPAQw4dy753ec5
------END CERTIFICATE-----
\ No newline at end of file
diff --git a/character-studio/key.pem b/character-studio/key.pem
deleted file mode 100644
index 0e47d656f..000000000
--- a/character-studio/key.pem
+++ /dev/null
@@ -1,28 +0,0 @@
------BEGIN PRIVATE KEY-----
-MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDE6IZDH3Rdf4R4
-2yy+fGbNDDHmywUREBSHOSpS0a6kjDoiv6t9SKJ3su6M1g39GuJUhRBAGrW8bHDd
-SHrPcGyQzrg4ED04ZWl697/RIDZ9SLz/g+DsFPv6/TIdjHBt3e9+CRX/LH+8kTYc
-4yu1kBqKM4QRWz0oWzsWJDTSZRwjJXk1p6G5jlsGbk9RuttufBn/N57iqxBDVOXV
-TmZIwgVj/GiSbrhyWjzt3PG3Ai6jdd24XUOzpXAPdv7p1WMNNyR1yiiw6INwn5Fh
-RN1L9aqFIJr2XDIuWcImvl02uSYt0jOrJuP/igjHlMn+oF4i9Kb2d7zSAAorSoaZ
-GhWRlzSlAgMBAAECggEAJqW4zG3dCgjgOFRUWOLTzoUJOlI4oVu1m8DVlMHA9Fzt
-gCp8fy+Fa9b7yTquLjJbn9kqElrrtprWICh8qkBXnqhkMeTGD06gQFlmFaar6zUe
-m0wIFm4b8uxFLNWGr5myytr/rUDPpXQe2dagmpc5Dk0EK9/rhgM5+qOKlozv09nL
-j30PREkvCkxCBpUAaPWc5mgRjgd4Er1oxjNbkDnPtCt9MsyBRF3LwttE4AX1UqpR
-M5jgtc68p9foVKzkOBEDqRz/C4uP1GRLUcyZ9xSfIw64EeZy89ixRynJriJjJIM/
-xnt2KNoDVU9k+uqq50WxPcwFeFxRy7Ye4rgDges4NQKBgQDNX4mtm6LxINbgERQP
-h71rIy2qDjfbWGUnLzbFLg2mIdbGp0H2WA5ADMJ8os//qBb+DyZJiKq8rfwI0Ogh
-9qCy3bwb+Zl5C8aJsPUfbpc5Lk6et2PlcxLoHrGwLSOlFYPULe1W+O+yu5wurW/T
-cwGA3o7GVpFjOIhd1m9GWc5TewKBgQD1cssgSuOlNxq40E3Qig+CD0RzAcQ51FF0
-Gn8qGS8/rJllNjEJLOyD4b1XTLOFIB3vmq9HafrzQTpQ5hewAM9op8jJk1+cjjOm
-WJCgg/om6XEFIT7vXXxJRE/E0moIXwKj1o90ikBgDRI3ATC+jaB3KiKS7K3WiJAS
-5CoUGaiOXwKBgQDGzhIH1d5wzxpSgxXJRtxNJxugP+1ATxx0Rxcc30zlImK3oNeQ
-sYLx66glYLI6yKuhOmcUzdCBn2aX3iqoHgdHvq/G4OL5MzX4ui0/RR3sg3Al4l84
-kSGfQ388jSWxO9eGgQL8qzPV8BjrcocKyIyPBGJviwNoaiRPujGzh2HcmwKBgQCW
-CEFZz+0vBGv1JH8sRfgMzEBO/Hlxz/KqQbgRh6t2BI8Pavy2WxuH0ejnAB+L9IHY
-AHm78XBQWULISJ2aHCSsGEOH0+nRzKqNt/1P4Nx8BJ3tQNEzh7V9I6CO8v+Vdl4q
-v/CYkBmhnNvRe4zMLc40iTDxFnN8e6V1prqB5t09iQKBgBuiPDlRcGoRlYmHrrbz
-5VV/+xtvDGWENWBKDrZR7GWE/bpZa2YuE9FfQuXnwu1H3ZZOBBOEHc5PcND8qoE1
-NpaatdY7aP/9ivFuVrPbb6siRcqHpnjma5P+vRbg82Jr3l6M+vbneqhkNFY0CKMA
-iC3TdI5phnHXIb6QsujVdfOt
------END PRIVATE KEY-----
\ No newline at end of file
diff --git a/docs/listings.md b/docs/listings.md
index 24ff8436f..6975328bb 100644
--- a/docs/listings.md
+++ b/docs/listings.md
@@ -35,6 +35,7 @@ Dappbay is BNB Chain's official dApp directory. The listing is about distributio
| Partner | Status | Links |
|---|---|---|
+| **IBM Community** | Live | [Embodied, Intelligent, and Self-Custodied: three.ws and the 3D AI Agent Stack](https://community.ibm.com/community/user/blogs/nich8/2026/06/08/3d-ai-web3-just-converge-threews-shipped-the-whole) — IBM Community blog covering the convergence of 3D, AI agents, and web3 in the three.ws stack. |
| **HackerNoon** | Live | [hackernoon.com/u/three-ws](https://hackernoon.com/u/three-ws) — three.ws posts auto-import from the RSS feed. Announcement: [three.ws Partners with HackerNoon](/news/partnered-with-hackernoon) |
| **Alibaba Cloud Marketplace Blog** | Live | [Editorial feature](https://marketplace.alibabacloud.com/doc/blog/detail/mplace-sgcmfw00036800.html) — Alibaba Cloud Marketplace published an editorial introducing three.ws. Announcement: [three.ws Featured on the Alibaba Cloud Marketplace Blog](/blog/three-ws-featured-on-alibaba-cloud-marketplace-blog) |
diff --git a/public/features.json b/public/features.json
index 8f3933886..3969ee161 100644
--- a/public/features.json
+++ b/public/features.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-06-09T00:40:41.715Z",
+ "generated_at": "2026-06-10T02:18:53.597Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json",
"site": {
"name": "three.ws",
@@ -1155,6 +1155,16 @@
"tags": [],
"showcase": false
},
+ {
+ "path": "/news/three-ws-dextools-social-boost-buyback",
+ "title": "three.ws Wins DEXTools Social Boost — $5,543 $three Buyback",
+ "description": "three.ws is DEXTools' Social Boost winner of the week, earning a $5,543 buyback of $three. The DEXTools wallet now holds a total of 2.47M $three.",
+ "added": null,
+ "auth": null,
+ "indexable": true,
+ "tags": [],
+ "showcase": false
+ },
{
"path": "/news/three-ws-featured-on-alibaba-cloud-marketplace-blog",
"title": "three.ws Featured on the Alibaba Cloud Marketplace Blog",
diff --git a/public/footer.html b/public/footer.html
index 6177341b1..63260cfa8 100644
--- a/public/footer.html
+++ b/public/footer.html
@@ -96,6 +96,7 @@
<div class="h-footer-link-col">
<h4 class="h-footer-link-heading">Press</h4>
<a href="https://markets.businessinsider.com/news/stocks/three-ws-and-ibm-announce-strategic-partnership-to-advance-ai-powered-3d-agent-technology-1036222181" target="_blank" rel="noopener">Business Insider</a>
+ <a href="https://community.ibm.com/community/user/blogs/nich8/2026/06/08/3d-ai-web3-just-converge-threews-shipped-the-whole" target="_blank" rel="noopener">IBM Community</a>
<a href="https://finance.yahoo.com/sectors/technology/articles/ibm-extends-ai-narrative-three-010650764.html" target="_blank" rel="noopener">Yahoo Finance</a>
<a href="https://www.crunchbase.com/organization/three-ws" target="_blank" rel="noopener">Crunchbase</a>
<a href="https://www.vogue.com/photovogue/photographers/416428" target="_blank" rel="noopener">Vogue</a>
diff --git a/public/llms-full.txt b/public/llms-full.txt
index 2c709ff4b..a67fa745c 100644
--- a/public/llms-full.txt
+++ b/public/llms-full.txt
@@ -715,6 +715,12 @@ URL: https://three.ws/news/
Product launches, integrations, and announcements from three.ws.
+### three.ws Wins DEXTools Social Boost — $5,543 $three Buyback
+
+URL: https://three.ws/news/three-ws-dextools-social-boost-buyback
+
+three.ws is DEXTools' Social Boost winner of the week, earning a $5,543 buyback of $three. The DEXTools wallet now holds a total of 2.47M $three.
+
### three.ws Featured on the Alibaba Cloud Marketplace Blog
URL: https://three.ws/news/three-ws-featured-on-alibaba-cloud-marketplace-blog
diff --git a/public/llms.txt b/public/llms.txt
index c41c16510..ed7f1f07e 100644
--- a/public/llms.txt
+++ b/public/llms.txt
@@ -145,6 +145,7 @@ Long-form announcements, launches, and writing from three.ws.
Product launches, integrations, and announcements from three.ws.
- [News & Announcements](https://three.ws/news/): Product launches, integrations, and announcements from three.ws.
+- [three.ws Wins DEXTools Social Boost — $5,543 $three Buyback](https://three.ws/news/three-ws-dextools-social-boost-buyback): three.ws is DEXTools' Social Boost winner of the week, earning a $5,543 buyback of $three. The DEXTools wallet now holds a total of 2.47M $three.
- [three.ws Featured on the Alibaba Cloud Marketplace Blog](https://three.ws/news/three-ws-featured-on-alibaba-cloud-marketplace-blog): Alibaba Cloud Marketplace published an editorial introducing three.ws — Render, Embody, Register, Embed: browser-native 3D AI agents deployed with a single <agent-3d> tag, with a Claude-powered runtime, ERC-8004 identity, and an Apache 2.0 open-source stack.
- [One Month In: How three.ws Built the 3D Agent Layer of the Internet](https://three.ws/news/three-ws-first-month-3d-agent-layer): In one month, three.ws went from launch to global coverage: browser-native 3D AI agents listed across major exchanges and data platforms, deployed on four hyperscale clouds, live in Anthropic's MCP Registry, and covered from CoinMarketCap to Vogue. A look back at 30 days of shipping.
- [three.ws Brings Autonomous Payments and 3D Generation to Anthropic's Official MCP Registry](https://three.ws/news/cmc-mcp-registry-article): CoinMarketCap article: three.ws brings autonomous payments and 3D generation to Anthropic's official MCP Registry — two new MCP servers give Claude and any MCP client the ability to spawn 3D agents and make on-chain x402 payments via the Coinbase-powered x402 Bazaar.
diff --git a/public/sitemap/index.html b/public/sitemap/index.html
index f7239c14f..5daa9d958 100644
--- a/public/sitemap/index.html
+++ b/public/sitemap/index.html
@@ -919,6 +919,13 @@
<span class="sm-desc">Product launches, integrations, and announcements from three.ws.</span>
</a>
</li>
+ <li>
+ <a href="/news/three-ws-dextools-social-boost-buyback">
+ <span class="sm-title">three.ws Wins DEXTools Social Boost — $5,543 $three Buyback</span>
+ <span class="sm-path">/news/three-ws-dextools-social-boost-buyback</span>
+ <span class="sm-desc">three.ws is DEXTools' Social Boost winner of the week, earning a $5,543 buyback of $three. The DEXTools wallet now holds a total of 2.47M $three.</span>
+ </a>
+ </li>
<li>
<a href="/news/three-ws-featured-on-alibaba-cloud-marketplace-blog">
<span class="sm-title">three.ws Featured on the Alibaba Cloud Marketplace Blog</span>
diff --git a/scripts/seed-agent.mjs b/scripts/seed-agent.mjs
index c9c4effa4..76dff6b17 100644
--- a/scripts/seed-agent.mjs
+++ b/scripts/seed-agent.mjs
@@ -1,8 +1,11 @@
import { neon } from '@neondatabase/serverless';
-const sql = neon(
- 'postgresql://neondb_owner:npg_4nWXZhq2Hjse@ep-rapid-surf-ak9p7occ-pooler.c-3.us-west-2.aws.neon.tech/neondb?channel_binding=require&sslmode=require',
-);
+const DATABASE_URL = process.env.DATABASE_URL;
+if (!DATABASE_URL) {
+ console.error('Set DATABASE_URL to your Neon connection string before running.');
+ process.exit(1);
+}
+const sql = neon(DATABASE_URL);
const [user] = await sql`
INSERT INTO users (email, display_name, email_verified)
diff --git a/scripts/seed-defi-agents.mjs b/scripts/seed-defi-agents.mjs
index d4b75fb98..79678189a 100644
--- a/scripts/seed-defi-agents.mjs
+++ b/scripts/seed-defi-agents.mjs
@@ -1,9 +1,12 @@
import { neon } from '@neondatabase/serverless';
import fetch from 'node-fetch';
-const sql = neon(
- 'postgresql://neondb_owner:npg_4nWXZhq2Hjse@ep-rapid-surf-ak9p7occ-pooler.c-3.us-west-2.aws.neon.tech/neondb?channel_binding=require&sslmode=require',
-);
+const DATABASE_URL = process.env.DATABASE_URL;
+if (!DATABASE_URL) {
+ console.error('Set DATABASE_URL to your Neon connection string before running.');
+ process.exit(1);
+}
+const sql = neon(DATABASE_URL);
async function main() {
console.log('Fetching agents from nirholas/defi-agents...');
diff --git a/scripts/x402-all.mjs b/scripts/x402-all.mjs
index 088aab8db..cb64758b9 100644
--- a/scripts/x402-all.mjs
+++ b/scripts/x402-all.mjs
@@ -3,14 +3,20 @@
// TransferWithAuthorization, retry with X-PAYMENT, capture the response +
// settlement receipt. Prints a summary table at the end.
//
-// Costs are billed in USDC on Base (eip155:8453) — the funded vanity wallet
-// 0x33369135724F53521dF38e69262792a1EC068cd7 holds the USDC; the facilitator
-// covers ETH gas. The handler runs BEFORE settle, so a 4xx from the route's
-// validation logic means no USDC was moved.
+// Costs are billed in USDC on Base (eip155:8453) — a funded payer wallet holds
+// the USDC; the facilitator covers ETH gas. The handler runs BEFORE settle, so
+// a 4xx from the route's validation logic means no USDC was moved.
+//
+// Provide the payer key via the X402_PAYER_PRIVATE_KEY env var — never hardcode
+// it here (a committed key is a leaked key).
import { Wallet, randomBytes, hexlify } from 'ethers';
-const PRIVATE_KEY = '0x5e306b436ea9cf2e9840eb9922094cc4a32beebc23588a8856ab75aab3f3f7b5';
+const PRIVATE_KEY = process.env.X402_PAYER_PRIVATE_KEY;
+if (!PRIVATE_KEY) {
+ console.error('Set X402_PAYER_PRIVATE_KEY to a funded Base wallet key before running.');
+ process.exit(1);
+}
const BASE = 'https://three.ws';
const wallet = new Wallet(PRIVATE_KEY);
diff --git a/scripts/x402-test.mjs b/scripts/x402-test.mjs
index 281b32108..8436d1aab 100644
--- a/scripts/x402-test.mjs
+++ b/scripts/x402-test.mjs
@@ -3,7 +3,11 @@
// inspection JSON.
import { Wallet, randomBytes, hexlify } from 'ethers';
-const PRIVATE_KEY = '0x5e306b436ea9cf2e9840eb9922094cc4a32beebc23588a8856ab75aab3f3f7b5';
+const PRIVATE_KEY = process.env.X402_PAYER_PRIVATE_KEY;
+if (!PRIVATE_KEY) {
+ console.error('Set X402_PAYER_PRIVATE_KEY to a funded Base wallet key before running.');
+ process.exit(1);
+}
const ENDPOINT = 'https://three.ws/api/x402/model-check?url=https://raw.githubusercontent.com/KhronosGroup/glTF-Sample-Models/master/2.0/Duck/glTF-Binary/Duck.glb';
const wallet = new Wallet(PRIVATE_KEY);
diff --git a/src/agent-detail.js b/src/agent-detail.js
index 06abde7ca..1a5e526fc 100644
--- a/src/agent-detail.js
+++ b/src/agent-detail.js
@@ -472,7 +472,7 @@ function render(agent) {
if (voiceProvider && voiceProvider !== 'browser') {
document.getElementById('ad-voice-row').style.display = '';
document.getElementById('ad-voice').innerHTML =
- `<span class="ad-pill ad-pill-green">cloned · ${voiceProvider}</span>`;
+ `<span class="ad-pill ad-pill-green">cloned · ${escapeText(voiceProvider)}</span>`;
} else if (voiceProvider === 'browser') {
document.getElementById('ad-voice-row').style.display = '';
document.getElementById('ad-voice').textContent = 'browser TTS';
@@ -911,8 +911,16 @@ function buildReviewItem(r, agentId, onRefresh) {
return item;
}
+// HTML-escape untrusted text before interpolating it into an innerHTML string.
+// Covers the five significant characters so attacker-controlled values (URL
+// params, on-chain metadata, API fields) can't break out into markup.
function escapeText(s) {
- return String(s == null ? '' : s);
+ return String(s == null ? '' : s)
+ .replace(/&/g, '&amp;')
+ .replace(/</g, '&lt;')
+ .replace(/>/g, '&gt;')
+ .replace(/"/g, '&quot;')
+ .replace(/'/g, '&#39;');
}
function fmtRelTime(iso) {
@@ -1396,7 +1404,7 @@ function renderNotFound(id, reason) {
<div style="padding:60px 24px;text-align:center;">
<h1 style="margin:0 0 8px;font-size:22px;font-weight:600;">Agent not found</h1>
<p style="color:rgba(231,233,238,0.55);font-size:14px;margin:0 0 22px;">
- ${reason || 'No agent registered with id'} <code style="font-family:ui-monospace,monospace;color:#e7e9ee;">${id || '(none)'}</code>.
+ ${escapeText(reason || 'No agent registered with id')} <code style="font-family:ui-monospace,monospace;color:#e7e9ee;">${escapeText(id || '(none)')}</code>.
</p>
<a class="ad-cta" style="display:inline-block;padding:10px 22px;" href="/agents">← Back to Registry</a>
</div>
diff --git a/src/erc8004/register-ui.js b/src/erc8004/register-ui.js
index 6eb852c35..f92a3a697 100644
--- a/src/erc8004/register-ui.js
+++ b/src/erc8004/register-ui.js
@@ -384,7 +384,7 @@ export class RegisterUI {
glbUrl: initial.glbUrl || '',
glbFile: null,
pastedGlbUrl: '',
- savedAvatar: null, // { id, name, url, thumbnailUrl }
+ savedAvatar: null, // { id, name, modelUrl, thumbnailUrl }
defaultAvatarId: null, // id of a pre-pinned DEFAULT_AVATARS entry
avatarSource: initial.glbUrl ? 'current' : 'upload',
services: [], // [{ name, type, endpoint }]
@@ -1786,6 +1786,183 @@ export class RegisterUI {
);
}
+ // -----------------------------------------------------------------------
+ // Avatar persistence — turn the chosen Step-3 source into a REAL avatars
+ // row (GLB stored in R2 + a rendered poster) so the minted asset resolves a
+ // 3D body and an image. The mint pipeline keys everything off a real
+ // avatar_id; a session/draft GLB that only ever lived in the viewer has no
+ // row, so without this the asset mints hollow (generic logo, empty body) —
+ // the exact bug being fixed. Returns { avatarId, modelUrl, imageUrl }, or
+ // null for the explicit metadata-only ("skip") choice.
+ // -----------------------------------------------------------------------
+
+ async _ensurePersistedAvatar(say = () => {}) {
+ const f = this.form;
+ const src = f.avatarSource;
+ if (src === 'skip') return null;
+
+ // Already a persisted row (saved-avatar pick, or a current-session avatar
+ // that was loaded from one). Reuse it — but guarantee it has a poster so
+ // the NFT image isn't blank.
+ const existingId =
+ (src === 'saved' && f.savedAvatar?.id) ? f.savedAvatar.id
+ : (src === 'current' && this._avatarId) ? this._avatarId
+ : null;
+
+ if (existingId) {
+ // The row already exists; prep resolves its poster + body server-side
+ // from thumbnail_key/storage_key by avatar_id, so no client fetch is
+ // needed. Pass through whatever URLs we have for the live preview.
+ const imageUrl = (src === 'saved' ? f.savedAvatar?.thumbnailUrl : null) || f.imageUrl || null;
+ const modelUrl = (src === 'saved' ? f.savedAvatar?.modelUrl : null) || f.glbUrl || null;
+ return { avatarId: existingId, modelUrl, imageUrl };
+ }
+
+ // A new row is required (current-draft / upload / pasted-url / default).
+ const { blob, filename } = await this._acquireGlbBlob(say);
+ say('Saving your avatar…');
+ const { storageKey, sizeBytes } = await this._ensureOwnedGlb(blob, filename, say);
+ const avatar = await this._createAvatarRow({ storageKey, sizeBytes, name: f.name, blob });
+ const imageUrl = await this._renderAndAttachThumbnail(avatar.id, blob, say);
+
+ // Cache so a back-and-retry doesn't re-upload the same bytes.
+ this._avatarId = avatar.id;
+ f.savedAvatar = { id: avatar.id, name: avatar.name, modelUrl: avatar.model_url || null, thumbnailUrl: imageUrl };
+ return { avatarId: avatar.id, modelUrl: avatar.model_url || null, imageUrl };
+ }
+
+ /** Fetch the chosen source's GLB bytes (needed for upload + poster render). */
+ async _acquireGlbBlob(say = () => {}) {
+ const f = this.form;
+ const src = f.avatarSource;
+ if (src === 'upload' && f.glbFile) {
+ return { blob: f.glbFile, filename: f.glbFile.name || 'avatar.glb' };
+ }
+ let url = '';
+ if (src === 'current') url = f.glbUrl;
+ else if (src === 'url') url = (f.pastedGlbUrl || '').trim();
+ else if (src === 'default') url = getDefaultAvatar(f.defaultAvatarId)?.url || '';
+ else url = f.glbUrl || (f.pastedGlbUrl || '').trim();
+ if (!url) throw new Error('No 3D model to attach — choose an avatar in the Avatar step first.');
+
+ const fetchUrl = url.startsWith('ipfs://')
+ ? url.replace('ipfs://', 'https://ipfs.io/ipfs/')
+ : url;
+ const sameOrigin = (() => { try { return new URL(fetchUrl, location.href).origin === location.origin; } catch { return false; } })();
+ say('Fetching 3D model…');
+ let resp;
+ try {
+ resp = await fetch(fetchUrl, { credentials: sameOrigin ? 'include' : 'omit' });
+ } catch {
+ throw new Error('Could not fetch the 3D model (network or CORS). Re-upload the GLB and retry.');
+ }
+ if (!resp.ok) throw new Error(`Could not fetch the 3D model (HTTP ${resp.status}).`);
+ const blob = await resp.blob();
+ if (!blob.size) throw new Error('The 3D model is empty.');
+ const base = (url.split('/').pop() || 'avatar.glb').split('?')[0];
+ return { blob, filename: base.toLowerCase().endsWith('.glb') ? base : 'avatar.glb' };
+ }
+
+ /**
+ * Return a caller-owned R2 storage key for the GLB. Reuses an already-uploaded
+ * draft when the current source points straight at our bucket (no re-upload);
+ * otherwise uploads the bytes via the presign+PUT path.
+ */
+ async _ensureOwnedGlb(blob, filename, say = () => {}) {
+ const derived = this.form.avatarSource === 'current' ? this._deriveOwnedGlbKey(this.form.glbUrl) : null;
+ if (derived) return { storageKey: derived, sizeBytes: blob.size };
+ return this._uploadGlb(blob, filename, say);
+ }
+
+ /** Map a public R2 URL back to its `u/<userId>/…/*.glb` object key, or null. */
+ _deriveOwnedGlbKey(url) {
+ if (!url) return null;
+ let path;
+ try { path = new URL(url, location.href).pathname; } catch { return null; }
+ const key = decodeURIComponent(path.replace(/^\/+/, ''));
+ return /^u\/[^/]+\/.+\.glb$/i.test(key) ? key : null;
+ }
+
+ /** Upload GLB bytes to R2 via a presigned PUT; returns the owned storage key. */
+ async _uploadGlb(blob, filename, say = () => {}) {
+ say('Uploading 3D model…');
+ const presignRes = await fetch('/api/avatar/presign-glb', {
+ method: 'POST',
+ credentials: 'include',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ filename: filename || 'avatar.glb', content_type: 'model/gltf-binary', bytes: blob.size }),
+ });
+ if (!presignRes.ok) {
+ const e = await presignRes.json().catch(() => ({}));
+ throw new Error(e.error_description || `Could not presign upload (HTTP ${presignRes.status}).`);
+ }
+ const { upload_url, storage_key } = await presignRes.json();
+ const put = await fetch(upload_url, {
+ method: 'PUT',
+ headers: { 'content-type': 'model/gltf-binary' },
+ body: blob,
+ });
+ if (!put.ok) throw new Error(`Upload to storage failed (HTTP ${put.status}).`);
+ return { storageKey: storage_key, sizeBytes: blob.size };
+ }
+
+ /** Create the avatars row from an owned storage key. Re-uploads + retries once
+ * if a reused draft key fails server validation. */
+ async _createAvatarRow({ storageKey, sizeBytes, name, blob }) {
+ const res = await fetch('/api/avatars', {
+ method: 'POST',
+ credentials: 'include',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({
+ name: (name || 'Agent').trim().slice(0, 80) || 'Agent',
+ storage_key: storageKey,
+ size_bytes: sizeBytes,
+ content_type: 'model/gltf-binary',
+ source: 'upload',
+ visibility: 'unlisted',
+ }),
+ });
+ if (res.ok) return (await res.json()).avatar;
+
+ const e = await res.json().catch(() => ({}));
+ if (blob && ['size_mismatch', 'upload_missing', 'invalid_storage_key'].includes(e.error)) {
+ const fresh = await this._uploadGlb(blob, 'avatar.glb');
+ return this._createAvatarRow({ storageKey: fresh.storageKey, sizeBytes: fresh.sizeBytes, name });
+ }
+ throw new Error(e.error_description || `Could not save avatar (HTTP ${res.status}).`);
+ }
+
+ /** Render a 512² poster from the GLB and attach it to the avatar row. A missing
+ * poster never blocks the mint — the body still resolves and the manifest
+ * falls back to the brand image. */
+ async _renderAndAttachThumbnail(avatarId, blob, say = () => {}) {
+ try {
+ say('Rendering preview image…');
+ const png = await glbFileToThumbnail(blob, { size: 512 });
+ const b64 = await this._blobToDataUrl(png);
+ const res = await fetch('/api/avatars/thumbnail', {
+ method: 'POST',
+ credentials: 'include',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ avatar_id: avatarId, png_base64: b64 }),
+ });
+ if (!res.ok) throw new Error(`HTTP ${res.status}`);
+ return (await res.json())?.data?.thumbnail_url || null;
+ } catch (err) {
+ say(`Preview image skipped (${err.message}) — minting with the brand image.`);
+ return null;
+ }
+ }
+
+ _blobToDataUrl(blob) {
+ return new Promise((resolve, reject) => {
+ const r = new FileReader();
+ r.onload = () => resolve(r.result);
+ r.onerror = reject;
+ r.readAsDataURL(blob);
+ });
+ }
+
async _doSolanaDeploy(body) {
const log = body.querySelector('[data-role="log"]');
const say = (msg, err = false) => {
@@ -1809,16 +1986,36 @@ export class RegisterUI {
setPhase('prepare');
const network = _solanaNetwork(this.selectedChainId);
- const synthAgent = {
- id: this._backendAgentId || 'wizard',
- name: this.form.name,
- description: this.form.description,
- avatarId: this.form.savedAvatar?.id || undefined,
- };
- say(`Connecting Solana wallet…`);
- setPhase('sign');
try {
+ // Persist the chosen avatar into a real avatars row (GLB + rendered
+ // poster) BEFORE spending SOL, so the minted asset resolves a 3D body
+ // and an image. The prior code forwarded only a saved-avatar id and
+ // silently dropped the live session/draft avatar — minting a hollow
+ // asset (generic logo, empty body). A metadata-only deploy is only ever
+ // the explicit "Skip — no 3D body" choice; any other source that can't
+ // be saved aborts here instead of writing an empty NFT.
+ let avatar = null;
+ if (this.form.avatarSource !== 'skip') {
+ avatar = await this._ensurePersistedAvatar(say);
+ if (!avatar?.avatarId) {
+ throw new Error('Could not prepare your avatar — fix the Avatar step and retry, or choose “Skip — no 3D body”.');
+ }
+ if (avatar.imageUrl) {
+ this.form.imageUrl = avatar.imageUrl;
+ try { this._refreshPreview(); } catch { /* preview is best-effort */ }
+ }
+ }
+
+ const synthAgent = {
+ id: this._backendAgentId || 'wizard',
+ name: this.form.name,
+ description: this.form.description,
+ avatarId: avatar?.avatarId || undefined,
+ };
+
+ say(avatar ? 'Avatar saved — connecting Solana wallet…' : 'Connecting Solana wallet…');
+ setPhase('sign');
const result = await runSolanaDeploy({ agent: synthAgent, network });
setPhase('confirm');
say(`Minted asset ${result.assetPubkey}`);
@@ -1872,17 +2069,24 @@ export class RegisterUI {
*/
_avatarSummary() {
const s = this.form.avatarSource;
+ // On Solana, a source that still needs a row gets saved + rendered into a
+ // poster at deploy time — say so, so "✓ Avatar" doesn't imply it's already
+ // attached. (EVM pins its own registration JSON via a different path.)
+ const willSave = _isSolana(this.selectedChainId)
+ ? ' <span class="erc8004-muted">· saved &amp; rendered on deploy</span>'
+ : '';
if (s === 'current' && this.form.glbUrl) {
- return `Current session avatar — <code>${esc(this.form.glbUrl)}</code>`;
+ const saved = this._avatarId ? '' : willSave;
+ return `Current session avatar — <code>${esc(this.form.glbUrl)}</code>${saved}`;
}
if (s === 'saved' && this.form.savedAvatar) {
return `Saved: ${esc(this.form.savedAvatar.name)}`;
}
if (s === 'upload' && this.form.glbFile) {
- return `Uploaded: ${esc(this.form.glbFile.name)} (${(this.form.glbFile.size / 1024).toFixed(1)} KB)`;
+ return `Uploaded: ${esc(this.form.glbFile.name)} (${(this.form.glbFile.size / 1024).toFixed(1)} KB)${willSave}`;
}
if (s === 'url' && this.form.pastedGlbUrl) {
- return `URL: <code>${esc(this.form.pastedGlbUrl)}</code>`;
+ return `URL: <code>${esc(this.form.pastedGlbUrl)}</code>${willSave}`;
}
if (s === 'default' && this.form.defaultAvatarId) {
const def = getDefaultAvatar(this.form.defaultAvatarId);
diff --git a/src/pump/agent-token-widget.js b/src/pump/agent-token-widget.js
index e8a1769f3..84fbedfdb 100644
--- a/src/pump/agent-token-widget.js
+++ b/src/pump/agent-token-widget.js
@@ -27,6 +27,19 @@ import { resolveUsdcAta, signAndSendVTx } from './pump-modals.js';
const POLL_MS = 10_000;
+// HTML-escape untrusted strings before interpolating into innerHTML. Token
+// symbol/name and the payments feed (tool_name, skill_id, invoice_pda) all
+// originate from pump.fun token creators / agent-supplied invoices, so they are
+// attacker-controlled and must be escaped at every sink.
+function esc(s) {
+ return String(s == null ? '' : s)
+ .replace(/&/g, '&amp;')
+ .replace(/</g, '&lt;')
+ .replace(/>/g, '&gt;')
+ .replace(/"/g, '&quot;')
+ .replace(/'/g, '&#39;');
+}
+
function fmtUsdc(atomics) {
const n = Number(BigInt(atomics || '0')) / 1_000_000;
if (n === 0) return '$0.00';
@@ -492,7 +505,7 @@ export class AgentTokenWidget {
const t = this.token;
const b = this.balances || {};
const q = this.quote || {};
- const symbol = t.symbol || 'AGENT';
+ const symbol = esc(t.symbol || 'AGENT');
const graduated = q.graduated === true;
const buybackBps = t.buyback_bps || 0;
const buybackPct = buybackBps / 100;
@@ -539,16 +552,16 @@ export class AgentTokenWidget {
.slice(0, 5)
.map((p) => {
const why = p.tool_name
- ? `<code>${p.tool_name}</code>`
+ ? `<code>${esc(p.tool_name)}</code>`
: p.skill_id
- ? `<code>${p.skill_id}</code>`
+ ? `<code>${esc(p.skill_id)}</code>`
: 'paid call';
const buybackShare = (BigInt(p.amount_atomics || '0') * BigInt(buybackBps)) / 10_000n;
const pdaLink = p.invoice_pda
- ? `<a href="https://solscan.io/account/${p.invoice_pda}${solscanCluster}" target="_blank" rel="noopener" title="Open on-chain invoice receipt" style="color:rgba(180,210,255,0.7);text-decoration:none;font-size:0.7rem;">PDA↗</a>`
+ ? `<a href="https://solscan.io/account/${encodeURIComponent(p.invoice_pda)}${solscanCluster}" target="_blank" rel="noopener" title="Open on-chain invoice receipt" style="color:rgba(180,210,255,0.7);text-decoration:none;font-size:0.7rem;">PDA↗</a>`
: '';
const txLink = p.tx_signature
- ? `<a href="https://solscan.io/tx/${p.tx_signature}${solscanCluster}" target="_blank" rel="noopener" title="Open settlement tx" style="color:rgba(180,210,255,0.7);text-decoration:none;font-size:0.7rem;">tx↗</a>`
+ ? `<a href="https://solscan.io/tx/${encodeURIComponent(p.tx_signature)}${solscanCluster}" target="_blank" rel="noopener" title="Open settlement tx" style="color:rgba(180,210,255,0.7);text-decoration:none;font-size:0.7rem;">tx↗</a>`
: '';
return `
<div class="atok-feed-row">
@@ -572,7 +585,7 @@ export class AgentTokenWidget {
<div>🔥 burn</div>
<div style="display:flex;gap:0.5rem;align-items:center;">
<span>${fmtUsdc(b.burn_amount || '0')}</span>
- ${b.tx_signature ? `<a href="https://solscan.io/tx/${b.tx_signature}${solscanCluster}" target="_blank" rel="noopener" style="color:rgba(180,210,255,0.7);text-decoration:none;font-size:0.7rem;">tx↗</a>` : ''}
+ ${b.tx_signature ? `<a href="https://solscan.io/tx/${encodeURIComponent(b.tx_signature)}${solscanCluster}" target="_blank" rel="noopener" style="color:rgba(180,210,255,0.7);text-decoration:none;font-size:0.7rem;">tx↗</a>` : ''}
<span style="color:rgba(255,255,255,0.35);font-size:0.7rem;">${timeAgo(b.created_at)}</span>
</div>
</div>`)
diff --git a/tests/api-sdp-client.test.js b/tests/api-sdp-client.test.js
new file mode 100644
index 000000000..f5d70a603
--- /dev/null
+++ b/tests/api-sdp-client.test.js
@@ -0,0 +1,171 @@
+// Unit tests for the Solana Developer Platform (SDP) client (api/_lib/sdp.js).
+// fetch is mocked, so these run with no network and no real SDP key. They pin
+// the wire contract the proxy (api/sdp/*) and any server-side caller depend on:
+// 1. the path allowlist mirrors the upstream router — unknown paths are
+// refused before any request goes out (no open-proxy).
+// 2. health/openapi/llms need no key; everything else fails closed with 503
+// when SDP_API_KEY is unset (never a fake success).
+// 3. the server-side key is attached as a Bearer Authorization header and the
+// base host is overridable via SDP_API_BASE.
+// 4. upstream non-2xx surfaces the structured { error: { code, message } }.
+
+import { vi, describe, it, expect, beforeEach, afterEach } from 'vitest';
+import {
+ isSdpAllowedPath,
+ sdpConfigured,
+ sdpPathNeedsKey,
+ sdpRequest,
+ sdpCall,
+ sdpHealth,
+} from '../api/_lib/sdp.js';
+
+const realFetch = global.fetch;
+let lastRequest = null; // { url, method, headers, body }
+
+function mockFetch(status, body, { contentType = 'application/json', traceId = null } = {}) {
+ global.fetch = vi.fn(async (url, init = {}) => {
+ lastRequest = {
+ url,
+ method: init.method || 'GET',
+ headers: init.headers || {},
+ body: init.body ?? null,
+ };
+ const text = typeof body === 'string' ? body : JSON.stringify(body);
+ const headers = new Map([['content-type', contentType]]);
+ if (traceId) headers.set('x-sdp-trace-id', traceId);
+ return {
+ status,
+ headers: { get: (k) => headers.get(k.toLowerCase()) ?? null },
+ text: async () => text,
+ };
+ });
+}
+
+beforeEach(() => {
+ lastRequest = null;
+ delete process.env.SDP_API_KEY;
+ delete process.env.SDP_API_BASE;
+});
+
+afterEach(() => {
+ global.fetch = realFetch;
+ vi.restoreAllMocks();
+});
+
+describe('path allowlist', () => {
+ it('accepts the documented v1 resources and top-level surfaces', () => {
+ for (const p of [
+ 'health',
+ 'health/ready',
+ 'openapi.json',
+ 'llms.txt',
+ 'v1/wallets',
+ 'v1/wallets/abc-123',
+ 'v1/issuance',
+ 'v1/payments',
+ 'v1/compliance/screen',
+ 'v1/projects',
+ ]) {
+ expect(isSdpAllowedPath(p), p).toBe(true);
+ }
+ });
+
+ it('rejects unknown resources, traversal, and arbitrary paths', () => {
+ for (const p of [
+ '',
+ 'v1/secrets',
+ 'v2/wallets',
+ '../etc/passwd',
+ 'v1/wallets/../../admin',
+ 'admin/allowlist',
+ ]) {
+ expect(isSdpAllowedPath(p), p).toBe(false);
+ }
+ });
+
+ it('leading slashes are normalized', () => {
+ expect(isSdpAllowedPath('/v1/wallets')).toBe(true);
+ });
+});
+
+describe('key requirements', () => {
+ it('health/openapi/llms need no key; v1 routes do', () => {
+ expect(sdpPathNeedsKey('health')).toBe(false);
+ expect(sdpPathNeedsKey('health/ready')).toBe(false);
+ expect(sdpPathNeedsKey('openapi.json')).toBe(false);
+ expect(sdpPathNeedsKey('llms.txt')).toBe(false);
+ expect(sdpPathNeedsKey('v1/wallets')).toBe(true);
+ });
+
+ it('sdpConfigured reflects SDP_API_KEY', () => {
+ expect(sdpConfigured()).toBe(false);
+ process.env.SDP_API_KEY = 'sdp_test_key';
+ expect(sdpConfigured()).toBe(true);
+ });
+});
+
+describe('sdpRequest', () => {
+ it('refuses a disallowed path without making a request', async () => {
+ mockFetch(200, { ok: true });
+ await expect(sdpRequest('v1/secrets')).rejects.toMatchObject({ status: 404 });
+ expect(global.fetch).not.toHaveBeenCalled();
+ });
+
+ it('fails closed with 503 when an authenticated route has no key', async () => {
+ mockFetch(200, { ok: true });
+ await expect(sdpRequest('v1/wallets')).rejects.toMatchObject({ status: 503 });
+ expect(global.fetch).not.toHaveBeenCalled();
+ });
+
+ it('calls health with no key and no Authorization header', async () => {
+ mockFetch(200, { status: 'ok' });
+ const res = await sdpRequest('health');
+ expect(res.status).toBe(200);
+ expect(res.body).toEqual({ status: 'ok' });
+ expect(lastRequest.url).toBe('https://api.solana.com/health');
+ expect(lastRequest.headers.authorization).toBeUndefined();
+ });
+
+ it('attaches the Bearer key and honors SDP_API_BASE', async () => {
+ process.env.SDP_API_KEY = 'sdp_live_abc';
+ process.env.SDP_API_BASE = 'https://sandbox.example.com/';
+ mockFetch(200, { items: [] });
+ await sdpRequest('v1/wallets', { query: { limit: 10, skip: '' } });
+ expect(lastRequest.url).toBe('https://sandbox.example.com/v1/wallets?limit=10');
+ expect(lastRequest.headers.authorization).toBe('Bearer sdp_live_abc');
+ });
+
+ it('serializes a JSON body on POST and sets content-type', async () => {
+ process.env.SDP_API_KEY = 'sdp_live_abc';
+ mockFetch(201, { id: 'wal_1' });
+ await sdpRequest('v1/wallets', { method: 'POST', body: { name: 'treasury' } });
+ expect(lastRequest.method).toBe('POST');
+ expect(lastRequest.headers['content-type']).toBe('application/json');
+ expect(JSON.parse(lastRequest.body)).toEqual({ name: 'treasury' });
+ });
+
+ it('returns the upstream status + body without throwing on HTTP errors', async () => {
+ process.env.SDP_API_KEY = 'sdp_live_abc';
+ mockFetch(400, { error: { code: 'BAD_REQUEST', message: 'nope' } }, { traceId: 'trace-9' });
+ const res = await sdpRequest('v1/wallets', { method: 'POST', body: {} });
+ expect(res.status).toBe(400);
+ expect(res.traceId).toBe('trace-9');
+ expect(res.body.error.code).toBe('BAD_REQUEST');
+ });
+});
+
+describe('sdpCall', () => {
+ it('returns the body on 2xx', async () => {
+ mockFetch(200, { status: 'ok' });
+ await expect(sdpHealth()).resolves.toEqual({ status: 'ok' });
+ });
+
+ it('throws the structured upstream error on non-2xx', async () => {
+ process.env.SDP_API_KEY = 'sdp_live_abc';
+ mockFetch(409, { error: { code: 'ALREADY_INITIALIZED', message: 'exists' } });
+ await expect(sdpCall('v1/wallets', { method: 'POST', body: {} })).rejects.toMatchObject({
+ status: 409,
+ code: 'ALREADY_INITIALIZED',
+ });
+ });
+});
diff --git a/tests/discover-rename.test.js b/tests/discover-rename.test.js
index 9fefcc83b..9877ad811 100644
--- a/tests/discover-rename.test.js
+++ b/tests/discover-rename.test.js
@@ -161,14 +161,16 @@ describe('discover/my-agents rename — vercel.json routing', () => {
// Vercel evaluates `routes` top-to-bottom; a permissive earlier rule (e.g. a
// catch-all `(.*)`) would prevent /discover and /my-agents from ever being
// reached. Lock this in so a future re-order can't silently shadow them.
- it('no catch-all rule sits before /discover or /my-agents rewrites', () => {
+ // A `continue: true` catch-all (e.g. the global security-headers route) is
+ // exempt — it only attaches headers and falls through, so it shadows nothing.
+ it('no terminating catch-all rule sits before /discover or /my-agents rewrites', () => {
const idx = (src) => routes.findIndex((x) => x.src === src);
const discoverAt = idx('/discover');
const myAgentsAt = idx('/my-agents');
const earliestProtected = Math.min(discoverAt, myAgentsAt);
const catchAllBefore = routes
.slice(0, earliestProtected)
- .some((r) => r.src === '/(.*)' || r.src === '(.*)');
+ .some((r) => (r.src === '/(.*)' || r.src === '(.*)') && !r.continue);
expect(catchAllBefore).toBe(false);
});
});
diff --git a/tests/pumpfun-signals.test.js b/tests/pumpfun-signals.test.js
index b0a5d8d37..706a7533e 100644
--- a/tests/pumpfun-signals.test.js
+++ b/tests/pumpfun-signals.test.js
@@ -74,9 +74,11 @@ describe('pumpfun-signals cron', () => {
// Subsequent sql calls: insert returning [{id}] for each insert.
sqlMock.mockResolvedValue([{ id: 1 }]);
- // Real Vercel cron requests carry `x-vercel-cron: 1`; without it the
- // handler now fails closed when CRON_SECRET is unset.
- const req = { headers: { 'x-vercel-cron': '1' }, method: 'POST' };
+ // Vercel cron sends `Authorization: Bearer $CRON_SECRET`; the handler now
+ // requires a valid secret unconditionally (the `x-vercel-cron` header is no
+ // longer trusted as an auth bypass).
+ process.env.CRON_SECRET = 'topsecret';
+ const req = { headers: { authorization: 'Bearer topsecret' }, method: 'POST' };
const res = mockRes();
await handler(req, res);
diff --git a/vercel.json b/vercel.json
index 924b2d69a..5a7415204 100644
--- a/vercel.json
+++ b/vercel.json
@@ -69,6 +69,15 @@
}
},
"routes": [
+ {
+ "src": "/(.*)",
+ "headers": {
+ "strict-transport-security": "max-age=63072000; includeSubDomains; preload",
+ "x-content-type-options": "nosniff",
+ "referrer-policy": "strict-origin-when-cross-origin"
+ },
+ "continue": true
+ },
{
"src": "/(login|register|forgot-password|reset-password|account|settings|wallet|pay|paywall|vanity-wallet|eth-vanity|evm-wallet|dashboard|dashboard-next|dashboard-classic)(/.*)?$",
"headers": {