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 the desktop runtime, home bridge, multiplayer rooms, x402 client parsing, crawler guard and server routing

nirholas0611502d9985
diff --git a/apps/desktop/src/runtime/feed.js b/apps/desktop/src/runtime/feed.js
index 5c3874a0a..bea8cb0e2 100644
--- a/apps/desktop/src/runtime/feed.js
+++ b/apps/desktop/src/runtime/feed.js
@@ -44,12 +44,28 @@ async function getJson(fetchImpl, url, ms = 8000) {
}
}
+/**
+ * Token symbols and names are attacker-chosen on-chain text. Strip control and
+ * bidi characters, collapse whitespace and cap the length so they cannot forge
+ * extra lines or rows in the approval dialog.
+ */
+export function cleanTokenLabel(v, max = 16) {
+ if (v == null) return null;
+ const out = String(v)
+ .replace(/[\u0000-\u001f\u007f-\u009f\u200b-\u200f\u202a-\u202e\u2066-\u2069\ufeff]/g, ' ')
+ .replace(/\s+/g, ' ')
+ .trim()
+ .slice(0, max)
+ .trim();
+ return out || null;
+}
+
export function normalizeLaunch(c, solUsd = 0) {
if (!c?.mint) return null;
const real = Number(c.real_sol_reserves);
const virt = Number(c.virtual_sol_reserves);
return {
- mint: c.mint, name: c.name || null, symbol: c.symbol || null,
+ mint: c.mint, name: cleanTokenLabel(c.name), symbol: cleanTokenLabel(c.symbol),
created_at: c.created_timestamp ? Number(c.created_timestamp) : null,
market_cap_usd: typeof c.usd_market_cap === 'number' ? c.usd_market_cap : typeof c.market_cap === 'number' && solUsd > 0 ? c.market_cap * solUsd : null,
liquidity_sol: real > 0 ? real / 1e9 : virt > 0 ? virt / 1e9 : null,
diff --git a/apps/desktop/src/runtime/runtime.js b/apps/desktop/src/runtime/runtime.js
index f7f08e479..a37bd9d95 100644
--- a/apps/desktop/src/runtime/runtime.js
+++ b/apps/desktop/src/runtime/runtime.js
@@ -10,7 +10,7 @@
import { randomUUID } from 'node:crypto';
import { canonicalJson, payloadHash, confirmationTable, confirmationText } from './hash.js';
import { validateStrategyConfig, matchesEntry, shouldExit, effectivePriceImpactPct } from './strategy-schema.js';
-import { createPumpFeed } from './feed.js';
+import { createPumpFeed, cleanTokenLabel } from './feed.js';
import { quoteBuy, quoteSell } from './curve.js';
export const APPROVAL_TTL_MS = 15 * 60 * 1000;
@@ -309,7 +309,7 @@ export function createRuntime({ stateStore, keystore, log, feed = createPumpFeed
}
const buyRow = (agent, p, symbol) => ({
- recipient: p.mint, recipient_label: symbol ? `$${symbol}` : null, amount: p.amount_sol, asset: 'SOL', chain: 'solana', network: agent.network, side: 'buy',
+ recipient: p.mint, recipient_label: cleanTokenLabel(symbol) ? `$${cleanTokenLabel(symbol)}` : null, amount: p.amount_sol, asset: 'SOL', chain: 'solana', network: agent.network, side: 'buy',
});
// ── scheduler ────────────────────────────────────────────────────────────
diff --git a/multiplayer/src/persistence.js b/multiplayer/src/persistence.js
index 68fd58bd0..987759fb9 100644
--- a/multiplayer/src/persistence.js
+++ b/multiplayer/src/persistence.js
@@ -28,6 +28,8 @@ import crypto from 'node:crypto';
const API_BASE = (process.env.WORLD_API_BASE || 'https://three.ws').replace(/\/$/, '');
const SAVE_DEBOUNCE_MS = 4000;
+// owner_id the game server stamps on every world row it creates (api/_lib/world-store.js).
+const SERVICE_OWNER = 'service:world';
const TOKEN_TTL_SEC = 120;
function secret() {
@@ -155,7 +157,9 @@ class WorldPersistence {
'content-type': 'application/json',
authorization: `Bearer ${signServiceToken()}`,
},
- body: JSON.stringify({ worldId, doc, ifMatch: ifMatch ?? null }),
+ // `owner` stamps a first save as service-owned, so no signed-in browser
+ // account can later claim or overwrite a game-server-managed world.
+ body: JSON.stringify({ worldId, doc, ifMatch: ifMatch ?? null, owner: SERVICE_OWNER }),
});
if (res.ok) {
const body = await res.json();
diff --git a/multiplayer/src/rooms/WalkRoom.js b/multiplayer/src/rooms/WalkRoom.js
index 69ebc44d8..7377fe80d 100644
--- a/multiplayer/src/rooms/WalkRoom.js
+++ b/multiplayer/src/rooms/WalkRoom.js
@@ -586,13 +586,14 @@ export class WalkRoom extends Room {
// instead of waiting on an HTTP round-trip. Non-blocking and fail-open.
warmEventDrop();
- // The first client to land in this coin's instance seeds its identity.
+ // A coin world's identity (name, symbol, image) comes from the coin's own
+ // record, fetched in _resolveCoinCreator, never from the first client to
+ // land here: join options are unsigned, so trusting them would let that
+ // client mislabel a real mint's world for everyone in the room.
this.state.coin = cleanCoin(options?.coin);
- this.state.coinName = clean(options?.coinName, 48);
- this.state.coinSymbol = clean(options?.coinSymbol, 16);
- this.state.coinImage = cleanAvatarUrl(options?.coinImage) || (
- typeof options?.coinImage === 'string' && options.coinImage.startsWith('http')
- ? options.coinImage.slice(0, 1024) : '');
+ this.state.coinName = '';
+ this.state.coinSymbol = '';
+ this.state.coinImage = '';
// Tier identity. The Holders world records the USD floor it gated on (from
// the joining pass) so the client HUD can state the requirement; the General
// world leaves both blank/zero.
@@ -3253,6 +3254,7 @@ export class WalkRoom extends Room {
if (!res.ok) return;
body = await res.json();
} finally { clearTimeout(timer); }
+ this._applyCoinIdentity(body);
const creator = typeof body?.creator === 'string' ? body.creator.trim() : '';
if (!MINT_RE.test(creator)) return; // a creator is a base58 wallet, same shape as a mint
this.coinCreator = creator;
@@ -3262,6 +3264,18 @@ export class WalkRoom extends Room {
}
}
+ // Stamp the room's coin identity from the coin record (same field fallbacks the
+ // in-world client reads from the pump.fun body). Text is control-stripped and
+ // length-capped; the image must be an http(s) URL.
+ _applyCoinIdentity(coin) {
+ this.state.coinName = clean(coin?.name, 48);
+ this.state.coinSymbol = clean(coin?.symbol, 16);
+ const image = coin?.image_uri || coin?.image || coin?.imageUri;
+ this.state.coinImage =
+ cleanAvatarUrl(image) ||
+ (typeof image === 'string' && /^https?:\/\//.test(image) ? image.slice(0, 1024) : '');
+ }
+
_editOk(sessionId) {
const now = Date.now();
let bucket = this._editCounters.get(sessionId);
diff --git a/packages/home-bridge/src/bridge.js b/packages/home-bridge/src/bridge.js
index 075ea438b..0256d3c86 100644
--- a/packages/home-bridge/src/bridge.js
+++ b/packages/home-bridge/src/bridge.js
@@ -9,10 +9,11 @@ import {
subscribeEntities,
} from 'home-assistant-js-websocket';
+import { isDeniedService } from './denylist.js';
import { ERR, HomeBridgeError } from './errors.js';
import { resolveIntent } from './intents.js';
import { buildHomeGraph, domainOf } from './rooms.js';
-import { classifyCallTargets, createAllowList } from './safety.js';
+import { classifyCallTargets, createAllowList, normalizeServiceData } from './safety.js';
import { normalizeBaseUrl } from './url.js';
/**
@@ -379,10 +380,20 @@ export class HomeBridge {
*/
async call(domain, service, data = {}, options = {}) {
this.#assertConnected();
+ domain = String(domain || '').trim().toLowerCase();
+ service = String(service || '').trim().toLowerCase();
+ // Host administration is refused here, for every transport and caller, and
+ // a confirmation does not lift it.
+ if (isDeniedService(domain, service)) {
+ throw new HomeBridgeError(ERR.SERVICE_DENIED, `${domain}.${service} administers the Home Assistant install and is not available.`);
+ }
+ // Classify and forward the SAME data: ids as the house will read them.
+ data = normalizeServiceData(data);
const verdict = classifyCallTargets({ domain, service, data, states: this.#states });
const entityId = verdict.entityIds[0] ?? firstEntityId(data);
- const allowed = !verdict.unresolved && verdict.entityIds.every((id) => this.allowList.has(id));
+ // An empty list is nothing to allow-list, not everything allowed.
+ const allowed = !verdict.unresolved && verdict.entityIds.length > 0 && verdict.entityIds.every((id) => this.allowList.has(id));
if (verdict.guarded && !options.confirmed && !allowed) {
const err = new HomeBridgeError(ERR.NEEDS_CONFIRMATION, verdict.reason);
err.pending = { domain, service, data, risk: verdict.risk, entityId };
diff --git a/packages/home-bridge/src/denylist.js b/packages/home-bridge/src/denylist.js
new file mode 100644
index 000000000..fdba09c04
--- /dev/null
+++ b/packages/home-bridge/src/denylist.js
@@ -0,0 +1,41 @@
+/**
+ * Service domains that administer the Home Assistant install or execute
+ * arbitrary code on the host, rather than controlling a device.
+ *
+ * Enforced in HomeBridge.call, the one funnel every transport and every caller
+ * goes through, and mirrored byte for byte by services/home-relay/src/protocol.js
+ * (tests/home-security.test.js fails if the two drift). A confirmation cannot
+ * override it: a `shell_command.*` is remote code execution on the user's server.
+ */
+export const DENIED_SERVICE_DOMAINS = Object.freeze([
+ 'shell_command',
+ 'python_script',
+ 'hassio',
+ 'supervisor',
+ 'backup',
+ 'update',
+ 'cloud',
+ 'config',
+ 'auth',
+ 'command_line',
+]);
+
+/** Individual services on otherwise legitimate domains that restart, stop or reconfigure the instance. */
+export const DENIED_SERVICES = Object.freeze([
+ 'homeassistant.restart',
+ 'homeassistant.stop',
+ 'homeassistant.check_config',
+ 'homeassistant.reload_all',
+ 'homeassistant.reload_core_config',
+ 'persistent_notification.create',
+]);
+
+const DENIED_DOMAIN_SET = new Set(DENIED_SERVICE_DOMAINS);
+const DENIED_SERVICE_SET = new Set(DENIED_SERVICES);
+
+/** True when `domain.service` administers the install. Case and whitespace are normalised. */
+export function isDeniedService(domain, service) {
+ const d = String(domain || '').trim().toLowerCase();
+ const s = String(service || '').trim().toLowerCase();
+ return DENIED_DOMAIN_SET.has(d) || DENIED_SERVICE_SET.has(`${d}.${s}`);
+}
diff --git a/packages/home-bridge/src/errors.js b/packages/home-bridge/src/errors.js
index 4c87a293a..aa1e337eb 100644
--- a/packages/home-bridge/src/errors.js
+++ b/packages/home-bridge/src/errors.js
@@ -22,6 +22,8 @@ export const ERR = {
CALL_FAILED: 'call_failed',
/** A guarded entity was targeted without an explicit confirmation. */
NEEDS_CONFIRMATION: 'needs_confirmation',
+ /** The service administers the Home Assistant install itself and is never callable. */
+ SERVICE_DENIED: 'service_denied',
/** The `mcp_server` integration is not enabled on this instance. */
NO_MCP: 'no_mcp',
/** A method was used before connect(), or after close(). */
diff --git a/packages/home-bridge/src/index.js b/packages/home-bridge/src/index.js
index a98e8be4d..b5a84d217 100644
--- a/packages/home-bridge/src/index.js
+++ b/packages/home-bridge/src/index.js
@@ -1,4 +1,5 @@
export { guardSubscriptions, HomeBridge, toBridgeError } from './bridge.js';
+export { DENIED_SERVICE_DOMAINS, DENIED_SERVICES, isDeniedService } from './denylist.js';
export { ERR, HomeBridgeError } from './errors.js';
// The two connection sentinels a custom socket factory has to reject with, so a
// server that supplies one (api/_lib/home-url-guard.js pins the socket to the
@@ -8,6 +9,6 @@ export { ERR_CANNOT_CONNECT, ERR_INVALID_AUTH } from 'home-assistant-js-websocke
export { MACROS, matchMacro, resolveIntent } from './intents.js';
export { connectHomeMcp } from './mcp.js';
export { buildHomeGraph, domainOf, flattenEntities, summarizeClimate, summarizeLighting, summarizeSecurity } from './rooms.js';
-export { classifyCall, classifyCallTargets, entityIdsOfData, hasSelectorTargets, classifyMcpCall, createAllowList, isSafetyAction, isSafetyMcpCall, resolveMcpTargets, GUARDED_COVER_CLASSES, GUARDED_DOMAINS } from './safety.js';
+export { classifyCall, classifyCallTargets, entityIdsOfData, normalizeServiceData, sceneEntityIdsOfData, hasSelectorTargets, classifyMcpCall, createAllowList, isSafetyAction, isSafetyMcpCall, resolveMcpTargets, GUARDED_COVER_CLASSES, GUARDED_DOMAINS } from './safety.js';
export { createRelayTransport, relayCloseError, RELAY_PROTOCOL_VERSION } from './transport-relay.js';
export { isPrivateHost, normalizeBaseUrl } from './url.js';
diff --git a/packages/home-bridge/src/safety.js b/packages/home-bridge/src/safety.js
index 9e197c0d0..03984a843 100644
--- a/packages/home-bridge/src/safety.js
+++ b/packages/home-bridge/src/safety.js
@@ -101,11 +101,84 @@ export function hasSelectorTargets(data) {
return SELECTOR_KEYS.some((k) => hasValue(data?.[k]));
}
-/** Every entity id named in service data: a string, a comma list, or an array. */
+/**
+ * Every entity id named in service data: a string, a comma list, or an array.
+ *
+ * Lowercased and trimmed, because Home Assistant's own validator lowercases ids
+ * (and accepts "ALL" for "all"): the gate must read the id the way the house
+ * will, or a mixed-case spelling walks past every lookup keyed on the real one.
+ */
export function entityIdsOfData(data) {
const raw = data?.entity_id;
const list = Array.isArray(raw) ? raw : typeof raw === 'string' ? raw.split(',') : [];
- return list.filter((v) => typeof v === 'string').map((v) => v.trim()).filter(Boolean);
+ return list.filter((v) => typeof v === 'string').map((v) => v.trim().toLowerCase()).filter(Boolean);
+}
+
+/** Entity ids a scene.apply / scene.create call would set, from `data.entities`. */
+export function sceneEntityIdsOfData(data) {
+ const raw = data?.entities;
+ const keys = Array.isArray(raw) ? raw : raw && typeof raw === 'object' ? Object.keys(raw) : [];
+ return keys.filter((v) => typeof v === 'string').map((v) => v.trim().toLowerCase()).filter(Boolean);
+}
+
+/**
+ * The service data exactly as the gate read it: entity_id lowercased, trimmed
+ * and split into an array. This is what must be forwarded, so the house acts on
+ * the ids that were classified and not on a different spelling of them.
+ */
+export function normalizeServiceData(data) {
+ if (!data || typeof data !== 'object' || data.entity_id === undefined) return data ?? {};
+ const raw = data.entity_id;
+ if (typeof raw !== 'string' && !Array.isArray(raw)) return data;
+ return { ...data, entity_id: entityIdsOfData(data) };
+}
+
+const NOT_GUARDED = Object.freeze({ guarded: false, risk: null, reason: '' });
+
+/** Would running something that touches this entity reach a lock, valve, alarm or building opening? */
+function reachesGuardedEntity(entityId, states) {
+ const domain = String(entityId).split('.')[0];
+ if (domain === 'lock' || domain === 'valve' || domain === 'alarm_control_panel') return true;
+ if (domain === 'cover') {
+ const state = states[entityId];
+ // No state record means we cannot see its device_class: fail closed.
+ return !state || GUARDED_COVER_CLASSES.has(String(state.attributes?.device_class || '').toLowerCase());
+ }
+ return false;
+}
+
+/** Services on scene/script/automation that run owner-authored content we cannot read. */
+function macroVerdict({ domain, service, ids, states, data }) {
+ const reason = (label) => `Running ${label} can unlock, open or disarm things it does not name.`;
+ const guard = (entityIds, label) => ({
+ guarded: true,
+ risk: 'physical',
+ reason: reason(label),
+ entityIds,
+ unresolved: false,
+ });
+ if (domain === 'scene') {
+ if (service === 'apply' || service === 'create') {
+ const hit = sceneEntityIdsOfData(data).filter((id) => reachesGuardedEntity(id, states));
+ return hit.length ? guard([], `a scene that sets ${hit.join(', ')}`) : null;
+ }
+ if (service !== 'turn_on') return null;
+ const hit = ids.filter((id) => {
+ const members = states[id]?.attributes?.entity_id;
+ if (!states[id]) return true;
+ return (Array.isArray(members) ? members : []).some((m) => typeof m === 'string' && reachesGuardedEntity(m.toLowerCase(), states));
+ });
+ return hit.length ? guard(hit, hit.join(', ')) : null;
+ }
+ if (domain === 'script') {
+ if (service === 'turn_off' || service === 'reload') return null;
+ const named = service === 'turn_on' || service === 'toggle' ? ids : [`script.${service}`];
+ return named.length ? guard(named, named.join(', ')) : guard([], 'a script');
+ }
+ if (domain === 'automation' && service === 'trigger') {
+ return ids.length ? guard(ids, ids.join(', ')) : guard([], 'an automation');
+ }
+ return null;
}
/**
@@ -113,33 +186,44 @@ export function entityIdsOfData(data) {
*
* Home Assistant expands entity lists, "all", and area/device/label/floor
* selectors itself, so the gate must look at every target it can see and treat
- * a selector it cannot resolve as the riskiest thing it could expand to.
+ * a selector it cannot resolve as the riskiest thing it could expand to. A
+ * selector is judged even when guarded entities are also named: a standing
+ * allowance for one door must not stretch to every lock in the area.
*
* @returns {{ guarded: boolean, risk: ('security'|'physical'|null), reason: string, entityIds: string[], unresolved: boolean }}
* entityIds are the guarded entities that need a standing allowance;
* unresolved means a selector hides targets, so no allowance can cover it.
*/
export function classifyCallTargets({ domain, service, data = {}, states = {} } = {}) {
+ const d = String(domain || '').trim().toLowerCase();
+ const s = String(service || '').trim().toLowerCase();
const ids = entityIdsOfData(data);
+
+ const macro = macroVerdict({ domain: d, service: s, ids, states, data });
+ if (macro) return macro;
+
let first = null;
const guardedIds = [];
for (const entityId of ids) {
- const v = classifyCall({ domain, service, entityId, attributes: states[entityId]?.attributes });
+ if (entityId === 'all' || entityId === 'none') continue;
+ const known = states[entityId];
+ // A cover we have no state for has no visible device_class. Opening it is
+ // judged as the worst thing it could be rather than waved through.
+ const attributes = known ? known.attributes : d === 'cover' ? { device_class: 'garage' } : undefined;
+ const v = classifyCall({ domain: d, service: s, entityId, attributes });
if (v.guarded) {
guardedIds.push(entityId);
first ??= v;
}
}
- if (first) return { ...first, entityIds: guardedIds, unresolved: false };
const selectors = hasSelectorTargets(data) || ids.includes('all');
- if (selectors) {
- const worst = ['lock', 'valve', 'alarm_control_panel', 'cover'].includes(String(domain).toLowerCase())
- ? classifyCall({ domain, service, entityId: undefined, attributes: { device_class: 'garage' } })
- : { guarded: false, risk: null, reason: '' };
- if (worst.guarded) return { ...worst, entityIds: [], unresolved: true };
+ if (selectors && ['lock', 'valve', 'alarm_control_panel', 'cover'].includes(d)) {
+ const worst = classifyCall({ domain: d, service: s, entityId: undefined, attributes: { device_class: 'garage' } });
+ if (worst.guarded) return { ...worst, entityIds: guardedIds, unresolved: true };
}
- return { guarded: false, risk: null, reason: '', entityIds: [], unresolved: false };
+ if (first) return { ...first, entityIds: guardedIds, unresolved: false };
+ return { ...NOT_GUARDED, entityIds: [], unresolved: false };
}
/**
diff --git a/packages/x402-fetch/src/parse-challenge.js b/packages/x402-fetch/src/parse-challenge.js
index 06a483cd2..6aa5a3a83 100644
--- a/packages/x402-fetch/src/parse-challenge.js
+++ b/packages/x402-fetch/src/parse-challenge.js
@@ -12,6 +12,23 @@
export const USDC_BASE = '0x833589fcd6edb6e08f4c7c32d4f71b54bda02913';
export const NETWORK_BASE = 'eip155:8453';
+// Pinned (network -> USDC contract). The 402 challenge is server-controlled, so
+// neither the asset nor its decimals are trusted: only these contracts are
+// signed for, and their decimals come from this table, never from the challenge.
+const PINNED_USDC = {
+ 'eip155:8453': '0x833589fcd6edb6e08f4c7c32d4f71b54bda02913',
+ 'eip155:84532': '0x036cbd53842c5426634e7929541ec2318f3dcf7e',
+ 'eip155:42161': '0xaf88d065e77c8cc2239327c5edb3a432268e5831',
+ 'eip155:1': '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48',
+ 'eip155:10': '0x0b2c639c533813f4aa9d7837caf62653d097ff85',
+};
+const PINNED_DECIMALS = 6;
+
+function isPinnedAsset(accept) {
+ const pinned = PINNED_USDC[accept?.network];
+ return typeof accept?.asset === 'string' && !!pinned && accept.asset.toLowerCase() === pinned;
+}
+
function b64decodeJson(str) {
if (!str) return null;
try {
@@ -36,6 +53,7 @@ function isEvmNetwork(net) {
function isEip3009Accept(accept) {
if (!isEvmNetwork(accept?.network)) return false;
if (accept.scheme && accept.scheme !== 'exact') return false;
+ if (!isPinnedAsset(accept)) return false;
const method = accept?.extra?.assetTransferMethod;
return !method || method === 'eip3009';
}
@@ -95,11 +113,16 @@ export function selectRequirement(accepts, { preferNetwork } = {}) {
return base || payable[0];
}
-/** Atomic price → USD float, honouring the asset's declared decimals (default 6). */
+/**
+ * Atomic price to USD float using the pinned USDC decimals. Anything that is not
+ * a finite, non-negative amount on a pinned asset prices as Infinity so every
+ * spend cap trips.
+ */
export function amountToUsd(accept) {
- const decimals = Number(accept?.extra?.decimals ?? 6);
- const atomic = Number(accept?.amount ?? 0);
- return atomic / 10 ** decimals;
+ if (!isPinnedAsset(accept)) return Infinity;
+ const atomic = Number(accept?.amount);
+ if (!Number.isFinite(atomic) || atomic < 0) return Infinity;
+ return atomic / 10 ** PINNED_DECIMALS;
}
export { isEvmNetwork, isEip3009Accept };
diff --git a/packages/x402-fetch/tests/client.test.mjs b/packages/x402-fetch/tests/client.test.mjs
index 2225fbf1b..cca103585 100644
--- a/packages/x402-fetch/tests/client.test.mjs
+++ b/packages/x402-fetch/tests/client.test.mjs
@@ -181,3 +181,29 @@ test('onPayment callback fires before signing with USD amount + recipient', asyn
assert.equal(seen[0].to, PAY_TO);
assert.equal(seen[0].requestUrl, 'https://three.ws/api/mcp');
});
+
+test('hostile extra.decimals cannot defeat maxPaymentUsd', async () => {
+ for (const decimals of [30, 'abc', -5, 1e9, null]) {
+ const accept = baseAccept(5_000_000_000); // $5000 on real USDC
+ accept.extra = { ...accept.extra, decimals };
+ const fetchMock = mockFetch({
+ accepts: [accept],
+ success: () => new Response('{}', { status: 200 }),
+ });
+ const pay = withX402(fetchMock, { wallet: WALLET, maxPaymentUsd: 1 });
+ await assert.rejects(() => pay('https://three.ws/api/mcp'), /exceeds maxPaymentUsd/);
+ assert.equal(fetchMock.calls.length, 1, `no payment signed for decimals=${decimals}`);
+ }
+});
+
+test('an unpinned asset is refused instead of being signed', async () => {
+ const accept = baseAccept(50_000);
+ accept.asset = '0x2222222222222222222222222222222222222222';
+ const fetchMock = mockFetch({
+ accepts: [accept],
+ success: () => new Response('{}', { status: 200 }),
+ });
+ const pay = withX402(fetchMock, { wallet: WALLET, maxPaymentUsd: 1 });
+ await assert.rejects(() => pay('https://three.ws/api/mcp'), /no supported network\/asset/);
+ assert.equal(fetchMock.calls.length, 1);
+});
diff --git a/server/bounded-cache.mjs b/server/bounded-cache.mjs
new file mode 100644
index 000000000..65207846f
--- /dev/null
+++ b/server/bounded-cache.mjs
@@ -0,0 +1,17 @@
+// Insert into a Map that must not grow without bound. When the map is at `max`
+// entries the least recently used key (first in insertion order) is evicted.
+// Pair with `touchBounded` on reads to keep recency.
+export function setBounded(map, key, value, max) {
+ if (map.has(key)) map.delete(key);
+ else if (map.size >= max) map.delete(map.keys().next().value);
+ map.set(key, value);
+ return value;
+}
+
+export function touchBounded(map, key) {
+ if (!map.has(key)) return undefined;
+ const value = map.get(key);
+ map.delete(key);
+ map.set(key, value);
+ return value;
+}
diff --git a/server/index.mjs b/server/index.mjs
index 437a5d863..50da68b7e 100644
--- a/server/index.mjs
+++ b/server/index.mjs
@@ -44,6 +44,7 @@ import { renderCrawlerBody } from './crawler-body.mjs';
import { isMissingShellPage } from './shell-pages.mjs';
import { hardenHeaderBag, hardenOnEnd } from './csp-hashes.mjs';
import { cronEdgeAuth } from './cron-edge-auth.mjs';
+import { setBounded, touchBounded } from './bounded-cache.mjs';
import { runWithRequestContext } from '../api/_lib/request-context.js';
// Route resolution lives in its own module so the audit scripts
// (scripts/audit-cron-liveness.mjs) exercise the SAME resolver production runs,
@@ -155,6 +156,9 @@ async function proxyExternal(req, res, dest) {
/** @type {Map<string, {file: string, params: Record<string, string>} | null>} */
const routeCache = new Map();
+// Keyed by request path, misses included, so it is capped (LRU) rather than
+// letting unique junk paths grow it for the life of the instance.
+const ROUTE_CACHE_MAX = 5000;
/** @type {Map<string, Promise<any>>} */
const moduleCache = new Map();
@@ -183,12 +187,12 @@ async function dispatchApi(req, res, pathname, extraQuery) {
return false;
const cacheKey = segments.join('/');
- let route = routeCache.get(cacheKey);
+ let route = touchBounded(routeCache, cacheKey);
if (route === undefined) {
route = resolveApi(API_ROOT, segments, {});
// Defense in depth: never route to a file that resolved outside API_ROOT.
if (route && !route.file.startsWith(API_ROOT + path.sep)) route = null;
- routeCache.set(cacheKey, route);
+ setBounded(routeCache, cacheKey, route, ROUTE_CACHE_MAX);
}
if (!route) return false;
diff --git a/services/home-satellite/src/token.js b/services/home-satellite/src/token.js
index 691e6c3a5..7a8eda183 100644
--- a/services/home-satellite/src/token.js
+++ b/services/home-satellite/src/token.js
@@ -23,6 +23,14 @@
import { createHmac, timingSafeEqual, randomBytes } from 'node:crypto';
/** Roles a token can carry. A socket gets exactly one. */
+/**
+ * How long a satellite's own hub token lasts. The hub keeps no revocation state,
+ * so this is also the window in which a revoked satellite can still rejoin its
+ * room. The satellite refreshes ahead of expiry (an API call that does check
+ * revocation), so a live one never notices a short lifetime.
+ */
+export const SATELLITE_TOKEN_TTL_SECONDS = 30 * 60;
+
export const ROLE = Object.freeze({ SATELLITE: 'satellite', VIEWER: 'viewer' });
const b64url = (buf) => Buffer.from(buf).toString('base64url');
diff --git a/src/character-creator.js b/src/character-creator.js
index 06dc911aa..12b56e41e 100644
--- a/src/character-creator.js
+++ b/src/character-creator.js
@@ -16,6 +16,7 @@
// loads pre-unlocked from /api/cosmetics/catalog. On save we persist the avatar +
// equipped loadout via the shared hand-off (play-handoff) and jump into /play.
+import { isReadyPlayerMeOrigin } from './rpm-origin.js';
import {
Scene, PerspectiveCamera, WebGLRenderer, Group,
HemisphereLight, DirectionalLight, Color, PMREMGenerator,
@@ -384,7 +385,7 @@ class CharacterCreator {
// RPM posts a JSON string event; the GLB URL arrives on v1.avatar.exported.
if (!this._rpmListener) {
this._rpmListener = (ev) => {
- if (!/readyplayer\.me/.test(ev.origin)) return;
+ if (ev.source !== frame.contentWindow || !isReadyPlayerMeOrigin(ev.origin)) return;
let data = ev.data;
try { if (typeof data === 'string') data = JSON.parse(data); } catch { return; }
if (data?.source !== 'readyplayerme') return;
@@ -408,6 +409,10 @@ class CharacterCreator {
_closeRpm() {
const modal = $('cc-rpm-modal');
const frame = $('cc-rpm-frame');
+ if (this._rpmListener) {
+ window.removeEventListener('message', this._rpmListener);
+ this._rpmListener = null;
+ }
modal.classList.remove('open');
modal.hidden = true;
frame.src = 'about:blank';
diff --git a/src/rpm-origin.js b/src/rpm-origin.js
new file mode 100644
index 000000000..ec6c18461
--- /dev/null
+++ b/src/rpm-origin.js
@@ -0,0 +1,12 @@
+// True only for an https origin whose host is readyplayer.me or one of its
+// subdomains. Used to trust postMessage events from the Ready Player Me frame.
+export function isReadyPlayerMeOrigin(origin) {
+ let url;
+ try {
+ url = new URL(origin);
+ } catch {
+ return false;
+ }
+ if (url.protocol !== 'https:') return false;
+ return url.hostname === 'readyplayer.me' || url.hostname.endsWith('.readyplayer.me');
+}
diff --git a/tests/agent-crawler-guard.test.js b/tests/agent-crawler-guard.test.js
index 673ee9eac..dbc62e2e7 100644
--- a/tests/agent-crawler-guard.test.js
+++ b/tests/agent-crawler-guard.test.js
@@ -1,7 +1,7 @@
// The Crawl worker's network fence (workers/agent-crawler/guard.js): every
// address a crawled page reaches is checked here before the browser connects.
-import { describe, expect, it } from 'vitest';
-import { guardHost, isBlockedAddress } from '../workers/agent-crawler/guard.js';
+import { afterEach, describe, expect, it } from 'vitest';
+import { guardHost, guardedFetch, isBlockedAddress } from '../workers/agent-crawler/guard.js';
describe('isBlockedAddress', () => {
it.each([
@@ -27,3 +27,43 @@ describe('guardHost', () => {
expect(await guardHost('8.8.8.8')).toBe(true);
});
});
+
+describe('guardedFetch redirects', () => {
+ const realFetch = globalThis.fetch;
+ afterEach(() => {
+ globalThis.fetch = realFetch;
+ });
+
+ it('refuses a redirect hop that lands on a private or metadata address', async () => {
+ const seen = [];
+ globalThis.fetch = async (u) => {
+ seen.push(String(u));
+ return new Response(null, { status: 302, headers: { location: 'http://169.254.169.254/latest/meta-data/' } });
+ };
+ await expect(guardedFetch('https://8.8.8.8/robots.txt')).rejects.toThrow(/refused private host/);
+ expect(seen).toEqual(['https://8.8.8.8/robots.txt']);
+ });
+
+ it('follows a redirect between public hosts', async () => {
+ const seen = [];
+ globalThis.fetch = async (u) => {
+ seen.push(String(u));
+ return seen.length === 1
+ ? new Response(null, { status: 301, headers: { location: 'https://1.1.1.1/robots.txt' } })
+ : new Response('User-agent: *', { status: 200 });
+ };
+ const res = await guardedFetch('https://8.8.8.8/robots.txt');
+ expect(await res.text()).toBe('User-agent: *');
+ expect(seen).toEqual(['https://8.8.8.8/robots.txt', 'https://1.1.1.1/robots.txt']);
+ });
+
+ it('gives up after a bounded number of hops', async () => {
+ globalThis.fetch = async () => new Response(null, { status: 302, headers: { location: 'https://8.8.8.8/loop' } });
+ await expect(guardedFetch('https://8.8.8.8/loop')).rejects.toThrow(/too many redirects/);
+ });
+
+ it('refuses a non-http scheme in a redirect', async () => {
+ globalThis.fetch = async () => new Response(null, { status: 302, headers: { location: 'file:///etc/passwd' } });
+ await expect(guardedFetch('https://8.8.8.8/x')).rejects.toThrow();
+ });
+});
diff --git a/tests/character-creator.test.js b/tests/character-creator.test.js
new file mode 100644
index 000000000..ef3725e31
--- /dev/null
+++ b/tests/character-creator.test.js
@@ -0,0 +1,27 @@
+import { describe, it, expect } from 'vitest';
+import { isReadyPlayerMeOrigin } from '../src/rpm-origin.js';
+
+// The creator trusts postMessage events from the Ready Player Me iframe. An
+// unanchored /readyplayer\.me/ test also matched https://readyplayer.me.evil.example.
+describe('isReadyPlayerMeOrigin', () => {
+ it('accepts readyplayer.me and its subdomains over https', () => {
+ expect(isReadyPlayerMeOrigin('https://readyplayer.me')).toBe(true);
+ expect(isReadyPlayerMeOrigin('https://demo.readyplayer.me')).toBe(true);
+ });
+
+ it('rejects lookalike hosts', () => {
+ for (const o of [
+ 'https://readyplayer.me.evil.example',
+ 'https://evil.example/readyplayer.me',
+ 'https://notreadyplayer.me',
+ 'https://evilreadyplayer.me',
+ 'https://[email protected]',
+ 'http://readyplayer.me',
+ 'null',
+ '',
+ undefined,
+ ]) {
+ expect(isReadyPlayerMeOrigin(o), String(o)).toBe(false);
+ }
+ });
+});
diff --git a/tests/desktop-runtime.test.js b/tests/desktop-runtime.test.js
index 291eb6af6..86cf59efc 100644
--- a/tests/desktop-runtime.test.js
+++ b/tests/desktop-runtime.test.js
@@ -17,7 +17,7 @@ import { createSecureStore } from '../apps/desktop/src/main/secure-store.js';
import { createKeystore } from '../apps/desktop/src/runtime/keystore.js';
import { createRuntime, RuntimeError } from '../apps/desktop/src/runtime/runtime.js';
import { quoteBuy, quoteSell } from '../apps/desktop/src/runtime/curve.js';
-import { bondingCurveAddress, parseBondingCurve } from '../apps/desktop/src/runtime/feed.js';
+import { bondingCurveAddress, parseBondingCurve, normalizeLaunch, cleanTokenLabel } from '../apps/desktop/src/runtime/feed.js';
const MINT = '5a4w3tawg8y595D8pXzLrZqTnUZ5xT7e2m1q8VhJpump';
const FIXTURE_COIN = { mint: MINT, symbol: 'FIX', virtual_sol_reserves: 30_000_000_000, virtual_token_reserves: 1_073_000_000_000_000 };
@@ -52,6 +52,25 @@ describe('approval hash parity with the cloud', () => {
});
});
+describe('untrusted on-chain token labels', () => {
+ const hostile = 'FIX\nAmount: 1000 SOL\r\u202e\u0000 Chain: Ethereum and a very long tail of forged text';
+ it('normalizeLaunch strips control characters, collapses whitespace and caps symbol and name', () => {
+ const l = normalizeLaunch({ mint: MINT, symbol: hostile, name: hostile });
+ for (const v of [l.symbol, l.name]) {
+ expect(v).not.toMatch(/[\u0000-\u001f\u007f-\u009f\u202a-\u202e\u2066-\u2069]/);
+ expect(v.length).toBeLessThanOrEqual(16);
+ }
+ expect(l.symbol).toBe('FIX Amount: 1000');
+ });
+ it('a label made only of control characters becomes null', () => {
+ expect(cleanTokenLabel('\n\t \u0000')).toBeNull();
+ expect(normalizeLaunch({ mint: MINT, symbol: '\n' }).symbol).toBeNull();
+ });
+ it('keeps an ordinary symbol unchanged', () => {
+ expect(cleanTokenLabel('FIX')).toBe('FIX');
+ });
+});
+
describe('log redaction', () => {
it('masks secret fields, key bytes, base58 keys and bearer tokens', () => {
const kp = Keypair.generate();
diff --git a/tests/home-call-targets.test.js b/tests/home-call-targets.test.js
index 83e9d1066..75ab7be9c 100644
--- a/tests/home-call-targets.test.js
+++ b/tests/home-call-targets.test.js
@@ -1,5 +1,33 @@
-import { describe, expect, it } from 'vitest';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+const wsMock = vi.hoisted(() => ({ calls: [], states: {} }));
+
+vi.mock('home-assistant-js-websocket', () => ({
+ callService: vi.fn(async (_conn, domain, service, data) => {
+ wsMock.calls.push({ domain, service, data });
+ return [];
+ }),
+ createConnection: vi.fn(async () => ({
+ connected: true,
+ addEventListener() {},
+ subscribeMessage: async () => () => {},
+ subscribeEvents: async () => () => {},
+ sendMessagePromise: async () => [],
+ ping: async () => {},
+ close() {},
+ })),
+ createLongLivedTokenAuth: vi.fn(() => ({})),
+ subscribeEntities: vi.fn((_conn, cb) => {
+ cb(wsMock.states);
+ return () => {};
+ }),
+ ERR_CANNOT_CONNECT: 1,
+ ERR_CONNECTION_LOST: 3,
+ ERR_INVALID_AUTH: 2,
+ ERR_INVALID_HTTPS_TO_HTTP: 4,
+}));
+
+import { ERR, HomeBridge } from '../packages/home-bridge/src/index.js';
import {
classifyCallTargets,
entityIdsOfData,
@@ -59,3 +87,145 @@ describe('target extraction for the scope check', () => {
expect(hasSelectorTargets({ entity_id: 'light.a' })).toBe(false);
});
});
+
+describe('gate input normalisation (Home Assistant lowercases ids)', () => {
+ it('lowercases and trims every id', () => {
+ expect(entityIdsOfData({ entity_id: [' COVER.Garage_Door ', 'ALL'] })).toEqual(['cover.garage_door', 'all']);
+ });
+
+ it('guards a mixed-case cover id that has no state record under that spelling', () => {
+ const v = classifyCallTargets({
+ domain: 'cover', service: 'open_cover', data: { entity_id: 'COVER.Garage' }, states,
+ });
+ expect(v.guarded).toBe(true);
+ expect(v.entityIds).toEqual(['cover.garage']);
+ });
+
+ it('fails closed on a cover id the house has no state for', () => {
+ const v = classifyCallTargets({
+ domain: 'cover', service: 'open_cover', data: { entity_id: 'cover.unknown_door' }, states,
+ });
+ expect(v.guarded).toBe(true);
+ });
+
+ it('treats ALL as the unresolved selector it is', () => {
+ const v = classifyCallTargets({ domain: 'cover', service: 'open_cover', data: { entity_id: 'ALL' }, states });
+ expect(v.guarded).toBe(true);
+ expect(v.unresolved).toBe(true);
+ });
+});
+
+describe('a named guarded entity does not launder a selector', () => {
+ it('stays unresolved when an area rides along with one named lock', () => {
+ const v = classifyCallTargets({
+ domain: 'lock', service: 'unlock',
+ data: { entity_id: 'lock.office_door', area_id: 'upstairs' }, states,
+ });
+ expect(v.guarded).toBe(true);
+ expect(v.unresolved).toBe(true);
+ });
+
+ it('stays unresolved when all rides along with one named cover', () => {
+ const v = classifyCallTargets({
+ domain: 'cover', service: 'open_cover', data: { entity_id: ['cover.garage', 'all'] }, states,
+ });
+ expect(v.unresolved).toBe(true);
+ });
+});
+
+describe('scene, script and automation indirection', () => {
+ const macroStates = {
+ ...states,
+ 'scene.movie': { attributes: { entity_id: ['light.tv', 'media_player.tv'] } },
+ 'scene.goodbye_unlock': { attributes: { entity_id: ['light.tv', 'lock.front'] } },
+ 'scene.open_up': { attributes: { entity_id: ['cover.garage'] } },
+ 'script.bedtime': { attributes: {} },
+ 'automation.arrive': { attributes: {} },
+ };
+
+ it('leaves a scene made only of lights alone', () => {
+ expect(classifyCallTargets({ domain: 'scene', service: 'turn_on', data: { entity_id: 'scene.movie' }, states: macroStates }).guarded).toBe(false);
+ });
+
+ it('guards a scene whose members include a lock or a gate-class cover', () => {
+ const lockScene = classifyCallTargets({ domain: 'scene', service: 'turn_on', data: { entity_id: 'scene.goodbye_unlock' }, states: macroStates });
+ expect(lockScene.guarded).toBe(true);
+ expect(lockScene.entityIds).toEqual(['scene.goodbye_unlock']);
+ expect(classifyCallTargets({ domain: 'scene', service: 'turn_on', data: { entity_id: 'scene.open_up' }, states: macroStates }).guarded).toBe(true);
+ });
+
+ it('guards scene.apply that names a lock in data.entities', () => {
+ const v = classifyCallTargets({
+ domain: 'scene', service: 'apply', data: { entities: { 'lock.front_door': 'unlocked' } }, states: macroStates,
+ });
+ expect(v.guarded).toBe(true);
+ });
+
+ it('guards an opaque script run, as script.turn_on and as script.<name>', () => {
+ expect(classifyCallTargets({ domain: 'script', service: 'turn_on', data: { entity_id: 'script.bedtime' }, states: macroStates }).entityIds).toEqual(['script.bedtime']);
+ expect(classifyCallTargets({ domain: 'script', service: 'bedtime', data: {}, states: macroStates }).entityIds).toEqual(['script.bedtime']);
+ });
+
+ it('guards automation.trigger but not automation.turn_off or script.turn_off', () => {
+ expect(classifyCallTargets({ domain: 'automation', service: 'trigger', data: { entity_id: 'automation.arrive' }, states: macroStates }).guarded).toBe(true);
+ expect(classifyCallTargets({ domain: 'automation', service: 'turn_off', data: { entity_id: 'automation.arrive' }, states: macroStates }).guarded).toBe(false);
+ expect(classifyCallTargets({ domain: 'script', service: 'turn_off', data: { entity_id: 'script.bedtime' }, states: macroStates }).guarded).toBe(false);
+ });
+});
+
+describe('HomeBridge.call enforces the gate on what it forwards', () => {
+ let bridge;
+ beforeEach(async () => {
+ wsMock.calls.length = 0;
+ wsMock.states = {
+ 'cover.garage': { entity_id: 'cover.garage', state: 'closed', attributes: { device_class: 'garage' } },
+ 'lock.front': { entity_id: 'lock.front', state: 'locked', attributes: {} },
+ 'light.hall': { entity_id: 'light.hall', state: 'off', attributes: {} },
+ };
+ bridge = new HomeBridge({ baseUrl: 'https://home.example.com', token: 'x', livenessIntervalMs: 0 });
+ await bridge.connect();
+ });
+
+ it('refuses COVER.Garage open_cover without a confirmation and forwards nothing', async () => {
+ await expect(bridge.call('cover', 'open_cover', { entity_id: 'COVER.Garage' })).rejects.toMatchObject({ code: ERR.NEEDS_CONFIRMATION });
+ expect(wsMock.calls).toEqual([]);
+ });
+
+ it('refuses cover ALL open_cover', async () => {
+ await expect(bridge.call('cover', 'open_cover', { entity_id: 'ALL' })).rejects.toMatchObject({ code: ERR.NEEDS_CONFIRMATION });
+ expect(wsMock.calls).toEqual([]);
+ });
+
+ it('a standing allowance for one lock does not cover an area selector sent with it', async () => {
+ bridge.allowList.add('lock.front');
+ await expect(
+ bridge.call('lock', 'unlock', { entity_id: 'lock.front', area_id: 'upstairs' }),
+ ).rejects.toMatchObject({ code: ERR.NEEDS_CONFIRMATION });
+ expect(wsMock.calls).toEqual([]);
+ await bridge.call('lock', 'unlock', { entity_id: 'lock.front' });
+ expect(wsMock.calls).toHaveLength(1);
+ });
+
+ it('forwards the normalised entity ids when a confirmed call goes through', async () => {
+ await bridge.call('cover', 'open_cover', { entity_id: ' COVER.Garage ' }, { confirmed: true });
+ expect(wsMock.calls[0].data.entity_id).toEqual(['cover.garage']);
+ });
+
+ it('refuses scene.apply naming a lock, and a script run, without a confirmation', async () => {
+ await expect(bridge.call('scene', 'apply', { entities: { 'lock.front': 'unlocked' } })).rejects.toMatchObject({ code: ERR.NEEDS_CONFIRMATION });
+ await expect(bridge.call('script', 'bedtime', {})).rejects.toMatchObject({ code: ERR.NEEDS_CONFIRMATION });
+ expect(wsMock.calls).toEqual([]);
+ });
+
+ it('refuses host-administration services even when confirmed', async () => {
+ for (const [domain, service] of [['shell_command', 'anything'], ['python_script', 'run'], ['homeassistant', 'restart'], ['HASSIO', 'host_reboot']]) {
+ await expect(bridge.call(domain, service, {}, { confirmed: true })).rejects.toMatchObject({ code: ERR.SERVICE_DENIED });
+ }
+ expect(wsMock.calls).toEqual([]);
+ });
+
+ it('still lets an ordinary light through', async () => {
+ await bridge.call('light', 'turn_on', { entity_id: 'light.hall' });
+ expect(wsMock.calls).toHaveLength(1);
+ });
+});
diff --git a/tests/home-satellite-pairing.test.js b/tests/home-satellite-pairing.test.js
index 2fc8539e5..c1a758bbc 100644
--- a/tests/home-satellite-pairing.test.js
+++ b/tests/home-satellite-pairing.test.js
@@ -16,7 +16,7 @@ import { fileURLToPath } from 'node:url';
import { generateCode, normalizeCode, CODE_TTL_MINUTES } from '../api/_lib/home/satellites.js';
import { saveIdentity } from '../services/home-satellite/src/pairing.js';
-import { newSecret, verifyToken, ROLE } from '../services/home-satellite/src/token.js';
+import { newSecret, verifyToken, ROLE, SATELLITE_TOKEN_TTL_SECONDS } from '../services/home-satellite/src/token.js';
import { PcmDownsampler, floatTo16kPcm } from '../src/voice/mic-capture.js';
describe('pairing codes', () => {
@@ -184,3 +184,16 @@ describe('the token role', () => {
}
});
});
+
+describe('satellite hub token lifetime', () => {
+ // The hub holds no revocation list, so a retired satellite keeps its room slot
+ // until its token expires. The lifetime is the revocation window: minutes, not a day.
+ it('is short enough that revoking a satellite takes effect within the hour', () => {
+ expect(SATELLITE_TOKEN_TTL_SECONDS).toBeLessThanOrEqual(30 * 60);
+ });
+
+ it('is long enough for the satellite to refresh ahead of expiry', () => {
+ // server.js refreshes HUB_TOKEN_LEAD_SECONDS (600) before exp, floor 60s.
+ expect(SATELLITE_TOKEN_TTL_SECONDS).toBeGreaterThan(600 + 60);
+ });
+});
diff --git a/tests/home-security.test.js b/tests/home-security.test.js
index 3d66d09b7..cbe7709ad 100644
--- a/tests/home-security.test.js
+++ b/tests/home-security.test.js
@@ -1501,3 +1501,28 @@ function haSocket() {
ws.addEventListener('error', reject);
});
}
+
+describe('service denylist is shared between the relay and the direct path', () => {
+ it('the bridge and the relay protocol deny exactly the same services', async () => {
+ const bridgeLists = await import('../packages/home-bridge/src/denylist.js');
+ const relay = await import('../services/home-relay/src/protocol.js');
+ expect([...bridgeLists.DENIED_SERVICE_DOMAINS]).toEqual([...relay.DENIED_SERVICE_DOMAINS]);
+ expect([...bridgeLists.DENIED_SERVICES]).toEqual([...relay.DENIED_SERVICES]);
+ expect(bridgeLists.isDeniedService('Shell_Command', 'x')).toBe(true);
+ expect(bridgeLists.isDeniedService('homeassistant', 'RESTART')).toBe(true);
+ expect(bridgeLists.isDeniedService('light', 'turn_on')).toBe(false);
+ });
+});
+
+describe('scoped members may only make target-based calls on named entities', () => {
+ it('refuses macro, admin and unknown domains and calls with no entity target', async () => {
+ const { scopedCallRefusal } = await import('../api/_lib/home/members.js');
+ expect(scopedCallRefusal('scene', ['lock.front_door'])).toBeTruthy();
+ for (const domain of ['script', 'automation', 'homeassistant', 'notify', 'rest_command', 'made_up']) {
+ expect(scopedCallRefusal(domain, ['light.kitchen'])).toBeTruthy();
+ }
+ expect(scopedCallRefusal('light', [])).toBeTruthy();
+ expect(scopedCallRefusal('light', ['light.kitchen'])).toBeNull();
+ expect(scopedCallRefusal('lock', ['lock.front_door'])).toBeNull();
+ });
+});
diff --git a/tests/server-routing.test.js b/tests/server-routing.test.js
new file mode 100644
index 000000000..24574c930
--- /dev/null
+++ b/tests/server-routing.test.js
@@ -0,0 +1,31 @@
+// The /api route cache is keyed by attacker-chosen paths, so it must be bounded.
+import { describe, it, expect } from 'vitest';
+import { setBounded, touchBounded } from '../server/bounded-cache.mjs';
+
+describe('bounded route cache', () => {
+ it('never grows past its cap under unique-path pressure', () => {
+ const m = new Map();
+ for (let i = 0; i < 20_000; i++) setBounded(m, `junk/${i}`, null, 5000);
+ expect(m.size).toBe(5000);
+ expect(m.has('junk/19999')).toBe(true);
+ expect(m.has('junk/0')).toBe(false);
+ });
+
+ it('keeps a hot key alive when it is touched', () => {
+ const m = new Map();
+ setBounded(m, 'hot', { file: 'a' }, 3);
+ setBounded(m, 'b', null, 3);
+ setBounded(m, 'c', null, 3);
+ expect(touchBounded(m, 'hot')).toEqual({ file: 'a' });
+ setBounded(m, 'd', null, 3);
+ expect(m.has('hot')).toBe(true);
+ expect(m.has('b')).toBe(false);
+ });
+
+ it('returns undefined for an unknown key so a cached null stays distinguishable', () => {
+ const m = new Map();
+ setBounded(m, 'miss', null, 3);
+ expect(touchBounded(m, 'miss')).toBeNull();
+ expect(touchBounded(m, 'other')).toBeUndefined();
+ });
+});
diff --git a/tests/walk-room.test.js b/tests/walk-room.test.js
new file mode 100644
index 000000000..e1aa514b2
--- /dev/null
+++ b/tests/walk-room.test.js
@@ -0,0 +1,55 @@
+// A coin world's identity (name, symbol, image) must come from the coin's own
+// record, never from the first client to join: join options are unsigned.
+import { describe, it, expect, vi, afterEach } from 'vitest';
+import { WalkRoom } from '../multiplayer/src/rooms/WalkRoom.js';
+
+const MINT = 'THREEsynthetic1111111111111111111111111111';
+
+function makeRoom() {
+ const room = Object.create(WalkRoom.prototype);
+ Object.defineProperty(room, 'roomId', { value: 'room-1' });
+ Object.defineProperty(room, 'clients', { value: [] });
+ room.coinCreator = '';
+ room.state = { coin: MINT, coinName: '', coinSymbol: '', coinImage: '' };
+ return room;
+}
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+});
+
+describe('WalkRoom coin identity', () => {
+ it('takes name, symbol and image from the coin record, not the joiner', async () => {
+ vi.stubGlobal(
+ 'fetch',
+ vi.fn(async () => ({
+ ok: true,
+ json: async () => ({ name: 'Synthetic Coin', symbol: 'SYN', image_uri: 'https://cdn.example/syn.png' }),
+ })),
+ );
+ const room = makeRoom();
+ await room._resolveCoinCreator();
+ expect(room.state.coinName).toBe('Synthetic Coin');
+ expect(room.state.coinSymbol).toBe('SYN');
+ expect(room.state.coinImage).toBe('https://cdn.example/syn.png');
+ });
+
+ it('strips control characters and caps length from the record', async () => {
+ vi.stubGlobal(
+ 'fetch',
+ vi.fn(async () => ({ ok: true, json: async () => ({ name: `Bad\u0007Name${'x'.repeat(100)}`, symbol: 'S\nY' }) })),
+ );
+ const room = makeRoom();
+ await room._resolveCoinCreator();
+ expect(room.state.coinName).not.toMatch(/[\u0000-\u001f]/);
+ expect(room.state.coinName.length).toBeLessThanOrEqual(48);
+ expect(room.state.coinSymbol).toBe('S Y');
+ });
+
+ it('leaves the identity blank when the record cannot be fetched', async () => {
+ vi.stubGlobal('fetch', vi.fn(async () => ({ ok: false })));
+ const room = makeRoom();
+ await room._resolveCoinCreator();
+ expect(room.state.coinName).toBe('');
+ });
+});
diff --git a/workers/agent-crawler/guard.js b/workers/agent-crawler/guard.js
index 3b9595103..15031adb8 100644
--- a/workers/agent-crawler/guard.js
+++ b/workers/agent-crawler/guard.js
@@ -55,13 +55,26 @@ export async function guardHost(hostname) {
}
// fetch() for the crawler's own side requests (robots.txt, search reseeds),
-// with the same host fence and a hard timeout.
+// with the same host fence and a hard timeout. Redirects are followed by hand so
+// every hop's host passes guardHost before we connect to it; following them
+// natively would only have checked the first URL.
+const MAX_REDIRECTS = 5;
+
export async function guardedFetch(url, { timeoutMs = 8000, headers = {} } = {}) {
- const u = new URL(url);
- if (!(await guardHost(u.hostname))) throw new Error(`refused private host ${u.hostname}`);
- return fetch(u, {
- headers: { 'user-agent': USER_AGENT, accept: '*/*', ...headers },
- redirect: 'follow',
- signal: AbortSignal.timeout(timeoutMs),
- });
+ const signal = AbortSignal.timeout(timeoutMs);
+ let u = new URL(url);
+ for (let hops = 0; ; hops++) {
+ if (u.protocol !== 'http:' && u.protocol !== 'https:') throw new Error(`refused scheme ${u.protocol}`);
+ if (!(await guardHost(u.hostname))) throw new Error(`refused private host ${u.hostname}`);
+ const res = await fetch(u, {
+ headers: { 'user-agent': USER_AGENT, accept: '*/*', ...headers },
+ redirect: 'manual',
+ signal,
+ });
+ const location = res.status >= 300 && res.status < 400 ? res.headers.get('location') : null;
+ if (!location) return res;
+ await res.body?.cancel().catch(() => {});
+ if (hops >= MAX_REDIRECTS) throw new Error('too many redirects');
+ u = new URL(location, u);
+ }
}
diff --git a/x402-payment-modal/src/index.js b/x402-payment-modal/src/index.js
index 1f79df5ad..360a91f32 100644
--- a/x402-payment-modal/src/index.js
+++ b/x402-payment-modal/src/index.js
@@ -248,6 +248,28 @@ function explorerUrl(net, tx) {
return meta ? `${meta.explorer}${tx}` : null;
}
+// ─────────────────────────────────────────────── receipt tx row ──────────
+// The settlement response (X-PAYMENT-RESPONSE) is supplied by the merchant, so
+// the transaction id is untrusted: it is validated against the two id shapes the
+// modal can pay on and HTML-escaped before it goes anywhere near innerHTML.
+// Solana signature (base58, 64 bytes encodes to 85-90 chars) or EVM tx hash.
+const SOLANA_SIG = /^[1-9A-HJ-NP-Za-km-z]{64,100}$/;
+const EVM_HASH = /^0x[0-9a-fA-F]{64}$/;
+
+export function isTxId(tx) {
+ return typeof tx === 'string' && (SOLANA_SIG.test(tx) || EVM_HASH.test(tx));
+}
+
+export function receiptTxRowHtml(transaction, explorer) {
+ if (typeof transaction !== 'string' || !transaction) return '';
+ const short = transaction.length > 14 ? `${transaction.slice(0, 8)}…${transaction.slice(-6)}` : transaction;
+ const linkable = isTxId(transaction) && typeof explorer === 'string' && /^https:\/\//.test(explorer);
+ const value = linkable
+ ? `<a href="${escapeHtml(explorer)}" target="_blank" rel="noopener">${escapeHtml(short)} ↗</a>`
+ : escapeHtml(short);
+ return `<div class="x402-receipt-row"><span class="x402-k">tx</span><span class="x402-v">${value}</span></div>`;
+}
+
function formatAmount(rawAtomics, decimals = 6) {
const n = Number(rawAtomics) / 10 ** decimals;
if (n < 0.01) return n.toFixed(6).replace(/0+$/, '').replace(/\.$/, '');
@@ -1391,8 +1413,7 @@ class CheckoutModal {
</div>
`;
} else {
- const explorer = explorerUrl(payment?.network, payment?.transaction);
- const txShort = payment?.transaction ? `${payment.transaction.slice(0, 8)}…${payment.transaction.slice(-6)}` : '—';
+ const explorer = isTxId(payment?.transaction) ? explorerUrl(payment?.network, payment.transaction) : null;
receiptHtml = `
<div class="x402-receipt">
<div class="x402-receipt-check">${ICONS.check}</div>
@@ -1405,13 +1426,7 @@ class CheckoutModal {
<span class="x402-k">payer</span>
<span class="x402-v">${escapeHtml(payment?.payer ? `${payment.payer.slice(0, 8)}…${payment.payer.slice(-6)}` : '—')}</span>
</div>
- ${
- payment?.transaction
- ? `<div class="x402-receipt-row"><span class="x402-k">tx</span><span class="x402-v">${
- explorer ? `<a href="${explorer}" target="_blank" rel="noopener">${txShort} ↗</a>` : txShort
- }</span></div>`
- : ''
- }
+ ${receiptTxRowHtml(payment?.transaction, explorer)}
</div>
`;
}
diff --git a/x402-payment-modal/test/client.test.js b/x402-payment-modal/test/client.test.js
index 421893327..ab5d7fb88 100644
--- a/x402-payment-modal/test/client.test.js
+++ b/x402-payment-modal/test/client.test.js
@@ -169,3 +169,30 @@ test('a real 402 challenge drives the modal to its price in a browser', async (t
await new Promise((resolve) => server.close(resolve));
}
});
+
+// The X-PAYMENT-RESPONSE header is merchant-controlled. Its `transaction` field
+// reaches the receipt's innerHTML, so it must be validated as a transaction id
+// and escaped; a quote in it must never be able to break out of the href.
+test('the receipt tx row refuses and escapes a hostile transaction string', async () => {
+ const { receiptTxRowHtml, isTxId } = await import('../src/index.js');
+ const evil = 'x" onmouseover="alert(1)" data-x="';
+ assert.equal(isTxId(evil), false);
+ const explorer = `https://solscan.io/tx/${evil}`;
+ const html = receiptTxRowHtml(evil, explorer);
+ assert.ok(!html.includes('onmouseover="'), 'attribute breakout must not survive');
+ assert.ok(!html.includes('<a '), 'no link for an invalid transaction id');
+ assert.ok(!html.includes('"alert'), html);
+ const tag = receiptTxRowHtml('<img src=x onerror=alert(1)>', null);
+ assert.ok(!tag.includes('<img'), 'markup in the id must be escaped');
+});
+
+test('the receipt tx row links a well-formed Solana signature and EVM hash', async () => {
+ const { receiptTxRowHtml, isTxId } = await import('../src/index.js');
+ const sig = '5'.repeat(88);
+ const evmHash = `0x${'ab'.repeat(32)}`;
+ assert.ok(isTxId(sig));
+ assert.ok(isTxId(evmHash));
+ assert.match(receiptTxRowHtml(sig, `https://solscan.io/tx/${sig}`), /<a href="https:\/\/solscan\.io\/tx\/5{88}"/);
+ assert.match(receiptTxRowHtml(evmHash, `https://basescan.org/tx/${evmHash}`), /<a href="https:\/\/basescan\.org\/tx\/0x/);
+ assert.equal(receiptTxRowHtml('', null), '');
+});