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(cli): device-link sign-in, whoami and loopback OAuth for the three-ws CLI

qhqf02796e42482d
diff --git a/api/_lib/api-keys.js b/api/_lib/api-keys.js
new file mode 100644
index 000000000..d04b2e932
--- /dev/null
+++ b/api/_lib/api-keys.js
@@ -0,0 +1,67 @@
+// API key scopes and minting, shared by every surface that issues a key:
+// /api/keys (the dashboard), /api/api-keys (the legacy route), and the CLI
+// device link (/api/cli/token). Each route used to carry its own copy of the
+// scope set, so a scope added for one surface was silently refused by another.
+
+import { sql } from './db.js';
+import { randomToken, sha256 } from './crypto.js';
+import { logAudit } from './audit.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
+// carrying them: every spend still passes the server-side caps and
+// THREEWS_AGENT_PAY_ENABLED, so a key is never a wider grant than consent.
+export const API_KEY_SCOPES = Object.freeze([
+ 'avatars:read',
+ 'avatars:write',
+ 'avatars:delete',
+ 'profile',
+ 'memory:read',
+ 'memory:write',
+ 'agents:read',
+ 'agents:write',
+ 'herald:announce',
+ 'wallet:read',
+ 'wallet:write',
+ 'services:write',
+ // Model calls on the OpenAI-compatible endpoint (/api/v1/chat/completions),
+ // billed to the account's credits. Keys minted by /api/me/inference/provision
+ // carry this scope alone, so a leaked inference key can spend credits on
+ // model calls and nothing else: no wallet, no agents, no profile.
+ 'inference',
+]);
+
+const ALLOWED = new Set(API_KEY_SCOPES);
+
+/**
+ * Split, dedupe and validate a space-separated scope string.
+ * @returns {{ scopes: string[], invalid: string[] }}
+ */
+export function normalizeKeyScopes(scope) {
+ const scopes = [...new Set(String(scope || '').split(/\s+/).filter(Boolean))];
+ return { scopes, invalid: scopes.filter((s) => !ALLOWED.has(s)) };
+}
+
+/**
+ * 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.
+ */
+export async function mintApiKey({ userId, name, scopes, expiresAt = null, environment = 'live', req = null, via = 'dashboard' }) {
+ const raw = `sk_${environment}_${randomToken(28)}`;
+ const hash = await sha256(raw);
+ const prefix = raw.slice(0, 12);
+ const [row] = await sql`
+ insert into api_keys (user_id, name, prefix, token_hash, scope, expires_at)
+ values (${userId}, ${name}, ${prefix}, ${hash}, ${scopes.join(' ')}, ${expiresAt})
+ returning id, name, prefix, scope, expires_at, created_at
+ `;
+ // Never the secret or its hash, only the id, prefix, and granted scope.
+ logAudit({
+ userId,
+ action: 'create_api_key',
+ resourceId: row.id,
+ meta: { prefix, scope: row.scope, environment, via },
+ req,
+ });
+ return { row, secret: raw };
+}
diff --git a/api/_lib/migrations/20260922130000_cli_link_requests.sql b/api/_lib/migrations/20260922130000_cli_link_requests.sql
new file mode 100644
index 000000000..97619508c
--- /dev/null
+++ b/api/_lib/migrations/20260922130000_cli_link_requests.sql
@@ -0,0 +1,46 @@
+-- Device links for the `three-ws` CLI (api/cli/[action].js, /cli/authorize).
+--
+-- `three-ws login --key` (and `setup` when the loopback OAuth redirect cannot
+-- reach the terminal, e.g. over SSH) starts a link: the CLI receives a secret
+-- device code it keeps to itself and a short user code it prints next to a URL.
+-- The person opens /cli/authorize, signs in, checks that the code on the page is
+-- the one in their terminal, and approves the scopes. The CLI polls with the
+-- device code and, on the first poll after approval, receives a freshly minted
+-- API key exactly once. This is the RFC 8628 device authorization grant shape,
+-- issuing a three.ws API key instead of an OAuth token.
+--
+-- device_code_hash sha256 of the device code. The plaintext is only ever in
+-- the CLI's memory, so a read of this table cannot finish a
+-- link that somebody else started.
+-- user_code What the person types or compares, XXXX-XXXX from an
+-- unambiguous consonant alphabet. Unique while it lives.
+-- requested_scope What the CLI asked for. The approver may narrow it.
+-- granted_scope What the approver allowed; the minted key carries this.
+-- status pending -> approved | denied, then approved -> consumed
+-- when the key is handed over. A consumed row never mints
+-- again, which is what makes the key single delivery.
+-- api_key_id The key this link minted, so /settings can say which
+-- machine a key came from and revoking it is one click.
+
+create table if not exists cli_link_requests (
+ id uuid primary key default gen_random_uuid(),
+ device_code_hash text not null unique,
+ user_code text not null unique,
+ client_name text not null,
+ hostname text,
+ requested_scope text not null,
+ granted_scope text,
+ user_id uuid references users(id) on delete cascade,
+ status text not null default 'pending'
+ check (status in ('pending', 'approved', 'denied', 'consumed')),
+ api_key_id uuid references api_keys(id) on delete set null,
+ created_ip text,
+ created_at timestamptz not null default now(),
+ expires_at timestamptz not null,
+ decided_at timestamptz,
+ consumed_at timestamptz,
+ last_polled_at timestamptz
+);
+
+create index if not exists cli_link_requests_expires_idx on cli_link_requests (expires_at);
+create index if not exists cli_link_requests_user_idx on cli_link_requests (user_id) where user_id is not null;
diff --git a/api/_lib/rate-limit.js b/api/_lib/rate-limit.js
index a78c79e45..ef0974e24 100644
--- a/api/_lib/rate-limit.js
+++ b/api/_lib/rate-limit.js
@@ -631,6 +631,16 @@ export const limits = {
getLimiter('auth:ip', { limit: 50, window: '10 m', critical: true, degradeToMemory: true }).limit(ip),
registerIp: (ip) =>
getLimiter('register:ip', { limit: 5, window: '1 h', critical: true, degradeToMemory: true }).limit(ip),
+ // `three-ws login` device links (api/cli/[action].js). Starting a link is
+ // unauthenticated, so it is capped per IP: 20 per 10 min covers a developer
+ // retrying across several machines behind one NAT and stops a script from
+ // flooding the table with codes. Polling is keyed on the device code itself
+ // and clears one poll every three seconds for the full ten-minute life of a
+ // code; anything faster is answered `slow_down` by the handler first.
+ cliLinkIp: (ip) =>
+ getLimiter('cli:link:ip', { limit: 20, window: '10 m', critical: true, degradeToMemory: true }).limit(ip),
+ cliPoll: (deviceHash) =>
+ getLimiter('cli:poll', { limit: 240, window: '10 m', local: true }).limit(deviceHash),
// Open inference network (api/nodes/*). Node registration is an idempotent
// upsert an operator runs once per boot, so it gets a tight per-IP ceiling.
// The poll loop and result submission are the node's steady-state traffic:
diff --git a/api/_lib/schema.sql b/api/_lib/schema.sql
index be4ee58c1..a12c92fbe 100644
--- a/api/_lib/schema.sql
+++ b/api/_lib/schema.sql
@@ -2543,3 +2543,30 @@ create index if not exists agent_memories_x_seed_consent
-- The X OAuth callback never supplied social_connections.scopes, which is NOT
-- NULL with no default, so every X connect died before writing a row.
alter table social_connections alter column scopes set default '';
+
+-- ── CLI device links ─────────────────────────────────────────────────────────
+-- `three-ws login --device` (api/cli/[action].js, /cli/authorize). The CLI keeps
+-- the device code; only its sha256 is stored. An approved row mints one API key
+-- on the next poll and becomes `consumed`, so the key is delivered exactly once.
+-- Full rationale: api/_lib/migrations/20260922130000_cli_link_requests.sql.
+create table if not exists cli_link_requests (
+ id uuid primary key default gen_random_uuid(),
+ device_code_hash text not null unique,
+ user_code text not null unique,
+ client_name text not null,
+ hostname text,
+ requested_scope text not null,
+ granted_scope text,
+ user_id uuid references users(id) on delete cascade,
+ status text not null default 'pending'
+ check (status in ('pending', 'approved', 'denied', 'consumed')),
+ api_key_id uuid references api_keys(id) on delete set null,
+ created_ip text,
+ created_at timestamptz not null default now(),
+ expires_at timestamptz not null,
+ decided_at timestamptz,
+ consumed_at timestamptz,
+ last_polled_at timestamptz
+);
+create index if not exists cli_link_requests_expires_idx on cli_link_requests (expires_at);
+create index if not exists cli_link_requests_user_idx on cli_link_requests (user_id) where user_id is not null;
diff --git a/api/_mcp/auth.js b/api/_mcp/auth.js
index 0cfde74a0..1c5ac6ca7 100644
--- a/api/_mcp/auth.js
+++ b/api/_mcp/auth.js
@@ -14,6 +14,16 @@ function quoteString(s) {
return `"${String(s).replace(/[\\"]/g, '\\$&')}"`;
}
+// Every 401 from a hosted MCP server tells a person reading it how to fix it
+// with one command. An MCP client runs its own OAuth off the WWW-Authenticate
+// header and ignores these fields; a developer looking at a raw 401 in curl or
+// a client log gets the answer instead of a trip through the docs.
+export const SETUP_HINT = Object.freeze({
+ command: 'npx three-ws setup',
+ message: 'Run `npx three-ws setup` to sign in and wire three.ws into your MCP client in one step.',
+ docs: 'https://three.ws/docs/cli',
+});
+
export function send401(res, msg) {
const resource = env.MCP_RESOURCE;
res.statusCode = 401;
@@ -22,7 +32,7 @@ export function send401(res, msg) {
`Bearer resource_metadata=${quoteString(`${env.APP_ORIGIN}/.well-known/oauth-protected-resource`)}, resource=${quoteString(resource)}`,
);
res.setHeader('content-type', 'application/json; charset=utf-8');
- res.end(JSON.stringify({ error: 'unauthorized', error_description: msg }));
+ res.end(JSON.stringify({ error: 'unauthorized', error_description: msg, setup: SETUP_HINT }));
}
// MCP clients speaking Streamable HTTP MUST advertise SSE support in Accept
@@ -81,8 +91,11 @@ export async function sendAuthChallenge(res, { req, resourceUrl, requirements, c
// build402Body's defaults, used by the main /api/mcp server.
// build402Body is async (it signs per-accept offer receipts), so await it —
// stringifying the unresolved Promise shipped an empty `{}` envelope before.
- const body = await build402Body({ resourceUrl, accepts: requirements, ...(challenge || {}) });
- const headerValue = paymentRequiredHeaderValue(body);
+ const envelope = await build402Body({ resourceUrl, accepts: requirements, ...(challenge || {}) });
+ const headerValue = paymentRequiredHeaderValue(envelope);
+ // The setup hint rides only on the 401 a protocol client receives; the 402
+ // stays the exact x402 envelope that payment tooling and audits parse.
+ const body = isProtocolClient ? { ...envelope, setup: SETUP_HINT } : envelope;
if (headerValue) res.setHeader('PAYMENT-REQUIRED', headerValue);
res.setHeader('content-type', 'application/json; charset=utf-8');
res.setHeader('cache-control', 'no-store');
diff --git a/api/api-keys.js b/api/api-keys.js
index de334427f..11d3afc16 100644
--- a/api/api-keys.js
+++ b/api/api-keys.js
@@ -6,8 +6,9 @@ import { limits, clientIp } from './_lib/rate-limit.js';
import { requireCsrf } from './_lib/csrf.js';
import { parse } from './_lib/validate.js';
import { z } from 'zod';
+import { API_KEY_SCOPES } from './_lib/api-keys.js';
-const ALLOWED_SCOPES = new Set(['avatars:read', 'avatars:write', 'avatars:delete', 'profile', 'memory:read', 'memory:write', 'agents:read', 'agents:write', 'herald:announce']);
+const ALLOWED_SCOPES = new Set(API_KEY_SCOPES);
const createSchema = z.object({
name: z.string().trim().min(1).max(80),
diff --git a/api/cli/[action].js b/api/cli/[action].js
new file mode 100644
index 000000000..9ffaa89ef
--- /dev/null
+++ b/api/cli/[action].js
@@ -0,0 +1,317 @@
+// The `three-ws` CLI's server half (packages/three-ws-cli).
+//
+// POST /api/cli/link start a device link: { client_name, hostname, scope }
+// -> { device_code, user_code, verification_uri, ... }
+// GET /api/cli/link ?code=XXXX-XXXX, signed in: what the link is asking for
+// POST /api/cli/approve signed in + CSRF: { code, decision, scope } allow or deny
+// POST /api/cli/token { device_code }: poll; hands over the minted key once
+// GET /api/cli/whoami Bearer: the account, credential, plan and agent wallet
+//
+// The link is the RFC 8628 device authorization grant, issuing a three.ws API
+// key instead of an OAuth token. It exists for the two places a loopback OAuth
+// redirect cannot reach: a terminal over SSH or in a container, and an API key
+// that the stdio `@three-ws/*-mcp` packages read from their env block. Error
+// codes on the poll are RFC 8628 §3.5's, so any device-flow client reads them.
+//
+// Approval is a person in a browser. `approve` refuses every bearer principal,
+// API keys and OAuth tokens included: a credential must never be able to widen
+// itself into a new credential without a human pressing the button.
+
+import { randomInt } from 'node:crypto';
+import { sql } from '../_lib/db.js';
+import { getSessionUser, authenticateBearer, extractBearer, hasScope } from '../_lib/auth.js';
+import { randomToken, sha256 } from '../_lib/crypto.js';
+import { cors, error, json, method, rateLimited, readJson, wrap } from '../_lib/http.js';
+import { limits, clientIp } from '../_lib/rate-limit.js';
+import { requireCsrf } from '../_lib/csrf.js';
+import { env } from '../_lib/env.js';
+import { API_KEY_SCOPES, mintApiKey, normalizeKeyScopes } from '../_lib/api-keys.js';
+import { getUserWalletStatus } from '../_lib/x402-user-payer.js';
+import { logAudit } from '../_lib/audit.js';
+
+const LINK_TTL_SECONDS = 600;
+const POLL_INTERVAL_SECONDS = 3;
+// RFC 8628 §6.1: consonants only, no vowels (so no words) and no characters
+// that read alike (0/O, 1/I/L). 19^8 is ~1.7e10 codes, and a code only lives
+// ten minutes behind a signed-in session, so guessing one is not a strategy.
+const USER_CODE_ALPHABET = 'BCDFGHJKMNPQRSTVWXZ';
+const DEFAULT_SCOPE = 'profile avatars:read avatars:write memory:read memory:write agents:read wallet:read';
+
+const SCOPE_LABELS = {
+ 'avatars:read': 'Read your avatars',
+ 'avatars:write': 'Create and update avatars',
+ 'avatars:delete': 'Delete your avatars',
+ profile: 'See your name, email and plan',
+ 'memory:read': 'Recall your agents’ memories',
+ 'memory:write': 'Store and forget your agents’ 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 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',
+ inference: 'Call models on your credits through the OpenAI-compatible endpoint',
+};
+// Scopes that let the key move money. The authorize page marks them so the
+// person sees the difference before they approve, not after.
+const FINANCIAL_SCOPES = new Set(['wallet:write', 'services:write']);
+
+export function generateUserCode() {
+ let out = '';
+ for (let i = 0; i < 8; i++) out += USER_CODE_ALPHABET[randomInt(USER_CODE_ALPHABET.length)];
+ return `${out.slice(0, 4)}-${out.slice(4)}`;
+}
+
+// Accepts what a person actually types: lower case, spaces, a missing dash.
+export function normalizeUserCode(input) {
+ const letters = String(input || '').toUpperCase().replace(/[^A-Z]/g, '');
+ if (letters.length !== 8) return null;
+ for (const c of letters) if (!USER_CODE_ALPHABET.includes(c)) return null;
+ return `${letters.slice(0, 4)}-${letters.slice(4)}`;
+}
+
+function cleanLabel(value, max) {
+ const s = String(value ?? '').replace(/[\u0000-\u001f\u007f]/g, '').trim();
+ return s ? s.slice(0, max) : null;
+}
+
+function describeScopes(scope) {
+ return String(scope || '').split(/\s+/).filter(Boolean).map((s) => ({
+ scope: s,
+ label: SCOPE_LABELS[s] || s,
+ financial: FINANCIAL_SCOPES.has(s),
+ }));
+}
+
+function publicLink(row) {
+ return {
+ user_code: row.user_code,
+ client_name: row.client_name,
+ hostname: row.hostname,
+ status: row.status,
+ requested_scopes: describeScopes(row.requested_scope),
+ created_at: row.created_at,
+ expires_at: row.expires_at,
+ expired: new Date(row.expires_at) < new Date(),
+ };
+}
+
+// ── link: start (POST, unauthenticated) and inspect (GET, signed in) ─────────
+
+async function handleLink(req, res) {
+ if (req.method === 'GET') return inspectLink(req, res);
+ const rl = await limits.cliLinkIp(clientIp(req));
+ if (!rl.success) return rateLimited(res, rl, 'too many sign-in links from this network, wait a few minutes');
+
+ const body = (await readJson(req, 4_000).catch(() => null)) || {};
+ const { scopes, invalid } = normalizeKeyScopes(body.scope || DEFAULT_SCOPE);
+ if (invalid.length) return error(res, 400, 'invalid_scope', `unknown scopes: ${invalid.join(', ')}`);
+ if (!scopes.length) return error(res, 400, 'invalid_scope', 'scope must name at least one permission');
+
+ const deviceCode = randomToken(32);
+ const deviceHash = await sha256(deviceCode);
+ const clientName = cleanLabel(body.client_name, 80) || 'three-ws CLI';
+ const hostname = cleanLabel(body.hostname, 120);
+
+ // A user-code collision is astronomically unlikely but the column is unique,
+ // so retry on the constraint instead of surfacing a 500 for it.
+ let userCode = null;
+ for (let attempt = 0; attempt < 5 && !userCode; attempt++) {
+ const candidate = generateUserCode();
+ const rows = await sql`
+ insert into cli_link_requests (device_code_hash, user_code, client_name, hostname, requested_scope, created_ip, expires_at)
+ values (${deviceHash}, ${candidate}, ${clientName}, ${hostname}, ${scopes.join(' ')}, ${clientIp(req)}, now() + ${`${LINK_TTL_SECONDS} seconds`}::interval)
+ on conflict (user_code) do nothing
+ returning user_code
+ `;
+ if (rows[0]) userCode = rows[0].user_code;
+ }
+ if (!userCode) return error(res, 503, 'unavailable', 'could not allocate a sign-in code, try again');
+
+ const verificationUri = `${env.APP_ORIGIN}/cli/authorize`;
+ return json(res, 201, {
+ device_code: deviceCode,
+ user_code: userCode,
+ verification_uri: verificationUri,
+ verification_uri_complete: `${verificationUri}?code=${encodeURIComponent(userCode)}`,
+ expires_in: LINK_TTL_SECONDS,
+ interval: POLL_INTERVAL_SECONDS,
+ scope: scopes.join(' '),
+ }, { 'cache-control': 'no-store' });
+}
+
+async function inspectLink(req, res) {
+ const user = await getSessionUser(req);
+ if (!user) return error(res, 401, 'unauthorized', 'sign in to approve a CLI sign-in');
+ const rl = await limits.authedReadIp(clientIp(req));
+ if (!rl.success) return rateLimited(res, rl);
+ const code = normalizeUserCode(new URL(req.url, 'http://x').searchParams.get('code'));
+ if (!code) return error(res, 400, 'invalid_code', 'that is not a three-ws sign-in code; codes look like BCDF-GHJK');
+ const [row] = await sql`select * from cli_link_requests where user_code = ${code} limit 1`;
+ if (!row) return error(res, 404, 'unknown_code', 'no sign-in is waiting for that code');
+ if (row.user_id && row.user_id !== user.id) return error(res, 404, 'unknown_code', 'no sign-in is waiting for that code');
+ return json(res, 200, {
+ link: publicLink(row),
+ account: { email: user.email, display_name: user.display_name || null },
+ available_scopes: describeScopes(API_KEY_SCOPES.join(' ')),
+ }, { 'cache-control': 'no-store' });
+}
+
+// ── approve (POST, browser session only) ─────────────────────────────────────
+
+async function handleApprove(req, res) {
+ if (!method(req, res, ['POST'])) return;
+ if (extractBearer(req)) return error(res, 403, 'forbidden', 'a CLI sign-in is approved by a person in a browser, not by a token');
+ const user = await getSessionUser(req);
+ if (!user) return error(res, 401, 'unauthorized', 'sign in to approve a CLI sign-in');
+ const rl = await limits.authIp(clientIp(req));
+ if (!rl.success) return rateLimited(res, rl);
+ if (!(await requireCsrf(req, res, user.id))) return;
+
+ const body = (await readJson(req, 4_000).catch(() => null)) || {};
+ const code = normalizeUserCode(body.code);
+ if (!code) return error(res, 400, 'invalid_code', 'that is not a three-ws sign-in code');
+ const decision = body.decision === 'allow' ? 'allow' : body.decision === 'deny' ? 'deny' : null;
+ if (!decision) return error(res, 400, 'invalid_request', 'decision must be allow or deny');
+
+ const [row] = await sql`select * from cli_link_requests where user_code = ${code} limit 1`;
+ if (!row) return error(res, 404, 'unknown_code', 'no sign-in is waiting for that code');
+ if (row.status !== 'pending') return error(res, 409, 'already_decided', `this sign-in was already ${row.status === 'denied' ? 'denied' : 'approved'}`);
+ if (new Date(row.expires_at) < new Date()) return error(res, 410, 'expired_token', 'this sign-in code expired; run the command again for a new one');
+
+ if (decision === 'deny') {
+ await sql`update cli_link_requests set status = 'denied', user_id = ${user.id}, decided_at = now() where id = ${row.id} and status = 'pending'`;
+ logAudit({ userId: user.id, action: 'cli_link_deny', resourceId: row.id, meta: { client: row.client_name, hostname: row.hostname }, req });
+ return json(res, 200, { status: 'denied' });
+ }
+
+ // The approver may narrow the request, never widen it.
+ const requested = new Set(row.requested_scope.split(/\s+/).filter(Boolean));
+ const { scopes: chosen } = normalizeKeyScopes(body.scope ?? row.requested_scope);
+ const granted = chosen.filter((s) => requested.has(s));
+ if (!granted.length) return error(res, 400, 'invalid_scope', 'keep at least one permission, or deny the sign-in instead');
+
+ const updated = await sql`
+ update cli_link_requests
+ set status = 'approved', user_id = ${user.id}, granted_scope = ${granted.join(' ')}, decided_at = now()
+ where id = ${row.id} and status = 'pending' and expires_at > now()
+ returning id
+ `;
+ if (!updated[0]) return error(res, 409, 'already_decided', 'this sign-in changed while you were looking at it; run the command again');
+ logAudit({ userId: user.id, action: 'cli_link_approve', resourceId: row.id, meta: { client: row.client_name, hostname: row.hostname, scope: granted.join(' ') }, req });
+ return json(res, 200, { status: 'approved', scope: granted.join(' ') });
+}
+
+// ── token (POST, the CLI polling with its device code) ───────────────────────
+
+async function handleToken(req, res) {
+ if (!method(req, res, ['POST'])) return;
+ const body = (await readJson(req, 4_000).catch(() => null)) || {};
+ const deviceCode = typeof body.device_code === 'string' ? body.device_code : '';
+ if (!deviceCode) return error(res, 400, 'invalid_request', 'device_code required');
+ const deviceHash = await sha256(deviceCode);
+ const rl = await limits.cliPoll(deviceHash);
+ if (!rl.success) return error(res, 400, 'slow_down', `poll at most every ${POLL_INTERVAL_SECONDS} seconds`);
+
+ const [row] = await sql`select * from cli_link_requests where device_code_hash = ${deviceHash} limit 1`;
+ if (!row) return error(res, 400, 'invalid_grant', 'unknown device code');
+ if (row.status === 'consumed') return error(res, 400, 'invalid_grant', 'this sign-in already delivered its key');
+ if (row.status === 'denied') return error(res, 400, 'access_denied', 'the sign-in was denied in the browser');
+ if (new Date(row.expires_at) < new Date()) return error(res, 400, 'expired_token', 'the sign-in code expired before it was approved');
+
+ if (row.status === 'pending') {
+ const tooSoon = row.last_polled_at && Date.now() - new Date(row.last_polled_at).getTime() < (POLL_INTERVAL_SECONDS - 1) * 1000;
+ await sql`update cli_link_requests set last_polled_at = now() where id = ${row.id}`;
+ if (tooSoon) return error(res, 400, 'slow_down', `poll at most every ${POLL_INTERVAL_SECONDS} seconds`);
+ return error(res, 400, 'authorization_pending', 'waiting for approval in the browser');
+ }
+
+ // Approved: claim the row first so two concurrent polls can never mint twice.
+ const claimed = await sql`
+ update cli_link_requests set status = 'consumed', consumed_at = now()
+ where id = ${row.id} and status = 'approved'
+ returning id, user_id, granted_scope, hostname, client_name
+ `;
+ if (!claimed[0]) return error(res, 400, 'invalid_grant', 'this sign-in already delivered its key');
+ const link = claimed[0];
+ const name = `${link.client_name}${link.hostname ? ` on ${link.hostname}` : ''}`.slice(0, 80);
+ const { row: key, secret } = await mintApiKey({
+ userId: link.user_id,
+ name,
+ scopes: link.granted_scope.split(/\s+/).filter(Boolean),
+ req,
+ via: 'cli_link',
+ });
+ await sql`update cli_link_requests set api_key_id = ${key.id} where id = ${link.id}`;
+ const [account] = await sql`select email from users where id = ${link.user_id} limit 1`;
+ return json(res, 200, {
+ access_token: secret,
+ token_type: 'Bearer',
+ scope: key.scope,
+ key: { id: key.id, name: key.name, prefix: key.prefix, created_at: key.created_at },
+ account: { email: account?.email || null },
+ }, { 'cache-control': 'no-store' });
+}
+
+// ── whoami (GET, bearer) ─────────────────────────────────────────────────────
+
+async function handleWhoami(req, res) {
+ if (!method(req, res, ['GET'])) return;
+ const token = extractBearer(req);
+ if (!token) return error(res, 401, 'unauthorized', 'send an API key or access token as a Bearer credential; run `npx three-ws login`');
+ const auth = await authenticateBearer(token, { audience: env.MCP_RESOURCE });
+ if (!auth) return error(res, 401, 'invalid_token', 'this credential is revoked, expired or unknown; run `npx three-ws login`');
+ const rl = await limits.authedReadIp(clientIp(req));
+ if (!rl.success) return rateLimited(res, rl);
+
+ const scope = auth.scope || '';
+ const canProfile = hasScope(scope, 'profile');
+ const canWallet = hasScope(scope, 'wallet:read') || hasScope(scope, 'wallet:write');
+
+ const [[user], keyRows, walletStatus] = await Promise.all([
+ sql`
+ select u.id, u.email, u.display_name, u.username, u.plan, q.mcp_calls_per_day,
+ (select count(*) from usage_events e where e.user_id = u.id and e.kind = 'tool_call' and e.created_at > now() - interval '24 hours') as mcp_calls_24h
+ from users u left join plan_quotas q on q.plan = u.plan
+ where u.id = ${auth.userId} and u.deleted_at is null limit 1
+ `,
+ auth.apiKeyId
+ ? sql`select name, prefix, expires_at, last_used_at, created_at from api_keys where id = ${auth.apiKeyId} limit 1`
+ : Promise.resolve([]),
+ canWallet ? getUserWalletStatus(auth.userId) : Promise.resolve(null),
+ ]);
+ if (!user) return error(res, 401, 'invalid_token', 'the account behind this credential no longer exists');
+
+ return json(res, 200, {
+ user: canProfile
+ ? { id: user.id, email: user.email, display_name: user.display_name || null, username: user.username || null }
+ : { id: user.id },
+ plan: canProfile
+ ? { plan: user.plan, mcp_calls_per_day: user.mcp_calls_per_day == null ? null : Number(user.mcp_calls_per_day), mcp_calls_24h: Number(user.mcp_calls_24h || 0) }
+ : null,
+ credential: {
+ source: auth.source,
+ scope,
+ client_id: auth.clientId || null,
+ api_key: keyRows[0] || null,
+ },
+ wallet: canWallet ? walletStatus : null,
+ missing: [!canProfile && 'profile', !canWallet && 'wallet:read'].filter(Boolean),
+ }, { 'cache-control': 'no-store' });
+}
+
+const DISPATCH = {
+ link: handleLink,
+ approve: handleApprove,
+ token: handleToken,
+ whoami: handleWhoami,
+};
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,POST,OPTIONS', credentials: true })) return;
+ const action = req.query?.action ?? new URL(req.url, 'http://x').pathname.split('/').pop();
+ const fn = DISPATCH[action];
+ if (!fn) return error(res, 404, 'not_found', `unknown cli action: ${action}`);
+ if (action === 'link' && !method(req, res, ['GET', 'POST'])) return;
+ return fn(req, res);
+});
diff --git a/api/keys/index.js b/api/keys/index.js
index e81496b3d..9e105d52e 100644
--- a/api/keys/index.js
+++ b/api/keys/index.js
@@ -4,16 +4,13 @@
import { sql } from '../_lib/db.js';
import { getSessionUser } from '../_lib/auth.js';
-import { logAudit } from '../_lib/audit.js';
-import { randomToken, sha256 } from '../_lib/crypto.js';
+import { normalizeKeyScopes, mintApiKey } 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';
import { parse } from '../_lib/validate.js';
import { z } from 'zod';
-const ALLOWED_SCOPES = new Set(['avatars:read', 'avatars:write', 'avatars:delete', 'profile', 'memory:read', 'memory:write', 'agents:read', 'agents:write', 'herald:announce']);
-
const createSchema = z.object({
name: z.string().trim().min(1).max(80),
scope: z
@@ -54,8 +51,7 @@ export default wrap(async (req, res) => {
// 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 requestedScopes = [...new Set(body.scope.split(/\s+/).filter(Boolean))];
- const invalid = requestedScopes.filter((s) => !ALLOWED_SCOPES.has(s));
+ const { scopes: requestedScopes, 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 " "
@@ -67,27 +63,17 @@ export default wrap(async (req, res) => {
if (!requestedScopes.length)
return error(res, 400, 'validation_error', 'scope must name at least one permission');
- const raw = `sk_${body.environment}_${randomToken(28)}`;
- const hash = await sha256(raw);
- const prefix = raw.slice(0, 12);
const expires = body.expires_in_days
? new Date(Date.now() + body.expires_in_days * 86400 * 1000).toISOString()
: null;
- const [row] = await sql`
- insert into api_keys (user_id, name, prefix, token_hash, scope, expires_at)
- values (${user.id}, ${body.name}, ${prefix}, ${hash}, ${requestedScopes.join(' ')}, ${expires})
- returning id, name, prefix, scope, expires_at, created_at
- `;
- // Issuing a long-lived credential belongs in the same trail as revoking one:
- // without it the audit log can say a key died but not that it was ever born.
- // Never the secret or its hash, only the id, prefix, and granted scope.
- logAudit({
+ const { row, secret } = await mintApiKey({
userId: user.id,
- action: 'create_api_key',
- resourceId: row.id,
- meta: { prefix, scope: row.scope, environment: body.environment },
+ name: body.name,
+ scopes: requestedScopes,
+ expiresAt: expires,
+ environment: body.environment,
req,
});
- return json(res, 201, { key: { ...row, secret: raw } });
+ return json(res, 201, { key: { ...row, secret } });
});
diff --git a/api/oauth/[action].js b/api/oauth/[action].js
index b837242e0..167c7bca4 100644
--- a/api/oauth/[action].js
+++ b/api/oauth/[action].js
@@ -18,6 +18,14 @@ import { filterRegisterableScope } from '../_lib/oauth-scopes.js';
// ── authorize ─────────────────────────────────────────────────────────────────
+// RFC 8252 §7.3: for a loopback IP redirect the authorization server MUST allow
+// any port at request time, because a native app (the `three-ws` CLI, a desktop
+// client) binds whatever ephemeral port the OS hands it and cannot know it when
+// it registers. Exact port matching forced such a client to re-register on every
+// login and burn the per-IP registration budget doing it. Only the IP literals
+// qualify: `localhost` can resolve somewhere else, so it keeps exact matching.
+const LOOPBACK_IP_HOSTS = new Set(['127.0.0.1', '[::1]']);
+
function redirectUriMatches(requested, registered) {
let reqUrl;
try { reqUrl = new URL(requested); } catch { return false; }
@@ -25,7 +33,9 @@ function redirectUriMatches(requested, registered) {
return registered.some((entry) => {
let regUrl;
try { regUrl = new URL(entry); } catch { return false; }
- return reqUrl.protocol === regUrl.protocol && reqUrl.host === regUrl.host && reqUrl.port === regUrl.port && reqUrl.pathname === regUrl.pathname;
+ if (reqUrl.protocol !== regUrl.protocol || reqUrl.hostname !== regUrl.hostname || reqUrl.pathname !== regUrl.pathname) return false;
+ if (reqUrl.protocol === 'http:' && LOOPBACK_IP_HOSTS.has(regUrl.hostname)) return true;
+ return reqUrl.port === regUrl.port;
});
}
diff --git a/data/pages.json b/data/pages.json
index ae6aadd04..98a47dcf2 100644
--- a/data/pages.json
+++ b/data/pages.json
@@ -1051,6 +1051,15 @@
"changefreq": "weekly",
"added": "2026-09-02"
},
+ {
+ "path": "/cli/authorize",
+ "title": "Authorize the three-ws CLI",
+ "description": "Approve a sign-in started by npx three-ws in your terminal. Check the code matches, choose what the new API key may do (money-moving permissions are flagged and can be removed), and the CLI finishes setup on its own.",
+ "priority": 0.3,
+ "changefreq": "yearly",
+ "added": "2026-09-22",
+ "indexable": false
+ },
{
"path": "/smart-home/join",
"title": "Join a home",
diff --git a/pages/cli-authorize.html b/pages/cli-authorize.html
new file mode 100644
index 000000000..ece34f724
--- /dev/null
+++ b/pages/cli-authorize.html
@@ -0,0 +1,60 @@
+<!doctype html>
+<html lang="en">
+<head>
+ <script>/* three.ws theme boot */(function(){document.documentElement.classList.add('js');try{var m=localStorage.getItem('twx_theme');var l=m==='auto'?(window.matchMedia&&window.matchMedia('(prefers-color-scheme: light)').matches):m==='light';document.documentElement.setAttribute('data-theme',l?'light':'dark');}catch(e){document.documentElement.setAttribute('data-theme','dark');}})();</script>
+ <meta charset="utf-8" />
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
+ <title>Authorize the three-ws CLI · three.ws</title>
+ <meta name="description" content="Approve a sign-in from the three-ws command line. Check the code matches your terminal, choose what the new API key may do, and the CLI finishes setup on its own." />
+ <link rel="canonical" href="https://three.ws/cli/authorize" />
+ <meta name="robots" content="noindex, follow" />
+ <meta property="og:type" content="website" />
+ <meta property="og:site_name" content="three.ws" />
+ <meta property="og:title" content="Authorize the three-ws CLI · three.ws" />
+ <meta property="og:description" content="Approve a sign-in from the three-ws command line and pick what the new API key may do." />
+ <meta property="og:url" content="https://three.ws/cli/authorize" />
+ <meta name="twitter:card" content="summary" />
+ <meta name="twitter:site" content="@trythreews" />
+ <link rel="icon" href="/favicon.ico" sizes="any" />
+ <link rel="stylesheet" href="/style.css" />
+ <link rel="stylesheet" href="/nav.css" />
+ <link rel="stylesheet" href="/src/cli-authorize.css" />
+</head>
+<body>
+ <main class="cla-wrap" id="main">
+ <header class="cla-hero">
+ <p class="cla-eyebrow">Command line</p>
+ <h1 class="cla-title">Sign in the three-ws CLI</h1>
+ <p class="cla-lede">
+ A terminal asked to connect to your three.ws account. Approving creates an API key that
+ only that terminal receives, once. You can revoke it any time from
+ <a href="/dashboard/api">your API keys</a>.
+ </p>
+ </header>
+
+ <!-- One live region the controller (src/cli-authorize.js) owns. The skeleton
+ is the shape of the approval card so the page does not jump. -->
+ <div id="cla-root" aria-live="polite" aria-busy="true">
+ <section class="cla-card">
+ <div class="cla-skeleton" style="height:1.1rem;width:14rem"></div>
+ <div class="cla-skeleton" style="height:2.6rem;width:16rem;margin-top:1rem"></div>
+ <div class="cla-skeleton" style="height:0.85rem;width:100%;margin-top:1.4rem"></div>
+ <div class="cla-skeleton" style="height:0.85rem;width:80%;margin-top:0.6rem"></div>
+ <div class="cla-skeleton" style="height:2.6rem;margin-top:1.6rem"></div>
+ </section>
+ </div>
+
+ <noscript>
+ <section class="cla-card">
+ <h2 class="cla-card-title">JavaScript is required here</h2>
+ <p class="cla-muted">Approving a sign-in reads it from your account, so this page needs JavaScript. Your terminal keeps waiting: turn JavaScript on and open the link again.</p>
+ </section>
+ </noscript>
+
+ <p class="cla-foot">Did not run <code>npx three-ws</code> yourself? Deny it. Nobody at three.ws will ever ask you for a code.</p>
+ </main>
+
+ <script src="/nav.js"></script>
+ <script type="module" src="/src/cli-authorize.js"></script>
+</body>
+</html>
diff --git a/public/.well-known/mcp.json b/public/.well-known/mcp.json
index 2befdb2a5..04c797221 100644
--- a/public/.well-known/mcp.json
+++ b/public/.well-known/mcp.json
@@ -4,6 +4,11 @@
"description": "The 3D agent economy: generate, rig, and animate 3D avatars and worlds; pay and get paid per call with x402 (USDC on Solana and Base); read live crypto market and on-chain intelligence.",
"website": "https://three.ws",
"documentation": "https://three.ws/docs/mcp",
+ "setup": {
+ "command": "npx three-ws setup",
+ "description": "One command signs you in (OAuth or API key), writes these servers into Claude Code, Claude Desktop, Cursor, Windsurf, VS Code, Codex, Gemini CLI or Hermes, and verifies each with a live tools/list.",
+ "documentation": "https://three.ws/docs/cli"
+ },
"registry": "https://registry.modelcontextprotocol.io/?q=io.github.nirholas",
"x402Catalog": "https://three.ws/.well-known/x402.json",
"agentCard": "https://three.ws/.well-known/agent-card.json",
diff --git a/src/cli-authorize.css b/src/cli-authorize.css
new file mode 100644
index 000000000..4340205c6
--- /dev/null
+++ b/src/cli-authorize.css
@@ -0,0 +1,145 @@
+/* /cli/authorize: approving a sign-in started by `npx three-ws`. */
+
+.cla-wrap {
+ max-width: 36rem;
+ margin: 0 auto;
+ padding: calc(var(--nav-h, 56px) + var(--space-xl)) var(--space-md) var(--space-2xl);
+ color: var(--ink);
+ font-family: var(--font-body);
+}
+
+.cla-hero { margin-bottom: var(--space-lg); }
+.cla-eyebrow {
+ margin: 0 0 var(--space-xs);
+ font-size: var(--text-xs);
+ letter-spacing: 0.08em;
+ text-transform: uppercase;
+ color: var(--ink-dim);
+}
+.cla-title { margin: 0 0 var(--space-sm); font-size: var(--text-2xl); line-height: var(--leading-tight); }
+.cla-lede { margin: 0; color: var(--ink-dim); line-height: var(--leading-normal); }
+.cla-lede a, .cla-muted a, .cla-foot a { color: var(--accent); }
+
+.cla-card {
+ background: var(--surface-1);
+ border: 1px solid var(--stroke);
+ border-radius: var(--radius-card, var(--radius-lg));
+ padding: var(--space-lg);
+ box-shadow: var(--shadow-1);
+ animation: cla-enter var(--duration-base) var(--ease-standard) both;
+}
+@keyframes cla-enter { from { opacity: 0; transform: translateY(6px); } to { opacity: 1; transform: none; } }
+
+.cla-card-title { margin: 0 0 var(--space-xs); font-size: var(--text-lg); }
+.cla-muted { margin: 0; color: var(--ink-dim); line-height: var(--leading-normal); }
+
+.cla-code {
+ display: inline-block;
+ margin: var(--space-sm) 0 var(--space-xs);
+ padding: var(--space-xs) var(--space-md);
+ font-family: var(--font-mono);
+ font-size: var(--text-2xl);
+ letter-spacing: 0.18em;
+ border: 1px dashed var(--stroke-strong);
+ border-radius: var(--radius-md);
+ background: var(--surface-2);
+ user-select: all;
+}
+
+.cla-meta {
+ display: grid;
+ grid-template-columns: auto 1fr;
+ gap: var(--space-2xs) var(--space-md);
+ margin: var(--space-md) 0;
+ font-size: var(--text-sm);
+}
+.cla-meta dt { color: var(--ink-dim); }
+.cla-meta dd { margin: 0; overflow-wrap: anywhere; }
+
+.cla-scopes { list-style: none; margin: var(--space-sm) 0 var(--space-md); padding: 0; border-top: 1px solid var(--stroke); }
+.cla-scope { border-bottom: 1px solid var(--stroke); }
+.cla-scope label {
+ display: flex;
+ align-items: flex-start;
+ gap: var(--space-sm);
+ padding: var(--space-sm) var(--space-2xs);
+ cursor: pointer;
+ border-radius: var(--radius-sm);
+ transition: background var(--duration-fast) var(--ease-standard);
+}
+.cla-scope label:hover { background: var(--surface-2); }
+.cla-scope input { margin-top: 0.2rem; accent-color: var(--accent); width: 1rem; height: 1rem; flex: none; }
+.cla-scope input:focus-visible { outline: var(--focus-ring-width, 2px) solid var(--focus-ring-color, var(--accent)); outline-offset: 2px; }
+.cla-scope-name { display: block; font-family: var(--font-mono); font-size: var(--text-xs); color: var(--ink-dim); }
+.cla-badge {
+ display: inline-block;
+ margin-left: var(--space-xs);
+ padding: 0 var(--space-xs);
+ font-size: var(--text-2xs, 0.7rem);
+ border-radius: var(--radius-pill);
+ color: var(--warn, #f5a524);
+ border: 1px solid currentColor;
+ vertical-align: middle;
+}
+
+.cla-warn {
+ margin: var(--space-md) 0;
+ padding: var(--space-sm) var(--space-md);
+ border-left: 3px solid var(--warn, #f5a524);
+ background: var(--surface-2);
+ border-radius: var(--radius-sm);
+ font-size: var(--text-sm);
+ color: var(--ink);
+}
+
+.cla-actions { display: flex; flex-wrap: wrap; gap: var(--space-sm); margin-top: var(--space-md); }
+.cla-actions .btn { flex: 1 1 10rem; justify-content: center; }
+
+.cla-form { display: flex; flex-wrap: wrap; gap: var(--space-sm); margin-top: var(--space-md); }
+.cla-input {
+ flex: 1 1 12rem;
+ min-width: 0;
+ padding: var(--space-sm) var(--space-md);
+ font-family: var(--font-mono);
+ font-size: var(--text-lg);
+ letter-spacing: 0.12em;
+ text-transform: uppercase;
+ color: var(--ink);
+ background: var(--surface-2);
+ border: 1px solid var(--stroke-strong);
+ border-radius: var(--radius-control, var(--radius-md));
+ transition: border-color var(--duration-fast) var(--ease-standard);
+}
+.cla-input:hover { border-color: var(--ink-dim); }
+.cla-input:focus-visible { outline: var(--focus-ring-width, 2px) solid var(--focus-ring-color, var(--accent)); outline-offset: 2px; }
+
+.cla-error { margin: var(--space-sm) 0 0; color: var(--danger); font-size: var(--text-sm); }
+
+.cla-status-icon {
+ display: grid;
+ place-items: center;
+ width: 2.75rem;
+ height: 2.75rem;
+ margin-bottom: var(--space-sm);
+ border-radius: 50%;
+ font-size: 1.4rem;
+ background: var(--surface-2);
+}
+.cla-status-icon[data-tone='ok'] { color: var(--success); }
+.cla-status-icon[data-tone='bad'] { color: var(--danger); }
+
+.cla-skeleton {
+ background: linear-gradient(90deg, var(--skeleton-base, var(--surface-2)) 25%, var(--skeleton-sheen, var(--surface-3)) 50%, var(--skeleton-base, var(--surface-2)) 75%);
+ background-size: 200% 100%;
+ animation: cla-shimmer 1.4s ease-in-out infinite;
+ border-radius: var(--radius-sm);
+}
+@keyframes cla-shimmer { 0% { background-position: 200% 0; } 100% { background-position: -200% 0; } }
+
+.cla-foot { margin-top: var(--space-lg); font-size: var(--text-sm); color: var(--ink-dim); }
+.cla-foot code, .cla-muted code { font-family: var(--font-mono); font-size: 0.92em; }
+
+@media (prefers-reduced-motion: reduce) {
+ .cla-skeleton, .cla-card { animation: none; }
+ .cla-scope label, .cla-input { transition: none; }
+}
diff --git a/src/cli-authorize.js b/src/cli-authorize.js
new file mode 100644
index 000000000..37202815d
--- /dev/null
+++ b/src/cli-authorize.js
@@ -0,0 +1,246 @@
+/**
+ * /cli/authorize: a person approving a sign-in their own terminal started.
+ *
+ * `npx three-ws login --device` (and `setup` when a browser redirect cannot
+ * reach the terminal) prints a URL and a short code, then polls
+ * /api/cli/token. This page is the other half:
+ *
+ * 1. Read the code from `?code=` or let the person type it.
+ * 2. Show exactly what is asking (client, machine, when) and which
+ * permissions the key would carry, money-moving ones flagged, each one
+ * removable. The approver can narrow the request, never widen it.
+ * 3. Allow or deny on an explicit press. Nothing is approved on load: a code
+ * opened by a link-preview fetcher must stay pending.
+ *
+ * The dead ends (expired, already used, unknown code) are separate screens
+ * because each needs a different next step.
+ */
+
+import { apiFetch } from './api.js';
+
+const root = document.getElementById('cla-root');
+
+function el(tag, attrs = {}, ...children) {
+ const node = document.createElement(tag);
+ for (const [k, v] of Object.entries(attrs)) {
+ if (v == null || v === false) continue;
+ if (k === 'class') node.className = v;
+ else if (k === 'text') node.textContent = v;
+ else if (k.startsWith('on')) node.addEventListener(k.slice(2), v);
+ else node.setAttribute(k, v === true ? '' : String(v));
+ }
+ for (const c of children.flat()) {
+ if (c == null) continue;
+ node.append(c instanceof Node ? c : document.createTextNode(String(c)));
+ }
+ return node;
+}
+
+function render(...nodes) {
+ root.replaceChildren(...nodes);
+ root.setAttribute('aria-busy', 'false');
+}
+
+function busy() {
+ root.setAttribute('aria-busy', 'true');
+}
+
+function normalizeCode(input) {
+ const letters = String(input || '').toUpperCase().replace(/[^A-Z]/g, '');
+ return letters.length === 8 ? `${letters.slice(0, 4)}-${letters.slice(4)}` : null;
+}
+
+function relTime(iso) {
+ const secs = Math.round((Date.now() - new Date(iso).getTime()) / 1000);
+ if (secs < 60) return 'just now';
+ const mins = Math.round(secs / 60);
+ return `${mins} minute${mins === 1 ? '' : 's'} ago`;
+}
+
+function statusCard({ tone, icon, title, body, actions = [] }) {
+ return el('section', { class: 'cla-card' },
+ el('div', { class: 'cla-status-icon', 'data-tone': tone, 'aria-hidden': 'true', text: icon }),
+ el('h2', { class: 'cla-card-title', text: title }),
+ el('p', { class: 'cla-muted' }, body),
+ actions.length ? el('div', { class: 'cla-actions' }, actions) : null,
+ );
+}
+
+function retryButton(code) {
+ return el('button', { class: 'btn btn--secondary', type: 'button', onclick: () => load(code), text: 'Try again' });
+}
+
+// ── Entry: no code yet ───────────────────────────────────────────────────────
+
+function renderCodeEntry(message = '') {
+ const input = el('input', {
+ class: 'cla-input',
+ id: 'cla-code-input',
+ name: 'code',
+ autocomplete: 'one-time-code',
+ autocapitalize: 'characters',
+ spellcheck: 'false',
+ inputmode: 'text',
+ maxlength: '9',
+ placeholder: 'BCDF-GHJK',
+ 'aria-describedby': message ? 'cla-code-error' : null,
+ 'aria-invalid': message ? 'true' : null,
+ });
+ const form = el('form', {
+ class: 'cla-form',
+ onsubmit: (e) => {
+ e.preventDefault();
+ const code = normalizeCode(input.value);
+ if (!code) return renderCodeEntry('Codes are eight letters, like BCDF-GHJK. Check your terminal.');
+ history.replaceState(null, '', `/cli/authorize?code=${encodeURIComponent(code)}`);
+ load(code);
+ },
+ },
+ el('label', { class: 'sr-only', for: 'cla-code-input', text: 'Sign-in code' }),
+ input,
+ el('button', { class: 'btn btn--primary', type: 'submit', text: 'Continue' }),
+ );
+ render(el('section', { class: 'cla-card' },
+ el('h2', { class: 'cla-card-title', text: 'Enter the code from your terminal' }),
+ el('p', { class: 'cla-muted' }, 'Run ', el('code', { text: 'npx three-ws login --device' }), ' and type the eight-letter code it prints.'),
+ form,
+ message ? el('p', { class: 'cla-error', id: 'cla-code-error', role: 'alert', text: message }) : null,
+ ));
+ input.focus();
+}
+
+// ── Load the link ────────────────────────────────────────────────────────────
+
+async function load(code) {
+ busy();
+ let res;
+ try {
+ res = await apiFetch(`/api/cli/link?code=${encodeURIComponent(code)}`, { allowAnonymous: true });
+ } catch {
+ return render(statusCard({
+ tone: 'bad', icon: '!', title: 'Could not reach three.ws',
+ body: 'Your connection dropped before the sign-in could load. Your terminal is still waiting, so try again.',
+ actions: [retryButton(code)],
+ }));
+ }
+ if (res.status === 401) return renderSignIn();
+ const data = await res.json().catch(() => ({}));
+ if (res.status === 404 || res.status === 400) return renderCodeEntry(data.error_description || 'No sign-in is waiting for that code. Check your terminal.');
+ if (!res.ok) {
+ return render(statusCard({
+ tone: 'bad', icon: '!', title: 'Something went wrong on our side',
+ body: data.error_description || `The server answered ${res.status}. Your terminal is still waiting; try again in a moment.`,
+ actions: [retryButton(code)],
+ }));
+ }
+ const { link, account } = data;
+ if (link.status === 'approved' || link.status === 'consumed') return renderDone('approved', link);
+ if (link.status === 'denied') return renderDone('denied', link);
+ if (link.expired) return renderExpired();
+ renderApproval(link, account);
+}
+
+function renderSignIn() {
+ const next = location.pathname + location.search;
+ render(statusCard({
+ tone: 'ok', icon: '→', title: 'Sign in to continue',
+ body: 'Sign in to the three.ws account the terminal should use. You will come straight back here to approve it.',
+ actions: [
+ el('a', { class: 'btn btn--primary', href: `/login?next=${encodeURIComponent(next)}`, text: 'Sign in' }),
+ el('a', { class: 'btn btn--ghost', href: `/register?next=${encodeURIComponent(next)}`, text: 'Create an account' }),
+ ],
+ }));
+}
+
+function renderExpired() {
+ render(statusCard({
+ tone: 'bad', icon: '⏱', title: 'This code expired',
+ body: el('span', {}, 'Codes last ten minutes. Run ', el('code', { text: 'npx three-ws login --device' }), ' again for a fresh one.'),
+ }));
+}
+
+function renderDone(kind, link) {
+ if (kind === 'approved') {
+ return render(statusCard({
+ tone: 'ok', icon: '✓', title: 'Approved. Back to your terminal',
+ body: `${link.client_name}${link.hostname ? ` on ${link.hostname}` : ''} is signed in and finishing setup. You can close this tab. The key it received is listed with your API keys, where you can revoke it.`,
+ actions: [el('a', { class: 'btn btn--secondary', href: '/dashboard/api', text: 'View API keys' })],
+ }));
+ }
+ return render(statusCard({
+ tone: 'bad', icon: '✕', title: 'Sign-in denied',
+ body: 'The terminal was told no and received nothing. If that was a mistake, run the command again.',
+ }));
+}
+
+// ── Approve or deny ─────────────────────────────────────────────────────────
+
+function renderApproval(link, account, errorMessage = '') {
+ const boxes = link.requested_scopes.map((s) => {
+ const box = el('input', { type: 'checkbox', name: 'scope', value: s.scope, checked: true });
+ return {
+ box,
+ item: el('li', { class: 'cla-scope' },
+ el('label', {},
+ box,
+ el('span', {},
+ s.label,
+ s.financial ? el('span', { class: 'cla-badge', text: 'moves funds' }) : null,
+ el('span', { class: 'cla-scope-name', text: s.scope }),
+ ),
+ ),
+ ),
+ };
+ });
+ const financial = link.requested_scopes.some((s) => s.financial);
+ const allow = el('button', { class: 'btn btn--primary', type: 'button', text: 'Approve' });
+ const deny = el('button', { class: 'btn btn--ghost', type: 'button', text: 'Deny' });
+
+ async function decide(decision) {
+ const scope = boxes.filter((b) => b.box.checked).map((b) => b.box.value).join(' ');
+ if (decision === 'allow' && !scope) return renderApproval(link, account, 'Keep at least one permission, or deny the sign-in instead.');
+ allow.disabled = true; deny.disabled = true;
+ (decision === 'allow' ? allow : deny).setAttribute('aria-busy', 'true');
+ let res;
+ try {
+ res = await apiFetch('/api/cli/approve', {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ code: link.user_code, decision, scope }),
+ });
+ } catch (err) {
+ if (err?.redirected) return;
+ return renderApproval(link, account, 'Your connection dropped before that went through. Nothing changed; try again.');
+ }
+ const data = await res.json().catch(() => ({}));
+ if (res.ok) return renderDone(data.status === 'approved' ? 'approved' : 'denied', link);
+ if (res.status === 410) return renderExpired();
+ if (res.status === 409) return load(link.user_code);
+ renderApproval(link, account, data.error_description || `The server answered ${res.status}. Nothing changed; try again.`);
+ }
+ allow.addEventListener('click', () => decide('allow'));
+ deny.addEventListener('click', () => decide('deny'));
+
+ render(el('section', { class: 'cla-card' },
+ el('h2', { class: 'cla-card-title', text: 'Does this code match your terminal?' }),
+ el('div', { class: 'cla-code', 'aria-label': `Code ${link.user_code.split('').join(' ')}`, text: link.user_code }),
+ el('dl', { class: 'cla-meta' },
+ el('dt', { text: 'App' }), el('dd', { text: link.client_name }),
+ el('dt', { text: 'Machine' }), el('dd', { text: link.hostname || 'Not reported' }),
+ el('dt', { text: 'Started' }), el('dd', { text: relTime(link.created_at) }),
+ el('dt', { text: 'Account' }), el('dd', { text: account.email }),
+ ),
+ el('p', { class: 'cla-muted', text: 'The new API key will be able to:' }),
+ el('ul', { class: 'cla-scopes' }, boxes.map((b) => b.item)),
+ financial
+ ? el('p', { class: 'cla-warn', text: 'Permissions marked "moves funds" let tools spend USDC from your agent wallet. Every spend still stops at your spending caps. Untick them if this terminal only needs to read.' })
+ : null,
+ el('div', { class: 'cla-actions' }, deny, allow),
+ errorMessage ? el('p', { class: 'cla-error', role: 'alert', text: errorMessage }) : null,
+ ));
+ allow.focus();
+}
+
+const initial = normalizeCode(new URLSearchParams(location.search).get('code'));
+if (initial) load(initial);
+else renderCodeEntry(new URLSearchParams(location.search).get('code') ? 'That code is not in the right shape. Codes are eight letters, like BCDF-GHJK.' : '');
diff --git a/src/dashboard-next/pages/api.js b/src/dashboard-next/pages/api.js
index bea415955..c1262cc63 100644
--- a/src/dashboard-next/pages/api.js
+++ b/src/dashboard-next/pages/api.js
@@ -23,7 +23,7 @@ import { requireUser, get, post, del, put, esc, relTime, ApiError } from '../api
import { apiFetch } from '../../api.js';
import { errorStateHTML, emptyStateHTML, skeletonHTML, ensureStateKitStyles } from '../../shared/state-kit.js';
-// Scopes accepted by /api/keys — match api/keys/index.js ALLOWED_SCOPES exactly.
+// Scopes accepted by /api/keys: match API_KEY_SCOPES in api/_lib/api-keys.js exactly.
const SCOPES = [
{ value: 'avatars:read', label: 'avatars:read', note: 'List, fetch, and stream avatars' },
{ value: 'avatars:write', label: 'avatars:write', note: 'Create or modify avatars' },
@@ -34,6 +34,10 @@ const SCOPES = [
{ value: 'agents:read', label: 'agents:read', note: 'Read your agents and their identities' },
{ value: 'agents:write', label: 'agents:write', note: 'Create, update, and register agents' },
{ value: 'herald:announce', label: 'herald:announce', note: 'Post announcements through the Herald' },
+ { value: 'wallet:read', label: 'wallet:read', note: 'See your agent wallet balance and spending caps' },
+ { value: 'wallet:write', label: 'wallet:write', note: 'Spend USDC from your agent wallet, within your caps' },
+ { value: 'services:write', label: 'services:write', note: 'Publish paid services that earn USDC to your agent wallet' },
+ { value: 'inference', label: 'inference', note: 'Call the OpenAI-compatible /api/v1 endpoint, billed to your credits' },
];
const EXPIRY_OPTIONS = [
diff --git a/tests/api/oauth-authorize.test.js b/tests/api/oauth-authorize.test.js
index 5e9df13d8..7f44ab18c 100644
--- a/tests/api/oauth-authorize.test.js
+++ b/tests/api/oauth-authorize.test.js
@@ -237,6 +237,34 @@ describe('GET /api/oauth/authorize — client and redirect_uri', () => {
expect(status).toBe(400);
expect(tryParseJson(body).error).toBe('invalid_redirect_uri');
});
+
+ // RFC 8252 §7.3: native apps (the desktop console) pick an ephemeral port.
+ it('accepts any port on a registered loopback IP redirect', async () => {
+ sqlState.queue.push([{ ...VALID_CLIENT, redirect_uris: ['http://127.0.0.1/callback'] }]);
+ const params = new URLSearchParams(VALID_QS);
+ params.set('redirect_uri', 'http://127.0.0.1:53127/callback');
+ const { status, location } = await invoke({ url: `/api/oauth/authorize?${params}` });
+ expect(status).toBe(302);
+ expect(location).toContain('/login');
+ });
+
+ it('keeps the loopback path and host exact while relaxing the port', async () => {
+ sqlState.queue.push([{ ...VALID_CLIENT, redirect_uris: ['http://127.0.0.1/callback'] }]);
+ const params = new URLSearchParams(VALID_QS);
+ params.set('redirect_uri', 'http://127.0.0.1:53127/other');
+ const { status, body } = await invoke({ url: `/api/oauth/authorize?${params}` });
+ expect(status).toBe(400);
+ expect(tryParseJson(body).error).toBe('invalid_redirect_uri');
+ });
+
+ it('keeps the port exact for localhost, whose resolution the app does not control', async () => {
+ sqlState.queue.push([{ ...VALID_CLIENT, redirect_uris: ['http://localhost/callback'] }]);
+ const params = new URLSearchParams(VALID_QS);
+ params.set('redirect_uri', 'http://localhost:53127/callback');
+ const { status, body } = await invoke({ url: `/api/oauth/authorize?${params}` });
+ expect(status).toBe(400);
+ expect(tryParseJson(body).error).toBe('invalid_redirect_uri');
+ });
});
// ── Unauthenticated flow → bounce to login ────────────────────────────────
diff --git a/vercel.json b/vercel.json
index 1768bae5d..1b5e8bc53 100644
--- a/vercel.json
+++ b/vercel.json
@@ -2234,6 +2234,10 @@
"src": "/smart-home/satellite/?",
"dest": "/smart-home-satellite.html"
},
+ {
+ "src": "/cli/authorize/?",
+ "dest": "/cli-authorize.html"
+ },
{
"src": "/smart-home/plan/?",
"dest": "/smart-home-plan.html"
@@ -4968,6 +4972,13 @@
"src": "/api/bazaar/context",
"dest": "/api/bazaar/context.js"
},
+ {
+ "src": "/settings/api-keys/?",
+ "headers": {
+ "Location": "/dashboard/api"
+ },
+ "status": 301
+ },
{
"src": "/settings",
"dest": "/settings/index.html"
diff --git a/vite.config.js b/vite.config.js
index 98cf8a09b..77d3d6cc8 100644
--- a/vite.config.js
+++ b/vite.config.js
@@ -647,6 +647,7 @@ const appConfig = {
materialize: resolve(__dirname, 'pages/materialize.html'),
'smart-home': resolve(__dirname, 'pages/smart-home.html'),
'smart-home-join': resolve(__dirname, 'pages/smart-home-join.html'),
+ 'cli-authorize': resolve(__dirname, 'pages/cli-authorize.html'),
'smart-home-plan': resolve(__dirname, 'pages/smart-home-plan.html'),
'smart-home-privacy': resolve(__dirname, 'pages/smart-home-privacy.html'),
'smart-home-satellite': resolve(__dirname, 'pages/smart-home-satellite.html'),