forked from enderofwings/NexusOS
Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1f6beed0d2 | ||
|
|
fe12eb1821 |
@@ -18,6 +18,7 @@ export function Chatbot({ conversationId, setConversationId, onConversationChang
|
||||
const [images, setImages] = useState([]); // {name, b64} for vision models
|
||||
const [activeTool, setActiveTool] = useState(null); // playbook tool currently running
|
||||
const [pendingApproval, setPendingApproval] = useState(null); // [{name, arguments}] awaiting yes/no
|
||||
const [approvalToken, setApprovalToken] = useState(null); // single-use token authorizing /chat/approve
|
||||
const [editingIdx, setEditingIdx] = useState(null); // user message being edited
|
||||
const [editText, setEditText] = useState("");
|
||||
const [listening, setListening] = useState(false); // mic dictation active
|
||||
@@ -286,7 +287,11 @@ export function Chatbot({ conversationId, setConversationId, onConversationChang
|
||||
continue;
|
||||
}
|
||||
if (pendingEventType === "tool_request") {
|
||||
try { setPendingApproval(JSON.parse(payload)); } catch { /* ignore */ }
|
||||
try {
|
||||
const parsed = JSON.parse(payload);
|
||||
setPendingApproval(parsed.actions || []);
|
||||
setApprovalToken(parsed.token || null);
|
||||
} catch { /* ignore */ }
|
||||
pendingEventType = null;
|
||||
continue;
|
||||
}
|
||||
@@ -401,13 +406,15 @@ export function Chatbot({ conversationId, setConversationId, onConversationChang
|
||||
// Approve or deny the pending action tool(s); the open chat stream resumes.
|
||||
const resolveApproval = async (approve) => {
|
||||
const req = pendingApproval || [];
|
||||
const token = approvalToken;
|
||||
setPendingApproval(null);
|
||||
setApprovalToken(null);
|
||||
const decisions = {};
|
||||
req.forEach(a => { decisions[a.name] = approve; });
|
||||
try {
|
||||
await fetch(`${API_BASE}/chat/approve`, {
|
||||
method: "POST", headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ conversation_id: conversationId, decisions }),
|
||||
body: JSON.stringify({ conversation_id: conversationId, token, decisions }),
|
||||
});
|
||||
} catch { /* ignore */ }
|
||||
};
|
||||
|
||||
+7
-1
@@ -112,6 +112,12 @@ class Service:
|
||||
return self._argv() if callable(self._argv) else self._argv
|
||||
|
||||
|
||||
# Bind loopback by default: the backend/memory REST APIs are unauthenticated, so
|
||||
# binding 0.0.0.0 handed the full admin+data plane to any host on the LAN. Set
|
||||
# NEXUS_BIND_HOST=0.0.0.0 to opt into LAN exposure once real auth is in place.
|
||||
BIND_HOST = os.environ.get("NEXUS_BIND_HOST", "127.0.0.1")
|
||||
|
||||
|
||||
def _uvicorn(app: str, port: int):
|
||||
# No --reload. It is a dev-loop flag: uvicorn's reloader runs a supervisor
|
||||
# that spawns the real server as a CHILD, so every service became two
|
||||
@@ -120,7 +126,7 @@ def _uvicorn(app: str, port: int):
|
||||
# terminals for what should have been a silent start. launch_nexus.sh still
|
||||
# passes --reload for the Linux dev loop, where a visible console is the
|
||||
# point; this launcher is the one users run.
|
||||
return [str(PYTHON), "-m", "uvicorn", app, "--host", "0.0.0.0",
|
||||
return [str(PYTHON), "-m", "uvicorn", app, "--host", BIND_HOST,
|
||||
"--port", str(port)]
|
||||
|
||||
|
||||
|
||||
+12
-3
@@ -3,6 +3,7 @@ from __future__ import annotations
|
||||
import asyncio
|
||||
import json as _json
|
||||
import logging
|
||||
import secrets
|
||||
import threading
|
||||
from typing import AsyncGenerator, Dict, List, Optional, Any
|
||||
|
||||
@@ -171,12 +172,20 @@ async def _run_tool_loop(manager, messages, model, tool_schemas, temperature, nu
|
||||
action_calls = [c for c in calls if _tools.is_action(c.get("function", {}).get("name", ""))]
|
||||
if policy == "ask" and action_calls:
|
||||
event = asyncio.Event()
|
||||
pending_approvals[conversation_id] = {"event": event, "decisions": {}}
|
||||
yield "__approve__" + _json.dumps([
|
||||
# Single-use capability token, delivered only to the client that owns
|
||||
# this stream. /chat/approve requires it, so knowing the (guessable,
|
||||
# enumerable) conversation_id is no longer enough to approve someone
|
||||
# else's pending action.
|
||||
token = secrets.token_urlsafe(32)
|
||||
pending_approvals[conversation_id] = {"event": event, "decisions": {}, "token": token}
|
||||
yield "__approve__" + _json.dumps({
|
||||
"token": token,
|
||||
"actions": [
|
||||
{"name": c.get("function", {}).get("name", ""),
|
||||
"arguments": c.get("function", {}).get("arguments")}
|
||||
for c in action_calls
|
||||
])
|
||||
],
|
||||
})
|
||||
try:
|
||||
await asyncio.wait_for(event.wait(), timeout=_APPROVAL_TIMEOUT)
|
||||
decisions = pending_approvals[conversation_id]["decisions"]
|
||||
|
||||
+24
-7
@@ -3,6 +3,7 @@ from __future__ import annotations
|
||||
|
||||
import asyncio as _asyncio
|
||||
import json as _json
|
||||
import secrets as _secrets
|
||||
import uuid as _uuid
|
||||
from collections import Counter as _Counter
|
||||
from typing import Any, AsyncGenerator, Dict, List, Optional, Tuple
|
||||
@@ -14,9 +15,10 @@ import platform as _platform
|
||||
from pathlib import Path
|
||||
from fastapi import FastAPI, HTTPException, Body
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
from starlette.middleware.trustedhost import TrustedHostMiddleware
|
||||
from fastapi.responses import StreamingResponse, FileResponse
|
||||
|
||||
from .nexus_config import settings, VERSION, DEFAULT_CHAT_MODEL
|
||||
from .nexus_config import settings, VERSION, DEFAULT_CHAT_MODEL, ALLOWED_HOSTS, ALLOWED_ORIGINS
|
||||
from .chat import generate_chat_response, stream_chat_response, _synapse_trace
|
||||
from . import chat as _chat
|
||||
from .ollama_manager import initialize_ollama, initialize_ollama_async, get_ollama_manager
|
||||
@@ -179,13 +181,20 @@ app = FastAPI(title="Synapse Backend", version=VERSION)
|
||||
# Alias for startup scripts
|
||||
sio_app = app
|
||||
|
||||
# --- CORS ---
|
||||
# allow_credentials=True is incompatible with allow_origins=["*"] — browsers
|
||||
# reject such responses. Since this is a local-only service with no cookies/auth,
|
||||
# wildcard origins without credentials is correct.
|
||||
# --- Local-access guard ---
|
||||
# These APIs are unauthenticated and meant for this machine only. Two layers:
|
||||
# 1. TrustedHostMiddleware rejects a foreign Host header, which is what defeats
|
||||
# DNS-rebinding — the browser treats a rebound attacker domain as
|
||||
# same-origin, so CORS alone can't stop it.
|
||||
# 2. CORS is scoped to known local origins (not "*"), so a malicious page can't
|
||||
# read responses cross-origin from the victim's browser.
|
||||
# NEXUS_ALLOWED_HOSTS=* / a custom NEXUS_ALLOWED_ORIGINS opts into LAN exposure,
|
||||
# and should only be used once real authentication is in front of these apps.
|
||||
if "*" not in ALLOWED_HOSTS:
|
||||
app.add_middleware(TrustedHostMiddleware, allowed_hosts=ALLOWED_HOSTS)
|
||||
app.add_middleware(
|
||||
CORSMiddleware,
|
||||
allow_origins=["*"],
|
||||
allow_origins=ALLOWED_ORIGINS,
|
||||
allow_credentials=False,
|
||||
allow_methods=["*"],
|
||||
allow_headers=["*"],
|
||||
@@ -500,12 +509,20 @@ async def chat_stream_endpoint(payload: Dict[str, Any]):
|
||||
@app.post("/chat/approve")
|
||||
async def chat_approve(payload: Dict[str, Any] = Body(...)):
|
||||
"""Resolve a pending per-call tool approval. `decisions` maps tool name ->
|
||||
bool; the awaiting chat stream resumes and runs the approved actions."""
|
||||
bool; the awaiting chat stream resumes and runs the approved actions.
|
||||
|
||||
The `token` (issued in the stream's tool_request event) is required: without
|
||||
it, anyone who can guess/enumerate a conversation_id could approve another
|
||||
client's pending action. Compared in constant time."""
|
||||
conversation_id = payload.get("conversation_id") or ""
|
||||
token = payload.get("token") or ""
|
||||
decisions = payload.get("decisions") or {}
|
||||
waiter = _chat.pending_approvals.get(conversation_id)
|
||||
if not waiter:
|
||||
raise HTTPException(status_code=404, detail="no pending approval for this conversation")
|
||||
expected = waiter.get("token") or ""
|
||||
if not token or not _secrets.compare_digest(str(token), str(expected)):
|
||||
raise HTTPException(status_code=403, detail="invalid or missing approval token")
|
||||
waiter["decisions"] = {k: bool(v) for k, v in decisions.items()}
|
||||
waiter["event"].set()
|
||||
return {"status": "resumed"}
|
||||
|
||||
@@ -19,17 +19,24 @@ from typing import Any, Dict, List, Optional
|
||||
|
||||
from fastapi import FastAPI, HTTPException, Body
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
from starlette.middleware.trustedhost import TrustedHostMiddleware
|
||||
from pydantic import BaseModel
|
||||
|
||||
from .store import store, MemoryItem
|
||||
from .extractor import extract_memory
|
||||
from ..ollama_manager import get_ollama_manager
|
||||
from ..nexus_config import ALLOWED_HOSTS, ALLOWED_ORIGINS
|
||||
|
||||
app = FastAPI(title="Nexus Memory Service", version="1.0")
|
||||
|
||||
# Same unauthenticated-local-only posture as the main backend: reject foreign
|
||||
# Host headers (anti DNS-rebind) and scope CORS to known local origins rather
|
||||
# than "*". See nexus_config.ALLOWED_HOSTS / ALLOWED_ORIGINS for env overrides.
|
||||
if "*" not in ALLOWED_HOSTS:
|
||||
app.add_middleware(TrustedHostMiddleware, allowed_hosts=ALLOWED_HOSTS)
|
||||
app.add_middleware(
|
||||
CORSMiddleware,
|
||||
allow_origins=["*"],
|
||||
allow_origins=ALLOWED_ORIGINS,
|
||||
allow_credentials=False,
|
||||
allow_methods=["*"],
|
||||
allow_headers=["*"],
|
||||
|
||||
+25
-1
@@ -143,6 +143,29 @@ class Settings:
|
||||
"ollama_timeout": self.ollama_timeout,
|
||||
}
|
||||
|
||||
# --- local-access allowlists (shared by the backend + memory FastAPI apps) ---
|
||||
# The REST APIs are unauthenticated, so they are meant to be reached only from
|
||||
# this machine. Two independent browser-side defenses depend on these lists:
|
||||
# * ALLOWED_ORIGINS drives CORS — blocks a malicious page from *reading*
|
||||
# responses cross-origin (was previously "*", which let any site read them).
|
||||
# * ALLOWED_HOSTS drives TrustedHostMiddleware — rejects a foreign Host header,
|
||||
# which is what stops DNS-rebinding (same-origin from the browser's view, so
|
||||
# CORS can't help there).
|
||||
# Both accept a comma-separated env override for the intentional-LAN case, to be
|
||||
# paired with real auth. NEXUS_ALLOWED_HOSTS=* disables the Host check.
|
||||
def _csv_env(name: str, default: list) -> list:
|
||||
raw = os.getenv(name, "").strip()
|
||||
return [p.strip() for p in raw.split(",") if p.strip()] if raw else list(default)
|
||||
|
||||
_LOCAL_HOSTS = ["localhost", "127.0.0.1", "[::1]", "::1", "testserver"]
|
||||
_LOCAL_ORIGINS = [
|
||||
f"http://{h}:{p}"
|
||||
for h in ("localhost", "127.0.0.1")
|
||||
for p in (8000, 8001, 5173)
|
||||
]
|
||||
ALLOWED_HOSTS = _csv_env("NEXUS_ALLOWED_HOSTS", _LOCAL_HOSTS)
|
||||
ALLOWED_ORIGINS = _csv_env("NEXUS_ALLOWED_ORIGINS", _LOCAL_ORIGINS)
|
||||
|
||||
# exported instance
|
||||
settings = Settings()
|
||||
|
||||
@@ -152,7 +175,8 @@ __all__ = ["Settings", "settings", "path", "VERSION",
|
||||
"PROJECT_ROOT", "DATA_DIR", "MODELS_DIR", "RUNTIME_DIR",
|
||||
"MEMORY_DIR", "LOGS_DIR", "PLAYBOOK_DIR", "UPLOADS_DIR",
|
||||
"EXPORTS_DIR", "MEMORY_DB",
|
||||
"BACKEND_LOG", "OLLAMA_LOG", "CHAT_LOG"]
|
||||
"BACKEND_LOG", "OLLAMA_LOG", "CHAT_LOG",
|
||||
"ALLOWED_HOSTS", "ALLOWED_ORIGINS"]
|
||||
|
||||
# --- quick runtime sanity check when run directly (no side effects on import) ---
|
||||
if __name__ == "__main__":
|
||||
|
||||
+67
-4
@@ -60,20 +60,83 @@ async def _web_search(query: str = "", **_) -> str:
|
||||
return res or "(no results)"
|
||||
|
||||
|
||||
_FETCH_MAX_REDIRECTS = 5
|
||||
|
||||
|
||||
def _ip_is_blocked(ip: str) -> bool:
|
||||
"""True if an address is one an outbound fetch has no business reaching:
|
||||
loopback, RFC1918/ULA private, link-local (incl. 169.254.169.254 cloud
|
||||
metadata), multicast, reserved, or unspecified. IPv4-mapped IPv6 is unwrapped
|
||||
first so ::ffff:127.0.0.1 can't sneak a loopback past the check."""
|
||||
import ipaddress
|
||||
try:
|
||||
addr = ipaddress.ip_address(ip.split("%")[0]) # drop any IPv6 zone id
|
||||
except ValueError:
|
||||
return True # unparseable -> refuse rather than guess
|
||||
mapped = getattr(addr, "ipv4_mapped", None)
|
||||
if mapped is not None:
|
||||
addr = mapped
|
||||
return (
|
||||
addr.is_loopback or addr.is_private or addr.is_link_local
|
||||
or addr.is_multicast or addr.is_reserved or addr.is_unspecified
|
||||
)
|
||||
|
||||
|
||||
def _ssrf_guard(host: str) -> str | None:
|
||||
"""Resolve a hostname and return an error string if ANY of its A/AAAA
|
||||
records is a blocked address, else None. Checking every answer stops a name
|
||||
from smuggling one private record alongside a public one.
|
||||
|
||||
ponytail: this validates then httpx re-resolves on connect, so a sub-second
|
||||
DNS-rebind could still slip a private address through the TOCTOU gap. That's
|
||||
an advanced attack against a playbook-gated, single-user tool; pin the
|
||||
connection to the resolved IP if this ever faces untrusted callers."""
|
||||
import socket
|
||||
if not host:
|
||||
return "missing host"
|
||||
try:
|
||||
infos = socket.getaddrinfo(host, None)
|
||||
except socket.gaierror as e:
|
||||
return f"cannot resolve host: {e}"
|
||||
ips = {info[4][0] for info in infos}
|
||||
if not ips:
|
||||
return "host did not resolve"
|
||||
blocked = [ip for ip in ips if _ip_is_blocked(ip)]
|
||||
if blocked:
|
||||
return f"refusing to fetch a private/loopback/link-local address ({', '.join(sorted(blocked))})"
|
||||
return None
|
||||
|
||||
|
||||
async def _fetch_url(url: str = "", **_) -> str:
|
||||
import re
|
||||
import httpx
|
||||
from urllib.parse import urlparse, urljoin
|
||||
url = (url or "").strip()
|
||||
if not url.startswith(("http://", "https://")):
|
||||
return json.dumps({"error": "url must start with http:// or https://"})
|
||||
# ponytail: no SSRF allow/deny-list — local single-user assistant, and the
|
||||
# tool only runs when a playbook explicitly grants fetch_url. Add host
|
||||
# filtering if this ever serves multiple/untrusted users.
|
||||
# SSRF guard: validate the host of the initial URL AND every redirect hop
|
||||
# against the private/loopback/link-local block-list before connecting, so a
|
||||
# granted fetch_url can't be steered at 127.0.0.1:11434, cloud metadata, or
|
||||
# LAN hosts — and a public URL can't 302 its way there either.
|
||||
try:
|
||||
async with httpx.AsyncClient(timeout=15.0, follow_redirects=True) as c:
|
||||
async with httpx.AsyncClient(timeout=15.0, follow_redirects=False) as c:
|
||||
for _ in range(_FETCH_MAX_REDIRECTS + 1):
|
||||
parsed = urlparse(url)
|
||||
if parsed.scheme not in ("http", "https"):
|
||||
return json.dumps({"error": "only http(s) URLs are allowed"})
|
||||
err = _ssrf_guard(parsed.hostname or "")
|
||||
if err:
|
||||
return json.dumps({"error": f"blocked: {err}"})
|
||||
r = await c.get(url, headers={"User-Agent": "NexusOS/1.0"})
|
||||
location = r.headers.get("location")
|
||||
if r.is_redirect and location:
|
||||
url = urljoin(url, location)
|
||||
continue
|
||||
r.raise_for_status()
|
||||
html = r.text
|
||||
break
|
||||
else:
|
||||
return json.dumps({"error": "too many redirects"})
|
||||
except Exception as e:
|
||||
return json.dumps({"error": f"fetch failed: {e}"})
|
||||
text = re.sub(r"(?is)<(script|style).*?</\1>", " ", html)
|
||||
|
||||
Reference in New Issue
Block a user