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): stop the we-pay embed brain from serving callers that omit Origin

nirholasc1e600a0420c
diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md
index 9c1069f67..05b9392bc 100644
--- a/ARCHITECTURE.md
+++ b/ARCHITECTURE.md
@@ -600,7 +600,7 @@ Representative endpoints:
|----------|-------------|
| `POST /api/brain/chat` | Multi-provider LLM playground (20+ models, SSE streaming) |
| `POST /api/chat` | Avatar chat endpoint: memory recall, tool dispatch, Guardian governance |
-| `POST /api/llm/anthropic` | We-pay proxy for Anthropic Claude (embed contexts, free tier) |
+| `POST /api/llm/anthropic` | We-pay proxy for Anthropic Claude (embed contexts, free tier). Scoped to the agent's allowlisted embed origins; header-less callers must authenticate, and host-billed models run only when the owner's policy selects one |
**Provider failover in `/api/chat`:** Groq → OpenRouter → NVIDIA NIM → SambaNova → Mistral → Z.AI → Anthropic → OpenAI → watsonx/Orchestrate (plus the Vertex Gemini anchor appended at the tail)
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 5d0b8972a..e9e44490f 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr
## 2026-08-07
- **The chat no longer refuses questions it was never asked to refuse**: Every message sent to a three.ws chat surface used to pass through a small safety classifier of ours before the actual model saw it, and when that classifier said "unsafe" you got a canned brush-off instead of an answer. It was wrong often enough to be a real problem: it judged one message at a time with no memory of the conversation, so an ordinary follow-up in a security, trading, or fiction discussion could read as alarming on its own and get blocked, and you were left staring at a refusal no model had actually made. That layer is gone from all of it: the main chat, the /chat app, the embeddable concierge, the widget chat on customer sites, and the agent-idea box on /create. Your question now goes to the model as written. If a model declines something, that is the model exercising its own judgment in its own words, and you can switch models or bring your own key. Nothing else changed: the same rate limits still apply, and the separate confirmation step before any wallet action is untouched. The one place a content check still runs is outbound: what our own official Sketchfab account publishes under the three.ws name. (`/chat`) `[improvement, fix]`
+- **The embedded avatar brain is now scoped to the sites it was meant for**: Every agent and avatar embed can chat for free because the platform pays for the model behind it, and the agent owner decides which sites may run that embed and which model it uses. Both of those controls only really applied to browsers: a request that simply left out the header a browser always sends slipped past the site allowlist entirely, and any caller could ask for a pricier model than the owner had chosen. Both are closed. A request with no site header now has to sign in (a session or an API key) instead of riding on an agent id anyone could read off our public sitemap, and a model that bills our own provider keys runs only when the owner selected it in the dashboard. There is also a new platform-wide ceiling across all of this traffic combined, so no amount of spreading requests around can drain the shared budget. Nothing changes for a normal embed on an allowlisted site. (`/docs/api-reference`) `[security, fix]`
## 2026-08-06
diff --git a/README.md b/README.md
index b5a216788..b865281e4 100644
--- a/README.md
+++ b/README.md
@@ -9965,7 +9965,7 @@ The full OpenAPI 3.1 spec is available at `/openapi.json`. The key API surface i
| Method | Route | Auth | Description |
| ------ | -------------------- | ------------------ | -------------------------------- |
| POST | `/api/chat` | session \| api-key | Chat with agent (Claude backend) |
-| POST | `/api/llm/anthropic` | session | Anthropic API proxy |
+| POST | `/api/llm/anthropic` | allowlisted embed origin \| session \| api-key | Anthropic API proxy |
### Cron Jobs
diff --git a/api/_lib/rate-limit.js b/api/_lib/rate-limit.js
index 551fcabd8..0d193beae 100644
--- a/api/_lib/rate-limit.js
+++ b/api/_lib/rate-limit.js
@@ -1271,7 +1271,10 @@ export const limits = {
window: '1 m',
}).limit(`${widgetId}:${ip}`),
// We-pay LLM proxy: 60 req/min per IP (global floor), and per-agent dynamic bucket.
- embedLlmIp: (ip) => getLimiter('embed:llm:ip', { limit: 60, window: '1 m' }).limit(ip),
+ // Critical: this lane spends the host's own provider keys, so a Redis outage
+ // must degrade to the Postgres-backed counter rather than to no counter at all.
+ embedLlmIp: (ip) =>
+ getLimiter('embed:llm:ip', { limit: 60, window: '1 m', critical: true }).limit(ip),
embedLlmAgent: (agentId, perMin) =>
getLimiter('embed:llm:agent', {
limit: Math.max(1, Math.min(1000, perMin || 10)),
diff --git a/api/llm/anthropic.js b/api/llm/anthropic.js
index 897bc5403..e0b1e0e96 100644
--- a/api/llm/anthropic.js
+++ b/api/llm/anthropic.js
@@ -16,6 +16,7 @@ import { getRedis as _getSharedRedis } from '../_lib/redis.js';
import { cors, error, method, wrap, readJson, json, rateLimited } from '../_lib/http.js';
import { parse } from '../_lib/validate.js';
import { limits, clientIp } from '../_lib/rate-limit.js';
+import { getRequestUser } from '../_lib/auth.js';
import { recordEvent, logger } from '../_lib/usage.js';
import { costMicroUsd } from '../_lib/llm-pricing.js';
import {
@@ -230,8 +231,15 @@ function monthKey() {
return `${now.getUTCFullYear()}-${String(now.getUTCMonth() + 1).padStart(2, '0')}`;
}
+// An embed request that carries no Origin/Referer is not a browser: every
+// browser attaches Origin to the cross-origin JSON POST this proxy serves, and
+// to same-origin POSTs as well. Treating the header's absence as "allowed"
+// made the allowlist advisory: a script that simply omitted the header spent
+// the platform's provider keys against any of the public agent/avatar ids the
+// sitemap publishes. Unknown origins are denied here; the handler re-admits a
+// header-less caller only when it authenticates as a real platform user.
function originAllowed(originHeader, policy) {
- if (!originHeader) return true;
+ if (!originHeader) return false;
let host;
try {
host = new URL(originHeader).hostname.toLowerCase();
@@ -249,6 +257,38 @@ function originAllowed(originHeader, policy) {
return mode === 'allowlist' ? matches : !matches;
}
+// Identity for a caller that sent no Origin. Cookie session or bearer API key
+// both count; an auth backend hiccup resolves to "anonymous", which fails the
+// gate closed rather than reopening it.
+async function machineCaller(req) {
+ try {
+ return (await getRequestUser(req)) || null;
+ } catch {
+ return null;
+ }
+}
+
+// Models billed to the host's own vendor keys. A caller may pick freely among
+// the free lanes, but escalating to one of these is the agent owner's decision
+// (policy.brain.model, set from the dashboard), never the embed visitor's.
+const PAID_HOST_KEY_MODELS = new Set(
+ Object.entries(MODELS)
+ .filter(([, route]) => route.kind === 'anthropic' || route.provider === 'grok')
+ .map(([id]) => id),
+);
+
+const FREE_DEFAULT_MODEL = 'openai/gpt-oss-20b:free';
+
+// Resolve the model to run: the caller's choice when it costs the host nothing
+// or matches what the owner configured, otherwise the policy's own model. The
+// response echoes the model actually used, so a clamped caller sees what it got.
+function resolveRequestedModel(requested, policyModel) {
+ const configured = policyModel || FREE_DEFAULT_MODEL;
+ if (!requested || requested === configured) return configured;
+ if (PAID_HOST_KEY_MODELS.has(requested)) return configured;
+ return requested;
+}
+
function buildCorsAllowlist(policy) {
const out = new Set();
if (env.APP_ORIGIN) out.add(env.APP_ORIGIN);
@@ -428,17 +468,35 @@ export default wrap(async (req, res) => {
const originHeader = req.headers.origin || req.headers.referer || '';
if (!originAllowed(originHeader, policy)) {
- return error(
- res,
- 403,
- 'embed_denied_origin',
- "origin not permitted by this agent's embed policy",
- );
+ // A header-less (non-browser) caller is not rejected outright (server-side
+ // integrations and our own smoke checks are legitimate), but it must carry a
+ // platform identity (session cookie or bearer API key) instead of riding an
+ // agent id anyone can read out of the public sitemap.
+ const caller = originHeader ? null : await machineCaller(req);
+ if (!caller) {
+ return error(
+ res,
+ 403,
+ 'embed_denied_origin',
+ originHeader
+ ? "origin not permitted by this agent's embed policy"
+ : 'requests without an Origin must authenticate (session cookie or bearer API key)',
+ );
+ }
}
const ipRl = await limits.embedLlmIp(clientIp(req));
if (!ipRl.success) return rateLimited(res, ipRl, 'too many requests from this IP');
+ // Platform-wide ceiling on inference billed to the host's provider keys. The
+ // per-IP and per-agent buckets above bound one caller against one agent; this
+ // bounds the whole fleet, so rotating IPs across the thousands of public agent
+ // ids can't collectively drain the vendor budget.
+ const hostKeyRl = await limits.chatHostKeyGlobal();
+ if (!hostKeyRl.success) {
+ return rateLimited(res, hostKeyRl, 'the shared embed brain is at capacity, try again shortly');
+ }
+
const perMin = policy.brain?.rate_limit_per_min;
if (perMin && perMin > 0) {
const agentRl = await limits.embedLlmAgent(agentId, perMin);
@@ -462,8 +520,7 @@ export default wrap(async (req, res) => {
const rawBody = await readJson(req);
const body = parse(bodySchema, rawBody);
- const requestedModel =
- body.model || policy.brain?.model || 'openai/gpt-oss-20b:free';
+ const requestedModel = resolveRequestedModel(body.model, policy.brain?.model);
// Ordered fallback chain for 429 / 5xx from OpenRouter free tier:
// 1. Requested model (e.g. llama-3.3-70b:free)
diff --git a/data/changelog.json b/data/changelog.json
index 27db2fd17..26ffd71b2 100644
--- a/data/changelog.json
+++ b/data/changelog.json
@@ -1,6 +1,16 @@
{
"$comment": "Curated changelog entries for three.ws, the editorial layer of the public changelog. New PAGE launches are tracked automatically via the `added` field in data/pages.json; this file is for everything else holders care about: improvements, fixes, SDK releases, trading/payments capabilities, security work. scripts/build-page-index.mjs merges both sources into CHANGELOG.md, public/changelog.json, and public/changelog.xml. Newest first. Allowed tags: feature, improvement, fix, sdk, infra, docs, security. `link` is optional and must be a live three.ws path.",
"entries": [
+ {
+ "date": "2026-08-07",
+ "title": "The embedded avatar brain is now scoped to the sites it was meant for",
+ "summary": "Every agent and avatar embed can chat for free because the platform pays for the model behind it, and the agent owner decides which sites may run that embed and which model it uses. Both of those controls only really applied to browsers: a request that simply left out the header a browser always sends slipped past the site allowlist entirely, and any caller could ask for a pricier model than the owner had chosen. Both are closed. A request with no site header now has to sign in (a session or an API key) instead of riding on an agent id anyone could read off our public sitemap, and a model that bills our own provider keys runs only when the owner selected it in the dashboard. There is also a new platform-wide ceiling across all of this traffic combined, so no amount of spreading requests around can drain the shared budget. Nothing changes for a normal embed on an allowlisted site.",
+ "tags": [
+ "security",
+ "fix"
+ ],
+ "link": "/docs/api-reference"
+ },
{
"date": "2026-08-07",
"title": "The chat no longer refuses questions it was never asked to refuse",
diff --git a/docs/api-reference.md b/docs/api-reference.md
index 77539793a..d8a553fec 100644
--- a/docs/api-reference.md
+++ b/docs/api-reference.md
@@ -609,6 +609,19 @@ POST /api/llm/anthropic?agent=<agent_id>
Older single-provider proxy. Request/response shape matches the [Anthropic Messages API](https://docs.anthropic.com/en/api/messages) exactly. New integrations should use `/api/brain/chat` instead — it supports more providers and emits richer events.
+**Who may call it.** This lane is billed to the platform's own provider keys, so it is scoped to the browser embed it exists for:
+
+| Caller | Result |
+|---|---|
+| Browser on `three.ws` or an origin the agent owner allowlisted | Served |
+| Browser on any other origin | `403 embed_denied_origin` |
+| No `Origin`/`Referer` header (scripts, servers) and no credentials | `403 embed_denied_origin`. Omitting the header is not a way around the allowlist |
+| No `Origin`/`Referer` header, with a session cookie or bearer API key | Served, attributed to that account |
+
+**Model selection.** `model` in the body may switch between free lanes freely. A host-billed model (the Claude and Grok families) runs only when the agent owner selected it in the dashboard, which stores it on the embed policy; any other request for one is served with the policy's configured model instead. The response body reports the model that actually ran.
+
+**Ceilings.** Per-IP and per-agent rate limits, the agent's monthly call quota and token budget, and a platform-wide ceiling across every host-key-billed request combined. A saturated platform ceiling returns `429`.
+
**Request normalisation.** Model generations disagree about which request fields they accept, and sending the wrong one returns a hard `400` from the upstream. Rather than surface that to an embed, the proxy adapts the body to the model it is about to call:
| Field you send | What happens |
diff --git a/public/changelog.json b/public/changelog.json
index a995c76d8..0c99629c2 100644
--- a/public/changelog.json
+++ b/public/changelog.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-08-07T03:41:03.803Z",
+ "generated_at": "2026-08-07T05:45:17.435Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json",
"site": {
"name": "three.ws",
@@ -17,6 +17,17 @@
"fix"
]
},
+ {
+ "date": "2026-08-07",
+ "type": "update",
+ "title": "The embedded avatar brain is now scoped to the sites it was meant for",
+ "summary": "Every agent and avatar embed can chat for free because the platform pays for the model behind it, and the agent owner decides which sites may run that embed and which model it uses. Both of those controls only really applied to browsers: a request that simply left out the header a browser always sends slipped past the site allowlist entirely, and any caller could ask for a pricier model than the owner had chosen. Both are closed. A request with no site header now has to sign in (a session or an API key) instead of riding on an agent id anyone could read off our public sitemap, and a model that bills our own provider keys runs only when the owner selected it in the dashboard. There is also a new platform-wide ceiling across all of this traffic combined, so no amount of spreading requests around can drain the shared budget. Nothing changes for a normal embed on an allowlisted site.",
+ "link": "/docs/api-reference",
+ "tags": [
+ "security",
+ "fix"
+ ]
+ },
{
"date": "2026-08-06",
"type": "launch",
diff --git a/public/changelog.xml b/public/changelog.xml
index 160cf1715..612ec82b5 100644
--- a/public/changelog.xml
+++ b/public/changelog.xml
@@ -14,6 +14,14 @@
<category>improvement</category>
<description>Every message sent to a three.ws chat surface used to pass through a small safety classifier of ours before the actual model saw it, and when that classifier said &quot;unsafe&quot; you got a canned brush-off instead of an answer. It was wrong often enough to be a real problem: it judged one message at a time with no memory of the conversation, so an ordinary follow-up in a security, trading, or fiction discussion could read as alarming on its own and get blocked, and you were left staring at a refusal no model had actually made. That layer is gone from all of it: the main chat, the /chat app, the embeddable concierge, the widget chat on customer sites, and the agent-idea box on /create. Your question now goes to the model as written. If a model declines something, that is the model exercising its own judgment in its own words, and you can switch models or bring your own key. Nothing else changed: the same rate limits still apply, and the separate confirmation step before any wallet action is untouched. The one place a content check still runs is outbound: what our own official Sketchfab account publishes under the three.ws name.</description>
</item>
+ <item>
+ <title>The embedded avatar brain is now scoped to the sites it was meant for</title>
+ <link>https://three.ws/docs/api-reference</link>
+ <guid isPermaLink="false">2026-08-07:The embedded avatar brain is now scoped to the sites it was meant for</guid>
+ <pubDate>Fri, 07 Aug 2026 12:00:00 GMT</pubDate>
+ <category>security</category>
+ <description>Every agent and avatar embed can chat for free because the platform pays for the model behind it, and the agent owner decides which sites may run that embed and which model it uses. Both of those controls only really applied to browsers: a request that simply left out the header a browser always sends slipped past the site allowlist entirely, and any caller could ask for a pricier model than the owner had chosen. Both are closed. A request with no site header now has to sign in (a session or an API key) instead of riding on an agent id anyone could read off our public sitemap, and a model that bills our own provider keys runs only when the owner selected it in the dashboard. There is also a new platform-wide ceiling across all of this traffic combined, so no amount of spreading requests around can drain the shared budget. Nothing changes for a normal embed on an allowlisted site.</description>
+ </item>
<item>
<title>Airdrop Checker</title>
<link>https://three.ws/airdrops</link>
diff --git a/public/features.json b/public/features.json
index 6d92cce50..6c12b010c 100644
--- a/public/features.json
+++ b/public/features.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-08-07T03:41:03.788Z",
+ "generated_at": "2026-08-07T05:45:17.424Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json",
"site": {
"name": "three.ws",
diff --git a/scripts/gcp/vertex-llm-smoke.mjs b/scripts/gcp/vertex-llm-smoke.mjs
index 37129e936..c40ae1970 100644
--- a/scripts/gcp/vertex-llm-smoke.mjs
+++ b/scripts/gcp/vertex-llm-smoke.mjs
@@ -15,7 +15,9 @@
// Optional env:
// BASE_URL — dev server origin (default http://localhost:3000)
// SMOKE_AGENT_ID — a public agent/avatar id to exercise /api/llm/anthropic
-// (the embed proxy). Skipped when unset.
+// (the embed proxy). Skipped when unset. Its embed policy
+// must select a Claude model: the proxy clamps a
+// caller-requested host-billed model back to the owner's.
// SMOKE_BEARER — a bearer token for an authenticated /api/chat call.
// /api/chat gates the Vertex (paid-tier) lane behind auth,
// so anonymous callers only get the free lanes — provide a
@@ -85,7 +87,10 @@ async function surfaceEmbedProxy() {
try {
res = await fetch(`${BASE_URL}/api/llm/anthropic?agent=${encodeURIComponent(AGENT_ID)}`, {
method: 'POST',
- headers: { 'content-type': 'application/json' },
+ // The proxy denies header-less anonymous callers (they bypass the embed
+ // origin allowlist). This is a first-party check, so it presents the
+ // first-party origin a real embed on the site would send.
+ headers: { 'content-type': 'application/json', origin: new URL(BASE_URL).origin },
body: JSON.stringify({
model: 'claude-haiku-4-5-20251001',
max_tokens: 64,
@@ -107,7 +112,12 @@ async function surfaceEmbedProxy() {
const text = await readSomeStream(res, 1500);
const streamed = /content_block_delta|text_delta|message_start/.test(text);
if (transport === 'vertex-anthropic') pass('served by Vertex (x-llm-transport=vertex-anthropic)');
- else fail(`expected x-llm-transport=vertex-anthropic, got "${transport}"`);
+ else
+ fail(
+ `expected x-llm-transport=vertex-anthropic, got "${transport}". ` +
+ "SMOKE_AGENT_ID's embed policy must select a Claude model: the proxy clamps a " +
+ 'caller-requested host-billed model back to the one the agent owner configured.',
+ );
if (streamed) pass('SSE tokens streamed');
else fail('no Anthropic SSE events observed in the stream');
}
diff --git a/tests/api/llm-anthropic.test.js b/tests/api/llm-anthropic.test.js
index a46131635..b04b39ef5 100644
--- a/tests/api/llm-anthropic.test.js
+++ b/tests/api/llm-anthropic.test.js
@@ -2,7 +2,7 @@
// Focus: monthly token budgeting (input+output), embed-policy enforcement
// (origin, surface, brain mode), upstream error sanitization, model allowlist.
-import { describe, it, expect, beforeEach, vi } from 'vitest';
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
import { Readable } from 'node:stream';
process.env.PUBLIC_APP_ORIGIN ||= 'https://app.test';
@@ -30,16 +30,26 @@ vi.mock('../../api/_lib/avatars.js', () => ({
const rlState = {
ip: { success: true },
agent: { success: true },
+ hostKeyGlobal: { success: true },
};
vi.mock('../../api/_lib/rate-limit.js', () => ({
limits: {
embedLlmIp: vi.fn(async () => rlState.ip),
embedLlmAgent: vi.fn(async () => rlState.agent),
+ chatHostKeyGlobal: vi.fn(async () => rlState.hostKeyGlobal),
},
clientIp: () => '203.0.113.1',
}));
+// Identity for the header-less (non-browser) lane. Null means anonymous, which
+// is what every browser-shaped test wants.
+const authState = { user: null };
+
+vi.mock('../../api/_lib/auth.js', () => ({
+ getRequestUser: vi.fn(async () => authState.user),
+}));
+
const usageEvents = [];
vi.mock('../../api/_lib/usage.js', () => ({
recordEvent: (evt) => usageEvents.push(evt),
@@ -126,13 +136,23 @@ const { default: handler } = await import('../../api/llm/anthropic.js');
// ── Helpers ───────────────────────────────────────────────────────────────
-function makeReq({ url = '/api/llm/anthropic?agent=agent-1', headers = {}, body = null } = {}) {
+// Requests default to a first-party localhost Origin, the shape a real browser
+// embed sends, so tests that aren't about the origin gate exercise the lane a
+// browser actually takes. Pass `noOrigin: true` for the header-less machine lane.
+function makeReq({
+ url = '/api/llm/anthropic?agent=agent-1',
+ headers = {},
+ body = null,
+ noOrigin = false,
+} = {}) {
const base = body ? Readable.from([Buffer.from(JSON.stringify(body))]) : Readable.from([]);
+ const hasOrigin = 'origin' in headers || 'referer' in headers;
base.method = 'POST';
base.url = url;
base.headers = {
host: 'app.test',
'content-type': 'application/json',
+ ...(hasOrigin || noOrigin ? {} : { origin: 'http://localhost:3000' }),
...headers,
};
return base;
@@ -222,6 +242,8 @@ beforeEach(() => {
avatarState.avatar = null;
rlState.ip = { success: true };
rlState.agent = { success: true };
+ rlState.hostKeyGlobal = { success: true };
+ authState.user = null;
usageEvents.length = 0;
redisStore.clear();
redisCalls.length = 0;
@@ -305,11 +327,39 @@ describe('/api/llm/anthropic — origin / referer policy', () => {
expect(body.error).toBe('embed_denied_origin');
});
- it('allows server-to-server (no Origin header) requests', async () => {
- const { status } = await invoke({ body: VALID_BODY });
+ // The header's absence used to mean "allowed", which made the allowlist
+ // advisory: any script could strip Origin and spend the host's provider keys
+ // against a public agent id. Anonymous header-less callers are now denied.
+ it('rejects an anonymous request that sends no Origin header', async () => {
+ authState.user = null;
+ const { status, body } = await invoke({ body: VALID_BODY, noOrigin: true });
+ expect(status).toBe(403);
+ expect(body.error).toBe('embed_denied_origin');
+ expect(body.error_description).toMatch(/authenticate/i);
+ });
+
+ it('allows a server-to-server request that authenticates', async () => {
+ authState.user = { id: 'user-1', source: 'bearer' };
+ const { status } = await invoke({
+ body: VALID_BODY,
+ noOrigin: true,
+ headers: { authorization: 'Bearer platform-key' },
+ });
expect(status).toBe(200);
});
+ // An authenticated caller still cannot launder a denied browser origin: the
+ // escape hatch is only for requests that carry no Origin at all.
+ it('does not let a signed-in caller override a denied Origin', async () => {
+ authState.user = { id: 'user-1', source: 'bearer' };
+ const { status, body } = await invoke({
+ body: VALID_BODY,
+ headers: { origin: 'https://attacker.test', authorization: 'Bearer platform-key' },
+ });
+ expect(status).toBe(403);
+ expect(body.error).toBe('embed_denied_origin');
+ });
+
it('allows first-party localhost origin without policy entry', async () => {
policyState.policy.origins.hosts = []; // explicitly empty
const { status } = await invoke({
@@ -424,11 +474,63 @@ describe('/api/llm/anthropic — request body + model', () => {
expect(sentBody.model).toBe('claude-sonnet-4-6');
});
- it('caller-supplied allowlisted model overrides policy default', async () => {
+ it('honours a paid model the owner configured on the policy', async () => {
policyState.policy.brain.model = 'claude-opus-4-6';
- await invoke({ body: { ...VALID_BODY, model: 'claude-opus-4-7' } });
+ await invoke({ body: { ...VALID_BODY, model: 'claude-opus-4-6' } });
const sentBody = JSON.parse(fetchState.calls[0].init.body);
- expect(sentBody.model).toBe('claude-opus-4-7');
+ expect(sentBody.model).toBe('claude-opus-4-6');
+ });
+});
+
+// ── caller-chosen model vs. the owner's policy ──────────────────────────
+//
+// Which host-billed model an embed runs is the agent owner's decision, taken in
+// the dashboard and stored on the policy. A visitor may switch between free
+// lanes; asking for a pricier host-keyed model returns the configured one.
+// The free lanes need their provider keys present, or the fallback chain
+// degrades past them and the assertion reads the wrong upstream call.
+
+describe('/api/llm/anthropic: paid-model clamp', () => {
+ beforeEach(() => {
+ process.env.OPENROUTER_API_KEY = 'sk-or-test';
+ process.env.GROQ_API_KEY = 'gsk-test';
+ });
+
+ afterEach(() => {
+ delete process.env.OPENROUTER_API_KEY;
+ delete process.env.GROQ_API_KEY;
+ });
+
+ it('caller-supplied free model overrides the policy default', async () => {
+ policyState.policy.brain.model = 'openai/gpt-oss-20b:free';
+ await invoke({ body: { ...VALID_BODY, model: 'llama-3.3-70b-versatile' } });
+ const sentBody = JSON.parse(fetchState.calls[0].init.body);
+ expect(sentBody.model).toBe('llama-3.3-70b-versatile');
+ });
+
+ it('clamps a caller-requested paid model back to the policy model', async () => {
+ policyState.policy.brain.model = 'openai/gpt-oss-20b:free';
+ await invoke({ body: { ...VALID_BODY, model: 'claude-opus-5' } });
+ const sentBody = JSON.parse(fetchState.calls[0].init.body);
+ expect(sentBody.model).toBe('openai/gpt-oss-20b:free');
+ });
+
+ it('clamps a paid model on the free default policy too', async () => {
+ delete policyState.policy.brain.model;
+ await invoke({ body: { ...VALID_BODY, model: 'grok-4.5' } });
+ const sentBody = JSON.parse(fetchState.calls[0].init.body);
+ expect(sentBody.model).toBe('openai/gpt-oss-20b:free');
+ });
+});
+
+// ── platform-wide host-key ceiling ──────────────────────────────────────
+
+describe('/api/llm/anthropic: host-key global ceiling', () => {
+ it('returns 429 when the shared host-key budget is saturated', async () => {
+ rlState.hostKeyGlobal = { success: false, reset: Date.now() + 1000 };
+ const { status, body } = await invoke({ body: VALID_BODY });
+ expect(status).toBe(429);
+ expect(body.error_description).toMatch(/capacity/i);
});
});