-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproxy.ts
More file actions
64 lines (58 loc) · 2.51 KB
/
proxy.ts
File metadata and controls
64 lines (58 loc) · 2.51 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
/**
* proxy.ts — Origin / Sec-Fetch-Site protection on mutating routes.
*
* Control Tower binds to 127.0.0.1 with no auth. The trust assumption is
* "anything on localhost is the legitimate user." That's wrong as soon as
* a browser is in the loop: any website you visit can `fetch()` against
* 127.0.0.1:3200, and a "simple" POST (no custom headers) is not
* preflighted by CORS — meaning the request hits the API and the malicious
* page's JS just doesn't see the response. The side effect (spawning a
* Claude session, writing to .redeye/*.md) still happens.
*
* Defense: validate Origin / Sec-Fetch-Site on every mutating method.
* Same-origin POSTs from the dashboard pass; cross-origin POSTs from
* drive-by pages fail with 403. GETs are still allowed — they're SOP for
* the no-credentials case and don't mutate.
*
* Migrated from middleware.ts (Next.js 16 renamed the convention to proxy).
*/
import { NextRequest, NextResponse } from "next/server";
const SAFE_METHODS = new Set(["GET", "HEAD", "OPTIONS"]);
const ALLOWED_HOSTS = new Set(["127.0.0.1", "localhost", "[::1]"]);
export function isSameOrigin(req: NextRequest): boolean {
// Sec-Fetch-Site is the modern primary signal. Browsers send it on every
// request and it cannot be set by JS. "same-origin" or "none" (top-level
// nav) are safe; "cross-site" / "same-site" from a different host are not.
const sfs = req.headers.get("sec-fetch-site");
if (sfs === "same-origin" || sfs === "none") return true;
if (sfs === "cross-site" || sfs === "same-site") return false;
// Fail closed when both signals are absent. Older browsers and embedded
// WebViews can omit Sec-Fetch-Site on cross-origin form POSTs (CORS
// "simple requests" aren't preflighted), so trust-on-absence reopens the
// drive-by RCE this middleware exists to block. CLI tools (curl) need to
// pass an Origin header — trivially `-H 'Origin: http://127.0.0.1:3200'`.
const origin = req.headers.get("origin");
if (!origin) return false;
try {
const url = new URL(origin);
return ALLOWED_HOSTS.has(url.hostname);
} catch {
return false;
}
}
// Next.js 16 requires the function to be exported as `proxy` (not `middleware`).
export function proxy(req: NextRequest) {
if (SAFE_METHODS.has(req.method)) {
return NextResponse.next();
}
if (!isSameOrigin(req)) {
return NextResponse.json(
{ error: "Cross-origin request blocked" },
{ status: 403 }
);
}
return NextResponse.next();
}
export const config = {
matcher: ["/api/:path*"],
};