Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
test(blinks): cover the avatar Blink end to end and document both endpoints
nirholas7b81a88f9060
diff --git a/api/_lib/render-clip.js b/api/_lib/render-clip.jsindex 8b7782774..7a3f967ef 100644--- a/api/_lib/render-clip.js+++ b/api/_lib/render-clip.js@@ -63,7 +63,7 @@ function poseById(id) {// and run its own code inside the render page. That page has network access, so// injected script can fetch internal endpoints and paint them into the// screenshot we hand back. Escape here, once, so no caller has to remember to.-function scriptJson(value) {+export function scriptJson(value) {return JSON.stringify(value === undefined ? null : value).replace(/</g, '\\u003c').replace(/>/g, '\\u003e')diff --git a/docs/api-reference.md b/docs/api-reference.mdindex 4ee64c584..ed96ea488 100644--- a/docs/api-reference.md+++ b/docs/api-reference.md@@ -4697,6 +4697,94 @@ The same stamp is served statically at `/build-info.json`.---+## Solana Actions API (Blinks)++three.ws publishes a Solana Action so "Claim Your 3D Avatar" unfurls as a Blink+card on X and in any Blink-aware wallet. `/.well-known/solana/actions.json` maps+`/api/actions/**` for Action clients, and the card's icon is a live headless+render of the avatar's own GLB rather than a static image.++### Claim-avatar action++```+GET /api/actions/avatar?avatar=default+POST /api/actions/avatar?avatar=<avatarId>+```++No auth required. `avatar` is either `default` or an avatar UUID; anything else is+`400 bad_request`. An avatar that is private, deleted, or unknown is `404 not_found`,+so a card never advertises a claim the viewer cannot complete. A named avatar's card+is titled with that avatar's name.++Responses carry `x-action-version: 2.1.3` and `x-blockchain-ids: solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp`,+including on the `OPTIONS` preflight. Errors carry both the standard+`error` / `error_description` envelope and the Actions spec's `message` field.++**GET response** (`ActionGetResponse`):++```json+{+ "type": "action",+ "icon": "https://three.ws/api/actions/avatar-icon?avatar=default",+ "label": "Claim Avatar",+ "title": "My 3D Avatar on three.ws",+ "description": "Register your Solana wallet to this 3D avatar. ...",+ "links": {+ "actions": [+ { "type": "transaction", "label": "Claim This Avatar", "href": "/api/actions/avatar?avatar=default" }+ ]+ }+}+```++**POST body:** `{ "account": "<wallet pubkey>" }`. The account must be a base58+ed25519 public key that is on the curve; a program-derived address (which no key+can sign for) is rejected with `400 bad_request` before any transaction is built.++**POST response** (`ActionPostResponse`): a base64 `VersionedTransaction` carrying a+single unsigned SPL Memo instruction. The server never signs; the wallet does.++```json+{+ "type": "transaction",+ "transaction": "AQAAAAAA...",+ "message": "Your 3D avatar identity is now recorded on Solana. Welcome to three.ws."+}+```++The memo payload is `{"v":1,"action":"avatar-claim","avatar":"<avatarId>","site":"three.ws"}`.+A Solana RPC that will not answer returns `503 rpc_unavailable`.++```bash+curl -s https://three.ws/api/actions/avatar | jq .title+curl -s -X POST https://three.ws/api/actions/avatar \+ -H 'content-type: application/json' \+ -d '{"account":"FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump"}' | jq -r .type+```++---++### Blink card icon++```+GET /api/actions/avatar-icon?avatar=default&pose=tpose&bg=%230a0a0a+```++Renders the avatar's GLB to a 512x512 `image/png` through headless chromium and+serves it with a one-day browser / one-week edge cache. No auth required; `GET`+and `HEAD` only, since every other method would boot a browser for nothing.++| Parameter | Default | Notes |+|---|---|---|+| `avatar` | `default` | `default` or an avatar UUID. Anything else is `400`. An avatar with no reachable model falls back to the default GLB. |+| `pose` | none | A pose preset id from `GET /api/render/avatar-clip`. Anything that is not a preset-shaped id is `400`. |+| `bg` | `#0a0a0a` | A CSS color (hex, `rgb()`/`rgba()`, `hsl()`/`hsla()`, a named color) or `transparent`. Anything else is `400`: this value is embedded in the renderer's page, so it is never passed through unchecked. |++Render failures surface the class of failure rather than one blanket code: `400`+for an unfetchable GLB, `413` for one over the size cap, `502` for a renderer fault.++---+## PaginationPaginated list endpoints use `limit`/`offset` query parameters unless noted otherwise (each endpoint's own parameter table is authoritative; some small per-user lists, like `/api/agents` and `/api/widgets`, return everything with no pagination).diff --git a/prompts/swarm-100/api-actions-01.md b/prompts/swarm-100/api-actions-01.mddeleted file mode 100644index 48928e4b4..000000000--- a/prompts/swarm-100/api-actions-01.md+++ /dev/null@@ -1,102 +0,0 @@-# API audit: api/actions batch 01 (2 files)--How to run: paste this file's repo path into a fresh Claude Code chat in this-repository and say "run this work order". This file is fully self-contained:-it depends on no other prompt file anywhere. If neighboring files in-prompts/swarm-100/ are gone, that work is done; if present, ignore them.-Every claim below rots; step 0 re-measures, and what you measure wins.--## Operating clause (binding)--- Read CLAUDE.md first. Its rules override everything, including this file.-- Finish 100% in this session. Never end the turn with a question, an option- list, or an unexecuted plan. A judgment call goes in one line of the final- report; it never becomes a question that halts work.-- The only permitted stops are the CLAUDE.md stop-and-ask gates: spending real- funds or any irreversible on-chain write, git push or a production deploy,- committing content that references a crypto project other than $THREE, and- destroying unrecoverable data.-- No mocks, no fake data, no placeholder stubs, no unfinished-work markers, no- commented-out code. Real APIs and real integrations only.-- The em-dash and en-dash characters are banned in everything you write.-- Concurrent agents share this worktree: stage explicit paths only (never a- bare add-everything), and commit finished work promptly.-- Before committing, run: npm run check:rules -- --paths <files you touched>.- It must exit 0.--## Step 0: re-derive the current state--1. Confirm each file below still exists; deleted ones are done, skip them.-2. For each, decide routability: grep its path in vercel.json and read how- server/index.mjs maps filesystem handlers. Routed files get an endpoint- audit; internal modules get a code and test audit.-3. Start a local server for endpoint checks: node server/index.mjs with .env- loaded, on a free PORT if 3000 is busy.--## Task: audit these api files, then fix everything found--Files in this batch:--- api/actions/avatar-icon.js-- api/actions/avatar.js--For every routed handler:--1. Exercise it with curl against the local server: the success path returns- real data with the correct status; malformed input returns a 4xx JSON- error, never a stack trace or an HTML error page; auth is enforced where- the code intends it; CORS matches neighboring handlers.-2. Hard-rule scan: no mock fallbacks, no fake-data arrays, no stubbed- responses, no unfinished markers. Errors are handled at the boundary and- internal code trusts itself.-3. Do not spend funds or sign anything on-chain while probing. Payment and- trading handlers get their validation and error paths exercised, never a- live settlement.--For every internal (non-routed) module:--4. Something must import it; if nothing does, delete it as dead code (verify- with a repo-wide grep first).-5. Its main path and one failure path must be covered in tests/; add the- missing test if not.--## Definition of done--- [ ] Every listed file has recorded evidence: a curl transcript for routed- handlers, a passing test or a deletion for internal modules.-- [ ] Zero hard-rule violations remain in these files.-- [ ] vitest run passes; npm run check:rules -- --paths <touched files>- exits 0.--## Never blocked--| Blocker | Resolution (act, do not ask) |-|---|---|-| Missing env var or credential | Check .env and .env.local, then the Cloud Run service env, then Secret Manager (the CLAUDE.md self-unblock playbook has the exact commands). If it truly exists nowhere, wire the code fully behind the env var, prove the wiring with a dry run, and name the single missing var in the report. |-| gcloud not on PATH | Run: export PATH="$HOME/google-cloud-sdk/bin:$PATH" |-| Dev server port 3000 busy | Another agent may be serving this repo; probe it and reuse if so. Otherwise start your own on a free port: npx vite --port 3101 |-| Playwright browser missing | npx playwright install chromium |-| A surface needs a signed-in user | Register a fresh account through the real /register flow against the real API and use it. Never mock the session. |-| A defect sits in code you did not touch | Fix it if it blocks a Definition of done line (root cause it, never mask it). Otherwise note it in the report and continue. |-| An unrelated test is red | Same rule. Never pipe npm test through tail; it masks exit codes. |--## Close out (required)--1. Verify every Definition of done line with the actual command output in- front of you. Never claim a line you did not verify.-2. Commit with explicit paths and a subject that describes the diff (house- style: type(scope): what changed and why a reader cares).-3. Delete this prompt file in that same commit:-- git rm prompts/swarm-100/api-actions-01.md-- The shrinking directory is this campaign's only progress ledger; there is- no progress log to update.-4. Final report: what step 0 measured, what changed (file list), evidence per- Definition of done line, and any one-line judgment calls. No trailing- questions, no unexecuted plans.--If a line genuinely cannot pass inside this session (an external party must-respond, or an owner-gated action is the final step), finish everything else,-leave this file in place, and state exactly which line remains and who owns-it. Never delete this file on a partial.diff --git a/tests/actions-avatar-blink.test.js b/tests/actions-avatar-blink.test.jsnew file mode 100644index 000000000..65a370ba6--- /dev/null+++ b/tests/actions-avatar-blink.test.js@@ -0,0 +1,316 @@+// Coverage for the "Claim Your 3D Avatar" Solana Blink pair:+//+// api/actions/avatar.js the Action itself (GET card, POST transaction)+// api/actions/avatar-icon.js the card's icon, a headless-chromium GLB render+//+// Both were reachable in production with no test at all. The cases below pin+// the behaviour a Blink client depends on and the input handling that keeps the+// renderer safe:+//+// 1. The GET card carries the Action spec's `type` and a live icon/href pair.+// 2. `?avatar=` only ever names "default" or a real avatar id. That string is+// written into the on-chain memo, so an arbitrary one must not reach it.+// 3. A private, deleted, or unknown avatar is a 404, not a card advertising it.+// 4. The version headers ride the OPTIONS preflight, per the Actions spec.+// 5. POST rejects an off-curve (PDA) account before building a transaction no+// wallet could ever sign, and surfaces an RPC outage as 503.+// 6. The icon's `bg` lands inside the render page's script block. A value+// containing a closing script tag is refused at the boundary AND neutered+// by the renderer's own escaper, so the injection is dead twice over.++import { describe, it, expect, vi, beforeEach } from 'vitest';++const getAvatar = vi.fn();+vi.mock('../api/_lib/avatars.js', () => ({ getAvatar: (...a) => getAvatar(...a) }));++const getLatestBlockhash = vi.fn();+vi.mock('../api/_lib/solana/connection.js', () => ({+ solanaConnection: () => ({ getLatestBlockhash: (...a) => getLatestBlockhash(...a) }),+}));++const renderClip = vi.fn();+vi.mock('../api/_lib/render-clip.js', async (importOriginal) => {+ const actual = await importOriginal();+ return { ...actual, renderClip: (...a) => renderClip(...a) };+});++const { default: actionHandler } = await import('../api/actions/avatar.js');+const { default: iconHandler } = await import('../api/actions/avatar-icon.js');+const { scriptJson } = await import('../api/_lib/render-clip.js');++// A real mainnet blockhash value. The RPC round-trip is what we stand in for,+// not the encoding, which @solana/web3.js does for real below.+const BLOCKHASH = '9zGE9NVsSGkoUZv8uZbGdFDNKvVjbQTG5Uu6iN4vVQBS';+// $THREE, the platform's own coin, doubles as a known-good on-curve pubkey.+const ON_CURVE = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';+const MEMO_PROGRAM = 'MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr';+const AVATAR_UUID = '3f1c8a52-9f6b-4a3d-8c21-0d5b7e9a1c44';+const LINE_SEP = String.fromCharCode(0x2028);+const PARA_SEP = String.fromCharCode(0x2029);++function mockReq(method, url, body) {+ const req = { method, url, headers: { host: 'localhost' } };+ if (body !== undefined) {+ req.headers['content-type'] = 'application/json';+ req.body = body;+ }+ return req;+}++function mockRes() {+ return {+ statusCode: 200,+ headers: {},+ body: undefined,+ ended: false,+ setHeader(k, v) { this.headers[k.toLowerCase()] = v; },+ getHeader(k) { return this.headers[k.toLowerCase()]; },+ end(b) { this.body = b; this.ended = true; },+ };+}++const parse = (res) => JSON.parse(String(res.body));++beforeEach(() => {+ getAvatar.mockReset();+ getLatestBlockhash.mockReset();+ renderClip.mockReset();+});++describe('api/actions/avatar GET (the Blink card)', () => {+ it('returns a spec-shaped action with a live icon and action href', async () => {+ const res = mockRes();+ await actionHandler(mockReq('GET', '/api/actions/avatar'), res);++ expect(res.statusCode).toBe(200);+ const card = parse(res);+ expect(card.type).toBe('action');+ expect(card.icon).toMatch(/\/api\/actions\/avatar-icon\?avatar=default$/);+ expect(card.links.actions[0]).toMatchObject({+ type: 'transaction',+ href: '/api/actions/avatar?avatar=default',+ });+ expect(res.headers['x-action-version']).toBe('2.1.3');+ expect(res.headers['x-blockchain-ids']).toMatch(/^solana:/);+ // No DB round-trip for the default avatar: the card is pure static copy.+ expect(getAvatar).not.toHaveBeenCalled();+ });++ it('titles the card with the avatar the Blink actually points at', async () => {+ getAvatar.mockResolvedValue({ id: AVATAR_UUID, name: 'Nova', visibility: 'public' });+ const res = mockRes();+ await actionHandler(mockReq('GET', `/api/actions/avatar?avatar=${AVATAR_UUID}`), res);++ expect(res.statusCode).toBe(200);+ expect(parse(res).title).toBe('Nova on three.ws');+ expect(getAvatar).toHaveBeenCalledWith({ id: AVATAR_UUID });+ });++ it('rejects an avatar id that could never name a real avatar', async () => {+ const res = mockRes();+ await actionHandler(mockReq('GET', '/api/actions/avatar?avatar=%3Cscript%3E'), res);++ expect(res.statusCode).toBe(400);+ expect(parse(res).error).toBe('bad_request');+ expect(getAvatar).not.toHaveBeenCalled();+ });++ it('404s an avatar the anonymous viewer cannot see', async () => {+ getAvatar.mockResolvedValue(null);+ const res = mockRes();+ await actionHandler(mockReq('GET', `/api/actions/avatar?avatar=${AVATAR_UUID}`), res);++ expect(res.statusCode).toBe(404);+ // Blink clients render ActionError.message, so it must be present too.+ expect(parse(res).message).toMatch(/not available/i);+ });++ it('puts the Action version headers on the OPTIONS preflight', async () => {+ const res = mockRes();+ await actionHandler(mockReq('OPTIONS', '/api/actions/avatar'), res);++ expect(res.statusCode).toBe(204);+ expect(res.headers['x-action-version']).toBe('2.1.3');+ expect(res.headers['x-blockchain-ids']).toMatch(/^solana:/);+ });++ it('405s a method the action does not serve', async () => {+ const res = mockRes();+ await actionHandler(mockReq('PUT', '/api/actions/avatar'), res);++ expect(res.statusCode).toBe(405);+ expect(parse(res).error).toBe('method_not_allowed');+ });+});++describe('api/actions/avatar POST (the claim transaction)', () => {+ it('builds a memo transaction naming the avatar being claimed', async () => {+ getAvatar.mockResolvedValue({ id: AVATAR_UUID, name: 'Nova', visibility: 'public' });+ getLatestBlockhash.mockResolvedValue({ blockhash: BLOCKHASH });+ const res = mockRes();+ await actionHandler(+ mockReq('POST', `/api/actions/avatar?avatar=${AVATAR_UUID}`, { account: ON_CURVE }),+ res,+ );++ expect(res.statusCode).toBe(200);+ const out = parse(res);+ expect(out.type).toBe('transaction');++ const { VersionedTransaction, PublicKey } = await import('@solana/web3.js');+ const tx = VersionedTransaction.deserialize(Buffer.from(out.transaction, 'base64'));+ expect(tx.message.recentBlockhash).toBe(BLOCKHASH);+ expect(tx.message.staticAccountKeys[0].toBase58()).toBe(ON_CURVE);+ expect(tx.message.staticAccountKeys.some((k) => k.toBase58() === MEMO_PROGRAM)).toBe(true);+ expect(PublicKey.isOnCurve(tx.message.staticAccountKeys[0].toBytes())).toBe(true);++ const memo = JSON.parse(+ Buffer.from(tx.message.compiledInstructions[0].data).toString('utf8'),+ );+ expect(memo).toMatchObject({ action: 'avatar-claim', avatar: AVATAR_UUID, site: 'three.ws' });+ // The claim is unsigned: the wallet, never the server, authorizes it.+ expect(tx.signatures.every((s) => s.every((b) => b === 0))).toBe(true);+ });++ it('rejects an off-curve account no wallet could sign for', async () => {+ const { PublicKey } = await import('@solana/web3.js');+ const [pda] = PublicKey.findProgramAddressSync(+ [Buffer.from('three')],+ new PublicKey(MEMO_PROGRAM),+ );+ const res = mockRes();+ await actionHandler(mockReq('POST', '/api/actions/avatar', { account: pda.toBase58() }), res);++ expect(res.statusCode).toBe(400);+ expect(parse(res).error_description).toMatch(/invalid account/i);+ expect(getLatestBlockhash).not.toHaveBeenCalled();+ });++ it('rejects a request with no account', async () => {+ const res = mockRes();+ await actionHandler(mockReq('POST', '/api/actions/avatar', {}), res);++ expect(res.statusCode).toBe(400);+ expect(parse(res).error_description).toMatch(/account is required/);+ expect(getLatestBlockhash).not.toHaveBeenCalled();+ });++ it('surfaces an unreachable RPC as 503 rather than hanging out the clock', async () => {+ getLatestBlockhash.mockRejectedValue(new Error('429 Too Many Requests'));+ const res = mockRes();+ await actionHandler(mockReq('POST', '/api/actions/avatar', { account: ON_CURVE }), res);++ expect(res.statusCode).toBe(503);+ expect(parse(res).error).toBe('rpc_unavailable');+ });+});++describe('api/actions/avatar-icon', () => {+ const PNG = Buffer.from('89504e470d0a1a0a', 'hex');++ it('renders the default avatar and serves it as a cacheable PNG', async () => {+ renderClip.mockResolvedValue({ png: PNG, pose: null });+ const res = mockRes();+ await iconHandler(mockReq('GET', '/api/actions/avatar-icon'), res);++ expect(res.statusCode).toBe(200);+ expect(res.headers['content-type']).toBe('image/png');+ expect(res.headers['cache-control']).toMatch(/max-age=86400/);+ expect(res.body).toBe(PNG);+ expect(renderClip).toHaveBeenCalledWith(+ expect.objectContaining({+ glbUrl: expect.stringMatching(/\/avatars\/default\.glb$/),+ width: 512,+ height: 512,+ background: '#0a0a0a',+ }),+ );+ });++ it('refuses a background that would break out of the render page script', async () => {+ const res = mockRes();+ await iconHandler(+ mockReq(+ 'GET',+ '/api/actions/avatar-icon?bg=%3C%2Fscript%3E%3Cscript%3Ewindow.__renderDone%3Dtrue%3C%2Fscript%3E',+ ),+ res,+ );++ expect(res.statusCode).toBe(400);+ expect(parse(res).error_description).toMatch(/CSS color/);+ expect(renderClip).not.toHaveBeenCalled();+ });++ it('accepts the CSS color forms three.js can actually parse', async () => {+ renderClip.mockResolvedValue({ png: PNG, pose: null });+ for (const bg of ['%23112233', 'midnightblue', 'rgb(20%2C30%2C40)', 'transparent']) {+ const res = mockRes();+ await iconHandler(mockReq('GET', `/api/actions/avatar-icon?bg=${bg}`), res);+ expect(res.statusCode, `bg=${bg}`).toBe(200);+ }+ expect(renderClip).toHaveBeenCalledTimes(4);+ });++ it('rejects a pose id that is a path rather than a preset', async () => {+ const res = mockRes();+ await iconHandler(mockReq('GET', '/api/actions/avatar-icon?pose=..%2Fetc%2Fpasswd'), res);++ expect(res.statusCode).toBe(400);+ expect(renderClip).not.toHaveBeenCalled();+ });++ it('rejects an avatar id that could never name a real avatar', async () => {+ const res = mockRes();+ await iconHandler(mockReq('GET', '/api/actions/avatar-icon?avatar=notauuid'), res);++ expect(res.statusCode).toBe(400);+ expect(getAvatar).not.toHaveBeenCalled();+ expect(renderClip).not.toHaveBeenCalled();+ });++ it('405s a write method instead of booting chromium for it', async () => {+ const res = mockRes();+ await iconHandler(mockReq('POST', '/api/actions/avatar-icon'), res);++ expect(res.statusCode).toBe(405);+ expect(renderClip).not.toHaveBeenCalled();+ });++ it('passes the renderer failure class through instead of flattening it to 502', async () => {+ getAvatar.mockResolvedValue({ id: AVATAR_UUID, model_url: 'https://three.ws/a.glb' });+ renderClip.mockRejectedValue(+ Object.assign(new Error('glb too large'), { status: 413, code: 'file_too_large' }),+ );+ const res = mockRes();+ await iconHandler(mockReq('GET', `/api/actions/avatar-icon?avatar=${AVATAR_UUID}`), res);++ expect(res.statusCode).toBe(413);+ expect(parse(res).error).toBe('file_too_large');+ });+});++describe('render-clip scriptJson', () => {+ it('neuters a value that would close the script tag it is embedded in', () => {+ const payload = '</script><script>fetch("http://169.254.169.254/")</script>';+ const out = scriptJson(payload);+ expect(out).not.toContain('<');+ expect(out).not.toContain('>');+ // Still valid JS producing the original string, so no render breaks.+ expect(JSON.parse(out)).toBe(payload);+ });++ it('escapes the JS line terminators JSON leaves raw', () => {+ const payload = `a${LINE_SEP}b${PARA_SEP}c`;+ const out = scriptJson(payload);+ expect(out).not.toContain(LINE_SEP);+ expect(out).not.toContain(PARA_SEP);+ expect(JSON.parse(out)).toBe(payload);+ });++ it('round-trips the structured values the viewer embeds', () => {+ const orbit = { theta: 10, phi: 75, radius: null };+ expect(JSON.parse(scriptJson(orbit))).toEqual(orbit);+ expect(scriptJson(undefined)).toBe('null');+ });+});