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.

13.1 KB
Raw Blame
// Tests for the free x402 developer toolkit — echo, debug, verify-receipt
// (api/x402/{echo,debug,verify-receipt}.js + api/_lib/x402/dev-tools.js).
//
// The pure core (redaction, structural verdict, diagnosis, attestation) is
// exercised directly. Handler tests drive the default exports with mock req/res.
// Malformed exchanges are generated by encoding real payment envelopes the wrong
// way (wrong version, shorthand network, decimal amount) — no captured mocks.
//
// Addresses/mints are three.ws's own (owner wallet, $THREE) or synthetic.

import { describe, it, expect } from 'vitest';
import { Readable } from 'node:stream';
import { createHash } from 'crypto';

import echoHandler from '../../api/x402/echo.js';
import debugHandler from '../../api/x402/debug.js';
import verifyHandler from '../../api/x402/verify-receipt.js';
import {
	redactSecrets,
	redactPaymentEnvelope,
	structuralVerdict,
	diagnoseExchange,
	recomputeAttestation,
	verifyAttestation,
} from '../../api/_lib/x402/dev-tools.js';
import { decodePaymentHeader } from '../../api/_lib/x402-spec.js';

// ── Fixtures ────────────────────────────────────────────────────────────────
const PAY_TO = '0x75d00a2713565171f33216e5aa2a375e076ecf69'; // three.ws owner wallet
const FULL_SIG = '0x' + 'de'.repeat(65); // 132-char fake signature

function eip3009Envelope({ value = '10000', to = PAY_TO, version = 2, network = 'eip155:8453' } = {}) {
	return {
		x402Version: version,
		scheme: 'exact',
		network,
		payload: {
			authorization: {
				from: '0xAAA1111111111111111111111111111111111111',
				to,
				value,
				validAfter: '0',
				validBefore: '9999999999',
				nonce: '0x' + 'ab'.repeat(32),
			},
			signature: FULL_SIG,
		},
	};
}

function encodeHeader(envelope) {
	return Buffer.from(JSON.stringify(envelope)).toString('base64');
}

function factCheckResult(overrides = {}) {
	const result = {
		verdict: 'true',
		confidence: 0.92,
		claim: 'the sky is blue',
		strictness: 'normal',
		sources: [{ url: 'https://a.example' }, { url: 'https://b.example' }],
		...overrides,
	};
	// Attestation computed EXACTLY as api/x402/fact-check.js does.
	result.attestation =
		'sha256:' +
		createHash('sha256')
			.update(
				JSON.stringify({
					verdict: result.verdict,
					confidence: result.confidence,
					claim: result.claim,
					sources: result.sources.map((s) => s.url),
				}),
			)
			.digest('hex');
	return result;
}

// ── req/res mocks ─────────────────────────────────────────────────────────
function makeReq({ method = 'POST', url = '/api/x402/echo', headers = {}, body = null } = {}) {
	const base = body ? Readable.from([Buffer.from(JSON.stringify(body))]) : Readable.from([]);
	base.method = method;
	base.url = url;
	base.headers = { host: 'localhost', ...(body ? { 'content-type': 'application/json' } : {}), ...headers };
	base.socket = { remoteAddress: '203.0.113.9' };
	return base;
}

function makeRes() {
	return {
		statusCode: 200,
		headers: {},
		body: '',
		headersSent: false,
		writableEnded: false,
		setHeader(k, v) { this.headers[k.toLowerCase()] = v; },
		getHeader(k) { return this.headers[k.toLowerCase()]; },
		end(chunk) { if (chunk !== undefined) this.body += chunk; this.writableEnded = true; this.headersSent = true; },
	};
}

async function invoke(handler, reqOpts) {
	const req = makeReq(reqOpts);
	const res = makeRes();
	await handler(req, res);
	return { res, status: res.statusCode, body: res.body ? JSON.parse(res.body) : null };
}

