// secret-scanner HTTP server. // // Surfaces: // POST /scan { content, deep? } -> FREE tier, IP rate-limited. // POST /pro/scan { content } -> PAID per call via x402 (USDC) OR prepaid key. DEEP. // GET /pro/scan ?content=… -> PAID, GET form for x402 discovery probes. // GET /health, GET / (landing/json) -> free. // POST /mcp -> MCP-over-HTTP (free). // GET /pro/checkout, /pro/success, POST /pro/webhook -> Stripe (human) lane. // // The deep /pro scan has TWO coexisting payment lanes (Kiran's dual-pay directive): // • x402 — agents pay USDC per call automatically (Base). Server holds NO private // key — payTo is a public receiving address only. // • Stripe — humans buy a prepaid API key via Checkout; a valid Bearer key skips x402. // The content to scan never leaves this process (detection is fully local). import express, { Request, Response, NextFunction } from "express"; import { paymentMiddleware, Network } from "x402-express"; import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js"; import { scan } from "./engine.js"; import { buildMcpServer } from "./mcpServer.js"; import { getProKey, kvIncr, kvCounters, kvEnabled } from "./kv.js"; import { stripeEnabled, createCheckoutSession, constructWebhookEvent, handleCheckoutCompleted, keyForSession, stripeConfig, } from "./stripeLane.js"; const PORT = Number(process.env.PORT ?? 8080); // Receiving wallet (public address only). const PAYTO = (process.env.X402_PAYTO ?? "0x074cFCfDf4509333a8d8dC0f90D18Ef276481c21") as `0x${string}`; const NETWORK = (process.env.X402_NETWORK ?? "base") as Network; const PRICE = process.env.X402_PRICE ?? "$0.02"; const FACILITATOR_URL = process.env.X402_FACILITATOR_URL; // mainnet needs a facilitator (Primer) to actually settle const PAYMENTS_ENABLED = process.env.X402_ENABLED !== "false"; // 402 Index domain-ownership proof hash. Filled in after POST /claim returns the // verification token (served at /.well-known/402index-verify.txt), then redeploy. const INDEX_VERIFY_HASH = process.env.INDEX_VERIFY_HASH ?? ""; // ---- Human payment lane: prepaid API keys ------------------------------ // A request carrying a valid `Authorization: Bearer ` skips x402 (the human // already paid via Stripe). Keys live in Cloudflare KV (minted by the webhook); // PRO_API_KEYS (comma-separated env) is a manual break-glass override. const PRO_API_KEYS = new Set( (process.env.PRO_API_KEYS ?? "") .split(",") .map((k) => k.trim()) .filter(Boolean) ); function bearerKey(req: Request): string | null { const h = req.headers["authorization"]; if (!h) return null; const m = /^Bearer\s+(.+)$/i.exec(String(h)); return m ? m[1].trim() : null; } async function isValidProKey(key: string | null): Promise { if (!key) return false; if (PRO_API_KEYS.has(key)) return true; if (kvEnabled()) { try { const rec = await getProKey(key); return !!rec; } catch { return false; } } return false; } // ---- Funnel instrumentation -------------------------------------------- function logFunnel(evt: "pro_hit" | "402_served" | "200_paid", extra: Record = {}) { try { console.log(JSON.stringify({ evt, svc: "secret-scanner", ts: Date.now(), ...extra })); } catch { /* logging must never break a request */ } void kvIncr(evt); } // Dual-pay message shown when a /pro request arrives unpaid. BOTH lanes visible. function paymentRequiredBody(reqOrigin: string) { return { error: "Payment required for the deep /pro scan.", message: "Choose either lane — both unlock the same deep secret scan:", pay_with_card_stripe: { how: "Buy a prepaid API key with a card (humans/teams).", checkout: `${reqOrigin}/pro/checkout`, then: "Send it as `Authorization: Bearer ` (or set SECRET_SCANNER_KEY in your MCP config).", price: `€${(stripeConfig.PRICE_CENTS / 100).toFixed(2)}`, }, pay_with_crypto_x402: { how: "Pay per call in USDC automatically (AI agents with a wallet).", protocol: "x402", price: `${PRICE} USDC on ${NETWORK}`, note: "Any x402-aware client satisfies the 402 challenge transparently — no signup, no key.", }, free_tier: `${reqOrigin}/scan { "content": "" } (standard scan, rate-limited)`, }; } function originOf(req: Request): string { const envBase = (process.env.PUBLIC_BASE_URL ?? "").trim().replace(/\/+$/, ""); if (envBase) return envBase; const proto = (req.headers["x-forwarded-proto"] as string) || req.protocol || "https"; const host = (req.headers["x-forwarded-host"] as string) || req.headers.host || "secret-scanner.vercel.app"; return `${proto}://${host}`; } const app = express(); app.disable("x-powered-by"); const landing = { name: "secret-scanner", description: "Scan a blob of code/text/diff for LEAKED SECRETS before you commit, push or share: API keys (AWS, GitHub, OpenAI, Stripe, Google, Slack…), tokens, private keys (RSA/EC/SSH/PGP), DB connection strings, .env dumps, JWTs and high-entropy strings. Returns findings with secret type, provider, severity and line. Fully local — the secret is never transmitted.", endpoints: { "POST /scan {content,deep?}": "Free (rate-limited: 30/h/IP).", "POST /pro/scan {content}": "Pay-per-call USDC via x402 (Base) OR prepaid key. DEEP: adds offline format-validity hints. No limit.", "POST /mcp": "MCP-over-HTTP (free) — use as an MCP server.", }, repo: "https://github.com/Baneado98/secret-scanner", }; const LANDING_HTML = `secret-scanner — catch leaked API keys & secrets before you commit

