Free, open-source AI video generator for Mac. Run LTX-2.5 and MiniMax H3 (Hailuo) locally on Apple Silicon: text-to-video and image-to-video with sound, lip-sync, character LoRA training, songs from lyrics (YuE2) and image editing (Qwen-Image-Edit). One-click install via Pinokio. Offline: no cloud, no API key, no NVIDIA GPU.
Python ai-filmmakingai-videoai-video-generatorapple-siliconhailuoimage-to-videolip-synclocal-ailora-trainingltx-2ltx-2-5ltx-videomacosminimax-h3mlxmusic-generationoffline-aipinokiotext-to-videovideo-generation
sec(agent): harden agent endpoints + state files
mrbizarro674e1fb3dd10
diff --git a/agent/runtime.py b/agent/runtime.pyindex bbf8cb2..5cfb3de 100644--- a/agent/runtime.py+++ b/agent/runtime.py@@ -26,6 +26,7 @@ from __future__ import annotationsimport jsonimport os+import reimport timeimport uuidfrom dataclasses import asdict, dataclass, field@@ -39,6 +40,17 @@ MAX_STEPS_PER_TURN = 30 # safety cap on tool-loop iterations per userSESSION_VERSION = 1+# Sessions are identified by uuid4().hex[:12] — a 12-char lowercase hex string.+# Reject anything else BEFORE touching the filesystem so a path like+# "../../etc/passwd" can't masquerade as a session id and cause a stat() / read+# of files outside state/agent_sessions/.+_VALID_SESSION_ID_RE = re.compile(r"^[0-9a-f]{12}$")+++def is_valid_session_id(sid: str) -> bool:+ return bool(sid and _VALID_SESSION_ID_RE.fullmatch(sid))++@dataclassclass Session:session_id: str@@ -51,6 +63,23 @@ class Session:finished: bool = Falsedef to_dict(self) -> dict:+ # NEVER include api_key on the wire — to_public_dict() masks it. The+ # session is the response shape for /agent/sessions/<id>; without this,+ # opening DevTools or any browser cache shows the raw key.+ return {+ "version": SESSION_VERSION,+ "session_id": self.session_id,+ "title": self.title,+ "messages": self.messages,+ "engine_config": self.engine_config.to_public_dict(),+ "tool_state": self.tool_state,+ "created_at": self.created_at,+ "updated_at": self.updated_at,+ "finished": self.finished,+ }++ def to_persisted_dict(self) -> dict:+ """Disk shape — INCLUDES api_key so a panel restart doesn't lose it."""return {"version": SESSION_VERSION,"session_id": self.session_id,@@ -88,11 +117,21 @@ def save_session(session: Session, state_dir: Path) -> None:session.updated_at = time.time()p = sessions_dir(state_dir) / f"{session.session_id}.json"tmp = p.with_suffix(p.suffix + ".tmp")- tmp.write_text(json.dumps(session.to_dict(), indent=2), encoding="utf-8")+ # Persisted shape keeps api_key so the conversation can resume after a+ # panel restart without the user re-entering their key.+ tmp.write_text(json.dumps(session.to_persisted_dict(), indent=2), encoding="utf-8")os.replace(tmp, p) # atomic — never see half-write on read+ # umask alone leaves these world-readable on most systems; the file holds+ # the user's full conversation history (often with API keys baked in).+ try:+ os.chmod(p, 0o600)+ except OSError:+ passdef load_session(session_id: str, state_dir: Path) -> Session | None:+ if not is_valid_session_id(session_id):+ return Nonep = sessions_dir(state_dir) / f"{session_id}.json"if not p.is_file():return None@@ -127,6 +166,8 @@ def list_sessions(state_dir: Path) -> list[dict]:def delete_session(session_id: str, state_dir: Path) -> bool:+ if not is_valid_session_id(session_id):+ return Falsep = sessions_dir(state_dir) / f"{session_id}.json"if p.is_file():p.unlink()diff --git a/agent/tools.py b/agent/tools.pyindex 415c3e6..f0821c3 100644--- a/agent/tools.py+++ b/agent/tools.py@@ -537,8 +537,12 @@ def _extract_frame(args: dict, ops: PanelOps, session: dict) -> dict:clip = j.get("output_path") or ""if not clip:raise _ToolValidationError("provide either job_id (finished) or clip_path")- if not Path(clip).is_file():+ clip_p = _ensure_under(+ Path(clip), [ops.outputs_dir, ops.uploads_dir]+ )+ if not clip_p.is_file():raise _ToolValidationError(f"clip not found: {clip}")+ clip = str(clip_p)which = args.get("which", "last")nb = _probe_frame_count(clip)@@ -553,7 +557,12 @@ def _extract_frame(args: dict, ops: PanelOps, session: dict) -> dict:out_name = (args.get("output_name") orf"frame_{Path(clip).stem}_{idx:04d}.png")- out_path = ops.uploads_dir / out_name+ # Strip any directory traversal — output_name is a filename, not a path.+ # Without this, an LLM nudged by a poisoned doc could write outside uploads_dir.+ out_name = Path(out_name).name or f"frame_{idx:04d}.png"+ out_path = (ops.uploads_dir / out_name).resolve()+ if not out_path.is_relative_to(ops.uploads_dir.resolve()):+ raise _ToolValidationError(f"output path escapes uploads dir: {out_name}")out_path.parent.mkdir(parents=True, exist_ok=True)# ffmpeg seek-by-index. -frames:v 1 + select+filter is precise but slow@@ -772,6 +781,10 @@ def _inspect_clip(args: dict, ops: PanelOps, session: dict) -> dict:p = Path(clip_path)if not p.is_absolute():p = (ops.outputs_dir / p).resolve()+ try:+ p = _ensure_under(p, [ops.outputs_dir, ops.uploads_dir])+ except _ToolValidationError as e:+ return {"error": str(e)}if not p.is_file():return {"error": f"clip not found on disk: {p}"}@@ -915,6 +928,32 @@ def _resolve_path(p: str, base: Path) -> str:return str(base / pp)+def _ensure_under(path: Path, allowed_roots: list[Path]) -> Path:+ """Resolve `path` and require it lives under one of `allowed_roots`.++ Defense against prompt-injected file paths reaching `inspect_clip` /+ `extract_frame`. Without this an LLM coaxed by a malicious doc could+ point ffmpeg at /etc/* or read sidecars outside the project tree.+ Symlink/.. tricks are neutralized because we resolve both ends.+ """+ resolved = path.resolve()+ rroots = []+ for r in allowed_roots:+ try:+ rroots.append(r.resolve())+ except OSError:+ pass+ for r in rroots:+ try:+ if resolved.is_relative_to(r):+ return resolved+ except ValueError:+ continue+ raise _ToolValidationError(+ f"path {resolved} is outside the allowed project directories"+ )++def _probe_frame_count(clip_path: str) -> int:"""Get nb_frames via ffprobe. Falls back to a duration*fps estimate.diff --git a/mlx_ltx_panel.py b/mlx_ltx_panel.pyindex c167288..ff35cbd 100644--- a/mlx_ltx_panel.py+++ b/mlx_ltx_panel.py@@ -1732,7 +1732,7 @@ def iso_now() -> str:return time.strftime("%Y-%m-%d %H:%M:%S")-def atomic_write_text(path: Path, text: str) -> None:+def atomic_write_text(path: Path, text: str, *, mode: int = 0o600) -> None:"""Write text to `path` via temp file + fsync + os.replace.Plain Path.write_text() can leave a half-written file if macOS sleeps,@@ -1750,6 +1750,13 @@ def atomic_write_text(path: Path, text: str) -> None:f.flush()os.fsync(f.fileno())os.replace(tmp, path)+ # Default 0o600 ensures secrets in state files (API keys in+ # agent_config.json / agent_image_config.json) aren't world/group+ # readable. umask alone leaves them at 0644 on most systems.+ try:+ os.chmod(path, mode)+ except OSError:+ passfinally:try:if tmp.exists():@@ -3463,6 +3470,45 @@ def _load_agent_config() -> agent_engine.EngineConfig:return cfg+_ALLOWED_REMOTE_HOSTS = {+ # OpenAI-compatible providers we've intentionally tested. The kind="custom"+ # branch lets the user point at any HTTPS endpoint (their own gateway,+ # OpenRouter, etc.); the allow-list below is purely informational and not+ # used to block — see _validate_engine_base_url for the actual policy.+}+++def _validate_engine_base_url(kind: str, base_url: str) -> tuple[bool, str]:+ """Block configs that would leak the user's API key to a hostile target.++ The agent posts the configured api_key as a Bearer token to whatever+ base_url we save. If the user is talked into pasting `http://evil.com/v1`+ the next message exfiltrates the key in plaintext. Two rules:++ * Any non-loopback URL must be HTTPS. Plain http:// outside loopback+ is rejected — even if the user "trusts" the host, an upstream MITM+ could still capture the bearer token.+ * The URL must parse to a real http/https scheme with a host.+ """+ from urllib.parse import urlparse as _u+ url = (base_url or "").strip()+ if not url:+ return False, "base_url is empty"+ try:+ p = _u(url)+ except Exception as e:+ return False, f"unparseable base_url: {e}"+ if p.scheme not in ("http", "https"):+ return False, "base_url must be http:// or https://"+ host = (p.hostname or "").lower()+ if not host:+ return False, "base_url has no host"+ is_loopback = host in {"127.0.0.1", "::1", "localhost"}+ if p.scheme == "http" and not is_loopback:+ return False, "remote base_url must use https:// (refusing to send API key over plaintext)"+ return True, ""++def _save_agent_config(updates: dict) -> agent_engine.EngineConfig:"""Merge `updates` into the current engine config and persist.@@ -3481,6 +3527,9 @@ def _save_agent_config(updates: dict) -> agent_engine.EngineConfig:continue # treat blank as no-change for secretsmerged[k] = vcfg = agent_engine.EngineConfig(**merged)+ ok, why = _validate_engine_base_url(cfg.kind, cfg.base_url)+ if not ok:+ raise ValueError(why)STATE_DIR.mkdir(parents=True, exist_ok=True)atomic_write_text(AGENT_CONFIG_PATH, json.dumps(cfg.__dict__, indent=2))_AGENT_CONFIG_CACHE = cfg@@ -3524,13 +3573,19 @@ def _save_agent_image_config(updates: dict) -> agent_image_engine.ImageEngineConreturn cfg-def _agent_capabilities() -> dict:+def _agent_capabilities(*, include_secrets: bool = False) -> dict:"""Hardware-tier snapshot the agent uses to clamp its plan.Mirrors the SYSTEM_CAPS table in tier-friendly form so the systemprompt can show the user what this Mac can actually render. Alsocarries the current image-engine config so the `generate_shot_images`tool can dispatch without circular imports.++ `include_secrets` controls whether the api_key fields (BFL key etc.)+ are returned. The HTTP-facing endpoint (`GET /agent/config`) calls+ this with the default (False) → masked dict. The PanelOps construction+ used by tools.py inside the agent loop calls with True so the actual+ BFL request can authenticate."""img_cfg = _load_agent_image_config()return {@@ -3543,7 +3598,10 @@ def _agent_capabilities() -> dict:"allows_q8": SYSTEM_CAPS.get("allows_q8", False),"allows_keyframe": SYSTEM_CAPS.get("allows_keyframe", False),"allows_extend": SYSTEM_CAPS.get("allows_extend", False),- "image_engine_config": dict(img_cfg.__dict__),+ "image_engine_config": (+ dict(img_cfg.__dict__) if include_secrets+ else img_cfg.to_public_dict()+ ),}@@ -3652,13 +3710,18 @@ def _agent_find_job(job_id: str) -> dict | None:def _build_panel_ops() -> agent_tools.PanelOps:+ # The PanelOps surface is in-process only — passed to tool dispatch.+ # The capabilities dict here MUST include the bfl_api_key / etc. so+ # `generate_shot_images` can authenticate. The HTTP-facing+ # `/agent/config` endpoint calls _agent_capabilities() WITHOUT+ # include_secrets, masking the keys.return agent_tools.PanelOps(submit_job=_agent_submit_job,queue_snapshot=_agent_queue_snapshot,find_job=_agent_find_job,outputs_dir=OUTPUT,uploads_dir=UPLOADS,- capabilities=_agent_capabilities(),+ capabilities=_agent_capabilities(include_secrets=True),)@@ -3979,6 +4042,43 @@ class Handler(BaseHTTPRequestHandler):def log_message(self, format, *args): # noqa: A002return+ def _is_local_request(self) -> bool:+ """Reject DNS-rebinding attacks.++ We bind to 127.0.0.1, but a malicious page on the open internet can+ still reach us if the user's resolver returns 127.0.0.1 for an+ attacker-controlled hostname (classic DNS rebinding). The browser+ sends the rebound hostname in the Host header and the page's own+ origin in Origin/Referer — both must point at localhost for the+ request to be considered legitimate.++ Rules:+ - Host header must be loopback (127.0.0.1, [::1], localhost) on+ our PORT, or empty (some local tooling omits it).+ - If Origin is present it must also be loopback.+ - Referer is only checked as a last-resort hint.+ """+ host = (self.headers.get("Host") or "").strip().lower()+ # Host can include the port; strip it.+ host_name = host.rsplit(":", 1)[0] if host else ""+ if host_name.startswith("[") and host_name.endswith("]"):+ host_name = host_name[1:-1]+ allowed = {"127.0.0.1", "::1", "localhost", ""}+ if host_name not in allowed:+ return False+ origin = (self.headers.get("Origin") or "").strip().lower()+ if origin and origin != "null":+ try:+ from urllib.parse import urlparse as _u+ ohost = (_u(origin).hostname or "").lower()+ if ohost.startswith("[") and ohost.endswith("]"):+ ohost = ohost[1:-1]+ if ohost not in {"127.0.0.1", "::1", "localhost"}:+ return False+ except Exception:+ return False+ return True+def _ok(self, body: bytes, content_type: str = "text/html; charset=utf-8") -> None:self.send_response(200)self.send_header("Content-Type", content_type)@@ -4080,6 +4180,9 @@ class Handler(BaseHTTPRequestHandler):returndef do_GET(self) -> None:+ if not self._is_local_request():+ self.send_error(403, "non-local request rejected")+ returnparsed = urlparse(self.path)if parsed.path == "/":self._ok(page().encode())@@ -4377,7 +4480,17 @@ class Handler(BaseHTTPRequestHandler):path = Path(qs.get("path", [""])[0]).resolve()except Exception:self.send_error(400); return- # Allow any image file that exists locally (this is a local-only panel)+ # Loopback alone isn't enough — a malicious page or extension on+ # the local machine could request /image?path=/etc/shadow. Resolve+ # both sides and require the requested path to live under our+ # OUTPUT, UPLOADS, or STATE_DIR. is_relative_to() already handles+ # the symlink/.. tricks since we resolved both ends.+ try:+ roots = [OUTPUT.resolve(), UPLOADS.resolve(), STATE_DIR.resolve()]+ except Exception:+ roots = []+ if not any(path.is_relative_to(r) for r in roots):+ self.send_error(403); returnif not path.exists() or not path.is_file():self.send_error(404); returnext = path.suffix.lower()@@ -4427,7 +4540,7 @@ class Handler(BaseHTTPRequestHandler):if parsed.path.startswith("/agent/sessions/"):sid = parsed.path[len("/agent/sessions/"):]sid = sid.split("/", 1)[0]- if not sid:+ if not agent_runtime.is_valid_session_id(sid):self.send_error(404); returnsess = agent_runtime.load_session(sid, STATE_DIR)if sess is None:@@ -4490,12 +4603,29 @@ class Handler(BaseHTTPRequestHandler):self.send_error(404)def do_POST(self) -> None:+ if not self._is_local_request():+ self.send_error(403, "non-local request rejected")+ returnpath = self.path.split("?")[0]qs = parse_qs(urlparse(self.path).query)ctype = self.headers.get("Content-Type", "")# Multipart uploadif path == "/upload" and ctype.startswith("multipart/form-data"):+ # Hard cap on body size so a misbehaving / malicious caller can't+ # spool a multi-GB file into memory via cgi.FieldStorage. 64 MB+ # comfortably covers any reasonable still-image reference; multipart+ # framing adds a small overhead so we read the declared length.+ MAX_UPLOAD_BYTES = 64 * 1024 * 1024+ try:+ clen = int(self.headers.get("Content-Length") or "0")+ except ValueError:+ clen = 0+ if clen <= 0:+ self._json({"error": "Content-Length required"}, 411); return+ if clen > MAX_UPLOAD_BYTES:+ self._json({"error": f"upload too large (max {MAX_UPLOAD_BYTES} bytes)"}, 413)+ returntry:form = cgi.FieldStorage(fp=self.rfile, headers=self.headers,@@ -4935,7 +5065,10 @@ class Handler(BaseHTTPRequestHandler):payload = {k: v[0] if v else "" for k, v in form.items()}except json.JSONDecodeError as e:self._json({"error": f"bad JSON: {e}"}, 400); return- cfg = _save_agent_config(payload)+ try:+ cfg = _save_agent_config(payload)+ except ValueError as e:+ self._json({"error": str(e)}, 400); returnpush(f"agent: engine config updated ({cfg.kind} → {cfg.model})")self._json({"ok": True, "engine": cfg.to_public_dict()})return@@ -4975,6 +5108,8 @@ class Handler(BaseHTTPRequestHandler):if path.startswith("/agent/sessions/") and path.endswith("/message"):sid = path[len("/agent/sessions/"):-len("/message")]+ if not agent_runtime.is_valid_session_id(sid):+ self._json({"error": "session not found"}, 404); returnsess = agent_runtime.load_session(sid, STATE_DIR)if sess is None:self._json({"error": "session not found"}, 404); return@@ -5107,6 +5242,8 @@ class Handler(BaseHTTPRequestHandler):if path.startswith("/agent/sessions/") and path.endswith("/anchors/select"):sid = path[len("/agent/sessions/"):-len("/anchors/select")]+ if not agent_runtime.is_valid_session_id(sid):+ self._json({"error": "session not found"}, 404); returnsess = agent_runtime.load_session(sid, STATE_DIR)if sess is None:self._json({"error": "session not found"}, 404); return