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 | 2x 9x 6x | /**
* The prototype's web surface, served by the API worker itself.
*
* Why it lives here and not in `apps/companion`: a new `apps/*` workspace has to
* be registered in eight places (APP_NAMES, mprocs, ports, setup.sh,
* verify-apps, cross-app-imports, and two deploy.yml entries — see
* `scripts/app-registry.test.ts`), including a deploy job we cannot fill in yet.
* Serving one page from the worker also puts the page on the SAME ORIGIN as the
* API, so no CORS and no cookie-domain questions while we test the thing we
* actually care about: does one conversation survive across two channels.
*
* When the sync test passes, this page is the spec for the real `apps/companion`
* Vite app, and this route goes away.
*
* Only served when ENVIRONMENT is local or dev.
*/
const COMPANION_PAGE_TEMPLATE = `<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>InterioringAI — channel sync prototype</title>
<style nonce="__CSP_NONCE__">
:root {
--ground: #f5f7f5; --surface: #fff; --ink: #18211e; --muted: #56645f;
--rule: #d6ddd9; --accent: #23705f; --accent-soft: #ddefea; --amber-soft: #f8ebd3;
--wa: #25d366;
}
@media (prefers-color-scheme: dark) {
:root {
--ground: #111715; --surface: #18201d; --ink: #e3eae6; --muted: #98a6a0;
--rule: #2b3531; --accent: #6cc2ac; --accent-soft: #1d3530; --amber-soft: #3a2e1b;
}
}
* { box-sizing: border-box; }
body {
margin: 0; background: var(--ground); color: var(--ink);
font: 15px/1.55 system-ui, -apple-system, "Segoe UI", sans-serif;
}
header {
padding: 14px 20px; border-bottom: 1px solid var(--rule);
display: flex; flex-wrap: wrap; gap: 8px 16px; align-items: baseline;
}
header h1 { font-size: 16px; margin: 0; font-weight: 600; }
header .tag {
font: 500 11px/1 ui-monospace, monospace; letter-spacing: .06em; text-transform: uppercase;
color: var(--accent); background: var(--accent-soft); padding: 4px 8px; border-radius: 999px;
}
main { display: grid; grid-template-columns: 1fr; gap: 16px; padding: 16px; max-width: 1100px; margin: 0 auto; }
@media (min-width: 900px) { main { grid-template-columns: minmax(0,1fr) 320px; } }
.panel { background: var(--surface); border: 1px solid var(--rule); border-radius: 10px; }
#log { padding: 16px; display: flex; flex-direction: column; gap: 10px; min-height: 55vh; max-height: 65vh; overflow-y: auto; }
.msg { max-width: 78%; padding: 9px 13px; border-radius: 12px; white-space: pre-wrap; word-wrap: break-word; }
.msg.user { align-self: flex-end; background: var(--accent-soft); border-bottom-right-radius: 3px; }
.msg.assistant { align-self: flex-start; background: var(--ground); border: 1px solid var(--rule); border-bottom-left-radius: 3px; }
.msg.system { align-self: center; background: var(--amber-soft); font-size: 13px; }
.msg img { display: block; max-width: 240px; max-height: 240px; margin-top: 6px; border-radius: 8px; }
.meta { display: block; font: 500 10px/1.4 ui-monospace, monospace; letter-spacing: .05em; text-transform: uppercase; color: var(--muted); margin-bottom: 4px; }
.meta .wa { color: var(--wa); }
form { display: flex; gap: 8px; padding: 12px; border-top: 1px solid var(--rule); }
input[type=text], input[type=tel] { flex: 1; padding: 10px 12px; border: 1px solid var(--rule); border-radius: 8px; background: var(--ground); color: var(--ink); font: inherit; }
button { padding: 10px 16px; border: 0; border-radius: 8px; background: var(--accent); color: var(--ground); font: 500 15px/1 inherit; cursor: pointer; }
button.ghost { background: transparent; color: var(--accent); border: 1px solid var(--rule); }
button:disabled { opacity: .5; cursor: default; }
aside .block { padding: 14px 16px; border-bottom: 1px solid var(--rule); }
aside .block:last-child { border-bottom: 0; }
aside h2 { font-size: 13px; margin: 0 0 8px; text-transform: uppercase; letter-spacing: .06em; color: var(--muted); font-weight: 500; }
code, .mono { font-family: ui-monospace, monospace; font-size: 12.5px; }
.hint { font-size: 12.5px; color: var(--muted); margin: 6px 0 0; }
[hidden] { display: none !important; }
aside form { display: grid; gap: 8px; padding: 0; border-top: 0; margin-top: 10px; }
aside label { font-size: 13px; color: var(--muted); }
aside label.check { display: flex; gap: 8px; align-items: flex-start; color: var(--ink); }
a.button { display: inline-block; margin-top: 8px; padding: 10px 16px; border-radius: 8px; background: #128c4a; color: #fff; text-decoration: none; font-weight: 500; }
#auth-error { color: #c0392b; }
#otp-dev { background: var(--amber-soft); color: var(--ink); padding: 6px 8px; border-radius: 6px; }
dl { display: grid; grid-template-columns: auto 1fr; gap: 4px 10px; margin: 0; font-size: 12.5px; }
dt { color: var(--muted); }
dd { margin: 0; font-family: ui-monospace, monospace; overflow-wrap: anywhere; }
</style>
</head>
<body>
<header>
<h1>InterioringAI</h1>
<span class="tag">channel sync prototype</span>
<span class="hint" id="status">starting…</span>
</header>
<main>
<section class="panel">
<div id="log" aria-live="polite"></div>
<form id="composer">
<input type="text" id="text" placeholder="Ask about your project…" autocomplete="off" required>
<button type="submit" id="send">Send</button>
</form>
</section>
<aside class="panel">
<div class="block">
<h2>Continue on WhatsApp</h2>
<div id="signin">
<p class="hint">Sign in with your phone number to carry this conversation over to WhatsApp.</p>
<form id="phone-form">
<label for="phone">Phone number</label>
<input type="tel" id="phone" value="+91" autocomplete="tel" required>
<button type="submit" id="send-otp">Send code</button>
</form>
<form id="otp-form" hidden>
<label for="otp">6-digit code</label>
<input type="text" id="otp" inputmode="numeric" maxlength="6" autocomplete="one-time-code" required>
<p class="hint" id="otp-dev" hidden></p>
<label class="check"><input type="checkbox" id="consent" checked> Send me project reminders on WhatsApp</label>
<button type="submit" id="verify">Verify and continue</button>
</form>
</div>
<div id="signed-in" hidden>
<p>Signed in as <strong id="me"></strong></p>
<a id="wa-link" class="button" target="_blank" rel="noopener">Continue on WhatsApp</a>
<p class="hint" id="wa-missing" hidden>The WhatsApp button needs WA_TEST_DISPLAY_NUMBER. Locally, WhatsApp messages are simulated with the fake-inbound script.</p>
<p class="hint" id="consent-state"></p>
</div>
<p class="hint" id="auth-error" role="alert"></p>
</div>
<div class="block">
<h2>Linked phones</h2>
<div id="phones" class="mono">none yet</div>
</div>
<div class="block">
<h2>Debug</h2>
<dl>
<dt>project</dt><dd id="pid">—</dd>
<dt>cursor</dt><dd id="cursor">0</dd>
<dt>messages</dt><dd id="count">0</dd>
<dt>last poll</dt><dd id="polled">—</dd>
</dl>
<p class="hint">Polls every 2s. Open this page on a second device with the same project id to watch both update.</p>
<button class="ghost" id="reset" type="button">Start a new project</button>
</div>
</aside>
</main>
<script nonce="__CSP_NONCE__">
const API = "/api/companion";
const $ = (id) => document.getElementById(id);
let projectId = null;
let cursor = 0;
let polling = false;
function setStatus(text) { $("status").textContent = text; }
function render(message) {
const el = document.createElement("div");
el.className = "msg " + message.role;
const who = message.role === "user" ? "you" : message.role === "assistant" ? "InterioringAI" : "system";
const meta = document.createElement("span");
meta.className = "meta";
meta.appendChild(document.createTextNode("#" + message.seq + " · "));
const channel = document.createElement("span");
if (message.channel === "whatsapp") {
channel.className = "wa";
channel.textContent = "WhatsApp";
} else {
channel.textContent = "Web";
}
meta.appendChild(channel);
meta.appendChild(document.createTextNode(" · " + who));
el.appendChild(meta);
el.appendChild(document.createTextNode(message.text));
if (message.mediaKey) {
const img = document.createElement("img");
img.src = API + "/media/" + message.mediaKey.split("/").map(encodeURIComponent).join("/");
img.alt = "Photo sent on WhatsApp";
img.loading = "lazy";
el.appendChild(img);
}
$("log").appendChild(el);
$("log").scrollTop = $("log").scrollHeight;
cursor = Math.max(cursor, message.seq);
$("cursor").textContent = cursor;
$("count").textContent = $("log").childElementCount;
}
async function api(path, options) {
const res = await fetch(API + path, {
headers: { "content-type": "application/json" },
...options,
});
const body = await res.json();
if (!res.ok || body.success === false) {
throw new Error(body.error?.message || body.message || ("HTTP " + res.status));
}
return body.data ?? body;
}
// A project (its D1 row and its Durable Object) is created LAZILY: only when
// the customer sends their first message or signs in. Opening the page and
// leaving creates nothing.
async function startProject() {
const data = await api("/projects", { method: "POST", body: JSON.stringify({}) });
projectId = data.projectId;
localStorage.setItem("companion.projectId", projectId);
$("pid").textContent = projectId;
}
async function ensureProject() {
if (projectId) return;
await startProject();
// A signed-in customer's new project becomes their active one on WhatsApp.
if (signedInPhone) await claim(undefined);
}
// Forget the current conversation without creating a new one yet.
function clearProject() {
localStorage.removeItem("companion.projectId");
projectId = null;
cursor = 0;
$("log").replaceChildren();
$("pid").textContent = "not created yet";
$("cursor").textContent = "0";
$("count").textContent = "0";
}
async function poll() {
if (!projectId || polling) return;
polling = true;
try {
const data = await api("/projects/" + projectId + "/messages?since=" + cursor);
for (const message of data.messages) render(message);
const links = await api("/projects/" + projectId + "/links");
$("phones").textContent = links.links.length
? links.links.map((l) => "+" + l.phone + " (" + l.status + (l.remindersConsentAt ? ", reminders on" : ", reminders off") + ")").join(", ")
: "none yet";
$("polled").textContent = new Date().toLocaleTimeString();
setStatus("connected");
} catch (err) {
setStatus("poll failed: " + err.message);
} finally {
polling = false;
}
}
$("composer").addEventListener("submit", async (event) => {
event.preventDefault();
const input = $("text");
const text = input.value.trim();
if (!text) return;
input.value = "";
$("send").disabled = true;
try {
await ensureProject();
await api("/projects/" + projectId + "/messages", {
method: "POST",
body: JSON.stringify({ text }),
});
await poll();
} catch (err) {
setStatus("send failed: " + err.message);
} finally {
$("send").disabled = false;
input.focus();
}
});
// ---- Sign in with phone (the existing homeowner phone OTP) ----------------
const AUTH = "/api/homeowner/auth";
let signedInPhone = null;
async function auth(path, body) {
const res = await fetch(AUTH + path, {
method: body === undefined ? "GET" : "POST",
headers: { "content-type": "application/json" },
body: body === undefined ? undefined : JSON.stringify(body),
});
const raw = await res.text();
const data = raw ? JSON.parse(raw) : null;
if (!res.ok) throw new Error((data && data.message) || ("HTTP " + res.status));
return data;
}
function showAuthError(message) { $("auth-error").textContent = message || ""; }
function cleanPhone(raw) { return raw.split(" ").join("").split("-").join(""); }
// Binds this project to the signed-in account and its verified number.
// consent: true / false from the checkbox, or undefined to keep what was saved.
async function claim(consent) {
// Signing in is reason enough to create the project, even before a message:
// the customer clearly means to use it, and WhatsApp needs one to land in.
if (!projectId) await startProject();
const body = consent === undefined ? {} : { remindersConsent: consent };
const data = await api("/projects/" + projectId + "/claim", {
method: "POST",
body: JSON.stringify(body),
});
signedInPhone = data.phone;
$("signin").hidden = true;
$("signed-in").hidden = false;
$("me").textContent = "+" + data.phone;
if (data.whatsappUrl) {
$("wa-link").href = data.whatsappUrl;
$("wa-link").hidden = false;
$("wa-missing").hidden = true;
} else {
$("wa-link").hidden = true;
$("wa-missing").hidden = false;
}
$("consent-state").textContent = data.remindersConsent
? "Reminders on WhatsApp: on"
: "Reminders on WhatsApp: off. You will still get replies when you message.";
await poll();
}
$("phone-form").addEventListener("submit", async (event) => {
event.preventDefault();
showAuthError("");
const phoneNumber = cleanPhone($("phone").value);
$("send-otp").disabled = true;
try {
await auth("/phone-number/send-otp", { phoneNumber });
$("otp-form").hidden = false;
$("otp").focus();
// Local only: the code is never actually sent, so show it here.
// This endpoint is 404 in dev, preview and production.
const dev = await fetch(API + "/dev/otp?phone=" + encodeURIComponent(phoneNumber));
if (dev.ok) {
const devBody = await dev.json();
$("otp-dev").textContent = "Local test mode: no message is sent. Your code is " + devBody.data.code;
$("otp-dev").hidden = false;
}
} catch (err) {
showAuthError("Could not send the code: " + err.message);
} finally {
$("send-otp").disabled = false;
}
});
$("otp-form").addEventListener("submit", async (event) => {
event.preventDefault();
showAuthError("");
$("verify").disabled = true;
try {
await auth("/phone-number/verify", {
phoneNumber: cleanPhone($("phone").value),
code: $("otp").value.trim(),
});
await claim($("consent").checked);
} catch (err) {
showAuthError("Could not sign in: " + err.message);
} finally {
$("verify").disabled = false;
}
});
// Already signed in (cookie from an earlier visit): claim straight away.
async function restoreSession() {
try {
const session = await auth("/get-session");
if (session && session.user) await claim(undefined);
} catch (err) {
// Not signed in, or signed in without a verified phone: stay on the form.
}
}
$("reset").addEventListener("click", () => {
clearProject();
setStatus("new conversation starts with your next message");
});
(async function init() {
try {
const saved = localStorage.getItem("companion.projectId");
if (saved) {
projectId = saved;
$("pid").textContent = projectId;
// Confirm it still exists; a wiped local D1 leaves a stale id behind.
// If it is gone, forget it rather than creating a replacement.
await api("/projects/" + projectId).catch(() => clearProject());
} else {
clearProject();
}
await restoreSession();
if (!projectId) setStatus("ready: your conversation starts with your first message");
await poll();
setInterval(poll, 2000);
} catch (err) {
setStatus("could not start: " + err.message);
}
})();
</script>
</body>
</html>`;
/**
* The page with a per-response CSP nonce stamped on its one <style> and one
* <script>. The API's global policy is `default-src 'none'`, which blocks all
* inline CSS and JS; this page instead ships its own strict policy that admits
* exactly these two blocks and nothing else (see `pageContentSecurityPolicy`).
*/
export function renderCompanionPage(nonce: string): string {
return COMPANION_PAGE_TEMPLATE.replaceAll("__CSP_NONCE__", nonce);
}
export function pageContentSecurityPolicy(nonce: string): string {
return [
"default-src 'none'",
`script-src 'nonce-${nonce}'`,
`style-src 'nonce-${nonce}'`,
// Polls and sends go to the same origin; WhatsApp photos are served
// from /api/companion/media on the same origin too.
"connect-src 'self'",
"img-src 'self'",
"base-uri 'none'",
"form-action 'none'",
"frame-ancestors 'none'",
].join("; ");
}
|