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(skill-import): refuse private GitHub repos, escape x402 modal challenge fields, keep spent budget after a post-sign 402

nirholas3d07630b2ff5
diff --git a/api/pay/execute.js b/api/pay/execute.js
index db305a614..a767aa183 100644
--- a/api/pay/execute.js
+++ b/api/pay/execute.js
@@ -323,7 +323,9 @@ async function settlePayment({
const durationMs = Date.now() - t0;
if (paid.status === 402) {
- await rollbackReservation(sessionRecord.id, amountAtomics, { railReservationId }).catch(() => {});
+ // The signed transfer was already handed to the host. A host that is also
+ // the fee payer can co-sign and broadcast it, then answer 402, so a 402
+ // is not proof nothing landed: the reservation stays spent.
await recordExecution({
sessionId: sessionRecord.id, userId: sessionRecord.user_id, endpointUrl: targetUrl, method,
amountAtomics, network: accept.network, txHash: null, payerAddress: payer, payeeAddress: accept.payTo,
@@ -332,7 +334,7 @@ async function settlePayment({
}).catch(() => {});
return {
ok: false, status: 402, code: 'payment_rejected',
- message: 'Service rejected the payment before settlement. Budget has been restored.',
+ message: 'Service answered 402 after the signed payment was submitted. The budget stays reserved because the transfer may still land.',
detail: typeof paidJson === 'object' ? paidJson : null,
};
}
diff --git a/packages/skill-import/src/github.js b/packages/skill-import/src/github.js
index c9a884c51..fe78460fd 100644
--- a/packages/skill-import/src/github.js
+++ b/packages/skill-import/src/github.js
@@ -62,6 +62,11 @@ export async function discoverGithubSource(input, { fetchUrl, githubToken } = {}
throw new GithubDiscoveryError(`GitHub repo lookup failed: ${repoRes.status} ${owner}/${repo}`);
}
const repoInfo = await repoRes.json();
+ // The platform token can read private repos, and the imported bundle is
+ // served without a session, so only public repos may be imported.
+ if (repoInfo.private !== false) {
+ throw new GithubDiscoveryError(`${owner}/${repo} is not a public repository`);
+ }
const branch = repoInfo.default_branch || 'main';
for (const candidate of SPEC_CANDIDATES) {
diff --git a/public/x402.js b/public/x402.js
index e0ac6fcc6..cdf62c51f 100644
--- a/public/x402.js
+++ b/public/x402.js
@@ -1286,7 +1286,7 @@ class CheckoutModal {
const decimals = accept.extra?.decimals ?? 6;
const amount = formatAmount(accept.amount, decimals);
const sym = assetSymbol(accept);
- this.priceEl.innerHTML = `${amount}<span class="x402-currency"> ${sym}</span>`;
+ this.priceEl.innerHTML = `${amount}<span class="x402-currency"> ${escapeHtml(sym)}</span>`;
this.networkEl.textContent = networkLabel(accept.network, accept);
}
@@ -1387,7 +1387,7 @@ class CheckoutModal {
<button class="x402-wallet-btn" data-wallet="phantom" ${phantomDetected ? '' : 'disabled'}>
<div class="x402-wallet-icon x402-phantom">${solanaProvider?.isThreeWs ? '3' : 'P'}</div>
<span class="x402-wallet-name">${phantomDetected ? solanaWalletLabel(solanaProvider) : 'No Solana wallet detected'}</span>
- <span class="x402-wallet-meta">${networkLabel(solanaAccept.network, solanaAccept)}</span>
+ <span class="x402-wallet-meta">${escapeHtml(networkLabel(solanaAccept.network, solanaAccept))}</span>
</button>
`);
}
@@ -1423,7 +1423,7 @@ class CheckoutModal {
<button class="x402-wallet-btn" data-wallet="evm" ${evmDetected ? '' : 'disabled'}>
<div class="x402-wallet-icon x402-metamask">M</div>
<span class="x402-wallet-name">${evmDetected ? 'Browser wallet' : 'No EVM wallet detected'}</span>
- <span class="x402-wallet-meta">${networkLabel(evmAccept.network, evmAccept)}</span>
+ <span class="x402-wallet-meta">${escapeHtml(networkLabel(evmAccept.network, evmAccept))}</span>
</button>
`);
}
@@ -1650,7 +1650,7 @@ class CheckoutModal {
${
payment?.transaction
? `<div class="x402-receipt-row"><span class="x402-k">tx</span><span class="x402-v">${
- explorer ? `<a href="${explorer}" target="_blank" rel="noopener">${txShort} ↗</a>` : txShort
+ explorer ? `<a href="${escapeHtml(explorer)}" target="_blank" rel="noopener">${escapeHtml(txShort)} ↗</a>` : escapeHtml(txShort)
}</span></div>`
: ''
}
diff --git a/tests/pay-execute-402-after-sign.test.js b/tests/pay-execute-402-after-sign.test.js
new file mode 100644
index 000000000..46ea77a42
--- /dev/null
+++ b/tests/pay-execute-402-after-sign.test.js
@@ -0,0 +1,67 @@
+// /api/pay/execute: once the signed transfer has been handed to the paid host,
+// an HTTP 402 answer is not proof that nothing landed (a host that is also the
+// transaction fee payer can co-sign and broadcast, then answer 402). The
+// session budget must therefore stay spent.
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
+import { Keypair } from '@solana/web3.js';
+
+vi.mock('../api/_lib/ssrf.js', async (importOriginal) => {
+ const actual = await importOriginal();
+ return { ...actual, resolvePublicHost: async () => ['203.0.113.10'], pinnedAgent: () => ({ destroy: async () => {} }) };
+});
+
+vi.mock('../api/_lib/pay/spend-governor.js', async (importOriginal) => {
+ const actual = await importOriginal();
+ return {
+ ...actual,
+ verifySessionToken: vi.fn(async () => SESSION),
+ reserveSessionSpend: vi.fn(async () => ({
+ session: { ...SESSION, spent_usdc: '2000000' },
+ railReservationId: 'rail-1', policyDigest: 'd', verdictCode: 'ok',
+ verdictSignature: 's', verdictSignedAt: '2026-10-15T00:00:00.000Z',
+ })),
+ rollbackReservation: vi.fn(async () => {}),
+ recordExecution: vi.fn(async () => {}),
+ };
+});
+vi.mock('../api/_lib/db.js', () => ({ sql: vi.fn(async () => []) }));
+const PAYER = Keypair.generate();
+vi.mock('../api/_lib/x402/pay.js', () => ({ loadSeedKeypair: vi.fn(() => PAYER) }));
+vi.mock('../api/_lib/solana/connection.js', () => ({ solanaConnection: vi.fn(() => ({})) }));
+const BLOCKHASH = Keypair.generate().publicKey.toBase58();
+vi.mock('../api/_lib/solana/read-guards.js', () => ({
+ mintDecimals: vi.fn(async () => 6), ataExists: vi.fn(async () => true),
+ getRecentBlockhash: vi.fn(async () => BLOCKHASH), isRpcUnavailable: vi.fn(() => false), RPC_RETRY_AFTER_SECONDS: 30,
+}));
+
+const { rollbackReservation, recordExecution } = await import('../api/_lib/pay/spend-governor.js');
+const { USDC_SOLANA_MINT } = await import('../api/_lib/pay/probe.js');
+const { default: handler } = await import('../api/pay/execute.js');
+
+const SESSION = { id: 'sess-1', user_id: 'owner-1', agent_id: null, label: 'x', network: 'solana', spent_usdc: '0', budget_usdc: '100000000' };
+const TARGET_URL = 'https://api.example.com/data';
+const challenge = () => JSON.stringify({
+ x402Version: 2, resource: TARGET_URL,
+ accepts: [{ scheme: 'exact', network: 'solana', amount: '2000000', asset: USDC_SOLANA_MINT,
+ payTo: Keypair.generate().publicKey.toBase58(), extra: { feePayer: Keypair.generate().publicKey.toBase58() } }],
+});
+
+let realFetch;
+beforeEach(() => { realFetch = globalThis.fetch; vi.clearAllMocks(); });
+afterEach(() => { globalThis.fetch = realFetch; });
+
+describe('POST /api/pay/execute: 402 after the signed transfer was handed over', () => {
+ it('keeps the budget spent and records the outcome as uncertain', async () => {
+ globalThis.fetch = vi.fn(async () => new Response(challenge(), { status: 402 }));
+ const res = { statusCode: 0, payload: null, headers: {},
+ setHeader(k, v) { this.headers[String(k).toLowerCase()] = v; }, getHeader(k) { return this.headers[String(k).toLowerCase()]; },
+ removeHeader() {}, writeHead(c) { this.statusCode = c; return this; }, get headersSent() { return false; }, get writableEnded() { return false; },
+ end(c) { if (c) { try { this.payload = JSON.parse(String(c)); } catch { this.payload = String(c); } } return this; } };
+ await handler({ method: 'POST', url: '/api/pay/execute', headers: { 'content-type': 'application/json', origin: 'https://three.ws' },
+ body: { session_token: 'pss_11111111-1111-4111-8111-111111111111_abc', url: TARGET_URL } }, res);
+
+ expect(globalThis.fetch).toHaveBeenCalledTimes(2);
+ expect(rollbackReservation).not.toHaveBeenCalled();
+ expect(recordExecution).toHaveBeenCalledWith(expect.objectContaining({ errorCode: 'payment_rejected' }));
+ });
+});
diff --git a/tests/skill-import-github-private-repo.test.js b/tests/skill-import-github-private-repo.test.js
new file mode 100644
index 000000000..e0bd885bf
--- /dev/null
+++ b/tests/skill-import-github-private-repo.test.js
@@ -0,0 +1,34 @@
+// The skill importer sends the platform GitHub token to api.github.com. A
+// private repo readable by that token must never be imported, because the
+// resulting draft bundle is served without a session.
+import { describe, it, expect } from 'vitest';
+import { discoverGithubSource, GithubDiscoveryError } from '../packages/skill-import/src/github.js';
+
+function fetchFor(repoInfo) {
+ const calls = [];
+ const fetchUrl = async (url, init) => {
+ calls.push(url);
+ if (url === 'https://api.github.com/repos/o/r') return Response.json(repoInfo);
+ if (url.startsWith('https://raw.githubusercontent.com/')) return new Response('', { status: 404 });
+ if (url.endsWith('/readme')) {
+ return Response.json({ content: Buffer.from('# secret readme').toString('base64'), encoding: 'base64', html_url: 'https://github.com/o/r' });
+ }
+ return new Response('', { status: 404 });
+ };
+ return { fetchUrl, calls };
+}
+
+describe('discoverGithubSource private repo guard', () => {
+ it('refuses a private repo before reading its README', async () => {
+ const { fetchUrl, calls } = fetchFor({ name: 'r', default_branch: 'main', private: true });
+ await expect(discoverGithubSource('o/r', { fetchUrl, githubToken: 'tok' })).rejects.toBeInstanceOf(GithubDiscoveryError);
+ expect(calls.some((u) => u.endsWith('/readme'))).toBe(false);
+ });
+
+ it('still imports a public repo README', async () => {
+ const { fetchUrl } = fetchFor({ name: 'r', default_branch: 'main', private: false });
+ const out = await discoverGithubSource('o/r', { fetchUrl, githubToken: 'tok' });
+ expect(out.kind).toBe('readme');
+ expect(out.text).toContain('secret readme');
+ });
+});
diff --git a/tests/x402-modal-challenge-escaping.test.js b/tests/x402-modal-challenge-escaping.test.js
new file mode 100644
index 000000000..fb014706f
--- /dev/null
+++ b/tests/x402-modal-challenge-escaping.test.js
@@ -0,0 +1,26 @@
+// The x402 modal renders fields from a merchant-controlled 402 challenge and
+// X-PAYMENT-RESPONSE header. Every one of them must pass through escapeHtml
+// before it reaches innerHTML, in the SDK source and the shipped /x402.js.
+import { describe, it, expect } from 'vitest';
+import { readFileSync } from 'node:fs';
+
+const FILES = ['../x402-modal-sdk/src/x402-modal.js', '../public/x402.js'];
+
+describe.each(FILES)('x402 modal challenge field escaping: %s', (rel) => {
+ const src = readFileSync(new URL(rel, import.meta.url), 'utf8');
+
+ it('escapes the currency symbol taken from accept.extra.name', () => {
+ expect(src).toMatch(/<span class="x402-currency"> \$\{escapeHtml\(sym\)\}<\/span>/);
+ });
+
+ it('escapes the network label in both wallet buttons', () => {
+ expect(src).not.toMatch(/x402-wallet-meta">\$\{networkLabel\(/);
+ expect(src).toMatch(/x402-wallet-meta">\$\{escapeHtml\(networkLabel\(solanaAccept\.network, solanaAccept\)\)\}/);
+ });
+
+ it('escapes the settlement transaction and explorer href', () => {
+ expect(src).not.toMatch(/<a href="\$\{explorer\}"/);
+ expect(src).toMatch(/<a href="\$\{escapeHtml\(explorer\)\}"[^>]*>\$\{escapeHtml\(txShort\)\}/);
+ expect(src).toMatch(/: escapeHtml\(txShort\)/);
+ });
+});
diff --git a/x402-modal-sdk/src/x402-modal.js b/x402-modal-sdk/src/x402-modal.js
index 343edeeea..2ee25dfe7 100644
--- a/x402-modal-sdk/src/x402-modal.js
+++ b/x402-modal-sdk/src/x402-modal.js
@@ -654,7 +654,7 @@ export class CheckoutModal {
const decimals = accept.extra?.decimals ?? 6;
const amount = formatAmount(accept.amount, decimals);
const sym = (accept.extra?.name || 'USDC').replace(/^USD Coin$/, 'USDC');
- this.priceEl.innerHTML = `${amount}<span class="x402-currency"> ${sym}</span>`;
+ this.priceEl.innerHTML = `${amount}<span class="x402-currency"> ${escapeHtml(sym)}</span>`;
this.networkEl.textContent = networkLabel(accept.network, accept);
}
@@ -695,7 +695,7 @@ export class CheckoutModal {
<button class="x402-wallet-btn" data-wallet="phantom" ${phantomDetected ? '' : 'disabled'}>
<div class="x402-wallet-icon x402-phantom">P</div>
<span class="x402-wallet-name">${phantomDetected ? 'Phantom' : 'Phantom (not detected)'}</span>
- <span class="x402-wallet-meta">${networkLabel(solanaAccept.network, solanaAccept)}</span>
+ <span class="x402-wallet-meta">${escapeHtml(networkLabel(solanaAccept.network, solanaAccept))}</span>
</button>
`);
}
@@ -704,7 +704,7 @@ export class CheckoutModal {
<button class="x402-wallet-btn" data-wallet="evm" ${evmDetected ? '' : 'disabled'}>
<div class="x402-wallet-icon x402-metamask">M</div>
<span class="x402-wallet-name">${evmDetected ? 'Browser wallet' : 'No EVM wallet detected'}</span>
- <span class="x402-wallet-meta">${networkLabel(evmAccept.network, evmAccept)}</span>
+ <span class="x402-wallet-meta">${escapeHtml(networkLabel(evmAccept.network, evmAccept))}</span>
</button>
`);
}
@@ -815,7 +815,7 @@ export class CheckoutModal {
${
payment?.transaction
? `<div class="x402-receipt-row"><span class="x402-k">tx</span><span class="x402-v">${
- explorer ? `<a href="${explorer}" target="_blank" rel="noopener">${txShort} ↗</a>` : txShort
+ explorer ? `<a href="${escapeHtml(explorer)}" target="_blank" rel="noopener">${escapeHtml(txShort)} ↗</a>` : escapeHtml(txShort)
}</span></div>`
: ''
}