cred402/api/v1/router.ts
caelum0x 086381d507 feat(gateway): make rate limiting org-scoped and plan-tiered
Rate limiting was per-API-key, so an org's `plan` field was decorative — a
free-plan org that minted 5 teammate keys got 5x the effective request
budget of a single-key free org. Org-scoped keys now share ONE rate-limit
bucket per org (`org:<id>`), sized by plan (free=120, pro=1000,
enterprise=10000 per window); orgless credentials (platform admin key,
anonymous dev identities) keep the prior per-identity behavior unchanged.

Adds GET /v1/orgs/usage (bucket status + total request count across an
org's keys) and a shared-bucket meter in the Orgs self-service console
panel.

Verified against a running dev server: 130 concurrent requests on a
free-plan org's owner key yielded exactly 120 successes + 10 real 429s,
and the org's teammate key immediately inherited the same depleted
remaining count (proving the bucket is shared, not per-key). A parallel
enterprise-plan org was unaffected. tsc + frontend build clean, 450/450
existing tests unchanged.
2026-10-24 00:40:11 +03:00

743 lines
39 KiB
TypeScript

import type { IncomingMessage, ServerResponse } from "node:http";
import type { ServerState } from "../state.js";
import type { AutomationDef } from "../../lib/flare/automations.js";
import {
Gateway,
ok,
fail,
toApiError,
ApiError,
RateLimitError,
parse,
v,
type Scope,
type AuthContext,
} from "../../lib/gateway/index.js";
import { casperLiveBridge } from "../../lib/casper/live_bridge.js";
/**
* Cred402 public REST API v1 (p2 §7.1).
*
* The production gateway surface: every route runs auth (scoped API keys) →
* rate limiting → body validation → idempotency (mutations) → handler →
* consistent {@link ok}/{@link fail} envelope, with a request id and structured
* access log. This is the externally-versioned API; the console keeps using the
* unversioned `/api/*` routes.
*/
export class V1Router {
constructor(
private readonly gateway: Gateway,
private readonly state: ServerState,
) {}
/** Returns true if it handled the request. */
async handle(req: IncomingMessage, res: ServerResponse, url: URL): Promise<boolean> {
const path = url.pathname;
if (!path.startsWith("/v1/") && path !== "/v1") return false;
const requestId = this.gateway.newRequestId();
const clientIp = (req.socket.remoteAddress ?? "unknown").replace(/^::ffff:/, "");
const method = req.method ?? "GET";
const routeLabel = `${method} /${path.split("/").filter(Boolean).slice(0, 2).join("/")}`;
const apiKey = extractApiKey(req);
const log = this.gateway.log.child({ request_id: requestId, method, path, ip: clientIp });
const started = Date.now();
try {
const route = this.match(method, path);
if (!route) throw new ApiError(404, "not_found", `no route for ${method} ${path}`);
const auth = this.gateway.authenticate(apiKey, clientIp, route.scope);
// Org-scoped keys share one bucket per org, sized by plan — see
// `rateLimitKeyFor` — so an org's effective limit doesn't multiply
// with its teammate-key count.
const rlKey = this.gateway.rateLimitKeyFor(auth);
const rl = this.gateway.enforceRateLimit(rlKey.identity, rlKey.capacity);
const rlHeaders = { "X-RateLimit-Limit": String(rl.limit), "X-RateLimit-Remaining": String(rl.remaining) };
const body = method === "POST" ? await readJson(req) : {};
// Idempotency for mutations carrying an Idempotency-Key header.
const idemKey = header(req, "idempotency-key");
if (method === "POST" && idemKey) {
const fp = this.gateway.fingerprint(body);
const hit = this.gateway.idempotency.get(idemKey, fp);
if (hit) {
log.info("idempotent replay", { status: hit.status, key_id: auth.key?.id });
return send(res, hit.status, hit.body, requestId, rlHeaders);
}
const result = await route.run({ params: route.params, body, url, auth });
this.gateway.idempotency.put(idemKey, fp, 200, ok(result, requestId));
log.info("ok", { status: 200, key_id: auth.key?.id, ms: Date.now() - started });
this.gateway.recordHttp(routeLabel, 200);
return send(res, 200, ok(result, requestId), requestId, rlHeaders);
}
const result = await route.run({ params: route.params, body, url, auth });
log.info("ok", { status: 200, key_id: auth.key?.id, ms: Date.now() - started });
this.gateway.recordHttp(routeLabel, 200);
return send(res, 200, ok(result, requestId), requestId, rlHeaders);
} catch (err) {
const apiErr = toApiError(err);
if (apiErr.status >= 500) log.error("request failed", { status: apiErr.status, error: apiErr.message });
else log.warn("request rejected", { status: apiErr.status, code: apiErr.code });
this.gateway.recordHttp(routeLabel, apiErr.status);
const headers: Record<string, string> = {};
if (apiErr instanceof RateLimitError) headers["Retry-After"] = String(Math.ceil(apiErr.retryAfterMs / 1000));
return send(res, apiErr.status, fail(apiErr.code, apiErr.message, requestId), requestId, headers);
}
}
// -- routing -------------------------------------------------------------
private match(
method: string,
path: string,
): { scope: Scope; params: Record<string, string>; run: (ctx: Ctx) => unknown | Promise<unknown> } | undefined {
const s = this.state;
const seg = path.split("/").filter(Boolean); // ["v1", ...]
const R = (
m: string,
pattern: string,
scope: Scope,
run: (ctx: Ctx) => unknown | Promise<unknown>,
) => {
if (method !== m) return undefined;
const pp = pattern.split("/").filter(Boolean);
if (pp.length !== seg.length) return undefined;
const params: Record<string, string> = {};
for (let i = 0; i < pp.length; i++) {
if (pp[i]!.startsWith(":")) params[pp[i]!.slice(1)] = decodeURIComponent(seg[i]!);
else if (pp[i] !== seg[i]) return undefined;
}
return { scope, params, run };
};
return (
R("GET", "v1/health", "read", () => ({ ok: true, env: this.gateway.config.env, policy: s.ledger.policy.version() })) ??
R("GET", "v1/config", "read", () => s.protocolConfig()) ??
// On-chain deployment manifest: real Casper Testnet contracts + install
// deploy transactions, each with a cspr.live link (observability, p2 §7.1).
R("GET", "v1/chain", "read", () => s.chainManifest()) ??
// Live write-path status (p8): is a funded operator key configured, is the
// node reachable, and the recent register/stake/score/deposit mirror log.
R("GET", "v1/casper/live", "read", () => s.casperLiveStatus()) ??
R("POST", "v1/auth/wallet/challenge", "read", ({ body }) => {
const b = parse(v.object({ account: v.string({ min: 66, max: 66 }) }), body);
return s.walletChallenge(b.account);
}) ??
R("POST", "v1/auth/wallet/verify", "read", ({ body }) => {
const b = parse(v.object({ nonce: v.string({ min: 8 }), signature: v.string({ min: 8 }) }), body);
return s.walletVerify(b.nonce, b.signature);
}) ??
R("GET", "v1/auth/wallet/agents", "read", ({ url }) => {
const token = url.searchParams.get("token") ?? "";
if (!token) throw new ApiError(400, "bad_request", "token query parameter required");
return s.walletAgents(token);
}) ??
R("GET", "v1/agents", "read", ({ url }) => {
let list = s.ledger.agents.list();
const svc = url.searchParams.get("service_type");
if (svc) list = list.filter((a) => a.service_type === svc);
const minRep = url.searchParams.get("min_reputation");
if (minRep) list = list.filter((a) => a.reputation_score >= Number(minRep));
return paginate(list, url);
}) ??
R("GET", "v1/agents/compare", "read", ({ url }) => {
const a = url.searchParams.get("a");
const b = url.searchParams.get("b");
if (!a || !b) throw new ApiError(400, "bad_request", "both ?a= and ?b= agent ids are required");
return s.compareAgents(a, b);
}) ??
R("GET", "v1/agents/:id", "read", ({ params }) => required(s.ledger.agents.get(params.id!), "agent")) ??
R("GET", "v1/agents/:id/passport", "read", ({ params }) => required(s.ledger.buildPassport(params.id!), "agent")) ??
R("GET", "v1/agents/:id/credit-line", "read", ({ params }) => required(s.ledger.pool.get(params.id!), "credit line")) ??
R("GET", "v1/agents/:id/safe-draw", "read", ({ params, url }) => s.safeDraw(params.id!, numParam(url, "target_hf_bps"))) ??
R("GET", "v1/agents/:id/credit-cost", "read", ({ params, url }) => {
const draw = numParam(url, "draw_cspr");
if (draw === undefined) throw new ApiError(400, "bad_request", "draw_cspr query parameter required");
return s.creditCost(params.id!, draw);
}) ??
R("GET", "v1/agents/:id/credit-explain", "read", ({ params }) => s.creditExplain(params.id!)) ??
R("GET", "v1/compliance/agents/:id", "read", ({ params }) => s.complianceScreen(params.id!)) ??
R("GET", "v1/compliance/report", "read", () => s.complianceReport()) ??
R("GET", "v1/agents/:id/profile", "read", ({ params }) => s.agentProfile(params.id!)) ??
// Convenience alias (STRATEGY-2026-10-23.md §2, "turn competitors into
// distribution channels"): the SAME credit-score logic the chain-specific
// x402-PAID routes serve (api/{algorand,qie,near}_x402_routes.ts — note
// "/v1/x402/credit-score/:id" without a chain segment is ALREADY the
// Algorand paid route, regex-matched in server.ts ahead of this router;
// this alias deliberately lives at a different path so it never shadows
// or is shadowed by that), as a plain scoped/rate-limited v1 GET for
// integrators who already bill their own callers over Skyfire/
// Nevermined/Coinbase x402 and just want one documented call to
// underwrite with — no second x402 paywall to clear.
R("GET", "v1/credit-score/:agentId", "read", ({ params }) => {
const report = s.x402CreditScore(params.agentId!);
if ("error" in report) throw new ApiError(404, "not_found", report.error ?? `unknown agent: ${params.agentId}`);
return report;
}) ??
R("POST", "v1/agents/:id/capabilities", "write", ({ params, body }) => {
const b = parse(v.object({ capabilities: v.array(v.string(), { max: 32 }), spending_limit_cspr: v.optional(v.number({ min: 0 })) }), body);
return s.setCapabilities(params.id!, b.capabilities, b.spending_limit_cspr);
}) ??
R("GET", "v1/agents/:id/credit-report", "read", ({ params }) => s.creditReport(params.id!)) ??
R("GET", "v1/agents/:id/tier", "read", ({ params }) => s.tier(params.id!)) ??
R("GET", "v1/tiers", "read", () => s.tiers()) ??
R("GET", "v1/credit/portfolio", "read", () => s.portfolioReport()) ??
R("GET", "v1/risk/alerts", "read", () => s.riskAlerts()) ??
R("GET", "v1/credit/yield-projection", "read", () => s.yieldProjection()) ??
// Credit-as-a-service oracle — "Cred402 Inside" (p3)
R("GET", "v1/credit/check/:id", "read", ({ params }) => s.creditCheck(params.id!)) ??
R("POST", "v1/credit/check", "read", ({ body }) => {
const b = parse(v.object({ agent_ids: v.array(v.string(), { max: 200 }) }), body);
return s.creditChecks(b.agent_ids);
}) ??
// ML risk-engine v2 score (p7)
R("GET", "v1/agents/:id/risk-score", "read", ({ params }) => s.riskScoreV2(params.id!)) ??
// Public credit-data commons (p6 data moat)
R("GET", "v1/credit/data-commons", "read", () => s.dataCommons()) ??
// Omnichain exposure reconciliation (p5)
R("GET", "v1/credit/exposure", "read", () => s.exposureReconciliation()) ??
R("GET", "v1/agents/:id/exposure", "read", ({ params }) => s.agentExposure(params.id!)) ??
// Service-vertical underwriting profiles (p10)
R("GET", "v1/verticals", "read", () => s.verticalProfiles()) ??
R("GET", "v1/verticals/:vertical", "read", ({ params }) => required(s.verticals.get(params.vertical!), "vertical")) ??
// ── Flare satellite (interoperable FXRP credit) + KeeperHub execution ──
R("GET", "v1/flare", "read", () => s.flareInfo()) ??
R("GET", "v1/flare/price", "read", () => s.flareXrpPrice()) ??
R("POST", "v1/flare/draw", "write", ({ body }) => {
const b = parse(v.object({ agent_id: v.string({ min: 2, max: 64 }), amount_fxrp: v.number({ min: 0 }) }), body);
return s.flareDraw(b.agent_id, b.amount_fxrp);
}) ??
R("POST", "v1/flare/repay", "write", ({ body }) => {
const b = parse(v.object({ agent_id: v.string({ min: 2, max: 64 }), amount_fxrp: v.number({ min: 0 }) }), body);
return s.flareRepay(b.agent_id, b.amount_fxrp);
}) ??
// KeeperHub execution observability — reliability summary + full audit trail
R("GET", "v1/keeperhub/reliability", "read", () => s.keeperhubReliability()) ??
R("GET", "v1/keeperhub/audit", "read", ({ url }) => s.keeperhubAudit(url.searchParams.get("agent_id") ?? undefined)) ??
// Flare Confidential Compute credit score — attested, raw features stay private
R("GET", "v1/agents/:id/confidential-score", "read", ({ params }) => s.confidentialScore(params.id!)) ??
// FTSO position health + Autonomous Credit Keeper (check → execute via KeeperHub)
R("GET", "v1/agents/:id/position", "read", ({ params, url }) => s.flarePosition(params.id!, numParam(url, "price"))) ??
// FTSO-priced multi-asset collateral — expands borrowing power
R("GET", "v1/agents/:id/collateral", "read", ({ params }) => s.collateralValue(params.id!)) ??
R("POST", "v1/agents/:id/collateral", "write", ({ params, body }) => {
const b = parse(v.object({ symbol: v.string({ min: 2, max: 8 }), amount: v.number({ min: 0 }) }), body);
return s.depositCollateral(params.id!, b.symbol, b.amount);
}) ??
R("POST", "v1/agents/:id/collateral/withdraw", "write", ({ params, body }) => {
const b = parse(v.object({ symbol: v.string({ min: 2, max: 8 }), amount: v.number({ min: 0 }) }), body);
return s.withdrawCollateral(params.id!, b.symbol, b.amount);
}) ??
R("GET", "v1/keeper/evaluate/:id", "read", ({ params }) => s.keeperEvaluate(params.id!)) ??
R("POST", "v1/keeper/run", "write", ({ body }) => {
const b = parse(v.object({ agent_id: v.string({ min: 2, max: 64 }) }), body);
return s.keeperRun(b.agent_id);
}) ??
R("POST", "v1/keeper/run-fleet", "write", () => s.keeperRunFleet()) ??
// Credit Automations — declarative price/health/schedule credit rules
R("GET", "v1/automations", "read", ({ url }) => s.listAutomations(url.searchParams.get("agent_id") ?? undefined)) ??
R("POST", "v1/automations", "write", ({ body }) => {
const b = parse(
v.object({
agent_id: v.string({ min: 2, max: 64 }),
name: v.string({ min: 1, max: 64 }),
trigger: v.object({
kind: v.string({ min: 1, max: 32 }),
price: v.optional(v.number({ min: 0 })),
threshold: v.optional(v.number({ min: 0 })),
every_seconds: v.optional(v.number({ min: 1 })),
}),
action: v.object({
kind: v.string({ min: 1, max: 32 }),
target_hf: v.optional(v.number({ min: 0 })),
amount_fxrp: v.optional(v.number({ min: 0 })),
}),
cooldown_seconds: v.optional(v.number({ min: 0 })),
}),
body,
);
return s.createAutomation(b as unknown as AutomationDef);
}) ??
R("POST", "v1/automations/tick", "write", () => s.tickAutomations()) ??
R("POST", "v1/automations/:id/toggle", "write", ({ params, body }) => {
const b = parse(v.object({ enabled: v.boolean() }), body);
return s.toggleAutomation(params.id!, b.enabled);
}) ??
R("POST", "v1/automations/:id/remove", "write", ({ params }) => s.removeAutomation(params.id!)) ??
// x402 Credit-Service Marketplace discovery (buy at POST /x402/services/:id)
R("GET", "v1/services", "read", () => ({ services: s.listServices(), stats: s.serviceMarketStats() })) ??
R("GET", "v1/services/receipts", "read", () => s.marketplaceReceipts()) ??
// FAssets: mint FXRP from attested XRP, then collateralize
R("GET", "v1/agents/:id/fassets", "read", ({ params }) => s.fassetsStatus(params.id!)) ??
R("POST", "v1/fassets/mint", "write", ({ body }) => {
const b = parse(v.object({ agent_id: v.string({ min: 2, max: 64 }), xrp: v.number({ min: 0 }), collateralize: v.optional(v.boolean()) }), body);
return b.collateralize ? s.mintAndCollateralize(b.agent_id, b.xrp) : s.mintFxrp(b.agent_id, b.xrp);
}) ??
R("POST", "v1/fassets/redeem", "write", ({ body }) => {
const b = parse(v.object({ agent_id: v.string({ min: 2, max: 64 }), fxrp: v.number({ min: 0 }) }), body);
return s.redeemFxrp(b.agent_id, b.fxrp);
}) ??
// Autonomous scheduler (KeeperHub cron) — runs keeper + automations unattended
R("GET", "v1/scheduler", "read", () => s.schedulerStatus()) ??
R("POST", "v1/scheduler/tick", "write", () => s.schedulerTick()) ??
R("POST", "v1/scheduler/start", "write", ({ body }) => {
const b = parse(v.object({ interval_ms: v.optional(v.number({ min: 1000 })) }), body);
return s.schedulerStart(b.interval_ms);
}) ??
R("POST", "v1/scheduler/stop", "write", () => s.schedulerStop()) ??
R("GET", "v1/credit/lp-preview", "read", ({ url }) => {
const deposit = numParam(url, "deposit_cspr");
if (deposit === undefined) throw new ApiError(400, "bad_request", "deposit_cspr query parameter required");
return s.lpDepositPreview(deposit);
}) ??
R("GET", "v1/credit/offers", "read", ({ url }) => s.listCreditOffers(url.searchParams.get("agent_id") ?? undefined)) ??
R("POST", "v1/credit/offers", "write", ({ body }) => {
const b = parse(
v.object({
agent_id: v.string({ min: 2, max: 64 }),
ttl_seconds: v.optional(v.number({ min: 60 })),
term_seconds: v.optional(v.number({ min: 60 })),
}),
body,
);
return s.issueCreditOffer(b.agent_id, { ttl_seconds: b.ttl_seconds, term_seconds: b.term_seconds });
}) ??
R("POST", "v1/credit/offers/:id/accept", "write", ({ params }) => s.acceptCreditOffer(params.id!)) ??
R("POST", "v1/credit/offers/:id/decline", "write", ({ params }) => s.declineCreditOffer(params.id!)) ??
R("POST", "v1/credit/simulate", "read", ({ body }) => {
const b = parse(
v.object({
monthly_revenue_cspr: v.number({ min: 0 }),
stake_cspr: v.optional(v.number({ min: 0 })),
reputation: v.optional(v.number({ min: 0, max: 100 })),
accuracy: v.optional(v.number({ min: 0, max: 100 })),
dispute_rate: v.optional(v.number({ min: 0, max: 1 })),
jobs_completed: v.optional(v.number({ min: 0 })),
service_type: v.optional(v.string({ max: 64 })),
}),
body,
);
return s.simulateCredit(b);
}) ??
R("GET", "v1/analytics/categories", "read", () => s.categoryAnalytics()) ??
R("GET", "v1/analytics/reputation-movers", "read", ({ url }) => s.reputationMovers(numParam(url, "limit"))) ??
R("GET", "v1/analytics/disputes", "read", () => s.disputeStats()) ??
R("GET", "v1/analytics/x402", "read", () => s.x402Stats()) ??
R("GET", "v1/analytics/marketplace", "read", () => s.marketplaceStats()) ??
R("GET", "v1/discovery", "read", ({ url }) =>
s.discover({
service_type: url.searchParams.get("service_type") ?? undefined,
min_reputation: numParam(url, "min_reputation"),
min_score: numParam(url, "min_score"),
limit: numParam(url, "limit"),
}),
) ??
R("GET", "v1/attestations/graph", "read", () => s.attestationGraph()) ??
R("GET", "v1/agents/:id/attestations", "read", ({ params }) => s.attestationsFor(params.id!)) ??
R("GET", "v1/agents/:id/benchmark", "read", ({ params }) => s.peerBenchmark(params.id!)) ??
R("GET", "v1/agents/:id/history", "read", ({ params }) => s.creditHistory(params.id!)) ??
R("GET", "v1/agents/:id/readiness", "read", ({ params }) => s.onboardingScorecard(params.id!)) ??
R("GET", "v1/agents/:id/score-trend", "read", ({ params }) => s.scoreTrend(params.id!)) ??
R("GET", "v1/agents/:id/reputation-breakdown", "read", ({ params }) => s.reputationBreakdown(params.id!)) ??
R("GET", "v1/agents/:id/multichain", "read", ({ params }) => s.agentMultichain(params.id!)) ??
R("GET", "v1/agents/:id/health", "read", ({ params }) => s.agentHealth(params.id!)) ??
R("GET", "v1/agents/:id/similar", "read", ({ params, url }) => s.similarAgents(params.id!, numParam(url, "limit"))) ??
R("GET", "v1/agents/:id/dossier", "read", ({ params }) => s.agentDossier(params.id!)) ??
R("POST", "v1/attestations", "write", ({ body }) => {
const b = parse(v.object({ from: v.string({ min: 2 }), to: v.string({ min: 2 }), note: v.withDefault(v.string({ max: 200 }), "") }), body);
return s.attest(b.from, b.to, b.note);
}) ??
R("POST", "v1/agents", "write", async ({ body }) => {
const a = parse(
v.object({
agent_id: v.string({ min: 2, max: 64 }),
service_type: v.literalUnion(
"solar_output_verification",
"weather_risk",
"receivable_quality",
"risk_scoring",
"treasury_routing",
"monitoring",
),
agent_public_key: v.withDefault(v.string({ max: 130 }), "01"),
owner_public_key: v.withDefault(v.string({ max: 130 }), "01"),
}),
body,
);
s.ledger.agents.register_agent(a);
const passport = s.ledger.buildPassport(a.agent_id);
const casper_live = await casperLiveBridge().mirrorRegisterAgent({
agentId: a.agent_id,
serviceType: a.service_type,
agentPublicKeyHex: a.agent_public_key,
});
return { ...passport, casper_live };
}) ??
R("POST", "v1/agents/batch", "write", ({ body }) => {
const b = parse(
v.object({
agents: v.array(
v.object({
agent_id: v.string({ min: 2, max: 64 }),
service_type: v.literalUnion(
"solar_output_verification",
"weather_risk",
"receivable_quality",
"risk_scoring",
"treasury_routing",
"monitoring",
),
agent_public_key: v.withDefault(v.string({ max: 130 }), "01"),
owner_public_key: v.withDefault(v.string({ max: 130 }), "01"),
}),
{ max: 100 },
),
}),
body,
);
const results = b.agents.map((a) => {
try {
s.ledger.agents.register_agent(a);
return { agent_id: a.agent_id, ok: true };
} catch (err) {
return { agent_id: a.agent_id, ok: false, error: (err as Error).message };
}
});
return { registered: results.filter((r) => r.ok).length, failed: results.filter((r) => !r.ok).length, results };
}) ??
R("GET", "v1/receipts", "read", ({ url }) => {
let list = s.ledger.receipts.list();
const status = url.searchParams.get("status");
if (status) list = list.filter((r) => r.status === status);
const seller = url.searchParams.get("seller");
if (seller) list = list.filter((r) => r.seller_agent === seller);
return paginate(list, url);
}) ??
R("GET", "v1/x402/receipts/:id", "read", ({ params }) => required(s.ledger.receipts.get(params.id!), "receipt")) ??
R("GET", "v1/credit/pool", "read", () => ({ ...s.ledger.pool.poolState(), creditLines: s.ledger.pool.list() })) ??
R("POST", "v1/credit/deposit", "write", ({ body }) => {
const b = parse(v.object({ amount_cspr: v.number({ min: 0 }) }), body);
return s.mDeposit(b.amount_cspr);
}) ??
R("POST", "v1/credit/withdraw", "write", ({ body }) => {
const b = parse(v.object({ amount_cspr: v.number({ min: 0 }) }), body);
return s.mWithdraw(b.amount_cspr);
}) ??
R("GET", "v1/governance/proposals", "read", () => s.governanceProposals.list()) ??
R("POST", "v1/governance/proposals", "write", ({ body }) => {
const b = parse(
v.object({
title: v.string({ min: 3, max: 200 }),
param_key: v.string({ min: 2 }),
new_value: v.number(),
proposer: v.string({ min: 2 }),
}),
body,
);
return s.governanceProposals.create(b);
}) ??
R("POST", "v1/governance/proposals/:id/vote", "write", ({ params, body }) => {
const b = parse(v.object({ agent_id: v.string({ min: 2 }), support: v.boolean() }), body);
return s.governanceProposals.vote(params.id!, b.agent_id, b.support);
}) ??
R("POST", "v1/governance/proposals/:id/execute", "admin", ({ params }) => s.governanceProposals.execute(params.id!)) ??
R("POST", "v1/governance/proposals/:id/apply", "admin", ({ params }) => s.governanceProposals.apply(params.id!)) ??
R("GET", "v1/economics", "read", () => s.economicsView()) ??
R("GET", "v1/credit/lp", "read", () => s.lpView()) ??
R("GET", "v1/credit/health", "read", () => s.creditHealth()) ??
R("GET", "v1/credit/stress-test", "read", () => s.stressTest()) ??
R("POST", "v1/credit/lines/:id/freeze", "admin", ({ params, body }) => {
const b = parse(v.object({ reason: v.withDefault(v.string({ max: 200 }), "risk freeze") }), body);
return s.freezeLine(params.id!, b.reason);
}) ??
R("GET", "v1/marketplace", "read", () => s.marketplaceView()) ??
R("POST", "v1/marketplace/listings", "write", ({ body }) => {
const b = parse(
v.object({
agent_id: v.string({ min: 2 }),
category: v.string({ min: 3 }),
strategy: v.optional(v.literalUnion("fixed", "dynamic", "auction", "subscription", "reputation_tiered", "urgency", "data_cost_plus")),
base_price_cspr: v.number({ min: 0 }),
}),
body,
);
return s.createListing(b);
}) ??
R("POST", "v1/marketplace/purchase", "write", ({ body }) => {
const b = parse(v.object({ listing_id: v.string({ min: 1 }), buyer_agent: v.string({ min: 1 }) }), body);
return s.marketplacePurchase(b.listing_id, b.buyer_agent);
}) ??
R("GET", "v1/analytics", "read", () => s.analytics()) ??
R("GET", "v1/notifications", "read", () => s.notifications()) ??
R("GET", "v1/search", "read", ({ url }) => s.search(url.searchParams.get("q") ?? "")) ??
R("POST", "v1/credit/lines", "write", ({ body }) => {
const b = parse(v.object({ agent_id: v.string({ min: 2 }), term_days: v.optional(v.number({ int: true, min: 1, max: 365 })) }), body);
const { decision, line } = s.economy.credit.underwrite(b.agent_id, { term_days: b.term_days });
return { decision, line };
}) ??
R("POST", "v1/operators/fleet-overview", "read", ({ body }) => {
const b = parse(v.object({ agent_ids: v.array(v.string({ min: 2 }), { max: 200 }) }), body);
return s.fleetOverview(b.agent_ids);
}) ??
R("POST", "v1/credit/underwrite-batch", "write", ({ body }) => {
const b = parse(v.object({ agent_ids: v.array(v.string({ min: 2 }), { max: 100 }) }), body);
return b.agent_ids.map((id) => {
try {
const { decision, line } = s.economy.credit.underwrite(id);
return { agent_id: id, ok: true, credit_line: line.max_credit.toString(), credit_score: decision.credit_score };
} catch (err) {
return { agent_id: id, ok: false, error: (err as Error).message };
}
});
}) ??
R("POST", "v1/credit/review-all", "admin", () => s.reviewAllCreditLines()) ??
R("POST", "v1/credit/lines/:id/review", "write", ({ params }) => s.reviewCreditLine(params.id!)) ??
R("POST", "v1/credit/lines/:id/draw", "write", ({ params, body }) => {
const b = parse(v.object({ amount_cspr: v.number({ min: 0 }) }), body);
return s.economy.treasury.fundDraw(params.id!, b.amount_cspr);
}) ??
R("POST", "v1/credit/lines/:id/repay", "write", ({ params, body }) => {
const b = parse(v.object({ amount_cspr: v.number({ min: 0 }) }), body);
return s.economy.treasury.collectRepayment(params.id!, b.amount_cspr);
}) ??
R("POST", "v1/agents/:id/stake", "write", ({ params, body }) => {
const b = parse(v.object({ amount_cspr: v.number({ min: 0 }) }), body);
return s.mStake(params.id!, b.amount_cspr);
}) ??
R("POST", "v1/disputes", "write", ({ body }) => {
const b = parse(
v.object({
respondent_agent: v.string({ min: 2 }),
dispute_type: v.withDefault(v.literalUnion("bad_evidence", "fake_receipt", "non_delivery", "agent_default", "collusion"), "bad_evidence"),
receipt_id: v.optional(v.string()),
note: v.withDefault(v.string({ max: 500 }), "opened via v1 API"),
}),
body,
);
return s.ledger.disputes.open({
dispute_type: b.dispute_type,
complainant: "api.v1",
respondent_agent: b.respondent_agent,
receipt_id: b.receipt_id,
note: b.note,
evidence_hash: "0x" + "00".repeat(32),
});
}) ??
R("POST", "v1/admin/advance-clock", "admin", ({ body }) => {
const b = parse(v.object({ seconds: v.number({ min: 1, max: 31_536_000 }) }), body);
return s.advanceClock(b.seconds);
}) ??
R("POST", "v1/reputation/decay", "admin", ({ body }) => {
const b = parse(v.object({ assume_inactive_days: v.optional(v.number({ min: 0 })) }), body);
return s.applyDecay(b.assume_inactive_days);
}) ??
R("POST", "v1/insurance/claim", "write", ({ body }) => {
const b = parse(v.object({ claimant: v.string({ min: 1 }), amount_cspr: v.number({ min: 0 }), reason: v.withDefault(v.string({ max: 200 }), "insurance claim") }), body);
return s.mClaimInsurance(b.claimant, b.amount_cspr, b.reason);
}) ??
R("POST", "v1/disputes/:id/verdict", "write", ({ params, body }) => {
const b = parse(
v.object({
verdict: v.literalUnion("agent_wins", "agent_loses", "partial_fault", "inconclusive", "malicious_dispute"),
slash_cspr: v.withDefault(v.number({ min: 0 }), 0),
}),
body,
);
return s.mResolveDispute(params.id!, b.verdict, b.slash_cspr);
}) ??
R("GET", "v1/realfi", "read", () => s.realfiState()) ??
R("POST", "v1/realfi/operators", "write", ({ body }) => {
const b = parse(
v.object({
operator_id: v.string({ min: 2 }),
verification_level: v.withDefault(v.literalUnion("unverified", "email_verified", "business_verified", "regulated_entity"), "business_verified"),
jurisdiction: v.withDefault(v.string({ min: 2, max: 2 }), "US"),
verification_reference: v.string({ min: 1 }),
}),
body,
);
return s.realfi.verifyOperator(b);
}) ??
R("POST", "v1/realfi/fiat-receipts", "write", ({ body }) => {
const b = parse(
v.object({
seller_agent: v.string({ min: 2 }),
operator_id: v.string({ min: 2 }),
amount: v.decimalString(),
currency: v.withDefault(v.string({ min: 3, max: 3 }), "USD"),
service_type: v.withDefault(v.string(), "rwa.weather_risk"),
provider_event_id: v.string({ min: 1 }),
provider_receipt_id: v.string({ min: 1 }),
}),
body,
);
return s.realfi.recordFiatReceipt({ ...b, payer_type: "enterprise_customer", request_hash: "0xreq", result_hash: "0xres" });
}) ??
// -- admin -----------------------------------------------------------
R("GET", "v1/admin/api-keys", "admin", () => this.gateway.apiKeys.list()) ??
R("POST", "v1/admin/api-keys", "admin", ({ body }) => {
const b = parse(
v.object({ name: v.string({ min: 1, max: 64 }), scopes: v.array(v.literalUnion("read", "write", "admin"), { max: 3 }) }),
body,
);
return this.gateway.apiKeys.issue(b.name, b.scopes);
}) ??
// -- organizations (multi-tenant API-key scoping) --------------------
// Platform operator onboards a new paying integrator once with the
// admin key; from then on the org is fully self-service through its
// OWN org-scoped key (no further admin-key involvement) — the actual
// tenant-isolation boundary, since a key can only ever see, mint, or
// revoke credentials inside its own org_id.
R("POST", "v1/orgs", "admin", ({ body }) => {
const b = parse(
v.object({ name: v.string({ min: 1, max: 80 }), plan: v.withDefault(v.literalUnion("free", "pro", "enterprise"), "free") }),
body,
);
const org = this.gateway.orgs.create(b.name, b.plan);
const owner_key = this.gateway.apiKeys.issue(`${b.name} — owner`, ["read", "write"], org.id);
return { org, owner_key };
}) ??
R("GET", "v1/orgs", "admin", () => this.gateway.orgs.list()) ??
// Below this line: callers authenticate with their OWN org key, not the
// platform admin key. `auth.key?.org_id` is undefined for the platform
// bootstrap key (orgless by design) and for dev-mode requests that
// present no key at all — both are correctly refused here.
//
// IMPORTANT: these literal-segment GETs ("me", "keys") must stay ABOVE
// "v1/orgs/:id" below — the router matches path patterns in the order
// they're written (no longest-match/specificity ranking), so if the
// wildcard were listed first it would swallow "me"/"keys" as an org id.
R("GET", "v1/orgs/me", "read", ({ auth }) => {
const orgId = requireOrg(auth);
return { ...required(this.gateway.orgs.get(orgId), "organization"), keys: this.gateway.apiKeys.listByOrg(orgId) };
}) ??
R("GET", "v1/orgs/keys", "read", ({ auth }) => this.gateway.apiKeys.listByOrg(requireOrg(auth))) ??
// Usage + rate-limit status for the caller's own org — the billing-
// correctness view: one shared bucket per org (sized by plan), not
// one per key. Listed above the "me"/"keys" literal guard note below
// doesn't apply here (no wildcard collision) but kept alongside its
// sibling self-service GETs for readability.
R("GET", "v1/orgs/usage", "read", ({ auth }) => this.gateway.orgUsage(requireOrg(auth))) ??
R("POST", "v1/orgs/keys", "write", ({ body, auth }) => {
const orgId = requireOrg(auth);
const b = parse(
v.object({ name: v.string({ min: 1, max: 64 }), scopes: v.optional(v.array(v.literalUnion("read", "write"), { max: 2 })) }),
body,
);
const scopes: Array<"read" | "write"> = b.scopes ?? ["read"];
const callerScopes = auth.key!.scopes;
const escalation = scopes.filter((sc) => !callerScopes.includes(sc));
if (escalation.length) throw new ApiError(403, "forbidden", `cannot mint a key with scopes your own key lacks: ${escalation.join(", ")}`);
return this.gateway.apiKeys.issue(b.name, scopes, orgId);
}) ??
R("DELETE", "v1/orgs/keys/:id", "write", ({ params, auth }) => {
const orgId = requireOrg(auth);
const target = this.gateway.apiKeys.get(params.id!);
if (!target || target.org_id !== orgId) throw new ApiError(404, "not_found", "no key with that id in your organization");
return { revoked: this.gateway.apiKeys.revoke(params.id!) };
}) ??
// Platform-operator lookup of any org by id — admin scope, deliberately
// listed AFTER the literal "me"/"keys" GETs above (see note there).
R("GET", "v1/orgs/:id", "admin", ({ params }) => {
const org = required(this.gateway.orgs.get(params.id!), "organization");
return { ...org, keys: this.gateway.apiKeys.listByOrg(org.id) };
}) ??
R("GET", "v1/webhooks", "admin", () => this.gateway.webhooks.list()) ??
R("GET", "v1/webhooks/deliveries", "admin", ({ url }) => this.gateway.webhooks.deliveries(url.searchParams.get("subscription_id") ?? undefined)) ??
R("POST", "v1/webhooks", "admin", ({ body }) => {
const b = parse(v.object({ url: v.string({ min: 8 }), events: v.withDefault(v.array(v.string(), { max: 50 }), ["*"]), agent_filter: v.optional(v.string()) }), body);
return this.gateway.webhooks.subscribe(b.url, b.events, b.agent_filter);
}) ??
R("POST", "v1/webhooks/deliveries/:id/retry", "admin", ({ params }) => this.gateway.webhooks.redeliver(params.id!)) ??
R("POST", "v1/webhooks/:id/enable", "admin", ({ params }) => ({ enabled: this.gateway.webhooks.enable(params.id!) })) ??
R("DELETE", "v1/webhooks/:id", "admin", ({ params }) => ({ disabled: this.gateway.webhooks.unsubscribe(params.id!) })) ??
undefined
);
}
}
interface Ctx {
params: Record<string, string>;
body: unknown;
url: URL;
auth: AuthContext;
}
function required<T>(value: T | undefined, what: string): T {
if (value === undefined || value === null) throw new ApiError(404, "not_found", `${what} not found`);
return value;
}
/** The org id of the calling key, or a 403 — the gate for every `/v1/orgs/*` self-service route. */
function requireOrg(auth: AuthContext): string {
const orgId = auth.key?.org_id;
if (!orgId) throw new ApiError(403, "forbidden", "this route requires an org-scoped API key (not the platform admin key)");
return orgId;
}
/**
* Apply ?limit=&offset= by slicing — returns the same ARRAY shape clients/SDKs
* already expect (no envelope change). Default limit is generous so unparam'd
* calls return everything; pass limit/offset to page.
*/
function paginate<T>(items: T[], url: URL): T[] {
const limit = clampInt(url.searchParams.get("limit"), 500, 1, 1000);
const offset = clampInt(url.searchParams.get("offset"), 0, 0, Number.MAX_SAFE_INTEGER);
return items.slice(offset, offset + limit);
}
/** Parse an optional numeric query param; returns undefined when absent/invalid. */
function numParam(url: URL, key: string): number | undefined {
const raw = url.searchParams.get(key);
if (raw === null) return undefined;
const n = Number(raw);
return Number.isFinite(n) ? n : undefined;
}
function clampInt(raw: string | null, fallback: number, min: number, max: number): number {
if (raw === null) return fallback;
const n = Number(raw);
if (!Number.isFinite(n)) return fallback;
return Math.max(min, Math.min(max, Math.trunc(n)));
}
function header(req: IncomingMessage, name: string): string | undefined {
const h = req.headers[name];
return Array.isArray(h) ? h[0] : h;
}
function extractApiKey(req: IncomingMessage): string | undefined {
const auth = header(req, "authorization");
if (auth?.startsWith("Bearer ")) return auth.slice(7);
return header(req, "x-api-key");
}
async function readJson(req: IncomingMessage): Promise<unknown> {
const chunks: Buffer[] = [];
for await (const c of req) chunks.push(c as Buffer);
const raw = Buffer.concat(chunks).toString("utf8");
if (!raw) return {};
try {
return JSON.parse(raw);
} catch {
throw new ApiError(400, "invalid_json", "request body is not valid JSON");
}
}
function send(res: ServerResponse, status: number, body: unknown, requestId: string, extra: Record<string, string> = {}): true {
const payload = JSON.stringify(body, (_k, v2) => (typeof v2 === "bigint" ? v2.toString() : v2));
res.writeHead(status, {
"Content-Type": "application/json",
"X-Request-Id": requestId,
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Headers": "Content-Type, Authorization, X-Api-Key, Idempotency-Key",
"Access-Control-Allow-Methods": "GET, POST, DELETE, OPTIONS",
...extra,
});
res.end(payload);
return true;
}