// ── Pure: redaction ───────────────────────────────────────────────────────
describe('redactSecrets / redactPaymentEnvelope', () => {
	it('redacts signature fields to a short prefix, never the full value', () => {
		const out = redactSecrets({ signature: FULL_SIG, value: '10000' });
		expect(out.signature).toContain('redacted');
		expect(out.signature).not.toContain('de'.repeat(65));
		expect(out.value).toBe('10000'); // non-secret preserved
	});

	it('redacts secret-looking keys regardless of nesting', () => {
		const out = redactSecrets({ a: { b: { privateKey: 'abcdef0123456789', passphrase: 'hunter2hunter2' } } });
		expect(out.a.b.privateKey).toContain('redacted');
		expect(out.a.b.passphrase).toContain('redacted');
	});

	it('decodes an X-PAYMENT header and never leaks the full signature', () => {
		const view = redactPaymentEnvelope(encodeHeader(eip3009Envelope()));
		expect(view.x402Version).toBe(2);
		expect(view.scheme).toBe('exact');
		expect(view.signedAmount).toBe('10000');
		expect(view.signedRecipient).toBe(PAY_TO.toLowerCase());
		expect(JSON.stringify(view)).not.toContain('de'.repeat(65));
	});

	it('throws on a structurally invalid header', () => {
		expect(() => redactPaymentEnvelope('not-base64-!!!')).toThrow();
		expect(() => redactPaymentEnvelope(Buffer.from('not json').toString('base64'))).toThrow();
	});
});

// ── Pure: structural verdict ────────────────────────────────────────────────
describe('structuralVerdict', () => {
	const decoded = () => decodePaymentHeader(encodeHeader(eip3009Envelope()));

	it('passes an exact-match payment against its requirement', () => {
		const v = structuralVerdict(decoded(), { scheme: 'exact', network: 'eip155:8453', amount: '10000', payTo: PAY_TO });
		expect(v.valid).toBe(true);
	});

	it('fails an underpayment', () => {
		const v = structuralVerdict(decoded(), { amount: '20000', payTo: PAY_TO, network: 'eip155:8453' });
		expect(v.valid).toBe(false);
		expect(v.reason).toMatch(/underpayment/);
	});

	it('fails a recipient mismatch', () => {
		const v = structuralVerdict(decoded(), { amount: '10000', payTo: '0x0000000000000000000000000000000000000001', network: 'eip155:8453' });
		expect(v.valid).toBe(false);
		expect(v.reason).toMatch(/recipient/);
	});

	it('flags a wrong x402Version even with no requirement', () => {
		const v = structuralVerdict(decodePaymentHeader(encodeHeader(eip3009Envelope({ version: 1 }))));
		expect(v.valid).toBe(false);
		expect(v.checks.find((c) => c.field === 'x402Version').pass).toBe(false);
	});
});

// ── Pure: diagnosis matrix ──────────────────────────────────────────────────
describe('diagnoseExchange', () => {
	it('returns an error when nothing is supplied', () => {
		const { findings, ok } = diagnoseExchange({});
		expect(ok).toBe(false);
		expect(findings[0].field).toBe('input');
	});

	it('catches version, shorthand-network, offered-network, and decimal footguns at once', () => {
		const { findings } = diagnoseExchange({
			challenge: { x402Version: 2, accepts: [{ scheme: 'exact', network: 'eip155:8453', amount: '10000', payTo: PAY_TO }] },
			payment: { x402Version: 1, network: 'base', payload: { authorization: { value: '0.01', to: PAY_TO } } },
			response: { error: 'invalid_payment' },
		});
		const fields = findings.map((f) => `${f.severity}:${f.field}`);
		expect(fields).toContain('error:payment.x402Version');
		expect(fields).toContain('error:payment.network'); // shorthand + offered mismatch
		expect(fields).toContain('error:payment.authorization.value'); // decimal
		expect(fields).toContain('info:response.error'); // maps the rail error code
		// errors sort ahead of info
		expect(findings[0].severity).toBe('error');
	});

	it('flags a decimal atomic amount in the challenge itself', () => {
		const { findings } = diagnoseExchange({
			challenge: { x402Version: 2, accepts: [{ scheme: 'exact', network: 'eip155:8453', amount: '0.01', payTo: PAY_TO }] },
		});
		expect(findings.some((f) => f.field.includes('accepts[0].amount'))).toBe(true);
	});

	it('reports a clean exchange as ok', () => {
		const { ok } = diagnoseExchange({
			challenge: { x402Version: 2, accepts: [{ scheme: 'exact', network: 'eip155:8453', amount: '10000', payTo: PAY_TO }] },
			payment: eip3009Envelope(),
		});
		expect(ok).toBe(true);
	});
});

