All files / routes/companion index.ts

99.31% Statements 144/145
97.22% Branches 70/72
100% Functions 21/21
99.3% Lines 143/144

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 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444                                                                                                              1x             1x 57x 10x   47x               1x   5x 5x 5x 5x     1x           14x 14x 2x       12x       1x 3x 3x 3x   1x 3x   3x           2x   1x         1x 3x 3x 3x 3x         3x 1x     2x 1x   2x               1x 4x 4x 4x 4x     3x   1x         1x 5x 5x 5x   1x 5x 5x 3x   2x 1x     1x           1x 1x         1x   4x                               1x 1x 9x 9x 9x 9x     9x   1x 9x   9x         9x 9x 1x   8x 1x     7x               7x   7x     9x 4x         3x 3x 2x           3x                 3x 3x 3x 2x             3x           3x           6x         1x 2x 2x 2x 2x       1x   1x                       1x 4x 2x   2x 2x 4x 4x           2x 4x 1x   1x   1x               1x 5x 5x 2x   3x 3x 1x   2x                                               1x 6x 6x 6x     1x   6x 6x 2x     4x 4x 4x   4x       6x 2x                           2x 2x       2x 14x         5x   2x 2x 1x       2x 1x     2x 1x   5x 4x     2x          
/**
 * InterioringAI companion routes (prototype).
 *
 * Purpose of this slice: prove that the web app and WhatsApp share ONE
 * conversation, along the real customer journey:
 *
 *   1. the customer starts on the site and can chat anonymously;
 *   2. they sign in with their phone (the existing homeowner phone OTP) at the
 *      latest when they tap "Continue on WhatsApp";
 *   3. POST /projects/:id/claim binds the project to their account and their
 *      verified number to the project — no link code, the login proved it;
 *   4. from then on WhatsApp messages from that number land in this project.
 *
 * The conversation lives in the CompanionProject Durable Object. These routes
 * are a thin shell: resolve the project, call the object, return JSON.
 */
 
import { desc, eq } from "drizzle-orm";
import { Hono } from "hono";
import type { CompanionProject } from "../../companion/durable-object";
import { isCompanionEnabled } from "../../companion/environment";
import {
	buildCompanionDeps,
	COMPANION_MEDIA_PREFIX,
} from "../../companion/webhook-bridge";
import {
	buildContinueUrl,
	createLinkStore,
	isInsideServiceWindow,
	toWhatsAppNumber,
} from "../../companion/whatsapp";
import { getDb } from "../../db";
import {
	companionPhoneLinks,
	companionProjects,
} from "../../db/schema/companion";
import { hoUsers } from "../../db/schema/homeowner";
import { notificationDeliveryLog } from "../../db/schema/notifications";
import {
	BadRequestError,
	ForbiddenError,
	NotFoundError,
} from "../../lib/errors";
import { handleError, success } from "../../lib/response";
import {
	hoAuthSessionMiddleware,
	requireHoAuth,
} from "../../middleware/ho-auth.middleware";
import { pageContentSecurityPolicy, renderCompanionPage } from "./page";
 
type Env = {
	Bindings: CloudflareBindings;
	Variables: { hoUser: { id: string; name: string; email: string } | null };
};
 
const companion = new Hono<Env>();
 
/**
 * Every companion route — chat endpoints included, not just the page — is
 * local/dev only. Unauthenticated project creation plus a Claude call per
 * message would be an open credit tap anywhere public.
 */
companion.use("*", async (c, next) => {
	if (!isCompanionEnabled(c.env)) {
		return c.text("Not found", 404);
	}
	await next();
});
 
/**
 * GET /api/companion/app — the prototype's web surface: the customer's chat on
 * the left, sign-in and "Continue on WhatsApp" on the right, plus a developer
 * debug panel a customer would never see.
 */
