All files / routes/internal landing-leads.routes.ts

100% Statements 16/16
100% Branches 12/12
100% Functions 2/2
100% Lines 15/15

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61                                            1x   1x 8x 8x           8x 1x           7x 8x 5x 5x     4x 1x     1x       6x   3x          
// POST /api/internal/landing-leads — go.'s homeowner forms (the quote check).
//
// go. has no D1 and no marketplace key, so it calls in over X-Internal-API-Key
// (guarded in ./index.ts), like every other internal caller. Validation, the
// lead store write and the first-contact email are the www route's — see
// routes/marketplace/landing-leads.routes.ts. What differs is the edge:
// go. calls worker-to-worker, so the visitor IP arrives as `ipHash` in the
// body and the rate limit keys on that; and a filled honeypot is a bot.
 
import { Hono } from "hono";
import type { Dal } from "../../dal";
import { logger } from "../../lib/logger";
import { handleError, success } from "../../lib/response";
import { submitLandingLead } from "../marketplace/landing-leads.routes";
 
type Env = {
	Bindings: CloudflareBindings;
	Variables: {
		dal: Dal;
	};
};
 
const internalLandingLeads = new Hono<Env>();
 
internalLandingLeads.post("/", async (c) => {
	try {
		const body = (await c.req.json().catch(() => null)) as Record<
			string,
			unknown
		> | null;
 
		// A bot gets the same 201 a person gets, but nothing is written or sent.
		if (typeof body?.hp === "string" && body.hp.trim()) {
			return success(c, { received: true }, 201);
		}
 
		// No hash skips the limit rather than throttling everyone into one
		// shared bucket, and a binding error fails open — a public form must
		// never 500 over its own rate limiter.
		const ipHash = typeof body?.ipHash === "string" ? body.ipHash : "";
		if (c.env.RL_RESOURCE && ipHash) {
			try {
				const { success: allowed } = await c.env.RL_RESOURCE.limit({
					key: `landing-lead:${ipHash}`,
				});
				if (!allowed) {
					return c.json({ success: false, error: "rate_limited" }, 429);
				}
			} catch (err) {
				logger.error("[landing-leads] rate limit check failed:", err);
			}
		}
 
		return await submitLandingLead(c, c.get("dal"), body);
	} catch (error) {
		return handleError(c, error);
	}
});
 
export default internalLandingLeads;