From 9d6d8307aec8c1d623547e2a209e3a4e9f37d6cd Mon Sep 17 00:00:00 2001 From: Ayush7614 Date: Thu, 8 Oct 2026 14:31:20 +0530 Subject: [PATCH 1/2] fix(api): harden presence + reported read paths and trust share formatting MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Presence GET/POST were the last JSON read routes without try/catch: a DB outage turned the site-wide pulse/beacon into HTML 500s instead of the JSON 502 contract every sibling keeps. Both verbs now return JSON 502 + no-store with a server log, keeping the per-IP beacon bucket untouched. GET /api/posts/reported had the same hole, with a two-stage break: AdminQueue called res.json() before checking res.ok with no try/catch (via void load()), so an HTML 500 became an unhandled rejection instead of the graceful error row. Route now returns JSON 502; the queue parses defensively and surfaces friendlyError. fmtShare was the last trust formatter missing the finite guard its siblings have: NaN painted as 'NaN%' and Infinity as 'Infinity%' in the holder/trust panel where users judge rug risk. Now '—'. Tests: fmtShare non-finite, presence bot/hash helpers (new file). Verified: npm test 1047 pass / 0 fail, typecheck + eslint clean. --- app/src/app/api/posts/reported/route.ts | 7 ++++- app/src/app/api/presence/route.ts | 29 ++++++++++++++++----- app/src/components/launchpad/AdminQueue.tsx | 24 ++++++++++++----- app/src/lib/launchpad/holders.test.ts | 3 +++ app/src/lib/launchpad/holders.ts | 1 + app/src/lib/launchpad/presence.test.ts | 19 ++++++++++++++ 6 files changed, 68 insertions(+), 15 deletions(-) create mode 100644 app/src/lib/launchpad/presence.test.ts diff --git a/app/src/app/api/posts/reported/route.ts b/app/src/app/api/posts/reported/route.ts index 552a5826..abc60a9c 100644 --- a/app/src/app/api/posts/reported/route.ts +++ b/app/src/app/api/posts/reported/route.ts @@ -8,5 +8,10 @@ export const dynamic = "force-dynamic"; export async function GET(req: Request) { const a = await requireAdmin(req); if (!a.ok) return NextResponse.json({ error: a.error }, { status: a.status }); - return NextResponse.json({ posts: await listReported() }, { headers: { "cache-control": "private, no-store" } }); + try { + return NextResponse.json({ posts: await listReported() }, { headers: { "cache-control": "private, no-store" } }); + } catch (err) { + console.error("[posts] reported failed:", err instanceof Error ? err.message : err); + return NextResponse.json({ error: "could not load reported posts" }, { status: 502, headers: { "cache-control": "private, no-store" } }); + } } diff --git a/app/src/app/api/presence/route.ts b/app/src/app/api/presence/route.ts index e0cd0e53..dcb3e2ab 100644 --- a/app/src/app/api/presence/route.ts +++ b/app/src/app/api/presence/route.ts @@ -9,23 +9,38 @@ export const dynamic = "force-dynamic"; /** GET → {visits, online}. POST (browser beacon) → records presence, returns the same. No cookies, no PII stored. */ export async function GET() { - return NextResponse.json(await memo("pulse", 2_000, () => readPulse()), { headers: { "cache-control": "no-store" } }); + try { + return NextResponse.json(await memo("pulse", 2_000, () => readPulse()), { headers: { "cache-control": "no-store" } }); + } catch (err) { + console.error("[presence] pulse failed:", err instanceof Error ? err.message : err); + return NextResponse.json({ error: "could not load presence" }, { status: 502, headers: { "cache-control": "no-store" } }); + } } let lastPrune = 0; export async function POST(req: Request) { const ua = req.headers.get("user-agent") ?? ""; - if (looksLikeBot(ua)) return NextResponse.json(await readPulse(), { headers: { "cache-control": "no-store" } }); + try { + if (looksLikeBot(ua)) return NextResponse.json(await readPulse(), { headers: { "cache-control": "no-store" } }); + } catch (err) { + console.error("[presence] pulse failed:", err instanceof Error ? err.message : err); + return NextResponse.json({ error: "could not load presence" }, { status: 502, headers: { "cache-control": "no-store" } }); + } const ip = clientIp(req); // The visitor hash mixes in the UA, which the caller fully controls: without // a bucket, rotating UAs mints a fresh bb_presence row per request and // inflates visits. 30/min leaves normal beaconing (~every few seconds) alone. if (rateLimited(`presence:ip:${ip}`, 30)) return NextResponse.json({ error: "slow down" }, { status: 429 }); - const pulse = await recordBeacon(visitorHash(ip, ua)); - if (Date.now() - lastPrune > 3_600_000) { - lastPrune = Date.now(); - void prunePresence().catch(() => {}); + try { + const pulse = await recordBeacon(visitorHash(ip, ua)); + if (Date.now() - lastPrune > 3_600_000) { + lastPrune = Date.now(); + void prunePresence().catch(() => {}); + } + return NextResponse.json(pulse, { headers: { "cache-control": "no-store" } }); + } catch (err) { + console.error("[presence] beacon failed:", err instanceof Error ? err.message : err); + return NextResponse.json({ error: "could not record presence" }, { status: 502, headers: { "cache-control": "no-store" } }); } - return NextResponse.json(pulse, { headers: { "cache-control": "no-store" } }); } diff --git a/app/src/components/launchpad/AdminQueue.tsx b/app/src/components/launchpad/AdminQueue.tsx index f46480c7..cc2c6bcf 100644 --- a/app/src/components/launchpad/AdminQueue.tsx +++ b/app/src/components/launchpad/AdminQueue.tsx @@ -21,15 +21,25 @@ export default function AdminQueue() { const [err, setErr] = useState(null); const load = useCallback(async () => { if (!address) return; - const res = await fetch("/api/posts/reported", { cache: "no-store" }); - const d = (await res.json()) as { posts?: PostRow[]; error?: string }; - if (!res.ok) { - setErr(d.error ?? "not allowed"); + try { + const res = await fetch("/api/posts/reported", { cache: "no-store" }); + let d: { posts?: PostRow[]; error?: string }; + try { + d = (await res.json()) as { posts?: PostRow[]; error?: string }; + } catch { + throw new Error(`moderation queue returned ${res.status}`); + } + if (!res.ok) { + setErr(d.error ?? "not allowed"); + setPosts(null); + return; + } + setErr(null); + setPosts(d.posts ?? []); + } catch (e) { + setErr(friendlyError(e)); setPosts(null); - return; } - setErr(null); - setPosts(d.posts ?? []); }, [address]); useEffect(() => { const id = setTimeout(() => void load(), 0); diff --git a/app/src/lib/launchpad/holders.test.ts b/app/src/lib/launchpad/holders.test.ts index 978482d4..1ffcd41e 100644 --- a/app/src/lib/launchpad/holders.test.ts +++ b/app/src/lib/launchpad/holders.test.ts @@ -36,6 +36,9 @@ test("shareBps / fmtShare", () => { assert.equal(fmtShare(42), "0.42%"); assert.equal(fmtShare(0), "0%"); assert.equal(fmtShare(0.5), "<0.01%"); + assert.equal(fmtShare(NaN), "—", "non-finite never paints NaN% in the trust panel"); + assert.equal(fmtShare(Infinity), "—"); + assert.equal(fmtShare(-Infinity), "—"); }); test("holderTags: creator, pool, burn, sniper, whale (whale never on pool/burn)", () => { diff --git a/app/src/lib/launchpad/holders.ts b/app/src/lib/launchpad/holders.ts index 601ee4b1..8563fea4 100644 --- a/app/src/lib/launchpad/holders.ts +++ b/app/src/lib/launchpad/holders.ts @@ -37,6 +37,7 @@ export function shareBps(balance: bigint, supply: bigint): number { } export function fmtShare(bps: number): string { + if (!Number.isFinite(bps)) return "—"; if (bps <= 0) return "0%"; if (bps < 1) return "<0.01%"; const pct = bps / 100; diff --git a/app/src/lib/launchpad/presence.test.ts b/app/src/lib/launchpad/presence.test.ts new file mode 100644 index 00000000..5e880988 --- /dev/null +++ b/app/src/lib/launchpad/presence.test.ts @@ -0,0 +1,19 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { looksLikeBot, visitorHash } from "./presence.ts"; + +test("bot beacons skip the write path without minting visits", () => { + for (const ua of ["Googlebot/2.1", "curl/8.0", "python-requests/2.31", "axios/1.0", "Lighthouse"]) assert.equal(looksLikeBot(ua), true, ua); + assert.equal(looksLikeBot("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36"), false); + assert.equal(looksLikeBot(""), false); +}); + +test("visitor hashes are opaque 64-hex and differ per visitor", () => { + const a = visitorHash("1.2.3.4", "Mozilla/5.0"); + const b = visitorHash("5.6.7.8", "Mozilla/5.0"); + const c = visitorHash("1.2.3.4", "curl/8.0"); + for (const h of [a, b, c]) assert.match(h, /^[0-9a-f]{64}$/); + assert.notEqual(a, b, "different IPs differ"); + assert.notEqual(a, c, "different UAs differ"); + assert.equal(a, visitorHash("1.2.3.4", "Mozilla/5.0"), "stable within the day"); +}); From ef1d4d7299e28cfd8e65365edc474eb1d7a7ef6c Mon Sep 17 00:00:00 2001 From: Ayush7614 Date: Mon, 30 Nov 2026 18:22:42 +0530 Subject: [PATCH 2/2] test(api): cover presence/reported database and client failure paths --- app/src/app/api/posts/reported/route.test.ts | 39 +++++++++++++++++ app/src/app/api/presence/route.test.ts | 45 ++++++++++++++++++++ app/src/components/launchpad/AdminQueue.tsx | 23 ++-------- app/src/lib/db-mock.ts | 21 +++++++++ app/src/lib/launchpad/adminQueue.test.ts | 26 +++++++++++ app/src/lib/launchpad/adminQueue.ts | 25 +++++++++++ 6 files changed, 160 insertions(+), 19 deletions(-) create mode 100644 app/src/app/api/posts/reported/route.test.ts create mode 100644 app/src/app/api/presence/route.test.ts create mode 100644 app/src/lib/launchpad/adminQueue.test.ts create mode 100644 app/src/lib/launchpad/adminQueue.ts diff --git a/app/src/app/api/posts/reported/route.test.ts b/app/src/app/api/posts/reported/route.test.ts new file mode 100644 index 00000000..982aeb60 --- /dev/null +++ b/app/src/app/api/posts/reported/route.test.ts @@ -0,0 +1,39 @@ +import assert from "node:assert/strict"; +import test, { beforeEach } from "node:test"; +import { ADMIN_COOKIE } from "@/lib/admin/session"; +import { getMock, resetMock } from "@/lib/db-mock"; +import { GET } from "./route.ts"; + +const ADMIN = `0x${"a".repeat(40)}`; +const authed = () => + new Request("http://localhost/api/posts/reported", { headers: { cookie: `${ADMIN_COOKIE}=${"B".repeat(43)}` } }); + +beforeEach(() => { + resetMock(); + process.env.ADMIN_WALLETS = ADMIN; +}); + +test("the reported queue turns a database outage into JSON 502 with the private no-store policy intact", async () => { + getMock().adminSessionValid = true; + getMock().reportedShouldThrow = true; + const res = await GET(authed()); + assert.equal(res.status, 502); + assert.equal(res.headers.get("cache-control"), "private, no-store"); + assert.deepEqual(await res.json(), { error: "could not load reported posts" }); +}); + +test("the admin session gate still runs before the queue read", async () => { + getMock().adminSessionValid = false; + getMock().reportedShouldThrow = true; + const res = await GET(new Request("http://localhost/api/posts/reported")); + assert.equal(res.status, 401); + assert.match(String((await res.json() as { error: string }).error), /admin session/); +}); + +test("an available database still serves the queue to the signed-in admin", async () => { + getMock().adminSessionValid = true; + const res = await GET(authed()); + assert.equal(res.status, 200); + assert.equal(res.headers.get("cache-control"), "private, no-store"); + assert.deepEqual(await res.json(), { posts: [] }); +}); diff --git a/app/src/app/api/presence/route.test.ts b/app/src/app/api/presence/route.test.ts new file mode 100644 index 00000000..371dbf2b --- /dev/null +++ b/app/src/app/api/presence/route.test.ts @@ -0,0 +1,45 @@ +import assert from "node:assert/strict"; +import test, { beforeEach } from "node:test"; +import { getMock, resetMock } from "@/lib/db-mock"; +import { clearMemo } from "@/lib/launchpad/memo"; +import { GET, POST } from "./route.ts"; + +const request = (ua: string, ip: string) => + new Request("http://localhost/api/presence", { method: "POST", headers: { "user-agent": ua, "fly-client-ip": ip } }); + +beforeEach(() => { + resetMock(); + clearMemo(); // the pulse memo caches a failure just as it caches a success +}); + +test("GET turns a pulse database outage into JSON 502 with no-store", async () => { + getMock().presenceShouldThrow = true; + const res = await GET(); + assert.equal(res.status, 502); + assert.equal(res.headers.get("cache-control"), "no-store"); + assert.deepEqual(await res.json(), { error: "could not load presence" }); +}); + +test("POST turns both the bot-pulse read failure and the beacon write failure into JSON 502", async () => { + getMock().presenceShouldThrow = true; + const bot = await POST(request("curl/8.0", "1.2.3.4")); + assert.equal(bot.status, 502); + assert.equal(bot.headers.get("cache-control"), "no-store"); + assert.deepEqual(await bot.json(), { error: "could not load presence" }); + + const browser = await POST(request("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)", "5.6.7.8")); + assert.equal(browser.status, 502); + assert.equal(browser.headers.get("cache-control"), "no-store"); + assert.deepEqual(await browser.json(), { error: "could not record presence" }); +}); + +test("an available database still returns the pulse for GET and POST", async () => { + const get = await GET(); + assert.equal(get.status, 200); + assert.equal(get.headers.get("cache-control"), "no-store"); + assert.deepEqual(await get.json(), { visits: 0, online: 0 }); + + const post = await POST(request("Mozilla/5.0 (X11; Linux x86_64)", "9.8.7.6")); + assert.equal(post.status, 200); + assert.deepEqual(await post.json(), { visits: 0, online: 0 }); +}); diff --git a/app/src/components/launchpad/AdminQueue.tsx b/app/src/components/launchpad/AdminQueue.tsx index cc2c6bcf..836648d4 100644 --- a/app/src/components/launchpad/AdminQueue.tsx +++ b/app/src/components/launchpad/AdminQueue.tsx @@ -11,6 +11,7 @@ import type { PostRow } from "@/lib/launchpad/postsServer"; import { CHAINS, shortAddr } from "@/lib/chainPublic"; import { nowMs } from "@/lib/launchpad/time"; import { friendlyError } from "@/lib/errors"; +import { readReportedQueue } from "@/lib/launchpad/adminQueue"; import { nonce } from "@/lib/nonce"; /** Moderation queue: reported posts, hide/unhide with an admin-wallet signature. */ @@ -21,25 +22,9 @@ export default function AdminQueue() { const [err, setErr] = useState(null); const load = useCallback(async () => { if (!address) return; - try { - const res = await fetch("/api/posts/reported", { cache: "no-store" }); - let d: { posts?: PostRow[]; error?: string }; - try { - d = (await res.json()) as { posts?: PostRow[]; error?: string }; - } catch { - throw new Error(`moderation queue returned ${res.status}`); - } - if (!res.ok) { - setErr(d.error ?? "not allowed"); - setPosts(null); - return; - } - setErr(null); - setPosts(d.posts ?? []); - } catch (e) { - setErr(friendlyError(e)); - setPosts(null); - } + const result = await readReportedQueue(fetch); + setErr(result.error); + setPosts(result.posts); }, [address]); useEffect(() => { const id = setTimeout(() => void load(), 0); diff --git a/app/src/lib/db-mock.ts b/app/src/lib/db-mock.ts index f87c87c7..1798924e 100644 --- a/app/src/lib/db-mock.ts +++ b/app/src/lib/db-mock.ts @@ -22,6 +22,11 @@ type MockState = { // unreachable transport, so the RPC-outage path is exercised through viem // itself rather than a hand-rolled stub. transportOutage: boolean; + // Simulated configured-database outages for the presence and reported-queue reads. + presenceShouldThrow: boolean; + reportedShouldThrow: boolean; + // Let requireAdmin see an authenticated session without going through the sign-in flow. + adminSessionValid: boolean; // What getLaunchTotals' one aggregation over bb_launches returns: a row per (chain, quote). launchTotalsRows: { chain_id: number; quote: string; launches: bigint; trades: bigint; volume: string; burned: string; creators: string; volume_usd?: number; collected_usd?: number; burned_usd?: number; volume_unpriced?: string; collected_unpriced?: string; burned_unpriced?: string }[]; // What the B20 node (chain-mock's b20Client) answers to totalSupply(), per address; "fail" = that call fails, null = the node is down. @@ -43,6 +48,9 @@ export function resetMock() { verifyShouldThrow: false, verifyResult: true, transportOutage: false, + presenceShouldThrow: false, + reportedShouldThrow: false, + adminSessionValid: false, launchTotalsRows: [], b20Supply: null, b20SupplyReads: 0, @@ -74,6 +82,19 @@ function fakeDb(strings: TemplateStringsArray, ...values: unknown[]): Promise 0")) { + throw new Error("mock reported DB outage"); + } + // UPDATE bb_edit_nonces SET used_at = now() ... RETURNING nonce // Checks all predicates from applySignedEdit: nonce, chain_id, token, // wallet, used_at IS NULL, expires_at > now(), and the exact signed expiry. diff --git a/app/src/lib/launchpad/adminQueue.test.ts b/app/src/lib/launchpad/adminQueue.test.ts new file mode 100644 index 00000000..8552b7b9 --- /dev/null +++ b/app/src/lib/launchpad/adminQueue.test.ts @@ -0,0 +1,26 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { readReportedQueue } from "./adminQueue.ts"; + +const fakeFetch = (res: Response | (() => Promise)): typeof fetch => + (async () => (typeof res === "function" ? res() : res)) as unknown as typeof fetch; + +test("readReportedQueue accepts a successful JSON queue", async () => { + const posts = [{ id: 7, chain: "base", token: "0xabc", wallet: "0xdef", parent_id: null, body: "spam", tag: null, created_at: "2026-01-01T00:00:00.000Z", reports: 3, hidden: false, symbol: "A", name: "A" }]; + const result = await readReportedQueue(fakeFetch(new Response(JSON.stringify({ posts }), { status: 200 }))); + assert.equal(result.error, null); + assert.deepEqual(result.posts, posts); +}); + +test("a 502 JSON outage is shown as the server's message, not as an empty queue", async () => { + const result = await readReportedQueue(fakeFetch(new Response(JSON.stringify({ error: "could not load reported posts" }), { status: 502 }))); + assert.deepEqual(result, { posts: null, error: "could not load reported posts" }); +}); + +test("a non-JSON body and a dropped connection become retryable UI errors, never unhandled rejections", async () => { + const html = await readReportedQueue(fakeFetch(new Response("bad gateway", { status: 200 }))); + assert.deepEqual(html, { posts: null, error: "moderation queue returned 200" }); + + const offline = await readReportedQueue(fakeFetch(async () => { throw new Error("network down"); })); + assert.deepEqual(offline, { posts: null, error: "network down" }); +}); diff --git a/app/src/lib/launchpad/adminQueue.ts b/app/src/lib/launchpad/adminQueue.ts new file mode 100644 index 00000000..a65aff17 --- /dev/null +++ b/app/src/lib/launchpad/adminQueue.ts @@ -0,0 +1,25 @@ +import { friendlyError } from "@/lib/errors"; +import type { PostRow } from "./postsServer"; + +export type QueueResult = { posts: PostRow[] | null; error: string | null }; + +/** + * Read the admin moderation queue for the UI. A JSON error from the server (including its 502 on a database outage) + * is a message to show; a non-JSON body or a dropped connection is a retryable error. Pure enough to test with a + * fake fetch, so `void load()` in AdminQueue can no longer become an unhandled rejection. + */ +export async function readReportedQueue(fetchImpl: typeof fetch): Promise { + try { + const res = await fetchImpl("/api/posts/reported", { cache: "no-store" }); + let d: { posts?: PostRow[]; error?: string }; + try { + d = (await res.json()) as { posts?: PostRow[]; error?: string }; + } catch { + throw new Error(`moderation queue returned ${res.status}`); + } + if (!res.ok) return { posts: null, error: d.error ?? "not allowed" }; + return { posts: d.posts ?? [], error: null }; + } catch (e) { + return { posts: null, error: friendlyError(e) }; + } +}