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(onboarding): require a CSRF token on the avatar session and link-avatar endpoints

nirholasb5401328d92d
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 63668c1f8..5ff426014 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -10,16 +10,23 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr
- **Docs · Recurring payments** (`/docs/recurring-payments`): Sign one permission, then a fixed USDC amount moves every day or week, or gets swapped into a token on a schedule. The lifecycle, the API, what every kind of failed charge does to a schedule, and the operator config settlement needs.
- **Docs · The Agent Index** (`/docs/agent-index`): The platform's own cross-chain index of agent registrations, token launches, reputation attestations, transfers and delegations, Solana first: one public endpoint, absolute on-chain timestamps, and published index freshness.
- **A bounty that does not exist now says so, instead of blaming pump.fun**: The bounty board at /bounties mirrors the public pump.fun GO board. When you opened a bounty link that had been deleted or mistyped, the page reported it the same way it reports pump.fun being down, so there was no way to tell a dead link from an outage. A bounty that genuinely is not there now answers as not found, and a real upstream problem keeps its own separate answer. A second, quieter case got fixed with it: when the submissions list for a bounty failed to load, the page showed the bounty with zero submissions and said nothing, which looks identical to a bounty nobody has entered. That failure is now recorded, so a pump.fun outage shows up as an outage rather than as a board that suddenly looks unpopular. (`/bounties`) `[fix]`
+- **Another site can no longer swap your agent's body or burn your avatar credits behind your back**: The two avatar onboarding endpoints (the one that opens the photo editor, and the one that attaches a finished avatar to an agent) accepted a request that arrived with your login cookie but no proof you meant to send it. A page you had merely visited could therefore repoint your agent to a different body, or spend your hourly avatar-editor allowance, without you doing anything. Both now require the same one-time token every other account-changing action on three.ws already asks for, and both refuse the request outright without it. API-key callers are unaffected. A second change: when the photo editor is not configured in an environment, the request is turned away before it counts against your hourly allowance, so a temporary outage no longer locks you out of the flow for an hour once it is back. `[security, fix]`
- **Apps that sign in with a client secret can now revoke and inspect their own tokens**: If you connect an app to three.ws over OAuth and registered it with a client secret sent in the Authorization header (client_secret_basic, the standard choice for server-side apps), only the token endpoint accepted those credentials. Revoking a token or checking whether one is still valid answered that the client_id was missing, and answered that the credentials were bad the moment you added it, so a confidential app had no way to sign a user out or verify a token it owned. All three endpoints now take the same credentials, in the header or in the form body, exactly as the OAuth revocation and introspection standards require. Dynamic client registration also now returns client_secret_expires_at alongside a new secret, so your client can tell that a three.ws secret never expires rather than guessing from a missing field. (`/docs/authentication`) `[fix, security]`
- **Avatar likeness is now measured against your photos, not assumed**: The promise behind the selfie flow is that the avatar looks like you, and until now nothing on the platform checked that. Two quality systems already existed and neither answered the question: one scores whether a generated model looks photorealistic, which a beautiful model of a stranger passes easily, and the other scores the head's shape offline against a synthetic test set and kept no record per avatar. Every finished reconstruction is now rendered from three angles and compared to the photos it was built from using the same kind of face-recognition model a phone uses to decide a face unlocks it. That produces a score out of 5 filed against the generation itself, and the scale is anchored to the model's own published cut-off for "same person" rather than to anyone's opinion, so 4 out of 5 means confidently you and not arguably you. A weekly sweep keeps the numbers current, and one of the three angles is a turned head on purpose: an avatar built by painting a photo onto a template can look right face-on and fall apart the moment it turns, and that is now a number somebody can see. The score is a measurement, never a guess: when the photos have no usable face, or the finished model has no recognisable face at all, it says which, instead of quietly reporting a bad score. `[infra, improvement, docs]`
- **Buying a skill from your phone no longer needs SOL in your wallet**: The QR code in the skill payment modal now hands your wallet a transaction we build for you, instead of asking the wallet to compose the transfer itself. Three things change for the buyer: three.ws pays the Solana network fee, so a wallet holding only USDC can complete the purchase; a creator who has never received this token before no longer causes the payment to fail, because the missing token account is created in the same transaction; and the whole payment still settles under one signature. Wallets that do not support this newer Solana Pay flow are one click away from the classic direct-transfer QR, which stays available under the code. (`/marketplace`) `[improvement, fix]`
+- **Buying USDC or SOL from Add funds again opens a checkout with your wallet already filled in**: The Add funds overlay builds a Coinbase checkout link for your three.ws wallet. It was still building that link the old way, passing the destination wallet in the URL, which Coinbase stopped accepting when it moved to server-minted session tokens. The link is now minted through Coinbase's current onramp API: one single-use token per click, bound to your Solana address and the asset you picked, so the checkout opens with the destination, the asset, and your chosen amount already set instead of dropping you on a generic buy page. If Coinbase is unreachable, funding does not break: you still get a working buy page and the address to send to, exactly as before. The endpoint is also rate limited now, so nobody can drive our Coinbase quota by hammering it. `[fix, improvement]`
+- **Chinese headlines no longer show up in the English crypto news feed**: BlockTempo, a Taiwanese crypto publisher that writes in Traditional Chinese, was listed in our news source registry without a language tag. Untagged sources are treated as English, so its headlines were being mixed into the default feed on /markets/news, the markets hub strip, and the RSS mirror, where they read as noise to anyone browsing in English. It is now tagged Chinese: the English feed is English only, and BlockTempo shows up when you pick Chinese from the language selector, alongside PANews. Nothing else about the feed changed. (`/markets/news`) `[fix]`
- **Controls that promised an action and did nothing now actually do it**: Several buttons across the site were links pointing at nothing, so clicking them moved the page to the top and nothing else happened. On a coin or category page whose market data failed to load, "Reload the page" was one of them: the one control offered for recovery had no handler at all, so a reader who hit a data outage had no way out of it. It now re-runs the real request in place, skeletons and all, so a recovered feed repaints without a full page load. The "+ Link wallet" button on your account page was the same kind of dead end, pointing back at the section it already sat in; it now opens your Solana wallet, signs the ownership message, and links the wallet to your account, including moving a wallet that is currently linked somewhere else once your signature has proved it is yours. Clear filter on derivatives, Show all on stablecoins, Retry on search and on the world generator, skip for now in the dashboard checklist, Create one in the agent registry, and View more in Related Agents were all links pretending to be buttons; they are real buttons now, which means they answer the space bar, sit in the tab order where you expect, and show a visible focus ring. Picking a coin in the compare search is announced properly to a screen reader as you arrow through the list. `[fix, improvement]`
- **Every agent now has a verifiable on-chain history you can read on its page**: Agents do things on-chain after they are registered: they launch a token, collect reputation attestations, change hands, delegate execution rights. Until now the platform recorded only who an agent currently was, so all of that history was dropped, and anyone who wanted it had to scan a chain themselves. Open any agent under the Discover directory and there is now an On-chain history panel: a timeline of everything the platform has indexed for that agent, each entry stamped with the real time the chain says it happened and linked to the transaction on a block explorer so you can check it yourself. The same data is available to developers as one public endpoint. Three failures were fixed to make it real. The Solana half of the indexer was crashing on every single agent it looked at, so despite tracking more than fifteen hundred agents it had recorded zero events; it now records them, and a token launch names the agent's actual coin instead of the wrapped SOL that paid for it. On the EVM side, five of the twenty-two supported chains were producing blocks faster than the indexer could read them, so their backlog grew every hour while the status page called them healthy: the indexer now widens its reading window until it catches up, and the status page publishes how many blocks behind the worst chain is, as a number. Reputation was the third: the platform was already asking every EVM chain for agent feedback and vouches on every pass, then throwing the answers away, so not a single reputation event had ever reached the index. Those now land alongside the rest of an agent's history, with the score, its tags, and a link to the attestation. (`/docs/agent-index`) `[feature, fix, infra]`
- **Platform counters stop reporting zero when the numbers are simply unavailable**: The public stats behind the home page and the monitor board (agents, avatars, widgets, views, countries, chains) used to answer with a row of zeroes whenever the database could not be reached, and that fabricated all-zero snapshot was then cached for five minutes at the edge, so the platform looked empty long after it had recovered. It now says the figures are unavailable instead, caches that for fifteen seconds, and the monitor board keeps the last real numbers on screen rather than flashing zeroes. The chain counter is also a real count again: it reads the mainnets that actually carry an indexed agent plus Solana, instead of a hardcoded six that had drifted from reality. (`/monitor`) `[fix]`
+- **Plugin marketplace: no more duplicate listings, and private plugins stay private**: The plugin grid listed every built-in plugin twice (two Calculators, two Weathers, and so on) because the platform's seed rows were inserted a second time without the duplicate check ever catching them. There are now seven built-ins again, one of each, and the database refuses a duplicate outright. Three plugin API fixes ship with it: a plugin published as private was readable in full by anyone who knew its link, and its install counter could be driven by anyone; recording an install now reports the real new total instead of always answering "ok", and counts one install per person per plugin rather than one per click; and asking for a page of plugins with a malformed cursor now returns a plain validation error rather than a server error. (`/marketplace`) `[fix, security]`
- **Recurring payments now have a home, a pause button, and a receipt for every charge**: Sign one permission and a fixed amount of USDC moves to an agent every day or week, or gets swapped into a token on a schedule. Until now there was no page for any of that: you could start a schedule from a skill and then never see it again, and one bad hour on the network ended it for good, because nothing could turn a paused schedule back on. The new /recurring page is the whole life of a schedule in one place. Create one, pause it, resume it, cancel it, and read every charge it has ever made with the transaction hash next to it. A second tab shows what is being paid into your own agents, with the paying wallet and the running total. When a period fails you now get told why, in a sentence: a revoked permission pauses the schedule and says so, a wallet short of USDC keeps the schedule alive and retries once you top up, and a charge that timed out is never retried at all, because that is the one case that could take your money twice. (`/recurring`) `[feature, improvement]`
+- **Sharing a build now checks that the coin world you are sharing to is real**: When you screenshot a voxel build in a coin's /play world and share it, the build is filed under that coin's address. The endpoint only checked that the address was the right length, not that it was an address at all, so anything between 32 and 64 characters was accepted and filed away under its own storage slot. It now checks the format the way every other coin-world surface does: a Solana mint or an EVM contract address gets through, anything else is turned away before it reaches storage. Real worlds are unaffected, on both Solana and the EVM chains. The live event board picked up its own test coverage in the same pass, including a check that a player's account key never appears in what the board sends to the browser. (`/play`) `[security, fix]`
+- **The $THREE holder count is back on the token page and its share card**: The holder count on the /three-token page, and on the badge image that previews wherever a $THREE link is shared, had been showing a dash instead of a number. Our own holder snapshot is rebuilt from a Solana indexer that has been refusing the scan, and once the snapshot went stale the page correctly declined to show an out-of-date figure, so the count simply disappeared rather than being briefly missing. Holder count now falls back to a second, independent source when our snapshot cannot refresh, so the figure stays real and current through an indexer outage. The share card was also reading a narrower set of sources than the page it mirrors, which is why the two could disagree; both now read the same ones. Separately, a shared agent link unfurls noticeably faster: the card was fetching the agent's portrait only after every other lookup had finished, and now fetches it alongside them. (`/three-token`) `[fix, improvement]`
- **The agent directory describes itself correctly in all 84 languages again**: The English description Google and every social preview show for the agent directory was updated a while back to say the directory spans Solana and every supported EVM chain. The 84 translated versions were never updated with it, so a reader in Spanish, Japanese, Arabic or any other language got the older, vaguer line that named no chain at all. All 84 now carry the current wording, with Solana and three.ws left in their real spelling rather than bent to fit each language's grammar. Retired copy was cleared out at the same time: eight strings that no page shows anymore had been sitting in every one of the 84 catalogs, which is 672 dead entries the site was shipping to readers for no reason. (`/agents`) `[fix, docs]`
- **The contracts that hold agent earnings, reputation stakes and skill licenses are now audit-ready**: Before an outside firm can review the contracts behind agent royalties, reputation staking and wallet delegation, someone has to write down what those contracts promise and then prove it holds. That pack now exists and is public. Every value-bearing contract has numbered invariants, each backed by a test proving the property holds and a second test proving that an attacker trying to break it is rejected, alongside a threat model naming what is worth stealing, who could try, and what stops them. The Solidity contracts sit at 100% test coverage across 242 tests. The two Solana programs, which had no automated tests at all, now have 32 running against their real compiled on-chain bytecode rather than a stand-in, with the real token programs loaded. Two standard analyzers were run across everything, and every finding is either fixed or answered in writing. One of those fixes closes a real gap: a cross-chain permission request that was declined rather than failed outright would have credited a seller and charged a buyer for access that was never going to be granted. `[security, infra, docs]`
- **The free object library can no longer be emptied by one bad upload**: The CC0 prop library at /objects reads a single index file from the CDN. If that file were ever uploaded truncated or in the wrong shape, the gallery treated it as a library with nothing in it and told the CDN to remember that answer for the next five minutes, so a bad upload kept the shelves bare long after it was replaced. A damaged index is now handled the same way as the CDN being briefly unreachable: the page stays quiet, nothing gets cached, and the props come back on the very next request. Two smaller fixes went with it: a request with a broken page cursor (a limit of "abc", a negative offset) is rejected outright instead of first fetching an index it was never going to use, and the developer documentation no longer claims the library API can be called from any website, which it cannot; it answers three.ws and its partner sites, and everything it points at is still yours to download and reuse anywhere. (`/objects`) `[fix, docs]`
+- **The internal money and platform health boards tell the truth again**: Three internal dashboards watch the platform for us: one for site and cron health, one for every money subsystem, one for payment outcomes. Two of them had gone quietly wrong. The platform board judged each scheduled job against a hand-written idea of how often it should run, and three jobs that run once a day were being judged against a window of minutes, so they reported as broken for roughly 23 hours out of every day and the board could never come back all-clear; every job is now measured against the schedule it genuinely runs on. One of its probes was also posting to a payments endpoint without declaring it was sending JSON, so it had been failing on its own mistake rather than on anything real. The money board was reading the wrong timestamp column on two payment logs and showing no activity at all for a payment ring that settles thousands of payments a day. It also accepted the credential our fund-moving scheduled jobs carry as an ops password; it now takes the same admin sign-in as the other boards, so an ops credential can never be escalated into triggering a payment job. `[fix, infra, security]`
- **The limits you set on an agent's spending can no longer be skipped**: An agent that pays other agents on its own is governed by the policy you set on its wallet: a ceiling per payment, a rolling 24-hour ceiling, a separate ceiling per payee so one peer cannot quietly absorb the whole day's budget, and a kill switch that halts every kind of autonomous spending the moment you flip it. Those rules were enforced wherever the platform asked for them, but the enforcement itself had a soft spot: code that asked the guard to check a payment without first loading the agent's settings was handed an empty policy, meaning no ceilings and no kill switch, and nothing anywhere said so. The guard now reads the agent's real policy itself in that case, and refuses outright to price a payment for an agent that no longer exists. Every ceiling and the kill switch are now proven, not asserted: one command spins up a real database and a real server, then shows each limit turning away an over-limit payment, eight simultaneous payments competing for the last dollar of headroom with exactly one getting through, a frozen agent halted before the other agent is even contacted while your own withdrawals stay open, and every settled payment coming back as a receipt with the payee, the amount and the transaction signature on your agent's ledger. (`/docs/a2a-payments`) `[security, improvement, docs]`
- **The MCP tool catalog now lists three tools it was hiding, and stops calling the x402 Bazaar free**: The public tool catalog at /mcp-tools is generated from the code so it cannot drift, which is exactly why two wrong things in it went unnoticed. The free 3D Studio connector builds its tool list from two source files and the generator only ever read one of them, so the three persona tools that give a generated body a name, bring it back in a later session, and make it lip-sync a reply were served by the endpoint but missing from the catalog, from the machine-readable /mcp-catalog.json an agent fetches to discover what it can call, and from the two build gates that hold every published tool to its declared contract and its declared safety annotations. All three are now covered by both gates and appear in the catalog. Separately, the x402 Bazaar was labelled as needing no account and no payment; a real search call with neither returns a payment request, so the catalog now says OAuth or x402, matching the server, its documentation, and the fleet directory at /.well-known/mcp.json. (`/mcp-tools`) `[fix, docs, sdk]`
- **The Oracle live action stream no longer goes quiet after a bad reconnect**: The trading floor at /activity reconnects to its live feed by telling the server the timestamp it last saw. If that timestamp arrived malformed, the server opened the stream anyway and then silently failed every lookup behind it: the page stayed connected, showed no error, and never received another action for as long as it was open. It now rejects the bad timestamp up front with a clear message so the page reconnects cleanly instead of sitting on a dead feed. Three neighbouring Oracle endpoints got the same treatment: a malformed paging cursor on the activity feed, and a non-text agent or chat id sent to the follow endpoint, used to come back as an unexplained server error and now come back as a plain description of what was wrong. An unreadable result limit on an agent's public track record no longer wipes out its recent-trade list. The activity feed and the calibration report also now allow cross-site reads, matching every other public Oracle endpoint. (`/activity`) `[fix, improvement]`
diff --git a/api/onboarding/[action].js b/api/onboarding/[action].js
index ac3e74866..9a32978a7 100644
--- a/api/onboarding/[action].js
+++ b/api/onboarding/[action].js
@@ -4,6 +4,7 @@ import { z } from 'zod';
import { sql } from '../_lib/db.js';
import { getSessionUser, authenticateBearer, extractBearer, hasScope } from '../_lib/auth.js';
import { cors, json, method, readJson, wrap, error, rateLimited } from '../_lib/http.js';
+import { requireCsrf } from '../_lib/csrf.js';
import { limits, clientIp } from '../_lib/rate-limit.js';
import { parse } from '../_lib/validate.js';
import { env } from '../_lib/env.js';
@@ -29,8 +30,24 @@ const avaturnSchema = z.object({
// an identity failure (401): answering 401 sends a machine client back to a token
// exchange that would mint the exact same token again. Mirrors the 403
// `insufficient_scope` answer in api/erc8004/[action].js and api/agents.js.
+//
+// Both actions are cookie-session-reachable POSTs that change server state, so
+// both also need the double-submit CSRF check every other session mutation in
+// api/ carries (api/avatars/_actions.js, api/friends/index.js). Without it a
+// cross-site form POST rode the victim's cookie: link-avatar would repoint their
+// agent's body (force:true even overrides an existing link) and avaturn-session
+// would burn their avatar-provider quota, both while the attacker page ignored
+// the CORS-blocked response it never needed to read. requireCsrf() exempts
+// bearer callers, so API-key clients are unaffected.
// Returns the user id, or null after having already written the error response.
async function resolveOnboardingUser(req, res, signInMessage) {
+ const userId = await resolveIdentity(req, res, signInMessage);
+ if (!userId) return null;
+ if (!(await requireCsrf(req, res, userId))) return null;
+ return userId;
+}
+
+async function resolveIdentity(req, res, signInMessage) {
const session = await getSessionUser(req);
if (session) return session.id;
const bearer = await authenticateBearer(extractBearer(req));
@@ -50,11 +67,15 @@ async function handleAvaturnSession(req, res) {
if (!method(req, res, ['POST'])) return;
const userId = await resolveOnboardingUser(req, res, 'sign in to create an avatar');
if (!userId) return;
+ // The not-configured check precedes the limiters on purpose: where the key is
+ // absent no request can ever succeed, so charging the caller's hourly upload
+ // budget for a guaranteed 501 only locks them out of the flow for an hour
+ // once the operator does set the key.
+ if (!env.AVATURN_API_KEY) return error(res, 501, 'not_configured', 'Avatar editor is not available right now. Please try again later.');
const rlUser = await limits.upload(userId);
if (!rlUser.success) return rateLimited(res, rlUser, 'too many avatar attempts, try again later');
const rlIp = await limits.authIp(clientIp(req));
if (!rlIp.success) return rateLimited(res, rlIp, 'too many requests from this network');
- if (!env.AVATURN_API_KEY) return error(res, 501, 'not_configured', 'Avatar editor is not available right now. Please try again later.');
const body = parse(avaturnSchema, await readJson(req, 8_000_000));
try {
const session = await createProviderSession(userId, body);
diff --git a/data/changelog.json b/data/changelog.json
index e0ccc6e0b..1d2adc249 100644
--- a/data/changelog.json
+++ b/data/changelog.json
@@ -1,6 +1,15 @@
{
"$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-14",
+ "title": "Another site can no longer swap your agent's body or burn your avatar credits behind your back",
+ "summary": "The two avatar onboarding endpoints (the one that opens the photo editor, and the one that attaches a finished avatar to an agent) accepted a request that arrived with your login cookie but no proof you meant to send it. A page you had merely visited could therefore repoint your agent to a different body, or spend your hourly avatar-editor allowance, without you doing anything. Both now require the same one-time token every other account-changing action on three.ws already asks for, and both refuse the request outright without it. API-key callers are unaffected. A second change: when the photo editor is not configured in an environment, the request is turned away before it counts against your hourly allowance, so a temporary outage no longer locks you out of the flow for an hour once it is back.",
+ "tags": [
+ "security",
+ "fix"
+ ]
+ },
{
"date": "2026-08-14",
"title": "Sharing a build now checks that the coin world you are sharing to is real",
diff --git a/docs/tutorials/selfie-to-avatar.md b/docs/tutorials/selfie-to-avatar.md
index 650587e3f..37f4723aa 100644
--- a/docs/tutorials/selfie-to-avatar.md
+++ b/docs/tutorials/selfie-to-avatar.md
@@ -165,9 +165,14 @@ You have two paths:
**Reassign it deliberately.** If you want this avatar to become the face of a *specific* existing agent, attach it explicitly:
```js
+// Session-cookie calls carry a CSRF token. Tokens are single-use, so mint a
+// fresh one per request. (API-key callers send `Authorization: Bearer <key>`
+// with the `avatars:write` scope instead and skip this step.)
+const { token } = await (await fetch('/api/csrf-token', { credentials: 'include' })).json();
+
await fetch('/api/onboarding/link-avatar', {
method: 'POST',
- headers: { 'Content-Type': 'application/json' },
+ headers: { 'Content-Type': 'application/json', 'X-CSRF-Token': token },
credentials: 'include',
body: JSON.stringify({
avatarId: '0f25b676-e27b-4929-875c-4135fea0f635', // your id from /avatars/<id>
@@ -177,7 +182,7 @@ await fetch('/api/onboarding/link-avatar', {
// → { agent: { id, avatar_id, updated_at } }
```
-`force: true` overrides an avatar the agent already has. Omit it (or set `false`) to only attach when the agent has no avatar yet. Either way the call is owner-scoped — you can only attach avatars to agents you own.
+`force: true` overrides an avatar the agent already has. Omit it (or set `false`) to only attach when the agent has no avatar yet. Either way the call is owner-scoped: you can only attach avatars to agents you own.
Once linked, give the agent a [personality](/tutorials/agent-personality) and a [brain](/tutorials/connect-ai-brain), then [share it](/tutorials/share-your-agent) or embed it on a site.
diff --git a/public/changelog.json b/public/changelog.json
index 68ae93e5e..cae4d3bc0 100644
--- a/public/changelog.json
+++ b/public/changelog.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-08-14T02:26:31.486Z",
+ "generated_at": "2026-08-14T04:43:15.796Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json",
"site": {
"name": "three.ws",
@@ -46,6 +46,17 @@
"fix"
]
},
+ {
+ "date": "2026-08-14",
+ "type": "update",
+ "title": "Another site can no longer swap your agent's body or burn your avatar credits behind your back",
+ "summary": "The two avatar onboarding endpoints (the one that opens the photo editor, and the one that attaches a finished avatar to an agent) accepted a request that arrived with your login cookie but no proof you meant to send it. A page you had merely visited could therefore repoint your agent to a different body, or spend your hourly avatar-editor allowance, without you doing anything. Both now require the same one-time token every other account-changing action on three.ws already asks for, and both refuse the request outright without it. API-key callers are unaffected. A second change: when the photo editor is not configured in an environment, the request is turned away before it counts against your hourly allowance, so a temporary outage no longer locks you out of the flow for an hour once it is back.",
+ "link": null,
+ "tags": [
+ "security",
+ "fix"
+ ]
+ },
{
"date": "2026-08-14",
"type": "update",
@@ -80,6 +91,27 @@
"fix"
]
},
+ {
+ "date": "2026-08-14",
+ "type": "update",
+ "title": "Buying USDC or SOL from Add funds again opens a checkout with your wallet already filled in",
+ "summary": "The Add funds overlay builds a Coinbase checkout link for your three.ws wallet. It was still building that link the old way, passing the destination wallet in the URL, which Coinbase stopped accepting when it moved to server-minted session tokens. The link is now minted through Coinbase's current onramp API: one single-use token per click, bound to your Solana address and the asset you picked, so the checkout opens with the destination, the asset, and your chosen amount already set instead of dropping you on a generic buy page. If Coinbase is unreachable, funding does not break: you still get a working buy page and the address to send to, exactly as before. The endpoint is also rate limited now, so nobody can drive our Coinbase quota by hammering it.",
+ "link": null,
+ "tags": [
+ "fix",
+ "improvement"
+ ]
+ },
+ {
+ "date": "2026-08-14",
+ "type": "update",
+ "title": "Chinese headlines no longer show up in the English crypto news feed",
+ "summary": "BlockTempo, a Taiwanese crypto publisher that writes in Traditional Chinese, was listed in our news source registry without a language tag. Untagged sources are treated as English, so its headlines were being mixed into the default feed on /markets/news, the markets hub strip, and the RSS mirror, where they read as noise to anyone browsing in English. It is now tagged Chinese: the English feed is English only, and BlockTempo shows up when you pick Chinese from the language selector, alongside PANews. Nothing else about the feed changed.",
+ "link": "/markets/news",
+ "tags": [
+ "fix"
+ ]
+ },
{
"date": "2026-08-14",
"type": "update",
@@ -113,6 +145,17 @@
"fix"
]
},
+ {
+ "date": "2026-08-14",
+ "type": "update",
+ "title": "Plugin marketplace: no more duplicate listings, and private plugins stay private",
+ "summary": "The plugin grid listed every built-in plugin twice (two Calculators, two Weathers, and so on) because the platform's seed rows were inserted a second time without the duplicate check ever catching them. There are now seven built-ins again, one of each, and the database refuses a duplicate outright. Three plugin API fixes ship with it: a plugin published as private was readable in full by anyone who knew its link, and its install counter could be driven by anyone; recording an install now reports the real new total instead of always answering \"ok\", and counts one install per person per plugin rather than one per click; and asking for a page of plugins with a malformed cursor now returns a plain validation error rather than a server error.",
+ "link": "/marketplace",
+ "tags": [
+ "fix",
+ "security"
+ ]
+ },
{
"date": "2026-08-14",
"type": "update",
@@ -124,6 +167,28 @@
"improvement"
]
},
+ {
+ "date": "2026-08-14",
+ "type": "update",
+ "title": "Sharing a build now checks that the coin world you are sharing to is real",
+ "summary": "When you screenshot a voxel build in a coin's /play world and share it, the build is filed under that coin's address. The endpoint only checked that the address was the right length, not that it was an address at all, so anything between 32 and 64 characters was accepted and filed away under its own storage slot. It now checks the format the way every other coin-world surface does: a Solana mint or an EVM contract address gets through, anything else is turned away before it reaches storage. Real worlds are unaffected, on both Solana and the EVM chains. The live event board picked up its own test coverage in the same pass, including a check that a player's account key never appears in what the board sends to the browser.",
+ "link": "/play",
+ "tags": [
+ "security",
+ "fix"
+ ]
+ },
+ {
+ "date": "2026-08-14",
+ "type": "update",
+ "title": "The $THREE holder count is back on the token page and its share card",
+ "summary": "The holder count on the /three-token page, and on the badge image that previews wherever a $THREE link is shared, had been showing a dash instead of a number. Our own holder snapshot is rebuilt from a Solana indexer that has been refusing the scan, and once the snapshot went stale the page correctly declined to show an out-of-date figure, so the count simply disappeared rather than being briefly missing. Holder count now falls back to a second, independent source when our snapshot cannot refresh, so the figure stays real and current through an indexer outage. The share card was also reading a narrower set of sources than the page it mirrors, which is why the two could disagree; both now read the same ones. Separately, a shared agent link unfurls noticeably faster: the card was fetching the agent's portrait only after every other lookup had finished, and now fetches it alongside them.",
+ "link": "/three-token",
+ "tags": [
+ "fix",
+ "improvement"
+ ]
+ },
{
"date": "2026-08-14",
"type": "update",
@@ -158,6 +223,18 @@
"docs"
]
},
+ {
+ "date": "2026-08-14",
+ "type": "update",
+ "title": "The internal money and platform health boards tell the truth again",
+ "summary": "Three internal dashboards watch the platform for us: one for site and cron health, one for every money subsystem, one for payment outcomes. Two of them had gone quietly wrong. The platform board judged each scheduled job against a hand-written idea of how often it should run, and three jobs that run once a day were being judged against a window of minutes, so they reported as broken for roughly 23 hours out of every day and the board could never come back all-clear; every job is now measured against the schedule it genuinely runs on. One of its probes was also posting to a payments endpoint without declaring it was sending JSON, so it had been failing on its own mistake rather than on anything real. The money board was reading the wrong timestamp column on two payment logs and showing no activity at all for a payment ring that settles thousands of payments a day. It also accepted the credential our fund-moving scheduled jobs carry as an ops password; it now takes the same admin sign-in as the other boards, so an ops credential can never be escalated into triggering a payment job.",
+ "link": null,
+ "tags": [
+ "fix",
+ "infra",
+ "security"
+ ]
+ },
{
"date": "2026-08-14",
"type": "update",
diff --git a/public/changelog.xml b/public/changelog.xml
index b6b024aae..65a4871af 100644
--- a/public/changelog.xml
+++ b/public/changelog.xml
@@ -38,6 +38,14 @@
<category>fix</category>
<description>The bounty board at /bounties mirrors the public pump.fun GO board. When you opened a bounty link that had been deleted or mistyped, the page reported it the same way it reports pump.fun being down, so there was no way to tell a dead link from an outage. A bounty that genuinely is not there now answers as not found, and a real upstream problem keeps its own separate answer. A second, quieter case got fixed with it: when the submissions list for a bounty failed to load, the page showed the bounty with zero submissions and said nothing, which looks identical to a bounty nobody has entered. That failure is now recorded, so a pump.fun outage shows up as an outage rather than as a board that suddenly looks unpopular.</description>
</item>
+ <item>
+ <title>Another site can no longer swap your agent's body or burn your avatar credits behind your back</title>
+ <link>https://three.ws/changelog</link>
+ <guid isPermaLink="false">2026-08-14:Another site can no longer swap your agent's body or burn your avatar credits behind your back</guid>
+ <pubDate>Fri, 14 Aug 2026 12:00:00 GMT</pubDate>
+ <category>security</category>
+ <description>The two avatar onboarding endpoints (the one that opens the photo editor, and the one that attaches a finished avatar to an agent) accepted a request that arrived with your login cookie but no proof you meant to send it. A page you had merely visited could therefore repoint your agent to a different body, or spend your hourly avatar-editor allowance, without you doing anything. Both now require the same one-time token every other account-changing action on three.ws already asks for, and both refuse the request outright without it. API-key callers are unaffected. A second change: when the photo editor is not configured in an environment, the request is turned away before it counts against your hourly allowance, so a temporary outage no longer locks you out of the flow for an hour once it is back.</description>
+ </item>
<item>
<title>Apps that sign in with a client secret can now revoke and inspect their own tokens</title>
<link>https://three.ws/docs/authentication</link>
@@ -62,6 +70,22 @@
<category>improvement</category>
<description>The QR code in the skill payment modal now hands your wallet a transaction we build for you, instead of asking the wallet to compose the transfer itself. Three things change for the buyer: three.ws pays the Solana network fee, so a wallet holding only USDC can complete the purchase; a creator who has never received this token before no longer causes the payment to fail, because the missing token account is created in the same transaction; and the whole payment still settles under one signature. Wallets that do not support this newer Solana Pay flow are one click away from the classic direct-transfer QR, which stays available under the code.</description>
</item>
+ <item>
+ <title>Buying USDC or SOL from Add funds again opens a checkout with your wallet already filled in</title>
+ <link>https://three.ws/changelog</link>
+ <guid isPermaLink="false">2026-08-14:Buying USDC or SOL from Add funds again opens a checkout with your wallet already filled in</guid>
+ <pubDate>Fri, 14 Aug 2026 12:00:00 GMT</pubDate>
+ <category>fix</category>
+ <description>The Add funds overlay builds a Coinbase checkout link for your three.ws wallet. It was still building that link the old way, passing the destination wallet in the URL, which Coinbase stopped accepting when it moved to server-minted session tokens. The link is now minted through Coinbase's current onramp API: one single-use token per click, bound to your Solana address and the asset you picked, so the checkout opens with the destination, the asset, and your chosen amount already set instead of dropping you on a generic buy page. If Coinbase is unreachable, funding does not break: you still get a working buy page and the address to send to, exactly as before. The endpoint is also rate limited now, so nobody can drive our Coinbase quota by hammering it.</description>
+ </item>
+ <item>
+ <title>Chinese headlines no longer show up in the English crypto news feed</title>
+ <link>https://three.ws/markets/news</link>
+ <guid isPermaLink="false">2026-08-14:Chinese headlines no longer show up in the English crypto news feed</guid>
+ <pubDate>Fri, 14 Aug 2026 12:00:00 GMT</pubDate>
+ <category>fix</category>
+ <description>BlockTempo, a Taiwanese crypto publisher that writes in Traditional Chinese, was listed in our news source registry without a language tag. Untagged sources are treated as English, so its headlines were being mixed into the default feed on /markets/news, the markets hub strip, and the RSS mirror, where they read as noise to anyone browsing in English. It is now tagged Chinese: the English feed is English only, and BlockTempo shows up when you pick Chinese from the language selector, alongside PANews. Nothing else about the feed changed.</description>
+ </item>
<item>
<title>Controls that promised an action and did nothing now actually do it</title>
<link>https://three.ws/changelog</link>
@@ -86,6 +110,14 @@
<category>fix</category>
<description>The public stats behind the home page and the monitor board (agents, avatars, widgets, views, countries, chains) used to answer with a row of zeroes whenever the database could not be reached, and that fabricated all-zero snapshot was then cached for five minutes at the edge, so the platform looked empty long after it had recovered. It now says the figures are unavailable instead, caches that for fifteen seconds, and the monitor board keeps the last real numbers on screen rather than flashing zeroes. The chain counter is also a real count again: it reads the mainnets that actually carry an indexed agent plus Solana, instead of a hardcoded six that had drifted from reality.</description>
</item>
+ <item>
+ <title>Plugin marketplace: no more duplicate listings, and private plugins stay private</title>
+ <link>https://three.ws/marketplace</link>
+ <guid isPermaLink="false">2026-08-14:Plugin marketplace: no more duplicate listings, and private plugins stay private</guid>
+ <pubDate>Fri, 14 Aug 2026 12:00:00 GMT</pubDate>
+ <category>fix</category>
+ <description>The plugin grid listed every built-in plugin twice (two Calculators, two Weathers, and so on) because the platform's seed rows were inserted a second time without the duplicate check ever catching them. There are now seven built-ins again, one of each, and the database refuses a duplicate outright. Three plugin API fixes ship with it: a plugin published as private was readable in full by anyone who knew its link, and its install counter could be driven by anyone; recording an install now reports the real new total instead of always answering &quot;ok&quot;, and counts one install per person per plugin rather than one per click; and asking for a page of plugins with a malformed cursor now returns a plain validation error rather than a server error.</description>
+ </item>
<item>
<title>Recurring payments now have a home, a pause button, and a receipt for every charge</title>
<link>https://three.ws/recurring</link>
@@ -94,6 +126,22 @@
<category>feature</category>
<description>Sign one permission and a fixed amount of USDC moves to an agent every day or week, or gets swapped into a token on a schedule. Until now there was no page for any of that: you could start a schedule from a skill and then never see it again, and one bad hour on the network ended it for good, because nothing could turn a paused schedule back on. The new /recurring page is the whole life of a schedule in one place. Create one, pause it, resume it, cancel it, and read every charge it has ever made with the transaction hash next to it. A second tab shows what is being paid into your own agents, with the paying wallet and the running total. When a period fails you now get told why, in a sentence: a revoked permission pauses the schedule and says so, a wallet short of USDC keeps the schedule alive and retries once you top up, and a charge that timed out is never retried at all, because that is the one case that could take your money twice.</description>
</item>
+ <item>
+ <title>Sharing a build now checks that the coin world you are sharing to is real</title>
+ <link>https://three.ws/play</link>
+ <guid isPermaLink="false">2026-08-14:Sharing a build now checks that the coin world you are sharing to is real</guid>
+ <pubDate>Fri, 14 Aug 2026 12:00:00 GMT</pubDate>
+ <category>security</category>
+ <description>When you screenshot a voxel build in a coin's /play world and share it, the build is filed under that coin's address. The endpoint only checked that the address was the right length, not that it was an address at all, so anything between 32 and 64 characters was accepted and filed away under its own storage slot. It now checks the format the way every other coin-world surface does: a Solana mint or an EVM contract address gets through, anything else is turned away before it reaches storage. Real worlds are unaffected, on both Solana and the EVM chains. The live event board picked up its own test coverage in the same pass, including a check that a player's account key never appears in what the board sends to the browser.</description>
+ </item>
+ <item>
+ <title>The $THREE holder count is back on the token page and its share card</title>
+ <link>https://three.ws/three-token</link>
+ <guid isPermaLink="false">2026-08-14:The $THREE holder count is back on the token page and its share card</guid>
+ <pubDate>Fri, 14 Aug 2026 12:00:00 GMT</pubDate>
+ <category>fix</category>
+ <description>The holder count on the /three-token page, and on the badge image that previews wherever a $THREE link is shared, had been showing a dash instead of a number. Our own holder snapshot is rebuilt from a Solana indexer that has been refusing the scan, and once the snapshot went stale the page correctly declined to show an out-of-date figure, so the count simply disappeared rather than being briefly missing. Holder count now falls back to a second, independent source when our snapshot cannot refresh, so the figure stays real and current through an indexer outage. The share card was also reading a narrower set of sources than the page it mirrors, which is why the two could disagree; both now read the same ones. Separately, a shared agent link unfurls noticeably faster: the card was fetching the agent's portrait only after every other lookup had finished, and now fetches it alongside them.</description>
+ </item>
<item>
<title>The agent directory describes itself correctly in all 84 languages again</title>
<link>https://three.ws/agents</link>
@@ -118,6 +166,14 @@
<category>fix</category>
<description>The CC0 prop library at /objects reads a single index file from the CDN. If that file were ever uploaded truncated or in the wrong shape, the gallery treated it as a library with nothing in it and told the CDN to remember that answer for the next five minutes, so a bad upload kept the shelves bare long after it was replaced. A damaged index is now handled the same way as the CDN being briefly unreachable: the page stays quiet, nothing gets cached, and the props come back on the very next request. Two smaller fixes went with it: a request with a broken page cursor (a limit of &quot;abc&quot;, a negative offset) is rejected outright instead of first fetching an index it was never going to use, and the developer documentation no longer claims the library API can be called from any website, which it cannot; it answers three.ws and its partner sites, and everything it points at is still yours to download and reuse anywhere.</description>
</item>
+ <item>
+ <title>The internal money and platform health boards tell the truth again</title>
+ <link>https://three.ws/changelog</link>
+ <guid isPermaLink="false">2026-08-14:The internal money and platform health boards tell the truth again</guid>
+ <pubDate>Fri, 14 Aug 2026 12:00:00 GMT</pubDate>
+ <category>fix</category>
+ <description>Three internal dashboards watch the platform for us: one for site and cron health, one for every money subsystem, one for payment outcomes. Two of them had gone quietly wrong. The platform board judged each scheduled job against a hand-written idea of how often it should run, and three jobs that run once a day were being judged against a window of minutes, so they reported as broken for roughly 23 hours out of every day and the board could never come back all-clear; every job is now measured against the schedule it genuinely runs on. One of its probes was also posting to a payments endpoint without declaring it was sending JSON, so it had been failing on its own mistake rather than on anything real. The money board was reading the wrong timestamp column on two payment logs and showing no activity at all for a payment ring that settles thousands of payments a day. It also accepted the credential our fund-moving scheduled jobs carry as an ops password; it now takes the same admin sign-in as the other boards, so an ops credential can never be escalated into triggering a payment job.</description>
+ </item>
<item>
<title>The limits you set on an agent's spending can no longer be skipped</title>
<link>https://three.ws/docs/a2a-payments</link>
diff --git a/public/demos/selfie-fit.html b/public/demos/selfie-fit.html
index 5760968f2..0a57b7aaa 100644
--- a/public/demos/selfie-fit.html
+++ b/public/demos/selfie-fit.html
@@ -256,6 +256,24 @@
const $ = (sel, root = document) => root.querySelector(sel);
const $$ = (sel, root = document) => Array.from(root.querySelectorAll(sel));
+ // Both submit endpoints below are cookie-session mutations behind the
+ // double-submit CSRF check (api/_lib/csrf.js), so each POST needs its
+ // own freshly minted token: they are single-use and burned on first
+ // use, which is why this mints per call rather than caching one.
+ // Signed-out visitors get null and the POST answers 401, which the
+ // submit handler already surfaces.
+ async function csrfHeader() {
+ try {
+ const r = await fetch('/api/csrf-token', { credentials: 'include' });
+ if (!r.ok) return {};
+ const j = await r.json();
+ const token = j?.data?.token || j?.token;
+ return token ? { 'x-csrf-token': token } : {};
+ } catch {
+ return {};
+ }
+ }
+
// ── Face quality scoring ─────────────────────────────────────────────
// Blur: variance of the 4-neighbour Laplacian on a 64×64 face crop.
// Scores below BLUR_MIN indicate the frame is too blurry to use.
@@ -886,7 +904,7 @@
const nativeRes = await fetch('/api/avatars/reconstruct', {
method: 'POST',
credentials: 'include',
- headers: { 'content-type': 'application/json' },
+ headers: { 'content-type': 'application/json', ...(await csrfHeader()) },
body: JSON.stringify({
name: `Selfie ${new Date().toISOString().slice(0, 10)}`,
photos: [photos.frontal, photos.left, photos.right],
@@ -919,7 +937,7 @@
const res = await fetch('/api/onboarding/avaturn-session', {
method: 'POST',
credentials: 'include',
- headers: { 'content-type': 'application/json' },
+ headers: { 'content-type': 'application/json', ...(await csrfHeader()) },
body: JSON.stringify({
photos,
body_type: state.bodyType,
diff --git a/public/features.json b/public/features.json
index 903cf670f..5424b1164 100644
--- a/public/features.json
+++ b/public/features.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-08-14T02:25:26.784Z",
+ "generated_at": "2026-08-14T04:43:15.777Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json",
"site": {
"name": "three.ws",
diff --git a/src/avaturn-client.js b/src/avaturn-client.js
index 86e206116..0e5781162 100644
--- a/src/avaturn-client.js
+++ b/src/avaturn-client.js
@@ -20,6 +20,8 @@
* });
*/
+import { consumeCsrfToken } from './api.js';
+
const SESSION_ENDPOINT = '/api/onboarding/avaturn-session';
const OVERALL_TIMEOUT_MS = 120_000;
// Reject immediately if session expires within this many ms.
@@ -66,11 +68,21 @@ export function blobToDataUrl(blob) {
*/
export async function createAvaturnSession({ front, left, right }) {
let res;
+ // The endpoint is a cookie-session mutation, so it carries the double-submit
+ // CSRF check (api/_lib/csrf.js). apiFetch() would attach the token for us but
+ // it also redirects the page to /login on a 401, which would swallow the
+ // 'auth' AvaturnError callers below depend on; consumeCsrfToken() is the
+ // documented escape hatch for exactly that case. A null token (signed out)
+ // still goes out and comes back as the 401 this client already handles.
+ const csrfToken = await consumeCsrfToken().catch(() => null);
try {
res = await fetch(SESSION_ENDPOINT, {
method: 'POST',
credentials: 'include',
- headers: { 'content-type': 'application/json' },
+ headers: {
+ 'content-type': 'application/json',
+ ...(csrfToken ? { 'x-csrf-token': csrfToken } : {}),
+ },
// API schema field is 'frontal'; caller-facing param is 'front' for brevity.
body: JSON.stringify({ photos: { frontal: front, left, right } }),
});
diff --git a/tests/api/onboarding-actions.test.js b/tests/api/onboarding-actions.test.js
new file mode 100644
index 000000000..6dfc3391a
--- /dev/null
+++ b/tests/api/onboarding-actions.test.js
@@ -0,0 +1,350 @@
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
+import { invoke } from '../_helpers/monetization.js';
+
+// api/onboarding/[action].js fans two actions out of one handler:
+// POST /api/onboarding/avaturn-session spends the avatar provider's quota
+// POST /api/onboarding/link-avatar repoints which body an agent wears
+//
+// Both are cookie-session-reachable state changes, so both must sit behind the
+// double-submit CSRF check every other session mutation in api/ carries. They
+// did not: a cross-site form POST rode the victim's cookie straight through.
+// These cases pin the guard, plus the credential rules the two share (session
+// or an avatars:write bearer, 403 rather than 401 on a scope miss) and the
+// upstream-failure mapping that keeps provider internals out of the caller's
+// response.
+
+const authState = { session: null, bearer: null };
+const csrfState = { rows: [] };
+const dbState = { avatars: [], agents: [], updates: [] };
+const rlState = { upload: true, authIp: true, avatarLink: true };
+
+vi.mock('../../api/_lib/auth.js', () => ({
+ getSessionUser: vi.fn(async () => authState.session),
+ authenticateBearer: vi.fn(async () => authState.bearer),
+ extractBearer: vi.fn((req) => {
+ const header = req?.headers?.authorization || '';
+ return header.startsWith('Bearer ') ? header.slice(7) : null;
+ }),
+ hasScope: vi.fn((scope, want) => String(scope || '').split(/[\s,]+/).includes(want)),
+}));
+
+// One fake `sql` tag serves both the CSRF token burn and the two onboarding
+// reads, keyed off the text of the template so each call answers in its own
+// shape rather than every query seeing the same rows.
+vi.mock('../../api/_lib/db.js', () => {
+ const sql = vi.fn(async (strings, ...values) => {
+ const text = strings.join(' ? ').toLowerCase();
+ if (text.includes('csrf_tokens')) {
+ const [token, userId] = values;
+ const idx = csrfState.rows.findIndex((r) => r.token === token && r.user_id === userId);
+ if (idx === -1) return [];
+ return csrfState.rows.splice(idx, 1).map((r) => ({ user_id: r.user_id }));
+ }
+ if (text.includes('from avatars')) {
+ const [avatarId, ownerId] = values;
+ return dbState.avatars.filter((a) => a.id === avatarId && a.owner_id === ownerId);
+ }
+ if (text.includes('from agent_identities')) {
+ const [userId] = values;
+ return dbState.agents.filter((a) => a.user_id === userId);
+ }
+ if (text.includes('update agent_identities')) {
+ const [avatarId, agentId] = values;
+ dbState.updates.push({ agentId, avatarId });
+ return [{ id: agentId, avatar_id: avatarId, updated_at: '2026-08-14T00:00:00.000Z' }];
+ }
+ throw new Error(`unexpected query in test: ${text}`);
+ });
+ return { sql, isDbUnavailableError: () => false, isDbCapacityError: () => false };
+});
+
+vi.mock('../../api/_lib/rate-limit.js', () => ({
+ limits: {
+ upload: vi.fn(async () => ({ success: rlState.upload, limit: 60, remaining: 0, reset: 0 })),
+ authIp: vi.fn(async () => ({ success: rlState.authIp, limit: 60, remaining: 0, reset: 0 })),
+ avatarLink: vi.fn(async () => ({ success: rlState.avatarLink, limit: 30, remaining: 0, reset: 0 })),
+ },
+ clientIp: vi.fn(() => '127.0.0.1'),
+}));
+
+const { default: handler } = await import('../../api/onboarding/[action].js');
+
+const USER = 'user-onboarding-1';
+const AVATAR_ID = '00000000-0000-4000-8000-00000000a1a1';
+const AGENT_ID = '00000000-0000-4000-8000-00000000b2b2';
+const PHOTO = `data:image/jpeg;base64,${'A'.repeat(64)}`;
+const PHOTOS = { frontal: PHOTO, left: PHOTO, right: PHOTO };
+
+function withCsrf(userId = USER) {
+ const token = `csrf-${csrfState.rows.length + 1}`;
+ csrfState.rows.push({ token, user_id: userId });
+ return { 'x-csrf-token': token };
+}
+
+function sessionReq(action, { body = {}, headers = {} } = {}) {
+ return {
+ method: 'POST',
+ url: `/api/onboarding/${action}`,
+ query: { action },
+ headers: { origin: 'https://three.ws', ...headers },
+ body,
+ };
+}
+
+beforeEach(() => {
+ authState.session = { id: USER };
+ authState.bearer = null;
+ csrfState.rows = [];
+ dbState.avatars = [{ id: AVATAR_ID, owner_id: USER }];
+ dbState.agents = [{ id: AGENT_ID, user_id: USER, avatar_id: null }];
+ dbState.updates = [];
+ rlState.upload = true;
+ rlState.authIp = true;
+ rlState.avatarLink = true;
+ process.env.AVATURN_API_KEY = 'test-avaturn-key';
+ process.env.AVATURN_API_URL = 'https://avaturn.test';
+ // The guard under test has a non-production escape hatch; an operator's stray
+ // CSRF_DISABLED=1 in the shell must not quietly turn these cases green.
+ delete process.env.CSRF_DISABLED;
+ vi.unstubAllGlobals();
+});
+
+afterEach(() => {
+ delete process.env.AVATURN_API_KEY;
+ delete process.env.AVATURN_API_URL;
+ vi.unstubAllGlobals();
+});
+
+function stubUpstream(response) {
+ const fetchMock = vi.fn(async () => response);
+ vi.stubGlobal('fetch', fetchMock);
+ return fetchMock;
+}
+
+function upstreamOk(payload) {
+ return { ok: true, status: 200, headers: new Headers(), json: async () => payload, text: async () => JSON.stringify(payload) };
+}
+
+function upstreamFail(status, body = '', headers = {}) {
+ return { ok: false, status, headers: new Headers(headers), json: async () => null, text: async () => body };
+}
+
+describe('onboarding CSRF guard', () => {
+ it('rejects a cookie-session avaturn-session POST that carries no CSRF token', async () => {
+ const fetchMock = stubUpstream(upstreamOk({ session_url: 'https://avaturn.test/s/1' }));
+ const { status, body } = await invoke(handler, sessionReq('avaturn-session', { body: { photos: PHOTOS } }));
+ expect(status).toBe(403);
+ expect(body.error).toBe('csrf_missing');
+ // The provider must never be called on a request that failed the guard.
+ expect(fetchMock).not.toHaveBeenCalled();
+ });
+
+ it('rejects a cookie-session link-avatar POST that carries no CSRF token', async () => {
+ const { status, body } = await invoke(handler, sessionReq('link-avatar', { body: { avatarId: AVATAR_ID } }));
+ expect(status).toBe(403);
+ expect(body.error).toBe('csrf_missing');
+ expect(dbState.updates).toEqual([]);
+ });
+
+ it('rejects a token minted for a different user', async () => {
+ csrfState.rows.push({ token: 'someone-elses', user_id: 'user-other' });
+ const { status, body } = await invoke(
+ handler,
+ sessionReq('link-avatar', { body: { avatarId: AVATAR_ID }, headers: { 'x-csrf-token': 'someone-elses' } }),
+ );
+ expect(status).toBe(403);
+ expect(body.error).toBe('csrf_invalid');
+ expect(dbState.updates).toEqual([]);
+ // The other user's token survives for its rightful owner.
+ expect(csrfState.rows).toHaveLength(1);
+ });
+
+ it('exempts bearer callers, which browsers never auto-attach', async () => {
+ authState.session = null;
+ authState.bearer = { userId: USER, scope: 'avatars:read avatars:write' };
+ const { status, body } = await invoke(
+ handler,
+ sessionReq('link-avatar', { body: { avatarId: AVATAR_ID }, headers: { authorization: 'Bearer key-1' } }),
+ );
+ expect(status).toBe(200);
+ expect(body.agent.avatar_id).toBe(AVATAR_ID);
+ });
+});
+
+describe('onboarding credential rules', () => {
+ it('answers 401 when neither a session nor a bearer identifies the caller', async () => {
+ authState.session = null;
+ const { status, body } = await invoke(handler, sessionReq('avaturn-session', { body: { photos: PHOTOS } }));
+ expect(status).toBe(401);
+ expect(body.error).toBe('unauthorized');
+ });
+
+ it('answers 403 insufficient_scope, not 401, for a read-only bearer', async () => {
+ authState.session = null;
+ authState.bearer = { userId: USER, scope: 'avatars:read' };
+ const { status, body } = await invoke(
+ handler,
+ sessionReq('link-avatar', { body: { avatarId: AVATAR_ID }, headers: { authorization: 'Bearer key-ro' } }),
+ );
+ expect(status).toBe(403);
+ expect(body.error).toBe('insufficient_scope');
+ expect(dbState.updates).toEqual([]);
+ });
+
+ it('404s an unknown action instead of throwing', async () => {
+ const { status, body } = await invoke(handler, sessionReq('bogus', { body: {} }));
+ expect(status).toBe(404);
+ expect(body.error).toBe('not_found');
+ });
+});
+
+describe('avaturn-session', () => {
+ it('returns the provider session url on the success path', async () => {
+ const fetchMock = stubUpstream(upstreamOk({ session_url: 'https://avaturn.test/s/9', expires_at: '2026-08-14T01:00:00Z' }));
+ const { status, body } = await invoke(
+ handler,
+ sessionReq('avaturn-session', { body: { photos: PHOTOS, body_type: 'female', avatar_type: 'v2' }, headers: withCsrf() }),
+ );
+ expect(status).toBe(200);
+ expect(body).toEqual({ session_url: 'https://avaturn.test/s/9', expires_at: '2026-08-14T01:00:00Z' });
+ const [url, init] = fetchMock.mock.calls[0];
+ expect(url).toBe('https://avaturn.test/api/v1/sessions');
+ expect(JSON.parse(init.body)).toMatchObject({ external_user_id: USER, body_type: 'female', version: 'v2' });
+ });
+
+ it('rejects a photo that is not a jpeg/png data url with a 400', async () => {
+ const fetchMock = stubUpstream(upstreamOk({ session_url: 'https://avaturn.test/s/1' }));
+ const { status, body } = await invoke(
+ handler,
+ sessionReq('avaturn-session', {
+ body: { photos: { ...PHOTOS, left: 'https://example.com/left.jpg' } },
+ headers: withCsrf(),
+ }),
+ );
+ expect(status).toBe(400);
+ expect(body.error).toBe('validation_error');
+ expect(fetchMock).not.toHaveBeenCalled();
+ });
+
+ it('answers 501 without charging the caller’s upload budget when the key is unset', async () => {
+ delete process.env.AVATURN_API_KEY;
+ const { limits } = await import('../../api/_lib/rate-limit.js');
+ limits.upload.mockClear();
+ const { status, body } = await invoke(
+ handler,
+ sessionReq('avaturn-session', { body: { photos: PHOTOS }, headers: withCsrf() }),
+ );
+ expect(status).toBe(501);
+ expect(body.error).toBe('not_configured');
+ expect(limits.upload).not.toHaveBeenCalled();
+ });
+
+ it('maps a provider 5xx to a 502 that carries none of the provider’s text', async () => {
+ stubUpstream(upstreamFail(500, 'avaturn internal: key sk-live-abc rejected by shard 3'));
+ const { status, body } = await invoke(
+ handler,
+ sessionReq('avaturn-session', { body: { photos: PHOTOS }, headers: withCsrf() }),
+ );
+ expect(status).toBe(502);
+ expect(body.error).toBe('upstream_error');
+ expect(body.error_description).not.toContain('sk-live-abc');
+ });
+
+ it('passes a provider 400 through as a caller-fixable 400', async () => {
+ stubUpstream(upstreamFail(400, 'no face detected in the frontal photo'));
+ const { status, body } = await invoke(
+ handler,
+ sessionReq('avaturn-session', { body: { photos: PHOTOS }, headers: withCsrf() }),
+ );
+ expect(status).toBe(400);
+ expect(body.error).toBe('upstream_rejected');
+ expect(body.error_description).toContain('no face detected');
+ });
+
+ it('surfaces a provider 429 as upstream_busy with a retry-after', async () => {
+ stubUpstream(upstreamFail(429, 'slow down', { 'retry-after': '45' }));
+ const { res, status, body } = await invoke(
+ handler,
+ sessionReq('avaturn-session', { body: { photos: PHOTOS }, headers: withCsrf() }),
+ );
+ expect(status).toBe(429);
+ expect(body.error).toBe('upstream_busy');
+ expect(res.headers['retry-after']).toBe('45');
+ });
+
+ it('502s a provider response that carries no session url', async () => {
+ stubUpstream(upstreamOk({ ok: true }));
+ const { status, body } = await invoke(
+ handler,
+ sessionReq('avaturn-session', { body: { photos: PHOTOS }, headers: withCsrf() }),
+ );
+ expect(status).toBe(502);
+ expect(body.error).toBe('upstream_error');
+ });
+});
+
+describe('link-avatar', () => {
+ it('links the avatar to the caller’s first agent identity', async () => {
+ const { status, body } = await invoke(
+ handler,
+ sessionReq('link-avatar', { body: { avatarId: AVATAR_ID }, headers: withCsrf() }),
+ );
+ expect(status).toBe(200);
+ expect(body.agent).toMatchObject({ id: AGENT_ID, avatar_id: AVATAR_ID });
+ expect(dbState.updates).toEqual([{ agentId: AGENT_ID, avatarId: AVATAR_ID }]);
+ });
+
+ it('404s an avatar owned by someone else', async () => {
+ dbState.avatars = [{ id: AVATAR_ID, owner_id: 'user-other' }];
+ const { status, body } = await invoke(
+ handler,
+ sessionReq('link-avatar', { body: { avatarId: AVATAR_ID }, headers: withCsrf() }),
+ );
+ expect(status).toBe(404);
+ expect(body.error).toBe('not_found');
+ expect(dbState.updates).toEqual([]);
+ });
+
+ it('409s when the agent already wears a different avatar and force is absent', async () => {
+ const other = '00000000-0000-4000-8000-00000000c3c3';
+ dbState.agents = [{ id: AGENT_ID, user_id: USER, avatar_id: other }];
+ const { status, body } = await invoke(
+ handler,
+ sessionReq('link-avatar', { body: { avatarId: AVATAR_ID }, headers: withCsrf() }),
+ );
+ expect(status).toBe(409);
+ expect(body.error).toBe('already_linked');
+ expect(body.current_avatar_id).toBe(other);
+ expect(dbState.updates).toEqual([]);
+ });
+
+ it('overrides an existing link when force is set', async () => {
+ dbState.agents = [{ id: AGENT_ID, user_id: USER, avatar_id: '00000000-0000-4000-8000-00000000c3c3' }];
+ const { status } = await invoke(
+ handler,
+ sessionReq('link-avatar', { body: { avatarId: AVATAR_ID, force: true }, headers: withCsrf() }),
+ );
+ expect(status).toBe(200);
+ expect(dbState.updates).toEqual([{ agentId: AGENT_ID, avatarId: AVATAR_ID }]);
+ });
+
+ it('400s a non-uuid avatarId before touching the database', async () => {
+ const { status, body } = await invoke(
+ handler,
+ sessionReq('link-avatar', { body: { avatarId: 'not-a-uuid' }, headers: withCsrf() }),
+ );
+ expect(status).toBe(400);
+ expect(body.error).toBe('validation_error');
+ expect(dbState.updates).toEqual([]);
+ });
+
+ it('429s when the per-user link limiter is exhausted', async () => {
+ rlState.avatarLink = false;
+ const { status } = await invoke(
+ handler,
+ sessionReq('link-avatar', { body: { avatarId: AVATAR_ID }, headers: withCsrf() }),
+ );
+ expect(status).toBe(429);
+ expect(dbState.updates).toEqual([]);
+ });
+});