x402-listing / tree / src/app.js ยท raw (this view has old GitHub links rewritten for the mirror; raw is byte-exact)
// YourAITools Listings: paid listing services for youraitools.co (a directory of AI tools), paid in USDC over x402.
//   POST /v1/fast-track  PAID $19  review within 24 h; refunded if rejected
//   POST /v1/launch      PAID $49  fast-track + 30 days Featured + one newsletter line once there are subscribers
//   POST /v1/featured    PAID $29  30 days Featured (badge, pinned in category); refunded if rejected
//     body {tool_url, name, contact_email, category[, description, notes]} is validated BEFORE payment:
//     invalid -> 400 (no 402, nobody pays); empty body / {} / GET / HEAD -> 402 terms (discovery probes).
//   GET  /v1/status/<ref>         free  status (no email, no payer address)
//   GET  /v1/tiers                free  tiers, prices, terms
//   GET  /v1/admin/list           admin (Bearer LISTING_ADMIN_TOKEN) every submission incl. email and payer
//   GET  /v1/admin/<ref>          admin one submission
//   POST /v1/admin/<ref>          admin {status: approved|rejected|refunded|received, note?, refund_tx?, refund?, public_note?}
//   GET / /health /openapi.json /.well-known/x402 /v1/stats   free
// Refunds are NEVER sent by this Worker: a rejection sets refund_pending; a person sends the USDC and records refund_tx.
import { Hono } from 'hono';
import { cors } from 'hono/cors';
import { paymentMiddleware, x402ResourceServer } from '@x402/hono';
import { ExactEvmScheme } from '@x402/evm/exact/server';
import { declareDiscoveryExtension, bazaarResourceServerExtension } from '@x402/extensions/bazaar';
import { multiNetworkRoutes, registerNetworks, supportedKinds, discoveryNetworks, networkStats, networkInfo } from './networks.js';
import { ROUTE_META } from './service-meta.js';
import { ResilientFacilitatorClient } from './facilitator.js';
import { selectFacilitator } from './facilitator-select.js';
import { DEFAULTS } from './config.js';
import { Stats, paidRouteStats, isSmoke, waitUntilOf } from './stats.js';
import { x402v1 } from './x402v1.js';
import { TIER_LIST, TIERS, usd, HOUR, STATUSES } from './tiers.js';
import { TERMS, TERMS_POINTS, TERMS_SHORT } from './terms.js';
import { validateSubmission, isEmptyBody } from './validate.js';
import { REF_RE, newRef, publicView, adminView } from './registry.js';
import { openapiDoc, wellKnownX402, LOGO_SVG, SUBMISSION_SCHEMA } from './discovery.js';
import { prefersHtml, landingHtml } from './landing.js';

export const VERSION = '0.1.0';
export const SOURCE_URL = 'https://agentgate-source.pages.dev/x402-listing/';
const USDC = { 'eip155:8453': '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913', 'eip155:84532': '0x036CbD53842c5426634e7929541eC2318f3dCF7e' };
export const EXAMPLE_BODY = { tool_url: 'https://example.com', name: 'Example Tool', contact_email: 'you@example.com', category: 'x402 API' };
export const receiptExample = (t) => ({ ref: 'LST-EXAMPLE000', status: 'received', tier: t.id, review_by: '2026-10-23T18:00:00.000Z', status_url: 'https://api.youraitools.co/listing/v1/status/LST-EXAMPLE000' });
// Kept under ~380 chars: CDP rejects payment payloads whose resource.description is much longer (seen live 2026-10-22).
export const describe = (t) => `YourAITools listing (${usd(t.amount)} USDC): ${t.short}. POST JSON {tool_url,name,contact_email,category}; invalid bodies get 400 before payment. Reviewed for legitimacy and fit; payment does not guarantee approval. Rejected = refunded manually in USDC. No traffic or revenue promises.`;

