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.

14.5 KB
Raw Blame
import { authenticateBearer, extractBearer } from '../_lib/auth.js';
import {
	paymentRequirements,
	verifyPayment,
	send402,
	build402Body,
	paymentRequiredHeaderValue,
	resolveResourceUrl,
} from '../_lib/x402-spec.js';
import { sendX402Error } from './payments.js';
import { streamSubscriptions, dropSubscriptions } from './resources.js';
import { acceptedAudiences, mcpResourceFor, protectedResourceMetadataUrl } from '../_lib/mcp-resources.js';
import { sessionIdOf } from '../_lib/mcp-clients.js';

function quoteString(s) {
	return `"${String(s).replace(/[\\"]/g, '\\$&')}"`;
}

// Every 401 from a hosted MCP server tells a person reading it how to fix it
// with one command. An MCP client runs its own OAuth off the WWW-Authenticate
// header and ignores these fields; a developer looking at a raw 401 in curl or
// a client log gets the answer instead of a trip through the docs.
export const SETUP_HINT = Object.freeze({
	command: 'npx three-ws setup',
	message: 'Run `npx three-ws setup` to sign in and wire three.ws into your MCP client in one step.',
	docs: 'https://three.ws/docs/cli',
});

// The protected resource a request is for: the endpoint's declared path when
// it passes one, else the path it was reached on. See ../_lib/mcp-resources.js
// for why each hosted server is its own resource.
function requestResource(req, resourcePath) {
	if (resourcePath) return mcpResourceFor(resourcePath);
	const url = req?.url ? String(req.url) : '';
	return mcpResourceFor(url.startsWith('/') ? url : '');
}

// RFC 9728 §5.1: the challenge names the metadata document for THIS resource,
// whose `resource` an MCP client checks against the URL it connected to.
export function bearerChallenge(resource) {
	return `Bearer resource_metadata=${quoteString(protectedResourceMetadataUrl(resource))}, resource=${quoteString(resource)}`;
}

export function send401(res, msg, { req, resourcePath } = {}) {
	const resource = requestResource(req || res?.req, resourcePath);
	res.statusCode = 401;
	res.setHeader('www-authenticate', bearerChallenge(resource));
	res.setHeader('content-type', 'application/json; charset=utf-8');
	res.end(JSON.stringify({ error: 'unauthorized', error_description: msg, setup: SETUP_HINT }));
}

// MCP clients speaking Streamable HTTP MUST advertise SSE support in Accept
// (spec 2025-06-18 §Transports), and post-initialize requests carry the
// MCP-Protocol-Version / Mcp-Session-Id headers. x402 agents, Bazaar
// validators, and registry crawlers (zauth) send none of these — they expect
// a plain 402 Payment Required.
//
// Exported so endpoints can scope free-discovery to plain (non-protocol)
// clients: an OAuth-capable MCP client must still receive the 401 on
// initialize, or it never starts the OAuth flow and dies later at tools/call.
export function isMcpProtocolClient(req) {
	const h = req?.headers || {};
	if (h['mcp-protocol-version'] || h['mcp-session-id']) return true;
	const accept = String(h.accept || '');
	return accept.includes('text/event-stream');
}

// Challenge for an unauthenticated request with no payment. MCP/OAuth clients
// (claude.ai connectors, the MCP TS SDK) get 401 with a WWW-Authenticate
// header so they can discover the protected-resource metadata and start the
// OAuth flow — they require status 401 per the MCP authorization spec
// (RFC 9728). Everything else (x402 agents, Bazaar validators, the zauth
// registry) gets the same envelope as a proper 402 Payment Required, which is
// what x402 tooling keys on. (A bare 402 for everyone made the connector
// probe spin; a blanket 401 made x402 crawlers misclassify the endpoints.)
//
// Both shapes ship the x402 payment envelope in the body + PAYMENT-REQUIRED
// header. WWW-Authenticate rides ONLY on the 401: on a 402 it would carry no
// `Payment` challenge (we speak x402, not MPP/Tempo), and x402scan's audit
// treats any WWW-Authenticate on a 402 as an MPP header and flags the missing
// Payment challenge. A plain client that actually wants OAuth can still find
// the metadata at /.well-known/oauth-protected-resource.
// `paymentStatus: 402` forces a Payment Required answer for EVERY caller, MCP
// protocol clients included, and drops the OAuth WWW-Authenticate hint. The
// OKX.AI surfaces need it: a spec-compliant MCP client sends
// `Accept: application/json, text/event-stream`, which reads as a protocol
// client here and used to earn a 401. The OKX buyer flow keys strictly on 402
// ("if it is not 402, return the body directly"), so a real MCP client calling
// a paid tool unpaid was handed a 401 it could not pay, and a reviewer probing
// with one saw a service with no payment integration. curl never showed it.
export async function sendAuthChallenge(res, { req, resourceUrl, resourcePath, requirements, challenge, paymentStatus = null }) {
	const forced402 = paymentStatus === 402;
	const isProtocolClient = !forced402 && isMcpProtocolClient(req);
	res.statusCode = isProtocolClient ? 401 : 402;
	if (isProtocolClient) res.setHeader('www-authenticate', bearerChallenge(requestResource(req, resourcePath)));
	// `challenge` (optional) lets a dedicated MCP endpoint advertise its own
	// service metadata + bazaar discovery in the 402 envelope (the Granite
	// server at /api/ibm-mcp, the 3D Studio at /api/mcp-3d). Omitted →
	// build402Body's defaults, used by the main /api/mcp server.
	// build402Body is async (it signs per-accept offer receipts), so await it —
	// stringifying the unresolved Promise shipped an empty `{}` envelope before.
	const envelope = await build402Body({ resourceUrl, accepts: requirements, ...(challenge || {}) });
	const headerValue = paymentRequiredHeaderValue(envelope);
	// The setup hint rides only on the 401 a protocol client receives; the 402
	// stays the exact x402 envelope that payment tooling and audits parse.
	const body = isProtocolClient ? { ...envelope, setup: SETUP_HINT } : envelope;
	if (headerValue) res.setHeader('PAYMENT-REQUIRED', headerValue);
	res.setHeader('content-type', 'application/json; charset=utf-8');
	res.setHeader('cache-control', 'no-store');
	res.end(JSON.stringify(body));
}

