Skip to content

Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.

fix(erc8004): resolve a cross-origin agent card through the proxy first so the page stops opening with CORS errors

nirholasc3487a38dcd7
diff --git a/src/erc8004/queries.js b/src/erc8004/queries.js
index 10304d700..ea2d68252 100644
--- a/src/erc8004/queries.js
+++ b/src/erc8004/queries.js
@@ -196,11 +196,15 @@ export { findAvatar3D } from './avatar-meta.js';
* Resolve any IPFS/Arweave/data/https URI to a fetchable URL and parse JSON.
*
* An agent's registration JSON lives wherever its registrant put it, and most
- * of those hosts send no Access-Control-Allow-Origin, so the direct browser
- * fetch below is blocked by CORS for a large share of real agents. When that
- * happens we retry through /api/erc8004/metadata, which fetches server-side
- * (no same-origin policy) behind the SSRF guard. The direct attempt stays
- * first so a CORS-friendly host never pays for the extra hop.
+ * of those hosts send no Access-Control-Allow-Origin, so a direct browser fetch
+ * is blocked by CORS for a large share of real agents. A blocked fetch cannot
+ * be caught quietly: the browser logs "blocked by CORS policy" plus a failed
+ * request before the promise ever rejects, so trying it first made every such
+ * agent's page open with two console errors even though the agent loaded fine.
+ * A cross-origin URI therefore goes to /api/erc8004/metadata first, which
+ * fetches server-side (no same-origin policy) behind the SSRF guard, and falls
+ * back to the direct fetch if our proxy is the one that fails. Same-origin URIs
+ * skip the proxy entirely: there is nothing to work around.
*
* @param {string} uri
* @returns {Promise<{ ok: boolean, data?: any, error?: string, resolvedUrl?: string, viaProxy?: boolean }>}
@@ -224,33 +228,50 @@ export async function fetchAgentMetadata(uri) {
if (uri.startsWith('ipfs://')) url = 'https://ipfs.io/ipfs/' + uri.slice(7);
else if (uri.startsWith('ar://')) url = 'https://arweave.net/' + uri.slice(5);
- let directError;
+ if (isSameOrigin(url)) return fetchAgentMetadataDirect(url);
+
+ const viaProxy = await fetchAgentMetadataViaProxy(uri, url);
+ if (viaProxy.ok) return viaProxy;
+
+ const direct = await fetchAgentMetadataDirect(url);
+ // Our proxy is the one that failed here, so its reason is the useful one
+ // unless the direct attempt got further and produced its own.
+ return direct.ok ? direct : { ...direct, error: viaProxy.error || direct.error };
+}
+
+function isSameOrigin(url) {
+ if (typeof location === 'undefined') return false;
+ try {
+ return new URL(url, location.href).origin === location.origin;
+ } catch {
+ return false;
+ }
+}
+
+async function fetchAgentMetadataDirect(url) {
try {
const res = await fetch(url);
if (res.ok) return { ok: true, data: await res.json(), resolvedUrl: url };
- directError = `HTTP ${res.status}`;
+ return { ok: false, error: `HTTP ${res.status}`, resolvedUrl: url };
} catch (err) {
// A CORS block surfaces here as an opaque TypeError with no status.
- directError = err.message;
+ return { ok: false, error: err.message, resolvedUrl: url };
}
-
- return fetchAgentMetadataViaProxy(uri, url, directError);
}
-async function fetchAgentMetadataViaProxy(uri, url, directError) {
+async function fetchAgentMetadataViaProxy(uri, url) {
try {
const res = await fetch(`/api/erc8004/metadata?uri=${encodeURIComponent(uri)}`);
const body = await res.json().catch(() => null);
if (!res.ok) {
return {
ok: false,
- error: body?.error_description || body?.error || directError,
+ error: body?.error_description || body?.error || `HTTP ${res.status}`,
resolvedUrl: url,
};
}
return { ok: true, data: body.data, resolvedUrl: body.resolvedUrl || url, viaProxy: true };
- } catch {
- // Both rungs failed; report the original failure, which is the useful one.
- return { ok: false, error: directError, resolvedUrl: url };
+ } catch (err) {
+ return { ok: false, error: err.message, resolvedUrl: url };
}
}
diff --git a/tests/erc8004-metadata-fetch-order.test.js b/tests/erc8004-metadata-fetch-order.test.js
new file mode 100644
index 000000000..15abfb420
--- /dev/null
+++ b/tests/erc8004-metadata-fetch-order.test.js
@@ -0,0 +1,102 @@
+// fetchAgentMetadata resolution order.
+//
+// An agent's registration JSON is hosted wherever its registrant put it, and
+// most of those hosts send no Access-Control-Allow-Origin. A browser cannot
+// fail that request quietly: it logs "blocked by CORS policy" and a failed
+// request BEFORE the promise rejects, so attempting the direct fetch first made
+// every such agent open its page with two console errors even though the agent
+// then loaded fine through the proxy. These pin the order (proxy first for a
+// cross-origin URI, direct first for a same-origin one) and the fallback that
+// keeps the second rung alive.
+
+import { describe, it, expect, beforeEach, vi } from 'vitest';
+
+vi.mock('ethers', () => ({
+ BrowserProvider: class {},
+ Contract: class {},
+ JsonRpcProvider: class {},
+}));
+
+const { fetchAgentMetadata } = await import('../src/erc8004/queries.js');
+
+const ORIGIN = 'https://three.ws';
+const CARD = { name: 'GetDigitalCraft', service: [] };
+
+let calls;
+function stubFetch(handlers) {
+ globalThis.fetch = vi.fn(async (url) => {
+ calls.push(String(url));
+ for (const [pattern, reply] of handlers) {
+ if (String(url).includes(pattern)) return reply();
+ }
+ throw new TypeError('Failed to fetch');
+ });
+}
+
+const okJson = (body) => () => ({ ok: true, status: 200, json: async () => body });
+const corsBlocked = () => () => {
+ throw new TypeError('Failed to fetch');
+};
+
+beforeEach(() => {
+ calls = [];
+ globalThis.location = new URL(`${ORIGIN}/app`);
+});
+
+describe('cross-origin registration URI', () => {
+ const uri = 'https://x402render.example/.well-known/agent-card.json';
+
+ it('asks our proxy before ever touching the third-party host', async () => {
+ stubFetch([['/api/erc8004/metadata', okJson({ data: CARD, resolvedUrl: uri })]]);
+ const out = await fetchAgentMetadata(uri);
+ expect(out.ok).toBe(true);
+ expect(out.data).toEqual(CARD);
+ expect(out.viaProxy).toBe(true);
+ expect(calls).toHaveLength(1);
+ expect(calls[0]).toContain('/api/erc8004/metadata');
+ expect(calls[0]).not.toContain('x402render.example/.well-known');
+ });
+
+ it('falls back to the direct fetch when our proxy is the one that fails', async () => {
+ stubFetch([
+ ['/api/erc8004/metadata', () => ({ ok: false, status: 502, json: async () => ({ error: 'upstream_failed' }) })],
+ ['x402render.example', okJson(CARD)],
+ ]);
+ const out = await fetchAgentMetadata(uri);
+ expect(out.ok).toBe(true);
+ expect(out.data).toEqual(CARD);
+ expect(calls).toHaveLength(2);
+ expect(calls[1]).toContain('x402render.example');
+ });
+
+ it('reports the proxy failure when both rungs fail', async () => {
+ stubFetch([
+ ['/api/erc8004/metadata', () => ({ ok: false, status: 502, json: async () => ({ error_description: 'upstream refused' }) })],
+ ['x402render.example', corsBlocked()],
+ ]);
+ const out = await fetchAgentMetadata(uri);
+ expect(out.ok).toBe(false);
+ expect(out.error).toBe('upstream refused');
+ });
+});
+
+describe('same-origin registration URI', () => {
+ it('fetches directly and never pays for the proxy hop', async () => {
+ stubFetch([[`${ORIGIN}/a/sol/x/.well-known`, okJson(CARD)]]);
+ const out = await fetchAgentMetadata(`${ORIGIN}/a/sol/x/.well-known/agent-card.json`);
+ expect(out.ok).toBe(true);
+ expect(calls).toHaveLength(1);
+ expect(calls[0]).not.toContain('/api/erc8004/metadata');
+ });
+});
+
+describe('inline data URI', () => {
+ it('parses without any network call at all', async () => {
+ stubFetch([]);
+ const payload = encodeURIComponent(JSON.stringify(CARD));
+ const out = await fetchAgentMetadata(`data:application/json,${payload}`);
+ expect(out.ok).toBe(true);
+ expect(out.data).toEqual(CARD);
+ expect(calls).toHaveLength(0);
+ });
+});