The open-source full-stack studio for Opus 5.5 motion video. Reverse engineering for any video. Code video with HTML: recreate, edit and render. BYOA + BYOK · Motion.md · Images, Video, Music & Voice.
TypeScript agent-skillsagentic-aiai-agentsai-videobyokclaude-codecodexdeepseek-harnessdsh-plugingenerative-ailocal-firstmcpmotionmotion-graphicsmultimodalopenmotionreverse-engineeringvideo-editingvideo-generationworkbuddy
fix(security): validate Host header on /api/* to block DNS rebinding (#61)
@aaronjmars2be93108d064
diff --git a/README.md b/README.mdindex 08110fe2..3c552e30 100644--- a/README.md+++ b/README.md@@ -440,6 +440,18 @@ Early but real. The closed loop — **detect agent → pick skill → SSE stream| History / version diff / IndexedDB archive | ⏳ planned || Skill marketplace (`install <github-repo>`) | ⏳ planned |+## Security++The Next API surface is the local-only side of the app — `/api/convert` spawns the user's coding-agent CLI with maximally permissive flags, `/api/deploy` writes credentialed config to disk. Both are intended for a single operator on a single machine. To prevent a malicious page from DNS-rebinding `attacker.example` to `127.0.0.1` and POSTing into those routes through the user's browser, every `/api/*` request is gated on a Host-header allowlist in [`next/src/middleware.ts`](next/src/middleware.ts).++| Setting | When to use |+|---|---|+| **Default (no env vars set)** | The common case — `next dev` / `next start` on your own machine. `127.0.0.1`, `localhost`, and `::1` Host headers (any port) are accepted. Everything else gets a 403 `{ "error": "Host not allowed" }`. |+| **`HTML_ANYTHING_ALLOWED_HOSTS=daemon.mirage.local,html-anything.lan`** | LAN / mDNS setup — you're reaching the app from another device on the same network and the browser dials a non-loopback hostname. Comma-separated; port-insensitive; case-insensitive. The default loopback set is still accepted on top of this. |+| **`HTML_ANYTHING_ALLOW_ANY_HOST=1`** | Reverse-proxy mode — Caddy / nginx / Cloudflare Tunnel is terminating the public hostname and forwarding to the app. The proxy is now responsible for Host policy. Loudly insecure if you set this without a trusted proxy in front, so it is not the default. |++Set the env var in whatever environment file your launcher reads (e.g. `next/.env.local`). The middleware is pinned to the Node runtime (`export const runtime = "nodejs"` in [`next/src/middleware.ts`](next/src/middleware.ts)) so `process.env` is read per-request — Edge middleware can inline `process.env.*` at build time, which would silently break operator overrides set after `next build`. The validation is unit-tested in [`next/src/lib/security/host-validation.test.ts`](next/src/lib/security/host-validation.test.ts) and the loopback-still-works dev path is exercised in the Playwright spec at [`e2e/ui/host-validation.spec.ts`](e2e/ui/host-validation.spec.ts).+## ContributingIssues, PRs, new skills, new agent adapters, new export targets, and translations are all welcome. The highest-leverage contributions are usually **one folder, one Markdown file, or one PR-sized adapter** — small surface area, big leverage. Pick the slot that matches what you want to add:diff --git a/e2e/ui/host-validation.spec.ts b/e2e/ui/host-validation.spec.tsnew file mode 100644index 00000000..128353f1--- /dev/null+++ b/e2e/ui/host-validation.spec.ts@@ -0,0 +1,131 @@+/**+ * End-to-end verification that the API surface refuses requests whose `Host`+ * header isn't on the loopback allowlist. The exact rebinding attack we are+ * defending against would deliver these requests from a real browser tab+ * after a DNS flip; here we use a raw `request.fetch` so we can forge the+ * header directly.+ *+ * The Playwright webServer in `e2e/playwright.config.ts` runs+ * `next start -p 3317`, which binds to every interface by default. The+ * default `baseURL` resolves to `127.0.0.1:3317` — the loopback path. To+ * exercise the rejection path we override the `Host` header to attacker-+ * controlled values while still dialing the real loopback IP.+ *+ * The accept-loopback tests prove the default dev path keeps working —+ * gating on Host must not break the common case where the user opens+ * `http://localhost:3317/` in a browser on their own machine.+ */+import { test, expect, request as playwrightRequest } from "@playwright/test";++const API_PATHS = [+ "/api/agents",+ "/api/templates",+ "/api/deploy/config?provider=vercel",+] as const;++// Matches the `webServer.url` in e2e/playwright.config.ts (port 3317). Used as+// a fallback when the `baseURL` fixture is undefined — exactOptionalPropertyTypes+// rejects passing `string | undefined` to newContext's `baseURL?: string`.+const DEFAULT_BASE_URL = "http://127.0.0.1:3317";++test.describe("API host-header validation", () => {+ test("accepts loopback Host (127.0.0.1) — default dev path", async ({ baseURL }) => {+ const ctx = await playwrightRequest.newContext({+ baseURL: baseURL ?? DEFAULT_BASE_URL,+ extraHTTPHeaders: { Host: "127.0.0.1:3317" },+ });+ for (const p of API_PATHS) {+ const r = await ctx.get(p);+ // Any 2xx / 4xx that ISN'T 403 from this middleware passes — the route+ // may legitimately 400 (missing query / not configured) but it should+ // not be the host-rejection 403.+ if (r.status() === 403) {+ const body = await r.json().catch(() => ({}));+ expect(body.error, `loopback host rejected on ${p}: ${JSON.stringify(body)}`).not.toBe(+ "Host not allowed",+ );+ }+ }+ await ctx.dispose();+ });++ test("accepts localhost Host — default dev path", async ({ baseURL }) => {+ const ctx = await playwrightRequest.newContext({+ baseURL: baseURL ?? DEFAULT_BASE_URL,+ extraHTTPHeaders: { Host: "localhost:3317" },+ });+ const r = await ctx.get("/api/agents");+ expect(r.status()).not.toBe(403);+ await ctx.dispose();+ });++ test("rejects attacker.example Host on every API path", async ({ baseURL }) => {+ const ctx = await playwrightRequest.newContext({+ baseURL: baseURL ?? DEFAULT_BASE_URL,+ extraHTTPHeaders: { Host: "attacker.example" },+ });+ for (const p of API_PATHS) {+ const r = await ctx.get(p);+ expect(r.status(), `${p} should reject attacker.example`).toBe(403);+ const body = await r.json();+ expect(body.error).toBe("Host not allowed");+ }+ await ctx.dispose();+ });++ test("rejects POST /api/convert with attacker Host (RCE vector)", async ({ baseURL }) => {+ const ctx = await playwrightRequest.newContext({+ baseURL: baseURL ?? DEFAULT_BASE_URL,+ extraHTTPHeaders: { Host: "attacker.example" },+ });+ const r = await ctx.post("/api/convert", {+ data: { agent: "claude", templateId: "deck-swiss-international", content: "ignore" },+ });+ expect(r.status(), "POST /api/convert must reject forged Host (RCE vector)").toBe(403);+ await ctx.dispose();+ });++ test("rejects PUT /api/deploy/config with attacker Host (token-write vector)", async ({+ baseURL,+ }) => {+ const ctx = await playwrightRequest.newContext({+ baseURL: baseURL ?? DEFAULT_BASE_URL,+ extraHTTPHeaders: { Host: "attacker.example" },+ });+ const r = await ctx.put("/api/deploy/config?provider=vercel", {+ data: { token: "attacker-token" },+ });+ expect(r.status()).toBe(403);+ await ctx.dispose();+ });++ test("rejects subdomain-tricks (localhost.attacker.example)", async ({ baseURL }) => {+ const ctx = await playwrightRequest.newContext({+ baseURL: baseURL ?? DEFAULT_BASE_URL,+ extraHTTPHeaders: { Host: "localhost.attacker.example" },+ });+ const r = await ctx.get("/api/agents");+ expect(r.status()).toBe(403);+ await ctx.dispose();+ });++ test("rejects empty Host", async ({ baseURL }) => {+ // A single space is deterministically transmitted; per RFC 7230 the+ // receiving parser strips the surrounding OWS and the server sees an+ // empty `host`. The validator's `stripPort.trim()` reduces it to "" and+ // `isAllowedHost("")` returns false → 403. An empty-string value would+ // be at the mercy of Playwright's header-serialization behavior (it may+ // drop the entry, in which case the request goes out with the default+ // loopback Host and the test passes for the wrong reason).+ const ctx = await playwrightRequest.newContext({+ baseURL: baseURL ?? DEFAULT_BASE_URL,+ extraHTTPHeaders: { Host: " " },+ });+ const r = await ctx.get("/api/agents");+ // Some HTTP stacks reject empty Host headers themselves with 400 before+ // it reaches middleware. Either 400 or 403 is acceptable; the key+ // invariant is "no 200".+ expect([400, 403]).toContain(r.status());+ await ctx.dispose();+ });+});diff --git a/next/src/lib/security/host-validation.test.ts b/next/src/lib/security/host-validation.test.tsnew file mode 100644index 00000000..810601a8--- /dev/null+++ b/next/src/lib/security/host-validation.test.ts@@ -0,0 +1,146 @@+import { afterEach, describe, expect, it } from "vitest";+import {+ isAllowedHost,+ isRequestHostAllowed,+ parseAllowedHosts,+ stripPort,+} from "./host-validation";++describe("stripPort", () => {+ it("preserves bare hostnames", () => {+ expect(stripPort("localhost")).toBe("localhost");+ expect(stripPort("127.0.0.1")).toBe("127.0.0.1");+ expect(stripPort("daemon.mirage.local")).toBe("daemon.mirage.local");+ });+ it("strips ipv4 + dns ports", () => {+ expect(stripPort("localhost:3000")).toBe("localhost");+ expect(stripPort("127.0.0.1:3317")).toBe("127.0.0.1");+ expect(stripPort("example.com:443")).toBe("example.com");+ });+ it("strips ipv6 ports while keeping brackets", () => {+ expect(stripPort("[::1]:3000")).toBe("[::1]");+ expect(stripPort("[::1]")).toBe("[::1]");+ });+ it("lower-cases", () => {+ expect(stripPort("LOCALHOST:3000")).toBe("localhost");+ });+ it("does not strip when the trailing chunk is not a port", () => {+ expect(stripPort("not-a-port:abc")).toBe("not-a-port:abc");+ });+ // Documents the fact that bare unbracketed `::1` is mangled by the+ // `last-colon-trailing-digit` branch — the last colon is index 1 and the+ // trailing "1" is all digits, so the slice returns ":". A bare `::1` can+ // therefore never match anything in `LOOPBACK_HOSTS`, which is why only+ // the bracketed `[::1]` form is on the allowlist.+ it("mangles bare ::1 to ':' (only [::1] is a real Host header anyway)", () => {+ expect(stripPort("::1")).toBe(":");+ });+});++describe("parseAllowedHosts", () => {+ it("returns an empty set for undefined / empty input", () => {+ expect(parseAllowedHosts(undefined).size).toBe(0);+ expect(parseAllowedHosts("").size).toBe(0);+ expect(parseAllowedHosts(" , ,").size).toBe(0);+ });+ it("splits + trims + lowercases + strips ports", () => {+ const set = parseAllowedHosts("Daemon.mirage.local, HOST-A:8080 , host-b");+ expect([...set].sort()).toEqual(["daemon.mirage.local", "host-a", "host-b"]);+ });+});++describe("isAllowedHost (defaults — loopback only)", () => {+ it("accepts loopback variants on any port", () => {+ expect(isAllowedHost("127.0.0.1")).toBe(true);+ expect(isAllowedHost("127.0.0.1:3000")).toBe(true);+ expect(isAllowedHost("localhost")).toBe(true);+ expect(isAllowedHost("LOCALHOST:3317")).toBe(true);+ expect(isAllowedHost("[::1]:3000")).toBe(true);+ expect(isAllowedHost("[::1]")).toBe(true);+ });+ it("rejects attacker hosts", () => {+ expect(isAllowedHost("attacker.example")).toBe(false);+ expect(isAllowedHost("attacker.example:80")).toBe(false);+ expect(isAllowedHost("evil.local")).toBe(false);+ // Adjacent loopback aliases that aren't on the allowlist — keep strict+ expect(isAllowedHost("127.0.0.2")).toBe(false);+ expect(isAllowedHost("localhost.attacker.example")).toBe(false);+ });+ // `0.0.0.0` is reachable from a public page on pre-fix Chrome (< 128) — it+ // routes to the local machine on macOS/Linux without needing DNS rebinding.+ // Must be rejected so the gate covers that sibling vector.+ it("rejects 0.0.0.0 (sidesteps DNS rebinding via 0.0.0.0-day vector)", () => {+ expect(isAllowedHost("0.0.0.0")).toBe(false);+ expect(isAllowedHost("0.0.0.0:3317")).toBe(false);+ });+ // Bare unbracketed `::1` is mangled by stripPort (see stripPort tests) and+ // browsers / HTTP/2 always bracket IPv6 in the Host / :authority field.+ it("rejects bare unbracketed ::1 (only [::1] is a real Host header)", () => {+ expect(isAllowedHost("::1")).toBe(false);+ });+ it("rejects empty / missing host", () => {+ expect(isAllowedHost(null)).toBe(false);+ expect(isAllowedHost(undefined)).toBe(false);+ expect(isAllowedHost("")).toBe(false);+ expect(isAllowedHost(" ")).toBe(false);+ });+});++describe("isAllowedHost — operator-extended allowlist", () => {+ const extras = parseAllowedHosts("daemon.mirage.local,html.anything.lan");+ it("accepts entries from extraAllowed (case + port insensitive)", () => {+ expect(isAllowedHost("daemon.mirage.local", { extraAllowed: extras })).toBe(true);+ expect(isAllowedHost("DAEMON.MIRAGE.LOCAL:3000", { extraAllowed: extras })).toBe(true);+ expect(isAllowedHost("html.anything.lan:8080", { extraAllowed: extras })).toBe(true);+ });+ it("still rejects non-listed hosts even when extras are configured", () => {+ expect(isAllowedHost("attacker.example", { extraAllowed: extras })).toBe(false);+ });+ it("accepts a string[] form for extraAllowed (not just Set)", () => {+ expect(+ isAllowedHost("daemon.mirage.local", { extraAllowed: ["daemon.mirage.local"] }),+ ).toBe(true);+ });+});++describe("isAllowedHost — wildcard opt-out", () => {+ it("allowAny=true accepts any host (reverse-proxy mode)", () => {+ expect(isAllowedHost("attacker.example", { allowAny: true })).toBe(true);+ expect(isAllowedHost(null, { allowAny: true })).toBe(true);+ expect(isAllowedHost("", { allowAny: true })).toBe(true);+ });+});++describe("isRequestHostAllowed (env-driven wrapper)", () => {+ const make = (host: string | null) => ({+ headers: {+ get(name: string) {+ return name.toLowerCase() === "host" ? host : null;+ },+ },+ });++ afterEach(() => {+ delete process.env.HTML_ANYTHING_ALLOWED_HOSTS;+ delete process.env.HTML_ANYTHING_ALLOW_ANY_HOST;+ });++ it("respects defaults when no env is set", () => {+ expect(isRequestHostAllowed(make("127.0.0.1:3317"))).toBe(true);+ expect(isRequestHostAllowed(make("attacker.example"))).toBe(false);+ expect(isRequestHostAllowed(make(null))).toBe(false);+ });+ it("extends allowlist via HTML_ANYTHING_ALLOWED_HOSTS", () => {+ process.env.HTML_ANYTHING_ALLOWED_HOSTS = "html.anything.lan";+ expect(isRequestHostAllowed(make("html.anything.lan:3000"))).toBe(true);+ expect(isRequestHostAllowed(make("attacker.example"))).toBe(false);+ });+ it("opt-out wildcard via HTML_ANYTHING_ALLOW_ANY_HOST=1 accepts everything", () => {+ process.env.HTML_ANYTHING_ALLOW_ANY_HOST = "1";+ expect(isRequestHostAllowed(make("attacker.example"))).toBe(true);+ });+ it("envVar=0 stays strict (only '1' opts out)", () => {+ process.env.HTML_ANYTHING_ALLOW_ANY_HOST = "0";+ expect(isRequestHostAllowed(make("attacker.example"))).toBe(false);+ });+});diff --git a/next/src/lib/security/host-validation.ts b/next/src/lib/security/host-validation.tsnew file mode 100644index 00000000..1c92892d--- /dev/null+++ b/next/src/lib/security/host-validation.ts@@ -0,0 +1,125 @@+/**+ * Host-header validator for the Next.js API surface.+ *+ * Threat model:+ * `next dev` and `next start` bind to `0.0.0.0` by default. Even with the+ * server bound to loopback only, a malicious page in the user's browser can+ * DNS-rebind an attacker-controlled name (`attacker.example` → `127.0.0.1`)+ * and POST to `/api/convert`, `/api/deploy`, `/api/deploy/config`, etc.+ * `/api/convert` spawns the user's local coding-agent CLI with maximally+ * permissive flags (`--permission-mode bypassPermissions`, `--yolo`,+ * `--allow-all-tools`, `--dangerously-skip-permissions`, …), so a successful+ * POST is unauthenticated RCE on the user's machine via the agent.+ *+ * The browser blocks attackers from forging `Host` to `localhost`, so a+ * Host-header allowlist is the canonical defense: the browser sends the+ * hostname it dialed (`attacker.example`), we reject it, the request never+ * reaches the handler. Origin / CSRF tokens are not sufficient on their own+ * because no-cors POSTs with `Content-Type: text/plain` skip preflight.+ *+ * Defaults:+ * loopback IPv4 + loopback IPv6 + literal `localhost`, on any port.+ *+ * Operator extensibility:+ * `HTML_ANYTHING_ALLOWED_HOSTS` — comma-separated list (e.g. for a LAN-host+ * setup or a `.local` mDNS name). Each entry matches case-insensitively+ * against the bare hostname; port is ignored.+ * `HTML_ANYTHING_ALLOW_ANY_HOST=1` — opt-out wildcard, intended for behind+ * a trusted reverse proxy that terminates Host itself. Loudly insecure;+ * not the default.+ */++// `0.0.0.0` is intentionally NOT on the allowlist: on macOS/Linux it routes+// to the local machine, and pre-fix Chrome (< 128) lets a public page fetch+// `http://0.0.0.0:<port>` directly — that path bypasses DNS rebinding entirely+// and would still reach the API if we accepted `Host: 0.0.0.0`. The Playwright+// suite dials `127.0.0.1` (see `e2e/playwright.config.ts`), so removing it+// breaks no test.+//+// `::1` (bare) is also omitted: `stripPort("::1")` produces `":"` (the+// last-colon-trailing-digit branch), so a bare unbracketed `::1` can never+// match anyway. Browsers and HTTP/2 `:authority` always bracket IPv6 literals,+// so a bare `::1` doesn't appear in real Host headers either.+const LOOPBACK_HOSTS = new Set([+ "127.0.0.1",+ "localhost",+ "[::1]",+]);++/**+ * Strip the optional port from a Host header value. Handles both IPv4 / DNS+ * (`example.com:3000`) and IPv6 (`[::1]:3000`).+ */+export function stripPort(host: string): string {+ const trimmed = host.trim().toLowerCase();+ if (!trimmed) return "";+ // IPv6 — `[::1]:3000` or `[::1]`+ if (trimmed.startsWith("[")) {+ const end = trimmed.indexOf("]");+ if (end === -1) return trimmed; // malformed; fail in isAllowedHost+ return trimmed.slice(0, end + 1);+ }+ const colon = trimmed.lastIndexOf(":");+ if (colon === -1) return trimmed;+ // Bare IPv6 with multiple colons but no brackets isn't valid in a Host+ // header per RFC 7230, but be defensive: only strip when the part after the+ // last colon is purely digits.+ const after = trimmed.slice(colon + 1);+ if (after.length > 0 && /^\d+$/.test(after)) return trimmed.slice(0, colon);+ return trimmed;+}++/**+ * Parse `HTML_ANYTHING_ALLOWED_HOSTS` into a normalized, lowercased set. Empty+ * entries and whitespace are tolerated.+ */+export function parseAllowedHosts(raw: string | undefined): Set<string> {+ const out = new Set<string>();+ if (!raw) return out;+ for (const part of raw.split(",")) {+ const v = part.trim().toLowerCase();+ if (v) out.add(stripPort(v));+ }+ return out;+}++export type HostValidationOptions = {+ /** Operator-extended allowlist, in addition to the loopback defaults. */+ extraAllowed?: Set<string> | string[];+ /** When true, bypass the allowlist entirely. Driven by env opt-out. */+ allowAny?: boolean;+};++/**+ * Return true iff the `Host` header is one of: a loopback variant, an entry+ * in the operator-extended allowlist, or `*` is enabled via env.+ *+ * `null` / empty host is treated as not allowed — HTTP/1.1 requires a Host+ * header and HTTP/2 maps `:authority` to it, so an empty value is anomalous.+ */+export function isAllowedHost(+ headerHost: string | null | undefined,+ opts: HostValidationOptions = {},+): boolean {+ if (opts.allowAny) return true;+ if (!headerHost) return false;+ const host = stripPort(headerHost);+ if (!host) return false;+ if (LOOPBACK_HOSTS.has(host)) return true;+ const extras =+ opts.extraAllowed instanceof Set+ ? opts.extraAllowed+ : new Set((opts.extraAllowed ?? []).map((h) => stripPort(h.toLowerCase())));+ return extras.has(host);+}++/**+ * Convenience wrapper that reads the two env-vars and the request's Host+ * header. Intended for use from `middleware.ts` so policy lives in one place.+ */+export function isRequestHostAllowed(req: { headers: { get(name: string): string | null } }): boolean {+ return isAllowedHost(req.headers.get("host"), {+ extraAllowed: parseAllowedHosts(process.env.HTML_ANYTHING_ALLOWED_HOSTS),+ allowAny: process.env.HTML_ANYTHING_ALLOW_ANY_HOST === "1",+ });+}diff --git a/next/src/middleware.ts b/next/src/middleware.tsnew file mode 100644index 00000000..1aa6552a--- /dev/null+++ b/next/src/middleware.ts@@ -0,0 +1,45 @@+import { NextRequest, NextResponse } from "next/server";+import { isRequestHostAllowed } from "@/lib/security/host-validation";++/**+ * Gate every `/api/*` request behind a Host-header allowlist. See+ * `next/src/lib/security/host-validation.ts` for the threat-model rationale and+ * env knobs (`HTML_ANYTHING_ALLOWED_HOSTS`, `HTML_ANYTHING_ALLOW_ANY_HOST`).+ *+ * Why /api/*: the static + RSC routes don't have side effects worth gating+ * (and refusing the document would just produce a confusing UX during DNS+ * rebinding). The agent-spawn, file-write, and credentialed network paths+ * all live under `/api/`.+ */+export function middleware(req: NextRequest) {+ if (isRequestHostAllowed(req)) return NextResponse.next();+ return new NextResponse(+ JSON.stringify({+ error: "Host not allowed",+ hint:+ "html-anything's API only accepts requests with a loopback Host header (127.0.0.1, localhost, ::1). " ++ "If you're fronting it behind a different hostname, add it to HTML_ANYTHING_ALLOWED_HOSTS (comma-separated) " ++ "or set HTML_ANYTHING_ALLOW_ANY_HOST=1 if a trusted reverse proxy is terminating Host upstream.",+ }),+ {+ status: 403,+ headers: { "Content-Type": "application/json; charset=utf-8" },+ },+ );+}++// Pin to the Node runtime so `process.env.HTML_ANYTHING_ALLOWED_HOSTS` and+// `process.env.HTML_ANYTHING_ALLOW_ANY_HOST` are read per-request, not+// inlined at build time. On Edge middleware, Next can fold `process.env.*`+// references into the build output — operator-set env in `next/.env.local`+// would then silently fail to take effect after `next start`, locking out+// legitimate LAN hosts (`HTML_ANYTHING_ALLOWED_HOSTS`) or failing to disable+// the gate (`HTML_ANYTHING_ALLOW_ANY_HOST=1`). Node runtime middleware+// (Next 15.2+) sidesteps that by reading env at request time.+export const runtime = "nodejs";++export const config = {+ // Run on every API route. Excludes static assets, RSC payloads, and the+ // page tree — those are not the rebinding-attack surface.+ matcher: ["/api/:path*"],+};