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.

fix(auth): hold bearer tokens to the scopes they were granted

nirholas6a888b301e92
diff --git a/api/_lib/auth.js b/api/_lib/auth.js
index ae84d82c8..f43e64c54 100644
--- a/api/_lib/auth.js
+++ b/api/_lib/auth.js
@@ -7,6 +7,7 @@ import { sql } from './db.js';
import { logAudit } from './audit.js';
import { randomToken, sha256, hmacSha256, constantTimeEquals } from './crypto.js';
import { recordDailyActivity } from './streaks.js';
+import { clientIp } from './rate-limit.js';
const ACCESS_TTL_SEC = 60 * 60; // 1h access tokens
const REFRESH_TTL_SEC = 60 * 60 * 24 * 30; // 30d refresh tokens
@@ -226,11 +227,7 @@ export async function getSessionUser(req, res) {
const nowMs = Date.now();
if (nowMs - seenMs > 86_400_000 && expiresMs - nowMs < SESSION_REFRESH_WINDOW_SEC * 1000) {
const ua = req.headers['user-agent'] || null;
- const ip =
- req.headers['x-vercel-forwarded-for']?.split(',')[0]?.trim() ||
- req.headers['x-real-ip'] ||
- req.socket?.remoteAddress ||
- null;
+ const ip = clientIp(req);
rotateSession({ currentSid: userFields.sid, userId: userFields.id, userAgent: ua, ip })
.then((newToken) => {
try {
@@ -397,3 +394,36 @@ export function hasScope(granted, required) {
const g = new Set((granted || '').split(/\s+/).filter(Boolean));
return required.split(/\s+/).every((s) => g.has(s));
}
+
+// Scope check for a principal returned by getRequestUser(). A cookie session is
+// the person, present, and carries every scope. A bearer principal (API key or
+// OAuth access token) holds only what it was granted, so a route that accepts a
+// bearer must name the scope its action needs; otherwise a narrow key (an
+// `inference`-only key, an MCP client granted `avatars:read`) acts with the
+// account's full authority.
+export function requestUserHasScope(user, required) {
+ if (!user) return false;
+ if (user.source !== 'bearer') return true;
+ return hasScope(user.scope, required);
+}
+
+// The scope a bearer principal must hold to move, commit, or redirect funds.
+export const SPEND_SCOPE = 'wallet:write';
+
+// Gate for a route that spends from a custodial wallet (withdraw, trade, pay,
+// hire, launch, arm an autonomous spender) or changes where its money goes. The
+// MCP tools behind these actions already demand `wallet:write`, but the REST
+// routes accepted ANY bearer, so an `inference`-only key or an OAuth client the
+// user approved for "Read your avatars" could withdraw an agent wallet to its
+// own address. A cookie session never reaches here (pass the bearer only).
+// Safe methods pass so a `wallet:read` key still reads balances and history.
+export function assertBearerMaySpend(bearer, req) {
+ if (!bearer) return bearer;
+ const verb = String(req?.method || 'POST').toUpperCase();
+ if (verb === 'GET' || verb === 'HEAD' || verb === 'OPTIONS') return bearer;
+ if (hasScope(bearer.scope, SPEND_SCOPE)) return bearer;
+ throw Object.assign(
+ new Error(`this credential lacks the ${SPEND_SCOPE} scope required to move funds`),
+ { status: 403, code: 'insufficient_scope', expose: true },
+ );
+}
diff --git a/api/api-keys.js b/api/api-keys.js
index 11d3afc16..1f14d5ad7 100644
--- a/api/api-keys.js
+++ b/api/api-keys.js
@@ -57,6 +57,22 @@ export default wrap(async (req, res) => {
if (invalid.length)
return error(res, 400, 'validation_error', `unknown scopes: ${invalid.join(', ')}`);
+ // A bearer caller can only mint a key at or below its own grant. `profile`
+ // is the gate to reach this endpoint, not a license to escalate: without
+ // this, an OAuth token a third-party client was granted for `profile` alone
+ // (or a narrow API key) could mint a non-expiring `wallet:write agents:write`
+ // key and walk out of the consent the user actually gave.
+ if (bearer) {
+ const beyond = requestedScopes.filter((s) => !hasScope(bearer.scope, s));
+ if (beyond.length)
+ return error(
+ res,
+ 403,
+ 'insufficient_scope',
+ `a bearer credential cannot mint scopes it does not hold: ${beyond.join(', ')}`,
+ );
+ }
+
const token = `sk_live_${randomToken(32)}`;
const prefix = token.slice(0, 14); // "sk_live_" + 6 chars
const tokenHash = await sha256(token);
diff --git a/api/companion/checkout.js b/api/companion/checkout.js
index e3382b1b9..c465fa687 100644
--- a/api/companion/checkout.js
+++ b/api/companion/checkout.js
@@ -36,7 +36,7 @@ import { z } from 'zod';
import { cors, json, method, wrap, error, readJson, rateLimited } from '../_lib/http.js';
import { limits } from '../_lib/rate-limit.js';
import { parse } from '../_lib/validate.js';
-import { getRequestUser } from '../_lib/auth.js';
+import { getRequestUser, requestUserHasScope } from '../_lib/auth.js';
import { sql } from '../_lib/db.js';
import { loadUserProviderKeys } from '../_lib/provider-keys.js';
import { userForIngestToken } from '../_lib/companion/store.js';
@@ -98,7 +98,10 @@ async function callerFor(req, res) {
const user = await userForIngestToken(bearer);
if (user) return user;
}
- return getRequestUser(req, res);
+ // A narrow bearer (an inference-only key, an avatars-only OAuth client)
+ // must not spend the account's own model key; it needs profile.
+ const user = await getRequestUser(req, res);
+ return user && requestUserHasScope(user, 'profile') ? user : null;
}
export default wrap(async function handler(req, res) {
diff --git a/api/companion/contacts/[id].js b/api/companion/contacts/[id].js
index a827a667f..2e01c5acc 100644
--- a/api/companion/contacts/[id].js
+++ b/api/companion/contacts/[id].js
@@ -1,7 +1,7 @@
// DELETE /api/companion/contacts/:id → forget a contact. Messages already
// stored keep their text; they simply stop being attributed to that person.
-import { getRequestUser } from '../../_lib/auth.js';
+import { getRequestUser, requestUserHasScope } from '../../_lib/auth.js';
import { cors, json, method, wrap, error, rateLimited } from '../../_lib/http.js';
import { requireCsrf } from '../../_lib/csrf.js';
import { limits } from '../../_lib/rate-limit.js';
@@ -13,6 +13,9 @@ export default wrap(async (req, res) => {
const user = await getRequestUser(req, res);
if (!user) return error(res, 401, 'unauthorized', 'sign in required');
+ // Private messages and the bridge token live behind this surface, so a
+ // bearer needs the account-level profile scope, not just any grant.
+ if (!requestUserHasScope(user, 'profile')) return error(res, 403, 'insufficient_scope', 'this token needs the profile scope');
if (!(await requireCsrf(req, res, user.id))) return;
const rl = await limits.companionWrite(user.id);
diff --git a/api/companion/contacts/index.js b/api/companion/contacts/index.js
index a852f20b4..2fa6a2290 100644
--- a/api/companion/contacts/index.js
+++ b/api/companion/contacts/index.js
@@ -6,7 +6,7 @@
// speaks in, and how much her messages outrank everything else.
import { z } from 'zod';
-import { getRequestUser } from '../../_lib/auth.js';
+import { getRequestUser, requestUserHasScope } from '../../_lib/auth.js';
import { cors, json, method, wrap, error, readJson, rateLimited } from '../../_lib/http.js';
import { requireCsrf } from '../../_lib/csrf.js';
import { limits } from '../../_lib/rate-limit.js';
@@ -29,6 +29,9 @@ export default wrap(async (req, res) => {
const user = await getRequestUser(req, res);
if (!user) return error(res, 401, 'unauthorized', 'sign in required');
+ // Private messages and the bridge token live behind this surface, so a
+ // bearer needs the account-level profile scope, not just any grant.
+ if (!requestUserHasScope(user, 'profile')) return error(res, 403, 'insufficient_scope', 'this token needs the profile scope');
if (req.method === 'GET') {
const rl = await limits.companionRead(user.id);
diff --git a/api/companion/events/[id].js b/api/companion/events/[id].js
index c2a5be14d..7b5e184ac 100644
--- a/api/companion/events/[id].js
+++ b/api/companion/events/[id].js
@@ -4,7 +4,7 @@
// so a message spoken on a laptop is not repeated by the phone an hour later.
import { z } from 'zod';
-import { getRequestUser } from '../../_lib/auth.js';
+import { getRequestUser, requestUserHasScope } from '../../_lib/auth.js';
import { cors, json, method, wrap, error, readJson, rateLimited } from '../../_lib/http.js';
import { requireCsrf } from '../../_lib/csrf.js';
import { limits } from '../../_lib/rate-limit.js';
@@ -22,6 +22,9 @@ export default wrap(async (req, res) => {
const user = await getRequestUser(req, res);
if (!user) return error(res, 401, 'unauthorized', 'sign in required');
+ // Private messages and the bridge token live behind this surface, so a
+ // bearer needs the account-level profile scope, not just any grant.
+ if (!requestUserHasScope(user, 'profile')) return error(res, 403, 'insufficient_scope', 'this token needs the profile scope');
if (!(await requireCsrf(req, res, user.id))) return;
const rl = await limits.companionRead(user.id);
diff --git a/api/companion/events/[id]/reply.js b/api/companion/events/[id]/reply.js
index cd111d5ad..baa11e0cc 100644
--- a/api/companion/events/[id]/reply.js
+++ b/api/companion/events/[id]/reply.js
@@ -11,7 +11,7 @@
// are refused with a message that says which lane could not do it.
import { z } from 'zod';
-import { getRequestUser } from '../../../_lib/auth.js';
+import { getRequestUser, requestUserHasScope } from '../../../_lib/auth.js';
import { cors, json, method, wrap, error, readJson, rateLimited } from '../../../_lib/http.js';
import { requireCsrf } from '../../../_lib/csrf.js';
import { limits } from '../../../_lib/rate-limit.js';
@@ -29,6 +29,9 @@ export default wrap(async (req, res) => {
const user = await getRequestUser(req, res);
if (!user) return error(res, 401, 'unauthorized', 'sign in required');
+ // Private messages and the bridge token live behind this surface, so a
+ // bearer needs the account-level profile scope, not just any grant.
+ if (!requestUserHasScope(user, 'profile')) return error(res, 403, 'insufficient_scope', 'this token needs the profile scope');
if (!(await requireCsrf(req, res, user.id))) return;
// A reply opens a connection to the user's own provider, so it shares the
diff --git a/api/companion/events/index.js b/api/companion/events/index.js
index 88cd82775..499eeed99 100644
--- a/api/companion/events/index.js
+++ b/api/companion/events/index.js
@@ -6,7 +6,7 @@
// pending=1 only what has not been delivered or dismissed
// min_importance=<0-100> floor, for the "only the loud ones" view
-import { getRequestUser } from '../../_lib/auth.js';
+import { getRequestUser, requestUserHasScope } from '../../_lib/auth.js';
import { cors, json, method, wrap, error, rateLimited } from '../../_lib/http.js';
import { limits } from '../../_lib/rate-limit.js';
import { listEvents, getSettings } from '../../_lib/companion/store.js';
@@ -17,6 +17,9 @@ export default wrap(async (req, res) => {
const user = await getRequestUser(req, res);
if (!user) return error(res, 401, 'unauthorized', 'sign in required');
+ // Private messages and the bridge token live behind this surface, so a
+ // bearer needs the account-level profile scope, not just any grant.
+ if (!requestUserHasScope(user, 'profile')) return error(res, 403, 'insufficient_scope', 'this token needs the profile scope');
const rl = await limits.companionRead(user.id);
if (!rl.success) return rateLimited(res, rl);
diff --git a/api/companion/poll.js b/api/companion/poll.js
index 6a6a1bc67..5d878b742 100644
--- a/api/companion/poll.js
+++ b/api/companion/poll.js
@@ -4,7 +4,7 @@
// the button on the setup page, so a user who just connected something sees it
// work in the same breath rather than waiting for the next tick.
-import { getRequestUser } from '../_lib/auth.js';
+import { getRequestUser, requestUserHasScope } from '../_lib/auth.js';
import { cors, json, method, wrap, error, rateLimited } from '../_lib/http.js';
import { requireCsrf } from '../_lib/csrf.js';
import { limits } from '../_lib/rate-limit.js';
@@ -18,6 +18,9 @@ export default wrap(async (req, res) => {
const user = await getRequestUser(req, res);
if (!user) return error(res, 401, 'unauthorized', 'sign in required');
+ // Private messages and the bridge token live behind this surface, so a
+ // bearer needs the account-level profile scope, not just any grant.
+ if (!requestUserHasScope(user, 'profile')) return error(res, 403, 'insufficient_scope', 'this token needs the profile scope');
if (!(await requireCsrf(req, res, user.id))) return;
const rl = await limits.companionPoll(user.id);
diff --git a/api/companion/settings.js b/api/companion/settings.js
index 39be89e0d..00f340120 100644
--- a/api/companion/settings.js
+++ b/api/companion/settings.js
@@ -6,7 +6,7 @@
// or a Mac script posts with, so the setup page has to be able to show it.
import { z } from 'zod';
-import { getRequestUser } from '../_lib/auth.js';
+import { getRequestUser, requestUserHasScope } from '../_lib/auth.js';
import { cors, json, method, wrap, error, readJson, rateLimited } from '../_lib/http.js';
import { requireCsrf } from '../_lib/csrf.js';
import { limits } from '../_lib/rate-limit.js';
@@ -66,6 +66,9 @@ export default wrap(async (req, res) => {
const user = await getRequestUser(req, res);
if (!user) return error(res, 401, 'unauthorized', 'sign in required');
+ // Private messages and the bridge token live behind this surface, so a
+ // bearer needs the account-level profile scope, not just any grant.
+ if (!requestUserHasScope(user, 'profile')) return error(res, 403, 'insufficient_scope', 'this token needs the profile scope');
if (req.method === 'GET') {
const rl = await limits.companionRead(user.id);
diff --git a/api/companion/sources/[id].js b/api/companion/sources/[id].js
index 926a83608..93cd45fa9 100644
--- a/api/companion/sources/[id].js
+++ b/api/companion/sources/[id].js
@@ -3,7 +3,7 @@
// POST /api/companion/sources/:id → poll it right now ("check now").
import { z } from 'zod';
-import { getRequestUser } from '../../_lib/auth.js';
+import { getRequestUser, requestUserHasScope } from '../../_lib/auth.js';
import { cors, json, method, wrap, error, readJson, rateLimited } from '../../_lib/http.js';
import { requireCsrf } from '../../_lib/csrf.js';
import { limits } from '../../_lib/rate-limit.js';
@@ -22,6 +22,9 @@ export default wrap(async (req, res) => {
const user = await getRequestUser(req, res);
if (!user) return error(res, 401, 'unauthorized', 'sign in required');
+ // Private messages and the bridge token live behind this surface, so a
+ // bearer needs the account-level profile scope, not just any grant.
+ if (!requestUserHasScope(user, 'profile')) return error(res, 403, 'insufficient_scope', 'this token needs the profile scope');
if (!(await requireCsrf(req, res, user.id))) return;
const id = String(req.query?.id || '').trim();
diff --git a/api/companion/sources/index.js b/api/companion/sources/index.js
index 0e6020b36..e7eb03ec7 100644
--- a/api/companion/sources/index.js
+++ b/api/companion/sources/index.js
@@ -7,7 +7,7 @@
// cron run three minutes later.
import { z } from 'zod';
-import { getRequestUser } from '../../_lib/auth.js';
+import { getRequestUser, requestUserHasScope } from '../../_lib/auth.js';
import { cors, json, method, wrap, error, readJson, rateLimited } from '../../_lib/http.js';
import { requireCsrf } from '../../_lib/csrf.js';
import { limits } from '../../_lib/rate-limit.js';
@@ -73,6 +73,9 @@ export default wrap(async (req, res) => {
const user = await getRequestUser(req, res);
if (!user) return error(res, 401, 'unauthorized', 'sign in required');
+ // Private messages and the bridge token live behind this surface, so a
+ // bearer needs the account-level profile scope, not just any grant.
+ if (!requestUserHasScope(user, 'profile')) return error(res, 403, 'insufficient_scope', 'this token needs the profile scope');
if (req.method === 'GET') {
const rl = await limits.companionRead(user.id);
diff --git a/api/gateway/connections.js b/api/gateway/connections.js
index 5bcd48160..142ee960e 100644
--- a/api/gateway/connections.js
+++ b/api/gateway/connections.js
@@ -9,12 +9,13 @@
// PATCH { id, notify?, default_agent_id? } → { link }
// DELETE ?id= → { revoked: true }
//
-// Session or bearer auth; writes are CSRF-gated (bearer exempt) and share the
-// gatewaySiteWrite budget. docs/chat-gateways.md describes the whole flow.
+// Session or bearer auth (a bearer needs agents:read to list and agents:write
+// plus wallet:write to change anything); writes are CSRF-gated (bearer exempt)
+// and share the gatewaySiteWrite budget. docs/chat-gateways.md describes the whole flow.
import { z } from 'zod';
import { sql } from '../_lib/db.js';
-import { getRequestUser } from '../_lib/auth.js';
+import { getRequestUser, requestUserHasScope } from '../_lib/auth.js';
import { cors, json, method, wrap, error, readJson, rateLimited } from '../_lib/http.js';
import { requireCsrf } from '../_lib/csrf.js';
import { limits } from '../_lib/rate-limit.js';
@@ -60,6 +61,13 @@ export default wrap(async (req, res) => {
if (!method(req, res, ['GET', 'POST', 'PATCH', 'DELETE'])) return;
const user = await getRequestUser(req, res);
if (!user) return error(res, 401, 'unauthorized', 'sign in to manage chat connections');
+ // A paired chat can approve the agent's trades and lift its risk limits, so
+ // pairing, editing or revoking one is a wallet-level grant. A bearer must
+ // hold agents:write and wallet:write; reading the list needs agents:read.
+ const needed = req.method === 'GET' ? 'agents:read' : 'agents:write wallet:write';
+ if (!requestUserHasScope(user, needed)) {
+ return error(res, 403, 'insufficient_scope', `this token needs the ${needed} scope`);
+ }
if (req.method === 'GET') {
const [links, agents, bots] = await Promise.all([
diff --git a/api/home/[id]/grants.js b/api/home/[id]/grants.js
index b63d13e6a..e6fcefcb7 100644
--- a/api/home/[id]/grants.js
+++ b/api/home/[id]/grants.js
@@ -15,7 +15,7 @@
import { logAudit } from '../../_lib/audit.js';
import { requireCsrf } from '../../_lib/csrf.js';
-import { resolveHomeAccess } from '../../_lib/home/access.js';
+import { canAssertConfirmation, CONFIRMATION_REQUIRES_SESSION, resolveHomeAccess } from '../../_lib/home/access.js';
import { homeError, homeFailure, HOME_ERR } from '../../_lib/home/errors.js';
import { grantEntity, listGrants, logHomeAction, revokeGrant } from '../../_lib/home/store.js';
import { cors, error, json, method, rateLimited, readJson, wrap } from '../../_lib/http.js';
@@ -45,7 +45,13 @@ export default wrap(async (req, res) => {
}
// Both writes change what the agent may do unattended, so both need a real
- // person behind them.
+ // person behind them. requireCsrf alone does not get there: it exempts every
+ // bearer caller by design, so a token holding `home:act` could otherwise
+ // grant itself `lock.front_door` and then unlock it with no confirmation.
+ // A grant is a standing yes, and only a session can say yes.
+ if (!canAssertConfirmation(caller)) {
+ return error(res, CONFIRMATION_REQUIRES_SESSION.status, CONFIRMATION_REQUIRES_SESSION.code, CONFIRMATION_REQUIRES_SESSION.message);
+ }
if (!(await requireCsrf(req, res, caller.userId))) return;
const rl = await limits.homeAct(caller.userId);
if (!rl.success) return rateLimited(res, rl, 'too many permission changes, slow down');
diff --git a/api/knock/settings.js b/api/knock/settings.js
index 48debcd12..b7a8c603d 100644
--- a/api/knock/settings.js
+++ b/api/knock/settings.js
@@ -7,7 +7,7 @@
// door.
import { z } from 'zod';
-import { getRequestUser } from '../_lib/auth.js';
+import { getRequestUser, requestUserHasScope } from '../_lib/auth.js';
import { cors, json, method, wrap, error, readJson, rateLimited } from '../_lib/http.js';
import { requireCsrf } from '../_lib/csrf.js';
import { limits } from '../_lib/rate-limit.js';
@@ -47,6 +47,9 @@ export default wrap(async (req, res) => {
if (!user) return error(res, 401, 'unauthorized', 'sign in required');
if (req.method === 'GET') {
+ if (!requestUserHasScope(user, 'profile')) {
+ return error(res, 403, 'insufficient_scope', 'this token needs the profile scope');
+ }
const rl = await limits.knockRead(user.id);
if (!rl.success) return rateLimited(res, rl);
return json(res, 200, await ownerView(user));
@@ -58,6 +61,14 @@ export default wrap(async (req, res) => {
const body = parse(patchBody, await readJson(req));
+ // Pointing the payout at another wallet redirects every future paid knock,
+ // so a bearer needs wallet:write for that; the rest of the door is profile.
+ const movesPayout = body.pay_to_solana !== undefined || body.pay_to_base !== undefined;
+ const needed = movesPayout ? 'profile wallet:write' : 'profile';
+ if (!requestUserHasScope(user, needed)) {
+ return error(res, 403, 'insufficient_scope', `this token needs the ${needed} scope`);
+ }
+
if (body.block) await addBlock(user.id, body.block);
if (body.unblock) await removeBlock(user.id, body.unblock);
diff --git a/tests/api/api-keys.test.js b/tests/api/api-keys.test.js
index 053906ac9..64236e78f 100644
--- a/tests/api/api-keys.test.js
+++ b/tests/api/api-keys.test.js
@@ -200,6 +200,29 @@ describe('POST /api/api-keys — create', () => {
expect(status).toBe(400);
expect(body.error).toBe('validation_error');
});
+
+ it('refuses a bearer minting scopes beyond its own grant (no escalation)', async () => {
+ authState.bearer = { userId: 'user-4', scope: 'profile', source: 'oauth' };
+ const { status, body } = await invoke({
+ method: 'POST',
+ body: { name: 'Escalate', scope: 'profile wallet:write agents:write' },
+ });
+ expect(status).toBe(403);
+ expect(body.error).toBe('insufficient_scope');
+ expect(sqlState.calls.some((c) => /insert into api_keys/i.test(c.query))).toBe(false);
+ });
+
+ it('lets a bearer mint a key within its own grant', async () => {
+ authState.bearer = { userId: 'user-5', scope: 'profile avatars:read', source: 'apikey' };
+ sqlState.queue.push([
+ { id: 'k5', name: 'Narrow', prefix: 'sk_live_xxxxxx', scope: 'avatars:read', expires_at: null, created_at: '2024-01-01T00:00:00Z' },
+ ]);
+ const { status } = await invoke({
+ method: 'POST',
+ body: { name: 'Narrow', scope: 'avatars:read' },
+ });
+ expect(status).toBe(201);
+ });
});
describe('method routing', () => {
diff --git a/tests/home-security.test.js b/tests/home-security.test.js
index 40b6f3b6c..4f72d6fa1 100644
--- a/tests/home-security.test.js
+++ b/tests/home-security.test.js
@@ -373,6 +373,19 @@ describe('home security 3: only a session with CSRF can redeem a confirmation',
expect(mapped.has(capability), `capability "${capability}" maps to no OAuth scope`).toBe(true);
}
});
+
+ it('a standing grant can only be written by a session, never a bearer', () => {
+ // A grant is a standing yes: the bridge and the MCP gate both skip the
+ // confirmation for a granted entity. requireCsrf exempts bearer callers,
+ // so without an explicit session check a token holding home:act could
+ // grant itself lock.front_door and then unlock it with nobody present.
+ const code = stripComments(read(join(REPO, 'api', 'home', '[id]', 'grants.js')));
+ const asked = code.search(/canAssertConfirmation\s*\(/);
+ expect(asked, 'grants.js must refuse a non-session principal on writes').toBeGreaterThan(-1);
+ const writes = code.search(/handleGrant\s*\(\s*req/);
+ expect(writes).toBeGreaterThan(-1);
+ expect(asked, 'the session check must run before any grant is written').toBeLessThan(writes);
+ });
});
// ---------------------------------------------------------------------------