diff --git a/app/scripts/posts-db-test-chain.ts b/app/scripts/posts-db-test-chain.ts new file mode 100644 index 00000000..4d72a87e --- /dev/null +++ b/app/scripts/posts-db-test-chain.ts @@ -0,0 +1,15 @@ +// The integration tests use real signatures, replacing only the external RPC. +import type { Abi, Address, Hex } from "viem"; +import type { ChainKey } from "../src/lib/chainPublic.ts"; + +type Client = { + readContract: (args: { address: Address; abi: Abi; functionName: string; args: readonly unknown[] }) => Promise; + verifyMessage: (args: { address: Address; message: string; signature: Hex }) => Promise; + getChainId: () => Promise; +}; +let client: Client | null = null; +export function setPostsTestClient(value: Client) { client = value; } +export function publicClient(_chain: ChainKey) { + if (!client) throw new Error("posts integration-test client not configured"); + return client; +} diff --git a/app/scripts/posts-db-test-db.ts b/app/scripts/posts-db-test-db.ts new file mode 100644 index 00000000..55b68746 --- /dev/null +++ b/app/scripts/posts-db-test-db.ts @@ -0,0 +1,8 @@ +// Explicit integration-test adapter. Never imported by the application build. +import type { Db } from "../src/lib/db.ts"; + +let connection: Db | null = null; + +export function setPostsTestDb(value: Db | null) { connection = value; } +export function maybeDb(): Db | null { return connection; } +export type { Db }; diff --git a/app/src/app/api/admin/session/route.test.ts b/app/src/app/api/admin/session/route.test.ts new file mode 100644 index 00000000..38516c38 --- /dev/null +++ b/app/src/app/api/admin/session/route.test.ts @@ -0,0 +1,76 @@ +import assert from "node:assert/strict"; +import { randomBytes } from "node:crypto"; +import test from "node:test"; +import { generatePrivateKey, privateKeyToAccount } from "viem/accounts"; +import { getMock, resetMock } from "../../../../lib/db-mock.ts"; +import { buildAdminSignInMessage } from "../../../../lib/admin/signIn.ts"; +import { POST } from "./route.ts"; + +let sequence = 0; +function fixture() { + resetMock(); + const account = privateKeyToAccount(generatePrivateKey()); + const nonces = new Set(); + let sessions = 0; + let onRead: (() => Promise) | undefined; + getMock().query = async (sql, values) => { + const nonce = String(values[0]); + if (sql.includes("SELECT 1 FROM bb_admin_nonces")) { + const open = nonces.has(nonce); + await onRead?.(); + return open ? [{}] : []; + } + if (sql.includes("UPDATE bb_admin_nonces SET used_at")) { + if (!nonces.delete(nonce)) return []; + return [{ nonce }]; + } + if (sql.includes("INSERT INTO bb_admin_sessions")) sessions++; + return []; + }; + async function signed() { + const nonce = randomBytes(16).toString("hex"); + nonces.add(nonce); + const message = buildAdminSignInMessage({ origin: "https://openlaunch.lol", address: account.address, nonce, issuedAt: new Date() }); + return { message, signature: await account.signMessage({ message }), nonce }; + } + function submit(body: unknown) { + return POST(new Request("http://localhost/api/admin/session", { + method: "POST", headers: { "content-type": "application/json", origin: "https://openlaunch.lol", "x-forwarded-for": `admin-quota-${++sequence}` }, body: JSON.stringify(body), + })); + } + function barrier(count: number) { + let arrived = 0; + let release!: () => void; + const ready = new Promise((resolve) => { release = resolve; }); + onRead = async () => { if (++arrived === count) { onRead = undefined; release(); } await ready; }; + } + return { account, nonces, sessions: () => sessions, signed, submit, barrier }; +} + +test("concurrent admin sign-in replays cannot consume the wallet's sign-in allowance", { timeout: 10_000 }, async (t) => { + const f = fixture(); + const previous = process.env.ADMIN_WALLETS; + process.env.ADMIN_WALLETS = f.account.address; + t.after(() => { if (previous === undefined) delete process.env.ADMIN_WALLETS; else process.env.ADMIN_WALLETS = previous; }); + const original = await f.signed(); + f.barrier(12); // Every precheck sees the nonce open before any contender consumes it. + const replies = await Promise.all(Array.from({ length: 12 }, () => f.submit(original))); + assert.equal(replies.filter((r) => r.status === 200).length, 1); + assert.equal(replies.filter((r) => r.status === 401).length, 11); + assert.equal(f.sessions(), 1); + assert.equal((await f.submit(await f.signed())).status, 200, "fresh login retains its allowance"); + assert.equal(f.sessions(), 2); +}); + +test("fresh signed admin logins retain the cap and over-quota nonces cannot be replayed", async (t) => { + const f = fixture(); + const previous = process.env.ADMIN_WALLETS; + process.env.ADMIN_WALLETS = f.account.address; + t.after(() => { if (previous === undefined) delete process.env.ADMIN_WALLETS; else process.env.ADMIN_WALLETS = previous; }); + for (let i = 0; i < 10; i++) assert.equal((await f.submit(await f.signed())).status, 200); + const excess = await f.signed(); + assert.equal((await f.submit(excess)).status, 429); + assert.equal(f.nonces.has(excess.nonce), false); + assert.equal((await f.submit(excess)).status, 401); + assert.equal(f.sessions(), 10); +}); diff --git a/app/src/app/api/admin/session/route.ts b/app/src/app/api/admin/session/route.ts index 94bce097..0a3c4f1d 100644 --- a/app/src/app/api/admin/session/route.ts +++ b/app/src/app/api/admin/session/route.ts @@ -1,5 +1,5 @@ import { NextResponse } from "next/server"; -import { rateLimited } from "@/lib/launchpad/editServer"; +import { rateLimited } from "@/lib/rateLimit"; import { adminWallets } from "@/lib/launchpad/postsServer"; import { clientIp, readJson } from "@/lib/profiles/http"; import { verifySig } from "@/lib/profiles/server"; @@ -42,10 +42,12 @@ export async function POST(req: Request) { if (v === "down") return json({ error: "signature check unavailable, try again" }, 503); if (v === "bad") return json({ error: "signature does not match (with a smart wallet, switch it to Base and sign again)" }, 401); if (typeof v === "object") return json({ error: "switch your wallet to Base and sign again" }, 409); - // the wallet bucket is spent only after the wallet is proven (a stranger cannot lock an admin out) - if (rateLimited(`admin-signin:wallet:${c.wallet}`, 10)) return json({ error: "slow down" }, 429); try { if (!(await consumeAdminNonce(c.nonce))) return json({ error: "sign-in expired or already used, try again" }, 401); + // Concurrent copies can all pass the earlier read. Only the atomic nonce + // winner spends a wallet allowance; a fresh over-quota attempt consumes its + // nonce and the sign-in UI obtains another on retry. + if (rateLimited(`admin-signin:wallet:${c.wallet}`, 10)) return json({ error: "slow down" }, 429); const device = deviceLabel(req.headers.get("user-agent")); const s = await createAdminSession(c.wallet, device); console.info(`[admin] signed in: ${c.wallet} (${device})`); diff --git a/app/src/app/api/launch/image/route.test.ts b/app/src/app/api/launch/image/route.test.ts new file mode 100644 index 00000000..df9f2776 --- /dev/null +++ b/app/src/app/api/launch/image/route.test.ts @@ -0,0 +1,173 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { PutObjectCommand, S3Client } from "@aws-sdk/client-s3"; +import sharp from "sharp"; +import { BANNER_MAX_BYTES, IMAGE_MAX_BYTES, IMAGE_UPLOADS_PER_HOUR } from "@/lib/launchpad/images"; +import { POST } from "./route.ts"; + +const wallet = (n: number) => `0x${n.toString(16).padStart(40, "0")}`; +const garbage = new Uint8Array(32); +const ipLimit = IMAGE_UPLOADS_PER_HOUR * 2; + +function request(ip: string, owner: string, bytes: Uint8Array, kind?: string, headers?: HeadersInit): Request { + const form = new FormData(); + form.set("wallet", owner); + // Intentionally misleading extension/MIME: the route must validate the actual bytes. + form.set("file", new Blob([new Uint8Array(bytes)], { type: "image/png" }), "upload.png"); + if (kind) form.set("kind", kind); + return new Request("http://localhost/api/launch/image", { + method: "POST", headers: { "x-forwarded-for": ip, ...headers }, body: form, + }); +} + +test("image upload route validates images and limits anonymous callers by trusted IP", async (t) => { + const env = { + BUCKET_NAME: "image-route-test", + AWS_ENDPOINT_URL_S3: "https://image-store.invalid", + AWS_ACCESS_KEY_ID: "test-key", + AWS_SECRET_ACCESS_KEY: "test-secret", + IMAGE_PUBLIC_BASE: "https://images.example/api/launch/image", + }; + const previous = Object.fromEntries(Object.keys(env).map((key) => [key, process.env[key]])); + Object.assign(process.env, env); + t.after(() => { + for (const [key, value] of Object.entries(previous)) { + if (value === undefined) delete process.env[key]; + else process.env[key] = value; + } + }); + // Exercise the real multipart parser, limiter, decoder and storage command without doing I/O. + const stored: PutObjectCommand[] = []; + t.mock.method(S3Client.prototype, "send", async (command: PutObjectCommand) => { + assert.ok(command instanceof PutObjectCommand); + stored.push(command); + return {}; + }); + const png = await sharp({ create: { width: 600, height: 240, channels: 4, background: "#0052ff" } }) + .withMetadata({ exif: { IFD0: { Copyright: "private metadata" } } }).png().toBuffer(); + + await t.test("invalid uploads naming another wallet cannot spend that wallet's allowance", async () => { + for (let i = 0; i < IMAGE_UPLOADS_PER_HOUR; i++) { + const denied = await POST(request("192.0.2.1", wallet(1), garbage)); + assert.equal(denied.status, 415); + } + const response = await POST(request("192.0.2.2", wallet(1), png)); + assert.equal(response.status, 200, "the named wallet can still upload from its own IP"); + assert.match((await response.json()).url, /\/t\/[0-9a-f]{48}\.webp$/); + }); + + await t.test("valid uploads naming another wallet cannot spend that wallet's allowance", async () => { + for (let i = 0; i < IMAGE_UPLOADS_PER_HOUR; i++) { + const response = await POST(request("192.0.2.3", wallet(2), png)); + assert.equal(response.status, 200); + } + const response = await POST(request("192.0.2.4", wallet(2), png)); + assert.equal(response.status, 200, "valid bytes still do not prove ownership of the wallet field"); + }); + + await t.test("rotating wallet fields cannot bypass the existing IP allowance", async () => { + const before = stored.length; + for (let i = 0; i < ipLimit; i++) { + const response = await POST(request("192.0.2.5", wallet(100 + i), i % 2 ? garbage : png)); + assert.equal(response.status, i % 2 ? 415 : 200); + } + const denied = await POST(request("192.0.2.5", wallet(999), png)); + assert.equal(denied.status, 429); + assert.deepEqual(await denied.json(), { error: "slow down" }); + assert.equal(stored.length - before, ipLimit / 2, "invalid and over-budget requests never reach storage"); + }); + + await t.test("spoofing forwarded prefixes cannot buy new IP allowances", async () => { + for (let i = 0; i < ipLimit; i++) { + const response = await POST(request(`198.51.100.${i}, 192.0.2.6`, wallet(200 + i), garbage)); + assert.equal(response.status, 415); + } + const denied = await POST(request("198.51.100.254, 192.0.2.6", wallet(998), png)); + assert.equal(denied.status, 429); + assert.deepEqual(await denied.json(), { error: "slow down" }); + }); + + await t.test("Fly's client IP takes precedence over forwarded values", async (t) => { + const previous = process.env.FLY_APP_NAME; + process.env.FLY_APP_NAME = "image-route-test"; + t.after(() => { if (previous === undefined) delete process.env.FLY_APP_NAME; else process.env.FLY_APP_NAME = previous; }); + for (let i = 0; i < ipLimit; i++) { + const response = await POST(request(`198.51.100.${i}`, wallet(300 + i), garbage, undefined, { "fly-client-ip": "192.0.2.7" })); + assert.equal(response.status, 415); + } + assert.equal((await POST(request("198.51.100.254", wallet(997), png, undefined, { "fly-client-ip": "192.0.2.7" }))).status, 429); + }); + + await t.test("wallet shape, format, decoder and size failures retain their responses", async () => { + const before = stored.length; + const disguised = new Uint8Array(32); + disguised.set([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]); + const tiny = await sharp({ create: { width: 8, height: 8, channels: 4, background: "#0052ff" } }).png().toBuffer(); + for (const [req, status, error] of [ + [request("192.0.2.8", "not-a-wallet", png), 400, "connect a wallet first"], + [request("192.0.2.8", wallet(3), garbage), 415, "PNG, JPEG, WebP or GIF only"], + [request("192.0.2.8", wallet(3), disguised), 415, "not a valid image"], + [request("192.0.2.8", wallet(3), tiny), 415, "image too small (min 16×16)"], + [request("192.0.2.8", wallet(3), new Uint8Array(IMAGE_MAX_BYTES + 1)), 413, "image must be ≤ 2 MB"], + [request("192.0.2.8", wallet(3), new Uint8Array(BANNER_MAX_BYTES + 1), "banner"), 413, "image must be ≤ 4 MB"], + [request("192.0.2.8", wallet(3), png, undefined, { "content-length": String(BANNER_MAX_BYTES + 16 * 1024 + 1) }), 413, "image must be ≤ 4 MB"], + ] as const) { + const response = await POST(req); + assert.equal(response.status, status); + assert.deepEqual(await response.json(), { error }); + } + assert.equal(stored.length, before, "rejected requests are never stored"); + }); + + await t.test("logos and banners still store stripped WebP bytes with random keys", async () => { + const keys: string[] = []; + for (const [kind, width, height] of [[undefined, 512, 512], ["banner", 1500, 500]] as const) { + const response = await POST(request("192.0.2.9", wallet(4), png, kind)); + assert.equal(response.status, 200); + assert.equal(response.headers.get("cache-control"), "no-store"); + const body = await response.json(); + const command = stored.at(-1)!; + assert.match(command.input.Key!, /^t\/[0-9a-f]{48}\.webp$/); + keys.push(command.input.Key!); + assert.equal(body.url, `${env.IMAGE_PUBLIC_BASE}/${command.input.Key}`); + assert.equal(command.input.ContentType, "image/webp"); + const output = command.input.Body as Buffer; + assert.equal(body.bytes, output.length); + const metadata = await sharp(output).metadata(); + assert.equal(metadata.format, "webp"); + assert.equal(metadata.width, width); + assert.equal(metadata.height, height); + assert.equal(metadata.exif, undefined); + assert.equal(output.includes("private metadata"), false); + } + assert.notEqual(keys[0], keys[1]); + }); + + for (const declared of [undefined, "10"]) { + await t.test(`stops reading oversized multipart streams with ${declared === undefined ? "no" : "an understated"} size header`, async () => { + const before = stored.length; + const chunk = new Uint8Array(64 * 1024); + const availableChunks = 80; + let chunksRead = 0; + let cancelled = false; + const body = new ReadableStream({ + pull(controller) { + if (chunksRead === availableChunks) controller.close(); + else { chunksRead++; controller.enqueue(chunk); } + }, + cancel() { cancelled = true; }, + }, { highWaterMark: 0 }); + const req = new Request("http://localhost/api/launch/image", { + method: "POST", body, duplex: "half", + headers: { "content-type": "multipart/form-data; boundary=test", "x-forwarded-for": "192.0.2.10", ...(declared === undefined ? {} : { "content-length": declared }) }, + } as RequestInit & { duplex: "half" }); + const response = await POST(req); + assert.equal(response.status, 413, `read ${chunksRead}/${availableChunks} chunks; cancelled=${cancelled}`); + assert.deepEqual(await response.json(), { error: "image must be ≤ 4 MB" }); + assert.equal(chunksRead, Math.floor((BANNER_MAX_BYTES + 16 * 1024) / chunk.length) + 1); + assert.ok(chunksRead < availableChunks, "the parser must not drain the rest of the request"); + assert.equal(cancelled, true); + assert.equal(stored.length, before); + }); + } +}); diff --git a/app/src/app/api/launch/image/route.ts b/app/src/app/api/launch/image/route.ts index 1ee4b888..90e5e8d0 100644 --- a/app/src/app/api/launch/image/route.ts +++ b/app/src/app/api/launch/image/route.ts @@ -1,6 +1,6 @@ import { NextResponse } from "next/server"; import { clientIp, readFormData } from "@/lib/http"; -import { rateLimited } from "@/lib/launchpad/editServer"; +import { rateLimited } from "@/lib/rateLimit"; import { BANNER_MAX_BYTES, IMAGE_UPLOADS_PER_HOUR, checkUpload, imageRole, isWalletParam, maxBytesFor, randomImageKey } from "@/lib/launchpad/images"; import { toBannerWebp, toLogoWebp } from "@/lib/launchpad/imageProcess"; import { imageUploadsEnabled, putImage } from "@/lib/launchpad/imageStore"; @@ -34,7 +34,7 @@ export async function POST(req: Request) { const max = maxBytesFor(role); if (!isWalletParam(wallet)) return NextResponse.json({ error: "connect a wallet first" }, { status: 400 }); if (!(file instanceof Blob)) return NextResponse.json({ error: "file required" }, { status: 400 }); - if (rateLimited(`img:wallet:${wallet.toLowerCase()}`, IMAGE_UPLOADS_PER_HOUR, HOUR)) return NextResponse.json({ error: "upload limit reached, try later" }, { status: 429 }); + // The unsigned wallet field is an image namespace, not an authenticated quota identity. if (file.size > max) return NextResponse.json({ error: `image must be ≤ ${max / 1024 / 1024} MB` }, { status: 413 }); const bytes = new Uint8Array(await file.arrayBuffer()); diff --git a/app/src/app/api/posts/report/route.test.ts b/app/src/app/api/posts/report/route.test.ts new file mode 100644 index 00000000..bbd9f843 --- /dev/null +++ b/app/src/app/api/posts/report/route.test.ts @@ -0,0 +1,86 @@ +import assert from "node:assert/strict"; +import { randomBytes } from "node:crypto"; +import test from "node:test"; +import { verifyMessage } from "viem"; +import { generatePrivateKey, privateKeyToAccount } from "viem/accounts"; +import { getMock, resetMock } from "../../../../lib/db-mock.ts"; +import { buildReportMessage } from "../../../../lib/launchpad/posts.ts"; +import { POST } from "./route.ts"; + +let requestSequence = 0; +function fixture() { + resetMock(); + const signer = privateKeyToAccount(generatePrivateKey()); + const nonces = new Set(); + let writes = 0; + getMock().publicClient = { verifyMessage }; + getMock().query = async (sql, values) => { + if (sql.includes("SELECT chain_id, wallet FROM bb_posts")) return [{ chain_id: 8453, wallet: "0x1111111111111111111111111111111111111111" }]; + if (sql.includes("SELECT (SELECT count(*)")) return [{ n: 1n }]; + if (sql.includes("INSERT INTO bb_post_nonces")) { + const nonce = String(values[0]); + if (nonces.has(nonce)) throw new Error("duplicate nonce"); + nonces.add(nonce); + } + if (sql.includes("INSERT INTO bb_post_reports")) writes++; + if (sql.includes("SELECT count(*)::bigint")) return [{ n: 1n }]; + return []; + }; + async function signed(postId = 1) { + const input = { postId, wallet: signer.address, reason: "spam", nonce: randomBytes(16).toString("hex"), ts: Date.now() }; + return { ...input, signature: await signer.signMessage({ message: buildReportMessage(input) }) }; + } + function submit(input: unknown, ip = `report-test-${++requestSequence}`) { + // Calls the real route with a local Request; no HTTP/RPC traffic is sent. + return POST(new Request("http://localhost/api/posts/report", { + method: "POST", headers: { "content-type": "application/json", "x-forwarded-for": ip }, body: JSON.stringify(input), + })); + } + return { signed, submit, nonces, writes: () => writes }; +} + +test("invalid reports cannot consume the named wallet's reporting allowance", async () => { + const f = fixture(); + const input = await f.signed(); + for (let i = 0; i < 21; i++) assert.equal((await f.submit({ ...input, reason: "invalid" })).status, 400); + for (let i = 0; i < 21; i++) assert.equal((await f.submit({ ...input, signature: "0x1234" })).status, 401); + assert.equal(f.nonces.size, 0); + assert.equal(f.writes(), 0); + assert.equal((await f.submit(input)).status, 200); + assert.equal(f.writes(), 1); +}); + +test("replays do not spend allowance; twenty fresh signed actions retain the wallet cap", async () => { + const f = fixture(); + const first = await f.signed(); + assert.equal((await f.submit(first)).status, 200); + for (let i = 0; i < 21; i++) assert.equal((await f.submit(first)).status, 401); + for (let i = 1; i < 20; i++) { + const input = await f.signed(i + 1); + // Case changes must not create a second wallet allowance. + assert.equal((await f.submit({ ...input, wallet: input.wallet.toLowerCase() })).status, 200); + } + assert.equal((await f.submit(await f.signed(21))).status, 429); + assert.equal(f.writes(), 20); +}); + +test("the IP limit still rejects excess invalid requests before verification", async () => { + const f = fixture(); + const ip = `report-limit-${++requestSequence}`; + const input = await f.signed(); + for (let i = 0; i < 20; i++) assert.equal((await f.submit({ ...input, signature: "0x1234" }, ip)).status, 401); + assert.equal((await f.submit(input, ip)).status, 429); + assert.equal(f.nonces.size, 0); + assert.equal(f.writes(), 0); +}); + +test("client-supplied forwarding prefixes cannot reset a proxy-appended IP bucket", async () => { + fixture(); + const proxyClient = `proxy-client-${++requestSequence}`; + for (let i = 0; i <= 20; i++) { + const response = await POST(new Request("http://localhost/api/posts/report", { + method: "POST", headers: { "content-type": "application/json", "x-forwarded-for": `untrusted-prefix-${i}, ${proxyClient}` }, body: "{}", + })); + assert.equal(response.status, i < 20 ? 400 : 429); + } +}); diff --git a/app/src/app/api/posts/report/route.ts b/app/src/app/api/posts/report/route.ts index 51706c6e..6baffb16 100644 --- a/app/src/app/api/posts/report/route.ts +++ b/app/src/app/api/posts/report/route.ts @@ -1,6 +1,6 @@ import { NextResponse } from "next/server"; import { SIGNED_BODY_MAX, clientIp, readJson } from "@/lib/http"; -import { rateLimited } from "@/lib/launchpad/editServer"; +import { rateLimited } from "@/lib/rateLimit"; import { reportPost } from "@/lib/launchpad/postsServer"; export const dynamic = "force-dynamic"; @@ -12,7 +12,6 @@ export async function POST(req: Request) { const b = await readJson(req, SIGNED_BODY_MAX); if (!b) return NextResponse.json({ error: "bad json" }, { status: 400 }); if (typeof b.wallet !== "string") return NextResponse.json({ error: "bad params" }, { status: 400 }); - if (rateLimited(`report:wallet:${b.wallet.toLowerCase()}`, 20)) return NextResponse.json({ error: "slow down" }, { status: 429 }); const r = await reportPost({ postId: b.postId, wallet: b.wallet, reason: b.reason, nonce: b.nonce, ts: b.ts, signature: b.signature }); if (!r.ok) return NextResponse.json({ error: r.error }, { status: r.status }); return NextResponse.json(r); diff --git a/app/src/lib/admin/admin.test.ts b/app/src/lib/admin/admin.test.ts index 7496aa89..c6ff2ba6 100644 --- a/app/src/lib/admin/admin.test.ts +++ b/app/src/lib/admin/admin.test.ts @@ -165,7 +165,7 @@ const SIGN_IN = new Set(["admin/session:POST", "admin/nonce:POST"]); test("every handler of every admin route requires the admin session", () => { const found: string[] = []; for (const file of routes()) { - const rel = path.relative(path.join(SRC, "app/api"), path.dirname(file)); + const rel = path.relative(path.join(SRC, "app/api"), path.dirname(file)).split(path.sep).join("/"); const s = readFileSync(file, "utf8"); if (!ADMIN_MARKERS.test(s) && !rel.startsWith("admin")) continue; found.push(rel); @@ -206,7 +206,7 @@ test("admin actions: the session is checked before the action, against the walle test("sign-in: same-origin, rate-limited, nonce spent only after the signature checks out", () => { const s = src("app/api/admin/session/route.ts"); const post = s.slice(s.indexOf("export async function POST("), s.indexOf("export async function DELETE(")); - const order = ["fromAdminOrigin(req)", "rateLimited(`admin-signin:ip:", "checkAdminSignIn(", "adminWallets().has(c.wallet)", "adminNonceOpen(c.nonce)", "verifySig(c.wallet, [b.message as string], b.signature, \"base\")", "rateLimited(`admin-signin:wallet:", "consumeAdminNonce(c.nonce)", "createAdminSession(", "res.cookies.set(ADMIN_COOKIE, s.token, adminCookieOptions(s.expiresAt))"]; + const order = ["fromAdminOrigin(req)", "rateLimited(`admin-signin:ip:", "checkAdminSignIn(", "adminWallets().has(c.wallet)", "adminNonceOpen(c.nonce)", "verifySig(c.wallet, [b.message as string], b.signature, \"base\")", "consumeAdminNonce(c.nonce)", "rateLimited(`admin-signin:wallet:", "createAdminSession(", "res.cookies.set(ADMIN_COOKIE, s.token, adminCookieOptions(s.expiresAt))"]; let at = -1; for (const step of order) { const i = post.indexOf(step); diff --git a/app/src/lib/chain-mock.ts b/app/src/lib/chain-mock.ts index aeaf1f61..67bc2427 100644 --- a/app/src/lib/chain-mock.ts +++ b/app/src/lib/chain-mock.ts @@ -42,6 +42,7 @@ const DEAD_RPC = "http://127.0.0.1:1"; export function publicClient(_key: ChainKey): any { const m = getMock(); + if (m.publicClient) return m.publicClient; if (m.transportOutage) { return createPublicClient({ chain: base, diff --git a/app/src/lib/db-mock.ts b/app/src/lib/db-mock.ts index f87c87c7..a8ba427b 100644 --- a/app/src/lib/db-mock.ts +++ b/app/src/lib/db-mock.ts @@ -12,6 +12,9 @@ type NonceRow = { }; type MockState = { + // Optional route-test dependencies; the defaults below keep existing edit tests unchanged. + query?: (sql: string, values: unknown[]) => Promise; + publicClient?: object; nonceRows: Record; launcherRows: Record; metaInserted: boolean; @@ -74,6 +77,8 @@ function fakeDb(strings: TemplateStringsArray, ...values: unknown[]): Promise now(), and the exact signed expiry. diff --git a/app/src/lib/launchpad/editServer.test.ts b/app/src/lib/launchpad/editServer.test.ts index 8a5599f0..43312bff 100644 --- a/app/src/lib/launchpad/editServer.test.ts +++ b/app/src/lib/launchpad/editServer.test.ts @@ -228,6 +228,48 @@ test("applySignedEdit: already-used nonce is rejected (401)", async () => { assert.equal(r.status, 401, "reused nonce should be 401"); }); +test("applySignedEdit: replayed valid signatures cannot exhaust the creator's edit allowance", async () => { + resetMock(); + const m = getMock(); + const wallet = "0x" + "ac".repeat(20); + m.launcherRows[TOKEN] = { launcher: wallet, name: "Replay fixture", symbol: "RPL" }; + m.verifyResult = true; + const first = "b".repeat(32); + const fresh = "c".repeat(32); + for (const nonce of [first, fresh]) m.nonceRows[nonce] = { + nonce, used_at: null, wallet, token: TOKEN, chain_id: 8453, expires_at: EXPIRES_AT_ISO, + }; + assert.equal((await ed.applySignedEdit(editRequest({ wallet, nonce: first }))).ok, true); + for (let i = 0; i < 10; i++) { + const replay = await ed.applySignedEdit(editRequest({ wallet, nonce: first })); + assert.equal(replay.ok, false); + assert.equal(replay.status, 401, "a consumed nonce cannot spend a wallet allowance"); + } + assert.equal((await ed.applySignedEdit(editRequest({ wallet, nonce: fresh }))).ok, true); +}); + +test("applySignedEdit: ten fresh signed edits retain the wallet limit and over-quota nonces are consumed", async () => { + resetMock(); + const m = getMock(); + const wallet = "0x" + "ad".repeat(20); + m.launcherRows[TOKEN] = { launcher: wallet, name: "Quota fixture", symbol: "QTA" }; + m.verifyResult = true; + for (let i = 0; i < 11; i++) { + const nonce = i.toString(16).padStart(32, "d"); + m.nonceRows[nonce] = { nonce, used_at: null, wallet, token: TOKEN, chain_id: 8453, expires_at: EXPIRES_AT_ISO }; + const response = await ed.applySignedEdit(editRequest({ wallet, nonce })); + if (i < 10) assert.equal(response.ok, true); + else { + assert.equal(response.ok, false); + assert.equal(response.status, 429); + assert.notEqual(m.nonceRows[nonce].used_at, null); + const replay = await ed.applySignedEdit(editRequest({ wallet, nonce })); + assert.equal(replay.ok, false); + assert.equal(replay.status, 401); + } + } +}); + // ── Finding 1: rateLimited keyed on unproven wallet ── test("rateLimited: 10 hits on a wallet key 429s the 11th (the DoS mechanism)", () => { diff --git a/app/src/lib/launchpad/editServer.ts b/app/src/lib/launchpad/editServer.ts index 030f2741..cb8ae02c 100644 --- a/app/src/lib/launchpad/editServer.ts +++ b/app/src/lib/launchpad/editServer.ts @@ -78,11 +78,6 @@ export async function applySignedEdit(r: EditRequest): Promise<{ ok: true } | { return { ok: false, error: "signature does not match", status: 401 }; } - // wallet rate limit is applied AFTER the signature is verified, so an - // attacker cannot freeze a creator's edit budget by sending requests with - // the creator's public address (the wallet is proven before the bucket is spent) - if (rateLimited(`edit:wallet:${wallet}`, 10)) return { ok: false, error: "slow down", status: 429 }; - // nonce: exists, matches, unexpired, unused — consumed atomically, only // after the signature is proven, inside a transaction with the metadata // write so a failed INSERT rolls the nonce back @@ -95,6 +90,11 @@ export async function applySignedEdit(r: EditRequest): Promise<{ ok: true } | { AND expires_at = ${new Date(expiresAt).toISOString()} RETURNING nonce`; if (consumed.length === 0) return { ok: false as const, error: "nonce invalid or already used", status: 401 }; + // A signature proves who signed it, not that this submission is fresh. Charge + // the wallet only after atomic nonce consumption so replays cannot spend its + // allowance. A valid over-quota attempt consumes its nonce; the UI requests a + // fresh nonce on retry, as it already does for every edit submission. + if (rateLimited(`edit:wallet:${wallet}`, 10)) return { ok: false as const, error: "slow down", status: 429 }; await t` INSERT INTO bb_launch_meta (chain_id, token, launcher, name, symbol, description, image_url, banner_url, website, x_handle, updated_at) VALUES (${cid}, ${token}, ${wallet}, ${row[0].name}, ${row[0].symbol}, ${v.value.description || null}, ${v.value.image_url || null}, ${v.value.banner_url || null}, ${v.value.website || null}, ${v.value.x_handle || null}, now()) diff --git a/app/src/lib/launchpad/images.ts b/app/src/lib/launchpad/images.ts index c7ebf1ca..9256b2e3 100644 --- a/app/src/lib/launchpad/images.ts +++ b/app/src/lib/launchpad/images.ts @@ -18,7 +18,7 @@ export function imageRole(v: unknown): ImageRole { export function maxBytesFor(role: ImageRole): number { return role === "banner" ? BANNER_MAX_BYTES : IMAGE_MAX_BYTES; } -export const IMAGE_UPLOADS_PER_HOUR = 10; // per wallet and per IP +export const IMAGE_UPLOADS_PER_HOUR = 10; // the anonymous route's IP allowance is twice this (20/hour) export const IMAGE_KEY_BYTES = 24; export type ImageKind = "png" | "jpeg" | "webp" | "gif"; @@ -116,7 +116,7 @@ export function isOwnImageUrl(url: string | null | undefined, publicBase: string return rel !== null && new RegExp(`^t/[0-9a-f]{${IMAGE_KEY_BYTES * 2}}\\.webp$`).test(rel); } -/** Validate a client-declared wallet before it's used as a rate-limit key. */ +/** Validate the client-declared wallet's shape; this does not prove ownership. */ export function isWalletParam(v: unknown): v is string { return typeof v === "string" && /^0x[0-9a-fA-F]{40}$/.test(v); } diff --git a/app/src/lib/launchpad/postsServer.db.test.ts b/app/src/lib/launchpad/postsServer.db.test.ts new file mode 100644 index 00000000..b7103506 --- /dev/null +++ b/app/src/lib/launchpad/postsServer.db.test.ts @@ -0,0 +1,211 @@ +import assert from "node:assert/strict"; +import { randomBytes } from "node:crypto"; +import test from "node:test"; +import { setTimeout as delay } from "node:timers/promises"; +import postgres from "postgres"; +import { verifyMessage } from "viem"; +import { generatePrivateKey, privateKeyToAccount } from "viem/accounts"; +import { setPostsTestDb, type Db } from "../../../scripts/posts-db-test-db.ts"; +import { setPostsTestClient } from "../../../scripts/posts-db-test-chain.ts"; +import { POST_MIN_GAP_MS, buildPostMessage } from "./posts.ts"; + +// Opt-in, real PostgreSQL concurrency checks. The URL must be loopback, with a port and no options. Each run owns a +// random schema and drops only that schema; it never reads application environment files. +// RUN_POSTS_DB_TESTS=1 POSTS_TEST_DATABASE_URL=postgres://...@127.0.0.1:PORT/audit +// npx tsx --conditions=react-server --tsconfig tsconfig.posts-db-test.json --test src/lib/launchpad/postsServer.db.test.ts +test("posting limits and nonce consumption stay atomic across PostgreSQL connections", { skip: process.env.RUN_POSTS_DB_TESTS !== "1" }, async (t) => { + const endpoint = process.env.POSTS_TEST_DATABASE_URL; + assert.ok(endpoint, "POSTS_TEST_DATABASE_URL is required for the opted-in test"); + const parsed = new URL(endpoint); + assert.ok(["postgres:", "postgresql:"].includes(parsed.protocol) + && ["127.0.0.1", "localhost", "[::1]"].includes(parsed.hostname) + && parsed.port && !parsed.search && !parsed.hash, + "posting tests require an explicit loopback PostgreSQL host and port, without URL options"); + const schema = `post_security_${randomBytes(8).toString("hex")}`; + assert.match(schema, /^post_security_[0-9a-f]{16}$/); + const root = postgres(endpoint, { max: 1, onnotice: () => {} }); + const sql = postgres(endpoint, { max: 8, connection: { search_path: schema, application_name: schema }, onnotice: () => {} }); + let schemaCreated = false; + t.after(async () => { + setPostsTestDb(null); + try { + await sql.end({ timeout: 5 }); + } finally { + try { + if (schemaCreated) { + assert.match(schema, /^post_security_[0-9a-f]{16}$/); + await root.unsafe(`DROP SCHEMA ${schema} CASCADE`); + } + } finally { + await root.end({ timeout: 5 }); + } + } + }); + await root.unsafe(`CREATE SCHEMA ${schema}`); + schemaCreated = true; + const [scope] = await sql<{ schema: string }[]>`SELECT current_schema() AS schema`; + assert.equal(scope.schema, schema, "posting fixture writes must use the owned schema"); + await sql.unsafe(` + CREATE TABLE bb_launches (chain_id integer, token text, launcher text, supply numeric); + CREATE TABLE bb_token_settings (chain_id integer, token text, comments_muted boolean); + CREATE TABLE bb_posts (id bigserial PRIMARY KEY, chain_id integer NOT NULL, token text NOT NULL, wallet text NOT NULL, parent_id bigint REFERENCES bb_posts(id), body text NOT NULL, tag text, signature text NOT NULL, created_at timestamptz NOT NULL DEFAULT now(), hidden boolean NOT NULL DEFAULT false, hidden_by text, reports integer NOT NULL DEFAULT 0); + CREATE TABLE bb_post_nonces (nonce text PRIMARY KEY, wallet text NOT NULL, created_at timestamptz NOT NULL DEFAULT now()); + `); + setPostsTestDb(sql as unknown as Db); + let beforeVerification: (() => Promise) | null = null; + setPostsTestClient({ + getChainId: async () => 8453, + readContract: async () => 1n, + verifyMessage: async (args) => { + const valid = await verifyMessage(args); + if (beforeVerification) await beforeVerification(); + return valid; + }, + }); + const { POST } = await import("../../app/api/posts/route.ts"); + const account = privateKeyToAccount(generatePrivateKey()); + const wallet = account.address.toLowerCase(); + const token = "0x2222222222222222222222222222222222222222"; + await sql`INSERT INTO bb_launches VALUES (8453, ${token}, ${wallet}, 1000000)`; + const postCount = async () => Number((await sql`SELECT count(*) AS n FROM bb_posts`)[0].n); + const nonceCount = async () => Number((await sql`SELECT count(*) AS n FROM bb_post_nonces`)[0].n); + async function clear(seed = 0) { + beforeVerification = null; + await sql`TRUNCATE bb_posts, bb_post_nonces RESTART IDENTITY CASCADE`; + if (seed) await sql`INSERT INTO bb_posts (chain_id,token,wallet,body,signature,created_at) SELECT 8453, ${token}, ${wallet}, 'previous post', 'synthetic seed', now() - interval '1 minute' FROM generate_series(1, ${seed})`; + } + async function payload(signer = account, nonce = randomBytes(16).toString("hex")) { + const ts = Date.now(); + const input = { chain: "base", token, wallet: signer.address.toLowerCase(), nonce, ts, parentId: null, body: "Synthetic integration post" }; + return { ...input, signature: await signer.signMessage({ message: buildPostMessage(input) }) }; + } + async function submit(body: Awaited>) { + return POST(new Request("http://localhost/api/posts", { method: "POST", headers: { "content-type": "application/json", "x-forwarded-for": "192.0.2.240" }, body: JSON.stringify(body) })); + } + function barrier(count: number) { + let arrived = 0; + let release!: () => void; + const ready = new Promise((resolve) => { release = resolve; }); + beforeVerification = async () => { if (++arrived === count) release(); await ready; }; + } + await t.test("sequential calls retain the 20-second gap", async () => { + await clear(); + assert.equal((await submit(await payload())).status, 200); + assert.equal((await submit(await payload())).status, 429); + assert.equal(await postCount(), 1); + }); + for (const skewMs of [-60_000, 60_000]) await t.test(`posting gaps use database time when the app clock is skewed by ${skewMs}ms`, async (t) => { + await clear(); + const realNow = Date.now; + t.mock.method(Date, "now", () => realNow() + skewMs); + assert.equal((await submit(await payload())).status, 200); + const immediate = await submit(await payload()); + assert.equal(immediate.status, 429, "an app clock ahead of PostgreSQL must not bypass the posting gap"); + assert.match((await immediate.json()).error, /^wait \d+s between posts$/); + assert.equal(await postCount(), 1); + assert.equal(await nonceCount(), 1); + await sql`UPDATE bb_posts SET created_at = clock_timestamp() - interval '21 seconds'`; + assert.equal((await submit(await payload())).status, 200, "an app clock behind PostgreSQL must not extend the posting gap"); + assert.equal(await postCount(), 2); + assert.equal(await nonceCount(), 2); + }); + await t.test("a post queued beyond the gap is timestamped after its wallet lock is released", { timeout: 45_000 }, async () => { + await clear(); + const locker = await sql.reserve(); + let locked = false; + let queued: Promise | undefined; + try { + await locker`SELECT pg_advisory_lock(hashtext(${`post:${wallet}`}))`; + locked = true; + queued = submit(await payload()); + const deadline = Date.now() + 5_000; + for (;;) { + const [state] = await root`SELECT count(*)::int AS waiting FROM pg_stat_activity WHERE application_name = ${schema} AND wait_event = 'advisory'`; + if (state.waiting > 0) break; + assert.ok(Date.now() < deadline, "the actual posting transaction must be waiting on the wallet lock"); + await delay(10); + } + await delay(POST_MIN_GAP_MS + 100); + const [clock] = await root`SELECT clock_timestamp() AS released_at`; + await locker`SELECT pg_advisory_unlock(hashtext(${`post:${wallet}`}))`; + locked = false; + const response = await queued; + assert.equal(response.status, 200); + const result = await response.json(); + assert.equal((await submit(await payload())).status, 429, "lock wait must not backdate a post and permit an immediate second post"); + assert.ok(new Date(result.post.created_at).getTime() >= new Date(clock.released_at).getTime(), "created_at must use insertion time, not transaction-start time"); + assert.equal(await postCount(), 1); + } finally { + if (locked) await locker`SELECT pg_advisory_unlock(hashtext(${`post:${wallet}`}))`; + locker.release(); + await queued?.catch(() => {}); + } + }); + for (const skewMs of [0, -60_000, 60_000]) await t.test(`distinct signed nonces cannot bypass the gap concurrently with app clock skew ${skewMs}ms`, async (t) => { + await clear(); + const realNow = Date.now; + t.mock.method(Date, "now", () => realNow() + skewMs); + barrier(2); + const inputs = await Promise.all([payload(), payload()]); + const responses = await Promise.all(inputs.map(submit)); + assert.deepEqual(responses.map((r) => r.status).sort(), [200, 429]); + assert.equal(await postCount(), 1); + assert.equal(await nonceCount(), 1, "a rejected quota attempt retains its unused nonce"); + }); + await t.test("the last daily allowance is shared atomically", async () => { + await clear(59); + barrier(2); + const inputs = await Promise.all([payload(), payload()]); + const responses = await Promise.all(inputs.map(submit)); + assert.deepEqual(responses.map((r) => r.status).sort(), [200, 429]); + assert.equal(await postCount(), 60); + assert.equal(await nonceCount(), 1); + }); + await t.test("an already exhausted daily cap and invalid signatures write nothing", async () => { + await clear(60); + assert.equal((await submit(await payload())).status, 429); + assert.equal(await nonceCount(), 0); + await clear(); + assert.equal((await submit({ ...await payload(), signature: "0x1234" })).status, 401); + assert.equal(await postCount(), 0); + assert.equal(await nonceCount(), 0); + }); + await t.test("the daily cap is rechecked after verification even when the short gap is clear", async () => { + await clear(59); + beforeVerification = async () => { + beforeVerification = null; + await sql`INSERT INTO bb_posts (chain_id,token,wallet,body,signature,created_at) VALUES (8453, ${token}, ${wallet}, 'another committed post', 'synthetic seed', now() - interval '1 minute')`; + }; + const response = await submit(await payload()); + assert.equal(response.status, 429); + assert.deepEqual(await response.json(), { error: "daily post limit reached" }); + assert.equal(await postCount(), 60); + assert.equal(await nonceCount(), 0); + }); + await t.test("a post insert failure rolls back its signing nonce", async () => { + await clear(); + const input = await payload(); + await sql`ALTER TABLE bb_posts ADD CONSTRAINT audit_reject_body CHECK (body <> 'Synthetic integration post')`; + try { await assert.rejects(submit(input)); } finally { await sql`ALTER TABLE bb_posts DROP CONSTRAINT audit_reject_body`; } + assert.equal(await postCount(), 0); + assert.equal(await nonceCount(), 0); + assert.equal((await submit(input)).status, 200, "the same signature can be retried after storage recovers"); + }); + await t.test("different wallets can post independently", async () => { + await clear(); + barrier(2); + const second = privateKeyToAccount(generatePrivateKey()); + const inputs = await Promise.all([payload(), payload(second)]); + const responses = await Promise.all(inputs.map(submit)); + assert.deepEqual(responses.map((r) => r.status), [200, 200]); + assert.equal(await postCount(), 2); + }); + await t.test("reusing a consumed nonce does not create a second post", async () => { + await clear(); + const input = await payload(); + assert.equal((await submit(input)).status, 200); + await sql`UPDATE bb_posts SET created_at = now() - interval '1 minute'`; + assert.equal((await submit(input)).status, 401); + assert.equal(await postCount(), 1); + }); +}); diff --git a/app/src/lib/launchpad/postsServer.ts b/app/src/lib/launchpad/postsServer.ts index 995410fe..ed248ed1 100644 --- a/app/src/lib/launchpad/postsServer.ts +++ b/app/src/lib/launchpad/postsServer.ts @@ -2,10 +2,11 @@ import "server-only"; import { isAddress, type Address, type Hex } from "viem"; import { publicClient } from "@/lib/chain"; import { CHAIN_KEY_PATTERN, DEFAULT_CHAIN, chainIdOf, chainKeyOf, type ChainKey } from "@/lib/chainPublic"; -import { maybeDb } from "@/lib/db"; +import { maybeDb, type Db } from "@/lib/db"; import { ERC20_MIN_ABI } from "./abi"; import { AUTO_HIDE_REPORTS, POST_DAILY_MAX, POST_MIN_GAP_MS, buildModMessage, buildPostMessage, buildReportMessage, canPostNow, holderTag, isReportReason, tsFresh, validateBody, type ModAction, type Tag } from "./posts"; import { clampFeedOffset } from "./posts-paging"; +import { rateLimited } from "@/lib/rateLimit"; /** Mute targets: `token::
`. */ const TOKEN_TARGET_RE = new RegExp(`^token:(${CHAIN_KEY_PATTERN}):(0x[0-9a-f]{40})$`); @@ -143,8 +144,9 @@ export async function createPost(p: { chain: ChainKey; token: string; wallet: st // policy before crypto (cheap first) const [st] = await db<{ comments_muted: boolean }[]>`SELECT comments_muted FROM bb_token_settings WHERE chain_id = ${cid} AND token = ${token}`; if (st?.comments_muted) return fail("comments are off for this token", 403); - const [rate] = await db<{ last: string | null; n24: bigint }[]>`SELECT max(created_at) AS last, count(*) FILTER (WHERE created_at > now() - interval '24 hours')::bigint AS n24 FROM bb_posts WHERE wallet = ${wallet}`; - const gate = canPostNow(rate.last ? new Date(rate.last).getTime() : null, Number(rate.n24), now); + // Stored post times and both gap checks use the database clock, regardless of app-host clock skew. + const [rate] = await db<{ last: string | null; n24: bigint; db_now: string }[]>`SELECT max(created_at) AS last, count(*) FILTER (WHERE created_at > clock_timestamp() - interval '24 hours')::bigint AS n24, clock_timestamp() AS db_now FROM bb_posts WHERE wallet = ${wallet}`; + const gate = canPostNow(rate.last ? new Date(rate.last).getTime() : null, Number(rate.n24), new Date(rate.db_now).getTime()); if (!gate.ok) return fail(gate.error, 429); if (parentId !== null) { const [parent] = await db<{ id: bigint; parent_id: bigint | null }[]>`SELECT id, parent_id FROM bb_posts WHERE id = ${parentId} AND chain_id = ${cid} AND token = ${token} AND NOT hidden`; @@ -156,13 +158,26 @@ export async function createPost(p: { chain: ChainKey; token: string; wallet: st const message = buildPostMessage({ chain: p.chain, token, wallet, nonce: p.nonce, ts: Number(p.ts), parentId, body: v.body }); if (!(await verify(p.chain, wallet, message, p.signature))) return fail("signature does not match", 401); - if (!(await consumeNonce(p.nonce, wallet))) return fail("nonce already used", 401); - - const [row] = await db` - INSERT INTO bb_posts (chain_id, token, wallet, parent_id, body, tag, signature) - VALUES (${cid}, ${token}, ${wallet}, ${parentId}, ${v.body}, ${elig.tag}, ${String(p.signature)}) - RETURNING id, chain_id, token, wallet, parent_id, body, tag, created_at, reports, hidden`; - return { ok: true, post: shape(row) }; + const nonce = p.nonce; + const result = await db.begin(async (tx) => { + const sql = tx as unknown as Db; + // Distinct signatures can pass the cheap preflight together. Serialize the final + // policy read and write for this wallet across every server process and chain. + await sql`SELECT pg_advisory_xact_lock(hashtext(${`post:${wallet}`}))`; + const [current] = await sql<{ last: string | null; n24: bigint; db_now: string }[]>`SELECT max(created_at) AS last, count(*) FILTER (WHERE created_at > clock_timestamp() - interval '24 hours')::bigint AS n24, clock_timestamp() AS db_now FROM bb_posts WHERE wallet = ${wallet}`; + const finalGate = canPostNow(current.last ? new Date(current.last).getTime() : null, Number(current.n24), new Date(current.db_now).getTime()); + if (!finalGate.ok) return fail(finalGate.error, 429); + // A refused quota attempt spends no nonce; a failed INSERT rolls its nonce back. + const used = await sql`INSERT INTO bb_post_nonces (nonce, wallet) VALUES (${nonce}, ${wallet}) ON CONFLICT (nonce) DO NOTHING RETURNING nonce`; + if (used.length === 0) return fail("nonce already used", 401); + const [row] = await sql` + INSERT INTO bb_posts (chain_id, token, wallet, parent_id, body, tag, signature, created_at) + VALUES (${cid}, ${token}, ${wallet}, ${parentId}, ${v.body}, ${elig.tag}, ${String(p.signature)}, clock_timestamp()) + RETURNING id, chain_id, token, wallet, parent_id, body, tag, created_at, reports, hidden`; + return { ok: true as const, post: shape(row) }; + }); + if (result.ok) void db`DELETE FROM bb_post_nonces WHERE created_at < now() - interval '1 hour'`.catch(() => {}); + return result; } export async function reportPost(p: { postId: unknown; wallet: string; reason: unknown; nonce: unknown; ts: unknown; signature: unknown }): Promise<{ ok: true; hidden: boolean } | Fail> { @@ -173,6 +188,7 @@ export async function reportPost(p: { postId: unknown; wallet: string; reason: u const postId = Number(p.postId); if (!Number.isInteger(postId) || postId <= 0) return fail("bad post", 400); if (!isReportReason(p.reason)) return fail("bad reason", 400); + const reason = p.reason; if (!isNonce(p.nonce) || !tsFresh(p.ts, Date.now())) return fail("stale or bad nonce", 400); const [post] = await db<{ chain_id: number; wallet: string }[]>`SELECT chain_id, wallet FROM bb_posts WHERE id = ${postId}`; if (!post) return fail("post not found", 404); @@ -181,10 +197,13 @@ export async function reportPost(p: { postId: unknown; wallet: string; reason: u // reporters need skin in the game too: any trade or launch on the site const [act] = await db<{ n: bigint }[]>`SELECT (SELECT count(*) FROM bb_launch_swaps WHERE trader = ${wallet}) + (SELECT count(*) FROM bb_launches WHERE launcher = ${wallet}) + (SELECT count(*) FROM bb_posts WHERE wallet = ${wallet}) AS n`; if (Number(act.n) === 0) return fail("trade, launch or post first to report", 403); - const message = buildReportMessage({ postId, wallet, nonce: p.nonce, ts: Number(p.ts), reason: p.reason }); + const message = buildReportMessage({ postId, wallet, nonce: p.nonce, ts: Number(p.ts), reason }); if (!(await verify(chain, wallet, message, p.signature))) return fail("signature does not match", 401); if (!(await consumeNonce(p.nonce, wallet))) return fail("nonce already used", 401); - await db`INSERT INTO bb_post_reports (post_id, wallet, reason) VALUES (${postId}, ${wallet}, ${p.reason}) ON CONFLICT DO NOTHING`; + // Only a fresh signed action may spend this wallet's allowance. Unsigned + // claims and replays must never lock another reporter out of moderation. + if (rateLimited(`report:wallet:${wallet}`, 20)) return fail("slow down", 429); + await db`INSERT INTO bb_post_reports (post_id, wallet, reason) VALUES (${postId}, ${wallet}, ${reason}) ON CONFLICT DO NOTHING`; const [c] = await db<{ n: bigint }[]>`SELECT count(*)::bigint AS n FROM bb_post_reports WHERE post_id = ${postId}`; const n = Number(c.n); const hide = n >= AUTO_HIDE_REPORTS; diff --git a/app/src/lib/profiles/profile-quota.test.ts b/app/src/lib/profiles/profile-quota.test.ts new file mode 100644 index 00000000..34464faa --- /dev/null +++ b/app/src/lib/profiles/profile-quota.test.ts @@ -0,0 +1,86 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { getMock, resetMock } from "@/lib/db-mock"; +import { admitAdmin, deleteProfile } from "./server"; + +// Exercise the shared admission path through its real public entry points. +// Only the DB uniqueness constraint and contract-wallet RPC are simulated. +function fixture(byte: string) { + resetMock(); + const wallet = `0x${byte.repeat(20)}`; + const nonces = new Set(); + const m = getMock(); + let valid = true; + m.publicClient = { + getCode: async () => "0x01", + verifyMessage: async () => valid, + getChainId: async () => 8453, + }; + m.query = async (sql, values) => { + if (sql.includes("INSERT INTO bb_profile_nonces")) { + const nonce = String(values[0]); + if (nonces.has(nonce)) throw Object.assign(new Error("duplicate profile nonce"), { code: "23505" }); + nonces.add(nonce); + } + // The synthetic wallet has no profile; deletion is an idempotent no-op + // after authentication, so no unrelated profile rules enter these tests. + return []; + }; + const request = (n: number) => ({ chain: "base", wallet, nonce: n.toString(16).padStart(32, "0"), ts: Date.now(), signature: "0x01" }); + return { wallet, nonces, request, setValid: (value: boolean) => { valid = value; } }; +} + +test("profile admission: a used valid signature cannot spend the wallet allowance", async () => { + const f = fixture("ae"); + const original = f.request(1); + assert.equal((await deleteProfile(original)).ok, true); + for (let i = 0; i < 12; i++) { + const replay = await deleteProfile(original); + assert.equal(replay.ok, false); + if (!replay.ok) assert.equal(replay.status, 401, "consumed nonce is rejected before wallet accounting"); + } + assert.equal((await deleteProfile(f.request(2))).ok, true, "a fresh signed action retains its allowance"); + assert.equal(f.nonces.size, 2); +}); + +test("profile admission: twelve fresh actions retain the quota and over-quota nonces are consumed", async () => { + const f = fixture("af"); + for (let i = 1; i <= 12; i++) assert.equal((await deleteProfile(f.request(i))).ok, true); + const excess = f.request(13); + const denied = await deleteProfile(excess); + assert.equal(denied.ok, false); + if (!denied.ok) assert.equal(denied.status, 429); + assert.ok(f.nonces.has(excess.nonce), "fresh over-quota attempt consumes its nonce"); + const replay = await deleteProfile(excess); + assert.equal(replay.ok, false); + if (!replay.ok) assert.equal(replay.status, 401); +}); + +test("admin admission: concurrent copies debit the shared profile wallet quota once", async (t) => { + const f = fixture("b0"); + const prior = process.env.ADMIN_WALLETS; + process.env.ADMIN_WALLETS = f.wallet; + t.after(() => { if (prior === undefined) delete process.env.ADMIN_WALLETS; else process.env.ADMIN_WALLETS = prior; }); + const original = f.request(1); + const message = (wallet: string, nonce: string, ts: number) => `Synthetic admin action: ${wallet}:${nonce}:${ts}`; + const responses = await Promise.all(Array.from({ length: 13 }, () => admitAdmin(original, message))); + assert.equal(responses.filter((r) => r.ok).length, 1); + assert.equal(responses.filter((r) => !r.ok && r.status === 401).length, 12); + for (let i = 2; i <= 12; i++) assert.equal((await admitAdmin(f.request(i), message)).ok, true); + const excess = await admitAdmin(f.request(13), message); + assert.equal(excess.ok, false); + if (!excess.ok) assert.equal(excess.status, 429); +}); + +test("profile admission: invalid signatures consume neither nonces nor wallet allowance", async () => { + const f = fixture("b1"); + f.setValid(false); + for (let i = 1; i <= 15; i++) { + const denied = await deleteProfile(f.request(i)); + assert.equal(denied.ok, false); + if (!denied.ok) assert.equal(denied.status, 401); + } + assert.equal(f.nonces.size, 0); + f.setValid(true); + assert.equal((await deleteProfile(f.request(1))).ok, true); +}); diff --git a/app/src/lib/profiles/server.ts b/app/src/lib/profiles/server.ts index 1eb7e527..aebe2788 100644 --- a/app/src/lib/profiles/server.ts +++ b/app/src/lib/profiles/server.ts @@ -5,7 +5,7 @@ import { publicClient } from "@/lib/chain"; import { CHAIN_LABELS, DEFAULT_CHAIN, isChainKey, type ChainKey } from "@/lib/chainPublic"; import { maybeDb, type Db } from "@/lib/db"; import { BRAND_DOMAIN, BRAND_X } from "@/lib/brand"; -import { rateLimited } from "@/lib/launchpad/editServer"; +import { rateLimited } from "@/lib/rateLimit"; import { adminWallets } from "@/lib/launchpad/postsServer"; import { VISIBLE_CHAINS } from "@/lib/launchpad/config"; import { buildProfileDeleteMessage, buildProfileMessage, buildProfileModMessage, isNonce, isProfileModAction, tsFresh } from "./auth"; @@ -278,8 +278,8 @@ export async function admitAdmin(s: Signed, message: (w: string, nonce: string, } /** - * Shared front of every signed write: shapes, freshness, signature, then (only then) the rate-limit bucket and the - * nonce. The signature may be over any one of several candidate messages, tried in order (a save accepts its fields + * Shared front of every signed write: shapes, freshness, signature, single-use nonce, then the rate-limit bucket. + * The signature may be over any one of several candidate messages, tried in order (a save accepts its fields * exactly as sent or their cleaned form). */ async function admit(db: Db, s: Signed, message: (w: string, nonce: string, ts: number) => string | string[]): Promise<{ ok: true; wallet: string; ts: number } | Fail> { @@ -293,9 +293,11 @@ async function admit(db: Db, s: Signed, message: (w: string, nonce: string, ts: if (v === "down") return fail("signature check unavailable, try again", 503); if (v === "bad") return fail("signature does not match (with a smart wallet, switch it to Base and sign again)", 401); if (typeof v === "object") return fail(`your wallet lives on ${CHAIN_LABELS[v.switchTo]}: switch your wallet to ${CHAIN_LABELS[v.switchTo]} and sign again`, 409); - // the wallet bucket is spent only after the wallet is proven (a stranger cannot freeze someone's edits) - if (rateLimited(`profile:wallet:${wallet}`, 12)) return fail("slow down", 429); if (!(await consumeNonce(db, s.nonce, wallet))) return fail("nonce already used", 401); + // Only a fresh signed action may spend this wallet's allowance. Replaying a + // valid signature cannot lock its owner out of profile or admin actions. + // A fresh over-quota attempt consumes its nonce; retries sign a new one. + if (rateLimited(`profile:wallet:${wallet}`, 12)) return fail("slow down", 429); return { ok: true, wallet, ts }; } diff --git a/app/tsconfig.posts-db-test.json b/app/tsconfig.posts-db-test.json new file mode 100644 index 00000000..3d29e2f4 --- /dev/null +++ b/app/tsconfig.posts-db-test.json @@ -0,0 +1,12 @@ +{ + "extends": "./tsconfig.json", + "compilerOptions": { + "paths": { + "@/*": ["./src/*"], + "@/lib/db": ["./scripts/posts-db-test-db.ts"], + "@/lib/chain": ["./scripts/posts-db-test-chain.ts"] + } + }, + "include": ["src/lib/launchpad/postsServer.db.test.ts"], + "exclude": ["node_modules"] +}