secret-scanner 🔐

Catch leaked secrets in a diff/file before you commit, push or open a PR.
MCP serverx402 pay-per-call100% localUSDC · Baseentropy + provider rulesprivate keys

Give it any code, text or git diff, get a CLEAN / REVIEW / LEAK verdict — every finding with its secret type, provider, severity and line:col, plus a masked excerpt (the full secret is never echoed) and how to rotate it. The blob is scanned in-process: nothing is sent anywhere.

What it catches

🔑 Provider keysAWS, GitHub, OpenAI, Anthropic, Stripe, Google, Slack, Twilio, SendGrid, npm, PyPI, Telegram, Discord, Shopify, Square, DigitalOcean, Cloudflare, Vault, Doppler…
📜 Private keysRSA / EC / DSA / OpenSSH / PGP / encrypted private-key blocks, GCP service-account JSON
🗄️ Connection stringspostgres/mysql/mongodb/redis URIs with embedded passwords, JDBC password=, basic-auth URLs
🎫 TokensJWTs, npm/PyPI publish tokens, generic api_key=… assignments
🎲 Unknown secretshigh Shannon-entropy base64/hex blobs that look like credentials even without a known prefix

Free HTTP API

curl -X POST https://secret-scanner.vercel.app/scan \\
  -H 'content-type: application/json' \\
  -d '{"content":"AWS_KEY=AKIAIOSFODNN7EXAMPLE"}'
# → { "verdict": "LEAK", "findings": [ { "rule":"aws-access-key-id", ... } ] }

MCP server (free)

{
  "mcpServers": {
    "secret-scanner": { "command": "npx", "args": ["-y", "secret-scanner-mcp"] }
  }
}

Or connect over HTTP at POST /mcp. Tool: scan_for_secrets.

Unlock /pro — two ways to pay

