(req)
| 50 | |
| 51 | export default { |
| 52 | async fetch(req) { |
| 53 | try { |
| 54 | // Cloudflare dashboard and browsers commonly test a Worker with GET. |
| 55 | // Return a friendly health response so users don't misread it as failure. |
| 56 | if (req.method === "GET") { |
| 57 | return Response.json( |
| 58 | { |
| 59 | ok: true, |
| 60 | status: "healthy", |
| 61 | message: "Everything is OK. Worker is deployed and reachable.", |
| 62 | usage: "Send POST with relay payload for actual proxy requests.", |
| 63 | }, |
| 64 | { status: 200 } |
| 65 | ); |
| 66 | } |
| 67 | |
| 68 | if (req.method !== "POST") { |
| 69 | return Response.json( |
| 70 | { |
| 71 | e: "method_not_allowed", |
| 72 | message: "Use POST for relay requests. GET is only a health check.", |
| 73 | }, |
| 74 | { status: 405 } |
| 75 | ); |
| 76 | } |
| 77 | |
| 78 | const body = await req.json(); |
| 79 | if (!body || typeof body !== "object") { |
| 80 | return Response.json({ e: "bad_json" }, { status: 400 }); |
| 81 | } |
| 82 | |
| 83 | if (!PSK) { |
| 84 | return Response.json({ e: "server_psk_missing" }, { status: 500 }); |
| 85 | } |
| 86 | |
| 87 | const k = String(body.k ?? ""); |
| 88 | const u = String(body.u ?? ""); |
| 89 | const m = String(body.m ?? "GET").toUpperCase(); |
| 90 | const h = sanitizeHeaders(body.h); |
| 91 | const b64 = body.b; |
| 92 | |
| 93 | if (k !== PSK) return Response.json({ e: "unauthorized" }, { status: 401 }); |
| 94 | if (!/^https?:\/\//i.test(u)) return Response.json({ e: "bad_url" }, { status: 400 }); |
| 95 | |
| 96 | // ── Loop detection ──────────────────────────────────────────────────── |
| 97 | // Case 1 — self-loop: target URL resolves back to this Worker. |
| 98 | // Happens when a user sets exit_node_url to the Worker URL itself. |
| 99 | try { |
| 100 | const targetHost = new URL(u).hostname.toLowerCase(); |
| 101 | const workerHost = new URL(req.url).hostname.toLowerCase(); |
| 102 | if (targetHost === workerHost) { |
| 103 | return Response.json( |
| 104 | { e: "loop_detected", detail: "target URL resolves to this Worker" }, |
| 105 | { status: 508 } |
| 106 | ); |
| 107 | } |
| 108 | } catch (_) { |
| 109 | // Malformed URL already caught by the regex above; ignore parse errors. |
no test coverage detected