Files
loki/scripts/test/email-escaping.ts
GandMao Nakamoto c41c1809e2 feat(widget): speak your feedback — plus the signals, escaping and docs that were lying (#462)
* fix(email): escape visitor text before it reaches an email body

feedbackShippedTemplate interpolated `excerpt` and `page` raw. Both are
visitor-authored — excerpt is the free-prose suggestion typed into the
widget on a customer's site, page is location.pathname read off that
site — and the resulting HTML is mailed from our own domain to an
address the same visitor supplied.

operatorMailTemplate, four lines below, escaped correctly with an inline
replace-chain. That is the tell: escaping was something each template had
to remember separately, and this one forgot. rss.xml had a third copy of
the same chain.

So the escape is now a named helper both callers share, covering the five
XML predefined entities (the two extra quote forms make it safe in an
attribute as well as a text node, so no caller has to pick a variant).

Also makes the templates importable without a database. logSend's
debug-logs import opened a DB client at module load, which every pure
template in the file inherited — the reason none of them had tests. It is
deferred into the function now; sending logs exactly as before.

Proven by mutation: reverting the escape turns exactly the three
injection assertions red, not the whole file.

* fix(feedback): stop a failed request from answering "nothing needs you"

Three surfaces read an empty array as an empty queue. An empty array is
also what a failed fetch leaves behind, so a 500 or a timeout rendered as
the confident answer "there is nothing here" — on the exact screens an
operator checks to be sure nothing is waiting.

- ControlInbox returned null when total === 0, so both fetches failing
  produced total silence. It now stays quiet while requests are still in
  flight (a failure that resolves fast should not flash), and once they
  settle with nothing, says which of the two happened. When one list
  loads and the other does not, the count renders with a note that it
  may be low rather than presenting a partial total as complete.

- FeedbackInbox dropped `error` from useFetch entirely and fell through
  to "No feedback yet". The load error is now aliased `loadError` —
  `error` was already the mutation error from useFeedbackActions, and
  that collision is how the load error came to be dropped.

- ProjectFeedbackSection treated a failed token GET as "no token", which
  offered "Enable & install" for a widget that may already be live on the
  customer's site. Not knowing is now its own state.

Every new branch is reachable only when a request actually failed; the
genuine empty states are untouched.

* feat(widget): let visitors speak their feedback instead of typing it

Typing a bug report on a phone, on someone else's site, is where most
reports die. The widget now offers a mic: record, the clip is transcribed,
and the text lands in the same textarea appended to whatever was already
typed. The visitor still presses Send — speech-to-text mishears things,
and a mic that auto-sent would file those mistakes under their name.

FleetCrown already had working transcription (terminal, Loki composer,
command palette) but the widget never got it. Two things were missing:

- CORS. /api/beacon/transcribe is public but answers no preflight and
  sets no ACAO, so a cross-origin caller can never read the response.
- Authorization. That route takes no token — it is guarded only by a
  per-IP limiter. Opening it cross-origin would have made it an
  anonymous endpoint that spends our Groq quota for anyone with the URL.

So this adds /api/widget/transcribe rather than widening the beacon
route: same fcw_* token that already authorizes ingest, same per-token
origin allowlist, per-IP and per-token rate limits, and Groq only — the
local-Whisper fallback spawns ffmpeg + python3 on the host, which is not
something to expose to anonymous traffic. The Groq step itself moved to
lib/transcribe.ts so both routes share one implementation instead of
growing two copies of the error mapping.

Also in the widget, from the same audit:
- Recording stops and the mic is released when the panel closes, so the
  browser's recording indicator never outlives the panel on a host site.
- Sub-44px touch targets (the 18px remove-image dot, attach button) get
  a coarse-pointer hit area without changing how they look.
- The pulsing record dot honours prefers-reduced-motion.

Progressive enhancement throughout: no MediaRecorder, or an insecure
origin where getUserMedia is undefined, renders no button at all rather
than a control that cannot work. Bundle 16.3KB -> 20.8KB.

/api/widget is classified "spend" in the demo sandbox — the repo's own
gate caught that omission before this commit existed.

* docs(claude): correct the claims that were sending agents the wrong way

CLAUDE.md is loaded into every agent session, so a false line in it is not
a stale doc — it is an instruction. Each of these was verified against the
code in both directions before editing.

- Session helpers. It named `getCurrentUserId()` and `DEFAULT_USER_ID`;
  neither has existed since 98e88b65. Zero hits in src/. The real API is
  `getApiUserId()` (routes) and `requirePageUserId()` (pages), 64 files.

- The executor model. It said home/ runs on the user's machine "not the
  hosted box", and that Fleet Runner desktop is the "sole" local executor.
  scripts/box-runner.ts is a systemd service ON the box that imports the
  same startWatcher, added in b62e3aeb to delete the laptop dependency,
  and is the DEFAULT per this repo's own SSOT. A third executor,
  scripts/hosted-runner.ts, also exists. Neither was mentioned. An agent
  reading the old text would reason about the wrong machine.

- Husky hooks. Documented as pre-commit tsc+eslint / pre-push test:home.
  Actually pre-commit is eslint on staged files with no tsc, and pre-push
  runs the whole `npm run verify` bundle plus smoke and prod dogfood. The
  practical consequence — pre-push takes minutes — is now stated.

- Dark mode. "always dark mode (.dark on html)" is not true: ThemeProvider
  sets defaultTheme="dark" and a ThemeToggle ships in 8 places. Light is a
  real state, so the old advice to lean on text-white/* would break it.

- Six named components do not exist (ProjectTile, AutopilotCard, PromptRow,
  FeaturedCard, CategoryBar) or survive only as type names
  (ProjectGrid/ProjectDetail). Replaced with what is actually on disk.

- /feedback had no row in the Views table and widget/ had no entry at all,
  despite being a top-level nav surface and the only code strangers on
  other people's sites execute.

Also closes the gap that let widget/ drift unnoticed: `npm run lint` now
covers it alongside src/ and home/. It passes clean today, so this costs
nothing and stops the next regression rather than documenting it.

* docs: delete the agent CLI registry spec

Three independent reasons, any one sufficient:

1. It contains a slur — "A new engineer (or the 'retard' user)" — in a
   public repo. That alone is not something to leave sitting in docs/.

2. Every script it analyses is gone: scripts/cockpit-daemon.sh,
   agent-hook-lib.sh, agent-hook-bridge.sh, and the _agent_definitions.sh
   it proposes creating. Its "high duplication areas" list describes a
   codebase that no longer exists.

3. Its central decision is now false. It names src/lib/agent-registry.ts
   the "Primary SSOT"; that file's own header says it is a compatibility
   shim over src/lib/agents/, kept only for back-compat, and that new code
   should import from @/lib/agents directly. An agent following this spec
   would extend the shim it is supposed to be migrating off.

The refactor this document proposed did happen — differently and better
(per-agent adapter modules, ~300 lines removed). The plan that lost is
not worth keeping as a description of the system that won.

README's link to it goes too, so the docs index has no dead entry.

* docs(widget): stop the architecture note describing a system that moved on

Corrections, each verified against code:

- It said "No rate limiter exists in FleetCrown yet — port revampit's".
  src/lib/rate-limit.ts exists, is owned by the shared limitkit package,
  and is already imported by the ingest route the same document describes.
  Left alone, that bullet is an instruction to write a second one — the
  precise mechanism by which this fleet accumulated 14 rate limiters.

- The API table listed 5 routes and omitted GET /api/widget-boot, which is
  the render gate, the remote kill switch, and the heartbeat behind the
  "Live" badge — i.e. most of what the surrounding prose sells. Added,
  along with the new /api/widget/transcribe pair.

- It claimed /widget.js is "immutable-cached with a version query". There
  is no version query and no cache rule for it; next.config.ts sets those
  for /sw.js only. The "upgrades ship centrally" story rested on caching
  behaviour nobody configured.

- Screenshot capture, the submitter email loop and auto-triage drafts were
  all listed under "Later (not now, YAGNI)" and "not in v1" while being
  shipped and documented elsewhere in the same file.

---------

Co-authored-by: Mao Nakamoto <41178744+maonakamoto@users.noreply.github.com>
2026-09-02 09:27:19 -07:00

70 lines
3.1 KiB
TypeScript

// Visitor-authored text must never reach an email body as markup.
//
// The widget accepts free prose from anonymous visitors on customer sites.
// feedbackShippedTemplate mails that prose back to an address the same visitor
// supplied, from our domain — so an unescaped `excerpt` is an injection path
// into mail that carries our From:. It shipped unescaped while the template
// four lines below it escaped correctly, which is exactly the shape a shared
// helper prevents: the escaping was a thing each template had to remember.
//
// `page` is equally untrusted — it is location.pathname read off the host page.
//
// This pins the invariant rather than the implementation: render a template
// with hostile input and assert no live markup survives.
// Run: npx tsx scripts/test/email-escaping.ts
import { escapeHtml, escapeHtmlWithBreaks } from "../../src/lib/escape-html";
import { feedbackShippedTemplate, operatorMailTemplate } from "../../src/lib/email";
let pass = 0;
let fail = 0;
function ok(cond: boolean, label: string) {
if (cond) {
pass++;
} else {
fail++;
console.error(`✗ ${label}`);
}
}
// ---- the helper itself ----
ok(escapeHtml("<script>") === "&lt;script&gt;", "escapes angle brackets");
ok(escapeHtml("a & b") === "a &amp; b", "escapes ampersand");
ok(escapeHtml(`"quoted"`) === "&quot;quoted&quot;", "escapes double quote (attribute safety)");
ok(escapeHtml("it's") === "it&#39;s", "escapes single quote (attribute safety)");
ok(
escapeHtml("&lt;") === "&amp;lt;",
"ampersand is escaped first, so an existing entity is not double-decoded",
);
ok(escapeHtmlWithBreaks("a\nb") === "a<br>b", "escapeHtmlWithBreaks turns newlines into <br>");
ok(
escapeHtmlWithBreaks("<br>") === "&lt;br&gt;",
"a literal <br> typed by a human stays visible text, not markup",
);
// ---- feedbackShippedTemplate: the route that shipped unescaped ----
const XSS = `<img src=x onerror="alert(1)">`;
const shipped = feedbackShippedTemplate({
site: "example.com",
excerpt: XSS,
page: `/p?<svg onload="alert(2)">`,
});
ok(!shipped.html.includes("<img src=x"), "excerpt: no live <img> tag in html");
ok(!shipped.html.includes('onerror="'), "excerpt: no live onerror attribute in html");
ok(shipped.html.includes("&lt;img"), "excerpt: the tag is present as escaped text");
ok(!shipped.html.includes("<svg onload"), "page: no live <svg> tag in html");
ok(shipped.html.includes("&lt;svg"), "page: the tag is present as escaped text");
// The text/plain alternative is not markup and deliberately keeps raw values —
// pin that too, so a future "escape everything" change does not corrupt it.
ok(shipped.text.includes(XSS), "text/plain alternative keeps the raw excerpt");
// ---- operatorMailTemplate: was already correct, keep it that way ----
const op = operatorMailTemplate({ subject: "hi", body: `<b>bold</b>\nsecond line` });
ok(!op.html.includes("<b>bold</b>"), "operator body: no live <b> tag");
ok(op.html.includes("&lt;b&gt;bold&lt;/b&gt;"), "operator body: tag escaped as text");
ok(op.html.includes("second line"), "operator body: newline preserved as a break");
console.log(`${pass} passed, ${fail} failed`);
process.exit(fail === 0 ? 0 : 1);