The deep /pro/* scan has two payment lanes that coexist — pick whichever fits you, both unlock the same deep scan.

💳 Card (Stripe)For humans/teams. Buy a prepaid API key at /pro/checkout, then send Authorization: Bearer <key> (or set SECRET_SCANNER_KEY in your MCP config).
🪙 x402 (USDC)For AI agents with a wallet. Pays ${PRICE} per call automatically — no sign-up, no key. Settles on-chain on Base.
POST /pro/scan   { "content": "<diff>" }    # 402 (shows BOTH lanes) → pay → result
`; app.get("/", (req, res) => { res.setHeader("Cache-Control", "no-store, max-age=0"); if (String(req.headers.accept ?? "").includes("application/json")) return res.json(landing); res.type("html").send(LANDING_HTML); }); app.get(["/api", "/api/", "/index"], (_req, res) => res.json(landing)); app.get("/health", (_req, res) => res.json({ ok: true })); // 402 Index domain-ownership proof (served when the claim hash is configured). app.get("/.well-known/402index-verify.txt", (_req, res) => { if (!INDEX_VERIFY_HASH) return res.status(404).type("text/plain").send("not configured"); res.type("text/plain").send(INDEX_VERIFY_HASH); }); // Standard x402 discovery manifest — crawlers/aggregators probe this path. app.get("/.well-known/x402", (_req, res) => res.json({ x402Version: 1, name: "secret-scanner", description: "Scan a blob of code, text or unified git diff for leaked secrets before commit/push/PR. Returns CLEAN/REVIEW/LEAK with type, provider, severity, line:column, masked excerpt and remediation. For AI coding agents.", category: "security", repository: "https://github.com/Baneado98/secret-scanner", mcp: { npx: "secret-scanner-mcp", http: "https://secret-scanner.vercel.app/mcp" }, accepts: [ { method: "GET", path: "/pro/scan", resource: "https://secret-scanner.vercel.app/pro/scan?content=API_KEY%3Dsk_live_123", price: { amount: (PRICE.replace("$", "") || "0.02"), currency: "USD", asset: "USDC", network: NETWORK }, payTo: PAYTO, scheme: "exact", description: "Deep secret scan of a code blob or git diff (pay-per-call).", }, ], free: { scan: "POST /scan {content|diff}" }, })); // ---- MCP-over-HTTP (free) — mounted BEFORE express.json + x402 middleware ---- app.post("/mcp", async (req: Request, res: Response) => { try { const server = buildMcpServer(); const transport = new StreamableHTTPServerTransport({ sessionIdGenerator: undefined }); res.on("close", () => { transport.close(); server.close(); }); await server.connect(transport); await transport.handleRequest(req, res); } catch (err: any) { if (!res.headersSent) { res.status(500).json({ jsonrpc: "2.0", error: { code: -32603, message: String(err?.message ?? err) }, id: null }); } } }); app.get("/mcp", (_req, res) => res.status(405).json({ error: "Use POST for MCP. POST /scan for the REST API." })); // ---- Stripe webhook (RAW body, mounted BEFORE express.json) ------------- app.post("/pro/webhook", express.raw({ type: "application/json", limit: "1mb" }), async (req: Request, res: Response) => { const sig = req.headers["stripe-signature"]; if (!sig || typeof sig !== "string") { return res.status(400).json({ error: "Missing stripe-signature header." }); } let event; try { event = constructWebhookEvent(req.body as Buffer, sig); } catch (err: any) { console.error(JSON.stringify({ evt: "webhook_bad_sig", err: String(err?.message ?? err) })); return res.status(400).json({ error: `Webhook signature verification failed: ${err?.message ?? err}` }); } try { if (event.type === "checkout.session.completed") { const key = await handleCheckoutCompleted(event); console.log(JSON.stringify({ evt: "checkout_completed", id: (event.data.object as any)?.id, minted: !!key })); void kvIncr("keys_minted"); } return res.json({ received: true, type: event.type }); } catch (err: any) { console.error(JSON.stringify({ evt: "webhook_handler_error", err: String(err?.message ?? err) })); return res.status(500).json({ error: "Webhook handler error", detail: String(err?.message ?? err) }); } }); app.use(express.json({ limit: "1mb" })); // raw source can be large // ---- Stripe checkout (human lane) -------------------------------------- app.get("/pro/checkout", async (req: Request, res: Response) => { if (!stripeEnabled()) { return res.status(503).json({ error: "Card checkout is not configured on this deployment. Use x402 (crypto) instead." }); } try { const { id, url } = await createCheckoutSession(originOf(req)); void kvIncr("checkout_created"); if (req.query.json || String(req.headers.accept ?? "").includes("application/json")) { return res.json({ id, url }); } return res.redirect(303, url); } catch (err: any) { return res.status(500).json({ error: "Could not create checkout session", detail: String(err?.message ?? err) }); } }); app.get("/pro/success", async (req: Request, res: Response) => { const sessionId = String(req.query.session_id ?? "").trim(); if (!sessionId) return res.status(400).type("text/plain").send("Missing session_id."); let key: string | null = null; for (let i = 0; i < 5 && !key; i++) { key = await keyForSession(sessionId).catch(() => null); if (!key) await new Promise((r) => setTimeout(r, 600)); } if (req.query.json) return res.json({ session_id: sessionId, api_key: key }); if (!key) { return res.type("html").send( `

Payment received ✅

Your API key is being provisioned. Refresh this page in a few seconds, or check your email.

` ); } return res.type("html").send( `

Payment received ✅ — here is your secret-scanner Pro key

${key}

Set it in your MCP config:

"env": { "SECRET_SCANNER_KEY": "${key}" }

Then re-run a scan with deep=true.

` ); }); // Funnel snapshot (read-only). app.get("/pro/funnel", async (_req: Request, res: Response) => { if (!kvEnabled()) return res.json({ kv: false, note: "KV not configured; counters live in vercel logs only." }); const c = await kvCounters(["pro_hit", "402_served", "200_paid", "checkout_created", "keys_minted"]); res.json({ kv: true, counters: c }); }); // ---- Free-tier rate limiter (in-memory, per IP) ------------------------- const WINDOW_MS = 60 * 60 * 1000; // 1h const FREE_LIMIT = 30; const hits = new Map(); function rateLimit(req: Request, res: Response, next: NextFunction) { const ip = (req.headers["x-forwarded-for"]?.toString().split(",")[0].trim()) || req.ip || "unknown"; const now = Date.now(); const rec = hits.get(ip); if (!rec || now > rec.resetAt) { hits.set(ip, { count: 1, resetAt: now + WINDOW_MS }); return next(); } rec.count++; if (rec.count > FREE_LIMIT) { res.setHeader("Retry-After", Math.ceil((rec.resetAt - now) / 1000).toString()); return res.status(429).json({ error: "Free-tier rate limit reached.", limit: FREE_LIMIT, window: "1h", hint: `For unlimited / commercial use, call the pay-per-call endpoint POST /pro/scan (${PRICE} USDC via x402, or a prepaid key).`, }); } next(); } setInterval(() => { const now = Date.now(); for (const [k, v] of hits) if (now > v.resetAt) hits.delete(k); }, WINDOW_MS).unref(); // ---- /pro funnel logging + API-key bypass (runs BEFORE x402) ------------ const KEY_PAID = Symbol("secretScannerKeyPaid"); const PRO_SCAN_PATHS = new Set(["/pro/scan"]); app.use("/pro", async (req: Request & { [KEY_PAID]?: boolean }, _res: Response, next: NextFunction) => { const full = req.baseUrl + req.path; // e.g. "/pro/scan" if (!PRO_SCAN_PATHS.has(full)) return next(); // checkout/webhook/success/funnel logFunnel("pro_hit", { path: full, method: req.method }); const key = bearerKey(req); if (await isValidProKey(key)) { req[KEY_PAID] = true; logFunnel("200_paid", { path: full, via: "key" }); } next(); }); // ---- x402 paid routes --------------------------------------------------- if (PAYMENTS_ENABLED) { const facilitator = FACILITATOR_URL ? { url: FACILITATOR_URL as `${string}://${string}` } : undefined; const proConfig = { price: PRICE, network: NETWORK, config: { description: "secret-scanner: deep scan of a code/diff blob for leaked secrets (pay-per-call)." }, }; const x402 = paymentMiddleware( PAYTO, { "POST /pro/scan": proConfig, // Also gate GET so x402 discovery probes (and the 402 Index verifier), // which fetch the resource URL with GET, receive a proper 402. "GET /pro/scan": proConfig, }, facilitator ); // A valid-key request skips x402; everyone else is gated. We also splice the // Stripe (card) lane INTO x402's 402 body so the dual-pay choice is visible. app.use((req: Request & { [KEY_PAID]?: boolean }, res: Response, next: NextFunction) => { if (req[KEY_PAID]) return next(); if (req.path.startsWith("/pro/")) { const origin = originOf(req); const dual = paymentRequiredBody(origin); const origJson = res.json.bind(res); res.json = (body: any) => { if (res.statusCode === 402 && body && typeof body === "object") { body = { ...body, pay_with_card_stripe: dual.pay_with_card_stripe, dual_pay: true }; } return origJson(body); }; res.on("finish", () => { if (res.statusCode === 402) logFunnel("402_served", { path: req.path }); else if (res.statusCode === 200) logFunnel("200_paid", { path: req.path, via: "x402" }); }); } return x402(req, res, next); }); } // If payments are DISABLED via env but a /pro/scan slips through without a key, // never serve the deep scan for free — return the dual-pay 402 ourselves. app.use("/pro", (req: Request & { [KEY_PAID]?: boolean }, res: Response, next: NextFunction) => { const full = req.baseUrl + req.path; if (!PRO_SCAN_PATHS.has(full)) return next(); if (req[KEY_PAID]) return next(); if (!PAYMENTS_ENABLED) { logFunnel("402_served", { path: full, via: "no-x402" }); return res.status(402).json(paymentRequiredBody(originOf(req))); } next(); }); // ---- handlers ----------------------------------------------------------- function handleScan(deep: boolean) { return (req: Request, res: Response) => { const content = typeof req.body?.content === "string" ? req.body.content : ""; if (!content.trim()) return res.status(400).json({ error: "Body field 'content' (string) is required." }); try { // SECURITY: the free handler (deep=false) MUST NOT run the premium DEEP // scan even if the caller passes {"deep":true} in the body. Deep is the // paid tier — only the /pro/scan route (deep=true) enables it, never a // user-supplied flag. (Closes the "deep:true gives premium free" leak.) const result = scan(content, { deep }); res.json(result); } catch (err: any) { res.status(500).json({ error: String(err?.message ?? err) }); } }; } // Free — standard scan. app.post("/scan", rateLimit, handleScan(false)); // Paid (key/x402-gated by the middleware above) — DEEP scan. POST takes JSON body; // GET takes ?content=… (the GET form exists so x402 discovery/verification probes // hit a 402 resource). app.post("/pro/scan", handleScan(true)); app.get("/pro/scan", (req: Request, res: Response) => { const content = typeof req.query.content === "string" ? req.query.content : ""; if (!content.trim()) return res.status(400).json({ error: "Query param 'content' is required (or POST a JSON body)." }); try { res.json(scan(content, { deep: true })); } catch (err: any) { res.status(500).json({ error: String(err?.message ?? err) }); } }); // Catch-all 404 + global error handler (serverless-safe). app.use((_req, res) => { res.status(404).json({ error: "Not found. See GET / for the endpoint list." }); }); app.use((err: any, _req: Request, res: Response, _next: NextFunction) => { if (!res.headersSent) res.status(500).json({ error: "Internal error", detail: String(err?.message ?? err) }); }); export { app }; export default app; const isDirectRun = process.argv[1] && import.meta.url === `file://${process.argv[1].replace(/\\/g, "/")}`; if (isDirectRun || process.env.FORCE_LISTEN === "true") { app.listen(PORT, () => { console.error(`secret-scanner HTTP on :${PORT} (payments ${PAYMENTS_ENABLED ? "ON" : "OFF"}, network=${NETWORK}, payTo=${PAYTO}, price=${PRICE})`); }); }