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(x402,wizard): always-on payment replay guard, avatar-required step, selfie CTAs

nirholas83273082a116
diff --git a/api/_lib/x402-paid-endpoint.js b/api/_lib/x402-paid-endpoint.js
index 389da4f03..ec744de5d 100644
--- a/api/_lib/x402-paid-endpoint.js
+++ b/api/_lib/x402-paid-endpoint.js
@@ -657,7 +657,7 @@ export function paidEndpoint(spec) {
// for our GET-only paid endpoints — none of them read request bodies.
// When/if a POST endpoint joins the family, the handler can buffer
// `req.body` and pass it in here.
- const paymentId = extractIdFromHeader(paymentHeader);
+ const clientPaymentId = extractIdFromHeader(paymentHeader);
const payloadHash = hashRequestPayload({
method: req.method,
url: req.url,
@@ -666,6 +666,20 @@ export function paidEndpoint(spec) {
// Bind the idempotency cache to the signed payment proof so a stolen or
// guessed payment-identifier can't redeem a prior paid response for free.
const paymentHash = hashPaymentProof(paymentHeader);
+ // Always-on replay guard. The payment-identifier extension is client-
+ // opt-in, so a payer who omits it would otherwise get NO server-side
+ // replay protection: a captured X-PAYMENT header could be replayed to
+ // re-run the handler (re-delivering the paid good, with side effects) and
+ // re-hit /settle. The flow delivers BEFORE settling, so we can't lean on
+ // on-chain nonce reuse to stop the re-delivery, and we don't trust the
+ // external facilitator to reject the replay -- same defense-in-depth
+ // stance as the amount/recipient/network checks in x402-spec.js. When the
+ // client sends no id we fall back to the proof hash itself as the dedup
+ // key (reproducible only by the original payer), making replay protection
+ // unconditional. Entries are written only AFTER a successful settle, so a
+ // transient verify/settle failure never locks a legitimate payer out of
+ // retrying the same payment.
+ const paymentId = clientPaymentId || (paymentHash ? `proof:${paymentHash}` : null);
if (paymentId) {
const lookup = await checkCache({ route, paymentId, payloadHash, paymentHash });
if (lookup.kind === 'hit') {
diff --git a/api/chat/proxy.js b/api/chat/proxy.js
index b953eda2d..eae225e31 100644
--- a/api/chat/proxy.js
+++ b/api/chat/proxy.js
@@ -17,7 +17,7 @@ export default wrap(async (req, res) => {
const ip = clientIp(req);
const rl = await limits.chatIp(ip);
if (!rl.success) {
- res.setHeader('retry-after', '60');
+ // rateLimited() sets a standards-correct Retry-After from the limiter result.
return rateLimited(res, rl);
}
diff --git a/pages/create-agent.html b/pages/create-agent.html
index 555851b60..84f4b36f4 100644
--- a/pages/create-agent.html
+++ b/pages/create-agent.html
@@ -1095,7 +1095,7 @@
<section class="panel" data-step="1" aria-label="3D model">
<p class="panel-eyebrow">Step 2 of 5</p>
<h2 class="panel-title">Give it a body</h2>
- <p class="panel-help">Pick a ready-made 3D character or upload your own glTF model. You can always swap it later.</p>
+ <p class="panel-help">Every agent gets a 3D avatar. Pick a ready-made character or upload your own glTF model — you can always swap it later.</p>
<div class="model-tabs" role="tablist">
<button type="button" class="model-tab is-active" data-pane="starter" role="tab" aria-selected="true">Starter library</button>
@@ -1122,9 +1122,19 @@
<div class="model-pane" data-pane="skip">
<p class="panel-help" style="margin: 6px 0 0">
- No problem — you can create the agent now and attach a 3D model anytime from its editor.
- It'll use a neutral placeholder until then.
+ A 3D avatar is how people recognize and connect with your agent across three.ws — we strongly recommend giving it one now from the Starter library or your own upload.
</p>
+ <div class="publish-box" style="margin-top: 14px">
+ <label class="toggle">
+ <input type="checkbox" id="f-skip-ack" />
+ <span class="track"></span>
+ <span class="knob"></span>
+ </label>
+ <div class="publish-text">
+ <strong>Create without a 3D avatar for now</strong>
+ <span>I understand my agent will use a neutral placeholder until I attach a model from its editor.</span>
+ </div>
+ </div>
</div>
<div class="model-preview" id="model-preview">
diff --git a/src/create-agent.js b/src/create-agent.js
index 311e353e3..cb4e5cbfd 100644
--- a/src/create-agent.js
+++ b/src/create-agent.js
@@ -83,7 +83,7 @@ const state = {
name: '',
description: '',
tags: [],
- model: { mode: 'starter', starterId: '', starterUrl: '', file: null, fileName: '' },
+ model: { mode: 'starter', starterId: '', starterUrl: '', file: null, fileName: '', skipAck: false },
skills: new Set(CORE_SKILLS.map((s) => s.id)),
category: '',
greeting: '',
@@ -254,6 +254,21 @@ function validateStep(n) {
return false;
}
}
+ if (n === 1) {
+ // Every agent gets a 3D avatar. Require a real choice — a starter, an
+ // upload, or an explicit acknowledgment that they're skipping for now.
+ const hasStarter = state.model.mode === 'starter' && !!state.model.starterUrl;
+ const hasUpload = state.model.mode === 'upload' && !!state.model.file;
+ const acknowledgedSkip = state.model.mode === 'none' && state.model.skipAck;
+ if (!hasStarter && !hasUpload && !acknowledgedSkip) {
+ if (state.model.mode === 'none') {
+ setMsg('Tick the box to confirm you want to create this agent without a 3D avatar.', 'err');
+ } else {
+ setMsg('Pick a starter avatar or upload a 3D model — or choose “Add later” and confirm.', 'err');
+ }
+ return false;
+ }
+ }
if (n === 3 && state.publish) {
// Publishing needs a category + profile prompt. Don't hard-block the step —
// just warn; the review step lets them turn off publishing instead.
@@ -394,7 +409,14 @@ function wireModel() {
p.classList.toggle('is-active', p.dataset.pane === pane),
);
if (pane === 'skip') {
- state.model = { mode: 'none', starterId: '', starterUrl: '', file: null, fileName: '' };
+ state.model = {
+ mode: 'none',
+ starterId: '',
+ starterUrl: '',
+ file: null,
+ fileName: '',
+ skipAck: !!$('f-skip-ack')?.checked,
+ };
document.querySelectorAll('.starter').forEach((c) => c.classList.remove('is-selected'));
syncModelPreview();
} else if (pane === 'starter' && state.model.mode !== 'starter') {
@@ -403,6 +425,12 @@ function wireModel() {
});
});
+ // "Add later" acknowledgment — required to advance without an avatar.
+ $('f-skip-ack')?.addEventListener('change', (e) => {
+ state.model.skipAck = e.target.checked;
+ if (state.step === 1) clearMsg();
+ });
+
// Dropzone + file input
const dz = $('dropzone');
const input = $('glb-input');
diff --git a/src/dashboard-next/pages/home.js b/src/dashboard-next/pages/home.js
index 881dc5230..09d292b25 100644
--- a/src/dashboard-next/pages/home.js
+++ b/src/dashboard-next/pages/home.js
@@ -194,7 +194,7 @@ function renderHero(host, avatars, err) {
if (!avatars.length) {
host.innerHTML = `
- <a href="/create" class="dn-panel dnx-create-cta">
+ <a href="/create/selfie" class="dn-panel dnx-create-cta">
<div class="dnx-create-icon">+</div>
<div>
<div class="dn-panel-title" style="margin:0 0 4px;font-size:16px">Create your first avatar</div>
@@ -295,7 +295,7 @@ async function refreshKpis(host, ctx) {
numeric: avatarTotal,
series: avatarSeries,
empty: avatarTotal === 0,
- emptyCta: { label: 'Create from selfie', href: '/create' },
+ emptyCta: { label: 'Create from selfie', href: '/create/selfie' },
},
];
@@ -487,8 +487,8 @@ function renderOnboarding(host, { avatars, agents, widgets }) {
id: 'avatar',
label: 'Create your first avatar',
sub: 'Snap a selfie — your 3D agent is ready in under 60 seconds.',
- href: avatars.length === 0 ? '/start' : '/create',
- cta: avatars.length === 0 ? 'Start wizard →' : 'Create another',
+ href: avatars.length === 0 ? '/create/selfie' : '/create',
+ cta: avatars.length === 0 ? 'Snap a selfie →' : 'Create another',
done: avatars.length > 0,
},
{
@@ -587,7 +587,7 @@ function renderQuickActions(host, { avatars = [], agents = [] } = {}) {
if (firstAvatar) {
defaults.push({ href: `/agents/${encodeURIComponent(firstAvatar.id)}`, title: 'View live agent page', sub: 'See how visitors experience your agent', iconKey: '/dashboard/agents', cat: 'Agents & Identity' });
} else {
- defaults.push({ href: '/create', title: 'Create avatar from selfie', sub: 'Snap a photo, get a 3D agent in 60 seconds', iconKey: '/create', cat: 'Create & Build' });
+ defaults.push({ href: '/create/selfie', title: 'Create avatar from selfie', sub: 'Snap a photo, get a 3D agent in 60 seconds', iconKey: '/create', cat: 'Create & Build' });
}
if (firstAgent) {
defaults.push({ href: `/app?agent=${encodeURIComponent(firstAgent.id)}`, title: 'Open 3D studio', sub: 'Edit, animate, and customize in 3D', iconKey: '/app', cat: '3D & Immersive' });
diff --git a/tests/_helpers/monetization.js b/tests/_helpers/monetization.js
index e0c4aaca4..e1b9c74cc 100644
--- a/tests/_helpers/monetization.js
+++ b/tests/_helpers/monetization.js
@@ -4,7 +4,10 @@ let counter = 0;
export function createTestAgent(overrides = {}) {
const userId = `user-${++counter}`;
- const agentId = `agent-${counter}-test-0000-0000-000000000000`;
+ // Must be a real UUID — the x402 handlers guard agent_id with isUuid() and
+ // 404 on anything that doesn't parse, so a synthetic "agent-N-…" id never
+ // reaches the manifest/invoke logic under test.
+ const agentId = `00000000-0000-4000-8000-${String(counter).padStart(12, '0')}`;
const agent = {
id: agentId,
user_id: userId,
diff --git a/tests/api/chat-proxy-ratelimit.test.js b/tests/api/chat-proxy-ratelimit.test.js
index 00422994e..d61c2cfad 100644
--- a/tests/api/chat-proxy-ratelimit.test.js
+++ b/tests/api/chat-proxy-ratelimit.test.js
@@ -86,7 +86,9 @@ describe('POST /api/chat/proxy — per-IP rate limit', () => {
expect(res.statusCode).toBe(429);
const body = JSON.parse(res.body);
expect(body.error).toBe('rate_limited');
- expect(res.getHeader('retry-after')).toBe('60');
+ // rateLimited() derives Retry-After from the limiter result, flooring at 1s
+ // when the mock provides no reset window.
+ expect(res.getHeader('retry-after')).toBe('1');
// Upstream fetch must NOT have been called.
expect(fetchMock).not.toHaveBeenCalled();
});
diff --git a/tests/api/siwe-handler.test.js b/tests/api/siwe-handler.test.js
index 36e0b48b3..1dbbfc5eb 100644
--- a/tests/api/siwe-handler.test.js
+++ b/tests/api/siwe-handler.test.js
@@ -192,16 +192,15 @@ describe('GET /api/auth/siwe/nonce', () => {
describe('POST /api/auth/siwe/verify', () => {
it('creates a session on valid message + signature (new wallet, new user)', async () => {
// Nonce lookup, burn nonce, wallet lookup, user lookup, insert user, insert wallet, fetch user
- // + seedDefaultAgent (queueMicrotask): SELECT existing agents, INSERT default agent
+ // + seedDefaultAgent (queueMicrotask): a single INSERT … WHERE NOT EXISTS
sqlState.queue.push([{ nonce: TEST_NONCE, expires_at: FUTURE, consumed_at: null }]);
sqlState.queue.push([{ nonce: TEST_NONCE }]); // burn RETURNING
sqlState.queue.push([]); // no wallet
sqlState.queue.push([]); // no existing user
sqlState.queue.push([{ id: 'user-new', inserted: true }]); // insert user
sqlState.queue.push([]); // insert wallet
- // seedDefaultAgent runs via queueMicrotask — may interleave with the final fetch
- sqlState.queue.push([]); // seedDefaultAgent: SELECT existing agents → none
- sqlState.queue.push([]); // seedDefaultAgent: INSERT default agent
+ // seedDefaultAgent runs via queueMicrotask — one combined INSERT call
+ sqlState.queue.push([]); // seedDefaultAgent: INSERT default agent (WHERE NOT EXISTS)
sqlState.queue.push([{ id: 'user-new', email: `[email protected]`, display_name: '0xd8dA…6045', plan: 'free', avatar_url: null, created_at: '2024-01-01' }]);
const { status, body, res } = await invoke({
diff --git a/tests/api/x402-paid-endpoint-replay.test.js b/tests/api/x402-paid-endpoint-replay.test.js
new file mode 100644
index 000000000..1806a8580
--- /dev/null
+++ b/tests/api/x402-paid-endpoint-replay.test.js
@@ -0,0 +1,240 @@
+// Always-on replay protection for api/_lib/x402-paid-endpoint.js.
+//
+// The payment-identifier idempotency extension is client-opt-in. A payer who
+// omits it must still not be able to replay a captured X-PAYMENT header to
+// re-run the handler (re-delivering the paid good) or re-settle. The wrapper
+// falls back to the signed payment-proof hash as the dedup key so replay
+// protection is unconditional, WITHOUT trusting the external facilitator.
+//
+// We drive the full paidEndpoint() handler with a stubbed req/res and mock only
+// verifyPayment + settlePayment (the external-facilitator round-trips); the rest
+// of the wrapper — 402 build, idempotency cache, proof binding — runs for real
+// against the in-memory cache fallback.
+
+import { Readable } from 'node:stream';
+
+import { beforeAll, beforeEach, afterAll, describe, it, expect, vi } from 'vitest';
+
+// Mock only the facilitator-facing verify/settle; keep every other export real
+// so send402/build402Body/encodePaymentResponseHeader behave normally.
+const verifyPayment = vi.fn();
+const settlePayment = vi.fn();
+vi.mock('../../api/_lib/x402-spec.js', async (importActual) => {
+ const actual = await importActual();
+ return { ...actual, verifyPayment, settlePayment };
+});
+
+// Heavy upstreams imported transitively — stub so the suite is fast + offline.
+vi.mock('@coinbase/x402', () => ({ createCdpAuthHeaders: vi.fn(async () => ({})) }));
+
+let paidEndpoint;
+let cacheMod;
+
+const BASE = 'eip155:8453';
+const PAY_TO_BASE = '0x4022de2d36c334e73c7a108805cea11c0564f402';
+const ASSET_BASE = '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913';
+const ROUTE = '/api/x402/replay-test';
+
+const HANDLER_BAZAAR = {
+ discoverable: true,
+ info: {
+ input: { type: 'object', properties: {}, required: [] },
+ output: { type: 'object', properties: { ok: { type: 'boolean' } } },
+ },
+ schema: { type: 'object' },
+};
+
+function mockReqRes({ method = 'GET', headers = {}, url = ROUTE } = {}) {
+ const lowerHeaders = {};
+ for (const [k, v] of Object.entries(headers)) lowerHeaders[k.toLowerCase()] = v;
+ const req = Object.assign(new Readable({ read() {} }), {
+ method,
+ url,
+ headers: lowerHeaders,
+ connection: { remoteAddress: '127.0.0.1' },
+ socket: { remoteAddress: '127.0.0.1' },
+ });
+ req.push(null);
+ const chunks = [];
+ const resHeaders = {};
+ const res = {
+ statusCode: 200,
+ writableEnded: false,
+ setHeader(k, v) {
+ resHeaders[k.toLowerCase()] = v;
+ },
+ getHeader(k) {
+ return resHeaders[k.toLowerCase()];
+ },
+ end(body) {
+ if (body !== undefined) chunks.push(body);
+ res.writableEnded = true;
+ },
+ write(chunk) {
+ chunks.push(chunk);
+ },
+ get body() {
+ return chunks.join('');
+ },
+ get headers() {
+ return resHeaders;
+ },
+ };
+ return { req, res };
+}
+
+// A base64 X-PAYMENT header. `withId` attaches a payment-identifier extension;
+// omit it to exercise the always-on proof-hash fallback. `salt` varies the
+// signed proof so distinct payments hash distinctly.
+function paymentHeader({ withId = null, salt = 'a' } = {}) {
+ const payload = {
+ x402Version: 2,
+ scheme: 'exact',
+ network: BASE,
+ payload: { authorization: { value: '1000', to: PAY_TO_BASE, salt } },
+ };
+ if (withId) {
+ payload.extensions = {
+ 'payment-identifier': { info: { required: false, id: withId } },
+ };
+ }
+ return Buffer.from(JSON.stringify(payload)).toString('base64');
+}
+
+function makeEndpoint(handler, spec = {}) {
+ return paidEndpoint({
+ route: ROUTE,
+ method: 'GET',
+ networks: ['base'],
+ description: 'replay protection test',
+ bazaar: HANDLER_BAZAAR,
+ offerReceipt: false,
+ handler,
+ ...spec,
+ });
+}
+
+const ORIG_ENV = { ...process.env };
+
+beforeAll(async () => {
+ process.env.X402_ALLOW_MEMORY_FALLBACK = '1';
+ paidEndpoint = (await import('../../api/_lib/x402-paid-endpoint.js')).paidEndpoint;
+ cacheMod = await import('../../api/_lib/x402/idempotency-cache.js');
+});
+
+beforeEach(() => {
+ process.env.X402_PAY_TO_BASE = PAY_TO_BASE;
+ process.env.X402_ASSET_ADDRESS_BASE = ASSET_BASE;
+ process.env.X402_MAX_AMOUNT_REQUIRED = '1000';
+ delete process.env.CDP_API_KEY_ID;
+ delete process.env.CDP_API_KEY_SECRET;
+ delete process.env.X402_BUILDER_CODE_APP;
+ cacheMod._resetMemoryStore();
+ verifyPayment.mockReset();
+ settlePayment.mockReset();
+ verifyPayment.mockImplementation(async () => ({
+ paymentPayload: {},
+ requirement: { scheme: 'exact', network: BASE, payTo: PAY_TO_BASE, asset: ASSET_BASE, amount: '1000' },
+ payer: 'PAYER',
+ }));
+ settlePayment.mockImplementation(async () => ({
+ success: true,
+ transaction: '0xdeadbeef',
+ network: BASE,
+ payer: 'PAYER',
+ }));
+});
+
+afterAll(() => {
+ for (const k of Object.keys(process.env)) if (!(k in ORIG_ENV)) delete process.env[k];
+ Object.assign(process.env, ORIG_ENV);
+});
+
+describe('paidEndpoint() always-on replay protection (no client payment-identifier)', () => {
+ it('first call delivers + settles; a replay of the same proof serves the cached body without re-running the handler or re-settling', async () => {
+ let handlerCalls = 0;
+ const handler = makeEndpoint(async ({ payer }) => {
+ handlerCalls += 1;
+ return { ok: true, n: handlerCalls, payer };
+ });
+ const header = paymentHeader();
+
+ const { req: r1, res: s1 } = mockReqRes({ headers: { 'x-payment': header } });
+ await handler(r1, s1);
+ expect(s1.statusCode).toBe(200);
+ expect(JSON.parse(s1.body)).toMatchObject({ ok: true, n: 1 });
+ expect(handlerCalls).toBe(1);
+ expect(settlePayment).toHaveBeenCalledTimes(1);
+
+ const { req: r2, res: s2 } = mockReqRes({ headers: { 'x-payment': header } });
+ await handler(r2, s2);
+ expect(s2.statusCode).toBe(200);
+ // Cached replay — same body, flagged, and crucially the handler + settle
+ // did NOT run a second time.
+ expect(s2.getHeader('x-x402-idempotent')).toBe('replay');
+ expect(s2.body).toBe(s1.body);
+ expect(handlerCalls).toBe(1);
+ expect(settlePayment).toHaveBeenCalledTimes(1);
+ });
+
+ it('a different payment (distinct signed proof) is NOT blocked', async () => {
+ let handlerCalls = 0;
+ const handler = makeEndpoint(async () => {
+ handlerCalls += 1;
+ return { ok: true, n: handlerCalls };
+ });
+
+ const { req: r1, res: s1 } = mockReqRes({ headers: { 'x-payment': paymentHeader({ salt: 'a' }) } });
+ await handler(r1, s1);
+ const { req: r2, res: s2 } = mockReqRes({ headers: { 'x-payment': paymentHeader({ salt: 'b' }) } });
+ await handler(r2, s2);
+
+ expect(s1.statusCode).toBe(200);
+ expect(s2.statusCode).toBe(200);
+ expect(s2.getHeader('x-x402-idempotent')).toBeUndefined();
+ expect(handlerCalls).toBe(2);
+ expect(settlePayment).toHaveBeenCalledTimes(2);
+ });
+
+ it('the same proof replayed against a different request payload is denied with 409 conflict', async () => {
+ const handler = makeEndpoint(async () => ({ ok: true }));
+ const header = paymentHeader();
+
+ const { req: r1, res: s1 } = mockReqRes({ url: `${ROUTE}?good=1`, headers: { 'x-payment': header } });
+ await handler(r1, s1);
+ expect(s1.statusCode).toBe(200);
+
+ // Same signed proof, different query string → payload hash differs → the
+ // payment is being reused for a different good. Deny rather than serve.
+ const { req: r2, res: s2 } = mockReqRes({ url: `${ROUTE}?good=2`, headers: { 'x-payment': header } });
+ await handler(r2, s2);
+ expect(s2.statusCode).toBe(409);
+ expect(s2.getHeader('x-x402-idempotent')).toBe('conflict');
+ expect(JSON.parse(s2.body).error).toBe('payment_identifier_conflict');
+ });
+
+ it('a transient settle failure does NOT cache, so the payer can retry the same payment', async () => {
+ let handlerCalls = 0;
+ const handler = makeEndpoint(async () => {
+ handlerCalls += 1;
+ return { ok: true, n: handlerCalls };
+ });
+ const header = paymentHeader();
+
+ // First attempt: settle blips (facilitator 5xx).
+ settlePayment.mockRejectedValueOnce(
+ Object.assign(new Error('facilitator down'), { status: 502, code: 'settle_failed' }),
+ );
+ const { req: r1, res: s1 } = mockReqRes({ headers: { 'x-payment': header } });
+ await handler(r1, s1);
+ expect(s1.statusCode).toBe(502);
+
+ // Retry the SAME payment: must not be treated as a replay (nothing was
+ // cached because settle never succeeded). Handler + settle run again.
+ const { req: r2, res: s2 } = mockReqRes({ headers: { 'x-payment': header } });
+ await handler(r2, s2);
+ expect(s2.statusCode).toBe(200);
+ expect(s2.getHeader('x-x402-idempotent')).toBeUndefined();
+ expect(handlerCalls).toBe(2);
+ });
+});