#[cfg(windows)]
#[allow(dead_code)]
const SYS_CURL: &str = "C:\\Windows\\System32\\curl.exe";
#[cfg(not(windows))]
#[allow(dead_code)]
const SYS_CURL: &str = "curl";
#[allow(dead_code)]
fn _helix_allowed(var: &str, what: &str) -> bool {
let ok = std::env::var(var).map(|v| v == "1").unwrap_or(false);
if !ok {
eprintln!("helix: BLOCKED {} -- permission denied (set {}=1 to allow; `hxc run` allows by default, a `hxc build`/`export-rust` binary does not)", what, var);
}
ok
}
#[cfg(windows)]
#[allow(dead_code)]
fn _nw_exec(mut c: std::process::Command) -> std::process::Command {
if !_helix_allowed("HELIX_ALLOW_RUN", "process execution") {
std::process::exit(13);
}
use std::os::windows::process::CommandExt;
c.creation_flags(0x08000000);
c
}
#[cfg(not(windows))]
#[allow(dead_code)]
fn _nw_exec(c: std::process::Command) -> std::process::Command {
if !_helix_allowed("HELIX_ALLOW_RUN", "process execution") {
std::process::exit(13);
}
c
}
#[cfg(windows)]
#[allow(dead_code)]
fn _nw_net(mut c: std::process::Command) -> std::process::Command {
if !_helix_allowed("HELIX_ALLOW_NET", "network access") {
std::process::exit(13);
}
use std::os::windows::process::CommandExt;
c.creation_flags(0x08000000);
c
}
#[cfg(not(windows))]
#[allow(dead_code)]
fn _nw_net(c: std::process::Command) -> std::process::Command {
if !_helix_allowed("HELIX_ALLOW_NET", "network access") {
std::process::exit(13);
}
c
}
pub const MAX_BODY: usize = 1 << 20;
pub const MAX_HEAD: usize = 16 * 1024;
const VERSIONS: [&str; 3] = ["2025-06-18", "2025-03-26", "2024-11-05"];
#[derive(Debug, Default)]
pub struct Head {
pub method: String,
pub path: String,
pub headers: Vec<(String, String)>,
pub length: Option<usize>,
}
pub fn head_end(buf: &[u8]) -> Option<usize> {
buf.windows(4).position(|w| w == b"\r\n\r\n").map(|i| i + 4)
}
pub fn parse_head(raw: &[u8]) -> Result<Head, u16> {
let text = std::str::from_utf8(raw).map_err(|_| 400u16)?;
let mut lines = text.trim_end_matches("\r\n").split("\r\n");
let request = lines.next().unwrap_or("");
let mut parts = request.split(' ');
let (Some(method), Some(target), Some(version), None) =
(parts.next(), parts.next(), parts.next(), parts.next())
else {
return Err(400);
};
if !version.starts_with("HTTP/1.") || method.is_empty() || !target.starts_with('/') {
return Err(400);
}
let mut head = Head {
method: method.to_string(),
path: target.split('?').next().unwrap_or("").to_string(),
..Head::default()
};
for line in lines {
if line.starts_with(' ') || line.starts_with('\t') {
return Err(400);
}
let Some((name, value)) = line.split_once(':') else {
return Err(400);
};
let name = name.to_ascii_lowercase();
if name.is_empty() || name.contains(' ') {
return Err(400);
}
if name == "transfer-encoding" {
return Err(501);
}
if name == "content-length" {
let n = value.trim().parse::<usize>().map_err(|_| 400u16)?;
if head.length.is_some() {
return Err(400);
}
head.length = Some(n);
}
head.headers.push((name, value.trim().to_string()));
}
Ok(head)
}
pub fn header<'a>(head: &'a Head, name: &str) -> Option<&'a str> {
head.headers
.iter()
.find(|(k, _)| k == name)
.map(|(_, v)| v.as_str())
}
pub fn same_secret(a: &[u8], b: &[u8]) -> bool {
if a.len() != b.len() {
return false;
}
let mut diff = 0u8;
for (x, y) in a.iter().zip(b.iter()) {
diff |= x ^ y;
}
std::hint::black_box(diff) == 0
}
pub fn origin_ok(origin: &str, allow: &[String]) -> bool {
origin.starts_with("https://") && allow.iter().any(|a| a.eq_ignore_ascii_case(origin))
}
pub fn version_ok(value: &str) -> bool {
VERSIONS.contains(&value)
}
pub fn admit(head: &Head, key: &str, allow: &[String]) -> Result<(), u16> {
if head.path != "/mcp" {
return Err(404);
}
if let Some(origin) = header(head, "origin") {
if !origin_ok(origin, allow) {
return Err(403);
}
}
let sent = header(head, "x-api-key").unwrap_or("");
if key.is_empty() || !same_secret(sent.as_bytes(), key.as_bytes()) {
return Err(401);
}
if head.method != "POST" {
return Err(405);
}
if let Some(v) = header(head, "mcp-protocol-version") {
if !version_ok(v) {
return Err(400);
}
}
match head.length {
None => return Err(411),
Some(n) if n > MAX_BODY => return Err(413),
Some(_) => {} }
Ok(())
}
pub fn reason(status: u16) -> &'static str {
match status {
200 => "OK",
202 => "Accepted",
400 => "Bad Request",
401 => "Unauthorized",
403 => "Forbidden",
404 => "Not Found",
405 => "Method Not Allowed",
408 => "Request Timeout",
411 => "Length Required",
413 => "Content Too Large",
431 => "Request Header Fields Too Large",
501 => "Not Implemented",
503 => "Service Unavailable",
_ => "Internal Server Error",
}
}
pub fn reply(status: u16, body: &str) -> Vec<u8> {
let none = status == 202;
let mut out = format!(
"HTTP/1.1 {status} {}\r\nConnection: close\r\nCache-Control: no-store\r\n",
reason(status)
);
if status == 405 {
out.push_str("Allow: POST\r\n");
}
if none {
out.push_str("Content-Length: 0\r\n\r\n");
} else {
out.push_str(&format!(
"Content-Type: application/json\r\nContent-Length: {}\r\n\r\n{body}",
body.len()
));
}
out.into_bytes()
}
pub fn refusal(status: u16) -> Vec<u8> {
reply(
status,
&format!(
"{{\"jsonrpc\":\"2.0\",\"id\":null,\"error\":{{\"code\":-32000,\"message\":\"{}\"}}}}",
reason(status)
),
)
}