Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 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 });
}
10 changes: 10 additions & 0 deletions next/src/app/api/marketplace/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { NextResponse } from "next/server";
import { listPackages } from "@/lib/skills/registry";

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

/** List every installed marketplace package. */
export async function GET() {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This new GET /api/marketplace route is the one marketplace endpoint that still skips isHostAllowed(). Because the stopgap host guard here exists specifically to cover the DNS-rebinding window before the global /api/* middleware lands, leaving the read endpoint open still lets an untrusted rebinding origin enumerate the user's installed packages, including repo owners/names/refs, from the local app. That is a real privacy leak even though install/uninstall are now protected. Please apply the same hostRejectedResponse() / isHostAllowed() check here (or land the shared middleware in the same release) so the temporary defense covers the whole marketplace API surface.

🔁 Powered by Looper · runner=reviewer · agent=opencode · An autonomous AI dev team for your GitHub repos.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in ce8c86e. You're right — the per-route guard's whole purpose is to cover the DNS-rebinding window until #61's /api/* middleware lands, so leaving the read endpoint open undermines that goal. Even though listing installed packages is "just" a read, the response includes source.{owner,repo,ref} + installedAt for every package, which is exactly the kind of info a rebinding origin should not be able to enumerate from the user's local app.

Applied the same hostRejectedResponse() / isHostAllowed() pair to GET. New regression test in api.test.ts > "returns 403 when the Host header is not loopback — even for the read endpoint" drives a request from http://evil.example.com/api/marketplace and asserts 403 + host_not_allowed, matching the existing install-route test. The empty-list and post-uninstall happy-path tests now pass a loopback Request.

The whole marketplace surface (GET /api/marketplace, POST /api/marketplace/install, DELETE /api/marketplace/packages/[id]) is now covered by the stopgap guard, and the entire stopgap can be deleted once #61 merges.

129/129 green, typecheck/build/guard clean.

return NextResponse.json({ packages: listPackages() });
}
Loading
Loading