companion.get("/app", (c) => {
	// Fresh nonce per response: only this page's own <style> and <script> run.
	const nonce = crypto.randomUUID().replaceAll("-", "");
	c.header("Content-Security-Policy", pageContentSecurityPolicy(nonce));
	c.header("Cache-Control", "no-store");
	return c.html(renderCompanionPage(nonce));
});
 
const MAX_MESSAGE_LENGTH = 4000;
 
function projectStub(
	env: CloudflareBindings,
	projectId: string,
): DurableObjectStub<CompanionProject> {
	const namespace = env.COMPANION_PROJECT;
	if (!namespace) {
		throw new BadRequestError(
			"COMPANION_PROJECT binding missing — check wrangler.jsonc",
		);
	}
	return namespace.get(namespace.idFromName(projectId));
}
 
/** POST /api/companion/projects — start a session. Returns the project id. */
companion.post("/projects", async (c) => {
	try {
		const db = getDb(c.env.DB);
		const body = await c.req
			.json<{ label?: string }>()
			.catch(() => ({}) as { label?: string });
		const id = crypto.randomUUID();
 
		await db.insert(companionProjects).values({
			id,
			label: body.label ?? null,
			lastActivityAt: new Date(),
		});
 
		return success(c, { projectId: id, label: body.label ?? null }, 201);
	} catch (err) {
		return handleError(c, err);
	}
});
 
/** GET /api/companion/projects/:id — message count, cursor, linked phones. */
companion.get("/projects/:id", async (c) => {
	try {
		const projectId = c.req.param("id");
		const db = getDb(c.env.DB);
		const rows = await db
			.select()
			.from(companionProjects)
			.where(eq(companionProjects.id, projectId))
			.limit(1);
		if (rows.length === 0) {
			throw new NotFoundError("Project not found");
		}
 
		const summary = await projectStub(c.env, projectId).summary();
		return success(c, { project: rows[0], ...summary });
	} catch (err) {
		return handleError(c, err);
	}
});
 
/**
 * GET /api/companion/projects/:id/messages?since=<seq>
 * The web app polls this. `since` is the last seq it has seen.
 */
companion.get("/projects/:id/messages", async (c) => {
	try {
		const projectId = c.req.param("id");
		const since = Number(c.req.query("since") ?? "0");
		const messages = await projectStub(c.env, projectId).messagesSince(
			Number.isFinite(since) ? since : 0,
		);
		return success(c, { messages });
	} catch (err) {
		return handleError(c, err);
	}
});
 
/** POST /api/companion/projects/:id/messages — send from the web surface. */
companion.post("/projects/:id/messages", async (c) => {
	try {
		const projectId = c.req.param("id");
		const body = await c.req
			.json<{ text?: string }>()
			.catch(() => ({}) as { text?: string });
		const text = (body.text ?? "").trim();
		if (!text) {
			throw new BadRequestError("text is required");
		}
		if (text.length > MAX_MESSAGE_LENGTH) {
			throw new BadRequestError("text is too long");
		}
 
		const result = await projectStub(c.env, projectId).handleIncoming({
			channel: "web",
			role: "user",
			text,
		});
 
		const db = getDb(c.env.DB);
		await db
			.update(companionProjects)
			.set({ lastActivityAt: new Date() })
			.where(eq(companionProjects.id, projectId));
 
		return success(c, result, 201);
	} catch (err) {
		return handleError(c, err);
	}
});
 
/**
 * POST /api/companion/projects/:id/claim
 * Body: { remindersConsent?: boolean }
 *
 * Called once the customer has signed in with their phone. Binds the project
 * to their account and their verified number to the project, then returns the
 * "Continue on WhatsApp" link. Safe to call again on every page load: it only
 * writes a timeline note the first time this account claims the project.
 *
 * `remindersConsent` is the "send me reminders on WhatsApp" checkbox. Omit it
 * to keep whatever was recorded before.
 */