const noFormat = (o) => JSON.parse(JSON.stringify(o, (k, v) => (k === 'format' ? undefined : v))); // Bazaar's validator has no uri/email formats
export function routesConfig({ network, payTo, publicUrl }) {
  const out = {};
  for (const t of TIER_LIST) {
    const base = { ...(publicUrl ? { resource: `${publicUrl.replace(/\/$/, '')}${t.path}` } : {}), accepts: { scheme: 'exact', price: t.price, network, payTo, maxTimeoutSeconds: 120 }, description: describe(t), mimeType: 'application/json', ...ROUTE_META };
    const output = { example: receiptExample(t) };
    out[`GET ${t.path}`] = { ...base, extensions: { ...declareDiscoveryExtension({ input: {}, output }) } };
    out[`POST ${t.path}`] = { ...base, extensions: { ...declareDiscoveryExtension({ bodyType: 'json', input: EXAMPLE_BODY, inputSchema: noFormat(SUBMISSION_SCHEMA), output }) } };
  }
  return out;
}

const clientIp = (c) => c.req.header('cf-connecting-ip') || c.req.header('x-forwarded-for')?.split(',')[0]?.trim() || 'unknown';
async function limited(limiter, c) {
  if (!limiter?.limit) return false;
  try { const { success } = await limiter.limit({ key: clientIp(c) }); return !success; } catch { return false; }
}
const NS = { 'cache-control': 'no-store' };
const bad = (c, message, status = 400, error = 'bad_request', extra = {}) => c.json({ error, message, ...extra }, status, NS);
const unb64 = (s) => JSON.parse(decodeURIComponent(escape(atob(s))));
export function paymentOf(res) {
  const h = res?.headers?.get('PAYMENT-RESPONSE') || res?.headers?.get('X-PAYMENT-RESPONSE');
  if (!h) return null;
  try { const p = unb64(h); return p && p.success !== false ? { network: p.network || null, transaction: p.transaction || null, payer: p.payer || null } : null; } catch { return null; }
}
const retry = async (fn, n = 3) => { let e; for (let i = 0; i < n; i++) { try { return await fn(); } catch (x) { e = x; } } throw e; };
const V1_NET = { base: 'eip155:8453', 'base-sepolia': 'eip155:84532' };

/** Constant-time bearer check against env.LISTING_ADMIN_TOKEN (compares SHA-256 digests). Fails closed when unset. */
async function adminOk(c, token) {
  if (!token || String(token).length < 32) return { ok: false, res: bad(c, 'Admin API disabled (no token configured).', 503, 'admin_disabled') };
  const m = (c.req.header('authorization') || '').trim().match(/^Bearer\s+(\S+)$/i);
  const given = m ? m[1] : '';
  const h = async (s) => new Uint8Array(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(s)));
  const [a, b] = await Promise.all([h(given), h(String(token))]);
  let diff = given ? 0 : 1; for (let i = 0; i < a.length; i++) diff |= a[i] ^ b[i];
  if (diff) { c.header('WWW-Authenticate', 'Bearer realm="listing-admin"'); return { ok: false, res: bad(c, 'Missing or wrong admin token.', 401, 'unauthorized') }; }
  return { ok: true };
}

/**
 * @param {object} [opts] payTo, network, facilitatorUrl, publicUrl, facilitatorClient (tests), registry (DO namespace;
 *   default c.env.REGISTRY), adminToken (default c.env.LISTING_ADMIN_TOKEN), stats, freeLimiter, v1FetchImpl, cdpDeps, now
 */
