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(oauth): cloud connector sign-in, client revocations and MCP studio installs

nirholas5d7774e5376d
diff --git a/api/_lib/auth.js b/api/_lib/auth.js
index 43da369c1..890152b0d 100644
--- a/api/_lib/auth.js
+++ b/api/_lib/auth.js
@@ -286,6 +286,36 @@ export function extractBearer(req) {
}
// Returns { userId, scope, source: 'oauth'|'apikey', clientId?, apiKeyId? } or null.
+// Access tokens are stateless JWTs, so revoking a connected app also records a
+// cutoff per (user, client). A token issued at or before the cutoff is dead on
+// its next use; a token minted after the person re-authorizes the app is not.
+async function isGrantRevoked(payload) {
+ const rows = await sql`
+ select 1 from oauth_client_revocations
+ where user_id = ${payload.sub} and client_id = ${payload.client_id}
+ and revoked_at >= to_timestamp(${payload.iat})
+ limit 1
+ `;
+ return rows.length > 0;
+}
+
+// Revoke everything one client holds for one user: its refresh tokens and, via
+// the cutoff row, every access token already in flight. Returns how many
+// refresh tokens were revoked.
+export async function revokeClientGrant({ userId, clientId }) {
+ const revoked = await sql`
+ update oauth_refresh_tokens set revoked_at = now()
+ where user_id = ${userId} and client_id = ${clientId} and revoked_at is null
+ returning id
+ `;
+ await sql`
+ insert into oauth_client_revocations (user_id, client_id, revoked_at)
+ values (${userId}, ${clientId}, now())
+ on conflict (user_id, client_id) do update set revoked_at = excluded.revoked_at
+ `;
+ return revoked.length;
+}
+
export async function authenticateBearer(token, { audience } = {}) {
if (!token) return null;
// API keys are prefixed with `sk_live_` (or `sk_test_`) — short-circuit.
@@ -309,6 +339,7 @@ export async function authenticateBearer(token, { audience } = {}) {
// token_use prevents a future token type (e.g. an id/refresh JWT) from
// being replayed against resource endpoints.
if (payload.token_use !== 'access') return null;
+ if (payload.client_id && await isGrantRevoked(payload)) return null;
return {
userId: payload.sub,
scope: payload.scope || '',
diff --git a/api/_lib/mcp-studio-installs.js b/api/_lib/mcp-studio-installs.js
new file mode 100644
index 000000000..117f3cd85
--- /dev/null
+++ b/api/_lib/mcp-studio-installs.js
@@ -0,0 +1,72 @@
+// Install tokens for the keyless 3D Studio MCP servers.
+//
+// A token is a free, anonymous, per-installation identity: `inst_` plus 32 hex
+// characters of CSPRNG output. Only its SHA-256 is stored (table
+// mcp_studio_installs, migration 20261009120000_mcp_studio_installs.sql). The
+// studio handler (api/_mcp-studio/handler.js) resolves ?install=<token> to a
+// per-caller rate-limit key; an unknown or malformed token resolves to null and
+// the caller is treated exactly as if it had sent none.
+
+import { createHash, randomBytes } from 'node:crypto';
+import { sql } from './db.js';
+
+const TOKEN_RE = /^inst_[0-9a-f]{32}$/;
+const POSITIVE_TTL_MS = 5 * 60_000;
+const NEGATIVE_TTL_MS = 30_000;
+const CACHE_MAX = 5000;
+
+/** @type {Map<string, { ok: boolean, until: number }>} */
+const cache = new Map();
+
+export function isInstallTokenShape(token) {
+ return typeof token === 'string' && TOKEN_RE.test(token);
+}
+
+export function hashInstallToken(token) {
+ return createHash('sha256').update(token).digest('hex');
+}
+
+/** The limiter key an install token maps to. Not reversible to the token. */
+export function installCallerKey(token) {
+ return `inst:${hashInstallToken(token).slice(0, 32)}`;
+}
+
+function remember(hash, ok) {
+ if (cache.size >= CACHE_MAX) cache.delete(cache.keys().next().value);
+ cache.set(hash, { ok, until: Date.now() + (ok ? POSITIVE_TTL_MS : NEGATIVE_TTL_MS) });
+}
+
+/** Mint and store a new token. Returns the plaintext token, shown to its owner once. */
+export async function createInstallToken() {
+ const token = `inst_${randomBytes(16).toString('hex')}`;
+ const hash = hashInstallToken(token);
+ await sql`insert into mcp_studio_installs (token_hash) values (${hash})`;
+ remember(hash, true);
+ return token;
+}
+
+/**
+ * The limiter key for a token that exists, or null for anything else (absent,
+ * malformed, unknown, or the database being unreachable: the caller then keeps
+ * today's keying rather than being denied a free feature).
+ */
+export async function resolveInstallToken(token) {
+ if (!isInstallTokenShape(token)) return null;
+ const hash = hashInstallToken(token);
+ const hit = cache.get(hash);
+ if (hit && hit.until > Date.now()) return hit.ok ? installCallerKey(token) : null;
+ try {
+ const rows = await sql`select 1 from mcp_studio_installs where token_hash = ${hash} limit 1`;
+ const ok = rows.length > 0;
+ remember(hash, ok);
+ return ok ? installCallerKey(token) : null;
+ } catch (err) {
+ console.warn('[mcp-studio] install token lookup failed, keying on the default:', err.message);
+ return null;
+ }
+}
+
+/** Test seam: forget every cached lookup. */
+export function clearInstallCache() {
+ cache.clear();
+}
diff --git a/api/_lib/migrations/20261009120000_mcp_studio_installs.sql b/api/_lib/migrations/20261009120000_mcp_studio_installs.sql
new file mode 100644
index 000000000..d4cb82b99
--- /dev/null
+++ b/api/_lib/migrations/20261009120000_mcp_studio_installs.sql
@@ -0,0 +1,18 @@
+-- Migration: free, anonymous install tokens for the keyless 3D Studio MCP servers.
+-- Apply: node scripts/apply-migrations.mjs --apply --file 20261009120000_mcp_studio_installs.sql
+-- Idempotent.
+--
+-- A cloud agent (Grok Bot, the xAI API, any hosted MCP client) reaches the free
+-- studio from a shared egress pool, so a per-IP generation cap rations every user
+-- of that pool as one caller. An install token gives each installation its own
+-- identity without an account: POST /api/mcp-studio/install mints a random
+-- token, the connector URL carries it as ?install=<token>, and the per-caller
+-- caps key on it. Only the SHA-256 of the token is stored, so a database read
+-- never yields a usable connector URL.
+
+create table if not exists mcp_studio_installs (
+ token_hash text primary key,
+ created_at timestamptz not null default now()
+);
+
+create index if not exists mcp_studio_installs_created_idx on mcp_studio_installs (created_at);
diff --git a/api/_lib/migrations/20261009120000_oauth_client_revocations.sql b/api/_lib/migrations/20261009120000_oauth_client_revocations.sql
new file mode 100644
index 000000000..2e310979c
--- /dev/null
+++ b/api/_lib/migrations/20261009120000_oauth_client_revocations.sql
@@ -0,0 +1,14 @@
+-- Immediate revocation for OAuth connected apps.
+--
+-- Access tokens are stateless JWTs that live an hour, so deleting an app's
+-- refresh tokens alone left a revoked cloud connector working until its current
+-- access token expired. One row per (user, client) records the moment the person
+-- revoked it; authenticateBearer rejects any access token issued at or before
+-- that moment. A token minted after the person re-authorizes the app is newer
+-- than the row and works again.
+CREATE TABLE IF NOT EXISTS oauth_client_revocations (
+ user_id uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE,
+ client_id text NOT NULL REFERENCES oauth_clients(client_id) ON DELETE CASCADE,
+ revoked_at timestamptz NOT NULL DEFAULT now(),
+ PRIMARY KEY (user_id, client_id)
+);
diff --git a/api/_lib/rate-limit.js b/api/_lib/rate-limit.js
index b5e93f96f..1b63eaf75 100644
--- a/api/_lib/rate-limit.js
+++ b/api/_lib/rate-limit.js
@@ -872,6 +872,11 @@ export const limits = {
// what stops a forged subject per call from escaping the limits entirely.
studioGenPoolHourly: (ip) =>
getLimiter('studio:gen:pool:hourly', { limit: 300, window: '1 h' }).limit(ip),
+ // Minting a free install token (POST /api/mcp-studio/install): one tiny insert,
+ // but unbounded minting would let one caller escape every per-caller cap, so it
+ // is capped per IP. Tokens still share studioGenPoolHourly per IP.
+ studioInstallCreate: (ip) =>
+ getLimiter('studio:install:create', { limit: 10, window: '1 h' }).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.
@@ -1078,6 +1083,22 @@ export const limits = {
window: '1 h',
critical: true,
}).limit('global'),
+ // CAD Forge (api/cad): a design is up to four LLM completions (write plus
+ // repair rounds) and as many sandboxed kernel builds on workers/cad-forge, so
+ // it is the heaviest anonymous action here and capped like the diorama
+ // composer: per IP plus a global hourly breaker, critical so a Redis outage
+ // fails closed. Rebuilds (slider moves on an existing design) skip the LLM and
+ // cost one build, so they get a looser bucket of their own.
+ cadForgeIp: (ip) =>
+ getLimiter('cad:forge:ip', { limit: 12, window: '10 m', critical: true }).limit(ip),
+ cadForgeGlobal: () =>
+ getLimiter('cad:forge:global', {
+ limit: Math.max(60, Number(process.env.CAD_FORGE_GLOBAL_HOURLY) || 400),
+ window: '1 h',
+ critical: true,
+ }).limit('global'),
+ cadRebuildIp: (ip) =>
+ getLimiter('cad:rebuild:ip', { limit: 90, window: '10 m', critical: true }).limit(ip),
// Portal (api/portal): fetches a caller-supplied website once and builds a
// walkable world from it. The spend is other people's bandwidth rather than
// ours, which is exactly why it is capped: a build is one origin request plus
diff --git a/api/_lib/schema.sql b/api/_lib/schema.sql
index 4f45d3281..394cdeec8 100644
--- a/api/_lib/schema.sql
+++ b/api/_lib/schema.sql
@@ -323,6 +323,15 @@ create table if not exists oauth_refresh_tokens (
create index if not exists oauth_refresh_user on oauth_refresh_tokens(user_id) where revoked_at is null;
create index if not exists oauth_refresh_expiry on oauth_refresh_tokens(expires_at);
+-- Revoking a connected app records a cutoff so its in-flight access tokens die
+-- on the next request (api/_lib/auth.js revokeClientGrant / authenticateBearer).
+create table if not exists oauth_client_revocations (
+ user_id uuid not null references users(id) on delete cascade,
+ client_id text not null references oauth_clients(client_id) on delete cascade,
+ revoked_at timestamptz not null default now(),
+ primary key (user_id, client_id)
+);
+
-- ── Developer API keys (for server-to-server MCP usage) ─────────────────────
create table if not exists api_keys (
id uuid primary key default gen_random_uuid(),
diff --git a/api/_mcp-studio/handler.js b/api/_mcp-studio/handler.js
index ad94f8c24..d6eff9094 100644
--- a/api/_mcp-studio/handler.js
+++ b/api/_mcp-studio/handler.js
@@ -8,6 +8,10 @@
// api/mcp-studio.js surface 'full' every tool, both widgets
// api/mcp-chatgpt.js surface 'chatgpt' generation tools, model viewer only
// api/mcp-grok.js surface 'grok' every tool, for Grok Bot and the xAI API
+// Per-caller caps key on an install token (?install=, minted free at
+// POST /api/mcp-studio/install) when one is present, else on the surface's own
+// subject (ChatGPT subject, Grok session), else the IP. A capped caller gets a
+// JSON-RPC error naming the limit, its reset time and how to lift it.
// Every front door shares one transport cap, one per-IP generation quota and one
// platform-wide circuit breaker, so a second door never doubles the free GPU
// budget.
@@ -21,10 +25,13 @@
// 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 { cors, wrap, readJson, setRateLimitHeaders } from '../_lib/http.js';
import { limits, clientIp } from '../_lib/rate-limit.js';
import { dispatch, PROTOCOL_VERSION } from './dispatch.js';
import { TOOL_NAMES } from './tools.js';
+import { resolveInstallToken } from '../_lib/mcp-studio-installs.js';
+
+const ORIGIN = 'https://three.ws';
// 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
@@ -37,10 +44,72 @@ export function isGenerationTool(name) {
return GEN_TOOLS.has(name);
}
-function rpcError(res, status, code, message, extra = {}) {
+function rpcError(res, status, code, message, extra = {}, id = null) {
res.statusCode = status;
res.setHeader('content-type', 'application/json; charset=utf-8');
- res.end(JSON.stringify({ jsonrpc: '2.0', id: null, error: { code, message, ...(Object.keys(extra).length ? { data: extra } : {}) } }));
+ res.end(JSON.stringify({ jsonrpc: '2.0', id, error: { code, message, ...(Object.keys(extra).length ? { data: extra } : {}) } }));
+}
+
+/** "in 12 minutes (at 14:05 UTC)" for a limiter reset time in epoch ms. */
+export function describeReset(resetMs, now = Date.now()) {
+ const secs = Math.max(1, Math.ceil(((Number(resetMs) || now) - now) / 1000));
+ const span = secs < 90 ? `${secs} seconds` : secs < 5400 ? `${Math.ceil(secs / 60)} minutes` : `${Math.ceil(secs / 3600)} hours`;
+ return `in ${span} (at ${new Date(now + secs * 1000).toISOString().slice(11, 16)} UTC)`;
+}
+
+/** How a capped caller lifts the limit: the install token, or an account. */
+function remedyFor(installed) {
+ if (installed) {
+ return `This installation's budget refills at the reset time. For a larger budget connect the account server ${ORIGIN}/api/mcp (OAuth sign-in).`;
+ }
+ return (
+ `Give this connector its own budget: POST ${ORIGIN}/api/mcp-studio/install returns a free token, then use ` +
+ `${ORIGIN}/api/mcp-studio?install=<token> as the connector URL. For an account-level budget connect ${ORIGIN}/api/mcp (OAuth sign-in).`
+ );
+}
+
+// A capped caller gets a JSON-RPC error (HTTP 429) that says which limit it hit,
+// when it resets and how to lift it, so an agent can relay a plan to its user
+// instead of a bare "rate limited". data carries the same facts for machines.
+function capped(res, result, { what, id, installed }) {
+ const retryAfter = Math.max(1, setRateLimitHeaders(res, result));
+ res.setHeader('retry-after', String(retryAfter));
+ res.setHeader('cache-control', 'no-store');
+ const resets = describeReset(result?.reset);
+ const unavailable = result?.reason === 'rate_limiter_unavailable';
+ const message = unavailable
+ ? `${what}: the limiter is temporarily unavailable. Retry in ${retryAfter} seconds.`
+ : `${what}. It resets ${resets}. ${remedyFor(installed)}`;
+ return rpcError(
+ res,
+ 429,
+ -32029,
+ message,
+ {
+ error: 'rate_limited',
+ limit: what,
+ retry_after: retryAfter,
+ resets_at: new Date(Date.now() + retryAfter * 1000).toISOString(),
+ remedy: {
+ install_token_endpoint: `POST ${ORIGIN}/api/mcp-studio/install`,
+ connector_url_template: `${ORIGIN}/api/mcp-studio?install=<token>`,
+ account_server: `${ORIGIN}/api/mcp`,
+ },
+ ...(result?.reason ? { reason: result.reason } : {}),
+ },
+ id,
+ );
+}
+
+/** The ?install= value of a request, from the parsed query or the raw URL. */
+export function installParam(req) {
+ const q = req?.query?.install;
+ if (typeof q === 'string') return q;
+ try {
+ return new URL(req?.url || '', 'http://x').searchParams.get('install');
+ } catch {
+ return null;
+ }
}
// Does the (possibly batched) body invoke any generation tool? Used to apply the
@@ -109,7 +178,7 @@ export function studioHandler({ surface = 'full' } = {}) {
// Cheap transport cap on every request (discovery + calls).
const ipRl = await limits.studioIp(ip);
- if (!ipRl.success) return rateLimited(res, ipRl, 'too many requests');
+ if (!ipRl.success) return capped(res, ipRl, { what: 'Too many requests from this network (300 per minute)', id: null, installed: false });
let body;
try {
@@ -124,21 +193,27 @@ export function studioHandler({ surface = 'full' } = {}) {
// Generation quota, burst then hourly, per IP. Applied only when the request
// actually calls a generation tool, so discovery is never throttled by it.
if (callsGenerationTool(body)) {
- const subject = callerSubject(surface, body, req);
+ // An install token (per-installation identity, free and anonymous) beats
+ // the surface's own subject, which beats the IP. An unknown or malformed
+ // token resolves to null and the caller is keyed exactly as without one.
+ const installKey = await resolveInstallToken(installParam(req));
+ const subject = installKey || callerSubject(surface, body, req);
+ const id = batch.find((m) => m && m.id !== undefined)?.id ?? null;
+ const installed = Boolean(installKey);
if (subject) {
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 capped(res, pool, { what: 'The free 3D studio is at capacity for this network right now (300 generations per hour across every installation behind one IP)', id, installed });
}
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');
+ if (!burst.success) return capped(res, burst, { what: 'Generation burst limit reached (4 generations per minute per caller)', id, installed });
const hourly = await limits.studioGenHourly(caller);
- if (!hourly.success) return rateLimited(res, hourly, 'hourly generation limit reached, try again later');
+ if (!hourly.success) return capped(res, hourly, { what: 'Hourly generation limit reached (30 generations per hour per caller)', id, installed });
// 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.
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 capped(res, global, { what: 'The free 3D studio is at capacity across all users right now', id, installed });
}
// Anonymous principal, no auth, no scope. rateKey carries the IP for usage logs.
diff --git a/api/_mcp3d/tools/studio.js b/api/_mcp3d/tools/studio.js
index 48b1b3ae0..09e035a75 100644
--- a/api/_mcp3d/tools/studio.js
+++ b/api/_mcp3d/tools/studio.js
@@ -21,6 +21,7 @@ import { limits } from '../../_lib/rate-limit.js';
import { assertSafePublicUrl, fetchSafePublicUrlPinned, MaxBytesExceededError } from '../../_lib/ssrf-guard.js';
import { createRegenProvider as createReplicateProvider } from '../../_providers/replicate.js';
import { createRegenProvider as createGcpProvider } from '../../_providers/gcp.js';
+import { isFbxMeshUrl, STYLIZE_FBX_MESSAGE } from '../../_lib/stylize-input.js';
import { BYOK_PROVIDER_FACTORIES, isByokGeometryBackend } from '../../_providers/byok-registry.js';
import { textToImage } from '../text-to-image.js';
import {
@@ -1259,14 +1260,14 @@ export const toolDefs = [
title: 'Remesh, simplify, repair, or convert a 3D model',
annotations: GENERATIVE_ANNOTATIONS,
description:
- 'Process an existing GLB/OBJ/STL/PLY mesh: fix holes and degenerate geometry, reduce face count via quadric decimation, or convert to a different format (including FBX with skeleton for Unity/Unreal — a convert of a rigged GLB keeps its bones, skin weights, and blendshapes). Returns a clean GLB (or the requested format) job_id to poll with generation_status.',
+ 'Process an existing GLB/GLTF/OBJ/FBX/STL/PLY/OFF/DAE mesh: fix holes and degenerate geometry, reduce face count via quadric decimation, or convert to a different format (including FBX with skeleton for Unity/Unreal: a convert of a rigged GLB keeps its bones, skin weights, and blendshapes). Returns a clean GLB (or the requested format) job_id to poll with generation_status.',
inputSchema: {
type: 'object',
properties: {
mesh_url: {
type: 'string',
format: 'uri',
- description: 'Public https URL of the source mesh (GLB/OBJ/FBX/STL/PLY).',
+ description: 'Public https URL of the source mesh (GLB/GLTF/OBJ/FBX/STL/PLY/OFF/DAE; FBX must be binary, 7.1 or later).',
},
operation: {
type: 'string',
@@ -1337,8 +1338,9 @@ export const toolDefs = [
title: 'Apply a one-click geometric stylization filter to a 3D model',
annotations: GENERATIVE_ANNOTATIONS,
description:
- 'Transform any GLB/OBJ/STL/PLY mesh into a stylized variant with a single geometry pass — ' +
- 'no model inference, fast and cheap. Styles: "voxel" (blocky cubes on a grid), "brick" ' +
+ 'Transform any GLB/GLTF/OBJ/STL/PLY/OFF/DAE mesh into a stylized variant with a single geometry pass: ' +
+ 'no model inference, fast and cheap. FBX is not accepted; convert it to GLB with remesh_model first. ' +
+ 'Styles: "voxel" (blocky cubes on a grid), "brick" ' +
'(voxels + studs, LEGO-like), "voronoi" (open strut-and-node lattice shell), "lowpoly" ' +
'(decimated + hard flat-shaded facets). Source color is preserved where the style allows. ' +
'Returns a job_id to poll with generation_status; typically completes in 10–40 seconds.',
@@ -1348,7 +1350,7 @@ export const toolDefs = [
mesh_url: {
type: 'string',
format: 'uri',
- description: 'Public https URL of the source mesh (GLB/OBJ/FBX/STL/PLY).',
+ description: 'Public https URL of the source mesh (GLB/GLTF/OBJ/STL/PLY/OFF/DAE; not FBX).',
},
style: {
type: 'string',
@@ -1383,6 +1385,9 @@ export const toolDefs = [
isError: true,
};
}
+ if (isFbxMeshUrl(args.mesh_url)) {
+ return { content: [{ type: 'text', text: `Error: ${STYLIZE_FBX_MESSAGE}` }], isError: true };
+ }
const provider = regenProvider('stylize');
const style = args.style || 'voxel';
const job = await provider.submit({
diff --git a/api/mcp-studio/install.js b/api/mcp-studio/install.js
new file mode 100644
index 000000000..4c5eff090
--- /dev/null
+++ b/api/mcp-studio/install.js
@@ -0,0 +1,42 @@
+// Mint a free, anonymous install token for the keyless 3D Studio MCP servers.
+//
+// POST /api/mcp-studio/install -> { token, connector_url, grok_connector_url, ... }
+//
+// No account, no key. Cloud agents share one egress IP, so the studio's
+// per-caller generation caps key on this token instead (see
+// api/_mcp-studio/handler.js). Creation is rate-limited per IP and the token is
+// stored hashed. Docs: docs/mcp-studio.md, "Install tokens".
+
+import { cors, json, method, wrap, rateLimited, error } from '../_lib/http.js';
+import { limits, clientIp } from '../_lib/rate-limit.js';
+import { createInstallToken } from '../_lib/mcp-studio-installs.js';
+
+const ORIGIN = 'https://three.ws';
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'POST,OPTIONS', origins: '*', payments: false })) return;
+ if (!method(req, res, ['POST'])) return;
+
+ const rl = await limits.studioInstallCreate(clientIp(req));
+ if (!rl.success) return rateLimited(res, rl, 'install token limit reached for this network, try again later');
+
+ let token;
+ try {
+ token = await createInstallToken();
+ } catch (err) {
+ console.error('[mcp-studio/install] could not store a token:', err.message);
+ return error(res, 503, 'install_unavailable', 'could not create an install token right now, retry in a moment');
+ }
+
+ return json(
+ res,
+ 201,
+ {
+ token,
+ connector_url: `${ORIGIN}/api/mcp-studio?install=${token}`,
+ grok_connector_url: `${ORIGIN}/api/mcp-grok?install=${token}`,
+ note: 'Anonymous and free. Keep the URL private: anyone holding it spends this installation\'s generation budget.',
+ },
+ { 'cache-control': 'no-store' },
+ );
+});
diff --git a/api/oauth/[action].js b/api/oauth/[action].js
index d795d11c4..6f4c99bdb 100644
--- a/api/oauth/[action].js
+++ b/api/oauth/[action].js
@@ -6,7 +6,7 @@ import { sql } from '../_lib/db.js';
import {
getSessionUser, csrfTokenFor, verifyCsrfToken, isSameSiteOrigin,
mintAccessToken, issueRefreshToken, rotateRefreshToken,
- revokeRefreshToken, verifyAccessToken,
+ revokeRefreshToken, verifyAccessToken, revokeClientGrant,
} from '../_lib/auth.js';
import { randomToken, sha256, sha256Base64Url, constantTimeEquals } from '../_lib/crypto.js';
import { cors, method, wrap, error, redirect, readForm, readJson, json, rateLimited } from '../_lib/http.js';
@@ -76,6 +76,26 @@ function esc(s) {
return String(s).replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[c]);
}
+// Host a person can check against what they expect: the client's own site when
+// it registered one, else where the code will be sent. Both are validated URLs.
+function clientHost(client, redirectUri) {
+ for (const candidate of [client.client_uri, redirectUri]) {
+ try { return new URL(candidate).host; } catch { /* try the next candidate */ }
+ }
+ return 'unknown host';
+}
+
+// Design rule 2: a token a cloud agent holds unattended does not spend. The
+// statement is only printed when it is true of THIS grant: wallet:write is the
+// one scope that authorizes spending (api/_lib/spend-scope.js), so a grant that
+// carries it is described honestly instead.
+function spendStatement(name, scopeList) {
+ if (scopeList.includes('wallet:write')) {
+ return `<b>${esc(name)}</b> is asking to spend from your agent wallet. Every spend stays inside your caps, and you can revoke this at any time.`;
+ }
+ return `<b>${esc(name)}</b> can never spend from a wallet or move funds. Payments only happen when you confirm them yourself on three.ws.`;
+}
+
function renderConsent(res, { client, user, params, csrf, grantedScope }) {
res.statusCode = 200;
res.setHeader('content-type', 'text/html; charset=utf-8');
@@ -99,7 +119,7 @@ function renderConsent(res, { client, user, params, csrf, grantedScope }) {
// registered scope, so showing the request itself made the consent screen
// promise one set of permissions and the issued code carry another.
const scopeList = grantedScope.split(/\s+/).filter(Boolean);
- res.end(`<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Authorize ${esc(client.name)} · three.ws</title><style>:root{color-scheme:light dark}body{font:16px/1.5 -apple-system,system-ui,Segoe UI,Roboto,sans-serif;background:#0b0b10;color:#eee;margin:0;min-height:100vh;display:grid;place-items:center;padding:24px}.card{background:#14141c;border:1px solid #2a2a36;border-radius:16px;padding:28px 28px 24px;max-width:440px;width:100%;box-shadow:0 10px 40px rgba(0,0,0,.4)}h1{font-size:20px;margin:0 0 8px}.sub{color:#aaa;margin:0 0 20px}.who{display:flex;align-items:center;gap:10px;margin-bottom:16px;padding:10px 12px;background:#1b1b25;border-radius:10px}.dot{width:32px;height:32px;border-radius:50%;background:linear-gradient(135deg,#6a5cff,#ff5ca8);display:grid;place-items:center;color:#fff;font-weight:600}ul{margin:12px 0 20px;padding-left:0;list-style:none}li{padding:8px 0;border-bottom:1px solid #22222e;display:flex;gap:10px}li:last-child{border:0}li::before{content:"✓";color:#6a5cff}.actions{display:flex;gap:10px}button{flex:1;padding:12px 16px;border-radius:10px;border:0;font-size:15px;font-weight:600;cursor:pointer}.allow{background:#6a5cff;color:#fff}.deny{background:transparent;color:#aaa;border:1px solid #2a2a36}.foot{margin-top:16px;font-size:12px;color:#777}a{color:#9a8cff}</style></head><body><form class="card" method="post" action="/api/oauth/authorize"><h1>Authorize <b>${esc(client.name)}</b></h1><p class="sub">Grant this application access to your three.ws account.</p><div class="who"><div class="dot">${esc((user.display_name || user.email)[0].toUpperCase())}</div><div><div>${esc(user.display_name || user.email)}</div><div style="color:#888;font-size:13px">${esc(user.email)}</div></div></div><p style="margin:0 0 4px"><b>${esc(client.name)}</b> will be able to:</p><ul>${scopeList.map((s) => `<li>${scopeLabel(s)}</li>`).join('')}</ul><input type="hidden" name="csrf" value="${esc(csrf || '')}"> ${Object.entries(params).filter(([k]) => k !== 'csrf' && k !== 'decision').map(([k, v]) => `<input type="hidden" name="${esc(k)}" value="${esc(v)}">`).join('')}<div class="actions"><button class="deny" type="submit" name="decision" value="deny">Cancel</button><button class="allow" type="submit" name="decision" value="allow">Authorize</button></div><p class="foot">You can revoke access any time from your <a href="/dashboard/connections">dashboard</a>.</p></form></body></html>`);
+ res.end(`<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Authorize ${esc(client.name)} · three.ws</title><style>:root{color-scheme:light dark}body{font:16px/1.5 -apple-system,system-ui,Segoe UI,Roboto,sans-serif;background:#0b0b10;color:#eee;margin:0;min-height:100vh;display:grid;place-items:center;padding:24px}.card{background:#14141c;border:1px solid #2a2a36;border-radius:16px;padding:28px 28px 24px;max-width:440px;width:100%;box-shadow:0 10px 40px rgba(0,0,0,.4)}h1{font-size:20px;margin:0 0 8px}.sub{color:#aaa;margin:0 0 20px}.who{display:flex;align-items:center;gap:10px;margin-bottom:16px;padding:10px 12px;background:#1b1b25;border-radius:10px}.dot{width:32px;height:32px;border-radius:50%;background:linear-gradient(135deg,#6a5cff,#ff5ca8);display:grid;place-items:center;color:#fff;font-weight:600}ul{margin:12px 0 20px;padding-left:0;list-style:none}li{padding:8px 0;border-bottom:1px solid #22222e;display:flex;gap:10px}li:last-child{border:0}li::before{content:"✓";color:#6a5cff}.actions{display:flex;gap:10px}button{flex:1;padding:12px 16px;border-radius:10px;border:0;font-size:15px;font-weight:600;cursor:pointer}.allow{background:#6a5cff;color:#fff}.deny{background:transparent;color:#aaa;border:1px solid #2a2a36}.foot{margin-top:16px;font-size:12px;color:#777}.host{display:block;font-size:13px;color:#aaa;word-break:break-all}.warn{margin:0 0 12px;padding:10px 12px;border-radius:10px;background:#1b1b25;border:1px solid #2a2a36;font-size:13px;color:#bbb}.nospend{margin:0 0 20px;padding:10px 12px;border-radius:10px;background:#12201a;border:1px solid #1f3a2c;font-size:13px;color:#b9e6cc}a{color:#9a8cff}</style></head><body><form class="card" method="post" action="/api/oauth/authorize"><h1>Authorize <b>${esc(client.name)}</b></h1><p class="sub">Grant this application access to your three.ws account.</p><p class="warn"><b>${esc(client.name)}</b><span class="host">Site: ${esc(clientHost(client, params.redirect_uri))}</span>This app registered itself. Only continue if you started this connection and you recognize the site.</p><div class="who"><div class="dot">${esc((user.display_name || user.email)[0].toUpperCase())}</div><div><div>${esc(user.display_name || user.email)}</div><div style="color:#888;font-size:13px">${esc(user.email)}</div></div></div><p style="margin:0 0 4px"><b>${esc(client.name)}</b> will be able to:</p><ul>${scopeList.map((s) => `<li>${scopeLabel(s)}</li>`).join('')}</ul><p class="nospend">${spendStatement(client.name, scopeList)}</p><input type="hidden" name="csrf" value="${esc(csrf || '')}"> ${Object.entries(params).filter(([k]) => k !== 'csrf' && k !== 'decision').map(([k, v]) => `<input type="hidden" name="${esc(k)}" value="${esc(v)}">`).join('')}<div class="actions"><button class="deny" type="submit" name="decision" value="deny">Cancel</button><button class="allow" type="submit" name="decision" value="allow">Authorize</button></div><p class="foot">You can revoke access any time from <a href="/dashboard/settings#connected-apps">Settings, Connected apps</a>.</p></form></body></html>`);
}
async function handleAuthorize(req, res) {
@@ -447,8 +467,9 @@ async function handleIntrospect(req, res) {
// token; DELETE ?client_id= revokes all of that client's refresh tokens.
// Session only, on purpose: a bearer token must not be able to list or revoke
// the other apps on the account, including itself.
-// Access tokens are stateless JWTs, so a revoked app keeps working until its
-// current access token expires (one hour at most) and then cannot renew.
+// Revoking is effective on the app's very next request: revokeClientGrant also
+// records a cutoff that authenticateBearer checks against every access token's
+// issue time, so the stateless JWT stops working immediately rather than at expiry.
async function handleGrants(req, res) {
if (cors(req, res, { methods: 'GET,DELETE,OPTIONS', credentials: true })) return;
@@ -482,12 +503,8 @@ async function handleGrants(req, res) {
if (!(await requireCsrf(req, res, user.id))) return;
const clientId = new URL(req.url, 'http://x').searchParams.get('client_id');
if (!clientId) return error(res, 400, 'invalid_request', 'client_id required');
- const revoked = await sql`
- update oauth_refresh_tokens set revoked_at = now()
- where user_id = ${user.id} and client_id = ${clientId} and revoked_at is null
- returning id
- `;
- return json(res, 200, { client_id: clientId, revoked: revoked.length });
+ const revoked = await revokeClientGrant({ userId: user.id, clientId });
+ return json(res, 200, { client_id: clientId, revoked });
}
// ── dispatcher ────────────────────────────────────────────────────────────────
diff --git a/pages/connect.html b/pages/connect.html
index 89b13ba2e..c75dfc5f1 100644
--- a/pages/connect.html
+++ b/pages/connect.html
@@ -151,6 +151,10 @@
border: 1px solid var(--stroke); border-radius: var(--radius-md, 10px);
}
+ .cn-cloud-actions { margin: 0 0 12px; }
+ .cn-url-second { margin-top: 8px; }
+ .cn-note a { text-decoration: underline; text-underline-offset: 3px; }
+
/* ── worth knowing ──────────────────────────────────────────────── */
.cn-facts { display: grid; grid-template-columns: repeat(auto-fit, minmax(240px, 1fr)); gap: 10px; }
.cn-fact { padding: 15px 16px; border: 1px solid var(--stroke); border-radius: var(--radius-md, 10px); background: var(--surface-1, rgba(255,255,255,0.03)); }
@@ -322,6 +326,31 @@
</div>
</section>
+ <section class="cn-step" aria-labelledby="cn-cloud">
+ <div class="cn-step-head">
+ <div>
+ <h2 id="cn-cloud">Connector URL for cloud agents</h2>
+ <p>Grok Bot, the xAI API and other hosted agents share one network address, so they share one generation allowance unless each installation has its own. Get a free, anonymous token: no account.</p>
+ </div>
+ </div>
+ <div class="cn-cloud-actions">
+ <button type="button" class="cn-btn" id="cn-cloud-mint">Generate my connector URL</button>
+ </div>
+ <div id="cn-cloud-result" hidden>
+ <div class="cn-url">
+ <span class="cn-url-label">Grok</span>
+ <code id="cn-cloud-grok"></code>
+ <button type="button" class="cn-btn" data-copy-target="cn-cloud-grok">Copy URL</button>
+ </div>
+ <div class="cn-url cn-url-second">
+ <span class="cn-url-label">Studio</span>
+ <code id="cn-cloud-studio"></code>
+ <button type="button" class="cn-btn" data-copy-target="cn-cloud-studio">Copy URL</button>
+ </div>
+ </div>
+ <p class="cn-note" id="cn-cloud-note" role="status" aria-live="polite">Keep the URL private: whoever holds it spends your installation's budget. <a href="/docs/mcp-studio">How install tokens work</a>.</p>
+ </section>
+
<section class="cn-step" aria-labelledby="cn-step3">
<div class="cn-step-head">
<span class="cn-step-num" aria-hidden="true">3</span>
@@ -514,6 +543,39 @@
tabs[next].focus();
});
+ // ── connector URL for cloud agents: a real token from the real endpoint ──
+ (function cloudConnector() {
+ const mintBtn = document.getElementById('cn-cloud-mint');
+ const result = document.getElementById('cn-cloud-result');
+ const note = document.getElementById('cn-cloud-note');
+ const grokEl = document.getElementById('cn-cloud-grok');
+ const studioEl = document.getElementById('cn-cloud-studio');
+ mintBtn.addEventListener('click', async () => {
+ mintBtn.disabled = true;
+ mintBtn.textContent = 'Generating...';
+ note.dataset.tone = '';
+ try {
+ const res = await fetch('/api/mcp-studio/install', { method: 'POST' });
+ const data = await res.json().catch(() => ({}));
+ if (!res.ok || !data.connector_url) {
+ const wait = data.retry_after ? ` Try again in ${Math.ceil(data.retry_after / 60)} min.` : ' Try again in a moment.';
+ throw new Error(res.status === 429 ? `This network has minted its 10 tokens for the hour.${wait}` : `Could not create a token.${wait}`);
+ }
+ grokEl.textContent = data.grok_connector_url;
+ studioEl.textContent = data.connector_url;
+ result.hidden = false;
+ mintBtn.textContent = 'Generate another';
+ note.textContent = 'Paste the Grok URL as a custom MCP connector in Grok Bot, or the Studio URL in any other client. Keep it private: whoever holds it spends your budget.';
+ } catch (err) {
+ note.dataset.tone = 'error';
+ note.textContent = err.message;
+ mintBtn.textContent = 'Generate my connector URL';
+ } finally {
+ mintBtn.disabled = false;
+ }
+ });
+ })();
+
// ── shareable state: /connect?client=cursor&server=three-ws-3d-studio-free ──
function writeQuery() {
const q = new URLSearchParams(location.search);
diff --git a/public/mcp-catalog.json b/public/mcp-catalog.json
index 823e2b4cb..bf2deca64 100644
--- a/public/mcp-catalog.json
+++ b/public/mcp-catalog.json
@@ -16312,7 +16312,7 @@
{
"name": "remesh_model",
"title": "Remesh, simplify, repair, or convert a 3D model",
- "description": "Process an existing GLB/OBJ/STL/PLY mesh: fix holes and degenerate geometry, reduce face count via quadric decimation, or convert to a different format (including FBX with skeleton for Unity/Unreal — a convert of a rigged GLB keeps its bones, skin weights, and blendshapes). Returns a clean GLB (or the requested format) job_id to poll with generation_status.",
+ "description": "Process an existing GLB/GLTF/OBJ/FBX/STL/PLY/OFF/DAE mesh: fix holes and degenerate geometry, reduce face count via quadric decimation, or convert to a different format (including FBX with skeleton for Unity/Unreal: a convert of a rigged GLB keeps its bones, skin weights, and blendshapes). Returns a clean GLB (or the requested format) job_id to poll with generation_status.",
"server": {
"id": "threews-3d-studio",
"title": "3D Studio",
@@ -16337,7 +16337,7 @@
"mesh_url": {
"type": "string",
"format": "uri",
- "description": "Public https URL of the source mesh (GLB/OBJ/FBX/STL/PLY)."
+ "description": "Public https URL of the source mesh (GLB/GLTF/OBJ/FBX/STL/PLY/OFF/DAE; FBX must be binary, 7.1 or later)."
},
"operation": {
"type": "string",
@@ -16739,7 +16739,7 @@
{
"name": "stylize_model",
"title": "Apply a one-click geometric stylization filter to a 3D model",
- "description": "Transform any GLB/OBJ/STL/PLY mesh into a stylized variant with a single geometry pass — no model inference, fast and cheap. Styles: \"voxel\" (blocky cubes on a grid), \"brick\" (voxels + studs, LEGO-like), \"voronoi\" (open strut-and-node lattice shell), \"lowpoly\" (decimated + hard flat-shaded facets). Source color is preserved where the style allows. Returns a job_id to poll with generation_status; typically completes in 10–40 seconds.",
+ "description": "Transform any GLB/GLTF/OBJ/STL/PLY/OFF/DAE mesh into a stylized variant with a single geometry pass: no model inference, fast and cheap. FBX is not accepted; convert it to GLB with remesh_model first. Styles: \"voxel\" (blocky cubes on a grid), \"brick\" (voxels + studs, LEGO-like), \"voronoi\" (open strut-and-node lattice shell), \"lowpoly\" (decimated + hard flat-shaded facets). Source color is preserved where the style allows. Returns a job_id to poll with generation_status; typically completes in 10–40 seconds.",
"server": {
"id": "threews-3d-studio",
"title": "3D Studio",
@@ -16764,7 +16764,7 @@
"mesh_url": {
"type": "string",
"format": "uri",
- "description": "Public https URL of the source mesh (GLB/OBJ/FBX/STL/PLY)."
+ "description": "Public https URL of the source mesh (GLB/GLTF/OBJ/STL/PLY/OFF/DAE; not FBX)."
},
"style": {
"type": "string",
diff --git a/scripts/mcp-client-probe.mjs b/scripts/mcp-client-probe.mjs
index 7ff6a82f5..b356cc841 100644
--- a/scripts/mcp-client-probe.mjs
+++ b/scripts/mcp-client-probe.mjs
@@ -499,7 +499,8 @@ async function main() {
if (args.json) {
const out = resolve(process.cwd(), args.json);
mkdirSync(dirname(out), { recursive: true });
- writeFileSync(out, `${JSON.stringify(report, null, '\t')}\n`);
+ // Server error bodies are quoted verbatim; the repo bans em and en dashes in committed text.
+ writeFileSync(out, `${JSON.stringify(report, null, '\t').replace(/[\u2013\u2014]/g, '-')}\n`);
console.log(`wrote ${args.json}`);
}
const failed = results.filter((r) => !r.pass).length;
diff --git a/tests/api/forge-pipeline-endpoints.test.js b/tests/api/forge-pipeline-endpoints.test.js
index 50835f477..5fa924939 100644
--- a/tests/api/forge-pipeline-endpoints.test.js
+++ b/tests/api/forge-pipeline-endpoints.test.js
@@ -249,6 +249,31 @@ describe('forge-stylize', () => {
expect(parse(res).error).toBe('invalid_mesh_url');
});
+ it('refuses an FBX mesh with a 400 naming the formats that work, before queuing a job', async () => {
+ submitted.length = 0;
+ const res = await call(stylize, {
+ method: 'POST',
+ url: '/api/forge-stylize',
+ body: { mesh_url: 'https://cdn.example/rig.FBX?sig=abc', style: 'voxel' },
+ });
+ expect(res.statusCode).toBe(400);
+ expect(parse(res).error).toBe('unsupported_mesh_format');
+ expect(parse(res).message).toContain('GLB, GLTF, OBJ, STL, PLY, OFF or DAE');
+ // The worker has no FBX reader, so a queued job could only fail later.
+ expect(submitted).toHaveLength(0);
+ });
+
+ it('still accepts a DAE mesh', async () => {
+ submitted.length = 0;
+ const res = await call(stylize, {
+ method: 'POST',
+ url: '/api/forge-stylize',
+ body: { mesh_url: 'https://cdn.example/scene.dae', style: 'voxel' },
+ });
+ expect(res.statusCode).toBe(202);
+ expect(submitted).toHaveLength(1);
+ });
+
it('answers 502, not 500, when the worker poll faults', async () => {
providerState.statusThrows = true;
const res = await call(stylize, { url: `/api/forge-stylize?job=${JOB}` });
diff --git a/tests/e2e/oauth-cloud-connector.spec.js b/tests/e2e/oauth-cloud-connector.spec.js
new file mode 100644
index 000000000..33aa35cac
--- /dev/null
+++ b/tests/e2e/oauth-cloud-connector.spec.js
@@ -0,0 +1,133 @@
+// A cloud connector (Grok Bot) signs in to /api/mcp the way it does in production:
+// dynamic registration with an external https redirect URI, the PKCE
+// authorization-code flow as the QA account, tools/list with the token, then the
+// person revokes it from Settings and the very next call fails.
+//
+// Needs AUDIT_EMAIL / AUDIT_PASSWORD (.env; `npm run audit:web:provision` creates
+// them). Run against a dev server whose /api reaches a build that includes
+// api/_lib/auth.js revokeClientGrant: DEV_API_PROXY=http://localhost:3001 npm run dev
+// with `PORT=3001 node server/index.mjs`.
+
+import { test, expect } from '@playwright/test';
+import { createHash, randomBytes } from 'node:crypto';
+import { readFileSync, existsSync } from 'node:fs';
+
+function loadEnv(file) {
+ if (!existsSync(file)) return;
+ for (const line of readFileSync(file, 'utf8').split('\n')) {
+ const m = line.match(/^([A-Z0-9_]+)=(.*)$/);
+ if (m && !(m[1] in process.env)) process.env[m[1]] = m[2].replace(/^["']|["']$/g, '');
+ }
+}
+loadEnv('.env');
+
+const EMAIL = process.env.AUDIT_EMAIL;
+const PASSWORD = process.env.AUDIT_PASSWORD;
+const REDIRECT = 'https://grok-bot-connector.example/oauth/callback';
+const RESOURCE = 'https://three.ws/api/mcp';
+
+const b64url = (buf) => buf.toString('base64url');
+
+async function toolsList(request, token) {
+ return request.post('/api/mcp', {
+ headers: {
+ authorization: `Bearer ${token}`,
+ 'content-type': 'application/json',
+ accept: 'application/json, text/event-stream',
+ },
+ data: { jsonrpc: '2.0', id: 1, method: 'tools/list' },
+ });
+}
+
+test.describe('OAuth for cloud connectors', () => {
+ test.skip(!EMAIL || !PASSWORD, 'AUDIT_EMAIL / AUDIT_PASSWORD missing: run npm run audit:web:provision');
+ test.setTimeout(240_000);
+
+ test('Grok Bot registers, authorizes with PKCE, calls tools/list, is revoked, and fails on the next call', async ({ page, context }) => {
+ // The connector's own redirect host does not exist: capture the navigation.
+ await context.route('https://grok-bot-connector.example/**', (route) =>
+ route.fulfill({ status: 200, contentType: 'text/html', body: '<h1>connector callback</h1>' }),
+ );
+
+ await page.goto('/login');
+ await page.waitForSelector('#email', { timeout: 60_000 });
+ await page.fill('#email', EMAIL);
+ await page.fill('#password', PASSWORD);
+ await page.click('form button[type="submit"]');
+ await page.waitForURL((u) => !/\/login/.test(u.pathname), { timeout: 60_000 });
+
+ const reg = await page.request.post('/api/oauth/register', {
+ data: {
+ client_name: 'Grok Bot',
+ client_uri: 'https://grok-bot-connector.example',
+ redirect_uris: [REDIRECT],
+ scope: 'avatars:read profile offline_access',
+ },
+ });
+ expect(reg.status()).toBe(201);
+ const client = await reg.json();
+ expect(client.client_name).toBe('Grok Bot');
+
+ const verifier = b64url(randomBytes(32));
+ const challenge = b64url(createHash('sha256').update(verifier).digest());
+ const state = b64url(randomBytes(8));
+ const authorize = new URLSearchParams({
+ response_type: 'code',
+ client_id: client.client_id,
+ redirect_uri: REDIRECT,
+ scope: 'avatars:read profile offline_access',
+ state,
+ code_challenge: challenge,
+ code_challenge_method: 'S256',
+ resource: RESOURCE,
+ });
+ await page.goto(`/api/oauth/authorize?${authorize}`);
+
+ await expect(page.locator('h1')).toContainText('Authorize Grok Bot');
+ await expect(page.locator('.host')).toContainText('grok-bot-connector.example');
+ await expect(page.locator('.nospend')).toContainText('can never spend from a wallet');
+ await expect(page.locator('li')).toContainText(['Read your avatars', 'See your name and email']);
+
+ await Promise.all([
+ page.waitForURL(/grok-bot-connector\.example\/oauth\/callback\?/),
+ page.click('button[value="allow"]'),
+ ]);
+ const back = new URL(page.url());
+ expect(back.searchParams.get('state')).toBe(state);
+ const code = back.searchParams.get('code');
+ expect(code).toBeTruthy();
+
+ const tokenRes = await page.request.post('/api/oauth/token', {
+ form: {
+ grant_type: 'authorization_code',
+ client_id: client.client_id,
+ code,
+ redirect_uri: REDIRECT,
+ code_verifier: verifier,
+ resource: RESOURCE,
+ },
+ });
+ expect(tokenRes.status()).toBe(200);
+ const tokens = await tokenRes.json();
+ expect(tokens.refresh_token).toBeTruthy();
+
+ const listed = await toolsList(page.request, tokens.access_token);
+ expect(listed.status()).toBe(200);
+ expect(JSON.stringify(await listed.json())).toContain('"tools"');
+
+ await page.goto('/dashboard/settings');
+ const row = page.locator('[data-client-id="' + client.client_id + '"]');
+ await expect(row).toContainText('Grok Bot', { timeout: 60_000 });
+ page.once('dialog', (d) => d.accept());
+ await row.getByRole('button', { name: 'Revoke' }).click();
+ await expect(row).toHaveCount(0);
+
+ const after = await toolsList(page.request, tokens.access_token);
+ expect(after.status()).toBe(401);
+
+ const refreshed = await page.request.post('/api/oauth/token', {
+ form: { grant_type: 'refresh_token', client_id: client.client_id, refresh_token: tokens.refresh_token, resource: RESOURCE },
+ });
+ expect(refreshed.status()).toBe(400);
+ });
+});
diff --git a/tests/fixtures/mcp-golden-tools.json b/tests/fixtures/mcp-golden-tools.json
index 75e440a0c..ba5a28d8b 100644
--- a/tests/fixtures/mcp-golden-tools.json
+++ b/tests/fixtures/mcp-golden-tools.json
@@ -1238,10 +1238,10 @@
{
"name": "remesh_model",
"title": "Remesh, simplify, repair, or convert a 3D model",
- "descHead": "Process an existing GLB/OBJ/STL/PLY mesh: fix holes and degenerate geome",
- "descHash": "47b083320257",
+ "descHead": "Process an existing GLB/GLTF/OBJ/FBX/STL/PLY/OFF/DAE mesh: fix holes and",
+ "descHash": "a8b3ca1d4a5e",
"annotations": "ref:GENERATIVE_ANNOTATIONS",
- "schemaHash": "c0c577c37614"
+ "schemaHash": "ee7335f4b61a"
},
{
"name": "remove_background",
@@ -1289,7 +1289,7 @@
"descHead": "dynamic",
"descHash": "dynamic",
"annotations": "ref:GENERATIVE_ANNOTATIONS",
- "schemaHash": "4fd28829ddac"
+ "schemaHash": "786f1efee28d"
},
{
"name": "text_to_3d",
diff --git a/tests/mcp-studio-install.test.js b/tests/mcp-studio-install.test.js
new file mode 100644
index 000000000..4db61cbc8
--- /dev/null
+++ b/tests/mcp-studio-install.test.js
@@ -0,0 +1,220 @@
+// Install tokens for the keyless 3D Studio MCP servers, against the REAL
+// mcp_studio_installs migration in an in-process Postgres (PGlite) and the REAL
+// rate limiters (in-memory store, no Redis). Pins the three contracts:
+// - two tokens from one IP get independent per-caller budgets;
+// - no token (or an unknown one) behaves exactly as before: keyed on the IP;
+// - minting a token is itself rate limited per IP, and stores only a hash.
+
+import { readFileSync } from 'node:fs';
+import { describe, it, expect, beforeAll, beforeEach, vi } from 'vitest';
+import { PGlite } from '@electric-sql/pglite';
+
+const dbState = { pg: null };
+
+vi.mock('../api/_lib/db.js', () => {
+ const sql = async (strings, ...values) => {
+ const text = strings.reduce((acc, part, i) => acc + part + (i < values.length ? `$${i + 1}` : ''), '');
+ const out = await dbState.pg.query(text, values);
+ return out.rows;
+ };
+ return { sql, isDbUnavailableError: () => false, isDbCapacityError: () => false };
+});
+
+vi.mock('../api/_mcp-studio/gpt-forge-client.js', async (importOriginal) => {
+ const real = await importOriginal();
+ return { ...real, generate: vi.fn(async () => ({ status: 'done', glb_url: 'https://three.ws/cdn/a.glb' })), rig: vi.fn(), directPrompt: vi.fn(async () => null) };
+});
+
+const studio = (await import('../api/mcp-studio.js')).default;
+const grok = (await import('../api/mcp-grok.js')).default;
+const install = (await import('../api/mcp-studio/install.js')).default;
+const { createInstallToken, resolveInstallToken, clearInstallCache, isInstallTokenShape, hashInstallToken } = await import('../api/_lib/mcp-studio-installs.js');
+const { describeReset, installParam } = await import('../api/_mcp-studio/handler.js');
+
+const MIGRATION = readFileSync(new URL('../api/_lib/migrations/20261009120000_mcp_studio_installs.sql', import.meta.url), 'utf8');
+
+function pair(method, url, body, ip) {
+ const payload = Buffer.from(body ? JSON.stringify(body) : '');
+ const req = {
+ method,
+ url,
+ headers: { host: 'three.ws', 'content-type': 'application/json', 'x-forwarded-for': ip },
+ socket: { remoteAddress: ip },
+ async *[Symbol.asyncIterator]() {
+ yield payload;
+ },
+ on(event, cb) {
+ if (event === 'data') cb(payload);
+ if (event === 'end') cb();
+ return this;
+ },
+ };
+ const out = { 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;
+ this.headersSent = true;
+ },
+ write(chunk) {
+ out.body += chunk;
+ },
+ };
+ return { req, res, out };
+}
+
+let ipCounter = 0;
+const freshIp = () => `198.51.100.${(ipCounter += 1)}`;
+
+const gen = (id = 1) => ({ jsonrpc: '2.0', id, method: 'tools/call', params: { name: 'forge_free', arguments: { prompt: 'a lunar lander' } } });
+
+async function callGen(handler, url, ip, id = 1) {
+ const { req, res, out } = pair('POST', url, gen(id), ip);
+ await handler(req, res);
+ return { status: res.statusCode, out, json: out.body ? JSON.parse(out.body) : null };
+}
+
+async function mint(ip) {
+ const { req, res, out } = pair('POST', '/api/mcp-studio/install', null, ip);
+ await install(req, res);
+ return { status: res.statusCode, out, json: JSON.parse(out.body) };
+}
+
+beforeAll(() => {
+ dbState.pg = new PGlite();
+});
+
+beforeEach(async () => {
+ await dbState.pg.exec('drop table if exists mcp_studio_installs');
+ await dbState.pg.exec(MIGRATION);
+ clearInstallCache();
+});
+
+describe('install token storage', () => {
+ it('mints a well-formed token and stores only its hash', async () => {
+ const token = await createInstallToken();
+ expect(isInstallTokenShape(token)).toBe(true);
+ const rows = (await dbState.pg.query('select token_hash from mcp_studio_installs')).rows;
+ expect(rows).toHaveLength(1);
+ expect(rows[0].token_hash).toBe(hashInstallToken(token));
+ expect(rows[0].token_hash).not.toContain(token);
+ });
+
+ it('resolves a known token to a stable key and an unknown or malformed one to null', async () => {
+ const token = await createInstallToken();
+ clearInstallCache();
+ const key = await resolveInstallToken(token);
+ expect(key).toMatch(/^inst:[0-9a-f]{32}$/);
+ expect(await resolveInstallToken(token)).toBe(key);
+ expect(await resolveInstallToken(`inst_${'0'.repeat(32)}`)).toBeNull();
+ expect(await resolveInstallToken('inst_short')).toBeNull();
+ expect(await resolveInstallToken(null)).toBeNull();
+ expect(await resolveInstallToken(['inst_x'])).toBeNull();
+ });
+
+ it('reads the token from the parsed query or the raw url', () => {
+ expect(installParam({ query: { install: 'inst_a' }, url: '/x' })).toBe('inst_a');
+ expect(installParam({ url: '/api/mcp-studio?install=inst_b' })).toBe('inst_b');
+ expect(installParam({ url: '/api/mcp-studio' })).toBeNull();
+ });
+});
+
+describe('POST /api/mcp-studio/install', () => {
+ it('returns a connector URL carrying the token', async () => {
+ const { status, json, out } = await mint(freshIp());
+ expect(status).toBe(201);
+ expect(json.connector_url).toBe(`https://three.ws/api/mcp-studio?install=${json.token}`);
+ expect(json.grok_connector_url).toBe(`https://three.ws/api/mcp-grok?install=${json.token}`);
+ expect(out.headers['cache-control']).toBe('no-store');
+ });
+
+ it('rate limits token creation per IP', async () => {
+ const ip = freshIp();
+ const results = [];
+ for (let i = 0; i < 11; i += 1) results.push((await mint(ip)).status);
+ expect(results.slice(0, 10).every((s) => s === 201)).toBe(true);
+ expect(results[10]).toBe(429);
+ expect((await mint(freshIp())).status).toBe(201);
+ });
+
+ it('rejects GET', async () => {
+ const { req, res } = pair('GET', '/api/mcp-studio/install', null, freshIp());
+ await install(req, res);
+ expect(res.statusCode).toBe(405);
+ });
+});
+
+describe('per-caller generation budgets', () => {
+ it('gives two tokens from one IP independent budgets', async () => {
+ const ip = freshIp();
+ const a = (await mint(freshIp())).json.token;
+ const b = (await mint(freshIp())).json.token;
+ const urlA = `/api/mcp-grok?install=${a}`;
+ const urlB = `/api/mcp-grok?install=${b}`;
+
+ for (let i = 0; i < 4; i += 1) expect((await callGen(grok, urlA, ip, i + 1)).status).toBe(200);
+ const capped = await callGen(grok, urlA, ip, 99);
+ expect(capped.status).toBe(429);
+ expect((await callGen(grok, urlB, ip, 1)).status).toBe(200);
+ });
+
+ it('answers a capped caller with a JSON-RPC error that names the limit, the reset and the remedy', async () => {
+ const ip = freshIp();
+ for (let i = 0; i < 4; i += 1) await callGen(studio, '/api/mcp-studio', ip, i + 1);
+ const capped = await callGen(studio, '/api/mcp-studio', ip, 77);
+ expect(capped.status).toBe(429);
+ expect(capped.json.jsonrpc).toBe('2.0');
+ expect(capped.json.id).toBe(77);
+ const msg = capped.json.error.message;
+ expect(msg).toContain('4 generations per minute');
+ expect(msg).toMatch(/resets in \d+ (seconds|minutes)/);
+ expect(msg).toContain('https://three.ws/api/mcp-studio/install');
+ expect(msg).toContain('https://three.ws/api/mcp-studio?install=<token>');
+ expect(msg).toContain('https://three.ws/api/mcp');
+ expect(capped.json.error.data.retry_after).toBeGreaterThan(0);
+ expect(capped.json.error.data.remedy.account_server).toBe('https://three.ws/api/mcp');
+ expect(Number(capped.out.headers['retry-after'])).toBeGreaterThan(0);
+ });
+
+ it('tells a capped install-token caller that its own budget refills, not to mint another token', async () => {
+ const ip = freshIp();
+ const token = (await mint(freshIp())).json.token;
+ for (let i = 0; i < 4; i += 1) await callGen(studio, `/api/mcp-studio?install=${token}`, ip, i + 1);
+ const capped = await callGen(studio, `/api/mcp-studio?install=${token}`, ip, 5);
+ expect(capped.status).toBe(429);
+ expect(capped.json.error.message).toContain("This installation's budget refills");
+ expect(capped.json.error.message).not.toContain('returns a free token');
+ });
+
+ it('keys a call with no token, or an unknown token, on the IP exactly as before', async () => {
+ const ip = freshIp();
+ const bogus = `inst_${'f'.repeat(32)}`;
+ // Two calls without a token and two with an unknown one share the IP bucket of 4.
+ expect((await callGen(studio, '/api/mcp-studio', ip, 1)).status).toBe(200);
+ expect((await callGen(studio, '/api/mcp-studio', ip, 2)).status).toBe(200);
+ expect((await callGen(studio, `/api/mcp-studio?install=${bogus}`, ip, 3)).status).toBe(200);
+ expect((await callGen(studio, `/api/mcp-studio?install=${bogus}`, ip, 4)).status).toBe(200);
+ expect((await callGen(studio, '/api/mcp-studio', ip, 5)).status).toBe(429);
+ // A different IP is untouched.
+ expect((await callGen(studio, '/api/mcp-studio', freshIp(), 1)).status).toBe(200);
+ });
+});
+
+describe('describeReset', () => {
+ it('words short and long waits', () => {
+ const now = Date.UTC(2026, 9, 9, 14, 0, 0);
+ expect(describeReset(now + 30_000, now)).toBe('in 30 seconds (at 14:00 UTC)');
+ expect(describeReset(now + 12 * 60_000, now)).toBe('in 12 minutes (at 14:12 UTC)');
+ expect(describeReset(now + 3 * 3600_000, now)).toBe('in 3 hours (at 17:00 UTC)');
+ });
+});
diff --git a/tests/oauth-endpoints.test.js b/tests/oauth-endpoints.test.js
index 1d48182f3..cca0846c1 100644
--- a/tests/oauth-endpoints.test.js
+++ b/tests/oauth-endpoints.test.js
@@ -26,6 +26,7 @@ process.env.JWT_SECRET ||= 'vitest-ephemeral-jwt-secret-00000000000000';
vi.mock('../api/_lib/zauth.js', () => ({ instrument: () => {}, drain: async () => {} }));
vi.mock('../api/_lib/sentry.js', () => ({ captureException: () => {} }));
+vi.mock('../api/_lib/csrf.js', () => ({ requireCsrf: async () => true }));
vi.mock('../api/_lib/audit.js', () => ({ logAudit: vi.fn() }));
vi.mock('../api/_lib/streaks.js', () => ({ recordDailyActivity: vi.fn(async () => {}) }));
vi.mock('../api/_lib/rate-limit.js', () => ({
@@ -38,7 +39,7 @@ vi.mock('../api/_lib/rate-limit.js', () => ({
}));
// ── in-memory stand-in for the three oauth tables ────────────────────────────
-const db = { clients: [], codes: [], refresh: [] };
+const db = { clients: [], codes: [], refresh: [], revocations: [] };
const statements = [];
function future(seconds) {
@@ -103,11 +104,22 @@ const sqlMock = vi.fn(async (strings, ...values) => {
}
if (text.startsWith('update oauth_refresh_tokens set revoked_at = now() where user_id')) {
const [userId, clientId] = values;
+ const hit = [];
for (const r of db.refresh) {
- if (r.user_id === userId && r.client_id === clientId && !r.revoked_at) r.revoked_at = new Date().toISOString();
+ if (r.user_id === userId && r.client_id === clientId && !r.revoked_at) { r.revoked_at = new Date().toISOString(); hit.push({ id: r.id }); }
}
+ return hit;
+ }
+ if (text.startsWith('insert into oauth_client_revocations')) {
+ const [userId, clientId] = values;
+ db.revocations = db.revocations.filter((r) => !(r.user_id === userId && r.client_id === clientId));
+ db.revocations.push({ user_id: userId, client_id: clientId, revoked_at: Date.now() });
return [];
}
+ if (text.startsWith('select 1 from oauth_client_revocations')) {
+ const [userId, clientId, iat] = values;
+ return db.revocations.filter((r) => r.user_id === userId && r.client_id === clientId && r.revoked_at >= iat * 1000).slice(0, 1).map(() => ({ '?column?': 1 }));
+ }
throw new Error(`unmodeled query: ${text}`);
});
// http.js's wrap() classifies caught errors with these predicates, so the mock
@@ -127,7 +139,7 @@ vi.mock('../api/_lib/auth.js', async () => {
});
const { default: handler } = await import('../api/oauth/[action].js');
-const { csrfTokenFor, verifyAccessToken } = await import('../api/_lib/auth.js');
+const { csrfTokenFor, verifyAccessToken, authenticateBearer } = await import('../api/_lib/auth.js');
const { sha256, sha256Base64Url } = await import('../api/_lib/crypto.js');
// ── request/response doubles ─────────────────────────────────────────────────
@@ -234,6 +246,7 @@ beforeEach(async () => {
db.clients.length = 0;
db.codes.length = 0;
db.refresh.length = 0;
+ db.revocations.length = 0;
statements.length = 0;
sqlMock.mockClear();
getSessionUser.mockReset();
@@ -253,6 +266,28 @@ describe('GET /oauth/authorize', () => {
expect(res.body).not.toContain('Store and forget');
});
+ it('names the asking app, its host, and that it can never spend', async () => {
+ seedClient({ name: 'Grok Bot', client_uri: 'https://grok.example/bot', redirect_uris: ['https://cb.grok.example/cb'] });
+ const res = await call('authorize', { query: authorizeQuery({ redirect_uri: 'https://cb.grok.example/cb' }) });
+ expect(res.body).toContain('Authorize <b>Grok Bot</b>');
+ expect(res.body).toContain('Site: grok.example');
+ expect(res.body).toContain('can never spend from a wallet');
+ expect(res.body).toContain('/dashboard/settings#connected-apps');
+ });
+
+ it('does not claim a client cannot spend when the grant carries wallet:write', async () => {
+ seedClient({ scope: 'avatars:read wallet:write' });
+ const res = await call('authorize', { query: authorizeQuery() });
+ expect(res.body).not.toContain('can never spend');
+ expect(res.body).toContain('asking to spend from your agent wallet');
+ });
+
+ it('escapes a hostile client name', async () => {
+ seedClient({ name: '<img src=x onerror=alert(1)>' });
+ const res = await call('authorize', { query: authorizeQuery() });
+ expect(res.body).not.toContain('<img src=x');
+ });
+
it('allows the client origin in form-action so the post-consent 302 is not blocked', async () => {
seedClient();
const res = await call('authorize', { query: authorizeQuery() });
@@ -605,6 +640,38 @@ describe('POST /oauth/revoke', () => {
});
});
+describe('DELETE /oauth/grants (connected apps)', () => {
+ it('kills an access token already in flight on the very next request', async () => {
+ seedClient();
+ const { access_token } = await issueTokens();
+ const audience = RESOURCE;
+ expect(await authenticateBearer(access_token, { audience })).toMatchObject({ userId: 'user-1', clientId: 'mcp_test_client' });
+
+ const res = await call('grants', { method: 'DELETE', query: { client_id: 'mcp_test_client' } });
+ expect(res.statusCode).toBe(200);
+ expect(res.json()).toEqual({ client_id: 'mcp_test_client', revoked: 1 });
+ expect(db.refresh[0].revoked_at).toBeTruthy();
+ expect(await authenticateBearer(access_token, { audience })).toBeNull();
+ });
+
+ it('accepts a token minted after the person authorizes the app again', async () => {
+ seedClient();
+ const first = await issueTokens();
+ await call('grants', { method: 'DELETE', query: { client_id: 'mcp_test_client' } });
+ await new Promise((r) => setTimeout(r, 1100));
+ const second = await issueTokens();
+ expect(await authenticateBearer(first.access_token, { audience: RESOURCE })).toBeNull();
+ expect(await authenticateBearer(second.access_token, { audience: RESOURCE })).not.toBeNull();
+ });
+
+ it('leaves other apps on the account working', async () => {
+ seedClient();
+ const { access_token } = await issueTokens();
+ await call('grants', { method: 'DELETE', query: { client_id: 'mcp_other' } });
+ expect(await authenticateBearer(access_token, { audience: RESOURCE })).not.toBeNull();
+ });
+});
+
describe('POST /oauth/introspect', () => {
it('reports an access token as active with its scope and subject', async () => {
seedClient();