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.

feat(zauth): instrument every paid x402 surface for Provider Hub telemetry

nirholas9b582b9f5f8a
diff --git a/api/_lib/x402-paid-endpoint.js b/api/_lib/x402-paid-endpoint.js
index ec744de5d..fcd3c1c10 100644
--- a/api/_lib/x402-paid-endpoint.js
+++ b/api/_lib/x402-paid-endpoint.js
@@ -28,7 +28,7 @@
// helper. Missing keys fall back to env (so a single override doesn't
// disable the other networks).
-import { cors, error, respondError } from './http.js';
+import { cors, error, respondError, wrap } from './http.js';
import { env } from './env.js';
import { clientIp } from './rate-limit.js';
import { logPaymentEvent } from './x402/audit-log.js';
@@ -59,16 +59,9 @@ import {
writeCachedResponse,
writeConflict,
} from './x402/payment-identifier-server.js';
-import {
- authenticateSiwx,
- declareSiwxExtensionFor,
- recordSiwxPayment,
-} from './siwx-server.js';
+import { authenticateSiwx, declareSiwxExtensionFor, recordSiwxPayment } from './siwx-server.js';
import { normalizeAddress } from './siwx-storage.js';
-import {
- buildOffersExtension,
- buildReceiptExtension,
-} from './x402/offer-receipt-server.js';
+import { buildOffersExtension, buildReceiptExtension } from './x402/offer-receipt-server.js';
import { recordReceipt } from './x402/receipt-storage.js';
import {
authenticateAuthHintsRequest,
@@ -281,7 +274,12 @@ export function paidEndpoint(spec) {
const pidTtlSeconds = paymentIdentifier.ttlSeconds;
const pidExtension = paymentIdentifierExtension(pidRequired);
- return async function paidHandler(req, res) {
+ // wrap() instruments the request for zauth Provider Hub telemetry (every
+ // paidEndpoint route is a monitored x402 surface) and converts any uncaught
+ // handler throw into the standard JSON error envelope. instrument() is
+ // idempotent, so dispatchers that are already wrap()-ed (wk.js,
+ // x402/service.js) don't double-report.
+ return wrap(async function paidHandler(req, res) {
const requestStartTime = Date.now();
if (cors(req, res, { methods: allowMethods, origins: '*' })) return;
if (req.method !== method.toUpperCase()) {
@@ -479,12 +477,7 @@ export function paidEndpoint(spec) {
if (err instanceof X402Error && err.status === 402) {
return send402(res, { ...challenge, error: err.message });
}
- return respondError(
- res,
- err.status || 500,
- err.code || 'internal_error',
- err,
- );
+ return respondError(res, err.status || 500, err.code || 'internal_error', err);
}
if (res.writableEnded) return;
res.setHeader('x-payment-bypass', `auth-hints:${result.principal.method}`);
@@ -552,12 +545,7 @@ export function paidEndpoint(spec) {
if (err instanceof X402Error && err.status === 402) {
return send402(res, { ...challenge, error: err.message });
}
- return respondError(
- res,
- err.status || 500,
- err.code || 'internal_error',
- err,
- );
+ return respondError(res, err.status || 500, err.code || 'internal_error', err);
}
if (res.writableEnded) return;
if (acResult.headers) {
@@ -605,12 +593,7 @@ export function paidEndpoint(spec) {
if (err instanceof X402Error && err.status === 402) {
return send402(res, { ...challenge, error: err.message });
}
- return respondError(
- res,
- err.status || 500,
- err.code || 'internal_error',
- err,
- );
+ return respondError(res, err.status || 500, err.code || 'internal_error', err);
}
if (res.writableEnded) return;
res.setHeader('x-siwx-address', auth.address);
@@ -830,5 +813,5 @@ export function paidEndpoint(spec) {
ttlSeconds: pidTtlSeconds,
});
}
- };
+ });
}
diff --git a/api/_lib/zauth.js b/api/_lib/zauth.js
index 25834dd3a..5520a1cd0 100644
--- a/api/_lib/zauth.js
+++ b/api/_lib/zauth.js
@@ -99,9 +99,9 @@ function buildMiddleware() {
enabled: refundEnabled,
privateKey: evmKey,
solanaPrivateKey: solKey,
- maxRefundUsd: Number(process.env.ZAUTH_REFUND_MAX_USD) || 0.10,
- dailyCapUsd: Number(process.env.ZAUTH_REFUND_DAILY_CAP_USD) || 25.00,
- monthlyCapUsd: Number(process.env.ZAUTH_REFUND_MONTHLY_CAP_USD) || 250.00,
+ maxRefundUsd: Number(process.env.ZAUTH_REFUND_MAX_USD) || 0.1,
+ dailyCapUsd: Number(process.env.ZAUTH_REFUND_DAILY_CAP_USD) || 25.0,
+ monthlyCapUsd: Number(process.env.ZAUTH_REFUND_MONTHLY_CAP_USD) || 250.0,
triggers: {
serverError: true,
emptyResponse: true,
@@ -155,12 +155,25 @@ function buildMiddleware() {
}
}
+// Paid x402 surfaces, by path. Three groups:
+// 1. MCP servers + payer/dispatcher routes (each one settles x402 payments).
+// 2. /api/x402/* paid services — every route here 402-challenges EXCEPT the
+// free metadata/read endpoints (admin console, DID document, buyer
+// receipt lookup), which must not pollute the public zauth registry.
+// 3. Agent payment routes (delegated x402 calls + invoice payments).
+const MONITORED_SERVERS =
+ /\/api\/(wk-x402|mcp|mcp-3d|mcp-agent|mcp-bazaar|pump-fun-mcp|ibm-mcp|x402-pay)(\/|$)/;
+const MONITORED_X402_FREE = /\/api\/x402\/(admin(\/|$)|did$|my-receipts$)/;
+const MONITORED_X402 = /\/api\/x402\/[^/]/;
+const MONITORED_AGENTS =
+ /\/api\/agents\/x402\/|\/api\/agents\/[^/]+\/x402\/|\/api\/agents\/payments\//;
+
function shouldMonitorReq(req) {
if (req.headers?.['x-payment-intent'] || req.headers?.['x-payment']) return true;
const p = req.path || '';
- return /\/api\/(wk-x402|mcp)(\/|$)|\/api\/agents\/x402\/|\/api\/agents\/[^/]+\/x402\/|\/api\/agents\/payments\//.test(
- p,
- );
+ if (MONITORED_SERVERS.test(p)) return true;
+ if (MONITORED_X402.test(p) && !MONITORED_X402_FREE.test(p)) return true;
+ return MONITORED_AGENTS.test(p);
}
function getMiddleware() {
@@ -248,11 +261,18 @@ function shimRequest(req) {
export function instrument(req, res) {
const mw = getMiddleware();
if (!mw) return false;
+ // Idempotency: dispatcher routes (wk.js, x402/service.js) run wrap() at the
+ // top level AND invoke paidEndpoint-built handlers (also wrap()-ed) inside —
+ // without this guard the SDK middleware would observe and report the same
+ // request twice.
+ if (req.__zauthInstrumented) return req.__zauthMonitored === true;
+ req.__zauthInstrumented = true;
try {
shimRequest(req);
shimResponse(res);
const monitored = shouldMonitorReq(req);
mw(req, res, () => {});
+ req.__zauthMonitored = monitored;
return monitored;
} catch (err) {
console.error('[zauth] middleware error:', err.message);
diff --git a/package.json b/package.json
index 40484def5..57deb4d93 100644
--- a/package.json
+++ b/package.json
@@ -100,6 +100,8 @@
"test:e2e": "playwright test",
"test:pages": "node scripts/test-pages.mjs",
"verify:ibm": "node scripts/verify-ibm-pages.mjs",
+ "verify:zauth": "node scripts/verify-zauth-runtime.mjs",
+ "zauth:register": "node scripts/zauth-register-endpoints.mjs",
"test:all": "npm run test && npm run test:pages",
"verify": "prettier --check . && vite build",
"format": "prettier --write .",
diff --git a/scripts/verify-zauth-runtime.mjs b/scripts/verify-zauth-runtime.mjs
index 76ef82b1c..df7ae9c42 100644
--- a/scripts/verify-zauth-runtime.mjs
+++ b/scripts/verify-zauth-runtime.mjs
@@ -118,6 +118,58 @@ results.push(
expectMonitored: true,
}),
);
+// Paid x402 service WITHOUT a payment header — path-matched since the
+// /api/x402/* monitor expansion (previously only header-matched).
+results.push(
+ await runCase({
+ name: '402 challenge on /api/x402/tutor (path-matched, no header)',
+ req: { url: '/api/x402/tutor', method: 'POST' },
+ statusCode: 402,
+ expectMonitored: true,
+ }),
+);
+// Paid MCP variants are their own endpoints, not sub-paths of /api/mcp.
+results.push(
+ await runCase({
+ name: '402 challenge on /api/mcp-bazaar (paid MCP variant)',
+ req: { url: '/api/mcp-bazaar', method: 'POST' },
+ statusCode: 402,
+ expectMonitored: true,
+ }),
+);
+results.push(
+ await runCase({
+ name: '402 challenge on /api/pump-fun-mcp (paid MCP variant)',
+ req: { url: '/api/pump-fun-mcp', method: 'POST' },
+ statusCode: 402,
+ expectMonitored: true,
+ }),
+);
+// Free x402 metadata/read endpoints must NOT pollute the registry.
+results.push(
+ await runCase({
+ name: 'free GET /api/x402/my-receipts (must be ignored)',
+ req: { url: '/api/x402/my-receipts?address=0xabc', method: 'GET' },
+ statusCode: 200,
+ expectMonitored: false,
+ }),
+);
+results.push(
+ await runCase({
+ name: 'free GET /api/x402/did (must be ignored)',
+ req: { url: '/api/x402/did', method: 'GET' },
+ statusCode: 200,
+ expectMonitored: false,
+ }),
+);
+results.push(
+ await runCase({
+ name: 'admin GET /api/x402/admin/skus (must be ignored)',
+ req: { url: '/api/x402/admin/skus', method: 'GET' },
+ statusCode: 200,
+ expectMonitored: false,
+ }),
+);
// Unrelated traffic must NOT be reported.
results.push(
await runCase({
@@ -129,5 +181,8 @@ results.push(
);
const allPass = initOk && results.every(Boolean);
-console.log('\nRESULT:', allPass ? 'PASS ✓ — telemetry fires for monitored x402 traffic' : 'FAIL ✗');
+console.log(
+ '\nRESULT:',
+ allPass ? 'PASS ✓ — telemetry fires for monitored x402 traffic' : 'FAIL ✗',
+);
process.exitCode = allPass ? 0 : 1;
diff --git a/scripts/zauth-register-endpoints.mjs b/scripts/zauth-register-endpoints.mjs
new file mode 100644
index 000000000..dd5f2544f
--- /dev/null
+++ b/scripts/zauth-register-endpoints.mjs
@@ -0,0 +1,138 @@
+// Sweep every paid x402 surface on production so the zauth Provider Hub SDK
+// observes — and auto-registers — each endpoint.
+//
+// node scripts/zauth-register-endpoints.mjs [--base https://three.ws]
+//
+// How it works: the deployed @zauthx402/sdk middleware (api/_lib/zauth.js)
+// reports every monitored request to the Provider Hub, and zauth registers
+// endpoints from observed traffic ("Auto-registered via SDK"). A request with
+// no X-PAYMENT header costs nothing — paid routes answer with a 402 challenge
+// that also carries pricing for the registry. So one unauthenticated request
+// per route is enough to take the Provider Hub from one endpoint to the full
+// catalog.
+//
+// After the sweep, the script polls zauth's public directory API and prints
+// every registered three.ws endpoint so the result is verifiable from here.
+
+const BASE = (() => {
+ const i = process.argv.indexOf('--base');
+ return (i >= 0 && process.argv[i + 1]) || process.env.THREE_WS_BASE || 'https://three.ws';
+})();
+const DIRECTORY_API = 'https://api.zauth.inc/api/directory';
+const MCP_BODY = JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'tools/list' });
+
+// Static catalog of paid surfaces. Methods mirror each route's paidEndpoint()
+// spec / handler. Dynamic routes (/api/x402/service/<slug>, per-agent x402
+// actions) register themselves as real traffic flows — they have no static
+// path to sweep.
+const ENDPOINTS = [
+ // MCP servers (Streamable HTTP, JSON-RPC) — each settles x402 payments.
+ { path: '/api/mcp', method: 'POST', body: MCP_BODY, json: true },
+ { path: '/api/mcp-3d', method: 'POST', body: MCP_BODY, json: true },
+ { path: '/api/mcp-agent', method: 'POST', body: MCP_BODY, json: true },
+ { path: '/api/mcp-bazaar', method: 'POST', body: MCP_BODY, json: true },
+ { path: '/api/pump-fun-mcp', method: 'POST', body: MCP_BODY, json: true },
+ { path: '/api/ibm-mcp', method: 'POST', body: MCP_BODY, json: true },
+ // Worker dispatcher x402 surface.
+ { path: '/api/wk-x402', method: 'GET' },
+ // /api/x402/* paid services.
+ { path: '/api/x402/agent-reputation', method: 'GET' },
+ // Param-gated routes use each handler's own documented INPUT_EXAMPLE so the
+ // request clears input validation and draws the 402 (which carries pricing).
+ { path: '/api/x402/asset-download?slug=pole-dancer-rumba', method: 'GET' },
+ { path: '/api/x402/cosmetic-purchase?id=skin-midnight&account=g_5f3c9a21b8', method: 'GET' },
+ { path: '/api/x402/crypto-intel', method: 'POST', json: true, body: '{}' },
+ { path: '/api/x402/dance-tip', method: 'GET' },
+ { path: '/api/x402/fact-check', method: 'POST', json: true, body: '{}' },
+ { path: '/api/x402/forge', method: 'POST', json: true, body: '{}' },
+ { path: '/api/x402/mint-to-mesh', method: 'GET' },
+ { path: '/api/x402/mint-to-mesh-batch', method: 'POST', json: true, body: '{}' },
+ { path: '/api/x402/model-check', method: 'GET' },
+ { path: '/api/x402/onchain-identity-verify', method: 'GET' },
+ { path: '/api/x402/pay-by-name?name=three.ws', method: 'GET' },
+ { path: '/api/x402/permit2-paid-demo', method: 'GET' },
+ { path: '/api/x402/pump-agent-audit', method: 'GET' },
+ { path: '/api/x402/pump-launch', method: 'POST', json: true, body: '{}' },
+ { path: '/api/x402/skill-call?skill=wallet-balance', method: 'GET' },
+ { path: '/api/x402/skill-marketplace', method: 'GET' },
+ { path: '/api/x402/symbol-availability', method: 'GET' },
+ { path: '/api/x402/tutor', method: 'POST', json: true, body: '{}' },
+ { path: '/api/x402/vanity', method: 'GET' },
+];
+
+async function touch({ path, method, body, json }) {
+ const headers = { 'user-agent': 'three.ws-zauth-register-sweep' };
+ if (json) headers['content-type'] = 'application/json';
+ try {
+ const res = await fetch(BASE + path, {
+ method,
+ headers,
+ body,
+ signal: AbortSignal.timeout(20_000),
+ });
+ // Drain the body so the lambda finishes its full lifecycle (and the
+ // zauth drain() hold-open isn't cut short by an aborted socket).
+ await res.arrayBuffer().catch(() => {});
+ return { path, method, status: res.status };
+ } catch (err) {
+ return { path, method, status: 0, error: err.message };
+ }
+}
+
+async function sweep() {
+ console.log(`— zauth endpoint registration sweep → ${BASE} —\n`);
+ const results = [];
+ // Small batches: enough parallelism to finish fast, low enough to stay
+ // polite to our own production functions.
+ for (let i = 0; i < ENDPOINTS.length; i += 4) {
+ const batch = ENDPOINTS.slice(i, i + 4);
+ results.push(...(await Promise.all(batch.map(touch))));
+ }
+ let challenged = 0;
+ let observed = 0;
+ let failed = 0;
+ for (const r of results) {
+ // 402 = challenge served with pricing (ideal). Any other HTTP response
+ // still drove the SDK observation; 0 = network failure, not observed.
+ const tag = r.status === 402 ? '402 ✓' : r.status > 0 ? `${r.status} ·` : `FAIL ${r.error}`;
+ if (r.status === 402) challenged++;
+ if (r.status > 0) observed++;
+ else failed++;
+ console.log(` ${tag} ${r.method.padEnd(4)} ${r.path}`);
+ }
+ console.log(
+ `\nobserved ${observed}/${ENDPOINTS.length} (402-challenged: ${challenged}, unreachable: ${failed})`,
+ );
+ return failed === 0;
+}
+
+async function confirmRegistry() {
+ console.log('\n— zauth public directory (api.zauth.inc) —');
+ try {
+ const res = await fetch(`${DIRECTORY_API}?search=three.ws&limit=100`, {
+ signal: AbortSignal.timeout(15_000),
+ });
+ const data = await res.json();
+ const endpoints = data?.endpoints || [];
+ console.log(
+ `registered three.ws endpoints: ${data?.pagination?.total ?? endpoints.length} ` +
+ `(verified: ${data?.stats?.verified ?? '?'})`,
+ );
+ for (const e of endpoints) {
+ console.log(
+ ` ${e.verified ? '✓' : '·'} ${e.method.padEnd(4)} ${e.url} [${e.status}]`,
+ );
+ }
+ // Telemetry is ingested asynchronously upstream; a sparse list right
+ // after the sweep is expected. Re-run this script (or just this check)
+ // after a few minutes to watch the registry fill in.
+ return endpoints.length;
+ } catch (err) {
+ console.log(`directory query failed: ${err.message}`);
+ return -1;
+ }
+}
+
+const swept = await sweep();
+await confirmRegistry();
+process.exitCode = swept ? 0 : 1;