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(security): harden auth, wallet policy, SDP, vault, skill sandbox and MCP bridge URL guard with regression tests

nirholas8a56a44abe29
diff --git a/api/_lib/agent-spend-policy.js b/api/_lib/agent-spend-policy.js
index 4ad8f4b07..075a33472 100644
--- a/api/_lib/agent-spend-policy.js
+++ b/api/_lib/agent-spend-policy.js
@@ -17,6 +17,7 @@
// past the daily cap.
import { sql } from './db.js';
+import { runLocked } from './locked-sql.js';
// SOL-outflow action types that draw down the daily cap.
export const SOL_OUTFLOW_TYPES = ['pumpfun.buy', 'pumpfun.launch', 'pumpfun.swap.buy'];
@@ -118,15 +119,13 @@ export async function reserveSpend({ agentId, meta, mint, solAmount, type, paylo
status: 'reserved',
});
- // The advisory xact lock is held for the duration of THIS statement's implicit
- // transaction, serializing concurrent spends per agent. The INSERT…SELECT only
- // materializes a row when the rolling 24h total plus this spend stays within
- // the cap, so the check and the reservation are atomic.
- const rows = await sql`
- WITH locked AS (
- SELECT pg_advisory_xact_lock(hashtextextended(${String(agentId)}, 0))
- ),
- spent AS (
+ // The advisory xact lock is taken in its own statement ahead of the INSERT…SELECT
+ // in one transaction (see locked-sql.js: a lock inside the same statement does
+ // not refresh the snapshot, so the loser would not see the winner's row). The
+ // INSERT…SELECT only materializes a row when the rolling 24h total plus this
+ // spend stays within the cap, so the check and the reservation are atomic.
+ const rows = await runLocked([agentId], sql`
+ WITH spent AS (
SELECT COALESCE(SUM((payload->>'solAmount')::numeric), 0) AS s
FROM agent_actions
WHERE agent_id = ${agentId}
@@ -135,10 +134,10 @@ export async function reserveSpend({ agentId, meta, mint, solAmount, type, paylo
)
INSERT INTO agent_actions (agent_id, type, payload, source_skill)
SELECT ${agentId}, ${type}, ${reserved}::jsonb, ${'pumpfun'}
- FROM spent, locked
+ FROM spent
WHERE spent.s + ${amount}::numeric <= ${policy.daily_sol_cap}::numeric
RETURNING id
- `;
+ `);
if (!rows.length) {
return {
diff --git a/api/_lib/agent-trade-guards.js b/api/_lib/agent-trade-guards.js
index 051096170..5b2b5a381 100644
--- a/api/_lib/agent-trade-guards.js
+++ b/api/_lib/agent-trade-guards.js
@@ -26,6 +26,7 @@
import { PublicKey } from '@solana/web3.js';
import { sql } from './db.js';
+import { runLocked } from './locked-sql.js';
import { solUsdPrice } from './avatar-wallet.js';
import { logAudit } from './audit.js';
// The destination whitelist: cooldown-gated allowlist for every outbound category.
@@ -1318,17 +1319,14 @@ export async function reserveSpendUsd({
return runAnomaly(reservationId, null);
}
- // Atomic cap reserve: the advisory xact lock serializes concurrent spends per
+ // Atomic cap reserve (lock taken as a separate statement, see locked-sql.js): the advisory xact lock serializes concurrent spends per
// agent, and the INSERT…SELECT only materializes the pending row when BOTH the
// rolling 24h wallet total and the rolling 24h total to this counterparty stay
// within their ceilings — check + reserve are one statement, so two requests can
// never both pass on the same stale total. A null ceiling drops out of the
// predicate, so this one statement serves a wallet that sets either cap or both.
- const rows = await sql`
- WITH locked AS (
- SELECT pg_advisory_xact_lock(hashtextextended(${String(agentId)}, 0))
- ),
- spent AS (
+ const rows = await runLocked([agentId], sql`
+ WITH spent AS (
SELECT COALESCE(SUM(usd), 0)::float8 AS s
FROM agent_custody_events
WHERE agent_id = ${agentId}
@@ -1353,11 +1351,11 @@ export async function reserveSpendUsd({
(agent_id, user_id, event_type, category, network, asset, usd, destination, status, meta)
SELECT ${agentId}, ${userId ?? null}, 'spend', ${category}, ${network}, ${asset},
${usdValue}, ${destination ?? null}, 'pending', ${metaJson}::jsonb
- FROM spent, cp, locked
+ FROM spent, cp
WHERE (${lim.daily_usd}::float8 IS NULL OR spent.s + ${usdValue}::float8 <= ${lim.daily_usd}::float8 + 1e-9)
AND (${cpCap}::float8 IS NULL OR cp.s + ${usdValue}::float8 <= ${cpCap}::float8 + 1e-9)
RETURNING id, (SELECT s FROM spent) AS spent_before, (SELECT s FROM cp) AS cp_spent_before
- `;
+ `);
if (!rows.length) {
// Re-read the totals for an accurate error message (outside the lock is fine)
diff --git a/api/_lib/agora-policy.js b/api/_lib/agora-policy.js
index a31006641..3e874d3fd 100644
--- a/api/_lib/agora-policy.js
+++ b/api/_lib/agora-policy.js
@@ -25,6 +25,7 @@
// THREE_TOKEN_DECIMALS (api/_lib/token/config.js).
import { sql } from './db.js';
+import { runLocked } from './locked-sql.js';
import { TOKEN_DECIMALS } from './token/config.js';
const LAMPORTS_PER_SOL = 1_000_000_000n;
@@ -219,11 +220,8 @@ export async function reservePostSpend({ citizenId, cluster, amountAtomic, reque
const amount = BigInt(amountAtomic).toString();
const daily = caps.dailyAtomic.toString();
const mint = caps.rewardMint;
- const rows = await sql`
- with locked as (
- select pg_advisory_xact_lock(hashtextextended(${String(citizenId)}, 0))
- ),
- spent as (
+ const rows = await runLocked([citizenId], sql`
+ with spent as (
select coalesce(sum(amount_atomic), 0) as s
from agora_activity
where citizen_id = ${citizenId}
@@ -241,10 +239,10 @@ export async function reservePostSpend({ citizenId, cluster, amountAtomic, reque
)
insert into agora_spend_reservations (citizen_id, amount_atomic, reward_mint)
select ${citizenId}, ${amount}::numeric, ${mint}
- from spent, held, locked
+ from spent, held
where spent.s + held.s + ${amount}::numeric <= ${daily}::numeric
returning id, ((select s from spent) + (select s from held))::text as committed_before
- `;
+ `);
if (!rows.length) {
return {
diff --git a/api/_lib/auth.js b/api/_lib/auth.js
index b527b0c75..7f1252be5 100644
--- a/api/_lib/auth.js
+++ b/api/_lib/auth.js
@@ -334,7 +334,9 @@ export async function authenticateBearer(token, { audience, ip } = {}) {
if (row === undefined) {
const rows = await sql`
select id, user_id, scope, preset, expires_at, revoked_at, ip_allowlist, overlap_until
- from api_keys where token_hash = ${hash} limit 1
+ from api_keys where token_hash = ${hash}
+ and exists (select 1 from users u where u.id = api_keys.user_id and u.deleted_at is null)
+ limit 1
`;
row = rows[0] ?? null;
rememberKeyRow(hash, row);
diff --git a/api/_lib/locked-sql.js b/api/_lib/locked-sql.js
new file mode 100644
index 000000000..c7df8b251
--- /dev/null
+++ b/api/_lib/locked-sql.js
@@ -0,0 +1,24 @@
+// Run one statement under per-key Postgres advisory locks, with the lock taken
+// in its OWN statement ahead of it inside a single transaction.
+//
+// Why not a `WITH locked AS (SELECT pg_advisory_xact_lock(...))` CTE inside the
+// statement itself: under READ COMMITTED a statement's snapshot is fixed when it
+// STARTS. A request that blocks on the lock mid-statement wakes up only after
+// the holder committed, but still reads the pre-commit snapshot, so it never
+// sees the holder's reservation row and a "sum of the last 24h + this spend <=
+// cap" check passes twice. Two statements in one transaction fix it: the second
+// statement takes a fresh snapshot after the lock is held.
+//
+// Locks are taken in sorted order so two callers needing the same pair cannot
+// deadlock. `query` must be an un-awaited sql`` fragment. Resolves to the rows
+// of `query`.
+import { sql } from './db.js';
+
+export async function runLocked(lockKeys, query) {
+ const keys = [...new Set(lockKeys.map(String))].sort();
+ const results = await sql.transaction([
+ ...keys.map((k) => sql`select pg_advisory_xact_lock(hashtextextended(${k}, 0))`),
+ query,
+ ]);
+ return results[results.length - 1];
+}
diff --git a/api/_lib/sdp.js b/api/_lib/sdp.js
index 410917093..ae909b317 100644
--- a/api/_lib/sdp.js
+++ b/api/_lib/sdp.js
@@ -55,6 +55,12 @@ export function sdpBase() {
export function isSdpAllowedPath(path) {
const clean = String(path || '').replace(/^\/+/, '');
if (!clean || clean.includes('..')) return false;
+ // The path is concatenated into the upstream URL, and the URL parser there
+ // collapses "%2e%2e" / ".%2E" / tab-split dots into real traversal segments
+ // and treats "?", "#" and "\\" as structure. The route surface is plain
+ // lowercase path segments, so refuse everything else before it gets that far.
+ if (!/^[A-Za-z0-9_\-.]+(\/[A-Za-z0-9_\-.]+)*\/?$/.test(clean)) return false;
+ if (clean.split('/').some((seg) => seg === '.')) return false;
if (SDP_TOP_LEVEL.includes(clean)) return true;
if (clean === 'health/ready') return true;
if (clean.startsWith('v1/')) {
diff --git a/api/_lib/vault-store.js b/api/_lib/vault-store.js
index dfc2a987f..276eb2f46 100644
--- a/api/_lib/vault-store.js
+++ b/api/_lib/vault-store.js
@@ -9,6 +9,7 @@
// vault-transfer.js. This module is purely the system of record.
import { sql } from './db.js';
+import { runLocked } from './locked-sql.js';
// Columns safe to expose publicly (NEVER the encrypted_secret). Spread into a
// SELECT to guarantee the vault keypair ciphertext can't leak through a read.
@@ -239,11 +240,8 @@ export async function claimVaultBuyBudget({
// A non-positive budget means "no ceiling configured" (same reading as
// tradeExceedsDailyBudget), so the claim only has to clear idempotency.
const budget = String(dailyBudgetAtomics ?? 0);
- const rows = await sql`
- WITH locked AS (
- SELECT pg_advisory_xact_lock(hashtextextended(${String(vaultId)}, 0))
- ),
- spent AS (
+ const rows = await runLocked([vaultId], sql`
+ WITH spent AS (
SELECT COALESCE(SUM((meta->>'usdc_in')::numeric), 0) AS s
FROM vault_events
WHERE vault_id = ${vaultId} AND type = 'trade' AND status IN ('ok', 'pending')
@@ -254,12 +252,12 @@ export async function claimVaultBuyBudget({
(vault_id, type, user_id, atomics_delta, status, reason, idempotency_key, meta)
SELECT ${vaultId}, 'trade', ${userId ?? null}, ${`-${amount}`}, 'pending', ${reason ?? null},
${idempotencyKey ?? null}, ${JSON.stringify(meta ?? {})}::jsonb
- FROM spent, locked
+ FROM spent
WHERE ${budget}::numeric <= 0
OR spent.s + ${amount}::numeric <= ${budget}::numeric
ON CONFLICT (vault_id, idempotency_key) WHERE idempotency_key IS NOT NULL DO NOTHING
RETURNING id, (SELECT s FROM spent)::text AS spent_before
- `;
+ `);
if (rows.length) {
return { ok: true, claimId: Number(rows[0].id), spentBefore: rows[0].spent_before ?? '0' };
}
diff --git a/api/_lib/wallet-capabilities.js b/api/_lib/wallet-capabilities.js
index cdafef7a9..23fdf02a7 100644
--- a/api/_lib/wallet-capabilities.js
+++ b/api/_lib/wallet-capabilities.js
@@ -34,6 +34,7 @@
import { createHmac, timingSafeEqual, randomUUID } from 'node:crypto';
import { sql } from './db.js';
+import { runLocked } from './locked-sql.js';
import { env } from './env.js';
// Circular by design: the shared guards import the capability gate from here, and
// we import the custody-ledger writer + the SpendLimitError class from there. Both
@@ -596,14 +597,8 @@ export async function reserveCapabilitySpend({
// under the lock, so a revoke/expiry that landed first is always honored.
const aggCap = cap.aggregate_usd == null ? null : Number(cap.aggregate_usd);
const dCap = dailyUsd == null ? null : Number(dailyUsd);
- const rows = await sql`
- WITH lock_cap AS (
- SELECT pg_advisory_xact_lock(hashtextextended(${'cap:' + String(capabilityId)}, 0))
- ),
- lock_agent AS (
- SELECT pg_advisory_xact_lock(hashtextextended(${String(agentId)}, 0))
- ),
- live AS (
+ const rows = await runLocked(['cap:' + String(capabilityId), agentId], sql`
+ WITH live AS (
SELECT id FROM agent_wallet_capabilities
WHERE id = ${capabilityId} AND revoked_at IS NULL AND expires_at > now()
),
@@ -632,13 +627,13 @@ export async function reserveCapabilitySpend({
(agent_id, user_id, event_type, category, network, asset, usd, destination, status, capability_id, meta)
SELECT ${agentId}, ${userId ?? null}, 'spend', ${action}, ${network}, ${asset},
${usdValue}, ${destination ?? null}, 'pending', ${capabilityId}, ${metaJson}::jsonb
- FROM cap_spent, day_spent, cp_spent, lock_cap, lock_agent
+ FROM cap_spent, day_spent, cp_spent
WHERE (SELECT count(*) FROM live) = 1
AND (${aggCap}::float8 IS NULL OR cap_spent.s + ${usdValue}::float8 <= ${aggCap}::float8 + 1e-9)
AND (${dCap}::float8 IS NULL OR day_spent.s + ${usdValue}::float8 <= ${dCap}::float8 + 1e-9)
AND (${cpCap}::float8 IS NULL OR cp_spent.s + ${usdValue}::float8 <= ${cpCap}::float8 + 1e-9)
RETURNING id, (SELECT s FROM cap_spent) AS cap_before, (SELECT s FROM day_spent) AS day_before
- `;
+ `);
if (!rows.length) {
// Distinguish WHY nothing inserted so the boundary message is honest: a
@@ -675,11 +670,8 @@ export async function reserveCapabilitySpend({
// on the capability being live at insert time (so a revoke is never raced) and
// tagged with capability_id for the audit trail + leash UI.
async function reserveUnmetered({ cap, agentId, userId, action, network, asset, destination, usd, metaJson }) {
- const rows = await sql`
- WITH lock_cap AS (
- SELECT pg_advisory_xact_lock(hashtextextended(${'cap:' + String(cap.id)}, 0))
- ),
- live AS (
+ const rows = await runLocked(['cap:' + String(cap.id)], sql`
+ WITH live AS (
SELECT id FROM agent_wallet_capabilities
WHERE id = ${cap.id} AND revoked_at IS NULL AND expires_at > now()
)
@@ -687,10 +679,10 @@ async function reserveUnmetered({ cap, agentId, userId, action, network, asset,
(agent_id, user_id, event_type, category, network, asset, usd, destination, status, capability_id, meta)
SELECT ${agentId}, ${userId ?? null}, 'spend', ${action}, ${network}, ${asset},
${usd}, ${destination ?? null}, 'pending', ${cap.id}, ${metaJson}::jsonb
- FROM live, lock_cap
+ FROM live
WHERE (SELECT count(*) FROM live) = 1
RETURNING id
- `;
+ `);
if (!rows.length) return null;
void sql`UPDATE agent_wallet_capabilities SET use_count = use_count + 1, last_used_at = now(), updated_at = now() WHERE id = ${cap.id}`
.catch(() => {});
diff --git a/api/_lib/wallet-intents.js b/api/_lib/wallet-intents.js
index d240212ce..38e412612 100644
--- a/api/_lib/wallet-intents.js
+++ b/api/_lib/wallet-intents.js
@@ -24,6 +24,7 @@
import { PublicKey } from '@solana/web3.js';
import { sql } from './db.js';
+import { runLocked } from './locked-sql.js';
import { confirmOrThrow } from './solana/confirm.js';
import { solUsdPrice, sendSol, explorerTxUrl } from './avatar-wallet.js';
import { solanaConnection } from './agent-pumpfun.js';
@@ -884,11 +885,8 @@ async function gatedSpend({ ctx, intent, discriminator, category, usd, lamports,
const intentDailyUsd = lim.daily_usd ?? null;
const intentTotalUsd = lim.total_usd ?? null;
const sinceIso = new Date(now.getTime() - 24 * 3600 * 1000).toISOString();
- const claim = await sql`
- WITH locked AS (
- SELECT pg_advisory_xact_lock(hashtextextended(${String(agentId)}, 0))
- ),
- wallet_day AS (
+ const claim = await runLocked([agentId], sql`
+ WITH wallet_day AS (
SELECT COALESCE(SUM(usd), 0)::float8 AS s
FROM agent_custody_events
WHERE agent_id = ${agentId} AND network = ${network} AND event_type = 'spend'
@@ -915,13 +913,13 @@ async function gatedSpend({ ctx, intent, discriminator, category, usd, lamports,
SELECT ${agentId}, ${userId ?? ownerId ?? null}, 'spend', ${category}, ${network}, 'SOL',
${lamports != null ? String(lamports) : null}, ${usd ?? null}, 'pending', ${idemKey},
${JSON.stringify({ ...rowMeta, intent_id: intent.id, intent_title: intent.title, trigger: intent.trigger?.type, action: intent.action?.type, ...(ctx.approval ? { approval_id: ctx.approval.id } : {}) })}::jsonb
- FROM wallet_day, rule_day, rule_life, locked
+ FROM wallet_day, rule_day, rule_life
WHERE NOT EXISTS (SELECT 1 FROM agent_custody_events WHERE agent_id = ${agentId} AND idempotency_key = ${idemKey})
AND (${dailyUsd}::float8 IS NULL OR wallet_day.s + ${usd}::float8 <= ${dailyUsd}::float8 + 1e-9)
AND (${intentDailyUsd}::float8 IS NULL OR rule_day.s + ${usd}::float8 <= ${intentDailyUsd}::float8 + 1e-9)
AND (${intentTotalUsd}::float8 IS NULL OR rule_life.s + ${usd}::float8 <= ${intentTotalUsd}::float8 + 1e-9)
RETURNING id
- `;
+ `);
if (!claim.length) return await claimRejection({ agentId, intentId: intent.id, idemKey, usd, network, dailyUsd, intentDailyUsd, intentTotalUsd, sinceIso });
const eventId = claim[0].id;
diff --git a/api/agent/send-sol.js b/api/agent/send-sol.js
index ae4998aaf..c41c5dc4d 100644
--- a/api/agent/send-sol.js
+++ b/api/agent/send-sol.js
@@ -12,6 +12,7 @@
// Guardrails: per-call USD cap (AVATAR_MAX_SEND_USD), pubkey validation,
// IP rate-limit, optional shared-secret header (AVATAR_DEMO_TOKEN).
+import { createHash, timingSafeEqual } from 'node:crypto';
import { z } from 'zod';
import { cors, json, method, readJson, wrap, error, rateLimited } from '../_lib/http.js';
import { parse } from '../_lib/validate.js';
@@ -63,7 +64,10 @@ export default wrap(async (req, res) => {
// Optional shared-secret gate. When set, the widget must echo it.
if (cfg.demoToken) {
const provided = req.headers['x-avatar-token'];
- if (provided !== cfg.demoToken) {
+ // Constant-time compare over fixed-length digests so the shared secret
+ // cannot be recovered byte by byte from response timing.
+ const digest = (v) => createHash('sha256').update(String(v ?? '')).digest();
+ if (typeof provided !== 'string' || !timingSafeEqual(digest(provided), digest(cfg.demoToken))) {
return error(res, 401, 'unauthorized', 'missing or invalid x-avatar-token');
}
}
diff --git a/api/auth/[action].js b/api/auth/[action].js
index 0330cac4b..cb9be619e 100644
--- a/api/auth/[action].js
+++ b/api/auth/[action].js
@@ -20,6 +20,7 @@ import { referralCodeCandidates, normalizeReferralCode } from '../_lib/referrals
import { seedDefaultAgent } from '../_lib/seed-default-agent.js';
import { recordEvent } from '../_lib/usage.js';
import { logAudit } from '../_lib/audit.js';
+import { invalidateApiKey } from '../_lib/api-key-cache.js';
import { tosAcceptanceFromBody, recordTosAcceptance } from '../_lib/legal.js';
import { revokeAllMemberships } from '../_lib/home/members.js';
import { z } from 'zod';
@@ -294,7 +295,18 @@ async function handleDeleteAccount(req, res) {
// wallet/SAML paths key their `account_deleted` answer off finding this row.
await sql`update users set deleted_at = now(), username = null, updated_at = now() where id = ${user.id} and deleted_at is null`;
await sql`update sessions set revoked_at = now() where user_id = ${user.id} and revoked_at is null`;
+ // Access tokens already in flight are stateless JWTs: stamp a cutoff for every
+ // client this account ever granted so authenticateBearer rejects them now.
+ await sql`
+ insert into oauth_client_revocations (user_id, client_id, revoked_at)
+ select distinct user_id, client_id, now() from oauth_refresh_tokens where user_id = ${user.id}
+ on conflict (user_id, client_id) do update set revoked_at = excluded.revoked_at
+ `;
await sql`update oauth_refresh_tokens set revoked_at = now() where user_id = ${user.id} and revoked_at is null`;
+ // API keys are bearer credentials that outlive a session: retire them too and
+ // evict them from every instance's key cache so none keeps answering.
+ const keys = await sql`update api_keys set revoked_at = now() where user_id = ${user.id} and revoked_at is null returning id`;
+ await Promise.all(keys.map((k) => invalidateApiKey(k.id)));
// Household membership outlives a session, so revoking sessions is not enough
// to deprovision somebody: an account with a `guest` row in a house still has
diff --git a/api/permissions/[action].js b/api/permissions/[action].js
index 5bdbf3442..69ff43459 100644
--- a/api/permissions/[action].js
+++ b/api/permissions/[action].js
@@ -18,6 +18,7 @@ import { ethers, Wallet, Contract, Interface, isAddress } from 'ethers';
import { evmFallbackProvider } from '../_lib/evm/rpc.js';
import { sql } from '../_lib/db.js';
+import { runLocked } from '../_lib/locked-sql.js';
import { getSessionUser, authenticateBearer, extractBearer, hasScope } from '../_lib/auth.js';
import { cors, json, method, readJson, wrap, error, rateLimited, reportServerError } from '../_lib/http.js';
import { requireCsrf } from '../_lib/csrf.js';
@@ -851,11 +852,8 @@ async function handleRedeem(req, res) {
// hash after submit, or deleted if the submit never lands. 'failed' rows are
// excluded from the period sum so a released reservation frees its budget.
const reserveMeta = JSON.stringify({ delegation_id: id, chain_id: chainId, amount: requestAmount.toString() });
- const reserveRows = await sql`
- WITH locked AS (
- SELECT pg_advisory_xact_lock(hashtextextended(${String(id)}, 0))
- ),
- spent AS (
+ const reserveRows = await runLocked([id], sql`
+ WITH spent AS (
SELECT trunc(COALESCE(SUM((meta->>'amount')::numeric), 0)) AS s
FROM usage_events
WHERE kind = 'permissions.redeem'
@@ -866,10 +864,10 @@ async function handleRedeem(req, res) {
INSERT INTO usage_events (user_id, api_key_id, agent_id, kind, status, meta)
SELECT ${bearer.userId}, ${bearer.apiKeyId ?? null}, ${row.agent_id},
'permissions.redeem', 'pending', ${reserveMeta}::jsonb
- FROM spent, locked
+ FROM spent
WHERE spent.s + ${requestAmount.toString()}::numeric <= ${maxAmount.toString()}::numeric
RETURNING id, (SELECT trunc(s)::text FROM spent) AS spent_before
- `;
+ `);
if (!reserveRows.length) {
// Re-read for an accurate error body (outside the lock is fine).
const [h] = await sql`
diff --git a/api/x402/rate-limit-probe.js b/api/x402/rate-limit-probe.js
index 11792c290..8098b5bed 100644
--- a/api/x402/rate-limit-probe.js
+++ b/api/x402/rate-limit-probe.js
@@ -124,8 +124,20 @@ function dailySpendKey() {
// that answer a 402 challenge, so this costs the product nothing.
const PROBEABLE_PREFIXES = ['/api/x402', '/api/mcp', '/api/ibm-mcp'];
+// The path half may only hold unreserved characters: the WHATWG URL parser that
+// fetch() uses collapses "%2e%2e", ".%2E" and tab-split ".<TAB>." into real ".."
+// segments, so a substring check for ".." on the raw string is not enough.
+const SAFE_ENDPOINT = /^\/api\/[A-Za-z0-9._~*\/-]*(\?[A-Za-z0-9._~=&%-]*)?$/;
+
function isProbeableEndpoint(endpoint) {
- if (endpoint.includes('..')) return false;
+ if (!SAFE_ENDPOINT.test(endpoint) || endpoint.includes('..')) return false;
+ let resolved;
+ try {
+ resolved = new URL(endpoint, 'http://probe.invalid');
+ } catch {
+ return false;
+ }
+ if (resolved.pathname !== endpoint.split('?')[0]) return false;
return PROBEABLE_PREFIXES.some(
(prefix) =>
endpoint === prefix ||
diff --git a/docs/security.md b/docs/security.md
index 90c0a3150..899c51c75 100644
--- a/docs/security.md
+++ b/docs/security.md
@@ -219,6 +219,23 @@ Post-registration takedowns operate at the gateway and discovery layer: the on-c
---
+## Dependency advisories (2026-10-12 audit)
+
+`npm audit fix` (no `--force`) was applied on 2026-10-12. It cleared the one critical advisory (`handlebars`, reachable only through dev and build tooling) and moved `npm audit --omit=dev` from 132 to 117 findings: 0 critical, 70 high, 22 moderate, 25 low. The remaining findings have no fix that stays inside the current semver ranges; `npm audit fix --force` would downgrade or replace direct dependencies (`@pump-fun/pump-sdk`, `@bonfida/spl-name-service`, `agent0-sdk`, `@solana/pay`) and is deliberately not run.
+
+High advisories left open, with reachability:
+
+| Package | Advisory | Pulled in by | Reachable from server code |
+| --- | --- | --- | --- |
+| `bigint-buffer` | `toBigIntLE()` buffer overflow | `@solana/spl-token` via `@solana/buffer-layout-utils` | Yes, in-process Solana token decoding. Inputs are RPC account data, not user-supplied buffers sized by the caller. Fix needs an upstream `spl-token` major. |
+| `toml` | uncontrolled recursion, prototype pollution | `@coral-xyz/anchor` (Anchor IDL tooling) | Parsing is of `Anchor.toml`-style config at tooling time. No server handler parses caller-supplied TOML. |
+| `@libp2p/kad-dht`, `@libp2p/peer-store`, `node-forge` | DHT disk exhaustion, PeerRecord spoofing, RSA PKCS#1 v1.5 | `helia` via `agent0-sdk` | `api/agents/8004/*` imports only the constants `DEFAULT_SUBGRAPH_URLS` and `DEFAULT_REGISTRIES` from `agent0-sdk`. No libp2p node is started, so the DHT and peer-store code paths do not run. |
+| `adm-zip`, `braces` | ZIP memory allocation, glob stack exhaustion | `hardhat` via `@ethereum-attestation-service/eas-sdk` | Contract-toolchain code. Not imported by `api/` or `server/`. |
+| `lodash.set` | prototype pollution | `@bnb-chain/greenfield-js-sdk` | BNB Greenfield client paths only. Callers pass fixed object paths, never user-supplied keys. |
+| `nanoid` < 3.3.8 / 2.x | predictable output for non-integer sizes | `@colyseus/core` (multiplayer worker) | Colyseus calls it with its own integer sizes. `api/` uses the patched root `nanoid@3`. |
+
+Rules for this list: re-run `npm audit --omit=dev` after each dependency bump, move a row out of this table when a non-breaking fix lands, and never import one of these packages into a request handler that parses untrusted input without first checking the advisory.
+
## Skill security
### Trust modes
diff --git a/mcp-bridge/src/url-guard.js b/mcp-bridge/src/url-guard.js
index 8a27a8f5c..ca113fda2 100644
--- a/mcp-bridge/src/url-guard.js
+++ b/mcp-bridge/src/url-guard.js
@@ -79,7 +79,11 @@ function isPrivateIPv4(ip) {
inV4Cidr(n, '169.254.0.0', 16) || // link-local incl. 169.254.169.254 metadata
inV4Cidr(n, '172.16.0.0', 12) || // RFC1918
inV4Cidr(n, '192.168.0.0', 16) || // RFC1918
- inV4Cidr(n, '100.64.0.0', 10) // CGNAT (RFC6598)
+ inV4Cidr(n, '100.64.0.0', 10) || // CGNAT (RFC6598)
+ inV4Cidr(n, '192.0.0.0', 24) || // IETF protocol assignments
+ inV4Cidr(n, '198.18.0.0', 15) || // benchmarking (RFC2544)
+ inV4Cidr(n, '224.0.0.0', 4) || // multicast
+ inV4Cidr(n, '240.0.0.0', 4) // reserved + broadcast
);
}
@@ -147,6 +151,18 @@ function isPrivateIPv6(addr) {
return isPrivateIPv4(v4);
}
+ // ff00::/8 multicast.
+ if ((h[0] & 0xff00) === 0xff00) return true;
+
+ // Tunnelled IPv4: NAT64 (64:ff9b::/96) and 6to4 (2002::/16) carry an IPv4
+ // address that a translator or relay will happily dial, so a private v4 in
+ // either wrapper is as unsafe as the bare address.
+ const embeds = (a, b) => `${a >>> 8}.${a & 0xff}.${b >>> 8}.${b & 0xff}`;
+ if (h[0] === 0x64 && h[1] === 0xff9b && h.slice(2, 6).every((x) => x === 0)) {
+ return isPrivateIPv4(embeds(h[6], h[7]));
+ }
+ if (h[0] === 0x2002) return isPrivateIPv4(embeds(h[1], h[2]));
+
return false;
}
diff --git a/scripts/agent-x402-demo/pay.mjs b/scripts/agent-x402-demo/pay.mjs
index 66480f9e8..f306d79b8 100644
--- a/scripts/agent-x402-demo/pay.mjs
+++ b/scripts/agent-x402-demo/pay.mjs
@@ -61,7 +61,7 @@ function loadOrCreateWallet() {
return Keypair.fromSecretKey(bs58decode(raw.secret));
}
const kp = Keypair.generate();
- writeFileSync(WALLET_FILE, JSON.stringify({ pubkey: kp.publicKey.toBase58(), secret: bs58encode(kp.secretKey) }, null, 2) + '\n');
+ writeFileSync(WALLET_FILE, JSON.stringify({ pubkey: kp.publicKey.toBase58(), secret: bs58encode(kp.secretKey) }, null, 2) + '\n', { mode: 0o600 });
return kp;
}
diff --git a/scripts/lib/pump-launch-core.mjs b/scripts/lib/pump-launch-core.mjs
index ec0e1b1a4..2572ecac7 100644
--- a/scripts/lib/pump-launch-core.mjs
+++ b/scripts/lib/pump-launch-core.mjs
@@ -297,7 +297,7 @@ export function ensureMaster(cfg) {
mkdirSync(cfg.walletDir, { recursive: true });
if (existsSync(cfg.masterPath)) return keypairFromFile(cfg.masterPath);
const master = Keypair.generate();
- writeFileSync(cfg.masterPath, JSON.stringify(Array.from(master.secretKey)));
+ writeFileSync(cfg.masterPath, JSON.stringify(Array.from(master.secretKey)), { mode: 0o600 });
return master;
}
export function masterPubkey(cfg) {
@@ -340,7 +340,7 @@ export function generate(cfg, repos) {
usedSymbols.add(symbol);
} else {
kp = Keypair.generate();
- writeFileSync(walletFile, JSON.stringify(Array.from(kp.secretKey)));
+ writeFileSync(walletFile, JSON.stringify(Array.from(kp.secretKey)), { mode: 0o600 });
symbol = r.symbol || makeSymbol(repoName, usedSymbols);
}
const name = (r.coinName || repoName).slice(0, 32);
diff --git a/src/skills/index.js b/src/skills/index.js
index 10fed182c..491ff3bda 100644
--- a/src/skills/index.js
+++ b/src/skills/index.js
@@ -99,6 +99,8 @@ export class SkillRegistry {
trust = 'owned-only',
ownerAddress,
mainThreadOrigins,
+ trustedAuthors = [],
+ trustedOrigins = [],
} = {}) {
this.fetchFn = fetchFn;
this.trust = trust;
@@ -108,6 +110,10 @@ export class SkillRegistry {
.map(originOf)
.filter(Boolean),
);
+ // `whitelist` trust: a bundle installs only when its manifest author or its
+ // serving origin is listed here. Empty lists admit nothing.
+ this.trustedAuthors = new Set(trustedAuthors.map((a) => String(a).toLowerCase()));
+ this.trustedOrigins = new Set(trustedOrigins.map(originOf).filter(Boolean));
this.skills = new Map();
}
@@ -135,7 +141,7 @@ export class SkillRegistry {
if (this.skills.has(uri)) return this.skills.get(uri);
const manifest = await this._fetchJSON(`${uri}manifest.json`);
- this._enforceTrust(manifest);
+ this._enforceTrust(manifest, uri);
const isTrusted = this.mayRunOnMainThread(manifest, uri);
if (manifest.sandboxPolicy === 'trusted-main-thread' && !isTrusted) {
@@ -260,7 +266,7 @@ export class SkillRegistry {
return res.text();
}
- _enforceTrust(manifest) {
+ _enforceTrust(manifest, uri = '') {
if (this.trust === 'any') return;
if (this.trust === 'owned-only') {
const author = (manifest.author || '').toLowerCase();
@@ -271,7 +277,16 @@ export class SkillRegistry {
}
}
if (this.trust === 'whitelist') {
- // Whitelist check would consult a configured allowlist; left as hook.
+ const author = String(manifest.author || '').toLowerCase();
+ const origin = originOf(uri);
+ const allowed =
+ (author && this.trustedAuthors.has(author)) ||
+ (origin && this.trustedOrigins.has(origin));
+ if (!allowed) {
+ throw new Error(
+ `Skill "${manifest.name}" is not on the whitelist (author ${author || 'unknown'}, origin ${origin || 'unknown'})`,
+ );
+ }
}
}
}
diff --git a/src/skills/sandbox-worker.js b/src/skills/sandbox-worker.js
index 7cb125604..a71ae3f42 100644
--- a/src/skills/sandbox-worker.js
+++ b/src/skills/sandbox-worker.js
@@ -1,6 +1,68 @@
// Sandbox worker — executes skill handlers in an isolated Web Worker scope.
// No DOM, no window, no document. Only ctx.* and native worker APIs.
+// ── Ambient authority lockdown ────────────────────────────────────────────────
+// The worker is a blob: worker, so it inherits the embedding page's origin. Left
+// alone, an untrusted handler could `fetch('/api/...')` and ride the user's
+// session cookie, read the origin's IndexedDB, or spawn a nested Worker that
+// starts with fresh, unrestricted globals. Strip those capabilities before any
+// skill code is imported. Network access stays (ctx.fetch / ctx.loadJSON), but
+// credential-less: cookies and HTTP auth are never attached.
+const DENIED_GLOBALS = [
+ 'XMLHttpRequest',
+ 'WebSocket',
+ 'WebTransport',
+ 'EventSource',
+ 'importScripts',
+ 'Worker',
+ 'SharedWorker',
+ 'indexedDB',
+ 'IDBFactory',
+ 'caches',
+ 'CacheStorage',
+ 'BroadcastChannel',
+ 'localStorage',
+ 'sessionStorage',
+ 'FileSystemDirectoryHandle',
+];
+
+function _lockdown(scope) {
+ const rawFetch = typeof scope.fetch === 'function' ? scope.fetch.bind(scope) : null;
+ const chain = [];
+ for (let o = scope; o && o !== Object.prototype; o = Object.getPrototypeOf(o)) chain.push(o);
+ const strip = (name, replacement) => {
+ for (const o of chain) {
+ if (!Object.prototype.hasOwnProperty.call(o, name)) continue;
+ try {
+ delete o[name];
+ } catch {}
+ if (Object.prototype.hasOwnProperty.call(o, name)) {
+ try {
+ Object.defineProperty(o, name, { value: undefined, configurable: false, writable: false });
+ } catch {}
+ }
+ }
+ if (replacement) {
+ Object.defineProperty(scope, name, {
+ value: replacement,
+ configurable: false,
+ writable: false,
+ enumerable: true,
+ });
+ }
+ };
+ for (const name of DENIED_GLOBALS) strip(name);
+ if (rawFetch) {
+ const credentialless = (input, init) => {
+ const opts = { ...(init || {}), credentials: 'omit' };
+ const req = typeof Request === 'function' && input instanceof Request ? new Request(input, opts) : null;
+ return req ? rawFetch(req) : rawFetch(input, opts);
+ };
+ strip('fetch', credentialless);
+ }
+}
+_lockdown(self);
+
/** @type {Map<string, object>} skillURI → module exports */
const _skillHandlers = new Map();
diff --git a/tests/advisory-lock-snapshot.test.js b/tests/advisory-lock-snapshot.test.js
new file mode 100644
index 000000000..1474206db
--- /dev/null
+++ b/tests/advisory-lock-snapshot.test.js
@@ -0,0 +1,78 @@
+// Regression: a rolling-cap reservation must take its advisory lock in a
+// SEPARATE statement ahead of the INSERT...SELECT that sums the window.
+//
+// Under READ COMMITTED a statement's snapshot is fixed when it starts, so a
+// `WITH locked AS (SELECT pg_advisory_xact_lock(..)) ... INSERT ... SELECT sum()`
+// single statement lets a request that waited on the lock read the pre-commit
+// snapshot and miss the winner's reservation: two concurrent spends both pass
+// the daily cap. Fixed by api/_lib/locked-sql.js (lock statement, then the
+// reservation, inside one transaction).
+
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { readFileSync, readdirSync, statSync } from 'node:fs';
+import { join } from 'node:path';
+
+const state = { txs: [], singles: [] };
+vi.mock('../api/_lib/db.js', () => {
+ const sql = vi.fn((strings, ...values) => {
+ const text = strings.join('?');
+ state.singles.push(text);
+ return { __q: text, values };
+ });
+ sql.transaction = vi.fn(async (queries) => {
+ state.txs.push(queries.map((q) => q.__q));
+ return queries.map((q, i) => (i === queries.length - 1 ? [{ id: 'r1' }] : []));
+ });
+ return { sql, isDbUnavailableError: () => false, isDbCapacityError: () => false };
+});
+
+beforeEach(() => {
+ state.txs = [];
+ state.singles = [];
+});
+
+describe('reserveSpend lock ordering', () => {
+ it('locks in its own statement before the reservation insert, in one transaction', async () => {
+ const { reserveSpend } = await import('../api/_lib/agent-spend-policy.js');
+ const r = await reserveSpend({
+ agentId: 'agent-1',
+ meta: { spend_policy: { daily_sol_cap: 5 } },
+ mint: null,
+ solAmount: 1,
+ type: 'pumpfun.buy',
+ });
+ expect(r.ok).toBe(true);
+ expect(state.txs).toHaveLength(1);
+ const [lock, insert] = state.txs[0];
+ expect(lock).toMatch(/pg_advisory_xact_lock/);
+ expect(lock).not.toMatch(/insert/i);
+ expect(insert).toMatch(/INSERT INTO agent_actions/);
+ expect(insert).not.toMatch(/pg_advisory_xact_lock/);
+ });
+});
+
+function walk(dir, out = []) {
+ for (const name of readdirSync(dir)) {
+ const p = join(dir, name);
+ if (statSync(p).isDirectory()) walk(p, out);
+ else if (p.endsWith('.js')) out.push(p);
+ }
+ return out;
+}
+
+describe('no single statement mixes an advisory lock with a windowed-sum INSERT', () => {
+ it('api/ has none', () => {
+ const offenders = [];
+ for (const file of walk('api')) {
+ const src = readFileSync(file, 'utf8');
+ if (!src.includes('pg_advisory_xact_lock')) continue;
+ for (const m of src.matchAll(/sql`([^`]*)`/g)) {
+ const t = m[1];
+ if (/pg_advisory_xact_lock/.test(t) && /insert\s+into/i.test(t) && /sum\s*\(/i.test(t)) {
+ offenders.push(file);
+ }
+ }
+ }
+ expect(offenders).toEqual([]);
+ });
+});
diff --git a/tests/api-sdp-client.test.js b/tests/api-sdp-client.test.js
index 60f218892..b68f2b1d8 100644
--- a/tests/api-sdp-client.test.js
+++ b/tests/api-sdp-client.test.js
@@ -83,6 +83,22 @@ describe('path allowlist', () => {
}
});
+ it('rejects encoded dot segments and URL-structure characters the upstream URL parser would act on', () => {
+ for (const p of [
+ 'v1/wallets/%2e%2e/%2e%2e/admin',
+ 'v1/wallets/.%2E/admin',
+ 'v1/wallets/%2E./admin',
+ 'v1/wallets/./x',
+ 'v1/wallets/.\t./admin',
+ 'v1/wallets%3fx=1',
+ 'v1/wallets?x=1',
+ 'v1/wallets#x',
+ 'v1/wallets\\..\\admin',
+ ]) {
+ expect(isSdpAllowedPath(p), p).toBe(false);
+ }
+ });
+
it('leading slashes are normalized', () => {
expect(isSdpAllowedPath('/v1/wallets')).toBe(true);
});
diff --git a/tests/auth-deleted-account-credentials.test.js b/tests/auth-deleted-account-credentials.test.js
new file mode 100644
index 000000000..ee7c1c922
--- /dev/null
+++ b/tests/auth-deleted-account-credentials.test.js
@@ -0,0 +1,93 @@
+// A deleted account must not keep a working credential.
+//
+// DELETE /api/auth/me revoked sessions and OAuth refresh tokens but left the
+// account's API keys alive, and authenticateBearer never asked whether the key's
+// owner still exists. A person who deleted their account (or an operator who
+// removed an abusive one) therefore kept a bearer credential that still
+// resolved to the dead user id on every key-authenticated route.
+
+import { createHash } from 'node:crypto';
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+process.env.PUBLIC_APP_ORIGIN = 'https://three.ws';
+process.env.APP_ORIGIN = 'https://three.ws';
+process.env.JWT_SECRET ||= 'vitest-ephemeral-jwt-secret-00000000000000';
+
+const hashOf = (t) => createHash('sha256').update(t).digest('hex');
+const TOKEN = 'sk_live_deletedowner_00000000000000000';
+const KEY_ID = '6f1d2c3b-0000-4000-8000-00000000d311';
+
+let ownerDeleted = false;
+const statements = [];
+
+vi.mock('../api/_lib/db.js', () => {
+ const sql = (strings, ...values) => {
+ const text = (Array.isArray(strings) ? strings.join('?') : String(strings)).replace(/\s+/g, ' ');
+ statements.push(text);
+ if (/from api_keys where token_hash/.test(text)) {
+ if (values.includes(hashOf(TOKEN)) === false) return Promise.resolve([]);
+ // A real database applies the owner-liveness predicate; model it.
+ if (ownerDeleted && /deleted_at is null/.test(text)) return Promise.resolve([]);
+ return Promise.resolve([{ id: KEY_ID, user_id: 'user-1', scope: 'read', preset: null, expires_at: null, revoked_at: null, ip_allowlist: null, overlap_until: null }]);
+ }
+ if (/select username from users/.test(text)) return Promise.resolve([{ username: 'ada' }]);
+ if (/returning id/i.test(text)) return Promise.resolve([{ id: KEY_ID }]);
+ return Promise.resolve([]);
+ };
+ return { sql, isDbUnavailableError: () => false, isDbCapacityError: () => false, isStoragePressured: () => false };
+});
+vi.mock('../api/_lib/redis.js', () => ({ getRedis: () => null }));
+vi.mock('../api/_lib/usage.js', () => ({ recordEvent: vi.fn(), logger: () => ({ info() {}, warn() {}, error() {} }) }));
+vi.mock('../api/_lib/zauth.js', () => ({ instrument: () => {}, drain: async () => {} }));
+vi.mock('../api/_lib/sentry.js', () => ({ captureException: () => {} }));
+vi.mock('../api/_lib/csrf.js', () => ({ requireCsrf: async () => true }));
+vi.mock('../api/_lib/rate-limit.js', () => ({
+ limits: { authIp: async () => ({ success: true }) },
+ clientIp: () => '127.0.0.1',
+}));
+vi.mock('../api/_lib/audit.js', () => ({ logAudit: vi.fn() }));
+vi.mock('../api/_lib/email.js', () => ({ sendPasswordResetEmail: vi.fn(), sendVerificationEmail: vi.fn() }));
+vi.mock('../api/_lib/seed-default-agent.js', () => ({ seedDefaultAgent: vi.fn() }));
+vi.mock('../api/_lib/legal.js', () => ({ tosAcceptanceFromBody: vi.fn(() => null), recordTosAcceptance: vi.fn(), TOS_VERSION: 2 }));
+vi.mock('../api/_lib/home/members.js', () => ({ revokeAllMemberships: async () => ({ removedFrom: [], ownedHomes: [] }) }));
+
+const realAuth = await vi.importActual('../api/_lib/auth.js');
+vi.mock('../api/_lib/auth.js', async () => {
+ const actual = await vi.importActual('../api/_lib/auth.js');
+ return {
+ ...actual,
+ getSessionUser: async () => ({ id: 'user-1', email: '[email protected]' }),
+ sessionCookie: () => '__Host-sid=; Max-Age=0',
+ };
+});
+
+const { authenticateBearer } = realAuth;
+const { resetApiKeyCache } = await import('../api/_lib/api-key-cache.js');
+const { default: handler } = await import('../api/auth/[action].js');
+
+beforeEach(() => {
+ ownerDeleted = false;
+ statements.length = 0;
+ resetApiKeyCache();
+});
+
+describe('credentials of a deleted account', () => {
+ it('authenticateBearer refuses an API key whose owner is deleted', async () => {
+ expect(await authenticateBearer(TOKEN)).toMatchObject({ userId: 'user-1' });
+ resetApiKeyCache();
+ ownerDeleted = true;
+ expect(await authenticateBearer(TOKEN)).toBeNull();
+ });
+
+ it('DELETE /api/auth/me revokes the account API keys', async () => {
+ const res = { statusCode: 200, _h: {}, setHeader(k, v) { this._h[k] = v; }, getHeader(k) { return this._h[k]; }, end(b) { this._b = b; } };
+ await handler({
+ method: 'DELETE', url: '/api/auth/me', query: { action: 'me' },
+ headers: { 'content-type': 'application/json', origin: 'https://three.ws' },
+ socket: { remoteAddress: '127.0.0.1' }, body: JSON.stringify({ confirm: 'delete my account' }),
+ }, res);
+ expect(res.statusCode).toBe(200);
+ expect(statements.some((s) => /update api_keys set revoked_at = now\(\)/.test(s))).toBe(true);
+ expect(statements.some((s) => /insert into oauth_client_revocations/.test(s))).toBe(true);
+ });
+});
diff --git a/tests/launch-mark-enforcement.test.js b/tests/launch-mark-enforcement.test.js
index f56f3ba17..0ba21fa0c 100644
--- a/tests/launch-mark-enforcement.test.js
+++ b/tests/launch-mark-enforcement.test.js
@@ -29,12 +29,17 @@ vi.mock('../api/_lib/auth.js', () => ({
// ── SQL ──────────────────────────────────────────────────────────────────────
const sqlState = { queue: [], calls: [] };
+// Advisory-lock statements (api/_lib/locked-sql.js) answer [] without drawing
+// from the queued results, which stay one-per-business-query.
+const sqlMock = vi.fn(async (strings, ...values) => {
+ if (String(strings?.[0] ?? '').includes('pg_advisory_xact_lock')) return [];
+ sqlState.calls.push({ query: strings.join('?'), values });
+ if (sqlState.queue.length === 0) return [];
+ return sqlState.queue.shift();
+});
+sqlMock.transaction = (queries) => Promise.all(queries);
vi.mock('../api/_lib/db.js', () => ({
- sql: vi.fn(async (strings, ...values) => {
- sqlState.calls.push({ query: strings.join('?'), values });
- if (sqlState.queue.length === 0) return [];
- return sqlState.queue.shift();
- }),
+ sql: sqlMock,
isDbUnavailableError: () => false,
isDbCapacityError: () => false,
}));
diff --git a/tests/mcp-bridge-url-guard-ranges.test.js b/tests/mcp-bridge-url-guard-ranges.test.js
new file mode 100644
index 000000000..7025e3ecd
--- /dev/null
+++ b/tests/mcp-bridge-url-guard-ranges.test.js
@@ -0,0 +1,27 @@
+import { describe, it, expect } from 'vitest';
+import { isBlockedAddress } from '../mcp-bridge/src/url-guard.js';
+
+describe('mcp-bridge url-guard: reserved ranges and tunnelled IPv4', () => {
+ it.each([
+ ['224.0.0.1', 'multicast'],
+ ['239.255.255.250', 'multicast'],
+ ['240.0.0.1', 'reserved class E'],
+ ['255.255.255.255', 'broadcast'],
+ ['198.18.0.1', 'benchmarking'],
+ ['192.0.0.8', 'IETF protocol assignments'],
+ ['64:ff9b::a9fe:a9fe', 'NAT64 wrapping 169.254.169.254'],
+ ['64:ff9b::7f00:1', 'NAT64 wrapping 127.0.0.1'],
+ ['2002:a9fe:a9fe::1', '6to4 wrapping 169.254.169.254'],
+ ['2002:7f00:1::1', '6to4 wrapping 127.0.0.1'],
+ ['ff02::1', 'IPv6 multicast'],
+ ])('blocks %s (%s)', (ip) => {
+ expect(isBlockedAddress(ip)).toBe(true);
+ });
+
+ it.each(['8.8.8.8', '1.1.1.1', '2606:4700:4700::1111', '64:ff9b::0808:0808', '2002:0808:0808::1'])(
+ 'still allows public %s',
+ (ip) => {
+ expect(isBlockedAddress(ip)).toBe(false);
+ },
+ );
+});
diff --git a/tests/permissions-api.test.js b/tests/permissions-api.test.js
index 94c5fbb4d..a99285f4a 100644
--- a/tests/permissions-api.test.js
+++ b/tests/permissions-api.test.js
@@ -20,8 +20,16 @@ import { AbiCoder, Interface } from 'ethers';
import { DELEGATION_MANAGER_ABI } from '../src/erc7710/abi.js';
const sqlMock = vi.fn();
+// The spend reservation takes its advisory lock as its own statement inside
+// sql.transaction (api/_lib/locked-sql.js); the lock statement answers [] without
+// drawing from the queued results, which stay one-per-business-query.
+const sqlTagged = (...a) => {
+ if (String(a[0]?.[0] ?? '').includes('pg_advisory_xact_lock')) return Promise.resolve([]);
+ return sqlMock(...a);
+};
+sqlTagged.transaction = (queries) => Promise.all(queries);
vi.mock('../api/_lib/db.js', () => ({
- sql: (...a) => sqlMock(...a),
+ sql: sqlTagged,
isDbUnavailableError: () => false,
isDbCapacityError: () => false,
}));
diff --git a/tests/skill-sandbox-lockdown.test.js b/tests/skill-sandbox-lockdown.test.js
new file mode 100644
index 000000000..cbf3ddfbd
--- /dev/null
+++ b/tests/skill-sandbox-lockdown.test.js
@@ -0,0 +1,52 @@
+import { describe, it, expect } from 'vitest';
+import { readFileSync } from 'node:fs';
+
+// Evaluate the real worker source against a stand-in worker global whose
+// prototype chain carries the ambient-authority APIs a browser worker has.
+function bootWorker() {
+ const calls = [];
+ const proto = {
+ fetch(input, init) {
+ calls.push({ input, init });
+ return Promise.resolve({ ok: true });
+ },
+ XMLHttpRequest: class {},
+ WebSocket: class {},
+ Worker: class {},
+ SharedWorker: class {},
+ indexedDB: {},
+ caches: {},
+ BroadcastChannel: class {},
+ importScripts() {},
+ };
+ const scope = Object.create(proto);
+ scope.postMessage = () => {};
+ scope.self = scope;
+ // The worker source only touches its global through `self`, so run it with the
+ // stand-in as `self` (a vm context hides the prototype chain being tested).
+ new Function('self', 'Request', readFileSync('src/skills/sandbox-worker.js', 'utf8'))(scope, undefined);
+ return { scope, calls, run: (code) => new Function('self', `return (${code.replace(/;?\s*$/, '')})`)(scope) };
+}
+
+describe('skill sandbox worker lockdown', () => {
+ it('strips ambient network, storage and nested-worker capabilities', () => {
+ const { run } = bootWorker();
+ for (const name of ['XMLHttpRequest', 'WebSocket', 'Worker', 'SharedWorker', 'indexedDB', 'caches', 'BroadcastChannel', 'importScripts']) {
+ expect(run(`typeof self.${name}`), name).toBe('undefined');
+ expect(run(`typeof Object.getPrototypeOf(self).${name}`), `proto ${name}`).toBe('undefined');
+ }
+ });
+
+ it('forces credential-less fetch even when the handler asks for credentials', async () => {
+ const { calls, run } = bootWorker();
+ await run(`self.fetch('/api/wallet', { credentials: 'include', method: 'POST' })`);
+ expect(calls).toHaveLength(1);
+ expect(calls[0].init.credentials).toBe('omit');
+ expect(calls[0].init.method).toBe('POST');
+ });
+
+ it('cannot recover the original fetch from the prototype chain', () => {
+ const { run } = bootWorker();
+ expect(run(`typeof Object.getPrototypeOf(self).fetch`)).toBe('undefined');
+ });
+});
diff --git a/tests/src/agent-skills.test.js b/tests/src/agent-skills.test.js
index f2f4c26bb..4c5a48102 100644
--- a/tests/src/agent-skills.test.js
+++ b/tests/src/agent-skills.test.js
@@ -111,14 +111,30 @@ describe('SkillRegistry.install – trust modes', () => {
expect(skill.name).toBe('test-skill');
});
- it('whitelist mode is a no-op and does not reject skills (enforcement is a hook)', async () => {
+ it('whitelist mode fails closed with no allowlist configured', async () => {
const registry = new SkillRegistry({
fetchFn: makeFetch(fixtureRoutes()),
trust: 'whitelist',
});
- // No whitelist config → currently installs without error
- const skill = await registry.install({ uri: 'https://example.com/skill/' });
- expect(skill.name).toBe('test-skill');
+ await expect(registry.install({ uri: 'https://example.com/skill/' })).rejects.toThrow(
+ /not on the whitelist/,
+ );
+ });
+
+ it('whitelist mode admits a listed author or a listed origin only', async () => {
+ const byAuthor = new SkillRegistry({
+ fetchFn: makeFetch(fixtureRoutes(fixtureManifest({ author: '0xOwner' }))),
+ trust: 'whitelist',
+ trustedAuthors: ['0xowner'],
+ });
+ expect((await byAuthor.install({ uri: 'https://example.com/skill/' })).name).toBe('test-skill');
+ const byOrigin = new SkillRegistry({
+ fetchFn: makeFetch(fixtureRoutes(fixtureManifest({ author: '0xstranger' }))),
+ trust: 'whitelist',
+ trustedOrigins: ['https://example.com'],
+ });
+ expect((await byOrigin.install({ uri: 'https://example.com/skill/' })).name).toBe('test-skill');
+ await expect(byOrigin.install({ uri: 'https://evil.example/skill/' })).rejects.toThrow(/whitelist/);
});
});
diff --git a/tests/x402-rate-limit-probe-target.test.js b/tests/x402-rate-limit-probe-target.test.js
index 3d751eaae..2b7559187 100644
--- a/tests/x402-rate-limit-probe-target.test.js
+++ b/tests/x402-rate-limit-probe-target.test.js
@@ -64,6 +64,23 @@ describe('rate-limit-probe target gating', () => {
expect(fetchSpy).not.toHaveBeenCalled();
});
+ it('rejects encoded and whitespace-obfuscated dot segments that the URL parser collapses', async () => {
+ for (const endpoint of [
+ '/api/x402/%2e%2e/creations',
+ '/api/x402/.%2E/creations',
+ '/api/x402/%2E./creations',
+ '/api/x402/.\t./creations',
+ '/api/x402/%2e%2e%2fcreations',
+ '/api/x402/foo%00',
+ ]) {
+ await expect(call({ endpoint }), endpoint).rejects.toMatchObject({
+ status: 400,
+ code: 'endpoint_not_metered',
+ });
+ }
+ expect(fetchSpy).not.toHaveBeenCalled();
+ });
+
it('rejects a prefix look-alike', async () => {
await expect(call({ endpoint: '/api/x402evil' })).rejects.toMatchObject({
status: 400,