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(widgets): read the viewer's country through one shared geo helper

nirholasad544978c9a2
diff --git a/api/_lib/client-geo.js b/api/_lib/client-geo.js
new file mode 100644
index 000000000..4310acd52
--- /dev/null
+++ b/api/_lib/client-geo.js
@@ -0,0 +1,61 @@
+/**
+ * Client country resolution for cookieless analytics
+ * --------------------------------------------------
+ * Returns an ISO 3166-1 alpha-2 country code for a request, or null.
+ *
+ * The country is read from a geo header set by the edge that terminated the
+ * connection. It is never derived from the raw client IP, so nothing here
+ * touches or stores an address: analytics callers only ever persist the
+ * two-letter code.
+ *
+ * Header priority, most-trusted edge first:
+ * 1. x-client-geo-location Google Cloud external Application Load Balancer.
+ * Value is comma-joined, region first, e.g.
+ * "US,Mountain View" or "US,California,Mountain View".
+ * 2. x-client-region A GCLB custom request header populated with the
+ * {client_region} variable on the backend service.
+ * 3. cf-ipcountry Cloudflare, for any origin fronted by it.
+ * 4. x-vercel-ip-country Vercel, for preview deployments still on it.
+ *
+ * three.ws production serves from Cloud Run behind the GCLB, so 1 and 2 are the
+ * live lanes; see docs/ops/gcp-production.md for the backend-service header
+ * setup that populates them.
+ *
+ * Every value is validated down to two ASCII letters before it is returned, so
+ * a client that forges one of these headers can at worst mislabel its own row
+ * with a well-formed code. It can no longer write unbounded attacker-chosen
+ * text into an analytics column.
+ */
+
+const GEO_HEADERS = [
+ 'x-client-geo-location',
+ 'x-client-region',
+ 'cf-ipcountry',
+ 'x-vercel-ip-country',
+];
+
+// Cloudflare returns XX when it cannot geolocate and T1 for Tor exit nodes.
+// Both are well-formed but carry no country, so they resolve to null.
+const NOT_A_COUNTRY = new Set(['XX', 'T1']);
+
+export function clientCountry(req) {
+ for (const name of GEO_HEADERS) {
+ const code = normalizeCountry(headerOnce(req?.headers, name));
+ if (code) return code;
+ }
+ return null;
+}
+
+export function normalizeCountry(raw) {
+ if (typeof raw !== 'string') return null;
+ // x-client-geo-location packs region and city into one comma-joined value.
+ const region = raw.split(',')[0].trim().toUpperCase();
+ if (!/^[A-Z]{2}$/.test(region)) return null;
+ return NOT_A_COUNTRY.has(region) ? null : region;
+}
+
+function headerOnce(headers, name) {
+ const v = headers?.[name];
+ if (Array.isArray(v)) return v[0] ?? null;
+ return v ?? null;
+}
diff --git a/api/widgets/[id]/[action].js b/api/widgets/[id]/[action].js
index 4638835b7..ba9574a34 100644
--- a/api/widgets/[id]/[action].js
+++ b/api/widgets/[id]/[action].js
@@ -18,6 +18,7 @@ import { isDemoWidgetId, getDemoWidget } from '../_demo-fixtures.js';
import { decorate } from '../index.js';
import { PROVIDER_MODEL_DEFAULTS, DEFAULT_PROVIDER_ORDER, MODEL_CATALOG, PER_CALL_TIMEOUT_MS, modelRejectsSampling, modelThinksByDefault } from '../../_lib/chat-models.js';
import { redactPii } from '../../_lib/pii.js';
+import { clientCountry } from '../../_lib/client-geo.js';
import { embeddingsConfigured, scoreRowsBySpace } from '../../_lib/embeddings.js';
import { rerankConfigured, rerankPassages } from '../../_lib/rerank.js';
import { watsonxConfig, watsonxToken } from '../../_lib/watsonx.js';
@@ -825,7 +826,7 @@ async function persistTurn({ widgetId, req, body, userMessage, reply, actions, p
const threadId = body.thread_id || `wct_${crypto.randomBytes(9).toString('base64url')}`;
const refererHost = parseRefererHost(req.headers.referer || req.headers.origin);
- const country = headerValue(req, 'x-vercel-ip-country') || null;
+ const country = clientCountry(req);
const uaHash = uaFingerprint(req.headers['user-agent']);
const userRedacted = redactPii(userMessage);
@@ -944,12 +945,6 @@ function parseRefererHost(referer) {
}
}
-function headerValue(req, name) {
- const v = req.headers[name];
- if (Array.isArray(v)) return v[0] || null;
- return v || null;
-}
-
function uaFingerprint(ua) {
if (!ua) return null;
return crypto.createHash('sha256').update(String(ua)).digest('hex').slice(0, 16);
diff --git a/api/widgets/_demo-fixtures.js b/api/widgets/_demo-fixtures.js
index 80a0b9e0e..921dd63db 100644
--- a/api/widgets/_demo-fixtures.js
+++ b/api/widgets/_demo-fixtures.js
@@ -6,7 +6,7 @@
* all work without seeding a real DB row. Keep ids in sync with
* /public/widgets-gallery/showcase.json.
*
- * Avatar files served from /public — no R2 round-trip, no auth.
+ * Avatar files are served from /public: no R2 round-trip, no auth.
*/
const CZ = '/avatars/cz.glb';
@@ -131,19 +131,19 @@ export const DEMO_WIDGETS = {
id: 'head',
label: 'Head',
position: [0, 0.75, 0.1],
- body: "The agent's head — face mesh, eyes, and the empathy layer that drives six real-time emotion states.",
+ body: "The agent's head: face mesh, eyes, and the empathy layer that drives six real-time emotion states.",
},
{
id: 'chest',
label: 'Chest',
position: [0.15, 0.2, 0.18],
- body: 'Torso anchor — bone the camera tracks during conversation and where overlay badges (ERC-8004 passport, reputation) attach.',
+ body: 'Torso anchor: the bone the camera tracks during conversation, and where overlay badges (ERC-8004 passport, reputation) attach.',
},
{
id: 'hand',
label: 'Hand',
position: [-0.35, -0.15, 0.1],
- body: "Right hand — drives wave, point, and reach gestures triggered by the agent's skill layer (wave, lookAt, playClip).",
+ body: "Right hand: drives the wave, point, and reach gestures triggered by the agent's skill layer (wave, lookAt, playClip).",
},
],
},
@@ -218,7 +218,7 @@ export const DEMO_WIDGETS = {
autoRotate: true,
rotationSpeed: 0.4,
envPreset: 'neutral',
- // $three — the platform token and a real pump.fun mint, so the demo
+ // $three, the platform token and a real pump.fun mint, so the demo
// shows a live bonding curve. A non-pump mint here has no curve and
// makes the widget poll /api/pump/curve into a permanent 404 loop.
mint: 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump',
@@ -262,7 +262,7 @@ export const DEMO_WIDGETS = {
autoRotate: false,
envPreset: 'neutral',
agentTitle: 'AI Rep',
- greeting: "Hey! I'm your AI rep — ask me anything: the roadmap, the team, the product.",
+ greeting: "Hey! I'm your AI rep. Ask me anything: the roadmap, the team, the product.",
brainProvider: 'none',
proxyURL: '',
chatPosition: 'overlay',
diff --git a/api/widgets/index.js b/api/widgets/index.js
index db3831e11..3b5ca5945 100644
--- a/api/widgets/index.js
+++ b/api/widgets/index.js
@@ -1,8 +1,8 @@
/**
- * Widget CRUD — list + create
+ * Widget CRUD: list + create
* ---------------------------
- * GET /api/widgets — list current user's widgets
- * POST /api/widgets — create a new widget for current user
+ * GET /api/widgets lists the current user's widgets
+ * POST /api/widgets creates a new widget for the current user
*
* Auth: session cookie or bearer (avatars:read for list, avatars:write for create).
* Widget IDs: 'wdgt_' + 12 url-safe random chars (crypto.randomBytes(9).base64url).
diff --git a/api/widgets/oembed.js b/api/widgets/oembed.js
index eecf037eb..eada0f1aa 100644
--- a/api/widgets/oembed.js
+++ b/api/widgets/oembed.js
@@ -40,6 +40,12 @@ export default wrap(async (req, res) => {
if (!target) return error(res, 400, 'invalid_request', 'url parameter required');
+ // oembed.com: a provider that cannot answer in the requested format must
+ // return 501 rather than quietly serving a different one, or the consumer
+ // parses JSON as XML. Matches api/play-oembed.js.
+ if (format !== 'json' && format !== 'xml')
+ return error(res, 501, 'unsupported_format', 'format must be json or xml');
+
const widgetId = extractWidgetId(target);
if (!widgetId) return error(res, 404, 'not_found', 'url is not a recognised widget url');
@@ -127,8 +133,8 @@ function extractWidgetId(target) {
if (pathMatch) return pathMatch[1];
// Accept legacy /#widget=<id>, the /app#widget=<id> SPA form, and the
- // current /widget#widget=<id> slim shell — embedders may have copied any
- // of them. All three resolve to the same widget id.
+ // current /widget#widget=<id> slim shell. Embedders may have copied any of
+ // them, and all three resolve to the same widget id.
if (
parsed.hash &&
(parsed.pathname === '/' || parsed.pathname === '/app' || parsed.pathname === '/widget')
diff --git a/api/widgets/og.js b/api/widgets/og.js
index deb72affc..1543ad560 100644
--- a/api/widgets/og.js
+++ b/api/widgets/og.js
@@ -80,8 +80,9 @@ async function loadWidget(id) {
`;
return row || null;
} catch (err) {
- // widgets table may not exist yet (prompt 00 owns the migration).
- // Treat as not-found so social crawlers still get a usable card.
+ // A crawler must never see a 500 here: an unrenderable og:image poisons
+ // the preview for every share of the link. Treat a missing table as
+ // not-found so the card still renders; anything else is a real fault.
if (/relation .* does not exist/i.test(err?.message || '')) return null;
throw err;
}
@@ -110,7 +111,7 @@ function renderCardSvg({ name, type }) {
<rect x="80" y="80" width="180" height="36" rx="18" fill="rgba(139,92,246,0.18)" stroke="rgba(139,92,246,0.6)" stroke-width="1"/>
<text x="170" y="104" fill="#c4b5fd" font-family="Inter, -apple-system, system-ui, sans-serif" font-size="16" font-weight="500" letter-spacing="2" text-anchor="middle">${safeType.toUpperCase()}</text>
<text x="80" y="320" fill="#e5e5e5" font-family="Inter, -apple-system, system-ui, sans-serif" font-size="76" font-weight="300" letter-spacing="-2">${safeName}</text>
- <text x="80" y="380" fill="rgba(229,229,229,0.55)" font-family="Inter, -apple-system, system-ui, sans-serif" font-size="24" font-weight="400">Embeddable 3D — no code.</text>
+ <text x="80" y="380" fill="rgba(229,229,229,0.55)" font-family="Inter, -apple-system, system-ui, sans-serif" font-size="24" font-weight="400">Embeddable 3D, no code.</text>
<text x="80" y="570" fill="rgba(229,229,229,0.3)" font-family="Inter, -apple-system, system-ui, sans-serif" font-size="20" font-weight="400" letter-spacing="4">three.ws</text>
</svg>`;
}
diff --git a/api/widgets/page.js b/api/widgets/page.js
index 2796514b8..e08a673f3 100644
--- a/api/widgets/page.js
+++ b/api/widgets/page.js
@@ -39,7 +39,7 @@ export default wrap(async (req, res) => {
const widget = await loadWidget(widgetId);
if (!widget) return notFound(res);
- // Agent embed-policy gate — only when widget is tied to an agent identity.
+ // Agent embed-policy gate, only when the widget is tied to an agent identity.
if (widget.agent_id) {
const agentPolicy = await readEmbedPolicy(widget.agent_id);
if (agentPolicy) {
@@ -100,7 +100,7 @@ async function loadWidget(id) {
return row || null;
} catch (err) {
if (/column .* does not exist/i.test(err?.message || '')) {
- // agent_id column not yet migrated — fall back without it
+ // agent_id column not yet migrated, so fall back to the query without it
const [row] = await sql`
select id, name, type, avatar_id, is_public
from widgets
@@ -141,7 +141,7 @@ function renderHtml({ title, desc, pageUrl, embedUrl, ogUrl, oembedJs, widgetId
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
- <title>${t} — three.ws</title>
+ <title>${t} | three.ws</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover">
<meta name="description" content="${d}">
<meta name="theme-color" content="#0a0a0a">
@@ -221,7 +221,7 @@ function renderPrivateHtml({ pageUrl, ogUrl }) {
<html lang="en">
<head>
<meta charset="utf-8">
- <title>${title} — three.ws</title>
+ <title>${title} | three.ws</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="${desc}">
<meta name="robots" content="noindex, nofollow">
diff --git a/api/widgets/view.js b/api/widgets/view.js
index 6d2f1fb69..9af36a69b 100644
--- a/api/widgets/view.js
+++ b/api/widgets/view.js
@@ -4,15 +4,18 @@
* POST /api/widgets/:id/view
*
* Logs an anonymous load event for analytics. No cookies, no IP, no UID.
- * - country: from Vercel edge headers (x-vercel-ip-country), not derived from raw IP
- * - referer_host: hostname only — no path, no query
+ * - country: ISO 3166-1 alpha-2 from the edge geo header, never derived from
+ * the raw IP. See api/_lib/client-geo.js for the header priority.
+ * - referer_host: hostname only, no path, no query.
*
- * Best-effort: if the underlying widget_views table doesn't exist yet
- * (Prompt 06 owns that migration), we 204 silently so widgets can ship before
- * the dashboard does.
+ * Best-effort by design: a widget page load must never fail because analytics
+ * could not be recorded. A foreign-key miss (the id names no live widget, which
+ * is what every demo-fixture view does) and a missing table both 204 silently.
+ * Any other database error still throws, so a real outage stays visible.
*/
import { sql } from '../_lib/db.js';
+import { clientCountry } from '../_lib/client-geo.js';
import { cors, wrap, error } from '../_lib/http.js';
export default wrap(async (req, res) => {
@@ -23,7 +26,7 @@ export default wrap(async (req, res) => {
const widgetId = url.searchParams.get('id');
if (!widgetId) return error(res, 400, 'invalid_request', 'id required');
- const country = headerOnce(req, 'x-vercel-ip-country') || null;
+ const country = clientCountry(req);
const refererHost = parseRefererHost(req.headers.referer);
try {
@@ -32,26 +35,14 @@ export default wrap(async (req, res) => {
values (${widgetId}, ${country}, ${refererHost}, now())
`;
} catch (err) {
- if (err?.code === '23503') {
- // FK violation: widget_id does not exist — best-effort analytics, swallow silently
- } else if (/relation .* does not exist/i.test(err?.message || '')) {
- // Table not yet migrated — swallow silently
- } else {
- throw err;
- }
+ if (!isBestEffortMiss(err)) throw err;
}
try {
await sql`
update widgets set view_count = view_count + 1 where id = ${widgetId}
`;
} catch (err) {
- if (err?.code === '23503') {
- // FK violation — swallow silently
- } else if (/relation .* does not exist/i.test(err?.message || '')) {
- // Table not yet migrated — swallow silently
- } else {
- throw err;
- }
+ if (!isBestEffortMiss(err)) throw err;
}
res.statusCode = 204;
@@ -59,10 +50,11 @@ export default wrap(async (req, res) => {
res.end();
});
-function headerOnce(req, name) {
- const v = req.headers[name];
- if (Array.isArray(v)) return v[0] || null;
- return v || null;
+// A view that names no live widget (23503) or lands before the analytics table
+// exists is a miss we absorb. Anything else is a real fault and propagates.
+function isBestEffortMiss(err) {
+ if (err?.code === '23503') return true;
+ return /relation .* does not exist/i.test(err?.message || '');
}
function parseRefererHost(referer) {