Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
fix(authz): require wallet:write, agents:write or memory scopes on the remaining money and agent-write routes
nirholas2b1b7b068381
diff --git a/api/_lib/account-auth.js b/api/_lib/account-auth.jsindex 01e743bf5..4a269ee7e 100644--- a/api/_lib/account-auth.js+++ b/api/_lib/account-auth.js@@ -9,6 +9,6 @@ export async function resolveAccount(req, res) {const session = await getSessionUser(req, res);if (session) return { userId: session.id, source: 'session' };const bearer = await authenticateBearer(extractBearer(req));- if (bearer) return { userId: bearer.userId, source: bearer.source };+ if (bearer) return { userId: bearer.userId, source: bearer.source, scope: bearer.scope || '' };return null;}diff --git a/api/_lib/labor-auth.js b/api/_lib/labor-auth.jsindex 30985b145..1b37a35e2 100644--- a/api/_lib/labor-auth.js+++ b/api/_lib/labor-auth.js@@ -4,6 +4,7 @@import { authenticateBearer, extractBearer, getSessionUser } from './auth.js';import { requireCsrf } from './csrf.js';+import { assertBearerMaySpend } from './spend-scope.js';import { error } from './http.js';import { sql } from './db.js';import { isUuid } from './validate.js';@@ -12,10 +13,22 @@ import { isUuid } from './validate.js';* Authenticate a write. Returns { userId, session } or null. When it returns* null it has ALREADY written the 401/403 response (CSRF failures included), so* the caller must simply `return`.+ *+ * `spend: true` marks a write that moves or commits the caller's funds (post a+ * bounty into escrow, award it, set auto-award autonomy, an Agora escrow): a+ * bearer must then hold wallet:write, not just any grant on the account.*/-export async function authWrite(req, res) {+export async function authWrite(req, res, { spend = false } = {}) {const session = await getSessionUser(req);const bearer = session ? null : await authenticateBearer(extractBearer(req));+ if (bearer && spend) {+ try {+ assertBearerMaySpend(bearer, req);+ } catch (e) {+ error(res, e.status, e.code, e.message);+ return null;+ }+ }if (!session && !bearer) {error(res, 401, 'unauthorized', 'sign in required');return null;diff --git a/api/_lib/strategy-loop/routes.js b/api/_lib/strategy-loop/routes.jsindex da939dffe..863d35087 100644--- a/api/_lib/strategy-loop/routes.js+++ b/api/_lib/strategy-loop/routes.js@@ -12,6 +12,7 @@// POST /agents/:id/stop lifecycle: stopped (an open tick cancels before its next step)import { sql } from '../db.js';+import { hasScope } from '../auth.js';import { apiError, intParam, page, requireUuid } from '../agents-v1/http.js';import { loadOwnedAgent, setAgentStatus } from '../agents-v1/agents.js';import { LoopSettingsError, parseLoopPatch, saveLoopSettings } from './settings.js';@@ -47,6 +48,13 @@ async function patchLoop({ params, principal, body }) {if (!Object.keys(patch).length) {throw apiError(400, 'empty_patch', 'Send at least one of enabled, goal, intervalSeconds, tools, maxSteps, caps or financialEnabled.');}+ // Turning the financial tier on or moving the USDC cap lets loop ticks spend+ // from the agent wallet, so a bearer needs wallet:write for it, the same bar+ // every other v1 money route sets. agents:write alone tunes the loop only.+ const touchesMoney = patch.financialEnabled === true || patch.dailyUsdcCapUsd != null;+ if (touchesMoney && principal.source !== 'session' && !hasScope(principal.scope, 'wallet:write')) {+ throw apiError(403, 'insufficient_scope', 'Enabling the financial tier or changing the USDC cap needs the wallet:write scope.');+ }if (patch.financialEnabled === true) await requireAgreement(principal.userId);await saveLoopSettings(agent, patch);return loopStatus(agent);diff --git a/api/_lib/vault-auth.js b/api/_lib/vault-auth.jsindex 2dfe0d430..a880af887 100644--- a/api/_lib/vault-auth.js+++ b/api/_lib/vault-auth.js@@ -6,6 +6,7 @@import { getSessionUser, authenticateBearer, extractBearer } from './auth.js';import { requireCsrf } from './csrf.js';+import { assertBearerMaySpend } from './spend-scope.js';import { error } from './http.js';import { sql } from './db.js';import { getTraderStats } from './trader-stats.js';@@ -15,7 +16,7 @@ export async function resolveUserId(req) {const session = await getSessionUser(req);if (session) return { userId: session.id, session: true };const bearer = await authenticateBearer(extractBearer(req));- if (bearer) return { userId: bearer.userId, session: false };+ if (bearer) return { userId: bearer.userId, session: false, scope: bearer.scope || '' };return null;}@@ -23,10 +24,21 @@ export async function resolveUserId(req) {* Authenticate a write. Returns { userId, session } or null (having already sent a* 401/403). CSRF is enforced for session callers; bearer/API-key callers are exempt* inside requireCsrf, like every other write path in the app.+ *+ * `spend: true` marks a write that moves vault or agent USDC (deposit, redeem,+ * trade, claim fees): a bearer must then hold wallet:write.*/-export async function authWrite(req, res) {+export async function authWrite(req, res, { spend = false } = {}) {const who = await resolveUserId(req);if (!who) { error(res, 401, 'unauthorized', 'sign in required'); return null; }+ if (spend && !who.session) {+ try {+ assertBearerMaySpend({ scope: who.scope }, req);+ } catch (e) {+ error(res, e.status, e.code, e.message);+ return null;+ }+ }if (who.session && !(await requireCsrf(req, res, who.userId))) return null;return who;}diff --git a/api/agents/[id]/api-service.js b/api/agents/[id]/api-service.jsindex 707f97486..38a3e2d21 100644--- a/api/agents/[id]/api-service.js+++ b/api/agents/[id]/api-service.js@@ -8,7 +8,7 @@// description } on meta.api_service. Activation is refused, with the reason,// when the agent is private, has no brain, or has no Solana payout address.-import { getSessionUser, authenticateBearer, extractBearer } from '../../_lib/auth.js';+import { getSessionUser, authenticateBearer, extractBearer, hasScope } from '../../_lib/auth.js';import { cors, error, json, readJson, respondError, wrap } from '../../_lib/http.js';import { requireCsrf } from '../../_lib/csrf.js';import { isUuid } from '../../_lib/validate.js';@@ -33,7 +33,10 @@ async function resolveAuth(req) {const session = await getSessionUser(req);if (session) return { userId: session.id };const bearer = await authenticateBearer(extractBearer(req));- if (bearer) return { userId: bearer.userId };+ // Selling the agent as a paid API (and its price) is an agents:write change;+ // reading the config is agents:read. A narrower key gets neither.+ const needed = req.method === 'GET' ? 'agents:read' : 'agents:write';+ if (bearer) return hasScope(bearer.scope, needed) ? { userId: bearer.userId } : { userId: null, scopeNeeded: needed };return null;}@@ -70,6 +73,7 @@ export default wrap(async (req, res) => {const auth = await resolveAuth(req);if (!auth) return error(res, 401, 'unauthorized', 'sign in required');+ if (auth.scopeNeeded) return error(res, 403, 'insufficient_scope', `this token needs the ${auth.scopeNeeded} scope`);if (!isUuid(id)) return error(res, 404, 'not_found', 'agent not found');if (req.method === 'PUT' && !(await requireCsrf(req, res, auth.userId))) return;diff --git a/api/agents/[id]/memory-seed-farcaster.js b/api/agents/[id]/memory-seed-farcaster.jsindex 1f78207e9..d87d9338b 100644--- a/api/agents/[id]/memory-seed-farcaster.js+++ b/api/agents/[id]/memory-seed-farcaster.js@@ -25,7 +25,7 @@ import { randomUUID } from 'node:crypto';import { z } from 'zod';import { verifyMessage } from 'ethers';import { sql } from '../../_lib/db.js';-import { getSessionUser, authenticateBearer, extractBearer } from '../../_lib/auth.js';+import { getSessionUser, authenticateBearer, extractBearer, hasScope } from '../../_lib/auth.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';@@ -94,6 +94,12 @@ async function requireOwnedAgent(req, agentId) {const bearer = session ? null : await authenticateBearer(extractBearer(req));const userId = session?.id ?? bearer?.userId;if (!userId) throw Object.assign(new Error('sign in required'), { status: 401, code: 'unauthorized' });+ // Seeding rewrites and deletes the agent's memories, so a bearer needs the+ // memory scope that matches the verb, exactly as the memory MCP tools do.+ const needed = req.method === 'GET' ? 'memory:read' : 'memory:write';+ if (bearer && !hasScope(bearer.scope, needed)) {+ throw Object.assign(new Error(`this token needs the ${needed} scope`), { status: 403, code: 'insufficient_scope' });+ }const [agent] = await sql`SELECT id, farcaster_fid, farcaster_fname, farcaster_seeded_atdiff --git a/api/agents/[id]/memory-seed-github.js b/api/agents/[id]/memory-seed-github.jsindex fe697a38c..45d8dba3e 100644--- a/api/agents/[id]/memory-seed-github.js+++ b/api/agents/[id]/memory-seed-github.js@@ -10,7 +10,7 @@// social_connection. Rate limit: 1 seed per agent per 6 hours.import { sql } from '../../_lib/db.js';-import { getSessionUser, authenticateBearer, extractBearer } from '../../_lib/auth.js';+import { getSessionUser, authenticateBearer, extractBearer, hasScope } from '../../_lib/auth.js';import { requireCsrf } from '../../_lib/csrf.js';import { cors, json, method, readJson, wrap, error, rateLimited } from '../../_lib/http.js';import { limits } from '../../_lib/rate-limit.js';@@ -38,6 +38,12 @@ async function requireOwnedAgent(req, agentId) {const bearer = session ? null : await authenticateBearer(extractBearer(req));const userId = session?.id ?? bearer?.userId;if (!userId) throw Object.assign(new Error('sign in required'), { status: 401, code: 'unauthorized' });+ // Seeding rewrites and deletes the agent's memories, so a bearer needs the+ // memory scope that matches the verb, exactly as the memory MCP tools do.+ const needed = req.method === 'GET' ? 'memory:read' : 'memory:write';+ if (bearer && !hasScope(bearer.scope, needed)) {+ throw Object.assign(new Error(`this token needs the ${needed} scope`), { status: 403, code: 'insufficient_scope' });+ }const [agent] = await sql`SELECT id FROM agent_identitiesdiff --git a/api/agents/_id/_sub.js b/api/agents/_id/_sub.jsindex 6b479412b..da52ec879 100644--- a/api/agents/_id/_sub.js+++ b/api/agents/_id/_sub.js@@ -6,6 +6,7 @@ import { Wallet } from 'ethers';import { z } from 'zod';import { sql } from '../../_lib/db.js';import { getSessionUser, authenticateBearer, extractBearer } from '../../_lib/auth.js';+import { assertBearerMaySpend } from '../../_lib/spend-scope.js';import { cors, json, method, readJson, wrap, error, rateLimited, embedReadCors } from '../../_lib/http.js';import { limits, clientIp } from '../../_lib/rate-limit.js';import { requireCsrf } from '../../_lib/csrf.js';@@ -27,7 +28,7 @@ async function resolveAuth(req) {const session = await getSessionUser(req);if (session) return { userId: session.id };const bearer = await authenticateBearer(extractBearer(req));- if (bearer) return { userId: bearer.userId };+ if (bearer) return { userId: bearer.userId, bearer };return null;}@@ -572,6 +573,9 @@ export const handleSign = wrap(async (req, res, id) => {const auth = await resolveAuth(req);if (!auth) return error(res, 401, 'unauthorized', 'sign in required');+ // A signature from the agent's custodial key can authorize off-platform value+ // (a login, an order), so a bearer needs the same wallet:write as a spend.+ assertBearerMaySpend(auth.bearer, req);// CSRF on state-changing session-cookie requests; bearer tokens are exempt.if (!(await requireCsrf(req, res, auth.userId))) return;diff --git a/api/agents/activity.js b/api/agents/activity.jsindex 160003b3e..bd2f211a1 100644--- a/api/agents/activity.js+++ b/api/agents/activity.js@@ -26,13 +26,15 @@// casting: ["<agentId>", ...] // has a non-expired agent:screen:*:frame// }//-// Public read: agent activity is already public on every agent profile, so no-// auth is required. Unknown ids are simply absent from `activity`.+// Public read for public agents: their activity is already on every agent+// profile, so no auth is required. A private agent's activity is returned only+// to its signed-in owner. Unknown and private ids are simply absent.import { cors, json, error, method, wrap, rateLimited, readBody } from '../_lib/http.js';import { limits, clientIp } from '../_lib/rate-limit.js';import { getRedis } from '../_lib/redis.js';import { sql } from '../_lib/db.js';+import { getSessionUser } from '../_lib/auth.js';import { isUuid } from '../_lib/validate.js';import { rowToEntry } from '../_lib/agent-activity.js';@@ -98,9 +100,15 @@ export default wrap(async function handleAgentsActivity(req, res) {// One LATERAL join over the id array: Postgres runs the per-agent index scan// once per id and stops at PER_AGENT rows, instead of the N separate queries a// per-card stream would have issued.+ // Public agents only, plus the caller's own: a private agent's actions are+ // owner-only on /api/agents/:id/actions, and a known id must not read them here.+ const viewer = (await getSessionUser(req).catch(() => null))?.id ?? null;const rows = await sql`SELECT a.agent_id, a.type, a.payload, a.created_atFROM unnest(${ids}::uuid[]) AS t(id)+ JOIN agent_identities ai+ ON ai.id = t.id AND ai.deleted_at IS NULL+ AND (ai.is_public IS DISTINCT FROM false OR ai.user_id = ${viewer})JOIN LATERAL (SELECT agent_id, type, payload, created_atFROM agent_actionsdiff --git a/api/agents/agent-mirror.js b/api/agents/agent-mirror.jsindex b106bc07b..9ef6d357a 100644--- a/api/agents/agent-mirror.js+++ b/api/agents/agent-mirror.js@@ -16,6 +16,7 @@// GET /api/agents/:id/mirror/fills recent mirror fills feed (owner)import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';+import { assertBearerMaySpend } from '../_lib/spend-scope.js';import { sql } from '../_lib/db.js';import { cors, json, method, error, readJson, rateLimited } from '../_lib/http.js';import { limits, clientIp } from '../_lib/rate-limit.js';@@ -33,7 +34,7 @@ const netOf = (v) => (NETWORKS.has(v) ? v : 'mainnet');async function resolveAuth(req) {const session = await getSessionUser(req);if (session) return { userId: session.id };- const bearer = await authenticateBearer(extractBearer(req));+ const bearer = assertBearerMaySpend(await authenticateBearer(extractBearer(req)), req);if (bearer) return { userId: bearer.userId };return null;}diff --git a/api/agents/capabilities.js b/api/agents/capabilities.jsindex 2e27d294e..097de0ca7 100644--- a/api/agents/capabilities.js+++ b/api/agents/capabilities.js@@ -14,6 +14,7 @@// guards). This endpoint is the issuance + lifecycle + owner-visibility surface.import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';+import { assertBearerMaySpend } from '../_lib/spend-scope.js';import { sql } from '../_lib/db.js';import { cors, json, method, error, readJson, rateLimited } from '../_lib/http.js';import { limits, clientIp } from '../_lib/rate-limit.js';@@ -29,7 +30,7 @@ import {async function resolveAuth(req) {const session = await getSessionUser(req);if (session) return { userId: session.id };- const bearer = await authenticateBearer(extractBearer(req));+ const bearer = assertBearerMaySpend(await authenticateBearer(extractBearer(req)), req);if (bearer) return { userId: bearer.userId };return null;}diff --git a/api/agora/act.js b/api/agora/act.jsindex 0a6381045..0e4e4ffa9 100644--- a/api/agora/act.js+++ b/api/agora/act.js@@ -604,7 +604,7 @@ export default wrap(async (req, res) => {if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;if (!method(req, res, ['POST'])) return;- const auth = await authWrite(req, res);+ const auth = await authWrite(req, res, { spend: true });if (!auth) return; // authWrite already wrote 401/403const { userId } = auth;diff --git a/api/labor/award.js b/api/labor/award.jsindex 7bf599c94..9efbc8f5b 100644--- a/api/labor/award.js+++ b/api/labor/award.js@@ -14,7 +14,7 @@ export default wrap(async (req, res) => {if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;if (!method(req, res, ['POST'])) return;- const auth = await authWrite(req, res);+ const auth = await authWrite(req, res, { spend: true });if (!auth) return;const { userId } = auth;diff --git a/api/labor/policy.js b/api/labor/policy.jsindex 46b48c054..384946594 100644--- a/api/labor/policy.js+++ b/api/labor/policy.js@@ -22,7 +22,7 @@ export default wrap(async (req, res) => {if (!method(req, res, ['GET', 'PUT'])) return;- const auth = await authWrite(req, res);+ const auth = await authWrite(req, res, { spend: true });if (!auth) return;const { userId } = auth;diff --git a/api/labor/post.js b/api/labor/post.jsindex a8d39503e..4a1471bda 100644--- a/api/labor/post.js+++ b/api/labor/post.js@@ -26,7 +26,7 @@ export default wrap(async (req, res) => {if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;if (!method(req, res, ['POST'])) return;- const auth = await authWrite(req, res);+ const auth = await authWrite(req, res, { spend: true });if (!auth) return;const { userId } = auth;diff --git a/api/marketplace/buy-asset.js b/api/marketplace/buy-asset.jsindex 3cf47fc64..b569a9bb6 100644--- a/api/marketplace/buy-asset.js+++ b/api/marketplace/buy-asset.js@@ -29,6 +29,7 @@ import crypto from 'node:crypto';import { sql } from '../_lib/db.js';import { authenticateBearer, extractBearer, getSessionUser } from '../_lib/auth.js';+import { assertBearerMaySpend } from '../_lib/spend-scope.js';import { cors, error, json, method, readJson, wrap, rateLimited } from '../_lib/http.js';import { clientIp, limits } from '../_lib/rate-limit.js';import { requireCsrf } from '../_lib/csrf.js';@@ -87,7 +88,7 @@ async function resolveAuth(req) {const session = await getSessionUser(req);if (session) return { userId: session.id };const bearer = await authenticateBearer(extractBearer(req));- if (bearer) return { userId: bearer.userId };+ if (bearer) return { userId: bearer.userId, bearer };return null;}@@ -183,6 +184,8 @@ async function handleCreate(req, res) {// autonomous spend rate).let buyerAgent = null;if (agentId) {+ // Paying from the agent's custodial wallet: a bearer needs wallet:write.+ assertBearerMaySpend(auth?.bearer, req);const rlAgent = await limits.agentBuy(agentId);if (!rlAgent.success) {return rateLimited(res, rlAgent, 'too many autonomous purchases — try again later');diff --git a/api/pay/session.js b/api/pay/session.jsindex eb19fcb2c..475d2bc06 100644--- a/api/pay/session.js+++ b/api/pay/session.js@@ -13,6 +13,7 @@// GET /api/pay/session list all sessions for the callerimport { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';+import { assertBearerMaySpend } from '../_lib/spend-scope.js';import { cors, error, json, method, readJson, wrap, rateLimited } from '../_lib/http.js';import { limits, clientIp } from '../_lib/rate-limit.js';import {@@ -29,7 +30,9 @@ import { isSessionId } from '../_lib/pay/spend-governor.js';async function resolveUser(req, res) {const session = await getSessionUser(req, res);if (session) return session;- const bearer = await authenticateBearer(extractBearer(req));+ // Creating or widening a session moves credits into a spend envelope that+ // pays arbitrary x402 hosts, so a bearer needs wallet:write to write here.+ const bearer = assertBearerMaySpend(await authenticateBearer(extractBearer(req)), req);if (bearer) return { id: bearer.userId };return null;}diff --git a/api/swarms/index.js b/api/swarms/index.jsindex 6116cf949..2709c6705 100644--- a/api/swarms/index.js+++ b/api/swarms/index.js@@ -19,6 +19,7 @@import { cors, method, json, error, wrap, readJson, rateLimited } from '../_lib/http.js';import { parseLimit, parseOffset } from '../_lib/http-params.js';import { resolveAccount } from '../_lib/account-auth.js';+import { assertBearerMaySpend } from '../_lib/spend-scope.js';import { requireCsrf } from '../_lib/csrf.js';import { requireRealFundsAgreement } from '../_lib/real-funds-agreement.js';import { limits } from '../_lib/rate-limit.js';@@ -81,6 +82,8 @@ export default wrap(async (req, res) => {const body = await readJson(req);const action = String(body?.action || '');if (REAL_FUNDS_ACTIONS.has(action)) {+ // A bearer moving swarm SOL (contribute, exit, trade) needs wallet:write.+ if (auth.source !== 'session') assertBearerMaySpend({ scope: auth.scope }, req);const network = await swarmNetworkFor(body, action);if (!(await requireRealFundsAgreement(req, res, { userId: auth.userId, network, context: `swarm-${action}` }))) return;}diff --git a/api/tournaments/[id].js b/api/tournaments/[id].jsindex a7db26dc1..f4cd7c9a1 100644--- a/api/tournaments/[id].js+++ b/api/tournaments/[id].js@@ -18,6 +18,7 @@ import { limits, clientIp } from '../_lib/rate-limit.js';import { sql } from '../_lib/db.js';import { isUuid } from '../_lib/validate.js';import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';+import { assertBearerMaySpend } from '../_lib/spend-scope.js';import { computeTraderMetrics, fetchTraderPositions } from '../_lib/trader-stats.js';import {getTournament,@@ -38,7 +39,7 @@ const SSE_POLL_MS = 3_000;async function resolveUser(req) {const session = await getSessionUser(req);if (session) return { userId: session.id };- const bearer = await authenticateBearer(extractBearer(req));+ const bearer = assertBearerMaySpend(await authenticateBearer(extractBearer(req)), req);if (bearer) return { userId: bearer.userId };return null;}diff --git a/api/vaults/claim-fees.js b/api/vaults/claim-fees.jsindex 5eed495c1..301b8fcb8 100644--- a/api/vaults/claim-fees.js+++ b/api/vaults/claim-fees.js@@ -17,7 +17,7 @@ export default wrap(async (req, res) => {if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;if (!method(req, res, ['POST'])) return;- const who = await authWrite(req, res);+ const who = await authWrite(req, res, { spend: true });if (!who) return;const { userId } = who;diff --git a/api/vaults/deposit.js b/api/vaults/deposit.jsindex 12fd06ddc..9b723df75 100644--- a/api/vaults/deposit.js+++ b/api/vaults/deposit.js@@ -19,7 +19,7 @@ export default wrap(async (req, res) => {if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;if (!method(req, res, ['POST'])) return;- const who = await authWrite(req, res);+ const who = await authWrite(req, res, { spend: true });if (!who) return;const { userId } = who;diff --git a/api/vaults/redeem.js b/api/vaults/redeem.jsindex f40b143d3..0d2418e4d 100644--- a/api/vaults/redeem.js+++ b/api/vaults/redeem.js@@ -18,7 +18,7 @@ export default wrap(async (req, res) => {if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;if (!method(req, res, ['POST'])) return;- const who = await authWrite(req, res);+ const who = await authWrite(req, res, { spend: true });if (!who) return;const { userId } = who;diff --git a/api/vaults/trade.js b/api/vaults/trade.jsindex 93be96b07..ce230c4ea 100644--- a/api/vaults/trade.js+++ b/api/vaults/trade.js@@ -21,7 +21,7 @@ export default wrap(async (req, res) => {if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;if (!method(req, res, ['POST'])) return;- const who = await authWrite(req, res);+ const who = await authWrite(req, res, { spend: true });if (!who) return;const { userId } = who;diff --git a/tests/api/authz-hardening-2026-10.test.js b/tests/api/authz-hardening-2026-10.test.jsnew file mode 100644index 000000000..afa55f7c7--- /dev/null+++ b/tests/api/authz-hardening-2026-10.test.js@@ -0,0 +1,258 @@+// Regression guards for the October 2026 authorization sweep.+//+// Each block pins one finding: a narrow bearer acting with the account's full+// authority, a sign-in flow handing an account to whoever pre-registered its+// address, a public endpoint closing someone else's stake, a reused idempotency+// key leaking another sender's receipt, a forged node receipt, and an+// unfiltered read awarding any agent the platform's "model verified" badge.++import { describe, it, expect, vi, beforeEach } from 'vitest';+import { readFileSync } from 'node:fs';+import { join } from 'node:path';+import { Readable } from 'node:stream';+import { Keypair } from '@solana/web3.js';+import { ed25519 } from '@noble/curves/ed25519.js';+import bs58 from 'bs58';++const REPO = join(import.meta.dirname, '..', '..');+const src = (rel) => readFileSync(join(REPO, rel), 'utf8');++vi.mock('../../api/_lib/zauth.js', () => ({ instrument: () => false, drain: async () => {} }));+vi.mock('../../api/_lib/sentry.js', () => ({ captureException: () => {} }));++// ── shared request plumbing ───────────────────────────────────────────────────++function mkReq({ method = 'GET', url = '/', headers = {}, body = null, query = {} } = {}) {+ const req = body ? Readable.from([Buffer.from(JSON.stringify(body))]) : Readable.from([]);+ req.method = method;+ req.url = url;+ req.query = query;+ req.headers = { host: 'three.ws', ...(body ? { 'content-type': 'application/json' } : {}), ...headers };+ req.socket = { remoteAddress: '127.0.0.1' };+ return req;+}+function mkRes() {+ return {+ statusCode: 200,+ headers: {},+ body: '',+ headersSent: false,+ writableEnded: false,+ setHeader(k, v) { this.headers[k.toLowerCase()] = v; },+ getHeader(k) { return this.headers[k.toLowerCase()]; },+ end(chunk) { if (chunk !== undefined) this.body += chunk; this.writableEnded = true; this.headersSent = true; },+ };+}+const parseBody = (res) => (res.body ? JSON.parse(res.body) : null);++// ── 1. requestUserHasScope ────────────────────────────────────────────────────++describe('requestUserHasScope', () => {+ it('lets a cookie session through and holds a bearer to its grant', async () => {+ const { requestUserHasScope } = await import('../../api/_lib/auth.js');+ expect(requestUserHasScope({ id: 'u', email: '[email protected]' }, 'wallet:write')).toBe(true);+ expect(requestUserHasScope({ id: 'u', source: 'bearer', scope: 'inference' }, 'profile')).toBe(false);+ expect(requestUserHasScope({ id: 'u', source: 'bearer', scope: 'profile wallet:write' }, 'profile wallet:write')).toBe(true);+ expect(requestUserHasScope(null, 'profile')).toBe(false);+ });+});++// ── 2. reserved .local registration addresses ─────────────────────────────────++describe('registration refuses platform-minted .local addresses', () => {+ it('rejects the wallet, privy, sso and username placeholder domains', async () => {+ const { registerBody } = await import('../../api/_lib/validate.js');+ const ok = (email) => registerBody.safeParse({ email, password: 'correct horse battery' }).success;+ expect(ok('[email protected]')).toBe(true);+ expect(ok('[email protected]')).toBe(false);+ expect(ok('[email protected]')).toBe(false);+ expect(ok('[email protected]')).toBe(false);+ expect(ok('[email protected]')).toBe(false);+ expect(ok('[email protected]')).toBe(false);+ });++ it('SIWS never adopts a password account squatting the placeholder', () => {+ const code = src('api/auth/siws/[action].js');+ expect(code).toMatch(/existingUser\?\.password_hash/);+ });+});++// ── 3. reputation market: only the staker withdraws ───────────────────────────++describe('verifyUnstakeProof', () => {+ const kp = Keypair.generate();+ const position = { network: 'devnet', signature: '5'.repeat(88), staker: kp.publicKey.toBase58() };++ async function sign(keypair, issuedAt, pos = position) {+ const { unstakeProofMessage } = await import('../../src/shared/reputation-staking.js');+ const msg = new TextEncoder().encode(unstakeProofMessage({ network: pos.network, stakeSignature: pos.signature, issuedAt }));+ return bs58.encode(ed25519.sign(msg, keypair.secretKey.slice(0, 32)));+ }++ it('accepts a fresh signature by the staker', async () => {+ const { verifyUnstakeProof } = await import('../../api/_lib/reputation-market.js');+ const now = Date.now();+ const signature = await sign(kp, now);+ expect(() => verifyUnstakeProof({ position, proof: { issued_at: now, signature }, now })).not.toThrow();+ });++ it('refuses a missing proof, a stale proof, and another wallet', async () => {+ const { verifyUnstakeProof } = await import('../../api/_lib/reputation-market.js');+ const now = Date.now();+ expect(() => verifyUnstakeProof({ position, proof: null, now })).toThrow(/Sign the unstake message/);+ const old = now - 10 * 60_000;+ const staleSig = await sign(kp, old);+ expect(() => verifyUnstakeProof({ position, proof: { issued_at: old, signature: staleSig }, now })).toThrow(/too old/);+ const otherSig = await sign(Keypair.generate(), now);+ expect(() => verifyUnstakeProof({ position, proof: { issued_at: now, signature: otherSig }, now })).toThrow(/Only the wallet/);+ });++ it('refuses a staker proof minted for a different position', async () => {+ const { verifyUnstakeProof } = await import('../../api/_lib/reputation-market.js');+ const now = Date.now();+ const sig = await sign(kp, now, { ...position, signature: '6'.repeat(88) });+ expect(() => verifyUnstakeProof({ position, proof: { issued_at: now, signature: sig }, now })).toThrow(/Only the wallet/);+ });+});++// ── 4. knock: a reused request_id is a retry only for the same knock ──────────++const knockStore = { existing: null };+vi.mock('../../api/_lib/knock/store.js', async (orig) => ({+ ...(await orig()),+ findByRequestId: vi.fn(async () => knockStore.existing),+ recordKnock: vi.fn(async () => ({ id: 'new-knock' })),+ getDoor: vi.fn(async () => ({})),+ isBlocked: vi.fn(async () => false),+ knocksToday: vi.fn(async () => 0),+}));+vi.mock('../../api/_lib/companion/store.js', () => ({ insertEvent: vi.fn(async () => ({ id: 'evt' })) }));+vi.mock('../../api/_lib/notify.js', () => ({ insertNotification: vi.fn() }));++describe('deliverKnock duplicate handling', () => {+ const clean = { senderName: 'Ada', message: 'hello there', requestId: 'ada-001', subject: null };++ it('returns the original knock for a genuine retry', async () => {+ const { deliverKnock } = await import('../../api/_lib/knock/deliver.js');+ knockStore.existing = { id: 'orig', sender_name: 'Ada', message: 'hello there' };+ const out = await deliverKnock({ userId: 'owner', clean });+ expect(out.duplicate).toBe(true);+ expect(out.knock.id).toBe('orig');+ });++ it('refuses a different knock reusing the key, without disclosing the original', async () => {+ const { deliverKnock } = await import('../../api/_lib/knock/deliver.js');+ knockStore.existing = { id: 'orig', sender_name: 'Someone', message: 'private' };+ await expect(deliverKnock({ userId: 'owner', clean })).rejects.toMatchObject({ status: 409, code: 'request_id_conflict' });+ });+});++// ── 5. bearer scope on account surfaces ───────────────────────────────────────++const authState = { user: null };+vi.mock('../../api/_lib/auth.js', async (orig) => {+ const actual = await orig();+ return { ...actual, getRequestUser: vi.fn(async () => authState.user) };+});+vi.mock('../../api/_lib/rate-limit.js', () => {+ const ok = async () => ({ success: true, limit: 1, remaining: 1, reset: Date.now() + 1000 });+ return { limits: new Proxy({}, { get: () => ok }), clientIp: () => '127.0.0.1' };+});+vi.mock('../../api/_lib/csrf.js', () => ({ requireCsrf: vi.fn(async () => true) }));+vi.mock('../../api/_lib/db.js', () => ({+ sql: Object.assign(vi.fn(async () => []), { transaction: vi.fn(async () => []) }),+ isDbUnavailableError: () => false,+ isDbCapacityError: () => false,+}));++describe('bearer scope on the knock door and the chat gateway', () => {+ beforeEach(() => {+ authState.user = { id: 'owner', source: 'bearer', scope: 'inference' };+ });++ it('an inference-only key cannot move the knock payout', async () => {+ const { default: handler } = await import('../../api/knock/settings.js');+ const res = mkRes();+ await handler(mkReq({ method: 'PATCH', url: '/api/knock/settings', body: { pay_to_solana: 'Attacker1111111111111111111111111111111111' } }), res);+ expect(res.statusCode).toBe(403);+ expect(parseBody(res).error).toBe('insufficient_scope');+ });++ it('a profile key still cannot move the payout without wallet:write', async () => {+ authState.user = { id: 'owner', source: 'bearer', scope: 'profile' };+ const { default: handler } = await import('../../api/knock/settings.js');+ const res = mkRes();+ await handler(mkReq({ method: 'PATCH', url: '/api/knock/settings', body: { pay_to_base: '0x0000000000000000000000000000000000000001' } }), res);+ expect(res.statusCode).toBe(403);+ });++ it('an avatars-only token cannot pair a chat that approves trades', async () => {+ authState.user = { id: 'owner', source: 'bearer', scope: 'avatars:read' };+ const { default: handler } = await import('../../api/gateway/connections.js');+ const res = mkRes();+ await handler(mkReq({ method: 'POST', url: '/api/gateway/connections', body: { action: 'issue' } }), res);+ expect(res.statusCode).toBe(403);+ expect(parseBody(res).error).toBe('insufficient_scope');+ });++ it('every companion account route checks the profile scope', () => {+ for (const rel of [+ 'api/companion/settings.js',+ 'api/companion/poll.js',+ 'api/companion/events/index.js',+ 'api/companion/events/[id].js',+ 'api/companion/events/[id]/reply.js',+ 'api/companion/sources/index.js',+ 'api/companion/sources/[id].js',+ 'api/companion/contacts/index.js',+ 'api/companion/contacts/[id].js',+ 'api/companion/checkout.js',+ ]) {+ expect(src(rel), rel).toMatch(/requestUserHasScope\(user, 'profile'\)/);+ }+ });+});++// ── 6. source-pinned fixes ────────────────────────────────────────────────────++describe('source-pinned authorization fixes', () => {+ it('a node result receipt must be signed by the claiming node key', () => {+ expect(src('api/nodes/jobs/[id]/result.js')).toMatch(/receipt\?\.publicKey === job\.claimedBy/);+ });++ it('password reset consumes its token atomically and revokes refresh tokens', () => {+ const code = src('api/auth/[action].js');+ const fn = code.slice(code.indexOf('async function handleResetPassword'), code.indexOf('// ── verify-email'));+ expect(fn).toMatch(/update password_resets r set consumed_at = now\(\)[\s\S]*returning r\.id, r\.user_id/);+ expect(fn).toMatch(/update oauth_refresh_tokens set revoked_at = now\(\) where user_id = \$\{userId\}/);+ });++ it('the model-verified validation reads only platform-signed memos', () => {+ const code = src('api/agents/solana/_handlers.js');+ const reads = [...code.matchAll(/payload->>'subkind' = \$\{SUBKIND_GLB_SCHEMA\}[^`]*/g)].map((m) => m[0]);+ expect(reads.length).toBeGreaterThanOrEqual(2);+ for (const r of reads) expect(r).toMatch(/attester = \$\{validator\}/);+ });++ it('the platform validator address fails closed without a key', async () => {+ const { platformValidatorAddress } = await import('../../api/_lib/solana-validation-attest.js');+ const saved = process.env.ATTEST_AGENT_SECRET_KEY;+ delete process.env.ATTEST_AGENT_SECRET_KEY;+ try {+ expect(platformValidatorAddress()).toBeNull();+ const kp = Keypair.generate();+ process.env.ATTEST_AGENT_SECRET_KEY = JSON.stringify([...kp.secretKey]);+ expect(platformValidatorAddress()).toBe(kp.publicKey.toBase58());+ } finally {+ if (saved === undefined) delete process.env.ATTEST_AGENT_SECRET_KEY;+ else process.env.ATTEST_AGENT_SECRET_KEY = saved;+ }+ });++ it('manifest publish and the strategy-loop money switch check bearer scope', () => {+ expect(src('api/agents/_id/manifest-signed.js')).toMatch(/hasScope\(bearer\.scope, 'agents:write'\)/);+ expect(src('api/_lib/strategy-loop/routes.js')).toMatch(/hasScope\(principal\.scope, 'wallet:write'\)/);+ expect(src('api/agents/[id]/api-service.js')).toMatch(/hasScope\(bearer\.scope, needed\)/);+ expect(src('api/agents/[id]/memory-seed-farcaster.js')).toMatch(/'memory:write'/);+ });+});diff --git a/tests/bearer-spend-scope.test.js b/tests/bearer-spend-scope.test.jsindex d257e4812..eed1fb299 100644--- a/tests/bearer-spend-scope.test.js+++ b/tests/bearer-spend-scope.test.js@@ -86,16 +86,34 @@ describe('every bearer-accepting spend route calls the gate', () => {'api/autopilot/proposals.js','api/autopilot/config.js','api/pump/[action].js',+ 'api/pay/session.js',+ 'api/agents/_id/_sub.js',+ 'api/agents/agent-mirror.js',+ 'api/agents/capabilities.js',+ 'api/swarms/index.js',+ 'api/_lib/labor-auth.js',+ 'api/_lib/vault-auth.js',+ 'api/marketplace/buy-asset.js',+ 'api/tournaments/[id].js',+ 'api/agent-wallet-bridge.js',];for (const rel of ROUTES) {it(rel, () => {const src = readFileSync(path.join(ROOT, rel), 'utf8');- expect(src).toMatch(/import \{ assertBearerMaySpend \} from '[./]*_lib\/spend-scope\.js'/);+ expect(src).toMatch(/import \{ assertBearerMaySpend \} from '[./]*(_lib\/)?spend-scope\.js'/);expect(src.match(/assertBearerMaySpend\(/g)?.length || 0).toBeGreaterThanOrEqual(1);});}+ it('labor, Agora and vault money writes ask authWrite for the spend gate', () => {+ for (const rel of ['api/labor/post.js', 'api/labor/award.js', 'api/labor/policy.js', 'api/agora/act.js',+ 'api/vaults/deposit.js', 'api/vaults/redeem.js', 'api/vaults/trade.js', 'api/vaults/claim-fees.js']) {+ const src = readFileSync(path.join(ROOT, rel), 'utf8');+ expect(src, rel).toMatch(/authWrite\(req, res, \{ spend: true \}\)/);+ }+ });+it('the trade and withdraw executors check scope only once the request is known to spend', () => {const trade = readFileSync(path.join(ROOT, 'api/agents/solana-trade.js'), 'utf8');expect(trade).toMatch(/if \(!parsed\.preview\) assertBearerMaySpend\(auth\.bearer, req\)/);diff --git a/tests/github-memory-seed-endpoint.test.js b/tests/github-memory-seed-endpoint.test.jsindex 500caa876..e6c745974 100644--- a/tests/github-memory-seed-endpoint.test.js+++ b/tests/github-memory-seed-endpoint.test.js@@ -24,6 +24,7 @@ vi.mock('../api/_lib/auth.js', () => ({getSessionUser: (...a) => getSessionUserMock(...a),authenticateBearer: (...a) => authenticateBearerMock(...a),extractBearer: (...a) => extractBearerMock(...a),+ hasScope: (granted, required) => required.split(/\s+/).every((x) => String(granted || '').split(/\s+/).includes(x)),}));const requireCsrfMock = vi.fn();@@ -138,6 +139,21 @@ function connected() {});}+describe('bearer scope on the seeding mutations', () => {+ it('refuses a bearer without memory:write before reading GitHub or touching memories', async () => {+ connected();+ getSessionUserMock.mockResolvedValue(null);+ extractBearerMock.mockReturnValue('sk_live_x');+ authenticateBearerMock.mockResolvedValue({ userId: USER, scope: 'inference', source: 'apikey' });+ const res = mkRes();+ await handler(post({ include_profile: true, repos: [], readmes: [] }), res);+ expect(res.statusCode).toBe(403);+ expect(parse(res).error).toBe('insufficient_scope');+ expect(fetchProfileMock).not.toHaveBeenCalled();+ expect(sqlMock.transaction).not.toHaveBeenCalled();+ });+});+describe('CSRF on the seeding mutations', () => {it('POST is refused when the CSRF gate fails, before GitHub is read', async () => {connected();