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: refactor GCP access token retrieval and add vanity address inventory migration

fudjiaddf353c6a83b
diff --git a/api/_lib/llm.js b/api/_lib/llm.js
index 85a622b4f..e7777238d 100644
--- a/api/_lib/llm.js
+++ b/api/_lib/llm.js
@@ -26,6 +26,13 @@ import { env } from './env.js';
import { recordEvent } from './usage.js';
import { costMicroUsd } from './llm-pricing.js';
import { sql } from './db.js';
+import {
+ vertexClaudeEnabled,
+ vertexClaudePrimary,
+ vertexMessagesUrl,
+ vertexRequestHeaders,
+ toVertexBody,
+} from './vertex-claude.js';
const GROQ_MODEL = 'llama-3.3-70b-versatile';
const OPENROUTER_MODEL = 'meta-llama/llama-3.3-70b-instruct';
@@ -114,6 +121,30 @@ function anthropicProvider(key, model) {
};
}
+// Vertex-served Claude, same Anthropic Messages shape as anthropicProvider but
+// billed to GCP credits. Headers carry a GCP OAuth bearer token resolved per
+// request (getHeaders is async — the completion loop awaits it), the model id
+// lives in the URL, and the body gains `anthropic_version`. A token-exchange or
+// upstream failure falls through the chain exactly like any other provider.
+function vertexAnthropicProvider(model) {
+ const m = model || ANTHROPIC_MODEL;
+ return {
+ name: 'vertex-anthropic',
+ model: m,
+ url: vertexMessagesUrl(m, { stream: false }),
+ getHeaders: vertexRequestHeaders,
+ buildBody: (system, user, maxTokens) =>
+ toVertexBody({
+ model: m,
+ max_tokens: maxTokens,
+ system,
+ messages: [{ role: 'user', content: user }],
+ }),
+ extractText: (r) => r.content?.[0]?.text || '',
+ extractUsage: (r) => ({ input: r.usage?.input_tokens ?? 0, output: r.usage?.output_tokens ?? 0 }),
+ };
+}
+
function openaiCompatProvider({ name, key, url, model, extraHeaders = {} }) {
return {
name,
diff --git a/api/_lib/migrations/20260706120000_vanity_premium_inventory.sql b/api/_lib/migrations/20260706120000_vanity_premium_inventory.sql
new file mode 100644
index 000000000..5dcd6ad66
--- /dev/null
+++ b/api/_lib/migrations/20260706120000_vanity_premium_inventory.sql
@@ -0,0 +1,106 @@
+begin;
+
+-- Premium vanity-address inventory — grind-ahead, sell-from-stock
+-- ==============================================================================
+-- The live `vanity_grinder` MCP tool / /api/x402/vanity endpoint grind a fresh
+-- keypair per request, in-process, capped at a 3-char pattern (~$0.05). Long
+-- (4–5+ char) brandable prefixes are unreachable that way. This table is the
+-- durable, sellable back-catalogue: keypairs ground AHEAD OF TIME on cheap batch
+-- CPU (workers/vanity-grinder, GCP spot) and sold from stock instantly.
+--
+-- SECURITY — this table stores REAL Solana private keys. Two hard rules the
+-- schema itself enforces as far as SQL can:
+-- 1. The secret is ONLY ever present as `secret_ciphertext`: AES-256-GCM (or a
+-- GCP-KMS envelope) sealed by workers/vanity-grinder BEFORE the first write.
+-- Plaintext never touches this table — see api/_lib/vanity-vault.js.
+-- 2. Single-use delivery is a state machine on `status`; the ciphertext is
+-- nulled at (or after) reveal per `retention_days`. Once `revealed`, the
+-- row is never served again (enforced server-side by an atomic UPDATE …
+-- WHERE status guard in api/_lib/vanity-inventory-store.js).
+--
+-- Custody honesty: the platform generated these keys, so every delivery and the
+-- listing UI tell the buyer plainly to treat a bought address as a token MINT or
+-- to sweep assets to a self-generated wallet, never as a high-value treasury.
+
+-- ── Grind batches — provenance + throughput for each spot run ─────────────────
+-- One row per batch job (a Cloud Run Job execution / spot instance run). Lets the
+-- inventory trace back to the run that produced it and records the economics
+-- (throughput, vCPU-seconds, credit cost) documented in docs/gcp-credits.md.
+create table if not exists vanity_grind_batches (
+ id uuid primary key default gen_random_uuid(),
+ label text not null,
+ -- Where it ran: 'local' (dev CPU), 'cloud-run-job', 'gce-spot-mig'.
+ runner text not null default 'cloud-run-job',
+ instance_id text, -- GCE/CloudRun execution id, if any
+ vcpus int, -- vCPUs the run used
+ keys_per_sec numeric(14,2), -- measured throughput (whole run)
+ total_attempts numeric(40,0) not null default 0,
+ found_count int not null default 0,
+ usd_cost_estimate numeric(12,4), -- credit $ this run consumed (may be 0 on preempt)
+ preempted boolean not null default false,
+ started_at timestamptz not null default now(),
+ finished_at timestamptz
+);
+
+-- ── Inventory — one row per pre-ground address ────────────────────────────────
+create table if not exists vanity_inventory (
+ id uuid primary key default gen_random_uuid(),
+ -- Public Base58 address. UNIQUE so the same address is never double-listed and
+ -- so an insert from a re-run batch is a safe idempotent no-op (ON CONFLICT).
+ address text not null unique,
+ -- The pattern this address satisfies + how it was matched.
+ prefix text,
+ suffix text,
+ ignore_case boolean not null default false,
+ pattern_label text not null, -- human label, e.g. "PUMP…", "…AGNT"
+ format text not null default 'keypair'
+ check (format in ('keypair', 'mnemonic')),
+
+ -- Difficulty / rarity (from src/solana/vanity/rarity.js at grind time). Drives
+ -- the price curve. `difficulty_attempts` is the naive expected-attempt count.
+ difficulty_attempts numeric(40,0) not null default 0,
+ rarity_bits numeric(10,2) not null default 0,
+ rarity_tier text not null default 'common',
+ rarity_score int not null default 0,
+
+ -- SEALED secret. `secret_scheme` records the envelope so decryption picks the
+ -- right opener: 'aes-256-gcm' (secret-box) or 'gcp-kms+aes-256-gcm' (envelope).
+ -- NULL once destroyed. The 64-byte keypair (or mnemonic) is inside — never here
+ -- in plaintext.
+ secret_ciphertext text,
+ secret_scheme text not null default 'aes-256-gcm',
+
+ -- Delivery state machine. available → reserved → revealed (→ ciphertext
+ -- destroyed). 'sold' is a terminal alias used if a purchase settled but the
+ -- one-shot reveal was never fetched (buyer can still be re-served the SAME
+ -- ciphertext until they reveal, then it's gone). 'destroyed' = ciphertext gone.
+ status text not null default 'available'
+ check (status in ('available', 'reserved', 'sold', 'revealed', 'destroyed')),
+
+ -- Difficulty-scaled list price (USDC, whole-dollar-ish; 6-dp for x402 atomics).
+ price_usd numeric(12,6) not null default 1,
+
+ -- Purchase / delivery bookkeeping.
+ purchaser text, -- buyer identity (wallet / payment payer)
+ payment_id text, -- x402 payment id that bought it (replay key)
+ batch_id uuid references vanity_grind_batches(id) on delete set null,
+ -- Days to keep the ciphertext AFTER reveal. 0 = destroy immediately at reveal
+ -- (the default — delete-after-reveal). >0 keeps it that many days for the buyer
+ -- to re-pull, then a sweep (scripts/vanity-inventory-load.mjs --sweep) nulls it.
+ retention_days int not null default 0 check (retention_days >= 0),
+
+ reserved_at timestamptz,
+ sold_at timestamptz,
+ revealed_at timestamptz,
+ destroyed_at timestamptz,
+ created_at timestamptz not null default now(),
+ updated_at timestamptz not null default now()
+);
+
+-- Fast "browse available, cheapest/rarest first" and pattern filtering.
+create index if not exists vanity_inventory_status_idx on vanity_inventory (status);
+create index if not exists vanity_inventory_available_idx on vanity_inventory (status, rarity_score desc) where status = 'available';
+create index if not exists vanity_inventory_prefix_idx on vanity_inventory (prefix) where prefix is not null;
+create index if not exists vanity_inventory_payment_idx on vanity_inventory (payment_id) where payment_id is not null;
+
+commit;
diff --git a/api/_lib/vertex-claude.js b/api/_lib/vertex-claude.js
new file mode 100644
index 000000000..588df6c95
--- /dev/null
+++ b/api/_lib/vertex-claude.js
@@ -0,0 +1,113 @@
+// Vertex AI Claude transport — routes first-party-shaped Anthropic Messages
+// requests to Google Vertex AI so platform LLM traffic bills the ~$100k GCP
+// credit pool instead of a paid Anthropic key.
+//
+// The Anthropic Messages wire format on Vertex differs from api.anthropic.com in
+// exactly four ways (everything else — request body, SSE event shapes — is
+// identical, so existing parsers work unchanged):
+// 1. The model id goes in the URL path, not the request body.
+// 2. The body gains `"anthropic_version": "vertex-2023-10-16"` and drops `model`.
+// 3. Auth is `Authorization: Bearer <oauth>` — no `x-api-key`, no
+// `anthropic-version` header.
+// 4. Dated first-party model ids convert to Vertex's `@` form
+// (claude-haiku-4-5-20251001 → claude-haiku-4-5@20251001); bare ids pass
+// through (claude-sonnet-4-6).
+//
+// Config (env):
+// GOOGLE_CLOUD_PROJECT — GCP project id (required)
+// GOOGLE_CLOUD_LOCATION_CLAUDE — region or "global" (default: "global")
+// VERTEX_CLAUDE_ENABLED=1 — Vertex becomes an available Anthropic transport
+// VERTEX_CLAUDE_PRIMARY=1 — Vertex Claude leads the provider chain (before
+// the free lanes); requires VERTEX_CLAUDE_ENABLED
+//
+// Both flags off → callers never construct a Vertex request, so behavior is
+// byte-identical to the pre-Vertex chain. Any Vertex error (429/5xx/quota/token
+// exchange) is a normal provider failure the caller's chain falls through.
+
+import { getGcpAccessToken } from './gcp-auth.js';
+
+const DEFAULT_LOCATION = 'global';
+const ANTHROPIC_VERTEX_VERSION = 'vertex-2023-10-16';
+
+function readEnv(name) {
+ if (typeof process !== 'undefined' && process.env?.[name]) return process.env[name];
+ return null;
+}
+
+function flag(name) {
+ const v = readEnv(name);
+ return v === '1' || v === 'true';
+}
+
+// Map a first-party Anthropic model id to its Vertex publisher-model id. A
+// trailing 8-digit date suffix (`-20251001`) becomes the Vertex `@` form
+// (`@20251001`); every other id — bare aliases like `claude-sonnet-4-6`, or ids
+// already in `@` form — passes through untouched. One shared helper so the
+// string surgery lives in exactly one place.
+export function toVertexModelId(modelId) {
+ if (!modelId) return modelId;
+ const m = /^(.*)-(\d{8})$/.exec(modelId);
+ return m ? `${m[1]}@${m[2]}` : modelId;
+}
+
+// True when the GCP project is configured — the minimum to attempt Vertex.
+export function vertexClaudeConfigured() {
+ return Boolean(readEnv('GOOGLE_CLOUD_PROJECT'));
+}
+
+// True when Vertex is an available Anthropic transport (flag on AND configured).
+export function vertexClaudeEnabled() {
+ return flag('VERTEX_CLAUDE_ENABLED') && vertexClaudeConfigured();
+}
+
+// True when Vertex Claude should LEAD the provider chain (inversion flag on, and
+// Vertex is otherwise enabled).
+export function vertexClaudePrimary() {
+ return vertexClaudeEnabled() && flag('VERTEX_CLAUDE_PRIMARY');
+}
+
+function vertexTarget() {
+ const project = readEnv('GOOGLE_CLOUD_PROJECT');
+ const location = readEnv('GOOGLE_CLOUD_LOCATION_CLAUDE') || DEFAULT_LOCATION;
+ // The global endpoint uses the bare host; a regional endpoint prefixes it.
+ const host = location === 'global' ? 'aiplatform.googleapis.com' : `${location}-aiplatform.googleapis.com`;
+ return { project, location, host };
+}
+
+// Build the Vertex Messages endpoint URL for a model. `:streamRawPredict` for
+// streaming SSE, `:rawPredict` for a single JSON response.
+export function vertexMessagesUrl(modelId, { stream = false } = {}) {
+ const { project, location, host } = vertexTarget();
+ const vid = toVertexModelId(modelId);
+ const verb = stream ? 'streamRawPredict' : 'rawPredict';
+ return `https://${host}/v1/projects/${project}/locations/${location}/publishers/anthropic/models/${vid}:${verb}`;
+}
+
+// Convert a first-party Anthropic Messages body to the Vertex body: drop `model`
+// (it lives in the URL), drop the caller's `stream` hint (streaming is chosen by
+// the URL verb, not the body), and add the required `anthropic_version`.
+export function toVertexBody(anthropicBody) {
+ const { model, stream, ...rest } = anthropicBody;
+ return { ...rest, anthropic_version: ANTHROPIC_VERTEX_VERSION };
+}
+
+// Resolve the request headers for a Vertex Messages call — a fresh (cached) GCP
+// OAuth bearer token. May throw when no GCP credentials are configured; callers
+// treat that like any other provider failure and fall through their chain.
+export async function vertexRequestHeaders() {
+ const token = await getGcpAccessToken();
+ return { authorization: `Bearer ${token}`, 'content-type': 'application/json' };
+}
+
+// Issue an Anthropic Messages request against Vertex and return the raw Response
+// (streaming or not), so callers can pass the SSE body through unchanged or read
+// the JSON. `body` is a first-party-shaped Anthropic body including `model`.
+export async function vertexAnthropicMessages(body, { stream = false } = {}) {
+ const url = vertexMessagesUrl(body.model, { stream });
+ const headers = await vertexRequestHeaders();
+ return fetch(url, {
+ method: 'POST',
+ headers,
+ body: JSON.stringify(toVertexBody(body)),
+ });
+}
diff --git a/api/_mcp3d/vertex-imagen.js b/api/_mcp3d/vertex-imagen.js
index 19967be08..cd0a06728 100644
--- a/api/_mcp3d/vertex-imagen.js
+++ b/api/_mcp3d/vertex-imagen.js
@@ -25,6 +25,8 @@
// Output: base64 PNG returned inline in the API response, uploaded to R2/S3
// by the caller (same pattern as the Replicate path in text-to-image.js).
+import { getGcpAccessToken } from '../_lib/gcp-auth.js';
+
const DEFAULT_MODEL = 'imagen-3.0-generate-001';
const DEFAULT_LOCATION = 'us-central1';
@@ -42,179 +44,8 @@ function readEnv(name) {
return null;
}
-// Obtain a Google OAuth 2.0 access token.
-//
-// Two auth paths, in priority order:
-// 1. GCP_SERVICE_ACCOUNT_JSON — service account JSON string (Vercel-friendly)
-// 2. Metadata server — works on Cloud Run / GCE with attached SA
-//
-// Tokens are cached in-process for (expiry - 60s) to avoid hammering the
-// token endpoint on every request.
-const _tokenCache = { token: null, expiresAt: 0 };
-
-async function getAccessToken() {
- const now = Date.now();
- if (_tokenCache.token && now < _tokenCache.expiresAt) {
- return _tokenCache.token;
- }
-
- const saJson = readEnv('GCP_SERVICE_ACCOUNT_JSON');
- if (saJson && saJson.trim() && saJson.trim() !== '""') {
- return _tokenFromServiceAccount(parseServiceAccount(saJson));
- }
-
- // Fall back to the metadata server (Cloud Run / GCE)
- const metaRes = await fetch(
- 'http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/token',
- { headers: { 'Metadata-Flavor': 'Google' } },
- ).catch(() => null);
-
- if (metaRes?.ok) {
- const data = await metaRes.json();
- _tokenCache.token = data.access_token;
- _tokenCache.expiresAt = now + (data.expires_in - 60) * 1000;
- return _tokenCache.token;
- }
-
- throw Object.assign(
- new Error(
- 'No GCP credentials found. Set GCP_SERVICE_ACCOUNT_JSON or run on GCE/Cloud Run.',
- ),
- { code: 'unconfigured' },
- );
-}
-
-// Service-account JSON pasted into a secrets UI routinely arrives mangled:
-// wrapped in an extra layer of quotes, with escaped inner quotes (`{\"type\"…}`),
-// or base64-encoded. Accept every common mangling; reject with a designed
-// `unconfigured` error (instead of a raw JSON.parse crash) so callers can
-// branch to a fallback provider.
-// Escape raw control characters (newline, carriage return, tab) that appear
-// *inside* JSON string literals, leaving structural whitespace and already-
-// escaped sequences untouched. Walks the string tracking in-string state so it
-// never mangles the JSON between tokens. Lets a multi-line key-file paste parse.
-function escapeJsonControlChars(s) {
- let out = '';
- let inString = false;
- let escaped = false;
- for (let i = 0; i < s.length; i++) {
- const ch = s[i];
- if (escaped) {
- out += ch;
- escaped = false;
- continue;
- }
- if (ch === '\\') {
- out += ch;
- escaped = true;
- continue;
- }
- if (ch === '"') {
- inString = !inString;
- out += ch;
- continue;
- }
- if (inString && ch === '\n') out += '\\n';
- else if (inString && ch === '\r') out += '\\r';
- else if (inString && ch === '\t') out += '\\t';
- else out += ch;
- }
- return out;
-}
-
-function parseServiceAccount(raw) {
- let v = raw.trim();
- if ((v.startsWith('"') && v.endsWith('"')) || (v.startsWith("'") && v.endsWith("'"))) {
- v = v.slice(1, -1).trim();
- }
- const candidates = [v, v.replace(/\\"/g, '"')];
- // A multi-line paste of the raw key file leaves literal newlines/tabs/CRs
- // *inside* the private_key string — valid in a file, but `JSON.parse` rejects
- // raw control characters in a string literal ("Bad control character"). Add a
- // candidate that escapes only those control chars so the paste parses cleanly.
- candidates.push(escapeJsonControlChars(v), escapeJsonControlChars(v.replace(/\\"/g, '"')));
- if (/^[A-Za-z0-9+/=\s]+$/.test(v)) {
- try {
- candidates.push(Buffer.from(v, 'base64').toString('utf8'));
- } catch {
- // not base64 — fall through to the error below
- }
- }
- for (const candidate of candidates) {
- try {
- const sa = JSON.parse(candidate);
- if (sa && typeof sa === 'object' && sa.client_email && sa.private_key) return sa;
- } catch {
- // try the next decoding
- }
- }
- throw Object.assign(
- new Error(
- 'GCP_SERVICE_ACCOUNT_JSON is set but is not a valid service-account JSON object (expected client_email + private_key). Re-paste the raw key file contents.',
- ),
- { code: 'unconfigured' },
- );
-}
-
-async function _tokenFromServiceAccount(sa) {
- // Build a JWT for the service account and exchange it for an access token.
- // Uses the Web Crypto API (available in Node 18+ and Vercel edge runtime).
- const now = Math.floor(Date.now() / 1000);
- const header = { alg: 'RS256', typ: 'JWT' };
- const payload = {
- iss: sa.client_email,
- scope: 'https://www.googleapis.com/auth/cloud-platform',
- aud: 'https://oauth2.googleapis.com/token',
- iat: now,
- exp: now + 3600,
- };
-
- const b64url = (obj) =>
- Buffer.from(JSON.stringify(obj)).toString('base64url');
- const signingInput = `${b64url(header)}.${b64url(payload)}`;
-
- // Import the RSA private key
- const keyData = sa.private_key
- .replace(/-----BEGIN PRIVATE KEY-----/, '')
- .replace(/-----END PRIVATE KEY-----/, '')
- .replace(/\s/g, '');
- const keyBuffer = Buffer.from(keyData, 'base64');
-
- const cryptoKey = await crypto.subtle.importKey(
- 'pkcs8',
- keyBuffer,
- { name: 'RSASSA-PKCS1-v1_5', hash: 'SHA-256' },
- false,
- ['sign'],
- );
-
- const sigBuffer = await crypto.subtle.sign(
- 'RSASSA-PKCS1-v1_5',
- cryptoKey,
- Buffer.from(signingInput),
- );
- const sig = Buffer.from(sigBuffer).toString('base64url');
- const jwt = `${signingInput}.${sig}`;
-
- const tokenRes = await fetch('https://oauth2.googleapis.com/token', {
- method: 'POST',
- headers: { 'content-type': 'application/x-www-form-urlencoded' },
- body: new URLSearchParams({
- grant_type: 'urn:ietf:params:oauth:grant-type:jwt-bearer',
- assertion: jwt,
- }),
- });
-
- if (!tokenRes.ok) {
- const err = await tokenRes.text().catch(() => tokenRes.status);
- throw new Error(`GCP token exchange failed: ${err}`);
- }
-
- const data = await tokenRes.json();
- _tokenCache.token = data.access_token;
- _tokenCache.expiresAt = Date.now() + (data.expires_in - 60) * 1000;
- return _tokenCache.token;
-}
+// Token minting (service-account JWT→OAuth exchange, caching, metadata-server
+// fallback) is shared with the Vertex Claude transport — see api/_lib/gcp-auth.js.
// Return true if Vertex AI Imagen is configured (GCP project present).
export function isConfigured() {
@@ -239,7 +70,7 @@ export async function generateImage(prompt, { aspectRatio = '1:1' } = {}) {
const model = readEnv('VERTEX_IMAGEN_MODEL') || DEFAULT_MODEL;
const aspectEnum = ASPECT_MAP[aspectRatio] || '1:1';
- const token = await getAccessToken();
+ const token = await getGcpAccessToken();
const endpoint =
`https://${location}-aiplatform.googleapis.com/v1/projects/${project}` +
@@ -321,7 +152,7 @@ export async function editImage(imageUrl, prompt, { maskUrl = null } = {}) {
const model =
readEnv('VERTEX_IMAGEN_EDIT_MODEL') || 'imagen-3.0-capability-001';
- const token = await getAccessToken();
+ const token = await getGcpAccessToken();
const endpoint =
`https://${location}-aiplatform.googleapis.com/v1/projects/${project}` +