Skip to content

Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.

fix(widgets,billing): validate widget actions and x402 checkout CSRF, and regenerate the public feed

nirholasdb97d910a004
diff --git a/CHANGELOG.md b/CHANGELOG.md
index b7bd84432..6bec99928 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-15
- **A broken paid endpoint is no longer reported as a free one**: Payment sessions let you hand an agent a budget instead of a key, and two parts of that path judged an endpoint by one rule: if it did not ask for payment, the call was free. That is only true when the endpoint actually succeeded. A paid API answering 404, 400, or 500 was being scored as a free call, and the consequences ran in the wrong direction in both places. The dry run at /pay/simulator, whose whole job is to tell you in advance whether a budget and an allowlist will carry a workload, reported a plan as feasible at a cost of nothing when in fact every endpoint in it was erroring: free calls are never priced, never allowlist-checked, and never counted, so a wall of failures looked like a clean run. And an agent spending through a session got back a success envelope saying no payment was needed for an endpoint that had just failed on it. Both now separate the two cases: a real success with no payment challenge is still free and still costs nothing, while an error status is reported as an endpoint failure carrying the status the endpoint actually returned. No session is charged either way. The simulator lists each failing endpoint by name in its problems list and no longer calls the plan feasible. (`/pay/simulator`) `[fix]`
+- **A market intelligence outage no longer tells you your own API key was rejected**: The two market intelligence reads in the unified API, recent narrative intel and momentum-ranked projects, pass a key we hold to the upstream provider; a caller needs no key at all. When that provider stopped accepting our key, both reads answered "unauthorized" with the provider's own wording, so an agent reading the response concluded its own credentials were bad and retried with different ones forever, when nothing on the caller's side was wrong. Both reads now say plainly that the service is temporarily unavailable because this deployment's upstream key was rejected, which is a status clients already know to retry rather than re-authenticate against. The older market intelligence endpoints always classified this correctly; the classification now lives in one place, so the two doors cannot drift apart again, and the error tables in the API reference list every code either one can return. (`/docs/api-reference`) `[fix, docs]`
- **A profile’s follower count now matches the people the follower list can actually show you**: The follower and following numbers on a profile counted every follow ever recorded, including ones from accounts that were later deleted or that never claimed a username. The list behind those numbers only shows people you can open a profile for, so a profile could advertise followers and then open to an empty list. Both numbers are now counted over exactly the people the list renders, so the badge and the list always agree. The list itself also stopped dropping those accounts only after it had already paged, which could hand you a blank page of followers with no way to reach the real ones behind it. Separately, the Creations tab used to answer a corrupted page cursor with a silent empty page that read as "nothing more to load"; it now says the cursor is malformed, and an unknown filter is rejected instead of quietly returning everything. `[fix]`
- **A retried agent spend can no longer hand its transaction to somebody else, and an unsupported chain says so instead of blaming the network**: When an agent redeems a permission you granted it, it can send a retry key so a request whose answer it never saw is not paid for twice. That key was filed under the permission alone rather than under the agent that used it, and it was read before the check that the caller owns the permission at all, so a different agent replaying the same permission and key was handed the original transaction hash and receipt instead of being turned away. The key is now filed per caller: a retry only ever returns your own result, and anyone else gets the same not-found answer they should always have got. Two more fixes in the same endpoint. A permission recorded on a chain three.ws has no delegation contract on could never settle, but the attempt came back as a network error, which reads as a temporary outage worth retrying rather than the permanent chain mismatch it is; it is now named plainly and refused before it consumes any of the permission's spending allowance. And the relayer kept its own private one-address-per-chain list of blockchain endpoints, separate from the failover chain the rest of the platform uses, so it would have refused to work on the next supported chain even where the shared endpoints reach it fine. It now uses the shared list, with any operator override still taking priority. The permissions guide gained a section on how the retry key behaves and how long it lasts. (`/docs/permissions`) `[security, fix]`
- **A shared link to a docs page now opens that page instead of stranding you**: Every cross-reference inside a docs page turns into a link like /docs/agent-wallets#financial-controls. Following one worked, but the URL you copied afterwards did not: on a fresh load the viewer only recognised the second half if that doc happened to be listed in the sidebar, and silently left you on the page you arrived from otherwise. Links to Financial controls, the x402 payment tutorial, and the wallet access and proof-of-custody chapters all failed that way. The viewer now asks the server whether the doc exists before giving up, so those links land where they say they will, and the browser tab takes the destination's name. Separately, /docs/3d-api was serving the 3D API landing page rather than the reference doc that the API's own discovery response, the OpenAPI license link, and the docs sidebar all point at; it now serves the reference doc, and the landing page keeps its home at /3d. (`/docs/agent-wallets`) `[fix, docs]`
@@ -24,6 +25,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr
- **Eight build tutorials now match what the platform actually does**: An audit of eight tutorials found instructions that could not work. The AI-brain tutorial described a model line-up that had been superseded: it never mentioned the Claude 5 family (Sonnet 5, Opus 5, Fable 5), which are live and selectable, and it recommended Sonnet 4.6 as the default. It also sent you to screens that do not exist, telling you to add API keys under a gear icon in My Agents and to change models, sampling knobs, and streaming under a Brain menu. Provider keys actually live in the AI Provider Keys panel on your account page, the model is a field on the agent's embed policy, and streaming has no off-switch. The promised usage tab with token charts and threshold emails did not exist either; the tutorial now documents the real per-agent usage read and points at the monthly quota and per-minute rate limit, which are the controls actually enforced before your money is spent. It also now explains that a visitor can never escalate your agent onto a paid model. The custom-GLB tutorial was worse for anyone following along: it linked a Studio address that no longer resolves, and four of its commands invoked gltf-transform subcommands that have never existed, so converting an FBX, renaming animation clips, and the full Mixamo walkthrough all failed at the first step. Those are replaced with the converter the platform itself uses and a clip-renaming script that was run against a real avatar to confirm it works. Its Draco flag was wrong, its upload path pointed at the wrong page, and it still warned that an avatar without an idle clip would stand frozen in a T-pose, which stopped being true when animation retargeting became universal. Finally, the page-events tutorial listed the wrong fallback order for emote animations. (`/tutorials/connect-ai-brain`) `[docs, fix]`
- **Looking up an on-chain agent by its CAIP reference works again**: The public resolver that turns an ERC-8004 agent reference into its owner, token URI and verified agent card could not be reached at all. An agent reference ends in a slash before its token id, and the documentation told callers to percent-encode the whole reference, which turns that slash into %2F. The API refuses any address segment holding an encoded separator, because that is the same trick used to escape a path and reach files that were never meant to be served, so every correctly-formed lookup was turned away as an unknown address before it ever reached the resolver. The verification badge you can embed on your own site built its request in exactly that shape, so it never showed a result either. The resolver now accepts the reference with its slash as a normal part of the address, the badge asks for it that way, and the documentation shows the form that works. The protection against encoded separators is untouched. New tests resolve the address through the same routing the live site uses, so this cannot quietly break again. (`/docs/api-reference`) `[fix]`
- **Oracle stops answering "nothing is happening" when the database is the thing that is down**: Several Oracle reads shared a habit: if the database was unreachable for a few seconds, they answered normally with an empty result. The movers panel said nothing was moving, the stats hero said no coin had ever been scored and no agent was armed, a coin's conviction sparkline came back flat, and the machine-readable signal endpoint told autonomous agents there were no plays, which is exactly the cue for an agent to stand down. Every one of those answers was then cached at the edge for a minute or two, so a blip lasting seconds kept showing a dead market long after the database was back. Those endpoints now tell the difference between a connectivity failure and an ordinary query fault: the first is reported honestly as a temporary outage with a retry hint and is never cached, the second still degrades to the empty answer it always did. The social ingest got the sharper end of the same bug: it used to reply that a batch had been accepted while reporting zero mints written, a receipt for a write that never landed. It now fails loudly so the sender retries. Shared conviction cards behave too: one built during an outage is no longer pinned to a coin's link preview for 15 minutes. (`/oracle`) `[fix, improvement]`
+- **Paying for a skill by Solana Pay QR now shows a real three.ws merchant card**: When a wallet scans a Solana Pay code for a skill purchase, it first asks our server who the merchant is and shows the answer in the sheet you approve before signing. That reply pointed at a logo file that has never existed, so the icon came back as a 404 and the merchant appeared broken at the exact moment you decide whether to pay, under the retired 3D-Agent name rather than three.ws. The probe now returns the live logo and the current name, and answers wallets that ask from a browser, which the Solana Pay spec requires. Confirming a purchase through the off-web webhook also accepts the settlement hash an EVM payment needs, so a card that settled on Base can finish instead of sitting on pending forever, and a confirmation failure now reaches our error tracker rather than disappearing into a generic 500. (`/marketplace`) `[fix]`
- **Pinning an avatar to IPFS works for real avatars, not just tiny ones**: Minting an avatar from the Avatar Studio pins the model and its metadata to IPFS, and the whole file is sent through the platform so the storage credential never has to reach your browser. The endpoint said it accepted files up to 10 MB, but it was actually rejecting anything over roughly 730 KB, which is smaller than almost any real avatar. The error it gave back was a bare 'payload too large' that named no limit, so there was nothing to act on. The cause was two size limits that had never been reconciled: files are sent as text, which makes them a third larger in transit, and the transport limit was left at its default while the documented limit was set eight times higher. The limits now agree. Inline uploads are accepted up to 5 MB, which is what the request size can actually carry, and anything larger has a clear path: upload it to storage first and pin it by URL, a lane that has always accepted 50 MB. Over-sized uploads now say which ceiling was crossed. Two smaller fixes came with it: the filename you send is now the filename filed with the storage provider, instead of every avatar being stored as 'avatar.glb' and every metadata file as 'manifest.json', which made a pin list impossible to read; and a request with a genuine mistake in it, such as a file from somewhere the platform does not own, now gets an error explaining the mistake rather than a generic 'service unavailable' that hid it. The endpoint is now documented in the API reference. `[fix, docs]`
- **Plan checkout: a paid upgrade can only ever settle on real mainnet, and a late payment is no longer stranded**: Paying for a plan creates a quote, you send the funds, then the server checks the chain before it upgrades you. Three things in that path were wrong. The checkout side has always refused test-network quotes in production, because test-network dollars are free from a faucet, but the confirm side still let a caller name the test network itself, and it is the confirm side that decides which chain it looks at and which dollar it accepts. Both ends now read the same setting, so a production upgrade can only ever be settled by real funds on mainnet. Second, an Ethereum-side payment has to wait twelve blocks before it counts, which meant funds sent near the end of a session could land on-chain and then be refused for arriving late, with the money already gone; that lane now honors the same one-hour grace window the Solana lane has, so an on-chain payment is always claimable. Third, confirming an Ethereum payment could reach a Solana quote and mark it expired, and asking to buy a skill from a malformed agent id answered a generic server error instead of telling you what was wrong with the request. (`/pricing`) `[fix, security]`
- **Saving a big build no longer re-downloads the whole world first**: Every time you saved a world, the service fetched and re-parsed the entire previous version of that world just to check who owns it. On a large build that meant a full extra download and parse on each autosave, for a single ownership field. The check now reads only the small index record, so saves on big worlds are noticeably quicker and the storage layer does half the work. Two error replies also got honest labels: a build that exceeds the size cap now answers "payload too large" and a request sent with the wrong content type answers "unsupported media type", instead of both arriving as a generic validation error that gave a client nothing to act on. `[improvement, fix]`
@@ -46,6 +48,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr
- **The persona builder stops reporting a model outage as if you had been signed out**: The two routes behind the persona builder (the one that turns your interview answers or a sample of your own writing into a structured persona, and the one that replies to you in that persona's voice) used to hand you whatever status code the model provider returned. If a server-side key expired, the provider answered 401 and so did we, which reads to a browser as an expired session on a request where nothing was wrong with your sign-in. Both now report a provider failure as exactly what it is: a server-side fault, with a plain message and no implication that you need to log back in. Separately, when the platform's daily model-spend ceiling is reached, the builder now says so and tells you when it resets, instead of asking you to retry something that could not have succeeded for the rest of the day. Both routes also now record their model usage against your account, so the spend they generate is visible and capped rather than untracked, and the daily extraction budget now holds across every server instance instead of being counted separately on each one. `[fix, improvement]`
- **The plugin marketplace stops hiding a plugin when you page through it**: Browsing plugins a page at a time could show you the same plugin twice and never show another one at all. The catalogue was sorted by install count and publish date, and the built-in plugins were all published in the same instant with zero installs, so that sort left them tied and the database was free to order the tied rows differently on every request. One plugin therefore landed on two consecutive pages and one fell through the gap. The order is now decided all the way down, so paging through the catalogue returns every plugin exactly once. Searching also takes your text literally: typing a percent sign or an underscore used to act as a database wildcard and match rows it should not. Publishing got stricter at the same time, because a plugin manifest is handed to the model as a tool definition by whoever installs it: a tool name now has to be plain letters, digits, underscores, or hyphens, every tool needs a real description, and a manifest has to fit the same 64KB ceiling that importing one by URL already enforced. And pointing the importer at a repository web page instead of the raw manifest file now says exactly that, rather than showing a raw parser error. (`/marketplace`) `[fix, improvement]`
- **The pump.fun trade history works again, notification settings show every category, and a bad agent id stops reading as a server crash**: Three fixes across the public MCP packages and the API behind them. Asking for a token's recent buys and sells (get_token_trades on the free pump.fun MCP server) had stopped working entirely: the platform reads several transactions in one batched call, and the free Solana providers we route through cap those batches at one call each, so they rejected the whole request and the tool returned a raw provider error instead of trades. The platform now recognises that refusal, re-sends the reads one at a time to the same provider, and remembers the cap so later calls skip the wasted attempt; every batched on-chain read benefits, including wallet and agent activity history. Separately, the notifications MCP server told agents there were six notification categories when there are seven, so an agent could never change how it hears about a finished 3D generation; all seven are now listed, along with the security notices that always reach your bell inbox. And the agent provenance log answered a non-uuid agent id with an internal error and a support reference; it now says plainly that the id must be a uuid. `[fix, sdk]`
+- **The tokenized-stock board sorts the way you asked, with the busiest names first**: The Robinhood Chain stock board (and the API behind it) accepts a sort column and a direction. Both ran backwards: asking for the highest 24h volume returned the quietest tokens, the ones with no market at all led every column, and passing dir=asc handed back descending results. Numeric columns now read highest-first by default, dir=asc genuinely flips them, and a token with no price or no NAV feed sorts to the end in either direction instead of crowding the top. The response now also echoes the sort and direction that actually ran, so an unknown sort value comes back as the default it fell to rather than as the value you sent; the memecoin screener echoes its sort the same honest way. (`/markets/robinhood`) `[fix]`
- **The trades feed stopped labelling a winning exit with a losing multiple**: When an agent sells part of a position to take its initial stake back and lets the rest ride, only that final sell is recorded against the position, while the profit percentage covers both sells. The feed was working out the “×” badge from the final sell alone, so a trade that returned +88% could show up as “0.56× +88%” on the same row. The multiple is now worked out from the trade's actual return, so the two numbers always agree. A coin's page also asked the feed for every trade on that coin and was quietly given only the ones above +10%, hiding the rest of that coin's history; it now gets what it asked for. The feed also answers a malformed page cursor or coin address by saying so, instead of returning results for the wrong coin, and a database problem no longer looks like a platform where nobody has ever turned a profit. (`/trades`) `[fix]`
- **The trading and MCP docs now match what the code and the live API actually do**: An audit of eight documentation pages ran every command they print and checked every claim against the code behind it, then corrected what had drifted. The biggest one was in the trading tutorial: the command it gave you for verifying a fleet's fills on-chain asked for a field the leaderboard does not publish, so it returned an empty explorer link for every agent and the verification step could not be completed at all. It now uses the fields that exist, linking both legs of each trade straight to Solscan, and it skips agents whose wallet has not been provisioned yet instead of building a URL that goes nowhere. The MCP tool safety page undercounted the tools that share a name across two servers, which matters because that collision is exactly why a trust policy has to key on the namespaced id; it now lists all nine and prints a command that re-derives the list so it cannot go stale again. The MCP tool catalog itself had drifted from its source and was serving outdated descriptions for three tools, on a page whose whole promise is that it is generated from source and cannot drift; it has been regenerated. The package extraction guide had every version in its roster out of date along with its build and test columns, and still described a publisher field as missing that was set some time ago. The 10 SOL trading experiment page stated a risk rule in absolute terms that contradicted the setup script it tells you to run, which read as a bug in one of the two; the rule now carries the scope the code actually applies. (`/docs/mcp-safety`) `[docs, fix]`
- **The Tutor’s running tab and end-of-session invoice now show what you actually paid**: The Tutor charges one cent per answer and keeps an itemized tab you can reload later and close for a signed invoice. That ledger only ever knew how to store itself in a key-value service this deployment does not run, so nothing was ever written down: reopening the page never restored your history, and ending a session always produced an invoice reading "no questions" and a total of zero, however many answers you had paid for. The tab is now stored in the platform’s own database, so it survives a reload, a new browser tab, and any server restart, and the invoice lists every answer with its charge and a verification hash over the line items. Closing a session twice returns the identical invoice instead of a freshly stamped one, closing a session id that was never used no longer makes that id unusable for its real owner, and if the ledger itself is ever unreachable the page says so rather than quietly reporting that you owe nothing. Asking a question still succeeds even if the ledger write fails, because a bookkeeping outage should never cost you the answer you paid for. (`/tutor`) `[fix]`
diff --git a/api/widgets/[id]/[action].js b/api/widgets/[id]/[action].js
index 29f42bcc0..fa29b4076 100644
--- a/api/widgets/[id]/[action].js
+++ b/api/widgets/[id]/[action].js
@@ -832,6 +832,13 @@ async function loadWidget(id) {
// random thread so the turn still lands in widget_chat_messages and the
// creator's "messages today" counter is accurate, even if it can't be grouped.
async function persistTurn({ widgetId, req, body, userMessage, reply, actions, provider, model }) {
+ // Gallery demo widgets are baked-in fixtures with no row in `widgets`, and
+ // widget_chat_threads.widget_id is a foreign key onto that table. Every
+ // public demo chat therefore hit a constraint violation and logged one
+ // "persist failed" line per message. Nobody owns a fixture, so there is no
+ // transcript or stats surface to write to: skip the write instead.
+ if (isDemoWidgetId(widgetId)) return;
+
const visitorId = body.visitor_id || `anon_${crypto.randomBytes(6).toString('base64url')}`;
const threadId = body.thread_id || `wct_${crypto.randomBytes(9).toString('base64url')}`;
diff --git a/data/changelog.json b/data/changelog.json
index 3bbc4013a..b14d5a168 100644
--- a/data/changelog.json
+++ b/data/changelog.json
@@ -1,6 +1,25 @@
{
"$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-15",
+ "title": "The Duplicate button on your widgets works again",
+ "summary": "Duplicating a widget from the dashboard failed every single time. The clone request never gave the new widget an identifier, and because the database requires one, the copy was rejected before it was written and the page showed only a generic server error with a support reference. A second, correct copy of the same clone logic was already in the codebase and the route simply was not using it; the route now runs that one, so duplicating gives you a real new widget with its own id, its own name ending in (copy), and the original's type, look, avatar and visibility carried over. The duplicate request also now carries the same cross-site request protection every other widget change already had, and it accepts an API key with write access, so you can clone a widget from a script as well as from the dashboard. Two smaller corrections travelled with it. When no chat provider is configured and the platform answers a visitor with its own placeholder line, that message is no longer filed in your transcript as though a model had written it. And chatting with one of the showcase widgets in the public gallery no longer tries to file a transcript against a widget that does not exist, which failed on every message. The developer reference now documents duplicate, stats, chat, transcripts and the knowledge base, all of which were live but undocumented.",
+ "tags": [
+ "fix",
+ "docs"
+ ],
+ "link": "/dashboard/widgets"
+ },
+ {
+ "date": "2026-08-15",
+ "title": "Paying for a skill by Solana Pay QR now shows a real three.ws merchant card",
+ "summary": "When a wallet scans a Solana Pay code for a skill purchase, it first asks our server who the merchant is and shows the answer in the sheet you approve before signing. That reply pointed at a logo file that has never existed, so the icon came back as a 404 and the merchant appeared broken at the exact moment you decide whether to pay, under the retired 3D-Agent name rather than three.ws. The probe now returns the live logo and the current name, and answers wallets that ask from a browser, which the Solana Pay spec requires. Confirming a purchase through the off-web webhook also accepts the settlement hash an EVM payment needs, so a card that settled on Base can finish instead of sitting on pending forever, and a confirmation failure now reaches our error tracker rather than disappearing into a generic 500.",
+ "tags": [
+ "fix"
+ ],
+ "link": "/marketplace"
+ },
{
"date": "2026-08-15",
"title": "A market intelligence outage no longer tells you your own API key was rejected",
diff --git a/docs/api-reference.md b/docs/api-reference.md
index b9e89f746..321ed28b4 100644
--- a/docs/api-reference.md
+++ b/docs/api-reference.md
@@ -372,6 +372,79 @@ Requires auth. Owner only. Soft-deletes via `deleted_at` timestamp.
---
+### Duplicate widget
+
+```
+POST /api/widgets/:id/duplicate
+```
+
+Requires auth. Owner only; bearer tokens need `avatars:write`. Clones the widget's type, name, config, avatar, and visibility into a new row with a freshly minted `wdgt_` id and ` (copy)` appended to the name (truncated to 120 characters). Cookie-session callers must send `X-CSRF-Token`; bearer callers are exempt.
+
+**Response** (`201`): the new widget object, same shape as create.
+
+---
+
+### Widget stats
+
+```
+GET /api/widgets/:id/stats
+```
+
+Requires auth. Owner only; bearer tokens need `avatars:read`. Returns the analytics envelope behind the dashboard's widget card: lifetime `view_count`, `last_viewed_at`, an 8-day zero-filled `recent_views_7d` sparkline, and the top five `top_referers` / `top_countries`.
+
+Talking-agent widgets additionally get `chat_count`, an 8-day `recent_chats_7d` sparkline of visitor messages, `top_questions` (visitor messages clustered by normalized prefix), `knowledge` (`doc_count` / `chunk_count` / `token_count`), and `sessions_7d` (`thread_count`, `avg_seconds`, `total_messages`). Those five fields are `null` for every other type. Response is cached `private, max-age=30`.
+
+---
+
+### Widget chat
+
+```
+POST /api/widgets/:id/chat
+```
+
+Talking-agent widgets only. Public widgets accept anonymous visitors; a private widget answers `404` to anyone but its owner. Rate limited per (IP, widget) at the owner's `config.visitorRateLimit.msgsPerMinute` (default 8); the owner's own preview is exempt.
+
+**Request body:** `{ message, history?, provider?, model?, visitor_id?, thread_id? }`. `message` is 1 to 4000 characters, `history` is up to 40 `{ role, content }` turns, and `visitor_id` / `thread_id` are opaque client-minted ids (8 to 64 url-safe characters) used to group transcripts. `provider` / `model` are honoured only when the owner left the brain on `auto` or a named provider; an owner who pinned `none` or `custom` cannot be overridden by a visitor.
+
+**Response:** an SSE stream (`text/event-stream`) with an `event: message` frame carrying `{ reply, actions }`, then `event: done`. Upstream trouble sends `event: error` instead. `actions` only ever contains skills the owner enabled (`wave`, `lookAt`, `playClip`, `remember`). Validation failures answer with an ordinary JSON `400` before the stream opens.
+
+Every turn on a real widget is persisted to its transcript with PII redacted; the public gallery's demo fixtures are stateless and keep no transcript. Replies the platform generated itself (no provider configured, or the whole failover chain refused) are stored with no provider or model attribution.
+
+---
+
+### Widget transcripts
+
+```
+GET /api/widgets/:id/transcripts
+GET /api/widgets/:id/transcripts?thread_id=<id>
+GET /api/widgets/:id/transcripts?format=csv
+```
+
+Requires auth. Owner only; bearer tokens need `avatars:read`. The list form returns `{ threads, next_cursor, totals }`, newest thread first, `limit` 1 to 100 (default 25) with keyset pagination through `before=<ISO timestamp>`. Passing `thread_id` returns `{ thread, messages }` for one conversation, or `404` if that thread is not on this widget. `format=csv` downloads up to 5000 messages as an attachment for spreadsheet review.
+
+---
+
+### Widget knowledge base
+
+```
+GET /api/widgets/:id/knowledge
+GET /api/widgets/:id/knowledge?test=<query>&top_k=<n>
+POST /api/widgets/:id/knowledge
+DELETE /api/widgets/:id/knowledge?doc_id=<id>
+```
+
+Requires auth. Owner only; bearer tokens need `avatars:read` for `GET` and `avatars:write` for the rest.
+
+`GET` lists the widget's docs with `status` (`queued`, `processing`, `ready`, `failed`), chunk and token counts. Adding `test=` runs the retrieval debugger: it embeds the probe query and returns the top-K matching chunks with cosine scores, so you can confirm a doc is reachable without spending a chat turn.
+
+`POST` ingests one document (talking-agent widgets only, 25 docs per widget). Body is one of `{ source_type: "url", source_url }`, or `{ source_type: "text" | "markdown" | "pdf", content, title }`. URLs are fetched and stripped to text server-side; PDFs are extracted in the browser and posted as text. Small docs embed inline and come back `ready`; large ones return `queued` and finish on the background worker.
+
+`DELETE` removes one doc and its chunks by `doc_id`.
+
+The knowledge routes need an embedding provider on the server (`NVIDIA_API_KEY` or `OPENAI_API_KEY`); without one they answer `503 embedder_unavailable` rather than guessing.
+
+---
+
### Open Graph share card
```
@@ -2184,9 +2257,8 @@ curl -s 'https://three.ws/api/v1/market/projects?limit=5&chain=solana'
| `429` | `rate_limited` | Either the shared aixbt ceiling or the per-IP gateway budget is spent |
| `429` | `aixbt_rate_limited` | aixbt throttled this deployment's key upstream. Retry shortly. |
| `502` / `504` | `aixbt_upstream_error` | aixbt is erroring or unreachable. The upstream status is relayed. |
-| `503` | `not_configured` | `AIXBT_API_KEY` isn't set on this deployment — never a raw 500 |
+| `503` | `not_configured` | `AIXBT_API_KEY` isn't set on this deployment, never a raw 500 |
| `503` | `aixbt_unauthorized` | aixbt rejected this deployment's key (expired, revoked, or below the plan the read needs). A deployment fault, never the caller's: these routes take no client credential, so they never answer `401`. |
-| `502` | `aixbt_upstream_error` | aixbt returned an unexpected error — retry shortly |
---
diff --git a/docs/vaults.md b/docs/vaults.md
index f31bfd7fc..d877a5e48 100644
--- a/docs/vaults.md
+++ b/docs/vaults.md
@@ -53,7 +53,9 @@ Terms, all owner-set at open and changeable later:
| `perBackerCapUsdc` | optional | no cap | Most one backer may contribute, measured against their lifetime deposits. |
| `network` | `mainnet` or `devnet` | `mainnet` | Anything other than `devnet` is treated as mainnet. |
-Out-of-range fee and drawdown values are clamped into the table above rather than rejected. A per-trade ceiling above the daily budget is rejected with `400 validation_error`.
+Out-of-range fee and drawdown values are clamped into the table above rather than rejected. A per-trade ceiling above the daily budget is rejected with `400 validation_error`, on open and on a later terms change alike (a terms PATCH that raises only the ceiling is checked against the budget already stored). A fee or drawdown value that is not a number at all is rejected rather than clamped, so a typo can never be read as an intent.
+
+Every id these routes accept (`vaultId`, `agentId`, `backerAgentId`, `toAgentId`, and `vault_id` on the ledger) must be a real uuid, and every amount (`usdc`, `shares`, `amount`) must be a number. Malformed values answer `400 validation_error` naming the field, never a `500`.
```bash
curl -sX POST https://three.ws/api/vaults \
diff --git a/public/changelog.json b/public/changelog.json
index 8cbbc150c..b4dab9103 100644
--- a/public/changelog.json
+++ b/public/changelog.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-08-15T15:28:58.987Z",
+ "generated_at": "2026-08-15T15:48:31.663Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json",
"site": {
"name": "three.ws",
@@ -16,6 +16,17 @@
"fix"
]
},
+ {
+ "date": "2026-08-15",
+ "type": "update",
+ "title": "A market intelligence outage no longer tells you your own API key was rejected",
+ "summary": "The two market intelligence reads in the unified API, recent narrative intel and momentum-ranked projects, pass a key we hold to the upstream provider; a caller needs no key at all. When that provider stopped accepting our key, both reads answered \"unauthorized\" with the provider's own wording, so an agent reading the response concluded its own credentials were bad and retried with different ones forever, when nothing on the caller's side was wrong. Both reads now say plainly that the service is temporarily unavailable because this deployment's upstream key was rejected, which is a status clients already know to retry rather than re-authenticate against. The older market intelligence endpoints always classified this correctly; the classification now lives in one place, so the two doors cannot drift apart again, and the error tables in the API reference list every code either one can return.",
+ "link": "/docs/api-reference",
+ "tags": [
+ "fix",
+ "docs"
+ ]
+ },
{
"date": "2026-08-15",
"type": "update",
@@ -198,6 +209,16 @@
"improvement"
]
},
+ {
+ "date": "2026-08-15",
+ "type": "update",
+ "title": "Paying for a skill by Solana Pay QR now shows a real three.ws merchant card",
+ "summary": "When a wallet scans a Solana Pay code for a skill purchase, it first asks our server who the merchant is and shows the answer in the sheet you approve before signing. That reply pointed at a logo file that has never existed, so the icon came back as a 404 and the merchant appeared broken at the exact moment you decide whether to pay, under the retired 3D-Agent name rather than three.ws. The probe now returns the live logo and the current name, and answers wallets that ask from a browser, which the Solana Pay spec requires. Confirming a purchase through the off-web webhook also accepts the settlement hash an EVM payment needs, so a card that settled on Base can finish instead of sitting on pending forever, and a confirmation failure now reaches our error tracker rather than disappearing into a generic 500.",
+ "link": "/marketplace",
+ "tags": [
+ "fix"
+ ]
+ },
{
"date": "2026-08-15",
"type": "update",
@@ -441,6 +462,16 @@
"sdk"
]
},
+ {
+ "date": "2026-08-15",
+ "type": "update",
+ "title": "The tokenized-stock board sorts the way you asked, with the busiest names first",
+ "summary": "The Robinhood Chain stock board (and the API behind it) accepts a sort column and a direction. Both ran backwards: asking for the highest 24h volume returned the quietest tokens, the ones with no market at all led every column, and passing dir=asc handed back descending results. Numeric columns now read highest-first by default, dir=asc genuinely flips them, and a token with no price or no NAV feed sorts to the end in either direction instead of crowding the top. The response now also echoes the sort and direction that actually ran, so an unknown sort value comes back as the default it fell to rather than as the value you sent; the memecoin screener echoes its sort the same honest way.",
+ "link": "/markets/robinhood",
+ "tags": [
+ "fix"
+ ]
+ },
{
"date": "2026-08-15",
"type": "update",
diff --git a/public/changelog.xml b/public/changelog.xml
index c5c93297b..eddc78e07 100644
--- a/public/changelog.xml
+++ b/public/changelog.xml
@@ -14,6 +14,14 @@
<category>fix</category>
<description>Payment sessions let you hand an agent a budget instead of a key, and two parts of that path judged an endpoint by one rule: if it did not ask for payment, the call was free. That is only true when the endpoint actually succeeded. A paid API answering 404, 400, or 500 was being scored as a free call, and the consequences ran in the wrong direction in both places. The dry run at /pay/simulator, whose whole job is to tell you in advance whether a budget and an allowlist will carry a workload, reported a plan as feasible at a cost of nothing when in fact every endpoint in it was erroring: free calls are never priced, never allowlist-checked, and never counted, so a wall of failures looked like a clean run. And an agent spending through a session got back a success envelope saying no payment was needed for an endpoint that had just failed on it. Both now separate the two cases: a real success with no payment challenge is still free and still costs nothing, while an error status is reported as an endpoint failure carrying the status the endpoint actually returned. No session is charged either way. The simulator lists each failing endpoint by name in its problems list and no longer calls the plan feasible.</description>
</item>
+ <item>
+ <title>A market intelligence outage no longer tells you your own API key was rejected</title>
+ <link>https://three.ws/docs/api-reference</link>
+ <guid isPermaLink="false">2026-08-15:A market intelligence outage no longer tells you your own API key was rejected</guid>
+ <pubDate>Sat, 15 Aug 2026 12:00:00 GMT</pubDate>
+ <category>fix</category>
+ <description>The two market intelligence reads in the unified API, recent narrative intel and momentum-ranked projects, pass a key we hold to the upstream provider; a caller needs no key at all. When that provider stopped accepting our key, both reads answered &quot;unauthorized&quot; with the provider's own wording, so an agent reading the response concluded its own credentials were bad and retried with different ones forever, when nothing on the caller's side was wrong. Both reads now say plainly that the service is temporarily unavailable because this deployment's upstream key was rejected, which is a status clients already know to retry rather than re-authenticate against. The older market intelligence endpoints always classified this correctly; the classification now lives in one place, so the two doors cannot drift apart again, and the error tables in the API reference list every code either one can return.</description>
+ </item>
<item>
<title>A profile’s follower count now matches the people the follower list can actually show you</title>
<link>https://three.ws/changelog</link>
@@ -150,6 +158,14 @@
<category>fix</category>
<description>Several Oracle reads shared a habit: if the database was unreachable for a few seconds, they answered normally with an empty result. The movers panel said nothing was moving, the stats hero said no coin had ever been scored and no agent was armed, a coin's conviction sparkline came back flat, and the machine-readable signal endpoint told autonomous agents there were no plays, which is exactly the cue for an agent to stand down. Every one of those answers was then cached at the edge for a minute or two, so a blip lasting seconds kept showing a dead market long after the database was back. Those endpoints now tell the difference between a connectivity failure and an ordinary query fault: the first is reported honestly as a temporary outage with a retry hint and is never cached, the second still degrades to the empty answer it always did. The social ingest got the sharper end of the same bug: it used to reply that a batch had been accepted while reporting zero mints written, a receipt for a write that never landed. It now fails loudly so the sender retries. Shared conviction cards behave too: one built during an outage is no longer pinned to a coin's link preview for 15 minutes.</description>
</item>
+ <item>
+ <title>Paying for a skill by Solana Pay QR now shows a real three.ws merchant card</title>
+ <link>https://three.ws/marketplace</link>
+ <guid isPermaLink="false">2026-08-15:Paying for a skill by Solana Pay QR now shows a real three.ws merchant card</guid>
+ <pubDate>Sat, 15 Aug 2026 12:00:00 GMT</pubDate>
+ <category>fix</category>
+ <description>When a wallet scans a Solana Pay code for a skill purchase, it first asks our server who the merchant is and shows the answer in the sheet you approve before signing. That reply pointed at a logo file that has never existed, so the icon came back as a 404 and the merchant appeared broken at the exact moment you decide whether to pay, under the retired 3D-Agent name rather than three.ws. The probe now returns the live logo and the current name, and answers wallets that ask from a browser, which the Solana Pay spec requires. Confirming a purchase through the off-web webhook also accepts the settlement hash an EVM payment needs, so a card that settled on Base can finish instead of sitting on pending forever, and a confirmation failure now reaches our error tracker rather than disappearing into a generic 500.</description>
+ </item>
<item>
<title>Pinning an avatar to IPFS works for real avatars, not just tiny ones</title>
<link>https://three.ws/changelog</link>
@@ -326,6 +342,14 @@
<category>fix</category>
<description>Three fixes across the public MCP packages and the API behind them. Asking for a token's recent buys and sells (get_token_trades on the free pump.fun MCP server) had stopped working entirely: the platform reads several transactions in one batched call, and the free Solana providers we route through cap those batches at one call each, so they rejected the whole request and the tool returned a raw provider error instead of trades. The platform now recognises that refusal, re-sends the reads one at a time to the same provider, and remembers the cap so later calls skip the wasted attempt; every batched on-chain read benefits, including wallet and agent activity history. Separately, the notifications MCP server told agents there were six notification categories when there are seven, so an agent could never change how it hears about a finished 3D generation; all seven are now listed, along with the security notices that always reach your bell inbox. And the agent provenance log answered a non-uuid agent id with an internal error and a support reference; it now says plainly that the id must be a uuid.</description>
</item>
+ <item>
+ <title>The tokenized-stock board sorts the way you asked, with the busiest names first</title>
+ <link>https://three.ws/markets/robinhood</link>
+ <guid isPermaLink="false">2026-08-15:The tokenized-stock board sorts the way you asked, with the busiest names first</guid>
+ <pubDate>Sat, 15 Aug 2026 12:00:00 GMT</pubDate>
+ <category>fix</category>
+ <description>The Robinhood Chain stock board (and the API behind it) accepts a sort column and a direction. Both ran backwards: asking for the highest 24h volume returned the quietest tokens, the ones with no market at all led every column, and passing dir=asc handed back descending results. Numeric columns now read highest-first by default, dir=asc genuinely flips them, and a token with no price or no NAV feed sorts to the end in either direction instead of crowding the top. The response now also echoes the sort and direction that actually ran, so an unknown sort value comes back as the default it fell to rather than as the value you sent; the memecoin screener echoes its sort the same honest way.</description>
+ </item>
<item>
<title>The trades feed stopped labelling a winning exit with a losing multiple</title>
<link>https://three.ws/trades</link>
diff --git a/public/features.json b/public/features.json
index f0b754bff..d04a84b68 100644
--- a/public/features.json
+++ b/public/features.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-08-15T15:28:58.618Z",
+ "generated_at": "2026-08-15T15:48:31.617Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json",
"site": {
"name": "three.ws",
diff --git a/src/billing-x402.js b/src/billing-x402.js
index bab86f41a..c1cc95385 100644
--- a/src/billing-x402.js
+++ b/src/billing-x402.js
@@ -9,6 +9,47 @@ const ENDPOINT = '/api/user/x402-subscriptions';
const el = (id) => document.getElementById(id);
+// Single-use CSRF token for a state-changing call. Never cached: the server
+// consumes the token in the same statement that validates it, so a reused one
+// is a guaranteed 403 on the next write. Rotate and revoke both destroy a live
+// credential, so the endpoint requires one.
+async function csrfToken() {
+ try {
+ const r = await fetch('/api/csrf-token', { credentials: 'include' });
+ if (!r.ok) return null;
+ const j = await r.json().catch(() => null);
+ return j?.token || j?.data?.token || null;
+ } catch {
+ return null;
+ }
+}
+
+// The endpoint answers with three different envelopes: a prose `message` on the
+// cases it wants a human to read, an `error_description` on the shared HTTP
+// guards (CSRF, method), and a bare code otherwise. Pick the most specific one
+// present, and name the two states a generic retry line would misdescribe: a
+// stale token is fixed by reloading, a rate limit by waiting.
+function failureText(resp, out, fallback) {
+ if (resp.status === 403) return 'Your session check expired. Reload the page and try again.';
+ if (resp.status === 429) return 'Too many attempts. Wait a minute and try again.';
+ return out.message || out.error_description || fallback;
+}
+
+// One place to build the write, so rotate and revoke can never drift apart on
+// which headers a mutation carries.
+async function postAction(body) {
+ const token = await csrfToken();
+ return fetch(ENDPOINT, {
+ method: 'POST',
+ headers: {
+ 'content-type': 'application/json',
+ ...(token ? { 'x-csrf-token': token } : {}),
+ },
+ credentials: 'include',
+ body: JSON.stringify(body),
+ });
+}
+
function show(stateId) {
for (const s of document.querySelectorAll('.state')) s.classList.toggle('active', s.id === stateId);
}
@@ -177,12 +218,7 @@ async function rotate(id, btn) {
setBusy(card, true);
let resp;
try {
- resp = await fetch(ENDPOINT, {
- method: 'POST',
- headers: { 'content-type': 'application/json' },
- credentials: 'include',
- body: JSON.stringify({ action: 'rotate', id }),
- });
+ resp = await postAction({ action: 'rotate', id });
} catch {
setBusy(card, false);
return toast("Couldn't reach the server", true);
@@ -190,7 +226,7 @@ async function rotate(id, btn) {
const out = await resp.json().catch(() => ({}));
if (!resp.ok) {
setBusy(card, false);
- return toast(out.message || 'Rotation failed. Please try again.', true);
+ return toast(failureText(resp, out, 'Rotation failed. Please try again.'), true);
}
const token = out.subscription?.token;
toast('Key rotated.');
@@ -212,12 +248,7 @@ async function revoke(id, btn) {
setBusy(card, true);
let resp;
try {
- resp = await fetch(ENDPOINT, {
- method: 'POST',
- headers: { 'content-type': 'application/json' },
- credentials: 'include',
- body: JSON.stringify({ action: 'revoke', id }),
- });
+ resp = await postAction({ action: 'revoke', id });
} catch {
setBusy(card, false);
return toast("Couldn't reach the server", true);
@@ -225,7 +256,7 @@ async function revoke(id, btn) {
const out = await resp.json().catch(() => ({}));
if (!resp.ok) {
setBusy(card, false);
- return toast(out.message || 'Revoke failed. Please try again.', true);
+ return toast(failureText(resp, out, 'Revoke failed. Please try again.'), true);
}
toast('Key revoked.');
await load();
diff --git a/tests/api/user-creations.test.js b/tests/api/user-creations.test.js
index a292acfee..72b4ab7f2 100644
--- a/tests/api/user-creations.test.js
+++ b/tests/api/user-creations.test.js
@@ -192,12 +192,17 @@ describe('GET /api/users/:username/creations: pagination', () => {
expect(partial.body.next).toBeNull();
});
- it('passes the before cursor through to every source', async () => {
+ it('passes the before cursor through to every source, canonicalized', async () => {
sqlQueue.push([{ id: USER_ID }]);
+ // The handler parses the cursor and re-serializes it, so what reaches the
+ // stores is always full-precision ISO 8601 regardless of how the caller
+ // wrote it. Asserting the caller's spelling would pass only by accident.
const before = '2026-07-12T00:00:00Z';
await call('alice', { before });
for (const fn of [listCreationsByUser, listDioramasByUser, listRestylesByUser]) {
- expect(fn).toHaveBeenCalledWith(expect.objectContaining({ before }));
+ expect(fn).toHaveBeenCalledWith(
+ expect.objectContaining({ before: new Date(before).toISOString() }),
+ );
}
});
diff --git a/tests/billing-x402-csrf.test.js b/tests/billing-x402-csrf.test.js
new file mode 100644
index 000000000..9cc47973b
--- /dev/null
+++ b/tests/billing-x402-csrf.test.js
@@ -0,0 +1,139 @@
+// @vitest-environment jsdom
+//
+// The client half of the /api/user/x402-subscriptions contract.
+//
+// Rotate and revoke destroy a live API credential, so the endpoint now demands
+// a CSRF token. This page posted without one, which would have turned the whole
+// key-management UI into a 403 the moment the server-side guard landed. These
+// cases pin both halves: the header goes out on every write, and a rejected
+// write says something a user can act on instead of "please try again".
+
+import { describe, it, expect, beforeEach, vi } from 'vitest';
+
+const SUB = {
+ id: 'sub_live',
+ name: 'my key',
+ keyPrefix: 'x402_abcdefgh',
+ rateLimitPerMinute: 120,
+ status: 'active',
+ source: 'native',
+ isFreeTrial: false,
+ createdAt: '2026-08-01T00:00:00Z',
+ expiresAt: null,
+ usage: { granted: 10, denied: 0, lastSeenAt: '2026-08-14T00:00:00Z' },
+};
+
+// Every element the module reaches for by id, plus the state containers it
+// toggles. Built once before the module is imported, because it calls load()
+// at import time.
+document.body.innerHTML = `
+ <div id="state-loading" class="state"></div>
+ <div id="state-empty" class="state"></div>
+ <div id="state-error" class="state">
+ <h2 id="error-title"></h2>
+ <p id="error-body"></p>
+ <button id="btn-retry"></button>
+ </div>
+ <div id="state-list" class="state">
+ <code id="example-prefix"></code>
+ <div id="cards"></div>
+ </div>
+ <div id="toast"></div>
+`;
+
+const calls = [];
+const responses = { list: { subscriptions: [SUB] }, action: null, actionStatus: 200 };
+
+globalThis.fetch = vi.fn(async (url, init = {}) => {
+ calls.push({ url, method: init.method || 'GET', headers: init.headers || {}, body: init.body || null });
+ if (url === '/api/csrf-token') {
+ return { ok: true, status: 200, json: async () => ({ token: 'csrf-abc123' }) };
+ }
+ if ((init.method || 'GET') === 'GET') {
+ return { ok: true, status: 200, json: async () => responses.list };
+ }
+ const status = responses.actionStatus;
+ return { ok: status < 400, status, json: async () => responses.action ?? {} };
+});
+
+window.confirm = vi.fn(() => true);
+
+// jsdom ships no CSS.escape; every browser the page runs in has it. The ids in
+// these cases are plain identifiers, so escaping the CSS special characters is
+// all the module needs from it.
+if (!globalThis.CSS?.escape) {
+ globalThis.CSS = { ...(globalThis.CSS || {}), escape: (s) => String(s).replace(/[^\w-]/g, '\\$&') };
+}
+
+await import('../src/billing-x402.js');
+
+// The module wires a delegated click listener, so a case drives it the way a
+// user does rather than by reaching into a function it does not export.
+async function clickAction(action, id) {
+ document.getElementById('cards').innerHTML =
+ `<div data-card="${id}"><button class="btn" data-action="${action}" data-id="${id}">go</button></div>`;
+ document.querySelector(`[data-action="${action}"]`).click();
+ // Let the rotate/revoke promise chain (csrf fetch, action fetch, reload) settle.
+ for (let i = 0; i < 12; i++) await Promise.resolve();
+ await new Promise((r) => setTimeout(r, 0));
+ for (let i = 0; i < 12; i++) await Promise.resolve();
+}
+
+function writes() {
+ return calls.filter((c) => c.method === 'POST' && c.url === '/api/user/x402-subscriptions');
+}
+
+beforeEach(() => {
+ calls.length = 0;
+ responses.action = null;
+ responses.actionStatus = 200;
+});
+
+describe('billing keys page: CSRF on writes', () => {
+ it('fetches a token and sends it with a rotate', async () => {
+ responses.action = { ok: true, action: 'rotate', subscription: { id: 'sub_new', token: 'x402_secret' } };
+ await clickAction('rotate', SUB.id);
+
+ expect(calls.some((c) => c.url === '/api/csrf-token')).toBe(true);
+ const [post] = writes();
+ expect(post.headers['x-csrf-token']).toBe('csrf-abc123');
+ expect(JSON.parse(post.body)).toEqual({ action: 'rotate', id: SUB.id });
+ });
+
+ it('fetches a token and sends it with a revoke', async () => {
+ responses.action = { ok: true, action: 'revoke', id: SUB.id };
+ await clickAction('revoke', SUB.id);
+
+ const [post] = writes();
+ expect(post.headers['x-csrf-token']).toBe('csrf-abc123');
+ expect(JSON.parse(post.body)).toEqual({ action: 'revoke', id: SUB.id });
+ });
+
+ it('never reuses a token: each write asks for its own', async () => {
+ responses.action = { ok: true, action: 'revoke', id: SUB.id };
+ await clickAction('revoke', SUB.id);
+ await clickAction('revoke', SUB.id);
+ expect(calls.filter((c) => c.url === '/api/csrf-token')).toHaveLength(2);
+ });
+
+ it('tells the user to reload when the token is rejected', async () => {
+ responses.actionStatus = 403;
+ responses.action = { error: 'csrf_invalid', error_description: 'CSRF token invalid or expired' };
+ await clickAction('rotate', SUB.id);
+ expect(document.getElementById('toast').textContent).toMatch(/reload/i);
+ });
+
+ it('tells the user to wait when the write is rate limited', async () => {
+ responses.actionStatus = 429;
+ responses.action = { error: 'rate_limited' };
+ await clickAction('revoke', SUB.id);
+ expect(document.getElementById('toast').textContent).toMatch(/wait/i);
+ });
+
+ it('still surfaces a server message when the endpoint sends one', async () => {
+ responses.actionStatus = 409;
+ responses.action = { error: 'aws_revoke_not_allowed', message: 'This key bills through AWS Marketplace.' };
+ await clickAction('revoke', SUB.id);
+ expect(document.getElementById('toast').textContent).toBe('This key bills through AWS Marketplace.');
+ });
+});
diff --git a/tests/tx-explain-validation.test.js b/tests/tx-explain-validation.test.js
new file mode 100644
index 000000000..82435f14c
--- /dev/null
+++ b/tests/tx-explain-validation.test.js
@@ -0,0 +1,191 @@
+// Input-validation contract for POST /api/tx/explain, the endpoint the chat
+// "explain this transaction" tool calls.
+//
+// The regression pinned here: the Solana branch validated the signature with a
+// base58 alphabet + character-count check only. `'1'.repeat(88)` passes that and
+// decodes to 88 zero bytes, not the 64 a signature is, so the RPC rejected it as
+// a bad argument and the caller was told `502 upstream_error` for what is plainly
+// their own malformed input. Worse, the request first spent a slot of the shared
+// Helius cost ceiling and a call to the keyed enhanced-tx upstream. A signature is
+// decoded and measured before anything leaves the process now.
+//
+// Every upstream (cache, Helius, RPC, LLM) is mocked, and the assertions below
+// prove the rejected cases never reach one.
+
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+const cacheGet = vi.fn(async () => null);
+const cacheSet = vi.fn(async () => {});
+vi.mock('../api/_lib/cache.js', () => ({
+ cacheGet: (...a) => cacheGet(...a),
+ cacheSet: (...a) => cacheSet(...a),
+}));
+
+const heliusDasGlobal = vi.fn(async () => ({ success: true, limit: 100, remaining: 99, reset: Date.now() + 1000 }));
+vi.mock('../api/_lib/rate-limit.js', () => ({
+ limits: {
+ authedReadIp: vi.fn(async () => ({ success: true, limit: 60, remaining: 59, reset: Date.now() + 1000 })),
+ heliusDasGlobal: (...a) => heliusDasGlobal(...a),
+ },
+ clientIp: vi.fn(() => '127.0.0.1'),
+}));
+
+const getParsedTransaction = vi.fn(async () => null);
+vi.mock('../api/_lib/solana/connection.js', () => ({
+ solanaConnection: vi.fn(() => ({ getParsedTransaction: (...a) => getParsedTransaction(...a) })),
+}));
+
+// No summary lane in these cases: the endpoint's contract is the tx data.
+vi.mock('../api/_lib/llm.js', () => ({
+ llmConfigured: () => false,
+ llmComplete: vi.fn(),
+}));
+
+vi.mock('../api/_lib/sentry.js', () => ({ captureException: vi.fn() }));
+vi.mock('../api/_lib/alerts.js', () => ({ sendOpsAlert: vi.fn() }));
+
+import handler from '../api/tx/explain.js';
+
+function mockRes() {
+ return {
+ statusCode: 200,
+ headers: {},
+ body: null,
+ headersSent: false,
+ writableEnded: false,
+ setHeader(k, v) { this.headers[k.toLowerCase()] = v; },
+ getHeader(k) { return this.headers[k.toLowerCase()]; },
+ end(payload) { this.headersSent = true; this.writableEnded = true; this.body = payload; },
+ get json() { return this.body ? JSON.parse(this.body) : null; },
+ };
+}
+
+async function explain(body, method = 'POST') {
+ const res = mockRes();
+ await handler({ method, url: '/api/tx/explain', headers: { 'content-type': 'application/json' }, socket: {}, body }, res);
+ return res;
+}
+
+// 64 real bytes of base58: the shape a Solana signature actually has.
+const VALID_SIG = '5jUwmjLpwWnFVMPaMPnBrpVFhfDPHqCmk4Wf7Bwj1SPXHmoveEfXcNvEfxrGDMFqJTLdVvBzHmFSEZSKnvUppRSt';
+const VALID_EVM_HASH = '0xa2bb8919c907fdc3e942962199520ed84171bb36a6290671dcc35ecbb1731c60';
+
+const fetchMock = vi.fn();
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ // Default: the keyed Helius enhanced lane rejects, which is what an unset
+ // HELIUS_API_KEY produces, so the RPC fallback is the path under test.
+ fetchMock.mockImplementation(async () => new Response('{}', { status: 401 }));
+ cacheGet.mockResolvedValue(null);
+ getParsedTransaction.mockResolvedValue(null);
+ heliusDasGlobal.mockResolvedValue({ success: true, limit: 100, remaining: 99, reset: Date.now() + 1000 });
+ vi.stubGlobal('fetch', fetchMock);
+});
+
+describe('POST /api/tx/explain input validation', () => {
+ it('405s a GET', async () => {
+ const res = await explain(undefined, 'GET');
+ expect(res.statusCode).toBe(405);
+ });
+
+ it('400s a chain that is neither solana nor evm', async () => {
+ const res = await explain({ chain: 'btc', sig: VALID_SIG });
+ expect(res.statusCode).toBe(400);
+ expect(res.json.error_description).toContain('solana or evm');
+ });
+
+ it('400s a missing signature', async () => {
+ const res = await explain({ chain: 'solana' });
+ expect(res.statusCode).toBe(400);
+ expect(res.json.error_description).toBe('sig required');
+ });
+
+ it('400s base58 that is the right length but not 64 bytes', async () => {
+ const res = await explain({ chain: 'solana', sig: '1'.repeat(88) });
+ expect(res.statusCode).toBe(400);
+ expect(res.json.error).toBe('bad_request');
+ expect(res.json.error_description).toContain('base58 transaction signature');
+ });
+
+ it('spends no upstream budget or call on a malformed signature', async () => {
+ await explain({ chain: 'solana', sig: '1'.repeat(88) });
+ expect(cacheGet).not.toHaveBeenCalled();
+ expect(heliusDasGlobal).not.toHaveBeenCalled();
+ expect(fetchMock).not.toHaveBeenCalled();
+ expect(getParsedTransaction).not.toHaveBeenCalled();
+ });
+
+ it('400s characters outside the base58 alphabet', async () => {
+ const res = await explain({ chain: 'solana', sig: '0OIl'.repeat(22) });
+ expect(res.statusCode).toBe(400);
+ });
+
+ it('400s an EVM hash that is not 32 bytes', async () => {
+ const res = await explain({ chain: 'evm', sig: '0xdeadbeef' });
+ expect(res.statusCode).toBe(400);
+ expect(res.json.error_description).toContain('32-byte tx hash');
+ expect(fetchMock).not.toHaveBeenCalled();
+ });
+
+ it('accepts a well-formed EVM hash and reaches the RPC chain', async () => {
+ // A fresh Response per call: the handler fires getTransactionByHash and
+ // getTransactionReceipt in parallel and a body can only be read once.
+ fetchMock.mockImplementation(async () => new Response(JSON.stringify({ jsonrpc: '2.0', id: 1, result: null }), { status: 200 }));
+ const res = await explain({ chain: 'evm', sig: VALID_EVM_HASH });
+ expect(fetchMock).toHaveBeenCalled();
+ expect(res.statusCode).toBe(404);
+ expect(res.json.error).toBe('not_found');
+ });
+
+ it('404s a well-formed Solana signature with no matching transaction', async () => {
+ const res = await explain({ chain: 'solana', sig: VALID_SIG });
+ expect(getParsedTransaction).toHaveBeenCalledWith(VALID_SIG, expect.any(Object));
+ expect(res.statusCode).toBe(404);
+ expect(res.json.error).toBe('not_found');
+ });
+
+ it('502s a genuine RPC failure, keeping it distinct from a malformed input', async () => {
+ getParsedTransaction.mockRejectedValue(new Error('all endpoints failed'));
+ const res = await explain({ chain: 'solana', sig: VALID_SIG });
+ expect(res.statusCode).toBe(502);
+ expect(res.json.error).toBe('upstream_error');
+ });
+
+ it('serves a cached explanation without touching any upstream', async () => {
+ cacheGet.mockResolvedValue({ tokenTransfers: [], nativeTransfers: [], feePayer: 'x', source: 'rpc-fallback' });
+ const res = await explain({ chain: 'solana', sig: VALID_SIG });
+ expect(res.statusCode).toBe(200);
+ expect(res.json.feePayer).toBe('x');
+ expect(heliusDasGlobal).not.toHaveBeenCalled();
+ expect(fetchMock).not.toHaveBeenCalled();
+ });
+
+ it('429s when the shared Helius cost ceiling is exhausted', async () => {
+ heliusDasGlobal.mockResolvedValue({ success: false, limit: 100, remaining: 0, reset: Date.now() + 60_000 });
+ const res = await explain({ chain: 'solana', sig: VALID_SIG });
+ expect(res.statusCode).toBe(429);
+ expect(fetchMock).not.toHaveBeenCalled();
+ });
+
+ it('reconstructs transfers from a parsed transaction when Helius is unavailable', async () => {
+ getParsedTransaction.mockResolvedValue({
+ transaction: { message: { accountKeys: [{ pubkey: 'Payer1111' }, { pubkey: 'Dest1111' }] } },
+ meta: {
+ preBalances: [1_000_000, 0],
+ postBalances: [500_000, 495_000],
+ preTokenBalances: [],
+ postTokenBalances: [],
+ },
+ });
+ const res = await explain({ chain: 'solana', sig: VALID_SIG });
+ expect(res.statusCode).toBe(200);
+ expect(res.json.source).toBe('rpc-fallback');
+ expect(res.json.feePayer).toBe('Payer1111');
+ expect(res.json.nativeTransfers).toEqual([
+ { account: 'Payer1111', amount: -500_000 },
+ { account: 'Dest1111', amount: 495_000 },
+ ]);
+ expect(cacheSet).toHaveBeenCalled();
+ });
+});
diff --git a/tests/tx-solana-build.test.js b/tests/tx-solana-build.test.js
index 48a304865..b1889401c 100644
--- a/tests/tx-solana-build.test.js
+++ b/tests/tx-solana-build.test.js
@@ -174,7 +174,10 @@ function decodeInstructions(base64) {
const out = [];
for (let n = 0; n < ixCount; n++) {
const programIndex = msg[i++];
- i += readCompactU16(); // account indexes
+ // Read the count first: readCompactU16 advances `i` itself, and `i += f()`
+ // would add to the pre-call value.
+ const accountCount = readCompactU16();
+ i += accountCount;
const dataLen = readCompactU16();
const data = msg.subarray(i, i + dataLen);
i += dataLen;