export function createApp(opts = {}) {
  const cfg = { ...DEFAULTS, ...Object.fromEntries(Object.entries(opts).filter(([, v]) => v !== undefined)) };
  const stats = opts.stats || new Stats(undefined);
  const now = opts.now || (() => Date.now());
  const fac = selectFacilitator(cfg, opts.cdpDeps);
  const facilitatorClient = opts.facilitatorClient || new ResilientFacilitatorClient({ url: fac.url, createAuthHeaders: fac.createAuthHeaders, name: fac.name, network: cfg.network, kinds: supportedKinds(cfg), staticSupported: opts.staticSupported ?? true });
  const resourceServer = new x402ResourceServer(facilitatorClient).register(cfg.network, new ExactEvmScheme()).registerExtension(bazaarResourceServerExtension);
  registerNetworks(resourceServer, cfg, ExactEvmScheme);
  const origin = (c) => (cfg.publicUrl || new URL(c.req.url).origin).replace(/\/$/, '');
  const count = (c, ev) => { if (!isSmoke(c)) stats.hit(ev, waitUntilOf(c)); };
  const registry = (c) => { const ns = opts.registry || c.env?.REGISTRY; return ns ? ns.get(ns.idFromName('registry')) : null; };
  const token = (c) => (opts.adminToken !== undefined ? opts.adminToken : c.env?.LISTING_ADMIN_TOKEN);
  const later = (c, p) => { const w = waitUntilOf(c); if (w) w(p.catch(() => {})); else p.catch(() => {}); };

  const app = new Hono();
  app.use('*', discoveryNetworks(cfg));
  app.use('*', networkStats({ hit: (e, w) => stats.hit(e, w) }, { isSmoke, waitUntilOf }));
  app.use('*', cors({ origin: '*', allowMethods: ['GET', 'POST', 'OPTIONS'], allowHeaders: ['Content-Type', 'Accept', 'PAYMENT-SIGNATURE', 'X-PAYMENT'], exposeHeaders: ['PAYMENT-REQUIRED', 'PAYMENT-RESPONSE', 'X-PAYMENT-RESPONSE'], maxAge: 86400 }));

  const tiersDoc = (c) => TIER_LIST.map((t) => ({ id: t.id, label: t.label, method: 'POST', path: t.path, url: `${origin(c)}${t.path}`, price: t.price, price_usd: usd(t.amount), amount_atomic: String(t.amount), review_within_hours: t.reviewHours, featured_days: t.featuredDays, newsletter_mention: t.newsletter ? 'once the newsletter has subscribers (none yet)' : false, what: t.what }));
  const info = (c) => ({
    name: 'YourAITools Listings',
    kind: 'service',
    description: 'Paid listing services for youraitools.co, a directory of AI tools and x402 APIs. Pay in USDC with one x402 call: fast-track review ($19), Launch bundle ($49) or Featured for 30 days ($29). Free listing stays free and is the default.',
    tiers: tiersDoc(c),
    request: { content_type: 'application/json', body: EXAMPLE_BODY, required: SUBMISSION_SCHEMA.required, optional: ['description', 'notes'], validated_before_payment: true },
    response: receiptExample(TIERS['fast-track']),
    status: `${origin(c)}/v1/status/<ref>`, statuses: STATUSES,
    payment: { protocol: 'x402 v2 (PAYMENT-SIGNATURE) on all networks, v1 (X-PAYMENT) on Base', asset: 'USDC', networks: networkInfo(cfg).length ? networkInfo(cfg) : [{ network: cfg.network, payTo: cfg.payTo }], credits: 'not accepted (USDC x402 only)' },
    refunds: 'Rejected submissions become refund_pending and are refunded manually in USDC to the paying address on the same network within 3 business days.',
    terms: TERMS_POINTS,
    free_listing: 'https://youraitools.co/submit', contact: 'hello@youraitools.co',
    source: SOURCE_URL, endpoint: origin(c), version: VERSION,
  });
  app.get('/', (c) => { c.header('Vary', 'Accept'); if (prefersHtml(c.req.header('accept'))) return c.html(landingHtml({ origin: origin(c), info: info(c) })); return c.json(info(c)); });
  app.get('/health', (c) => c.json({ ok: true, version: VERSION, registry: !!(opts.registry || c.env?.REGISTRY), admin: !!token(c) }));
  const disc = (c) => ({ origin: origin(c), network: cfg.network, payTo: cfg.payTo, asset: USDC[cfg.network] });
  app.get('/openapi.json', (c) => { c.header('Cache-Control', 'public, max-age=300'); return c.json(openapiDoc(disc(c))); });
  app.get('/.well-known/x402', (c) => { c.header('Cache-Control', 'public, max-age=300'); return c.json(wellKnownX402(disc(c))); });
  for (const p of ['/favicon.svg', '/favicon.ico', '/logo.svg']) app.get(p, (c) => c.body(LOGO_SVG, 200, { 'content-type': 'image/svg+xml', 'cache-control': 'public, max-age=86400' }));
  app.get('/v1/stats', async (c) => { c.header('Cache-Control', 'public, max-age=60'); return c.json(await stats.summary(30)); });
  app.get('/v1/tiers', (c) => { c.header('Cache-Control', 'public, max-age=300'); return c.json({ tiers: tiersDoc(c), terms: TERMS_POINTS }); });

  // ---- free status ----
  app.get('/v1/status/:ref', async (c) => {
    if (await limited(opts.freeLimiter, c)) { c.header('Retry-After', '60'); return bad(c, 'Rate limited (per IP per minute).', 429, 'rate_limited'); }
    const ref = String(c.req.param('ref') || '').toUpperCase();
    if (!REF_RE.test(ref)) return bad(c, 'ref looks like LST- plus 10 characters.', 404, 'not_found');
    const reg = registry(c); if (!reg) return bad(c, 'Storage unavailable, retry shortly.', 503, 'unavailable');
    const r = await reg.get({ ref });
    if (!r.ok || r.record.status === 'pending_payment') return bad(c, 'Unknown ref.', 404, 'not_found');
    count(c, 'status');
    return c.json(publicView(r.record, origin(c)), 200, NS);
  });

  // ---- admin (YourAITools) ----
  app.get('/v1/admin/list', async (c) => {
    const a = await adminOk(c, token(c)); if (!a.ok) return a.res;
    const reg = registry(c); if (!reg) return bad(c, 'Storage unavailable.', 503, 'unavailable');
    const status = c.req.query('status');
    if (status && !STATUSES.includes(status) && status !== 'pending_payment') return bad(c, `status must be one of ${STATUSES.join(', ')}`);
    const r = await reg.list({ status: status || undefined, includePending: c.req.query('pending') === '1' });
    return c.json({ count: r.records.length, generated_at: new Date(now()).toISOString(), submissions: r.records.map(adminView) }, 200, NS);
  });
  app.get('/v1/admin/:ref', async (c) => {
    const a = await adminOk(c, token(c)); if (!a.ok) return a.res;
    const reg = registry(c); if (!reg) return bad(c, 'Storage unavailable.', 503, 'unavailable');
    const r = await reg.get({ ref: String(c.req.param('ref')).toUpperCase() });
    if (!r.ok) return bad(c, 'Unknown ref.', 404, 'not_found');
    return c.json(adminView(r.record), 200, NS);
  });
  app.post('/v1/admin/:ref', async (c) => {
    const a = await adminOk(c, token(c)); if (!a.ok) return a.res;
    let b; try { b = await c.req.json(); } catch { return bad(c, 'Send JSON: {"status":"approved|rejected|refunded|received","note":"..."}'); }
    if (!b || typeof b !== 'object') return bad(c, 'Send a JSON object.');
    const action = String(b.status || '');
    if (!['approved', 'rejected', 'refund_pending', 'refunded', 'received'].includes(action)) return bad(c, 'status must be approved, rejected, refund_pending, refunded or received.');
    const reg = registry(c); if (!reg) return bad(c, 'Storage unavailable.', 503, 'unavailable');
    const r = await reg.setStatus({ ref: String(c.req.param('ref')).toUpperCase(), action, note: typeof b.note === 'string' ? b.note : undefined, refund_tx: b.refund_tx, refund: b.refund, public_note: b.public_note, featured_from: b.featured_from, by: typeof b.by === 'string' ? b.by : 'admin', now: now() });
    if (!r.ok) return bad(c, r.message || r.reason, r.http || 400, r.reason);
    count(c, `admin:${r.record.status}`);
    return c.json({ ok: true, submission: adminView(r.record), public: publicView(r.record, origin(c)) }, 200, NS);
  });

  // ---- paid routes ----
  const v1s = [];
  for (const t of TIER_LIST) {
    // Outermost: after x402 has settled (or not), finalise. The receipt (ref) only leaves in a settled 200.
    app.use(t.path, async (c, next) => {
      await next();
      const ref = c.get('pendingRef'); if (!ref) return;
      const reg = registry(c);
      const pay = c.res && c.res.status === 200 ? paymentOf(c.res) : null;
      if (!pay) { later(c, retry(() => reg.cancel({ ref }))); return; }
      if (pay.network && V1_NET[pay.network]) pay.network = V1_NET[pay.network];
      let rec = null;
      try { rec = (await retry(() => reg.confirm({ ref, payment: pay, now: now() }))).record; }
      catch (e) { console.error(`listing: ${ref} settled (${pay.transaction}) but confirm failed: ${e && e.message}`); later(c, retry(() => reg.confirm({ ref, payment: pay, now: now() }), 5)); }
      count(c, [`sold:${t.id}`]);
      try {
        const body = await c.res.clone().json();
        if (rec) { body.review_by = new Date(rec.review_by).toISOString(); }
        body.payment = { network: pay.network, transaction: pay.transaction, payer: pay.payer, amount_usd: usd(t.amount) };
        const headers = new Headers(c.res.headers); headers.delete('content-length');
        c.res = undefined; c.res = new Response(JSON.stringify(body), { status: 200, headers });
      } catch { /* keep the receipt as built */ }
    });
    app.use(t.path, paidRouteStats(stats, t.id));
    // Validate BEFORE payment. Empty body / {} -> fall through to the 402 terms; anything else must be a valid submission.
    app.use(t.path, async (c, next) => {
      if (c.req.method !== 'POST') return next();
      let text = '';
      try { text = await c.req.text(); } catch { return bad(c, 'Could not read the body.'); }
      if (new TextEncoder().encode(text).length > cfg.maxBodyBytes) return bad(c, `Body too large (max ${cfg.maxBodyBytes} bytes).`, 413, 'too_large');
      if (isEmptyBody(text)) return next();
      let body; try { body = JSON.parse(text); } catch { return bad(c, 'Body must be JSON: {"tool_url","name","contact_email","category"}. Nothing was charged.', 400, 'bad_request', { example: EXAMPLE_BODY }); }
      const v = validateSubmission(body);
      if (!v.ok) return bad(c, `Invalid submission (nothing was charged): ${v.errors.join('; ')}.`, 400, 'invalid_submission', { errors: v.errors, example: EXAMPLE_BODY });
      c.set('submission', v.value);
      return next();
    });
    v1s.push(x402v1({ path: t.path, amount: String(t.amount), asset: USDC[cfg.network], payTo: cfg.payTo, network: cfg.network, description: describe(t), mimeType: 'application/json', publicUrl: cfg.publicUrl, facilitatorUrl: cfg.facilitatorUrl, fetchImpl: opts.v1FetchImpl,
      outputSchema: { input: { type: 'http', method: 'POST', discoverable: true, bodyType: 'json', bodyFields: Object.fromEntries(Object.entries(SUBMISSION_SCHEMA.properties).map(([k, v]) => [k, { type: 'string', required: SUBMISSION_SCHEMA.required.includes(k), description: v.description || k }])) }, output: receiptExample(t) } }));
  }
  for (const v of v1s) app.use(v.middleware);
  const skipV1 = (mw) => (c, next) => (c.get('x402v1') ? next() : mw(c, next));
  app.use(skipV1(paymentMiddleware(multiNetworkRoutes(routesConfig(cfg), cfg), resourceServer, undefined, undefined, opts.syncFacilitatorOnStart ?? true)));
  for (const t of TIER_LIST) {
    // Reached only with a verified payment. Any 4xx/5xx here means x402 does not settle (nothing is charged).
    app.on(['GET', 'POST'], t.path, async (c) => {
      const sub = c.get('submission');
      if (!sub) return bad(c, 'Paid requests must POST the submission JSON {"tool_url","name","contact_email","category"}. Nothing was charged.', 400, 'missing_body', { example: EXAMPLE_BODY });
      const reg = registry(c); if (!reg) return bad(c, 'Storage unavailable; nothing was charged. Retry shortly.', 503, 'unavailable');
      let made = null; let ref;
      for (let i = 0; i < 3 && !made?.ok; i++) { ref = newRef(); try { made = await reg.create({ ref, tier: t.id, submission: sub, now: now() }); } catch { made = null; } }
      if (!made?.ok) return bad(c, 'Could not store the submission; nothing was charged. Retry.', 503, 'unavailable');
      c.set('pendingRef', ref);
      return c.json({ ref, status: 'received', tier: t.id, tier_label: t.label, price_usd: usd(t.amount), name: sub.name, tool_url: sub.tool_url, category: sub.category,
        review_by: new Date(now() + t.reviewHours * HOUR).toISOString(), status_url: `${origin(c)}/v1/status/${ref}`,
        ...(t.featuredDays ? { featured: `${t.featuredDays} days on youraitools.co from approval` } : {}),
        ...(t.newsletter ? { newsletter: 'one mention once the newsletter has subscribers (none yet)' } : {}),
        next: 'A person reviews it for legitimacy and fit. If rejected, the full amount is refunded manually in USDC to the paying address on the same network within 3 business days.',
        contact: 'hello@youraitools.co (quote your ref)', terms: TERMS }, 200, NS);
    });
  }
  return app;
}

agentgate-source: code mirror on Cloudflare Pages. All repos