Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
72 changes: 72 additions & 0 deletions next/src/app/api/marketplace/_lib/__tests__/host-guard.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import { hostRejectedResponse, isHostAllowed } from "../host-guard";

describe("isHostAllowed", () => {
const original = {
allowed: process.env.HTML_ANYTHING_ALLOWED_HOSTS,
any: process.env.HTML_ANYTHING_ALLOW_ANY_HOST,
};

beforeEach(() => {
delete process.env.HTML_ANYTHING_ALLOWED_HOSTS;
delete process.env.HTML_ANYTHING_ALLOW_ANY_HOST;
});

afterEach(() => {
if (original.allowed === undefined) delete process.env.HTML_ANYTHING_ALLOWED_HOSTS;
else process.env.HTML_ANYTHING_ALLOWED_HOSTS = original.allowed;
if (original.any === undefined) delete process.env.HTML_ANYTHING_ALLOW_ANY_HOST;
else process.env.HTML_ANYTHING_ALLOW_ANY_HOST = original.any;
});

function reqWithHost(host: string | null): Request {
// undici (fetch-spec) forbids the "host" request header; encode the host
// into the URL instead. The guard reads `req.headers.get('host')` first
// and falls back to `new URL(req.url).host`, which matches reality —
// browsers populate Host from the URL they dial.
const url = host === null ? "file:///no-url-host" : `http://${host}/api/marketplace/install`;
return new Request(url, { method: "POST" });
}

it("allows loopback IPv4 with a port", () => {
expect(isHostAllowed(reqWithHost("127.0.0.1:3000"))).toBe(true);
});

it("allows literal localhost", () => {
expect(isHostAllowed(reqWithHost("localhost"))).toBe(true);
});

it("allows IPv6 loopback in bracketed form", () => {
expect(isHostAllowed(reqWithHost("[::1]:3000"))).toBe(true);
});

it("rejects an attacker-controlled hostname (the DNS-rebinding case)", () => {
expect(isHostAllowed(reqWithHost("evil.example.com"))).toBe(false);
});

it("rejects a request with no Host header", () => {
expect(isHostAllowed(reqWithHost(null))).toBe(false);
});

it("allows a hostname listed in HTML_ANYTHING_ALLOWED_HOSTS", () => {
process.env.HTML_ANYTHING_ALLOWED_HOSTS = "ha.local, my-box";
expect(isHostAllowed(reqWithHost("ha.local:3000"))).toBe(true);
expect(isHostAllowed(reqWithHost("my-box"))).toBe(true);
expect(isHostAllowed(reqWithHost("other.host"))).toBe(false);
});

it("accepts any host when HTML_ANYTHING_ALLOW_ANY_HOST=1 (trusted-proxy mode)", () => {
process.env.HTML_ANYTHING_ALLOW_ANY_HOST = "1";
expect(isHostAllowed(reqWithHost("anything.com"))).toBe(true);
});
});

describe("hostRejectedResponse", () => {
it("returns a 403 JSON response with an actionable hint", async () => {
const res = hostRejectedResponse();
expect(res.status).toBe(403);
const body = (await res.json()) as { error: string; hint: string };
expect(body.error).toBe("host_not_allowed");
expect(body.hint).toContain("HTML_ANYTHING_ALLOWED_HOSTS");
});
});
78 changes: 78 additions & 0 deletions next/src/app/api/marketplace/_lib/host-guard.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
/**
* Per-route Host-header guard for marketplace install/uninstall.
*
* Why this lives next to the marketplace routes rather than at the middleware
* layer: a sibling PR (security/api-host-validation) introduces a global
* `/api/*` middleware that covers every API route. Until that lands, the
* marketplace POST is a particularly attractive DNS-rebinding target — it
* downloads and writes arbitrary user-supplied GitHub repos to disk and
* registers them as installable skills. So we ship a local check here that:
* - mirrors the same default (loopback-only) and env knobs
* (`HTML_ANYTHING_ALLOWED_HOSTS`, `HTML_ANYTHING_ALLOW_ANY_HOST`),
* - is independent of the middleware so it works whichever PR lands first,
* - becomes a redundant no-op once the global middleware also runs.
*
* Once the global host-validation middleware merges, this module can be
* deleted and the routes can rely on the middleware alone.
*/

const LOOPBACK_HOSTS = new Set(["127.0.0.1", "localhost", "::1", "0.0.0.0"]);

function stripPort(host: string): string {
const trimmed = host.trim().toLowerCase();
if (!trimmed) return "";
if (trimmed.startsWith("[")) {
const end = trimmed.indexOf("]");
if (end === -1) return trimmed;
return trimmed.slice(1, end);
}
const colon = trimmed.lastIndexOf(":");
if (colon === -1) return trimmed;
const tail = trimmed.slice(colon + 1);
return /^\d+$/.test(tail) ? trimmed.slice(0, colon) : trimmed;
}

