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(keys): add a "For an AI agent" API key that can never spend, enforced on every MCP server
nirholasd551023c2829
diff --git a/api/_lib/api-keys.js b/api/_lib/api-keys.jsindex d04b2e932..73f0790f9 100644--- a/api/_lib/api-keys.js+++ b/api/_lib/api-keys.js@@ -6,6 +6,7 @@import { sql } from './db.js';import { randomToken, sha256 } from './crypto.js';import { logAudit } from './audit.js';+import { CONNECTOR_KEY_SCOPES, CONNECTOR_MARKER } from './spend-scope.js';// The wallet and services scopes gate the agent-wallet MCP server// (api/mcp-agent). A key carrying them is bounded exactly like an OAuth token@@ -42,6 +43,20 @@ export function normalizeKeyScopes(scope) {return { scopes, invalid: scopes.filter((s) => !ALLOWED.has(s)) };}+// Named presets a key can be created from. A preset fixes the scope set on+// the server, so no request body can widen it. `connector` is the key for an+// AI agent that holds it unattended (Grok Bot, schedules, CI): it reads,+// generates and edits agent data and never spends, and its marker makes+// authenticateBearer() cap it to that set for as long as it lives.+export const KEY_PRESETS = Object.freeze({+ connector: Object.freeze([...CONNECTOR_KEY_SCOPES, CONNECTOR_MARKER]),+});++/** The scope list for a named preset, or null for an unknown name. */+export function presetScopes(preset) {+ return Object.hasOwn(KEY_PRESETS, preset) ? [...KEY_PRESETS[preset]] : null;+}+/*** Insert a new API key and return its row plus the plaintext secret. The secret* is never stored; only its sha256 is. Callers validate scopes first.diff --git a/api/_lib/auth.js b/api/_lib/auth.jsindex 322d65fb3..c56de420d 100644--- a/api/_lib/auth.js+++ b/api/_lib/auth.js@@ -8,6 +8,7 @@ import { logAudit } from './audit.js';import { randomToken, sha256, hmacSha256, constantTimeEquals } from './crypto.js';import { recordDailyActivity } from './streaks.js';import { clientIp } from './rate-limit.js';+import { capConnectorScope } from './spend-scope.js';const ACCESS_TTL_SEC = 60 * 60; // 1h access tokensconst REFRESH_TTL_SEC = 60 * 60 * 24 * 30; // 30d refresh tokens@@ -332,7 +333,9 @@ export async function authenticateBearer(token, { audience } = {}) {if (!row || row.revoked_at) return null;if (row.expires_at && new Date(row.expires_at) < new Date()) return null;await sql`update api_keys set last_used_at = now() where id = ${row.id}`;- return { userId: row.user_id, scope: row.scope, source: 'apikey', apiKeyId: row.id };+ // A connector key's power is capped here, on every request, rather than+ // trusted from the stored string (api/_lib/spend-scope.js).+ return { userId: row.user_id, scope: capConnectorScope(row.scope), source: 'apikey', apiKeyId: row.id };}// Otherwise treat as JWT access token.let payload;diff --git a/api/_lib/spend-scope.js b/api/_lib/spend-scope.jsindex afc10f039..dc616d65a 100644--- a/api/_lib/spend-scope.js+++ b/api/_lib/spend-scope.js@@ -13,8 +13,61 @@// The scope a bearer principal must hold to move, commit, or redirect funds.export const SPEND_SCOPE = 'wallet:write';+// Where a person goes to do in a browser what a key was refused.+export const SPEND_BROWSER_URL = 'https://three.ws/dashboard';+export const SCOPES_DOCS_URL = 'https://three.ws/docs/mcp#api-key-scopes';++// Connector keys: the API key preset for an AI agent that holds the key+// unattended (Grok Bot as a Bot secret, a schedule, CI). It reads, generates,+// and edits agent data, and can never spend. The marker token rides in the+// key's stored scope string, and capConnectorScope() is applied every time+// the key authenticates, so the cap holds even if the stored string is ever+// edited to name a spend scope: there is no path from a connector key to+// wallet:write short of minting a different key in a browser.+export const CONNECTOR_MARKER = 'connector';+export const CONNECTOR_KEY_SCOPES = Object.freeze([+ 'avatars:read',+ 'avatars:write',+ 'agents:read',+ 'agents:write',+ 'memory:read',+ 'memory:write',+]);+const CONNECTOR_ALLOWED = new Set(CONNECTOR_KEY_SCOPES);++function tokens(scope) {+ return String(scope || '').split(/\s+/).filter(Boolean);+}+function grants(scope, required) {- return String(scope || '').split(/\s+/).filter(Boolean).includes(required);+ return tokens(scope).includes(required);+}++/** True when a stored or effective scope string belongs to a connector key. */+export function isConnectorScope(scope) {+ return grants(scope, CONNECTOR_MARKER);+}++/**+ * The effective scope of a stored API key scope string. A standard key keeps+ * exactly what it was granted. A connector key keeps only the connector set+ * (plus its marker), whatever the stored string says.+ */+export function capConnectorScope(scope) {+ const list = tokens(scope);+ if (!list.includes(CONNECTOR_MARKER)) return String(scope || '');+ return [...new Set(list.filter((s) => CONNECTOR_ALLOWED.has(s))), CONNECTOR_MARKER].join(' ');+}++/**+ * The sentence a refused bearer reads: what it cannot do, why, and where a+ * person does it instead. Shared by the HTTP routes and every MCP server.+ */+export function spendRefusalMessage(scope, { action = 'This action', required = SPEND_SCOPE } = {}) {+ if (isConnectorScope(scope)) {+ return `${action} moves or routes funds, so it needs a browser session on three.ws. Connector keys read, generate and edit agent data and can never spend. Sign in at ${SPEND_BROWSER_URL} to do it yourself.`;+ }+ return `${action} moves or routes funds and this credential lacks the ${required} scope. Do it from a browser session at ${SPEND_BROWSER_URL}, or use a key or app grant that carries ${required}.`;}// Gate for a route that spends from a custodial wallet (withdraw, trade, pay,@@ -28,7 +81,7 @@ export function assertBearerMaySpend(bearer, req) {if (verb === 'GET' || verb === 'HEAD' || verb === 'OPTIONS') return bearer;if (grants(bearer.scope, SPEND_SCOPE)) return bearer;throw Object.assign(- new Error(`this credential lacks the ${SPEND_SCOPE} scope required to move funds`),+ new Error(spendRefusalMessage(bearer.scope)),{ status: 403, code: 'insufficient_scope', expose: true },);}diff --git a/api/_mcp/policy.js b/api/_mcp/policy.jsindex 6d5345bc1..cfdbbbbf7 100644--- a/api/_mcp/policy.js+++ b/api/_mcp/policy.js@@ -16,11 +16,12 @@// Every dispatcher calls the same three functions: listForRequest on// tools/list, gateCall before a handler runs, finishCall after it returns.-import { createPolicy, resolveEnablement, describeEnablement } from '@three-ws/mcp-policy';+import { createPolicy, resolveEnablement, describeEnablement, POLICY } from '@three-ws/mcp-policy';import { cacheDel, cacheGetFresh, cacheSet } from '../_lib/cache.js';import { sql } from '../_lib/db.js';import { logger } from '../_lib/usage.js';+import { SCOPES_DOCS_URL, SPEND_BROWSER_URL, SPEND_SCOPE, isConnectorScope, spendRefusalMessage } from '../_lib/spend-scope.js';const log = logger('mcp-policy');const PREVIEW_KEY = (id) => `mcp:preview:${id}`;@@ -139,12 +140,107 @@ export async function listForRequest(serverId, catalog, auth, req) {return policyFor(serverId).listTools(catalog, await enablementFor(req, auth));}+// ── The spend gate ──────────────────────────────────────────────────────────+//+// Design rule for cloud connectors: a key or token an agent holds unattended+// can read, generate and edit agent data, and never move funds. Every hosted+// server passes through gateCall, so the rule is enforced once, here, keyed by+// the policy table rather than by each handler remembering its own check.+//+// A tool is value-moving when the table puts it in the financial tier behind a+// confirm flag that names a money consequence (deletes and `confirm_run` acts+// on a house move no money and are left to their own scopes), or when it is a+// write-tier tool that commits or routes funds (SPEND_WRITE_TOOLS).+// tests/mcp-spend-gate.test.js walks every hosted catalog and fails when a tool+// that declares a spend scope is not classified here.++const VALUE_FLAGS = new Set([+ 'confirm_swap',+ 'confirm_transfer',+ 'confirm_launch',+ 'confirm_spend',+ 'confirm_payment',+ 'confirm_deposit',+ 'confirm_withdraw',+ 'confirm_bid',+ 'confirm_send',+ 'confirm_listing',+ 'confirm_delist',+ 'confirm_accept',+ 'confirm_trade',+ 'confirm_reveal',+ 'confirm_cancel',+]);++// Write-tier tools that need a spend grant: card quotes and secrets, wallet+// provisioning (the custodial address funds are routed to, and a devnet+// airdrop), and publishing a paid endpoint, which decides where its earnings+// go. Value: the scope the tool requires. A write tool that moves nothing+// (predictions_watch) keeps its own handler check and stays out of this list.+export const SPEND_WRITE_TOOLS = Object.freeze({+ 'three.ws': Object.freeze({+ agent_card_quote: SPEND_SCOPE,+ agent_card_data: SPEND_SCOPE,+ agent_card_connect_link: SPEND_SCOPE,+ }),+ 'threews-agent': Object.freeze({+ provision_wallet: SPEND_SCOPE,+ monetize_endpoint: 'services:write',+ }),+});++/**+ * The scope a hosted tool needs because it moves value, or null when it moves+ * none. Financial value-moving tools need `wallet:write`.+ */+export function spendScopeFor(serverId, name) {+ const extra = SPEND_WRITE_TOOLS[serverId];+ if (extra && Object.hasOwn(extra, name)) return extra[name];+ const entry = POLICY[serverId]?.[name];+ if (entry?.tier === 'financial' && VALUE_FLAGS.has(entry.confirmFlag)) return SPEND_SCOPE;+ return null;+}++function holds(scope, required) {+ return String(scope || '').split(/\s+/).includes(required);+}++/** JSON-RPC error code for "this credential may not move funds". */+export const SPEND_REFUSED_CODE = -32003;++/**+ * Refuse a value-moving call from an account-bound bearer that lacks the+ * spend scope, before enablement or previews are consulted: turning the tool+ * on in settings cannot help a key that may never spend, so the caller is told+ * the one thing that does. Anonymous principals (free, x402) hold no account+ * funds and fall through to the handlers' own ownership checks.+ * Throws a JSON-RPC error every dispatcher renders as-is.+ */+export function assertMaySpend(serverId, name, auth) {+ const required = spendScopeFor(serverId, name);+ if (!required || !auth?.userId || holds(auth.scope, required)) return;+ const connector = isConnectorScope(auth.scope);+ const err = new Error(spendRefusalMessage(auth.scope, { action: name, required }));+ err.code = SPEND_REFUSED_CODE;+ err.data = {+ reason: connector ? 'connector_key_cannot_spend' : 'spend_scope_required',+ tool: name,+ required_scope: required,+ needs: 'browser_session',+ url: SPEND_BROWSER_URL,+ docs: SCOPES_DOCS_URL,+ };+ throw err;+}+/*** Gate one tools/call. Returns { ok: false, result } with a designed refusal,* or { ok: true, args, preview } with the arguments to pass the handler.+ * Throws the spend refusal (assertMaySpend) as a JSON-RPC error.* @param {string[]} ownArgs argument names the tool's own schema declares*/export async function gateCall(serverId, name, args, auth, req, ownArgs = []) {+ assertMaySpend(serverId, name, auth);const en = await enablementFor(req, auth);return policyFor(serverId).beforeCall({ name, args, en, principal: principalOf(auth), ownArgs });}diff --git a/api/keys/index.js b/api/keys/index.jsindex 9e105d52e..4dce0dd6e 100644--- a/api/keys/index.js+++ b/api/keys/index.js@@ -1,10 +1,12 @@// Developer API key management.// GET /api/keys list caller's keys (hashed, no secret)-// POST /api/keys create a new key; returns the plaintext secret ONCE+// POST /api/keys create a new key; returns the plaintext secret ONCE.+// `preset: "connector"` issues the AI-agent key that+// can never spend (api/_lib/api-keys.js KEY_PRESETS).import { sql } from '../_lib/db.js';import { getSessionUser } from '../_lib/auth.js';-import { normalizeKeyScopes, mintApiKey } from '../_lib/api-keys.js';+import { normalizeKeyScopes, mintApiKey, presetScopes } from '../_lib/api-keys.js';import { cors, json, method, readJson, wrap, error, rateLimited } from '../_lib/http.js';import { requireCsrf } from '../_lib/csrf.js';import { limits } from '../_lib/rate-limit.js';@@ -18,6 +20,8 @@ const createSchema = z.object({.optional().default('avatars:read avatars:write').transform((s) => s.trim()),+ // A named preset replaces `scope` entirely; see KEY_PRESETS.+ preset: z.enum(['connector']).optional(),expires_in_days: z.number().int().positive().max(3650).optional(),environment: z.enum(['live', 'test']).default('live'),});@@ -49,9 +53,12 @@ export default wrap(async (req, res) => {const body = parse(createSchema, await readJson(req));+ // A preset ignores `scope` rather than merging it, so a connector key can+ // never be asked into carrying a spend scope.+ const preset = body.preset ? presetScopes(body.preset) : null;// Dedupe so "avatars:read avatars:read" stores one grant, not two: the stored// string is rendered verbatim as scope chips in the dashboard key table.- const { scopes: requestedScopes, invalid } = normalizeKeyScopes(body.scope);+ const { scopes: requestedScopes, invalid } = preset ? { scopes: preset, invalid: [] } : normalizeKeyScopes(body.scope);if (invalid.length)return error(res, 400, 'validation_error', `unknown scopes: ${invalid.join(', ')}`);// zod's .default() only fires on an absent field, so an explicit "" or " "@@ -74,6 +81,7 @@ export default wrap(async (req, res) => {expiresAt: expires,environment: body.environment,req,+ via: body.preset ? `dashboard:${body.preset}` : 'dashboard',});return json(res, 201, { key: { ...row, secret } });});diff --git a/docs/api-reference.md b/docs/api-reference.mdindex c81eade39..2a30048c9 100644--- a/docs/api-reference.md+++ b/docs/api-reference.md@@ -22,9 +22,11 @@ Authorization: Bearer sk_live_xxxxxSession cookies (set after SIWE or Privy login) are accepted on all endpoints that support Bearer auth.-**API keys.** Create one at [Dashboard → API](https://three.ws/dashboard/api). A key starts with `sk_live_` and is shown exactly once: three.ws stores only its SHA-256 hash plus the first 14 characters as a visible prefix, so a lost key cannot be recovered, only replaced. Each key carries the scopes you chose when you made it, and a call outside them fails with `insufficient_scope`. Revoking a key takes effect on the next request, because keys are checked against the database on every call. Keep keys server-side; never ship one in a browser or mobile bundle.+**API keys.** Create one at [Dashboard → API](https://three.ws/dashboard/api). A key starts with `sk_live_` and is shown exactly once: three.ws stores only its SHA-256 hash plus the first 14 characters as a visible prefix, so a lost key cannot be recovered, only replaced. Each key carries the scopes you chose when you made it ([the scope table](#scopes)), and a call outside them fails with `insufficient_scope`. Revoking a key takes effect on the next request, because keys are checked against the database on every call. Keep keys server-side; never ship one in a browser or mobile bundle.-**OAuth tokens.** MCP clients and the [CLI](/docs/cli) sign in with OAuth instead of a key. Access tokens last one hour and refresh automatically. Revoking a client under [Dashboard → Settings → Connected apps](https://three.ws/dashboard/settings) stops its refresh token at once, so the client loses access when its current access token expires, within the hour.+**OAuth tokens.** MCP clients and the [CLI](/docs/cli) sign in with OAuth instead of a key. Access tokens last one hour and refresh automatically. Revoking a client under [Dashboard → Settings → Connected apps](https://three.ws/dashboard/settings) takes effect on its next request: its access and refresh tokens are refused from that moment.++**Keys for AI agents.** A key an agent holds unattended should be a connector key, which reads, generates and edits agent data and can never spend. See [Keys for AI agents](#keys-for-ai-agents-the-connector-preset).### Response format@@ -4251,82 +4253,118 @@ Authentication is covered in detail in the [Authentication documentation](authen## API Keys API-### List API keys+Two routes manage keys. `/api/keys` is what [Dashboard → API](https://three.ws/dashboard/api) uses and accepts only a signed-in browser session. `/api/api-keys` also accepts a bearer credential that holds the `profile` scope, and such a bearer can only mint a key at or below its own grant. Both store the SHA-256 of the secret, never the secret itself.++### Scopes++Each key carries a space-separated scope string. A call outside it fails with `insufficient_scope`.++| Scope | What it allows |+| --- | --- |+| `avatars:read` | List, fetch and stream your avatars |+| `avatars:write` | Create, generate and modify avatars |+| `avatars:delete` | Permanently remove avatars |+| `profile` | Read the signed-in user record, and manage keys through `/api/api-keys` |+| `memory:read` | Recall your agents' stored memories |+| `memory:write` | Store and forget agent memories |+| `agents:read` | Read your agents and their identities |+| `agents:write` | Create, update and register agents |+| `herald:announce` | Post announcements through the Herald |+| `wallet:read` | See agent wallet balances, history and spending caps |+| `wallet:write` | **Spend.** Pay, send, trade, withdraw, launch, bid and buy from an agent wallet, within your caps |+| `services:write` | Publish paid services whose earnings go to your agent wallet |+| `inference` | Call the OpenAI-compatible `/api/v1/chat/completions`, billed to your credits |++`wallet:write` is the one scope that moves money. Every route and MCP tool that pays, sends, trades, withdraws, launches, places an order, issues a spending mandate or changes where funds go refuses a bearer without it with `403 insufficient_scope` (MCP: JSON-RPC error `-32003`). A browser session is the account holder and needs no scope.++### Keys for AI agents (the connector preset)++An agent that holds a key unattended (Grok Bot storing it as a Bot secret, a schedule, a CI job) should get a **connector key**: in the dashboard choose **For an AI agent (Grok Bot, schedules, CI)**, or send `preset: "connector"`. The server fixes its scopes:```-GET /api/api-keys+avatars:read avatars:write agents:read agents:write memory:read memory:write connector```-Requires auth. Returns all API keys for the current user. Plaintext key values are never returned after creation.+The trailing `connector` marks the key's kind. It is not something you can request as a raw scope, and it caps the key every time it authenticates: whatever its stored scope string says, a connector key only ever acts with the six scopes above, so it can read, generate and edit agent data and can never spend. A connector key that calls a value-moving route or tool gets an answer that says so and links back to three.ws, where a person approves the action in a browser:-**Response**+```json+{ "error": "insufficient_scope", "error_description": "This action moves or routes funds, so it needs a browser session on three.ws. Connector keys read, generate and edit agent data and can never spend. Sign in at https://three.ws/dashboard to do it yourself." }+```++Keys made before the preset existed are unchanged: they keep exactly the scopes they were minted with.++### List API keys++```+GET /api/keys+```++Browser session only. Returns every key the account has made, revoked and expired ones included, so the dashboard can label them. No secret material is ever returned.```json{"keys": [{- "id": "key_abc",- "name": "My Integration",- "scopes": ["avatars:read", "avatars:write"],- "created_at": "2025-01-15T10:00:00Z",- "last_used_at": "2025-01-20T08:30:00Z"+ "id": "2c25ec0c-f1a3-475d-9a9f-fe926c832db5",+ "name": "Grok Bot",+ "prefix": "sk_live_Xb3Q",+ "scope": "avatars:read avatars:write agents:read agents:write memory:read memory:write connector",+ "last_used_at": "2026-10-08T08:30:00.000Z",+ "expires_at": null,+ "revoked_at": null,+ "created_at": "2026-10-08T07:00:00.000Z"}]}```+`GET /api/api-keys` returns the live keys only, as `{ "data": [...] }`, to a session or a `profile` bearer.+---### Create API key```-POST /api/api-keys+POST /api/keys```-Requires auth.--**Request body**+Browser session only, with the `X-CSRF-Token` header.```json-{- "name": "My Integration",- "scopes": ["avatars:read", "avatars:write"]-}+{ "name": "Production server", "scope": "avatars:read avatars:write", "expires_in_days": 90, "environment": "live" }```-**Available scopes**+or, for an AI agent:++```json+{ "name": "Grok Bot", "preset": "connector" }+```-| Scope | Description |-| ---------------- | ------------------------------------ |-| `avatars:read` | Read agents and avatars |-| `avatars:write` | Create and update agents and avatars |-| `avatars:delete` | Delete agents and avatars |-| `profile` | Read user profile data |+| Field | Notes |+| --- | --- |+| `name` | Required, 1 to 80 characters |+| `scope` | Space-separated scopes from the table above. Defaults to `avatars:read avatars:write`. Ignored when `preset` is sent |+| `preset` | `connector` issues the AI-agent key described above |+| `expires_in_days` | Optional, 1 to 3650 |+| `environment` | `live` (default) or `test`, which sets the `sk_live_` / `sk_test_` prefix |-**Response**+**Response** `201````json-{- "id": "key_abc",- "key": "sk_live_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"-}+{ "key": { "id": "2c25ec0c-…", "name": "Grok Bot", "prefix": "sk_live_Xb3Q", "scope": "avatars:read … connector", "expires_at": null, "created_at": "…", "secret": "sk_live_…" } }```-The plaintext `key` is returned **only once** at creation time. Store it immediately — it cannot be retrieved again.--Keys use the format `sk_live_` + 32 random characters.+The `secret` is returned **only once**. Store it immediately; it cannot be retrieved, only replaced. `POST /api/api-keys` takes `{ name, scope, expires_at }` and answers `{ "data": { ..., "token": "sk_live_…" } }`.---### Revoke API key```-DELETE /api/api-keys/:id+DELETE /api/keys/:id```-Requires auth. Permanently revokes the key.--**Response:** `{ "ok": true }`+Browser session only, with the `X-CSRF-Token` header. Revocation takes effect on the key's next request. **Response:** `{ "ok": true }`. `DELETE /api/api-keys/:id` does the same for a session or a `profile` bearer and answers `{ "data": { "id": "…", "revoked": true } }`.---diff --git a/docs/grok.md b/docs/grok.mdindex a358444c6..33e6ec4fb 100644--- a/docs/grok.md+++ b/docs/grok.md@@ -35,6 +35,22 @@ in any task, or attach the server with `@three-ws`:Grok Bot works on its own cloud computer, so it can save the GLB to its files,hand it to another tool in the same task, or run the request on a schedule.+## Your account with a connector key++The free server above needs no account. To let Grok Bot work with **your**+avatars, agents and their memory (on a schedule, say), connect it to the core+server with a connector key:++1. At [three.ws/dashboard/api](/dashboard/api) choose **New key**, then **For an AI agent (Grok Bot, schedules, CI)**, name it, and copy the key it shows once.+2. Ask Grok Bot to add a custom MCP server at `https://three.ws/api/mcp` with API key authentication, and store the key as a Bot secret.++A connector key reads, generates and edits agent data and can never spend.+If a task reaches anything that pays, sends, trades or launches, the server+answers with a JSON-RPC error that says the action needs a browser session on+three.ws and links there, so Grok Bot can tell you instead of retrying. Revoke+the key from the same page at any time; it stops on its next request. Scopes+and the exact error: [API key scopes](./mcp.md#api-key-scopes).+## Grok connectorsOn paid Grok plans, custom connectors take a remote MCP URL (remote serversdiff --git a/docs/mcp.md b/docs/mcp.mdindex 9bf917f6b..2e12e3868 100644--- a/docs/mcp.md+++ b/docs/mcp.md@@ -227,6 +227,35 @@ curl -X POST https://three.ws/api/mcp \Keys are tied to a single user account and inherit that user's plan quotas.+### API key scopes++A key acts only within the scopes it was minted with ([the full table](./api-reference.md#scopes)). Generation, avatars and agent data need `avatars:*`, `agents:*` and `memory:*`. `wallet:write` is the one scope that moves money, and `services:write` publishes a paid endpoint whose earnings go to your agent wallet.++**For an AI agent, make a connector key.** At [/dashboard/api](https://three.ws/dashboard/api) choose **New key**, then **For an AI agent (Grok Bot, schedules, CI)**. The key gets `avatars:read avatars:write agents:read agents:write memory:read memory:write` and is marked as a connector, which caps it on every request: it can read, generate and edit agent data and can never spend, and no later change to its stored scopes can give it `wallet:write`. Use it wherever a key is held unattended: a Grok Bot secret, a cron job, CI. The same key over the API: `POST /api/keys` with `{"name": "Grok Bot", "preset": "connector"}` ([API reference](./api-reference.md#keys-for-ai-agents-the-connector-preset)).++**What a key without the spend scope gets.** Every hosted server checks one table before a tool runs (`gateCall` in `api/_mcp/policy.js`). A tool that pays, sends, trades, bids, lists, launches, reveals a card, provisions a wallet or publishes a paid endpoint answers a key that lacks the scope with a JSON-RPC error, not a tool result, so a model cannot mistake it for a transient failure:++```json+{+ "jsonrpc": "2.0",+ "id": 7,+ "error": {+ "code": -32003,+ "message": "pay_and_call moves or routes funds, so it needs a browser session on three.ws. Connector keys read, generate and edit agent data and can never spend. Sign in at https://three.ws/dashboard to do it yourself.",+ "data": {+ "reason": "connector_key_cannot_spend",+ "tool": "pay_and_call",+ "required_scope": "wallet:write",+ "needs": "browser_session",+ "url": "https://three.ws/dashboard",+ "docs": "https://three.ws/docs/mcp#api-key-scopes"+ }+ }+}+```++A standard key that simply was not given the scope gets `reason: "spend_scope_required"` and a message naming the scope it lacks. The check runs before tool enablement, so turning a financial tool on in [tool settings](https://three.ws/settings/mcp-tools) does not let a connector key reach it. The REST routes behind the same actions answer `403 insufficient_scope` with the same sentence. Keys minted before connector keys existed keep exactly the scopes they had.+---## Connecting Claude Code@@ -299,14 +328,14 @@ The probe reads its server list from [`/.well-known/mcp.json`](../public/.well-k| Core | `https://three.ws/api/mcp` | Streamable HTTP | API key, OAuth 2.1 | Transport: Streamable HTTP. URL: `https://three.ws/api/mcp`. Authentication: API key or OAuth 2.1 || 3D Studio | `https://three.ws/api/mcp-3d` | Streamable HTTP | API key, OAuth 2.1 | Transport: Streamable HTTP. URL: `https://three.ws/api/mcp-3d`. Authentication: API key or OAuth 2.1 || 3D Studio (free) | `https://three.ws/api/mcp-studio` | Streamable HTTP | None | Transport: Streamable HTTP. URL: `https://three.ws/api/mcp-studio`. Authentication: None |-| Agent wallet | `https://three.ws/api/mcp-agent` | Streamable HTTP | API key (read-only scopes), OAuth 2.1 | Transport: Streamable HTTP. URL: `https://three.ws/api/mcp-agent`. Authentication: API key without `wallet:write` |+| Agent wallet | `https://three.ws/api/mcp-agent` | Streamable HTTP | API key (read-only scopes), OAuth 2.1 | Transport: Streamable HTTP. URL: `https://three.ws/api/mcp-agent`. Authentication: connector key (browses and quotes; spending answers with a link to three.ws) || x402 Bazaar | `https://three.ws/api/mcp-bazaar` | Streamable HTTP | API key, OAuth 2.1 | Transport: Streamable HTTP. URL: `https://three.ws/api/mcp-bazaar`. Authentication: API key or OAuth 2.1 || pump.fun | `https://three.ws/api/pump-fun-mcp` | Streamable HTTP | None (read-only tools), API key | Transport: Streamable HTTP. URL: `https://three.ws/api/pump-fun-mcp`. Authentication: None || IBM x402 | `https://three.ws/api/ibm-mcp` | Streamable HTTP | API key, OAuth 2.1 | Transport: Streamable HTTP. URL: `https://three.ws/api/ibm-mcp`. Authentication: API key or OAuth 2.1 |Notes for connector setup:-- **API key.** Create one at [/dashboard/api](https://three.ws/dashboard/api) and store it as the connector's secret. It is sent as `Authorization: Bearer sk_live_…`; if the connector asks for a header name, use `Authorization` with the value `Bearer sk_live_…`. A cloud agent holds this key unattended, so give it only the scopes it needs (`avatars:read avatars:write profile agents:read memory:read` covers generation, avatars and agent data) and never `wallet:write`: spending stays a same-site action you confirm yourself.+- **API key.** Create a connector key at [/dashboard/api](https://three.ws/dashboard/api) (**New key**, then **For an AI agent**) and store it as the connector's secret. It is sent as `Authorization: Bearer sk_live_…`; if the connector asks for a header name, use `Authorization` with the value `Bearer sk_live_…`. A cloud agent holds this key unattended, and a connector key covers generation, avatars and agent data while never being able to spend: anything that moves funds answers with a link back to three.ws, where you confirm it yourself ([API key scopes](#api-key-scopes)).- **OAuth 2.1.** The connector registers itself through dynamic client registration (RFC 7591), so there is no client ID to create; you approve the consent screen once and it refreshes the token on its own. PKCE S256 is required and advertised.- **x402 pay-per-call** is not an unattended connector mode: every paid call needs a signed payment, which a connector cannot make on your behalf.- **The URL must be public.** Grok Bot connects from xAI's cloud, so `localhost` never works; use the `https://three.ws` URLs above.diff --git a/src/dashboard-next/pages/api.js b/src/dashboard-next/pages/api.jsindex eb1d0ecc7..a4e98b6cc 100644--- a/src/dashboard-next/pages/api.js+++ b/src/dashboard-next/pages/api.js@@ -40,6 +40,13 @@ const SCOPES = [{ value: 'inference', label: 'inference', note: 'Call the OpenAI-compatible /api/v1 endpoint, billed to your credits' },];+// The "For an AI agent" preset: match KEY_PRESETS.connector in+// api/_lib/api-keys.js. The server fixes the scope set from the preset name, so+// this list only explains it; nothing the page sends can widen it.+const CONNECTOR_MARKER = 'connector';+const CONNECTOR_SCOPES = ['avatars:read', 'avatars:write', 'agents:read', 'agents:write', 'memory:read', 'memory:write'];+const CONNECTOR_NEVER = ['wallet:write', 'services:write', 'inference', 'profile'];+const EXPIRY_OPTIONS = [{ label: 'Never', days: null },{ label: '30 days', days: 30 },@@ -539,7 +546,7 @@ export function renderKeysTable(keys) {</td><td><div class="dn-chip-row">- ${(k.scope || '').split(/\s+/).filter(Boolean).map((s) => `<span class="dn-tag">${esc(s)}</span>`).join('')}+ ${renderScopeChips(k.scope)}</div></td><td><span class="dn-dim">${esc(relTime(k.created_at))}</span></td>@@ -558,6 +565,21 @@ export function renderKeysTable(keys) {`;}+// A connector key's marker renders as one badge, not a scope chip: it is the+// key's kind, and the page should say what that kind can never do.+export function isConnectorKey(k) {+ return String(k?.scope || '').split(/\s+/).includes(CONNECTOR_MARKER);+}++export function renderScopeChips(scope) {+ const list = String(scope || '').split(/\s+/).filter(Boolean);+ const connector = list.includes(CONNECTOR_MARKER);+ const badge = connector+ ? '<span class="dn-tag dn-tag-agent" title="Made for an AI agent that holds it unattended. It reads, generates and edits agent data and can never spend.">AI agent · cannot spend</span>'+ : '';+ return badge + list.filter((s) => s !== CONNECTOR_MARKER).map((s) => `<span class="dn-tag">${esc(s)}</span>`).join('');+}+function openNewKeyModal(state) {const { close, el } = openModal(`<form data-form="new-key">@@ -570,6 +592,32 @@ function openNewKeyModal(state) {<input data-autofocus name="name" type="text" placeholder="e.g. Production server" required maxlength="80" /></label><fieldset class="dn-field">+ <legend>What is this key for?</legend>+ <div class="dn-presets" role="radiogroup">+ <label class="dn-preset">+ <input type="radio" name="preset" value="custom" checked />+ <span class="dn-preset-body">+ <span class="dn-preset-title">Custom scopes</span>+ <span class="dn-preset-note">Your own server or script. Pick exactly what it may do.</span>+ </span>+ </label>+ <label class="dn-preset">+ <input type="radio" name="preset" value="connector" />+ <span class="dn-preset-body">+ <span class="dn-preset-title">For an AI agent <span class="dn-preset-eg">Grok Bot, schedules, CI</span></span>+ <span class="dn-preset-note">Reads, generates and edits agent data. Can never spend.</span>+ </span>+ </label>+ </div>+ </fieldset>+ <div class="dn-field" data-slot="connector-scopes" hidden>+ <span>Scopes</span>+ <div class="dn-scopes dn-scopes-locked">+ <div class="dn-chip-row">${CONNECTOR_SCOPES.map((s) => `<span class="dn-tag">${esc(s)}</span>`).join('')}</div>+ <p class="dn-scope-note">Never included, and a key made this way can never gain them: ${CONNECTOR_NEVER.map((s) => `<code>${esc(s)}</code>`).join(', ')}. Paying, sending, trading and launching stay in your browser session on three.ws, where you confirm each one. <a class="dn-link" href="/docs/mcp#api-key-scopes" target="_blank" rel="noopener">How scopes work</a></p>+ </div>+ </div>+ <fieldset class="dn-field" data-slot="custom-scopes"><legend>Scopes</legend><div class="dn-scopes">${SCOPES.map((s) => `@@ -600,6 +648,21 @@ function openNewKeyModal(state) {const form = el.querySelector('form');const errSlot = form.querySelector('[data-slot="error"]');const submitBtn = form.querySelector('[data-submit]');+ const nameInput = form.querySelector('input[name="name"]');+ const customSlot = form.querySelector('[data-slot="custom-scopes"]');+ const connectorSlot = form.querySelector('[data-slot="connector-scopes"]');++ const presetOf = () => (form.querySelector('input[name="preset"]:checked')?.value === 'connector' ? 'connector' : 'custom');+ const syncPreset = () => {+ const connector = presetOf() === 'connector';+ customSlot.hidden = connector;+ connectorSlot.hidden = !connector;+ // Hidden checkboxes still submit; disabling them keeps the form honest.+ customSlot.querySelectorAll('input').forEach((i) => { i.disabled = connector; });+ nameInput.placeholder = connector ? 'e.g. Grok Bot' : 'e.g. Production server';+ errSlot.hidden = true;+ };+ form.querySelectorAll('input[name="preset"]').forEach((r) => r.addEventListener('change', syncPreset));form.addEventListener('submit', async (e) => {e.preventDefault();@@ -607,15 +670,18 @@ function openNewKeyModal(state) {errSlot.textContent = '';const fd = new FormData(form);const name = String(fd.get('name') || '').trim();+ const preset = presetOf();const scopes = fd.getAll('scope');const expiryIdx = parseInt(String(fd.get('expiry') ?? '0'), 10);if (!name) { errSlot.textContent = 'Name is required.'; errSlot.hidden = false; return; }- if (!scopes.length) { errSlot.textContent = 'Pick at least one scope.'; errSlot.hidden = false; return; }+ if (preset === 'custom' && !scopes.length) { errSlot.textContent = 'Pick at least one scope.'; errSlot.hidden = false; return; }submitBtn.disabled = true;submitBtn.textContent = 'Creating…';try {- const payload = { name, scope: scopes.join(' '), environment: 'live' };+ const payload = preset === 'connector'+ ? { name, preset: 'connector', environment: 'live' }+ : { name, scope: scopes.join(' '), environment: 'live' };const days = EXPIRY_OPTIONS[expiryIdx]?.days;if (days) payload.expires_in_days = days;const resp = await post('/api/keys', payload);@@ -650,12 +716,17 @@ function openKeyRevealModal(key) {</div><div class="dn-warn-banner"><strong>This is the only time you'll see this key.</strong>- Store it somewhere safe — we hash and discard the plaintext after this page closes.+ Store it somewhere safe. We hash and discard the plaintext after this page closes.</div><div class="dn-code-block"><pre><code data-secret>${esc(key.secret)}</code></pre><button type="button" class="dn-code-copy" data-copy aria-label="Copy secret API key">Copy</button></div>+ ${isConnectorKey(key) ? `+ <div class="dn-modal-block dn-agent-next">+ <div class="dn-modal-block-label">Give it to your agent</div>+ <p class="dn-modal-hint">Add a custom MCP server at <code>${esc(origin())}/api/mcp</code> and store this key as its API key (in Grok Bot, a Bot secret). The agent can then work with your avatars, agents and their memory on a schedule. Anything that moves funds answers with a link back to three.ws, where you approve it yourself. <a class="dn-link" href="/docs/grok#your-account-with-a-connector-key" target="_blank" rel="noopener">Grok Bot setup</a></p>+ </div>` : ''}<div class="dn-modal-foot"><button type="button" class="dn-btn primary" data-modal-close data-autofocus>I've saved it</button></div>@@ -1462,8 +1533,8 @@ function injectStyles() {.dn-policy-actions { display: flex; flex-direction: column; gap: 6px; align-items: stretch; }/* Modal */- .dn-modal-backdrop { position: fixed; inset: 0; background: rgba(5,6,12,0.7); backdrop-filter: blur(6px); display: grid; place-items: center; z-index: 200; padding: 24px; }- .dn-modal { background: linear-gradient(180deg, rgba(20,21,28,0.95), rgba(14,15,22,0.95)); border: 1px solid var(--nxt-stroke); border-radius: var(--nxt-radius); padding: 22px; width: 520px; max-width: 100%; max-height: 90vh; overflow-y: auto; box-shadow: 0 24px 60px rgba(0,0,0,0.5); }+ .dn-modal-backdrop { position: fixed; inset: 0; background: rgba(5,6,12,0.7); backdrop-filter: blur(6px); display: grid; place-items: center; grid-template-columns: minmax(0, 520px); justify-content: center; z-index: 200; padding: 24px 16px; }+ .dn-modal { background: linear-gradient(180deg, rgba(20,21,28,0.95), rgba(14,15,22,0.95)); border: 1px solid var(--nxt-stroke); border-radius: var(--nxt-radius); padding: 22px; width: 100%; max-height: 90vh; overflow-y: auto; box-shadow: 0 24px 60px rgba(0,0,0,0.5); }.dn-modal-head { display: flex; align-items: center; justify-content: space-between; gap: 16px; margin-bottom: 14px; }.dn-modal-head h2 { margin: 0; font-size: 17px; font-weight: 600; letter-spacing: -0.01em; }.dn-modal-body { font-size: 13.5px; color: var(--nxt-ink-dim); line-height: 1.6; }@@ -1474,12 +1545,31 @@ function injectStyles() {.dn-field > span, .dn-field > legend { font-weight: 500; }.dn-field input, .dn-field select { background: rgba(255,255,255,0.04); border: 1px solid var(--nxt-stroke); color: var(--nxt-ink); padding: 9px 11px; border-radius: var(--nxt-radius-sm); font-size: 13.5px; font-family: inherit; }.dn-field input:focus, .dn-field select:focus { outline: none; border-color: var(--nxt-accent); }+ fieldset.dn-field { border: 0; padding: 0; margin-inline: 0; min-width: 0; }+ fieldset.dn-field > legend { padding: 0; margin-bottom: 6px; }.dn-scopes { display: flex; flex-direction: column; gap: 10px; padding: 10px; border: 1px solid var(--nxt-stroke); border-radius: var(--nxt-radius-sm); background: rgba(255,255,255,0.02); }.dn-scope-row { display: flex; gap: 10px; align-items: flex-start; cursor: pointer; }.dn-scope-row input { margin-top: 3px; }.dn-scope-label { font-size: 13px; color: var(--nxt-ink); }.dn-scope-label code { font-family: 'JetBrains Mono', ui-monospace, monospace; font-size: 12px; }.dn-scope-note { font-size: 12px; color: var(--nxt-ink-fade); }+ .dn-scopes-locked { gap: 8px; }+ .dn-scopes-locked .dn-scope-note { margin: 0; line-height: 1.55; }+ .dn-scopes-locked code, .dn-agent-next code { font-family: 'JetBrains Mono', ui-monospace, monospace; font-size: 11.5px; padding: 1px 5px; background: rgba(255,255,255,0.06); border-radius: 4px; }+ .dn-presets { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 8px; }+ .dn-preset { display: flex; gap: 10px; align-items: flex-start; padding: 11px 12px; border: 1px solid var(--nxt-stroke); border-radius: var(--nxt-radius-sm); background: rgba(255,255,255,0.02); cursor: pointer; transition: border-color 0.12s ease, background 0.12s ease; }+ .dn-preset:hover { border-color: rgba(255,255,255,0.22); }+ .dn-preset:has(input:checked) { border-color: var(--nxt-accent); background: var(--nxt-accent-soft, rgba(255,255,255,0.06)); }+ .dn-preset:active { transform: translateY(1px); }+ .dn-field .dn-preset input, .dn-field .dn-scope-row input { padding: 0; background: none; border: 0; border-radius: 50%; margin: 3px 0 0; flex: none; accent-color: var(--nxt-accent); }+ .dn-field .dn-scope-row input { border-radius: 3px; }+ .dn-preset input:focus-visible { outline: 2px solid var(--nxt-accent); outline-offset: 2px; }+ .dn-preset-body { display: flex; flex-direction: column; gap: 3px; min-width: 0; }+ .dn-preset-title { font-size: 13px; font-weight: 500; color: var(--nxt-ink); }+ .dn-preset-eg { font-weight: 400; font-size: 11.5px; color: var(--nxt-ink-fade); white-space: nowrap; }+ .dn-preset-note { font-size: 12px; line-height: 1.45; color: var(--nxt-ink-fade); }+ .dn-tag-agent { border-color: var(--nxt-accent); color: var(--nxt-ink); }+ .dn-agent-next { margin-top: 14px; }.dn-warn-banner { padding: 12px 14px; border-radius: var(--nxt-radius-sm); background: rgba(168,173,181,0.08); border: 1px solid rgba(168,173,181,0.25); color: var(--nxt-warn); font-size: 13px; margin-bottom: 14px; line-height: 1.5; }.dn-warn-banner strong { color: var(--nxt-ink); display: block; margin-bottom: 4px; }.dn-error { padding: 10px 12px; border-radius: var(--nxt-radius-sm); background: rgba(150,155,163,0.1); border: 1px solid rgba(150,155,163,0.25); color: var(--nxt-danger); font-size: 13px; margin-bottom: 12px; }@@ -1508,7 +1598,8 @@ function injectStyles() {/* Honor reduced-motion: drop transforms and transitions, keep state changes instant */@media (prefers-reduced-motion: reduce) {.dn-toolkit-card, .dn-tab, .dn-code-copy, .dn-toolkit-cmd-copy,- .dn-toolkit-card-doc, .dn-toast { transition: none; }+ .dn-toolkit-card-doc, .dn-toast, .dn-preset { transition: none; }+ .dn-preset:active { transform: none; }.dn-toolkit-card:hover { transform: none; }}`;diff --git a/tests/api/keys-endpoint.test.js b/tests/api/keys-endpoint.test.jsindex 988628292..394a39944 100644--- a/tests/api/keys-endpoint.test.js+++ b/tests/api/keys-endpoint.test.js@@ -185,6 +185,40 @@ describe('POST /api/keys', () => {expect(sqlState.calls[0].values).toContain('avatars:read profile');});+ it('issues the AI-agent preset with its fixed scopes and no spend scope', async () => {+ sqlState.queue.push([{ id: KEY_ID, name: 'Grok Bot', prefix: 'sk_live_abcd', scope: '', expires_at: null, created_at: '2026-10-08T01:04:36.801Z' }]);+ const { status } = await invoke(keysHandler, {+ method: 'POST',+ url: '/api/keys',+ body: { name: 'Grok Bot', preset: 'connector' },+ });+ expect(status).toBe(201);+ expect(sqlState.calls[0].values).toContain('avatars:read avatars:write agents:read agents:write memory:read memory:write connector');+ const audit = auditState.entries.find((e) => e.action === 'create_api_key');+ expect(audit.meta.via).toBe('dashboard:connector');+ });++ it('ignores a scope sent alongside the preset, so a connector key cannot be asked into spending', async () => {+ sqlState.queue.push([{ id: KEY_ID, name: 'sneaky', prefix: 'sk_live_abcd', scope: '', expires_at: null, created_at: '2026-10-08T01:04:36.801Z' }]);+ await invoke(keysHandler, {+ method: 'POST',+ url: '/api/keys',+ body: { name: 'sneaky', preset: 'connector', scope: 'wallet:write services:write' },+ });+ const stored = sqlState.calls[0].values.find((v) => typeof v === 'string' && v.includes('connector'));+ expect(stored).not.toContain('wallet:write');+ expect(stored).not.toContain('services:write');+ });++ it('refuses the connector marker as a raw scope and an unknown preset', async () => {+ const raw = await invoke(keysHandler, { method: 'POST', url: '/api/keys', body: { name: 'raw', scope: 'avatars:read connector' } });+ expect(raw.status).toBe(400);+ expect(raw.body.error_description).toContain('connector');+ const unknown = await invoke(keysHandler, { method: 'POST', url: '/api/keys', body: { name: 'x', preset: 'admin' } });+ expect(unknown.status).toBe(400);+ expect(sqlState.calls).toHaveLength(0);+ });+it('rejects a missing name with a structured 400', async () => {const { status, body } = await invoke(keysHandler, {method: 'POST',diff --git a/tests/api/mcp-agent.test.js b/tests/api/mcp-agent.test.jsindex 92e7e992a..5f9ecdbdd 100644--- a/tests/api/mcp-agent.test.js+++ b/tests/api/mcp-agent.test.js@@ -320,21 +320,27 @@ describe('threews-agent MCP', () => {expect(r.result.structuredContent.reason).toBe('no_solana_wallet');});+ // The spend gate in api/_mcp/policy.js refuses before the handler runs, so+ // the answer is a JSON-RPC error naming the browser session, not a tool result.it('refuses to spend for a read-only token, before any payment call', async () => {const r = await quoteThenPay({ resource_url: 'https://paid.test/x' }, READONLY);expect(payer.payExternalX402).not.toHaveBeenCalled();- expect(r.result.isError).toBe(true);- expect(r.result.structuredContent).toMatchObject({- reason: 'insufficient_scope',- required: 'wallet:write',+ expect(r.result).toBeUndefined();+ expect(r.error.code).toBe(-32003);+ expect(r.error.data).toMatchObject({+ reason: 'spend_scope_required',+ required_scope: 'wallet:write',+ needs: 'browser_session',+ url: 'https://three.ws/dashboard',});});- it('still hands a read-only token the manual pay link when spend is off', async () => {+ it('refuses a read-only token at the spend gate even when spend is off', async () => {payerState.spendEnabled = false;const r = await quoteThenPay({ resource_url: 'https://paid.test/x' }, READONLY);- expect(r.result.structuredContent).toMatchObject({ paid: false, reason: 'spend_disabled' });- expect(r.result.structuredContent.pay_link).toContain('https://three.ws/pay?resource=');+ expect(payer.payExternalX402).not.toHaveBeenCalled();+ expect(r.error.code).toBe(-32003);+ expect(r.error.message).toContain('https://three.ws/dashboard');});it('rejects an out-of-range max_price_usdc as invalid params, not an internal error', async () => {diff --git a/tests/api/mcp-wallet-provision.test.js b/tests/api/mcp-wallet-provision.test.jsindex 680a2bd11..b01331658 100644--- a/tests/api/mcp-wallet-provision.test.js+++ b/tests/api/mcp-wallet-provision.test.js@@ -250,8 +250,8 @@ describe('agent-wallet MCP — provisioning + earning', () => {it('enforces the wallet:write scope', async () => {const r = await call('provision_wallet', { agent_id: AGENT_ID }, READONLY);- expect(r.result.isError).toBe(true);- expect(r.result.structuredContent).toMatchObject({ reason: 'insufficient_scope', required: 'wallet:write' });+ expect(r.error.code).toBe(-32003);+ expect(r.error.data).toMatchObject({ reason: 'spend_scope_required', required_scope: 'wallet:write' });});// ── monetize_endpoint ────────────────────────────────────────────────────────@@ -379,7 +379,7 @@ describe('agent-wallet MCP — provisioning + earning', () => {},READONLY,);- expect(r.result.isError).toBe(true);- expect(r.result.structuredContent).toMatchObject({ reason: 'insufficient_scope', required: 'services:write' });+ expect(r.error.code).toBe(-32003);+ expect(r.error.data).toMatchObject({ reason: 'spend_scope_required', required_scope: 'services:write' });});});diff --git a/tests/dashboard-api-keys-table.test.js b/tests/dashboard-api-keys-table.test.jsindex c87812433..8b0306ab3 100644--- a/tests/dashboard-api-keys-table.test.js+++ b/tests/dashboard-api-keys-table.test.js@@ -12,7 +12,7 @@import { describe, it, expect } from 'vitest';-const { keyStatus, renderKeysTable } = await import('../src/dashboard-next/pages/api.js');+const { keyStatus, renderKeysTable, isConnectorKey } = await import('../src/dashboard-next/pages/api.js');const DAY = 86_400_000;const base = {@@ -84,6 +84,15 @@ describe('renderKeysTable', () => {expect(row.textContent).toContain('<img src=x onerror=alert(1)>');});+ it('shows a connector key as an AI agent key that cannot spend, not as a bare marker chip', () => {+ const key = { ...base, scope: 'avatars:read agents:write connector' };+ const row = rowFor(key);+ const chips = [...row.querySelectorAll('.dn-chip-row .dn-tag')].map((el) => el.textContent);+ expect(chips).toEqual(['AI agent · cannot spend', 'avatars:read', 'agents:write']);+ expect(isConnectorKey(key)).toBe(true);+ expect(isConnectorKey(base)).toBe(false);+ });+it('renders one chip per granted scope', () => {const row = rowFor({ ...base, scope: 'avatars:read agents:write' });const chips = [...row.querySelectorAll('.dn-chip-row .dn-tag')].map((el) => el.textContent);diff --git a/tests/e2e/connector-key.spec.js b/tests/e2e/connector-key.spec.jsnew file mode 100644index 000000000..06cadb057--- /dev/null+++ b/tests/e2e/connector-key.spec.js@@ -0,0 +1,113 @@+import { test, expect, request as playwrightRequest } from '@playwright/test';+import { randomBytes } from 'node:crypto';++// An API key made for an AI agent, end to end, as a real person.+//+// Grok Bot can hold an API key as a Bot secret and use it unattended. This+// signs in as the QA account, makes a key with the "For an AI agent" preset on+// /dashboard/api, checks the table marks it as a key that cannot spend, then+// uses it the way Grok Bot's cloud would: a tool that edits nothing runs, and+// a tool that moves funds answers with the JSON-RPC error that names the+// browser session. Revoking it in the table cuts it off on the next request.+//+// Needs AUDIT_EMAIL / AUDIT_PASSWORD (`npm run audit:web:provision` makes+// them) and skips cleanly without them. It talks to whatever API the dev+// server proxies to, so run the API from this tree beside it to test local+// code (docs/mcp.md, "Client compatibility").++const EMAIL = process.env.AUDIT_EMAIL;+const PASSWORD = process.env.AUDIT_PASSWORD;+const SHOTS = process.env.CONNECTOR_KEY_SHOTS || '';++function mcpCall(api, origin, key, name, args = {}) {+ return api.post(`${origin}/api/mcp`, {+ headers: {+ authorization: `Bearer ${key}`,+ 'content-type': 'application/json',+ accept: 'application/json, text/event-stream',+ },+ data: { jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name, arguments: args } },+ });+}++async function shot(page, name) {+ if (SHOTS) await page.screenshot({ path: `${SHOTS}/${name}.png`, fullPage: false });+}++test.describe('API keys for AI agents', () => {+ test.skip(!EMAIL || !PASSWORD, 'needs AUDIT_EMAIL and AUDIT_PASSWORD (npm run audit:web:provision)');++ test('the connector preset issues a key that works, cannot spend, and dies on revoke', async ({ page, baseURL }) => {+ test.setTimeout(240_000);+ const origin = baseURL.replace(/\/$/, '');+ const name = `Grok Bot e2e ${randomBytes(3).toString('hex')}`;+ const machine = await playwrightRequest.newContext();++ const login = await page.context().request.post(`${origin}/api/auth/login`, { data: { email: EMAIL, password: PASSWORD } });+ expect(login.ok(), `login failed: HTTP ${login.status()}`).toBe(true);++ await page.goto(`${origin}/dashboard/api`);+ await page.getByRole('button', { name: '+ New key' }).first().click();+ const dialog = page.getByRole('dialog');+ await expect(dialog.getByText('What is this key for?')).toBeVisible();++ // The custom scopes are the default; the preset swaps them for a locked list.+ await expect(dialog.locator('[data-slot="custom-scopes"]')).toBeVisible();+ await dialog.getByText('For an AI agent').click();+ await expect(dialog.locator('[data-slot="custom-scopes"]')).toBeHidden();+ const locked = dialog.locator('[data-slot="connector-scopes"]');+ await expect(locked).toBeVisible();+ await expect(locked).toContainText('agents:write');+ await expect(locked).toContainText('wallet:write');+ await expect(dialog.locator('input[name="name"]')).toHaveAttribute('placeholder', 'e.g. Grok Bot');+ await shot(page, '1-preset');++ // Error state: a missing name is caught before any request.+ await dialog.getByRole('button', { name: 'Create key' }).click();+ await expect(dialog.locator('input[name="name"]:invalid')).toHaveCount(1);++ await dialog.locator('input[name="name"]').fill(name);+ const created = page.waitForResponse((r) => r.url().endsWith('/api/keys') && r.request().method() === 'POST');+ await dialog.getByRole('button', { name: 'Create key' }).click();+ const resp = await created;+ expect(resp.status()).toBe(201);+ const { key } = await resp.json();+ expect(key.scope.split(' ')).toEqual(['avatars:read', 'avatars:write', 'agents:read', 'agents:write', 'memory:read', 'memory:write', 'connector']);++ const reveal = page.getByRole('dialog');+ await expect(reveal.getByText('Give it to your agent')).toBeVisible();+ await expect(reveal.locator('[data-secret]')).toHaveText(key.secret);+ await shot(page, '2-reveal');+ await reveal.getByRole('button', { name: "I've saved it" }).click();++ const row = page.locator('tbody tr', { hasText: name });+ await expect(row.getByText('AI agent · cannot spend')).toBeVisible();+ await expect(row.locator('.dn-tag', { hasText: /^connector$/ })).toHaveCount(0);+ await shot(page, '3-table');++ // Used like Grok Bot would: no cookies, the key alone.+ const ok = await (await mcpCall(machine, origin, key.secret, 'list_my_avatars')).json();+ expect(ok.error, JSON.stringify(ok.error)).toBeUndefined();+ expect(ok.result.isError, JSON.stringify(ok.result)).not.toBe(true);++ const spend = await (await mcpCall(machine, origin, key.secret, 'agent_card_create', { confirm_spend: true })).json();+ expect(spend.error.code).toBe(-32003);+ expect(spend.error.message).toContain('needs a browser session on three.ws');+ expect(spend.error.data).toMatchObject({ reason: 'connector_key_cannot_spend', url: 'https://three.ws/dashboard' });++ // The REST spend routes refuse it the same way.+ const rest = await machine.post(`${origin}/api/monetization/withdrawals`, {+ headers: { authorization: `Bearer ${key.secret}`, 'content-type': 'application/json' },+ data: { amount: 1 },+ });+ expect(rest.status()).toBe(403);+ expect((await rest.json()).error_description).toContain('Connector keys');++ await row.getByRole('button', { name: `Revoke API key ${name}` }).click();+ await page.getByRole('dialog').getByRole('button', { name: 'Revoke key' }).click();+ await expect(page.locator('tbody tr', { hasText: name })).toHaveCount(0);+ const after = await mcpCall(machine, origin, key.secret, 'list_my_avatars');+ expect(after.status()).toBe(401);+ await machine.dispose();+ });+});diff --git a/tests/mcp-spend-gate.test.js b/tests/mcp-spend-gate.test.jsnew file mode 100644index 000000000..b298759b6--- /dev/null+++ b/tests/mcp-spend-gate.test.js@@ -0,0 +1,242 @@+// Connector keys can never spend (x-grok order 026, design rule 2).+//+// A key an AI agent holds unattended (Grok Bot, a schedule, CI) reads,+// generates and edits agent data. Every value-moving tool on every hosted MCP+// server refuses it at one choke point, gateCall in api/_mcp/policy.js, with a+// JSON-RPC error that names the browser session. These tests drive the real+// dispatchers with a connector principal, and walk each server's tools/list so+// a value-moving tool added later cannot slip past the gate unclassified.++import { describe, it, expect, vi } from 'vitest';++process.env.PUBLIC_APP_ORIGIN ||= 'https://three.ws';++vi.mock('../api/_lib/usage.js', () => ({+ recordEvent: vi.fn(),+ logger: () => ({ info: () => {}, warn: () => {}, error: () => {} }),+}));++const { POLICY } = await import('@three-ws/mcp-policy');+const {+ CONNECTOR_KEY_SCOPES,+ CONNECTOR_MARKER,+ SPEND_SCOPE,+ assertBearerMaySpend,+ capConnectorScope,+ isConnectorScope,+} = await import('../api/_lib/spend-scope.js');+const { KEY_PRESETS, presetScopes, normalizeKeyScopes } = await import('../api/_lib/api-keys.js');+const { SPEND_REFUSED_CODE, SPEND_WRITE_TOOLS, assertMaySpend, gateCall, spendScopeFor } = await import('../api/_mcp/policy.js');++const SERVERS = {+ 'three.ws': { dispatch: (await import('../api/_mcp/dispatch.js')).dispatch, tools: (await import('../api/_mcp/catalog.js')).TOOLS },+ 'threews-agent': { dispatch: (await import('../api/_mcpagent/dispatch.js')).dispatch, tools: (await import('../api/_mcpagent/catalog.js')).TOOLS },+ 'threews-3d-studio': { dispatch: (await import('../api/_mcp3d/dispatch.js')).dispatch, tools: (await import('../api/_mcp3d/catalog.js')).TOOLS },+ 'threews-x402-bazaar': { dispatch: (await import('../api/_mcpbazaar/dispatch.js')).dispatch, tools: (await import('../api/_mcpbazaar/catalog.js')).TOOLS },+ 'ibm-x402-mcp-remote': { dispatch: (await import('../api/_mcpibm/dispatch.js')).dispatch, tools: (await import('../api/_mcpibm/catalog.js')).TOOLS },+};++// The effective principal a connector key authenticates as: its preset scope,+// capped exactly the way authenticateBearer caps it.+const CONNECTOR_KEY_SCOPE = capConnectorScope(presetScopes('connector').join(' '));+const CONNECTOR = { userId: 'user-1', rateKey: 'user-1', scope: CONNECTOR_KEY_SCOPE, source: 'apikey', apiKeyId: 'key-1' };+// Everything turned on, so tools/list shows the financial tier too.+const ALL_ON = { headers: { 'x-three-tools': 'default,financial' } };++const call = (serverId, name, args = {}, auth = CONNECTOR) =>+ SERVERS[serverId].dispatch({ jsonrpc: '2.0', id: 7, method: 'tools/call', params: { name, arguments: args } }, auth, { ...ALL_ON });++function expectBrowserRefusal(r, { tool, required = SPEND_SCOPE } = {}) {+ expect(r.result).toBeUndefined();+ expect(r.error.code).toBe(SPEND_REFUSED_CODE);+ expect(r.error.message).toContain('needs a browser session on three.ws');+ expect(r.error.message).toContain('https://three.ws/dashboard');+ expect(r.error.data).toMatchObject({+ reason: 'connector_key_cannot_spend',+ required_scope: required,+ needs: 'browser_session',+ url: 'https://three.ws/dashboard',+ docs: 'https://three.ws/docs/mcp#api-key-scopes',+ });+ if (tool) expect(r.error.data.tool).toBe(tool);+}++describe('the connector preset', () => {+ it('issues read, generate and agent-data scopes and nothing that spends', () => {+ const scopes = presetScopes('connector');+ expect(scopes).toEqual([...CONNECTOR_KEY_SCOPES, CONNECTOR_MARKER]);+ for (const s of ['wallet:write', 'wallet:read', 'services:write', 'inference', 'profile', 'herald:announce', 'avatars:delete']) {+ expect(scopes).not.toContain(s);+ }+ expect(Object.isFrozen(KEY_PRESETS.connector)).toBe(true);+ expect(presetScopes('admin')).toBeNull();+ expect(presetScopes('__proto__')).toBeNull();+ });++ it('cannot be requested as a raw scope, only through the preset', () => {+ expect(normalizeKeyScopes(`avatars:read ${CONNECTOR_MARKER}`).invalid).toEqual([CONNECTOR_MARKER]);+ });++ it('is capped at authentication, so an edited stored scope can never spend', () => {+ const tampered = `avatars:read ${CONNECTOR_MARKER} wallet:write services:write profile agents:write`;+ const effective = capConnectorScope(tampered);+ expect(effective.split(' ')).toEqual(['avatars:read', 'agents:write', CONNECTOR_MARKER]);+ expect(isConnectorScope(effective)).toBe(true);+ });++ it('leaves a standard key exactly as granted', () => {+ const full = 'avatars:read avatars:write wallet:read wallet:write services:write';+ expect(capConnectorScope(full)).toBe(full);+ expect(isConnectorScope(full)).toBe(false);+ });+});++describe('every value-moving tool family refuses a connector key', () => {+ it('x402: pay_and_call', async () => {+ expectBrowserRefusal(await call('threews-agent', 'pay_and_call', { resource_url: 'https://paid.test/x', quote_id: 'q_aaaaaaaaaaaaaaaa', confirm_payment: true }), { tool: 'pay_and_call' });+ });++ // swap_execute is classified in the policy table but ships only in the stdio+ // trading package, so no hosted server answers it; the gate still knows it.+ it('trading: oracle_arm_watch, and swap_execute is classified', async () => {+ expect(spendScopeFor('threews-agent', 'swap_execute')).toBe(SPEND_SCOPE);+ expectBrowserRefusal(await call('three.ws', 'oracle_arm_watch', { agent_id: '00000000-0000-4000-8000-000000000000', confirm_spend: true }), { tool: 'oracle_arm_watch' });+ });++ it('marketplace: listing, bids, buy now and accept', async () => {+ for (const name of ['create_marketplace_listing', 'delist_marketplace_listing', 'place_bid', 'buy_now', 'accept_marketplace_bid', 'withdraw_marketplace_bid']) {+ expectBrowserRefusal(await call('threews-agent', name, {}), { tool: name });+ }+ });++ it('predictions: open, close and redeem; a watch moves nothing and is left to its handler', async () => {+ for (const name of ['predictions_open', 'predictions_close', 'predictions_redeem']) {+ expectBrowserRefusal(await call('threews-agent', name, {}), { tool: name });+ }+ expect(spendScopeFor('threews-agent', 'predictions_watch')).toBeNull();+ });++ it('wallet: provisioning and persona sends', async () => {+ expectBrowserRefusal(await call('threews-agent', 'provision_wallet', { agent_id: '00000000-0000-4000-8000-000000000000' }), { tool: 'provision_wallet' });+ for (const name of ['persona_tip', 'persona_send']) {+ expectBrowserRefusal(await call('threews-3d-studio', name, { persona_id: 'p', to: 'x', usdc: 1, confirm_send: true }), { tool: name });+ }+ });++ it('cards: quote, create, data, reveal, cancel, withdraw and connect', async () => {+ for (const name of ['agent_card_quote', 'agent_card_create', 'agent_card_data', 'agent_card_reveal', 'agent_card_cancel', 'agent_card_withdraw', 'agent_card_connect_link']) {+ expectBrowserRefusal(await call('three.ws', name, {}), { tool: name });+ }+ });++ it('services: publishing a paid endpoint needs services:write', async () => {+ expectBrowserRefusal(await call('threews-agent', 'monetize_endpoint', {}), { tool: 'monetize_endpoint', required: 'services:write' });+ });++ it('launch and every HTTP spend route: assertBearerMaySpend tells a connector where to go', () => {+ const post = { method: 'POST' };+ expect(() => assertBearerMaySpend({ scope: CONNECTOR_KEY_SCOPE }, post)).toThrowError(/needs a browser session on three\.ws.*https:\/\/three\.ws\/dashboard/);+ try {+ assertBearerMaySpend({ scope: CONNECTOR_KEY_SCOPE }, post);+ } catch (err) {+ expect(err).toMatchObject({ status: 403, code: 'insufficient_scope', expose: true });+ }+ // Reads still pass, so a connector can look before a person acts.+ expect(assertBearerMaySpend({ scope: CONNECTOR_KEY_SCOPE }, { method: 'GET' })).toBeTruthy();+ });++ it('refuses before tool enablement, so turning a tool on cannot help', async () => {+ await expect(gateCall('threews-agent', 'pay_and_call', {}, CONNECTOR, { headers: { 'x-three-tools': 'default,pay_and_call' } })).rejects.toMatchObject({ code: SPEND_REFUSED_CODE });+ });++ it('still runs non-spending tools for a connector key', async () => {+ const r = await call('three.ws', 'getting_started', {});+ expect(r.error).toBeUndefined();+ expect(r.result).toBeTruthy();+ });+});++describe('the gate covers every hosted tools/list', () => {+ for (const [serverId, { dispatch, tools }] of Object.entries(SERVERS)) {+ it(`${serverId}: every listed value-moving tool refuses a connector key`, async () => {+ const listed = await dispatch({ jsonrpc: '2.0', id: 1, method: 'tools/list' }, CONNECTOR, { ...ALL_ON });+ const names = listed.result.tools.map((t) => t.name);+ expect(names.length).toBeGreaterThan(0);+ for (const name of names) {+ if (!spendScopeFor(serverId, name)) continue;+ const r = await call(serverId, name, {});+ expect(r.error?.code, `${serverId}/${name}`).toBe(SPEND_REFUSED_CODE);+ }+ // A tool declaring a spend scope must be classified, or a new one+ // could ship that only its handler remembers to guard.+ for (const [name, tool] of Object.entries(tools)) {+ if (tool?.scope === 'wallet:write' || tool?.scope === 'services:write') {+ expect(spendScopeFor(serverId, name), `${serverId}/${name} declares ${tool.scope}`).toBe(tool.scope);+ }+ }+ });+ }++ it('every financial tool that moves money on a hosted server is classified', () => {+ const moneyFlags = /^confirm_(swap|transfer|launch|spend|payment|deposit|withdraw|bid|send|listing|delist|accept|trade|reveal|cancel)$/;+ for (const serverId of Object.keys(SERVERS)) {+ for (const [name, entry] of Object.entries(POLICY[serverId] || {})) {+ if (entry.tier === 'financial' && moneyFlags.test(entry.confirmFlag)) expect(spendScopeFor(serverId, name), `${serverId}/${name}`).toBe(SPEND_SCOPE);+ if (entry.confirmFlag === 'confirm_delete' || entry.confirmFlag === 'confirm_run') expect(spendScopeFor(serverId, name), `${serverId}/${name}`).toBeNull();+ }+ }+ });++ it('names no tool in SPEND_WRITE_TOOLS that its server does not ship', () => {+ for (const [serverId, extra] of Object.entries(SPEND_WRITE_TOOLS)) {+ for (const name of Object.keys(extra)) expect(Object.hasOwn(SERVERS[serverId].tools, name), `${serverId}/${name}`).toBe(true);+ }+ });+});++describe('existing keys keep working', () => {+ // A row exactly as api_keys stored it before connector keys existed: no+ // marker, its own scope string, nothing else new.+ const PRE_MIGRATION_ROW = { id: 'k-old', user_id: 'user-1', scope: 'avatars:read avatars:write wallet:read wallet:write services:write', expires_at: null, revoked_at: null };++ it('authenticates with its stored scope unchanged and may still spend', async () => {+ vi.resetModules();+ vi.doMock('../api/_lib/db.js', () => ({ sql: vi.fn(async (strings) => (String(strings.join('?')).includes('select') ? [PRE_MIGRATION_ROW] : [])) }));+ const { authenticateBearer } = await import('../api/_lib/auth.js');+ const auth = await authenticateBearer('sk_live_pre_migration_key');+ expect(auth).toMatchObject({ userId: 'user-1', scope: PRE_MIGRATION_ROW.scope, source: 'apikey', apiKeyId: 'k-old' });+ expect(() => assertMaySpend('threews-agent', 'pay_and_call', auth)).not.toThrow();+ expect(() => assertMaySpend('threews-agent', 'monetize_endpoint', auth)).not.toThrow();+ expect(assertBearerMaySpend(auth, { method: 'POST' })).toBe(auth);+ vi.doUnmock('../api/_lib/db.js');+ });++ it('a stored connector row is capped on the way in', async () => {+ vi.resetModules();+ const row = { ...PRE_MIGRATION_ROW, id: 'k-conn', scope: `avatars:read agents:write ${CONNECTOR_MARKER} wallet:write` };+ vi.doMock('../api/_lib/db.js', () => ({ sql: vi.fn(async (strings) => (String(strings.join('?')).includes('select') ? [row] : [])) }));+ const { authenticateBearer } = await import('../api/_lib/auth.js');+ const auth = await authenticateBearer('sk_live_connector_key');+ expect(auth.scope).toBe(`avatars:read agents:write ${CONNECTOR_MARKER}`);+ expect(() => assertMaySpend('three.ws', 'agent_card_create', auth)).toThrow(/Connector keys/);+ vi.doUnmock('../api/_lib/db.js');+ });++ it('a standard key without wallet:write is told which scope it lacks', () => {+ const narrow = { userId: 'user-1', scope: 'avatars:read', source: 'apikey' };+ let thrown;+ try {+ assertMaySpend('threews-agent', 'swap_execute', narrow);+ } catch (err) {+ thrown = err;+ }+ expect(thrown.code).toBe(SPEND_REFUSED_CODE);+ expect(thrown.data.reason).toBe('spend_scope_required');+ expect(thrown.message).toContain('lacks the wallet:write scope');+ });++ it('anonymous x402 and free callers hold no account funds and are left to the handlers', () => {+ expect(() => assertMaySpend('threews-3d-studio', 'persona_tip', { userId: null, scope: '', source: 'x402' })).not.toThrow();+ expect(() => assertMaySpend('threews-agent', 'pay_and_call', null)).not.toThrow();+ });+});