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): let cloud connectors like Grok Bot sign in safely and make Revoke take effect on the next request

nirholascf30be2697fe
diff --git a/api/_lib/auth.js b/api/_lib/auth.js
index 43da369c1..322d65fb3 100644
--- a/api/_lib/auth.js
+++ b/api/_lib/auth.js
@@ -120,6 +120,39 @@ export async function revokeRefreshToken(secret, clientId) {
}
}
+// ── grant liveness (revocation that takes effect on the next request) ───────
+// Access tokens are stateless JWTs, so on their own a revoked app kept working
+// until its current token expired, up to an hour. Revocation now ends every
+// access token minted for that person and client before the moment it
+// happened: the person pressing Revoke in Connected apps, the client revoking
+// its own refresh token (RFC 7009 §2.1 asks the server to drop the access
+// tokens of the same grant too), refresh-token reuse, and a replayed code.
+// All four leave a refresh row with `revoked_at` set and no `replaced_by`;
+// normal rotation always sets `replaced_by`, so a refresh never cuts off the
+// token it replaces. A grant authorized again later mints tokens issued after
+// the revocation, which pass.
+//
+// The same statement stamps `last_used_at` on the live refresh row, at most
+// every five minutes, so Connected apps shows when an app last called in
+// rather than when it last refreshed.
+export async function oauthGrantRevoked({ userId, clientId, issuedAt }) {
+ if (!userId || !clientId || !issuedAt) return false;
+ const [row] = await sql`
+ with touched as (
+ update oauth_refresh_tokens set last_used_at = now()
+ where user_id = ${userId} and client_id = ${clientId} and revoked_at is null and expires_at > now()
+ and (last_used_at is null or last_used_at < now() - interval '5 minutes')
+ returning id
+ )
+ select exists (
+ select 1 from oauth_refresh_tokens
+ where user_id = ${userId} and client_id = ${clientId} and replaced_by is null
+ and revoked_at >= to_timestamp(${issuedAt})
+ ) as revoked
+ `;
+ return !!row?.revoked;
+}
+
// ── browser sessions (cookie auth for the site itself) ──────────────────────
// __Host- prefix requires Path=/; Secure; no Domain — browser enforces cookie
// can't be set by any subdomain, eliminating subdomain cookie injection.
@@ -302,22 +335,27 @@ export async function authenticateBearer(token, { audience } = {}) {
return { userId: row.user_id, scope: row.scope, source: 'apikey', apiKeyId: row.id };
}
// Otherwise treat as JWT access token.
+ let payload;
try {
- const payload = await verifyAccessToken(token, { audience });
- // Only ACCESS tokens authorize API calls. Refresh tokens are opaque (never
- // JWTs) so this is belt-and-suspenders, but rejecting any non-'access'
- // 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;
- return {
- userId: payload.sub,
- scope: payload.scope || '',
- source: 'oauth',
- clientId: payload.client_id,
- };
+ payload = await verifyAccessToken(token, { audience });
} catch {
return null;
}
+ // Only ACCESS tokens authorize API calls. Refresh tokens are opaque (never
+ // JWTs) so this is belt-and-suspenders, but rejecting any non-'access'
+ // 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;
+ // Outside the try on purpose: a database error here surfaces as a 503 from
+ // wrap() instead of a 401, which would send every connected client back
+ // through sign-in during an outage.
+ if (await oauthGrantRevoked({ userId: payload.sub, clientId: payload.client_id, issuedAt: payload.iat })) return null;
+ return {
+ userId: payload.sub,
+ scope: payload.scope || '',
+ source: 'oauth',
+ clientId: payload.client_id,
+ };
}
// Resolve the request's user from a session cookie OR a bearer credential
diff --git a/api/_lib/migrations/20261008190000_oauth_refresh_user_client_index.sql b/api/_lib/migrations/20261008190000_oauth_refresh_user_client_index.sql
new file mode 100644
index 000000000..49e315208
--- /dev/null
+++ b/api/_lib/migrations/20261008190000_oauth_refresh_user_client_index.sql
@@ -0,0 +1,13 @@
+-- Migration: index refresh tokens by person and client.
+-- Apply: node scripts/apply-migrations.mjs --apply --file 20261008190000_oauth_refresh_user_client_index.sql
+-- Idempotent.
+--
+-- Every OAuth access token is now checked against its grant on each request,
+-- so revoking an app in Connected apps ends it on the next call instead of
+-- when its hour-long token expires (oauthGrantRevoked in api/_lib/auth.js).
+-- That lookup filters on (user_id, client_id) across revoked rows too, which
+-- the existing partial index on live rows cannot serve. The table gains a row
+-- per refresh, so without this index the check grows into a scan on every
+-- MCP call. The code is correct without it; this keeps it fast.
+
+create index if not exists oauth_refresh_user_client on oauth_refresh_tokens (user_id, client_id);
diff --git a/api/_lib/oauth-scopes.js b/api/_lib/oauth-scopes.js
index c82932fcb..e3ecf162e 100644
--- a/api/_lib/oauth-scopes.js
+++ b/api/_lib/oauth-scopes.js
@@ -18,6 +18,8 @@
// sides now read this array, and tests/api/oauth-scope-discovery.test.js
// pins them together.
+import { SPEND_SCOPE } from './spend-scope.js';
+
// Scopes a dynamically-registered client may request. Anything outside this set
// (notably privileged scopes like `permissions:redeem`, which authorizes
// gas-spending on-chain redemption) is silently dropped at registration so a
@@ -51,7 +53,8 @@ export const REGISTERABLE_SCOPES = Object.freeze([
'home:act',
// The wallet/services scopes gate the agent-wallet MCP server
// (api/mcp-agent). They are registerable because the user approves each one
- // by name on the consent screen and every spend they authorize is still
+ // by name on the consent screen, `wallet:write` only by ticking a separate
+ // box (splitSpendScope below), and every spend they authorize is still
// bounded by the server-side caps and THREEWS_AGENT_PAY_ENABLED.
'wallet:read',
'wallet:write',
@@ -76,3 +79,19 @@ export function filterRegisterableScope(requested) {
.filter((s) => REGISTERABLE.has(s));
return kept.length ? kept.join(' ') : 'avatars:read';
}
+
+// Design rule for connectors: an app a person signs in to three.ws can never
+// spend from their wallet unless they tick a box saying so on the consent
+// screen (api/oauth/[action].js). A
+// cloud agent such as Grok Bot registers for every scope the protected-resource
+// metadata lists, `wallet:write` included, and then holds the token unattended,
+// so spending is opt-in rather than something a person approves by clicking
+// Authorize. Left unticked, `wallet:write` is dropped and `wallet:read` kept,
+// so the app still sees balances and caps.
+export function splitSpendScope(scope) {
+ const scopes = String(scope || '').split(/\s+/).filter(Boolean);
+ const spend = scopes.includes(SPEND_SCOPE);
+ const base = scopes.filter((s) => s !== SPEND_SCOPE);
+ if (spend && !base.includes('wallet:read')) base.push('wallet:read');
+ return { base: base.join(' '), spend };
+}
diff --git a/api/_lib/schema.sql b/api/_lib/schema.sql
index 4f45d3281..2f4aa2f6d 100644
--- a/api/_lib/schema.sql
+++ b/api/_lib/schema.sql
@@ -321,6 +321,7 @@ 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_user_client on oauth_refresh_tokens(user_id, client_id);
create index if not exists oauth_refresh_expiry on oauth_refresh_tokens(expires_at);
-- ── Developer API keys (for server-to-server MCP usage) ─────────────────────
diff --git a/api/oauth/[action].js b/api/oauth/[action].js
index d795d11c4..2d0b01b47 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, oauthGrantRevoked,
} 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';
@@ -14,7 +14,7 @@ import { limits, clientIp } from '../_lib/rate-limit.js';
import { env } from '../_lib/env.js';
import { z } from 'zod';
import { parse } from '../_lib/validate.js';
-import { filterRegisterableScope } from '../_lib/oauth-scopes.js';
+import { filterRegisterableScope, splitSpendScope } from '../_lib/oauth-scopes.js';
import { requireCsrf } from '../_lib/csrf.js';
import { canonicalMcpResource, allMcpAudiences } from '../_lib/mcp-resources.js';
@@ -67,15 +67,57 @@ const INVALID_TARGET = 'unknown resource, this server issues tokens only for the
// keeps and the scopes /.well-known/oauth-protected-resource advertises are
// read from one array and cannot drift apart.
+// Plain-language lines for the consent screen and Connected apps. A scope with
+// no line here is shown by its raw name, escaped.
+const SCOPE_LABELS = {
+ 'avatars:read': 'See your avatars',
+ 'avatars:write': 'Create and update your avatars',
+ 'avatars:delete': 'Delete your avatars',
+ profile: 'See your name and email address',
+ offline_access: 'Stay connected without asking you to sign in again',
+ 'memory:read': 'Read what your agents remember',
+ 'memory:write': 'Save and erase what your agents remember',
+ 'agents:read': 'See your agents and their identities',
+ 'agents:write': 'Create, update and register your agents',
+ 'feedback:read': 'Read feedback visitors left on your agents',
+ 'wallet:read': 'See your agent wallet balance and spending caps',
+ 'wallet:write': 'Spend USDC from your agent wallet, within your caps',
+ 'services:write': 'Publish paid services that earn USDC into your agent wallet',
+ 'home:read': 'See the state of your connected home',
+ 'home:act': 'Control your connected home (unlocking, opening and disarming still need your yes each time)',
+};
+
function scopeLabel(s) {
- const labels = { 'avatars:read': 'Read your avatars', 'avatars:write': 'Create and update avatars', 'avatars:delete': 'Delete your avatars', profile: 'See your name and email', offline_access: 'Stay signed in across sessions', 'memory:read': 'Recall your agents’ memories', 'memory:write': 'Store and forget your agents’ memories', 'agents:read': 'Screen your agents’ identities', 'agents:write': 'Register your agents on-chain', 'wallet:read': 'See your agent wallet balance and spending caps', 'wallet:write': 'Spend USDC from your agent wallet, within your caps', 'services:write': 'Publish paid services that earn USDC to your agent wallet', 'home:read': 'See the state of your connected home', 'home:act': 'Control your connected home (unlocking, opening and disarming still need your explicit yes each time)' };
- return labels[s] || esc(s);
+ return SCOPE_LABELS[s] ? esc(SCOPE_LABELS[s]) : esc(s);
}
function esc(s) {
return String(s).replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[c]);
}
+function hostOf(uri) {
+ try { return new URL(uri).host || null; } catch { return null; }
+}
+
+const CONSENT_CSS = `:root{color-scheme:dark;--bg:#0b0b10;--card:#14141c;--line:#2a2a36;--soft:#1b1b25;--ink:#eee;--dim:#aaa;--fade:#808090;--accent:#6a5cff;--accent-ink:#fff;--ok:#3ecf8e;--ok-bg:rgba(62,207,142,.1);--warn:#f5a524;--warn-bg:rgba(245,165,36,.1)}
+@media (prefers-color-scheme:light){:root{color-scheme:light;--bg:#f4f4f7;--card:#fff;--line:#e2e2ea;--soft:#f6f6fa;--ink:#16161d;--dim:#55556a;--fade:#6b6b80;--accent:#5a4cf0;--ok:#0f8a57;--ok-bg:rgba(15,138,87,.08);--warn:#9a5b00;--warn-bg:rgba(245,165,36,.12)}}
+*{box-sizing:border-box}body{font:16px/1.5 -apple-system,system-ui,Segoe UI,Roboto,sans-serif;background:var(--bg);color:var(--ink);margin:0;min-height:100vh;display:grid;place-items:center;padding:24px 16px}
+.card{background:var(--card);border:1px solid var(--line);border-radius:16px;padding:28px 24px 22px;max-width:460px;width:100%;box-shadow:0 10px 40px rgba(0,0,0,.25)}
+.app{display:flex;gap:14px;align-items:center;margin-bottom:16px}.mark{flex:0 0 auto;width:44px;height:44px;border-radius:12px;background:linear-gradient(135deg,#6a5cff,#ff5ca8);display:grid;place-items:center;color:#fff;font-weight:700;font-size:20px}
+h1{font-size:19px;line-height:1.3;margin:0}h1 b{word-break:break-word}
+.facts{margin:0 0 12px;padding:10px 12px;background:var(--soft);border-radius:10px;font-size:14px}.facts div{display:flex;justify-content:space-between;gap:12px;padding:3px 0}.facts dt{color:var(--dim);white-space:nowrap}.facts dd{margin:0;font-family:ui-monospace,SFMono-Regular,Menlo,monospace;font-size:13px;text-align:right;word-break:break-all}
+.unverified{margin:0 0 16px;font-size:13px;color:var(--dim)}
+.who{display:flex;align-items:center;gap:10px;margin-bottom:16px;padding:10px 12px;border:1px solid var(--line);border-radius:10px;font-size:14px}.dot{flex:0 0 auto;width:30px;height:30px;border-radius:50%;background:var(--accent);display:grid;place-items:center;color:var(--accent-ink);font-weight:600}.who small{display:block;color:var(--fade);font-size:13px;overflow-wrap:anywhere}
+h2{font-size:14px;font-weight:600;margin:0 0 4px}
+ul{margin:4px 0 16px;padding:0;list-style:none}li{padding:7px 0 7px 24px;border-bottom:1px solid var(--line);position:relative;font-size:15px}li:last-child{border:0}li::before{content:"";position:absolute;left:4px;top:15px;width:8px;height:8px;border-radius:50%;background:var(--accent)}
+.safe,.warn{border-radius:10px;padding:12px 14px;font-size:14px;margin:0 0 14px}.safe{background:var(--ok-bg);border:1px solid var(--ok)}.safe strong{color:var(--ok)}.warn{display:none;background:var(--warn-bg);border:1px solid var(--warn)}.warn strong{color:var(--warn)}
+.spend{display:flex;gap:10px;align-items:flex-start;padding:10px 12px;border:1px dashed var(--line);border-radius:10px;margin:0 0 14px;font-size:14px;cursor:pointer}.spend input{margin-top:3px;width:16px;height:16px;accent-color:var(--warn)}
+.card:has(#allow-spend:checked) .safe{display:none}.card:has(#allow-spend:checked) .warn{display:block}
+.actions{display:flex;gap:10px}button{flex:1;padding:12px 16px;border-radius:10px;border:0;font:inherit;font-size:15px;font-weight:600;cursor:pointer;transition:filter .15s ease,background .15s ease}
+.allow{background:var(--accent);color:var(--accent-ink)}.allow:hover{filter:brightness(1.1)}.deny{background:transparent;color:var(--dim);border:1px solid var(--line)}.deny:hover{background:var(--soft);color:var(--ink)}
+button:focus-visible,.spend:has(input:focus-visible),a:focus-visible{outline:2px solid var(--accent);outline-offset:2px}
+.foot{margin:16px 0 0;font-size:12.5px;color:var(--fade)}a{color:var(--accent)}`;
+
function renderConsent(res, { client, user, params, csrf, grantedScope }) {
res.statusCode = 200;
res.setHeader('content-type', 'text/html; charset=utf-8');
@@ -97,9 +139,32 @@ function renderConsent(res, { client, user, params, csrf, grantedScope }) {
// client asked for. They diverge whenever a client requests a scope it did
// not register: intersectScopes drops it and falls back to the client's
// 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>`);
+ // promise one set of permissions and the issued code carry another. The
+ // spend scope is split off and shown only beside the box that grants it.
+ const { base, spend } = splitSpendScope(grantedScope);
+ const scopeList = base.split(/\s+/).filter(Boolean);
+ const name = esc(client.name);
+ const siteHost = hostOf(client.client_uri);
+ const returnHost = hostOf(params.redirect_uri) || params.redirect_uri;
+ const who = user.display_name || user.email;
+ const hidden = Object.entries(params)
+ .filter(([k]) => k !== 'csrf' && k !== 'decision' && k !== 'allow_spend')
+ .map(([k, v]) => `<input type="hidden" name="${esc(k)}" value="${esc(v)}">`).join('');
+ res.end(`<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Authorize ${name} · three.ws</title><style>${CONSENT_CSS}</style></head><body><form class="card" method="post" action="/api/oauth/authorize">`
+ + `<div class="app"><div class="mark" aria-hidden="true">${esc((client.name || '?').trim()[0]?.toUpperCase() || '?')}</div><h1><b>${name}</b> wants to connect to your three.ws account</h1></div>`
+ + `<dl class="facts">${siteHost ? `<div><dt>App website</dt><dd data-fact="client-host">${esc(siteHost)}</dd></div>` : ''}<div><dt>Sends you back to</dt><dd data-fact="return-host">${esc(returnHost)}</dd></div></dl>`
+ + (client.dynamically_registered ? `<p class="unverified">three.ws has not verified this app. Its name was chosen by the app itself, so continue only if you started this from ${name} and the addresses above belong to it.</p>` : '')
+ + `<div class="who"><div class="dot" aria-hidden="true">${esc(who[0].toUpperCase())}</div><div>${esc(who)}<small>${esc(user.email)}</small></div></div>`
+ + `<h2>${name} will be able to</h2><ul data-scopes>${scopeList.map((s) => `<li>${scopeLabel(s)}</li>`).join('')}</ul>`
+ + `<p class="safe" data-wallet="never-spends"><strong>It can never spend from your wallet.</strong> ${name} cannot move funds, pay for anything, or launch a coin from your wallets. Those always need you, signed in on three.ws.</p>`
+ + (spend
+ ? `<label class="spend"><input type="checkbox" id="allow-spend" name="allow_spend" value="yes"><span>Also let ${name} <b>spend USDC from your agent wallet</b> on its own, within the caps you set</span></label>`
+ + `<p class="warn" data-wallet="may-spend"><strong>${name} will be able to spend.</strong> It can pay from your agent wallet without asking you, up to your caps. Leave the box unticked for an app that runs unattended.</p>`
+ : '')
+ + `<input type="hidden" name="csrf" value="${esc(csrf || '')}">${hidden}`
+ + `<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 see ${name} and revoke it at any time in <a href="/dashboard/settings#connected-apps">Settings, Connected apps</a>. Revoking cuts it off on its very next request.</p>`
+ + `</form></body></html>`);
}
async function handleAuthorize(req, res) {
@@ -139,8 +204,10 @@ async function handleAuthorize(req, res) {
if (state) denied.searchParams.set('state', state);
return redirect(res, denied.toString());
}
+ // The spend scope rides only on a ticked box (splitSpendScope).
+ const approvedScope = params.allow_spend === 'yes' ? grantedScope : splitSpendScope(grantedScope).base;
const code = randomToken(24);
- await sql`insert into oauth_auth_codes (code, client_id, user_id, redirect_uri, scope, resource, code_challenge, code_challenge_method, expires_at) values (${code}, ${client_id}, ${user.id}, ${redirect_uri}, ${grantedScope}, ${targetResource}, ${code_challenge}, 'S256', now() + ${'60 seconds'}::interval)`;
+ await sql`insert into oauth_auth_codes (code, client_id, user_id, redirect_uri, scope, resource, code_challenge, code_challenge_method, expires_at) values (${code}, ${client_id}, ${user.id}, ${redirect_uri}, ${approvedScope}, ${targetResource}, ${code_challenge}, 'S256', now() + ${'60 seconds'}::interval)`;
const back = new URL(redirect_uri);
back.searchParams.set('code', code);
if (state) back.searchParams.set('state', state);
@@ -299,6 +366,12 @@ const registerSchema = z.object({
// then splice its "origin" (the literal string `null`) into the CSP form-action
// allowlist and 302 the browser at it after approval.
const EXECUTABLE_URI_SCHEMES = new Set(['javascript:', 'data:', 'vbscript:', 'blob:', 'file:', 'about:', 'filesystem:', 'view-source:']);
+// Network schemes that would carry the code to a remote host without TLS, or
+// to something that is not a browser redirect at all. A cloud connector (Grok
+// Bot, claude.ai) redirects to an https host we cannot predict, which is why
+// any https URI is accepted; these are the plain-text and non-redirect
+// neighbours that the private-use rule below would otherwise let through.
+const NETWORK_URI_SCHEMES = new Set(['ftp:', 'ftps:', 'sftp:', 'ws:', 'wss:', 'ssh:', 'telnet:', 'gopher:', 'ldap:', 'ldaps:', 'smb:', 'nntp:', 'irc:', 'mailto:', 'tel:', 'sms:', 'news:']);
// RFC 8252 §8.3 permits loopback redirects over plain http, IPv6 included.
const LOOPBACK_HOSTS = new Set(['localhost', '127.0.0.1', '[::1]']);
@@ -307,7 +380,7 @@ function redirectUriRejection(uri) {
let u;
try { u = new URL(uri); } catch { return 'redirect_uri must be an absolute URI'; }
const scheme = u.protocol.toLowerCase();
- if (EXECUTABLE_URI_SCHEMES.has(scheme)) return `redirect URI scheme "${scheme}" is not allowed`;
+ if (EXECUTABLE_URI_SCHEMES.has(scheme) || NETWORK_URI_SCHEMES.has(scheme)) return `redirect URI scheme "${scheme}" is not allowed`;
if (scheme === 'https:') return null;
if (scheme === 'http:') return LOOPBACK_HOSTS.has(u.hostname) ? null : 'non-https redirect URIs only allowed for localhost';
// A private-use scheme (RFC 8252 §7.1) is how native clients receive the
@@ -431,6 +504,7 @@ async function handleIntrospect(req, res) {
try {
const payload = await verifyAccessToken(token, { audience: allMcpAudiences() });
if (payload.client_id && payload.client_id !== clientId) return json(res, 200, { active: false });
+ if (await oauthGrantRevoked({ userId: payload.sub, clientId: payload.client_id, issuedAt: payload.iat })) return json(res, 200, { active: false });
return json(res, 200, { active: true, scope: payload.scope, client_id: payload.client_id, sub: payload.sub, aud: payload.aud, iss: payload.iss, exp: payload.exp, iat: payload.iat, token_type: 'Bearer' });
} catch {
const h = await sha256(token);
@@ -447,8 +521,8 @@ 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 ends the app's access tokens on their next request too, not just its
+// refresh tokens (oauthGrantRevoked in ../_lib/auth.js).
async function handleGrants(req, res) {
if (cors(req, res, { methods: 'GET,DELETE,OPTIONS', credentials: true })) return;
@@ -471,9 +545,11 @@ async function handleGrants(req, res) {
client_id: r.client_id,
name: r.name,
client_uri: r.client_uri,
+ client_host: hostOf(r.client_uri),
logo_uri: r.logo_uri,
software: r.software_id ? `${r.software_id}${r.software_version ? ` ${r.software_version}` : ''}` : null,
scopes: [...new Set(String(r.scopes || '').split(/\s+/).filter(Boolean))],
+ can_spend: splitSpendScope(r.scopes).spend,
authorized_at: r.authorized_at,
last_used_at: r.last_used_at,
})),
diff --git a/data/changelog.json b/data/changelog.json
index b368f7d75..04154098a 100644
--- a/data/changelog.json
+++ b/data/changelog.json
@@ -1,6 +1,16 @@
{
"$comment": "Curated changelog entries for three.ws, the editorial layer of the public changelog. New PAGE launches are tracked automatically via the `added` field in data/pages.json; this file is for everything else holders care about: improvements, fixes, SDK releases, trading/payments capabilities, security work. scripts/build-page-index.mjs merges both sources into CHANGELOG.md, public/changelog.json, and public/changelog.xml. Newest first. Allowed tags: feature, improvement, fix, sdk, infra, docs, security, desktop (desktop entries become the desktop app's release notes). `link` is optional and must be a live three.ws path.",
"entries": [
+ {
+ "date": "2026-10-08",
+ "title": "Connect Grok Bot and other cloud agents with OAuth, and revoke them instantly",
+ "summary": "Cloud agents such as Grok Bot can now sign in to your three.ws account over OAuth 2.1 from wherever they run, with a callback on any https address. The sign-in screen says plainly which app is asking, which site it belongs to, where it will send you back, and what it will be able to do, and it states that the app can never spend from your wallet. Spending is only granted if you tick a separate box. Settings, Connected apps lists every app with when it last called in, and Revoke now cuts an app off on its very next request instead of up to an hour later.",
+ "tags": [
+ "feature",
+ "security"
+ ],
+ "link": "/docs/mcp"
+ },
{
"date": "2026-10-08",
"title": "Topping up an agent's inference credits now asks for the real-funds agreements first",
diff --git a/docs/mcp.md b/docs/mcp.md
index ae9b6634f..9bf917f6b 100644
--- a/docs/mcp.md
+++ b/docs/mcp.md
@@ -184,6 +184,36 @@ Each OAuth-protected hosted server is its own resource. On a `401`, the `WWW-Aut
This is also why an MCP client asks you to sign in as soon as you add `https://three.ws/api/mcp`, even if you only meant to use the free tools: the `401` arrives on `initialize`, before any tool is chosen. A client with no account belongs on `https://three.ws/api/mcp-studio`, which never challenges and serves the free 3D generation and asset catalog tools.
+### Cloud connectors and revocation
+
+A cloud agent such as Grok Bot, or a claude.ai custom connector, signs in with the same OAuth 2.1 flow, from servers we have never seen. Choose OAuth 2.1 as the connector's authentication and give it a server URL such as `https://three.ws/api/mcp`. The client does the rest:
+
+- **Registration accepts any https callback.** `POST /oauth/register` (RFC 7591) needs no pre-arrangement. Any `https://` redirect URI is accepted, on whatever host the connector's cloud uses, as are plain-http loopback URIs (`http://localhost`, `http://127.0.0.1`, `http://[::1]`, any port) for desktop clients and private-use schemes such as `com.example.app:/callback` for native apps. Plain http on a public host, `ftp:`, `ws:`, `wss:`, `mailto:`, `javascript:`, `data:` and the like are refused with `invalid_redirect_uri`. The `client_name` and `client_uri` a client registers are stored and shown to the person who approves it.
+- **PKCE S256 is mandatory.** `/oauth/authorize` refuses a request without `code_challenge`, or with any method other than `S256`, and the token endpoint checks the verifier. Codes live 60 seconds and work once; a replayed code revokes everything issued from it.
+- **The consent screen says who is asking.** It shows the app's name, the host of its `client_uri`, the host the code will be sent back to, and an "unverified" note for self-registered apps (any app can call itself "Grok Bot", so the addresses are what to check). Every permission is listed in plain language.
+- **A connector can never spend unless you tick a box.** `wallet:write` is the one scope that moves money, and cloud agents tend to register for every scope the metadata lists. The consent screen never grants it on Authorize alone: it states that the app can never spend from your wallet and grants `wallet:read` in its place, so balances and caps stay visible. Spending is granted only when you tick "Also let ... spend USDC from your agent wallet", which swaps that statement for a warning. The routes and tools that pay, trade, withdraw, launch, place orders or issue a spending mandate all refuse a token without `wallet:write` (the shared gate is `api/_lib/spend-scope.js`).
+- **Tokens.** Access tokens are JWTs that live one hour. Refresh tokens live 30 days, rotate on every use, and a reused refresh token revokes the whole chain.
+- **See and revoke connected apps** in [Settings, Connected apps](https://three.ws/dashboard/settings#connected-apps) (`/dashboard/connections` redirects there). Each app shows its name, site, permissions, when it last called in and when you authorized it, and a "Can spend" tag if you ticked the box. **Revoke takes effect on the app's very next request**: every access token issued to it before that moment is refused with `401` by every MCP server and API route, and its refresh tokens stop working, so it has to send you through consent again. The same immediate cut-off applies when the app revokes its own refresh token at `POST /oauth/revoke` (RFC 7009), and `POST /oauth/introspect` reports such a token as `{"active": false}`.
+
+The programmatic form of the list, for the signed-in browser session only (a bearer token cannot list or revoke apps, including itself):
+
+```
+GET /api/oauth/grants # { grants: [{ client_id, name, client_host, scopes, can_spend, last_used_at, authorized_at }] }
+DELETE /api/oauth/grants?client_id=... # revoke one app; needs the X-CSRF-Token header
+```
+
+The end-to-end proof is [`tests/e2e/oauth-cloud-connector.spec.js`](../tests/e2e/oauth-cloud-connector.spec.js): it registers "Grok Bot" with an external https callback, approves it as the QA account, exchanges the code with PKCE, calls `tools/list` on `/api/mcp`, then presses Revoke and sees the next call refused. To run it against your own code, start the API beside the dev server (see [Client compatibility](#client-compatibility)) and pass the QA login:
+
+```bash
+# Terminal 1: the API from this tree. JWT_SECRET can be any local value.
+PORT=3108 PUBLIC_APP_ORIGIN=http://localhost:3107 JWT_SECRET=$(openssl rand -hex 32) \
+ node --env-file=.env.local --env-file-if-exists=.env server/index.mjs
+
+# Terminal 2: the spec, on a dev server that proxies to it
+DEV_API_PROXY=http://localhost:3108 E2E_PORT=3107 \
+ node --env-file=.env ./node_modules/@playwright/test/cli.js test tests/e2e/oauth-cloud-connector.spec.js
+```
+
### API key (server-to-server)
For scripts, CI, and server agents, generate a key at **[/dashboard/api](https://three.ws/dashboard/api)** and pass it as a bearer token:
diff --git a/src/dashboard-next/pages/settings.js b/src/dashboard-next/pages/settings.js
index 09061edf2..dfaaec43b 100644
--- a/src/dashboard-next/pages/settings.js
+++ b/src/dashboard-next/pages/settings.js
@@ -281,7 +281,7 @@ function renderConnectedApps(resp, onRetry) {
<div class="set-panel-head">
<div>
<div class="dn-panel-title">Connected apps</div>
- <div class="dn-panel-sub" style="margin:2px 0 0">Apps you signed in with three.ws: the desktop app, the CLI, and coding clients using your MCP tools. Revoking stops an app within an hour, when its current access expires.</div>
+ <div class="dn-panel-sub" style="margin:2px 0 0">Apps you signed in with three.ws: the desktop app, the CLI, coding clients, and cloud agents such as Grok Bot using your MCP tools. Revoking cuts an app off on its very next request.</div>
</div>
</div>
<div data-slot="grants-list"></div>
@@ -294,13 +294,13 @@ function renderConnectedApps(resp, onRetry) {
}
const render = (grants) => {
if (!grants.length) {
- listHost.innerHTML = emptyStateHTML({ icon: '', title: 'No connected apps', body: 'When you sign in to three.ws Desktop, the CLI, or an editor over MCP, it appears here.', compact: true });
+ listHost.innerHTML = emptyStateHTML({ icon: '', title: 'No connected apps', body: 'When you connect three.ws Desktop, the CLI, an editor, or a cloud agent such as Grok Bot over MCP, it appears here with a Revoke button.', compact: true });
return;
}
listHost.innerHTML = grants.map((g) => `
<div style="display:flex;align-items:center;gap:12px;padding:12px 0;border-bottom:1px solid var(--nxt-stroke);flex-wrap:wrap" data-client-id="${esc(g.client_id)}">
<div style="flex:1;min-width:200px">
- <div style="font-size:13.5px;color:var(--nxt-ink);font-weight:500">${esc(g.name)}${g.software ? ` <span style="color:var(--nxt-ink-fade);font-weight:400;font-family:${MONO};font-size:11.5px">${esc(g.software)}</span>` : ''}</div>
+ <div style="font-size:13.5px;color:var(--nxt-ink);font-weight:500;overflow-wrap:anywhere">${esc(g.name)}${g.client_host ? ` <span style="color:var(--nxt-ink-fade);font-weight:400;font-family:${MONO};font-size:11.5px">${esc(g.client_host)}</span>` : ''}${g.software ? ` <span style="color:var(--nxt-ink-fade);font-weight:400;font-family:${MONO};font-size:11.5px">${esc(g.software)}</span>` : ''}${g.can_spend ? ` <span class="dn-tag warn" title="You ticked “spend from my agent wallet” when you connected it">Can spend</span>` : ''}</div>
<div style="font-size:12px;color:var(--nxt-ink-fade);margin-top:3px">
Can ${esc(g.scopes.map((sc) => SCOPE_WORDS[sc] || sc).join(', '))} · used ${esc(relTime(g.last_used_at))} · authorized ${esc(relTime(g.authorized_at))}
</div>
@@ -310,7 +310,7 @@ function renderConnectedApps(resp, onRetry) {
`).join('');
listHost.querySelectorAll('[data-action="revoke-grant"]').forEach((btn) => {
btn.addEventListener('click', async () => {
- if (!confirm(`Revoke ${btn.dataset.name}? It will need to sign in again.`)) return;
+ if (!confirm(`Revoke ${btn.dataset.name}? It loses access on its next request and will need you to sign in again.`)) return;
btn.disabled = true;
btn.textContent = 'Revoking…';
try {
diff --git a/tests/api/oauth-authorize.test.js b/tests/api/oauth-authorize.test.js
index 7f44ab18c..d591467c7 100644
--- a/tests/api/oauth-authorize.test.js
+++ b/tests/api/oauth-authorize.test.js
@@ -292,7 +292,7 @@ describe('GET /api/oauth/authorize — consent page render', () => {
const { res, status, body } = await invoke({ url: `/api/oauth/authorize?${VALID_QS}` });
expect(status).toBe(200);
expect(res.headers['content-type']).toMatch(/text\/html/);
- expect(body).toContain('Authorize <b>Test Client</b>');
+ expect(body).toContain('<b>Test Client</b> wants to connect to your three.ws account');
expect(body).toContain('name="csrf"');
// Original PKCE params are preserved as hidden inputs for POST submit.
expect(body).toContain('name="code_challenge"');
diff --git a/tests/api/oauth-introspect.test.js b/tests/api/oauth-introspect.test.js
index 480df881b..7ccb349b6 100644
--- a/tests/api/oauth-introspect.test.js
+++ b/tests/api/oauth-introspect.test.js
@@ -33,6 +33,7 @@ vi.mock('../../api/_lib/rate-limit.js', () => ({
const authState = {
verifyResult: null, // set to a payload object → returns it; null → throws
+ grantRevoked: false, // the person revoked this app after the token was issued
};
vi.mock('../../api/_lib/auth.js', () => ({
@@ -44,6 +45,7 @@ vi.mock('../../api/_lib/auth.js', () => ({
issueRefreshToken: vi.fn(async () => ({ token: 'rt', id: 'rt-id' })),
rotateRefreshToken: vi.fn(async () => { throw Object.assign(new Error('invalid_grant'), { status: 400 }); }),
revokeRefreshToken: vi.fn(async () => {}),
+ oauthGrantRevoked: vi.fn(async () => authState.grantRevoked),
getSessionUser: vi.fn(async () => null),
csrfTokenFor: vi.fn(async () => null),
verifyCsrfToken: vi.fn(async () => false),
@@ -107,6 +109,7 @@ const PAST = new Date(Date.now() - 3_600_000).toISOString();
beforeEach(() => {
sqlState.queue = [];
+ authState.grantRevoked = false;
sqlState.calls = [];
authState.verifyResult = null;
});
@@ -153,6 +156,15 @@ describe('POST /api/oauth/introspect', () => {
expect(body.token_type).toBe('Bearer');
});
+ it('returns { active: false } for a JWT whose app the person has since revoked', async () => {
+ sqlState.queue.push([PUBLIC_CLIENT]);
+ authState.verifyResult = { sub: 'user-1', scope: 'avatars:read', client_id: 'mcp_pub', aud: 'https://app.test/api/mcp', iss: 'https://app.test', exp: Math.floor(Date.now() / 1000) + 3600, iat: Math.floor(Date.now() / 1000) };
+ authState.grantRevoked = true;
+ const { status, body } = await invoke({ formBody: { token: 'valid.jwt.token', client_id: 'mcp_pub' } });
+ expect(status).toBe(200);
+ expect(body).toEqual({ active: false });
+ });
+
it('returns { active: false } for an invalid/expired JWT (falls through to refresh token lookup which also misses)', async () => {
sqlState.queue.push([PUBLIC_CLIENT]); // client lookup
// verifyAccessToken throws (authState.verifyResult = null)
diff --git a/tests/e2e/oauth-cloud-connector.spec.js b/tests/e2e/oauth-cloud-connector.spec.js
new file mode 100644
index 000000000..93738c336
--- /dev/null
+++ b/tests/e2e/oauth-cloud-connector.spec.js
@@ -0,0 +1,164 @@
+import { test, expect, request as playwrightRequest } from '@playwright/test';
+import { createHash, randomBytes } from 'node:crypto';
+
+// A cloud MCP connector signing in to three.ws, end to end, as a real person.
+//
+// Grok Bot adds an MCP server with OAuth 2.1 from xAI's cloud: it registers a
+// client we have never seen, with a callback on a host nobody could list in
+// advance, then runs the PKCE authorization-code flow in the person's browser.
+// This drives every step of that against the dev server with the QA account:
+// register "Grok Bot", read the consent screen, approve, catch the code at the
+// external callback, exchange it, call tools/list on /api/mcp with the token,
+// then press Revoke in Settings > Connected apps and see the very next call
+// refused.
+//
+// Needs AUDIT_EMAIL / AUDIT_PASSWORD (the QA account, `npm run
+// audit:web:provision` makes one) 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, "Cloud connectors and revocation").
+
+const EMAIL = process.env.AUDIT_EMAIL;
+const PASSWORD = process.env.AUDIT_PASSWORD;
+
+// An https callback on a host three.ws could never have predicted. The name is
+// on a reserved TLD, so nothing outside this machine ever receives the code:
+// the spec reads it from the request the browser makes.
+const CALLBACK_ORIGIN = 'https://connectors.grok-cloud.example';
+const CALLBACK = `${CALLBACK_ORIGIN}/oauth/callback/${randomBytes(4).toString('hex')}`;
+
+const base64url = (buf) => buf.toString('base64').replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
+
+function pkcePair() {
+ const verifier = base64url(randomBytes(48));
+ return { verifier, challenge: base64url(createHash('sha256').update(verifier).digest()) };
+}
+
+async function toolsList(api, origin, accessToken) {
+ return api.post(`${origin}/api/mcp`, {
+ headers: {
+ authorization: `Bearer ${accessToken}`,
+ 'content-type': 'application/json',
+ accept: 'application/json, text/event-stream',
+ },
+ data: { jsonrpc: '2.0', id: 1, method: 'tools/list', params: {} },
+ });
+}
+
+test.describe('OAuth 2.1 for a cloud connector', () => {
+ test.skip(!EMAIL || !PASSWORD, 'needs AUDIT_EMAIL and AUDIT_PASSWORD (npm run audit:web:provision)');
+
+ test('Grok Bot registers, signs in with PKCE, lists tools, and is cut off the moment it is revoked', async ({ page, baseURL }) => {
+ test.setTimeout(300_000);
+ const origin = baseURL.replace(/\/$/, '');
+ // A context with no cookies, so every MCP call below is authorized by
+ // the bearer token alone, exactly as Grok Bot's cloud would send it.
+ const machine = await playwrightRequest.newContext();
+
+ // 1. Dynamic client registration, the way the connector discovers it.
+ const meta = await (await machine.get(`${origin}/.well-known/oauth-authorization-server`)).json();
+ expect(meta.code_challenge_methods_supported).toEqual(['S256']);
+ const registrationEndpoint = new URL(new URL(meta.registration_endpoint).pathname, origin).href;
+ const registered = await machine.post(registrationEndpoint, {
+ data: {
+ client_name: 'Grok Bot',
+ client_uri: 'https://grok.com',
+ redirect_uris: [CALLBACK],
+ grant_types: ['authorization_code', 'refresh_token'],
+ response_types: ['code'],
+ token_endpoint_auth_method: 'none',
+ scope: 'avatars:read avatars:write profile offline_access agents:read wallet:read wallet:write',
+ },
+ });
+ expect(registered.status(), await registered.text()).toBe(201);
+ const client = await registered.json();
+ expect(client.client_name).toBe('Grok Bot');
+ expect(client.redirect_uris).toEqual([CALLBACK]);
+
+ // 2. The person signs in to three.ws in their browser.
+ 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);
+
+ // 3. The connector sends them to the consent screen.
+ const { verifier, challenge } = pkcePair();
+ const state = base64url(randomBytes(12));
+ const authorize = new URL('/oauth/authorize', origin);
+ for (const [k, v] of Object.entries({
+ response_type: 'code', client_id: client.client_id, redirect_uri: CALLBACK, scope: client.scope,
+ state, code_challenge: challenge, code_challenge_method: 'S256', resource: `${origin}/api/mcp`,
+ })) authorize.searchParams.set(k, v);
+
+ await page.goto(authorize.href);
+ await expect(page.locator('h1')).toHaveText('Grok Bot wants to connect to your three.ws account');
+ await expect(page.locator('[data-fact="client-host"]')).toHaveText('grok.com');
+ await expect(page.locator('[data-fact="return-host"]')).toHaveText('connectors.grok-cloud.example');
+ await expect(page.getByText('three.ws has not verified this app')).toBeVisible();
+ await expect(page.locator('[data-scopes] li').first()).toBeVisible();
+ await expect(page.locator('[data-scopes]')).not.toContainText('Spend USDC');
+ const neverSpends = page.locator('[data-wallet="never-spends"]');
+ await expect(neverSpends).toBeVisible();
+ await expect(neverSpends).toContainText('It can never spend from your wallet.');
+ // The spend box starts unticked, and ticking it swaps the statement.
+ const spendBox = page.locator('#allow-spend');
+ await expect(spendBox).not.toBeChecked();
+ await spendBox.check();
+ await expect(page.locator('[data-wallet="may-spend"]')).toBeVisible();
+ await expect(neverSpends).toBeHidden();
+ await spendBox.uncheck();
+ await expect(neverSpends).toBeVisible();
+
+ // The browser follows the 302 to the connector's host, which proves the
+ // consent page's CSP form-action lets that cross-origin hop through.
+ const callbackRequest = page.waitForRequest((r) => r.url().startsWith(`${CALLBACK_ORIGIN}/`));
+ await page.getByRole('button', { name: 'Authorize' }).click();
+ const back = new URL((await callbackRequest).url());
+ expect(back.origin + back.pathname).toBe(CALLBACK);
+ expect(back.searchParams.get('state')).toBe(state);
+ const code = back.searchParams.get('code');
+ expect(code).toBeTruthy();
+
+ // 4. The connector exchanges the code with its PKCE verifier.
+ const tokenEndpoint = new URL(new URL(meta.token_endpoint).pathname, origin).href;
+ const wrongVerifier = await machine.post(tokenEndpoint, {
+ form: { grant_type: 'authorization_code', client_id: client.client_id, code, redirect_uri: CALLBACK, code_verifier: pkcePair().verifier, resource: `${origin}/api/mcp` },
+ });
+ expect(wrongVerifier.status()).toBe(400);
+ const exchanged = await machine.post(tokenEndpoint, {
+ form: { grant_type: 'authorization_code', client_id: client.client_id, code, redirect_uri: CALLBACK, code_verifier: verifier, resource: `${origin}/api/mcp` },
+ });
+ expect(exchanged.status(), await exchanged.text()).toBe(200);
+ const tokens = await exchanged.json();
+ expect(tokens.token_type).toBe('Bearer');
+ expect(tokens.refresh_token).toBeTruthy();
+ const granted = tokens.scope.split(' ');
+ expect(granted).not.toContain('wallet:write');
+ expect(granted).toContain('wallet:read');
+
+ // 5. The token works on the MCP server.
+ const listed = await toolsList(machine, origin, tokens.access_token);
+ expect(listed.status(), await listed.text()).toBe(200);
+ const listing = await listed.json();
+ expect(Array.isArray(listing.result?.tools)).toBe(true);
+ expect(listing.result.tools.length).toBeGreaterThan(0);
+
+ // 6. The person revokes it in Settings > Connected apps.
+ await page.goto(`${origin}/dashboard/settings#connected-apps`);
+ const row = page.locator(`#connected-apps [data-client-id="${client.client_id}"]`);
+ await expect(row).toBeVisible({ timeout: 60_000 });
+ await expect(row).toContainText('Grok Bot');
+ await expect(row).toContainText('grok.com');
+ page.once('dialog', (dialog) => dialog.accept());
+ await row.getByRole('button', { name: 'Revoke' }).click();
+ await expect(row).toHaveCount(0);
+
+ // 7. The very next call with the same access token is refused, and the
+ // refresh token can no longer mint a new one.
+ const afterRevoke = await toolsList(machine, origin, tokens.access_token);
+ expect(afterRevoke.status()).toBe(401);
+ const refreshed = await machine.post(tokenEndpoint, {
+ form: { grant_type: 'refresh_token', client_id: client.client_id, refresh_token: tokens.refresh_token, resource: `${origin}/api/mcp` },
+ });
+ expect(refreshed.status()).toBe(400);
+
+ await machine.dispose();
+ });
+});
diff --git a/tests/oauth-endpoints.test.js b/tests/oauth-endpoints.test.js
index 1d48182f3..0d904f002 100644
--- a/tests/oauth-endpoints.test.js
+++ b/tests/oauth-endpoints.test.js
@@ -28,6 +28,9 @@ vi.mock('../api/_lib/zauth.js', () => ({ instrument: () => {}, drain: async () =
vi.mock('../api/_lib/sentry.js', () => ({ captureException: () => {} }));
vi.mock('../api/_lib/audit.js', () => ({ logAudit: vi.fn() }));
vi.mock('../api/_lib/streaks.js', () => ({ recordDailyActivity: vi.fn(async () => {}) }));
+// Connected apps (DELETE /oauth/grants) checks the dashboard's CSRF token, which
+// lives in its own table; that check has its own suite.
+vi.mock('../api/_lib/csrf.js', () => ({ requireCsrf: vi.fn(async () => true) }));
vi.mock('../api/_lib/rate-limit.js', () => ({
limits: {
authIp: vi.fn(async () => ({ success: true })),
@@ -55,7 +58,7 @@ const sqlMock = vi.fn(async (strings, ...values) => {
}
if (text.startsWith('insert into oauth_clients')) {
const [client_id, client_secret_hash, client_type, name, logo_uri, client_uri, redirect_uris, grant_types, response_types, token_endpoint_auth, scope] = values;
- db.clients.push({ client_id, client_secret_hash, client_type, name, logo_uri, client_uri, redirect_uris, grant_types, response_types, token_endpoint_auth, scope });
+ db.clients.push({ client_id, client_secret_hash, client_type, name, logo_uri, client_uri, redirect_uris, grant_types, response_types, token_endpoint_auth, scope, dynamically_registered: true });
return [];
}
if (text.startsWith('insert into oauth_auth_codes')) {
@@ -76,7 +79,7 @@ const sqlMock = vi.fn(async (strings, ...values) => {
}
if (text.startsWith('insert into oauth_refresh_tokens')) {
const [token_hash, client_id, user_id, scope, resource] = values;
- const row = { id: `rt-${db.refresh.length + 1}`, token_hash, client_id, user_id, scope, resource, revoked_at: null, replaced_by: null, expires_at: future(2_592_000) };
+ const row = { id: `rt-${db.refresh.length + 1}`, token_hash, client_id, user_id, scope, resource, revoked_at: null, replaced_by: null, last_used_at: null, created_at: new Date().toISOString(), expires_at: future(2_592_000) };
db.refresh.push(row);
return [{ id: row.id }];
}
@@ -103,10 +106,39 @@ 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 revoked = [];
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();
+ revoked.push({ id: r.id });
+ }
}
- return [];
+ return revoked;
+ }
+ // oauthGrantRevoked (api/_lib/auth.js): stamp last use on the live row, then
+ // ask whether the grant was ended at or after the token was issued.
+ if (text.startsWith('with touched as ( update oauth_refresh_tokens set last_used_at')) {
+ const [liveUser, liveClient, userId, clientId, issuedAt] = values;
+ for (const r of db.refresh) {
+ if (r.user_id === liveUser && r.client_id === liveClient && !r.revoked_at) r.last_used_at = new Date().toISOString();
+ }
+ const revoked = db.refresh.some((r) => r.user_id === userId && r.client_id === clientId && !r.replaced_by
+ && r.revoked_at && Date.parse(r.revoked_at) >= issuedAt * 1000);
+ return [{ revoked }];
+ }
+ // handleGrants GET: one row per client holding a live refresh token.
+ if (text.startsWith('select c.client_id, c.name, c.client_uri')) {
+ const [userId] = values;
+ const live = db.refresh.filter((r) => r.user_id === userId && !r.revoked_at);
+ return [...new Set(live.map((r) => r.client_id))].map((clientId) => {
+ const c = db.clients.find((x) => x.client_id === clientId);
+ const rows = live.filter((r) => r.client_id === clientId);
+ return {
+ client_id: clientId, name: c.name, client_uri: c.client_uri ?? null, logo_uri: null, software_id: null, software_version: null,
+ authorized_at: rows[0].created_at ?? null, last_used_at: rows.map((r) => r.last_used_at).filter(Boolean).sort().pop() ?? null,
+ scopes: rows.map((r) => r.scope).join(' '),
+ };
+ });
}
throw new Error(`unmodeled query: ${text}`);
});
@@ -127,7 +159,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 ─────────────────────────────────────────────────
@@ -248,9 +280,9 @@ describe('GET /oauth/authorize', () => {
const res = await call('authorize', { query: authorizeQuery({ scope: 'memory:write' }) });
expect(res.statusCode).toBe(200);
expect(res.getHeader('content-type')).toContain('text/html');
- expect(res.body).toContain('Read your avatars');
+ expect(res.body).toContain('See your avatars');
expect(res.body).toContain('See your name and email');
- expect(res.body).not.toContain('Store and forget');
+ expect(res.body).not.toContain('Save and erase');
});
it('allows the client origin in form-action so the post-consent 302 is not blocked', async () => {
@@ -559,6 +591,206 @@ describe('POST /oauth/register', () => {
});
});
+// A cloud connector (Grok Bot, claude.ai) registers from a cloud we have never
+// seen, with a callback on a host nobody could list in advance. Any https URI
+// has to work for it, and nothing that would carry the code in plain text or
+// off to a non-browser handler may.
+describe('POST /oauth/register for a cloud connector', () => {
+ const GROK = { client_name: 'Grok Bot', client_uri: 'https://grok.com', redirect_uris: ['https://connectors.grok-cloud.example/oauth/callback/3f9a'], scope: 'avatars:read avatars:write profile offline_access wallet:read wallet:write' };
+
+ it('registers Grok Bot with an https callback on an unpredictable host and keeps its name and site for consent', async () => {
+ const res = await call('register', { method: 'POST', jsonBody: GROK });
+ expect(res.statusCode).toBe(201);
+ const body = res.json();
+ expect(body.client_name).toBe('Grok Bot');
+ expect(body.client_uri).toBe('https://grok.com');
+ expect(body.redirect_uris).toEqual(GROK.redirect_uris);
+ expect(db.clients[0]).toMatchObject({ name: 'Grok Bot', client_uri: 'https://grok.com', client_type: 'public' });
+
+ const consent = await call('authorize', { query: { ...authorizeQuery({ client_id: body.client_id, redirect_uri: GROK.redirect_uris[0] }) } });
+ expect(consent.statusCode).toBe(200);
+ expect(consent.body).toContain('<b>Grok Bot</b> wants to connect to your three.ws account');
+ });
+
+ it.each([
+ ['plain http on a public host', 'http://connectors.grok-cloud.example/oauth/callback'],
+ ['ftp', 'ftp://connectors.grok-cloud.example/oauth/callback'],
+ ['an unencrypted websocket', 'ws://connectors.grok-cloud.example/oauth/callback'],
+ ['an encrypted websocket', 'wss://connectors.grok-cloud.example/oauth/callback'],
+ ['mailto', 'mailto:/[email protected]'],
+ ['javascript', 'javascript:alert(1)'],
+ ])('rejects %s, which is neither https nor loopback', async (_label, uri) => {
+ const res = await call('register', { method: 'POST', jsonBody: { ...GROK, redirect_uris: [uri] } });
+ expect(res.statusCode).toBe(400);
+ expect(res.json().error).toBe('invalid_redirect_uri');
+ expect(db.clients).toHaveLength(0);
+ });
+
+ it.each([
+ ['localhost', 'http://localhost:6274/oauth/callback'],
+ ['127.0.0.1', 'http://127.0.0.1:33418/callback'],
+ ['IPv6 loopback', 'http://[::1]:8080/cb'],
+ ])('accepts plain http on %s for a desktop client', async (_label, uri) => {
+ const res = await call('register', { method: 'POST', jsonBody: { ...GROK, redirect_uris: [uri] } });
+ expect(res.statusCode).toBe(201);
+ });
+});
+
+describe('consent screen for a cloud connector', () => {
+ const grok = (overrides = {}) => seedClient({
+ name: 'Grok Bot',
+ client_uri: 'https://grok.com',
+ redirect_uris: ['https://client.example/cb'],
+ scope: 'avatars:read profile wallet:write',
+ dynamically_registered: true,
+ ...overrides,
+ });
+
+ it('names the client, its site host and where the code goes, and says it can never spend', async () => {
+ grok();
+ const res = await call('authorize', { query: authorizeQuery() });
+ expect(res.statusCode).toBe(200);
+ expect(res.body).toContain('<b>Grok Bot</b> wants to connect');
+ expect(res.body).toContain('<dd data-fact="client-host">grok.com</dd>');
+ expect(res.body).toContain('<dd data-fact="return-host">client.example</dd>');
+ expect(res.body).toContain('three.ws has not verified this app');
+ expect(res.body).toContain('It can never spend from your wallet.');
+ expect(res.body).toContain('<li>See your avatars</li>');
+ expect(res.body).toContain('<li>See your name and email address</li>');
+ });
+
+ it('keeps the spend scope out of the list and behind an unticked box', async () => {
+ grok();
+ const res = await call('authorize', { query: authorizeQuery() });
+ const list = res.body.match(/<ul data-scopes>(.*?)<\/ul>/)[1];
+ expect(list).not.toContain('Spend USDC');
+ expect(list).toContain('See your agent wallet balance and spending caps');
+ expect(res.body).toMatch(/<input type="checkbox" id="allow-spend" name="allow_spend" value="yes">/);
+ expect(res.body).not.toMatch(/id="allow-spend"[^>]*checked/);
+ });
+
+ it('shows no spend box when the client never asked to spend', async () => {
+ grok({ scope: 'avatars:read profile' });
+ const res = await call('authorize', { query: authorizeQuery() });
+ expect(res.body).not.toContain('allow_spend');
+ expect(res.body).toContain('It can never spend from your wallet.');
+ });
+
+ it('escapes a hostile client name everywhere it appears', async () => {
+ grok({ name: '<img src=x onerror=alert(1)>' });
+ const res = await call('authorize', { query: authorizeQuery() });
+ expect(res.body).not.toContain('<img src=x');
+ expect(res.body).toContain('&lt;img src=x onerror=alert(1)&gt;');
+ });
+
+ it('grants wallet:read, not wallet:write, when the person leaves the box unticked', async () => {
+ grok();
+ await approve({ scope: 'avatars:read profile wallet:write' });
+ expect(db.codes[0].scope.split(' ').sort()).toEqual(['avatars:read', 'profile', 'wallet:read']);
+ });
+
+ it('grants wallet:write only when the person ticks the box', async () => {
+ grok();
+ await approve({ scope: 'avatars:read profile wallet:write', allow_spend: 'yes' });
+ expect(db.codes[0].scope.split(' ')).toContain('wallet:write');
+ });
+});
+
+// Revoking an app has to stop it on its next call. Access tokens are JWTs,
+// so before this the app kept working for up to an hour after Revoke.
+describe('revocation is effective within one request', () => {
+ const mcpAudience = { audience: RESOURCE };
+
+ async function revokeInConnectedApps(clientId = 'mcp_test_client') {
+ return call('grants', { method: 'DELETE', query: { client_id: clientId } });
+ }
+
+ it('rejects the access token on the very next request after Revoke in Connected apps', async () => {
+ seedClient();
+ const { access_token } = await issueTokens();
+ expect(await authenticateBearer(access_token, mcpAudience)).toMatchObject({ userId: 'user-1', clientId: 'mcp_test_client', source: 'oauth' });
+
+ const revoked = await revokeInConnectedApps();
+ expect(revoked.statusCode).toBe(200);
+ expect(revoked.json()).toEqual({ client_id: 'mcp_test_client', revoked: 1 });
+
+ expect(await authenticateBearer(access_token, mcpAudience)).toBeNull();
+ const introspected = await call('introspect', { method: 'POST', form: { token: access_token, client_id: 'mcp_test_client' } });
+ expect(introspected.json()).toEqual({ active: false });
+ });
+
+ it('also refuses the revoked refresh token, so the app cannot mint a fresh access token', async () => {
+ seedClient();
+ const { refresh_token } = await issueTokens();
+ await revokeInConnectedApps();
+ const res = await call('token', { method: 'POST', form: { grant_type: 'refresh_token', client_id: 'mcp_test_client', refresh_token } });
+ expect(res.statusCode).toBe(400);
+ });
+
+ it('ends the access token when the client revokes its own refresh token (RFC 7009)', async () => {
+ seedClient();
+ const { access_token, refresh_token } = await issueTokens();
+ await call('revoke', { method: 'POST', form: { token: refresh_token, client_id: 'mcp_test_client' } });
+ expect(await authenticateBearer(access_token, mcpAudience)).toBeNull();
+ });
+
+ it('does not cut off the access token a normal refresh replaced', async () => {
+ seedClient();
+ const { access_token, refresh_token } = await issueTokens();
+ const refreshed = await call('token', { method: 'POST', form: { grant_type: 'refresh_token', client_id: 'mcp_test_client', refresh_token } });
+ expect(refreshed.statusCode).toBe(200);
+ expect(await authenticateBearer(access_token, mcpAudience)).not.toBeNull();
+ expect(await authenticateBearer(refreshed.json().access_token, mcpAudience)).not.toBeNull();
+ });
+
+ it('leaves another app the same person connected untouched', async () => {
+ seedClient();
+ seedClient({ client_id: 'mcp_other_client', name: 'Other App' });
+ const mine = await issueTokens();
+ const authorized = await approve({ client_id: 'mcp_other_client' });
+ const code = new URL(authorized.getHeader('location')).searchParams.get('code');
+ const other = (await call('token', { method: 'POST', form: { grant_type: 'authorization_code', client_id: 'mcp_other_client', code, redirect_uri: 'https://client.example/cb', code_verifier: VERIFIER } })).json();
+
+ await revokeInConnectedApps('mcp_test_client');
+ expect(await authenticateBearer(mine.access_token, mcpAudience)).toBeNull();
+ expect(await authenticateBearer(other.access_token, mcpAudience)).toMatchObject({ clientId: 'mcp_other_client' });
+ });
+
+ it('lets the person connect the app again after revoking it', async () => {
+ seedClient();
+ vi.useFakeTimers({ toFake: ['Date'] });
+ try {
+ await issueTokens();
+ await revokeInConnectedApps();
+ vi.setSystemTime(Date.now() + 2_000);
+ db.codes.length = 0;
+ const again = await issueTokens();
+ expect(await authenticateBearer(again.access_token, mcpAudience)).toMatchObject({ clientId: 'mcp_test_client' });
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('lists the connected app with its site host and last use, then drops it after Revoke', async () => {
+ seedClient({ name: 'Grok Bot', client_uri: 'https://grok.com' });
+ const { access_token } = await issueTokens();
+ await authenticateBearer(access_token, mcpAudience);
+ const listed = (await call('grants')).json().grants;
+ expect(listed).toHaveLength(1);
+ expect(listed[0]).toMatchObject({ client_id: 'mcp_test_client', name: 'Grok Bot', client_host: 'grok.com', can_spend: false });
+ expect(listed[0].last_used_at).toBeTruthy();
+
+ await revokeInConnectedApps();
+ expect((await call('grants')).json().grants).toEqual([]);
+ });
+
+ it('refuses to list or revoke apps without a signed-in session', async () => {
+ getSessionUser.mockResolvedValue(null);
+ expect((await call('grants')).statusCode).toBe(401);
+ expect((await revokeInConnectedApps()).statusCode).toBe(401);
+ });
+});
+
describe('POST /oauth/revoke', () => {
it('revokes a refresh token', async () => {
seedClient();
diff --git a/vite.config.js b/vite.config.js
index fccf024b2..6e0893998 100644
--- a/vite.config.js
+++ b/vite.config.js
@@ -404,6 +404,19 @@ const appConfig = {
},
}
: {}),
+ // The OAuth authorization server lives at /oauth/* in the metadata
+ // (/.well-known/oauth-authorization-server), and vercel.json rewrites
+ // those paths to api/oauth/[action]. Vite dev runs no functions, so an
+ // MCP client signing in through the dev server, and the /login return
+ // trip to /oauth/consent, hit the SPA fallback instead of the consent
+ // screen. Forward them like the rest of the API. Vite tests the pattern
+ // against the URL with its query string, which every authorize request
+ // carries, so the end anchor allows one.
+ '^/oauth/(?:authorize|consent|token|register|revoke|introspect)/?(?:\\?|$)': {
+ target: DEV_API_PROXY,
+ changeOrigin: true,
+ secure: true,
+ },
// /openapi.json is generated by the api/openapi-json function and
// rewritten from /openapi.json in prod (vercel.json). Vite dev does
// not run that function, so forward the bare path to the upstream so