function parseAllowlist(): Set<string> {
const raw = process.env.HTML_ANYTHING_ALLOWED_HOSTS;
if (!raw) return new Set();
return new Set(
raw
.split(",")
.map((s) => s.trim().toLowerCase())
.filter(Boolean),
);
}

export function isHostAllowed(req: Request): boolean {
if (process.env.HTML_ANYTHING_ALLOW_ANY_HOST === "1") return true;
// Prefer the Host header — that's what browsers send and what the dev-server
// populates over the wire. Fall back to `new URL(req.url).host` because
// fetch-spec-compliant `Request` constructors (undici, browsers) forbid
// setting Host explicitly, and tests have to rely on the URL.
const rawHost = req.headers.get("host") ?? safeUrlHost(req.url);
if (!rawHost) return false;
const host = stripPort(rawHost);
if (!host) return false;
if (LOOPBACK_HOSTS.has(host)) return true;
return parseAllowlist().has(host);
}

function safeUrlHost(url: string): string | null {
try {
return new URL(url).host;
} catch {
return null;
}
}

export function hostRejectedResponse(): Response {
return new Response(
JSON.stringify({
error: "host_not_allowed",
hint:
"marketplace install/uninstall only accepts loopback Host. " +
"Add the hostname to HTML_ANYTHING_ALLOWED_HOSTS or set HTML_ANYTHING_ALLOW_ANY_HOST=1 behind a trusted proxy.",
}),
{ status: 403, headers: { "Content-Type": "application/json; charset=utf-8" } },
);
}
32 changes: 32 additions & 0 deletions next/src/app/api/marketplace/install/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import { NextResponse } from "next/server";
import { installFromGitHub, InstallError } from "@/lib/skills/install";
import { invalidateSkillsCache } from "@/lib/templates/loader";
import { hostRejectedResponse, isHostAllowed } from "../_lib/host-guard";

export const runtime = "nodejs";
export const dynamic = "force-dynamic";

export async function POST(req: Request) {
if (!isHostAllowed(req)) return hostRejectedResponse();
let body: unknown;
try {
body = await req.json();
} catch {
return NextResponse.json({ error: "invalid_json" }, { status: 400 });
}
const spec = (body as { source?: unknown } | null)?.source;
if (typeof spec !== "string" || !spec.trim()) {
return NextResponse.json({ error: "missing_source" }, { status: 400 });
}
try {
const result = await installFromGitHub(spec);
invalidateSkillsCache();
return NextResponse.json({ package: result.package });
} catch (err) {
if (err instanceof InstallError) {
return NextResponse.json({ error: err.code, message: err.message }, { status: 400 });
}
const message = err instanceof Error ? err.message : String(err);
return NextResponse.json({ error: "install_failed", message }, { status: 500 });
}
}
23 changes: 23 additions & 0 deletions next/src/app/api/marketplace/packages/[id]/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { NextResponse } from "next/server";
import { uninstallPackage } from "@/lib/skills/install";
import { invalidateSkillsCache } from "@/lib/templates/loader";
import { hostRejectedResponse, isHostAllowed } from "../../_lib/host-guard";

export const runtime = "nodejs";
export const dynamic = "force-dynamic";

type Ctx = { params: Promise<{ id: string }> };

export async function DELETE(req: Request, ctx: Ctx) {
if (!isHostAllowed(req)) return hostRejectedResponse();
const { id } = await ctx.params;
if (!/^[a-z0-9._-]+__[a-z0-9._-]+$/i.test(id)) {
return NextResponse.json({ error: "invalid_id" }, { status: 400 });
}
const removed = await uninstallPackage(id);
if (!removed) {
return NextResponse.json({ error: "not_found" }, { status: 404 });
}
invalidateSkillsCache();
return NextResponse.json({ ok: true });
}
21 changes: 21 additions & 0 deletions next/src/app/api/marketplace/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { NextResponse } from "next/server";
import { listPackages } from "@/lib/skills/registry";
import { hostRejectedResponse, isHostAllowed } from "./_lib/host-guard";

export const runtime = "nodejs";
export const dynamic = "force-dynamic";

/**
* List every installed marketplace package.
*
* Gated behind the same Host guard as install/uninstall — even though this
* is read-only, returning installed packages to a DNS-rebinding origin
* would leak repo owners / names / refs from the user's local app to any
* site they visit. Once the global `/api/*` middleware (PR #61) lands, the
* per-route check here is redundant; until then it must cover the whole
* marketplace surface, not just the write endpoints.
*/
export async function GET(req: Request) {
if (!isHostAllowed(req)) return hostRejectedResponse();
return NextResponse.json({ packages: listPackages() });
}
Loading
Loading