companion.use("/projects/:id/claim", hoAuthSessionMiddleware, requireHoAuth);
companion.post("/projects/:id/claim", async (c) => {
	try {
		const projectId = c.req.param("id");
		const user = c.get("hoUser");
		Iif (!user) {
			throw new BadRequestError("Sign in first");
		}
		const body = await c.req
			.json<{ remindersConsent?: boolean }>()
			.catch(() => ({}) as { remindersConsent?: boolean });
		const db = getDb(c.env.DB);
 
		const projects = await db
			.select()
			.from(companionProjects)
			.where(eq(companionProjects.id, projectId))
			.limit(1);
		const project = projects[0];
		if (!project) {
			throw new NotFoundError("Project not found");
		}
		if (project.hoUserId && project.hoUserId !== user.id) {
			throw new ForbiddenError("This conversation belongs to another account");
		}
 
		const accounts = await db
			.select({
				phoneNumber: hoUsers.phoneNumber,
				phoneNumberVerified: hoUsers.phoneNumberVerified,
			})
			.from(hoUsers)
			.where(eq(hoUsers.id, user.id))
			.limit(1);
		const account = accounts[0];
		const phone =
			account?.phoneNumber && account.phoneNumberVerified
				? toWhatsAppNumber(account.phoneNumber)
				: null;
		if (!phone) {
			throw new BadRequestError(
				"Sign in with your phone number to continue on WhatsApp",
			);
		}
 
		const firstClaim = project.hoUserId !== user.id;
		if (firstClaim) {
			await db
				.update(companionProjects)
				.set({ hoUserId: user.id, lastActivityAt: new Date() })
				.where(eq(companionProjects.id, projectId));
		}
 
		await createLinkStore(db).upsertPhoneLink(phone, {
			projectId,
			hoUserId: user.id,
			remindersConsent:
				typeof body.remindersConsent === "boolean"
					? body.remindersConsent
					: undefined,
		});
 
		const stub = projectStub(c.env, projectId);
		await stub.linkPhone(phone);
		if (firstClaim) {
			await stub.append({
				channel: "web",
				role: "system",
				text: `Signed in as +${phone}. WhatsApp from this number now continues this conversation.`,
			});
		}
 
		const links = await db
			.select()
			.from(companionPhoneLinks)
			.where(eq(companionPhoneLinks.phone, phone))
			.limit(1);
 
		return success(c, {
			phone,
			whatsappUrl: buildContinueUrl(c.env.WA_TEST_DISPLAY_NUMBER),
			remindersConsent: Boolean(links[0]?.remindersConsentAt),
		});
	} catch (err) {
		return handleError(c, err);
	}
});
 
/** GET /api/companion/projects/:id/links — which phones are bound. */
companion.get("/projects/:id/links", async (c) => {
	try {
		const projectId = c.req.param("id");
		const db = getDb(c.env.DB);
		const links = await db
			.select()
			.from(companionPhoneLinks)
			.where(eq(companionPhoneLinks.projectId, projectId));
		return success(c, { links });
	} catch (err) {
		return handleError(c, err);
	}
});
 
/**
 * GET /api/companion/dev/otp?phone=+91…
 *
 * LOCAL ONLY, and only when no WhatsApp token is configured. Locally the login
 * code is never sent anywhere — `sendWhatsAppOtp` prints it to the worker log
 * and writes it to notification_delivery_log — so the test page reads it here
 * to let someone finish signing in. Never reachable in dev, preview or prod.
 */
companion.get("/dev/otp", async (c) => {
	if (c.env.ENVIRONMENT !== "local" || c.env.WHATSAPP_ACCESS_TOKEN) {
		return c.text("Not found", 404);
	}
	try {
		const phone = c.req.query("phone") ?? "";
		const db = getDb(c.env.DB);
		const rows = await db
			.select({ previewText: notificationDeliveryLog.previewText })
			.from(notificationDeliveryLog)
			.where(eq(notificationDeliveryLog.recipient, phone))
			.orderBy(desc(notificationDeliveryLog.id))
			.limit(1);
		const code = rows[0]?.previewText?.match(/\d{6}/)?.[0] ?? null;
		if (!code) {
			throw new NotFoundError("No code sent to that number yet");
		}
		return success(c, { code });
	} catch (err) {
		return handleError(c, err);
	}
});
 
