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.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
feat: bazaar listing/search, x402 subscriptions + paid-assets + siwx schemas
nirholasf041cf666fd2
diff --git a/api/_lib/env.js b/api/_lib/env.jsindex 313f0b27f..97117cd93 100644--- a/api/_lib/env.js+++ b/api/_lib/env.js@@ -246,6 +246,44 @@ export const env = {return opt('BSC_OPERATOR_KEY');},+ // ── x402 Offer & Receipt extension (USE-17) ─────────────────────────────+ // DEDICATED signing key for the offer-receipt extension. MUST NOT be any+ // X402_PAY_TO_* key — those receive funds; this one only signs commitments.+ // Generate with: node -e "console.log(require('viem/accounts').generatePrivateKey())"+ // When unset, the extension is silently disabled (no signed offers/receipts+ // are emitted; 402/200 bodies stay protocol-compatible without them).+ get OFFER_RECEIPT_SIGNING_PRIVATE_KEY() {+ return opt('OFFER_RECEIPT_SIGNING_PRIVATE_KEY');+ },+ // "eip712" (default — uses the dedicated EOA above as a did:pkh signer) or+ // "jws" (uses a JWK private key from OFFER_RECEIPT_JWK to sign Ed25519 /+ // ES256K with a did:web kid resolved at /.well-known/did.json).+ get OFFER_RECEIPT_FORMAT() {+ return opt('OFFER_RECEIPT_FORMAT', 'eip712');+ },+ // JWK private key (JSON string) used when OFFER_RECEIPT_FORMAT=jws. The+ // public components are published in /.well-known/did.json so verifiers can+ // resolve the kid back to a key. Generate with `jose newkey -s 256 -t OKP -c EdDSA`.+ get OFFER_RECEIPT_JWK() {+ return opt('OFFER_RECEIPT_JWK');+ },+ // JWS algorithm (default EdDSA — Ed25519). Other supported: ES256K (secp256k1).+ get OFFER_RECEIPT_JWS_ALG() {+ return opt('OFFER_RECEIPT_JWS_ALG', 'EdDSA');+ },+ // Bare hostname for did:web identifiers (omit scheme + path). Used to build+ // kid = `did:web:<SERVER_DOMAIN>#key-1` and the matching `id` field in+ // /.well-known/did.json. Defaults to the host parsed from APP_ORIGIN.+ get SERVER_DOMAIN() {+ const explicit = opt('SERVER_DOMAIN');+ if (explicit) return explicit;+ try {+ return new URL(this.APP_ORIGIN).host;+ } catch {+ return 'three.ws';+ }+ },+// zauthx402 SDK — optional telemetry for x402 endpoints. When unset,// the SDK is not initialized and request monitoring is skipped.get ZAUTH_API_KEY() {diff --git a/api/_lib/migrations/2026-05-21-paid-assets.sql b/api/_lib/migrations/2026-05-21-paid-assets.sqlnew file mode 100644index 000000000..57a1f9d37--- /dev/null+++ b/api/_lib/migrations/2026-05-21-paid-assets.sql@@ -0,0 +1,26 @@+-- Migration: paid_assets catalog for /api/x402/asset-download.+-- Apply: psql "$DATABASE_URL" -f api/_lib/migrations/2026-05-21-paid-assets.sql+-- Idempotent.+--+-- Canonical "buy once, re-download forever" 3D-asset bazaar: creators upload a+-- GLB / avatar / accessory to R2, price it in USDC atomics, and the asset is+-- served via the SIWX-enabled asset-download endpoint. Per-row payout overrides+-- let creators receive USDC directly to their own wallet; when NULL the global+-- env.X402_PAY_TO_* fallbacks apply (handled in api/_lib/x402-paid-endpoint.js).++CREATE TABLE IF NOT EXISTS paid_assets (+ id uuid PRIMARY KEY DEFAULT gen_random_uuid(),+ slug text NOT NULL UNIQUE,+ title text NOT NULL,+ description text NOT NULL,+ mime_type text NOT NULL,+ size_bytes bigint NOT NULL,+ r2_key text NOT NULL,+ price_atomics text NOT NULL,+ creator_payto_base text,+ creator_payto_solana text,+ creator_payto_bsc text,+ created_at timestamptz NOT NULL DEFAULT now()+);++CREATE INDEX IF NOT EXISTS paid_assets_slug_idx ON paid_assets (slug);diff --git a/api/_lib/migrations/2026-05-21-siwx.sql b/api/_lib/migrations/2026-05-21-siwx.sqlnew file mode 100644index 000000000..2d0959856--- /dev/null+++ b/api/_lib/migrations/2026-05-21-siwx.sql@@ -0,0 +1,35 @@+-- Migration: Sign-In-With-X (SIWX, CAIP-122) payment-history + nonce tables.+-- Apply: psql "$DATABASE_URL" -f api/_lib/migrations/2026-05-21-siwx.sql+-- Idempotent.+--+-- These tables back the SIWxStorage adapter used by paidEndpoint(): a wallet+-- that has paid for a resource can re-access it by signing a CAIP-122 message+-- instead of paying again. Stored addresses follow the CAIP-122 payload exactly:+-- lowercase hex for EVM (`eip155:*`), Base58 for Solana (`solana:*`). The+-- adapter in api/_lib/siwx-storage.js normalizes before SELECT/INSERT — no CHECK+-- constraint here, since the canonical form differs by chain.++CREATE TABLE IF NOT EXISTS siwx_payments (+ resource text NOT NULL,+ address text NOT NULL,+ network text NOT NULL,+ paid_at timestamptz NOT NULL DEFAULT now(),+ expires_at timestamptz,+ last_used_at timestamptz,+ use_count integer NOT NULL DEFAULT 0,+ PRIMARY KEY (resource, address)+);++CREATE INDEX IF NOT EXISTS siwx_payments_expires_idx+ ON siwx_payments (expires_at)+ WHERE expires_at IS NOT NULL;++CREATE TABLE IF NOT EXISTS siwx_nonces (+ nonce text PRIMARY KEY,+ resource text NOT NULL,+ address text NOT NULL,+ used_at timestamptz NOT NULL DEFAULT now()+);++CREATE INDEX IF NOT EXISTS siwx_nonces_used_at_idx+ ON siwx_nonces (used_at);diff --git a/api/_lib/migrations/2026-05-21-x402-subscriptions.sql b/api/_lib/migrations/2026-05-21-x402-subscriptions.sqlnew file mode 100644index 000000000..9a1b87f01--- /dev/null+++ b/api/_lib/migrations/2026-05-21-x402-subscriptions.sql@@ -0,0 +1,42 @@+-- Migration: x402 subscription API keys + access bypass audit trail.+-- Apply: psql "$DATABASE_URL" -f api/_lib/migrations/2026-05-21-x402-subscriptions.sql+-- Idempotent.+--+-- USE-23 wiring: api/_lib/x402/api-keys.js + api/_lib/x402/access-control.js+-- read/write these tables. The onProtectedRequest hook installed by+-- installAccessControl() short-circuits the 402 challenge when a request+-- carries either INTERNAL_API_KEY (env), a subscription key (this table),+-- or an OAuth bearer with the route's required scope. Every bypass — and+-- every abort (invalid key, expired, rate-limited) — writes one row to+-- x402_access_log so USE-24 audit dashboards can reconstruct who used+-- which endpoint without paying.++create table if not exists x402_subscriptions (+ id text primary key, -- short id, surfaced in access-log captions+ name text not null, -- human-readable label (e.g. "Partner Acme")+ key_hash text not null unique, -- sha256(plaintext key); plaintext shown once at creation+ key_prefix text not null, -- "x402_live_<6char>" for UI display + log correlation+ rate_limit_per_minute integer not null default 60, -- sliding-window cap per route+ expires_at timestamptz, -- null = no expiry+ revoked_at timestamptz, -- null = active+ meta jsonb, -- contact, tier, notes — never PII required for billing+ created_by uuid references users(id) on delete set null,+ created_at timestamptz not null default now()+);++create index if not exists x402_subscriptions_prefix_idx on x402_subscriptions(key_prefix);+create index if not exists x402_subscriptions_active_idx on x402_subscriptions(revoked_at, expires_at);++create table if not exists x402_access_log (+ id uuid primary key default gen_random_uuid(),+ caller_id text not null, -- 'internal' | 'subscription:<id>' | 'oauth:<sub>' | 'abort:<reason>'+ route text not null, -- e.g. '/api/x402/model-check'+ reason text not null, -- short tag — full context in meta+ granted boolean not null, -- true = bypass granted, false = denied (abort)+ meta jsonb, -- ip, ua, requiredScope, etc.+ created_at timestamptz not null default now()+);++create index if not exists x402_access_log_caller_idx on x402_access_log(caller_id, created_at desc);+create index if not exists x402_access_log_route_idx on x402_access_log(route, created_at desc);+create index if not exists x402_access_log_created_idx on x402_access_log(created_at desc);diff --git a/api/_lib/x402-builder-code.js b/api/_lib/x402-builder-code.jsnew file mode 100644index 000000000..2f51f2303--- /dev/null+++ b/api/_lib/x402-builder-code.js@@ -0,0 +1,260 @@+// ERC-8021 Schema 2 builder-code extension for x402.+// Spec: https://eips.ethereum.org/EIPS/eip-8021+// x402 extension shape: /tmp/x402-docs/specs/extensions/builder_code.md+//+// On-chain attribution: when a facilitator settles an x402 payment, the+// settlement tx calldata is suffixed with a CBOR map of attribution fields+// — `a` (app code, set by the app), `s` (service codes, echoed/appended by+// the client), `w` (wallet/facilitator code, set at settlement). Off-chain+// parsers (Coinbase builder rewards, x402scan analytics) decode the suffix+// to attribute volume to the originating app and intermediaries.+//+// This module implements:+// - declareBuilderCodeExtension({ a, s? }) — for PaymentRequired+// - declareBuilderCodeOnPayload({ a, s? }) — for PaymentPayload+// - validateBuilderCode(code) — pattern check+// - encodeBuilderCodeSuffix({ a, w?, s? }) — CBOR + ERC-8021 frame+// - parseBuilderCodeSuffix(calldata) — decode from tx data+// - verifyClientEcho({ required, payload }) — anti-tampering check+//+// The ERC-8021 Schema 2 suffix wire-format (read end of calldata backwards):+// [ cborData ][ cborLength : 2B BE ][ schemaId : 0x02 ][ ercMarker : 16B ]+// Marker = constant 80218021_80218021_80218021_80218021 (16 bytes).++import { decode as cborDecode, encode as cborEncode } from 'cborg';++export const BUILDER_CODE = 'builder-code';++// Pattern from ERC-8021 + builder_code.md: lowercase alnum + underscore, 1-32.+const BUILDER_CODE_PATTERN = /^[a-z0-9_]{1,32}$/;++// 16-byte ERC-8021 marker (8x repetition of 0x8021).+const ERC8021_MARKER_HEX = '80218021802180218021802180218021';+const ERC8021_MARKER_BYTES = hexToBytes(ERC8021_MARKER_HEX);+const SCHEMA_ID = 0x02;++// JSON Schema (Draft 2020-12) the spec attaches to the extension `info` block.+const BUILDER_CODE_SCHEMA = Object.freeze({+ $schema: 'https://json-schema.org/draft/2020-12/schema',+ type: 'object',+ properties: {+ a: {+ type: 'string',+ pattern: '^[a-z0-9_]{1,32}$',+ description: 'App builder code',+ },+ w: {+ type: 'string',+ pattern: '^[a-z0-9_]{1,32}$',+ description: 'Wallet builder code',+ },+ s: {+ type: 'array',+ items: { type: 'string', pattern: '^[a-z0-9_]{1,32}$' },+ description: 'Service builder codes',+ },+ },+ additionalProperties: false,+});++export function isValidBuilderCode(code) {+ return typeof code === 'string' && BUILDER_CODE_PATTERN.test(code);+}++export function assertValidBuilderCode(code, label = 'builder code') {+ if (!isValidBuilderCode(code)) {+ throw new Error(+ `invalid ${label}: must match ^[a-z0-9_]{1,32}$ (got ${JSON.stringify(code)})`,+ );+ }+}++function validateServices(services, label = 's') {+ if (services == null) return undefined;+ if (!Array.isArray(services)) {+ throw new Error(`${label} must be an array of builder codes`);+ }+ for (const s of services) assertValidBuilderCode(s, `${label} entry`);+ return services.length ? [...services] : undefined;+}++// Build the v2 extension entry the server attaches to `PaymentRequired`.+//+// extensions: { [BUILDER_CODE]: declareBuilderCodeExtension({ a, s? }) }+//+// `info.a` is the app code that the client MUST echo verbatim in the+// PaymentPayload (see verifyClientEcho). `info.s` is informational only —+// the client supplies the runtime `s` list in its payload.+export function declareBuilderCodeExtension({ a, s } = {}) {+ assertValidBuilderCode(a, 'app builder code (a)');+ const info = { a };+ const services = validateServices(s, 'declared services (s)');+ if (services) info.s = services;+ return {+ info,+ schema: BUILDER_CODE_SCHEMA,+ };+}++// Build the `extensions[BUILDER_CODE]` block the client puts in its+// `PaymentPayload`. Client echoes the app code and may append its own+// service codes. The wallet code `w` is NOT set here — the facilitator+// fills it at settlement.+export function declareBuilderCodeOnPayload({ a, s } = {}) {+ assertValidBuilderCode(a, 'app builder code (a)');+ const out = { a };+ const services = validateServices(s, 'service codes (s)');+ if (services) out.s = services;+ return out;+}++// Concatenate Uint8Arrays.+function concatBytes(arrays) {+ let len = 0;+ for (const a of arrays) len += a.length;+ const out = new Uint8Array(len);+ let off = 0;+ for (const a of arrays) {+ out.set(a, off);+ off += a.length;+ }+ return out;+}++function hexToBytes(hex) {+ const clean = String(hex || '').replace(/^0x/i, '');+ if (clean.length % 2) throw new Error('hex string has odd length');+ const out = new Uint8Array(clean.length / 2);+ for (let i = 0; i < out.length; i++) {+ out[i] = parseInt(clean.slice(i * 2, i * 2 + 2), 16);+ }+ return out;+}++function bytesToHex(bytes) {+ let out = '';+ for (let i = 0; i < bytes.length; i++) {+ out += bytes[i].toString(16).padStart(2, '0');+ }+ return out;+}++function bytesEqual(a, b) {+ if (a.length !== b.length) return false;+ for (let i = 0; i < a.length; i++) if (a[i] !== b[i]) return false;+ return true;+}++// Encode the ERC-8021 Schema 2 suffix for the given attribution fields.+// Returns a Uint8Array; callers append it to settlement-tx calldata.+//+// Wire order (left-to-right as written into calldata):+// [cborData][cborLength (2B BE)][schemaId (1B)][ercMarker (16B)]+//+// `a` is required; `w` and `s` are optional. CBOR map key order matches the+// spec examples (`a` → `s` → `w`).+export function encodeBuilderCodeSuffix({ a, w, s } = {}) {+ assertValidBuilderCode(a, 'app builder code (a)');+ const services = validateServices(s, 'service codes (s)');+ const map = { a };+ if (services) map.s = services;+ if (w !== undefined) {+ assertValidBuilderCode(w, 'wallet builder code (w)');+ map.w = w;+ }+ const cborData = cborEncode(map);+ if (cborData.length > 0xffff) {+ throw new Error(`builder-code CBOR too large: ${cborData.length} > 65535`);+ }+ const cborLength = new Uint8Array(2);+ cborLength[0] = (cborData.length >> 8) & 0xff;+ cborLength[1] = cborData.length & 0xff;+ const schemaIdByte = new Uint8Array([SCHEMA_ID]);+ return concatBytes([cborData, cborLength, schemaIdByte, ERC8021_MARKER_BYTES]);+}++export function encodeBuilderCodeSuffixHex(fields) {+ return bytesToHex(encodeBuilderCodeSuffix(fields));+}++// Parse the ERC-8021 Schema 2 suffix from a hex-encoded calldata blob+// (with or without `0x` prefix). Returns null when the suffix is absent+// or malformed — callers should treat this as "no attribution" rather+// than an error, since non-x402 calldata won't carry the marker.+export function parseBuilderCodeSuffix(calldataHexOrBytes) {+ let bytes;+ if (typeof calldataHexOrBytes === 'string') {+ try {+ bytes = hexToBytes(calldataHexOrBytes);+ } catch {+ return null;+ }+ } else if (calldataHexOrBytes instanceof Uint8Array) {+ bytes = calldataHexOrBytes;+ } else if (Array.isArray(calldataHexOrBytes)) {+ bytes = Uint8Array.from(calldataHexOrBytes);+ } else {+ return null;+ }+ if (bytes.length < 16 + 1 + 2) return null;+ const markerStart = bytes.length - 16;+ const marker = bytes.subarray(markerStart);+ if (!bytesEqual(marker, ERC8021_MARKER_BYTES)) return null;+ const schemaId = bytes[markerStart - 1];+ if (schemaId !== SCHEMA_ID) return null;+ const cborLen = (bytes[markerStart - 3] << 8) | bytes[markerStart - 2];+ const cborStart = markerStart - 3 - cborLen;+ if (cborStart < 0) return null;+ const cborData = bytes.subarray(cborStart, markerStart - 3);+ let decoded;+ try {+ decoded = cborDecode(cborData);+ } catch {+ return null;+ }+ if (!decoded || typeof decoded !== 'object') return null;+ const out = {};+ if (typeof decoded.a === 'string') out.a = decoded.a;+ if (typeof decoded.w === 'string') out.w = decoded.w;+ if (Array.isArray(decoded.s)) {+ out.s = decoded.s.filter((x) => typeof x === 'string');+ }+ out.schemaId = schemaId;+ out.cborLength = cborLen;+ return out;+}++// Anti-tampering: the facilitator MUST verify the `a` echoed in the payload+// matches the `a` declared on the route. A mismatch indicates the client+// tampered with attribution; reject the payment.+export function verifyClientEcho({ required, payload }) {+ if (!required || !required.info || !required.info.a) return { ok: true };+ const declaredA = required.info.a;+ const echoedA = payload?.a;+ if (echoedA === undefined) {+ return {+ ok: false,+ reason: `builder-code: client did not echo app code "${declaredA}"`,+ };+ }+ if (echoedA !== declaredA) {+ return {+ ok: false,+ reason: `builder-code: client echoed "${echoedA}" but app declared "${declaredA}"`,+ };+ }+ if (payload.s !== undefined) {+ try {+ validateServices(payload.s, 'service codes (s)');+ } catch (err) {+ return { ok: false, reason: `builder-code: ${err.message}` };+ }+ }+ return { ok: true };+}++export const ERC8021 = Object.freeze({+ MARKER_HEX: ERC8021_MARKER_HEX,+ MARKER_BYTES: ERC8021_MARKER_BYTES,+ SCHEMA_ID,+});diff --git a/api/_lib/x402/api-keys.js b/api/_lib/x402/api-keys.jsnew file mode 100644index 000000000..0e5c75863--- /dev/null+++ b/api/_lib/x402/api-keys.js@@ -0,0 +1,301 @@+// x402 subscription API keys — issuance, lookup, revocation, sliding-window+// rate limiting. Backed by Postgres (api/_lib/migrations/2026-05-21-x402-subscriptions.sql)+// with Upstash Redis sorted-set rate limiting where credentials are present+// and an in-memory fallback for local dev.+//+// USE-23 wiring: api/_lib/x402/access-control.js calls this module from+// inside the onProtectedRequest hook to look up the subscription a request+// belongs to before deciding whether to bypass the 402 challenge.+//+// Key format:+// plaintext = "x402_live_" + base64url(32 bytes of CSPRNG entropy)+// prefix = plaintext.slice(0, 16) // visible in logs / UI+// hash = hex(sha256(plaintext)) // stored in db+//+// The plaintext is shown ONCE at creation and never persisted in clear.++import { Redis } from '@upstash/redis';+import { sql } from '../db.js';+import { env } from '../env.js';+import { randomToken, sha256 } from '../crypto.js';++const KEY_PREFIX = 'x402_live_';++let _redis = null;+let _redisChecked = false;+function getRedis() {+ if (_redisChecked) return _redis;+ _redisChecked = true;+ if (env.UPSTASH_REDIS_REST_URL && env.UPSTASH_REDIS_REST_TOKEN) {+ _redis = new Redis({+ url: env.UPSTASH_REDIS_REST_URL,+ token: env.UPSTASH_REDIS_REST_TOKEN,+ });+ }+ return _redis;+}++// In-memory sliding-window fallback for local dev (no Upstash configured).+// Maps key → array of millisecond timestamps within the current window.+const _memoryWindows = new Map();++/**+ * Look up a subscription by its plaintext API key.+ * Returns the row (without key_hash) or null when no active subscription matches.+ *+ * "Active" = not revoked AND (expires_at IS NULL OR expires_at > now).+ *+ * @param {string} plaintextKey+ * @returns {Promise<null | { id, name, key_prefix, rate_limit_per_minute, expires_at, revoked_at, meta, created_at }>}+ */+export async function lookupSubscription(plaintextKey) {+ if (!plaintextKey || typeof plaintextKey !== 'string') return null;+ if (!plaintextKey.startsWith(KEY_PREFIX)) return null;+ const hash = await sha256(plaintextKey);+ const rows = await sql`+ select id, name, key_prefix, rate_limit_per_minute, expires_at, revoked_at, meta, created_at+ from x402_subscriptions+ where key_hash = ${hash}+ limit 1+ `;+ const row = rows[0];+ if (!row) return null;+ if (row.revoked_at) return { ...row, _status: 'revoked' };+ if (row.expires_at && new Date(row.expires_at).getTime() < Date.now()) {+ return { ...row, _status: 'expired' };+ }+ return { ...row, _status: 'active' };+}++/**+ * Sliding-window rate limit: returns { allowed, remaining, limit, resetAt }.+ * The window is 60 seconds. Each (subscriptionId, route) pair is bucketed+ * independently so partner traffic on one endpoint cannot starve another.+ *+ * @param {object} subscription — row returned by lookupSubscription()+ * @param {string} route — e.g. "/api/x402/model-check"+ * @returns {Promise<{ allowed: boolean, remaining: number, limit: number, resetAt: number }>}+ */+export async function checkRateLimit(subscription, route) {+ const limit = Math.max(1, Number(subscription?.rate_limit_per_minute) || 60);+ const windowMs = 60_000;+ const now = Date.now();+ const bucketKey = `x402:rl:${subscription.id}:${route}`;++ const redis = getRedis();+ if (redis) {+ // Redis sorted-set sliding window: ZREMRANGEBYSCORE drops expired+ // timestamps, ZCARD counts the rest, ZADD writes the new one. EXPIRE+ // keeps the key from leaking when the partner stops calling.+ const cutoff = now - windowMs;+ const member = `${now}:${Math.random().toString(36).slice(2, 10)}`;+ const pipeline = redis.pipeline();+ pipeline.zremrangebyscore(bucketKey, 0, cutoff);+ pipeline.zadd(bucketKey, { score: now, member });+ pipeline.zcard(bucketKey);+ pipeline.expire(bucketKey, Math.ceil(windowMs / 1000) + 5);+ const results = await pipeline.exec();+ const count = Number(results?.[2] ?? 0);+ if (count > limit) {+ // Remove the candidate we just added so it doesn't count against+ // the next legitimate request after the window slides.+ await redis.zrem(bucketKey, member);+ const oldest = await redis.zrange(bucketKey, 0, 0, { withScores: true });+ const resetAt = oldest?.length >= 2 ? Number(oldest[1]) + windowMs : now + windowMs;+ return { allowed: false, remaining: 0, limit, resetAt };+ }+ return {+ allowed: true,+ remaining: Math.max(0, limit - count),+ limit,+ resetAt: now + windowMs,+ };+ }++ // In-memory fallback. Single-process correctness only — fine for local+ // dev, would over-allow across Vercel lambda instances. Production must+ // have Upstash configured.+ const cutoff = now - windowMs;+ const stamps = (_memoryWindows.get(bucketKey) || []).filter((t) => t > cutoff);+ if (stamps.length >= limit) {+ _memoryWindows.set(bucketKey, stamps);+ return {+ allowed: false,+ remaining: 0,+ limit,+ resetAt: stamps[0] + windowMs,+ };+ }+ stamps.push(now);+ _memoryWindows.set(bucketKey, stamps);+ return {+ allowed: true,+ remaining: Math.max(0, limit - stamps.length),+ limit,+ resetAt: now + windowMs,+ };+}++/**+ * Issue a new subscription. Returns the row plus the plaintext token.+ * The plaintext is shown ONCE — callers MUST surface it to the operator and+ * we never store it.+ *+ * @param {object} opts+ * @param {string} opts.name — required, human-readable label+ * @param {string} [opts.id] — optional explicit id (default: random 12-char slug)+ * @param {number} [opts.rateLimitPerMinute=60]+ * @param {Date|string|null} [opts.expiresAt]+ * @param {object|null} [opts.meta]+ * @param {string|null} [opts.createdBy] — user.id of issuing admin+ * @returns {Promise<{ id, name, key_prefix, rate_limit_per_minute, expires_at, meta, created_at, token: string }>}+ */+export async function createSubscription({+ name,+ id,+ rateLimitPerMinute = 60,+ expiresAt = null,+ meta = null,+ createdBy = null,+}) {+ if (!name || typeof name !== 'string') {+ const err = new Error('subscription name is required');+ err.status = 400;+ err.code = 'validation_error';+ throw err;+ }+ const subId = id || `sub_${randomToken(8).slice(0, 12)}`;+ const tokenSecret = randomToken(32);+ const plaintext = `${KEY_PREFIX}${tokenSecret}`;+ const prefix = plaintext.slice(0, 16);+ const hash = await sha256(plaintext);++ const [row] = await sql`+ insert into x402_subscriptions+ (id, name, key_hash, key_prefix, rate_limit_per_minute, expires_at, meta, created_by)+ values+ (${subId}, ${name}, ${hash}, ${prefix}, ${rateLimitPerMinute},+ ${expiresAt}, ${meta}, ${createdBy})+ returning id, name, key_prefix, rate_limit_per_minute, expires_at, meta, created_at+ `;+ return { ...row, token: plaintext };+}++/**+ * Revoke a subscription. Idempotent: re-revoking is a no-op. Returns the+ * updated row, or null when no subscription with this id exists.+ */+export async function revokeSubscription(id) {+ const [row] = await sql`+ update x402_subscriptions+ set revoked_at = coalesce(revoked_at, now())+ where id = ${id}+ returning id, name, key_prefix, rate_limit_per_minute, expires_at, revoked_at, meta, created_at+ `;+ return row || null;+}++/**+ * Aggregate usage for a subscription. Reads from x402_access_log: total+ * grants, total denials, per-route counts, and the most recent N entries+ * for quick eyeballing.+ */+export async function getUsage(id, { recentLimit = 50 } = {}) {+ const [sub] = await sql`+ select id, name, key_prefix, rate_limit_per_minute, expires_at, revoked_at, created_at+ from x402_subscriptions where id = ${id}+ `;+ if (!sub) return null;+ const callerId = `subscription:${id}`;+ const [counts] = await sql`+ select+ count(*) filter (where granted) as granted,+ count(*) filter (where not granted) as denied,+ max(created_at) as last_seen+ from x402_access_log+ where caller_id = ${callerId}+ `;+ const perRoute = await sql`+ select route,+ count(*) filter (where granted) as granted,+ count(*) filter (where not granted) as denied+ from x402_access_log+ where caller_id = ${callerId}+ group by route+ order by granted desc, denied desc+ `;+ const recent = await sql`+ select route, granted, reason, meta, created_at+ from x402_access_log+ where caller_id = ${callerId}+ order by created_at desc+ limit ${recentLimit}+ `;+ return {+ subscription: sub,+ totals: {+ granted: Number(counts?.granted || 0),+ denied: Number(counts?.denied || 0),+ lastSeenAt: counts?.last_seen || null,+ },+ perRoute: perRoute.map((r) => ({+ route: r.route,+ granted: Number(r.granted || 0),+ denied: Number(r.denied || 0),+ })),+ recent,+ };+}++/**+ * List active subscriptions (or all when includeInactive is true). Never+ * returns the key hash — only the prefix.+ */+export async function listSubscriptions({ includeInactive = false } = {}) {+ if (includeInactive) {+ return sql`+ select id, name, key_prefix, rate_limit_per_minute, expires_at, revoked_at,+ meta, created_at, created_by+ from x402_subscriptions+ order by created_at desc+ `;+ }+ return sql`+ select id, name, key_prefix, rate_limit_per_minute, expires_at, revoked_at,+ meta, created_at, created_by+ from x402_subscriptions+ where revoked_at is null+ and (expires_at is null or expires_at > now())+ order by created_at desc+ `;+}++/**+ * Write one row to x402_access_log. Fire-and-forget (errors logged, never+ * thrown) so the audit trail can never break a paid endpoint response.+ *+ * @param {object} entry+ * @param {string} entry.callerId — 'internal' | 'subscription:<id>' | 'oauth:<sub>' | 'abort:<short>'+ * @param {string} entry.route+ * @param {string} entry.reason+ * @param {boolean} entry.granted+ * @param {object|null} [entry.meta]+ */+export function logAccess({ callerId, route, reason, granted, meta = null }) {+ queueMicrotask(async () => {+ try {+ await sql`+ insert into x402_access_log (caller_id, route, reason, granted, meta)+ values (${callerId}, ${route}, ${reason}, ${granted}, ${meta})+ `;+ } catch (err) {+ console.error('[x402-access-log] insert failed', {+ route,+ callerId,+ error: err?.message,+ });+ }+ });+}++export const __test = { KEY_PREFIX };diff --git a/api/_lib/x402/bazaar-client.js b/api/_lib/x402/bazaar-client.jsnew file mode 100644index 000000000..446e4503d--- /dev/null+++ b/api/_lib/x402/bazaar-client.js@@ -0,0 +1,359 @@+// x402 Bazaar discovery client.+//+// Talks directly to facilitator `/discovery/resources` endpoints (HTTP GET).+// No SDK dependency — the wire format is stable enough to consume with fetch.+// We normalize items returned by both spec versions:+// - v1 facilitators (PayAI): flat shape, network strings like "base"/"solana"+// - v2 facilitators (CDP): `extensions.bazaar.info`, CAIP-2 networks+//+// Search is implemented client-side as a text query over normalized items+// because none of the public facilitators expose a server-side search route.+// Multi-facilitator merging dedupes HTTP by `resource` and MCP by+// `(resource, toolName)` per spec.++const DEFAULT_FACILITATORS = (() => {+ const list = [];+ const base = process.env.X402_FACILITATOR_URL_BASE || 'https://facilitator.payai.network';+ const cdp = process.env.X402_CDP_FACILITATOR_URL || 'https://api.cdp.coinbase.com/platform/v2/x402';+ const sol = process.env.X402_FACILITATOR_URL_SOLANA;+ list.push(base);+ if (cdp && cdp !== base) list.push(cdp);+ if (sol && !list.includes(sol)) list.push(sol);+ return list;+})();++const COMMON_ASSETS = {+ // Base USDC+ '0x833589fcd6edb6e08f4c7c32d4f71b54bda02913': { symbol: 'USDC', decimals: 6 },+ // Solana USDC+ epjfwdd5aufqssqem2qn1xzybapc8g4weggkzwytdt1v: { symbol: 'USDC', decimals: 6 },+ // Optimism USDC+ '0x0b2c639c533813f4aa9d7837caf62653d097ff85': { symbol: 'USDC', decimals: 6 },+ // Arbitrum USDC+ '0xaf88d065e77c8cc2239327c5edb3a432268e5831': { symbol: 'USDC', decimals: 6 },+ // Polygon USDC+ '0x3c499c542cef5e3811e1192ce70d8cc03d5c3359': { symbol: 'USDC', decimals: 6 },+};++function normalizeNetwork(net) {+ if (!net) return '';+ const n = String(net).toLowerCase();+ if (n === 'base') return 'eip155:8453';+ if (n === 'base-sepolia') return 'eip155:84532';+ if (n === 'arbitrum') return 'eip155:42161';+ if (n === 'optimism') return 'eip155:10';+ if (n === 'polygon') return 'eip155:137';+ if (n === 'solana') return 'solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp';+ if (n === 'solana-devnet') return 'solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1';+ return n;+}++function networkFamily(net) {+ const n = normalizeNetwork(net);+ if (n.startsWith('eip155:')) return 'evm';+ if (n.startsWith('solana')) return 'solana';+ return 'unknown';+}++function assetInfo(asset) {+ if (!asset) return { symbol: '', decimals: 6 };+ const meta = COMMON_ASSETS[String(asset).toLowerCase()];+ return meta || { symbol: '', decimals: 6 };+}++function pickAmount(accept) {+ // v2 spec uses `amount`; v1 PayAI uses `maxAmountRequired`.+ return accept?.amount ?? accept?.maxAmountRequired ?? '0';+}++// Convert atomic units to a human string. We don't trust the decimals when+// unknown — fall back to USDC 6dp which is the common case in practice.+function formatPrice(atomic, asset) {+ const { symbol, decimals } = assetInfo(asset);+ const n = Number(atomic) / 10 ** decimals;+ let str;+ if (n === 0) str = '0';+ else if (n < 0.01) str = n.toFixed(6).replace(/0+$/, '').replace(/\.$/, '');+ else if (n < 1) str = n.toFixed(4).replace(/0+$/, '').replace(/\.$/, '');+ else str = n.toFixed(2);+ return symbol ? `${str} ${symbol}` : str;+}++// Normalize one raw item into a stable shape. We keep the original under+// `raw` so callers needing facilitator-specific fields still have them.+export function normalizeItem(item, facilitator) {+ if (!item || typeof item !== 'object') return null;+ const accepts = Array.isArray(item.accepts) ? item.accepts : [];+ const primary = accepts[0] || {};++ const bazaarInfo = item?.extensions?.bazaar?.info || item?.inputSchema || null;+ const input = bazaarInfo?.input || bazaarInfo || null;+ const isMcp = input?.type === 'mcp';+ const toolName = isMcp ? input?.toolName || '' : '';++ const resourceUrl =+ typeof item.resource === 'string'+ ? item.resource+ : item.resource?.url || primary?.resource || '';++ const resourceMeta = typeof item.resource === 'object' ? item.resource : {};+ const description =+ item.description || resourceMeta.description || primary?.description || '';+ const serviceName = resourceMeta.serviceName || resourceMeta.name || '';+ const iconUrl = resourceMeta.iconUrl || resourceMeta.icon || '';+ const tags = Array.isArray(resourceMeta.tags)+ ? resourceMeta.tags+ : Array.isArray(item.tags)+ ? item.tags+ : [];++ const normalizedAccepts = accepts.map((a) => {+ const net = normalizeNetwork(a.network);+ const amount = pickAmount(a);+ return {+ ...a,+ network: net,+ networkRaw: a.network,+ amount,+ amountAtomic: amount,+ family: networkFamily(a.network),+ assetInfo: assetInfo(a.asset),+ priceLabel: formatPrice(amount, a.asset),+ };+ });++ const minAtomic = normalizedAccepts.reduce((min, a) => {+ const n = Number(a.amountAtomic);+ return Number.isFinite(n) && (min == null || n < min) ? n : min;+ }, null);+ const minAccept = normalizedAccepts.find((a) => Number(a.amountAtomic) === minAtomic) || normalizedAccepts[0];++ const extensionsList = item.extensions ? Object.keys(item.extensions) : [];+ const method =+ item.method ||+ input?.method ||+ primary?.method ||+ (isMcp ? 'MCP' : '');++ return {+ type: item.type || (isMcp ? 'mcp' : 'http'),+ resource: resourceUrl,+ toolName,+ uniqueKey: isMcp ? `${resourceUrl}#${toolName}` : resourceUrl,+ serviceName,+ description,+ iconUrl,+ tags,+ method,+ accepts: normalizedAccepts,+ minPriceAtomic: minAtomic,+ minPriceLabel: minAccept ? minAccept.priceLabel : '',+ families: [...new Set(normalizedAccepts.map((a) => a.family))],+ networks: [...new Set(normalizedAccepts.map((a) => a.network))],+ extensions: extensionsList,+ input,+ output: bazaarInfo?.output || null,+ lastUpdated: item.lastUpdated || null,+ facilitator,+ raw: item,+ };+}++async function fetchJson(url, { timeoutMs = 15000 } = {}) {+ const ctrl = new AbortController();+ const t = setTimeout(() => ctrl.abort(), timeoutMs);+ try {+ const r = await fetch(url, {+ method: 'GET',+ headers: { accept: 'application/json' },+ signal: ctrl.signal,+ });+ if (!r.ok) {+ const body = await r.text().catch(() => '');+ throw Object.assign(new Error(`facilitator ${r.status} ${r.statusText}: ${body.slice(0, 200)}`), {+ status: r.status,+ facilitator: url,+ });+ }+ return await r.json();+ } finally {+ clearTimeout(t);+ }+}++// Page through a facilitator's /discovery/resources. We stop at `maxItems`+// (default 500) to keep responses bounded — operators that need everything can+// raise the cap explicitly.+async function listOneFacilitator(facilitatorUrl, { type, limit, maxItems }) {+ const items = [];+ const pageSize = Math.min(200, Math.max(1, limit || 200));+ let offset = 0;+ let total = null;+ while (items.length < maxItems) {+ const u = new URL(facilitatorUrl.replace(/\/$/, '') + '/discovery/resources');+ if (type) u.searchParams.set('type', type);+ u.searchParams.set('limit', String(pageSize));+ u.searchParams.set('offset', String(offset));+ const body = await fetchJson(u.toString());+ const got = Array.isArray(body?.items) ? body.items : Array.isArray(body) ? body : [];+ if (got.length === 0) break;+ for (const it of got) items.push(it);+ if (body?.pagination?.total != null) total = body.pagination.total;+ offset += got.length;+ // Stop if facilitator returned fewer than requested (last page).+ if (got.length < pageSize) break;+ // Or if we've reached the reported total.+ if (total != null && offset >= total) break;+ }+ return items;+}++// Bazaar client. Stateless aside from the configured facilitator list.+export class Bazaar {+ constructor({ facilitators } = {}) {+ const urls = Array.isArray(facilitators) && facilitators.length ? facilitators : DEFAULT_FACILITATORS;+ this.facilitators = urls.filter(Boolean);+ }++ async list({ type = 'http', limit = 200, maxItems = 500 } = {}) {+ const settled = await Promise.allSettled(+ this.facilitators.map(async (f) => {+ const items = await listOneFacilitator(f, { type, limit, maxItems });+ return items.map((it) => normalizeItem(it, f)).filter(Boolean);+ }),+ );+ const items = [];+ const sources = [];+ const errors = [];+ const seen = new Map(); // uniqueKey → index in items+ for (let i = 0; i < settled.length; i++) {+ const f = this.facilitators[i];+ const r = settled[i];+ if (r.status !== 'fulfilled') {+ errors.push({ facilitator: f, error: String(r.reason?.message || r.reason || 'error') });+ sources.push({ facilitator: f, count: 0, ok: false });+ continue;+ }+ let added = 0;+ for (const it of r.value) {+ if (!it.uniqueKey) continue;+ const existing = seen.get(it.uniqueKey);+ if (existing == null) {+ seen.set(it.uniqueKey, items.length);+ items.push(it);+ added++;+ } else {+ // Prefer the entry with richer bazaar metadata when deduping.+ const prev = items[existing];+ if (!prev.description && it.description) items[existing] = it;+ }+ }+ sources.push({ facilitator: f, count: added, ok: true });+ }+ return { items, sources, errors };+ }++ async search({ query, type = 'http', maxItems = 500 } = {}) {+ const q = String(query || '').trim().toLowerCase();+ const { items, sources, errors } = await this.list({ type, maxItems });+ if (!q) return { resources: items, sources, errors };+ const terms = q.split(/\s+/g).filter(Boolean);+ const scored = items+ .map((it) => ({ it, score: scoreItem(it, terms) }))+ .filter((x) => x.score > 0)+ .sort((a, b) => b.score - a.score)+ .map((x) => x.it);+ return { resources: scored, sources, errors };+ }++ // Look up a single resource by URL (and optional MCP tool name).+ async get(resourceUrl, { toolName } = {}) {+ const key = toolName ? `${resourceUrl}#${toolName}` : resourceUrl;+ const type = toolName ? 'mcp' : 'http';+ const { items } = await this.list({ type, maxItems: 1000 });+ return items.find((it) => it.uniqueKey === key) || null;+ }+}++function scoreItem(it, terms) {+ const hay = [it.serviceName, it.description, it.resource, it.toolName, ...(it.tags || [])]+ .filter(Boolean)+ .join(' ')+ .toLowerCase();+ let score = 0;+ for (const t of terms) {+ if (!hay.includes(t)) return 0;+ // Title/tag hits are worth more than generic hits.+ if (it.serviceName && it.serviceName.toLowerCase().includes(t)) score += 4;+ if (it.tags?.some((tag) => tag.toLowerCase().includes(t))) score += 3;+ if (it.toolName && it.toolName.toLowerCase().includes(t)) score += 3;+ if (it.description && it.description.toLowerCase().includes(t)) score += 2;+ score += 1;+ }+ return score;+}++// ---- Filtering helpers ----++export function filterByMaxPrice(items, atomicMax, asset = null) {+ const max = BigInt(atomicMax);+ const wantAsset = asset ? String(asset).toLowerCase() : null;+ return items.filter((it) =>+ it.accepts.some((a) => {+ if (wantAsset && String(a.asset || '').toLowerCase() !== wantAsset) return false;+ try {+ return BigInt(a.amountAtomic || 0) <= max;+ } catch {+ return false;+ }+ }),+ );+}++export function filterByNetwork(items, pattern) {+ if (!pattern) return items;+ const re = patternToRegex(pattern);+ return items.filter((it) => it.networks.some((n) => re.test(n)));+}++function patternToRegex(pattern) {+ if (pattern instanceof RegExp) return pattern;+ // support wildcards like "eip155:*" or "solana:*"+ const escaped = String(pattern)+ .replace(/[.+^${}()|[\]\\]/g, '\\$&')+ .replace(/\*/g, '.*');+ return new RegExp(`^${escaped}$`, 'i');+}++export function filterByExtension(items, extensionName) {+ if (!extensionName) return items;+ return items.filter((it) => it.extensions.includes(extensionName));+}++export function filterByTag(items, tag) {+ if (!tag) return items;+ const t = String(tag).toLowerCase();+ return items.filter((it) => (it.tags || []).some((x) => String(x).toLowerCase() === t));+}++export function groupBy(items, key) {+ const out = new Map();+ for (const it of items) {+ const k = typeof key === 'function' ? key(it) : it[key] ?? '';+ if (!out.has(k)) out.set(k, []);+ out.get(k).push(it);+ }+ return out;+}++export function sortByPriceAsc(items) {+ return [...items].sort((a, b) => {+ const av = a.minPriceAtomic ?? Number.MAX_SAFE_INTEGER;+ const bv = b.minPriceAtomic ?? Number.MAX_SAFE_INTEGER;+ return av - bv;+ });+}++export function defaultFacilitators() {+ return [...DEFAULT_FACILITATORS];+}diff --git a/api/bazaar/list.js b/api/bazaar/list.jsnew file mode 100644index 000000000..dc1e6ef45--- /dev/null+++ b/api/bazaar/list.js@@ -0,0 +1,70 @@+// GET /api/bazaar/list?type=http&network=eip155:*&maxPrice=100000&extension=sign-in-with-x&maxItems=500+//+// Proxy over the configured x402 facilitators' /discovery/resources endpoints.+// We merge across facilitators, dedupe by resource (HTTP) or (resource,toolName)+// (MCP), normalize the item shape, and apply the optional filters.++import { cors, json, error, wrap } from '../_lib/http.js';+import {+ Bazaar,+ filterByExtension,+ filterByMaxPrice,+ filterByNetwork,+ filterByTag,+ sortByPriceAsc,+} from '../_lib/x402/bazaar-client.js';++async function handler(req, res) {+ if (cors(req, res, { origins: '*', methods: 'GET,OPTIONS' })) return;+ if (req.method !== 'GET') return error(res, 405, 'method_not_allowed', 'GET only');++ const url = new URL(req.url, 'http://x');+ const type = (url.searchParams.get('type') || 'http').toLowerCase();+ if (type !== 'http' && type !== 'mcp') {+ return error(res, 400, 'bad_request', 'type must be "http" or "mcp"');+ }+ const network = url.searchParams.get('network') || null;+ const maxPrice = url.searchParams.get('maxPrice');+ const asset = url.searchParams.get('asset');+ const extension = url.searchParams.get('extension');+ const tag = url.searchParams.get('tag');+ const maxItems = clampInt(url.searchParams.get('maxItems'), 500, 1, 5000);+ const limit = clampInt(url.searchParams.get('limit'), 200, 1, 200);+ const sort = url.searchParams.get('sort'); // "price"+ const facilitatorsCsv = url.searchParams.get('facilitators');+ const facilitators = facilitatorsCsv+ ? facilitatorsCsv.split(',').map((s) => s.trim()).filter(Boolean)+ : undefined;++ const baz = new Bazaar({ facilitators });+ let result;+ try {+ result = await baz.list({ type, limit, maxItems });+ } catch (e) {+ return error(res, 502, 'facilitator_error', String(e?.message || e));+ }++ let items = result.items;+ if (network) items = filterByNetwork(items, network);+ if (maxPrice) items = filterByMaxPrice(items, maxPrice, asset);+ if (extension) items = filterByExtension(items, extension);+ if (tag) items = filterByTag(items, tag);+ if (sort === 'price') items = sortByPriceAsc(items);++ res.setHeader('cache-control', 'public, max-age=15, stale-while-revalidate=60');+ return json(res, 200, {+ type,+ count: items.length,+ items,+ sources: result.sources,+ errors: result.errors,+ });+}++function clampInt(v, fallback, min, max) {+ const n = Number(v);+ if (!Number.isFinite(n)) return fallback;+ return Math.max(min, Math.min(max, Math.floor(n)));+}++export default wrap(handler);diff --git a/api/bazaar/search.js b/api/bazaar/search.jsnew file mode 100644index 000000000..188643fcb--- /dev/null+++ b/api/bazaar/search.js@@ -0,0 +1,71 @@+// GET /api/bazaar/search?query=weather&type=http&network=eip155:*&maxPrice=100000+//+// Ranked text search over the merged facilitator catalog. Implemented client+// side because none of the public facilitators expose a server-side search+// route — we pull the list, score items against the query terms, and sort.++import { cors, json, error, wrap } from '../_lib/http.js';+import {+ Bazaar,+ filterByExtension,+ filterByMaxPrice,+ filterByNetwork,+ filterByTag,+} from '../_lib/x402/bazaar-client.js';++async function handler(req, res) {+ if (cors(req, res, { origins: '*', methods: 'GET,OPTIONS' })) return;+ if (req.method !== 'GET') return error(res, 405, 'method_not_allowed', 'GET only');++ const url = new URL(req.url, 'http://x');+ const query = url.searchParams.get('query') || url.searchParams.get('q') || '';+ const type = (url.searchParams.get('type') || 'http').toLowerCase();+ if (type !== 'http' && type !== 'mcp') {+ return error(res, 400, 'bad_request', 'type must be "http" or "mcp"');+ }+ const network = url.searchParams.get('network') || null;+ const maxPrice = url.searchParams.get('maxPrice');+ const asset = url.searchParams.get('asset');+ const extension = url.searchParams.get('extension');+ const tag = url.searchParams.get('tag');+ const maxItems = clampInt(url.searchParams.get('maxItems'), 500, 1, 5000);+ const limit = clampInt(url.searchParams.get('limit'), 50, 1, 500);+ const facilitatorsCsv = url.searchParams.get('facilitators');+ const facilitators = facilitatorsCsv+ ? facilitatorsCsv.split(',').map((s) => s.trim()).filter(Boolean)+ : undefined;++ const baz = new Bazaar({ facilitators });+ let result;+ try {+ result = await baz.search({ query, type, maxItems });+ } catch (e) {+ return error(res, 502, 'facilitator_error', String(e?.message || e));+ }++ let resources = result.resources;+ if (network) resources = filterByNetwork(resources, network);+ if (maxPrice) resources = filterByMaxPrice(resources, maxPrice, asset);+ if (extension) resources = filterByExtension(resources, extension);+ if (tag) resources = filterByTag(resources, tag);++ if (resources.length > limit) resources = resources.slice(0, limit);++ res.setHeader('cache-control', 'public, max-age=15, stale-while-revalidate=60');+ return json(res, 200, {+ type,+ query,+ count: resources.length,+ resources,+ sources: result.sources,+ errors: result.errors,+ });+}++function clampInt(v, fallback, min, max) {+ const n = Number(v);+ if (!Number.isFinite(n)) return fallback;+ return Math.max(min, Math.min(max, Math.floor(n)));+}++export default wrap(handler);diff --git a/api/cron/[name].js b/api/cron/[name].jsindex e8c5ce2fc..e32f9b6bf 100644--- a/api/cron/[name].js+++ b/api/cron/[name].js@@ -73,6 +73,7 @@ const HANDLERS = {'run-coin-cycle': handleRunCoinCycle,'run-coin-payouts': handleRunCoinPayouts,'club-payouts': handleClubPayouts,+ 'siwx-gc': handleSiwxGc,};export default wrap(async (req, res) => {@@ -2424,6 +2425,35 @@ async function handleCleanupCsrfTokens(req, res) {return json(res, 200, { deleted: result.length });}+// ═══════════════════════════════════════════════════════════════════════════+// siwx-gc — prune SIWX nonces (replay window) and expired payment grants.+// Hourly. Nonce window of 10 min is well above the 5-min SIWX maxAge;+// payments grace of 7 days avoids cutting off slow clients at the boundary.+// ═══════════════════════════════════════════════════════════════════════════++async function handleSiwxGc(req, res) {+ if (cors(req, res, { methods: 'GET,POST,OPTIONS' })) return;++ const auth = req.headers['authorization'] || '';+ const expected = env.CRON_SECRET ? `Bearer ${env.CRON_SECRET}` : null;+ const fromCron = req.headers['x-vercel-cron'] === '1';+ if (!fromCron && (!expected || auth !== expected)) {+ return error(res, 401, 'unauthorized', 'cron secret required');+ }++ const { pruneOldNonces, pruneExpiredPayments } = await import('../_lib/siwx-storage.js');++ const noncesDeleted = await pruneOldNonces(10 * 60);+ const paymentsDeleted = await pruneExpiredPayments(7 * 24 * 3600);++ return json(res, 200, {+ ok: true,+ noncesDeleted,+ paymentsDeleted,+ ranAt: new Date().toISOString(),+ });+}+// ═══════════════════════════════════════════════════════════════════════════// process-withdrawals — pick up pending Solana USDC withdrawals and execute// them from the treasury keypair. Runs hourly.diff --git a/package-lock.json b/package-lock.jsonindex 6bfba7957..23725199a 100644--- a/package-lock.json+++ b/package-lock.json@@ -36,6 +36,7 @@"@metaplex-foundation/mpl-core": "^1.10.0","@metaplex-foundation/umi": "^1.5.1","@metaplex-foundation/umi-bundle-defaults": "^1.5.1",+ "@modelcontextprotocol/sdk": "^1.29.0","@neondatabase/serverless": "^0.10.1","@neynar/nodejs-sdk": "^3.174.0","@nirholas/pump-sdk": "^1.0.0",@@ -64,10 +65,12 @@"@upstash/ratelimit": "^2.0.5","@upstash/redis": "^1.34.3","@vercel/og": "^0.11.1",+ "@x402/axios": "^2.12.0","@x402/core": "^2.11.0","@x402/evm": "^2.11.0","@x402/express": "^2.11.0","@x402/extensions": "^2.11.0",+ "@x402/svm": "^2.12.0","@zauthx402/sdk": "^0.1.14","agent0-sdk": "^1.7.1","ai": "^6.0.184",@@ -8016,6 +8019,18 @@"multiformats": "^13.0.0"}},+ "node_modules/@hono/node-server": {+ "version": "1.19.14",+ "resolved": "https://registry.npmjs.org/@hono/node-server/-/node-server-1.19.14.tgz",+ "integrity": "sha512-GwtvgtXxnWsucXvbQXkRgqksiH2Qed37H9xHZocE5sA3N8O8O8/8FA3uclQXxXVzc9XBZuEOMK7+r02FmSpHtw==",+ "license": "MIT",+ "engines": {+ "node": ">=18.14.1"+ },+ "peerDependencies": {+ "hono": "^4"+ }+ },"node_modules/@huggingface/inference": {"version": "2.8.1","resolved": "https://registry.npmjs.org/@huggingface/inference/-/inference-2.8.1.tgz",@@ -11950,6 +11965,371 @@"node": ">= 10.*"}},+ "node_modules/@modelcontextprotocol/sdk": {+ "version": "1.29.0",+ "resolved": "https://registry.npmjs.org/@modelcontextprotocol/sdk/-/sdk-1.29.0.tgz",+ "integrity": "sha512-zo37mZA9hJWpULgkRpowewez1y6ML5GsXJPY8FI0tBBCd77HEvza4jDqRKOXgHNn867PVGCyTdzqpz0izu5ZjQ==",+ "license": "MIT",+ "dependencies": {+ "@hono/node-server": "^1.19.9",+ "ajv": "^8.17.1",+ "ajv-formats": "^3.0.1",+ "content-type": "^1.0.5",+ "cors": "^2.8.5",+ "cross-spawn": "^7.0.5",+ "eventsource": "^3.0.2",+ "eventsource-parser": "^3.0.0",+ "express": "^5.2.1",+ "express-rate-limit": "^8.2.1",+ "hono": "^4.11.4",+ "jose": "^6.1.3",+ "json-schema-typed": "^8.0.2",+ "pkce-challenge": "^5.0.0",+ "raw-body": "^3.0.0",+ "zod": "^3.25 || ^4.0",+ "zod-to-json-schema": "^3.25.1"+ },+ "engines": {+ "node": ">=18"+ },+ "peerDependencies": {+ "@cfworker/json-schema": "^4.1.1",+ "zod": "^3.25 || ^4.0"+ },+ "peerDependenciesMeta": {+ "@cfworker/json-schema": {+ "optional": true+ },+ "zod": {+ "optional": false+ }+ }+ },+ "node_modules/@modelcontextprotocol/sdk/node_modules/accepts": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/accepts/-/accepts-2.0.0.tgz",+ "integrity": "sha512-5cvg6CtKwfgdmVqY1WIiXKc3Q1bkRqGLi+2W/6ao+6Y7gu/RCwRuAhGEzh5B4KlszSuTLgZYuqFqo5bImjNKng==",+ "license": "MIT",+ "dependencies": {+ "mime-types": "^3.0.0",+ "negotiator": "^1.0.0"+ },+ "engines": {+ "node": ">= 0.6"+ }+ },+ "node_modules/@modelcontextprotocol/sdk/node_modules/body-parser": {+ "version": "2.2.2",+ "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-2.2.2.tgz",+ "integrity": "sha512-oP5VkATKlNwcgvxi0vM0p/D3n2C3EReYVX+DNYs5TjZFn/oQt2j+4sVJtSMr18pdRr8wjTcBl6LoV+FUwzPmNA==",+ "license": "MIT",+ "dependencies": {+ "bytes": "^3.1.2",+ "content-type": "^1.0.5",+ "debug": "^4.4.3",+ "http-errors": "^2.0.0",+ "iconv-lite": "^0.7.0",+ "on-finished": "^2.4.1",+ "qs": "^6.14.1",+ "raw-body": "^3.0.1",+ "type-is": "^2.0.1"+ },+ "engines": {+ "node": ">=18"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/express"+ }+ },+ "node_modules/@modelcontextprotocol/sdk/node_modules/content-disposition": {+ "version": "1.1.0",+ "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-1.1.0.tgz",+ "integrity": "sha512-5jRCH9Z/+DRP7rkvY83B+yGIGX96OYdJmzngqnw2SBSxqCFPd0w2km3s5iawpGX8krnwSGmF0FW5Nhr0Hfai3g==",+ "license": "MIT",+ "engines": {+ "node": ">=18"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/express"+ }+ },+ "node_modules/@modelcontextprotocol/sdk/node_modules/cookie": {+ "version": "0.7.2",+ "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.7.2.tgz",+ "integrity": "sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.6"+ }+ },+ "node_modules/@modelcontextprotocol/sdk/node_modules/cookie-signature": {+ "version": "1.2.2",+ "resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.2.2.tgz",+ "integrity": "sha512-D76uU73ulSXrD1UXF4KE2TMxVVwhsnCgfAyTg9k8P6KGZjlXKrOLe4dJQKI3Bxi5wjesZoFXJWElNWBjPZMbhg==",+ "license": "MIT",+ "engines": {+ "node": ">=6.6.0"+ }+ },+ "node_modules/@modelcontextprotocol/sdk/node_modules/express": {+ "version": "5.2.1",+ "resolved": "https://registry.npmjs.org/express/-/express-5.2.1.tgz",+ "integrity": "sha512-hIS4idWWai69NezIdRt2xFVofaF4j+6INOpJlVOLDO8zXGpUVEVzIYk12UUi2JzjEzWL3IOAxcTubgz9Po0yXw==",+ "license": "MIT",+ "dependencies": {+ "accepts": "^2.0.0",+ "body-parser": "^2.2.1",+ "content-disposition": "^1.0.0",+ "content-type": "^1.0.5",+ "cookie": "^0.7.1",+ "cookie-signature": "^1.2.1",+ "debug": "^4.4.0",+ "depd": "^2.0.0",+ "encodeurl": "^2.0.0",+ "escape-html": "^1.0.3",+ "etag": "^1.8.1",+ "finalhandler": "^2.1.0",+ "fresh": "^2.0.0",+ "http-errors": "^2.0.0",+ "merge-descriptors": "^2.0.0",+ "mime-types": "^3.0.0",+ "on-finished": "^2.4.1",+ "once": "^1.4.0",+ "parseurl": "^1.3.3",+ "proxy-addr": "^2.0.7",+ "qs": "^6.14.0",+ "range-parser": "^1.2.1",+ "router": "^2.2.0",+ "send": "^1.1.0",+ "serve-static": "^2.2.0",+ "statuses": "^2.0.1",+ "type-is": "^2.0.1",+ "vary": "^1.1.2"+ },+ "engines": {+ "node": ">= 18"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/express"+ }+ },+ "node_modules/@modelcontextprotocol/sdk/node_modules/finalhandler": {+ "version": "2.1.1",+ "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-2.1.1.tgz",+ "integrity": "sha512-S8KoZgRZN+a5rNwqTxlZZePjT/4cnm0ROV70LedRHZ0p8u9fRID0hJUZQpkKLzro8LfmC8sx23bY6tVNxv8pQA==",+ "license": "MIT",+ "dependencies": {+ "debug": "^4.4.0",+ "encodeurl": "^2.0.0",+ "escape-html": "^1.0.3",+ "on-finished": "^2.4.1",+ "parseurl": "^1.3.3",+ "statuses": "^2.0.1"+ },+ "engines": {+ "node": ">= 18.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/express"+ }+ },+ "node_modules/@modelcontextprotocol/sdk/node_modules/fresh": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/fresh/-/fresh-2.0.0.tgz",+ "integrity": "sha512-Rx/WycZ60HOaqLKAi6cHRKKI7zxWbJ31MhntmtwMoaTeF7XFH9hhBp8vITaMidfljRQ6eYWCKkaTK+ykVJHP2A==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.8"+ }+ },+ "node_modules/@modelcontextprotocol/sdk/node_modules/http-errors": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.1.tgz",+ "integrity": "sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ==",+ "license": "MIT",+ "dependencies": {+ "depd": "~2.0.0",+ "inherits": "~2.0.4",+ "setprototypeof": "~1.2.0",+ "statuses": "~2.0.2",+ "toidentifier": "~1.0.1"+ },+ "engines": {+ "node": ">= 0.8"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/express"+ }+ },+ "node_modules/@modelcontextprotocol/sdk/node_modules/jose": {+ "version": "6.2.3",+ "resolved": "https://registry.npmjs.org/jose/-/jose-6.2.3.tgz",+ "integrity": "sha512-YYVDInQKFJfR/xa3ojUTl8c2KoTwiL1R5Wg9YCydwH0x0B9grbzlg5HC7mMjCtUJjbQ/YnGEZIhI5tCgfTb4Hw==",+ "license": "MIT",+ "funding": {+ "url": "https://github.com/sponsors/panva"+ }+ },+ "node_modules/@modelcontextprotocol/sdk/node_modules/media-typer": {+ "version": "1.1.0",+ "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-1.1.0.tgz",+ "integrity": "sha512-aisnrDP4GNe06UcKFnV5bfMNPBUw4jsLGaWwWfnH3v02GnBuXX2MCVn5RbrWo0j3pczUilYblq7fQ7Nw2t5XKw==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.8"+ }+ },+ "node_modules/@modelcontextprotocol/sdk/node_modules/merge-descriptors": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-2.0.0.tgz",+ "integrity": "sha512-Snk314V5ayFLhp3fkUREub6WtjBfPdCPY1Ln8/8munuLuiYhsABgBVWsozAG+MWMbVEvcdcpbi9R7ww22l9Q3g==",+ "license": "MIT",+ "engines": {+ "node": ">=18"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/@modelcontextprotocol/sdk/node_modules/mime-db": {+ "version": "1.54.0",+ "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.54.0.tgz",+ "integrity": "sha512-aU5EJuIN2WDemCcAp2vFBfp/m4EAhWJnUNSSw0ixs7/kXbd6Pg64EmwJkNdFhB8aWt1sH2CTXrLxo/iAGV3oPQ==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.6"+ }+ },+ "node_modules/@modelcontextprotocol/sdk/node_modules/mime-types": {+ "version": "3.0.2",+ "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-3.0.2.tgz",+ "integrity": "sha512-Lbgzdk0h4juoQ9fCKXW4by0UJqj+nOOrI9MJ1sSj4nI8aI2eo1qmvQEie4VD1glsS250n15LsWsYtCugiStS5A==",+ "license": "MIT",+ "dependencies": {+ "mime-db": "^1.54.0"+ },+ "engines": {+ "node": ">=18"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/express"+ }+ },+ "node_modules/@modelcontextprotocol/sdk/node_modules/negotiator": {+ "version": "1.0.0",+ "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-1.0.0.tgz",+ "integrity": "sha512-8Ofs/AUQh8MaEcrlq5xOX0CQ9ypTF5dl78mjlMNfOK08fzpgTHQRQPBxcPlEtIw0yRpws+Zo/3r+5WRby7u3Gg==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.6"+ }+ },+ "node_modules/@modelcontextprotocol/sdk/node_modules/raw-body": {+ "version": "3.0.2",+ "resolved": "https://registry.npmjs.org/raw-body/-/raw-body-3.0.2.tgz",+ "integrity": "sha512-K5zQjDllxWkf7Z5xJdV0/B0WTNqx6vxG70zJE4N0kBs4LovmEYWJzQGxC9bS9RAKu3bgM40lrd5zoLJ12MQ5BA==",+ "license": "MIT",+ "dependencies": {+ "bytes": "~3.1.2",+ "http-errors": "~2.0.1",+ "iconv-lite": "~0.7.0",+ "unpipe": "~1.0.0"+ },+ "engines": {+ "node": ">= 0.10"+ }+ },+ "node_modules/@modelcontextprotocol/sdk/node_modules/send": {+ "version": "1.2.1",+ "resolved": "https://registry.npmjs.org/send/-/send-1.2.1.tgz",+ "integrity": "sha512-1gnZf7DFcoIcajTjTwjwuDjzuz4PPcY2StKPlsGAQ1+YH20IRVrBaXSWmdjowTJ6u8Rc01PoYOGHXfP1mYcZNQ==",+ "license": "MIT",+ "dependencies": {+ "debug": "^4.4.3",+ "encodeurl": "^2.0.0",+ "escape-html": "^1.0.3",+ "etag": "^1.8.1",+ "fresh": "^2.0.0",+ "http-errors": "^2.0.1",+ "mime-types": "^3.0.2",+ "ms": "^2.1.3",+ "on-finished": "^2.4.1",+ "range-parser": "^1.2.1",+ "statuses": "^2.0.2"+ },+ "engines": {+ "node": ">= 18"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/express"+ }+ },+ "node_modules/@modelcontextprotocol/sdk/node_modules/serve-static": {+ "version": "2.2.1",+ "resolved": "https://registry.npmjs.org/serve-static/-/serve-static-2.2.1.tgz",+ "integrity": "sha512-xRXBn0pPqQTVQiC8wyQrKs2MOlX24zQ0POGaj0kultvoOCstBQM5yvOhAVSUwOMjQtTvsPWoNCHfPGwaaQJhTw==",+ "license": "MIT",+ "dependencies": {+ "encodeurl": "^2.0.0",+ "escape-html": "^1.0.3",+ "parseurl": "^1.3.3",+ "send": "^1.2.0"+ },+ "engines": {+ "node": ">= 18"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/express"+ }+ },+ "node_modules/@modelcontextprotocol/sdk/node_modules/statuses": {+ "version": "2.0.2",+ "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.2.tgz",+ "integrity": "sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.8"+ }+ },+ "node_modules/@modelcontextprotocol/sdk/node_modules/type-is": {+ "version": "2.1.0",+ "resolved": "https://registry.npmjs.org/type-is/-/type-is-2.1.0.tgz",+ "integrity": "sha512-faYHw0anBbc/kWF3zFTEnxSFOAGUX9GFbOBthvDdLsIlEoWOFOtS0zgCiQYwIskL9iGXZL3kAXD8OoZ4GmMATA==",+ "license": "MIT",+ "dependencies": {+ "content-type": "^2.0.0",+ "media-typer": "^1.1.0",+ "mime-types": "^3.0.0"+ },+ "engines": {+ "node": ">= 18"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/express"+ }+ },+ "node_modules/@modelcontextprotocol/sdk/node_modules/type-is/node_modules/content-type": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/content-type/-/content-type-2.0.0.tgz",+ "integrity": "sha512-j/O/d7GcZCyNl7/hwZAb606rzqkyvaDctLmckbxLzHvFBzTJHuGEdodATcP3yIRoDrLHkIATJuvzbFlp/ki2cQ==",+ "license": "MIT",+ "engines": {+ "node": ">=18"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/express"+ }+ },"node_modules/@msgpack/msgpack": {"version": "3.1.3","resolved": "https://registry.npmjs.org/@msgpack/msgpack/-/msgpack-3.1.3.tgz",@@ -26158,6 +26538,27 @@"integrity": "sha512-ofGmfDhxmNT1/P/MgVa8IKSkCStFiyvXe+U5tyZurKdrtTDFU+wJ/LxClPDtFerWpczNFPUSrKcuhfPX1sI6+A==","license": "GPL-3.0-or-later"},+ "node_modules/@x402/axios": {+ "version": "2.12.0",+ "resolved": "https://registry.npmjs.org/@x402/axios/-/axios-2.12.0.tgz",+ "integrity": "sha512-5B+WLrK9YLf1gZSDQ3/kcxQhATN1fQmGaPoF25RAzwqlm9PyukkZ5D/DoGINO6PWnMFRAK7z/McbVI5BPzdT6w==",+ "license": "Apache-2.0",+ "dependencies": {+ "@x402/core": "~2.12.0"+ },+ "peerDependencies": {+ "axios": "^1.7.9"+ }+ },+ "node_modules/@x402/axios/node_modules/@x402/core": {+ "version": "2.12.0",+ "resolved": "https://registry.npmjs.org/@x402/core/-/core-2.12.0.tgz",+ "integrity": "sha512-dLae9AbZRN/W7GsKe9ngqGsflnP+esE72s0GjmqDZbPihM/tlHCA6UnDdgM0qfOiDOf9iL+mmCs1OyLWpwnGLQ==",+ "license": "Apache-2.0",+ "dependencies": {+ "zod": "^3.24.2"+ }+ },"node_modules/@x402/core": {"version": "2.11.0","resolved": "https://registry.npmjs.org/@x402/core/-/core-2.11.0.tgz",@@ -26255,6 +26656,40 @@"zod": "^3.24.2"}},+ "node_modules/@x402/svm": {+ "version": "2.12.0",+ "resolved": "https://registry.npmjs.org/@x402/svm/-/svm-2.12.0.tgz",+ "integrity": "sha512-MgICmyJcwIu15ItPkT4ekiCpP/IczHN00QoXHxr4laWmJ4Eb9UovVq8gqJ+g3R4E5G3oSAXdu9CqRlapefgg/A==",+ "license": "Apache-2.0",+ "dependencies": {+ "@solana-program/compute-budget": "^0.11.0",+ "@solana-program/token": "^0.9.0",+ "@solana-program/token-2022": "^0.6.1",+ "@x402/core": "~2.12.0"+ },+ "peerDependencies": {+ "@solana/kit": ">=5.1.0"+ }+ },+ "node_modules/@x402/svm/node_modules/@solana-program/token-2022": {+ "version": "0.6.1",+ "resolved": "https://registry.npmjs.org/@solana-program/token-2022/-/token-2022-0.6.1.tgz",+ "integrity": "sha512-Ex02cruDMGfBMvZZCrggVR45vdQQSI/unHVpt/7HPt/IwFYB4eTlXtO8otYZyqV/ce5GqZ8S6uwyRf0zy6fdbA==",+ "license": "Apache-2.0",+ "peerDependencies": {+ "@solana/kit": "^5.0",+ "@solana/sysvars": "^5.0"+ }+ },+ "node_modules/@x402/svm/node_modules/@x402/core": {+ "version": "2.12.0",+ "resolved": "https://registry.npmjs.org/@x402/core/-/core-2.12.0.tgz",+ "integrity": "sha512-dLae9AbZRN/W7GsKe9ngqGsflnP+esE72s0GjmqDZbPihM/tlHCA6UnDdgM0qfOiDOf9iL+mmCs1OyLWpwnGLQ==",+ "license": "Apache-2.0",+ "dependencies": {+ "zod": "^3.24.2"+ }+ },"node_modules/@xrplf/isomorphic": {"version": "1.0.1","resolved": "https://registry.npmjs.org/@xrplf/isomorphic/-/isomorphic-1.0.1.tgz",@@ -27470,7 +27905,6 @@"version": "3.0.1","resolved": "https://registry.npmjs.org/ajv-formats/-/ajv-formats-3.0.1.tgz","integrity": "sha512-8iUql50EUR+uUcdRQ3HDqa6EVyo3docL8g5WJ3FNcWmu62IbkGUue/pEyLBW8VGKKucTPgqeks4fIU1DA4yowQ==",- "dev": true,"license": "MIT","dependencies": {"ajv": "^8.0.0"@@ -30047,6 +30481,23 @@"integrity": "sha512-ZQBvi1DcpJ4GDqanjucZ2Hj3wEO5pZDS89BWbkcrvdxksJorwUDDZamX9ldFkp9aw2lmBDLgkObEA4DWNJ9FYQ==","license": "MIT"},+ "node_modules/cors": {+ "version": "2.8.6",+ "resolved": "https://registry.npmjs.org/cors/-/cors-2.8.6.tgz",+ "integrity": "sha512-tJtZBBHA6vjIAaF6EnIaq6laBBP9aq/Y3ouVJjEfoHbRBcHBAHYcMh/w8LDrk2PvIMMq8gmopa5D4V8RmbrxGw==",+ "license": "MIT",+ "dependencies": {+ "object-assign": "^4",+ "vary": "^1"+ },+ "engines": {+ "node": ">= 0.10"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/express"+ }+ },"node_modules/cosmiconfig": {"version": "9.0.1","resolved": "https://registry.npmjs.org/cosmiconfig/-/cosmiconfig-9.0.1.tgz",@@ -34034,6 +34485,24 @@"url": "https://opencollective.com/express"}},+ "node_modules/express-rate-limit": {+ "version": "8.5.2",+ "resolved": "https://registry.npmjs.org/express-rate-limit/-/express-rate-limit-8.5.2.tgz",+ "integrity": "sha512-5Kb34ipNX694DH48vN9irak1Qx30nb0PLYHXfJgw4YEjiC3ZEmZJhwOp+VfiCYwFzvFTdB9QkArYS5kXa2cx2A==",+ "license": "MIT",+ "dependencies": {+ "ip-address": "^10.2.0"+ },+ "engines": {+ "node": ">= 16"+ },+ "funding": {+ "url": "https://github.com/sponsors/express-rate-limit"+ },+ "peerDependencies": {+ "express": ">= 4.11"+ }+ },"node_modules/express/node_modules/cookie": {"version": "0.7.2","resolved": "https://registry.npmjs.org/cookie/-/cookie-0.7.2.tgz",@@ -37096,6 +37565,15 @@"react-is": "^16.7.0"}},+ "node_modules/hono": {+ "version": "4.12.21",+ "resolved": "https://registry.npmjs.org/hono/-/hono-4.12.21.tgz",+ "integrity": "sha512-uV63apnb0kyPtAUwoWgaGh9HyIFcv8lgmzPZSiTBQAFOFGIzka5EZ1dZocmGnn0XdX0+XTqJ6Tqv7selMuGLRQ==",+ "license": "MIT",+ "engines": {+ "node": ">=16.9.0"+ }+ },"node_modules/howler": {"version": "2.2.4","resolved": "https://registry.npmjs.org/howler/-/howler-2.2.4.tgz",@@ -37579,9 +38057,9 @@"license": "MIT"},"node_modules/ip-address": {- "version": "10.1.1",- "resolved": "https://registry.npmjs.org/ip-address/-/ip-address-10.1.1.tgz",- "integrity": "sha512-1FMu8/N15Ck1BL551Jf42NYIoin2unWjLQ2Fze/DXryJRl5twqtwNHlO39qERGbIOcKYWHdgRryhOC+NG4eaLw==",+ "version": "10.2.0",+ "resolved": "https://registry.npmjs.org/ip-address/-/ip-address-10.2.0.tgz",+ "integrity": "sha512-/+S6j4E9AHvW9SWMSEY9Xfy66O5PWvVEJ08O0y5JGyEKQpojb0K0GKpz/v5HJ/G0vi3D2sjGK78119oXZeE0qA==","license": "MIT","engines": {"node": ">= 12"@@ -38294,6 +38772,12 @@"dev": true,"license": "MIT"},+ "node_modules/is-promise": {+ "version": "4.0.0",+ "resolved": "https://registry.npmjs.org/is-promise/-/is-promise-4.0.0.tgz",+ "integrity": "sha512-hvpoI6korhJMnej285dSg6nu1+e6uxs7zG3BYAm5byqDsgJNWwxzM6z6iZiAgQR4TJ30JmBTOwqZUw3WlyH3AQ==",+ "license": "MIT"+ },"node_modules/is-regex": {"version": "1.2.1","resolved": "https://registry.npmjs.org/is-regex/-/is-regex-1.2.1.tgz",@@ -40998,6 +41482,12 @@"integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==","license": "MIT"},+ "node_modules/json-schema-typed": {+ "version": "8.0.2",+ "resolved": "https://registry.npmjs.org/json-schema-typed/-/json-schema-typed-8.0.2.tgz",+ "integrity": "sha512-fQhoXdcvc3V28x7C7BMs4P5+kNlgUURe2jmUT1T//oBRMDrqy1QPelJimwZGo7Hg9VPV3EQV5Bnq4hbFy2vetA==",+ "license": "BSD-2-Clause"+ },"node_modules/json-stable-stringify": {"version": "1.3.0","resolved": "https://registry.npmjs.org/json-stable-stringify/-/json-stable-stringify-1.3.0.tgz",@@ -45379,6 +45869,15 @@"node": ">= 6"}},+ "node_modules/pkce-challenge": {+ "version": "5.0.1",+ "resolved": "https://registry.npmjs.org/pkce-challenge/-/pkce-challenge-5.0.1.tgz",+ "integrity": "sha512-wQ0b/W4Fr01qtpHlqSqspcj3EhBvimsdh0KlHhH8HRZnMsEa0ea2fTULOXOS9ccQr3om+GcGRk4e+isrZWV8qQ==",+ "license": "MIT",+ "engines": {+ "node": ">=16.20.0"+ }+ },"node_modules/pkg-dir": {"version": "4.2.0","resolved": "https://registry.npmjs.org/pkg-dir/-/pkg-dir-4.2.0.tgz",@@ -47550,6 +48049,32 @@"dev": true,"license": "MIT"},+ "node_modules/router": {+ "version": "2.2.0",+ "resolved": "https://registry.npmjs.org/router/-/router-2.2.0.tgz",+ "integrity": "sha512-nLTrUKm2UyiL7rlhapu/Zl45FwNgkZGaCpZbIHajDYgwlJCOzLSk+cIPAnsEqV955GjILJnKbdQC1nVPz+gAYQ==",+ "license": "MIT",+ "dependencies": {+ "debug": "^4.4.0",+ "depd": "^2.0.0",+ "is-promise": "^4.0.0",+ "parseurl": "^1.3.3",+ "path-to-regexp": "^8.0.0"+ },+ "engines": {+ "node": ">= 18"+ }+ },+ "node_modules/router/node_modules/path-to-regexp": {+ "version": "8.4.2",+ "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-8.4.2.tgz",+ "integrity": "sha512-qRcuIdP69NPm4qbACK+aDogI5CBDMi1jKe0ry5rSQJz8JVLsC7jV8XpiJjGRLLol3N+R5ihGYcrPLTno6pAdBA==",+ "license": "MIT",+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/express"+ }+ },"node_modules/rpc-websockets": {"version": "9.3.8","resolved": "https://registry.npmjs.org/rpc-websockets/-/rpc-websockets-9.3.8.tgz",@@ -54209,6 +54734,15 @@"url": "https://github.com/sponsors/colinhacks"}},+ "node_modules/zod-to-json-schema": {+ "version": "3.25.2",+ "resolved": "https://registry.npmjs.org/zod-to-json-schema/-/zod-to-json-schema-3.25.2.tgz",+ "integrity": "sha512-O/PgfnpT1xKSDeQYSCfRI5Gy3hPf91mKVDuYLUHZJMiDFptvP41MSnWofm8dnCm0256ZNfZIM7DSzuSMAFnjHA==",+ "license": "ISC",+ "peerDependencies": {+ "zod": "^3.25.28 || ^4"+ }+ },"node_modules/zustand": {"version": "3.7.2","resolved": "https://registry.npmjs.org/zustand/-/zustand-3.7.2.tgz",diff --git a/package.json b/package.jsonindex 1db9e622d..0b5128dc4 100644--- a/package.json+++ b/package.json@@ -110,6 +110,7 @@"@metaplex-foundation/mpl-core": "^1.10.0","@metaplex-foundation/umi": "^1.5.1","@metaplex-foundation/umi-bundle-defaults": "^1.5.1",+ "@modelcontextprotocol/sdk": "^1.29.0","@neondatabase/serverless": "^0.10.1","@neynar/nodejs-sdk": "^3.174.0","@nirholas/pump-sdk": "^1.0.0",@@ -138,10 +139,12 @@"@upstash/ratelimit": "^2.0.5","@upstash/redis": "^1.34.3","@vercel/og": "^0.11.1",+ "@x402/axios": "^2.12.0","@x402/core": "^2.11.0","@x402/evm": "^2.11.0","@x402/express": "^2.11.0","@x402/extensions": "^2.11.0",+ "@x402/svm": "^2.12.0","@zauthx402/sdk": "^0.1.14","agent0-sdk": "^1.7.1","ai": "^6.0.184",diff --git a/pages/club.html b/pages/club.htmlindex 9a8bd6647..cab0d6ba3 100644--- a/pages/club.html+++ b/pages/club.html@@ -225,6 +225,27 @@display: flex;flex-direction: column;gap: 0;+ /* Touch handling: the canvas owns horizontal drag (orbit),+ the panel scrolls vertically. `pan-y` lets the user+ flick-scroll the tip feed without the orbit handler+ intercepting on the panel. */+ touch-action: pan-y;+ }+ /* Bottom-sheet drag handle — only visible on mobile (see media+ query at the bottom of this stylesheet). */+ #club-sheet-handle {+ display: none;+ }+ /* Mobile-only: hide the summary's default marker; we render our+ own pill. On desktop the leaderboard is always expanded and+ the summary is hidden. */+ .club-lb-details > summary {+ list-style: none;+ cursor: pointer;+ }+ .club-lb-details > summary::-webkit-details-marker { display: none; }+ @media (min-width: 801px) {+ .club-lb-details > summary { display: none; }}.club-section {padding: 16px 16px 14px;@@ -529,16 +550,126 @@@media (max-width: 800px) {#club-app {grid-template-columns: 1fr;- grid-template-rows: 52px 1fr auto;+ grid-template-rows: 52px 1fr;grid-template-areas:"top"- "stage"- "right";+ "stage";}+ /* Bottom-sheet: the panel is fixed to the viewport bottom+ instead of stacking in the grid, so the canvas can fill+ the screen. Two heights — peeking (collapsed) and full+ (expanded). Toggled via the .is-expanded class, set by+ tapping the drag handle. CSS transform animates the+ slide without a JS gesture library. */#club-right {+ position: fixed;+ left: 0;+ right: 0;+ bottom: 0;+ grid-area: unset;border-left: none;- border-top: 1px solid var(--border);- max-height: 45vh;+ border-top: 1px solid var(--border-strong);+ border-top-left-radius: 16px;+ border-top-right-radius: 16px;+ max-height: 85vh;+ height: 85vh;+ /* Slide the bulk of the panel below the fold; only the+ handle + the "Poles" section peek above. Bumped to+ include both the safe-area inset and the iOS bottom+ bar so the tip buttons stay reachable. */+ transform: translateY(calc(85vh - 240px));+ transition: transform 0.28s cubic-bezier(0.2, 0.7, 0.2, 1);+ box-shadow: 0 -12px 32px rgba(0, 0, 0, 0.55);+ z-index: 12;+ padding-bottom: env(safe-area-inset-bottom, 0px);+ }+ #club-right.is-expanded {+ transform: translateY(0);+ }+ #club-sheet-handle {+ display: flex;+ align-items: center;+ justify-content: center;+ position: sticky;+ top: 0;+ left: 0;+ right: 0;+ padding: 10px 0 8px;+ background: var(--panel-solid);+ border-top-left-radius: 16px;+ border-top-right-radius: 16px;+ /* 44pt min touch target per Apple HIG / Material spec. */+ min-height: 44px;+ cursor: pointer;+ appearance: none;+ border: none;+ width: 100%;+ font: inherit;+ color: var(--text-3);+ z-index: 1;+ }+ #club-sheet-handle::before {+ content: '';+ width: 36px;+ height: 4px;+ border-radius: 999px;+ background: var(--text-3);+ opacity: 0.5;+ }+ /* When the sheet is collapsed, the leaderboard + tip-feed+ sections sit below the fold; we still ship them in DOM+ order so tapping the handle reveals everything. The+ `<details>` wrapper around the leaderboard means the+ user can also keep it tucked away when expanded. */++ /* Touch-target sizing on small screens — 44x44 minimum. */+ .club-cam-btn {+ min-width: 44px;+ min-height: 44px;+ padding: 6px 8px;+ font-size: 14px;+ }+ .club-tip-btn {+ min-height: 44px;+ font-size: 13px;+ }+ .club-pole-select {+ min-height: 36px;+ font-size: 14px;+ }+ .club-lb-tab {+ min-height: 36px;+ padding: 6px 12px;+ }+ /* The canvas owns all pointer gestures (orbit + pinch). */+ #club-canvas { touch-action: none; }++ /* Mobile-only summary styling — a compact pill that mirrors+ the existing section header but signals tap-to-expand. */+ .club-lb-details > summary {+ display: flex;+ align-items: center;+ justify-content: space-between;+ margin: 0 0 12px;+ font-size: 11px;+ font-weight: 700;+ color: var(--text-3);+ letter-spacing: 0.1em;+ text-transform: uppercase;+ min-height: 36px;+ }+ .club-lb-details > summary::after {+ content: '▾';+ font-size: 14px;+ transition: transform 0.18s ease;+ }+ .club-lb-details[open] > summary::after {+ transform: rotate(180deg);+ }+ /* The inner <h2> duplicates the <summary> label on mobile;+ hide it so users only see one "Leaderboard" heading. */+ .club-lb-details > h2 {+ display: none;}}</style>@@ -575,6 +706,13 @@<!-- RIGHT PANEL --><aside id="club-right">+ <button+ id="club-sheet-handle"+ type="button"+ aria-label="Expand or collapse panel"+ aria-controls="club-right"+ aria-expanded="false"+ ></button><section class="club-section"><h2>How it works</h2><p class="club-intro">@@ -598,15 +736,18 @@</section><section class="club-section">- <h2>Leaderboard</h2>- <div class="club-lb-tabs" role="tablist">- <button type="button" class="club-lb-tab is-active" data-window="day" role="tab">24h</button>- <button type="button" class="club-lb-tab" data-window="hour" role="tab">1h</button>- <button type="button" class="club-lb-tab" data-window="all" role="tab">All</button>- </div>- <div id="club-lb-rows">- <div class="club-lb-empty">Loading…</div>- </div>+ <details class="club-lb-details" id="club-lb-details">+ <summary>Leaderboard</summary>+ <h2>Leaderboard</h2>+ <div class="club-lb-tabs" role="tablist">+ <button type="button" class="club-lb-tab is-active" data-window="day" role="tab">24h</button>+ <button type="button" class="club-lb-tab" data-window="hour" role="tab">1h</button>+ <button type="button" class="club-lb-tab" data-window="all" role="tab">All</button>+ </div>+ <div id="club-lb-rows">+ <div class="club-lb-empty">Loading…</div>+ </div>+ </details></section><section class="club-section">diff --git a/public/bazaar.html b/public/bazaar.htmlnew file mode 100644index 000000000..46adf56ae--- /dev/null+++ b/public/bazaar.html@@ -0,0 +1,410 @@+<!doctype html>+<html lang="en">+<head>+<meta charset="utf-8" />+<meta name="viewport" content="width=device-width,initial-scale=1" />+<title>x402 Bazaar — discover paid APIs and MCP tools</title>+<meta name="description" content="Search and browse the x402 facilitator catalog. Filter by network, price, extensions. Pay any service in one click." />+<meta name="theme-color" content="#0a0b10" />+<meta property="og:title" content="x402 Bazaar — discover paid APIs and MCP tools" />+<meta property="og:description" content="Search and browse the x402 facilitator catalog. Filter by network, price, extensions. Pay any service in one click." />+<meta property="og:type" content="website" />+<style>+ :root {+ --bg: #0a0b10;+ --bg-2: #0f1119;+ --panel: #14161f;+ --panel-2: #1a1d29;+ --border: #232636;+ --border-strong: #2e3447;+ --text: #f0f2f8;+ --muted: #8a90a8;+ --muted-2: #6b7088;+ --accent: #ffffff;+ --accent-blue: #60a5fa;+ --accent-green: #4ade80;+ --accent-red: #f87171;+ --mono: ui-monospace, "JetBrains Mono", "Fira Code", Menlo, monospace;+ }+ * { box-sizing: border-box; }+ html, body { margin: 0; padding: 0; background: var(--bg); color: var(--text); }+ body {+ font-family: -apple-system, BlinkMacSystemFont, "Inter", "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;+ -webkit-font-smoothing: antialiased;+ line-height: 1.5;+ min-height: 100vh;+ }+ a { color: var(--accent-blue); text-decoration: none; }+ a:hover { color: #93c5fd; }++ .wrap { max-width: 1280px; margin: 0 auto; padding: 0 28px; }+ @media (max-width: 720px) { .wrap { padding: 0 16px; } }++ nav {+ padding: 22px 0;+ display: flex; align-items: center; justify-content: space-between;+ border-bottom: 1px solid var(--border);+ }+ nav .brand { display: flex; align-items: center; gap: 10px; font-weight: 700; font-size: 16px; letter-spacing: -0.01em; }+ nav .brand .dot {+ width: 22px; height: 22px;+ background: conic-gradient(from 200deg, #ffffff, #60a5fa, #ffffff);+ border-radius: 6px;+ }+ nav .links { display: flex; gap: 18px; font-size: 13.5px; color: var(--muted); }+ nav .links a { color: var(--muted); }+ nav .links a:hover { color: var(--text); }++ header.hero { padding: 44px 0 18px; }+ header.hero h1 { font-size: 36px; line-height: 1.1; margin: 0 0 8px; letter-spacing: -0.02em; }+ header.hero p { color: var(--muted); margin: 0; font-size: 15px; max-width: 680px; }++ .search-bar {+ margin: 22px 0 6px;+ display: flex; gap: 10px; flex-wrap: wrap;+ }+ .search-bar input[type=search] {+ flex: 1 1 360px;+ min-width: 200px;+ background: var(--panel);+ border: 1px solid var(--border-strong);+ color: var(--text);+ font-size: 15px;+ padding: 12px 14px;+ border-radius: 10px;+ outline: none;+ }+ .search-bar input[type=search]:focus { border-color: var(--accent-blue); }+ .search-bar button {+ background: var(--accent-blue);+ color: #0a0b10;+ border: none;+ font-weight: 600;+ padding: 0 20px;+ border-radius: 10px;+ cursor: pointer;+ font-size: 14px;+ }+ .search-bar button.ghost {+ background: var(--panel);+ color: var(--text);+ border: 1px solid var(--border-strong);+ }+ .search-bar button:hover { filter: brightness(1.08); }++ .layout {+ display: grid;+ grid-template-columns: 260px 1fr;+ gap: 28px;+ padding: 24px 0 56px;+ }+ @media (max-width: 960px) { .layout { grid-template-columns: 1fr; } }++ aside.filters {+ background: var(--panel);+ border: 1px solid var(--border);+ border-radius: 12px;+ padding: 18px;+ height: max-content;+ position: sticky;+ top: 16px;+ }+ aside.filters h3 {+ margin: 0 0 12px;+ font-size: 11px;+ text-transform: uppercase;+ letter-spacing: 0.08em;+ color: var(--muted);+ font-weight: 600;+ }+ aside.filters .group { margin-bottom: 18px; }+ aside.filters label {+ display: block;+ font-size: 13px;+ color: var(--muted);+ margin-bottom: 6px;+ }+ aside.filters select, aside.filters input[type=number], aside.filters input[type=text] {+ width: 100%;+ background: var(--panel-2);+ border: 1px solid var(--border);+ color: var(--text);+ padding: 8px 10px;+ border-radius: 8px;+ font-size: 13.5px;+ outline: none;+ }+ aside.filters select:focus, aside.filters input:focus { border-color: var(--accent-blue); }+ aside.filters .row { display: flex; gap: 8px; }+ aside.filters .row > * { flex: 1; }+ aside.filters .reset {+ width: 100%;+ background: transparent;+ border: 1px solid var(--border-strong);+ color: var(--muted);+ padding: 8px;+ border-radius: 8px;+ cursor: pointer;+ font-size: 13px;+ }+ aside.filters .reset:hover { color: var(--text); border-color: var(--accent-blue); }++ .results-meta {+ display: flex;+ align-items: baseline;+ justify-content: space-between;+ gap: 12px;+ margin-bottom: 14px;+ color: var(--muted);+ font-size: 13px;+ }+ .results-meta strong { color: var(--text); font-weight: 600; }+ .results-meta select {+ background: var(--panel);+ color: var(--text);+ border: 1px solid var(--border);+ padding: 6px 10px;+ border-radius: 8px;+ font-size: 13px;+ }++ .cards {+ display: grid;+ grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));+ gap: 14px;+ }+ .card {+ background: var(--panel);+ border: 1px solid var(--border);+ border-radius: 12px;+ padding: 16px;+ display: flex;+ flex-direction: column;+ gap: 10px;+ min-height: 200px;+ }+ .card:hover { border-color: var(--border-strong); }+ .card .head { display: flex; align-items: center; gap: 10px; }+ .card .icon {+ width: 36px; height: 36px;+ border-radius: 8px;+ background: var(--panel-2);+ border: 1px solid var(--border);+ display: flex; align-items: center; justify-content: center;+ flex-shrink: 0;+ font-size: 14px;+ color: var(--muted);+ overflow: hidden;+ }+ .card .icon img { width: 100%; height: 100%; object-fit: cover; }+ .card .title { font-weight: 600; font-size: 14px; line-height: 1.3; word-break: break-word; }+ .card .subtitle { color: var(--muted); font-size: 12px; word-break: break-all; }+ .card .desc { color: var(--muted); font-size: 13px; flex-grow: 1; }+ .card .meta { display: flex; gap: 6px; flex-wrap: wrap; font-size: 11px; }+ .tag {+ background: var(--panel-2);+ border: 1px solid var(--border);+ color: var(--muted);+ padding: 3px 8px;+ border-radius: 999px;+ font-family: var(--mono);+ font-size: 11px;+ }+ .tag.price { color: var(--accent-green); border-color: rgba(74,222,128,0.3); }+ .tag.net { color: var(--accent-blue); border-color: rgba(96,165,250,0.3); }+ .tag.method { color: var(--text); }+ .tag.ext { color: #c084fc; border-color: rgba(192,132,252,0.3); }+ .card .actions { display: flex; gap: 8px; margin-top: 4px; }+ .btn-pay {+ background: var(--accent-blue);+ color: #0a0b10;+ border: none;+ padding: 9px 14px;+ font-size: 13px;+ border-radius: 8px;+ cursor: pointer;+ font-weight: 600;+ }+ .btn-pay:hover { filter: brightness(1.1); }+ .btn-pay:disabled { opacity: 0.55; cursor: progress; }+ .btn-details {+ background: transparent;+ border: 1px solid var(--border-strong);+ color: var(--text);+ padding: 9px 12px;+ font-size: 13px;+ border-radius: 8px;+ cursor: pointer;+ }+ .btn-details:hover { border-color: var(--accent-blue); }++ .receipt {+ margin-top: 8px;+ padding: 10px 12px;+ background: var(--bg-2);+ border: 1px solid var(--border);+ border-radius: 8px;+ font-family: var(--mono);+ font-size: 12px;+ color: var(--muted);+ max-height: 260px;+ overflow: auto;+ white-space: pre-wrap;+ word-break: break-all;+ }+ .receipt.ok { border-color: rgba(74,222,128,0.4); color: #d1fae5; }+ .receipt.err { border-color: rgba(248,113,113,0.4); color: #fecaca; }+ .receipt a { color: var(--accent-blue); }++ .empty {+ padding: 60px 20px;+ text-align: center;+ color: var(--muted);+ border: 1px dashed var(--border-strong);+ border-radius: 12px;+ }+ .spinner {+ display: inline-block;+ width: 14px; height: 14px;+ border: 2px solid var(--border-strong);+ border-top-color: var(--accent-blue);+ border-radius: 50%;+ animation: spin 0.7s linear infinite;+ vertical-align: -2px;+ }+ @keyframes spin { to { transform: rotate(360deg); } }++ .sources {+ font-size: 11px;+ color: var(--muted-2);+ font-family: var(--mono);+ margin-top: 6px;+ }+ .sources .ok { color: #4ade80; }+ .sources .err { color: var(--accent-red); }++ dialog.modal {+ background: var(--panel);+ color: var(--text);+ border: 1px solid var(--border-strong);+ border-radius: 14px;+ max-width: 720px;+ width: calc(100% - 32px);+ padding: 0;+ }+ dialog.modal::backdrop { background: rgba(0,0,0,0.65); }+ dialog.modal header { padding: 18px 20px; border-bottom: 1px solid var(--border); display: flex; align-items: center; justify-content: space-between; }+ dialog.modal header h2 { margin: 0; font-size: 15px; font-weight: 600; }+ dialog.modal header button { background: transparent; color: var(--muted); border: none; cursor: pointer; font-size: 22px; line-height: 1; }+ dialog.modal section { padding: 16px 20px; }+ dialog.modal pre {+ background: var(--bg-2);+ border: 1px solid var(--border);+ padding: 12px;+ border-radius: 8px;+ overflow: auto;+ font-family: var(--mono);+ font-size: 12px;+ color: var(--muted);+ max-height: 360px;+ }+</style>+</head>+<body>+<div class="wrap">+ <nav>+ <div class="brand"><span class="dot"></span><span>x402 bazaar</span></div>+ <div class="links">+ <a href="/">Home</a>+ <a href="https://www.x402.org/docs/extensions/bazaar" target="_blank" rel="noopener">Spec</a>+ <a href="/.well-known/x402.json">Our listing</a>+ </div>+ </nav>+ <header class="hero">+ <h1>Discover paid APIs and MCP tools</h1>+ <p>Live catalog merged across x402 facilitators. Search, filter, and pay any endpoint with a single click — settlement is on-chain via the x402 protocol.</p>+ </header>++ <form class="search-bar" id="search-form" autocomplete="off">+ <input type="search" id="q" name="q" placeholder="Search: weather, sanctions, mcp tools, address…" />+ <button type="submit">Search</button>+ <button type="button" class="ghost" id="clear-btn">Clear</button>+ </form>++ <div class="layout">+ <aside class="filters">+ <h3>Filters</h3>+ <div class="group">+ <label for="f-type">Type</label>+ <select id="f-type">+ <option value="http">HTTP endpoints</option>+ <option value="mcp">MCP tools</option>+ </select>+ </div>+ <div class="group">+ <label for="f-network">Network</label>+ <select id="f-network">+ <option value="">All networks</option>+ <option value="eip155:*">EVM (any)</option>+ <option value="eip155:8453">Base</option>+ <option value="eip155:42161">Arbitrum</option>+ <option value="eip155:10">Optimism</option>+ <option value="eip155:137">Polygon</option>+ <option value="solana:*">Solana (any)</option>+ </select>+ </div>+ <div class="group">+ <label for="f-max">Max price (USDC)</label>+ <div class="row">+ <input type="number" id="f-max" placeholder="0.10" step="0.001" min="0" />+ </div>+ </div>+ <div class="group">+ <label for="f-ext">Extension</label>+ <select id="f-ext">+ <option value="">Any</option>+ <option value="bazaar">bazaar</option>+ <option value="sign-in-with-x">sign-in-with-x</option>+ <option value="payment-identifier">payment-identifier</option>+ <option value="offer-receipt">offer-receipt</option>+ </select>+ </div>+ <div class="group">+ <label for="f-sort">Sort by</label>+ <select id="f-sort">+ <option value="">Default (rank or facilitator order)</option>+ <option value="price">Price (lowest first)</option>+ </select>+ </div>+ <button type="button" class="reset" id="reset-btn">Reset filters</button>+ </aside>++ <main>+ <div class="results-meta">+ <div>+ <strong id="count">…</strong>+ <span> results <span id="qlabel"></span></span>+ <div class="sources" id="sources"></div>+ </div>+ </div>+ <div id="results" class="cards"></div>+ <div id="empty" class="empty" hidden>No matching services. Try fewer filters or a different query.</div>+ </main>+ </div>+</div>++<dialog class="modal" id="details-modal">+ <header>+ <h2 id="dm-title">Resource details</h2>+ <button type="button" id="dm-close" aria-label="Close">×</button>+ </header>+ <section>+ <div id="dm-body"></div>+ </section>+</dialog>++<!-- The drop-in x402 modal, which we use for the "Try it" pay flow. -->+<script type="module" src="/x402.js"></script>+<script type="module" src="/bazaar.js"></script>+</body>+</html>diff --git a/public/home.css b/public/home.cssindex 0f564b764..de6f83f98 100644--- a/public/home.css+++ b/public/home.css@@ -1720,219 +1720,9 @@width: 100%;}-/* ── Nav ── */--.home-nav {- margin-left: auto;- display: flex;- align-items: center;- gap: var(--space-lg);- -webkit-app-region: no-drag;-}--.home-nav a {- color: rgba(255, 255, 255, 0.6);- text-decoration: none;- font-size: 0.92rem;- font-weight: 500;- letter-spacing: 0.005em;- font-family: 'Space Grotesk', 'Inter', sans-serif;- transition: color 0.2s ease;-}--.home-nav a:hover {- color: #fff;-}--.home-nav .nav-cta {- padding: 0.5rem 1.2rem;- background: linear-gradient(135deg, #ffd76a 0%, #ff8f4d 100%);- color: #1a0f08;- border-radius: 6px;- font-weight: 600;- font-size: 0.9rem;- box-shadow: 0 4px 18px -6px rgba(255, 143, 77, 0.6);- transition:- transform 0.25s cubic-bezier(0.2, 0.9, 0.3, 1),- box-shadow 0.25s ease;-}--.home-nav .nav-cta:hover {- transform: translateY(-1px) scale(1.03);- box-shadow: 0 8px 24px -6px rgba(255, 143, 77, 0.8);- color: #1a0f08;-}--.home-nav .nav-user {- display: inline-flex;- align-items: center;- gap: 6px;- padding: 4px 10px;- border-radius: 20px;- border: 1px solid rgba(255, 255, 255, 0.1);- background: rgba(255, 255, 255, 0.04);- font-size: 0.85rem;- color: rgba(255, 255, 255, 0.55);- max-width: 140px;- overflow: hidden;- text-overflow: ellipsis;- white-space: nowrap;-}--.home-nav .nav-user::before {- content: '';- width: 6px;- height: 6px;- border-radius: 50%;- background: #4ade80;- flex-shrink: 0;-}--.home-nav .nav-user:hover {- color: rgba(255, 255, 255, 0.85);- border-color: rgba(255, 255, 255, 0.2);- background: rgba(255, 255, 255, 0.07);-}--/* ── Dropdown nav ── */-.home-nav .nav-root,-.home-nav .nav-menu {- list-style: none !important;- margin: 0;- padding: 0;-}--.home-nav .nav-root {- display: flex !important;- align-items: center;- gap: var(--space-lg);-}--.home-nav .nav-item {- position: relative;- display: block;-}--.home-nav .nav-item[hidden] {- display: none !important;-}--.home-nav .nav-menu li {- display: block;- margin: 0;- padding: 0;-}--.home-nav .nav-trigger {- display: inline-flex;- align-items: center;- gap: 4px;- background: none;- border: 0;- padding: 0;- cursor: pointer;- color: rgba(255, 255, 255, 0.6);- font: inherit;- font-size: 0.92rem;- font-weight: 500;- letter-spacing: 0.005em;- font-family: 'Space Grotesk', 'Inter', sans-serif;- transition: color 0.2s ease;-}--.home-nav .nav-trigger:hover,-.home-nav .nav-trigger[aria-expanded='true'] {- color: #fff;-}--.home-nav .nav-caret {- font-size: 0.7em;- opacity: 0.7;- transition: transform 0.2s ease;-}--.home-nav .nav-trigger[aria-expanded='true'] .nav-caret {- transform: rotate(180deg);-}--.home-nav .nav-menu {- position: absolute;- top: calc(100% + 14px);- left: -12px;- min-width: 240px;- margin: 0;- padding: 8px;- list-style: none;- background: rgba(14, 12, 22, 0.92);- backdrop-filter: blur(18px) saturate(140%);- -webkit-backdrop-filter: blur(18px) saturate(140%);- border: 1px solid rgba(255, 255, 255, 0.08);- border-radius: 12px;- box-shadow:- 0 20px 40px -12px rgba(0, 0, 0, 0.6),- 0 4px 12px -4px rgba(0, 0, 0, 0.5);- opacity: 0;- transform: translateY(-6px);- pointer-events: none;- transition:- opacity 0.18s ease,- transform 0.18s ease;- z-index: 1000;-}--.home-nav .nav-trigger[aria-expanded='true'] + .nav-menu {- opacity: 1;- transform: translateY(0);- pointer-events: auto;-}--.home-nav .nav-menu a {- display: flex;- flex-direction: column;- gap: 2px;- padding: 10px 12px;- border-radius: 8px;- color: rgba(255, 255, 255, 0.85);- text-decoration: none;- transition:- background 0.15s ease,- color 0.15s ease;-}--.home-nav .nav-menu a:hover,-.home-nav .nav-menu a:focus-visible {- background: rgba(255, 255, 255, 0.06);- color: #fff;-}--.home-nav .nav-mi-title {- font-size: 0.92rem;- font-weight: 500;- letter-spacing: 0.005em;-}--.home-nav .nav-mi-sub {- font-size: 0.78rem;- color: rgba(255, 255, 255, 0.45);- font-weight: 400;-}--.home-nav .nav-menu a:hover .nav-mi-sub,-.home-nav .nav-menu a:focus-visible .nav-mi-sub {- color: rgba(255, 255, 255, 0.65);-}--@media (max-width: 900px) {- .home-nav .nav-root {- gap: var(--space-md);- flex-wrap: wrap;- justify-content: flex-end;- }- .home-nav .nav-menu {- left: auto;- right: 0;- }-}+/* All .home-nav styles (desktop dropdowns + mobile hamburger panel) live in+ /public/nav.css. The previous duplicate here overrode nav.css's mobile+ media query and prevented the menu from collapsing on phones. *//* ── Scroll reveal ── */diff --git a/public/reputation/index.html b/public/reputation/index.htmlindex 95ad38e1a..9116c384b 100644--- a/public/reputation/index.html+++ b/public/reputation/index.html@@ -11,6 +11,7 @@<link rel="shortcut icon" href="/favicon.ico" /><link rel="stylesheet" href="/fonts/fonts.css" /><link rel="stylesheet" href="/style.css" />+ <link rel="stylesheet" href="/nav.css" /><link rel="stylesheet" href="/home.css" /><link rel="stylesheet" href="/footer.css" /><script defer src="/footer-newsletter.js"></script>@@ -526,59 +527,9 @@>three.ws</a></h1>- <nav class="home-nav" aria-label="Primary">- <ul class="nav-root" role="menubar">- <li class="nav-item nav-has-menu" role="none">- <button type="button" class="nav-trigger" aria-haspopup="true" aria-expanded="false" role="menuitem">- Build<span class="nav-caret" aria-hidden="true">▾</span>- </button>- <ul class="nav-menu" role="menu" aria-label="Build">- <li role="none"><a href="/create" role="menuitem"><span class="nav-mi-title">Create agent</span><span class="nav-mi-sub">Avatar + brain wizard</span></a></li>- <li role="none"><a href="/app" role="menuitem"><span class="nav-mi-title">Viewer</span><span class="nav-mi-sub">Drag-and-drop GLB</span></a></li>- <li role="none"><a href="/validation" role="menuitem"><span class="nav-mi-title">glTF Validator</span><span class="nav-mi-sub">Khronos spec check</span></a></li>- </ul>- </li>- <li role="none"><a href="/discover" role="menuitem">Discover</a></li>- <li class="nav-item nav-has-menu" role="none">- <button type="button" class="nav-trigger" aria-haspopup="true" aria-expanded="false" role="menuitem">- Solana<span class="nav-caret" aria-hidden="true">▾</span>- </button>- <ul class="nav-menu" role="menu" aria-label="Solana">- <li role="none"><a href="/pumpfun" role="menuitem"><span class="nav-mi-title">Pump.fun stream</span><span class="nav-mi-sub">Mint agent tokens</span></a></li>- <li role="none"><a href="/vanity-wallet" role="menuitem"><span class="nav-mi-title">Vanity wallet</span><span class="nav-mi-sub">Grind a Solana address</span></a></li>- <li role="none"><a href="/eth-vanity" role="menuitem"><span class="nav-mi-title">ETH vanity (CREATE2)</span><span class="nav-mi-sub">Grind a smart-contract address</span></a></li>- <li role="none"><a href="/strategy-lab" role="menuitem"><span class="nav-mi-title">Strategy Lab</span><span class="nav-mi-sub">DCA + subscriptions</span></a></li>- <li role="none"><a href="/pump-live" role="menuitem"><span class="nav-mi-title">Live launches</span><span class="nav-mi-sub">Real-time mint feed</span></a></li>- <li role="none"><a href="/pump-dashboard" role="menuitem"><span class="nav-mi-title">Pump Dashboard</span><span class="nav-mi-sub">Watches · scanner · quotes</span></a></li>- <li role="none"><a href="/docs#solana" role="menuitem"><span class="nav-mi-title">Solana SDK</span><span class="nav-mi-sub">Attestations + agent-kit</span></a></li>- </ul>- </li>- <li class="nav-item nav-has-menu" role="none">- <button type="button" class="nav-trigger" aria-haspopup="true" aria-expanded="false" role="menuitem">- Embed<span class="nav-caret" aria-hidden="true">▾</span>- </button>- <ul class="nav-menu" role="menu" aria-label="Embed">- <li role="none"><a href="/studio" role="menuitem"><span class="nav-mi-title">Widget Studio</span><span class="nav-mi-sub">Pick avatar → copy snippet</span></a></li>- <li role="none"><a href="/artifact" role="menuitem"><span class="nav-mi-title">Artifact viewer</span><span class="nav-mi-sub">Claude artifact bundle</span></a></li>- <li role="none"><a href="/docs#embedding" role="menuitem"><span class="nav-mi-title">Embed docs</span><span class="nav-mi-sub">iframe + oEmbed</span></a></li>- <li role="none"><a href="/docs#web-component" role="menuitem"><span class="nav-mi-title"><agent-3d></span><span class="nav-mi-sub">Web component reference</span></a></li>- </ul>- </li>- <li class="nav-item" role="none"><a href="/marketplace" role="menuitem">Marketplace</a></li>- <li class="nav-item" role="none"><a href="/chat" role="menuitem">Chat</a></li>- <li class="nav-item" role="none"><a href="/tutorials" role="menuitem">Tutorials</a></li>- <li class="nav-item" id="home-nav-my-agents-li" role="none" hidden>- <a href="/my-agents" id="home-nav-my-agents" role="menuitem">My Agents</a>- </li>- <li class="nav-item" id="home-nav-user-li" role="none" hidden>- <a href="/dashboard" id="home-nav-user" class="nav-user" role="menuitem"></a>- </li>- <li class="nav-item" role="none">- <a href="/login" class="nav-cta" id="home-nav-cta" role="menuitem">Get started</a>- </li>- </ul>- </nav>+ <div id="nav-container"></div></header>+ <script src="/nav.js"></script><main id="rep-content"><div class="rep-page-wrap">@@ -688,54 +639,6 @@</div></footer>- <script>- // Auth-aware nav CTA- (function () {- try {- const raw = localStorage.getItem('3dagent:auth-hint');- if (!raw) return;- const { authed, name } = JSON.parse(raw);- if (!authed) return;- const cta = document.getElementById('home-nav-cta');- if (cta) { cta.textContent = 'Dashboard'; cta.href = '/dashboard'; }- const myAgentsLi = document.getElementById('home-nav-my-agents-li');- if (myAgentsLi) myAgentsLi.hidden = false;- const userLi = document.getElementById('home-nav-user-li');- const userEl = document.getElementById('home-nav-user');- if (userEl && userLi && name) { userEl.textContent = name; userLi.hidden = false; }- } catch (_) {}- })();-- // Dropdown nav- (function () {- const triggers = document.querySelectorAll('.home-nav .nav-trigger');- if (!triggers.length) return;- function closeAll(except) {- triggers.forEach((t) => { if (t !== except) t.setAttribute('aria-expanded', 'false'); });- }- triggers.forEach((trigger) => {- trigger.addEventListener('click', (e) => {- e.stopPropagation();- const open = trigger.getAttribute('aria-expanded') === 'true';- closeAll(open ? null : trigger);- trigger.setAttribute('aria-expanded', open ? 'false' : 'true');- if (!open) { const first = trigger.nextElementSibling?.querySelector('a'); first?.focus(); }- });- const menu = trigger.nextElementSibling;- if (!menu) return;- menu.addEventListener('keydown', (e) => {- const items = Array.from(menu.querySelectorAll('a'));- const idx = items.indexOf(document.activeElement);- if (e.key === 'ArrowDown') { e.preventDefault(); items[(idx + 1) % items.length]?.focus(); }- else if (e.key === 'ArrowUp') { e.preventDefault(); items[(idx - 1 + items.length) % items.length]?.focus(); }- else if (e.key === 'Escape') { trigger.setAttribute('aria-expanded', 'false'); trigger.focus(); }- });- });- document.addEventListener('click', (e) => { if (!e.target.closest('.home-nav')) closeAll(null); });- document.addEventListener('keydown', (e) => { if (e.key === 'Escape') closeAll(null); });- })();- </script>-<script type="importmap">{"imports": {diff --git a/scripts/apply-paid-assets-migration.mjs b/scripts/apply-paid-assets-migration.mjsnew file mode 100644index 000000000..591463ec6--- /dev/null+++ b/scripts/apply-paid-assets-migration.mjs@@ -0,0 +1,54 @@+#!/usr/bin/env node+// Apply the paid_assets migration against $DATABASE_URL.+// Usage: DATABASE_URL=... node scripts/apply-paid-assets-migration.mjs+//+// Idempotent — the migration uses IF NOT EXISTS on every CREATE.++import { readFileSync } from 'node:fs';+import { readFile } from 'node:fs/promises';+import { fileURLToPath } from 'node:url';+import path from 'node:path';+import { neon } from '@neondatabase/serverless';++const HERE = path.dirname(fileURLToPath(import.meta.url));+const REPO_ROOT = path.resolve(HERE, '..');++for (const envFile of ['.env.local', '.env']) {+ try {+ const raw = readFileSync(path.resolve(REPO_ROOT, envFile), 'utf8');+ for (const line of raw.split('\n')) {+ const m = line.match(/^([A-Z_][A-Z0-9_]*)=(.*)$/);+ if (!m || process.env[m[1]]) continue;+ let val = m[2].trim();+ if ((val.startsWith('"') && val.endsWith('"')) || (val.startsWith("'") && val.endsWith("'"))) {+ val = val.slice(1, -1);+ }+ process.env[m[1]] = val;+ }+ break;+ } catch {+ /* file not present */+ }+}++const url = process.env.DATABASE_URL;+if (!url) {+ console.error('DATABASE_URL not set');+ process.exit(1);+}+const sql = neon(url);+const text = await readFile(+ new URL('../api/_lib/migrations/2026-05-21-paid-assets.sql', import.meta.url),+ 'utf8',+);++const statements = text+ .split(/;\s*$/m)+ .map((s) => s.trim())+ .filter((s) => s && !/^--/.test(s));++for (const s of statements) {+ await sql.query(s);+ console.log('OK:', s.slice(0, 80).replace(/\s+/g, ' '));+}+console.log('paid_assets table ready');diff --git a/scripts/apply-siwx-migration.mjs b/scripts/apply-siwx-migration.mjsnew file mode 100644index 000000000..cd7468383--- /dev/null+++ b/scripts/apply-siwx-migration.mjs@@ -0,0 +1,56 @@+#!/usr/bin/env node+// Apply the SIWX migration against $DATABASE_URL.+// Usage: DATABASE_URL=... node scripts/apply-siwx-migration.mjs+//+// Idempotent — re-runnable. The migration uses IF NOT EXISTS on every CREATE.++import { readFileSync } from 'node:fs';+import { readFile } from 'node:fs/promises';+import { fileURLToPath } from 'node:url';+import path from 'node:path';+import { neon } from '@neondatabase/serverless';++const HERE = path.dirname(fileURLToPath(import.meta.url));+const REPO_ROOT = path.resolve(HERE, '..');++for (const envFile of ['.env.local', '.env']) {+ try {+ const raw = readFileSync(path.resolve(REPO_ROOT, envFile), 'utf8');+ for (const line of raw.split('\n')) {+ const m = line.match(/^([A-Z_][A-Z0-9_]*)=(.*)$/);+ if (!m || process.env[m[1]]) continue;+ let val = m[2].trim();+ if ((val.startsWith('"') && val.endsWith('"')) || (val.startsWith("'") && val.endsWith("'"))) {+ val = val.slice(1, -1);+ }+ process.env[m[1]] = val;+ }+ break;+ } catch {+ /* file not present */+ }+}++const url = process.env.DATABASE_URL;+if (!url) {+ console.error('DATABASE_URL not set');+ process.exit(1);+}+const sql = neon(url);+const text = await readFile(+ new URL('../api/_lib/migrations/2026-05-21-siwx.sql', import.meta.url),+ 'utf8',+);++// Neon HTTP API runs one statement per call. Split on top-level semicolons —+// the SIWX migration uses no DO blocks / dollar-quoted strings.+const statements = text+ .split(/;\s*$/m)+ .map((s) => s.trim())+ .filter((s) => s && !/^--/.test(s));++for (const s of statements) {+ await sql.query(s);+ console.log('OK:', s.slice(0, 80).replace(/\s+/g, ' '));+}+console.log('siwx tables ready');diff --git a/src/club.js b/src/club.jsindex 77de84b0c..a80e81ea9 100644--- a/src/club.js+++ b/src/club.js@@ -833,6 +833,34 @@ async function tipDancer({ dancer, dance, button }) {}}+// ── Mobile bottom-sheet handle + leaderboard auto-collapse ───────────────+// The right panel becomes a bottom sheet on mobile. The drag handle at the+// top of the sheet toggles `.is-expanded` (CSS transform handles the+// slide). The leaderboard <details> is force-open on desktop and starts+// collapsed on mobile to keep the viewport canvas-first.+{+ const handle = document.getElementById('club-sheet-handle');+ const sheet = document.getElementById('club-right');+ if (handle && sheet) {+ handle.addEventListener('click', () => {+ const expanded = sheet.classList.toggle('is-expanded');+ handle.setAttribute('aria-expanded', expanded ? 'true' : 'false');+ });+ }++ const lbDetails = document.getElementById('club-lb-details');+ if (lbDetails && typeof window.matchMedia === 'function') {+ const mq = window.matchMedia('(max-width: 800px)');+ const apply = () => {+ if (mq.matches) lbDetails.removeAttribute('open');+ else lbDetails.setAttribute('open', '');+ };+ apply();+ if (typeof mq.addEventListener === 'function') mq.addEventListener('change', apply);+ else if (typeof mq.addListener === 'function') mq.addListener(apply);+ }+}+// ── Mute pill in top bar ─────────────────────────────────────────────────function bindMutePill() {const btn = document.getElementById('club-audio-toggle');@@ -1005,12 +1033,44 @@ window.addEventListener('keydown', (e) => {}});+// ── Frame-budget watchdog ────────────────────────────────────────────────+// Even with the boot-time profile, a phone can throttle mid-session (thermal,+// background sync, etc.). The watchdog drops us one tier on sustained slow+// frames and we never auto-upgrade. Downgrade re-applies cheap render-state+// flags (pixelRatio, shadowMap, antialias-already-baked); features built+// once (mirror ball, volumetric cones) stay as constructed — turning them+// off mid-flight would mean destroying GPU resources which itself spikes+// frame time. Halting their per-frame work is enough.+const watchdog = createFrameWatchdog({+ initialTier: activeProfile.tier,+ onDowngrade: (nextTier) => {+ const next = PROFILES[nextTier];+ if (!next) return;+ activeProfile = next;+ if (typeof window !== 'undefined') window.__clubProfile = next;+ renderer.setPixelRatio(next.pixelRatio);+ renderer.shadowMap.enabled = next.shadows;+ for (const station of stations) {+ if (station.spot) station.spot.castShadow = next.shadows;+ }+ // Trim disco lights to the new cap so we render fewer point lights.+ while (disco.children.length > next.discoLights) {+ const dropped = disco.children[disco.children.length - 1];+ disco.remove(dropped);+ }+ console.info('[club] downgrading profile to', nextTier);+ },+});+// ── Render loop ──────────────────────────────────────────────────────────const clock = new Clock();+let rafId = null;function animate() {const dt = Math.min(clock.getDelta(), 0.066);const t = clock.getElapsedTime();+ watchdog.tick(dt);+for (const station of stations) station.tick(dt);// Disco light slow swirl.@@ -1020,7 +1080,7 @@ function animate() {clubCam.tick(dt);renderer.render(scene, camera);- requestAnimationFrame(animate);+ rafId = requestAnimationFrame(animate);}renderPoles();@@ -1123,9 +1183,20 @@ function stopLeaderboardPolling() {document.addEventListener('visibilitychange', () => {if (document.hidden) {stopLeaderboardPolling();+ // Stop the rAF loop entirely on hidden tabs — on mobile, leaving it+ // running heats the phone and drains battery for a tab the user+ // isn't even looking at.+ if (rafId != null) {+ cancelAnimationFrame(rafId);+ rafId = null;+ }} else {fetchLeaderboard();startLeaderboardPolling();+ // Discard the gap delta so the watchdog doesn't see one huge frame+ // (which would immediately count as "slow") on resume.+ clock.getDelta();+ if (rafId == null) animate();}});diff --git a/tests/club-perf.test.js b/tests/club-perf.test.jsnew file mode 100644index 000000000..d4dce11e5--- /dev/null+++ b/tests/club-perf.test.js@@ -0,0 +1,235 @@+// Tests for the /club performance profile detector + frame watchdog.+//+// detectProfile() reads `navigator` capability signals; we pass a stubbed+// env so it's testable in Node (vitest runs under `environment: 'node'`).+// The watchdog is pure math — feed it dt frames and assert it downgrades+// after sustained slow frames and never auto-upgrades.++import { describe, it, expect, vi } from 'vitest';+import {+ detectProfile,+ PROFILES,+ nextLowerTier,+ createFrameWatchdog,+} from '../src/club-perf.js';++function envFor({ ua = 'Mozilla/5.0', mem, cores, coarse = false } = {}) {+ return {+ navigator: {+ userAgent: ua,+ deviceMemory: mem,+ hardwareConcurrency: cores,+ },+ window: {+ matchMedia: (q) => ({ matches: q.includes('coarse') ? !!coarse : false }),+ },+ };+}++describe('detectProfile', () => {+ it('returns high for a beefy desktop', () => {+ expect(+ detectProfile(envFor({+ ua: 'Mozilla/5.0 (Macintosh; Intel Mac OS X)',+ mem: 16,+ cores: 12,+ })),+ ).toBe('high');+ });++ it('returns low for a memory-starved Android', () => {+ expect(+ detectProfile(envFor({+ ua: 'Mozilla/5.0 (Linux; Android 11) Mobile',+ mem: 2,+ cores: 8,+ })),+ ).toBe('low');+ });++ it('returns low for a low-core mobile', () => {+ expect(+ detectProfile(envFor({+ ua: 'Mozilla/5.0 (Linux; Android 10) Mobile',+ mem: 6,+ cores: 2,+ })),+ ).toBe('low');+ });++ it('returns medium for an iPhone (mem/cores undefined, coarse pointer)', () => {+ // Safari hides deviceMemory + hardwareConcurrency; the iPhone falls+ // through to the coarse-pointer branch → medium.+ expect(+ detectProfile(envFor({+ ua: 'Mozilla/5.0 (iPhone; CPU iPhone OS 17_0 like Mac OS X) Mobile',+ mem: undefined,+ cores: undefined,+ coarse: true,+ })),+ ).toBe('medium');+ });++ it('returns medium for a desktop with coarse pointer (touch laptop)', () => {+ expect(+ detectProfile(envFor({+ ua: 'Mozilla/5.0 (Windows NT 10.0)',+ mem: 8,+ cores: 8,+ coarse: true,+ })),+ ).toBe('high');+ // ^ A touch-Windows laptop with 8GB + 8 cores is "high" because the+ // UA isn't mobile. The coarse-pointer rule only kicks in for+ // non-desktop + non-low-spec.+ });++ it('returns medium when capability signals are missing entirely', () => {+ expect(detectProfile({ navigator: {}, window: { matchMedia: () => ({ matches: false }) } })).toBe('high');+ // Missing signals default to "plenty" (8) — without UA mobile match+ // we treat it as a desktop and pick high. Mobile UA with no signal+ // also defaults to plenty → falls through to medium.+ expect(+ detectProfile(envFor({+ ua: 'Mozilla/5.0 (Linux; Android 10) Mobile',+ mem: undefined,+ cores: undefined,+ coarse: false,+ })),+ ).toBe('medium');+ });+});++describe('PROFILES', () => {+ it('PROFILES.low disables bloom, shadows, cube cam, mirror ball, cones', () => {+ const low = PROFILES.low;+ expect(low.bloom).toBe(false);+ expect(low.shadows).toBe(false);+ expect(low.cubeCam).toBe(false);+ expect(low.mirrorBall).toBe(false);+ expect(low.volumetricCones).toBe(false);+ expect(low.chromaticAberration).toBe(false);+ expect(low.shadowMapSize).toBe(0);+ });++ it('PROFILES.high enables all feature flags', () => {+ const high = PROFILES.high;+ expect(high.bloom).toBe(true);+ expect(high.shadows).toBe(true);+ expect(high.cubeCam).toBe(true);+ expect(high.mirrorBall).toBe(true);+ expect(high.volumetricCones).toBe(true);+ expect(high.chromaticAberration).toBe(true);+ });++ it('PROFILES.medium keeps mirror ball + bloom but drops cube cam', () => {+ const med = PROFILES.medium;+ expect(med.bloom).toBe(true);+ expect(med.mirrorBall).toBe(true);+ expect(med.cubeCam).toBe(false);+ expect(med.chromaticAberration).toBe(false);+ });++ it('crowd instance counts step down monotonically across tiers', () => {+ expect(PROFILES.high.crowdInstances).toBeGreaterThan(PROFILES.medium.crowdInstances);+ expect(PROFILES.medium.crowdInstances).toBeGreaterThan(PROFILES.low.crowdInstances);+ });++ it('every tier tags itself with `tier`', () => {+ expect(PROFILES.high.tier).toBe('high');+ expect(PROFILES.medium.tier).toBe('medium');+ expect(PROFILES.low.tier).toBe('low');+ });+});++describe('nextLowerTier', () => {+ it('walks high → medium → low and floors at low', () => {+ expect(nextLowerTier('high')).toBe('medium');+ expect(nextLowerTier('medium')).toBe('low');+ expect(nextLowerTier('low')).toBe('low');+ });++ it('returns low for unknown input (safe fallback)', () => {+ expect(nextLowerTier('ultra')).toBe('low');+ });+});++describe('createFrameWatchdog', () => {+ it('downgrades after sustained slow frames', () => {+ const onDowngrade = vi.fn();+ const wd = createFrameWatchdog({+ initialTier: 'high',+ holdSec: 2.0,+ emaAlpha: 1.0, // make EMA == latest dt for deterministic test+ onDowngrade,+ });+ // Pump 3 seconds of slow frames (33 fps == 30ms per frame, but our+ // slow threshold is 1/28s ≈ 35.7ms). Feed 40ms frames.+ const slowDt = 0.040;+ const frameCount = Math.ceil(3.0 / slowDt);+ for (let i = 0; i < frameCount; i++) wd.tick(slowDt);+ expect(onDowngrade).toHaveBeenCalledTimes(1);+ expect(onDowngrade).toHaveBeenCalledWith('medium');+ expect(wd.tier).toBe('medium');+ });++ it('does not downgrade if slow frames are not sustained', () => {+ const onDowngrade = vi.fn();+ const wd = createFrameWatchdog({+ initialTier: 'high',+ holdSec: 2.0,+ emaAlpha: 1.0,+ onDowngrade,+ });+ // One blip of slow frames (~1s) then back to normal.+ for (let i = 0; i < 25; i++) wd.tick(0.040); // ~1s slow+ for (let i = 0; i < 120; i++) wd.tick(1 / 60); // 2s normal+ expect(onDowngrade).not.toHaveBeenCalled();+ expect(wd.tier).toBe('high');+ });++ it('never upgrades on its own', () => {+ const calls = [];+ const wd = createFrameWatchdog({+ initialTier: 'medium',+ holdSec: 2.0,+ emaAlpha: 1.0,+ onDowngrade: (t) => calls.push(t),+ });+ // Run 5 seconds of fast 60fps frames — should remain medium.+ for (let i = 0; i < 300; i++) wd.tick(1 / 60);+ expect(calls).toEqual([]);+ expect(wd.tier).toBe('medium');+ });++ it('floors at low after two downgrades', () => {+ const calls = [];+ const wd = createFrameWatchdog({+ initialTier: 'high',+ holdSec: 1.0,+ emaAlpha: 1.0,+ onDowngrade: (t) => calls.push(t),+ });+ // Slow frames for ~5 seconds — long enough to walk high→medium→low+ // and then sit at low (no further calls).+ for (let i = 0; i < 200; i++) wd.tick(0.080);+ expect(calls[0]).toBe('medium');+ expect(calls[1]).toBe('low');+ expect(wd.tier).toBe('low');+ // No further downgrade calls past low.+ const before = calls.length;+ for (let i = 0; i < 200; i++) wd.tick(0.080);+ expect(calls.length).toBe(before);+ });++ it('ignores non-finite dt values without throwing', () => {+ const wd = createFrameWatchdog({+ initialTier: 'high',+ onDowngrade: () => {},+ });+ expect(() => wd.tick(NaN)).not.toThrow();+ expect(() => wd.tick(-1)).not.toThrow();+ expect(() => wd.tick(0)).not.toThrow();+ expect(wd.tier).toBe('high');+ });+});diff --git a/vercel.json b/vercel.jsonindex bb1ea05b7..b50e4d8bd 100644--- a/vercel.json+++ b/vercel.json@@ -1704,6 +1704,10 @@{"path": "/api/cron/club-payouts","schedule": "2-59/5 * * * *"+ },+ {+ "path": "/api/cron/siwx-gc",+ "schedule": "23 * * * *"}]}