231 lines
8.3 KiB
TypeScript
231 lines
8.3 KiB
TypeScript
/**
|
|
* Smoke tests for the public lead-capture endpoint. Covers the three documented
|
|
* anti-spam layers (origin allowlist, honeypot, rate-limit) plus happy-path
|
|
* persistence and Turnstile-flag-on rejection. Heavy collaborators are mocked
|
|
* at the module boundary so tests stay hermetic.
|
|
*/
|
|
import { describe, expect, it, vi, beforeEach } from "vitest";
|
|
|
|
const captureLeadMock = vi.fn(async () => ({ leadId: "lead_1", created: true }));
|
|
|
|
vi.mock("~/utils/leads/captureLead.server", () => ({
|
|
captureLead: captureLeadMock,
|
|
}));
|
|
|
|
vi.mock("~/utils/db.server", () => ({
|
|
db: {},
|
|
}));
|
|
|
|
vi.mock("~/utils/logger.server", () => ({
|
|
createScopedLogger: () => ({
|
|
info: () => undefined,
|
|
warn: () => undefined,
|
|
error: () => undefined,
|
|
}),
|
|
}));
|
|
|
|
const evaluateFlagMock = vi.fn(async () => ({ enabled: false, reason: "disabled" }));
|
|
vi.mock("~/utils/services/.server/featureFlagEvaluator.server", () => ({
|
|
evaluateFlagForContext: evaluateFlagMock,
|
|
}));
|
|
|
|
const leadCaptureTranslations: Record<string, string> = {
|
|
"api.errors.leadCapture.methodNotAllowed": "Method not allowed",
|
|
"api.errors.leadCapture.originNotAllowed": "Origin not allowed",
|
|
"api.errors.leadCapture.payloadTooLarge": "Payload too large",
|
|
"api.errors.leadCapture.invalidPayload": "Invalid payload",
|
|
"api.errors.leadCapture.invalidPayloadShape": "Invalid payload shape",
|
|
"api.errors.leadCapture.tooManyRequests": "Too many requests. Try again shortly.",
|
|
"api.errors.leadCapture.antiSpamFailed": "Anti-spam check failed",
|
|
"api.errors.leadCapture.captureFailed": "Capture failed",
|
|
};
|
|
const getTranslationsMock = vi.fn(async () => ({
|
|
t: (key: string) => leadCaptureTranslations[key] ?? key,
|
|
locale: "en",
|
|
translations: {},
|
|
}));
|
|
vi.mock("~/locale/i18next.server", () => ({
|
|
getTranslations: getTranslationsMock,
|
|
}));
|
|
|
|
const limiterDecision = { allowed: true, remaining: 9, oldestAt: null };
|
|
vi.mock("~/shared-store.server", () => ({
|
|
getSharedStore: () => ({}),
|
|
}));
|
|
vi.mock("@hivegrid/shared-store", async (orig) => {
|
|
const real = (await orig()) as Record<string, unknown>;
|
|
return {
|
|
...real,
|
|
createSlidingWindowRateLimiter: () => ({
|
|
consume: async () => limiterDecision,
|
|
reset: async () => undefined,
|
|
}),
|
|
};
|
|
});
|
|
|
|
async function loadAction() {
|
|
const mod = await import("./api.leads.capture");
|
|
return mod.action;
|
|
}
|
|
|
|
async function loadLoader() {
|
|
const mod = await import("./api.leads.capture");
|
|
return mod.loader;
|
|
}
|
|
|
|
function makeRequest(body: unknown, origin: string | null, opts: { ip?: string; method?: string } = {}): Request {
|
|
return new Request("https://app.example.com/api/leads/capture", {
|
|
method: opts.method ?? "POST",
|
|
body: typeof body === "string" ? body : JSON.stringify(body),
|
|
headers: {
|
|
"content-type": "application/json",
|
|
...(origin ? { origin } : {}),
|
|
// Trusted proxy-set header — the endpoint no longer keys the per-IP
|
|
// limiter on the client-spoofable X-Forwarded-For.
|
|
"cf-connecting-ip": opts.ip ?? "1.2.3.4",
|
|
"user-agent": "vitest",
|
|
},
|
|
});
|
|
}
|
|
|
|
describe("api.leads.capture action", () => {
|
|
beforeEach(() => {
|
|
captureLeadMock.mockClear();
|
|
evaluateFlagMock.mockClear();
|
|
getTranslationsMock.mockClear();
|
|
process.env.MARKETING_ALLOWED_ORIGINS = "https://marketing.example.com,https://*.hivegrid.de";
|
|
delete process.env.MCAPTCHA_INSTANCE_URL;
|
|
delete process.env.MCAPTCHA_ACCOUNT_SECRET;
|
|
delete process.env.MCAPTCHA_SITEKEY_FORMS;
|
|
limiterDecision.allowed = true;
|
|
});
|
|
|
|
it("localizes loader method errors", async () => {
|
|
const loader = await loadLoader();
|
|
const res = await loader({
|
|
request: new Request("https://app.example.com/api/leads/capture"),
|
|
});
|
|
await expect(res.json()).resolves.toEqual({ ok: false, error: "Method not allowed" });
|
|
expect(res.status).toBe(405);
|
|
expect(getTranslationsMock).toHaveBeenCalledTimes(1);
|
|
});
|
|
|
|
it("answers OPTIONS preflight with allow headers", async () => {
|
|
const action = await loadAction();
|
|
const res = await action({
|
|
request: new Request("https://app.example.com/api/leads/capture", {
|
|
method: "OPTIONS",
|
|
headers: { origin: "https://marketing.example.com" },
|
|
}),
|
|
});
|
|
expect(res.status).toBe(204);
|
|
expect(res.headers.get("access-control-allow-origin")).toBe("https://marketing.example.com");
|
|
});
|
|
|
|
it("rejects unknown origin with 403", async () => {
|
|
const action = await loadAction();
|
|
const res = await action({
|
|
request: makeRequest({ email: "a@b.co" }, "https://attacker.example.com"),
|
|
});
|
|
expect(res.status).toBe(403);
|
|
await expect(res.json()).resolves.toEqual({ ok: false, error: "Origin not allowed" });
|
|
expect(captureLeadMock).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("accepts wildcard subdomain", async () => {
|
|
const action = await loadAction();
|
|
const res = await action({
|
|
request: makeRequest({ email: "a@b.co" }, "https://landing.hivegrid.de"),
|
|
});
|
|
expect(res.status).toBe(200);
|
|
expect(captureLeadMock).toHaveBeenCalledTimes(1);
|
|
});
|
|
|
|
it("silently 204s on honeypot trigger", async () => {
|
|
const action = await loadAction();
|
|
const res = await action({
|
|
request: makeRequest(
|
|
{ email: "a@b.co", website_url: "spam-bot-was-here" },
|
|
"https://marketing.example.com",
|
|
),
|
|
});
|
|
expect(res.status).toBe(204);
|
|
expect(captureLeadMock).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("rejects malformed email shape with 400", async () => {
|
|
const action = await loadAction();
|
|
const res = await action({
|
|
request: makeRequest({ email: "not-an-email" }, "https://marketing.example.com"),
|
|
});
|
|
expect(res.status).toBe(400);
|
|
await expect(res.json()).resolves.toEqual({ ok: false, error: "Invalid payload shape" });
|
|
});
|
|
|
|
it("returns 429 when per-IP rate-limit triggers", async () => {
|
|
const action = await loadAction();
|
|
limiterDecision.allowed = false;
|
|
const res = await action({
|
|
request: makeRequest({ email: "rate@example.com" }, "https://marketing.example.com"),
|
|
});
|
|
expect(res.status).toBe(429);
|
|
await expect(res.json()).resolves.toEqual({ ok: false, error: "Too many requests. Try again shortly." });
|
|
expect(captureLeadMock).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("persists on the happy path with empty body and CORS header", async () => {
|
|
const action = await loadAction();
|
|
const res = await action({
|
|
request: makeRequest(
|
|
{
|
|
email: "alice@example.com",
|
|
firstName: "Alice",
|
|
source: "landing-pro",
|
|
attribution: { utmSource: "google", utmCampaign: "spring" },
|
|
},
|
|
"https://marketing.example.com",
|
|
),
|
|
});
|
|
expect(res.status).toBe(200);
|
|
expect(res.headers.get("access-control-allow-origin")).toBe("https://marketing.example.com");
|
|
expect(captureLeadMock).toHaveBeenCalledTimes(1);
|
|
const call = captureLeadMock.mock.calls[0]![0] as {
|
|
email: string;
|
|
firstName: string | null;
|
|
source: string | null;
|
|
attribution?: { utmSource?: string | null };
|
|
};
|
|
expect(call.email).toBe("alice@example.com");
|
|
expect(call.firstName).toBe("Alice");
|
|
expect(call.source).toBe("landing-pro");
|
|
expect(call.attribution?.utmSource).toBe("google");
|
|
});
|
|
|
|
it("rejects when captcha flag is on and token is missing", async () => {
|
|
const action = await loadAction();
|
|
evaluateFlagMock.mockResolvedValueOnce({ enabled: true, reason: "rule-matched" });
|
|
process.env.MCAPTCHA_INSTANCE_URL = "https://captcha.example.test";
|
|
process.env.MCAPTCHA_ACCOUNT_SECRET = "test-secret";
|
|
process.env.MCAPTCHA_SITEKEY_FORMS = "forms-key";
|
|
const res = await action({
|
|
request: makeRequest(
|
|
{ email: "alice@example.com" /* no captcha token */ },
|
|
"https://marketing.example.com",
|
|
),
|
|
});
|
|
expect(res.status).toBe(403);
|
|
await expect(res.json()).resolves.toEqual({ ok: false, error: "Anti-spam check failed" });
|
|
});
|
|
|
|
it("localizes persistence failures without changing the status or CORS headers", async () => {
|
|
const action = await loadAction();
|
|
captureLeadMock.mockRejectedValueOnce(new Error("db down"));
|
|
const res = await action({
|
|
request: makeRequest({ email: "alice@example.com" }, "https://marketing.example.com"),
|
|
});
|
|
expect(res.status).toBe(500);
|
|
expect(res.headers.get("access-control-allow-origin")).toBe("https://marketing.example.com");
|
|
await expect(res.json()).resolves.toEqual({ ok: false, error: "Capture failed" });
|
|
});
|
|
});
|