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.

feat(skills): serve one priced skill on x402, MPP, A2A and AP2 with one split and one receipt

nirholas8d56cd92cc6f
diff --git a/api/_lib/skill-rails.js b/api/_lib/skill-rails.js
index 7eaa15234..e315c17e8 100644
--- a/api/_lib/skill-rails.js
+++ b/api/_lib/skill-rails.js
@@ -16,8 +16,6 @@
// identical whichever rail carried the call. This module is the pure policy
// (rail names, quote, endpoint map, MPP framing) plus that one writer.
-import { createHmac, timingSafeEqual } from 'node:crypto';
-
import { sql } from './db.js';
import { env } from './env.js';
import { priceFor } from './x402-prices.js';
@@ -166,92 +164,15 @@ export function detectRail(req, body) {
}
// ── MPP framing ──────────────────────────────────────────────────────────────
-
-const MPP_REALM = 'three.ws';
-const MPP_CHALLENGE_TTL_SECONDS = 300;
-
-const b64url = (buf) => Buffer.from(buf).toString('base64url');
-
-function mppSecret() {
- return env.A2A_MANDATE_SECRET;
-}
-
-function mppChallengeId({ request, expires }) {
- return b64url(
- createHmac('sha256', mppSecret()).update(`${MPP_REALM}|solana|charge|${request}|${expires}`).digest(),
- );
-}
-
-/**
- * Build the MPP challenge for a skill: a stateless, HMAC-bound `Payment` challenge
- * whose request carries the exact Solana USDC charge (amount, recipient, asset,
- * resource). Nothing is stored server-side; the id proves we issued these terms.
- * @param {{ requirement: object, resourceUrl: string, description: string, nowSec?: number }} args
- */
-export function buildMppChallenge({ requirement, resourceUrl, description, nowSec = Math.floor(Date.now() / 1000) }) {
- const expires = nowSec + MPP_CHALLENGE_TTL_SECONDS;
- const request = b64url(
- JSON.stringify({
- amount: String(requirement.amount),
- currency: requirement.asset,
- recipient: requirement.payTo,
- network: requirement.network,
- resource: resourceUrl,
- description,
- scheme: requirement.scheme,
- extra: requirement.extra ?? {},
- }),
- );
- const id = mppChallengeId({ request, expires });
- const header =
- `Payment id="${id}", realm="${MPP_REALM}", method="solana", intent="charge", ` +
- `request="${request}", expires="${expires}"`;
- return { id, request, expires, header };
-}
-
-/**
- * Parse and authenticate an `Authorization: Payment <b64url JSON>` credential. The
- * credential echoes the challenge (id, request, expires) beside the payment payload;
- * the id must be the HMAC of exactly those terms and still inside its lifetime.
- * @returns {{ ok: true, payload: object, request: object } | { ok: false, code: string, message: string }}
- */
-export function parseMppCredential(authorization, { nowSec = Math.floor(Date.now() / 1000) } = {}) {
- const m = /^\s*payment\s+(\S+)\s*$/i.exec(String(authorization || ''));
- if (!m) return { ok: false, code: 'invalid_credential', message: 'Authorization must be "Payment <credential>"' };
- let cred;
- try {
- cred = JSON.parse(Buffer.from(m[1], 'base64url').toString('utf8'));
- } catch {
- return { ok: false, code: 'invalid_credential', message: 'credential is not base64url JSON' };
- }
- const ch = cred?.challenge;
- if (!ch || typeof ch.id !== 'string' || typeof ch.request !== 'string' || !cred.payload || typeof cred.payload !== 'object') {
- return { ok: false, code: 'invalid_credential', message: 'credential needs { challenge: {id, request, expires}, payload }' };
- }
- const expires = Number(ch.expires);
- if (!Number.isFinite(expires) || nowSec >= expires) {
- return { ok: false, code: 'challenge_expired', message: 'the payment challenge has expired, request a new one' };
- }
- const want = Buffer.from(mppChallengeId({ request: ch.request, expires }));
- const got = Buffer.from(ch.id);
- if (want.length !== got.length || !timingSafeEqual(want, got)) {
- return { ok: false, code: 'challenge_mismatch', message: 'credential does not match a challenge issued by this server' };
- }
- let request;
- try {
- request = JSON.parse(Buffer.from(ch.request, 'base64url').toString('utf8'));
- } catch {
- return { ok: false, code: 'invalid_credential', message: 'challenge request is not base64url JSON' };
- }
- return { ok: true, payload: cred.payload, request };
-}
-
-/** The MPP `Payment-Receipt` header value for a settled charge. */
-export function mppReceiptHeader({ transaction, network, payer, nowSec = Math.floor(Date.now() / 1000) }) {
- return b64url(
- JSON.stringify({ status: 'success', method: 'solana', reference: transaction, network, payer, timestamp: nowSec }),
- );
-}
+// The wire format (spec-shaped Solana charge challenge, credential and receipt)
+// lives in mpp-solana.js so the skill rail, paid endpoints, the agent payer and
+// the CLI all speak the same bytes. These aliases keep the rail module's API.
+
+export {
+ buildSolanaChargeChallenge as buildMppChallenge,
+ parseSolanaChargeCredential as parseMppCredential,
+ solanaChargeReceiptHeader as mppReceiptHeader,
+} from './mpp-solana.js';
/** x402 payment header (base64 JSON) from a decoded payment payload. */
export function encodePaymentHeader(payload) {
diff --git a/api/skills/[id]/invoke.js b/api/skills/[id]/invoke.js
index 6e1df6dc6..9ed9154e5 100644
--- a/api/skills/[id]/invoke.js
+++ b/api/skills/[id]/invoke.js
@@ -53,6 +53,7 @@ import {
skillDelivery,
splitSummary,
} from '../../_lib/skill-rails.js';
+import { chargeMatchesRequirement, chargeToX402Payment } from '../../_lib/mpp-solana.js';
import { isSolanaNetwork } from '../../_lib/x402/a2a-client.js';
const DESCRIPTION_SUFFIX = 'paid per call in USDC, settled to the skill author';
@@ -186,7 +187,7 @@ function mppRequirement(requirements) {
}
function sendMppChallenge(res, skill, quote, requirement, errText) {
- const challenge = buildMppChallenge({ requirement, resourceUrl: quote.resourceUrl, description: describe(skill) });
+ const challenge = buildMppChallenge({ requirement, description: describe(skill) });
return sendJson(
res,
402,
@@ -217,12 +218,7 @@ async function handleMpp(req, res, skill, quote) {
? sendMppChallenge(res, skill, quote, requirement, parsed.message)
: error(res, status, parsed.code, parsed.message);
}
- const charge = parsed.request;
- if (
- charge.resource !== quote.resourceUrl ||
- String(charge.amount) !== String(requirement.amount) ||
- charge.recipient !== requirement.payTo
- ) {
+ if (!chargeMatchesRequirement(parsed.request, requirement)) {
return sendMppChallenge(res, skill, quote, requirement, 'the skill price or payout changed since this challenge, retry with a fresh one');
}
try {
@@ -231,7 +227,7 @@ async function handleMpp(req, res, skill, quote) {
quote,
rail: 'mpp',
requirements: [requirement],
- paymentHeader: encodePaymentHeader(parsed.payload),
+ paymentHeader: encodePaymentHeader(chargeToX402Payment({ requirement, transaction: parsed.transaction })),
});
return sendJson(res, 200, skillDelivery(skill), {
'payment-receipt': mppReceiptHeader({ transaction: settled.transaction, network: settled.network, payer }),
@@ -433,7 +429,7 @@ async function dryRun(res, rail, skill, quote) {
} else if (rail === 'mpp') {
const requirement = mppRequirement(requirements);
if (!requirement) return error(res, 501, 'mpp_unavailable', 'no Solana payout is configured for this skill');
- const c = buildMppChallenge({ requirement, resourceUrl: quote.resourceUrl, description: describe(skill) });
+ const c = buildMppChallenge({ requirement, description: describe(skill) });
challenge = { 'WWW-Authenticate': c.header };
} else if (rail === 'a2a') {
const { task } = buildPaymentRequiredTask({
diff --git a/docs/skill-rails.md b/docs/skill-rails.md
new file mode 100644
index 000000000..af30531a9
--- /dev/null
+++ b/docs/skill-rails.md
@@ -0,0 +1,41 @@
+# One paid skill, four rails
+
+A priced marketplace skill is defined once and served over every payment rail its author enables. Callers pick the rail; the price, the author and platform split and the receipt are the same on all of them.
+
+| Rail | How a caller reaches it | Settles as |
+|---|---|---|
+| `x402` | Plain `GET`/`POST /api/skills/:id/invoke`, pay with `X-PAYMENT` | x402 `exact` on Solana (Base when the author set a Base payout) |
+| `mpp` | `x-payment-rail: mpp` (or `?rail=mpp`), pay with `Authorization: Payment` ([MPP on Solana](./mpp-solana.md)) | the same Solana `exact` transaction |
+| `a2a` | JSON-RPC `message/send` with the `x402` extension | x402 `exact` through the A2A task flow |
+| `ap2` | Present an `x-ap2-mandate` and `x-ap2-cart` | a signed mandate debited against its spend ledger |
+
+`rails` defaults to `["x402","a2a"]`. The author toggles the rest in the publish flow on `/marketplace` (the rail checkboxes next to the price), or sends `rails` to `POST /api/skills`. A skill with a price and no rail enabled is refused at publish.
+
+## One quote
+
+`quoteSkill()` in [api/_lib/skill-rails.js](../api/_lib/skill-rails.js) turns the skill's per-call USD price into atomics and the author/platform split. Every rail calls it, so the dry run below prices each rail identically:
+
+```
+GET /api/skills/:id/invoke?dry_run=1&rail=<rail>
+```
+
+| rail | price_atomics | author_atomics | platform_atomics | platform_bps | currency |
+|---|---|---|---|---|---|
+| x402 | 10000 | 9750 | 250 | 250 | USDC |
+| mpp | 10000 | 9750 | 250 | 250 | USDC |
+| a2a | 10000 | 9750 | 250 | 250 | USDC |
+| ap2 | 10000 | 9750 | 250 | 250 | USDC |
+
+A dry run moves no funds and writes no receipt.
+
+## Agent card
+
+`GET /api/skills/:id/card` is the skill's A2A agent card. It lists each enabled rail with its endpoint and headers. A rail the author switched off is absent from the card and answers `404` on `invoke`.
+
+## Receipts
+
+Whatever the rail, a successful call runs the same `recordSkillInvocation()`: one `x402_receipts` row (tagged with the rail) and one royalty ledger accrual carrying the author/platform split.
+
+## Tests
+
+`npx vitest run tests/skill-rails.test.js` runs the router, mandate and cart signing, the spend ledger and royalty accrual for real against local counterparties; `tests/mpp-solana.test.js` covers the MPP wire format end to end.
diff --git a/tests/skill-rails.test.js b/tests/skill-rails.test.js
index 07aeea619..1c48272d9 100644
--- a/tests/skill-rails.test.js
+++ b/tests/skill-rails.test.js
@@ -9,11 +9,15 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { Readable } from 'node:stream';
+import { Challenge } from 'mppx';
+import { solanaChargeAuthorization } from '../api/_lib/mpp-solana.js';
const { state } = vi.hoisted(() => {
process.env.JWT_SECRET = 'skill-rails-test-secret-0123456789abcdef';
process.env.A2A_MANDATE_SECRET = 'skill-rails-mandate-secret-0123456789abcdef';
process.env.PUBLIC_APP_ORIGIN = 'https://three.test';
+ process.env.X402_FEE_PAYER_SOLANA = 'THREEsynthetic2222222222222222222222222222';
+ process.env.X402_ASSET_MINT_SOLANA = 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v';
return {
state: {
skill: null,
@@ -33,6 +37,7 @@ vi.mock('../api/_lib/db.js', () => {
state.inserts.push({ vals });
return Promise.resolve([{ id: `receipt-${state.inserts.length}` }]);
}
+ if (text.startsWith('insert into x402_spent_payments')) return Promise.resolve([{ payment_hash: String(vals[0]) }]);
if (text.startsWith('insert into royalty_ledger')) {
state.ledger.push({ vals });
return Promise.resolve([{ id: `ledger-${state.ledger.length}` }]);
@@ -127,19 +132,13 @@ async function call(handler, opts) {
return res;
}
+let proofSeq = 0;
const paymentHeader = (network = 'solana') =>
- Buffer.from(JSON.stringify({ x402Version: 2, network, payer: PAYER, scheme: 'exact' })).toString('base64');
-
-function mppAuthorization(res, { payer = PAYER } = {}) {
- const www = res.getHeader('www-authenticate');
- const id = /id="([^"]+)"/.exec(www)[1];
- const request = /request="([^"]+)"/.exec(www)[1];
- const expires = Number(/expires="([^"]+)"/.exec(www)[1]);
- const credential = {
- challenge: { id, request, expires },
- payload: { x402Version: 2, network: 'solana', payer, scheme: 'exact' },
- };
- return `Payment ${Buffer.from(JSON.stringify(credential)).toString('base64url')}`;
+ Buffer.from(JSON.stringify({ x402Version: 2, network, payer: PAYER, scheme: 'exact', nonce: ++proofSeq })).toString('base64');
+
+function mppAuthorization(res) {
+ const [challenge] = Challenge.fromHeadersList(new Headers({ 'www-authenticate': res.getHeader('www-authenticate') }));
+ return solanaChargeAuthorization({ challenge, transaction: 'dGVzdC10cmFuc2FjdGlvbg==', source: PAYER });
}
function a2aBody(metadata = {}) {
@@ -223,20 +222,22 @@ describe('challenges', () => {
expect(accepts[0].payTo).toBe(THREE_MINT);
});
- it('mpp: answers 402 with a Payment challenge bound to the quote', async () => {
+ it('mpp: answers 402 with a spec Payment challenge for a Solana charge', async () => {
const res = await call(invoke, { headers: { 'x-payment-rail': 'mpp' } });
expect(res.statusCode).toBe(402);
const www = res.getHeader('www-authenticate');
expect(www).toMatch(/^Payment id="/);
- const request = JSON.parse(Buffer.from(/request="([^"]+)"/.exec(www)[1], 'base64url').toString());
- expect(request.amount).toBe('10000');
- expect(request.recipient).toBe(THREE_MINT);
- expect(request.resource).toBe(`https://three.test/api/skills/${SKILL_ID}/invoke`);
+ const [challenge] = Challenge.fromHeadersList(new Headers({ 'www-authenticate': www }));
+ expect(challenge.method).toBe('solana');
+ expect(challenge.intent).toBe('charge');
+ expect(challenge.request.amount).toBe('10000');
+ expect(challenge.request.recipient).toBe(THREE_MINT);
+ expect(challenge.request.methodDetails.decimals).toBe(6);
});
it('a2a: a JSON-RPC call without payment gets a payment-required task', async () => {
const res = await call(invoke, { method: 'POST', headers: a2aHeaders, body: a2aBody() });
- expect(res.statusCode).toBe(200);
+ expect(res.statusCode, res._body).toBe(200);
const task = res.json.result;
expect(task.status.state).toBe('input-required');
expect(task.status.message.metadata['x402.payment.status']).toBe('payment-required');
@@ -341,12 +342,11 @@ describe('settlement writes one receipt shape on every rail', () => {
});
describe('mpp credentials', () => {
- it('rejects a credential whose challenge id was not issued here', async () => {
+ it('rejects a credential whose challenge terms were altered', async () => {
const challenge = await call(invoke, { headers: { 'x-payment-rail': 'mpp' } });
- const auth = mppAuthorization(challenge);
- const cred = JSON.parse(Buffer.from(auth.split(' ')[1], 'base64url').toString());
- cred.challenge.id = 'AAAA' + cred.challenge.id.slice(4);
- const forged = `Payment ${Buffer.from(JSON.stringify(cred)).toString('base64url')}`;
+ const [c] = Challenge.fromHeadersList(new Headers({ 'www-authenticate': challenge.getHeader('www-authenticate') }));
+ c.request = { ...c.request, amount: '1' };
+ const forged = solanaChargeAuthorization({ challenge: c, transaction: 'dGVzdA==' });
const res = await call(invoke, { headers: { authorization: forged } });
expect(res.statusCode).toBe(401);
expect(res.json.error).toBe('challenge_mismatch');
@@ -355,8 +355,8 @@ describe('mpp credentials', () => {
it('treats an expired challenge as payment required again', () => {
const requirement = { amount: '10000', asset: 'USDC', payTo: THREE_MINT, network: 'solana', scheme: 'exact' };
- const c = rails.buildMppChallenge({ requirement, resourceUrl: 'https://three.test/x', description: 'd', nowSec: 1000 });
- const auth = `Payment ${Buffer.from(JSON.stringify({ challenge: { id: c.id, request: c.request, expires: c.expires }, payload: { a: 1 } })).toString('base64url')}`;
+ const c = rails.buildMppChallenge({ requirement, description: 'd', nowSec: 1000 });
+ const auth = solanaChargeAuthorization({ challenge: c.challenge, transaction: 'dGVzdA==' });
expect(rails.parseMppCredential(auth, { nowSec: 1001 }).ok).toBe(true);
const late = rails.parseMppCredential(auth, { nowSec: c.expires + 1 });
expect(late.ok).toBe(false);