export function sendJsonRpcError(res, id, code, message, data) {
	res.statusCode = 200;
	res.setHeader('content-type', 'application/json; charset=utf-8');
	res.end(JSON.stringify({ jsonrpc: '2.0', id: id ?? null, error: { code, message, data } }));
}

// Returns { auth, x402Ctx } on success, or null if a response was already sent.
//
// `opts.x402Amount` (atomic-unit string | null) is the per-tool price for the
// tools/call being made. When provided it overrides the flat env price in the
// 402 challenge AND in the requirements used to verify the X-PAYMENT, so the
// advertised price and the charged price agree. null = use the flat default
// (initialize / tools/list / free tools / mixed batches).
// Prepended rails can collide with the shared builder's own output: when the
// OKX X Layer rail is configured, paymentRequirements() already emits it, so a
// bare prepend leaves two identical `exact` entries in accepts[]. Harmless to a
// payer, but it is the first thing a marketplace reviewer reads, and a listing
// that advertises the same rail twice looks broken. Keep the FIRST occurrence
// (that is the whole point of prepending) and drop later twins.
function mergeAccepts(extra, base) {
	const seen = new Set();
	const out = [];
	for (const a of [...extra, ...base]) {
		const key = [a?.scheme, a?.network, a?.asset, a?.amount ?? a?.maxAmountRequired, a?.payTo]
			.map((v) => String(v ?? '').toLowerCase())
			.join('|');
		if (seen.has(key)) continue;
		seen.add(key);
		out.push(a);
	}
	return out;
}

export async function authenticateRequest(
	req,
	res,
	{ x402Amount, resourcePath = '/api/mcp', challenge, allowFree = false, extraAccepts = [], paymentStatus = null } = {},
) {
	const bearer = extractBearer(req);
	// OKX Agent Payments Protocol buyers replay with PAYMENT-SIGNATURE (x402 v2
	// HTTP transport); everything else uses the legacy X-PAYMENT name. Same
	// base64-JSON payload either way — verifyPayment handles both dialects.
	const paymentHeader = req.headers['x-payment'] || req.headers['payment-signature'];

	if (bearer) {
		const auth = await authenticateBearer(bearer, { audience: acceptedAudiences(mcpResourceFor(resourcePath)) });
		if (!auth) {
			send401(res, 'missing or invalid access token', { req, resourcePath });
			return null;
		}
		return { auth, x402Ctx: null };
	}

	// Free, public entry point. When the caller has no bearer/payment AND the
	// request targets an explicitly-public tool (the endpoint passes
	// allowFree=true only for those — never for merely-unpriced scoped tools), we
	// serve as an anonymous principal instead of issuing the OAuth/x402 challenge.
	// scope '' means scoped tools stay locked; rateKey null so per-user limits key
	// off the caller IP. This is what lets getting_started work with no credentials.
	if (allowFree) {
		return {
			auth: { userId: null, rateKey: null, scope: '', source: 'free' },
			x402Ctx: null,
		};
	}

	const resourceUrl = resolveResourceUrl(req, resourcePath);
	// A dedicated endpoint can prepend rails the shared builder doesn't emit —
	// e.g. the OKX X Layer (eip155:196) accept must LEAD for OKX buyers (their
	// CLI auto-selects the first `exact` entry). Prepended so it also participates
	// in verifyPayment, letting an X Layer replay verify + settle here.
	const requirements = mergeAccepts(
		extraAccepts,
		paymentRequirements(resourceUrl, x402Amount != null ? { amount: x402Amount } : {}),
	);

	if (paymentHeader) {
		try {
			const verified = await verifyPayment({ paymentHeader, requirements });
			const x402Ctx = {
				resourceUrl,
				requirements,
				requirement: verified.requirement,
				paymentPayload: verified.paymentPayload,
				payer: verified.payer,
				// Carry the full verified envelope so the settle path can
				// pass it to settlePayment({ verified }) and enforce
				// payer-binding on the facilitator's response.
				verified,
			};
			// Anonymous paid caller — synthesize an auth principal scoped to public-read tools.
			// userId is null because usage_events.user_id is a UUID FK; the payer wallet is
			// kept on the auth object so handlers and rate limits can key off of it.
			return {
				auth: {
					userId: null,
					rateKey: `x402:${x402Ctx.payer || 'anon'}`,
					// Pay-per-call callers have no user account, so they cannot read or
					// write account-scoped data. They get only the no-scope public tools
					// (search_public_avatars, validate/inspect/optimize_model, solana_*).
					scope: '',
					source: 'x402',
					payer: x402Ctx.payer,
					// The HTTP layer verified this X-PAYMENT against the per-tool
					// price (paymentRequirements amount === x402AmountForTool). The
					// dispatcher reads this to avoid double-billing the caller with a
					// redundant pump-agent-payments subscription demand.
					x402Paid: true,
				},
				x402Ctx,
			};
		} catch (err) {
			await sendX402Error(res, { resourceUrl, accepts: requirements, challenge }, err);
			return null;
		}
	}

	await sendAuthChallenge(res, { req, resourceUrl, resourcePath, requirements, challenge, paymentStatus });
	return null;
}

