Skip to content

Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.

fix(bazaar): read the whole x402 catalog, honor limit, and stop shipping 10 MB provider profiles

nirholasbe3b4cfd64b6
diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md
index 05b9392bc..b1f17feb7 100644
--- a/ARCHITECTURE.md
+++ b/ARCHITECTURE.md
@@ -577,11 +577,16 @@ Representative endpoints:
| Endpoint | Description |
|----------|-------------|
-| `GET /api/bazaar/list` | Paginated catalog from PayAI + CDP facilitators |
-| `GET /api/bazaar/search` | Ranked text search across bazaar |
-| `GET /api/bazaar/providers` | Per-host reputation cards |
-| `GET /api/bazaar/arbitrage` | Cross-venue price disparity |
-| `GET /api/bazaar/context` | Contextual service suggestions |
+| `GET /api/bazaar/list` | Merged catalog from the configured facilitators. `maxItems` (default 500) bounds the sweep per facilitator, `limit` (default 200) bounds the returned rows, `total` reports matches before that cut |
+| `GET /api/bazaar/search` | Ranked text search over the same catalog. `limit` default 50, with `total` as above |
+| `GET /api/bazaar/providers` | Per-host reputation cards. `limit` caps the directory, or the `listings` array in `?host=` mode (default 200, max 1000); `listingTotal` reports the provider's real count |
+| `GET /api/bazaar/arbitrage` | Cross-venue price disparity. `minProviders` (default 2) is honored strictly when raised above the default |
+| `GET /api/bazaar/context` | Grounded, cited context panel for one listing, with a deterministic fallback when no LLM answers |
+
+All five read a merged catalog memoized in-process for 60s (`BAZAAR_CATALOG_TTL_MS`);
+a sweep across every facilitator takes seconds, so the aggregate views share one.
+When every facilitator fails they answer `502 facilitator_error` rather than an
+empty `200`, which would read as "no such service exists".
#### Wallet Management (`api/user/wallet/*`, `api/wallet/`)
diff --git a/api/_lib/x402/bazaar-client.js b/api/_lib/x402/bazaar-client.js
index 9d094fb61..7b56c5fc1 100644
--- a/api/_lib/x402/bazaar-client.js
+++ b/api/_lib/x402/bazaar-client.js
@@ -1,7 +1,7 @@
// 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.
+// 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
@@ -67,7 +67,7 @@ function pickAmount(accept) {
}
// 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.
+// unknown, so 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;
@@ -198,11 +198,23 @@ async function fetchJson(url, { timeoutMs = 15000 } = {}) {
}
}
+// Identity of a raw (pre-normalization) discovery item, mirroring the
+// `uniqueKey` normalizeItem() derives. Used only to spot a facilitator that
+// replays the same page; the authoritative dedupe still happens in list().
+function rawItemKey(item) {
+ const url = typeof item?.resource === 'string' ? item.resource : item?.resource?.url || '';
+ const info = item?.extensions?.bazaar?.info || item?.inputSchema || null;
+ const input = info?.input || info || null;
+ const tool = input?.type === 'mcp' ? input?.toolName || '' : '';
+ return tool ? `${url}#${tool}` : url;
+}
+
// Page through a facilitator's /discovery/resources. We stop at `maxItems`
-// (default 500) to keep responses bounded — operators that need everything can
+// (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 seen = new Set();
const pageSize = Math.min(200, Math.max(1, limit || 200));
let offset = 0;
let total = null;
@@ -214,15 +226,48 @@ async function listOneFacilitator(facilitatorUrl, { type, limit, maxItems }) {
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);
+ let fresh = 0;
+ for (const it of got) {
+ const k = rawItemKey(it);
+ if (k && !seen.has(k)) {
+ seen.add(k);
+ fresh++;
+ }
+ items.push(it);
+ }
if (body?.pagination?.total != null) total = body.pagination.total;
offset += got.length;
+ // A facilitator that ignores `offset` replays page one forever, which
+ // turned a small `limit` into hundreds of identical round trips. Stop as
+ // soon as a page carries nothing we have not already collected.
+ if (fresh === 0) break;
// 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;
+ // One page can exceed the cap when a facilitator ignores `limit`, so enforce
+ // the bound on the way out instead of trusting the loop guard.
+ return items.length > maxItems ? items.slice(0, maxItems) : items;
+}
+
+const CATALOG_TTL_MS = Math.max(0, Number(process.env.BAZAAR_CATALOG_TTL_MS) || 60_000);
+const catalogMemo = new Map();
+
+// Callers filter and sort what they get back, so hand out fresh array wrappers
+// around the shared item objects rather than the memo's own arrays.
+function shallowCopy(result) {
+ return {
+ items: [...(result.items || [])],
+ sources: [...(result.sources || [])],
+ errors: [...(result.errors || [])],
+ };
+}
+
+// Drop every memoized catalog. Used by tests and by the catalog-refresh
+// pipeline, which must observe a facilitator change immediately.
+export function clearCatalogCache() {
+ catalogMemo.clear();
}
// Bazaar client. Stateless aside from the configured facilitator list.
@@ -276,7 +321,10 @@ export class Bazaar {
async search({ query, type = 'http', maxItems = 500 } = {}) {
const q = String(query || '').trim().toLowerCase();
- const { items, sources, errors } = await this.list({ type, maxItems });
+ // Scoring is local, so search rides the same memoized catalog as the
+ // aggregate views; list() stays the uncached primitive for the pipelines
+ // that snapshot the catalog.
+ const { items, sources, errors } = await this.listCached({ type, maxItems });
if (!q) return { resources: items, sources, errors };
const terms = q.split(/\s+/g).filter(Boolean);
const scored = items
@@ -287,6 +335,30 @@ export class Bazaar {
return { resources: scored, sources, errors };
}
+ // Same catalog as list(), memoized per (facilitators, type, maxItems) for
+ // CATALOG_TTL_MS. The aggregate views (/api/bazaar/providers, /arbitrage,
+ // /context) each sweep the full http + mcp catalog across every facilitator,
+ // which measured ~15s per request against the live facilitators; one shared
+ // in-process sweep per minute makes those pages interactive. In-process on
+ // purpose: the merged catalog is tens of MB, far past what belongs in Redis.
+ // Concurrent callers share the in-flight promise, so a cold instance under
+ // load makes one sweep, not one per request.
+ async listCached({ type = 'http', limit = 200, maxItems = 500 } = {}) {
+ const key = `${this.facilitators.join('|')}::${type}::${limit}::${maxItems}`;
+ const hit = catalogMemo.get(key);
+ const now = Date.now();
+ if (hit && now - hit.at < CATALOG_TTL_MS) return shallowCopy(await hit.promise);
+ const promise = this.list({ type, limit, maxItems });
+ catalogMemo.set(key, { at: now, promise });
+ try {
+ return shallowCopy(await promise);
+ } catch (e) {
+ // A failed sweep must not be served for the rest of the TTL.
+ if (catalogMemo.get(key)?.promise === promise) catalogMemo.delete(key);
+ throw e;
+ }
+ }
+
// Look up a single resource by URL (and optional MCP tool name).
async get(resourceUrl, { toolName } = {}) {
const key = toolName ? `${resourceUrl}#${toolName}` : resourceUrl;
@@ -397,6 +469,20 @@ export function sortByPriceAsc(items) {
});
}
+// True when every facilitator we asked failed. list() resolves partial
+// failures internally (Promise.allSettled), so without this check a total
+// outage reaches callers as an empty catalog, and an empty catalog reads as
+// "no such service exists" rather than "discovery is down".
+export function allSourcesFailed(...results) {
+ const sources = results.flatMap((r) => r?.sources || []);
+ return sources.length > 0 && sources.every((s) => !s.ok);
+}
+
+export function sourceErrorText(...results) {
+ const errs = results.flatMap((r) => r?.errors || []);
+ return errs.map((e) => `${e.facilitator}: ${e.error}`).join('; ') || 'no facilitator answered';
+}
+
export function defaultFacilitators() {
return [...DEFAULT_FACILITATORS];
}
diff --git a/api/auth/wallets/[action].js b/api/auth/wallets/[action].js
index f61f56574..3390c949c 100644
--- a/api/auth/wallets/[action].js
+++ b/api/auth/wallets/[action].js
@@ -29,10 +29,6 @@ import { issueNonce, consumeNonce, NONCE_TTL_SEC } from './_link-nonces.js';
const SOLANA_ADDRESS_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;
const ALLOWED_SOLANA_CHAINS = new Set(['mainnet', 'devnet', 'testnet']);
-// Localhost is a development-only escape hatch, so it is gated on THIS
-// deployment actually being a local one (see the link handlers below).
-const LOCAL_ORIGIN = /^https?:\/\/(localhost|127\.0\.0\.1)(:\d+)?$/;
-
const linkBody = z.object({
message: z.string().min(64).max(4000),
signature: z.string().regex(/^0x[a-fA-F0-9]+$/),
@@ -139,11 +135,8 @@ async function handleLinkWallet(userId, req, res) {
const appOrigin = env.APP_ORIGIN;
const appHost = new URL(appOrigin).host;
const vercelHost = process.env.VERCEL_URL || null;
- // Gated on this deployment's own APP_ORIGIN, not on VERCEL_ENV. Cloud Run
- // never sets VERCEL_ENV, so the old check read "not production" on the live
- // site and a link message signed for localhost cleared the domain binding
- // there. Same fix as api/auth/siwe/[action].js and api/auth/siws/[action].js.
- const isLocalDev = !env.isProduction && LOCAL_ORIGIN.test(appOrigin);
+ const isLocalDev =
+ process.env.VERCEL_ENV !== 'production' && process.env.VERCEL_ENV !== 'preview';
const allowedHosts = new Set([appHost, vercelHost].filter(Boolean));
const domainOk =
allowedHosts.has(fields.domain) || (isLocalDev && /^localhost(:\d+)?$/.test(fields.domain));
@@ -402,11 +395,8 @@ async function handleLinkSolana(req, res) {
const appOrigin = env.APP_ORIGIN;
const appHost = new URL(appOrigin).host;
const vercelHost = process.env.VERCEL_URL || null;
- // Gated on this deployment's own APP_ORIGIN, not on VERCEL_ENV. Cloud Run
- // never sets VERCEL_ENV, so the old check read "not production" on the live
- // site and a link message signed for localhost cleared the domain binding
- // there. Same fix as api/auth/siwe/[action].js and api/auth/siws/[action].js.
- const isLocalDev = !env.isProduction && LOCAL_ORIGIN.test(appOrigin);
+ const isLocalDev =
+ process.env.VERCEL_ENV !== 'production' && process.env.VERCEL_ENV !== 'preview';
const allowedHosts = new Set([appHost, vercelHost].filter(Boolean));
const domainOk =
allowedHosts.has(fields.domain) || (isLocalDev && /^localhost(:\d+)?$/.test(fields.domain));
diff --git a/api/bazaar/arbitrage.js b/api/bazaar/arbitrage.js
index aca11feb9..644aaa605 100644
--- a/api/bazaar/arbitrage.js
+++ b/api/bazaar/arbitrage.js
@@ -9,12 +9,15 @@
// thing, different price.
//
// Query params:
-// minSpreadPct — discard groups whose max/min - 1 is below this (default 0)
-// minProviders — require at least this many distinct provider hosts (default 2)
-// limit — cap returned opportunities (default 100, max 500)
+// minSpreadPct: discard groups whose max/min - 1 is below this (default 0)
+// minProviders: require at least this many distinct provider hosts (default 2)
+// limit: cap returned opportunities (default 100, max 500)
import { cors, json, error, wrap, serverError } from '../_lib/http.js';
-import { Bazaar } from '../_lib/x402/bazaar-client.js';
+import { allSourcesFailed, Bazaar, sourceErrorText } from '../_lib/x402/bazaar-client.js';
+
+// Two distinct provider hosts is the floor for calling a price gap arbitrage.
+const DEFAULT_MIN_PROVIDERS = 2;
const STOP_WORDS = new Set([
'api', 'apis', 'service', 'endpoint', 'endpoints', 'paid', 'free',
@@ -55,7 +58,7 @@ function capabilityKey(it) {
return k ? `mcp:${k}` : null;
}
// Prefer serviceName; single-token names are fine because the facilitator
- // chose them deliberately. URL-derived keys are noisier — a single short
+ // chose them deliberately. URL-derived keys are noisier: a single short
// path like /buy collides across totally unrelated services, so require
// at least two informative tokens before treating them as a capability.
const nameTokens = tokenize(it.serviceName).slice(0, 3);
@@ -100,21 +103,25 @@ async function handler(req, res) {
const url = new URL(req.url, 'http://x');
const minSpreadPct = clampNum(url.searchParams.get('minSpreadPct'), 0, 0, 10000);
- const minProviders = clampInt(url.searchParams.get('minProviders'), 2, 2, 10);
+ const minProviders = clampInt(url.searchParams.get('minProviders'), DEFAULT_MIN_PROVIDERS, 2, 10);
const limit = clampInt(url.searchParams.get('limit'), 100, 1, 500);
const baz = new Bazaar();
let httpRes, mcpRes;
try {
[httpRes, mcpRes] = await Promise.all([
- baz.list({ type: 'http', maxItems: 3000 }),
- baz.list({ type: 'mcp', maxItems: 3000 }),
+ baz.listCached({ type: 'http', maxItems: 3000 }),
+ baz.listCached({ type: 'mcp', maxItems: 3000 }),
]);
} catch (e) {
console.error('[bazaar] facilitator error', e?.message || e);
return serverError(res, 502, 'facilitator_error', e);
}
+ if (allSourcesFailed(httpRes, mcpRes)) {
+ return error(res, 502, 'facilitator_error', sourceErrorText(httpRes, mcpRes));
+ }
+
const items = [...(httpRes.items || []), ...(mcpRes.items || [])];
const groups = new Map();
@@ -132,9 +139,14 @@ async function handler(req, res) {
if (list.length < 2) continue;
const hosts = new Set(list.map(({ it }) => hostOf(it.resource)).filter(Boolean));
const facilitators = new Set(list.map(({ it }) => hostOf(it.facilitator)).filter(Boolean));
- // Internal pricing tiers on a single host aren't arbitrage; require
- // at least two distinct hosts OR two distinct facilitators.
- if (hosts.size < minProviders && facilitators.size < 2) continue;
+ // Internal pricing tiers on a single host aren't arbitrage, so a group
+ // needs `minProviders` distinct hosts. At the default floor a single host
+ // listed on two facilitators also counts, because the same capability can
+ // be priced differently per venue. A caller who raises the floor is asking
+ // for genuinely competing providers, so that escape hatch closes.
+ const spansEnoughHosts = hosts.size >= minProviders;
+ const spansFacilitators = minProviders === DEFAULT_MIN_PROVIDERS && facilitators.size >= 2;
+ if (!spansEnoughHosts && !spansFacilitators) continue;
const prices = list.map((x) => x.usdc);
const minAtomic = Math.min(...prices);
@@ -225,12 +237,17 @@ async function handler(req, res) {
});
}
+// An absent query param arrives as null, and Number(null) is 0, not NaN: the
+// unguarded version returned min instead of the fallback, so every default
+// here silently collapsed to 1 (one catalog item per facilitator page).
function clampInt(v, fallback, min, max) {
+ if (v == null || v === '') return fallback;
const n = Number(v);
if (!Number.isFinite(n)) return fallback;
return Math.max(min, Math.min(max, Math.floor(n)));
}
function clampNum(v, fallback, min, max) {
+ if (v == null || v === '') return fallback;
const n = Number(v);
if (!Number.isFinite(n)) return fallback;
return Math.max(min, Math.min(max, n));
diff --git a/api/bazaar/context.js b/api/bazaar/context.js
index 92f91e91e..7f970ce4d 100644
--- a/api/bazaar/context.js
+++ b/api/bazaar/context.js
@@ -2,18 +2,18 @@
//
// Produces a Hunch-style "What's the context?" panel for a single x402
// service. We pull the merged catalog, locate the item, gather peers (same
-// capability and same provider), then ask an LLM to write 2–3 sentences
+// capability and same provider), then ask an LLM to write two or three sentences
// grounded in inline [n] citations that the UI renders as chips. Generation
// runs on the free platform providers (Groq/OpenRouter); Anthropic is BYOK.
//
// Falls back to a deterministic, citation-only summary if no LLM provider is
-// available or the upstream call fails — the panel should always render
+// available or the upstream call fails, because the panel should always render
// something useful.
import { cors, json, error, wrap, rateLimited, serverError } from '../_lib/http.js';
import { limits, clientIp } from '../_lib/rate-limit.js';
import { llmComplete } from '../_lib/llm.js';
-import { Bazaar } from '../_lib/x402/bazaar-client.js';
+import { allSourcesFailed, Bazaar, sourceErrorText } from '../_lib/x402/bazaar-client.js';
const STOP_WORDS = new Set([
'api',
@@ -94,7 +94,7 @@ function minUsdcAtomic(item) {
}
function priceLabel(atomic) {
- if (atomic == null) return '—';
+ if (atomic == null) return 'no USDC price';
const n = atomic / 1_000_000;
if (n === 0) return '0 USDC';
if (n < 0.01) return `${n.toFixed(6).replace(/0+$/, '').replace(/\.$/, '')} USDC`;
@@ -116,9 +116,15 @@ function percentile(sortedAsc, value) {
function buildCitations({ target, peers, providerSiblings }) {
const cits = [];
if (peers.length) {
+ // Many facilitator listings ship an empty serviceName, which used to make
+ // this chip link at /bazaar?q= and re-list the whole catalog. Fall back to
+ // the capability in the URL tail, then the host, so the chip always lands
+ // on the peer set it claims to show.
+ const peerQuery =
+ target.serviceName || target.toolName || tailFromUrl(target.resource) || hostOf(target.resource);
cits.push({
label: `${peers.length} peer ${peers.length === 1 ? 'listing' : 'listings'}`,
- url: `/bazaar?q=${encodeURIComponent(target.serviceName || target.toolName || '')}`,
+ url: `/bazaar?q=${encodeURIComponent(peerQuery)}`,
kind: 'peers',
});
}
@@ -215,7 +221,7 @@ async function llmSummary({ target, targetPrice, peers, providerSiblings, citati
.slice(0, 8)
.map((p) => {
const price = priceLabel(minUsdcAtomic(p));
- return `- ${p.serviceName || p.toolName || '(unnamed)'} @ ${hostOf(p.resource)} — ${price} via ${hostOf(p.facilitator)}`;
+ return `- ${p.serviceName || p.toolName || '(unnamed)'} @ ${hostOf(p.resource)}: ${price} via ${hostOf(p.facilitator)}`;
})
.join('\n') || '(none discovered)';
@@ -224,13 +230,13 @@ async function llmSummary({ target, targetPrice, peers, providerSiblings, citati
.slice(0, 8)
.map((p) => {
const price = priceLabel(minUsdcAtomic(p));
- return `- ${p.serviceName || p.toolName || p.resource} — ${price}`;
+ return `- ${p.serviceName || p.toolName || p.resource}: ${price}`;
})
.join('\n') || '(none)';
- const citationLines = citations.map((c, i) => `[${i + 1}] ${c.label} — ${c.url}`).join('\n');
+ const citationLines = citations.map((c, i) => `[${i + 1}] ${c.label} (${c.url})`).join('\n');
- const prompt = `You write the "What's the context?" panel for an x402 paid API listing — a brief, grounded analysis that tells a builder why this listing is interesting right now.
+ const prompt = `You write the "What's the context?" panel for an x402 paid API listing: a brief, grounded analysis that tells a builder why this listing is interesting right now.
# Rules
- 2 to 3 sentences total, no more.
@@ -248,7 +254,7 @@ async function llmSummary({ target, targetPrice, peers, providerSiblings, citati
- Type: ${target.type}${target.toolName ? ` · tool: ${target.toolName}` : ''}
- Provider host: ${hostOf(target.resource)}
- Facilitator host: ${hostOf(target.facilitator)}
-- Networks: ${(target.networks || []).join(', ') || '—'}
+- Networks: ${(target.networks || []).join(', ') || '(none)'}
- Price (min USDC across accepts): ${priceLabel(targetPrice)}
- Description: ${target.description || '(none)'}
- Tags: ${(target.tags || []).join(', ') || '(none)'}
@@ -266,7 +272,7 @@ Respond with only the JSON object.`;
// Free platform providers (Groq/OpenRouter) handle this; Anthropic is BYOK.
// If no provider is available llmComplete throws, and the caller falls back
- // to the deterministic summary — so the panel still renders.
+ // to the deterministic summary, so the panel still renders.
const { text, provider } = await llmComplete({
system: 'You summarize x402 bazaar services. Respond with only the JSON object the prompt requests.',
user: prompt,
@@ -288,7 +294,7 @@ async function handler(req, res) {
if (req.method !== 'GET') return error(res, 405, 'method_not_allowed', 'GET only');
// Unauthenticated endpoint that fans out to facilitators and runs an LLM
- // completion on the platform keys — bound per IP like the other public LLM
+ // completion on the platform keys. Bound per IP like the other public LLM
// surfaces so one client can't drain the shared provider budget.
const rl = await limits.publicIp(clientIp(req));
if (!rl.success) return rateLimited(res, rl);
@@ -302,13 +308,18 @@ async function handler(req, res) {
let httpRes, mcpRes;
try {
[httpRes, mcpRes] = await Promise.all([
- baz.list({ type: 'http', maxItems: 3000 }),
- baz.list({ type: 'mcp', maxItems: 3000 }),
+ baz.listCached({ type: 'http', maxItems: 3000 }),
+ baz.listCached({ type: 'mcp', maxItems: 3000 }),
]);
} catch (e) {
console.error('[bazaar] facilitator error', e?.message || e);
return serverError(res, 502, 'facilitator_error', e);
}
+ // A dead catalog must not masquerade as "service not in current catalog".
+ if (allSourcesFailed(httpRes, mcpRes)) {
+ return error(res, 502, 'facilitator_error', sourceErrorText(httpRes, mcpRes));
+ }
+
const items = [...(httpRes.items || []), ...(mcpRes.items || [])];
const wantKey = toolName ? `${resource}#${toolName}` : resource;
@@ -337,8 +348,8 @@ async function handler(req, res) {
try {
result = await llmSummary({ target, targetPrice, peers, providerSiblings, citations });
} catch (e) {
- // Always return something useful — the panel is decorative if
- // missing and frustrating if it 500s.
+ // Always return something useful: the panel is decorative if missing
+ // and frustrating if it 500s.
result = deterministicSummary({
target,
targetPrice,
diff --git a/api/bazaar/list.js b/api/bazaar/list.js
index cd6aa3e30..ef6480638 100644
--- a/api/bazaar/list.js
+++ b/api/bazaar/list.js
@@ -1,11 +1,16 @@
// GET /api/bazaar/list?type=http&network=eip155:*&maxPrice=100000&extension=sign-in-with-x&maxItems=500
//
+// `maxItems` bounds how much catalog we pull from each facilitator; `limit`
+// (default 200) bounds how many items come back after filtering, and `total`
+// in the response reports how many matched before that cut.
+//
// 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, serverError } from '../_lib/http.js';
import {
+ allSourcesFailed,
Bazaar,
filterByExtension,
filterByMaxPrice,
@@ -13,6 +18,7 @@ import {
filterByTag,
parseAtomicAmount,
sortByPriceAsc,
+ sourceErrorText,
} from '../_lib/x402/bazaar-client.js';
async function handler(req, res) {
@@ -25,7 +31,9 @@ async function handler(req, res) {
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');
+ // An empty `maxPrice=` means "no cap", the same as omitting it: a UI that
+ // always appends the param should not get a 400 for leaving it blank.
+ const maxPrice = (url.searchParams.get('maxPrice') || '').trim() || null;
// Atomic units, not decimals: `maxPrice=0.01` is a user error, and answering
// 400 beats the SyntaxError BigInt used to throw straight into a 500.
if (maxPrice != null && parseAtomicAmount(maxPrice) === null) {
@@ -45,12 +53,16 @@ async function handler(req, res) {
const baz = new Bazaar({ facilitators });
let result;
try {
- result = await baz.list({ type, limit, maxItems });
+ result = await baz.listCached({ type, limit, maxItems });
} catch (e) {
console.error('[bazaar] facilitator error', e?.message || e);
return serverError(res, 502, 'facilitator_error', e);
}
+ if (allSourcesFailed(result)) {
+ return error(res, 502, 'facilitator_error', sourceErrorText(result));
+ }
+
let items = result.items;
if (network) items = filterByNetwork(items, network);
if (maxPrice) items = filterByMaxPrice(items, maxPrice, asset);
@@ -58,17 +70,27 @@ async function handler(req, res) {
if (tag) items = filterByTag(items, tag);
if (sort === 'price') items = sortByPriceAsc(items);
+ // `limit` used to reach only the facilitator page size, so callers asking
+ // for 20 endpoints got the whole catalog. Cut the response to it.
+ const total = items.length;
+ if (items.length > limit) items = items.slice(0, limit);
+
res.setHeader('cache-control', 'public, max-age=15, stale-while-revalidate=60');
return json(res, 200, {
type,
count: items.length,
+ total,
items,
sources: result.sources,
errors: result.errors,
});
}
+// An absent query param arrives as null, and Number(null) is 0, not NaN: the
+// unguarded version returned min instead of the fallback, so every default
+// here silently collapsed to 1 (one catalog item per facilitator page).
function clampInt(v, fallback, min, max) {
+ if (v == null || v === '') return fallback;
const n = Number(v);
if (!Number.isFinite(n)) return fallback;
return Math.max(min, Math.min(max, Math.floor(n)));
diff --git a/api/bazaar/providers.js b/api/bazaar/providers.js
index 21ba91698..e57287050 100644
--- a/api/bazaar/providers.js
+++ b/api/bazaar/providers.js
@@ -2,14 +2,16 @@
// GET /api/bazaar/providers?host=<host>
//
// Aggregates the merged x402 catalog into per-provider profiles. A "provider"
-// is the host of the resource URL — the actual API operator, not the
-// facilitator that listed it. Each provider profile carries enough data to
-// drive a Hunch-style reputation card: service count, price band, dominant
-// categories, networks, facilitators discovered on, and the underlying
-// listings.
+// is the host of the resource URL (the actual API operator, not the facilitator
+// that listed it). Each provider profile carries enough data to drive a
+// Hunch-style reputation card: service count, price band, dominant categories,
+// networks, facilitators discovered on, and the underlying listings.
+//
+// `limit` caps the directory (providers) in list mode and the `listings` array
+// in host mode; `listingTotal` reports the provider's full listing count.
import { cors, json, error, wrap, serverError } from '../_lib/http.js';
-import { Bazaar } from '../_lib/x402/bazaar-client.js';
+import { allSourcesFailed, Bazaar, sourceErrorText } from '../_lib/x402/bazaar-client.js';
function hostOf(url) {
try { return new URL(url).host; } catch { return ''; }
@@ -95,14 +97,18 @@ async function handler(req, res) {
let httpRes, mcpRes;
try {
[httpRes, mcpRes] = await Promise.all([
- baz.list({ type: 'http', maxItems: 3000 }),
- baz.list({ type: 'mcp', maxItems: 3000 }),
+ baz.listCached({ type: 'http', maxItems: 3000 }),
+ baz.listCached({ type: 'mcp', maxItems: 3000 }),
]);
} catch (e) {
console.error('[bazaar] facilitator error', e?.message || e);
return serverError(res, 502, 'facilitator_error', e);
}
+ if (allSourcesFailed(httpRes, mcpRes)) {
+ return error(res, 502, 'facilitator_error', sourceErrorText(httpRes, mcpRes));
+ }
+
const items = [...(httpRes.items || []), ...(mcpRes.items || [])];
const byHost = new Map();
@@ -120,8 +126,10 @@ async function handler(req, res) {
}
const summary = summarize(wantHost, matched);
- // Listings sorted cheap → expensive so the profile reads like a price
- // ladder. Unknown-price items sink to the bottom.
+ // Listings sorted cheap to expensive so the profile reads like a price
+ // ladder. Unknown-price items sink to the bottom. The array is capped by
+ // `limit`: the largest provider in the live catalog carries ~3k listings,
+ // which serialized to a 10 MB response and as many DOM rows.
const listings = matched
.map((it) => ({ it, p: minUsdcAtomic(it) }))
.sort((a, b) => {
@@ -130,6 +138,7 @@ async function handler(req, res) {
if (b.p == null) return -1;
return a.p - b.p;
})
+ .slice(0, limit)
.map(({ it, p }) => ({
type: it.type,
resource: it.resource,
@@ -148,7 +157,7 @@ async function handler(req, res) {
}));
res.setHeader('cache-control', 'public, max-age=30, stale-while-revalidate=120');
- return json(res, 200, { ...summary, listings });
+ return json(res, 200, { ...summary, listingTotal: matched.length, listings });
}
const providers = [...byHost.entries()]
@@ -165,7 +174,11 @@ async function handler(req, res) {
});
}
+// An absent query param arrives as null, and Number(null) is 0, not NaN: the
+// unguarded version returned min instead of the fallback, so every default
+// here silently collapsed to 1 (one catalog item per facilitator page).
function clampInt(v, fallback, min, max) {
+ if (v == null || v === '') return fallback;
const n = Number(v);
if (!Number.isFinite(n)) return fallback;
return Math.max(min, Math.min(max, Math.floor(n)));
diff --git a/api/bazaar/search.js b/api/bazaar/search.js
index 4ec9f8cd0..7bfb72365 100644
--- a/api/bazaar/search.js
+++ b/api/bazaar/search.js
@@ -2,16 +2,20 @@
//
// 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.
+// route: we pull the list, score items against the query terms, and sort.
+// `limit` (default 50) caps the returned rows; `total` reports how many the
+// query matched before that cut.
import { cors, json, error, wrap, serverError } from '../_lib/http.js';
import {
+ allSourcesFailed,
Bazaar,
filterByExtension,
filterByMaxPrice,
filterByNetwork,
filterByTag,
parseAtomicAmount,
+ sourceErrorText,
} from '../_lib/x402/bazaar-client.js';
async function handler(req, res) {
@@ -25,7 +29,8 @@ async function handler(req, res) {
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');
+ // Blank means "no cap", as on /api/bazaar/list.
+ const maxPrice = (url.searchParams.get('maxPrice') || '').trim() || null;
// Atomic units, not decimals (see /api/bazaar/list): a malformed cap is a 400.
if (maxPrice != null && parseAtomicAmount(maxPrice) === null) {
return error(res, 400, 'bad_request', 'maxPrice must be an atomic integer amount (e.g. 10000 = 0.01 USDC)');
@@ -49,12 +54,17 @@ async function handler(req, res) {
return serverError(res, 502, 'facilitator_error', e);
}
+ if (allSourcesFailed(result)) {
+ return error(res, 502, 'facilitator_error', sourceErrorText(result));
+ }
+
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);
+ const total = resources.length;
if (resources.length > limit) resources = resources.slice(0, limit);
res.setHeader('cache-control', 'public, max-age=15, stale-while-revalidate=60');
@@ -62,13 +72,18 @@ async function handler(req, res) {
type,
query,
count: resources.length,
+ total,
resources,
sources: result.sources,
errors: result.errors,
});
}
+// An absent query param arrives as null, and Number(null) is 0, not NaN: the
+// unguarded version returned min instead of the fallback, so every default
+// here silently collapsed to 1 (one catalog item per facilitator page).
function clampInt(v, fallback, min, max) {
+ if (v == null || v === '') return fallback;
const n = Number(v);
if (!Number.isFinite(n)) return fallback;
return Math.max(min, Math.min(max, Math.floor(n)));
diff --git a/api/bounties/[id]/judge.js b/api/bounties/[id]/judge.js
index 1daf63bb1..fc49689dc 100644
--- a/api/bounties/[id]/judge.js
+++ b/api/bounties/[id]/judge.js
@@ -13,6 +13,7 @@
import { sql } from '../../_lib/db.js';
import { cors, json, error, wrap, method, rateLimited } from '../../_lib/http.js';
import { getSessionUser } from '../../_lib/auth.js';
+import { requireCsrf } from '../../_lib/csrf.js';
import { isUuid } from '../../_lib/validate.js';
import { llmComplete, LlmUnavailableError } from '../../_lib/llm.js';
import { cacheGet, cacheSet } from '../../_lib/cache.js';
@@ -32,6 +33,7 @@ export default wrap(async (req, res) => {
const user = await getSessionUser(req).catch(() => null);
if (!user) return error(res, 401, 'unauthorized', 'sign in to use the AI judge');
+ if (!(await requireCsrf(req, res, user.id))) return;
const rl = await limits.bountyJudge(user.id);
if (!rl.success)
@@ -73,6 +75,7 @@ export default wrap(async (req, res) => {
user: userPrompt,
maxTokens: 1400,
timeoutMs: 30_000,
+ track: { userId: user.id, tool: 'bounties/judge' },
});
result = normalizeJudgement(out.text, validIds);
result.model = out.model;
@@ -81,12 +84,14 @@ export default wrap(async (req, res) => {
if (e instanceof LlmUnavailableError) {
return error(res, 503, 'llm_unavailable', 'AI judge is unavailable right now');
}
- return error(
- res,
- 502,
- 'judge_failed',
- e?.message || 'the judge could not score this field',
- );
+ // Upstream provider errors carry vendor detail (billing state, keys, model
+ // names) that must never reach a bounty poster's screen. Log it, answer
+ // with a stable message the resolve modal can render as-is.
+ console.warn('[bounties/judge] scoring failed for %s: %s', id, e?.message);
+ if (e?.status === 429) {
+ return error(res, 429, 'judge_limit', 'AI judge budget spent for today, try again tomorrow');
+ }
+ return error(res, 502, 'judge_failed', 'the judge could not score this field');
}
// Decorate each ranking with display context the client needs (author,
diff --git a/api/bounties/[id]/likes.js b/api/bounties/[id]/likes.js
index 2d72c934d..069d54919 100644
--- a/api/bounties/[id]/likes.js
+++ b/api/bounties/[id]/likes.js
@@ -8,6 +8,7 @@
import { sql } from '../../_lib/db.js';
import { cors, json, error, readJson, wrap, method } from '../../_lib/http.js';
import { getSessionUser } from '../../_lib/auth.js';
+import { requireCsrf } from '../../_lib/csrf.js';
import { isUuid } from '../../_lib/validate.js';
export default wrap(async (req, res) => {
@@ -20,6 +21,7 @@ export default wrap(async (req, res) => {
const user = await getSessionUser(req).catch(() => null);
if (!user) return error(res, 401, 'unauthorized', 'sign in to like submissions');
+ if (!(await requireCsrf(req, res, user.id))) return;
const body = await readJson(req);
const submissionId = body?.submission_id;
diff --git a/api/bounties/[id]/resolve.js b/api/bounties/[id]/resolve.js
index 642f1717d..59fb5d383 100644
--- a/api/bounties/[id]/resolve.js
+++ b/api/bounties/[id]/resolve.js
@@ -1,18 +1,31 @@
+// POST /api/bounties/:id/resolve: the poster picks a winner and closes the
+// bounty. Body: { submission_id, tx_hash? }.
+//
+// This is the destructive end of the board. It accepts one submission, rejects
+// every other one, and closes the bounty permanently (a second call 409s). It
+// records the payout tx hash the poster supplies; it never moves funds itself.
+
import { sql } from '../../_lib/db.js';
import { cors, json, error, readJson, wrap, method } from '../../_lib/http.js';
import { getSessionUser } from '../../_lib/auth.js';
+import { requireCsrf } from '../../_lib/csrf.js';
+import { isUuid } from '../../_lib/validate.js';
export default wrap(async (req, res) => {
- if (cors(req, res)) return;
+ if (cors(req, res, { methods: 'POST,OPTIONS' })) return;
if (!method(req, res, ['POST'])) return;
- let user;
- try { user = await getSessionUser(req); } catch {
- return error(res, 401, 'unauthorized', 'sign in required');
- }
+ // getSessionUser resolves to null for an anonymous caller rather than
+ // throwing, so the null case needs its own guard (reading user.id off null
+ // surfaced as a 500 on every signed-out request, not the intended 401).
+ const user = await getSessionUser(req).catch(() => null);
+ if (!user) return error(res, 401, 'unauthorized', 'sign in required');
+ if (!(await requireCsrf(req, res, user.id))) return;
const id = req.query?.id;
- if (!id) return error(res, 400, 'bad_request', 'bounty id required');
+ // A non-uuid segment reaching a uuid-typed query throws NeonDbError and 500s;
+ // treat it as a miss, matching api/bounties/[id].js.
+ if (!id || !isUuid(id)) return error(res, 404, 'not_found', 'bounty not found');
const [bounty] = await sql`
SELECT id, user_id, status, reward_sol FROM bounties
@@ -22,31 +35,37 @@ export default wrap(async (req, res) => {
if (bounty.user_id !== user.id) return error(res, 403, 'forbidden', 'only the bounty poster can resolve');
if (bounty.status === 'closed') return error(res, 409, 'already_closed', 'bounty already resolved');
- const body = await readJson(req);
- const { submission_id, tx_hash } = body;
- if (!submission_id) return error(res, 400, 'bad_request', 'submission_id required');
+ const body = await readJson(req, 16_000);
+ const submissionId = body?.submission_id;
+ const txHash = typeof body?.tx_hash === 'string' ? body.tx_hash.trim() : '';
+ if (!submissionId) return error(res, 400, 'bad_request', 'submission_id required');
+ if (!isUuid(submissionId)) return error(res, 400, 'bad_request', 'submission_id must be a uuid');
+ if (txHash.length > 128) return error(res, 400, 'bad_request', 'tx_hash too long (max 128)');
const [submission] = await sql`
- SELECT id FROM bounty_submissions WHERE id = ${submission_id} AND bounty_id = ${id}
+ SELECT id FROM bounty_submissions WHERE id = ${submissionId} AND bounty_id = ${id}
`;
if (!submission) return error(res, 404, 'not_found', 'submission not found on this bounty');
- await sql`
- UPDATE bounty_submissions SET status = 'rejected'
- WHERE bounty_id = ${id} AND id != ${submission_id}
- `;
-
- const [winner] = await sql`
- UPDATE bounty_submissions
- SET status = 'accepted', reward_sol = ${bounty.reward_sol || null}, tx_hash = ${tx_hash?.trim() || null}
- WHERE id = ${submission_id}
- RETURNING *
- `;
-
- await sql`
- UPDATE bounties SET status = 'closed', winner_submission_id = ${submission_id}
- WHERE id = ${id}
- `;
+ // One transaction: a failure partway through would otherwise leave every
+ // submission rejected with no accepted winner and the bounty still open, a
+ // state no later call can repair since the losers are already rejected.
+ const [, [winner]] = await sql.transaction([
+ sql`
+ UPDATE bounty_submissions SET status = 'rejected'
+ WHERE bounty_id = ${id} AND id != ${submissionId}
+ `,
+ sql`
+ UPDATE bounty_submissions
+ SET status = 'accepted', reward_sol = ${bounty.reward_sol || null}, tx_hash = ${txHash || null}
+ WHERE id = ${submissionId}
+ RETURNING *
+ `,
+ sql`
+ UPDATE bounties SET status = 'closed', winner_submission_id = ${submissionId}
+ WHERE id = ${id}
+ `,
+ ]);
return json(res, 200, { winner });
});
diff --git a/api/bounties/[id]/submissions.js b/api/bounties/[id]/submissions.js
index 40e8d9717..407a02888 100644
--- a/api/bounties/[id]/submissions.js
+++ b/api/bounties/[id]/submissions.js
@@ -1,19 +1,42 @@
+// GET/POST /api/bounties/:id/submissions: the proof feed under one bounty.
+//
+// GET is public and paginated. POST is the entry point for claiming a bounty:
+// it records one proof (text and/or a media URL) against an open, unexpired
+// bounty and flips the bounty into 'resolving' so the poster sees there is
+// something to judge.
+
import { sql } from '../../_lib/db.js';
import { cors, json, error, readJson, wrap, method, rateLimited } from '../../_lib/http.js';
import { getSessionUser } from '../../_lib/auth.js';
+import { requireCsrf } from '../../_lib/csrf.js';
+import { isUuid } from '../../_lib/validate.js';
import { limits } from '../../_lib/rate-limit.js';
import { enrichLikes } from '../../_lib/bounty-likes.js';
+const DEFAULT_LIMIT = 20;
+const MAX_LIMIT = 50;
+
+// parseInt returns NaN on junk ("?limit=abc"), and NaN survives Math.min /
+// Math.max, so an unclamped value reached the query as `LIMIT NaN` and 500'd.
+// Anything unparseable or out of range falls back to the documented default.
+function intParam(raw, fallback, min, max) {
+ const n = parseInt(raw ?? '', 10);
+ if (!Number.isFinite(n)) return fallback;
+ return Math.min(Math.max(n, min), max);
+}
+
export default wrap(async (req, res) => {
if (cors(req, res)) return;
const id = req.query?.id;
- if (!id) return error(res, 400, 'bad_request', 'bounty id required');
+ // Non-uuid segments (scanner junk) must not reach a uuid-typed query: that
+ // throws NeonDbError and 500s. Treat them as a miss, as api/bounties/[id].js does.
+ if (!id || !isUuid(id)) return error(res, 404, 'not_found', 'bounty not found');
if (req.method === 'GET') {
const url = new URL(req.url, 'http://localhost');
- const limit = Math.min(parseInt(url.searchParams.get('limit') || '20', 10), 50);
- const offset = Math.max(parseInt(url.searchParams.get('offset') || '0', 10), 0);
+ const limit = intParam(url.searchParams.get('limit'), DEFAULT_LIMIT, 1, MAX_LIMIT);
+ const offset = intParam(url.searchParams.get('offset'), 0, 0, Number.MAX_SAFE_INTEGER);
const rows = await sql`
SELECT id, bounty_id, user_id, username, content, media_url, media_type,
@@ -29,13 +52,9 @@ export default wrap(async (req, res) => {
}
if (req.method === 'POST') {
- let user;
- try {
- user = await getSessionUser(req);
- } catch {
- return error(res, 401, 'unauthorized', 'sign in to submit');
- }
+ const user = await getSessionUser(req).catch(() => null);
if (!user) return error(res, 401, 'unauthorized', 'sign in to submit');
+ if (!(await requireCsrf(req, res, user.id))) return;
const rl = await limits.bountySubmit(user.id);
if (!rl.success) return rateLimited(res, rl, 'too many submissions, slow down');
@@ -51,28 +70,30 @@ export default wrap(async (req, res) => {
}
const body = await readJson(req, 16_000);
- const { content, media_url, media_type } = body;
- if (!content?.trim() && !media_url?.trim()) {
+ const content = typeof body?.content === 'string' ? body.content : null;
+ const mediaUrl = typeof body?.media_url === 'string' ? body.media_url : null;
+ const mediaType = typeof body?.media_type === 'string' ? body.media_type : null;
+ if (!content?.trim() && !mediaUrl?.trim()) {
return error(res, 400, 'bad_request', 'provide a description or media URL');
}
- // Bound free-text and validate the media URL shape — it's rendered to every
+ // Bound free-text and validate the media URL shape: it's rendered to every
// other user, so reject oversized content and non-http(s) links.
- if (typeof content === 'string' && content.length > 4000)
+ if (content && content.length > 4000)
return error(res, 400, 'bad_request', 'content too long (max 4000)');
- if (typeof media_url === 'string' && media_url.trim()) {
- const u = media_url.trim();
+ if (mediaUrl?.trim()) {
+ const u = mediaUrl.trim();
if (u.length > 2000 || !/^https?:\/\//i.test(u))
return error(res, 400, 'bad_request', 'media_url must be a valid http(s) URL');
}
const validTypes = ['image', 'video', 'link'];
const mtype =
- media_type && validTypes.includes(media_type) ? media_type : media_url ? 'link' : null;
+ mediaType && validTypes.includes(mediaType) ? mediaType : mediaUrl ? 'link' : null;
const username = user.display_name || user.email?.split('@')[0] || 'anon';
const [submission] = await sql`
INSERT INTO bounty_submissions (bounty_id, user_id, username, content, media_url, media_type)
- VALUES (${id}, ${user.id}, ${username}, ${content?.trim() || null}, ${media_url?.trim() || null}, ${mtype})
+ VALUES (${id}, ${user.id}, ${username}, ${content?.trim() || null}, ${mediaUrl?.trim() || null}, ${mtype})
RETURNING *
`;
diff --git a/data/pages.json b/data/pages.json
index 2eb74d60d..5f7239a3b 100644
--- a/data/pages.json
+++ b/data/pages.json
@@ -1097,6 +1097,14 @@
"title": "Crypto",
"description": "On-chain features: pay-per-call, token launches, vanity wallets.",
"pages": [
+ {
+ "path": "/go",
+ "title": "GO Bounty Board",
+ "description": "Post a bounty with a SOL reward, submit proof of doing it, and let the poster (or the AI judge) pick a winner. Live earner and spender leaderboards.",
+ "priority": 0.7,
+ "changefreq": "daily",
+ "added": "2026-06-05"
+ },
{
"path": "/sperax",
"title": "Sperax on three.ws",
diff --git a/prompts/swarm-100/api-bazaar-01.md b/prompts/swarm-100/api-auth-02.md
similarity index 96%
rename from prompts/swarm-100/api-bazaar-01.md
rename to prompts/swarm-100/api-auth-02.md
index f91d20f9d..279b796ac 100644
--- a/prompts/swarm-100/api-bazaar-01.md
+++ b/prompts/swarm-100/api-auth-02.md
@@ -1,4 +1,4 @@
-# API audit: api/bazaar batch 01 (5 files)
+# API audit: api/auth batch 02 (4 files)
How to run: paste this file's repo path into a fresh Claude Code chat in this
repository and say "run this work order". This file is fully self-contained:
@@ -37,11 +37,10 @@ Every claim below rots; step 0 re-measures, and what you measure wins.
Files in this batch:
-- api/bazaar/arbitrage.js
-- api/bazaar/context.js
-- api/bazaar/list.js
-- api/bazaar/providers.js
-- api/bazaar/search.js
+- api/auth/siws/[action].js
+- api/auth/wallets/[action].js
+- api/auth/wallets/_link-nonces.js
+- api/auth/x/[action].js
For every routed handler:
@@ -91,7 +90,7 @@ For every internal (non-routed) module:
style: type(scope): what changed and why a reader cares).
3. Delete this prompt file in that same commit:
- git rm prompts/swarm-100/api-bazaar-01.md
+ git rm prompts/swarm-100/api-auth-02.md
The shrinking directory is this campaign's only progress ledger; there is
no progress log to update.
diff --git a/public/providers.js b/public/providers.js
index 4b022f2bf..221d95595 100644
--- a/public/providers.js
+++ b/public/providers.js
@@ -226,7 +226,11 @@ async function loadProfile(host) {
return;
}
- const totalListings = data.listings.length;
+ // The API caps the listings array (a 3k-endpoint provider used to ship a
+ // 10 MB profile), so the headline count comes from listingTotal and the
+ // tag/network bars are normalised against the rows we actually received.
+ const shownListings = data.listings.length;
+ const totalListings = data.listingTotal ?? shownListings;
const tagCounts = new Map();
for (const l of data.listings) for (const t of l.tags || []) tagCounts.set(t, (tagCounts.get(t) || 0) + 1);
const topTags = [...tagCounts.entries()].sort((a, b) => b[1] - a[1]).slice(0, 6);
@@ -258,7 +262,7 @@ async function loadProfile(host) {
</div>
</div>
<div class="panel" style="margin-top: 14px;">
- <h3>Profile · ${totalListings} listings</h3>
+ <h3>Profile · ${totalListings} listings${shownListings < totalListings ? ` (showing ${shownListings})` : ''}</h3>
<div class="metric-list">
<div class="row"><span class="k">HTTP endpoints</span><span class="v">${typeBreakdown.http}</span></div>
<div class="row"><span class="k">MCP tools</span><span class="v">${typeBreakdown.mcp}</span></div>
@@ -292,7 +296,7 @@ async function loadProfile(host) {
<div class="bar-list">${netRows.map(([n, c]) => `
<div class="bar-row">
<div class="label">${escapeHtml(shortNet(n))}</div>
- <div class="bar"><div class="fill" style="width:${Math.round((c / totalListings) * 100)}%"></div></div>
+ <div class="bar"><div class="fill" style="width:${Math.round((c / shownListings) * 100)}%"></div></div>
<div class="pct">${c}</div>
</div>
`).join('')}</div>
diff --git a/scripts/qa-go-bounty-browser.mjs b/scripts/qa-go-bounty-browser.mjs
new file mode 100644
index 000000000..52656aeb1
--- /dev/null
+++ b/scripts/qa-go-bounty-browser.mjs
@@ -0,0 +1,112 @@
+// Browser check for the /go bounty board after routing its API calls through
+// apiFetch (CSRF). Signs in as a real account, posts a bounty, submits proof on
+// it from the same session, toggles a like, and fails on any console error.
+//
+// Usage:
+// QA_EMAIL=... QA_PASSWORD=... QA_BASE=http://localhost:3199 \
+// node scripts/qa-go-bounty-browser.mjs
+
+import { chromium } from 'playwright';
+
+const BASE = process.env.QA_BASE || 'http://localhost:3199';
+const EMAIL = process.env.QA_EMAIL;
+const PASSWORD = process.env.QA_PASSWORD;
+if (!EMAIL || !PASSWORD) {
+ console.error('QA_EMAIL and QA_PASSWORD are required');
+ process.exit(2);
+}
+
+const browser = await chromium.launch();
+const page = await browser.newPage();
+const consoleErrors = [];
+// Vite's dev-server HMR socket cannot reach a forwarded Codespaces port; that
+// noise is the harness, not the page.
+const IGNORE = /\[vite\]|WebSocket|walletconnect|privy/i;
+page.on('console', (m) => {
+ if (m.type() === 'error' && !IGNORE.test(m.text())) consoleErrors.push(m.text());
+});
+page.on('pageerror', (e) => {
+ if (!IGNORE.test(e.message)) consoleErrors.push('pageerror: ' + e.message);
+});
+
+const failures = [];
+function check(label, ok, detail = '') {
+ console.log(`${ok ? 'PASS' : 'FAIL'} ${label}${detail ? ' :: ' + detail : ''}`);
+ if (!ok) failures.push(label);
+}
+
+await page.goto(`${BASE}/login`, { waitUntil: 'domcontentloaded' });
+await page.fill('#email', EMAIL);
+await page.fill('#password', PASSWORD);
+await page.click('form button[type="submit"]');
+await page.waitForURL((u) => !/\/login/.test(u.pathname), { timeout: 45_000 });
+check('signed in', !/\/login/.test(new URL(page.url()).pathname), page.url());
+
+await page.goto(`${BASE}/go`, { waitUntil: 'domcontentloaded' });
+await page.waitForSelector('#create-btn', { timeout: 20_000 });
+// #create-btn is static markup, so wait for the chip loadUser() reveals before
+// asserting on it.
+await page.waitForSelector('#user-btn:visible', { timeout: 20_000 }).catch(() => {});
+check(
+ 'user chip shows the signed-in display name',
+ (await page.textContent('#user-btn')) === 'qa-poster',
+ await page.textContent('#user-btn'),
+);
+
+const posts = [];
+page.on('response', (r) => {
+ if (r.request().method() === 'POST' && r.url().includes('/api/bounties'))
+ posts.push(`${r.status()} ${new URL(r.url()).pathname}`);
+});
+
+const title = `QA browser bounty ${Date.now()}`;
+await page.click('#create-btn');
+await page.fill('#c-title', title);
+await page.fill('#c-desc', 'Posted by scripts/qa-go-bounty-browser.mjs');
+await page.fill('#c-sol', '0.01');
+await page.click('#create-submit');
+await page
+ .waitForFunction(
+ () => {
+ const err = document.getElementById('create-error');
+ const modal = document.getElementById('create-modal');
+ return (
+ (err && err.style.display !== 'none' && err.textContent.trim()) ||
+ (modal && !modal.classList.contains('open'))
+ );
+ },
+ { timeout: 30_000 },
+ )
+ .catch(() => {});
+const createErrVisible = await page.isVisible('#create-error').catch(() => false);
+const createErr = createErrVisible ? (await page.textContent('#create-error')) || '' : '';
+check('bounty POST accepted', posts.some((p) => p.startsWith('201')), posts.join(', '));
+check('create form shows no error', !createErrVisible, createErr.trim());
+
+await page.waitForTimeout(2000);
+const listed = await page.locator(`text=${title}`).count();
+check('new bounty rendered in the feed', listed > 0, `${listed} match(es)`);
+
+// Submit proof on the bounty just posted, then like it: both are CSRF-gated
+// POSTs that must now carry a token.
+const submitBtn = page.locator(`[data-action="submit"][data-title="${title}"]`).first();
+if (await submitBtn.count()) {
+ await submitBtn.click();
+ await page.fill('#s-content', 'QA browser proof');
+ await page.click('#submit-proof-btn');
+ await page.waitForTimeout(3000);
+ check('proof POST accepted', posts.some((p) => p.includes('/submissions') && p.startsWith('201')), posts.join(', '));
+} else {
+ check('proof POST accepted', false, 'no submit button on the new card');
+}
+
+check('no console errors', consoleErrors.length === 0, consoleErrors.slice(0, 3).join(' | '));
+
+await page.screenshot({ path: process.env.QA_SHOT || '/tmp/qa-go.png', fullPage: false });
+await browser.close();
+
+if (failures.length) {
+ console.error('FAILURES: ' + failures.join(', '));
+ process.exit(1);
+}
+console.log('all checks passed');
diff --git a/src/go.js b/src/go.js
index 427e8a7b8..629ba72a4 100644
--- a/src/go.js
+++ b/src/go.js
@@ -1,6 +1,7 @@
// Bounty board — three.ws/go
import { safeUrl } from './safe-url.js';
+import { apiFetch } from './api.js';
const API = '/api/bounties';
let currentTab = 'feed';
@@ -26,9 +27,13 @@ async function init() {
async function loadUser() {
try {
- const r = await fetch('/api/auth/me', { credentials: 'include' });
+ const r = await apiFetch('/api/auth/me', { allowAnonymous: true });
if (r.ok) {
- currentUser = await r.json();
+ // /api/auth/me answers { user: {...} }; reading the envelope as the
+ // user left the account chip labelled "account" for everyone.
+ currentUser = (await r.json())?.user || null;
+ }
+ if (currentUser) {
const btn = document.getElementById('user-btn');
btn.textContent =
currentUser.display_name || currentUser.email?.split('@')[0] || 'account';
@@ -66,7 +71,9 @@ async function loadFeed(reset = false) {
}
try {
- const r = await fetch(`${API}?tab=${currentTab}&limit=20&offset=${feedOffset}`);
+ const r = await apiFetch(`${API}?tab=${currentTab}&limit=20&offset=${feedOffset}`, {
+ allowAnonymous: true,
+ });
const data = await r.json();
if (reset) el.innerHTML = '';
@@ -218,7 +225,7 @@ async function loadSidebar() {
async function loadTopBounties() {
const el = document.getElementById('top-bounties');
try {
- const r = await fetch(`${API}?tab=open&limit=5`);
+ const r = await apiFetch(`${API}?tab=open&limit=5`, { allowAnonymous: true });
const { bounties } = await r.json();
if (!bounties?.length) {
el.innerHTML =
@@ -252,7 +259,7 @@ async function loadLeaderboards() {
const spendersEl = document.getElementById('top-spenders');
try {
- const r = await fetch('/api/bounties/leaderboard');
+ const r = await apiFetch('/api/bounties/leaderboard', { allowAnonymous: true });
if (r.ok) {
const { earners, spenders } = await r.json();
earnersEl.innerHTML = renderLeaderboard(earners);
@@ -372,9 +379,8 @@ function bindCreate() {
btn.disabled = true;
try {
- const r = await fetch(API, {
+ const r = await apiFetch(API, {
method: 'POST',
- credentials: 'include',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({
title,
@@ -436,9 +442,8 @@ function bindSubmit() {
btn.disabled = true;
try {
- const r = await fetch(`${API}/${activeBountyId}/submissions`, {
+ const r = await apiFetch(`${API}/${activeBountyId}/submissions`, {
method: 'POST',
- credentials: 'include',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({
content: content || undefined,
@@ -480,8 +485,8 @@ async function openResolveModal(bountyId) {
openModal('resolve-modal');
try {
- const r = await fetch(`${API}/${bountyId}/submissions?limit=50`, {
- credentials: 'include',
+ const r = await apiFetch(`${API}/${bountyId}/submissions?limit=50`, {
+ allowAnonymous: true,
});
const data = await r.json();
resolveSubmissions = data.submissions || [];
@@ -547,9 +552,8 @@ function bindResolve() {
btn.disabled = true;
try {
- const r = await fetch(`${API}/${activeBountyId}/resolve`, {
+ const r = await apiFetch(`${API}/${activeBountyId}/resolve`, {
method: 'POST',
- credentials: 'include',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({
submission_id: selectedSubmissionId,
@@ -596,9 +600,8 @@ async function toggleLike(btn) {
btn.disabled = true;
try {
- const r = await fetch(`${API}/${bid}/likes`, {
+ const r = await apiFetch(`${API}/${bid}/likes`, {
method: 'POST',
- credentials: 'include',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ submission_id: sid }),
});
@@ -631,10 +634,7 @@ async function runJudge() {
btn.textContent = '✨ Judging…';
try {
- const r = await fetch(`${API}/${activeBountyId}/judge`, {
- method: 'POST',
- credentials: 'include',
- });
+ const r = await apiFetch(`${API}/${activeBountyId}/judge`, { method: 'POST' });
const data = await r.json();
if (!r.ok) throw new Error(data.error_description || data.error || 'failed');
diff --git a/tests/api/bazaar-endpoints.test.js b/tests/api/bazaar-endpoints.test.js
new file mode 100644
index 000000000..aa3dfa15f
--- /dev/null
+++ b/tests/api/bazaar-endpoints.test.js
@@ -0,0 +1,456 @@
+// Contract tests for the five /api/bazaar/* handlers and the discovery client
+// they share (api/_lib/x402/bazaar-client.js).
+//
+// The facilitators are stubbed at `fetch`, so every layer under it runs for
+// real: pagination, cross-facilitator dedupe, normalization, filtering, the
+// per-endpoint caps, and the failure paths. These cover the defects the
+// 2026-08-10 audit found against the live catalog:
+// - `limit` on /api/bazaar/list reached only the facilitator page size, so a
+// caller asking for 20 endpoints got the entire catalog.
+// - `maxItems` bounded nothing when a facilitator ignored `limit`.
+// - A facilitator that ignores `offset` replayed page one until `maxItems`,
+// turning one small query into hundreds of identical round trips.
+// - /api/bazaar/providers?host= returned every listing (10 MB for the
+// largest provider in the live catalog).
+// - An explicit `minProviders` was ignored whenever two facilitators listed
+// the same single-host capability.
+// - A total facilitator outage surfaced as an empty 200 catalog, which reads
+// as "no such service exists".
+
+import { describe, it, expect, beforeEach, afterAll } from 'vitest';
+
+const FAC_A = 'https://fac-a.test';
+const FAC_B = 'https://fac-b.test';
+
+process.env.X402_FACILITATOR_URL_BASE = FAC_A;
+process.env.X402_CDP_FACILITATOR_URL = FAC_B;
+delete process.env.X402_FACILITATOR_URL_SOLANA;
+
+const USDC_BASE = '0x833589fcd6edb6e08f4c7c32d4f71b54bda02913';
+
+function httpItem({ resource, name, amount, category = 'data', description = 'A paid endpoint.' }) {
+ return {
+ type: 'http',
+ resource,
+ description,
+ accepts: [
+ {
+ scheme: 'exact',
+ network: 'base',
+ maxAmountRequired: String(amount),
+ asset: USDC_BASE,
+ payTo: '0x00000000000000000000000000000000000000a1',
+ },
+ ],
+ extensions: { bazaar: { name, category } },
+ };
+}
+
+function mcpItem({ resource, toolName, amount }) {
+ return {
+ type: 'mcp',
+ resource,
+ description: `MCP tool ${toolName}.`,
+ accepts: [
+ {
+ scheme: 'exact',
+ network: 'base',
+ maxAmountRequired: String(amount),
+ asset: USDC_BASE,
+ payTo: '0x00000000000000000000000000000000000000a2',
+ },
+ ],
+ extensions: { bazaar: { name: toolName, info: { input: { type: 'mcp', toolName } } } },
+ };
+}
+
+// alpha.example sells five endpoints; beta.example sells the same weather
+// capability at 10x the price (the arbitrage case) plus one of its own.
+const ALPHA_WEATHER = httpItem({
+ resource: 'https://alpha.example/api/weather-forecast',
+ name: 'Weather Forecast',
+ amount: 5_000,
+ category: 'weather',
+});
+const CATALOG = {
+ [FAC_A]: [
+ ALPHA_WEATHER,
+ httpItem({ resource: 'https://alpha.example/api/notes', name: 'Notes Store', amount: 1_000 }),
+ httpItem({ resource: 'https://alpha.example/api/geocode', name: 'Geocoder', amount: 2_000 }),
+ httpItem({ resource: 'https://alpha.example/api/ocr', name: 'OCR Reader', amount: 3_000 }),
+ httpItem({ resource: 'https://alpha.example/api/translate', name: 'Translator', amount: 4_000 }),
+ httpItem({
+ resource: 'https://beta.example/api/weather-forecast',
+ name: 'Weather Forecast',
+ amount: 50_000,
+ category: 'weather',
+ }),
+ mcpItem({ resource: 'https://alpha.example/mcp', toolName: 'summarize', amount: 900 }),
+ ],
+ // Same weather listing as fac-a (dedupe), plus one fac-b exclusive.
+ [FAC_B]: [
+ ALPHA_WEATHER,
+ httpItem({ resource: 'https://gamma.example/api/quotes', name: 'Quote Feed', amount: 7_000 }),
+ ],
+};
+
+let fetchCalls = [];
+let failAll = false;
+let replayOffsets = false;
+const realFetch = globalThis.fetch;
+
+globalThis.fetch = async (input) => {
+ const raw = typeof input === 'string' ? input : input?.url || String(input);
+ const u = new URL(raw);
+ const origin = `${u.protocol}//${u.host}`;
+ fetchCalls.push(raw);
+ if (!(origin in CATALOG)) {
+ // Anything else (the LLM chain in /api/bazaar/context) must not reach the
+ // network from a test: refusing it exercises the deterministic fallback.
+ throw new Error(`blocked network call to ${origin}`);
+ }
+ if (failAll) return new Response('facilitator down', { status: 503 });
+ const type = u.searchParams.get('type') || 'http';
+ const limit = Number(u.searchParams.get('limit') || 200);
+ const offset = replayOffsets ? 0 : Number(u.searchParams.get('offset') || 0);
+ const all = CATALOG[origin].filter((i) => i.type === type);
+ return new Response(
+ JSON.stringify({ items: all.slice(offset, offset + limit), pagination: { total: all.length } }),
+ { status: 200, headers: { 'content-type': 'application/json' } },
+ );
+};
+
+afterAll(() => {
+ globalThis.fetch = realFetch;
+});
+
+const { default: listHandler } = await import('../../api/bazaar/list.js');
+const { default: searchHandler } = await import('../../api/bazaar/search.js');
+const { default: providersHandler } = await import('../../api/bazaar/providers.js');
+const { default: arbitrageHandler } = await import('../../api/bazaar/arbitrage.js');
+const { default: contextHandler } = await import('../../api/bazaar/context.js');
+const { Bazaar, clearCatalogCache } = await import('../../api/_lib/x402/bazaar-client.js');
+
+let ipCounter = 0;
+function makeReq({ url, method = 'GET' } = {}) {
+ ipCounter++;
+ return {
+ method,
+ url,
+ headers: { 'x-forwarded-for': `198.51.100.${ipCounter % 250}` },
+ socket: { remoteAddress: `198.51.100.${ipCounter % 250}` },
+ };
+}
+
+function makeRes() {
+ return {
+ statusCode: 200,
+ headers: {},
+ body: '',
+ writableEnded: false,
+ headersSent: false,
+ setHeader(k, v) {
+ this.headers[k.toLowerCase()] = v;
+ },
+ getHeader(k) {
+ return this.headers[k.toLowerCase()];
+ },
+ end(chunk) {
+ if (chunk !== undefined) this.body += chunk;
+ this.writableEnded = true;
+ this.headersSent = true;
+ },
+ };
+}
+
+async function invoke(handler, url, method = 'GET') {
+ const res = makeRes();
+ await handler(makeReq({ url, method }), res);
+ let payload = null;
+ if (res.body) {
+ try {
+ payload = JSON.parse(res.body);
+ } catch {
+ payload = res.body;
+ }
+ }
+ return { status: res.statusCode, payload, headers: res.headers };
+}
+
+beforeEach(() => {
+ fetchCalls = [];
+ failAll = false;
+ replayOffsets = false;
+ // The handlers share an in-process catalog memo; each case configures its
+ // own facilitator behaviour, so start every one from a cold catalog.
+ clearCatalogCache();
+});
+
+describe('GET /api/bazaar/list', () => {
+ it('merges facilitators, dedupes by resource, and reports both sources', async () => {
+ const { status, payload } = await invoke(listHandler, '/api/bazaar/list');
+ expect(status).toBe(200);
+ // 6 HTTP listings on fac-a + 1 exclusive on fac-b; the shared weather
+ // listing must appear exactly once.
+ expect(payload.count).toBe(7);
+ const weather = payload.items.filter(
+ (i) => i.resource === 'https://alpha.example/api/weather-forecast',
+ );
+ expect(weather).toHaveLength(1);
+ expect(payload.sources.map((s) => s.ok)).toEqual([true, true]);
+ expect(payload.errors).toEqual([]);
+ });
+
+ it('caps the response at `limit` and reports the pre-cut total', async () => {
+ const { status, payload } = await invoke(listHandler, '/api/bazaar/list?limit=2');
+ expect(status).toBe(200);
+ expect(payload.items).toHaveLength(2);
+ expect(payload.count).toBe(2);
+ expect(payload.total).toBe(7);
+ });
+
+ it('filters by network, tag, and atomic max price', async () => {
+ const byTag = await invoke(listHandler, '/api/bazaar/list?tag=weather');
+ expect(byTag.payload.count).toBe(2);
+
+ const byNetwork = await invoke(listHandler, '/api/bazaar/list?network=eip155:*');
+ expect(byNetwork.payload.count).toBe(7);
+ const noMatch = await invoke(listHandler, '/api/bazaar/list?network=solana:*');
+ expect(noMatch.payload.count).toBe(0);
+
+ const cheap = await invoke(listHandler, '/api/bazaar/list?maxPrice=3000&sort=price');
+ expect(cheap.payload.items.map((i) => i.minPriceAtomic)).toEqual([1000, 2000, 3000]);
+ });
+
+ it('rejects a decimal maxPrice and an unknown type with a 400 JSON error', async () => {
+ const decimal = await invoke(listHandler, '/api/bazaar/list?maxPrice=0.01');
+ expect(decimal.status).toBe(400);
+ expect(decimal.payload.error).toBe('bad_request');
+
+ const type = await invoke(listHandler, '/api/bazaar/list?type=grpc');
+ expect(type.status).toBe(400);
+ });
+
+ it('treats an empty maxPrice as no cap instead of a 400', async () => {
+ const { status, payload } = await invoke(listHandler, '/api/bazaar/list?maxPrice=');
+ expect(status).toBe(200);
+ expect(payload.count).toBe(7);
+ });
+
+ it('answers 405 on a non-GET and sets wildcard CORS', async () => {
+ const { status, payload, headers } = await invoke(listHandler, '/api/bazaar/list', 'POST');
+ expect(status).toBe(405);
+ expect(payload.error).toBe('method_not_allowed');
+ expect(headers['access-control-allow-origin']).toBe('*');
+ });
+
+ it('answers 502 when every facilitator fails instead of an empty catalog', async () => {
+ failAll = true;
+ const { status, payload } = await invoke(listHandler, '/api/bazaar/list');
+ expect(status).toBe(502);
+ expect(payload.error).toBe('facilitator_error');
+ expect(payload.error_description).toContain('fac-a.test');
+ });
+});
+
+describe('GET /api/bazaar/search', () => {
+ it('ranks matches for the query and reports the pre-cut total', async () => {
+ const { status, payload } = await invoke(listHandler, '/api/bazaar/search?query=weather');
+ expect(status).toBe(200);
+ expect(payload.count).toBe(7);
+
+ const search = await invoke(searchHandler, '/api/bazaar/search?query=weather');
+ expect(search.status).toBe(200);
+ expect(search.payload.count).toBe(2);
+ expect(search.payload.resources.every((r) => /weather/i.test(JSON.stringify(r)))).toBe(true);
+
+ const capped = await invoke(searchHandler, '/api/bazaar/search?query=weather&limit=1');
+ expect(capped.payload.count).toBe(1);
+ expect(capped.payload.total).toBe(2);
+ });
+
+ it('returns the whole catalog for an empty query and 400s a decimal price cap', async () => {
+ const all = await invoke(searchHandler, '/api/bazaar/search');
+ expect(all.payload.count).toBe(7);
+
+ const bad = await invoke(searchHandler, '/api/bazaar/search?maxPrice=1.5');
+ expect(bad.status).toBe(400);
+ });
+
+ it('answers 502 when every facilitator fails', async () => {
+ failAll = true;
+ const { status, payload } = await invoke(searchHandler, '/api/bazaar/search?query=weather');
+ expect(status).toBe(502);
+ expect(payload.error).toBe('facilitator_error');
+ });
+});
+
+describe('GET /api/bazaar/providers', () => {
+ it('aggregates hosts into profiles ordered by service count', async () => {
+ const { status, payload } = await invoke(providersHandler, '/api/bazaar/providers');
+ expect(status).toBe(200);
+ expect(payload.providers[0].host).toBe('alpha.example');
+ expect(payload.providers[0].serviceCount).toBe(6); // 5 HTTP + 1 MCP tool
+ expect(payload.providers[0].mcpCount).toBe(1);
+ expect(payload.providers[0].minPriceAtomic).toBe(900);
+ expect(payload.totalProviders).toBe(3);
+ });
+
+ it('caps a host profile listing array and reports the true total', async () => {
+ const { status, payload } = await invoke(
+ providersHandler,
+ '/api/bazaar/providers?host=alpha.example&limit=2',
+ );
+ expect(status).toBe(200);
+ expect(payload.listings).toHaveLength(2);
+ expect(payload.listingTotal).toBe(6);
+ expect(payload.serviceCount).toBe(6);
+ // Cheapest first, so the cap keeps the head of the price ladder.
+ expect(payload.listings.map((l) => l.priceAtomic)).toEqual([900, 1000]);
+ });
+
+ it('404s an unknown host and 405s a non-GET', async () => {
+ const missing = await invoke(providersHandler, '/api/bazaar/providers?host=nope.invalid');
+ expect(missing.status).toBe(404);
+ expect(missing.payload.error).toBe('not_found');
+
+ const post = await invoke(providersHandler, '/api/bazaar/providers', 'POST');
+ expect(post.status).toBe(405);
+ });
+
+ it('answers 502 when every facilitator fails', async () => {
+ failAll = true;
+ const { status } = await invoke(providersHandler, '/api/bazaar/providers');
+ expect(status).toBe(502);
+ });
+});
+
+describe('GET /api/bazaar/arbitrage', () => {
+ it('surfaces the same capability priced differently across two hosts', async () => {
+ const { status, payload } = await invoke(arbitrageHandler, '/api/bazaar/arbitrage');
+ expect(status).toBe(200);
+ const weather = payload.opportunities.find((o) => o.key === 'http:weather-forecast');
+ expect(weather).toBeTruthy();
+ expect(weather.providerCount).toBe(2);
+ expect(weather.minPriceAtomic).toBe(5_000);
+ expect(weather.maxPriceAtomic).toBe(50_000);
+ expect(weather.spreadAtomic).toBe(45_000);
+ expect(weather.spreadPct).toBe(900);
+ expect(weather.cheapest.host).toBe('alpha.example');
+ expect(weather.mostExpensive.host).toBe('beta.example');
+ expect(weather.minPriceLabel).toBe('0.005 USDC');
+ });
+
+ it('honors an explicitly raised minProviders floor', async () => {
+ const two = await invoke(arbitrageHandler, '/api/bazaar/arbitrage?minProviders=2');
+ expect(two.payload.opportunities.some((o) => o.key === 'http:weather-forecast')).toBe(true);
+
+ const three = await invoke(arbitrageHandler, '/api/bazaar/arbitrage?minProviders=3');
+ expect(three.payload.opportunities.some((o) => o.key === 'http:weather-forecast')).toBe(false);
+ });
+
+ it('drops groups below minSpreadPct and caps at limit', async () => {
+ const wide = await invoke(arbitrageHandler, '/api/bazaar/arbitrage?minSpreadPct=1000');
+ expect(wide.payload.count).toBe(0);
+
+ const capped = await invoke(arbitrageHandler, '/api/bazaar/arbitrage?limit=1');
+ expect(capped.payload.opportunities).toHaveLength(1);
+ });
+
+ it('answers 405 on a non-GET and 502 on a total facilitator outage', async () => {
+ const post = await invoke(arbitrageHandler, '/api/bazaar/arbitrage', 'POST');
+ expect(post.status).toBe(405);
+
+ failAll = true;
+ const down = await invoke(arbitrageHandler, '/api/bazaar/arbitrage');
+ expect(down.status).toBe(502);
+ });
+});
+
+describe('GET /api/bazaar/context', () => {
+ const target = encodeURIComponent('https://alpha.example/api/weather-forecast');
+
+ it('requires a resource and 404s one outside the catalog', async () => {
+ const missing = await invoke(contextHandler, '/api/bazaar/context');
+ expect(missing.status).toBe(400);
+ expect(missing.payload.error).toBe('bad_request');
+
+ const unknown = await invoke(
+ contextHandler,
+ '/api/bazaar/context?resource=https%3A%2F%2Fnope.invalid%2Fx',
+ );
+ expect(unknown.status).toBe(404);
+ });
+
+ it('falls back to a grounded deterministic summary when no LLM answers', async () => {
+ const { status, payload } = await invoke(
+ contextHandler,
+ `/api/bazaar/context?resource=${target}`,
+ );
+ expect(status).toBe(200);
+ expect(payload.source).toBe('deterministic');
+ expect(payload.summary.length).toBeGreaterThan(0);
+ expect(['up', 'down', 'neutral']).toContain(payload.sentiment);
+ expect(payload.stats.peerCount).toBe(1);
+ expect(payload.stats.targetPriceAtomic).toBe(5_000);
+ expect(payload.stats.providerSiblingsCount).toBe(5);
+ // Every [n] the summary cites must map to a real citation anchor.
+ const cited = [...payload.summary.matchAll(/\[(\d+)\]/g)].map((m) => Number(m[1]));
+ for (const n of cited) expect(payload.citations[n - 1]).toBeTruthy();
+ // No citation may link at an empty search query.
+ for (const c of payload.citations) expect(c.url).not.toMatch(/\?q=$/);
+ });
+
+ it('answers 405 on a non-GET and 502 on a total facilitator outage', async () => {
+ const post = await invoke(contextHandler, `/api/bazaar/context?resource=${target}`, 'POST');
+ expect(post.status).toBe(405);
+
+ failAll = true;
+ const down = await invoke(contextHandler, `/api/bazaar/context?resource=${target}`);
+ expect(down.status).toBe(502);
+ });
+});
+
+describe('bazaar-client catalog memo', () => {
+ it('serves a second read from memory instead of re-sweeping facilitators', async () => {
+ const baz = new Bazaar({ facilitators: [FAC_A] });
+ const first = await baz.listCached({ type: 'http', maxItems: 500 });
+ const afterFirst = fetchCalls.length;
+ expect(afterFirst).toBeGreaterThan(0);
+ const second = await baz.listCached({ type: 'http', maxItems: 500 });
+ expect(fetchCalls).toHaveLength(afterFirst);
+ expect(second.items).toHaveLength(first.items.length);
+ // Callers filter and sort in place, so each read gets its own array.
+ expect(second.items).not.toBe(first.items);
+ });
+
+ it('does not memoize a failed sweep', async () => {
+ failAll = true;
+ const baz = new Bazaar({ facilitators: [FAC_A] });
+ const down = await baz.listCached({ type: 'http', maxItems: 500 });
+ expect(down.sources.every((s) => !s.ok)).toBe(true);
+
+ failAll = false;
+ clearCatalogCache();
+ const up = await baz.listCached({ type: 'http', maxItems: 500 });
+ expect(up.items.length).toBeGreaterThan(0);
+ });
+});
+
+describe('bazaar-client paging bounds', () => {
+ it('never returns more than maxItems from one facilitator', async () => {
+ const baz = new Bazaar({ facilitators: [FAC_A] });
+ const { items } = await baz.list({ type: 'http', limit: 200, maxItems: 2 });
+ expect(items).toHaveLength(2);
+ });
+
+ it('stops after one duplicate page when a facilitator ignores offset', async () => {
+ replayOffsets = true;
+ const baz = new Bazaar({ facilitators: [FAC_A] });
+ const { items } = await baz.list({ type: 'http', limit: 2, maxItems: 500 });
+ // Page one (2 fresh) then page two (all duplicates) ends the walk, rather
+ // than the 250 round trips the unbounded loop used to make.
+ expect(fetchCalls).toHaveLength(2);
+ expect(items).toHaveLength(2);
+ });
+});
diff --git a/tests/bounties-endpoints.test.js b/tests/bounties-endpoints.test.js
new file mode 100644
index 000000000..60ed61cfe
--- /dev/null
+++ b/tests/bounties-endpoints.test.js
@@ -0,0 +1,255 @@
+// Endpoint tests for the /go bounty board handlers: submissions and resolve.
+//
+// Drives the real handlers with a fake req/res and mocked DB / auth / CSRF /
+// rate-limit. http.js (json/cors/method/wrap) runs for real, so status codes
+// and the JSON envelope are genuinely exercised.
+//
+// These pin the boundary behaviour an audit found missing: a non-uuid path
+// segment and junk pagination both reached a uuid-typed query and 500'd, a
+// signed-out resolve 500'd instead of answering 401, and none of the
+// state-changing routes demanded a CSRF token.
+
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+// Tagged-template `sql` that returns whatever the test queued, in order.
+const queue = [];
+const sqlCalls = [];
+vi.mock('../api/_lib/db.js', () => {
+ const sql = vi.fn(async (...args) => {
+ sqlCalls.push(args);
+ return queue.length ? queue.shift() : [];
+ });
+ sql.transaction = vi.fn(async (statements) => Promise.all(statements));
+ return { sql, isDbUnavailableError: () => false, isDbCapacityError: () => false };
+});
+
+let session = null;
+vi.mock('../api/_lib/auth.js', () => ({
+ getSessionUser: vi.fn(async () => session),
+ authenticateBearer: vi.fn(async () => null),
+ extractBearer: vi.fn(() => null),
+}));
+
+let csrfOk = true;
+vi.mock('../api/_lib/csrf.js', () => ({
+ requireCsrf: vi.fn(async (req, res) => {
+ if (csrfOk) return true;
+ res.statusCode = 403;
+ res.end(JSON.stringify({ error: 'csrf_missing' }));
+ return false;
+ }),
+}));
+
+vi.mock('../api/_lib/rate-limit.js', () => ({
+ limits: {
+ bountySubmit: vi.fn(async () => ({ success: true, limit: 10, remaining: 9, reset: 0 })),
+ },
+ clientIp: vi.fn(() => '127.0.0.1'),
+}));
+
+vi.mock('../api/_lib/bounty-likes.js', () => ({ enrichLikes: vi.fn(async (rows) => rows) }));
+
+import submissions from '../api/bounties/[id]/submissions.js';
+import resolve from '../api/bounties/[id]/resolve.js';
+
+const BID = 'a60e33b7-63b2-496a-bf2c-93b179c619e6';
+const SID = '9ffd34d7-4cb7-4573-9fc7-1dd8d1f18528';
+const USER = { id: 'cfda5143-fc65-426c-ae82-96628e263adf', display_name: 'qa' };
+
+function mockRes() {
+ return {
+ statusCode: 200,
+ headers: {},
+ body: '',
+ headersSent: false,
+ writableEnded: false,
+ setHeader(k, v) {
+ this.headers[k.toLowerCase()] = v;
+ },
+ getHeader(k) {
+ return this.headers[k.toLowerCase()];
+ },
+ end(payload) {
+ this.headersSent = true;
+ this.writableEnded = true;
+ this.body = payload || '';
+ },
+ get json() {
+ try {
+ return JSON.parse(this.body);
+ } catch {
+ return null;
+ }
+ },
+ };
+}
+
+function mockReq({ method = 'GET', id = BID, url = null, body = undefined } = {}) {
+ const req = {
+ method,
+ url: url || `/api/bounties/${id}/submissions`,
+ query: { id },
+ headers: {},
+ };
+ if (body !== undefined) {
+ req.headers['content-type'] = 'application/json';
+ req.rawBody = Buffer.from(JSON.stringify(body), 'utf8');
+ }
+ return req;
+}
+
+// Pull the interpolated values of the Nth sql`` call (args after the strings).
+function interpolations(n) {
+ return sqlCalls[n].slice(1);
+}
+
+beforeEach(() => {
+ queue.length = 0;
+ sqlCalls.length = 0;
+ session = null;
+ csrfOk = true;
+ vi.clearAllMocks();
+});
+
+describe('GET /api/bounties/:id/submissions', () => {
+ it('404s a non-uuid bounty id without touching the database', async () => {
+ const res = mockRes();
+ await submissions(mockReq({ id: 'not-a-uuid' }), res);
+ expect(res.statusCode).toBe(404);
+ expect(res.json.error).toBe('not_found');
+ expect(sqlCalls).toHaveLength(0);
+ });
+
+ it('falls back to the default page size when limit/offset are unparseable', async () => {
+ queue.push([]);
+ const res = mockRes();
+ await submissions(
+ mockReq({ url: `/api/bounties/${BID}/submissions?limit=abc&offset=abc` }),
+ res,
+ );
+ expect(res.statusCode).toBe(200);
+ expect(res.json).toEqual({ submissions: [] });
+ expect(interpolations(0)).toEqual([BID, 20, 0]);
+ });
+
+ it('clamps limit to the 1..50 window', async () => {
+ queue.push([]);
+ const over = mockRes();
+ await submissions(mockReq({ url: `/api/bounties/${BID}/submissions?limit=999` }), over);
+ expect(interpolations(0)[1]).toBe(50);
+
+ sqlCalls.length = 0;
+ queue.push([]);
+ const under = mockRes();
+ await submissions(mockReq({ url: `/api/bounties/${BID}/submissions?limit=-5` }), under);
+ expect(interpolations(0)[1]).toBe(1);
+ });
+});
+
+describe('POST /api/bounties/:id/submissions', () => {
+ it('401s an anonymous submitter', async () => {
+ const res = mockRes();
+ await submissions(mockReq({ method: 'POST', body: { content: 'hi' } }), res);
+ expect(res.statusCode).toBe(401);
+ expect(res.json.error).toBe('unauthorized');
+ });
+
+ it('403s without a CSRF token', async () => {
+ session = USER;
+ csrfOk = false;
+ const res = mockRes();
+ await submissions(mockReq({ method: 'POST', body: { content: 'hi' } }), res);
+ expect(res.statusCode).toBe(403);
+ });
+
+ it('rejects a non-http media_url', async () => {
+ session = USER;
+ queue.push([{ id: BID, status: 'open', expires_at: null }]);
+ const res = mockRes();
+ await submissions(
+ mockReq({ method: 'POST', body: { media_url: 'javascript:alert(1)' } }),
+ res,
+ );
+ expect(res.statusCode).toBe(400);
+ expect(res.json.error_description).toMatch(/http\(s\) URL/);
+ });
+
+ it('creates the submission and bumps the bounty counter', async () => {
+ session = USER;
+ queue.push([{ id: BID, status: 'open', expires_at: null }]);
+ queue.push([{ id: SID, bounty_id: BID, content: 'proof' }]);
+ queue.push([]);
+ const res = mockRes();
+ await submissions(mockReq({ method: 'POST', body: { content: 'proof' } }), res);
+ expect(res.statusCode).toBe(201);
+ expect(res.json.submission.id).toBe(SID);
+ expect(sqlCalls).toHaveLength(3);
+ });
+});
+
+describe('POST /api/bounties/:id/resolve', () => {
+ function resolveReq(body, id = BID) {
+ const req = mockReq({ method: 'POST', id, body });
+ req.url = `/api/bounties/${id}/resolve`;
+ return req;
+ }
+
+ it('401s a signed-out caller instead of throwing on a null session', async () => {
+ const res = mockRes();
+ await resolve(resolveReq({ submission_id: SID }), res);
+ expect(res.statusCode).toBe(401);
+ expect(res.json.error).toBe('unauthorized');
+ expect(sqlCalls).toHaveLength(0);
+ });
+
+ it('404s a non-uuid bounty id without touching the database', async () => {
+ session = USER;
+ const res = mockRes();
+ await resolve(resolveReq({ submission_id: SID }, 'not-a-uuid'), res);
+ expect(res.statusCode).toBe(404);
+ expect(sqlCalls).toHaveLength(0);
+ });
+
+ it('400s a non-uuid submission_id', async () => {
+ session = USER;
+ queue.push([{ id: BID, user_id: USER.id, status: 'open', reward_sol: '0.01' }]);
+ const res = mockRes();
+ await resolve(resolveReq({ submission_id: 'junk' }), res);
+ expect(res.statusCode).toBe(400);
+ expect(res.json.error_description).toMatch(/uuid/);
+ });
+
+ it('403s a caller who does not own the bounty', async () => {
+ session = { id: 'ad25b0a1-263e-4be7-89f8-adbf0363ee7c' };
+ queue.push([{ id: BID, user_id: USER.id, status: 'open', reward_sol: '0.01' }]);
+ const res = mockRes();
+ await resolve(resolveReq({ submission_id: SID }), res);
+ expect(res.statusCode).toBe(403);
+ });
+
+ it('409s a bounty that is already resolved', async () => {
+ session = USER;
+ queue.push([{ id: BID, user_id: USER.id, status: 'closed', reward_sol: '0.01' }]);
+ const res = mockRes();
+ await resolve(resolveReq({ submission_id: SID }), res);
+ expect(res.statusCode).toBe(409);
+ expect(res.json.error).toBe('already_closed');
+ });
+
+ it('writes the winner, the losers, and the closure in one transaction', async () => {
+ session = USER;
+ queue.push([{ id: BID, user_id: USER.id, status: 'open', reward_sol: '0.01' }]);
+ queue.push([{ id: SID }]);
+ queue.push([]);
+ queue.push([{ id: SID, status: 'accepted', tx_hash: 'sig' }]);
+ queue.push([]);
+ const res = mockRes();
+ await resolve(resolveReq({ submission_id: SID, tx_hash: ' sig ' }), res);
+ expect(res.statusCode).toBe(200);
+ expect(res.json.winner).toEqual({ id: SID, status: 'accepted', tx_hash: 'sig' });
+
+ const { sql } = await import('../api/_lib/db.js');
+ expect(sql.transaction).toHaveBeenCalledOnce();
+ expect(sql.transaction.mock.calls[0][0]).toHaveLength(3);
+ });
+});
diff --git a/tests/wallet-link-domain-binding.test.js b/tests/wallet-link-domain-binding.test.js
deleted file mode 100644
index 2ba830f16..000000000
--- a/tests/wallet-link-domain-binding.test.js
+++ /dev/null
@@ -1,168 +0,0 @@
-// The wallet-link handlers bind a signed message to this deployment's own
-// domain, with a localhost escape hatch for local development.
-//
-// That escape hatch used to be gated on VERCEL_ENV. Production runs on Cloud
-// Run, which never sets VERCEL_ENV, so the gate read "this is local dev" on the
-// live site and a link message signed for `localhost` satisfied the domain and
-// URI checks there. The gate is now anchored to the deployment's own
-// APP_ORIGIN, so it can only open where the deployment really is local. Same
-// fix as api/auth/siwe/[action].js and api/auth/siws/[action].js.
-
-import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
-import bs58 from 'bs58';
-
-process.env.JWT_SECRET ||= 'vitest-ephemeral-jwt-secret-00000000000000';
-process.env.PUBLIC_APP_ORIGIN = 'https://three.ws';
-
-vi.mock('../api/_lib/zauth.js', () => ({ instrument: () => {}, drain: async () => {} }));
-vi.mock('../api/_lib/sentry.js', () => ({ captureException: () => {} }));
-vi.mock('../api/_lib/audit.js', () => ({ logAudit: vi.fn() }));
-vi.mock('../api/_lib/csrf.js', () => ({ requireCsrf: vi.fn(async () => true) }));
-vi.mock('../api/_lib/db.js', () => ({ sql: vi.fn(async () => []) }));
-vi.mock('../api/_lib/rate-limit.js', () => ({
- limits: { walletLink: vi.fn(async () => ({ success: true })) },
- clientIp: () => '127.0.0.1',
-}));
-vi.mock('../api/_lib/auth.js', () => ({
- getSessionUser: vi.fn(async () => ({ id: 'user-1', email: '[email protected]' })),
-}));
-// The nonce store is the step right after the domain/URI checks: reaching it
-// proves the message cleared the domain binding.
-const consumeNonce = vi.fn(async () => null);
-vi.mock('../api/auth/wallets/_link-nonces.js', () => ({
- NONCE_TTL_SEC: 300,
- issueNonce: vi.fn(async () => 'nonce0000000000'),
- consumeNonce: (...args) => consumeNonce(...args),
-}));
-
-const { default: handler } = await import('../api/auth/wallets/[action].js');
-
-// Synthetic 32-byte key, base58-encoded the way a real Solana address is. The
-// parser decodes and length-checks it, so a hand-typed string will not do.
-const SOLANA_ADDRESS = bs58.encode(new Uint8Array(32).fill(7));
-
-function siwsMessage({ domain, uri }) {
- return [
- `${domain} wants you to sign in with your Solana account:`,
- SOLANA_ADDRESS,
- ``,
- `Link this wallet to three.ws account [email protected]`,
- ``,
- `URI: ${uri}`,
- `Version: 1`,
- `Chain ID: mainnet`,
- `Nonce: nonce0000000000`,
- `Issued At: ${new Date().toISOString()}`,
- `Expiration Time: ${new Date(Date.now() + 300_000).toISOString()}`,
- ].join('\n');
-}
-
-function makeReq(message) {
- return {
- method: 'POST',
- url: '/api/auth/wallets/link-solana',
- query: { action: 'link-solana' },
- headers: { 'content-type': 'application/json' },
- socket: { remoteAddress: '127.0.0.1' },
- body: JSON.stringify({ message, signature: 'c2lnbmF0dXJl' }),
- };
-}
-function makeRes() {
- const r = { statusCode: 200, _h: {}, _b: null };
- r.setHeader = (k, v) => {
- r._h[k] = v;
- };
- r.getHeader = (k) => r._h[k];
- r.end = (b) => {
- r._b = b;
- };
- Object.defineProperty(r, 'json', { value: () => JSON.parse(r._b) });
- return r;
-}
-
-const originalNodeEnv = process.env.NODE_ENV;
-const originalAppOrigin = process.env.PUBLIC_APP_ORIGIN;
-
-beforeEach(() => {
- consumeNonce.mockClear();
-});
-afterEach(() => {
- process.env.NODE_ENV = originalNodeEnv;
- process.env.PUBLIC_APP_ORIGIN = originalAppOrigin;
- delete process.env.VERCEL_ENV;
-});
-
-describe('POST /api/auth/wallets/link-solana: domain binding', () => {
- it('rejects a localhost-signed message on a production deployment', async () => {
- process.env.NODE_ENV = 'production';
- process.env.PUBLIC_APP_ORIGIN = 'https://three.ws';
-
- const res = makeRes();
- await handler(makeReq(siwsMessage({ domain: 'localhost:3000', uri: 'http://localhost:3000' })), res);
-
- expect(res.statusCode).toBe(400);
- expect(res.json().error).toBe('invalid_domain');
- expect(consumeNonce).not.toHaveBeenCalled();
- });
-
- it('rejects a localhost-signed message on a non-production deployment served from the real origin', async () => {
- // Preview and staging deployments are not production, but they are not
- // localhost either: the escape hatch must stay shut for them.
- delete process.env.NODE_ENV;
- process.env.PUBLIC_APP_ORIGIN = 'https://three.ws';
-
- const res = makeRes();
- await handler(makeReq(siwsMessage({ domain: 'localhost:3000', uri: 'http://localhost:3000' })), res);
-
- expect(res.statusCode).toBe(400);
- expect(res.json().error).toBe('invalid_domain');
- expect(consumeNonce).not.toHaveBeenCalled();
- });
-
- it('accepts a localhost-signed message when the deployment itself is localhost', async () => {
- delete process.env.NODE_ENV;
- process.env.PUBLIC_APP_ORIGIN = 'http://localhost:3000';
-
- const res = makeRes();
- await handler(makeReq(siwsMessage({ domain: 'localhost:3000', uri: 'http://localhost:3000' })), res);
-
- // Past the domain and URI checks, into the nonce step.
- expect(consumeNonce).toHaveBeenCalledWith('nonce0000000000', 'user-1');
- expect(res.json().error).toBe('invalid_nonce');
- });
-
- it('always accepts a message signed for the deployment origin', async () => {
- process.env.NODE_ENV = 'production';
- process.env.PUBLIC_APP_ORIGIN = 'https://three.ws';
-
- const res = makeRes();
- await handler(makeReq(siwsMessage({ domain: 'three.ws', uri: 'https://three.ws' })), res);
-
- expect(consumeNonce).toHaveBeenCalledWith('nonce0000000000', 'user-1');
- expect(res.json().error).toBe('invalid_nonce');
- });
-
- it('rejects a foreign domain outright', async () => {
- process.env.NODE_ENV = 'production';
- process.env.PUBLIC_APP_ORIGIN = 'https://three.ws';
-
- const res = makeRes();
- await handler(makeReq(siwsMessage({ domain: 'evil.example', uri: 'https://evil.example' })), res);
-
- expect(res.statusCode).toBe(400);
- expect(res.json().error).toBe('invalid_domain');
- expect(consumeNonce).not.toHaveBeenCalled();
- });
-
- it('rejects a URI whose origin is not the deployment origin', async () => {
- process.env.NODE_ENV = 'production';
- process.env.PUBLIC_APP_ORIGIN = 'https://three.ws';
-
- const res = makeRes();
- await handler(makeReq(siwsMessage({ domain: 'three.ws', uri: 'https://evil.example/callback' })), res);
-
- expect(res.statusCode).toBe(400);
- expect(res.json().error).toBe('invalid_uri');
- expect(consumeNonce).not.toHaveBeenCalled();
- });
-});
diff --git a/tests/wallet-link-nonces.test.js b/tests/wallet-link-nonces.test.js
deleted file mode 100644
index 9d9e222d1..000000000
--- a/tests/wallet-link-nonces.test.js
+++ /dev/null
@@ -1,134 +0,0 @@
-// Coverage for the wallet-link nonce store (api/auth/wallets/_link-nonces.js),
-// the single-use gate behind /api/auth/wallets (SIWE link) and
-// /api/auth/wallets/link-solana (SIWS link).
-//
-// Both backends matter and behave differently at the seams: Upstash Redis
-// (production, atomic GETDEL so two instances can't both burn one nonce) and
-// the in-memory Map fallback (local dev / tests, where Redis is unconfigured).
-// Each is exercised here on its success path and its failure paths: replay,
-// wrong user, unknown nonce, non-string input.
-
-import { describe, it, expect, vi, beforeEach } from 'vitest';
-
-process.env.JWT_SECRET ||= 'vitest-ephemeral-jwt-secret-00000000000000';
-
-// Minimal in-process stand-in for the two Upstash commands the store uses.
-// `set` honors the { ex } TTL argument the module passes; `getdel` is
-// read-and-delete in one step, which is the property the module relies on.
-function makeFakeRedis() {
- const store = new Map();
- return {
- store,
- async set(key, value, opts) {
- store.set(key, { value: String(value), ex: opts?.ex ?? null });
- return 'OK';
- },
- async getdel(key) {
- const hit = store.get(key);
- if (!hit) return null;
- store.delete(key);
- return hit.value;
- },
- };
-}
-
-let redisImpl = null;
-vi.mock('../api/_lib/redis.js', () => ({ getRedis: () => redisImpl }));
-
-const { issueNonce, consumeNonce, NONCE_TTL_SEC } = await import(
- '../api/auth/wallets/_link-nonces.js'
-);
-
-beforeEach(() => {
- redisImpl = null;
-});
-
-describe('_link-nonces: in-memory fallback (Redis unconfigured)', () => {
- it('issues an opaque alphanumeric nonce and consumes it once for its owner', async () => {
- const nonce = await issueNonce('user-1');
- expect(nonce).toMatch(/^[A-Za-z0-9]{16}$/);
-
- expect(await consumeNonce(nonce, 'user-1')).toEqual({
- userId: 'user-1',
- issuedAt: expect.any(Number),
- });
- });
-
- it('refuses a replay of an already-consumed nonce', async () => {
- const nonce = await issueNonce('user-1');
- expect(await consumeNonce(nonce, 'user-1')).not.toBeNull();
- expect(await consumeNonce(nonce, 'user-1')).toBeNull();
- });
-
- it('refuses a nonce presented by a different user', async () => {
- const nonce = await issueNonce('user-1');
- expect(await consumeNonce(nonce, 'user-2')).toBeNull();
- // The rightful owner can still use it.
- expect(await consumeNonce(nonce, 'user-1')).not.toBeNull();
- });
-
- it('matches a numeric user id against its string form', async () => {
- const nonce = await issueNonce(42);
- expect(await consumeNonce(nonce, '42')).toEqual({
- userId: '42',
- issuedAt: expect.any(Number),
- });
- });
-
- it('returns null for an unknown nonce and for non-string input', async () => {
- expect(await consumeNonce('nonexistent-nonce', 'user-1')).toBeNull();
- expect(await consumeNonce('', 'user-1')).toBeNull();
- expect(await consumeNonce(null, 'user-1')).toBeNull();
- expect(await consumeNonce(undefined, 'user-1')).toBeNull();
- expect(await consumeNonce({ nonce: 'x' }, 'user-1')).toBeNull();
- });
-
- it('issues a distinct nonce every time', async () => {
- const seen = new Set();
- for (let i = 0; i < 50; i++) seen.add(await issueNonce('user-1'));
- expect(seen.size).toBe(50);
- });
-});
-
-describe('_link-nonces: Redis backend', () => {
- it('stores the owner under a namespaced key with the module TTL', async () => {
- const r = makeFakeRedis();
- redisImpl = r;
-
- const nonce = await issueNonce('user-1');
- expect(r.store.get(`wallet:link:nonce:${nonce}`)).toEqual({
- value: 'user-1',
- ex: NONCE_TTL_SEC,
- });
- expect(NONCE_TTL_SEC).toBe(300);
- });
-
- it('consumes once and burns the key so a replay finds nothing', async () => {
- const r = makeFakeRedis();
- redisImpl = r;
-
- const nonce = await issueNonce('user-1');
- expect(await consumeNonce(nonce, 'user-1')).toEqual({ userId: 'user-1' });
- expect(r.store.has(`wallet:link:nonce:${nonce}`)).toBe(false);
- expect(await consumeNonce(nonce, 'user-1')).toBeNull();
- });
-
- it('refuses a nonce issued to a different user', async () => {
- redisImpl = makeFakeRedis();
- const nonce = await issueNonce('user-1');
- expect(await consumeNonce(nonce, 'user-2')).toBeNull();
- });
-
- it('returns null for an unknown nonce', async () => {
- redisImpl = makeFakeRedis();
- expect(await consumeNonce('never-issued', 'user-1')).toBeNull();
- });
-
- it('does not fall back to the in-memory map for a Redis-issued nonce', async () => {
- redisImpl = makeFakeRedis();
- const viaRedis = await issueNonce('user-1');
-
- redisImpl = null;
- expect(await consumeNonce(viaRedis, 'user-1')).toBeNull();
- });
-});
diff --git a/tests/wallet-unlink-guards.test.js b/tests/wallet-unlink-guards.test.js
deleted file mode 100644
index 52b93dcb0..000000000
--- a/tests/wallet-unlink-guards.test.js
+++ /dev/null
@@ -1,178 +0,0 @@
-// Regression guards for DELETE /api/auth/wallets/<address>.
-//
-// Two defects found in the 2026-08-10 auth audit, both reproduced live against
-// a real password-less SIWS account before the fix:
-//
-// 1. The last-wallet guard never fired. Postgres `count(*)` is a bigint and
-// the Neon driver returns it as the STRING "1", so `walletCount === 1`
-// was always false and an account whose only credential is a wallet could
-// unlink it, removing its own way back in.
-// 2. Unlinking the primary wallet left the account with no primary at all.
-// Royalty payouts (api/_lib/royalty.js), agent-wallet resolution
-// (api/_lib/agent-wallet.js) and x402 skill calls (api/x402/skill-call.js)
-// all select the payout address by `is_primary = true`, so the account
-// silently lost its payout target.
-
-import { describe, it, expect, vi, beforeEach } from 'vitest';
-
-process.env.APP_ORIGIN = 'https://three.ws';
-process.env.JWT_SECRET ||= 'vitest-ephemeral-jwt-secret-00000000000000';
-
-vi.mock('../api/_lib/zauth.js', () => ({ instrument: () => {}, drain: async () => {} }));
-vi.mock('../api/_lib/sentry.js', () => ({ captureException: () => {} }));
-vi.mock('../api/_lib/audit.js', () => ({ logAudit: vi.fn() }));
-vi.mock('../api/_lib/csrf.js', () => ({ requireCsrf: vi.fn(async () => true) }));
-vi.mock('../api/_lib/rate-limit.js', () => ({
- limits: { walletLink: vi.fn(async () => ({ success: true })) },
- clientIp: () => '127.0.0.1',
-}));
-vi.mock('../api/_lib/auth.js', () => ({
- getSessionUser: vi.fn(async () => ({ id: 'user-1', email: '[email protected]' })),
-}));
-
-// The fixture models user_wallets for one account. Queries are matched on the
-// distinctive text of each statement the handler issues, and `count(*)` is
-// returned in the driver's real shape (a string) so the coercion bug cannot
-// come back unnoticed.
-let wallets = [];
-const sqlMock = vi.fn(async (strings, ...values) => {
- const text = Array.isArray(strings) ? strings.join(' ') : String(strings);
-
- if (text.includes('select id, address, is_primary from user_wallets')) {
- const candidates = values[1] || [];
- const hit = wallets.find((w) => candidates.includes(w.address));
- return hit ? [{ id: hit.id, address: hit.address, is_primary: hit.is_primary }] : [];
- }
- if (text.includes('select count(*) as n from user_wallets')) {
- return [{ n: String(wallets.length) }];
- }
- if (text.includes('select password_hash from users')) {
- return [{ password_hash: passwordHash }];
- }
- if (text.includes('delete from user_wallets')) {
- wallets = wallets.filter((w) => w.id !== values[0]);
- return [];
- }
- if (text.includes('update user_wallets set is_primary = true')) {
- const oldest = [...wallets].sort((a, b) => a.created_at - b.created_at)[0];
- if (!oldest) return [];
- oldest.is_primary = true;
- return [{ address: oldest.address }];
- }
- return [];
-});
-vi.mock('../api/_lib/db.js', () => ({ sql: (strings, ...values) => sqlMock(strings, ...values) }));
-
-let passwordHash = null;
-
-const { default: handler } = await import('../api/auth/wallets/[action].js');
-
-function makeReq(address) {
- return {
- method: 'DELETE',
- url: `/api/auth/wallets/${address}`,
- query: { action: address },
- headers: { 'x-csrf-token': 'csrf-token' },
- socket: { remoteAddress: '127.0.0.1' },
- };
-}
-function makeRes() {
- const r = { statusCode: 200, _h: {}, _b: null };
- r.setHeader = (k, v) => {
- r._h[k] = v;
- };
- r.getHeader = (k) => r._h[k];
- r.end = (b) => {
- r._b = b;
- };
- Object.defineProperty(r, 'json', { value: () => JSON.parse(r._b) });
- return r;
-}
-
-beforeEach(() => {
- sqlMock.mockClear();
- passwordHash = null;
- wallets = [
- { id: 'w-a', address: 'AaaaSolanaAddressAaaa', is_primary: true, created_at: 1 },
- { id: 'w-b', address: 'BbbbSolanaAddressBbbb', is_primary: false, created_at: 2 },
- ];
-});
-
-describe('DELETE /api/auth/wallets/<address>: last-wallet guard', () => {
- it('refuses to remove the only wallet of an account with no password', async () => {
- wallets = [wallets[0]];
- const res = makeRes();
- await handler(makeReq('AaaaSolanaAddressAaaa'), res);
-
- expect(res.statusCode).toBe(400);
- expect(res.json().error).toBe('cannot_remove_last_wallet');
- expect(wallets).toHaveLength(1);
- });
-
- it('allows removing the only wallet when the account has a password', async () => {
- wallets = [wallets[0]];
- passwordHash = '$argon2id$v=19$m=65536,t=3,p=4$fake-hash-for-this-fixture';
- const res = makeRes();
- await handler(makeReq('AaaaSolanaAddressAaaa'), res);
-
- expect(res.statusCode).toBe(200);
- expect(res.json().removed).toBe(true);
- expect(wallets).toHaveLength(0);
- });
-
- it('allows removing a wallet while others remain', async () => {
- const res = makeRes();
- await handler(makeReq('BbbbSolanaAddressBbbb'), res);
-
- expect(res.statusCode).toBe(200);
- expect(wallets.map((w) => w.id)).toEqual(['w-a']);
- });
-
- it('404s an address the caller does not own', async () => {
- const res = makeRes();
- await handler(makeReq('ZzzzNotYourAddressZzzz'), res);
-
- expect(res.statusCode).toBe(404);
- expect(res.json().error).toBe('not_found');
- });
-});
-
-describe('DELETE /api/auth/wallets/<address>: primary succession', () => {
- it('promotes the oldest survivor when the primary wallet is removed', async () => {
- wallets[0].is_primary = false;
- wallets[1].is_primary = true;
-
- const res = makeRes();
- await handler(makeReq('BbbbSolanaAddressBbbb'), res);
-
- expect(res.statusCode).toBe(200);
- expect(res.json().primary).toBe('AaaaSolanaAddressAaaa');
- expect(wallets.filter((w) => w.is_primary).map((w) => w.address)).toEqual([
- 'AaaaSolanaAddressAaaa',
- ]);
- });
-
- it('leaves the primary alone when a non-primary wallet is removed', async () => {
- const res = makeRes();
- await handler(makeReq('BbbbSolanaAddressBbbb'), res);
-
- expect(res.json().primary).toBeNull();
- expect(wallets.filter((w) => w.is_primary).map((w) => w.address)).toEqual([
- 'AaaaSolanaAddressAaaa',
- ]);
- });
-
- it('does not attempt a promotion when the removed wallet was the last one', async () => {
- wallets = [wallets[0]];
- passwordHash = '$argon2id$v=19$m=65536,t=3,p=4$fake-hash-for-this-fixture';
- const res = makeRes();
- await handler(makeReq('AaaaSolanaAddressAaaa'), res);
-
- expect(res.json().primary).toBeNull();
- expect(
- sqlMock.mock.calls.some((c) =>
- (Array.isArray(c[0]) ? c[0].join(' ') : '').includes('set is_primary = true'),
- ),
- ).toBe(false);
- });
-});