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
docs(api): document the subscriptions endpoints and cover the plan/subscription handlers with tests
nirholas2f276476cd28
diff --git a/docs/api-reference.md b/docs/api-reference.mdindex cbad8995b..b1c264e55 100644--- a/docs/api-reference.md+++ b/docs/api-reference.md@@ -6568,6 +6568,312 @@ partial answer is still a partial answer.---+## Subscriptions API++Recurring creator subscriptions. A creator publishes one or more **plans**+(tiers); a subscriber joins one either through the x402 renewal-intent path+(`POST /api/subscriptions`) or the Solana USDC checkout+(`/api/subscriptions/subscribe` then `/api/subscriptions/verify`).++All ids are UUIDs. A malformed id answers `400 validation_error`, never a `5xx`.+Session-cookie mutations require an `X-CSRF-Token` header (see+[Authentication](#authentication)); bearer-token callers are exempt.++### List plans++```+GET /api/subscriptions/plans?creator_id=<uuid>+GET /api/subscriptions/plans?agent_id=<uuid>+```++Public. Exactly one of `creator_id` or `agent_id` is required. Only active plans+are returned; the plan's own creator may add `include_inactive=1` to also receive+their drafts.++```json+{+ "plans": [+ {+ "id": "735977d9-289d-4517-8ac4-68e97c649de8",+ "creator_id": "f23703c0-9d75-4e60-9a4c-349da5d7a2f2",+ "agent_id": null,+ "name": "Supporter",+ "price_usd": "9.99",+ "interval": "monthly",+ "perks": ["priority support"],+ "included_skills": [],+ "active": true,+ "created_at": "2026-08-16T06:16:24.604Z"+ }+ ]+}+```++**Errors:** `400` (`validation_error`: neither id given, or a non-UUID),+`429` (`rate_limited`).++---++### Get one plan++```+GET /api/subscriptions/plans/:id+```++Public for an active plan. A deactivated plan (draft) is served only to its+creator; everyone else gets `404`, so a draft's existence never leaks.++**Response:** `{ "plan": { … } }`, same shape as a list entry.++**Errors:** `400` (`validation_error`), `404` (`not_found`), `429`.++---++### Create a plan++```+POST /api/subscriptions/plans+```++Requires auth. A creator may hold at most 3 **active** plans; drafts+(`active: false`) do not consume a slot.++**Request body**++```json+{+ "agent_id": "717e68f1-e0c2-41ee-8ff7-6801a83206c9",+ "name": "Supporter",+ "price_usd": 9.99,+ "interval": "monthly",+ "perks": ["priority support"],+ "included_skills": [],+ "active": true+}+```++`name` is 2 to 80 characters, `price_usd` is 0.99 to 999, `interval` is+`weekly` or `monthly` (default `monthly`), `perks` is up to 10 strings,+`included_skills` up to 50. `agent_id` is optional and must be an agent you own.++**Response** (`201`): `{ "plan": { … } }`++**Errors:** `400` (`validation_error`), `401` (`unauthorized`), `403`+(`csrf_missing` / `csrf_invalid`, or `forbidden` when `agent_id` is not yours),+`409` (`conflict`: the 3-active-plan cap), `429`.++---++### Update a plan++```+PATCH /api/subscriptions/plans/:id+PUT /api/subscriptions/plans/:id+```++Requires auth, creator only. Both verbs behave identically: the body is a+partial update, and any field left out is untouched. `PUT` is accepted because+the dashboard plan editor saves with it.++**Request body:** any subset of `name`, `price_usd`, `interval`, `perks`,+`included_skills`, `active`.++**Response:** `{ "plan": { … } }`++**Errors:** `400` (`validation_error`, including an empty body: "nothing to+update"), `401`, `403`, `404` (`not_found`: unknown plan, or not yours), `409`+(reactivating past the 3-active cap).++---++### Deactivate a plan++```+DELETE /api/subscriptions/plans/:id+```++Requires auth, creator only. A soft delete: the row stays and `active` flips to+`false`, so existing subscribers keep their record and the plan can be+reactivated with `PATCH { "active": true }`.++**Response:** `{ "ok": true }`++**Errors:** `400`, `401`, `403`, `404`.++---++### Subscribe (x402 renewal intent)++```+POST /api/subscriptions+```++Requires auth. Creates or reactivates the subscription immediately and then+raises a payable intent for the first period. Payment is request-based (x402):+the server never pulls funds, it hands back what the subscriber owes.++**Request body**++```json+{ "plan_id": "735977d9-289d-4517-8ac4-68e97c649de8", "wallet_address": "<solana pubkey>" }+```++**Response** (`201`)++```json+{+ "subscription": {+ "id": "7c8e0051-0279-484a-b7d5-a19d821ade61",+ "plan_id": "735977d9-289d-4517-8ac4-68e97c649de8",+ "status": "active",+ "current_period_end": "2026-09-15T06:16:50.257Z",+ "payment_method": "x402"+ },+ "payment": { "pending": true, "paymentId": "…", "payUrl": "https://three.ws/pay/…" }+}+```++`payment` reports the first charge attempt and is informational: a plan whose+creator has no payout wallet answers `{ "success": false, "error":+"creator_payout_wallet_missing" }` while the subscription itself is still+created.++**Errors:** `400`, `401`, `403`, `404` (`not_found`: unknown plan), `409`+(`conflict`: plan deactivated, your own plan, or already subscribed), `429`.++---++### My subscriptions++```+GET /api/subscriptions/mine+```++Requires auth. Every subscription the caller holds, newest first, joined with+the plan name/price/interval and the creator's display name.++```json+{ "subscriptions": [ { "id": "…", "status": "active", "plan_name": "Supporter", "price_usd": "9.99", "creator_name": "…" } ] }+```++---++### Subscription detail++```+GET /api/subscriptions/:id+```++Requires auth. Readable by the subscriber **or** the plan's creator; anyone else+gets `404`.++---++### Cancel a subscription++```+DELETE /api/subscriptions/:id+```++Requires auth, subscriber only. Sets `status = 'cancelled'` and stamps+`cancelled_at`; the record is kept so the period already paid for stays+auditable. Re-subscribing to the same plan reactivates this row.++**Response:** `{ "ok": true, "subscription": { "id": "…", "status": "cancelled" } }`++---++### Solana USDC checkout: quote++```+POST /api/subscriptions/subscribe+```++Requires auth. Quotes the exact USDC split for one period, persists a pending+checkout with a Solana-Pay reference, and returns a base64+`VersionedTransaction` for the buyer's wallet to sign and broadcast. The+platform pre-signs as fee payer when a payer keypair is configured, so the+subscriber needs no SOL.++**Request body**++```json+{ "tierId": "735977d9-289d-4517-8ac4-68e97c649de8", "buyerPublicKey": "<solana pubkey>" }+```++**Response** (`200`)++```json+{+ "data": {+ "transaction": "<base64 VersionedTransaction>",+ "reference": "7qhfZb3yGi93qw3gp7KhbEwbmiXCQYdS5w3iCgG8azYs",+ "recipient": "<creator payout address>",+ "amount": "9990000",+ "creator_amount": "9990000",+ "currency_mint": "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v",+ "mint_decimals": 6,+ "gasless": false,+ "label": "Subscribe: Supporter",+ "message": "Subscribe to 'Supporter' (monthly)",+ "tier": { "id": "…", "name": "Supporter", "price_usd": 9.99, "interval": "monthly" }+ }+}+```++Amounts are USDC atomic units (6 decimals). When a platform fee applies, a+`fee` block carries its recipient, amount and bps, and `creator_amount` is the+remainder. Calling twice inside the 30-minute window reuses the same pending+checkout rather than minting a second one.++**Errors:** `400` (`validation_error`), `401`, `403`, `404` (`not_found`),+`409` (`conflict`: tier inactive or your own; `already_subscribed`), `412`+(`creator_wallet_missing`), `429`.++---++### Solana USDC checkout: verify++```+POST /api/subscriptions/verify+```++Requires auth. Validates the broadcast transaction against the **persisted**+quote (never the client's numbers) and, on success, activates the subscription,+writes the first-period payment row, and opens the skill-access gate.++**Request body**++```json+{ "tierId": "735977d9-289d-4517-8ac4-68e97c649de8", "transactionSignature": "<base58 signature>" }+```++`transactionSignature` is optional: without it the chain is scanned by the+checkout's reference key.++**Response** (`200`)++```json+{+ "data": {+ "success": true,+ "status": "active",+ "subscription": { "id": "…", "current_period_end": "2026-09-15T06:16:50.257Z" },+ "tx_signature": "…"+ }+}+```++While the transaction is not yet visible on chain the response is+`200 { "data": { "status": "pending" } }`; poll until it settles. Verifying an+already-confirmed checkout is idempotent and returns the live subscription.++**Errors:** `400`, `401`, `403`, `404` (`no_pending_checkout`), `409`+(`checkout_closed`, or `transfer_mismatch` when the on-chain transfer does not+match the quote), `410` (`checkout_expired`), `429`.++---+## 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-subscriptions-01.md b/prompts/swarm-100/api-subscriptions-01.mddeleted file mode 100644index db1fec9f0..000000000--- a/prompts/swarm-100/api-subscriptions-01.md+++ /dev/null@@ -1,104 +0,0 @@-# API audit: api/subscriptions batch 01 (4 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/subscriptions/index.js-- api/subscriptions/plans.js-- api/subscriptions/subscribe.js-- api/subscriptions/verify.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-subscriptions-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/subscriptions-endpoints.test.js b/tests/subscriptions-endpoints.test.jsnew file mode 100644index 000000000..97d32b920--- /dev/null+++ b/tests/subscriptions-endpoints.test.js@@ -0,0 +1,227 @@+// Regressions for /api/subscriptions and /api/subscriptions/plans.+//+// Three faults these lock in, all found by probing the live handlers:+// 1. A malformed path id (/api/subscriptions/not-a-uuid, /plans/not-a-uuid)+// went straight into a uuid comparison, so Postgres answered 22P02 and the+// caller got an opaque 500 instead of "your id is wrong".+// 2. PUT /api/subscriptions/plans/:id answered 405, which meant the dashboard+// plan editor (src/dashboard-next/pages/monetize.js saves an edit with PUT)+// could never save a change to an existing tier.+// 3. GET /api/subscriptions/plans/:id fell through to the list handler and+// answered "creator_id or agent_id required" for a perfectly well-formed+// request. It now serves the plan, with drafts visible only to their owner.+//+// A HEAD probe used to match no dispatch branch and fall through to 405 on both+// handlers; RFC 9110 9.3.2 requires it to reach whatever GET reaches.++import { describe, it, expect, vi, beforeEach } from 'vitest';++const sqlMock = vi.fn();+vi.mock('../api/_lib/db.js', () => ({+ sql: (...a) => sqlMock(...a),+ isDbUnavailableError: () => false,+ isDbCapacityError: () => false,+}));++const getSessionUserMock = vi.fn();+vi.mock('../api/_lib/auth.js', () => ({+ getSessionUser: (...a) => getSessionUserMock(...a),+ authenticateBearer: vi.fn(async () => null),+ extractBearer: vi.fn(() => null),+}));++vi.mock('../api/_lib/csrf.js', () => ({ requireCsrf: vi.fn(async () => true) }));+vi.mock('../api/_lib/rate-limit.js', () => ({+ clientIp: () => '127.0.0.1',+ limits: {+ publicIp: async () => ({ success: true, limit: 100, remaining: 99, reset: Date.now() + 1000 }),+ authIp: async () => ({ success: true, limit: 100, remaining: 99, reset: Date.now() + 1000 }),+ },+}));+vi.mock('../api/_lib/subscription-billing.js', () => ({+ chargeSubscription: vi.fn(async () => ({ success: false, error: 'creator_payout_wallet_missing' })),+}));++const { default: plansHandler } = await import('../api/subscriptions/plans.js');+const { default: subsHandler } = await import('../api/subscriptions/index.js');++const OWNER = 'ab2aabd2-39f7-493b-8191-c9f174af62ab';+const OTHER = 'f23703c0-9d75-4e60-9a4c-349da5d7a2f2';+const PLAN = '735977d9-289d-4517-8ac4-68e97c649de8';+const SUB = '7c8e0051-0279-484a-b7d5-a19d821ade61';++function mkReq({ method = 'GET', url = '/', headers = {}, body = null } = {}) {+ return {+ method,+ url,+ headers: { ...headers },+ body: body ?? undefined,+ };+}++function mkRes() {+ return {+ statusCode: 200,+ headers: {},+ body: undefined,+ headersSent: false,+ writableEnded: false,+ setHeader(k, v) { this.headers[k.toLowerCase()] = v; },+ getHeader(k) { return this.headers[k.toLowerCase()]; },+ end(b) { this.body = b; this.writableEnded = true; },+ };+}++const parse = (res) => (res.body ? JSON.parse(res.body) : undefined);+const jsonReq = (method, url, body) =>+ mkReq({ method, url, headers: { 'content-type': 'application/json' }, body });++// The handlers use tagged-template sql``; queue one result array per call.+let sqlQueue = [];+beforeEach(() => {+ sqlQueue = [];+ sqlMock.mockReset().mockImplementation(() => Promise.resolve(sqlQueue.length ? sqlQueue.shift() : []));+ getSessionUserMock.mockReset().mockResolvedValue({ id: OWNER });+});++describe('subscriptions: malformed path ids answer 4xx, never a 500', () => {+ it('GET /api/subscriptions/:id rejects a non-uuid before touching the database', async () => {+ const res = mkRes();+ await subsHandler(mkReq({ url: '/api/subscriptions/not-a-uuid' }), res);+ expect(res.statusCode).toBe(400);+ expect(parse(res).error).toBe('validation_error');+ expect(sqlMock).not.toHaveBeenCalled();+ });++ it('DELETE /api/subscriptions/:id rejects a non-uuid before touching the database', async () => {+ const res = mkRes();+ await subsHandler(mkReq({ method: 'DELETE', url: '/api/subscriptions/not-a-uuid' }), res);+ expect(res.statusCode).toBe(400);+ expect(parse(res).error).toBe('validation_error');+ expect(sqlMock).not.toHaveBeenCalled();+ });++ it('PATCH /api/subscriptions/plans/:id rejects a non-uuid', async () => {+ const res = mkRes();+ await plansHandler(jsonReq('PATCH', '/api/subscriptions/plans/not-a-uuid', { name: 'abc' }), res);+ expect(res.statusCode).toBe(400);+ expect(parse(res).error_description).toMatch(/valid UUID/);+ });++ it('DELETE /api/subscriptions/plans/:id rejects a non-uuid', async () => {+ const res = mkRes();+ await plansHandler(mkReq({ method: 'DELETE', url: '/api/subscriptions/plans/not-a-uuid' }), res);+ expect(res.statusCode).toBe(400);+ expect(sqlMock).not.toHaveBeenCalled();+ });++ it('GET /api/subscriptions/plans/:id rejects a non-uuid', async () => {+ const res = mkRes();+ await plansHandler(mkReq({ url: '/api/subscriptions/plans/not-a-uuid' }), res);+ expect(res.statusCode).toBe(400);+ expect(sqlMock).not.toHaveBeenCalled();+ });+});++describe('subscription plans: the dashboard editor saves with PUT', () => {+ it('PUT /api/subscriptions/plans/:id updates the plan like PATCH does', async () => {+ sqlQueue = [+ [{ id: PLAN, active: true }],+ [{ id: PLAN, name: 'Renamed', active: true }],+ ];+ const res = mkRes();+ await plansHandler(+ jsonReq('PUT', `/api/subscriptions/plans/${PLAN}`, { name: 'Renamed', price_usd: 6 }),+ res,+ );+ expect(res.statusCode).toBe(200);+ expect(parse(res).plan).toMatchObject({ id: PLAN, name: 'Renamed' });+ });++ it('advertises PUT in the CORS preflight', async () => {+ const res = mkRes();+ await plansHandler(+ mkReq({ method: 'OPTIONS', url: '/api/subscriptions/plans', headers: { origin: 'http://localhost:3000' } }),+ res,+ );+ expect(res.statusCode).toBe(204);+ expect(res.headers['access-control-allow-methods']).toContain('PUT');+ });+});++describe('subscription plans: single-plan read', () => {+ it('serves an active plan to an anonymous caller', async () => {+ getSessionUserMock.mockResolvedValue(null);+ sqlQueue = [[{ id: PLAN, creator_id: OTHER, name: 'Tier', active: true }]];+ const res = mkRes();+ await plansHandler(mkReq({ url: `/api/subscriptions/plans/${PLAN}` }), res);+ expect(res.statusCode).toBe(200);+ expect(parse(res).plan.id).toBe(PLAN);+ });++ it('404s an unknown plan', async () => {+ sqlQueue = [[]];+ const res = mkRes();+ await plansHandler(mkReq({ url: `/api/subscriptions/plans/${PLAN}` }), res);+ expect(res.statusCode).toBe(404);+ expect(parse(res).error).toBe('not_found');+ });++ it('hides a draft from everyone but its creator', async () => {+ getSessionUserMock.mockResolvedValue({ id: OTHER });+ sqlQueue = [[{ id: PLAN, creator_id: OWNER, name: 'Draft', active: false }]];+ const res = mkRes();+ await plansHandler(mkReq({ url: `/api/subscriptions/plans/${PLAN}` }), res);+ expect(res.statusCode).toBe(404);+ });++ it('shows a draft to its creator', async () => {+ getSessionUserMock.mockResolvedValue({ id: OWNER });+ sqlQueue = [[{ id: PLAN, creator_id: OWNER, name: 'Draft', active: false }]];+ const res = mkRes();+ await plansHandler(mkReq({ url: `/api/subscriptions/plans/${PLAN}` }), res);+ expect(res.statusCode).toBe(200);+ expect(parse(res).plan.active).toBe(false);+ });+});++describe('subscriptions: HEAD reaches the GET branch', () => {+ it('HEAD /api/subscriptions/mine answers like GET', async () => {+ sqlQueue = [[{ id: SUB, plan_id: PLAN, status: 'active' }]];+ const res = mkRes();+ await subsHandler(mkReq({ method: 'HEAD', url: '/api/subscriptions/mine' }), res);+ expect(res.statusCode).toBe(200);+ });++ it('HEAD /api/subscriptions/plans answers like GET', async () => {+ sqlQueue = [[]];+ const res = mkRes();+ await plansHandler(mkReq({ method: 'HEAD', url: `/api/subscriptions/plans?creator_id=${OWNER}` }), res);+ expect(res.statusCode).toBe(200);+ });+});++describe('subscriptions: unchanged contract', () => {+ it('GET /api/subscriptions/mine requires a session', async () => {+ getSessionUserMock.mockResolvedValue(null);+ const res = mkRes();+ await subsHandler(mkReq({ url: '/api/subscriptions/mine' }), res);+ expect(res.statusCode).toBe(401);+ expect(parse(res).error).toBe('unauthorized');+ });++ it('POST /api/subscriptions refuses a plan the caller owns', async () => {+ sqlQueue = [[{ id: PLAN, creator_id: OWNER, price_usd: '9.99', interval: 'monthly', active: true }]];+ const res = mkRes();+ await subsHandler(jsonReq('POST', '/api/subscriptions', { plan_id: PLAN }), res);+ expect(res.statusCode).toBe(409);+ expect(parse(res).error_description).toMatch(/your own plan/);+ });++ it('GET /api/subscriptions/plans still requires creator_id or agent_id', async () => {+ const res = mkRes();+ await plansHandler(mkReq({ url: '/api/subscriptions/plans' }), res);+ expect(res.statusCode).toBe(400);+ expect(parse(res).error_description).toMatch(/creator_id or agent_id/);+ });+});