Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
fix(watch): make the watch-wanted worker secret a testable seam and show the real API error in the panel
nirholas0edd03f65a5d
diff --git a/api/agent/watch-wanted.js b/api/agent/watch-wanted.jsindex edd471da0..c9ad87ffa 100644--- a/api/agent/watch-wanted.js+++ b/api/agent/watch-wanted.js@@ -1,4 +1,4 @@-// GET /api/agent/watch-wanted → { agents: [{ agentId, name, lastSeen }], ts }+// GET /api/agent/watch-wanted -> { agents: [{ agentId, name, homeUrl }], ts }//// Read side of the on-demand caster pool. The pool worker polls this to learn// which agents viewers are currently watching, then maintains a bounded pool of@@ -6,7 +6,7 @@// workers/agent-screen-pool). Agents fall out of the window automatically once// nobody is watching, so the worker can tear their browsers down.//-// Auth: the shared first-party worker secret (SCREEN_WORKER_SECRET) — the same+// Auth: the shared first-party worker secret (SCREEN_WORKER_SECRET), the same// secret the worker uses to push frames for any agent. Without it configured the// endpoint reports the pool as disabled rather than leaking the watch set.@@ -15,32 +15,50 @@ import { cors, json, method, error, wrap } from '../_lib/http.js';import { getRedis } from '../_lib/redis.js';import { sql } from '../_lib/db.js';import { extractBearer } from '../_lib/auth.js';+import { isUuid } from '../_lib/validate.js';const WANTED_KEY = 'screen:wanted';const WINDOW_MS = 90_000; // agents wanted within the last 90s are "live-watched"const MAX_AGENTS = 48; // hard cap returned to the worker-const WORKER_SECRET = process.env.SCREEN_WORKER_SECRET || '';-function isPoolWorker(bearer) {- if (!bearer || !WORKER_SECRET || WORKER_SECRET.length < 16) return false;+// A secret shorter than this is treated as absent: a stray one-character value+// in the env would otherwise be a trivially guessable key to the whole watch set.+export const MIN_SECRET_LEN = 16;++// Pure auth seam (unit-tested): constant-time compare of the presented bearer+// against the configured worker secret. Takes the secret as an argument so the+// decision can be exercised without reaching into module-scope env state.+export function isPoolWorker(bearer, secret) {+ if (!bearer || !secret || secret.length < MIN_SECRET_LEN) return false;const a = Buffer.from(bearer);- const b = Buffer.from(WORKER_SECRET);+ const b = Buffer.from(secret);return a.length === b.length && timingSafeEqual(a, b);}+// Read at call time rather than at module load, so rotating the secret takes+// effect on the next request instead of on the next cold start.+function workerSecret() {+ return process.env.SCREEN_WORKER_SECRET || '';+}++// The watch set changes every few seconds and is worker-private: no cache layer+// between here and the pool should ever hold a copy of it.+const NO_STORE = { 'cache-control': 'no-store' };+export default wrap(async (req, res) => {if (cors(req, res, { methods: 'GET,OPTIONS' })) return;if (!method(req, res, ['GET'])) return;- if (!WORKER_SECRET || WORKER_SECRET.length < 16) {- return json(res, 200, { agents: [], disabled: true, reason: 'SCREEN_WORKER_SECRET not configured' });+ const secret = workerSecret();+ if (secret.length < MIN_SECRET_LEN) {+ return json(res, 200, { agents: [], disabled: true, reason: 'SCREEN_WORKER_SECRET not configured' }, NO_STORE);}- if (!isPoolWorker(extractBearer(req))) {+ if (!isPoolWorker(extractBearer(req), secret)) {return error(res, 401, 'unauthorized', 'pool worker secret required');}const r = getRedis();- if (!r) return json(res, 200, { agents: [], ts: Date.now() });+ if (!r) return json(res, 200, { agents: [], ts: Date.now() }, NO_STORE);const now = Date.now();let ids = [];@@ -52,35 +70,46 @@ export default wrap(async (req, res) => {offset: 0,count: MAX_AGENTS,});- ids = Array.isArray(raw) ? raw.slice(0, MAX_AGENTS) : [];+ // agent_identities.id is a uuid column, and the set is keyed by whatever a+ // writer put there. One malformed member would make the batch lookup below+ // throw 22P02 and blind the pool to every other agent, so drop it here.+ ids = (Array.isArray(raw) ? raw : []).filter((id) => typeof id === 'string' && isUuid(id)).slice(0, MAX_AGENTS);} catch {- return json(res, 200, { agents: [], ts: now });+ return json(res, 200, { agents: [], ts: now }, NO_STORE);}- if (!ids.length) return json(res, 200, { agents: [], ts: now });+ if (!ids.length) return json(res, 200, { agents: [], ts: now }, NO_STORE);// Resolve names + a coin-agnostic home so the worker knows where to point the// browser for each agent (its profile by default).let rows = [];+ let resolved = true;try {rows = await sql`SELECT id, name, home_urlFROM agent_identitiesWHERE id = ANY(${ids}) AND deleted_at IS NULL`;- } catch { /* fall through with ids only */ }+ } catch {+ // A DB blip must not read as "every watched agent was deleted": that would+ // hand the pool an empty set and tear down every live browser. Remember the+ // lookup failed and fall back to id-only entries below.+ resolved = false;+ }const byId = new Map(rows.map((x) => [x.id, x]));const agents = ids- .filter((id) => byId.has(id))+ // When the lookup succeeded, an id with no row is a deleted agent and is+ // correctly dropped. When it failed, nothing was resolved, so keep them all.+ .filter((id) => !resolved || byId.has(id)).map((id) => {const a = byId.get(id);return {agentId: id,- name: a.name || 'Agent',- homeUrl: a.home_url || `/agent/${id}`,+ name: a?.name || 'Agent',+ homeUrl: a?.home_url || `/agent/${id}`,};});- return json(res, 200, { agents, ts: now }, { 'cache-control': 'no-store' });+ return json(res, 200, { agents, ts: now }, NO_STORE);});diff --git a/src/shared/agent-watch-panel.js b/src/shared/agent-watch-panel.jsindex f9d448820..fdca7b93a 100644--- a/src/shared/agent-watch-panel.js+++ b/src/shared/agent-watch-panel.js@@ -23,6 +23,7 @@ import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';import { getMeshoptDecoder } from '../viewer/internal.js';import { clone as cloneSkinnedScene } from 'three/addons/utils/SkeletonUtils.js';import { applyCinematicDefaults, detectQualityTier, loadEnvironment } from './cinematic-render.js';+import { consumeCsrfToken } from '../api.js';// Top-level endpoint — this is the real-time frame+log SSE stream.const STREAM_URL = (id) => `/api/agent-screen-stream?agentId=${encodeURIComponent(id)}`;@@ -912,15 +913,23 @@ class WatchPanel {btn.disabled = true;btn.classList.add('loading');try {+ // Single-use CSRF token, burned by this request: fetch a fresh one per+ // mint rather than caching, so two panels open at once can't race.+ const csrf = await consumeCsrfToken().catch(() => null);+ const headers = { 'Content-Type': 'application/json' };+ if (csrf) headers['x-csrf-token'] = csrf;const res = await fetch(SESSION_URL(), {method: 'POST',credentials: 'include',- headers: { 'Content-Type': 'application/json' },+ headers,body: JSON.stringify({ agentId: this.agentId }),});if (!res.ok) {+ // The API error envelope is { error, error_description }; reading only+ // `message` reduced every failure to a bare "HTTP 401" with no hint that+ // signing in (or owning the agent) was the missing piece.const err = await res.json().catch(() => ({}));- throw new Error(err.message || `HTTP ${res.status}`);+ throw new Error(err.error_description || err.message || `HTTP ${res.status}`);}const data = await res.json();this._showSessionModal(data);