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(mcp): call the forge on the configured origin, never one named by a request header

nirholas20d2001fa2d9
diff --git a/api/_lib/self-origin.js b/api/_lib/self-origin.js
new file mode 100644
index 000000000..7604f5eff
--- /dev/null
+++ b/api/_lib/self-origin.js
@@ -0,0 +1,29 @@
+// The origin a handler uses to call this same deployment server-side, and to
+// build links it hands back to callers.
+//
+// It is never taken from `x-forwarded-host`, and in production never from
+// `host` either: both are whatever the client sent. A self-call that trusts
+// them is an SSRF primitive (the server fetches `${host}/api/...` for any host
+// the caller names) and, where the self-call carries an internal credential
+// such as the forge seed header, a way to hand that credential to an attacker.
+// Production always anchors on env.APP_ORIGIN, the same rule resolveResourceUrl
+// (api/_lib/x402-spec.js) applies to payment URLs.
+//
+// Local development keeps working without configuration: a loopback Host header
+// outside production is honored so `npm run dev` calls itself on its own port.
+
+import { env } from './env.js';
+
+const LOOPBACK_HOST = /^(localhost|127\.0\.0\.1|\[::1\])(:\d{1,5})?$/i;
+
+/**
+ * @param {{ headers?: Record<string, string | string[] | undefined> }} [req]
+ * @returns {string} absolute origin with no trailing slash
+ */
+export function selfOrigin(req) {
+ if (!env.isProduction) {
+ const host = String(req?.headers?.host || '').trim();
+ if (LOOPBACK_HOST.test(host)) return `http://${host}`;
+ }
+ return env.APP_ORIGIN.replace(/\/$/, '');
+}
diff --git a/api/_lib/solana/connection.js b/api/_lib/solana/connection.js
index 6046a7031..31e45ef22 100644
--- a/api/_lib/solana/connection.js
+++ b/api/_lib/solana/connection.js
@@ -201,6 +201,7 @@ const RATE_LIMIT_COOLDOWN_MS = 10 * 60_000; // 10m, transient 429
const AUTH_COOLDOWN_MS = 30 * 60_000; // 30m: bad/expired key on this provider only
const SERVER_COOLDOWN_MS = 2 * 60_000; // 2m: provider 5xx
const NETWORK_COOLDOWN_MS = 30_000; // 30s: fetch threw (DNS/connection blip)
+const TLS_FAULT_COOLDOWN_MS = AUTH_COOLDOWN_MS; // 30m: the lane's own TLS terminator refused us
// ---------------------------------------------------------------------------
// Whole-chain transport failure: re-sweep, then serve last-good
@@ -270,6 +271,32 @@ export function transportCause(err) {
return '';
}
+// TLS handshake and certificate failures, by the undici/OpenSSL cause code.
+// These are NOT wire weather. The TCP connection reached the provider and the
+// provider's own TLS terminator refused us (an alert) or presented a certificate
+// nobody should trust. Every retry gets the identical answer until someone fixes
+// the endpoint: a QuickNode endpoint that has been disabled, deleted or suspended
+// answers every handshake with `tlsv1 alert internal error`.
+const TLS_LANE_FAULT =
+ /^(?:ERR_SSL_|ERR_TLS_|CERT_|UNABLE_TO_(?:GET|VERIFY)_|DEPTH_ZERO_SELF_SIGNED_CERT|SELF_SIGNED_CERT_IN_CHAIN|HOSTNAME_MISMATCH)/;
+
+/**
+ * Is this transport cause (from transportCause) a TLS refusal by the lane itself?
+ *
+ * Measured on 2026-10-08: the operator's last-resort QuickNode endpoint failed
+ * every handshake with ERR_SSL_TLSV1_ALERT_INTERNAL_ERROR. Treated as a 30-second
+ * network blip it re-qualified twice a minute, so whenever the other lanes were
+ * cooling it was the only candidate left, and because its failure read as
+ * "transport only" it triggered the whole-chain re-sweep, which re-hammered the
+ * 429-cooling free lanes on every request. That one dead endpoint is why 126 of
+ * the Solana agent index's cursors carried its error after a single tick.
+ * @param {string} cause
+ * @returns {boolean}
+ */
+export function isTlsLaneFault(cause) {
+ return TLS_LANE_FAULT.test(String(cause || ''));
+}
+
/** djb2 over a string. Keys the last-good cache; collisions are made harmless by including the method and length in the key. */
function hashText(text) {
let h = 5381;
@@ -1596,8 +1623,22 @@ export function makeRotatingFetch(endpoints) {
attemptTimedOut: attemptSignal.aborted,
hasMethods: methods.length > 0,
});
+ const cause = disposition === 'cool-lane' ? transportCause(err) : '';
+ const tlsFault = isTlsLaneFault(cause);
if (disposition === 'demote-method') {
penalise(url, 504, '', true, `no answer within ${Math.round(ATTEMPT_TIMEOUT_MS / 1000)}s`);
+ } else if (tlsFault) {
+ // The lane refused the handshake itself: park it like a rejected key,
+ // and tell the fleet, so it stops being the last candidate standing.
+ const alreadyCooling = isEndpointCooling(url);
+ const now = Date.now();
+ _endpointCooldown.set(url, now + TLS_FAULT_COOLDOWN_MS);
+ publishCooldowns(now);
+ if (!alreadyCooling) {
+ console.log(
+ `[solana-rpc] ${maskUrl(url)} refused the TLS handshake (${cause}), cooling ${formatCooldown(TLS_FAULT_COOLDOWN_MS)}, failing over`,
+ );
+ }
} else if (disposition === 'cool-lane') {
_endpointCooldown.set(url, Date.now() + NETWORK_COOLDOWN_MS);
}
@@ -1606,10 +1647,13 @@ export function makeRotatingFetch(endpoints) {
// (EAI_AGAIN is a resolver problem, ECONNRESET a socket one) instead of
// undici's bare "fetch failed". The original stays on `cause`.
noteRpc(url, 'fail', Date.now() - attemptStartedAt, 'live', err?.name === 'TimeoutError' ? 'timeout' : 'network');
- const cause = disposition === 'cool-lane' ? transportCause(err) : '';
if (cause) {
const tagged = new Error(`${err?.message || 'fetch failed'} (${cause}) @ ${maskUrl(url)}`, { cause: err });
- return { error: tagged, transport: true };
+ // A TLS refusal is a verdict about the lane, not about our egress, so
+ // it must not arm the whole-chain re-sweep: re-asking every lane in
+ // the same request cannot change the peer's answer, and on a tick
+ // where the other lanes are 429-cooling it only extends their bench.
+ return { error: tagged, transport: !tlsFault };
}
return { error: err };
}
diff --git a/api/_mcp-studio/forge-client.js b/api/_mcp-studio/forge-client.js
index 75f8532f3..6dafd3231 100644
--- a/api/_mcp-studio/forge-client.js
+++ b/api/_mcp-studio/forge-client.js
@@ -7,11 +7,11 @@
// payment, or API key is ever involved. This module is the SAME submit/poll
// logic the npm MCP tools use, factored once — not a fork and not a mock.
//
-// All work runs against the deployment's own origin (resolved from the incoming
-// request, falling back to PUBLIC_APP_ORIGIN / https://three.ws), so the studio
+// All work runs against the deployment's own origin (STUDIO_API_BASE, else the
+// configured PUBLIC_APP_ORIGIN; see api/_lib/self-origin.js), so the studio
// front door and the generation pipeline are always the same deployment.
-import { env } from '../_lib/env.js';
+import { selfOrigin } from '../_lib/self-origin.js';
import { watsonxConfig, watsonxChatComplete } from '../_lib/watsonx.js';
import { llmComplete } from '../_lib/llm.js';
@@ -23,18 +23,14 @@ function envNum(key, def) {
return Number.isFinite(v) && v > 0 ? v : def;
}
-// Resolve the origin to call /api/forge on. Prefer the request's own host so the
-// studio endpoint is self-referential on any deployment (preview, prod, local
-// dev), then PUBLIC_APP_ORIGIN, then the canonical fallback.
+// Resolve the origin to call /api/forge on: STUDIO_API_BASE when set, otherwise
+// the configured app origin (selfOrigin). Never a request header: the forge
+// self-call can carry the internal seed credential, and a caller-chosen
+// `x-forwarded-host` would send it, and the request, to any host they name.
export function originFromReq(req) {
const explicit = process.env.STUDIO_API_BASE && String(process.env.STUDIO_API_BASE).trim();
if (explicit) return explicit.replace(/\/$/, '');
- const host = req?.headers?.['x-forwarded-host'] || req?.headers?.host;
- if (host) {
- const proto = req.headers['x-forwarded-proto'] || (/^localhost|127\.0\.0\.1/.test(host) ? 'http' : 'https');
- return `${proto}://${host}`.replace(/\/$/, '');
- }
- return env.APP_ORIGIN.replace(/\/$/, '');
+ return selfOrigin(req);
}
export function viewerUrl(base, glbUrl) {
diff --git a/api/_mcp-studio/gpt-forge-client.js b/api/_mcp-studio/gpt-forge-client.js
index 630d5f0d6..e77cc2ca0 100644
--- a/api/_mcp-studio/gpt-forge-client.js
+++ b/api/_mcp-studio/gpt-forge-client.js
@@ -11,11 +11,11 @@
// payment, or API key is ever involved. This module is the SAME submit/poll
// logic the npm MCP tools use, factored once — not a fork and not a mock.
//
-// All work runs against the deployment's own origin (resolved from the incoming
-// request, falling back to PUBLIC_APP_ORIGIN / https://three.ws), so the studio
+// All work runs against the deployment's own origin (STUDIO_API_BASE, else the
+// configured PUBLIC_APP_ORIGIN; see api/_lib/self-origin.js), so the studio
// front door and the generation pipeline are always the same deployment.
-import { env } from '../_lib/env.js';
+import { selfOrigin } from '../_lib/self-origin.js';
import { watsonxConfig, watsonxChatComplete } from '../_lib/watsonx.js';
import { llmComplete } from '../_lib/llm.js';
import { TICKET_HEADER, newTicket, ticketHandle } from '../_lib/forge-submit-ticket.js';
@@ -45,18 +45,14 @@ function envNum(key, def) {
return Number.isFinite(v) && v > 0 ? v : def;
}
-// Resolve the origin to call /api/gpt-forge on. Prefer the request's own host so the
-// studio endpoint is self-referential on any deployment (preview, prod, local
-// dev), then PUBLIC_APP_ORIGIN, then the canonical fallback.
+// Resolve the origin to call /api/gpt-forge on: STUDIO_API_BASE when set, otherwise
+// the configured app origin (selfOrigin). Never a request header: the forge
+// self-call can carry the internal seed credential, and a caller-chosen
+// `x-forwarded-host` would send it, and the request, to any host they name.
export function originFromReq(req) {
const explicit = process.env.STUDIO_API_BASE && String(process.env.STUDIO_API_BASE).trim();
if (explicit) return explicit.replace(/\/$/, '');
- const host = req?.headers?.['x-forwarded-host'] || req?.headers?.host;
- if (host) {
- const proto = req.headers['x-forwarded-proto'] || (/^localhost|127\.0\.0\.1/.test(host) ? 'http' : 'https');
- return `${proto}://${host}`.replace(/\/$/, '');
- }
- return env.APP_ORIGIN.replace(/\/$/, '');
+ return selfOrigin(req);
}
export function viewerUrl(base, glbUrl) {
diff --git a/docs/ops/solana-rpc-lanes.md b/docs/ops/solana-rpc-lanes.md
index 106342e8d..023eb0705 100644
--- a/docs/ops/solana-rpc-lanes.md
+++ b/docs/ops/solana-rpc-lanes.md
@@ -331,6 +331,17 @@ answers, cheapest first:
- **One jittered re-sweep.** When the first sweep was transport-only, every lane
is tried once more after a 250-700 ms pause. An HTTP 429 or a quota body is a
verdict about the lane, not the wire, and never triggers it.
+- **A TLS refusal is a lane verdict too.** A handshake alert or an untrusted
+ certificate (`ERR_SSL_*`, `ERR_TLS_*`, `CERT_*`, see `isTlsLaneFault`) means the
+ connection reached the provider and the provider's own TLS terminator said no;
+ every retry gets the same answer. Those lanes cool for 30 minutes (published to
+ the fleet) and never arm the re-sweep. On 2026-10-08 a disabled QuickNode
+ endpoint in `SOLANA_RPC_LAST_RESORT_URLS` answered every handshake with
+ `ERR_SSL_TLSV1_ALERT_INTERNAL_ERROR`; read as a 30-second blip it re-qualified
+ twice a minute, was the last lane standing whenever the rest were cooling, and
+ re-hammered the 429-cooling free lanes on every request through the re-sweep.
+ If `curl -v` against a lane ends in `TLS alert, internal error`, the endpoint is
+ dead: remove or replace it in the service env.
- **Last-good reads instead of a 502.** Idempotent read methods (`getBalance`,
`getAccountInfo`, `getMultipleAccounts`, `getTokenAccountsByOwner`,
`getTokenLargestAccounts`, `getProgramAccounts`, `getSignaturesForAddress`,
diff --git a/tests/solana-rpc-transport-fallback.test.js b/tests/solana-rpc-transport-fallback.test.js
index 8f5dd88fc..0388b0c4b 100644
--- a/tests/solana-rpc-transport-fallback.test.js
+++ b/tests/solana-rpc-transport-fallback.test.js
@@ -5,6 +5,8 @@ import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
import {
makeRotatingFetch,
transportCause,
+ isTlsLaneFault,
+ isEndpointCooling,
lastGoodKey,
_resetLastGoodMemo,
} from '../api/_lib/solana/connection.js';
@@ -148,3 +150,55 @@ describe('makeRotatingFetch whole-chain transport fallbacks', () => {
await expect(rotate(eps[0], { method: 'POST', body: body('getLatestBlockhash') })).rejects.toThrow(/ECONNRESET/);
});
});
+
+describe('TLS refusals are a verdict about the lane, not egress weather', () => {
+ // Measured 2026-10-08: the operator's QuickNode last-resort lane failed every
+ // handshake with ERR_SSL_TLSV1_ALERT_INTERNAL_ERROR. As a 30-second blip it
+ // re-qualified twice a minute and armed the whole-chain re-sweep each time.
+ it('classifies handshake and certificate failures, and nothing else', () => {
+ expect(isTlsLaneFault('ERR_SSL_TLSV1_ALERT_INTERNAL_ERROR')).toBe(true);
+ expect(isTlsLaneFault('ERR_SSL_SSL/TLS_ALERT_HANDSHAKE_FAILURE')).toBe(true);
+ expect(isTlsLaneFault('CERT_HAS_EXPIRED')).toBe(true);
+ expect(isTlsLaneFault('UNABLE_TO_VERIFY_LEAF_SIGNATURE')).toBe(true);
+ expect(isTlsLaneFault('ERR_TLS_CERT_ALTNAME_INVALID')).toBe(true);
+ for (const code of ['ECONNRESET', 'EAI_AGAIN', 'ECONNREFUSED', 'ETIMEDOUT', 'transport', '', null]) {
+ expect(isTlsLaneFault(code)).toBe(false);
+ }
+ });
+
+ it('parks the lane for the long window and does not re-sweep the chain', async () => {
+ const eps = ['https://tls-dead.test/', 'https://tls-busy.test/'];
+ let calls = 0;
+ global.fetch = vi.fn(async (url) => {
+ calls += 1;
+ if (String(url).includes('tls-dead')) throw netFail('ERR_SSL_TLSV1_ALERT_INTERNAL_ERROR');
+ return new Response('slow down', { status: 429 });
+ });
+ vi.spyOn(console, 'log').mockImplementation(() => {});
+ vi.spyOn(console, 'warn').mockImplementation(() => {});
+ await expect(
+ makeRotatingFetch(eps)(eps[0], { method: 'POST', body: body('getSlot') }),
+ ).rejects.toThrow();
+ // One attempt per lane, no transport re-sweep on top.
+ expect(calls).toBe(2);
+ // Still parked well past the 30-second network-blip window.
+ const realNow = Date.now();
+ vi.spyOn(Date, 'now').mockReturnValue(realNow + 20 * 60_000);
+ expect(isEndpointCooling(eps[0])).toBe(true);
+ });
+
+ it('still names the TLS cause on the exhausted-chain error', async () => {
+ const eps = ['https://tls-only.test/'];
+ let calls = 0;
+ global.fetch = vi.fn(async () => {
+ calls += 1;
+ throw netFail('ERR_SSL_TLSV1_ALERT_INTERNAL_ERROR');
+ });
+ vi.spyOn(console, 'log').mockImplementation(() => {});
+ vi.spyOn(console, 'warn').mockImplementation(() => {});
+ await expect(
+ makeRotatingFetch(eps)(eps[0], { method: 'POST', body: body('getSlot') }),
+ ).rejects.toThrow(/ERR_SSL_TLSV1_ALERT_INTERNAL_ERROR\) @ https:\/\/tls-only\.test/);
+ expect(calls).toBe(1);
+ });
+});