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
fix(x402): canonicalize payment proofs for replay checks, verify ring signatures, and scope Premium pass keys
nirholas182f51e51233
diff --git a/api/_lib/x402-paid-endpoint.js b/api/_lib/x402-paid-endpoint.jsindex 30f5b099c..ab1ef5908 100644--- a/api/_lib/x402-paid-endpoint.js+++ b/api/_lib/x402-paid-endpoint.js@@ -59,6 +59,7 @@ import {enforceRequired,extractIdFromHeader,hashPaymentProof,+ legacyPaymentProofHash,hashRequestPayload,paymentIdentifierExtension,reserveSlot,@@ -952,7 +953,9 @@ export function paidEndpoint(spec) {// OPEN on a DB outage — see api/_lib/x402/spent-payments.js for why this// control's failure policy is the inverse of settle-credit's.if (paymentHash) {- const spent = await isPaymentSpent(paymentHash);+ let spent = await isPaymentSpent(paymentHash);+ const legacyHash = legacyPaymentProofHash(paymentHeader);+ if (!spent.spent && legacyHash && legacyHash !== paymentHash) spent = await isPaymentSpent(legacyHash);if (spent.spent) {logPaymentEvent({eventType: 'payment_replay_rejected',diff --git a/api/_lib/x402/access-control.js b/api/_lib/x402/access-control.jsindex 99194c935..d46a6da78 100644--- a/api/_lib/x402/access-control.js+++ b/api/_lib/x402/access-control.js@@ -31,6 +31,20 @@ import {const API_KEY_HEADER = 'x-api-key';+// Routes a self-serve Premium pass key covers (docs/premium.md: the Data API).+// A pass is sold for archive search; before this list its key bypassed payment+// on EVERY paid route, so a $19.99 pass launched coins on the platform's SOL,+// burned GPU pipelines and vanity grinds for free. Partner and marketplace keys+// are issued by an operator for whatever they were sold and keep full scope.+// Extend this list when a new surface joins the pass.+export const PREMIUM_PASS_ROUTES = Object.freeze(['/api/news/archive']);++export function subscriptionCoversRoute(sub, route) {+ if (sub?.meta?.source !== 'premium-pass') return true;+ const path = String(route || '').split('?')[0];+ return PREMIUM_PASS_ROUTES.includes(path);+}+/*** Build an `accessControl` hook for `paidEndpoint(spec)`. Returns an async* function `(req, routeConfig) => result` matching the v2 `onProtectedRequest`@@ -147,6 +161,17 @@ export function installAccessControl({ requiredScope, resolveCaller } = {}) {});return { abort: true, status: 403, reason: 'AWS Marketplace subscription inactive' };}+ if (!subscriptionCoversRoute(sub, route)) {+ logAccess({+ callerId: `abort:pass_scope:${sub.id}`,+ route,+ reason: 'Premium pass does not cover this route',+ granted: false,+ meta,+ });+ // Not an auth failure: fall through to the 402 so the caller can pay.+ return null;+ }const rl = await checkRateLimit(sub, route);if (!rl.allowed) {logAccess({diff --git a/api/_lib/x402/idempotency-cache.js b/api/_lib/x402/idempotency-cache.jsindex 242d89478..d8c604b43 100644--- a/api/_lib/x402/idempotency-cache.js+++ b/api/_lib/x402/idempotency-cache.js@@ -88,11 +88,65 @@ export function hashRequestPayload({ method, url, body }) {// merely learned or guessed the id, but holds a different/forged payment,// hashes differently and is denied the cached body. Returns null when there's// no header to hash.+//+// The hash is taken over the payment's CANONICAL identity, not the header's+// bytes. Hashing the raw string let a replay strip the base64 padding, switch+// to the URL-safe alphabet, or reflow the JSON: the decoded payment was+// identical, the hash was not, and every replay guard keyed on it (this cache,+// isPaymentSpent, claimSpentPayment) missed, so one settled payment unlocked the+// good again and again.export function hashPaymentProof(paymentHeader) {+ if (!paymentHeader) return null;+ const canonical = canonicalPaymentIdentity(paymentHeader);+ return createHash('sha256').update(canonical ?? String(paymentHeader).trim()).digest('hex');+}++function decodeHeaderJson(header) {+ const raw = String(header).trim();+ if (raw.startsWith('{')) {+ try { return JSON.parse(raw); } catch { return null; }+ }+ const b64 = raw.replace(/-/g, '+').replace(/_/g, '/').replace(/\s+/g, '');+ try {+ return JSON.parse(Buffer.from(b64, 'base64').toString('utf8'));+ } catch {+ return null;+ }+}++// Sorted-key JSON, so key order and whitespace never change the identity. A+// signed Solana transaction is reduced to its bytes (hex), so re-encoding the+// inner base64 does not either.+function canonicalValue(value, key) {+ if (key === 'transaction' && typeof value === 'string') {+ const bytes = Buffer.from(value.replace(/-/g, '+').replace(/_/g, '/').replace(/\s+/g, ''), 'base64');+ if (bytes.length) return `tx:${bytes.toString('hex')}`;+ }+ if (Array.isArray(value)) return value.map((v) => canonicalValue(v));+ if (value && typeof value === 'object') {+ const out = {};+ for (const k of Object.keys(value).sort()) out[k] = canonicalValue(value[k], k);+ return out;+ }+ if (typeof value === 'string' && /^0x[0-9a-fA-F]+$/.test(value)) return value.toLowerCase();+ return value;+}++// The pre-canonical hash (raw header bytes). Payments recorded spent before the+// canonical hash shipped are keyed on this, so the spent check reads both until+// those rows age out.+export function legacyPaymentProofHash(paymentHeader) {if (!paymentHeader) return null;return createHash('sha256').update(String(paymentHeader)).digest('hex');}+export function canonicalPaymentIdentity(paymentHeader) {+ const decoded = decodeHeaderJson(paymentHeader);+ const payload = decoded && typeof decoded === 'object' ? decoded.payload : null;+ if (!payload || typeof payload !== 'object') return null;+ return JSON.stringify(canonicalValue(payload));+}+// Read a cached response by route + paymentId. Returns null if the key is// missing or expired. The returned shape is whatever `set()` was given.export async function get(route, paymentId) {diff --git a/api/_lib/x402/payment-identifier-server.js b/api/_lib/x402/payment-identifier-server.jsindex aa6f9ada7..963c5956b 100644--- a/api/_lib/x402/payment-identifier-server.js+++ b/api/_lib/x402/payment-identifier-server.js@@ -318,5 +318,5 @@ export function writeInflight(res) {);}-export { hashRequestPayload, hashPaymentProof } from './idempotency-cache.js';+export { hashRequestPayload, hashPaymentProof, legacyPaymentProofHash } from './idempotency-cache.js';export const ttlSeconds = envTtl;diff --git a/api/_lib/x402/self-facilitator.js b/api/_lib/x402/self-facilitator.jsindex a11e62248..efd7c4b95 100644--- a/api/_lib/x402/self-facilitator.js+++ b/api/_lib/x402/self-facilitator.js@@ -23,6 +23,7 @@// drained".import bs58 from 'bs58';+import { ed25519 } from '@noble/curves/ed25519.js';import { PublicKey, Keypair, VersionedTransaction } from '@solana/web3.js';import {getAssociatedTokenAddressSync,@@ -447,6 +448,67 @@ export function validateRingTransaction({ txBase64, requirement, feePayerPubkey,};}+// Check every buyer signature on a decoded ring transaction against its message.+//+// validateRingTransaction proves the authority is LISTED as a signer and the+// settleability simulation runs with sigVerify:false (the sponsor has not+// co-signed yet), so nothing on the verify path ever checked a signature. A+// transfer naming any funded wallet as authority, carrying garbage signatures,+// therefore verified as valid and the paid handler ran (a coin launch on the+// platform's SOL, a cosmetic grant and creator payout, a GPU job) before settle+// failed. In sponsor mode the fee-payer slot is skipped: the sponsor signs only+// at settle.+export function verifyBuyerSignatures({ tx, feePayer, selfPay }) {+ const msg = tx.message;+ const required = msg.header.numRequiredSignatures;+ let bytes;+ try {+ bytes = msg.serialize();+ } catch (err) {+ return { ok: false, reason: `message_unserializable:${err?.message || err}` };+ }+ for (let i = 0; i < required; i += 1) {+ const key = msg.staticAccountKeys[i];+ if (!key) return { ok: false, reason: 'missing_signer_key' };+ const b58 = key.toBase58();+ if (!selfPay && b58 === feePayer) continue;+ const sig = tx.signatures?.[i];+ if (!sig || sig.length !== 64 || sig.every((b) => b === 0)) {+ return { ok: false, reason: `missing_signature:${b58}` };+ }+ let ok = false;+ try {+ ok = ed25519.verify(sig, bytes, key.toBytes());+ } catch {+ ok = false;+ }+ if (!ok) return { ok: false, reason: `invalid_signature:${b58}` };+ }+ return { ok: true };+}++// Is the transaction's recent blockhash still live? Returns true, false, or null+// when the RPC cannot say. A node a few slots behind the buyer's may not know a+// brand-new hash yet, so a `false` is re-asked once after a short pause before it+// is believed. A dead or made-up blockhash can never land, and the settle path+// would otherwise answer it `pending`, which the resource server delivers on.+export async function blockhashIsLive(connection, blockhash, { recheckMs = 1500 } = {}) {+ if (typeof connection?.isBlockhashValid !== 'function' || !blockhash) return null;+ const ask = async () => {+ try {+ const r = await connection.isBlockhashValid(blockhash, { commitment: 'processed' });+ const v = r && typeof r === 'object' && 'value' in r ? r.value : r;+ return typeof v === 'boolean' ? v : null;+ } catch {+ return null;+ }+ };+ const first = await ask();+ if (first !== false) return first;+ if (recheckMs > 0) await new Promise((r) => setTimeout(r, recheckMs));+ return ask();+}+// Extract the base64 signed transaction from an x402 payment payload.export function txBase64FromPayload(paymentPayload) {return (@@ -768,6 +830,8 @@ export async function settleRingPayment({if (!validation.ok) return { success: false, reason: validation.reason };const decoded = validation.decoded;const { tx, payer, estFeeLamports, selfPay } = decoded;+ const sigCheck = verifyBuyerSignatures(decoded);+ if (!sigCheck.ok) return { success: false, reason: sigCheck.reason };// Metadata every pending record and reconcile pass needs, assembled once.const pendingKey = pendingSettlementKey(txBase64);@@ -916,6 +980,7 @@ export async function settleRingPayment({// the reported reason distinguishes "our read node was stale" from "the payment// was genuinely unsendable".let preflightRetryNote = '';+ let preflightBlockhashRejected = false;try {signature = await connection.sendRawTransaction(tx.serialize(), {skipPreflight: false,@@ -995,6 +1060,7 @@ export async function settleRingPayment({// only cost is the confirm wait below. Resending the identical signed bytes is// idempotent (Solana dedupes by signature), so this cannot double-settle.if (provablyNeverLanded) {+ preflightBlockhashRejected = true;try {signature = await connection.sendRawTransaction(tx.serialize(), {skipPreflight: true,@@ -1062,6 +1128,17 @@ export async function settleRingPayment({if (pendingStore && pendingKey) await pendingStore.delete(pendingKey);return { success: false, reason: `not_confirmed:${conf.err}`, transaction: signature };}+ // A send our node rejected as "blockhash not found" and that still has not+ // landed is pending only if that blockhash can still be included. A dead+ // or made-up hash never lands, and answering pending would deliver the paid+ // good for a payment that can never settle, as often as the buyer likes.+ if (preflightBlockhashRejected) {+ const live = await blockhashIsLive(connection, tx.message.recentBlockhash, { recheckMs: 0 });+ if (live === false) {+ if (pendingStore && pendingKey) await pendingStore.delete(pendingKey);+ return { success: false, reason: 'blockhash_expired', transaction: signature };+ }+ }// Outcome unknown. The transaction is broadcast and may land at any moment,// so reporting failure here would tell a buyer who is about to be charged// that they were not. Record the signature and answer `settlement_pending`;@@ -1230,6 +1307,14 @@ export async function verifyRingPayment({ paymentPayload, requirement, feePayerP});if (!validation.ok) return { isValid: false, invalidReason: validation.reason };+ const sigCheck = verifyBuyerSignatures(validation.decoded);+ if (!sigCheck.ok) return { isValid: false, invalidReason: sigCheck.reason };+ // The settleability simulation swaps in a fresh blockhash, so it cannot see a+ // dead one. Refuse it here, before the paid handler runs.+ if ((await blockhashIsLive(connection, validation.decoded.tx.message.recentBlockhash)) === false) {+ return { isValid: false, invalidReason: 'blockhash_expired' };+ }+const settleable = await assertSettleable({tx: validation.decoded.tx,connection,diff --git a/tests/x402-payment-proof-canonical.test.js b/tests/x402-payment-proof-canonical.test.jsnew file mode 100644index 000000000..ecea82efb--- /dev/null+++ b/tests/x402-payment-proof-canonical.test.js@@ -0,0 +1,48 @@+// One settled x402 payment has one identity, however its header is encoded.+//+// The replay guards (idempotency cache, isPaymentSpent, claimSpentPayment) were+// keyed on SHA-256 of the raw X-PAYMENT string, so stripping base64 padding,+// switching to the URL-safe alphabet or reflowing the JSON produced a "new"+// payment and the same settled transaction unlocked the good again.++import { describe, it, expect } from 'vitest';+import { hashPaymentProof, legacyPaymentProofHash } from '../api/_lib/x402/idempotency-cache.js';++const TX = Buffer.from('signed-solana-transaction-bytes-for-test').toString('base64');+const payment = { x402Version: 2, accepted: { network: 'solana:mainnet', amount: '10000' }, payload: { transaction: TX } };++function std(obj) { return Buffer.from(JSON.stringify(obj)).toString('base64'); }++describe('hashPaymentProof', () => {+ it('is stable across base64 padding, alphabet and JSON layout', () => {+ const a = std(payment);+ const unpadded = a.replace(/=+$/, '');+ const urlSafe = a.replace(/\+/g, '-').replace(/\//g, '_');+ const reflowed = Buffer.from(JSON.stringify(payment, null, 2)).toString('base64');+ const reordered = std({ payload: { transaction: TX }, accepted: payment.accepted, x402Version: 2 });+ const innerUnpadded = std({ ...payment, payload: { transaction: TX.replace(/=+$/, '') } });+ const h = hashPaymentProof(a);+ for (const v of [unpadded, urlSafe, reflowed, reordered, innerUnpadded]) expect(hashPaymentProof(v)).toBe(h);+ });++ it('binds to the payment, not the route it is presented to', () => {+ const other = std({ ...payment, accepted: { network: 'solana:mainnet', amount: '5000' }, resource: { url: '/api/x402/other' } });+ expect(hashPaymentProof(other)).toBe(hashPaymentProof(std(payment)));+ });++ it('distinguishes different payments', () => {+ const diff = std({ ...payment, payload: { transaction: Buffer.from('another-transaction').toString('base64') } });+ expect(hashPaymentProof(diff)).not.toBe(hashPaymentProof(std(payment)));+ });++ it('canonicalizes EVM hex case', () => {+ const evm = (nonce) => std({ x402Version: 2, payload: { signature: '0xABCD', authorization: { from: '0xAAaa', nonce } } });+ expect(hashPaymentProof(evm('0xFF01'))).toBe(hashPaymentProof(evm('0xff01')));+ });++ it('keeps the legacy raw-bytes hash available for the transition', () => {+ const a = std(payment);+ expect(legacyPaymentProofHash(a)).toMatch(/^[0-9a-f]{64}$/);+ expect(hashPaymentProof('not-a-payment')).toMatch(/^[0-9a-f]{64}$/);+ });+});diff --git a/tests/x402-premium-pass-scope.test.js b/tests/x402-premium-pass-scope.test.jsnew file mode 100644index 000000000..7ca425598--- /dev/null+++ b/tests/x402-premium-pass-scope.test.js@@ -0,0 +1,55 @@+// A self-serve Premium pass key only bypasses payment on the routes the pass is+// sold for. Before this gate any active x402_subscriptions key, including a+// $19.99 archive-search pass, skipped the 402 on every paid route, so the pass+// launched coins on the platform's SOL and ran GPU pipelines for free.++import { describe, it, expect, vi, beforeEach } from 'vitest';++let sub = null;+const logAccess = vi.fn();+vi.mock('../api/_lib/x402/api-keys.js', () => ({+ lookupSubscription: vi.fn(async () => sub),+ checkRateLimit: vi.fn(async () => ({ allowed: true, remaining: 10, limit: 120, resetAt: Date.now() + 60_000 })),+ logAccess: (...a) => logAccess(...a),+}));+vi.mock('../api/_lib/aws-marketplace-bridge.js', () => ({+ isAwsCustomerInactive: vi.fn(async () => false),+ meterAwsSubscriptionUsage: vi.fn(),+}));+vi.mock('../api/_lib/auth.js', () => ({+ authenticateBearer: vi.fn(async () => null),+ extractBearer: vi.fn(() => null),+ hasScope: vi.fn(() => false),+}));+vi.mock('../api/_lib/rate-limit.js', () => ({ clientIp: () => '127.0.0.1' }));++const { installAccessControl, subscriptionCoversRoute } = await import('../api/_lib/x402/access-control.js');++const req = { headers: { 'x-api-key': 'x402_live_abcdef' } };+const hook = installAccessControl({ requiredScope: 'x402:bypass' });++beforeEach(() => { logAccess.mockClear(); });++describe('premium pass key scope', () => {+ it('grants the archive route it is sold for', async () => {+ sub = { id: 's1', name: 'pass', meta: { source: 'premium-pass' } };+ const r = await hook(req, { path: '/api/news/archive' });+ expect(r?.grantAccess).toBe(true);+ });++ it('does not bypass payment on any other paid route; the caller gets the 402', async () => {+ sub = { id: 's1', name: 'pass', meta: { source: 'premium-pass' } };+ for (const path of ['/api/x402/pump-launch', '/api/x402/vanity', '/api/x402/pipeline', '/api/x402/llm-proxy']) {+ const r = await hook(req, { path });+ expect(r, path).toBeNull();+ }+ expect(logAccess).toHaveBeenCalledWith(expect.objectContaining({ granted: false, reason: 'Premium pass does not cover this route' }));+ });++ it('leaves operator-issued partner keys at full scope', async () => {+ sub = { id: 'p1', name: 'Partner', meta: { source: 'admin' } };+ const r = await hook(req, { path: '/api/x402/pipeline' });+ expect(r?.grantAccess).toBe(true);+ expect(subscriptionCoversRoute({ meta: null }, '/api/x402/anything')).toBe(true);+ });+});diff --git a/tests/x402-self-facilitator-signatures.test.js b/tests/x402-self-facilitator-signatures.test.jsnew file mode 100644index 000000000..d33dc6e66--- /dev/null+++ b/tests/x402-self-facilitator-signatures.test.js@@ -0,0 +1,84 @@+// The self-hosted Solana facilitator checks buyer signatures and blockhash+// liveness before /verify answers valid.+//+// verify used to prove only that the authority was LISTED as a signer and then+// simulate with sigVerify:false and a replaced blockhash, so:+// - a transfer naming any funded wallet, with garbage signatures, verified as+// valid and the paid handler ran before settle failed;+// - a transfer signed against a dead blockhash verified, then settle resent it+// with preflight off, timed out, and answered `pending`, which the resource+// server delivers on. The buyer never paid and could repeat it forever.++import { describe, it, expect } from 'vitest';+import { Keypair, TransactionMessage, VersionedTransaction, SystemProgram } from '@solana/web3.js';+import { verifyBuyerSignatures, blockhashIsLive } from '../api/_lib/x402/self-facilitator.js';++const BLOCKHASH = '11111111111111111111111111111111';++function txSignedBy(payerKp, signer = payerKp, feePayer = payerKp.publicKey) {+ const ix = SystemProgram.transfer({ fromPubkey: payerKp.publicKey, toPubkey: Keypair.generate().publicKey, lamports: 1 });+ const msg = new TransactionMessage({ payerKey: feePayer, recentBlockhash: BLOCKHASH, instructions: [ix] }).compileToV0Message();+ const tx = new VersionedTransaction(msg);+ if (signer) tx.sign([signer]);+ return tx;+}++describe('verifyBuyerSignatures', () => {+ it('accepts a self-pay transaction the buyer really signed', () => {+ const buyer = Keypair.generate();+ const tx = txSignedBy(buyer);+ expect(verifyBuyerSignatures({ tx, feePayer: buyer.publicKey.toBase58(), selfPay: true })).toEqual({ ok: true });+ });++ it('refuses a transaction signed by a different key than the listed authority', () => {+ const victim = Keypair.generate();+ const attacker = Keypair.generate();+ const tx = txSignedBy(victim, null);+ tx.signatures[0] = attacker.secretKey.slice(0, 64);+ const r = verifyBuyerSignatures({ tx, feePayer: victim.publicKey.toBase58(), selfPay: true });+ expect(r.ok).toBe(false);+ expect(r.reason).toMatch(/^invalid_signature:/);+ });++ it('refuses an unsigned (all-zero) buyer slot', () => {+ const buyer = Keypair.generate();+ const tx = txSignedBy(buyer, null);+ const r = verifyBuyerSignatures({ tx, feePayer: buyer.publicKey.toBase58(), selfPay: true });+ expect(r).toEqual({ ok: false, reason: `missing_signature:${buyer.publicKey.toBase58()}` });+ });++ it('skips only the sponsor slot in sponsor mode, and still checks the buyer', () => {+ const buyer = Keypair.generate();+ const sponsor = Keypair.generate();+ const ix = SystemProgram.transfer({ fromPubkey: buyer.publicKey, toPubkey: Keypair.generate().publicKey, lamports: 1 });+ const msg = new TransactionMessage({ payerKey: sponsor.publicKey, recentBlockhash: BLOCKHASH, instructions: [ix] }).compileToV0Message();+ const signed = new VersionedTransaction(msg);+ signed.sign([buyer]);+ expect(verifyBuyerSignatures({ tx: signed, feePayer: sponsor.publicKey.toBase58(), selfPay: false })).toEqual({ ok: true });++ const forged = new VersionedTransaction(msg);+ const r = verifyBuyerSignatures({ tx: forged, feePayer: sponsor.publicKey.toBase58(), selfPay: false });+ expect(r).toEqual({ ok: false, reason: `missing_signature:${buyer.publicKey.toBase58()}` });+ });+});++describe('blockhashIsLive', () => {+ it('reports a live blockhash', async () => {+ const conn = { isBlockhashValid: async () => ({ value: true }) };+ expect(await blockhashIsLive(conn, BLOCKHASH, { recheckMs: 0 })).toBe(true);+ });++ it('re-asks once before believing a dead blockhash', async () => {+ let calls = 0;+ const conn = { isBlockhashValid: async () => { calls += 1; return { value: calls > 1 }; } };+ expect(await blockhashIsLive(conn, BLOCKHASH, { recheckMs: 1 })).toBe(true);+ const dead = { isBlockhashValid: async () => ({ value: false }) };+ expect(await blockhashIsLive(dead, BLOCKHASH, { recheckMs: 1 })).toBe(false);+ });++ it('answers unknown (null) when the RPC cannot say, so an outage never fails a payment on its own', async () => {+ const down = { isBlockhashValid: async () => { throw new Error('rpc down'); } };+ expect(await blockhashIsLive(down, BLOCKHASH, { recheckMs: 0 })).toBeNull();+ expect(await blockhashIsLive({}, BLOCKHASH)).toBeNull();+ });+});