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.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
fix(onramp): mint a CDP session token instead of building the retired checkout URL
nirholas7810f6368c24
diff --git a/api/_lib/coinbase-onramp.js b/api/_lib/coinbase-onramp.jsnew file mode 100644index 000000000..262c7854c--- /dev/null+++ b/api/_lib/coinbase-onramp.js@@ -0,0 +1,188 @@+// @ts-check+// Coinbase Onramp session tokens.+//+// Coinbase's hosted onramp used to accept the destination wallet directly in the+// checkout URL (`appId` + `destinationWallets`). That initialization path is gone:+// https://pay.coinbase.com/buy/select-asset now requires a `sessionToken` minted+// server-side from the CDP Onramp Session Token API, and the wallet address is+// passed to that API instead of the query string. A URL built the old way lands+// the buyer on an error page, so this module is the only supported way for us to+// send someone to Coinbase with their three.ws wallet pre-filled as the+// destination.+//+// Requires CDP_API_KEY_ID + CDP_API_KEY_SECRET (the same CDP key pair the x402+// facilitator already uses, see api/_lib/x402-spec.js). Tokens are single-use and+// expire after five minutes, so one is minted per checkout link, never cached.+//+// Spec: https://docs.cdp.coinbase.com/onramp/coinbase-hosted-onramp/generating-onramp-url++import { generateJwt } from '@coinbase/cdp-sdk/auth';+import { env } from './env.js';+import { clientIp } from './rate-limit.js';++const CDP_HOST = 'api.developer.coinbase.com';+const TOKEN_PATH = '/onramp/v1/token';+const TOKEN_URL = `https://${CDP_HOST}${TOKEN_PATH}`;++// The token call is on the critical path of a user click, so it fails fast to the+// keyless fallback rather than leaving the "Add funds" button spinning.+const TOKEN_TIMEOUT_MS = 8_000;++// The CDP API rejects private and loopback source addresses, which is exactly what+// a local dev box or a container-internal call reports. Coinbase's own integration+// guide prescribes the RFC 5737 documentation address for that case; it is a+// placeholder for the caller's network location, not for any response data.+const DOCUMENTATION_IP = '192.0.2.1';++const PRIVATE_V4 = [+ /^10\./,+ /^127\./,+ /^169\.254\./,+ /^192\.168\./,+ /^172\.(1[6-9]|2\d|3[01])\./,+ /^100\.(6[4-9]|[7-9]\d|1[01]\d|12[0-7])\./,+ /^0\./,+];++/**+ * Is this address routable on the public internet? Anything private, loopback,+ * link-local, or unique-local is not, and must not be sent to CDP.+ *+ * @param {string} ip+ * @returns {boolean}+ */+export function isPublicIp(ip) {+ if (!ip || typeof ip !== 'string') return false;+ // A v4-mapped v6 address (::ffff:203.0.113.7) is judged on its v4 half.+ const addr = ip.startsWith('::ffff:') ? ip.slice(7) : ip;+ if (addr.includes(':')) {+ const v6 = addr.toLowerCase();+ if (v6 === '::' || v6 === '::1') return false;+ // fc00::/7 (unique-local) and fe80::/10 (link-local)+ return !/^(f[cd]|fe[89ab])/.test(v6);+ }+ if (!/^\d{1,3}(\.\d{1,3}){3}$/.test(addr)) return false;+ return !PRIVATE_V4.some((re) => re.test(addr));+}++/**+ * The caller's IP in the form CDP accepts. Falls back to the documentation+ * address when the real one is unroutable (local dev, container-internal call),+ * which is what Coinbase's integration guide prescribes.+ *+ * @param {{ headers?: Record<string, unknown>, socket?: { remoteAddress?: string } }} req+ * @returns {string}+ */+export function onrampClientIp(req) {+ const ip = clientIp(req);+ return isPublicIp(ip) ? ip : DOCUMENTATION_IP;+}++/**+ * Are CDP credentials configured for this deployment?+ * @returns {boolean}+ */+export function onrampConfigured() {+ return Boolean(env.CDP_API_KEY_ID && env.CDP_API_KEY_SECRET);+}++export class CoinbaseOnrampError extends Error {+ /**+ * @param {string} code+ * @param {string} message+ * @param {number} [status]+ */+ constructor(code, message, status = 502) {+ super(message);+ this.name = 'CoinbaseOnrampError';+ this.code = code;+ this.status = status;+ }+}++/**+ * Mint a single-use Coinbase Onramp session token bound to a destination wallet.+ *+ * @param {object} opts+ * @param {string} opts.address destination wallet address+ * @param {string[]} opts.blockchains chains that address is valid on (e.g. ['solana'])+ * @param {string[]} [opts.assets] asset tickers to offer (e.g. ['USDC'])+ * @param {string} opts.clientIp the buyer's public IP, from onrampClientIp()+ * @returns {Promise<string>} the session token+ * @throws {CoinbaseOnrampError} when credentials are absent or CDP rejects the call+ */+export async function createOnrampSessionToken({ address, blockchains, assets, clientIp: ip }) {+ if (!onrampConfigured()) {+ throw new CoinbaseOnrampError(+ 'onramp_not_configured',+ 'Coinbase Onramp requires CDP_API_KEY_ID + CDP_API_KEY_SECRET',+ 503,+ );+ }++ // EC keys are commonly stored with escaped newlines in an env var; the signer+ // needs the real PEM. Ed25519 secrets are plain base64 and pass through.+ const apiKeySecret = String(env.CDP_API_KEY_SECRET).replace(/\\n/g, '\n');++ let jwt;+ try {+ jwt = await generateJwt({+ apiKeyId: String(env.CDP_API_KEY_ID),+ apiKeySecret,+ requestMethod: 'POST',+ requestHost: CDP_HOST,+ requestPath: TOKEN_PATH,+ expiresIn: 120,+ });+ } catch (err) {+ throw new CoinbaseOnrampError(+ 'onramp_auth_failed',+ `could not sign the CDP request: ${err?.message || err}`,+ 500,+ );+ }++ let response;+ try {+ response = await fetch(TOKEN_URL, {+ method: 'POST',+ headers: {+ 'content-type': 'application/json',+ accept: 'application/json',+ authorization: `Bearer ${jwt}`,+ },+ body: JSON.stringify({+ addresses: [{ address, blockchains }],+ ...(assets?.length ? { assets } : {}),+ clientIp: ip,+ }),+ signal: AbortSignal.timeout(TOKEN_TIMEOUT_MS),+ });+ } catch (err) {+ throw new CoinbaseOnrampError(+ 'onramp_unreachable',+ `CDP session token request failed: ${err?.message || err}`,+ );+ }++ const body = await response.text();+ if (!response.ok) {+ throw new CoinbaseOnrampError(+ 'onramp_rejected',+ `CDP session token request returned ${response.status}: ${body.slice(0, 300)}`,+ response.status === 401 || response.status === 403 ? 500 : 502,+ );+ }++ let parsed;+ try {+ parsed = JSON.parse(body);+ } catch {+ throw new CoinbaseOnrampError('onramp_bad_response', 'CDP session token response was not JSON');+ }+ const token = parsed?.token || parsed?.data?.token;+ if (typeof token !== 'string' || !token) {+ throw new CoinbaseOnrampError('onramp_bad_response', 'CDP session token response carried no token');+ }+ return token;+}diff --git a/api/onramp/link.js b/api/onramp/link.jsindex f7f5876d3..5b599f7ab 100644--- a/api/onramp/link.js+++ b/api/onramp/link.js@@ -1,30 +1,35 @@// GET /api/onramp/link?address=SOLANA_ADDR&amount=25&asset=USDC//// Returns a URL the client should open (in a popup) to let the user buy the-// requested asset without leaving the app. Tries Coinbase Pay (hosted-// checkout) first, then falls back to that asset's Coinbase buy page.+// requested asset without leaving the app. Tries Coinbase's hosted onramp+// (destination wallet pre-filled) first, then falls back to that asset's+// Coinbase buy page.//// `asset` is USDC (default) or SOL. Both settle on Solana. SOL exists because// some wallets on this platform pay in native lamports (the agent-economy demo// wallet, for one), and sending them USDC would never make them spendable.//// Requires:-// COINBASE_PAY_APP_ID (optional) — Coinbase Pay SDK App ID from-// https://pay.coinbase.com → Projects. When set, the-// returned URL is a pre-populated Coinbase Pay checkout-// targeting the user's Solana wallet. When absent, the-// URL falls back to Coinbase's general USDC buy page.+// CDP_API_KEY_ID + CDP_API_KEY_SECRET (optional) — the Coinbase Developer+// Platform key pair, already used by the x402+// facilitator. When set, each call mints a single-use+// Onramp session token bound to the user's Solana+// wallet and returns a pre-populated Coinbase checkout.+// When absent (or when Coinbase rejects the call), the+// URL falls back to that asset's Coinbase buy page and+// the user sends to the address the overlay shows them.//// The address param is NOT a secret (it's a Solana public key) and is only// used as the deposit destination — it is safe to pass in a query string.-import { cors, json, error } from '../_lib/http.js';--const COINBASE_PAY_APP_ID = process.env.COINBASE_PAY_APP_ID;+import { cors, json, error, rateLimited, reportServerError, wrap } from '../_lib/http.js';+import { isValidSolanaAddress } from '../_lib/validate.js';+import { limits, clientIp } from '../_lib/rate-limit.js';+import { createOnrampSessionToken, onrampClientIp, onrampConfigured } from '../_lib/coinbase-onramp.js';// Assets buyable through the onramp, all settling on Solana mainnet. Each maps-// to the Coinbase Pay asset ticker and the Coinbase price page used when no-// Coinbase Pay App ID is configured.+// to the Coinbase asset ticker and the Coinbase price page used when no session+// token can be minted.const SOLANA_BLOCKCHAIN = 'solana';const ASSETS = {USDC: { ticker: 'USDC', fallbackUrl: 'https://www.coinbase.com/price/usd-coin' },@@ -32,38 +37,25 @@ const ASSETS = {};const DEFAULT_ASSET = 'USDC';-// Length bounds for a Solana base58 public key-const SOL_ADDR_MIN = 32;-const SOL_ADDR_MAX = 44;-const BASE58_RE = /^[1-9A-HJ-NP-Za-km-z]+$/;--function isValidSolanaAddress(addr) {- if (!addr || typeof addr !== 'string') return false;- if (addr.length < SOL_ADDR_MIN || addr.length > SOL_ADDR_MAX) return false;- return BASE58_RE.test(addr);-}+const MIN_AMOUNT_USD = 10;+const MAX_AMOUNT_USD = 500;+const DEFAULT_AMOUNT_USD = 25;/**- * Build a Coinbase Pay hosted checkout URL.- * Spec: https://docs.cdp.coinbase.com/onramp/docs/api-initializing+ * Build a Coinbase hosted checkout URL around a freshly minted session token.+ * The token carries the destination wallet; everything else is presentation.+ * Spec: https://docs.cdp.coinbase.com/onramp/coinbase-hosted-onramp/generating-onramp-url*- * @param {string} appId Coinbase Pay App ID- * @param {string} destinationAddress Solana wallet address- * @param {number} amount preset fiat amount in USD+ * @param {string} sessionToken single-use token from the CDP token API* @param {string} assetTicker Coinbase asset ticker (USDC or SOL)+ * @param {number} amount preset fiat amount in USD* @returns {string}*/-function buildCoinbasePayUrl(appId, destinationAddress, amount, assetTicker) {- const destinationWallets = JSON.stringify([- {- address: destinationAddress,- blockchains: [SOLANA_BLOCKCHAIN],- assets: [assetTicker],- },- ]);+function buildCoinbaseOnrampUrl(sessionToken, assetTicker, amount) {const params = new URLSearchParams({- appId,- destinationWallets,+ sessionToken,+ defaultNetwork: SOLANA_BLOCKCHAIN,+ defaultAsset: assetTicker,presetFiatAmount: String(amount),fiatCurrency: 'USD',});@@ -72,8 +64,9 @@ function buildCoinbasePayUrl(appId, destinationAddress, amount, assetTicker) {/*** Fallback: the asset's Coinbase price page. The user lands on Coinbase,- * selects their amount, and sends the asset to their own address. Still real;- * not as frictionless as Coinbase Pay but 100% functional without an App ID.+ * selects their amount, and sends the asset to the address the Add funds+ * overlay is already showing them. Still real; not as frictionless as the+ * hosted onramp but 100% functional without CDP credentials.** @param {string} asset normalized asset key (a key of ASSETS)* @returns {string}@@ -82,14 +75,23 @@ function buildCoinbaseFallbackUrl(asset) {return ASSETS[asset].fallbackUrl;}-export default function handler(req, res) {+async function handler(req, res) {if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;if (req.method !== 'GET') return error(res, 405, 'method_not_allowed', 'GET only');+ // Every configured call mints a session token against CDP, so an unauthenticated+ // caller must not be able to drive that upstream at will. Generous enough that+ // a user reopening the overlay and switching assets never trips it.+ const rl = await limits.onrampLinkIp(clientIp(req));+ if (!rl.success) return rateLimited(res, rl);+const url = new URL(req.url, `http://${req.headers.host || 'localhost'}`);const address = url.searchParams.get('address') || '';const amountRaw = url.searchParams.get('amount');- const amount = Math.max(10, Math.min(500, Number(amountRaw) || 25));+ const amount = Math.max(+ MIN_AMOUNT_USD,+ Math.min(MAX_AMOUNT_USD, Number(amountRaw) || DEFAULT_AMOUNT_USD),+ );const assetRaw = (url.searchParams.get('asset') || DEFAULT_ASSET).toUpperCase();const asset = Object.hasOwn(ASSETS, assetRaw) ? assetRaw : DEFAULT_ASSET;@@ -97,15 +99,28 @@ export default function handler(req, res) {return error(res, 400, 'invalid_address', 'address must be a valid Solana public key');}- let onrampUrl;- let mode;+ let onrampUrl = buildCoinbaseFallbackUrl(asset);+ let mode = 'coinbase-fallback';- if (COINBASE_PAY_APP_ID) {- onrampUrl = buildCoinbasePayUrl(COINBASE_PAY_APP_ID, address, amount, ASSETS[asset].ticker);- mode = 'coinbase-pay';- } else {- onrampUrl = buildCoinbaseFallbackUrl(asset);- mode = 'coinbase-fallback';+ if (onrampConfigured()) {+ try {+ const sessionToken = await createOnrampSessionToken({+ address,+ blockchains: [SOLANA_BLOCKCHAIN],+ assets: [ASSETS[asset].ticker],+ clientIp: onrampClientIp(req),+ });+ onrampUrl = buildCoinbaseOnrampUrl(sessionToken, ASSETS[asset].ticker, amount);+ mode = 'coinbase-onramp';+ } catch (err) {+ // Coinbase being down or the key being rotated must not take "Add funds"+ // down with it: log it and hand back the keyless path, which still works.+ reportServerError(err, {+ code: err?.code || 'onramp_session_token',+ status: err?.status || 502,+ context: { asset },+ });+ }}return json(res, 200, {@@ -116,3 +131,5 @@ export default function handler(req, res) {asset,});}++export default wrap(handler);