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(payments-sdk): bind pump-agent invoices to the resource server with an HMAC-tagged memo and reject closed windows before the on-chain check

nirholasc698e4b0f37f
diff --git a/agent-payments-sdk/src/solana/x402/facilitator.ts b/agent-payments-sdk/src/solana/x402/facilitator.ts
index 7c84e80ab..685f20528 100644
--- a/agent-payments-sdk/src/solana/x402/facilitator.ts
+++ b/agent-payments-sdk/src/solana/x402/facilitator.ts
@@ -15,6 +15,7 @@
* that returns 402s, verifies payment via a facilitator, and settles.
*/
+import { createHmac, randomBytes, timingSafeEqual } from "node:crypto";
import { PublicKey, Connection } from "@solana/web3.js";
import { PumpAgent } from "../PumpAgent";
import {
@@ -120,6 +121,78 @@ function generateMemo(): string {
return `${ts}${String(memoCounter).padStart(6, "0")}`;
}
+/**
+ * Server-bound invoice memos. The on-chain invoice id is client-visible, so
+ * without a binding any paid invoice for the same agent, asset and amount
+ * (another server's, or a stranger's) could be presented here and redeemed. With
+ * an `invoiceSecret` the memo is a u64: the high 40 bits are an HMAC tag over
+ * the invoice fields plus a 24-bit nonce in the low bits. Only this server can
+ * mint a memo that verifies, and the nonce keeps same-second invoices unique.
+ */
+const MEMO_NONCE_BITS = 24n;
+const MEMO_TAG_BITS = 40n;
+
+function memoTag(
+ secret: string,
+ fields: { agentMint: string; asset: string; amount: string; payTo: string; startTime: number; endTime: number },
+ nonce: bigint,
+): bigint {
+ const mac = createHmac("sha256", secret)
+ .update(
+ [fields.agentMint, fields.asset, fields.amount, fields.payTo, fields.startTime, fields.endTime, nonce].join(":"),
+ )
+ .digest();
+ return mac.readBigUInt64BE(0) >> (64n - MEMO_TAG_BITS);
+}
+
+function generateSignedMemo(
+ secret: string,
+ fields: { agentMint: string; asset: string; amount: string; payTo: string; startTime: number; endTime: number },
+): string {
+ const nonce = BigInt(randomBytes(3).readUIntBE(0, 3));
+ return String((memoTag(secret, fields, nonce) << MEMO_NONCE_BITS) | nonce);
+}
+
+/** Skew allowed between the issuing clock and the verifying clock, seconds. */
+const INVOICE_CLOCK_SKEW_SECONDS = 60;
+
+/**
+ * True when the echoed invoice carries a memo this server minted for exactly
+ * these fields and its validity window is open now.
+ */
+function invoiceIsServerBound(secret: string, req: PumpAgentPaymentRequirements): boolean {
+ let memo: bigint;
+ try {
+ memo = BigInt(String(req.extra.memo));
+ } catch {
+ return false;
+ }
+ if (memo < 0n || memo >= 1n << 64n) return false;
+ const nonce = memo & ((1n << MEMO_NONCE_BITS) - 1n);
+ const expected = memoTag(
+ secret,
+ {
+ agentMint: req.extra.agentMint,
+ asset: req.asset,
+ amount: req.amount,
+ payTo: req.payTo,
+ startTime: req.extra.startTime,
+ endTime: req.extra.endTime,
+ },
+ nonce,
+ );
+ const got = Buffer.alloc(8);
+ const want = Buffer.alloc(8);
+ got.writeBigUInt64BE(memo >> MEMO_NONCE_BITS);
+ want.writeBigUInt64BE(expected);
+ if (!timingSafeEqual(got, want)) return false;
+ const now = Math.floor(Date.now() / 1000);
+ return (
+ req.extra.startTime <= now + INVOICE_CLOCK_SKEW_SECONDS &&
+ now <= req.extra.endTime + INVOICE_CLOCK_SKEW_SECONDS
+ );
+}
+
/**
* Stable logical key for an invoice, mirroring the on-chain invoice-id seeds:
* (agentMint, currencyMint/asset, amount, memo, startTime, endTime). Used as
@@ -299,6 +372,11 @@ export interface PumpAgentRequirementsConfig {
invoiceWindowSeconds?: number;
/** Max settlement timeout in seconds (default: 60) */
maxTimeoutSeconds?: number;
+ /**
+ * Server secret that binds each minted memo to this server. Pass the same
+ * value to {@link createResourceServer} so it rejects invoices it did not mint.
+ */
+ invoiceSecret?: string;
}
/**
@@ -309,17 +387,27 @@ export function buildPumpAgentRequirements(
): PumpAgentPaymentRequirements {
const windowSec = config.invoiceWindowSeconds ?? 300;
const now = Math.floor(Date.now() / 1000);
+ const asset = config.asset ?? USDC_MAINNET;
return {
scheme: "pump-agent",
network: config.network ?? SOLANA_MAINNET,
- asset: config.asset ?? USDC_MAINNET,
+ asset,
amount: config.amount,
payTo: config.payTo,
maxTimeoutSeconds: config.maxTimeoutSeconds ?? 60,
extra: {
agentMint: config.agentMint,
- memo: generateMemo(),
+ memo: config.invoiceSecret
+ ? generateSignedMemo(config.invoiceSecret, {
+ agentMint: config.agentMint,
+ asset,
+ amount: config.amount,
+ payTo: config.payTo,
+ startTime: now,
+ endTime: now + windowSec,
+ })
+ : generateMemo(),
startTime: now,
endTime: now + windowSec,
},
@@ -332,18 +420,31 @@ export function buildPumpAgentRequirements(
* (amount, asset, payTo, agentMint, network) are preserved from the template.
* Non-pump-agent requirements are returned unchanged.
*/
-function refreshRequirement(req: PaymentRequirements): PaymentRequirements {
+function refreshRequirement(
+ req: PaymentRequirements,
+ invoiceSecret?: string,
+): PaymentRequirements {
if (req.scheme !== "pump-agent") return req;
const pump = req as PumpAgentPaymentRequirements;
const now = Math.floor(Date.now() / 1000);
const windowSec = Math.max(1, pump.extra.endTime - pump.extra.startTime || 300);
+ const endTime = now + windowSec;
return {
...pump,
extra: {
...pump.extra,
- memo: generateMemo(),
+ memo: invoiceSecret
+ ? generateSignedMemo(invoiceSecret, {
+ agentMint: pump.extra.agentMint,
+ asset: pump.asset,
+ amount: pump.amount,
+ payTo: pump.payTo,
+ startTime: now,
+ endTime,
+ })
+ : generateMemo(),
startTime: now,
- endTime: now + windowSec,
+ endTime,
},
};
}
@@ -361,7 +462,7 @@ async function mintRequirements(
if (config.mintRequirements) {
return config.mintRequirements(request);
}
- return config.requirements.map(refreshRequirement);
+ return config.requirements.map((r) => refreshRequirement(r, config.invoiceSecret));
}
/**
@@ -502,6 +603,16 @@ export function createResourceServer(
return new Response("Payment requirement mismatch", { status: 400 });
}
+ if (
+ config.invoiceSecret &&
+ accepted.scheme === "pump-agent" &&
+ !invoiceIsServerBound(config.invoiceSecret, accepted as PumpAgentPaymentRequirements)
+ ) {
+ return new Response("Invoice was not issued by this server or has expired", {
+ status: 400,
+ });
+ }
+
const matchedReq = accepted;
// Verify
diff --git a/agent-payments-sdk/src/solana/x402/invoice-binding.test.ts b/agent-payments-sdk/src/solana/x402/invoice-binding.test.ts
new file mode 100644
index 000000000..e44d89e8c
--- /dev/null
+++ b/agent-payments-sdk/src/solana/x402/invoice-binding.test.ts
@@ -0,0 +1,113 @@
+import { describe, it, expect, vi } from "vitest";
+import {
+ buildPumpAgentRequirements,
+ createResourceServer,
+} from "./facilitator";
+import { encodePaymentPayload } from "./headers";
+import type {
+ FacilitatorClient,
+ PaymentPayload,
+ PumpAgentPaymentRequirements,
+} from "./types";
+
+const AGENT_MINT = "11111111111111111111111111111112";
+const PAY_TO = "11111111111111111111111111111113";
+const SECRET = "test-invoice-secret-not-for-production";
+
+function stubFacilitator() {
+ const verify = vi.fn(async () => ({ isValid: true }));
+ const settle = vi.fn(async () => ({
+ success: true,
+ transaction: "sig",
+ network: "solana",
+ payer: "payer",
+ }));
+ return {
+ verify,
+ settle,
+ client: { verify, settle, getSupported: async () => ({ kinds: [] }) } as unknown as FacilitatorClient,
+ };
+}
+
+function gateFor(invoiceSecret: string | undefined, facilitator: FacilitatorClient) {
+ return createResourceServer({
+ facilitator,
+ invoiceSecret,
+ requirements: [
+ buildPumpAgentRequirements({
+ agentMint: AGENT_MINT,
+ payTo: PAY_TO,
+ amount: "1000000",
+ invoiceSecret,
+ }),
+ ],
+ resource: { url: "/api/x", description: "x" },
+ });
+}
+
+async function mintedInvoice(gate: ReturnType<typeof gateFor>) {
+ const res = await gate(new Request("https://x.test/api/x"), () => new Response("ok"));
+ const body = (await res.json()) as { accepts: PumpAgentPaymentRequirements[] };
+ return body.accepts[0];
+}
+
+function pay(accepted: PumpAgentPaymentRequirements) {
+ const payload: PaymentPayload = {
+ x402Version: 2,
+ scheme: "pump-agent",
+ network: accepted.network,
+ accepted,
+ payload: {},
+ };
+ return new Request("https://x.test/api/x", {
+ headers: { "X-PAYMENT": encodePaymentPayload(payload) },
+ });
+}
+
+describe("resource server invoice binding", () => {
+ it("accepts an invoice this server minted", async () => {
+ const f = stubFacilitator();
+ const gate = gateFor(SECRET, f.client);
+ const res = await gate(pay(await mintedInvoice(gate)), () => new Response("ok"));
+ expect(res.status).toBe(200);
+ expect(f.verify).toHaveBeenCalledOnce();
+ });
+
+ it("rejects a memo the server never issued before touching the chain", async () => {
+ const f = stubFacilitator();
+ const gate = gateFor(SECRET, f.client);
+ const minted = await mintedInvoice(gate);
+ const forged = { ...minted, extra: { ...minted.extra, memo: "1700000000000000001" } };
+ const res = await gate(pay(forged), () => new Response("ok"));
+ expect(res.status).toBe(400);
+ expect(f.verify).not.toHaveBeenCalled();
+ });
+
+ it("rejects a minted memo moved onto a different invoice window", async () => {
+ const f = stubFacilitator();
+ const gate = gateFor(SECRET, f.client);
+ const minted = await mintedInvoice(gate);
+ const shifted = {
+ ...minted,
+ extra: { ...minted.extra, startTime: minted.extra.startTime - 10, endTime: minted.extra.endTime - 10 },
+ };
+ const res = await gate(pay(shifted), () => new Response("ok"));
+ expect(res.status).toBe(400);
+ expect(f.verify).not.toHaveBeenCalled();
+ });
+
+ it("rejects an invoice whose window has already closed", async () => {
+ const f = stubFacilitator();
+ const gate = gateFor(SECRET, f.client);
+ vi.useFakeTimers();
+ try {
+ const minted = await mintedInvoice(gate);
+ vi.setSystemTime(Date.now() + 3_600_000);
+ const res = await gate(pay(minted), () => new Response("ok"));
+ expect(res.status).toBe(400);
+ expect(f.verify).not.toHaveBeenCalled();
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+});
diff --git a/agent-payments-sdk/src/solana/x402/types.ts b/agent-payments-sdk/src/solana/x402/types.ts
index eaf09bb58..44ee70713 100644
--- a/agent-payments-sdk/src/solana/x402/types.ts
+++ b/agent-payments-sdk/src/solana/x402/types.ts
@@ -247,6 +247,15 @@ export interface ResourceServerConfig {
mintRequirements?: (
request: Request,
) => PaymentRequirements[] | Promise<PaymentRequirements[]>;
+ /**
+ * Server secret that binds every `pump-agent` invoice to this server. Memos are
+ * minted as an HMAC-tagged u64 and the resource server refuses an echoed
+ * invoice whose memo it did not mint for those exact fields, or whose window is
+ * closed, before any on-chain check. Strongly recommended in production; when
+ * you supply {@link mintRequirements}, mint with `buildPumpAgentRequirements`
+ * and the same `invoiceSecret`.
+ */
+ invoiceSecret?: string;
}
// ─── Client Configuration ───────────────────────────────────────────────────