452 lines
17 KiB
TypeScript
452 lines
17 KiB
TypeScript
import { randomUUID } from "node:crypto";
|
|
|
|
import { Prisma } from "../generated/prisma/client/client.js";
|
|
import type { Blacklist, IpAddress, IpAddressLog, Registration } from "./prisma-browser.js";
|
|
|
|
import { getDbClient, type DbClient } from "./client.server.js";
|
|
|
|
type CapabilityClient = Pick<DbClient, "$queryRaw">;
|
|
|
|
export type RegistrationSummary = Pick<Registration, "id" | "createdTenantId">;
|
|
|
|
export type RegistrationBillingPreference = {
|
|
readonly selectedSubscriptionPriceId: string;
|
|
readonly selectedOfficeSeatQuantity: number;
|
|
readonly selectedFieldSeatQuantity: number;
|
|
};
|
|
|
|
export type RegistrationCreateInput = Pick<
|
|
Registration,
|
|
| "email"
|
|
| "firstName"
|
|
| "lastName"
|
|
| "token"
|
|
| "company"
|
|
| "selectedSubscriptionPriceId"
|
|
| "selectedOfficeSeatQuantity"
|
|
| "selectedFieldSeatQuantity"
|
|
| "leadConversionLeadId"
|
|
| "leadConversionToken"
|
|
| "leadConversionPlanId"
|
|
| "ipAddress"
|
|
| "slug"
|
|
>;
|
|
|
|
export class RegistrationCreateConflictError extends Error {
|
|
constructor() {
|
|
super("Registration create capability did not create or rotate a row");
|
|
this.name = "RegistrationCreateConflictError";
|
|
}
|
|
}
|
|
|
|
export type RegistrationPatch = { createdTenantId: string; token?: never } | { token: string; createdTenantId?: never };
|
|
|
|
export type MarketingLeadCaptureCapabilityInput = {
|
|
email: string;
|
|
firstName?: string | null;
|
|
lastName?: string | null;
|
|
phone?: string | null;
|
|
company?: string | null;
|
|
source?: string | null;
|
|
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;
|
|
lastIpHash?: string | null;
|
|
userAgent?: string | null;
|
|
eventPayload: Record<string, unknown>;
|
|
};
|
|
|
|
export type SignedLeadConversionSummary = {
|
|
leadId: string;
|
|
email: string;
|
|
firstName: string | null;
|
|
lastName: string | null;
|
|
company: string | null;
|
|
convertedToTenantId: string | null;
|
|
};
|
|
|
|
export type SelfServiceLeadConversionCapabilityInput = {
|
|
leadId: string;
|
|
tenantId: string;
|
|
userId: string;
|
|
expectedEmail: string;
|
|
planId?: string | null;
|
|
};
|
|
|
|
export type SelfServiceLeadConversionSummary = {
|
|
leadId: string;
|
|
convertedToTenantId: string;
|
|
alreadyConverted: boolean;
|
|
email: string;
|
|
firstName: string | null;
|
|
lastName: string | null;
|
|
company: string | null;
|
|
source: string | null;
|
|
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;
|
|
firstSeenAt: string;
|
|
convertedAt: string | null;
|
|
};
|
|
|
|
export async function findRegistrationSummaryByEmail(email: string, client: CapabilityClient = getDbClient()): Promise<RegistrationSummary | null> {
|
|
const normalized = normalizeEmail(email);
|
|
if (!normalized) return null;
|
|
const rows = await client.$queryRaw<Array<{ id: string; created_tenant_id: string | null }>>(
|
|
Prisma.sql`SELECT id, created_tenant_id FROM public.hivegrid_find_registration_by_email(${normalized})`
|
|
);
|
|
const row = readSingle(rows, "registration email");
|
|
return row ? { id: row.id, createdTenantId: row.created_tenant_id } : null;
|
|
}
|
|
|
|
export async function findRegistrationByTokenCapability(token: string, client: CapabilityClient = getDbClient()): Promise<Registration | null> {
|
|
const normalized = normalizeCapability(token);
|
|
if (!normalized) return null;
|
|
const rows = await client.$queryRaw<Registration[]>(Prisma.sql`SELECT * FROM public.hivegrid_find_registration_by_token(${normalized})`);
|
|
return readSingle(rows, "registration token");
|
|
}
|
|
|
|
/**
|
|
* Returns only the consumed signup preference for the active tenant member.
|
|
* PostgreSQL independently binds both ids to the transaction-local RLS context
|
|
* and never exposes the registration's pre-auth identity or token fields.
|
|
*/
|
|
export async function findRegistrationBillingPreferenceCapability(
|
|
tenantId: string,
|
|
userId: string,
|
|
client: CapabilityClient = getDbClient()
|
|
): Promise<RegistrationBillingPreference | null> {
|
|
const normalizedTenantId = normalizeIdentifier(tenantId);
|
|
const normalizedUserId = normalizeIdentifier(userId);
|
|
if (!normalizedTenantId || !normalizedUserId) return null;
|
|
const rows = await client.$queryRaw<
|
|
Array<{
|
|
selected_subscription_price_id: string;
|
|
selected_office_seat_quantity: number;
|
|
selected_field_seat_quantity: number;
|
|
}>
|
|
>(Prisma.sql`SELECT * FROM public.hivegrid_find_registration_billing_preference(${normalizedTenantId}, ${normalizedUserId})`);
|
|
const row = readSingle(rows, "registration billing preference");
|
|
return row
|
|
? {
|
|
selectedSubscriptionPriceId: row.selected_subscription_price_id,
|
|
selectedOfficeSeatQuantity: row.selected_office_seat_quantity,
|
|
selectedFieldSeatQuantity: row.selected_field_seat_quantity,
|
|
}
|
|
: null;
|
|
}
|
|
|
|
export async function createRegistrationCapability(input: RegistrationCreateInput, client: CapabilityClient = getDbClient()): Promise<Registration> {
|
|
const rows = await client.$queryRaw<Registration[]>(Prisma.sql`
|
|
SELECT * FROM public.hivegrid_create_registration_v2(
|
|
${randomUUID()}, ${input.email}, ${input.firstName}, ${input.lastName}, ${input.token},
|
|
${input.company}, ${input.selectedSubscriptionPriceId}, ${input.selectedOfficeSeatQuantity},
|
|
${input.selectedFieldSeatQuantity}, ${input.leadConversionLeadId}, ${input.leadConversionToken},
|
|
${input.leadConversionPlanId}, ${input.ipAddress}, ${input.slug}
|
|
)
|
|
`);
|
|
const row = readSingle(rows, "registration create");
|
|
if (!row) throw new RegistrationCreateConflictError();
|
|
return row;
|
|
}
|
|
|
|
export async function updateRegistrationCapability(
|
|
input: {
|
|
id: string;
|
|
expectedToken: string;
|
|
patch: RegistrationPatch;
|
|
},
|
|
client: CapabilityClient = getDbClient()
|
|
): Promise<boolean> {
|
|
const expectedToken = normalizeCapability(input.expectedToken);
|
|
if (!expectedToken) throw new Error("Registration update requires a token capability");
|
|
const patch = JSON.stringify(input.patch);
|
|
const rows = await client.$queryRaw<Array<{ updated: boolean }>>(
|
|
Prisma.sql`SELECT public.hivegrid_update_registration(${input.id}, ${null}, ${expectedToken}, ${patch}::jsonb) AS updated`
|
|
);
|
|
return rows[0]?.updated === true;
|
|
}
|
|
|
|
export async function rotateRegistrationVerificationCapability(
|
|
input: { id: string; expectedToken: string; token: string },
|
|
client: CapabilityClient = getDbClient()
|
|
): Promise<boolean> {
|
|
const token = normalizeCapability(input.token);
|
|
if (!token || !/^[a-f0-9]{40}$/iu.test(token)) {
|
|
throw new Error("Registration verification rotation requires a 40-hex token");
|
|
}
|
|
return await updateRegistrationCapability(
|
|
{
|
|
id: input.id,
|
|
expectedToken: input.expectedToken,
|
|
patch: { token },
|
|
},
|
|
client
|
|
);
|
|
}
|
|
|
|
/**
|
|
* Performs the anonymous marketing capture as one reviewed database
|
|
* capability. The runtime role never receives SELECT or UPDATE on Lead.
|
|
*/
|
|
export async function captureMarketingLeadCapability(
|
|
input: MarketingLeadCaptureCapabilityInput,
|
|
client: CapabilityClient = getDbClient()
|
|
): Promise<{ leadId: string; created: boolean }> {
|
|
const email = normalizeMarketingEmail(input.email);
|
|
if (!email) throw new Error("Invalid marketing lead email");
|
|
const payload = {
|
|
email,
|
|
firstName: normalizeOptionalText(input.firstName, 200),
|
|
lastName: normalizeOptionalText(input.lastName, 200),
|
|
phone: normalizeOptionalText(input.phone, 100),
|
|
company: normalizeOptionalText(input.company, 300),
|
|
source: normalizeOptionalText(input.source, 200),
|
|
utmSource: normalizeOptionalText(input.utmSource, 500),
|
|
utmMedium: normalizeOptionalText(input.utmMedium, 500),
|
|
utmCampaign: normalizeOptionalText(input.utmCampaign, 500),
|
|
utmTerm: normalizeOptionalText(input.utmTerm, 500),
|
|
utmContent: normalizeOptionalText(input.utmContent, 500),
|
|
gclid: normalizeOptionalText(input.gclid, 2_048),
|
|
fbclid: normalizeOptionalText(input.fbclid, 2_048),
|
|
referrer: normalizeOptionalText(input.referrer, 2_048),
|
|
landingPage: normalizeOptionalText(input.landingPage, 2_048),
|
|
lastIpHash: normalizeOptionalText(input.lastIpHash, 128),
|
|
userAgent: normalizeOptionalText(input.userAgent, 500),
|
|
eventPayload: input.eventPayload,
|
|
};
|
|
const serialized = serializeCapabilityJson(payload, "marketing lead capture");
|
|
const rows = await client.$queryRaw<Array<{ result: unknown }>>(Prisma.sql`
|
|
SELECT public.hivegrid_capture_marketing_lead(
|
|
${randomUUID()}, ${randomUUID()}, ${serialized}::jsonb
|
|
) AS result
|
|
`);
|
|
const result = readJsonObject(readSingle(rows, "marketing lead capture")?.result, "marketing lead capture");
|
|
if (typeof result.leadId !== "string" || typeof result.created !== "boolean") {
|
|
throw new Error("Marketing lead capture capability returned an invalid result");
|
|
}
|
|
return { leadId: result.leadId, created: result.created };
|
|
}
|
|
|
|
/**
|
|
* Returns only the fields required by the signup form. Callers must verify the
|
|
* signed lead token before invoking this capability.
|
|
*/
|
|
export async function findLeadForSignedConversionCapability(
|
|
leadId: string,
|
|
client: CapabilityClient = getDbClient()
|
|
): Promise<SignedLeadConversionSummary | null> {
|
|
const normalizedLeadId = normalizeIdentifier(leadId);
|
|
if (!normalizedLeadId) return null;
|
|
const rows = await client.$queryRaw<Array<{ result: unknown }>>(
|
|
Prisma.sql`SELECT public.hivegrid_find_lead_for_signed_conversion(${normalizedLeadId}) AS result`
|
|
);
|
|
const row = readSingle(rows, "signed lead conversion");
|
|
if (!row?.result) return null;
|
|
const result = readJsonObject(row.result, "signed lead conversion");
|
|
if (typeof result.leadId !== "string" || typeof result.email !== "string") {
|
|
throw new Error("Signed lead conversion capability returned an invalid result");
|
|
}
|
|
return {
|
|
leadId: result.leadId,
|
|
email: result.email,
|
|
firstName: nullableString(result.firstName),
|
|
lastName: nullableString(result.lastName),
|
|
company: nullableString(result.company),
|
|
convertedToTenantId: nullableString(result.convertedToTenantId),
|
|
};
|
|
}
|
|
|
|
/**
|
|
* Converts a lead only when PostgreSQL can prove that the current app.user_id
|
|
* owns the lead email and is an active member of app.tenant_id.
|
|
*/
|
|
export async function convertSelfServiceMarketingLeadCapability(
|
|
input: SelfServiceLeadConversionCapabilityInput,
|
|
client: CapabilityClient = getDbClient()
|
|
): Promise<SelfServiceLeadConversionSummary | null> {
|
|
const leadId = normalizeIdentifier(input.leadId);
|
|
const tenantId = normalizeIdentifier(input.tenantId);
|
|
const userId = normalizeIdentifier(input.userId);
|
|
const expectedEmail = normalizeMarketingEmail(input.expectedEmail);
|
|
if (!leadId || !tenantId || !userId || !expectedEmail) {
|
|
throw new Error("Invalid self-service lead conversion identity");
|
|
}
|
|
const serialized = serializeCapabilityJson(
|
|
{
|
|
leadId,
|
|
tenantId,
|
|
userId,
|
|
expectedEmail,
|
|
planId: normalizeOptionalText(input.planId, 191),
|
|
},
|
|
"self-service lead conversion"
|
|
);
|
|
const rows = await client.$queryRaw<Array<{ result: unknown }>>(Prisma.sql`
|
|
SELECT public.hivegrid_convert_self_service_lead(
|
|
${randomUUID()}, ${randomUUID()}, ${serialized}::jsonb
|
|
) AS result
|
|
`);
|
|
const row = readSingle(rows, "self-service lead conversion");
|
|
if (!row?.result) return null;
|
|
const result = readJsonObject(row.result, "self-service lead conversion");
|
|
if (
|
|
typeof result.leadId !== "string" ||
|
|
typeof result.convertedToTenantId !== "string" ||
|
|
typeof result.alreadyConverted !== "boolean" ||
|
|
typeof result.email !== "string" ||
|
|
typeof result.firstSeenAt !== "string"
|
|
) {
|
|
throw new Error("Self-service lead conversion capability returned an invalid result");
|
|
}
|
|
return {
|
|
leadId: result.leadId,
|
|
convertedToTenantId: result.convertedToTenantId,
|
|
alreadyConverted: result.alreadyConverted,
|
|
email: result.email,
|
|
firstName: nullableString(result.firstName),
|
|
lastName: nullableString(result.lastName),
|
|
company: nullableString(result.company),
|
|
source: nullableString(result.source),
|
|
utmSource: nullableString(result.utmSource),
|
|
utmMedium: nullableString(result.utmMedium),
|
|
utmCampaign: nullableString(result.utmCampaign),
|
|
utmTerm: nullableString(result.utmTerm),
|
|
utmContent: nullableString(result.utmContent),
|
|
gclid: nullableString(result.gclid),
|
|
fbclid: nullableString(result.fbclid),
|
|
referrer: nullableString(result.referrer),
|
|
landingPage: nullableString(result.landingPage),
|
|
firstSeenAt: result.firstSeenAt,
|
|
convertedAt: nullableString(result.convertedAt),
|
|
};
|
|
}
|
|
|
|
export async function findBlacklistCapability(type: string, value: string, client: CapabilityClient = getDbClient()): Promise<Blacklist | null> {
|
|
const rows = await client.$queryRaw<Blacklist[]>(Prisma.sql`SELECT * FROM public.hivegrid_find_blacklist(${type}, ${value})`);
|
|
return readSingle(rows, "blacklist lookup");
|
|
}
|
|
|
|
export async function addBlacklistCapability(input: { type: string; value: string }, client: CapabilityClient = getDbClient()): Promise<Blacklist> {
|
|
const rows = await client.$queryRaw<Blacklist[]>(Prisma.sql`SELECT * FROM public.hivegrid_add_blacklist(${randomUUID()}, ${input.type}, ${input.value})`);
|
|
const row = readSingle(rows, "blacklist create");
|
|
if (!row) throw new Error("Blacklist capability did not create a row");
|
|
return row;
|
|
}
|
|
|
|
export async function recordBlacklistAttemptCapability(
|
|
input: Pick<Blacklist, "id" | "type" | "value">,
|
|
client: CapabilityClient = getDbClient()
|
|
): Promise<Blacklist | null> {
|
|
const rows = await client.$queryRaw<Blacklist[]>(
|
|
Prisma.sql`SELECT * FROM public.hivegrid_record_blacklist_attempt(${input.id}, ${input.type}, ${input.value})`
|
|
);
|
|
return readSingle(rows, "blacklist attempt");
|
|
}
|
|
|
|
export async function findIpAddressCapability(ipHash: string, client: CapabilityClient = getDbClient()): Promise<IpAddress | null> {
|
|
const rows = await client.$queryRaw<IpAddress[]>(Prisma.sql`SELECT * FROM public.hivegrid_find_ip_address(${ipHash})`);
|
|
return readSingle(rows, "IP lookup");
|
|
}
|
|
|
|
export async function upsertIpAddressCapability(
|
|
input: Omit<IpAddress, "id" | "createdAt" | "updatedAt">,
|
|
client: CapabilityClient = getDbClient()
|
|
): Promise<IpAddress> {
|
|
const rows = await client.$queryRaw<IpAddress[]>(Prisma.sql`
|
|
SELECT * FROM public.hivegrid_upsert_ip_address(
|
|
${randomUUID()}, ${input.ip}, ${input.provider}, ${input.type}, ${input.countryCode},
|
|
${input.countryName}, ${input.regionCode}, ${input.regionName}, ${input.city},
|
|
${input.zipCode}, ${input.latitude}, ${input.longitude}, ${input.metadata}
|
|
)
|
|
`);
|
|
const row = readSingle(rows, "IP upsert");
|
|
if (!row) throw new Error("IP capability did not return a row");
|
|
return row;
|
|
}
|
|
|
|
export async function appendIpAddressLogCapability(
|
|
input: Omit<IpAddressLog, "id" | "createdAt">,
|
|
client: CapabilityClient = getDbClient()
|
|
): Promise<IpAddressLog> {
|
|
const rows = await client.$queryRaw<IpAddressLog[]>(Prisma.sql`
|
|
SELECT * FROM public.hivegrid_append_ip_address_log(
|
|
${randomUUID()}, ${input.ip}, ${input.url}, ${input.action}, ${input.description},
|
|
${input.success}, ${input.error}, ${input.metadata}, ${input.ipAddressId}
|
|
)
|
|
`);
|
|
const row = readSingle(rows, "IP log append");
|
|
if (!row) throw new Error("IP log capability did not create a row");
|
|
return row;
|
|
}
|
|
|
|
function normalizeEmail(value: string): string | null {
|
|
const normalized = normalizeCapability(value)?.toLowerCase() ?? null;
|
|
return normalized && normalized.includes("@") ? normalized : null;
|
|
}
|
|
|
|
function normalizeMarketingEmail(value: string): string | null {
|
|
const normalized = value.trim().toLowerCase();
|
|
if (!normalized || normalized.length > 320 || normalized.includes("\u0000") || !normalized.includes("@")) return null;
|
|
return normalized;
|
|
}
|
|
|
|
function normalizeIdentifier(value: string): string | null {
|
|
const normalized = value.trim();
|
|
if (!normalized || normalized.length > 191 || normalized.includes("\u0000")) return null;
|
|
return normalized;
|
|
}
|
|
|
|
function normalizeOptionalText(value: string | null | undefined, maximumLength: number): string | null {
|
|
if (value === null || value === undefined) return null;
|
|
const normalized = String(value).trim();
|
|
if (!normalized) return null;
|
|
if (normalized.length > maximumLength || normalized.includes("\u0000")) {
|
|
throw new Error("Invalid marketing lead capability value");
|
|
}
|
|
return normalized;
|
|
}
|
|
|
|
function serializeCapabilityJson(value: unknown, label: string): string {
|
|
const serialized = JSON.stringify(value);
|
|
if (!serialized || serialized.length > 16_384) {
|
|
throw new Error(`Invalid ${label} capability payload`);
|
|
}
|
|
return serialized;
|
|
}
|
|
|
|
function readJsonObject(value: unknown, label: string): Record<string, unknown> {
|
|
if (!value || typeof value !== "object" || Array.isArray(value)) {
|
|
throw new Error(`Invalid ${label} capability result`);
|
|
}
|
|
return value as Record<string, unknown>;
|
|
}
|
|
|
|
function nullableString(value: unknown): string | null {
|
|
return typeof value === "string" ? value : null;
|
|
}
|
|
|
|
function normalizeCapability(value: string): string | null {
|
|
const normalized = value.trim();
|
|
if (!normalized || normalized.length > 2_048 || normalized.includes("\u0000")) return null;
|
|
return normalized;
|
|
}
|
|
|
|
function readSingle<T>(rows: T[], label: string): T | null {
|
|
if (rows.length === 0) return null;
|
|
if (rows.length !== 1) throw new Error(`Ambiguous ${label} capability result`);
|
|
return rows[0] ?? null;
|
|
}
|