// `x402Amount` is the endpoint's list price. Without it, paymentRequirements()
// quotes the shared default here while the prepended rail quotes the real price,
// so the discovery challenge advertised the SAME rail twice at two DIFFERENT
// amounts. A buyer reading accepts[] could not tell which one the endpoint
// actually charges, and it is the first array a marketplace reviewer opens.
//
// `resourceServer` ('mcp' | 'mcp-agent' | 'mcp-3d' | 'mcp-bazaar') turns an
// authenticated GET into the server-to-client event stream that carries
// notifications/resources/updated for the caller's resources/subscribe calls
// (api/_mcp/resources.js). Without it, an authenticated GET answers 405.
export async function handleSse(
	req,
	res,
	{ resourcePath = '/api/mcp', challenge, extraAccepts = [], x402Amount = null, paymentStatus = null, resourceServer = null } = {},
) {
	const bearer = extractBearer(req);
	// Unauthenticated callers without an X-PAYMENT header get a 401 +
	// WWW-Authenticate so OAuth clients (claude.ai) can discover the auth
	// server, with the x402 envelope still attached for x402 clients. Invalid
	// bearers also get 401 with WWW-Authenticate so they can re-auth correctly.
	if (!bearer && !req.headers['x-payment'] && !req.headers['payment-signature']) {
		const sseResourceUrl = resolveResourceUrl(req, resourcePath);
		return await sendAuthChallenge(res, {
			req,
			resourceUrl: sseResourceUrl,
			resourcePath,
			requirements: mergeAccepts(
				extraAccepts,
				paymentRequirements(sseResourceUrl, x402Amount != null ? { amount: x402Amount } : {}),
			),
			challenge,
			paymentStatus,
		});
	}
	const auth = await authenticateBearer(bearer, { audience: acceptedAudiences(mcpResourceFor(resourcePath)) });
	if (!auth) return send401(res, 'missing or invalid access token', { req, resourcePath });
	const wantsStream = String(req.headers?.accept || '').includes('text/event-stream');
	if (resourceServer && req.method === 'GET' && wantsStream) {
		return streamSubscriptions(resourceServer, req, res, auth);
	}
	res.statusCode = 405;
	res.setHeader('allow', resourceServer ? 'GET, POST, DELETE' : 'POST, DELETE');
	res.end();
}

// A DELETE also releases the caller's resource subscriptions on `resourceServer`
// (keyed by session id when sent, otherwise by credential), so a client that
// tears down cleanly stops being polled for.
export async function handleTerminate(req, res, { resourceServer = null } = {}) {
	if (resourceServer) {
		const auth = await authenticateBearer(extractBearer(req), { audience: acceptedAudiences(mcpResourceFor(`/api/${resourceServer}`)) });
		if (auth) {
			await dropSubscriptions(resourceServer, auth, req).catch((err) =>
				console.warn('[mcp] subscription cleanup failed', resourceServer, err?.message),
			);
		}
	}
	// This server serves every request statelessly. The only session ids it
	// issues are the analytics ids handed out on initialize
	// (api/_lib/mcp-clients.js), which hold no server state, so ending one is
	// the ordinary polite teardown: 204. Any other id names a session that does
	// not exist here, and the Streamable HTTP transport says a server MUST
	// answer 404 for a session id it does not hold, which is the client's
	// signal to start a fresh session. A DELETE with no session id: 204.
	const sessionId = req.headers?.['mcp-session-id'];
	if (sessionId && !sessionIdOf(req)) {
		res.statusCode = 404;
		res.setHeader('content-type', 'application/json');
		res.end(JSON.stringify({ error: 'unknown_session', message: 'no such MCP session; start a new one' }));
		return;
	}
	res.statusCode = 204;
	res.end();
}