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(api): tighten the mint-scene, notifications and skill-purchase handlers, with tests

nirholas0d1555900251
diff --git a/api/nft/mint-scene.js b/api/nft/mint-scene.js
index f61b7fefd..52d07a676 100644
--- a/api/nft/mint-scene.js
+++ b/api/nft/mint-scene.js
@@ -5,6 +5,7 @@ import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.
import { createUmi } from '@metaplex-foundation/umi-bundle-defaults';
import { mplCore, createV1 } from '@metaplex-foundation/mpl-core';
import { solanaConnection } from '../_lib/solana/connection.js';
+import { pinToIPFS, ipfsPinningConfigured } from '../_lib/ipfs-pin.js';
import {
generateSigner,
publicKey as umiPublicKey,
@@ -12,24 +13,27 @@ import {
createNoopSigner,
} from '@metaplex-foundation/umi';
-async function uploadToNftStorage(token, bytes, contentType) {
- const resp = await fetch('https://api.nft.storage/upload', {
- method: 'POST',
- headers: {
- Authorization: `Bearer ${token}`,
- 'Content-Type': contentType,
- },
- body: bytes,
- });
- if (!resp.ok) {
- const txt = await resp.text();
- throw Object.assign(new Error(`NFT.Storage upload failed (${resp.status}): ${txt}`), {
- status: 502,
- code: 'upstream_error',
+// Pin through the platform's shared IPFS transport rather than a second,
+// hand-rolled uploader. The old path posted to NFT.Storage on NFT_STORAGE_TOKEN,
+// a variable set in no environment (not .env, not .env.local, not the Cloud Run
+// service), so every scene mint answered 503 not_configured before it read a
+// byte of the body. api/_lib/ipfs-pin.js is the same Pinata/web3.storage chain
+// the pump launch lane and the pinning API already run on, and Pinata IS
+// configured in production, so this is what makes the endpoint work at all.
+//
+// A pinned uri is the public gateway URL, not an ipfs:// pointer: wallets,
+// marketplaces, and our own chat NFT viewer all fetch it directly, and the
+// viewer hands the model URL straight to GLTFLoader, which cannot resolve
+// ipfs://.
+async function pinAsset(bytes, filename) {
+ const pinned = await pinToIPFS(bytes, filename);
+ if (!pinned) {
+ throw Object.assign(new Error('no IPFS pinning provider configured'), {
+ status: 503,
+ code: 'not_configured',
});
}
- const data = await resp.json();
- return `ipfs://${data.value.cid}`;
+ return pinned.uri;
}
// Strict base64: the scene GLB and its thumbnail arrive base64-encoded, and
@@ -49,14 +53,14 @@ export default wrap(async (req, res) => {
if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
if (!method(req, res, ['POST'])) return;
- const storageToken = env.NFT_STORAGE_TOKEN;
- if (!storageToken) return error(res, 503, 'not_configured', 'NFT_STORAGE_TOKEN not configured');
+ if (!ipfsPinningConfigured())
+ return error(res, 503, 'not_configured', 'no IPFS pinning provider configured (set PINATA_JWT)');
const rl = await limits.authIp(clientIp(req));
if (!rl.success) return rateLimited(res, rl);
- // The uploads below run on the platform's NFT.Storage token, never let an
- // anonymous caller push arbitrary blobs to IPFS on our account.
+ // The pins below run on the platform's own pinning account, never let an
+ // anonymous caller push arbitrary blobs to IPFS on it.
const session = await getSessionUser(req);
const bearer = session ? null : await authenticateBearer(extractBearer(req));
if (!session && !bearer) {
@@ -97,14 +101,16 @@ export default wrap(async (req, res) => {
return error(res, 400, 'validation_error', 'invalid ownerPubkey');
}
+ const slug = name.trim().toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '') || 'scene';
+
let glbUri, thumbUri;
try {
[glbUri, thumbUri] = await Promise.all([
- uploadToNftStorage(storageToken, glbBytes, 'model/gltf-binary'),
- uploadToNftStorage(storageToken, thumbBytes, 'image/png'),
+ pinAsset(glbBytes, `${slug}.glb`),
+ pinAsset(thumbBytes, `${slug}.png`),
]);
} catch (e) {
- console.error('[nft/mint-scene] asset upload failed', e?.message);
+ console.error('[nft/mint-scene] asset pin failed', e?.message);
return respondError(res, e.status || 502, e.code || 'upstream_error', e);
}
@@ -124,13 +130,9 @@ export default wrap(async (req, res) => {
let metadataUri;
try {
- metadataUri = await uploadToNftStorage(
- storageToken,
- Buffer.from(JSON.stringify(metadata)),
- 'application/json',
- );
+ metadataUri = await pinAsset(Buffer.from(JSON.stringify(metadata)), `${slug}.json`);
} catch (e) {
- console.error('[nft/mint-scene] metadata upload failed', e?.message);
+ console.error('[nft/mint-scene] metadata pin failed', e?.message);
return respondError(res, e.status || 502, e.code || 'upstream_error', e);
}
diff --git a/api/notifications/read-all.js b/api/notifications/read-all.js
index 0ecda340d..aeaa45ecd 100644
--- a/api/notifications/read-all.js
+++ b/api/notifications/read-all.js
@@ -14,12 +14,17 @@ export default wrap(async (req, res) => {
if (!(await requireCsrf(req, res, user.id))) return;
+ // Count the rows, do not ask Postgres to count them: a window function is
+ // illegal in RETURNING ("window functions are not allowed in RETURNING"), so
+ // the aggregate form threw on every call and the bell's "mark all read"
+ // answered 500 for every user. RETURNING one column per updated row and
+ // taking its length is the form Postgres actually allows.
const rows = await sql`
update user_notifications
set read_at = now()
where user_id = ${user.id} and read_at is null
- returning count(*) over ()::int as count
+ returning id
`;
- return json(res, 200, { marked_read: rows[0]?.count ?? 0 });
+ return json(res, 200, { marked_read: rows.length });
});
diff --git a/api/purchase/skill.js b/api/purchase/skill.js
index 5ad80e50d..62efd588d 100644
--- a/api/purchase/skill.js
+++ b/api/purchase/skill.js
@@ -1,105 +1,201 @@
/**
- * GET /api/purchase/skill?agent_id=&skill= — Solana Pay transaction request GET (label/icon)
- * POST /api/purchase/skill?agent_id=&skill= — Solana Pay transaction request POST (build tx)
+ * Solana Pay TRANSACTION request for a pending skill purchase.
*
- * Implements the Solana Pay Transaction Request spec so wallets that scan a
- * QR code can fetch and sign the USDC transfer directly.
+ * GET /api/purchase/skill?reference=<base58>
+ * → { label, icon } — what the wallet shows before it asks to sign.
+ * POST /api/purchase/skill?reference=<base58> body: { account: <base58> }
+ * → { transaction: <base64>, message } — the prepared purchase transfer.
+ *
+ * Why this exists next to the plain `solana:<recipient>?amount=…` transfer-request
+ * QR (src/shared/skill-purchase.js): a transfer request can only express ONE leg
+ * paid by the scanning wallet, so on that rail the buyer must already hold SOL for
+ * the network fee, the creator's token account must already exist, and a platform
+ * fee split cannot be expressed at all. Building the transaction here fixes all
+ * three: the marketplace payer sponsors the network fee when it is configured,
+ * missing associated token accounts are created idempotently, and the treasury fee
+ * leg rides the same transaction the buyer signs.
+ *
+ * The purchase row is NEVER created here. A buyer is a signed-in user and this
+ * endpoint is reached by a wallet with no session, so the pending row (buyer,
+ * price, fee split, expiry) is created by the authenticated checkout,
+ * POST /api/marketplace/purchase, and this endpoint only builds the transaction
+ * that settles it. `reference` is the base58 Solana Pay key of that row.
+ *
+ * Instruction order is load-bearing: @solana/pay's validateTransfer inspects the
+ * LAST instruction, so the reference-carrying creator leg is always last and the
+ * treasury fee leg (when there is one) sits before it. api/_lib/purchase-confirm.js
+ * verifies exactly that shape.
*/
-import { Keypair, PublicKey, Transaction } from '@solana/web3.js';
-import { solanaConnection } from '../_lib/solana/connection.js';
-import { getAssociatedTokenAddressSync, createTransferCheckedInstruction, getMint } from '@solana/spl-token';
-import { findReference } from '@solana/pay';
+import { PublicKey, Transaction } from '@solana/web3.js';
+import {
+ getAssociatedTokenAddressSync,
+ createAssociatedTokenAccountIdempotentInstruction,
+ createTransferCheckedInstruction,
+} from '@solana/spl-token';
import { sql } from '../_lib/db.js';
-import { cors, error, json, method, readJson, wrap } from '../_lib/http.js';
+import { env } from '../_lib/env.js';
+import { cors, error, json, method, readJson, wrap, rateLimited } from '../_lib/http.js';
+import { clientIp, limits } from '../_lib/rate-limit.js';
+import { logEvent, resolvePayoutAddress } from '../_lib/purchase-confirm.js';
+import { solanaConnection } from '../_lib/solana/connection.js';
+import { resolveMarketplacePayer } from '../_lib/solana/gasless-tx.js';
const SOLANA_RPC = process.env.SOLANA_RPC_URL || 'https://api.mainnet-beta.solana.com';
+const REFERENCE_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/; // base58 Pubkey
+
+// Solana Pay wallets surface `message` on a failed request; the rest of the
+// platform reads the { error, error_description } shape. Send both.
+function payError(res, status, code, message) {
+ return error(res, status, code, message, { message });
+}
export default wrap(async (req, res) => {
- if (cors(req, res, { methods: 'GET,POST,OPTIONS' })) return;
+ if (cors(req, res, { methods: 'GET,POST,OPTIONS', origins: '*' })) return;
if (!method(req, res, ['GET', 'POST'])) return;
const url = new URL(req.url, 'http://x');
- const agentId = url.searchParams.get('agent_id');
- const skillName = url.searchParams.get('skill');
-
- if (!agentId || !skillName) {
- return error(res, 400, 'validation_error', 'agent_id and skill query params required');
+ const reference = (url.searchParams.get('reference') || '').trim();
+ if (!REFERENCE_RE.test(reference)) {
+ return payError(res, 400, 'validation_error', 'a valid purchase reference is required');
}
+ const rl = await limits.publicIp(clientIp(req));
+ if (!rl.success) return rateLimited(res, rl);
+
+ const [purchase] = await sql`
+ SELECT sp.reference, sp.status, sp.expires_at, sp.agent_id, sp.skill, sp.kind,
+ sp.amount, sp.currency_mint, sp.chain,
+ sp.platform_fee_amount, sp.platform_fee_wallet,
+ COALESCE(asp.mint_decimals, 6) AS mint_decimals,
+ a.name AS agent_name
+ FROM skill_purchases sp
+ LEFT JOIN agent_skill_prices asp
+ ON asp.agent_id = sp.agent_id AND asp.skill = sp.skill
+ LEFT JOIN agent_identities a ON a.id = sp.agent_id
+ WHERE sp.reference = ${reference}
+ LIMIT 1
+ `;
+ if (!purchase) return payError(res, 404, 'not_found', 'no pending purchase matches this reference');
+
+ const skillLabel = String(purchase.skill).slice(0, 40);
+
if (req.method === 'GET') {
- // Solana Pay spec: return label + icon for the wallet QR display
- return json(res, 200, {
- label: 'three.ws Agent Marketplace',
- icon: 'https://three.ws/favicon.ico',
- });
+ // Solana Pay spec: the GET is the wallet's "who am I paying" probe.
+ return json(
+ res,
+ 200,
+ { label: `three.ws · ${skillLabel}`, icon: `${env.APP_ORIGIN}/favicon.svg` },
+ { 'cache-control': 'no-store' },
+ );
}
- // POST — wallet sends its account (public key), we return a prepared transaction
- const body = await readJson(req).catch(() => null);
- const account = body?.account;
- if (!account) return error(res, 400, 'validation_error', 'account required');
+ if (purchase.status === 'confirmed') {
+ return payError(res, 409, 'already_confirmed', 'this purchase is already paid');
+ }
+ if (purchase.status !== 'pending') {
+ return payError(res, 410, 'purchase_not_payable', `this purchase is ${purchase.status}`);
+ }
+ if (purchase.expires_at && new Date(purchase.expires_at).getTime() <= Date.now()) {
+ return payError(res, 410, 'purchase_expired', 'this pending purchase expired; start a new one');
+ }
+ if (purchase.chain !== 'solana') {
+ return payError(res, 400, 'unsupported_chain', 'only solana purchases settle through this endpoint');
+ }
- const [price] = await sql`
- SELECT amount, currency_mint, chain
- FROM agent_skill_prices
- WHERE agent_id = ${agentId} AND skill = ${skillName} AND is_active = true
- LIMIT 1
- `;
- if (!price) return error(res, 404, 'not_found', 'skill is not for sale');
- if (price.chain !== 'solana') {
- return error(res, 400, 'unsupported_chain', 'only solana transactions are supported via this endpoint');
+ const body = await readJson(req).catch(() => null);
+ const account = typeof body?.account === 'string' ? body.account.trim() : '';
+ if (!REFERENCE_RE.test(account)) {
+ return payError(res, 400, 'validation_error', 'account must be a base58 wallet address');
}
- // Resolve payout wallet
- const [payout] = await sql`
- SELECT pw.address
- FROM agent_identities a
- JOIN agent_payout_wallets pw
- ON pw.user_id = a.user_id
- AND pw.chain = 'solana'
- AND (pw.agent_id = a.id OR pw.is_default = true)
- WHERE a.id = ${agentId} AND a.deleted_at IS NULL
- ORDER BY (pw.agent_id IS NOT NULL) DESC, pw.is_default DESC, pw.created_at ASC
- LIMIT 1
- `;
- let recipient = payout?.address;
- if (!recipient) {
- const [row] = await sql`SELECT meta FROM agent_identities WHERE id = ${agentId}`;
- recipient = row?.meta?.solana_address ?? null;
+ const payoutAddress = await resolvePayoutAddress(purchase.agent_id, 'solana');
+ if (!payoutAddress) {
+ return payError(res, 412, 'creator_wallet_missing', 'the agent owner has not configured a payout wallet');
}
- if (!recipient) return error(res, 412, 'creator_wallet_missing', 'agent owner has not configured a payout wallet');
-
- // Reference keypair for Solana Pay tracking
- const referenceKeypair = Keypair.generate();
- const referenceKey = referenceKeypair.publicKey;
-
- // Record pending purchase
- await sql`
- INSERT INTO skill_purchases (agent_id, skill, status, reference, amount, currency_mint, chain)
- VALUES (${agentId}, ${skillName}, 'pending', ${referenceKey.toBase58()},
- ${price.amount}, ${price.currency_mint}, 'solana')
- ON CONFLICT DO NOTHING
- `;
- // Build transaction
- const connection = solanaConnection({ url: SOLANA_RPC, commitment: 'confirmed' });
- const { blockhash } = await connection.getLatestBlockhash('confirmed');
+ const feeAtomics = BigInt(purchase.platform_fee_amount || 0);
+ const feeWallet = feeAtomics > 0n ? purchase.platform_fee_wallet : null;
+ const creatorAtomics = BigInt(purchase.amount) - (feeWallet ? feeAtomics : 0n);
+ if (creatorAtomics <= 0n) {
+ return payError(res, 409, 'invalid_quote', 'this purchase has no payable creator amount');
+ }
- const mintInfo = await getMint(connection, new PublicKey(price.currency_mint));
- const buyer = new PublicKey(account);
- const mintKey = new PublicKey(price.currency_mint);
+ let buyer;
+ let mintKey;
+ let creatorKey;
+ let feeKey = null;
+ try {
+ buyer = new PublicKey(account);
+ mintKey = new PublicKey(purchase.currency_mint);
+ creatorKey = new PublicKey(payoutAddress);
+ if (feeWallet) feeKey = new PublicKey(feeWallet);
+ } catch {
+ return payError(res, 400, 'validation_error', 'account, mint, or payout address is not a valid public key');
+ }
- const fromAta = getAssociatedTokenAddressSync(mintKey, buyer);
- const toAta = getAssociatedTokenAddressSync(mintKey, new PublicKey(recipient));
+ const decimals = Number(purchase.mint_decimals ?? 6);
+ const referenceKey = new PublicKey(reference);
+ const connection = solanaConnection({ url: SOLANA_RPC, commitment: 'confirmed' });
+ const payer = await resolveMarketplacePayer();
+ const feePayer = payer ? payer.publicKey : buyer;
+
+ const buyerAta = getAssociatedTokenAddressSync(mintKey, buyer);
+ const creatorAta = getAssociatedTokenAddressSync(mintKey, creatorKey);
+ const instructions = [];
+
+ // A creator (or treasury) who has never held this mint has no token account
+ // yet, and a transfer into a missing account fails. Idempotent creation costs
+ // nothing when the account already exists and rescues the purchase when it
+ // does not; the fee payer funds the rent.
+ instructions.push(
+ createAssociatedTokenAccountIdempotentInstruction(feePayer, creatorAta, creatorKey, mintKey),
+ );
+ if (feeKey) {
+ const treasuryAta = getAssociatedTokenAddressSync(mintKey, feeKey);
+ instructions.push(
+ createAssociatedTokenAccountIdempotentInstruction(feePayer, treasuryAta, feeKey, mintKey),
+ createTransferCheckedInstruction(buyerAta, mintKey, treasuryAta, buyer, feeAtomics, decimals),
+ );
+ }
- const ix = createTransferCheckedInstruction(
- fromAta, mintKey, toAta, buyer, BigInt(price.amount), mintInfo.decimals,
+ // Creator leg LAST, carrying the Solana Pay reference — this is the
+ // instruction findReference locates and validateTransfer checks.
+ const creatorIx = createTransferCheckedInstruction(
+ buyerAta,
+ mintKey,
+ creatorAta,
+ buyer,
+ creatorAtomics,
+ decimals,
);
- ix.keys.push({ pubkey: referenceKey, isSigner: false, isWritable: false });
+ creatorIx.keys.push({ pubkey: referenceKey, isSigner: false, isWritable: false });
+ instructions.push(creatorIx);
+
+ const { blockhash } = await connection.getLatestBlockhash('confirmed');
+ const tx = new Transaction({ feePayer, recentBlockhash: blockhash }).add(...instructions);
+ // Sponsored checkout: the platform signs as fee payer so a buyer holding only
+ // USDC can still pay. The buyer adds the authority signature in their wallet.
+ if (payer) tx.partialSign(payer);
- const tx = new Transaction({ feePayer: buyer, recentBlockhash: blockhash }).add(ix);
const serialized = tx.serialize({ requireAllSignatures: false, verifySignatures: false });
- return json(res, 200, { transaction: serialized.toString('base64') });
+ await logEvent(reference, 'transaction_request_built', {
+ account,
+ gasless: !!payer,
+ fee_leg: !!feeKey,
+ });
+
+ const agentName = purchase.agent_name ? ` on ${String(purchase.agent_name).slice(0, 40)}` : '';
+ return json(
+ res,
+ 200,
+ {
+ transaction: serialized.toString('base64'),
+ message: purchase.kind === 'time_pass'
+ ? `Unlock timed access to ${skillLabel}${agentName}`
+ : `Unlock ${skillLabel}${agentName}`,
+ },
+ { 'cache-control': 'no-store' },
+ );
});
diff --git a/tests/_helpers/monetization.js b/tests/_helpers/monetization.js
index d84192049..2b772785d 100644
--- a/tests/_helpers/monetization.js
+++ b/tests/_helpers/monetization.js
@@ -32,9 +32,12 @@ export function createTestUser() {
return { session: { id: userId } };
}
+// `body` is JSON-encoded for you. Pass a string instead to send exact bytes,
+// which is the only way to express a literal JSON.stringify cannot produce
+// (`1e400`, which parses back as Infinity, is the one that matters here).
export function makeReq({ method = 'GET', url = '/', headers = {}, body = null, query = null } = {}) {
const base = body
- ? Readable.from([Buffer.from(JSON.stringify(body))])
+ ? Readable.from([Buffer.from(typeof body === 'string' ? body : JSON.stringify(body))])
: Readable.from([]);
base.method = method;
base.url = url;
diff --git a/tests/play-builds-mint-gate.test.js b/tests/play-builds-mint-gate.test.js
new file mode 100644
index 000000000..a74414063
--- /dev/null
+++ b/tests/play-builds-mint-gate.test.js
@@ -0,0 +1,162 @@
+// HTTP-level tests for /api/play/builds, the featured-builds surface of the
+// /play coin worlds.
+//
+// The mint a caller sends is not just an identifier: builds-store.js turns it
+// straight into the Redis key a coin's builds live under. So the handler has to
+// reject anything that is not a real coin-world address BEFORE the store sees
+// it, on the unauthenticated POST as well as the public GET. These tests pin
+// that boundary: real Solana mints and EVM coin worlds get through, malformed
+// strings of a plausible length do not.
+
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { Readable } from 'node:stream';
+
+const SOLANA_MINT = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';
+const EVM_WORLD = '0x1234567890abcdef1234567890ABCDEF12345678';
+const THUMB = 'data:image/jpeg;base64,' + 'A'.repeat(64);
+
+// The store is stubbed so these tests exercise the handler's validation, not
+// Redis. Every call it does receive is recorded, which is how the rejection
+// cases prove the store was never reached rather than merely that a 400 came
+// back for some other reason.
+const listBuilds = vi.fn(async () => []);
+const publishBuild = vi.fn(async () => ({ id: 'b_test' }));
+vi.mock('../api/_lib/builds-store.js', () => ({
+ listBuilds: (...a) => listBuilds(...a),
+ publishBuild: (...a) => publishBuild(...a),
+}));
+
+const { default: handler } = await import('../api/play/builds.js');
+
+function mockRes() {
+ return {
+ statusCode: 200, _headers: {}, _body: '', _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; },
+ get json() { try { return JSON.parse(this._body); } catch { return null; } },
+ };
+}
+
+function mockReq({ method = 'GET', url = '/api/play/builds', query = {}, body = null } = {}) {
+ const r = Readable.from(body != null ? [Buffer.from(JSON.stringify(body))] : []);
+ r.method = method;
+ r.url = url;
+ r.query = query;
+ r.headers = { origin: 'http://localhost:3000', 'content-type': 'application/json' };
+ return r;
+}
+
+const get = async (mint) => {
+ const res = mockRes();
+ await handler(mockReq({ method: 'GET', query: { mint } }), res);
+ return res;
+};
+
+const post = async (mint) => {
+ const res = mockRes();
+ await handler(mockReq({ method: 'POST', body: { mint, blocks: 12, thumb: THUMB, title: 'test', author: 'test' } }), res);
+ return res;
+};
+
+beforeEach(() => {
+ listBuilds.mockClear();
+ publishBuild.mockClear();
+});
+
+// Strings that are the right LENGTH for a mint but are not addresses. Before the
+// format check, every one of these reached the store and minted a Redis key.
+const MALFORMED = {
+ 'a path traversal': '../../evil-key-000OIl-aaaaaaaaaaaaaaaa',
+ 'characters outside the base58 alphabet': '0'.repeat(40),
+ 'embedded spaces': 'a b c d e f g h i j k l m n o p q',
+ 'an EVM address with a bad hex digit': '0xZZZ4567890abcdef1234567890ABCDEF12345678',
+};
+
+describe('GET /api/play/builds', () => {
+ it('lists a Solana coin world', async () => {
+ const res = await get(SOLANA_MINT);
+ expect(res.statusCode).toBe(200);
+ expect(res.json).toEqual({ builds: [] });
+ expect(listBuilds).toHaveBeenCalledWith(SOLANA_MINT);
+ });
+
+ it('lists an EVM coin world', async () => {
+ const res = await get(EVM_WORLD);
+ expect(res.statusCode).toBe(200);
+ expect(listBuilds).toHaveBeenCalledWith(EVM_WORLD);
+ });
+
+ for (const [what, mint] of Object.entries(MALFORMED)) {
+ it(`refuses ${what} without reading the store`, async () => {
+ const res = await get(mint);
+ expect(res.statusCode).toBe(400);
+ expect(res.json.error).toBe('bad_mint');
+ expect(listBuilds).not.toHaveBeenCalled();
+ });
+ }
+
+ it('refuses a missing mint', async () => {
+ const res = await get('');
+ expect(res.statusCode).toBe(400);
+ expect(res.json.error).toBe('bad_mint');
+ expect(listBuilds).not.toHaveBeenCalled();
+ });
+});
+
+describe('POST /api/play/builds', () => {
+ it('publishes to a Solana coin world', async () => {
+ const res = await post(SOLANA_MINT);
+ expect(res.statusCode).toBe(201);
+ expect(res.json.ok).toBe(true);
+ expect(publishBuild).toHaveBeenCalledWith(SOLANA_MINT, expect.objectContaining({ blocks: 12, thumb: THUMB }));
+ });
+
+ it('publishes to an EVM coin world', async () => {
+ const res = await post(EVM_WORLD);
+ expect(res.statusCode).toBe(201);
+ expect(publishBuild).toHaveBeenCalledWith(EVM_WORLD, expect.anything());
+ });
+
+ for (const [what, mint] of Object.entries(MALFORMED)) {
+ it(`refuses ${what} without writing to the store`, async () => {
+ const res = await post(mint);
+ expect(res.statusCode).toBe(400);
+ expect(res.json.error).toBe('validation_error');
+ expect(publishBuild).not.toHaveBeenCalled();
+ });
+ }
+
+ it('answers 503, not 500, when persistence is unavailable', async () => {
+ publishBuild.mockRejectedValueOnce(new Error('persistence_unavailable'));
+ const res = await post(SOLANA_MINT);
+ expect(res.statusCode).toBe(503);
+ expect(res.json.error).toBe('unavailable');
+ });
+
+ it('refuses a screenshot past the size cap with a 413', async () => {
+ const res = mockRes();
+ await handler(mockReq({
+ method: 'POST',
+ body: { mint: SOLANA_MINT, blocks: 1, thumb: 'data:image/jpeg;base64,' + 'A'.repeat(300_000) },
+ }), res);
+ expect(res.statusCode).toBe(413);
+ expect(res.json.error).toBe('thumb_too_large');
+ expect(publishBuild).not.toHaveBeenCalled();
+ });
+
+ it('refuses a block count past the world cap', async () => {
+ const res = mockRes();
+ await handler(mockReq({ method: 'POST', body: { mint: SOLANA_MINT, blocks: 99_999, thumb: THUMB } }), res);
+ expect(res.statusCode).toBe(400);
+ expect(publishBuild).not.toHaveBeenCalled();
+ });
+});
+
+describe('/api/play/builds method handling', () => {
+ it('refuses a verb the surface does not serve', async () => {
+ const res = mockRes();
+ await handler(mockReq({ method: 'PUT' }), res);
+ expect(res.statusCode).toBe(405);
+ });
+});
diff --git a/tests/premium-endpoints.test.js b/tests/premium-endpoints.test.js
new file mode 100644
index 000000000..9b021ef14
--- /dev/null
+++ b/tests/premium-endpoints.test.js
@@ -0,0 +1,163 @@
+/**
+ * Boundary behaviour for two premium endpoints.
+ *
+ * POST /api/premium/subscribe
+ * premium_quotes.id is a uuid column. A quote_id that is not uuid-shaped used
+ * to reach the driver and come back as SQLSTATE 22P02, which the wrapper
+ * turned into a 500 with an opaque support ref. Malformed input has to answer
+ * 4xx, so the id is shaped at the boundary before any query runs.
+ *
+ * POST /api/premium/keys (rotate)
+ * The old credential must be revoked only AFTER its replacement exists. The
+ * reverse order means a failed mint leaves a paying customer with a revoked
+ * key and no way back (the retry hits the key_revoked branch).
+ *
+ * DB, session, CSRF, key mint, and the premium lib are mocked; the HTTP
+ * envelope helpers run for real so status codes and JSON bodies are genuine.
+ */
+
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+const USER = { id: '28e98fb2-2a98-4500-b45a-5a9ad7b3f7a8', email: '[email protected]' };
+const KEY_ID = 'sub_premiumkey01';
+const QUOTE_ID = '2af3ee5e-8b10-40d5-bbf2-f375197dc39f';
+const TX_SIG = '5Zx1uWnPZ8kkVYQ9mLXJx3nQ8Yb2c1D4eF5gH6jK7mN8pQ9rS1tU2vW3xY4zA5bC6dE7fG8hJ9kL1mN2pQ3r';
+
+const db = vi.hoisted(() => ({ handlers: [], calls: [] }));
+const keyLane = vi.hoisted(() => ({ order: [], mintFails: false }));
+
+vi.mock('../api/_lib/db.js', () => ({
+ sql: async (strings, ...values) => {
+ const text = strings.join(' $ ').replace(/\s+/g, ' ').trim();
+ db.calls.push({ text, values });
+ for (const h of db.handlers) {
+ if (h.match.test(text)) return h.result(values, text);
+ }
+ return [];
+ },
+ // http.js's wrap() classifies thrown errors through these on the 5xx path.
+ isDbUnavailableError: () => false,
+ isDbCapacityError: () => false,
+}));
+vi.mock('../api/_lib/auth.js', () => ({ getSessionUser: vi.fn(async () => USER) }));
+vi.mock('../api/_lib/csrf.js', () => ({ requireCsrf: vi.fn(async () => true) }));
+vi.mock('../api/_lib/rate-limit.js', () => ({
+ limits: {
+ premiumSubscribeIp: vi.fn(async () => ({ success: true, reset: Date.now() + 60_000 })),
+ },
+ clientIp: () => '127.0.0.1',
+}));
+vi.mock('../api/_lib/premium.js', () => ({
+ verifyPassPayment: vi.fn(async () => ({ ok: false, pending: true, reason: 'still confirming' })),
+ activatePass: vi.fn(async () => ({ pass: { id: 'pass-1' }, apiKey: null, renewed: false })),
+}));
+vi.mock('../api/_lib/x402/api-keys.js', () => ({
+ createSubscription: vi.fn(async (opts) => {
+ keyLane.order.push('mint');
+ if (keyLane.mintFails) throw new Error('key mint unavailable');
+ return { id: 'sub_freshkey02', name: opts.name, key_prefix: 'x402_live_FRESH', token: 'x402_live_freshplaintext' };
+ }),
+ revokeSubscription: vi.fn(async () => {
+ keyLane.order.push('revoke');
+ return { id: KEY_ID };
+ }),
+}));
+
+const { default: subscribeHandler } = await import('../api/premium/subscribe.js');
+const { default: keysHandler } = await import('../api/premium/keys.js');
+
+function makeReq(url, body) {
+ return {
+ method: 'POST',
+ url,
+ headers: { origin: 'https://three.ws', 'content-type': 'application/json' },
+ body,
+ socket: { remoteAddress: '127.0.0.1' },
+ };
+}
+function makeRes() {
+ const r = { statusCode: 200, _h: {}, _b: null };
+ r.setHeader = (k, v) => { r._h[k] = v; };
+ r.getHeader = (k) => r._h[k];
+ r.end = (b) => { r._b = b; };
+ Object.defineProperty(r, '_s', { get() { return this.statusCode; } });
+ Object.defineProperty(r, 'json', { value: () => JSON.parse(r._b) });
+ return r;
+}
+async function call(handler, url, body) {
+ const res = makeRes();
+ await handler(makeReq(url, body), res);
+ return res;
+}
+
+beforeEach(() => {
+ db.handlers = [];
+ db.calls = [];
+ keyLane.order = [];
+ keyLane.mintFails = false;
+ vi.clearAllMocks();
+});
+
+describe('POST /api/premium/subscribe: quote_id shape', () => {
+ it('answers 400 on a non-uuid quote_id without querying the quote table', async () => {
+ const r = await call(subscribeHandler, '/api/premium/subscribe', {
+ quote_id: 'not-a-uuid',
+ tx_signature: TX_SIG,
+ });
+ expect(r._s).toBe(400);
+ expect(r.json().error).toBe('bad_quote');
+ expect(db.calls.some((c) => /premium_quotes/.test(c.text))).toBe(false);
+ });
+
+ it('still reaches the lookup for a well-formed quote_id it has never seen', async () => {
+ const r = await call(subscribeHandler, '/api/premium/subscribe', {
+ quote_id: QUOTE_ID,
+ tx_signature: TX_SIG,
+ });
+ expect(r._s).toBe(404);
+ expect(r.json().error).toBe('quote_not_found');
+ expect(db.calls.some((c) => /premium_quotes/.test(c.text))).toBe(true);
+ });
+});
+
+describe('POST /api/premium/keys: rotate ordering', () => {
+ const premiumKeyRow = {
+ id: KEY_ID,
+ name: 'three.ws Developer pass',
+ rate_limit_per_minute: 120,
+ expires_at: '2026-09-13T00:00:00.000Z',
+ revoked_at: null,
+ meta: { source: 'premium-pass', plan: 'developer', user_id: USER.id, wallet: 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump' },
+ };
+
+ beforeEach(() => {
+ db.handlers = [{ match: /from x402_subscriptions/, result: () => [premiumKeyRow] }];
+ });
+
+ it('mints the replacement before revoking the old credential', async () => {
+ const r = await call(keysHandler, '/api/premium/keys', { action: 'rotate', id: KEY_ID });
+ expect(r._s).toBe(200);
+ expect(r.json()).toMatchObject({ rotated: true, id: 'sub_freshkey02', api_key: 'x402_live_freshplaintext' });
+ expect(keyLane.order).toEqual(['mint', 'revoke']);
+ const repoint = db.calls.find((c) => /update premium_passes/.test(c.text));
+ expect(repoint.values).toEqual(['sub_freshkey02', KEY_ID]);
+ });
+
+ it('leaves the paid key usable when the replacement cannot be minted', async () => {
+ keyLane.mintFails = true;
+ const r = await call(keysHandler, '/api/premium/keys', { action: 'rotate', id: KEY_ID });
+ expect(r._s).toBe(500);
+ expect(keyLane.order).toEqual(['mint']);
+ expect(db.calls.some((c) => /update premium_passes/.test(c.text))).toBe(false);
+ });
+
+ it('rejects a key that belongs to another account', async () => {
+ db.handlers = [
+ { match: /from x402_subscriptions/, result: () => [{ ...premiumKeyRow, meta: { source: 'premium-pass', user_id: 'someone-else' } }] },
+ ];
+ const r = await call(keysHandler, '/api/premium/keys', { action: 'rotate', id: KEY_ID });
+ expect(r._s).toBe(404);
+ expect(r.json().error).toBe('key_not_found');
+ expect(keyLane.order).toEqual([]);
+ });
+});