Skip to content

FilmCraft: An open-source, nonlinear video editor written by scratch in pure Rust

control: Require session-token authentication before dispatching requests (#2764)

coderabbitai[bot]d3801e2df8aa
diff --git a/Cargo.lock b/Cargo.lock
index 26cf21297..cd3e6a624 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1704,6 +1704,7 @@ dependencies = [
"pollster 0.4.0",
"rfd",
"serde_json",
+ "subtle",
"sys-locale",
"winit",
"winresource",
diff --git a/apps/filmcraft/Cargo.toml b/apps/filmcraft/Cargo.toml
index 3ae35e6c6..6962a2330 100644
--- a/apps/filmcraft/Cargo.toml
+++ b/apps/filmcraft/Cargo.toml
@@ -29,6 +29,8 @@ filmcraft-platform = { workspace = true }
egui = { workspace = true }
eframe = { workspace = true, features = ["default_fonts", "wgpu", "accesskit", "wayland", "x11"] }
serde_json = { workspace = true }
+# Constant-time comparison of control-channel credentials.
+subtle = "2.6"
log = { workspace = true }
rfd = { workspace = true }
cpal = "0.16"
diff --git a/apps/filmcraft/src/args.rs b/apps/filmcraft/src/args.rs
index c64e3509f..130e23ee2 100644
--- a/apps/filmcraft/src/args.rs
+++ b/apps/filmcraft/src/args.rs
@@ -9,7 +9,8 @@ Usage: filmcraft [options] [project.fcproj | media files...]
Options:
--control <port> start the localhost JSON-lines control server
- (also: FILMCRAFT_CONTROL_PORT)
+ (also: FILMCRAFT_CONTROL_PORT; requires FILMCRAFT_CONTROL_TOKEN,
+ 64 random hex characters; see docs/control-protocol.md)
--control-input-only accept widget input only from the control server
(requires --control or FILMCRAFT_CONTROL_PORT)
--demo open the demo project
diff --git a/apps/filmcraft/src/control_server.rs b/apps/filmcraft/src/control_server.rs
index d3b40f320..af1876f7b 100644
--- a/apps/filmcraft/src/control_server.rs
+++ b/apps/filmcraft/src/control_server.rs
@@ -4,7 +4,9 @@
//! (an HTTP request line from a browser's cross-origin `fetch`, a stray `nc`, binary junk) gets
//! one error reply and the connection is closed, so nothing after it is executed. Lines are
//! bounded ([`MAX_LINE`]) and so is the number of open connections ([`MAX_CONNECTIONS`]); junk
-//! never reaches the UI thread. See `docs/control-protocol.md`.
+//! never reaches the UI thread. Every request must carry the session credential from
+//! `FILMCRAFT_CONTROL_TOKEN`; without a configured credential the listener stays closed.
+//! See `docs/control-protocol.md`.
use std::io::{BufRead, BufReader, Read, Write};
use std::net::{TcpListener, TcpStream};
@@ -15,6 +17,7 @@ use std::time::Duration;
use filmcraft_ui_egui::ControlRequest;
use serde_json::{Value, json};
+use subtle::ConstantTimeEq;
/// Longest accepted request line (bytes, without the newline). Requests are small JSON objects;
/// anything longer is refused and the connection closed.
@@ -23,7 +26,17 @@ pub const MAX_LINE: usize = 4 * 1024 * 1024;
pub const MAX_CONNECTIONS: usize = 16;
pub fn start(port: u16, ctx: egui::Context) -> Receiver<ControlRequest> {
+ start_with_token(port, ctx, std::env::var("FILMCRAFT_CONTROL_TOKEN").ok())
+}
+
+fn start_with_token(port: u16, ctx: egui::Context, token: Option<String>) -> Receiver<ControlRequest> {
let (tx, rx) = channel::<ControlRequest>();
+ // An inherited environment variable shares the credential with the owner's bridge process
+ // without exposing it in command-line arguments, logs, or a shared discovery file.
+ let Some(token) = token.filter(|t| t.len() == 64 && t.bytes().all(|b| b.is_ascii_hexdigit())) else {
+ eprintln!("filmcraft: control server disabled: FILMCRAFT_CONTROL_TOKEN must contain 64 random hex characters (see docs/control-protocol.md)");
+ return rx;
+ };
let listener = match TcpListener::bind(("127.0.0.1", port)) {
Ok(l) => l,
Err(e) => {
@@ -32,11 +45,11 @@ pub fn start(port: u16, ctx: egui::Context) -> Receiver<ControlRequest> {
}
};
eprintln!("filmcraft: control server listening on 127.0.0.1:{port}");
- std::thread::spawn(move || accept_loop(listener, tx, ctx));
+ std::thread::spawn(move || accept_loop(listener, tx, ctx, token));
rx
}
-fn accept_loop(listener: TcpListener, tx: Sender<ControlRequest>, ctx: egui::Context) {
+fn accept_loop(listener: TcpListener, tx: Sender<ControlRequest>, ctx: egui::Context, token: String) {
let open = Arc::new(AtomicUsize::new(0));
for mut stream in listener.incoming().flatten() {
if open.fetch_add(1, Ordering::SeqCst) >= MAX_CONNECTIONS {
@@ -46,12 +59,13 @@ fn accept_loop(listener: TcpListener, tx: Sender<ControlRequest>, ctx: egui::Con
}
let tx = tx.clone();
let ctx = ctx.clone();
+ let token = token.clone();
// The slot is given back when the guard drops: after `serve` returns, if it panics, or if
// the thread can't be started (the closure, and with it the guard, is dropped).
let slot = Slot(Arc::clone(&open));
let spawned = std::thread::Builder::new().name("control-conn".into()).spawn(move || {
let _slot = slot;
- serve(stream, &tx, &ctx);
+ serve(stream, &tx, &ctx, &token);
});
if let Err(e) = spawned {
eprintln!("filmcraft: control server could not start a connection thread: {e}");
@@ -68,9 +82,9 @@ impl Drop for Slot {
}
}
-fn serve(stream: TcpStream, tx: &Sender<ControlRequest>, ctx: &egui::Context) {
+fn serve(stream: TcpStream, tx: &Sender<ControlRequest>, ctx: &egui::Context, token: &str) {
let Ok(read) = stream.try_clone() else { return };
- serve_lines(read, stream, |method, params| {
+ serve_lines(read, stream, token, |method, params| {
let (req, rrx) = ControlRequest::new(method, params);
tx.send(req).ok()?;
ctx.request_repaint();
@@ -90,7 +104,7 @@ enum Line {
Reject(String),
}
-fn parse_line(bytes: &[u8]) -> Line {
+fn parse_line(bytes: &[u8], token: &str) -> Line {
let Ok(text) = std::str::from_utf8(bytes) else {
return Line::Reject("not a control request (invalid UTF-8); closing the connection".into());
};
@@ -108,6 +122,12 @@ fn parse_line(bytes: &[u8]) -> Line {
let Some(method) = obj.get("method").and_then(Value::as_str) else {
return Line::Reject("not a control request (missing string `method`); closing the connection".into());
};
+ // Authenticate every request before constructing or enqueueing a ControlRequest. A valid
+ // earlier request must not authorize a later one with a missing or incorrect credential.
+ let authenticated = obj.get("token").and_then(Value::as_str).is_some_and(|supplied| bool::from(supplied.as_bytes().ct_eq(token.as_bytes())));
+ if !authenticated {
+ return Line::Reject("control authentication failed; closing the connection".into());
+ }
Line::Request { id: obj.get("id").cloned().unwrap_or(Value::Null), method: method.to_string(), params: obj.get("params").cloned().unwrap_or(json!({})) }
}
@@ -138,14 +158,14 @@ fn read_bounded_line(reader: &mut impl BufRead, buf: &mut Vec<u8>, max: usize) -
/// Serve requests from `read`, answering on `out`, until the peer closes, sends something that is
/// not a request, or `handle` returns `None` (app gone). `handle` gets `(method, params)` and
/// returns the reply object (the request's `id` is added here).
-fn serve_lines<R: Read, W: Write>(read: R, mut out: W, mut handle: impl FnMut(String, Value) -> Option<Value>) {
+fn serve_lines<R: Read, W: Write>(read: R, mut out: W, token: &str, mut handle: impl FnMut(String, Value) -> Option<Value>) {
let mut reader = BufReader::new(read);
let mut buf = Vec::new();
loop {
let reject = match read_bounded_line(&mut reader, &mut buf, MAX_LINE) {
Ok(false) => return,
Err(e) => e,
- Ok(true) => match parse_line(&buf) {
+ Ok(true) => match parse_line(&buf, token) {
Line::Blank => continue,
Line::Reject(e) => e,
Line::Request { id, method, params } => {
@@ -169,10 +189,12 @@ fn serve_lines<R: Read, W: Write>(read: R, mut out: W, mut handle: impl FnMut(St
mod tests {
use super::*;
+ const TOKEN: &str = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef";
+
fn run(input: &[u8]) -> (Vec<Value>, Vec<String>) {
let mut out = Vec::new();
let mut calls = Vec::new();
- serve_lines(input, &mut out, |m, _p| {
+ serve_lines(input, &mut out, TOKEN, |m, _p| {
calls.push(m);
Some(json!({"ok": true, "result": null}))
});
@@ -182,7 +204,10 @@ mod tests {
#[test]
fn requests_are_answered_in_order_with_ids() {
- let (r, calls) = run(b"{\"id\":1,\"method\":\"a\"}\n\n{\"id\":2,\"method\":\"b\",\"params\":{}}\r\n{\"method\":\"c\"}");
+ let input = format!(
+ "{{\"token\":\"{TOKEN}\",\"id\":1,\"method\":\"a\"}}\n\n{{\"token\":\"{TOKEN}\",\"id\":2,\"method\":\"b\",\"params\":{{}}}}\r\n{{\"token\":\"{TOKEN}\",\"method\":\"c\"}}"
+ );
+ let (r, calls) = run(input.as_bytes());
assert_eq!(calls, ["a", "b", "c"]);
assert_eq!(r.len(), 3);
assert_eq!(r[0]["id"], 1);
@@ -220,7 +245,8 @@ mod tests {
#[test]
fn a_request_before_junk_still_runs() {
- let (r, calls) = run(b"{\"method\":\"a\"}\nGET / HTTP/1.1\n{\"method\":\"b\"}\n");
+ let input = format!("{{\"token\":\"{TOKEN}\",\"method\":\"a\"}}\nGET / HTTP/1.1\n{{\"token\":\"{TOKEN}\",\"method\":\"b\"}}\n");
+ let (r, calls) = run(input.as_bytes());
assert_eq!(calls, ["a"]);
assert_eq!(r.len(), 2);
assert_eq!(r[1]["ok"], false);
@@ -256,11 +282,11 @@ mod tests {
let server = std::thread::spawn(move || {
let (s, _) = listener.accept().unwrap();
let read = s.try_clone().unwrap();
- serve_lines(read, s, |_, _| Some(json!({"ok": true})));
+ serve_lines(read, s, TOKEN, |_, _| Some(json!({"ok": true})));
});
let mut c = TcpStream::connect(addr).unwrap();
c.set_read_timeout(Some(Duration::from_secs(5))).unwrap();
- c.write_all(b"{\"id\":7,\"method\":\"x\"}\nhello\n{\"method\":\"y\"}\n").unwrap();
+ c.write_all(format!("{{\"token\":\"{TOKEN}\",\"id\":7,\"method\":\"x\"}}\nhello\n{{\"token\":\"{TOKEN}\",\"method\":\"y\"}}\n").as_bytes()).unwrap();
let mut text = String::new();
c.read_to_string(&mut text).unwrap(); // returns at EOF: the server closed the connection
server.join().unwrap();
@@ -275,7 +301,7 @@ mod tests {
let listener = TcpListener::bind(("127.0.0.1", 0)).unwrap();
let addr = listener.local_addr().unwrap();
let (tx, _rx) = channel::<ControlRequest>();
- std::thread::spawn(move || accept_loop(listener, tx, egui::Context::default()));
+ std::thread::spawn(move || accept_loop(listener, tx, egui::Context::default(), TOKEN.into()));
// Idle connections are accepted in order and held open.
let held: Vec<TcpStream> = (0..16).map(|_| TcpStream::connect(addr).unwrap()).collect();
let mut extra = TcpStream::connect(addr).unwrap();
@@ -285,4 +311,91 @@ mod tests {
assert!(line.contains("too many control connections"), "{line}");
drop(held);
}
+
+ #[test]
+ fn missing_or_invalid_token_leaves_the_listener_closed() {
+ for token in [None, Some(String::new()), Some("a".repeat(63)), Some("a".repeat(65)), Some("z".repeat(64))] {
+ let listener = TcpListener::bind(("127.0.0.1", 0)).unwrap();
+ let port = listener.local_addr().unwrap().port();
+ drop(listener);
+ let rx = start_with_token(port, egui::Context::default(), token);
+ assert!(matches!(rx.try_recv(), Err(std::sync::mpsc::TryRecvError::Disconnected)));
+ let _still_available = TcpListener::bind(("127.0.0.1", port)).unwrap();
+ }
+ }
+
+ #[test]
+ fn unauthenticated_save_as_closes_before_any_command_runs() {
+ for token in
+ [Value::Null, json!(false), json!(42), json!([]), json!({}), json!(""), json!("a".repeat(64)), json!(&TOKEN[..63]), json!(format!("{TOKEN}0"))]
+ {
+ let mut request = json!({"id": 1, "method": "engine.execute", "params": {"command": "file.saveAs", "params": {"path": "/owner/project.fcproj"}}});
+ if !token.is_null() {
+ request["token"] = token;
+ }
+ // A valid request after a rejected one must never execute, either.
+ let input = format!("{request}\n{}\n", json!({"token": TOKEN, "method": "ui.inspect"}));
+ let (replies, calls) = run(input.as_bytes());
+ assert!(calls.is_empty());
+ assert_eq!(replies, [json!({"ok": false, "error": "control authentication failed; closing the connection"})]);
+ }
+ }
+
+ #[test]
+ fn authentication_is_required_on_every_request() {
+ let input = format!(
+ "{}\n{}\n{}\n",
+ json!({"token": TOKEN, "method": "ui.inspect"}),
+ json!({"method": "app.quit"}),
+ json!({"token": TOKEN, "method": "app.quit"})
+ );
+ let (replies, calls) = run(input.as_bytes());
+ assert_eq!(calls, ["ui.inspect"]);
+ assert_eq!(replies.len(), 2);
+ assert_eq!(replies[1]["ok"], false);
+ }
+
+ #[test]
+ fn tcp_authentication_happens_before_enqueueing() {
+ let listener = TcpListener::bind(("127.0.0.1", 0)).unwrap();
+ let addr = listener.local_addr().unwrap();
+ let (tx, rx) = channel::<ControlRequest>();
+ let server = std::thread::spawn(move || {
+ let (s, _) = listener.accept().unwrap();
+ serve(s, &tx, &egui::Context::default(), TOKEN);
+ });
+ let mut c = TcpStream::connect(addr).unwrap();
+ c.set_read_timeout(Some(Duration::from_secs(5))).unwrap();
+ c.write_all(b"{\"method\":\"engine.execute\",\"params\":{\"command\":\"file.saveAs\",\"params\":{\"path\":\"/owner/project.fcproj\"}}}\n").unwrap();
+ c.shutdown(std::net::Shutdown::Write).unwrap();
+ let mut reply = String::new();
+ c.read_to_string(&mut reply).unwrap();
+ server.join().unwrap();
+ assert!(reply.contains("control authentication failed"));
+ assert!(matches!(rx.try_recv(), Err(std::sync::mpsc::TryRecvError::Disconnected)));
+ }
+
+ #[test]
+ fn authenticated_tcp_request_reaches_the_ui_queue() {
+ let listener = TcpListener::bind(("127.0.0.1", 0)).unwrap();
+ let addr = listener.local_addr().unwrap();
+ let (tx, rx) = channel::<ControlRequest>();
+ let server = std::thread::spawn(move || {
+ let (s, _) = listener.accept().unwrap();
+ serve(s, &tx, &egui::Context::default(), TOKEN);
+ });
+ let params = json!({"command": "file.saveAs", "params": {"path": "/owner/project.fcproj"}});
+ let mut c = TcpStream::connect(addr).unwrap();
+ c.set_read_timeout(Some(Duration::from_secs(5))).unwrap();
+ writeln!(c, "{}", json!({"id": 7, "token": TOKEN, "method": "engine.execute", "params": params})).unwrap();
+ c.shutdown(std::net::Shutdown::Write).unwrap();
+ let request = rx.recv_timeout(Duration::from_secs(5)).unwrap();
+ assert_eq!(request.method, "engine.execute");
+ assert_eq!(request.params, params);
+ request.reply.send(json!({"ok": true})).unwrap();
+ let mut reply = String::new();
+ c.read_to_string(&mut reply).unwrap();
+ server.join().unwrap();
+ assert_eq!(serde_json::from_str::<Value>(&reply).unwrap(), json!({"id": 7, "ok": true}));
+ }
}
diff --git a/apps/filmcraft/src/main.rs b/apps/filmcraft/src/main.rs
index f850b1638..5ffec5aa2 100644
--- a/apps/filmcraft/src/main.rs
+++ b/apps/filmcraft/src/main.rs
@@ -8,6 +8,7 @@
//! (the demo project), Open Most Recent, or an empty project.
//!
//! `--control <port>` (or `FILMCRAFT_CONTROL_PORT`) starts a localhost JSON-lines control server;
+//! `FILMCRAFT_CONTROL_TOKEN` is required (see `docs/control-protocol.md`).
//! see `filmcraft_ui_egui::control` for the methods. A port that is not a number is an error from
//! either source.
//!
diff --git a/crates/automation/src/bridge.rs b/crates/automation/src/bridge.rs
index f51db9adf..032e4e657 100644
--- a/crates/automation/src/bridge.rs
+++ b/crates/automation/src/bridge.rs
@@ -20,6 +20,8 @@ type Conn = (BufReader<tokio::net::tcp::OwnedReadHalf>, tokio::net::tcp::OwnedWr
pub struct BridgeClient {
addr: String,
+ /// Inherited from the same owner-controlled environment as the desktop app.
+ token: Option<String>,
/// Connections with no request in flight. A request takes one (or opens one) for its whole
/// round trip and puts it back only once the reply is read, so a slow or abandoned request
/// never holds up the others or leaves its late reply for the next one to read (#1538).
@@ -28,14 +30,15 @@ pub struct BridgeClient {
}
impl BridgeClient {
- /// `addr` such as `127.0.0.1:9876` (loopback only).
+ /// `addr` such as `127.0.0.1:9876` (loopback only). Reads `FILMCRAFT_CONTROL_TOKEN`
+ /// from the environment; the desktop app requires this credential on every request.
pub fn new(addr: impl Into<String>) -> Result<Self, AutomationError> {
let addr = addr.into();
let host = addr.rsplit_once(':').map(|(h, _)| h).unwrap_or(&addr);
if !matches!(host, "127.0.0.1" | "localhost" | "[::1]" | "::1") {
return Err(AutomationError::BadRequest(format!("bridge address must be loopback, got `{addr}`")));
}
- Ok(Self { addr, idle: Mutex::new(Vec::new()), next_id: AtomicU64::new(1) })
+ Ok(Self { addr, token: std::env::var("FILMCRAFT_CONTROL_TOKEN").ok(), idle: Mutex::new(Vec::new()), next_id: AtomicU64::new(1) })
}
/// Run engine command `id` in the app. A blocking export (`file.exportMedia` with
@@ -85,7 +88,7 @@ impl BridgeClient {
None => self.connect().await?,
};
let id = self.next_id.fetch_add(1, Ordering::Relaxed);
- let line = format!("{}\n", json!({"id": id, "method": method, "params": params}));
+ let line = format!("{}\n", json!({"id": id, "token": self.token, "method": method, "params": params}));
let res: Result<Value, AutomationError> = async {
conn.1.write_all(line.as_bytes()).await.map_err(|e| AutomationError::Bridge(e.to_string()))?;
let mut buf = String::new();
@@ -282,4 +285,19 @@ mod tests {
assert_eq!(seen.len(), 2);
assert_eq!(seen[1]["params"]["command"], "sequence.inspect");
}
+
+ #[tokio::test]
+ async fn credential_is_sent_on_every_request() {
+ let (addr, seen) = fake_app(Value::Null).await;
+ let mut b = BridgeClient::new(addr).unwrap();
+ // Inject directly to avoid mutating the process environment in parallel tests.
+ let token = "0123456789abcdef".repeat(4);
+ b.token = Some(token.clone());
+ b.call("ui.inspect", json!({})).await.unwrap();
+ b.execute("file.saveAs", json!({"path": "/owner/project.fcproj"})).await.unwrap();
+ let seen = seen.lock().await;
+ assert_eq!(seen.len(), 2);
+ assert!(seen.iter().all(|request| request["token"] == token));
+ assert_eq!(seen[1]["params"]["params"]["path"], "/owner/project.fcproj");
+ }
}
diff --git a/docs/agents.md b/docs/agents.md
index 4b85410f0..b680ce99a 100644
--- a/docs/agents.md
+++ b/docs/agents.md
@@ -23,6 +23,7 @@ and write wherever the user can.
```sh
cargo build --release -p filmcraft-cli -p filmcraft
+export FILMCRAFT_CONTROL_TOKEN="$(python3 -c 'import secrets; print(secrets.token_hex(32))')"
./target/release/filmcraft --control 9876 & # only for the bridge server
claude # approve the project MCP servers when asked
```
@@ -134,29 +135,31 @@ progress and stop it:
## 2. Control channel
`filmcraft --control 9876` (or `FILMCRAFT_CONTROL_PORT=9876`) listens on `127.0.0.1` only. Send one
-JSON request per line and get one JSON reply per line. Full method table:
+JSON request per line and get one JSON reply per line. Set a fresh `FILMCRAFT_CONTROL_TOKEN` for the
+desktop session as above; the CLI / MCP bridge must inherit the same variable. Raw requests must
+include it as `token` on every line (replace the placeholders below). Full setup and method table:
[control-protocol.md](control-protocol.md).
```jsonc
-{"id":1,"method":"engine.commands"}
-{"id":2,"method":"engine.execute","params":{"command":"file.openDemoProject"}}
-{"id":3,"method":"engine.execute","params":{"command":"playhead.set","params":{"seconds":2}}}
-{"id":4,"method":"engine.execute","params":{"command":"sequence.addEdit"}}
-{"id":5,"method":"engine.execute","params":{"command":"effects.apply","params":{"effect":"Gaussian Blur"}}}
-{"id":6,"method":"ui.elements","params":{"prefix":"tools."}}
-{"id":7,"method":"ui.click","params":{"id":"tools.Razor"}}
-{"id":8,"method":"ui.key","params":{"key":"Cmd+Z"}}
-{"id":9,"method":"ui.screenshot","params":{"path":"/tmp/timeline.png","panel":"Timeline"}}
+{"id":1,"token":"<FILMCRAFT_CONTROL_TOKEN>","method":"engine.commands"}
+{"id":2,"token":"<FILMCRAFT_CONTROL_TOKEN>","method":"engine.execute","params":{"command":"file.openDemoProject"}}
+{"id":3,"token":"<FILMCRAFT_CONTROL_TOKEN>","method":"engine.execute","params":{"command":"playhead.set","params":{"seconds":2}}}
+{"id":4,"token":"<FILMCRAFT_CONTROL_TOKEN>","method":"engine.execute","params":{"command":"sequence.addEdit"}}
+{"id":5,"token":"<FILMCRAFT_CONTROL_TOKEN>","method":"engine.execute","params":{"command":"effects.apply","params":{"effect":"Gaussian Blur"}}}
+{"id":6,"token":"<FILMCRAFT_CONTROL_TOKEN>","method":"ui.elements","params":{"prefix":"tools."}}
+{"id":7,"token":"<FILMCRAFT_CONTROL_TOKEN>","method":"ui.click","params":{"id":"tools.Razor"}}
+{"id":8,"token":"<FILMCRAFT_CONTROL_TOKEN>","method":"ui.key","params":{"key":"Cmd+Z"}}
+{"id":9,"token":"<FILMCRAFT_CONTROL_TOKEN>","method":"ui.screenshot","params":{"path":"/tmp/timeline.png","panel":"Timeline"}}
```
Replies look like `{"id":4,"ok":true,"result":{"cuts":2}}` or `{"id":7,"ok":false,"error":"…"}`.
Minimal client:
```python
-import json, socket
+import json, os, socket
s = socket.create_connection(("127.0.0.1", 9876)); f = s.makefile("rw")
def call(method, **params):
- f.write(json.dumps({"id": 1, "method": method, "params": params}) + "\n"); f.flush()
+ f.write(json.dumps({"id": 1, "token": os.environ["FILMCRAFT_CONTROL_TOKEN"], "method": method, "params": params}) + "\n"); f.flush()
return json.loads(f.readline())
print(call("engine.execute", command="sequence.inspect"))
```
diff --git a/docs/contributing.md b/docs/contributing.md
index c7af17706..6b5c05108 100644
--- a/docs/contributing.md
+++ b/docs/contributing.md
@@ -39,6 +39,7 @@ cargo xtask web --serve 8765 # the web app on http://12
| Variable | Effect |
|---|---|
| `FILMCRAFT_CONTROL_PORT` | Same as `--control <port>` |
+| `FILMCRAFT_CONTROL_TOKEN` | Required for `--control`: 64 random hex characters, inherited by authorized clients; [setup](control-protocol.md) |
| `FILMCRAFT_CPU_COMPOSITE=1` | Disables the GPU compositor |
| `FILMCRAFT_DEV_DESKTOP_ENTRY=1` | Linux, opt-in: a run from a source tree installs a user-level desktop entry (and the icons from `assets/app-icon`) so the taskbar shows the FilmCraft icon. Nothing is written without it; packaged runs never write one |
| `FILMCRAFT_DATA_DIR` | Same as `--data-dir <dir>`: auto-save, crash recovery, settings and logs |
diff --git a/docs/control-protocol.md b/docs/control-protocol.md
index 80802cf20..9cdb36791 100644
--- a/docs/control-protocol.md
+++ b/docs/control-protocol.md
@@ -2,6 +2,22 @@
## Desktop control channel
`filmcraft --control 9876` (or `FILMCRAFT_CONTROL_PORT`) listens on `127.0.0.1:<port>` (loopback only).
+The listener requires `FILMCRAFT_CONTROL_TOKEN`: 64 random hex characters shared with authorized
+clients through their inherited environment. Generate a fresh token for each desktop session, then
+start the desktop and bridge from that environment:
+
+```sh
+export FILMCRAFT_CONTROL_TOKEN="$(python3 -c 'import secrets; print(secrets.token_hex(32))')"
+filmcraft --control 9876 &
+filmcraft-cli mcp --bridge 127.0.0.1:9876
+```
+
+The CLI / MCP bridge reads this variable automatically. Keep it private: don't put the value in
+command-line arguments, logs, checked-in MCP configuration, or shared files. Without a valid value,
+the desktop leaves the listener closed. Every raw JSON request must include the same top-level
+`token` string; missing or incorrect credentials get an error and close the connection before any
+request is dispatched. Loopback alone does not restrict clients to the desktop owner's OS account.
+
One JSON request per line → one JSON reply per line. The app opts out of macOS App Nap
(`apps/filmcraft/src/app_nap.rs`): a hidden window would otherwise drop the whole process to
background priority, and on a busy machine it would stop answering.
@@ -13,11 +29,11 @@ nothing sent after it on that connection runs. That covers text that isn't JSON,
an object without `method`, invalid UTF-8, and a line longer than 4 MiB. An HTTP request (for example a
web page's cross-origin `fetch` to `127.0.0.1:<port>`) therefore can't smuggle a command in its body:
its request line is rejected first. At most 16 connections are served at once; further ones get an error
-line and are closed. Clients that get an error reply should reconnect. The port has no authentication,
-so only enable it while you use it. Transport: `apps/filmcraft/src/control_server.rs`.
+line and are closed. Clients that get an error reply should reconnect. Transport:
+`apps/filmcraft/src/control_server.rs`.
```json
-{"id": 1, "method": "engine.execute", "params": {"command": "sequence.addEdit", "params": {"seconds": 3}}}
+{"id": 1, "token": "<FILMCRAFT_CONTROL_TOKEN>", "method": "engine.execute", "params": {"command": "sequence.addEdit", "params": {"seconds": 3}}}
{"id": 1, "ok": true, "result": {"cuts": 2}}
```