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
feat(mcp-studio): install tokens give each keyless cloud-agent connector its own generation budget
nirholas0e9635b52aab
diff --git a/api/_lib/http.js b/api/_lib/http.jsindex 7c923eb95..6b0b6a9d7 100644--- a/api/_lib/http.js+++ b/api/_lib/http.js@@ -87,6 +87,9 @@ const SENSITIVE_QUERY_KEYS = new Set(['token', 'devicetoken', 'accesstoken', 'refreshtoken', 'idtoken','authorization', 'auth', 'bearer', 'session', 'sessionid', 'sid','password', 'passwd', 'pwd', 'pin', 'otp',+ // free-studio install token (api/_mcp-studio/install-token.js): a stolen one+ // spends its owner's generation budget+ 'install',// API keys / signing secrets'apikey', 'key', 'accesskey', 'secret', 'clientsecret', 'signature', 'sig',// wallet secretsdiff --git a/api/_lib/rate-limit.js b/api/_lib/rate-limit.jsindex b5e93f96f..a8967d933 100644--- a/api/_lib/rate-limit.js+++ b/api/_lib/rate-limit.js@@ -561,6 +561,17 @@ function fallbackLimiter(name, opts) {}// Preset limiters. Tune once viral traffic shape is known.+// The free 3D Studio's buckets, exported so its denials can name the limit a+// caller hit (api/_mcp-studio/handler.js) from the same numbers that enforce it.+export const STUDIO_LIMITS = Object.freeze({+ genBurst: { limit: 4, window: '1 m' },+ genHourly: { limit: 30, window: '1 h' },+ genPoolHourly: { limit: 300, window: '1 h' },+ genGlobal: { limit: FORGE_PAID_GLOBAL_HOURLY, window: '1 h' },+ transport: { limit: 300, window: '1 m' },+ installMint: { limit: 10, window: '1 h' },+});+export const limits = {// One-click "Surprise me" avatar composition. Each call composes a rigged GLB// (~1s CPU + a few base-body fetches), so the ceiling stops a script from@@ -861,21 +872,27 @@ export const limits = {// denial of a free feature for no spend saved. Spend is still protected in// depth: /api/forge underneath fail-CLOSES its own paid-lane global breaker// (mcp3dGenerateGlobal), so even a misrouted paid call can't drain budget.- studioGenBurst: (ip) =>- getLimiter('studio:gen:burst', { limit: 4, window: '1 m' }).limit(ip),- studioGenHourly: (ip) =>- getLimiter('studio:gen:hourly', { limit: 30, window: '1 h' }).limit(ip),+ studioGenBurst: (ip) => getLimiter('studio:gen:burst', STUDIO_LIMITS.genBurst).limit(ip),+ studioGenHourly: (ip) => getLimiter('studio:gen:hourly', STUDIO_LIMITS.genHourly).limit(ip),// Ceiling on one source IP when the burst/hourly caps above are keyed per// ChatGPT user (openai/subject) instead of per IP. Every ChatGPT user reaches// us from OpenAI's shared egress pool, so a per-IP 30/h would ration the whole// directory as one caller; the subject is client-supplied, so this pool cap is// what stops a forged subject per call from escaping the limits entirely.+ // Install-token callers (api/_mcp-studio/install-token.js) ride this pool too.studioGenPoolHourly: (ip) =>- getLimiter('studio:gen:pool:hourly', { limit: 300, window: '1 h' }).limit(ip),+ getLimiter('studio:gen:pool:hourly', STUDIO_LIMITS.genPoolHourly).limit(ip),// Cheap per-IP cap on studio transport/discovery (initialize, tools/list,// ping, resources). Bounds discovery floods without touching the generation// budget. Non-critical: a missing-Redis misconfig degrades gracefully.- studioIp: (ip) => getLimiter('studio:ip', { limit: 300, window: '1 m' }).limit(ip),+ studioIp: (ip) => getLimiter('studio:ip', STUDIO_LIMITS.transport).limit(ip),+ // Minting a free-studio install token (POST /api/mcp-studio/install). Each+ // token is one more caller-sized generation budget, so minting is what bounds+ // how many budgets one source can hold. Ten an hour covers a person setting up+ // several agents; the page caches its token so a revisit never mints again.+ // Non-critical like the caps it feeds: the per-IP pool and the global breaker+ // still bound what any number of tokens can generate.+ studioInstallMint: (ip) => getLimiter('studio:install:mint', STUDIO_LIMITS.installMint).limit(ip),// Free-studio persona writes (create_agent_persona / persona_say): each fetches// or restores a bounded GLB and writes a small identity record — cheap, but not// free, so a per-IP burst cap stops a scripted flood from filling storage. The@@ -1003,10 +1020,7 @@ export const limits = {// breaker only backstops. (studioIp / studioGenBurst / studioGenHourly are// defined above next to the other mcp buckets.)studioGenerateGlobal: () =>- getLimiter('studio:generate:global', {- limit: FORGE_PAID_GLOBAL_HOURLY,- window: '1 h',- }).limit('global'),+ getLimiter('studio:generate:global', STUDIO_LIMITS.genGlobal).limit('global'),// Forge prompt enhancer — one free-tier LLM rewrite per call. Cheap text// completion, but each one hits an upstream provider, so cap per principal to// keep that egress bounded. Non-critical: a Redis outage must never block adiff --git a/api/_mcp-studio/handler.js b/api/_mcp-studio/handler.jsindex ad94f8c24..9e1bec162 100644--- a/api/_mcp-studio/handler.js+++ b/api/_mcp-studio/handler.js@@ -14,17 +14,22 @@//// There is no OAuth and no payment path anywhere in this server: generation runs// operator-funded over /api/forge, whose server-side keys cover provider cost.-// Abuse protection is real: a per-IP transport cap plus a per-IP generation burst-// and hourly quota (../_lib/rate-limit.js), enforced whenever Redis is healthy.+// Abuse protection is real: a per-caller transport cap plus a per-caller+// generation burst and hourly quota (../_lib/rate-limit.js), enforced whenever+// Redis is healthy. The caller is, in order: a verified install token on the+// connector URL (./install-token.js), the per-user subject a shared-egress+// surface carries, else the IP. A capped generation answers a JSON-RPC error+// that names the limit, when it resets and the connector URL that lifts it.// Because every studio tool routes through a zero-cost free lane, these// generation caps fail OPEN on a Redis outage, so a Redis blip never dead-ends a// free feature; real paid spend stays fail-closed one layer down in /api/forge.import { randomUUID } from 'node:crypto';-import { cors, wrap, readJson, rateLimited } from '../_lib/http.js';-import { limits, clientIp } from '../_lib/rate-limit.js';+import { cors, wrap, readJson, rateLimited, setRateLimitHeaders } from '../_lib/http.js';+import { limits, clientIp, STUDIO_LIMITS } from '../_lib/rate-limit.js';import { dispatch, PROTOCOL_VERSION } from './dispatch.js';import { TOOL_NAMES } from './tools.js';+import { installTokenFrom, studioOrigin, INSTALL_PARAM } from './install-token.js';// check_job collects a job that is already running rather than starting one: it// must never burn the caller's generation quota, or collecting a pending job@@ -91,6 +96,125 @@ export function callerSubject(surface, body, req) {return null;}+/**+ * Who the per-caller caps charge, on every surface: a verified install token+ * first, then the surface's own subject, then the IP. An unknown or forged token+ * is ignored, so the request keys exactly as it would with no token at all.+ * @returns {{ key: string, kind: 'install'|'session'|'chatgpt_user'|'ip' }}+ */+export function studioCaller(surface, body, req, ip, install = installTokenFrom(req)) {+ if (install) return { key: `inst:${install.id}`, kind: 'install' };+ const subject = callerSubject(surface, body, req);+ if (subject) return { key: subject, kind: surface === 'chatgpt' ? 'chatgpt_user' : 'session' };+ return { key: ip, kind: 'ip' };+}++// JSON-RPC implementation-defined server error, the code the authenticated MCP+// server uses for rate_limited too (api/_mcp/tools/agents.js).+export const STUDIO_RATE_LIMITED = -32000;++const CALLER_SCOPE = {+ install: 'this install token',+ session: 'this MCP session',+ chatgpt_user: 'this ChatGPT user',+ ip: 'your IP address',+};++const WINDOW_WORDS = { '1 m': 'minute', '1 h': 'hour' };++// Each generation bucket a denial can name: the numbers come from the limiter's+// own table, so the message can never drift from what is enforced.+const GEN_BUCKETS = {+ pool: { id: 'generation_ip_pool', spec: STUDIO_LIMITS.genPoolHourly, scope: () => 'one source IP, across every caller on it' },+ burst: { id: 'generation_burst', spec: STUDIO_LIMITS.genBurst, scope: (kind) => CALLER_SCOPE[kind] },+ hourly: { id: 'generation_hourly', spec: STUDIO_LIMITS.genHourly, scope: (kind) => CALLER_SCOPE[kind] },+ global: { id: 'generation_global', spec: STUDIO_LIMITS.genGlobal, scope: () => 'the whole free studio, every caller combined' },+};++function resetAt(result) {+ const reset = Number(result?.reset);+ return Number.isFinite(reset) && reset > Date.now() ? new Date(reset) : new Date(Date.now() + 1000);+}++/**+ * The remedy for a capped caller. A per-IP caller is told to get an install+ * token (one URL of its own); a caller that already has its own budget, or hit a+ * cap no token lifts, is pointed at the signed-in server, whose free lane is+ * metered per account.+ */+export function studioRemedy(kind, bucket, surfacePath) {+ const origin = studioOrigin();+ const installEndpoint = `${origin}/api/mcp-studio/install`;+ const accountServer = `${origin}/api/mcp-3d`;+ if (bucket !== 'global' && bucket !== 'pool' && kind !== 'install') {+ return {+ kind: 'install_token',+ install_endpoint: installEndpoint,+ connector_url: `${origin}${surfacePath}?${INSTALL_PARAM}=<token>`,+ text:+ `Lift it with a free install token: POST ${installEndpoint} (no account, no key) and reconnect at ` ++ `${origin}${surfacePath}?${INSTALL_PARAM}=<token>, which gets its own budget. Or sign in at ${accountServer} ` ++ '(OAuth 2.1), metered per account.',+ };+ }+ return {+ kind: 'account',+ oauth_server: accountServer,+ text: `Wait for the reset, or sign in at ${accountServer} (OAuth 2.1), whose generation is metered per account instead.`,+ };+}++/**+ * The JSON-RPC error for a capped generation: what limit, when it resets, and+ * the connector URL that lifts it. Exported for tests and docs.+ */+export function studioDenial({ bucket, kind, result, surfacePath, now = Date.now() }) {+ const b = GEN_BUCKETS[bucket];+ const at = resetAt(result);+ const retryAfter = Math.max(1, Math.ceil((at.getTime() - now) / 1000));+ const remedy = studioRemedy(kind, bucket, surfacePath);+ const per = WINDOW_WORDS[b.spec.window] || b.spec.window;+ const message =+ `Rate limited: the free 3D studio allows ${b.spec.limit} generations per ${per} for ${b.scope(kind)}, ` ++ `and that limit is used up. It resets at ${at.toISOString()} (in ${retryAfter} s). ${remedy.text}`;+ return {+ code: STUDIO_RATE_LIMITED,+ message,+ data: {+ reason: 'rate_limited',+ limit: b.id,+ max: b.spec.limit,+ window: b.spec.window,+ keyed_on: bucket === 'global' ? 'platform' : bucket === 'pool' ? 'ip' : kind,+ reset_at: at.toISOString(),+ retry_after: retryAfter,+ ...(result?.reason ? { limiter: result.reason } : {}),+ remedy: remedyData(remedy),+ },+ };+}++// The machine-readable half of a remedy; its text already rides the message.+function remedyData({ text: _text, ...rest }) {+ return rest;+}++// Every request in the body that expects a response gets the same denial, so a+// client matching responses by id sees its own call refused, never a stray id.+function rpcDenial(res, body, denial, result) {+ setRateLimitHeaders(res, result);+ res.setHeader('retry-after', String(denial.data.retry_after));+ res.statusCode = 200;+ res.setHeader('content-type', 'application/json; charset=utf-8');+ res.setHeader('mcp-protocol-version', PROTOCOL_VERSION);+ const one = (m) => ({ jsonrpc: '2.0', id: m?.id ?? null, error: denial });+ if (Array.isArray(body)) {+ res.end(JSON.stringify(body.filter((m) => m && m.id !== undefined).map(one)));+ return;+ }+ res.end(JSON.stringify(one(body)));+}+export function studioHandler({ surface = 'full' } = {}) {return wrap(async (req, res) => {if (cors(req, res, { methods: 'GET,HEAD,POST,OPTIONS', origins: '*', payments: false })) return;@@ -106,10 +230,23 @@ export function studioHandler({ surface = 'full' } = {}) {if (req.method !== 'POST') return rpcError(res, 405, -32600, 'method not supported');const ip = clientIp(req);+ const install = installTokenFrom(req);+ const surfacePath = new URL(req.url || '/api/mcp-studio', 'http://localhost').pathname;- // Cheap transport cap on every request (discovery + calls).- const ipRl = await limits.studioIp(ip);- if (!ipRl.success) return rateLimited(res, ipRl, 'too many requests');+ // Cheap transport cap on every request (discovery + calls), per install+ // token when the connector URL carries one, so callers sharing a cloud+ // agent's egress do not share one flood guard either.+ const ipRl = await limits.studioIp(install ? `inst:${install.id}` : ip);+ if (!ipRl.success) {+ const at = resetAt(ipRl);+ const remedy = studioRemedy(install ? 'install' : 'ip', 'transport', surfacePath);+ return rateLimited(+ res,+ ipRl,+ `too many requests: ${STUDIO_LIMITS.transport.limit} per minute for ${install ? 'this install token' : 'your IP address'}, resets at ${at.toISOString()}. ${remedy.text}`,+ { reset_at: at.toISOString(), remedy: remedyData(remedy) },+ );+ }let body;try {@@ -121,24 +258,29 @@ export function studioHandler({ surface = 'full' } = {}) {const batch = Array.isArray(body) ? body : [body];if (batch.length > 16) return rpcError(res, 400, -32600, 'batch too large (max 16)');- // Generation quota, burst then hourly, per IP. Applied only when the request- // actually calls a generation tool, so discovery is never throttled by it.+ // Generation quota, burst then hourly, per caller. Applied only when the+ // request actually calls a generation tool, so discovery is never throttled+ // by it. A denial is a JSON-RPC error on HTTP 200: an MCP client hands that+ // message to the model, where a 429 body is often dropped by the transport.if (callsGenerationTool(body)) {- const subject = callerSubject(surface, body, req);- if (subject) {+ const caller = studioCaller(surface, body, req, ip, install);+ const deny = (bucket, result) =>+ rpcDenial(res, body, studioDenial({ bucket, kind: caller.kind, result, surfacePath }), result);+ // Any caller key other than the IP is one the client chose, so one source+ // IP is still held to a pool across all of them.+ if (caller.kind !== 'ip') {const pool = await limits.studioGenPoolHourly(ip);- if (!pool.success) return rateLimited(res, pool, 'the free 3D studio is at capacity right now, please try again later');+ if (!pool.success) return deny('pool', pool);}- const caller = subject || ip;- const burst = await limits.studioGenBurst(caller);- if (!burst.success) return rateLimited(res, burst, 'generation rate limit, slow down and try again shortly');- const hourly = await limits.studioGenHourly(caller);- if (!hourly.success) return rateLimited(res, hourly, 'hourly generation limit reached, try again later');+ const burst = await limits.studioGenBurst(caller.key);+ if (!burst.success) return deny('burst', burst);+ const hourly = await limits.studioGenHourly(caller.key);+ if (!hourly.success) return deny('hourly', hourly);// Platform-wide circuit breaker across ALL free-studio callers, backstops// the shared GPU/provider budget when many distinct IPs, each under their- // own hourly cap, would collectively drain it. Fails closed in prod.+ // own hourly cap, would collectively drain it.const global = await limits.studioGenerateGlobal();- if (!global.success) return rateLimited(res, global, 'the free 3D studio is at capacity right now, please try again later');+ if (!global.success) return deny('global', global);}// Anonymous principal, no auth, no scope. rateKey carries the IP for usage logs.diff --git a/api/_mcp-studio/install-token.js b/api/_mcp-studio/install-token.jsnew file mode 100644index 000000000..a2827e13e--- /dev/null+++ b/api/_mcp-studio/install-token.js@@ -0,0 +1,108 @@+// Install tokens: a free, anonymous identity for keyless studio callers.+//+// A cloud agent (Grok Bot, the xAI Responses API, any hosted MCP client) reaches+// the free studio from its vendor's shared egress, so keying the per-caller+// generation caps on its IP rations every user of that agent as one caller. An+// install token gives one installation its own budget without an account:+// POST /api/mcp-studio/install mints one, and the connector URL carries it as+// `?install=<token>` on any studio surface (./handler.js reads it).+//+// The token is self-authenticating, so nothing is stored and no request pays a+// database round trip: `tws_<created>_<nonce><sig>`, where created is the mint+// time in base-36 seconds, nonce is 16 random bytes and sig is a truncated+// HMAC-SHA256 over both under a key derived from MCP_INSTALL_SECRET (falling+// back to JWT_SECRET, domain-separated so the two can never be confused). A+// caller cannot forge one, and minting is rate-limited per IP (limits.+// studioInstallMint), so a token buys exactly one more caller-sized budget per+// mint and every token still shares the per-IP pool cap and the global breaker.+// A token is a rate-limit key and nothing else: it unlocks no tool, no account+// and no spend, so there is nothing to revoke.++import { createHmac, randomBytes, timingSafeEqual } from 'node:crypto';+import { env } from '../_lib/env.js';++const PREFIX = 'tws_';+const KEY_LABEL = 'three.ws mcp-studio install token v1';+// 16 random bytes and a 16-byte MAC, both hex.+const TOKEN_RE = /^tws_([0-9a-z]{1,10})_([0-9a-f]{32})([0-9a-f]{32})$/;+// A token minted on a host whose clock runs ahead is still honored.+const FUTURE_SKEW_S = 300;++/** The query parameter a connector URL carries the token in. */+export const INSTALL_PARAM = 'install';++function signingKey() {+ const root = process.env.MCP_INSTALL_SECRET || process.env.JWT_SECRET;+ if (!root) return null;+ return createHmac('sha256', root).update(KEY_LABEL).digest();+}++/** True when this deployment can mint and verify install tokens. */+export function installTokensConfigured() {+ return signingKey() !== null;+}++function mac(key, created, nonce) {+ return createHmac('sha256', key).update(`${created}.${nonce}`).digest('hex').slice(0, 32);+}++/**+ * Mint a new install token.+ * @returns {{ token: string, id: string, createdAt: Date } | null} null when no signing secret is configured.+ */+export function mintInstallToken({ now = Date.now() } = {}) {+ const key = signingKey();+ if (!key) return null;+ const created = Math.floor(now / 1000).toString(36);+ const nonce = randomBytes(16).toString('hex');+ return {+ token: `${PREFIX}${created}_${nonce}${mac(key, created, nonce)}`,+ id: nonce,+ createdAt: new Date(parseInt(created, 36) * 1000),+ };+}++/**+ * Verify a token. Returns its stable id (the nonce, used as the rate-limit key)+ * and mint time, or null for anything this deployment did not mint.+ * @param {unknown} token+ * @returns {{ id: string, createdAt: Date } | null}+ */+export function verifyInstallToken(token, { now = Date.now() } = {}) {+ if (typeof token !== 'string') return null;+ const m = TOKEN_RE.exec(token);+ if (!m) return null;+ const key = signingKey();+ if (!key) return null;+ const [, created, nonce, sig] = m;+ const expected = Buffer.from(mac(key, created, nonce), 'hex');+ if (!timingSafeEqual(expected, Buffer.from(sig, 'hex'))) return null;+ const createdS = parseInt(created, 36);+ if (!Number.isFinite(createdS) || createdS > now / 1000 + FUTURE_SKEW_S) return null;+ return { id: nonce, createdAt: new Date(createdS * 1000) };+}++/** The raw `install` query value on a request, or null. */+export function installParam(req) {+ const fromQuery = req?.query?.[INSTALL_PARAM];+ if (typeof fromQuery === 'string') return fromQuery;+ const url = typeof req?.url === 'string' ? req.url : '';+ const q = url.indexOf('?');+ if (q < 0) return null;+ return new URLSearchParams(url.slice(q + 1)).get(INSTALL_PARAM);+}++/** The verified install token on a request, or null (missing, malformed, forged). */+export function installTokenFrom(req) {+ return verifyInstallToken(installParam(req));+}++/** The site origin connector URLs are built on (PUBLIC_APP_ORIGIN, else https://three.ws). */+export function studioOrigin() {+ return env.APP_ORIGIN;+}++/** The connector URL for one studio surface path, with the token attached. */+export function connectorUrl(token, path = '/api/mcp-studio') {+ return `${studioOrigin()}${path}?${INSTALL_PARAM}=${encodeURIComponent(token)}`;+}diff --git a/api/mcp-studio/install.js b/api/mcp-studio/install.jsnew file mode 100644index 000000000..5dd2821fb--- /dev/null+++ b/api/mcp-studio/install.js@@ -0,0 +1,62 @@+// Mint a free-studio install token.+//+// POST /api/mcp-studio/install 201 { token, connector_urls, ... }+//+// An install token gives one keyless MCP installation (a Grok Bot connector, a+// hosted agent, any client behind a shared egress) its own generation budget on+// the free 3D studio without an account. The connector URL carries it as+// `?install=<token>`; see ../_mcp-studio/install-token.js for the format and+// ../_mcp-studio/handler.js for how the caps key on it. Minting is free and+// anonymous, and rate-limited per IP, because each token is one more budget.++import { cors, wrap, json, error, method, rateLimited } from '../_lib/http.js';+import { limits, clientIp, STUDIO_LIMITS } from '../_lib/rate-limit.js';+import { mintInstallToken, connectorUrl } from '../_mcp-studio/install-token.js';++// Every studio surface honors the same token.+const SURFACES = {+ studio: '/api/mcp-studio',+ grok: '/api/mcp-grok',+ chatgpt: '/api/mcp-chatgpt',+};++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'POST,OPTIONS', origins: '*', payments: false })) return;+ if (!method(req, res, ['POST'])) return;++ const ip = clientIp(req);+ const rl = await limits.studioInstallMint(ip);+ if (!rl.success) {+ const reset = new Date(Number(rl.reset) || Date.now() + 60_000).toISOString();+ return rateLimited(+ res,+ rl,+ `install token limit reached: ${STUDIO_LIMITS.installMint.limit} new tokens per hour from one IP, resets at ${reset}. ` ++ 'Reuse a token you already have; one token works on every studio connector URL.',+ { reset_at: reset },+ );+ }++ const minted = mintInstallToken();+ if (!minted) {+ return error(res, 503, 'not_configured', 'install tokens are not configured on this deployment');+ }++ return json(+ res,+ 201,+ {+ token: minted.token,+ created_at: minted.createdAt.toISOString(),+ connector_url: connectorUrl(minted.token, SURFACES.studio),+ connector_urls: Object.fromEntries(Object.entries(SURFACES).map(([k, p]) => [k, connectorUrl(minted.token, p)])),+ limits: {+ generations_per_minute: STUDIO_LIMITS.genBurst.limit,+ generations_per_hour: STUDIO_LIMITS.genHourly.limit,+ requests_per_minute: STUDIO_LIMITS.transport.limit,+ },+ note: 'Keep this URL private: anyone holding the token spends its budget. It never expires and unlocks no account or payment.',+ },+ { 'cache-control': 'no-store' },+ );+});diff --git a/tests/mcp-studio-install-token.test.js b/tests/mcp-studio-install-token.test.jsnew file mode 100644index 000000000..50b7bb70a--- /dev/null+++ b/tests/mcp-studio-install-token.test.js@@ -0,0 +1,242 @@+// Install tokens for the free 3D studio (POST /api/mcp-studio/install, then+// `?install=<token>` on any studio connector URL). Cloud agents reach the studio+// from one shared egress, so per-IP caps would ration every user of an agent as+// one caller. These tests run the real handlers over the real in-memory limiter+// (no Redis in the test env) and pin the order's three cases: two tokens from+// one IP get independent budgets, no token keys exactly as before, and minting a+// token is itself rate-limited. Only the GPU call (generate) is stubbed.++import { describe, it, expect, vi, beforeAll, afterEach } from 'vitest';++vi.mock('../api/_mcp-studio/gpt-forge-client.js', async (importOriginal) => {+ const real = await importOriginal();+ return { ...real, generate: vi.fn(), rig: vi.fn(), directPrompt: vi.fn(async () => null) };+});++const SECRET = 'install-token-test-secret-0123456789abcdef';+let generate, studioHandlerFull, installHandler, tokens, handler;++beforeAll(async () => {+ process.env.MCP_INSTALL_SECRET = SECRET;+ ({ generate } = await import('../api/_mcp-studio/gpt-forge-client.js'));+ studioHandlerFull = (await import('../api/mcp-studio.js')).default;+ installHandler = (await import('../api/mcp-studio/install.js')).default;+ tokens = await import('../api/_mcp-studio/install-token.js');+ handler = await import('../api/_mcp-studio/handler.js');+});++afterEach(() => {+ vi.mocked(generate).mockReset();+});++// A minimal node-style req/res pair for driving a real HTTP handler.+function httpPair({ url, body, ip, method = 'POST', headers = {} }) {+ const payload = Buffer.from(body === undefined ? '' : JSON.stringify(body));+ const req = {+ method,+ url,+ headers: { host: 'three.ws', 'content-type': 'application/json', 'x-forwarded-for': ip, ...headers },+ socket: { remoteAddress: ip },+ async *[Symbol.asyncIterator]() {+ yield payload;+ },+ on(event, cb) {+ if (event === 'data') cb(payload);+ if (event === 'end') cb();+ return this;+ },+ };+ const out = { status: 200, headers: {}, body: '' };+ const res = {+ statusCode: 200,+ headersSent: false,+ setHeader(k, v) {+ out.headers[k.toLowerCase()] = v;+ },+ getHeader(k) {+ return out.headers[k.toLowerCase()];+ },+ removeHeader(k) {+ delete out.headers[k.toLowerCase()];+ },+ end(chunk) {+ if (chunk) out.body += chunk;+ out.status = this.statusCode;+ this.headersSent = true;+ },+ write(chunk) {+ out.body += chunk;+ },+ };+ return { req, res, out };+}++async function mint(ip) {+ const { req, res, out } = httpPair({ url: '/api/mcp-studio/install', ip });+ await installHandler(req, res);+ return { status: out.status, headers: out.headers, json: JSON.parse(out.body) };+}++let rpcId = 0;+async function forge(ip, token) {+ vi.mocked(generate).mockResolvedValue({ status: 'done', glb_url: 'https://three.ws/cdn/forge/fixture.glb' });+ const url = token ? `/api/mcp-studio?install=${encodeURIComponent(token)}` : '/api/mcp-studio';+ const body = { jsonrpc: '2.0', id: ++rpcId, method: 'tools/call', params: { name: 'forge_free', arguments: { prompt: 'a brass lantern' } } };+ const { req, res, out } = httpPair({ url, body, ip });+ await studioHandlerFull(req, res);+ return { status: out.status, headers: out.headers, json: JSON.parse(out.body) };+}++// The burst cap (4 a minute) is the first one a fast caller meets.+async function exhaust(ip, token) {+ for (let i = 0; i < 4; i++) {+ const r = await forge(ip, token);+ expect(r.json.error, `call ${i + 1} should pass`).toBeUndefined();+ }+ return forge(ip, token);+}++describe('install token format', () => {+ it('mints a token that verifies, and rejects a forged or altered one', () => {+ const { token, id } = tokens.mintInstallToken();+ expect(token).toMatch(/^tws_[0-9a-z]+_[0-9a-f]{64}$/);+ expect(tokens.verifyInstallToken(token)?.id).toBe(id);+ const flipped = token.slice(0, -1) + (token.endsWith('0') ? '1' : '0');+ expect(tokens.verifyInstallToken(flipped)).toBeNull();+ expect(tokens.verifyInstallToken(`tws_zzz_${'a'.repeat(64)}`)).toBeNull();+ expect(tokens.verifyInstallToken('grk_0f8e2c1a-5b6d-4e7f-8a9b-0c1d2e3f4a5b')).toBeNull();+ expect(tokens.verifyInstallToken(undefined)).toBeNull();+ });++ it('refuses a token signed under another secret', () => {+ const { token } = tokens.mintInstallToken();+ process.env.MCP_INSTALL_SECRET = 'a-different-deployment-secret';+ try {+ expect(tokens.verifyInstallToken(token)).toBeNull();+ } finally {+ process.env.MCP_INSTALL_SECRET = SECRET;+ }+ });++ it('reads the token from the connector URL query', () => {+ const { token, id } = tokens.mintInstallToken();+ expect(tokens.installTokenFrom({ url: `/api/mcp-grok?install=${token}` })?.id).toBe(id);+ expect(tokens.installTokenFrom({ url: '/api/mcp-grok' })).toBeNull();+ });+});++describe('POST /api/mcp-studio/install', () => {+ it('returns a token and connector URLs for every studio surface', async () => {+ const r = await mint('198.51.100.10');+ expect(r.status).toBe(201);+ expect(r.headers['cache-control']).toBe('no-store');+ expect(tokens.verifyInstallToken(r.json.token)).not.toBeNull();+ expect(r.json.connector_url).toBe(`https://three.ws/api/mcp-studio?install=${r.json.token}`);+ expect(r.json.connector_urls.grok).toBe(`https://three.ws/api/mcp-grok?install=${r.json.token}`);+ expect(r.json.limits.generations_per_hour).toBe(30);+ });++ it('is rate-limited per IP: the eleventh mint in an hour is refused, another IP is not', async () => {+ const ip = '198.51.100.20';+ for (let i = 0; i < 10; i++) expect((await mint(ip)).status).toBe(201);+ const denied = await mint(ip);+ expect(denied.status).toBe(429);+ expect(Number(denied.headers['retry-after'])).toBeGreaterThan(0);+ expect(denied.json.error_description).toContain('10 new tokens per hour');+ expect(denied.json.reset_at).toMatch(/^\d{4}-\d{2}-\d{2}T/);+ expect((await mint('198.51.100.21')).status).toBe(201);+ });++ it('answers 405 to anything but POST', async () => {+ const { req, res, out } = httpPair({ url: '/api/mcp-studio/install', ip: '198.51.100.22', method: 'GET' });+ await installHandler(req, res);+ expect(out.status).toBe(405);+ });+});++describe('generation caps keyed on the install token', () => {+ it('gives two tokens from one IP independent budgets', async () => {+ const ip = '203.0.113.40';+ const a = (await mint(ip)).json.token;+ const b = (await mint(ip)).json.token;++ const capped = await exhaust(ip, a);+ expect(capped.status).toBe(200);+ expect(capped.json.error.code).toBe(handler.STUDIO_RATE_LIMITED);+ expect(capped.json.error.data.limit).toBe('generation_burst');+ expect(capped.json.error.data.keyed_on).toBe('install');++ const other = await forge(ip, b);+ expect(other.json.error).toBeUndefined();+ expect(other.json.result.isError).toBeFalsy();+ });++ it('keys a request with no token on the IP, exactly as before', async () => {+ const ip = '203.0.113.41';+ const capped = await exhaust(ip, null);+ expect(capped.json.error.data.keyed_on).toBe('ip');+ // A forged token is ignored, so it shares the exhausted IP budget.+ const forged = await forge(ip, `tws_abc_${'0'.repeat(64)}`);+ expect(forged.json.error.data.keyed_on).toBe('ip');+ // A different IP with no token is untouched.+ expect((await forge('203.0.113.42', null)).json.error).toBeUndefined();+ // A real token from the exhausted IP gets its own budget.+ const token = (await mint(ip)).json.token;+ expect((await forge(ip, token)).json.error).toBeUndefined();+ });++ it('picks the install token over the surface subject and the IP', () => {+ const { token, id } = tokens.mintInstallToken();+ const sid = 'grk_0f8e2c1a-5b6d-4e7f-8a9b-0c1d2e3f4a5b';+ const req = { url: `/api/mcp-grok?install=${token}`, headers: { 'mcp-session-id': sid } };+ expect(handler.studioCaller('grok', {}, req, '203.0.113.43')).toEqual({ key: `inst:${id}`, kind: 'install' });+ expect(handler.studioCaller('grok', {}, { url: '/api/mcp-grok', headers: { 'mcp-session-id': sid } }, '203.0.113.43')).toEqual({ key: sid, kind: 'session' });+ expect(handler.studioCaller('full', {}, { url: '/api/mcp-studio', headers: {} }, '203.0.113.43')).toEqual({ key: '203.0.113.43', kind: 'ip' });+ });+});++describe('denials name the limit, the reset and the remedy', () => {+ it('tells a per-IP caller how to get an install token', async () => {+ const capped = await exhaust('203.0.113.50', null);+ const { message, data } = capped.json.error;+ expect(message).toContain('4 generations per minute for your IP address');+ expect(message).toMatch(/resets at \d{4}-\d{2}-\d{2}T[\d:.]+Z \(in \d+ s\)/);+ expect(message).toContain('POST https://three.ws/api/mcp-studio/install');+ expect(message).toContain('https://three.ws/api/mcp-studio?install=<token>');+ expect(data.remedy).toEqual({+ kind: 'install_token',+ install_endpoint: 'https://three.ws/api/mcp-studio/install',+ connector_url: 'https://three.ws/api/mcp-studio?install=<token>',+ });+ expect(Date.parse(data.reset_at)).toBeGreaterThan(Date.now());+ expect(Number(capped.headers['retry-after'])).toBe(data.retry_after);+ expect(capped.json.id).toBe(rpcId);+ });++ it('points a caller that already has a token at the account server', async () => {+ const ip = '203.0.113.51';+ const token = (await mint(ip)).json.token;+ const capped = await exhaust(ip, token);+ expect(capped.json.error.message).toContain('for this install token');+ expect(capped.json.error.data.remedy).toEqual({ kind: 'account', oauth_server: 'https://three.ws/api/mcp-3d' });+ });++ it('names the platform-wide breaker with no token remedy', () => {+ const d = handler.studioDenial({ bucket: 'global', kind: 'install', result: { reset: Date.now() + 90_000 }, surfacePath: '/api/mcp-grok' });+ expect(d.message).toContain('the whole free studio');+ expect(d.data.keyed_on).toBe('platform');+ expect(d.data.remedy.kind).toBe('account');+ });++ it('answers a batch with one denial per request id', async () => {+ const ip = '203.0.113.52';+ await exhaust(ip, null);+ vi.mocked(generate).mockResolvedValue({ status: 'done', glb_url: 'https://three.ws/cdn/forge/fixture.glb' });+ const call = (id) => ({ jsonrpc: '2.0', id, method: 'tools/call', params: { name: 'forge_free', arguments: { prompt: 'a kite' } } });+ const { req, res, out } = httpPair({ url: '/api/mcp-studio', body: [call('a'), call('b')], ip });+ await studioHandlerFull(req, res);+ const parsed = JSON.parse(out.body);+ expect(parsed.map((r) => r.id)).toEqual(['a', 'b']);+ expect(parsed.every((r) => r.error?.data?.limit === 'generation_burst')).toBe(true);+ });+});