Track HiveGrid Cloud planning reference

This commit is contained in:
david committed 2026-06-26 20:48:01 +02:00
1 parent b3d5ea6764
commit e341c5938a
5784 files changed
+1104929 -3

No files matched your search

@@ -0,0 +1,178 @@
/**
* `captureLead` — idempotent upsert helper for the marketing capture endpoint
* (Phase 05 #78).
*
* Behaviour:
* - When no Lead exists for the email: insert a new row, populate
* first-touch UTM/referrer/landingPage attribution, store first
* captured `LeadEvent` of type `captured`.
* - When a Lead exists: update `lastTouchAt` + `lastIpHash` + `userAgent`,
* merge missing optional profile fields (firstName, lastName, phone,
* company), but NEVER overwrite already-set attribution columns (first-
* touch semantics). Append a `re-captured` LeadEvent.
*
* The helper never throws on duplicate-email — the unique index guarantees
* idempotency. Validation is the caller's responsibility (Zod-parsed input).
*/
import { createHash } from "node:crypto";
import type { Prisma } from "@toolctrl/db/prisma-browser";
import { db } from "~/utils/db.server";
export interface CaptureLeadInput {
email: string;
firstName?: string | null;
lastName?: string | null;
phone?: string | null;
company?: string | null;
source?: string | null;
/** Attribution fields. Treated as first-touch — set only on insert. */
attribution?: {
utmSource?: string | null;
utmMedium?: string | null;
utmCampaign?: string | null;
utmTerm?: string | null;
utmContent?: string | null;
gclid?: string | null;
fbclid?: string | null;
referrer?: string | null;
landingPage?: string | null;
};
ip?: string | null;
userAgent?: string | null;
}
export interface CaptureLeadResult {
/** Persisted (or already-existing) lead id. */
leadId: string;
/** `true` when a new row was inserted, `false` when an existing row was touched. */
created: boolean;
}
export function hashIp(ip: string | null | undefined): string | null {
if (!ip) return null;
return createHash("sha256").update(ip).digest("hex").slice(0, 32);
}
export async function captureLead(input: CaptureLeadInput): Promise<CaptureLeadResult> {
const email = input.email.trim().toLowerCase();
const ipHash = hashIp(input.ip);
const ua = input.userAgent ? input.userAgent.slice(0, 500) : null;
const attr = input.attribution ?? {};
const existing = await db.lead.findUnique({ where: { email }, select: { id: true } });
if (!existing) {
const lead = await db.lead.create({
data: {
email,
firstName: trim(input.firstName),
lastName: trim(input.lastName),
phone: trim(input.phone),
company: trim(input.company),
source: trim(input.source),
utmSource: trim(attr.utmSource),
utmMedium: trim(attr.utmMedium),
utmCampaign: trim(attr.utmCampaign),
utmTerm: trim(attr.utmTerm),
utmContent: trim(attr.utmContent),
gclid: trim(attr.gclid),
fbclid: trim(attr.fbclid),
referrer: trim(attr.referrer),
landingPage: trim(attr.landingPage),
lastIpHash: ipHash,
userAgent: ua,
events: {
create: {
type: "captured",
payload: serialisePayload({
source: trim(input.source),
attribution: cleanAttribution(attr),
}),
},
},
},
select: { id: true },
});
return { leadId: lead.id, created: true };
}
// Existing — only fill blanks, never overwrite. First-touch attribution wins.
const updateData: Prisma.LeadUpdateInput = {
lastTouchAt: new Date(),
lastIpHash: ipHash,
userAgent: ua,
firstName: nonNullSetIfMissing(input.firstName),
lastName: nonNullSetIfMissing(input.lastName),
phone: nonNullSetIfMissing(input.phone),
company: nonNullSetIfMissing(input.company),
events: {
create: {
type: "re-captured",
payload: serialisePayload({
source: trim(input.source),
attribution: cleanAttribution(attr),
}),
},
},
};
// Only conditionally fill blanks — Prisma update treats `undefined` as
// "leave alone", and `null` as "set to NULL" which we explicitly do NOT want.
// We re-fetch the row only for fields that need conditional patching to
// avoid extra reads; the merge logic happens in the next query batch.
await db.lead.update({ where: { id: existing.id }, data: updateData });
// Best-effort fill-blanks: only touches columns where the existing value is
// NULL and the incoming value is set. This is two queries in the dup-case
// which keeps the common path simple.
await fillBlankProfileFields(existing.id, input);
return { leadId: existing.id, created: false };
}
function trim(v: string | null | undefined): string | null {
if (v === null || v === undefined) return null;
const t = String(v).trim();
return t === "" ? null : t;
}
function nonNullSetIfMissing(_v: string | null | undefined): undefined {
// Returning `undefined` so Prisma keeps the existing value untouched.
// The fill-blanks step (`fillBlankProfileFields`) handles actual patches.
return undefined;
}
async function fillBlankProfileFields(leadId: string, input: CaptureLeadInput): Promise<void> {
const row = await db.lead.findUnique({
where: { id: leadId },
select: { firstName: true, lastName: true, phone: true, company: true },
});
if (!row) return;
const patch: Prisma.LeadUpdateInput = {};
if (row.firstName == null && trim(input.firstName)) patch.firstName = trim(input.firstName);
if (row.lastName == null && trim(input.lastName)) patch.lastName = trim(input.lastName);
if (row.phone == null && trim(input.phone)) patch.phone = trim(input.phone);
if (row.company == null && trim(input.company)) patch.company = trim(input.company);
if (Object.keys(patch).length === 0) return;
await db.lead.update({ where: { id: leadId }, data: patch });
}
function cleanAttribution(attr: NonNullable<CaptureLeadInput["attribution"]>): Record<string, string> {
const out: Record<string, string> = {};
for (const [k, v] of Object.entries(attr)) {
const t = trim(v ?? null);
if (t) out[k] = t;
}
return out;
}
function serialisePayload(obj: Record<string, unknown>): Prisma.InputJsonValue {
// Drop top-level keys with empty / undefined values for compact JSON storage.
const out: Record<string, unknown> = {};
for (const [k, v] of Object.entries(obj)) {
if (v === null || v === undefined) continue;
if (typeof v === "object" && Object.keys(v as Record<string, unknown>).length === 0) continue;
out[k] = v;
}
return out as Prisma.InputJsonValue;
}
@@ -0,0 +1,404 @@
/**
* Atomic Lead-to-Tenant conversion service (Marketing-funnel Phase 2,
* Phase 05 #79).
*
* `convertLeadToTenant` runs inside a single Prisma `$transaction` so the
* following five effects either all commit or all roll back together:
*
* 1. New Tenant row (via direct prisma.create — we cannot reuse the
* higher-level `createTenant` helper because it runs outside a
* transaction. Slug + inboundAddress allocation is delegated to the
* pre-computed values passed in by the caller).
* 2. Lead row update: `status` advances to `trial` (default) or
* `customer` (when caller requests it), `convertedToTenantId` +
* `convertedAt` populated.
* 3. `LeadEvent` of type `converted` appended for the activity
* timeline.
* 4. `TenantAcquisition` row inserted with first-touch attribution
* snapshot copied from the Lead.
* 5. `OutboxEvent` published — `marketing.lead.convertedtotrial` or
* `marketing.lead.convertedtocustomer` — picked up downstream by
* the marketing-outbound worker handler to fan out webhooks (Slack,
* Discord, Mailchimp, HubSpot, Brevo, custom).
*
* Idempotency: the outbox dispatchKey is `lead-convert:<leadId>` so a
* re-run after partial failure produces the same outbox row (publishOutboxEvent
* returns the existing event on unique-constraint conflict). The Lead's
* `convertedToTenantId` check up-front turns repeated conversion attempts
* into no-ops, returning the already-created Tenant + Lead.
*/
import { Prisma } from "@toolctrl/db/prisma-browser";
import { publishOutboxEvent, type OutboxPublisherTransaction } from "@toolctrl/db/outbox";
import { db } from "~/utils/db.server";
export type ConvertedStatus = "trial" | "customer";
export type ConversionPath = "self-service" | "admin-override" | "api";
export interface ConvertLeadInput {
leadId: string;
/** Lead-status target after conversion. Defaults to `trial`. */
targetStatus?: ConvertedStatus;
/** Free-text path label for the TenantAcquisition row. */
conversionPath?: ConversionPath;
/** Pre-computed tenant params — caller resolves slug and inbound address. */
tenant: {
name: string;
slug: string;
icon?: string | null;
/** Pre-computed inbound address (e.g. via `getAvailableTenantInboundAddress`). */
inboundAddress: string;
};
/** Optional acting admin user id when conversionPath === "admin-override". */
actorId?: string | null;
/**
* Optional plan-id (SubscriptionProduct.id) carried through to the
* webhook payload — does NOT enrol the tenant into a subscription. The
* existing `addToTrialOrFreePlan` post-register flow handles that
* separately so we don't accidentally double-bill.
*/
planId?: string | null;
}
export interface ConvertLeadResult {
tenantId: string;
leadId: string;
status: ConvertedStatus;
alreadyConverted: boolean;
/** Outbox event id (useful for tests). */
outboxEventId: string | null;
}
export interface RecordExistingTenantLeadConversionInput {
leadId: string;
tenantId: string;
targetStatus?: ConvertedStatus;
conversionPath?: ConversionPath;
actorId?: string | null;
planId?: string | null;
}
export class LeadNotFoundError extends Error {
override readonly name = "LeadNotFoundError";
constructor(leadId: string) {
super(`Lead ${leadId} not found`);
}
}
export class LeadAlreadyConvertedError extends Error {
override readonly name = "LeadAlreadyConvertedError";
constructor(
leadId: string,
public readonly convertedToTenantId: string
) {
super(`Lead ${leadId} is already converted.`);
}
}
export class LeadConversionDisabledError extends Error {
override readonly name = "LeadConversionDisabledError";
constructor() {
super("Lead conversion is disabled (LEAD_CONVERSION_ENABLED=false).");
}
}
export const MARKETING_LEAD_EVENT_PREFIX = "marketing.lead";
export function buildLeadConversionEventType(status: ConvertedStatus): string {
return status === "customer"
? `${MARKETING_LEAD_EVENT_PREFIX}.convertedtocustomer`
: `${MARKETING_LEAD_EVENT_PREFIX}.convertedtotrial`;
}
export async function recordExistingTenantLeadConversion(input: RecordExistingTenantLeadConversionInput): Promise<ConvertLeadResult> {
if (process.env.LEAD_CONVERSION_ENABLED === "false") {
throw new LeadConversionDisabledError();
}
const status: ConvertedStatus = input.targetStatus ?? "trial";
const conversionPath: ConversionPath = input.conversionPath ?? "self-service";
return await db.$transaction(async (tx) => {
const lead = await tx.lead.findUnique({
where: { id: input.leadId },
select: {
id: true,
email: true,
firstName: true,
lastName: true,
company: true,
source: true,
utmSource: true,
utmMedium: true,
utmCampaign: true,
utmTerm: true,
utmContent: true,
gclid: true,
fbclid: true,
referrer: true,
landingPage: true,
firstSeenAt: true,
convertedToTenantId: true,
},
});
if (!lead) throw new LeadNotFoundError(input.leadId);
if (lead.convertedToTenantId) {
if (lead.convertedToTenantId !== input.tenantId) {
throw new LeadAlreadyConvertedError(lead.id, lead.convertedToTenantId);
}
return {
tenantId: input.tenantId,
leadId: lead.id,
status,
alreadyConverted: true,
outboxEventId: null,
};
}
const now = new Date();
await tx.lead.update({
where: { id: lead.id },
data: {
status,
convertedToTenantId: input.tenantId,
convertedAt: now,
},
});
await tx.leadEvent.create({
data: {
leadId: lead.id,
type: "converted",
actorId: input.actorId ?? null,
payload: {
tenantId: input.tenantId,
conversionPath,
targetStatus: status,
planId: input.planId ?? null,
} as Prisma.InputJsonValue,
},
});
await tx.tenantAcquisition.upsert({
where: { tenantId: input.tenantId },
create: {
tenantId: input.tenantId,
leadId: lead.id,
source: lead.source ?? conversionPath,
utmSource: lead.utmSource,
utmMedium: lead.utmMedium,
utmCampaign: lead.utmCampaign,
utmTerm: lead.utmTerm,
utmContent: lead.utmContent,
gclid: lead.gclid,
fbclid: lead.fbclid,
referrer: lead.referrer,
landingPage: lead.landingPage,
capturedAt: lead.firstSeenAt,
convertedAt: now,
conversionPath,
customFields:
input.planId != null
? ({ planId: input.planId } as Prisma.InputJsonValue)
: Prisma.JsonNull,
},
update: {
leadId: lead.id,
source: lead.source ?? conversionPath,
utmSource: lead.utmSource,
utmMedium: lead.utmMedium,
utmCampaign: lead.utmCampaign,
utmTerm: lead.utmTerm,
utmContent: lead.utmContent,
gclid: lead.gclid,
fbclid: lead.fbclid,
referrer: lead.referrer,
landingPage: lead.landingPage,
capturedAt: lead.firstSeenAt,
convertedAt: now,
conversionPath,
customFields:
input.planId != null
? ({ planId: input.planId } as Prisma.InputJsonValue)
: Prisma.JsonNull,
},
});
const outboxEvent = await publishOutboxEvent(tx as unknown as OutboxPublisherTransaction, {
tenantId: input.tenantId,
type: buildLeadConversionEventType(status),
payload: {
leadId: lead.id,
tenantId: input.tenantId,
targetStatus: status,
conversionPath,
planId: input.planId ?? null,
email: lead.email,
firstName: lead.firstName,
lastName: lead.lastName,
company: lead.company,
utm: {
source: lead.utmSource,
medium: lead.utmMedium,
campaign: lead.utmCampaign,
term: lead.utmTerm,
content: lead.utmContent,
},
referrer: lead.referrer,
landingPage: lead.landingPage,
convertedAt: now.toISOString(),
} as Prisma.InputJsonValue,
dispatchKey: `lead-convert:${lead.id}`,
});
return {
tenantId: input.tenantId,
leadId: lead.id,
status,
alreadyConverted: false,
outboxEventId: outboxEvent.id,
};
});
}
export async function convertLeadToTenant(input: ConvertLeadInput): Promise<ConvertLeadResult> {
if (process.env.LEAD_CONVERSION_ENABLED === "false") {
throw new LeadConversionDisabledError();
}
const status: ConvertedStatus = input.targetStatus ?? "trial";
const conversionPath: ConversionPath = input.conversionPath ?? "self-service";
return await db.$transaction(async (tx) => {
const lead = await tx.lead.findUnique({
where: { id: input.leadId },
select: {
id: true,
email: true,
firstName: true,
lastName: true,
company: true,
source: true,
utmSource: true,
utmMedium: true,
utmCampaign: true,
utmTerm: true,
utmContent: true,
gclid: true,
fbclid: true,
referrer: true,
landingPage: true,
firstSeenAt: true,
status: true,
convertedToTenantId: true,
},
});
if (!lead) throw new LeadNotFoundError(input.leadId);
// Idempotent re-run: already-converted leads return existing tenant.
if (lead.convertedToTenantId) {
return {
tenantId: lead.convertedToTenantId,
leadId: lead.id,
status,
alreadyConverted: true,
outboxEventId: null,
};
}
const tenant = await tx.tenant.create({
data: {
name: input.tenant.name,
slug: input.tenant.slug,
icon: input.tenant.icon ?? undefined,
inboundAddresses: {
create: [{ address: input.tenant.inboundAddress }],
},
},
select: { id: true },
});
const now = new Date();
await tx.lead.update({
where: { id: lead.id },
data: {
status,
convertedToTenantId: tenant.id,
convertedAt: now,
},
});
await tx.leadEvent.create({
data: {
leadId: lead.id,
type: "converted",
actorId: input.actorId ?? null,
payload: {
tenantId: tenant.id,
tenantSlug: input.tenant.slug,
conversionPath,
targetStatus: status,
planId: input.planId ?? null,
} as Prisma.InputJsonValue,
},
});
await tx.tenantAcquisition.create({
data: {
tenantId: tenant.id,
leadId: lead.id,
source: lead.source ?? conversionPath,
utmSource: lead.utmSource,
utmMedium: lead.utmMedium,
utmCampaign: lead.utmCampaign,
utmTerm: lead.utmTerm,
utmContent: lead.utmContent,
gclid: lead.gclid,
fbclid: lead.fbclid,
referrer: lead.referrer,
landingPage: lead.landingPage,
capturedAt: lead.firstSeenAt,
convertedAt: now,
conversionPath,
customFields:
input.planId != null
? ({ planId: input.planId } as Prisma.InputJsonValue)
: Prisma.JsonNull,
},
});
const eventType = buildLeadConversionEventType(status);
const outboxEvent = await publishOutboxEvent(tx as unknown as OutboxPublisherTransaction, {
tenantId: tenant.id,
type: eventType,
payload: {
leadId: lead.id,
tenantId: tenant.id,
targetStatus: status,
conversionPath,
planId: input.planId ?? null,
email: lead.email,
firstName: lead.firstName,
lastName: lead.lastName,
company: lead.company,
utm: {
source: lead.utmSource,
medium: lead.utmMedium,
campaign: lead.utmCampaign,
term: lead.utmTerm,
content: lead.utmContent,
},
referrer: lead.referrer,
landingPage: lead.landingPage,
convertedAt: now.toISOString(),
} as Prisma.InputJsonValue,
dispatchKey: `lead-convert:${lead.id}`,
});
return {
tenantId: tenant.id,
leadId: lead.id,
status,
alreadyConverted: false,
outboxEventId: outboxEvent.id,
};
});
}
@@ -0,0 +1,314 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { buildLeadConversionEventType, LeadAlreadyConvertedError, LeadNotFoundError } from "./convertLead.server";
vi.mock("~/utils/db.server", () => {
return { db: { $transaction: vi.fn() } };
});
vi.mock("@toolctrl/db/outbox", () => {
return {
publishOutboxEvent: vi.fn(),
};
});
describe("buildLeadConversionEventType", () => {
it("returns convertedtotrial for trial status", () => {
expect(buildLeadConversionEventType("trial")).toBe("marketing.lead.convertedtotrial");
});
it("returns convertedtocustomer for customer status", () => {
expect(buildLeadConversionEventType("customer")).toBe("marketing.lead.convertedtocustomer");
});
});
describe("convertLeadToTenant", () => {
let dbMock: any;
let publishMock: any;
let convertLeadToTenant: typeof import("./convertLead.server").convertLeadToTenant;
beforeEach(async () => {
vi.resetModules();
dbMock = (await import("~/utils/db.server")).db as any;
publishMock = (await import("@toolctrl/db/outbox")).publishOutboxEvent as any;
convertLeadToTenant = (await import("./convertLead.server")).convertLeadToTenant;
});
afterEach(() => {
vi.clearAllMocks();
});
function buildTx(leadOverrides: Record<string, unknown> = {}) {
const tx: any = {
lead: {
findUnique: vi.fn().mockResolvedValue({
id: "lead_1",
email: "test@example.com",
firstName: "Test",
lastName: "User",
company: "Acme",
source: "landing-pro",
utmSource: "google",
utmMedium: "cpc",
utmCampaign: "q2-launch",
utmTerm: null,
utmContent: null,
gclid: null,
fbclid: null,
referrer: null,
landingPage: "/pricing",
firstSeenAt: new Date("2026-05-10T00:00:00Z"),
status: "new",
convertedToTenantId: null,
...leadOverrides,
}),
update: vi.fn().mockResolvedValue({}),
},
tenant: {
create: vi.fn().mockResolvedValue({ id: "tenant_1" }),
},
leadEvent: {
create: vi.fn().mockResolvedValue({}),
},
tenantAcquisition: {
create: vi.fn().mockResolvedValue({}),
upsert: vi.fn().mockResolvedValue({}),
},
};
return tx;
}
it("happy-path creates tenant, updates lead, inserts acquisition, publishes outbox", async () => {
const tx = buildTx();
dbMock.$transaction.mockImplementation(async (fn: any) => fn(tx));
publishMock.mockResolvedValue({ id: "outbox_1" });
const result = await convertLeadToTenant({
leadId: "lead_1",
tenant: { name: "Acme", slug: "acme", inboundAddress: "acme@inbox.local" },
});
expect(result.tenantId).toBe("tenant_1");
expect(result.status).toBe("trial");
expect(result.alreadyConverted).toBe(false);
expect(result.outboxEventId).toBe("outbox_1");
expect(tx.tenant.create).toHaveBeenCalledOnce();
expect(tx.lead.update).toHaveBeenCalledWith(
expect.objectContaining({
where: { id: "lead_1" },
data: expect.objectContaining({ status: "trial", convertedToTenantId: "tenant_1" }),
})
);
expect(tx.leadEvent.create).toHaveBeenCalledWith(
expect.objectContaining({ data: expect.objectContaining({ type: "converted" }) })
);
expect(tx.tenantAcquisition.create).toHaveBeenCalledWith(
expect.objectContaining({
data: expect.objectContaining({
tenantId: "tenant_1",
leadId: "lead_1",
utmSource: "google",
utmCampaign: "q2-launch",
}),
})
);
expect(publishMock).toHaveBeenCalledWith(
tx,
expect.objectContaining({
type: "marketing.lead.convertedtotrial",
tenantId: "tenant_1",
dispatchKey: "lead-convert:lead_1",
})
);
});
it("publishes customer event when targetStatus=customer", async () => {
const tx = buildTx();
dbMock.$transaction.mockImplementation(async (fn: any) => fn(tx));
publishMock.mockResolvedValue({ id: "outbox_2" });
await convertLeadToTenant({
leadId: "lead_1",
targetStatus: "customer",
tenant: { name: "Acme", slug: "acme", inboundAddress: "acme@inbox.local" },
});
expect(publishMock).toHaveBeenCalledWith(
tx,
expect.objectContaining({ type: "marketing.lead.convertedtocustomer" })
);
});
it("returns alreadyConverted=true without re-creating tenant when lead already converted", async () => {
const tx = buildTx({ convertedToTenantId: "tenant_existing" });
dbMock.$transaction.mockImplementation(async (fn: any) => fn(tx));
const result = await convertLeadToTenant({
leadId: "lead_1",
tenant: { name: "Acme", slug: "acme", inboundAddress: "acme@inbox.local" },
});
expect(result.alreadyConverted).toBe(true);
expect(result.tenantId).toBe("tenant_existing");
expect(tx.tenant.create).not.toHaveBeenCalled();
expect(publishMock).not.toHaveBeenCalled();
});
it("throws LeadNotFoundError when lead missing", async () => {
const tx = buildTx();
tx.lead.findUnique.mockResolvedValue(null);
dbMock.$transaction.mockImplementation(async (fn: any) => fn(tx));
await expect(
convertLeadToTenant({
leadId: "lead_unknown",
tenant: { name: "Acme", slug: "acme", inboundAddress: "acme@inbox.local" },
})
).rejects.toMatchObject({ name: "LeadNotFoundError" });
expect(LeadNotFoundError.name).toBe("LeadNotFoundError");
});
it("admin-override path stamps conversionPath=admin-override + actorId on LeadEvent", async () => {
const tx = buildTx();
dbMock.$transaction.mockImplementation(async (fn: any) => fn(tx));
publishMock.mockResolvedValue({ id: "outbox_3" });
await convertLeadToTenant({
leadId: "lead_1",
conversionPath: "admin-override",
actorId: "user_admin",
tenant: { name: "Acme", slug: "acme", inboundAddress: "acme@inbox.local" },
});
expect(tx.leadEvent.create).toHaveBeenCalledWith(
expect.objectContaining({
data: expect.objectContaining({ actorId: "user_admin" }),
})
);
expect(tx.tenantAcquisition.create).toHaveBeenCalledWith(
expect.objectContaining({
data: expect.objectContaining({ conversionPath: "admin-override" }),
})
);
});
it("respects LEAD_CONVERSION_ENABLED=false rollback flag", async () => {
const originalEnv = process.env.LEAD_CONVERSION_ENABLED;
process.env.LEAD_CONVERSION_ENABLED = "false";
try {
await expect(
convertLeadToTenant({
leadId: "lead_1",
tenant: { name: "Acme", slug: "acme", inboundAddress: "acme@inbox.local" },
})
).rejects.toThrow(/disabled/i);
} finally {
if (originalEnv === undefined) delete process.env.LEAD_CONVERSION_ENABLED;
else process.env.LEAD_CONVERSION_ENABLED = originalEnv;
}
});
});
describe("recordExistingTenantLeadConversion", () => {
let dbMock: any;
let publishMock: any;
let recordExistingTenantLeadConversion: typeof import("./convertLead.server").recordExistingTenantLeadConversion;
beforeEach(async () => {
vi.resetModules();
dbMock = (await import("~/utils/db.server")).db as any;
publishMock = (await import("@toolctrl/db/outbox")).publishOutboxEvent as any;
recordExistingTenantLeadConversion = (await import("./convertLead.server")).recordExistingTenantLeadConversion;
});
afterEach(() => {
vi.clearAllMocks();
});
function buildExistingTenantTx(leadOverrides: Record<string, unknown> = {}) {
const tx: any = {
lead: {
findUnique: vi.fn().mockResolvedValue({
id: "lead_1",
email: "test@example.com",
firstName: "Test",
lastName: "User",
company: "Acme",
source: "landing-pro",
utmSource: "google",
utmMedium: "cpc",
utmCampaign: "q2-launch",
utmTerm: null,
utmContent: null,
gclid: null,
fbclid: null,
referrer: null,
landingPage: "/pricing",
firstSeenAt: new Date("2026-05-10T00:00:00Z"),
convertedToTenantId: null,
...leadOverrides,
}),
update: vi.fn().mockResolvedValue({}),
},
leadEvent: {
create: vi.fn().mockResolvedValue({}),
},
tenantAcquisition: {
upsert: vi.fn().mockResolvedValue({}),
},
};
return tx;
}
it("links an already-created registration tenant to the lead attribution and outbox event", async () => {
const tx = buildExistingTenantTx();
dbMock.$transaction.mockImplementation(async (fn: any) => fn(tx));
publishMock.mockResolvedValue({ id: "outbox_4" });
const result = await recordExistingTenantLeadConversion({
leadId: "lead_1",
tenantId: "tenant_registered",
planId: "plan_pro",
conversionPath: "self-service",
});
expect(result).toMatchObject({ tenantId: "tenant_registered", leadId: "lead_1", alreadyConverted: false, outboxEventId: "outbox_4" });
expect(tx.lead.update).toHaveBeenCalledWith(
expect.objectContaining({
where: { id: "lead_1" },
data: expect.objectContaining({ status: "trial", convertedToTenantId: "tenant_registered" }),
})
);
expect(tx.tenantAcquisition.upsert).toHaveBeenCalledWith(
expect.objectContaining({
where: { tenantId: "tenant_registered" },
create: expect.objectContaining({ tenantId: "tenant_registered", leadId: "lead_1", conversionPath: "self-service" }),
update: expect.objectContaining({ leadId: "lead_1", conversionPath: "self-service" }),
})
);
expect(publishMock).toHaveBeenCalledWith(
tx,
expect.objectContaining({
tenantId: "tenant_registered",
type: "marketing.lead.convertedtotrial",
dispatchKey: "lead-convert:lead_1",
payload: expect.objectContaining({ leadId: "lead_1", tenantId: "tenant_registered", planId: "plan_pro" }),
})
);
});
it("is idempotent when the same tenant already owns the lead conversion", async () => {
const tx = buildExistingTenantTx({ convertedToTenantId: "tenant_registered" });
dbMock.$transaction.mockImplementation(async (fn: any) => fn(tx));
const result = await recordExistingTenantLeadConversion({ leadId: "lead_1", tenantId: "tenant_registered" });
expect(result.alreadyConverted).toBe(true);
expect(tx.lead.update).not.toHaveBeenCalled();
expect(tx.tenantAcquisition.upsert).not.toHaveBeenCalled();
expect(publishMock).not.toHaveBeenCalled();
});
it("rejects a lead already converted to a different tenant", async () => {
const tx = buildExistingTenantTx({ convertedToTenantId: "tenant_other" });
dbMock.$transaction.mockImplementation(async (fn: any) => fn(tx));
await expect(recordExistingTenantLeadConversion({ leadId: "lead_1", tenantId: "tenant_registered" })).rejects.toMatchObject({
name: "LeadAlreadyConvertedError",
convertedToTenantId: "tenant_other",
});
expect(LeadAlreadyConvertedError.name).toBe("LeadAlreadyConvertedError");
expect(tx.lead.update).not.toHaveBeenCalled();
});
});
@@ -0,0 +1,171 @@
/**
* Signed-Lead-Token helper for the Marketing-Funnel Phase 2 self-service
* conversion flow (Phase 05 #79).
*
* The operator (or an automated nurture email) sends a Lead a deep-link
* such as `/signup?leadId=<id>&token=<token>&plan=<planId>`. The signup
* loader verifies the token before pre-filling the registration form so:
*
* - Random visitors can't enumerate `?leadId=…` URLs to extract PII
* from the prefilled form fields.
* - Tokens expire after 7 days by default — captured leads have a
* reasonable conversion window without leaving long-lived bearer
* tokens floating around.
* - Lead-row identity is bound to the token: tampering with the
* leadId / plan / expiry payload invalidates the signature.
*
* The token format is `v1.<base64url(payload)>.<base64url(hmac-sha256)>`.
* `LEAD_CONVERSION_SECRET` (env, min-32-byte hex) is the HMAC key. When
* the env is missing every call fails-closed (`verifyLeadToken` returns
* `null`, `signLeadToken` throws) so misconfiguration cannot silently
* accept unsigned URLs.
*/
import { createHmac, timingSafeEqual } from "node:crypto";
export interface LeadTokenPayload {
/** Lead.id this token is bound to. */
leadId: string;
/** Optional pre-selected SubscriptionProduct.id surfaced on the signup form. */
planId?: string | null;
/** Issued-at (unix seconds). */
iat: number;
/** Expires-at (unix seconds). */
exp: number;
}
export interface SignLeadTokenInput {
leadId: string;
planId?: string | null;
/** Token lifetime in days. Capped at 30 to bound exposure. Default 7. */
expiresInDays?: number;
/** Override system clock (test seam). */
now?: () => Date;
/** Override env lookup (test seam). */
secret?: string;
}
export interface VerifyLeadTokenOptions {
now?: () => Date;
secret?: string;
}
export class LeadTokenSecretMissingError extends Error {
override readonly name = "LeadTokenSecretMissingError";
constructor() {
super("LEAD_CONVERSION_SECRET env var is not set; cannot sign or verify lead tokens.");
}
}
const TOKEN_VERSION = "v1";
const MAX_TTL_DAYS = 30;
const DEFAULT_TTL_DAYS = 7;
const MIN_SECRET_BYTES = 32;
function getSecret(override?: string): Buffer {
const raw = override ?? process.env.LEAD_CONVERSION_SECRET;
if (!raw || raw.length === 0) {
throw new LeadTokenSecretMissingError();
}
// Accept hex-encoded or raw secrets. We don't enforce hex specifically
// (operators may roll arbitrary base64) but we *do* enforce a minimum
// length so a weak secret rejects fail-fast.
if (raw.length < MIN_SECRET_BYTES) {
throw new LeadTokenSecretMissingError();
}
return Buffer.from(raw, "utf8");
}
function base64UrlEncode(input: Buffer | string): string {
const buf = Buffer.isBuffer(input) ? input : Buffer.from(input, "utf8");
return buf.toString("base64url");
}
function base64UrlDecode(input: string): Buffer | null {
// base64url accepts only [A-Za-z0-9_-]
if (!/^[A-Za-z0-9_-]+$/u.test(input)) return null;
try {
return Buffer.from(input, "base64url");
} catch {
return null;
}
}
function nowSec(now?: () => Date): number {
return Math.floor((now ? now() : new Date()).getTime() / 1000);
}
/**
* Sign a lead-token. Returns the `v1.<payload>.<sig>` string. Throws
* {@link LeadTokenSecretMissingError} when `LEAD_CONVERSION_SECRET` is
* unset or shorter than 32 bytes — callers MUST handle that case so the
* conversion-disabled rollback path stays usable.
*/
export function signLeadToken(input: SignLeadTokenInput): string {
if (!input.leadId || typeof input.leadId !== "string") {
throw new TypeError("signLeadToken: leadId required");
}
const secret = getSecret(input.secret);
const ttlDays = clampTtl(input.expiresInDays);
const iat = nowSec(input.now);
const exp = iat + ttlDays * 24 * 60 * 60;
const payload: LeadTokenPayload = {
leadId: input.leadId,
planId: input.planId ?? null,
iat,
exp,
};
const payloadStr = JSON.stringify(payload);
const payloadB64 = base64UrlEncode(payloadStr);
const sig = createHmac("sha256", secret).update(`${TOKEN_VERSION}.${payloadB64}`).digest();
return `${TOKEN_VERSION}.${payloadB64}.${base64UrlEncode(sig)}`;
}
function clampTtl(days: number | undefined): number {
if (!days || !Number.isFinite(days) || days <= 0) return DEFAULT_TTL_DAYS;
return Math.min(Math.floor(days), MAX_TTL_DAYS);
}
/**
* Verify a lead-token. Returns the decoded payload when the signature
* matches AND the token has not expired. Returns `null` otherwise.
* NEVER throws on bad input — fail-closed silently so route loaders can
* fall back to the plain-signup form without leaking which check failed.
*/
export function verifyLeadToken(token: string | null | undefined, options: VerifyLeadTokenOptions = {}): LeadTokenPayload | null {
if (!token || typeof token !== "string") return null;
const parts = token.split(".");
if (parts.length !== 3) return null;
const [version, payloadB64, sigB64] = parts;
if (version !== TOKEN_VERSION) return null;
let secret: Buffer;
try {
secret = getSecret(options.secret);
} catch {
return null;
}
const expectedSig = createHmac("sha256", secret).update(`${version}.${payloadB64}`).digest();
const actualSig = base64UrlDecode(sigB64);
if (!actualSig || actualSig.length !== expectedSig.length) return null;
if (!timingSafeEqual(actualSig, expectedSig)) return null;
const payloadBuf = base64UrlDecode(payloadB64);
if (!payloadBuf) return null;
let parsed: unknown;
try {
parsed = JSON.parse(payloadBuf.toString("utf8"));
} catch {
return null;
}
if (!parsed || typeof parsed !== "object") return null;
const rec = parsed as Record<string, unknown>;
if (typeof rec.leadId !== "string" || rec.leadId.length === 0) return null;
if (typeof rec.iat !== "number" || typeof rec.exp !== "number") return null;
if (rec.exp <= nowSec(options.now)) return null;
return {
leadId: rec.leadId,
planId: typeof rec.planId === "string" ? rec.planId : null,
iat: rec.iat,
exp: rec.exp,
};
}
@@ -0,0 +1,105 @@
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import { LeadTokenSecretMissingError, signLeadToken, verifyLeadToken } from "./leadToken.server";
const TEST_SECRET = "x".repeat(48);
describe("leadToken", () => {
const originalEnv = process.env.LEAD_CONVERSION_SECRET;
beforeEach(() => {
process.env.LEAD_CONVERSION_SECRET = TEST_SECRET;
});
afterEach(() => {
if (originalEnv === undefined) delete process.env.LEAD_CONVERSION_SECRET;
else process.env.LEAD_CONVERSION_SECRET = originalEnv;
});
it("sign + verify roundtrip returns same leadId and planId", () => {
const tok = signLeadToken({ leadId: "lead_1", planId: "plan_pro" });
const decoded = verifyLeadToken(tok);
expect(decoded).toMatchObject({ leadId: "lead_1", planId: "plan_pro" });
expect(decoded?.exp).toBeGreaterThan(decoded?.iat ?? 0);
});
it("defaults to 7-day TTL", () => {
const fixedNow = () => new Date("2026-05-17T00:00:00Z");
const tok = signLeadToken({ leadId: "lead_1", now: fixedNow });
const decoded = verifyLeadToken(tok, { now: fixedNow });
expect(decoded).not.toBeNull();
expect((decoded!.exp - decoded!.iat) / (24 * 60 * 60)).toBeCloseTo(7);
});
it("clamps TTL to max 30 days", () => {
const fixedNow = () => new Date("2026-05-17T00:00:00Z");
const tok = signLeadToken({ leadId: "lead_1", expiresInDays: 9999, now: fixedNow });
const decoded = verifyLeadToken(tok, { now: fixedNow });
expect(decoded).not.toBeNull();
expect((decoded!.exp - decoded!.iat) / (24 * 60 * 60)).toBeLessThanOrEqual(30);
});
it("returns null for expired tokens", () => {
const past = () => new Date("2026-01-01T00:00:00Z");
const future = () => new Date("2026-12-31T00:00:00Z");
const tok = signLeadToken({ leadId: "lead_1", expiresInDays: 1, now: past });
expect(verifyLeadToken(tok, { now: future })).toBeNull();
});
it("returns null for tampered payload", () => {
const tok = signLeadToken({ leadId: "lead_1" });
const [v, p, s] = tok.split(".");
// Re-encode with a different leadId — signature should no longer match.
const tampered = Buffer.from(JSON.stringify({ leadId: "lead_hijack", iat: 0, exp: 2 ** 31 - 1 }), "utf8").toString("base64url");
expect(verifyLeadToken(`${v}.${tampered}.${s}`)).toBeNull();
expect(p).toBeDefined();
});
it("returns null for tampered signature", () => {
const tok = signLeadToken({ leadId: "lead_1" });
const [v, p] = tok.split(".");
const badSig = Buffer.alloc(32, 0).toString("base64url");
expect(verifyLeadToken(`${v}.${p}.${badSig}`)).toBeNull();
});
it("returns null when version prefix is wrong", () => {
const tok = signLeadToken({ leadId: "lead_1" });
const [, p, s] = tok.split(".");
expect(verifyLeadToken(`v2.${p}.${s}`)).toBeNull();
});
it("returns null for malformed tokens", () => {
expect(verifyLeadToken("")).toBeNull();
expect(verifyLeadToken(null)).toBeNull();
expect(verifyLeadToken(undefined)).toBeNull();
expect(verifyLeadToken("not.a.token.extrapart")).toBeNull();
expect(verifyLeadToken("v1.@@@.bad")).toBeNull();
});
it("throws when LEAD_CONVERSION_SECRET is unset", () => {
delete process.env.LEAD_CONVERSION_SECRET;
expect(() => signLeadToken({ leadId: "lead_1" })).toThrow(LeadTokenSecretMissingError);
});
it("throws when LEAD_CONVERSION_SECRET is too short", () => {
process.env.LEAD_CONVERSION_SECRET = "too-short";
expect(() => signLeadToken({ leadId: "lead_1" })).toThrow(LeadTokenSecretMissingError);
});
it("verify returns null when secret env is missing", () => {
const tok = signLeadToken({ leadId: "lead_1", secret: TEST_SECRET });
delete process.env.LEAD_CONVERSION_SECRET;
expect(verifyLeadToken(tok)).toBeNull();
});
it("rejects empty leadId on sign", () => {
expect(() => signLeadToken({ leadId: "" })).toThrow(TypeError);
});
it("rotation: token signed with secret-A fails verify under secret-B", () => {
const secretA = "a".repeat(48);
const secretB = "b".repeat(48);
const tok = signLeadToken({ leadId: "lead_1", secret: secretA });
expect(verifyLeadToken(tok, { secret: secretB })).toBeNull();
expect(verifyLeadToken(tok, { secret: secretA })?.leadId).toBe("lead_1");
});
});
@@ -0,0 +1,229 @@
/**
* Server-side Prisma helpers for the admin lead inbox (Phase 05 #78).
* Keeps loader/action handlers free of raw query plumbing.
*/
import type { LeadStatus } from "@toolctrl/db/prisma-browser";
import { db } from "~/utils/db.server";
export type LeadFilter = {
status?: LeadStatus;
source?: string;
search?: string;
page?: number;
pageSize?: number;
};
export interface LeadListItem {
id: string;
email: string;
firstName: string | null;
lastName: string | null;
company: string | null;
source: string | null;
status: LeadStatus;
utmSource: string | null;
utmCampaign: string | null;
createdAt: Date;
lastTouchAt: Date;
}
export interface LeadListResult {
items: LeadListItem[];
total: number;
page: number;
pageSize: number;
}
const LEAD_EXPORT_MAX = 50_000;
export interface LeadExportRow {
id: string;
email: string;
firstName: string | null;
lastName: string | null;
phone: string | null;
company: string | null;
source: string | null;
status: LeadStatus;
utmSource: string | null;
utmMedium: string | null;
utmCampaign: string | null;
utmTerm: string | null;
utmContent: string | null;
gclid: string | null;
fbclid: string | null;
referrer: string | null;
landingPage: string | null;
score: number;
createdAt: Date;
lastTouchAt: Date;
}
function buildLeadWhere(filter: Pick<LeadFilter, "status" | "source" | "search">): Record<string, unknown> {
const where: Record<string, unknown> = {};
if (filter.status) where.status = filter.status;
if (filter.source) where.source = filter.source;
if (filter.search) {
const q = filter.search.trim();
if (q.length > 0) {
where.OR = [
{ email: { contains: q, mode: "insensitive" } },
{ firstName: { contains: q, mode: "insensitive" } },
{ lastName: { contains: q, mode: "insensitive" } },
{ company: { contains: q, mode: "insensitive" } },
];
}
}
return where;
}
export async function listLeadsForExport(filter: Pick<LeadFilter, "status" | "source" | "search"> = {}): Promise<LeadExportRow[]> {
const where = buildLeadWhere(filter);
return db.lead.findMany({
where,
orderBy: { createdAt: "desc" },
take: LEAD_EXPORT_MAX,
select: {
id: true,
email: true,
firstName: true,
lastName: true,
phone: true,
company: true,
source: true,
status: true,
utmSource: true,
utmMedium: true,
utmCampaign: true,
utmTerm: true,
utmContent: true,
gclid: true,
fbclid: true,
referrer: true,
landingPage: true,
score: true,
createdAt: true,
lastTouchAt: true,
},
});
}
export { LEAD_EXPORT_MAX };
export async function listLeads(filter: LeadFilter = {}): Promise<LeadListResult> {
const page = Math.max(1, filter.page ?? 1);
const pageSize = Math.min(100, Math.max(5, filter.pageSize ?? 25));
const where: Record<string, unknown> = {};
if (filter.status) where.status = filter.status;
if (filter.source) where.source = filter.source;
if (filter.search) {
const q = filter.search.trim();
if (q.length > 0) {
where.OR = [
{ email: { contains: q, mode: "insensitive" } },
{ firstName: { contains: q, mode: "insensitive" } },
{ lastName: { contains: q, mode: "insensitive" } },
{ company: { contains: q, mode: "insensitive" } },
];
}
}
const [items, total] = await Promise.all([
db.lead.findMany({
where,
orderBy: { createdAt: "desc" },
skip: (page - 1) * pageSize,
take: pageSize,
select: {
id: true,
email: true,
firstName: true,
lastName: true,
company: true,
source: true,
status: true,
utmSource: true,
utmCampaign: true,
createdAt: true,
lastTouchAt: true,
},
}),
db.lead.count({ where }),
]);
return { items, total, page, pageSize };
}
export async function getLead(id: string) {
return db.lead.findUnique({
where: { id },
include: {
events: {
orderBy: { createdAt: "desc" },
take: 100,
},
},
});
}
export async function appendLeadEvent(
leadId: string,
type: string,
payload: Record<string, unknown>,
actorId?: string | null,
): Promise<void> {
await db.leadEvent.create({
data: {
leadId,
type,
actorId: actorId ?? null,
payload: payload as object,
},
});
}
export async function updateLeadStatus(
leadId: string,
next: LeadStatus,
actorId: string | null,
): Promise<void> {
const current = await db.lead.findUnique({ where: { id: leadId }, select: { status: true } });
if (!current) return;
if (current.status === next) return;
await db.$transaction([
db.lead.update({ where: { id: leadId }, data: { status: next } }),
db.leadEvent.create({
data: {
leadId,
type: "status-changed",
actorId,
payload: { from: current.status, to: next } as object,
},
}),
]);
}
export async function appendNote(leadId: string, body: string, actorId: string | null): Promise<void> {
const lead = await db.lead.findUnique({ where: { id: leadId }, select: { notes: true } });
if (!lead) return;
const previous = (lead.notes ?? null) as Record<string, unknown> | null;
const updated = {
body,
updatedAt: new Date().toISOString(),
history: [
...(((previous?.history as unknown[]) ?? []).slice(-19)),
{ body: (previous?.body as string | undefined) ?? "", at: (previous?.updatedAt as string | undefined) ?? null },
],
};
await db.$transaction([
db.lead.update({ where: { id: leadId }, data: { notes: updated as object } }),
db.leadEvent.create({
data: {
leadId,
type: "note-added",
actorId,
payload: { length: body.length } as object,
},
}),
]);
}
@@ -0,0 +1,112 @@
import { describe, expect, it } from "vitest";
import { LEAD_CSV_COLUMNS, escapeCsvValue, leadsCsvFilename, serializeLeadsCsv } from "./leadsCsv";
describe("escapeCsvValue", () => {
it("returns an empty string for null and undefined", () => {
expect(escapeCsvValue(null)).toBe("");
expect(escapeCsvValue(undefined)).toBe("");
});
it("renders Date as an ISO 8601 string", () => {
const value = new Date("2026-05-20T13:45:00.000Z");
expect(escapeCsvValue(value)).toBe("2026-05-20T13:45:00.000Z");
});
it("does not quote values without separators or quotes", () => {
expect(escapeCsvValue("plain")).toBe("plain");
expect(escapeCsvValue(42)).toBe("42");
});
it("quotes and doubles inner quotes for values containing commas, quotes, or newlines", () => {
expect(escapeCsvValue('a,b')).toBe('"a,b"');
expect(escapeCsvValue('he said "hi"')).toBe('"he said ""hi"""');
expect(escapeCsvValue("line1\nline2")).toBe('"line1\nline2"');
expect(escapeCsvValue("line1\r\nline2")).toBe('"line1\r\nline2"');
});
});
describe("serializeLeadsCsv", () => {
it("emits exactly the documented header row, even for an empty input", () => {
expect(serializeLeadsCsv([])).toBe(`${LEAD_CSV_COLUMNS.join(",")}\n`);
});
it("aligns each row's columns with the header order", () => {
const csv = serializeLeadsCsv([
{
id: "lead_1",
email: "alice@example.com",
firstName: "Alice",
lastName: null,
phone: null,
company: "Acme",
source: "landing-pro",
status: "qualified",
utmSource: "google",
utmMedium: "cpc",
utmCampaign: "spring",
utmTerm: null,
utmContent: null,
gclid: null,
fbclid: null,
referrer: null,
landingPage: "/pricing",
score: 5,
createdAt: new Date("2026-05-20T09:00:00.000Z"),
lastTouchAt: new Date("2026-05-20T09:15:00.000Z"),
},
]);
const lines = csv.split("\n");
expect(lines[0]).toBe(LEAD_CSV_COLUMNS.join(","));
expect(lines[1]).toBe(
[
"lead_1",
"alice@example.com",
"Alice",
"",
"",
"Acme",
"landing-pro",
"qualified",
"google",
"cpc",
"spring",
"",
"",
"",
"",
"",
"/pricing",
"5",
"2026-05-20T09:00:00.000Z",
"2026-05-20T09:15:00.000Z",
].join(","),
);
expect(lines.at(-1)).toBe("");
});
it("escapes commas, quotes, and newlines inside string fields", () => {
const csv = serializeLeadsCsv([
{ id: "lead_2", email: 'quoted"name@example.com', firstName: "Comma, Name", lastName: "Multi\nLine" },
]);
expect(csv).toContain('"quoted""name@example.com"');
expect(csv).toContain('"Comma, Name"');
expect(csv).toContain('"Multi\nLine"');
});
it("treats absent keys identically to nulls", () => {
const csv = serializeLeadsCsv([{ id: "lead_3", email: "x@y.z" }]);
const rowLine = csv.split("\n")[1] ?? "";
const cells = rowLine.split(",");
expect(cells.length).toBe(LEAD_CSV_COLUMNS.length);
expect(cells[0]).toBe("lead_3");
expect(cells[1]).toBe("x@y.z");
for (let i = 2; i < cells.length; i++) expect(cells[i]).toBe("");
});
});
describe("leadsCsvFilename", () => {
it("emits UTC-stamped YYYYMMDD suffix", () => {
expect(leadsCsvFilename(new Date("2026-05-20T23:00:00.000Z"))).toBe("marketing-leads-20260520.csv");
expect(leadsCsvFilename(new Date("2026-01-05T00:00:00.000Z"))).toBe("marketing-leads-20260105.csv");
});
});
@@ -0,0 +1,61 @@
/**
* Pure CSV serializer for the admin marketing-leads inbox export
* (Phase 05 #78, admin-UI CSV download).
*
* Column ordering and CSV-escaping rules mirror `packages/cli/src/commands/
* leads/export.ts` so the admin-UI download and the `toolctrl-cli leads
* export` operator-side dump are byte-compatible.
*/
export const LEAD_CSV_COLUMNS = [
"id",
"email",
"firstName",
"lastName",
"phone",
"company",
"source",
"status",
"utmSource",
"utmMedium",
"utmCampaign",
"utmTerm",
"utmContent",
"gclid",
"fbclid",
"referrer",
"landingPage",
"score",
"createdAt",
"lastTouchAt",
] as const;
export type LeadCsvColumn = (typeof LEAD_CSV_COLUMNS)[number];
export type LeadCsvRow = {
readonly [K in LeadCsvColumn]?: unknown;
};
export function escapeCsvValue(value: unknown): string {
if (value === null || value === undefined) return "";
const raw = value instanceof Date ? value.toISOString() : String(value);
if (/[",\n\r]/.test(raw)) {
return `"${raw.replace(/"/g, '""')}"`;
}
return raw;
}
export function serializeLeadsCsv(rows: ReadonlyArray<LeadCsvRow>): string {
const lines: string[] = [LEAD_CSV_COLUMNS.join(",")];
for (const row of rows) {
lines.push(LEAD_CSV_COLUMNS.map((col) => escapeCsvValue(row[col])).join(","));
}
return `${lines.join("\n")}\n`;
}
export function leadsCsvFilename(date: Date = new Date()): string {
const yyyy = date.getUTCFullYear();
const mm = String(date.getUTCMonth() + 1).padStart(2, "0");
const dd = String(date.getUTCDate()).padStart(2, "0");
return `marketing-leads-${yyyy}${mm}${dd}.csv`;
}
@@ -0,0 +1,185 @@
/**
* Server-side helpers for `MarketingIntegration` (Phase 05 #79).
*
* `configJson` stores the raw object — but every string field whose key
* matches an entry in {@link SENSITIVE_KEYS} is encrypted at rest with
* AES-256-GCM via the shared CryptoApi helper. Round-trip decryption
* happens on read so call-sites operate on plain configs.
*
* The admin UI never re-displays decrypted secrets; on edit the field
* is masked + replaced only when the operator types a new value.
*/
import CryptoApi from "~/utils/api/.server/CryptoApi";
import { db } from "~/utils/db.server";
import { Prisma } from "@toolctrl/db/prisma-browser";
export type MarketingIntegrationType = "slack" | "discord" | "mailchimp" | "hubspot" | "brevo" | "webhook";
export interface MarketingIntegrationRecord {
id: string;
type: MarketingIntegrationType;
name: string;
enabled: boolean;
triggerEvents: string[];
config: Record<string, unknown>;
lastDeliveredAt: Date | null;
lastError: string | null;
createdAt: Date;
updatedAt: Date;
}
const SENSITIVE_KEYS = new Set([
"webhookUrl",
"apiKey",
"accessToken",
"signingSecret",
]);
const CRYPTO_TAG = "enc:";
function encryptSensitive(config: Record<string, unknown>): Record<string, unknown> {
const out: Record<string, unknown> = {};
for (const [k, v] of Object.entries(config)) {
if (SENSITIVE_KEYS.has(k) && typeof v === "string" && v.length > 0 && !v.startsWith(CRYPTO_TAG)) {
out[k] = `${CRYPTO_TAG}${CryptoApi.encrypt(v)}`;
} else {
out[k] = v;
}
}
return out;
}
function decryptSensitive(config: Record<string, unknown>): Record<string, unknown> {
const out: Record<string, unknown> = {};
for (const [k, v] of Object.entries(config)) {
if (SENSITIVE_KEYS.has(k) && typeof v === "string" && v.startsWith(CRYPTO_TAG)) {
try {
out[k] = CryptoApi.decrypt(v.slice(CRYPTO_TAG.length));
} catch {
out[k] = "";
}
} else {
out[k] = v;
}
}
return out;
}
/**
* Mask secret values for admin display. Returns the input config with
* every {@link SENSITIVE_KEYS} value replaced by `***`.
*/
export function maskConfig(config: Record<string, unknown>): Record<string, unknown> {
const out: Record<string, unknown> = {};
for (const [k, v] of Object.entries(config)) {
out[k] = SENSITIVE_KEYS.has(k) && typeof v === "string" && v.length > 0 ? "***" : v;
}
return out;
}
export async function listMarketingIntegrations(): Promise<MarketingIntegrationRecord[]> {
const rows = await db.marketingIntegration.findMany({
orderBy: { createdAt: "desc" },
});
return rows.map((r) => ({
id: r.id,
type: r.type as MarketingIntegrationType,
name: r.name,
enabled: r.enabled,
triggerEvents: r.triggerEvents,
config: decryptSensitive(asObject(r.configJson)),
lastDeliveredAt: r.lastDeliveredAt,
lastError: r.lastError,
createdAt: r.createdAt,
updatedAt: r.updatedAt,
}));
}
export async function getMarketingIntegrationDecrypted(id: string): Promise<MarketingIntegrationRecord | null> {
const r = await db.marketingIntegration.findUnique({ where: { id } });
if (!r) return null;
return {
id: r.id,
type: r.type as MarketingIntegrationType,
name: r.name,
enabled: r.enabled,
triggerEvents: r.triggerEvents,
config: decryptSensitive(asObject(r.configJson)),
lastDeliveredAt: r.lastDeliveredAt,
lastError: r.lastError,
createdAt: r.createdAt,
updatedAt: r.updatedAt,
};
}
export interface CreateMarketingIntegrationInput {
type: MarketingIntegrationType;
name: string;
enabled?: boolean;
triggerEvents: string[];
config: Record<string, unknown>;
}
export async function createMarketingIntegration(input: CreateMarketingIntegrationInput): Promise<string> {
const row = await db.marketingIntegration.create({
data: {
type: input.type,
name: input.name,
enabled: input.enabled ?? true,
triggerEvents: input.triggerEvents,
configJson: encryptSensitive(input.config) as Prisma.InputJsonValue,
},
select: { id: true },
});
return row.id;
}
export interface UpdateMarketingIntegrationInput {
name?: string;
enabled?: boolean;
triggerEvents?: string[];
/** Partial config patch — only keys present overwrite. */
config?: Record<string, unknown>;
}
export async function updateMarketingIntegration(id: string, input: UpdateMarketingIntegrationInput): Promise<void> {
const data: Prisma.MarketingIntegrationUpdateInput = {};
if (input.name !== undefined) data.name = input.name;
if (input.enabled !== undefined) data.enabled = input.enabled;
if (input.triggerEvents !== undefined) data.triggerEvents = input.triggerEvents;
if (input.config !== undefined) {
// Merge existing config with patch then re-encrypt.
const existing = await db.marketingIntegration.findUnique({ where: { id }, select: { configJson: true } });
if (existing) {
const decrypted = decryptSensitive(asObject(existing.configJson));
const merged = { ...decrypted, ...input.config };
data.configJson = encryptSensitive(merged) as Prisma.InputJsonValue;
} else {
data.configJson = encryptSensitive(input.config) as Prisma.InputJsonValue;
}
}
await db.marketingIntegration.update({ where: { id }, data });
}
export async function deleteMarketingIntegration(id: string): Promise<void> {
await db.marketingIntegration.delete({ where: { id } });
}
export async function recordIntegrationDelivery(
id: string,
result: { ok: boolean; errorTag?: string | null }
): Promise<void> {
await db.marketingIntegration.update({
where: { id },
data: {
lastDeliveredAt: result.ok ? new Date() : undefined,
lastError: result.ok ? null : result.errorTag ?? "unknown_error",
},
});
}
function asObject(v: unknown): Record<string, unknown> {
if (v && typeof v === "object" && !Array.isArray(v)) return v as Record<string, unknown>;
return {};
}
@@ -0,0 +1,48 @@
import { describe, expect, it } from "vitest";
import { matchAllowedOrigin, parseAllowedOrigins } from "./originCheck";
describe("parseAllowedOrigins", () => {
it("splits CSV and trims whitespace", () => {
expect(parseAllowedOrigins("https://a.example, https://b.example ,https://c.example")).toEqual([
"https://a.example",
"https://b.example",
"https://c.example",
]);
});
it("returns [] for empty / null / undefined", () => {
expect(parseAllowedOrigins("")).toEqual([]);
expect(parseAllowedOrigins(null)).toEqual([]);
expect(parseAllowedOrigins(undefined)).toEqual([]);
});
it("ignores empty entries from trailing commas", () => {
expect(parseAllowedOrigins(",https://a.example,,")).toEqual(["https://a.example"]);
});
});
describe("matchAllowedOrigin", () => {
it("rejects null origin", () => {
expect(matchAllowedOrigin(null, ["https://example.com"])).toBe(false);
});
it("rejects when allowlist is empty (fail-closed)", () => {
expect(matchAllowedOrigin("https://example.com", [])).toBe(false);
});
it("rejects malformed origin", () => {
expect(matchAllowedOrigin("not-a-url", ["https://example.com"])).toBe(false);
});
it("matches exact origin", () => {
expect(matchAllowedOrigin("https://example.com", ["https://example.com"])).toBe(true);
});
it("ignores path/query on incoming origin", () => {
expect(matchAllowedOrigin("https://example.com/page?x=1", ["https://example.com"])).toBe(true);
});
it("matches wildcard subdomain", () => {
expect(matchAllowedOrigin("https://app.example.com", ["https://*.example.com"])).toBe(true);
expect(matchAllowedOrigin("https://api.staging.example.com", ["https://*.example.com"])).toBe(false);
});
it("rejects different protocol", () => {
expect(matchAllowedOrigin("http://example.com", ["https://example.com"])).toBe(false);
});
it("rejects different host", () => {
expect(matchAllowedOrigin("https://attacker.com", ["https://example.com"])).toBe(false);
});
});
@@ -0,0 +1,70 @@
/**
* CORS-allowlist matcher for the marketing-funnel capture endpoint (Phase 05 #78).
*
* The endpoint is intentionally public so external landing-pages can ingest
* leads, but the Origin header is matched against `MARKETING_ALLOWED_ORIGINS`
* (comma-separated env list). Wildcards are supported via a single leading `*`
* in the host (e.g. `https://*.toolctrl.de`).
*
* Server-to-server bots can spoof Origin — this layer is one of three (origin
* allowlist, rate-limit, optional Turnstile). It does NOT replace rate-limiting.
*/
export function parseAllowedOrigins(raw: string | undefined | null): string[] {
if (!raw) return [];
return raw
.split(",")
.map((s) => s.trim())
.filter((s) => s.length > 0);
}
/**
* Normalise an origin string to `https://host` (no trailing slash, no path).
* Returns null when the input is not a valid origin URL.
*/
function normaliseOrigin(value: string | null | undefined): string | null {
if (!value) return null;
try {
const u = new URL(value);
return `${u.protocol}//${u.host}`;
} catch {
return null;
}
}
/**
* Match the request `Origin` header against an allowlist with wildcard support.
*
* - Empty allowlist + non-null origin → reject (fail-closed default).
* - Empty allowlist + null/missing origin → reject (server-to-server bot).
* - Wildcard entries match the host portion only (e.g. `https://*.example.com`
* matches `https://app.example.com` but not `https://example.com`).
*/
export function matchAllowedOrigin(origin: string | null | undefined, allowed: readonly string[]): boolean {
const normalised = normaliseOrigin(origin);
if (!normalised) return false;
if (allowed.length === 0) return false;
for (const entry of allowed) {
const entryNorm = normaliseOrigin(entry);
if (!entryNorm) {
// Allow bare host wildcard like `https://*.example.com` which is not a
// valid URL because of the literal `*`.
if (entry.includes("*")) {
if (wildcardMatch(entry, normalised)) return true;
}
continue;
}
if (entryNorm === normalised) return true;
if (entry.includes("*") && wildcardMatch(entry, normalised)) return true;
}
return false;
}
function wildcardMatch(pattern: string, candidate: string): boolean {
// Convert wildcard pattern (`https://*.example.com`) to anchored regex.
// Only `*` is special; everything else is escaped.
const escaped = pattern.replace(/[.+?^${}()|[\]\\]/g, "\\$&").replace(/\*/g, "[a-zA-Z0-9-]+");
const re = new RegExp(`^${escaped}$`);
return re.test(candidate);
}