Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 39 additions & 0 deletions app/src/app/api/posts/reported/route.test.ts
Original file line number Diff line number Diff line change
@@ -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: [] });
});
7 changes: 6 additions & 1 deletion app/src/app/api/posts/reported/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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" } });
}
}
45 changes: 45 additions & 0 deletions app/src/app/api/presence/route.test.ts
Original file line number Diff line number Diff line change
@@ -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 });
});
29 changes: 22 additions & 7 deletions app/src/app/api/presence/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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" } });
}
13 changes: 4 additions & 9 deletions app/src/components/launchpad/AdminQueue.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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. */
Expand All @@ -21,15 +22,9 @@ export default function AdminQueue() {
const [err, setErr] = useState<string | null>(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");
setPosts(null);
return;
}
setErr(null);
setPosts(d.posts ?? []);
const result = await readReportedQueue(fetch);
setErr(result.error);
setPosts(result.posts);
}, [address]);
useEffect(() => {
const id = setTimeout(() => void load(), 0);
Expand Down
21 changes: 21 additions & 0 deletions app/src/lib/db-mock.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -43,6 +48,9 @@ export function resetMock() {
verifyShouldThrow: false,
verifyResult: true,
transportOutage: false,
presenceShouldThrow: false,
reportedShouldThrow: false,
adminSessionValid: false,
launchTotalsRows: [],
b20Supply: null,
b20SupplyReads: 0,
Expand Down Expand Up @@ -74,6 +82,19 @@ function fakeDb(strings: TemplateStringsArray, ...values: unknown[]): Promise<an
const sql = strings.join("?");
const m = getMock();

// An authenticated admin session for the reported-queue route tests; opt-in so the sign-in tests still see no row.
if (m.adminSessionValid && sql.includes("FROM bb_admin_sessions") && sql.includes("token_hash")) {
const wallet = (process.env.ADMIN_WALLETS ?? "").split(",")[0]?.trim().toLowerCase() ?? "0x" + "a".repeat(40);
return Promise.resolve([{ id: "1", wallet, expires_at: new Date(Date.now() + 3_600_000) }] as any[]);
}
// Configured-DB outages throw from the tagged template, as postgres.js does, rather than returning an empty array.
if (m.presenceShouldThrow && (sql.includes("bb_site_counters") || sql.includes("bb_presence"))) {
throw new Error("mock presence DB outage");
}
if (m.reportedShouldThrow && sql.includes("p.reports > 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.
Expand Down
26 changes: 26 additions & 0 deletions app/src/lib/launchpad/adminQueue.test.ts
Original file line number Diff line number Diff line change
@@ -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<Response>)): 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("<html>bad gateway</html>", { 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" });
});
25 changes: 25 additions & 0 deletions app/src/lib/launchpad/adminQueue.ts
Original file line number Diff line number Diff line change
@@ -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<QueueResult> {
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) };
}
}
3 changes: 3 additions & 0 deletions app/src/lib/launchpad/holders.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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)", () => {
Expand Down
1 change: 1 addition & 0 deletions app/src/lib/launchpad/holders.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
19 changes: 19 additions & 0 deletions app/src/lib/launchpad/presence.test.ts
Original file line number Diff line number Diff line change
@@ -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");
});
Loading