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 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 | 1x 1x 1x 49x 49x 49x 49x 49x 1x 48x 1x 47x 47x 1x 46x 46x 1x 45x 45x 2x 43x 43x 1x 42x 1x 41x 49x 1x 40x 49x 1x 39x 1x 38x 4x 4x 1x 3x 1x 36x 3x 3x 1x 2x 2x 1x 34x 34x 2x 32x 1x 31x 5x 1x 5x 3x 28x 28x 49x 8x 1x 8x 6x 6x 6x 1x 27x 4x 23x 2x 21x 21x 3x 3x 2x 1x 21x 21x 21x 3x 3x 3x 21x 21x 21x 1x 21x 21x 21x 1x 21x 21x 21x 21x 21x 1x 21x 21x 1x 21x 21x 21x 21x 21x 1x 1x 1x 20x 28x | // Public Marketplace Inquiry Routes (API Key Protected)
import {
cityNameErrorMessage,
validateCityName,
} from "@interioring/utils/validation/address";
import {
customerNameErrorMessage,
normalizeCustomerName,
validateCustomerName,
} from "@interioring/utils/validation/customer-name";
import { isValidEmail } from "@interioring/utils/validation/email";
import { parseIndianPhone } from "@interioring/utils/validation/phone";
import { Hono } from "hono";
import type { Dal } from "../../dal";
import { CommunicationGateway } from "../../lib/communication/gateway";
import { NewInquiryHandler } from "../../lib/communication/handlers/new-inquiry.handler";
import { resolveEnvironment } from "../../lib/domain-utils";
import { getWhatsAppSafetyConfig } from "../../lib/env-config";
import { UnauthorizedError, ValidationError } from "../../lib/errors";
import { fireInternalNotification } from "../../lib/internal-notifications";
import { logger } from "../../lib/logger";
import { handleError, success } from "../../lib/response";
import { isContactRestricted } from "../../lib/restriction";
import {
buildWhatsAppRedirectUrl,
VALID_REQUIREMENT_TYPES,
VALID_SOURCE_TYPES,
} from "../../lib/whatsapp";
import { rateLimit } from "../../middleware/rate-limit.middleware";
import type { Services } from "../../services";
type Env = {
Bindings: CloudflareBindings;
Variables: {
dal: Dal;
services: Services;
};
};
const inquiries = new Hono<Env>();
// Rate limit: 5 requests per 10 minutes per IP in production.
// devMax keeps local/dev and parallel E2E workers (which share the "unknown"
// IP) from tripping the limit after 5 submissions — matches the other limiters.
const inquiryRateLimit = rateLimit({
windowMs: 10 * 60 * 1000,
max: 5,
devMax: 1000,
message: "Too many inquiries. Please try again in 10 minutes.",
});
// Submit a new inquiry
inquiries.post("/", inquiryRateLimit, async (c) => {
try {
const services = c.get("services");
const dal = c.get("dal");
const body = await c.req.json();
// Validate required fields
if (!body.proId) {
throw new ValidationError("proId is required");
}
if (!body.customerName) {
throw new ValidationError("customerName is required");
}
const nameError = validateCustomerName(String(body.customerName));
if (nameError) {
throw new ValidationError(customerNameErrorMessage(nameError));
}
const normalizedCustomerName = normalizeCustomerName(
String(body.customerName),
);
if (!body.customerPhone) {
throw new ValidationError("customerPhone is required");
}
const parsedPhone = parseIndianPhone(String(body.customerPhone));
if (!parsedPhone || parsedPhone.type !== "mobile") {
throw new ValidationError(
"customerPhone must be a valid 10-digit Indian mobile number",
);
}
const normalizedPhone = parsedPhone.e164;
// Validate optional fields
if (
body.requirementType &&
!VALID_REQUIREMENT_TYPES.includes(body.requirementType)
) {
throw new ValidationError(
`Invalid requirementType. Must be one of: ${VALID_REQUIREMENT_TYPES.join(", ")}`,
);
}
if (body.sourceType && !VALID_SOURCE_TYPES.includes(body.sourceType)) {
throw new ValidationError(
`Invalid sourceType. Must be one of: ${VALID_SOURCE_TYPES.join(", ")}`,
);
}
const rawDescription =
body.requirementType === "other" && body.requirementDescription
? String(body.requirementDescription).trim()
: undefined;
if (rawDescription && rawDescription.length > 500) {
throw new ValidationError(
"requirementDescription must be 500 characters or fewer",
);
}
const requirementDescription = rawDescription?.slice(0, 500);
// Length-cap free-text fields before they're persisted or forwarded
// to the notification pipeline. Previously `requirement`, `sourcePage`,
// and `customerEmail` were written to D1 with no bound — a caller
// could persist 100KB+ payloads that slow down every subsequent read.
if (body.requirement && String(body.requirement).length > 5000) {
throw new ValidationError("requirement must be 5000 characters or fewer");
}
if (body.sourcePage && String(body.sourcePage).length > 500) {
throw new ValidationError("sourcePage must be 500 characters or fewer");
}
if (body.customerEmail) {
const email = String(body.customerEmail).trim();
if (email.length > 254) {
throw new ValidationError(
"customerEmail must be 254 characters or fewer",
);
}
if (!isValidEmail(email)) {
throw new ValidationError(
"customerEmail must be a valid email address",
);
}
}
// `customerLocation` is forwarded to WhatsApp/email notification
// payloads. It must be a recognisable city name when present —
// otherwise junk like "12345" reaches the pro's inbox (audit during
// issue #563 fix surfaced this gap).
if (body.customerLocation) {
const loc = String(body.customerLocation).trim();
if (loc.length > 200) {
throw new ValidationError(
"customerLocation must be 200 characters or fewer",
);
}
const locError = validateCityName(loc);
if (locError) {
throw new ValidationError(
`customerLocation: ${cityNameErrorMessage(locError)}`,
);
}
}
// Verify pro exists and is published. Wrap getById so the "does not
// exist" and "not published" cases both resolve to the same 400
// response — otherwise the error-status differential (404 vs 400)
// lets an attacker enumerate which pro IDs exist in the system.
const pro = await services.pro.getById(body.proId).catch(() => null);
if (!pro || pro.status !== "published") {
throw new ValidationError("Pro not found");
}
// WhatsApp path: validate pro has WhatsApp before creating inquiry
if (body.type === "whatsapp" && !pro.whatsapp) {
throw new ValidationError("This pro does not have WhatsApp configured");
}
// If projectId provided, verify it belongs to the pro AND is published.
// Previously only the proId link was checked; referencing a draft or
// archived project with the correct proId succeeded, leaking the
// existence of unpublished projects. Same catch-and-uniform-error
// pattern as the pro check above.
if (body.projectId) {
const project = await services.project
.getById(body.projectId)
.catch(() => null);
if (
!project ||
project.proId !== body.proId ||
project.status !== "published"
) {
throw new ValidationError("Project does not belong to this pro");
}
}
// Restrict Direct Contact — when active for this pro, contact must come
// from a logged-in homeowner via the portal inquiry flow. `homeownerId`
// is supplied by the marketplace SSR proxy from a session it already
// validated (trusted S2S / API-key boundary); we still verify the row
// exists so a stale or forged id can never create a dangling link.
const restricted = await isContactRestricted(body.proId, c.env, dal);
const claimedHomeownerId =
typeof body.homeownerId === "string" && body.homeownerId.trim()
? body.homeownerId.trim()
: undefined;
let linkedHomeownerId: string | undefined;
if (claimedHomeownerId) {
const ho = await dal.hoUsers
.findById(claimedHomeownerId)
.catch(() => null);
if (ho) {
linkedHomeownerId = ho.id;
// 3-active-inquiry cap (spec: crm_homeowner_inquiry_list).
const activeCount =
await dal.homeownerInquiries.countActive(linkedHomeownerId);
if (activeCount >= 3) {
throw new ValidationError(
"You have 3 active inquiries. Complete or close one before starting a new one.",
);
}
}
}
if (restricted && !linkedHomeownerId) {
throw new UnauthorizedError(
"Please log in to contact this professional on Interioring.",
);
}
// Restrict Direct Contact also closes the WhatsApp redirect path: the
// success response for `type: "whatsapp"` hands back a wa.me URL built
// from the pro's REAL number (services.pro.getById is unredacted), which
// would leak the exact contact the feature hides. Force the on-platform
// form flow for restricted pros.
if (restricted && body.type === "whatsapp") {
throw new ValidationError(
"This professional handles all conversations through your inquiry on Interioring.",
);
}
const inquiry = await services.inquiry.create({
proId: body.proId,
projectId: body.projectId,
homeownerId: linkedHomeownerId,
customerName: normalizedCustomerName,
customerPhone: normalizedPhone,
customerEmail: body.customerEmail,
requirement: body.requirement,
type: body.type || "form_submit",
sourcePage: body.sourcePage,
requirementType: body.requirementType,
sourceType: body.sourceType || "marketplace",
});
// Homeowner-linked inquiries: record the pro match + advance the
// homeowner-facing status to "pros_notified". Match + status are written
// synchronously so the homeowner's inquiry list is correct immediately.
if (linkedHomeownerId) {
try {
await dal.homeownerInquiries.createMatch(inquiry.id, body.proId);
await dal.homeownerInquiries.setHomeownerStatus(
inquiry.id,
"pros_notified",
{ prosNotifiedCount: 1 },
);
} catch (err) {
logger.error("[INQUIRY] match/status write failed:", err);
}
}
// Communication History Log (spec: every inquiry has a log, created at
// submission). `inquiry_submitted` is logged for ALL inquiries — actor is
// the homeowner when linked, otherwise the system (anonymous submission).
// Linked inquiries additionally get the match/status/notification events.
// Best-effort, off the request path.
c.executionCtx.waitUntil(
(async () => {
await services.commLog.logEventSafe({
inquiryId: inquiry.id,
eventType: "inquiry_submitted",
actorType: linkedHomeownerId ? "homeowner" : "system",
actorId: linkedHomeownerId ?? null,
});
if (linkedHomeownerId) {
await services.commLog.logEventSafe({
inquiryId: inquiry.id,
eventType: "pros_matched",
actorType: "system",
metadata: { proIds: [body.proId] },
});
await services.commLog.logEventSafe({
inquiryId: inquiry.id,
eventType: "status_changed",
actorType: "system",
metadata: { from: "submitted", to: "pros_notified" },
});
await services.commLog.logEventSafe({
inquiryId: inquiry.id,
eventType: "lead_notification_sent",
actorType: "system",
metadata: { proId: body.proId, channel: "whatsapp/email" },
});
}
})(),
);
// Send notifications via communication gateway
c.executionCtx.waitUntil(
(async () => {
try {
const project = body.projectId
? await services.project.getById(body.projectId).catch(() => null)
: null;
const gateway = new CommunicationGateway(dal, c.env);
const handler = new NewInquiryHandler(gateway, dal);
await handler.handle({
inquiryId: inquiry.id,
proId: body.proId,
customerName: normalizedCustomerName,
customerPhone: normalizedPhone,
customerEmail: body.customerEmail,
customerLocation: body.customerLocation,
requirement: body.requirement,
requirementType: body.requirementType,
projectTitle: project?.title,
});
} catch (err) {
logger.error("[INQUIRY] Failed to send notifications:", err);
}
})(),
);
// Internal leadership notification (fire-and-forget, never blocks request)
fireInternalNotification(c, dal, {
event: "new_lead_internal",
proName: pro.businessName,
customerName: normalizedCustomerName,
customerPhone: normalizedPhone,
message: body.requirement,
inquiryId: inquiry.id,
});
// Auto-create CRM lead from inquiry, then send in-app + push notification
// Notification fires AFTER lead creation so we have the correct lead ID for deep linking
c.executionCtx.waitUntil(
(async () => {
let lead: Awaited<
ReturnType<typeof services.leads.createFromInquiry>
> | null = null;
try {
await services.pipelineStages.ensureInitialized(body.proId);
} catch (err) {
logger.error("[INQUIRY] Pipeline init failed:", err);
}
try {
lead = await services.leads.createFromInquiry(body.proId, {
customerName: normalizedCustomerName,
customerPhone: normalizedPhone,
customerEmail: body.customerEmail,
customerLocation: body.customerLocation,
requirement: body.requirement,
requirementType: body.requirementType,
inquiryId: inquiry.id,
});
} catch (err) {
logger.error("[INQUIRY] CRM lead creation failed:", err);
}
try {
const deepLink = lead ? `/crm/leads/${lead.id}` : "/crm";
await services.notification.notify({
proId: body.proId,
eventType: "new_inquiry",
title: `New enquiry from ${normalizedCustomerName}`,
body:
body.requirement?.substring(0, 200) ??
"New customer enquiry received",
data: {
url: deepLink,
...(lead && { leadId: lead.id }),
inquiryId: inquiry.id,
},
});
} catch (err) {
logger.error("[INQUIRY] Notification delivery failed:", err);
}
})(),
);
// WhatsApp path: generate redirect URL
if (body.type === "whatsapp") {
const safetyConfig = getWhatsAppSafetyConfig(
resolveEnvironment(c.env.ENVIRONMENT),
);
const whatsappRedirectUrl = buildWhatsAppRedirectUrl({
proWhatsapp: pro.whatsapp as string,
proName: pro.businessName,
customerName: normalizedCustomerName,
customerPhone: normalizedPhone,
requirementType: body.requirementType,
requirementDescription,
environment: c.env.ENVIRONMENT,
overrideNumber: safetyConfig.overrideNumber,
});
return success(
c,
{ id: inquiry.id, whatsapp_redirect_url: whatsappRedirectUrl },
201,
);
}
return success(c, inquiry, 201);
} catch (err) {
return handleError(c, err);
}
});
export default inquiries;
|