// ── Pure: attestation ───────────────────────────────────────────────────────
describe('verifyAttestation', () => {
	it('confirms an untampered fact-check attestation (matches the real scheme)', () => {
		const result = factCheckResult();
		expect(recomputeAttestation(result)).toBe(result.attestation);
		expect(verifyAttestation(result).verified).toBe(true);
	});

	it('denies a tampered result', () => {
		const result = factCheckResult();
		const tampered = { ...result, verdict: 'false' }; // attestation unchanged
		expect(verifyAttestation(tampered).verified).toBe(false);
		expect(verifyAttestation(tampered).mismatchReason).toMatch(/altered/);
	});

	it('reports partial when the attested fields are missing', () => {
		const r = verifyAttestation({ attestation: 'sha256:deadbeef' });
		expect(r.verified).toBe(false);
		expect(r.mismatchReason).toMatch(/missing/);
	});

	it('reports absent when no attestation string is present', () => {
		const r = verifyAttestation({ verdict: 'true' });
		expect(r.verified).toBe(false);
		expect(r.mismatchReason).toMatch(/no sha256/);
	});
});

// ── Handler: echo ───────────────────────────────────────────────────────────
describe('POST /api/x402/echo', () => {
	it('reflects the request and decodes+redacts an X-PAYMENT header', async () => {
		const header = encodeHeader(eip3009Envelope());
		const { status, body } = await invoke(echoHandler, {
			url: '/api/x402/echo',
			headers: { 'x-payment': header },
			body: { requirement: { amount: '10000', payTo: PAY_TO, network: 'eip155:8453' } },
		});
		expect(status).toBe(200);
		expect(body.method).toBe('POST');
		// header echoed but redacted
		expect(body.headers['x-payment']).toContain('redacted');
		// decoded envelope + local verdict, no full signature anywhere
		expect(body.payment.verdict.valid).toBe(true);
		expect(JSON.stringify(body)).not.toContain('de'.repeat(65));
		expect(body.payment.note).toMatch(/no settlement/i);
	});

	it('accepts paymentHeader in the body and reports a malformed one as decodable:false', async () => {
		const { status, body } = await invoke(echoHandler, {
			body: { paymentHeader: Buffer.from('not json').toString('base64') },
		});
		expect(status).toBe(200);
		expect(body.payment.decodable).toBe(false);
	});

	it('works as a bare GET with no payment', async () => {
		const { status, body } = await invoke(echoHandler, { method: 'GET' });
		expect(status).toBe(200);
		expect(body.payment).toBeUndefined();
	});
});

// ── Handler: debug ──────────────────────────────────────────────────────────
describe('POST /api/x402/debug', () => {
	it('diagnoses a broken exchange with fix guidance', async () => {
		const { status, body } = await invoke(debugHandler, {
			url: '/api/x402/debug',
			body: {
				challenge: { x402Version: 2, accepts: [{ scheme: 'exact', network: 'eip155:8453', amount: '10000', payTo: PAY_TO }] },
				payment: { x402Version: 1, network: 'base', payload: { authorization: { value: '0.01', to: PAY_TO } } },
			},
		});
		expect(status).toBe(200);
		expect(body.ok).toBe(false);
		expect(body.count).toBeGreaterThan(0);
		expect(body.findings.every((f) => f.fix && f.problem)).toBe(true);
	});

	it('rejects a GET', async () => {
		const { status } = await invoke(debugHandler, { method: 'GET', url: '/api/x402/debug' });
		expect(status).toBe(405);
	});
});

// ── Handler: verify-receipt ─────────────────────────────────────────────────
describe('POST /api/x402/verify-receipt', () => {
	it('confirms a valid attestation', async () => {
		const { status, body } = await invoke(verifyHandler, {
			url: '/api/x402/verify-receipt',
			body: { result: factCheckResult() },
		});
		expect(status).toBe(200);
		expect(body.attestation.verified).toBe(true);
	});

	it('denies a tampered attestation', async () => {
		const result = factCheckResult();
		const { body } = await invoke(verifyHandler, {
			url: '/api/x402/verify-receipt',
			body: { result: { ...result, confidence: 0.1 } },
		});
		expect(body.attestation.verified).toBe(false);
	});

	it('400s when nothing to verify', async () => {
		const { status, body } = await invoke(verifyHandler, { url: '/api/x402/verify-receipt', body: {} });
		expect(status).toBe(400);
		expect(body.error).toBe('nothing_to_verify');
	});

	it('reports an unsupported settlement network without throwing', async () => {
		const { status, body } = await invoke(verifyHandler, {
			url: '/api/x402/verify-receipt',
			body: { tx: { hash: 'abc', network: 'dogechain' } },
		});
		expect(status).toBe(200);
		expect(body.settlement.verified).toBe(false);
		expect(body.settlement.status).toBe('unsupported_network');
	});
});