Fix Neko browser proxy routing so blocked hosts use ShellCrash and UI toggle applies reliably.
Direct-first egress with proxycheap (7894) vs mix (7890) fallback, dedupe stack env keys, share proxy across 9200/9201, and force reconfigure on manual toggle. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
parent
ff70c9f5f6
commit
e41897d341
@ -52,16 +52,19 @@ SHELLCRASH_WG_CIDR=10.88.0.0/24
|
||||
# LIVE_HTTP_PROXY=
|
||||
# LIVE_HTTPS_PROXY=
|
||||
# LIVE_NO_PROXY=localhost,127.0.0.1,10.0.0.0/8,172.16.0.0/12,192.168.0.0/16,*.lan,*.local
|
||||
# Neko 浏览器 HTTP 代理总开关;默认 0=关闭(走宿主机/软路由直连)。
|
||||
# 当直连 Google/YouTube 失败且 ShellCrash 代理可用时,控制台/启动脚本会自动设为 1(除非 NEKO_BROWSER_PROXY_MANUAL=1)。
|
||||
# Neko 浏览器代理总开关(proxycheap 静态住宅 IP,默认端口 7894)。
|
||||
# 仅当宿主机本身无法直连 Google/YouTube 时,Neko 才走 ShellCrash:
|
||||
# - 开关 ON -> proxycheap 专用 listener(NEKO_SHELLCRASH_PROXY_PORT,默认 7894)
|
||||
# - 开关 OFF -> ShellCrash 主 mixed 口(7890),仍翻墙,不走 proxycheap
|
||||
# 若宿主机已有软路由/可直连外网,Neko 始终直连,不受此开关影响。
|
||||
ENABLE_NEKO_BROWSER_PROXY=0
|
||||
# 用户在控制台手动切换 Neko 代理后设为 1,阻止自动开关覆盖手动选择。
|
||||
# NEKO_BROWSER_PROXY_MANUAL=0
|
||||
# Neko 专用 ShellCrash mixed listener(与 FFmpeg 的 7890/tuic3 出口隔离;仅 ENABLE_NEKO_BROWSER_PROXY=1 时生效)
|
||||
# Neko 专用 ShellCrash mixed listener(proxycheap 静态住宅 IP;仅直连失败且开关 ON 时生效)
|
||||
NEKO_SHELLCRASH_PROXY_PORT=7894
|
||||
SHELLCRASH_NEKO_PROXY_NODE=proxycheap
|
||||
# 多开 Neko 时务必给每条线路独立出口,否则 Google 会把同 IP 第二账号登录判为“登录取消”。
|
||||
# 方式 A:总开关,自动用 7894、7895、7896...
|
||||
# 仅当 NEKO_BROWSER_PROXY_PER_INSTANCE=1 且 proxycheap 开关 ON 时,实例 2/3... 才会使用独立端口。
|
||||
# NEKO_BROWSER_PROXY_PER_INSTANCE=1
|
||||
# 方式 B:显式指定(推荐)
|
||||
# NEKO_SHELLCRASH_PROXY_PORT_1=7894
|
||||
|
||||
@ -2238,37 +2238,84 @@ shellcrash_proxy_available() {
|
||||
return 1
|
||||
}
|
||||
|
||||
neko_shellcrash_proxy_port_from_url() {
|
||||
local url="${1:-}" port=""
|
||||
port="$(printf '%s' "$url" | sed -n 's|.*:\([0-9][0-9]*\)$|\1|p')"
|
||||
case "$port" in
|
||||
"$(shellcrash_neko_proxy_port)"|"$(shellcrash_mix_port)"|"$(shellcrash_redir_port)"|"$(shellcrash_tproxy_port)")
|
||||
printf '%s' "$port"
|
||||
return 0
|
||||
;;
|
||||
esac
|
||||
return 1
|
||||
}
|
||||
|
||||
neko_shellcrash_attach_disabled() {
|
||||
case "${SHELLCRASH_ATTACH_NEKO:-auto}" in
|
||||
0|false|FALSE|off|OFF|none|NONE|direct|DIRECT) return 0 ;;
|
||||
*) return 1 ;;
|
||||
esac
|
||||
}
|
||||
|
||||
resolve_neko_browser_proxy_primary_port() {
|
||||
if neko_browser_proxy_switch_enabled; then
|
||||
shellcrash_neko_proxy_port
|
||||
else
|
||||
shellcrash_mix_port
|
||||
fi
|
||||
}
|
||||
|
||||
resolve_neko_browser_proxy_fallback_port() {
|
||||
if neko_browser_proxy_switch_enabled; then
|
||||
shellcrash_mix_port
|
||||
else
|
||||
shellcrash_neko_proxy_port
|
||||
fi
|
||||
}
|
||||
|
||||
resolve_neko_browser_proxy() {
|
||||
case "${NEKO_BROWSER_PROXY:-}" in
|
||||
0|false|FALSE|off|OFF|none|NONE|direct|DIRECT)
|
||||
printf '%s' "$NEKO_BROWSER_PROXY"
|
||||
return 0
|
||||
neko_shellcrash_attach_disabled && printf '%s' "$NEKO_BROWSER_PROXY" && return 0
|
||||
;;
|
||||
?*)
|
||||
printf '%s' "$NEKO_BROWSER_PROXY"
|
||||
return 0
|
||||
if neko_browser_proxy_url_is_usable "$NEKO_BROWSER_PROXY"; then
|
||||
if neko_shellcrash_proxy_port_from_url "$NEKO_BROWSER_PROXY" >/dev/null 2>&1; then
|
||||
local shell_port
|
||||
shell_port="$(neko_shellcrash_proxy_port_from_url "$NEKO_BROWSER_PROXY")"
|
||||
if shellcrash_proxy_available "$shell_port"; then
|
||||
printf 'http://host.docker.internal:%s' "$shell_port"
|
||||
return 0
|
||||
fi
|
||||
system_direct_global_ready && return 0
|
||||
else
|
||||
printf '%s' "$NEKO_BROWSER_PROXY"
|
||||
return 0
|
||||
fi
|
||||
fi
|
||||
;;
|
||||
esac
|
||||
neko_browser_proxy_switch_enabled || return 0
|
||||
case "${SHELLCRASH_ATTACH_NEKO:-auto}" in
|
||||
0|false|FALSE|off|OFF|none|NONE|direct|DIRECT)
|
||||
return 0
|
||||
;;
|
||||
esac
|
||||
local port
|
||||
port="$(shellcrash_neko_proxy_port)"
|
||||
neko_shellcrash_attach_disabled && return 0
|
||||
system_direct_global_ready && return 0
|
||||
local port fallback
|
||||
port="$(resolve_neko_browser_proxy_primary_port)"
|
||||
if shellcrash_proxy_available "$port"; then
|
||||
printf 'http://host.docker.internal:%s' "$port"
|
||||
return 0
|
||||
fi
|
||||
if system_direct_global_ready; then
|
||||
fallback="$(resolve_neko_browser_proxy_fallback_port)"
|
||||
if [ -n "$fallback" ] && [ "$fallback" != "$port" ] && shellcrash_proxy_available "$fallback"; then
|
||||
printf 'http://host.docker.internal:%s' "$fallback"
|
||||
return 0
|
||||
fi
|
||||
shellcrash_autostart_if_needed >/dev/null 2>&1 || true
|
||||
port="$(shellcrash_neko_proxy_port)"
|
||||
if shellcrash_proxy_available "$port"; then
|
||||
printf 'http://host.docker.internal:%s' "$port"
|
||||
fi
|
||||
for port in "$(resolve_neko_browser_proxy_primary_port)" "$(resolve_neko_browser_proxy_fallback_port)"; do
|
||||
[ -n "$port" ] || continue
|
||||
if shellcrash_proxy_available "$port"; then
|
||||
printf 'http://host.docker.internal:%s' "$port"
|
||||
return 0
|
||||
fi
|
||||
done
|
||||
}
|
||||
|
||||
ensure_neko_browser_launcher_executable() {
|
||||
|
||||
@ -227,14 +227,28 @@ stack_env_upsert() {
|
||||
[ -n "$key" ] || return 1
|
||||
mkdir -p "$(dirname "$STACK_ENV")"
|
||||
touch "$STACK_ENV"
|
||||
# Always keep Unix newlines; CR breaks `source` and docker publish ports.
|
||||
sed -i 's/\r$//' "$STACK_ENV" 2>/dev/null || true
|
||||
value="${value//$'\r'/}"
|
||||
if grep -q "^${key}=" "$STACK_ENV" 2>/dev/null; then
|
||||
sed -i "s|^${key}=.*|${key}=${value}|" "$STACK_ENV"
|
||||
else
|
||||
printf '%s=%s\n' "$key" "$value" >>"$STACK_ENV"
|
||||
local prefix="${key}=" next_line="${key}=${value}"
|
||||
local line kept="" found=0
|
||||
: >"${STACK_ENV}.tmp"
|
||||
while IFS= read -r line || [ -n "$line" ]; do
|
||||
case "$line" in
|
||||
"${prefix}"*)
|
||||
if [ "$found" -eq 0 ]; then
|
||||
printf '%s\n' "$next_line" >>"${STACK_ENV}.tmp"
|
||||
found=1
|
||||
fi
|
||||
;;
|
||||
*)
|
||||
printf '%s\n' "$line" >>"${STACK_ENV}.tmp"
|
||||
;;
|
||||
esac
|
||||
done <"$STACK_ENV"
|
||||
if [ "$found" -eq 0 ]; then
|
||||
printf '%s\n' "$next_line" >>"${STACK_ENV}.tmp"
|
||||
fi
|
||||
mv "${STACK_ENV}.tmp" "$STACK_ENV"
|
||||
sed -i 's/\r$//' "$STACK_ENV" 2>/dev/null || true
|
||||
}
|
||||
|
||||
@ -1432,14 +1446,10 @@ neko_browser_proxy_url_is_usable() {
|
||||
}
|
||||
|
||||
neko_proxy_url_for_port() {
|
||||
local port="$1" host_ip
|
||||
local port="$1"
|
||||
[ -n "$port" ] || return 1
|
||||
host_ip="$(resolve_neko_docker_host_ip)"
|
||||
if [ "$host_ip" = "host-gateway" ] || ! neko_docker_bridge_ipv4_is_usable "$host_ip"; then
|
||||
printf 'http://host.docker.internal:%s' "$port"
|
||||
else
|
||||
printf 'http://%s:%s' "$host_ip" "$port"
|
||||
fi
|
||||
# Use host.docker.internal; compose extra_hosts maps it to the reachable host gateway.
|
||||
printf 'http://host.docker.internal:%s' "$port"
|
||||
}
|
||||
|
||||
shellcrash_docker_cidr() {
|
||||
@ -1564,11 +1574,36 @@ shellcrash_proxy_available() {
|
||||
return 1
|
||||
}
|
||||
|
||||
neko_shellcrash_attach_disabled() {
|
||||
case "${SHELLCRASH_ATTACH_NEKO:-auto}" in
|
||||
0|false|FALSE|off|OFF|none|NONE|direct|DIRECT) return 0 ;;
|
||||
*) return 1 ;;
|
||||
esac
|
||||
}
|
||||
|
||||
# ENABLE_NEKO_BROWSER_PROXY=1 -> proxycheap listener (NEKO_SHELLCRASH_PROXY_PORT, default 7894).
|
||||
# ENABLE_NEKO_BROWSER_PROXY=0 -> ShellCrash mixed port (7890) when direct egress is blocked.
|
||||
# When the host already has soft-router/direct Google access, Neko stays on direct for both switch states.
|
||||
resolve_neko_browser_proxy_primary_port() {
|
||||
if neko_browser_proxy_switch_enabled; then
|
||||
shellcrash_neko_proxy_port
|
||||
else
|
||||
shellcrash_mix_port
|
||||
fi
|
||||
}
|
||||
|
||||
resolve_neko_browser_proxy_fallback_port() {
|
||||
if neko_browser_proxy_switch_enabled; then
|
||||
shellcrash_mix_port
|
||||
else
|
||||
shellcrash_neko_proxy_port
|
||||
fi
|
||||
}
|
||||
|
||||
resolve_neko_browser_proxy() {
|
||||
case "${NEKO_BROWSER_PROXY:-}" in
|
||||
0|false|FALSE|off|OFF|none|NONE|direct|DIRECT)
|
||||
printf '%s' "$NEKO_BROWSER_PROXY"
|
||||
return 0
|
||||
neko_shellcrash_attach_disabled && printf '%s' "$NEKO_BROWSER_PROXY" && return 0
|
||||
;;
|
||||
?*)
|
||||
if neko_browser_proxy_url_is_usable "$NEKO_BROWSER_PROXY"; then
|
||||
@ -1576,12 +1611,10 @@ resolve_neko_browser_proxy() {
|
||||
local shell_port
|
||||
shell_port="$(neko_shellcrash_proxy_port_from_url "$NEKO_BROWSER_PROXY")"
|
||||
if shellcrash_proxy_available "$shell_port"; then
|
||||
printf '%s' "$NEKO_BROWSER_PROXY"
|
||||
return 0
|
||||
fi
|
||||
if system_direct_global_ready; then
|
||||
neko_proxy_url_for_port "$shell_port"
|
||||
return 0
|
||||
fi
|
||||
system_direct_global_ready && return 0
|
||||
else
|
||||
printf '%s' "$NEKO_BROWSER_PROXY"
|
||||
return 0
|
||||
@ -1589,26 +1622,27 @@ resolve_neko_browser_proxy() {
|
||||
fi
|
||||
;;
|
||||
esac
|
||||
neko_browser_proxy_switch_enabled || return 0
|
||||
case "$SHELLCRASH_ATTACH_NEKO" in
|
||||
0|false|FALSE|off|OFF|none|NONE|direct|DIRECT)
|
||||
return 0
|
||||
;;
|
||||
esac
|
||||
local port
|
||||
port="$(shellcrash_neko_proxy_port)"
|
||||
neko_shellcrash_attach_disabled && return 0
|
||||
system_direct_global_ready && return 0
|
||||
local port fallback
|
||||
port="$(resolve_neko_browser_proxy_primary_port)"
|
||||
if shellcrash_proxy_available "$port"; then
|
||||
neko_proxy_url_for_port "$port"
|
||||
return 0
|
||||
fi
|
||||
if system_direct_global_ready; then
|
||||
fallback="$(resolve_neko_browser_proxy_fallback_port)"
|
||||
if [ -n "$fallback" ] && [ "$fallback" != "$port" ] && shellcrash_proxy_available "$fallback"; then
|
||||
neko_proxy_url_for_port "$fallback"
|
||||
return 0
|
||||
fi
|
||||
shellcrash_autostart_if_needed >/dev/null 2>&1 || true
|
||||
port="$(shellcrash_neko_proxy_port)"
|
||||
if shellcrash_proxy_available "$port"; then
|
||||
neko_proxy_url_for_port "$port"
|
||||
fi
|
||||
for port in "$(resolve_neko_browser_proxy_primary_port)" "$(resolve_neko_browser_proxy_fallback_port)"; do
|
||||
[ -n "$port" ] || continue
|
||||
if shellcrash_proxy_available "$port"; then
|
||||
neko_proxy_url_for_port "$port"
|
||||
return 0
|
||||
fi
|
||||
done
|
||||
}
|
||||
|
||||
service_neko_reconfigure_for_shellcrash_change() {
|
||||
@ -1619,16 +1653,14 @@ service_neko_reconfigure_for_shellcrash_change() {
|
||||
esac
|
||||
have docker || return 0
|
||||
docker ps --format '{{.Names}}' 2>/dev/null | grep -Eq '^live-neko-[0-9]+$' || return 0
|
||||
if ! shellcrash_proxy_available "$(shellcrash_neko_proxy_port)"; then
|
||||
if ! shellcrash_proxy_available "$(shellcrash_neko_proxy_port)" \
|
||||
&& ! shellcrash_proxy_available "$(shellcrash_mix_port)" \
|
||||
&& system_direct_global_ready; then
|
||||
case "${NEKO_BROWSER_PROXY:-}" in
|
||||
""|0|false|FALSE|off|OFF|none|NONE|direct|DIRECT) ;;
|
||||
*)
|
||||
if system_direct_global_ready || ! shellcrash_proxy_available "$(shellcrash_mix_port)"; then
|
||||
stack_env_upsert NEKO_BROWSER_PROXY ""
|
||||
stack_env_upsert ENABLE_NEKO_BROWSER_PROXY 0
|
||||
export NEKO_BROWSER_PROXY=""
|
||||
export ENABLE_NEKO_BROWSER_PROXY=0
|
||||
fi
|
||||
stack_env_upsert NEKO_BROWSER_PROXY ""
|
||||
export NEKO_BROWSER_PROXY=""
|
||||
;;
|
||||
esac
|
||||
fi
|
||||
|
||||
@ -49,20 +49,27 @@ def upsert_env_value(path: Path, key: str, value: str) -> bool:
|
||||
lines = []
|
||||
prefix = f"{key}="
|
||||
next_line = f"{key}={value}"
|
||||
kept: list[str] = []
|
||||
found = False
|
||||
changed = False
|
||||
for idx, raw in enumerate(lines):
|
||||
for raw in lines:
|
||||
if raw.strip().startswith(prefix):
|
||||
if raw != next_line:
|
||||
lines[idx] = next_line
|
||||
if not found:
|
||||
kept.append(next_line)
|
||||
found = True
|
||||
if raw != next_line:
|
||||
changed = True
|
||||
else:
|
||||
changed = True
|
||||
break
|
||||
else:
|
||||
if lines and lines[-1].strip():
|
||||
lines.append("")
|
||||
lines.append(next_line)
|
||||
continue
|
||||
kept.append(raw)
|
||||
if not found:
|
||||
if kept and kept[-1].strip():
|
||||
kept.append("")
|
||||
kept.append(next_line)
|
||||
changed = True
|
||||
if changed:
|
||||
path.write_text("\n".join(lines).rstrip() + "\n", encoding="utf-8")
|
||||
path.write_text("\n".join(kept).rstrip() + "\n", encoding="utf-8")
|
||||
return changed
|
||||
|
||||
|
||||
|
||||
@ -918,17 +918,25 @@ def _upsert_stack_env_values(repo_root: Path, values: dict[str, str]) -> bool:
|
||||
for key, value in values.items():
|
||||
prefix = f"{key}="
|
||||
next_line = f"{key}={value}"
|
||||
for idx, raw in enumerate(lines):
|
||||
kept: list[str] = []
|
||||
found = False
|
||||
for raw in lines:
|
||||
if raw.strip().startswith(prefix):
|
||||
if raw != next_line:
|
||||
lines[idx] = next_line
|
||||
if not found:
|
||||
kept.append(next_line)
|
||||
found = True
|
||||
if raw != next_line:
|
||||
changed = True
|
||||
else:
|
||||
changed = True
|
||||
break
|
||||
else:
|
||||
if lines and lines[-1].strip():
|
||||
lines.append("")
|
||||
lines.append(next_line)
|
||||
continue
|
||||
kept.append(raw)
|
||||
if not found:
|
||||
if kept and kept[-1].strip():
|
||||
kept.append("")
|
||||
kept.append(next_line)
|
||||
changed = True
|
||||
lines = kept
|
||||
if changed:
|
||||
env_path.write_text("\n".join(lines).rstrip() + "\n", encoding="utf-8")
|
||||
return changed
|
||||
@ -1222,7 +1230,7 @@ def _wireguard_quality(
|
||||
|
||||
|
||||
def wireguard_runtime_status(*, repo_root: Path) -> dict[str, Any]:
|
||||
auto_neko = ensure_neko_browser_proxy_for_network(repo_root, restart=True)
|
||||
auto_neko = ensure_neko_browser_proxy_for_network(repo_root, restart=False)
|
||||
commands = {name: bool(shutil.which(name)) for name in ("wg", "wg-quick", "ip", "systemctl")}
|
||||
system_configs = _system_wireguard_configs()
|
||||
repo_configs = list_imported_wireguard_configs(repo_root)
|
||||
@ -1370,6 +1378,40 @@ def _resolve_neko_docker_host_ip() -> str:
|
||||
return sanitize_docker_host_ip(gw)
|
||||
|
||||
|
||||
def _neko_shellcrash_attach_disabled(env: dict[str, str]) -> bool:
|
||||
attach = str(env.get("SHELLCRASH_ATTACH_NEKO") or "auto").strip().lower()
|
||||
return attach in {"0", "false", "off", "none", "direct", "disable", "disabled"}
|
||||
|
||||
|
||||
def _resolve_neko_browser_proxy_url(env: dict[str, str], *, proxycheap_enabled: bool) -> str:
|
||||
if _neko_shellcrash_attach_disabled(env):
|
||||
return ""
|
||||
try:
|
||||
from src.network_preflight import system_network_probe
|
||||
|
||||
if bool(system_network_probe(include_proxy=False).get("global_direct_ok")):
|
||||
return ""
|
||||
except Exception:
|
||||
pass
|
||||
from src.neko_docker_host import build_neko_browser_proxy_url, sanitize_neko_browser_proxy
|
||||
|
||||
explicit = str(env.get("NEKO_BROWSER_PROXY") or "").strip()
|
||||
if explicit and explicit.lower() not in {"0", "false", "off", "none", "direct"}:
|
||||
resolved = sanitize_neko_browser_proxy(explicit)
|
||||
if resolved:
|
||||
return resolved
|
||||
docker_host_ip = _resolve_neko_docker_host_ip()
|
||||
neko_port = str(env.get("NEKO_SHELLCRASH_PROXY_PORT") or "7894").strip() or "7894"
|
||||
try:
|
||||
from src.network_preflight import shellcrash_runtime
|
||||
|
||||
mix_port = str(shellcrash_runtime().get("mixed_port") or "7890").strip() or "7890"
|
||||
except Exception:
|
||||
mix_port = "7890"
|
||||
port = neko_port if proxycheap_enabled else mix_port
|
||||
return build_neko_browser_proxy_url(docker_host_ip, port)
|
||||
|
||||
|
||||
def _neko_browser_proxy_status(repo_root: Path) -> dict[str, Any]:
|
||||
env = _read_stack_env(repo_root)
|
||||
enabled = _env_flag_enabled(env, "ENABLE_NEKO_BROWSER_PROXY", default=False)
|
||||
@ -1378,20 +1420,13 @@ def _neko_browser_proxy_status(repo_root: Path) -> dict[str, Any]:
|
||||
node = str(env.get("SHELLCRASH_NEKO_PROXY_NODE") or "proxycheap").strip() or "proxycheap"
|
||||
attach = str(env.get("SHELLCRASH_ATTACH_NEKO") or "auto").strip() or "auto"
|
||||
docker_host_ip = _resolve_neko_docker_host_ip()
|
||||
resolved = ""
|
||||
if enabled:
|
||||
if explicit and explicit.lower() not in {"0", "false", "off", "none", "direct"}:
|
||||
from src.neko_docker_host import sanitize_neko_browser_proxy
|
||||
resolved = _resolve_neko_browser_proxy_url(env, proxycheap_enabled=enabled)
|
||||
try:
|
||||
from src.network_preflight import shellcrash_runtime
|
||||
|
||||
resolved = sanitize_neko_browser_proxy(explicit)
|
||||
if not resolved and attach.lower() not in {"0", "false", "off", "none", "direct"}:
|
||||
from src.neko_docker_host import build_neko_browser_proxy_url
|
||||
|
||||
resolved = build_neko_browser_proxy_url(docker_host_ip, port)
|
||||
elif attach.lower() not in {"0", "false", "off", "none", "direct"}:
|
||||
from src.neko_docker_host import build_neko_browser_proxy_url
|
||||
|
||||
resolved = build_neko_browser_proxy_url(docker_host_ip, port)
|
||||
mix_port = str(shellcrash_runtime().get("mixed_port") or "7890").strip() or "7890"
|
||||
except Exception:
|
||||
mix_port = "7890"
|
||||
return {
|
||||
"enabled": enabled,
|
||||
"switch": "ENABLE_NEKO_BROWSER_PROXY",
|
||||
@ -1399,8 +1434,10 @@ def _neko_browser_proxy_status(repo_root: Path) -> dict[str, Any]:
|
||||
"explicit_proxy": explicit,
|
||||
"resolved_proxy": resolved,
|
||||
"docker_host_ip": docker_host_ip,
|
||||
"shellcrash_port": port,
|
||||
"shellcrash_node": node,
|
||||
"shellcrash_port": port if enabled else mix_port,
|
||||
"shellcrash_node": node if enabled else "default",
|
||||
"proxycheap_port": port,
|
||||
"fallback_port": mix_port,
|
||||
"attach_mode": attach,
|
||||
}
|
||||
|
||||
@ -1433,12 +1470,18 @@ def configure_neko_browser_proxy(
|
||||
restart: bool = True,
|
||||
manual: bool = True,
|
||||
) -> dict[str, Any]:
|
||||
updates: dict[str, str] = {"ENABLE_NEKO_BROWSER_PROXY": "1" if enabled else "0"}
|
||||
updates: dict[str, str] = {
|
||||
"ENABLE_NEKO_BROWSER_PROXY": "1" if enabled else "0",
|
||||
# Drop stale per-host bridge IP overrides so resolve_neko_browser_proxy recalculates.
|
||||
"NEKO_BROWSER_PROXY": "",
|
||||
}
|
||||
if manual:
|
||||
updates["NEKO_BROWSER_PROXY_MANUAL"] = "1"
|
||||
changed = _upsert_stack_env_values(repo_root, updates)
|
||||
reconfigure: dict[str, Any] = {"ok": True, "skipped": True, "reason": "unchanged"}
|
||||
if restart and changed:
|
||||
# Manual UI toggles must always re-render compose even when env values look unchanged
|
||||
# (e.g. duplicate keys were deduped but containers still carry stale proxy).
|
||||
if restart and (changed or manual):
|
||||
reconfigure = _reconfigure_neko_containers(repo_root)
|
||||
status = _neko_browser_proxy_status(repo_root)
|
||||
return {
|
||||
|
||||
@ -208,6 +208,43 @@ class NekoConfigTests(unittest.TestCase):
|
||||
self.assertIn('"./no-managed-policies:/etc/chromium-browser/policies/managed:ro"', personal_rendered)
|
||||
self.assertIn('"./no-managed-policies:/etc/opt/chrome/policies/managed:ro"', personal_rendered)
|
||||
|
||||
def test_dynamic_neko_instances_inherit_shared_proxy_unless_per_instance_enabled(self) -> None:
|
||||
spec = importlib.util.spec_from_file_location(
|
||||
"render_neko_compose",
|
||||
ROOT / "tools" / "render_neko_compose.py",
|
||||
)
|
||||
self.assertIsNotNone(spec)
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
assert spec and spec.loader
|
||||
spec.loader.exec_module(module)
|
||||
|
||||
with patch.dict(
|
||||
os.environ,
|
||||
{
|
||||
"NEKO_BROWSER_PROXY": "http://host.docker.internal:7890",
|
||||
"NEKO_BROWSER_PROXY_2": "http://172.19.0.1:7895",
|
||||
"NEKO_SHELLCRASH_PROXY_PORT_2": "7895",
|
||||
"NEKO_BROWSER_PROXY_PER_INSTANCE": "0",
|
||||
},
|
||||
clear=False,
|
||||
):
|
||||
rendered = module.render(2)
|
||||
self.assertEqual(rendered.count('NEKO_BROWSER_PROXY: "http://host.docker.internal:7890"'), 2)
|
||||
|
||||
with patch.dict(
|
||||
os.environ,
|
||||
{
|
||||
"ENABLE_NEKO_BROWSER_PROXY": "1",
|
||||
"NEKO_BROWSER_PROXY": "",
|
||||
"NEKO_SHELLCRASH_PROXY_PORT": "7894",
|
||||
"NEKO_BROWSER_PROXY_PER_INSTANCE": "1",
|
||||
},
|
||||
clear=False,
|
||||
):
|
||||
per_instance = module.render(2)
|
||||
self.assertIn('NEKO_BROWSER_PROXY: "http://host.docker.internal:7894"', per_instance)
|
||||
self.assertIn('NEKO_BROWSER_PROXY: "http://host.docker.internal:7895"', per_instance)
|
||||
|
||||
def test_neko_runtime_scripts_use_generated_compose(self) -> None:
|
||||
service_ctl = (ROOT / "scripts" / "linux" / "service_ctl.sh").read_text(encoding="utf-8")
|
||||
common = (ROOT / "scripts" / "linux" / "lib" / "common.sh").read_text(encoding="utf-8")
|
||||
@ -280,7 +317,7 @@ class NekoConfigTests(unittest.TestCase):
|
||||
"neko_shellcrash_proxy_enabled()",
|
||||
"SHELLCRASH_NEKO_PROXY_NODE",
|
||||
"SHELLCRASH_DOCKER_CIDR",
|
||||
'ip saddr $cidr $proto dport $port accept',
|
||||
'insert rule inet shellcrash input ip saddr $cidr accept comment "shellcrash-trusted"',
|
||||
"docker_container_http_port_published()",
|
||||
"docker_container_network_attached()",
|
||||
"remove_unreachable_neko_containers",
|
||||
@ -323,7 +360,7 @@ class NekoConfigTests(unittest.TestCase):
|
||||
'ufw allow in proto "$proto" from "$cidr" to any port "$port" >/dev/null 2>&1',
|
||||
"''|*[!0-9]*) return 0 ;;",
|
||||
'if [ "$ufw_rule_ok" != "1" ] && have iptables; then',
|
||||
'insert rule inet shellcrash input ip saddr $cidr $proto dport $port accept',
|
||||
'insert rule inet shellcrash input ip saddr $cidr accept comment "shellcrash-trusted"',
|
||||
'ensure_shellcrash_docker_port_access "$(shellcrash_redir_port)" tcp "ShellCrash redir from Docker"',
|
||||
'ensure_shellcrash_docker_port_access "$(shellcrash_tproxy_port)" tcp "ShellCrash tproxy from Docker"',
|
||||
'ensure_shellcrash_docker_port_access "$(shellcrash_tproxy_port)" udp "ShellCrash tproxy from Docker"',
|
||||
@ -555,9 +592,8 @@ class NekoConfigTests(unittest.TestCase):
|
||||
self.assertIn("live-neko-ip-watch.service", common)
|
||||
self.assertIn("ExecStart=/bin/bash", common)
|
||||
self.assertIn("scripts/linux/neko_ip_watch.sh", common)
|
||||
self.assertIn("detect_preferred_lan_ip", watcher)
|
||||
self.assertIn('target="${NEKO_WEBRTC_NAT1TO1:-}"', watcher)
|
||||
self.assertIn('case "${NEKO_ACCESS_MODE:-lan}"', watcher)
|
||||
self.assertIn("resolve_neko_nat1to1", watcher)
|
||||
self.assertNotIn('target="${NEKO_WEBRTC_NAT1TO1:-}"', watcher)
|
||||
self.assertIn('bash "$SERVICE_CTL" neko reconfigure', watcher)
|
||||
self.assertIn("NEKO_IP_WATCH_INTERVAL", watcher)
|
||||
self.assertIn("service_neko_reconfigure()", (ROOT / "scripts" / "linux" / "service_ctl.sh").read_text(encoding="utf-8"))
|
||||
|
||||
@ -264,16 +264,26 @@ class WireGuardConfigTests(unittest.TestCase):
|
||||
"NEKO_SHELLCRASH_PROXY_PORT=7894\nSHELLCRASH_NEKO_PROXY_NODE=proxycheap\n",
|
||||
encoding="utf-8",
|
||||
)
|
||||
status = configure_neko_browser_proxy(repo_root=repo, enabled=False, restart=False)
|
||||
direct_probe = {"global_direct_ok": True}
|
||||
blocked_probe = {"global_direct_ok": False}
|
||||
with patch("src.network_preflight.system_network_probe", return_value=direct_probe):
|
||||
status = configure_neko_browser_proxy(repo_root=repo, enabled=False, restart=False)
|
||||
self.assertFalse(status["enabled"])
|
||||
self.assertEqual(status["resolved_proxy"], "")
|
||||
|
||||
with patch("src.wireguard_config._reconfigure_neko_containers", return_value={"ok": True, "skipped": False}):
|
||||
enabled = configure_neko_browser_proxy(repo_root=repo, enabled=True, restart=True)
|
||||
with patch("src.network_preflight.system_network_probe", return_value=blocked_probe):
|
||||
with patch("src.wireguard_config._reconfigure_neko_containers", return_value={"ok": True, "skipped": False}):
|
||||
enabled = configure_neko_browser_proxy(repo_root=repo, enabled=True, restart=True)
|
||||
self.assertTrue(enabled["enabled"])
|
||||
self.assertEqual(enabled["resolved_proxy"], "http://host.docker.internal:7894")
|
||||
self.assertIn("ENABLE_NEKO_BROWSER_PROXY=1", env.read_text(encoding="utf-8"))
|
||||
self.assertIn("NEKO_BROWSER_PROXY_MANUAL=1", env.read_text(encoding="utf-8"))
|
||||
self.assertIn("NEKO_BROWSER_PROXY=\n", env.read_text(encoding="utf-8"))
|
||||
|
||||
with patch("src.network_preflight.system_network_probe", return_value=blocked_probe):
|
||||
shellcrash_off = configure_neko_browser_proxy(repo_root=repo, enabled=False, restart=False)
|
||||
self.assertFalse(shellcrash_off["enabled"])
|
||||
self.assertEqual(shellcrash_off["resolved_proxy"], "http://host.docker.internal:7890")
|
||||
|
||||
def test_neko_browser_proxy_auto_enables_when_shellcrash_only(self) -> None:
|
||||
from src.wireguard_config import ensure_neko_browser_proxy_for_network
|
||||
@ -320,6 +330,26 @@ class WireGuardConfigTests(unittest.TestCase):
|
||||
self.assertFalse(result["applied"])
|
||||
self.assertEqual(result["reason"], "not_needed")
|
||||
|
||||
def test_upsert_stack_env_dedupes_duplicate_keys(self) -> None:
|
||||
from src.wireguard_config import _read_stack_env, _upsert_stack_env_values
|
||||
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
repo = Path(tmp)
|
||||
env = repo / "config" / "system-stack.env"
|
||||
env.parent.mkdir(parents=True)
|
||||
env.write_text(
|
||||
"ENABLE_NEKO_BROWSER_PROXY=0\n"
|
||||
"NEKO_BROWSER_PROXY_MANUAL=0\n"
|
||||
"ENABLE_NEKO_BROWSER_PROXY=1\n",
|
||||
encoding="utf-8",
|
||||
)
|
||||
changed = _upsert_stack_env_values(repo_root=repo, values={"ENABLE_NEKO_BROWSER_PROXY": "0"})
|
||||
self.assertTrue(changed)
|
||||
text = env.read_text(encoding="utf-8")
|
||||
self.assertEqual(text.count("ENABLE_NEKO_BROWSER_PROXY="), 1)
|
||||
self.assertIn("ENABLE_NEKO_BROWSER_PROXY=0", text)
|
||||
self.assertFalse(_read_stack_env(repo)["ENABLE_NEKO_BROWSER_PROXY"] == "1")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
|
||||
@ -67,6 +67,41 @@ def host_path(base: str, name: str) -> str:
|
||||
return f"{base.rstrip('/')}/{name}"
|
||||
|
||||
|
||||
def resolve_shared_browser_proxy(docker_host_ip: str) -> str:
|
||||
"""Match service_ctl resolve_neko_browser_proxy: use exported NEKO_BROWSER_PROXY when set."""
|
||||
browser_proxy = sanitize_neko_browser_proxy(env("NEKO_BROWSER_PROXY", ""))
|
||||
if browser_proxy:
|
||||
return browser_proxy
|
||||
if env_enabled("ENABLE_NEKO_BROWSER_PROXY", False):
|
||||
return build_neko_browser_proxy_url(
|
||||
docker_host_ip,
|
||||
env("NEKO_SHELLCRASH_PROXY_PORT", "7894"),
|
||||
)
|
||||
# service_ctl exports NEKO_BROWSER_PROXY before render when direct is blocked.
|
||||
return ""
|
||||
|
||||
|
||||
def resolve_instance_browser_proxy(
|
||||
idx: int,
|
||||
*,
|
||||
shared_proxy: str,
|
||||
docker_host_ip: str,
|
||||
per_instance_proxy: bool,
|
||||
proxy_port_base: int,
|
||||
) -> str:
|
||||
# Default install (9200) and dynamically added channels (9201+) share the same
|
||||
# proxy policy unless explicit per-instance proxycheap mode is enabled.
|
||||
if not per_instance_proxy or not env_enabled("ENABLE_NEKO_BROWSER_PROXY", False):
|
||||
return shared_proxy
|
||||
inst_proxy = sanitize_neko_browser_proxy(instance_value("NEKO_BROWSER_PROXY", idx, ""))
|
||||
if inst_proxy:
|
||||
return inst_proxy
|
||||
inst_proxy_port = instance_value("NEKO_SHELLCRASH_PROXY_PORT", idx, "")
|
||||
if inst_proxy_port:
|
||||
return build_neko_browser_proxy_url(docker_host_ip, inst_proxy_port)
|
||||
return build_neko_browser_proxy_url(docker_host_ip, str(proxy_port_base + idx - 1))
|
||||
|
||||
|
||||
def render(count: int) -> str:
|
||||
image = env("NEKO_IMAGE", "ghcr.io/m1k1o/neko/chromium:3.0.0")
|
||||
shm = env("NEKO_SHM_SIZE", "512mb")
|
||||
@ -84,12 +119,7 @@ def render(count: int) -> str:
|
||||
container_home = env("NEKO_CONTAINER_HOME", f"/home/{container_user}")
|
||||
render_mode = env("NEKO_BROWSER_RENDER_MODE", "auto")
|
||||
docker_host_ip = sanitize_docker_host_ip(env("NEKO_DOCKER_HOST_IP", ""))
|
||||
browser_proxy = sanitize_neko_browser_proxy(env("NEKO_BROWSER_PROXY", ""))
|
||||
if not browser_proxy and env_enabled("ENABLE_NEKO_BROWSER_PROXY", False):
|
||||
browser_proxy = build_neko_browser_proxy_url(
|
||||
docker_host_ip,
|
||||
env("NEKO_SHELLCRASH_PROXY_PORT", "7894"),
|
||||
)
|
||||
browser_proxy = resolve_shared_browser_proxy(docker_host_ip)
|
||||
browser_proxy_bypass = env(
|
||||
"NEKO_BROWSER_PROXY_BYPASS",
|
||||
"<-loopback>;localhost;127.0.0.1;::1;10.*;172.16.*;172.17.*;172.18.*;172.19.*;172.20.*;"
|
||||
@ -133,19 +163,15 @@ def render(count: int) -> str:
|
||||
udp_range = instance_value("NEKO_WEBRTC_UDP_RANGE", idx, default_udp_range(idx))
|
||||
epr = instance_value("NEKO_WEBRTC_EPR", idx, udp_range)
|
||||
profile = instance_value("NEKO_PROFILE_HOST_DIR", idx, base_profile if idx == 1 else f"{base_profile}-{idx}")
|
||||
inst_proxy = sanitize_neko_browser_proxy(instance_value("NEKO_BROWSER_PROXY", idx, ""))
|
||||
inst_proxy_port = instance_value("NEKO_SHELLCRASH_PROXY_PORT", idx, "")
|
||||
if inst_proxy:
|
||||
browser_proxy_i = inst_proxy
|
||||
elif inst_proxy_port:
|
||||
browser_proxy_i = build_neko_browser_proxy_url(docker_host_ip, inst_proxy_port)
|
||||
elif per_instance_proxy and env_enabled("ENABLE_NEKO_BROWSER_PROXY", False):
|
||||
browser_proxy_i = build_neko_browser_proxy_url(
|
||||
docker_host_ip,
|
||||
str(proxy_port_base + idx - 1),
|
||||
)
|
||||
else:
|
||||
browser_proxy_i = browser_proxy
|
||||
browser_proxy_i = resolve_instance_browser_proxy(
|
||||
idx,
|
||||
shared_proxy=browser_proxy,
|
||||
docker_host_ip=docker_host_ip,
|
||||
per_instance_proxy=per_instance_proxy,
|
||||
proxy_port_base=proxy_port_base,
|
||||
)
|
||||
_ = inst_proxy_port # kept for backward-compatible env keys in docs/tests
|
||||
lines.extend(
|
||||
[
|
||||
f" neko{idx}:",
|
||||
|
||||
@ -946,17 +946,21 @@ export default function LiveControlApp() {
|
||||
const setNekoBrowserProxy = async (enabled: boolean) => {
|
||||
setBusy(`neko:proxy:${enabled ? "on" : "off"}`);
|
||||
try {
|
||||
await fetchJson<{ neko_browser_proxy?: WireGuardRuntimeStatus["neko_browser_proxy"] }>("/hub/network/neko_browser_proxy", {
|
||||
const data = await fetchJson<{ neko_browser_proxy?: WireGuardRuntimeStatus["neko_browser_proxy"] }>("/hub/network/neko_browser_proxy", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ enabled, restart: true }),
|
||||
});
|
||||
if (data.neko_browser_proxy) {
|
||||
setWgStatus((prev) => (prev ? { ...prev, neko_browser_proxy: data.neko_browser_proxy } : prev));
|
||||
}
|
||||
await refreshWireGuardStatus();
|
||||
await refreshSystemNetworkProbe();
|
||||
await refreshDashboard();
|
||||
notify(
|
||||
enabled
|
||||
? t("已开启 Neko 浏览器代理", "Neko browser proxy enabled")
|
||||
: t("已关闭 Neko 浏览器代理", "Neko browser proxy disabled"),
|
||||
? t("已开启 Neko proxycheap 代理(7894)", "Neko proxycheap proxy enabled (7894)")
|
||||
: t("已关闭 proxycheap,直连失败时将走 ShellCrash 7890", "Proxycheap off; ShellCrash 7890 when direct blocked"),
|
||||
);
|
||||
} catch (e) {
|
||||
notify((e as Error).message);
|
||||
@ -2535,7 +2539,7 @@ export default function LiveControlApp() {
|
||||
</div>
|
||||
<div className={`mt-3 rounded-lg border px-3 py-2 ${portalTheme === "light" ? "border-slate-200 bg-white" : "border-white/10 bg-black/20"}`}>
|
||||
<p className={`text-[11px] font-medium ${portalTheme === "light" ? "text-slate-500" : "text-zinc-500"}`}>
|
||||
{t("Neko 浏览器代理", "Neko browser proxy")}
|
||||
{t("Neko proxycheap(7894)", "Neko proxycheap (7894)")}
|
||||
</p>
|
||||
<div className={`mt-2 grid grid-cols-2 rounded-lg p-1 text-xs font-semibold ${portalTheme === "light" ? "bg-slate-200/70" : "bg-black/40"}`}>
|
||||
{([false, true] as const).map((enabled) => {
|
||||
@ -2556,7 +2560,7 @@ export default function LiveControlApp() {
|
||||
: "text-zinc-300 hover:bg-white/10"
|
||||
}`}
|
||||
>
|
||||
{enabled ? t("开启", "On") : t("关闭", "Off")}
|
||||
{enabled ? t("proxycheap", "proxycheap") : t("ShellCrash", "ShellCrash")}
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
@ -2568,11 +2572,16 @@ export default function LiveControlApp() {
|
||||
<p>
|
||||
{t("节点", "Node")}: {wgStatus?.neko_browser_proxy?.shellcrash_node || "-"} · :{wgStatus?.neko_browser_proxy?.shellcrash_port || "7894"}
|
||||
</p>
|
||||
{systemNetworkProbe?.global_direct_ok ? (
|
||||
<p className={portalTheme === "light" ? "text-emerald-700" : "text-emerald-200"}>
|
||||
{t("宿主机可直连外网,Neko 不走 ShellCrash", "Host has direct egress; Neko stays direct")}
|
||||
</p>
|
||||
) : null}
|
||||
{systemNetworkProbe?.shellcrash_policy?.neko_browser_proxy_recommended &&
|
||||
!wgStatus?.neko_browser_proxy?.enabled &&
|
||||
!wgStatus?.neko_browser_proxy?.manual ? (
|
||||
<p className={portalTheme === "light" ? "text-cyan-700" : "text-cyan-200"}>
|
||||
{t("直连不可用且 ShellCrash 代理正常,将自动开启浏览器代理", "Direct egress failed; ShellCrash proxy is healthy — browser proxy will auto-enable")}
|
||||
{t("直连不可用,将自动开启 proxycheap(7894)", "Direct blocked; proxycheap (7894) will auto-enable")}
|
||||
</p>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
Loading…
Reference in New Issue
Block a user