/**
 * GET /api/companion/media/<key> — photos that arrived on WhatsApp, so the web
 * page can show them. Only under the companion prefix.
 */
companion.get("/media/*", async (c) => {
	const key = c.req.path.replace(/^.*\/media\//, "");
	if (!key.startsWith(COMPANION_MEDIA_PREFIX) || key.includes("..")) {
		return c.text("Not found", 404);
	}
	const object = await c.env.R2.get(key);
	if (!object) {
		return c.text("Not found", 404);
	}
	return new Response(object.body, {
		headers: {
			"content-type":
				object.httpMetadata?.contentType ?? "application/octet-stream",
			"cache-control": "private, max-age=3600",
		},
	});
});
 
/**
 * POST /api/companion/projects/:id/whatsapp-nudge
 * Body: { text, simulateHoursSinceInbound? }
 *
 * The proactive path — the one checkpoint reminders will use. Two rules:
 *
 * - Meta's 24-hour window: inside it, free-form text; outside it, 409 and a
 *   template is required, because that is what Meta would do.
 * - Consent: reminders go only to phones that are `active` AND ticked "send me
 *   reminders on WhatsApp". Replies to the customer's own messages need no
 *   consent; reminders the customer did not ask for do.
 *
 * `simulateHoursSinceInbound` pretends the last WhatsApp message was that
 * long ago, so the window can be tested without waiting a day.
 */
companion.post("/projects/:id/whatsapp-nudge", async (c) => {
	try {
		const projectId = c.req.param("id");
		const body = await c.req
			.json<{ text?: string; simulateHoursSinceInbound?: number }>()
			.catch(
				() => ({}) as { text?: string; simulateHoursSinceInbound?: number },
			);
		const text = (body.text ?? "").trim();
		if (!text) {
			throw new BadRequestError("text is required");
		}
 
		const stub = projectStub(c.env, projectId);
		const summary = await stub.summary();
		const now = Date.now();
		const lastInboundAt =
			typeof body.simulateHoursSinceInbound === "number"
				? now - body.simulateHoursSinceInbound * 60 * 60 * 1000
				: summary.lastInboundAt.whatsapp;
 
		if (!isInsideServiceWindow(lastInboundAt, now)) {
			return c.json(
				{
					success: false,
					error: {
						code: "TEMPLATE_REQUIRED",
						message:
							"Outside the 24-hour window: a free-form message would be rejected by Meta. Send an approved template instead.",
					},
					data: { lastInboundAt, simulated: body.simulateHoursSinceInbound },
				},
				409,
			);
		}
 
		const db = getDb(c.env.DB);
		const links = await db
			.select()
			.from(companionPhoneLinks)
			.where(eq(companionPhoneLinks.projectId, projectId));
		const reasonSkipped = (l: (typeof links)[number]) =>
			l.status !== "active"
				? l.status
				: l.remindersConsentAt
					? null
					: "no_consent";
		const recipients = links.filter((l) => reasonSkipped(l) === null);
 
		const deps = buildCompanionDeps(c.env);
		for (const link of recipients) {
			await deps.send(link.phone, text);
		}
		// Only record what was actually delivered. A nudge nobody could receive
		// goes nowhere, and the timeline must not claim otherwise.
		if (recipients.length > 0) {
			await stub.append({ channel: "whatsapp", role: "assistant", text });
		}
 
		return success(c, {
			sent: recipients.map((l) => l.phone),
			skipped: links
				.filter((l) => reasonSkipped(l) !== null)
				.map((l) => ({ phone: l.phone, reason: reasonSkipped(l) })),
		});
	} catch (err) {
		return handleError(c, err);
	}
});
 
export default companion;