Skip to main content

litz_cli/
editor_link.rs

1//! `litz connect-editor`: the link between a build and the editor page.
2//!
3//! The editor cannot run a firmware toolchain, and `litz build` cannot draw a
4//! circuit. This module is the smallest bridge between the two: one process,
5//! one loopback port, a pairing token, WebSocket text messages for commands
6//! and build output, and an in-memory artifact store the editor fetches over
7//! plain HTTP.
8//!
9//! Nothing leaves the machine. The token is the only way in: a page that was
10//! not handed the URL printed by `connect-editor` gets 403 on every route.
11//! The socket accepts three commands — build this project's own recipe, accept
12//! bytes a `litz build --push` already produced, and read or write the editor's
13//! project library — and never a command string, so the link is not a shell.
14//!
15//! The library is the only place the link touches the filesystem for the page:
16//! flat `.litzproject.json` files under `.litz/projects`, each named by a stem
17//! that cannot leave that directory.
18
19use crate::build;
20use sha2::{Digest, Sha256};
21use std::collections::HashMap;
22use std::io::{Read, Write};
23use std::net::{TcpListener, TcpStream};
24use std::path::{Path, PathBuf};
25use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
26use std::sync::{Arc, Mutex, RwLock, mpsc};
27use std::time::Duration;
28
29pub const DEFAULT_PORT: u16 = 4317;
30
31/// A connection that sends nothing for this long is dropped. The editor pings
32/// every 25 seconds, so this only ends links whose page is gone.
33const IDLE: Duration = Duration::from_secs(90);
34/// JSON messages are tiny; only a pushed image is large.
35const MAX_FRAME: usize = 64 * 1024 * 1024;
36const MAX_ARTIFACTS: usize = 8;
37const LOCK_FILE: &str = ".litz/editor.json";
38const GUID: &str = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
39/// Where the editor keeps the projects it saves through the link. A project is
40/// one file, so the library is a directory the user can list, copy or commit.
41const LIBRARY: &str = ".litz/projects";
42const PROJECT_SUFFIX: &str = ".litzproject.json";
43/// A project carries its parts, code and wires; 8 MB is generous for one and
44/// still small enough that a save cannot stall the socket.
45const MAX_PROJECT: usize = 8 * 1024 * 1024;
46
47/// One image the editor can fetch, keyed by its SHA-256.
48struct Artifact {
49    board: Option<String>,
50    name: String,
51    bytes: Arc<Vec<u8>>,
52}
53
54/// A connected page (or a `--push` client) and the channel its writer drains.
55struct Session {
56    id: u64,
57    out: mpsc::Sender<Message>,
58}
59
60enum Message {
61    Text(String),
62    /// A WebSocket control frame. The server never sends a binary data frame:
63    /// images leave through the artifact route, which the page fetches itself.
64    Pong(Vec<u8>),
65    Close,
66}
67
68/// What a link serves and who may reach it.
69pub struct Options {
70    pub directory: PathBuf,
71    pub port: u16,
72    /// Interface to bind. Loopback by default; a server sets this on purpose.
73    pub host: String,
74    /// Pages allowed to open the socket. Empty accepts any page that holds the
75    /// code, which is the loopback case.
76    pub origins: Vec<String>,
77    /// An editor build to serve beside the link, so page and socket share one
78    /// origin and the browser has nothing to negotiate.
79    pub assets: Option<PathBuf>,
80}
81
82struct State {
83    dir: PathBuf,
84    token: String,
85    origins: Vec<String>,
86    assets: Option<PathBuf>,
87    sessions: RwLock<Vec<Session>>,
88    artifacts: Mutex<Vec<(String, Artifact)>>,
89    next_id: AtomicU64,
90    /// One build at a time: two recipes writing the same output directory
91    /// would interleave their files and produce an image neither intended.
92    building: AtomicBool,
93}
94
95impl State {
96    fn keep(&self, sha: String, artifact: Artifact) {
97        let mut artifacts = self.artifacts.lock().unwrap();
98        artifacts.retain(|(key, _)| key != &sha);
99        artifacts.push((sha, artifact));
100        if artifacts.len() > MAX_ARTIFACTS {
101            artifacts.remove(0);
102        }
103    }
104
105    fn artifact(&self, sha: &str) -> Option<(Option<String>, String, Arc<Vec<u8>>)> {
106        let artifacts = self.artifacts.lock().unwrap();
107        artifacts
108            .iter()
109            .find(|(key, _)| key == sha)
110            .map(|(_, artifact)| {
111                (
112                    artifact.board.clone(),
113                    artifact.name.clone(),
114                    artifact.bytes.clone(),
115                )
116            })
117    }
118}
119
120/// Serve a project to an editor page until the process is interrupted.
121///
122/// `port` 0 asks the system for one, which is what the tests use.
123pub fn serve(options: &Options) -> Result<(), String> {
124    let (listener, token) = listen(options)?;
125    let port = listener
126        .local_addr()
127        .map_err(|e| format!("editor link: {e}"))?
128        .port();
129    // A wildcard bind is not an address a browser can use, so the printed URL
130    // names loopback and says what to replace it with.
131    let wildcard = options.host == "0.0.0.0" || options.host == "::";
132    let host = if wildcard { "127.0.0.1" } else { &options.host };
133    // One line to copy: the page reads the pairing code from the fragment, so
134    // the code never reaches the server in a request line or a log.
135    match &options.assets {
136        Some(assets) => {
137            println!("litz: editor at http://{host}:{port}/#{token}");
138            println!("litz: serving {} as well; Ctrl-C to stop", assets.display());
139        }
140        None => {
141            println!("litz: editor link ws://{host}:{port}/ws#{token}");
142            println!("litz: paste that into the editor's Connect dialog; Ctrl-C to stop");
143        }
144    }
145    if wildcard {
146        println!(
147            "litz: listening on every interface; replace 127.0.0.1 with the name the editor reaches"
148        );
149    }
150    if wildcard || !loopback(&options.host) {
151        if options.origins.is_empty() {
152            eprintln!(
153                "litz: warning: bound to {} without --origin; any page holding the code may attach",
154                options.host
155            );
156        }
157        eprintln!("litz: warning: this listener speaks plain HTTP; terminate TLS in front of it");
158    }
159    println!("litz: `litz build --push` from another terminal sends an image here");
160    accept_loop(listener, Arc::new(state(options, token)));
161    Ok(())
162}
163
164fn loopback(host: &str) -> bool {
165    host == "127.0.0.1" || host == "::1" || host == "localhost"
166}
167
168/// Bind the listener and claim the project's lock file.
169fn listen(options: &Options) -> Result<(TcpListener, String), String> {
170    let dir = options
171        .directory
172        .canonicalize()
173        .map_err(|e| format!("{}: {e}", options.directory.display()))?;
174    if let Ok((running, _)) = read_lock(&dir)
175        && TcpStream::connect(("127.0.0.1", running)).is_ok()
176    {
177        return Err(format!(
178            "an editor link is already running on port {running}; close it first"
179        ));
180    }
181    let listener = TcpListener::bind((options.host.as_str(), options.port))
182        .map_err(|e| format!("cannot listen on {}:{}: {e}", options.host, options.port))?;
183    let actual = listener
184        .local_addr()
185        .map_err(|e| format!("editor link: {e}"))?
186        .port();
187    let token = token();
188    write_lock(&dir, actual, &token)?;
189    Ok((listener, token))
190}
191
192fn state(options: &Options, token: String) -> State {
193    State {
194        dir: options.directory.to_path_buf(),
195        token,
196        origins: options.origins.clone(),
197        assets: options.assets.clone(),
198        sessions: RwLock::new(Vec::new()),
199        artifacts: Mutex::new(Vec::new()),
200        next_id: AtomicU64::new(1),
201        building: AtomicBool::new(false),
202    }
203}
204
205fn accept_loop(listener: TcpListener, state: Arc<State>) {
206    for stream in listener.incoming() {
207        match stream {
208            Ok(stream) => {
209                let state = state.clone();
210                std::thread::spawn(move || handle(stream, state));
211            }
212            Err(e) => eprintln!("litz: editor link: {e}"),
213        }
214    }
215}
216
217/// A project's built image, ready to hand to an editor.
218///
219/// `board` names a `[[board]]` entry; without one the recipe's `[build]
220/// firmware` is the answer, which is what a single-board project builds.
221pub fn push(dir: &Path, board: Option<&str>) -> Result<String, String> {
222    let (port, token) = read_lock(&dir.canonicalize().map_err(|e| e.to_string())?)?;
223    let (name, path) = build::image_for(dir, board)?;
224    let bytes = std::fs::read(&path).map_err(|e| format!("{}: {e}", path.display()))?;
225    let sha = hex(&Sha256::digest(&bytes));
226    let file = path
227        .file_name()
228        .map(|name| name.to_string_lossy().into_owned())
229        .unwrap_or_else(|| "firmware.bin".to_string());
230
231    let mut stream = TcpStream::connect(("127.0.0.1", port))
232        .map_err(|e| format!("editor link on port {port}: {e}"))?;
233    stream
234        .set_read_timeout(Some(Duration::from_secs(30)))
235        .map_err(|e| e.to_string())?;
236    client_handshake(&mut stream, port, &token)?;
237    let published = publish_message(board.or(name.as_deref()), &file, &sha, bytes.len());
238    write_frame(&mut stream, 0x1, published.as_bytes(), true)?;
239    let ready = read_text(&mut stream, false)?;
240    if ready.get("type").and_then(|kind| kind.as_str()) != Some("publish.ready") {
241        return Err(format!("editor link refused the image: {ready}"));
242    }
243    write_frame(&mut stream, 0x2, &bytes, true)?;
244    let done = read_text(&mut stream, false)?;
245    match done.get("type").and_then(|kind| kind.as_str()) {
246        Some("pushed") => Ok(format!("pushed {file} to the editor ({sha})")),
247        _ => Err(format!("editor link did not accept the image: {done}")),
248    }
249}
250
251fn publish_message(board: Option<&str>, file: &str, sha: &str, size: usize) -> String {
252    serde_json::json!({
253        "type": "publish",
254        "board": board,
255        "name": file,
256        "sha256": sha,
257        "size": size,
258    })
259    .to_string()
260}
261
262// ---------------------------------------------------------------------------
263// HTTP side
264
265fn handle(mut stream: TcpStream, state: Arc<State>) {
266    let _ = stream.set_nodelay(true);
267    let _ = stream.set_read_timeout(Some(IDLE));
268    let Ok(request) = read_request(&mut stream) else {
269        return;
270    };
271    let origin = request.headers.get("origin").map(String::as_str);
272    if !allowed(&state.origins, origin) {
273        let _ = respond(
274            &mut stream,
275            403,
276            "text/plain",
277            b"this page is not allowed on this link",
278            origin,
279            &[],
280        );
281        return;
282    }
283    let (path, query) = split_target(&request.target);
284    // The code arrives in the query for a plain link, in the socket protocol or
285    // an Authorization header once a page wants it out of request lines.
286    let bearer = request
287        .headers
288        .get("authorization")
289        .and_then(|value| value.strip_prefix("Bearer "))
290        .unwrap_or("");
291    let offered = offered_token(
292        request
293            .headers
294            .get("sec-websocket-protocol")
295            .map(String::as_str),
296    );
297    let provided = query.get("token").map(String::as_str).unwrap_or("");
298    let authorized =
299        same(&state.token, provided) || same(&state.token, bearer) || same(&state.token, offered);
300    let protocol = if request.headers.contains_key("sec-websocket-protocol") {
301        "Sec-WebSocket-Protocol: litz\r\n"
302    } else {
303        ""
304    };
305
306    if request.method == "OPTIONS" {
307        let _ = respond(&mut stream, 204, "text/plain", b"", origin, &[]);
308        return;
309    }
310    match path.as_str() {
311        "/health" => {
312            let body = serde_json::json!({
313                "ok": true,
314                "version": env!("CARGO_PKG_VERSION"),
315                "project": state.dir.file_name().and_then(|name| name.to_str()).unwrap_or(""),
316            })
317            .to_string();
318            let _ = respond(
319                &mut stream,
320                200,
321                "application/json",
322                body.as_bytes(),
323                origin,
324                &[],
325            );
326        }
327        "/ws" => {
328            if !authorized {
329                let _ = respond(
330                    &mut stream,
331                    403,
332                    "text/plain",
333                    b"the pairing code does not match",
334                    origin,
335                    &[],
336                );
337                return;
338            }
339            let Some(key) = request.headers.get("sec-websocket-key") else {
340                let _ = respond(
341                    &mut stream,
342                    400,
343                    "text/plain",
344                    b"not a websocket handshake",
345                    origin,
346                    &[],
347                );
348                return;
349            };
350            let accept = base64(&sha1(format!("{key}{GUID}").as_bytes()));
351            let _ = write!(
352                stream,
353                "HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: {accept}\r\n{protocol}\r\n"
354            );
355            run_socket(stream, state);
356        }
357        target if target.starts_with("/artifact/") => {
358            if !authorized {
359                let _ = respond(
360                    &mut stream,
361                    403,
362                    "text/plain",
363                    b"the pairing code does not match",
364                    origin,
365                    &[],
366                );
367                return;
368            }
369            let sha = &target["/artifact/".len()..];
370            match state.artifact(sha) {
371                Some((_, _, bytes)) => {
372                    let _ = respond(
373                        &mut stream,
374                        200,
375                        "application/octet-stream",
376                        &bytes,
377                        origin,
378                        &["Content-Disposition", "attachment"],
379                    );
380                }
381                None => {
382                    let _ = respond(
383                        &mut stream,
384                        404,
385                        "text/plain",
386                        b"no such image",
387                        origin,
388                        &[],
389                    );
390                }
391            }
392        }
393        _ => match &state.assets {
394            Some(root) if request.method == "GET" => {
395                let _ = serve_asset(&mut stream, root, &request.target, origin);
396            }
397            Some(_) => {
398                let _ = respond(
399                    &mut stream,
400                    405,
401                    "text/plain",
402                    b"only GET is served",
403                    origin,
404                    &[],
405                );
406            }
407            None => {
408                let _ = respond(&mut stream, 404, "text/plain", b"not found", origin, &[]);
409            }
410        },
411    }
412}
413
414/// Serve the editor build. A path with no file behind it goes to `index.html`:
415/// the page owns its routes, not the file tree.
416fn serve_asset(
417    stream: &mut TcpStream,
418    root: &Path,
419    target: &str,
420    origin: Option<&str>,
421) -> std::io::Result<()> {
422    let Some(path) = crate::serve::resolve(root, target) else {
423        return respond(
424            stream,
425            403,
426            "text/plain",
427            b"outside the served directory",
428            origin,
429            &[],
430        );
431    };
432    if let Ok(body) = std::fs::read(&path) {
433        return respond(stream, 200, crate::serve::mime(&path), &body, origin, &[]);
434    }
435    match std::fs::read(root.join("index.html")) {
436        Ok(body) => respond(stream, 200, "text/html; charset=utf-8", &body, origin, &[]),
437        Err(_) => respond(stream, 404, "text/plain", b"not found", origin, &[]),
438    }
439}
440
441/// A client that names no Origin (curl, `litz build --push`) is fine. A page
442/// that names one must be on the list, when a list was given.
443fn allowed(origins: &[String], origin: Option<&str>) -> bool {
444    match origin {
445        None => true,
446        Some(origin) => origins.is_empty() || origins.iter().any(|entry| entry == origin),
447    }
448}
449
450/// The code a page offered as `Sec-WebSocket-Protocol: litz, CODE`.
451fn offered_token(header: Option<&str>) -> &str {
452    header
453        .map(|value| {
454            value
455                .split(',')
456                .map(str::trim)
457                .find(|part| *part != "litz")
458                .unwrap_or("")
459        })
460        .unwrap_or("")
461}
462
463struct Request {
464    method: String,
465    target: String,
466    headers: HashMap<String, String>,
467}
468
469/// Read a request head without swallowing the bytes that follow it: the first
470/// WebSocket frame may already be in flight when the handshake is answered.
471fn read_request(stream: &mut TcpStream) -> Result<Request, String> {
472    let mut head = Vec::new();
473    let mut byte = [0u8; 1];
474    while !head.ends_with(b"\r\n\r\n") {
475        match stream.read(&mut byte) {
476            Ok(0) => return Err("connection closed during the request".to_string()),
477            Ok(_) => head.push(byte[0]),
478            Err(e) => return Err(e.to_string()),
479        }
480        if head.len() > 16 * 1024 {
481            return Err("request head too large".to_string());
482        }
483    }
484    let text = String::from_utf8_lossy(&head);
485    let mut lines = text.split("\r\n");
486    let mut first = lines.next().unwrap_or("").split(' ');
487    let method = first.next().unwrap_or("").to_string();
488    let target = first.next().unwrap_or("").to_string();
489    let mut headers = HashMap::new();
490    for line in lines {
491        if line.is_empty() {
492            break;
493        }
494        if let Some((name, value)) = line.split_once(':') {
495            headers.insert(name.trim().to_ascii_lowercase(), value.trim().to_string());
496        }
497    }
498    Ok(Request {
499        method,
500        target,
501        headers,
502    })
503}
504
505fn split_target(target: &str) -> (String, HashMap<String, String>) {
506    let (path, query) = target.split_once('?').unwrap_or((target, ""));
507    let mut values = HashMap::new();
508    for pair in query.split('&') {
509        if let Some((key, value)) = pair.split_once('=') {
510            values.insert(key.to_string(), value.replace("%2D", "-"));
511        }
512    }
513    (path.to_string(), values)
514}
515
516#[allow(clippy::too_many_arguments)]
517fn respond(
518    stream: &mut TcpStream,
519    status: u16,
520    mime: &str,
521    body: &[u8],
522    origin: Option<&str>,
523    extra: &[&str],
524) -> std::io::Result<()> {
525    let reason = match status {
526        200 => "OK",
527        204 => "No Content",
528        400 => "Bad Request",
529        403 => "Forbidden",
530        404 => "Not Found",
531        _ => "Unknown",
532    };
533    let allow_origin = origin.unwrap_or("*");
534    write!(
535        stream,
536        "HTTP/1.1 {status} {reason}\r\nContent-Type: {mime}\r\nContent-Length: {}\r\nConnection: close\r\nCache-Control: no-store\r\nAccess-Control-Allow-Origin: {allow_origin}\r\nAccess-Control-Allow-Methods: GET, POST, OPTIONS\r\nAccess-Control-Allow-Headers: *\r\nAccess-Control-Allow-Private-Network: true\r\nAccess-Control-Expose-Headers: Content-Length\r\nVary: Origin\r\n",
537        body.len()
538    )?;
539    let mut index = 0;
540    while index + 1 < extra.len() {
541        write!(stream, "{}: {}\r\n", extra[index], extra[index + 1])?;
542        index += 2;
543    }
544    write!(stream, "\r\n")?;
545    stream.write_all(body)
546}
547
548// ---------------------------------------------------------------------------
549// WebSocket side
550
551fn run_socket(stream: TcpStream, state: Arc<State>) {
552    let Ok(writer_stream) = stream.try_clone() else {
553        return;
554    };
555    let (out, incoming) = mpsc::channel();
556    std::thread::spawn(move || write_loop(writer_stream, incoming));
557
558    let id = state.next_id.fetch_add(1, Ordering::SeqCst);
559    state.sessions.write().unwrap().push(Session {
560        id,
561        out: out.clone(),
562    });
563
564    let hello = serde_json::json!({
565        "type": "hello",
566        "version": env!("CARGO_PKG_VERSION"),
567        "project": state.dir.file_name().and_then(|name| name.to_str()).unwrap_or(""),
568        "library": library(&state.dir).display().to_string(),
569        "boards": boards(&state.dir),
570    });
571    let _ = out.send(Message::Text(hello.to_string()));
572
573    let mut stream = stream;
574    let mut upload: Option<Upload> = None;
575    while let Ok(frame) = read_frame(&mut stream, true) {
576        match frame.opcode {
577            0x8 => break,
578            0x9 => {
579                let _ = out.send(Message::Pong(frame.payload));
580            }
581            0xA => {}
582            0x2 => {
583                let Some(pending) = upload.take() else {
584                    let _ = out.send(Message::Text(error("an image arrived without a publish")));
585                    continue;
586                };
587                accept_image(&state, id, &out, pending, &frame.payload);
588            }
589            0x1 => {
590                let Ok(message) = serde_json::from_slice::<serde_json::Value>(&frame.payload)
591                else {
592                    let _ = out.send(Message::Text(error("each message is a JSON object")));
593                    continue;
594                };
595                // Only requests that reach the filesystem carry an id: the
596                // page awaits one answer and must not mistake it for another.
597                let id = message.get("id").and_then(|value| value.as_u64());
598                match message.get("type").and_then(|kind| kind.as_str()) {
599                    Some("ping") => {
600                        let _ = out.send(Message::Text(r#"{"type":"pong"}"#.to_string()));
601                    }
602                    Some("projects.list") => reply(
603                        &out,
604                        id,
605                        serde_json::json!({
606                            "type": "projects.listed",
607                            "items": list_projects(&state.dir),
608                        }),
609                    ),
610                    Some("project.read") => {
611                        let name = message.get("name").and_then(|v| v.as_str()).unwrap_or("");
612                        match project_path(&state.dir, name) {
613                            Some(path) => match read_project(&path) {
614                                Ok(body) => reply(
615                                    &out,
616                                    id,
617                                    serde_json::json!({
618                                        "type": "project.text",
619                                        "key": name.trim(),
620                                        "text": body,
621                                    }),
622                                ),
623                                Err(failure) => reply(&out, id, failure_message(&failure)),
624                            },
625                            None => reply(&out, id, failure_message(&bad_name(name))),
626                        }
627                    }
628                    Some("project.write") => {
629                        let name = message.get("name").and_then(|v| v.as_str()).unwrap_or("");
630                        let body = message.get("text").and_then(|v| v.as_str()).unwrap_or("");
631                        match project_path(&state.dir, name) {
632                            Some(path) if body.len() <= MAX_PROJECT => {
633                                match write_project(&path, body) {
634                                    Ok(()) => reply(
635                                        &out,
636                                        id,
637                                        serde_json::json!({
638                                            "type": "project.written",
639                                            "key": name.trim(),
640                                        }),
641                                    ),
642                                    Err(failure) => reply(&out, id, failure_message(&failure)),
643                                }
644                            }
645                            Some(_) => {
646                                reply(&out, id, failure_message("the project is larger than 8 MB"))
647                            }
648                            None => reply(&out, id, failure_message(&bad_name(name))),
649                        }
650                    }
651                    Some("project.remove") => {
652                        let name = message.get("name").and_then(|v| v.as_str()).unwrap_or("");
653                        match project_path(&state.dir, name) {
654                            Some(path) => match std::fs::remove_file(&path) {
655                                Ok(()) => reply(
656                                    &out,
657                                    id,
658                                    serde_json::json!({
659                                        "type": "project.removed",
660                                        "key": name.trim(),
661                                    }),
662                                ),
663                                Err(failure) => reply(
664                                    &out,
665                                    id,
666                                    failure_message(&format!("{}: {failure}", path.display())),
667                                ),
668                            },
669                            None => reply(&out, id, failure_message(&bad_name(name))),
670                        }
671                    }
672                    Some("build") => {
673                        let board = message
674                            .get("board")
675                            .and_then(|value| value.as_str())
676                            .map(str::to_string);
677                        start_build(state.clone(), out.clone(), board);
678                    }
679                    Some("publish") => match Upload::from_message(&message) {
680                        Some(pending) => {
681                            upload = Some(pending);
682                            let _ =
683                                out.send(Message::Text(r#"{"type":"publish.ready"}"#.to_string()));
684                        }
685                        None => {
686                            let _ = out
687                                .send(Message::Text(error("publish needs name, sha256 and size")));
688                        }
689                    },
690                    Some(other) => {
691                        let _ =
692                            out.send(Message::Text(error(&format!("unknown message {other:?}"))));
693                    }
694                    None => {
695                        let _ = out.send(Message::Text(error("a message needs a type")));
696                    }
697                }
698            }
699            _ => {}
700        }
701    }
702
703    state
704        .sessions
705        .write()
706        .unwrap()
707        .retain(|session| session.id != id);
708    let _ = out.send(Message::Close);
709}
710
711fn boards(dir: &Path) -> Vec<String> {
712    litz_engine::config::Config::load_project(dir)
713        .map(|config| config.boards.into_iter().map(|entry| entry.id).collect())
714        .unwrap_or_default()
715}
716
717// ---------------------------------------------------------------------------
718// Project library
719
720fn library(dir: &Path) -> PathBuf {
721    dir.join(LIBRARY)
722}
723
724/// A name is a file stem, never a path: the library is flat, so nothing the
725/// page sends can address a file outside it.
726fn project_name(name: &str) -> Option<&str> {
727    let name = name.trim();
728    let plain = name
729        .chars()
730        .all(|c| !c.is_control() && c != '/' && c != '\\');
731    (!name.is_empty() && name.len() <= 120 && !name.starts_with('.') && plain).then_some(name)
732}
733
734fn bad_name(name: &str) -> String {
735    if name.trim().is_empty() {
736        "a project needs a name".to_string()
737    } else {
738        "a project name cannot contain a path".to_string()
739    }
740}
741
742fn project_path(dir: &Path, name: &str) -> Option<PathBuf> {
743    Some(library(dir).join(format!("{}{PROJECT_SUFFIX}", project_name(name)?)))
744}
745
746fn list_projects(dir: &Path) -> Vec<serde_json::Value> {
747    let mut items = Vec::new();
748    let Ok(entries) = std::fs::read_dir(library(dir)) else {
749        return items;
750    };
751    for entry in entries.flatten() {
752        let path = entry.path();
753        let Some(stem) = path
754            .file_name()
755            .and_then(|name| name.to_str())
756            .and_then(|name| name.strip_suffix(PROJECT_SUFFIX))
757        else {
758            continue;
759        };
760        let Ok(meta) = entry.metadata() else {
761            continue;
762        };
763        if !meta.is_file() {
764            continue;
765        }
766        // Milliseconds since the epoch: the page turns this into a local time,
767        // which the CLI has no business deciding.
768        let modified = meta
769            .modified()
770            .ok()
771            .and_then(|time| time.duration_since(std::time::UNIX_EPOCH).ok())
772            .map(|age| age.as_millis() as u64)
773            .unwrap_or(0);
774        items.push(serde_json::json!({
775            "key": stem,
776            "name": stem,
777            "size": meta.len(),
778            "modified": modified,
779        }));
780    }
781    items.sort_by(|left, right| right["modified"].as_u64().cmp(&left["modified"].as_u64()));
782    items
783}
784
785fn read_project(path: &Path) -> Result<String, String> {
786    let size = std::fs::metadata(path).map_err(|e| format!("{}: {e}", path.display()))?;
787    if size.len() > MAX_PROJECT as u64 {
788        return Err("the project is larger than 8 MB".to_string());
789    }
790    std::fs::read_to_string(path).map_err(|e| format!("{}: {e}", path.display()))
791}
792
793fn write_project(path: &Path, body: &str) -> Result<(), String> {
794    if let Some(parent) = path.parent() {
795        std::fs::create_dir_all(parent).map_err(|e| format!("{}: {e}", parent.display()))?;
796    }
797    // Write beside the target and rename: a crash mid-save keeps the previous
798    // project readable instead of leaving half a file.
799    let staging = path.with_extension("json.tmp");
800    std::fs::write(&staging, body).map_err(|e| format!("{}: {e}", staging.display()))?;
801    std::fs::rename(&staging, path).map_err(|e| format!("{}: {e}", path.display()))
802}
803
804fn error(message: &str) -> String {
805    serde_json::json!({ "type": "error", "message": message }).to_string()
806}
807
808fn failure_message(message: &str) -> serde_json::Value {
809    serde_json::json!({ "type": "error", "message": message })
810}
811
812/// Answer a request the page is waiting on. A message without an id was sent
813/// fire-and-forget, and its answer needs nothing to match against.
814fn reply(out: &mpsc::Sender<Message>, id: Option<u64>, mut value: serde_json::Value) {
815    if let Some(id) = id {
816        value["id"] = serde_json::json!(id);
817    }
818    let _ = out.send(Message::Text(value.to_string()));
819}
820
821struct Upload {
822    board: Option<String>,
823    name: String,
824    sha: String,
825    size: usize,
826}
827
828impl Upload {
829    fn from_message(message: &serde_json::Value) -> Option<Self> {
830        let text = |key: &str| {
831            message
832                .get(key)
833                .and_then(|value| value.as_str())
834                .map(str::to_string)
835        };
836        Some(Self {
837            board: text("board"),
838            name: text("name")?,
839            sha: text("sha256")?,
840            size: message.get("size")?.as_u64()? as usize,
841        })
842    }
843}
844
845fn accept_image(
846    state: &State,
847    id: u64,
848    out: &mpsc::Sender<Message>,
849    pending: Upload,
850    bytes: &[u8],
851) {
852    if bytes.len() != pending.size {
853        let _ = out.send(Message::Text(error(&format!(
854            "expected {} bytes, received {}",
855            pending.size,
856            bytes.len()
857        ))));
858        return;
859    }
860    let sha = hex(&Sha256::digest(bytes));
861    if !same(&sha, &pending.sha) {
862        let _ = out.send(Message::Text(error("the image does not match its sha256")));
863        return;
864    }
865    state.keep(
866        sha.clone(),
867        Artifact {
868            board: pending.board.clone(),
869            name: pending.name.clone(),
870            bytes: Arc::new(bytes.to_vec()),
871        },
872    );
873    // The publisher is answered with `pushed` instead: it asked for an
874    // acknowledgement, not a second copy of what it just sent.
875    broadcast_except(
876        state,
877        Some(id),
878        &artifact_message(pending.board.as_deref(), &pending.name, &sha, bytes.len()),
879    );
880    let _ = out.send(Message::Text(
881        serde_json::json!({ "type": "pushed", "sha256": sha }).to_string(),
882    ));
883}
884
885fn start_build(state: Arc<State>, out: mpsc::Sender<Message>, board: Option<String>) {
886    if state.building.swap(true, Ordering::SeqCst) {
887        let _ = out.send(Message::Text(error("a build is already running")));
888        return;
889    }
890    std::thread::spawn(move || {
891        let started = serde_json::json!({ "type": "build.started", "board": board }).to_string();
892        broadcast(&state, &started);
893        let outcome = run_build(&state, &out, board.as_deref());
894        if let Err(message) = outcome {
895            broadcast(
896                &state,
897                &serde_json::json!({ "type": "build.failed", "message": message }).to_string(),
898            );
899        }
900        state.building.store(false, Ordering::SeqCst);
901    });
902}
903
904fn run_build(
905    state: &State,
906    out: &mpsc::Sender<Message>,
907    board: Option<&str>,
908) -> Result<(), String> {
909    let mut emit = |chunk: &str| {
910        let message = serde_json::json!({ "type": "log", "chunk": chunk }).to_string();
911        let _ = out.send(Message::Text(message));
912    };
913    build::run_with(&state.dir, false, &mut emit)?;
914    let (name, path) = build::image_for(&state.dir, board)?;
915    let bytes = std::fs::read(&path).map_err(|e| format!("{}: {e}", path.display()))?;
916    let size = bytes.len();
917    let sha = hex(&Sha256::digest(&bytes));
918    let file = path
919        .file_name()
920        .map(|name| name.to_string_lossy().into_owned())
921        .unwrap_or_else(|| "firmware.bin".to_string());
922    state.keep(
923        sha.clone(),
924        Artifact {
925            board: name.clone(),
926            name: file.clone(),
927            bytes: Arc::new(bytes),
928        },
929    );
930    broadcast(state, &artifact_message(name.as_deref(), &file, &sha, size));
931    Ok(())
932}
933
934fn artifact_message(board: Option<&str>, name: &str, sha: &str, size: usize) -> String {
935    serde_json::json!({
936        "type": "artifact",
937        "board": board,
938        "name": name,
939        "sha256": sha,
940        "size": size,
941        "url": format!("/artifact/{sha}"),
942    })
943    .to_string()
944}
945
946fn broadcast(state: &State, message: &str) {
947    broadcast_except(state, None, message);
948}
949
950fn broadcast_except(state: &State, skip: Option<u64>, message: &str) {
951    let sessions = state.sessions.read().unwrap();
952    for session in sessions.iter() {
953        if Some(session.id) == skip {
954            continue;
955        }
956        let _ = session.out.send(Message::Text(message.to_string()));
957    }
958}
959
960fn write_loop(mut stream: TcpStream, incoming: mpsc::Receiver<Message>) {
961    while let Ok(message) = incoming.recv() {
962        let written = match message {
963            Message::Text(text) => write_frame(&mut stream, 0x1, text.as_bytes(), false),
964            Message::Pong(payload) => write_frame(&mut stream, 0xA, &payload, false),
965            Message::Close => {
966                let _ = write_frame(&mut stream, 0x8, &[], false);
967                return;
968            }
969        };
970        if written.is_err() {
971            return;
972        }
973    }
974}
975
976struct Frame {
977    opcode: u8,
978    payload: Vec<u8>,
979}
980
981fn read_frame(stream: &mut TcpStream, from_client: bool) -> Result<Frame, String> {
982    let mut header = [0u8; 2];
983    read_exact(stream, &mut header)?;
984    let opcode = header[0] & 0x0f;
985    let masked = header[1] & 0x80 != 0;
986    let mut length = (header[1] & 0x7f) as u64;
987    if length == 126 {
988        let mut extended = [0u8; 2];
989        read_exact(stream, &mut extended)?;
990        length = u16::from_be_bytes(extended) as u64;
991    } else if length == 127 {
992        let mut extended = [0u8; 8];
993        read_exact(stream, &mut extended)?;
994        length = u64::from_be_bytes(extended);
995    }
996    if length as usize > MAX_FRAME {
997        return Err("frame too large".to_string());
998    }
999    if from_client && !masked {
1000        // RFC 6455: every client frame is masked. Refusing the shape as well
1001        // as the token keeps a stray local sender from writing bytes verbatim.
1002        return Err("a client frame must be masked".to_string());
1003    }
1004    let mut payload = vec![0u8; length as usize];
1005    if masked {
1006        let mut mask = [0u8; 4];
1007        read_exact(stream, &mut mask)?;
1008        read_exact(stream, &mut payload)?;
1009        for (index, byte) in payload.iter_mut().enumerate() {
1010            *byte ^= mask[index % 4];
1011        }
1012    } else {
1013        read_exact(stream, &mut payload)?;
1014    }
1015    Ok(Frame { opcode, payload })
1016}
1017
1018fn write_frame(
1019    stream: &mut TcpStream,
1020    opcode: u8,
1021    payload: &[u8],
1022    mask: bool,
1023) -> Result<(), String> {
1024    let mut head = Vec::with_capacity(14);
1025    head.push(0x80 | opcode);
1026    let mask_bit = if mask { 0x80u8 } else { 0 };
1027    if payload.len() < 126 {
1028        head.push(mask_bit | payload.len() as u8);
1029    } else if payload.len() <= u16::MAX as usize {
1030        head.push(mask_bit | 126);
1031        head.extend_from_slice(&(payload.len() as u16).to_be_bytes());
1032    } else {
1033        head.push(mask_bit | 127);
1034        head.extend_from_slice(&(payload.len() as u64).to_be_bytes());
1035    }
1036    if mask {
1037        let key = mask_key();
1038        head.extend_from_slice(&key);
1039        let mut body = payload.to_vec();
1040        for (index, byte) in body.iter_mut().enumerate() {
1041            *byte ^= key[index % 4];
1042        }
1043        stream.write_all(&head).map_err(|e| e.to_string())?;
1044        stream.write_all(&body).map_err(|e| e.to_string())?;
1045    } else {
1046        stream.write_all(&head).map_err(|e| e.to_string())?;
1047        stream.write_all(payload).map_err(|e| e.to_string())?;
1048    }
1049    stream.flush().map_err(|e| e.to_string())
1050}
1051
1052fn read_exact(stream: &mut TcpStream, buffer: &mut [u8]) -> Result<(), String> {
1053    let mut filled = 0;
1054    while filled < buffer.len() {
1055        match stream.read(&mut buffer[filled..]) {
1056            Ok(0) => return Err("connection closed".to_string()),
1057            Ok(n) => filled += n,
1058            Err(e) => return Err(e.to_string()),
1059        }
1060    }
1061    Ok(())
1062}
1063
1064fn read_text(stream: &mut TcpStream, from_client: bool) -> Result<serde_json::Value, String> {
1065    let frame = read_frame(stream, from_client)?;
1066    if frame.opcode != 0x1 {
1067        return Err(format!(
1068            "expected a text frame, received opcode {}",
1069            frame.opcode
1070        ));
1071    }
1072    serde_json::from_slice(&frame.payload).map_err(|e| e.to_string())
1073}
1074
1075fn client_handshake(stream: &mut TcpStream, port: u16, token: &str) -> Result<(), String> {
1076    let key = base64(&entropy_bytes(16));
1077    write!(
1078        stream,
1079        "GET /ws?token={token} HTTP/1.1\r\nHost: 127.0.0.1:{port}\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Key: {key}\r\nSec-WebSocket-Version: 13\r\n\r\n"
1080    )
1081    .map_err(|e| e.to_string())?;
1082    let mut head = Vec::new();
1083    let mut byte = [0u8; 1];
1084    while !head.ends_with(b"\r\n\r\n") {
1085        match stream.read(&mut byte) {
1086            Ok(0) => return Err("the link closed during the handshake".to_string()),
1087            Ok(_) => head.push(byte[0]),
1088            Err(e) => return Err(e.to_string()),
1089        }
1090        if head.len() > 16 * 1024 {
1091            return Err("handshake head too large".to_string());
1092        }
1093    }
1094    let text = String::from_utf8_lossy(&head);
1095    let status = text.lines().next().unwrap_or("");
1096    if !status.contains(" 101 ") {
1097        return Err(format!("the link refused the handshake: {status}"));
1098    }
1099    // Drive the first server frame (hello) out of the way.
1100    let hello = read_text(stream, false)?;
1101    if hello.get("type").and_then(|kind| kind.as_str()) != Some("hello") {
1102        return Err(format!("the link did not greet: {hello}"));
1103    }
1104    Ok(())
1105}
1106
1107// ---------------------------------------------------------------------------
1108// The project's lock file: how `build --push` finds a running link.
1109
1110fn write_lock(dir: &Path, port: u16, token: &str) -> Result<(), String> {
1111    let path = dir.join(LOCK_FILE);
1112    if let Some(parent) = path.parent() {
1113        std::fs::create_dir_all(parent).map_err(|e| format!("{}: {e}", parent.display()))?;
1114    }
1115    let body = serde_json::json!({ "port": port, "token": token }).to_string();
1116    std::fs::write(&path, body).map_err(|e| format!("{}: {e}", path.display()))?;
1117    #[cfg(unix)]
1118    {
1119        use std::os::unix::fs::PermissionsExt;
1120        let _ = std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600));
1121    }
1122    Ok(())
1123}
1124
1125fn read_lock(dir: &Path) -> Result<(u16, String), String> {
1126    let path = dir.join(LOCK_FILE);
1127    let text = std::fs::read_to_string(&path).map_err(|_| {
1128        format!(
1129            "no editor link is running here; start `litz connect-editor` first ({} missing)",
1130            path.display()
1131        )
1132    })?;
1133    let value: serde_json::Value =
1134        serde_json::from_str(&text).map_err(|e| format!("{}: {e}", path.display()))?;
1135    let port = value
1136        .get("port")
1137        .and_then(|port| port.as_u64())
1138        .ok_or_else(|| format!("{}: no port", path.display()))?;
1139    let token = value
1140        .get("token")
1141        .and_then(|token| token.as_str())
1142        .ok_or_else(|| format!("{}: no token", path.display()))?;
1143    Ok((port as u16, token.to_string()))
1144}
1145
1146// ---------------------------------------------------------------------------
1147// Small primitives, kept here so the link adds no dependency.
1148
1149fn token() -> String {
1150    let mut text = String::new();
1151    for salt in 0..4u8 {
1152        if salt > 0 {
1153            text.push('-');
1154        }
1155        text.push_str(&format!("{:04X}", (entropy(salt) & 0xFFFF) as u16));
1156    }
1157    text
1158}
1159
1160/// A value seeded from the OS through `RandomState`, mixed with the clock and
1161/// the process id. `RandomState`'s keys come from the platform's entropy, and
1162/// the salt keeps the four groups of a token from being slices of one value.
1163fn entropy(salt: u8) -> u64 {
1164    use std::hash::{BuildHasher, Hasher};
1165    let mut hasher = std::collections::hash_map::RandomState::new().build_hasher();
1166    hasher.write_u8(salt);
1167    hasher.write_u32(std::process::id());
1168    hasher.write_u128(
1169        std::time::SystemTime::now()
1170            .duration_since(std::time::UNIX_EPOCH)
1171            .map(|elapsed| elapsed.as_nanos())
1172            .unwrap_or(0),
1173    );
1174    hasher.finish()
1175}
1176
1177fn entropy_bytes(length: usize) -> Vec<u8> {
1178    let mut bytes = Vec::with_capacity(length);
1179    while bytes.len() < length {
1180        bytes.extend_from_slice(&entropy(bytes.len() as u8).to_be_bytes());
1181    }
1182    bytes.truncate(length);
1183    bytes
1184}
1185
1186fn mask_key() -> [u8; 4] {
1187    let value = entropy(0xFF).to_be_bytes();
1188    [value[0], value[1], value[2], value[3]]
1189}
1190
1191fn same(left: &str, right: &str) -> bool {
1192    if left.len() != right.len() {
1193        return false;
1194    }
1195    left.bytes()
1196        .zip(right.bytes())
1197        .fold(0u8, |acc, (a, b)| acc | (a ^ b))
1198        == 0
1199}
1200
1201fn hex(bytes: &[u8]) -> String {
1202    let mut text = String::with_capacity(bytes.len() * 2);
1203    for byte in bytes {
1204        text.push_str(&format!("{byte:02x}"));
1205    }
1206    text
1207}
1208
1209fn sha1(data: &[u8]) -> [u8; 20] {
1210    let mut state: [u32; 5] = [0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476, 0xC3D2E1F0];
1211    let mut message = data.to_vec();
1212    let bits = (message.len() as u64) * 8;
1213    message.push(0x80);
1214    while message.len() % 64 != 56 {
1215        message.push(0);
1216    }
1217    message.extend_from_slice(&bits.to_be_bytes());
1218
1219    for block in message.as_chunks::<64>().0 {
1220        let mut words = [0u32; 80];
1221        for (index, word) in block.as_chunks::<4>().0.iter().enumerate() {
1222            words[index] = u32::from_be_bytes(*word);
1223        }
1224        for index in 16..80 {
1225            words[index] =
1226                (words[index - 3] ^ words[index - 8] ^ words[index - 14] ^ words[index - 16])
1227                    .rotate_left(1);
1228        }
1229        let (mut a, mut b, mut c, mut d, mut e) =
1230            (state[0], state[1], state[2], state[3], state[4]);
1231        for (index, word) in words.iter().enumerate() {
1232            let (function, constant) = match index {
1233                0..=19 => ((b & c) | (!b & d), 0x5A827999u32),
1234                20..=39 => (b ^ c ^ d, 0x6ED9EBA1),
1235                40..=59 => ((b & c) | (b & d) | (c & d), 0x8F1BBCDC),
1236                _ => (b ^ c ^ d, 0xCA62C1D6),
1237            };
1238            let temp = a
1239                .rotate_left(5)
1240                .wrapping_add(function)
1241                .wrapping_add(e)
1242                .wrapping_add(constant)
1243                .wrapping_add(*word);
1244            e = d;
1245            d = c;
1246            c = b.rotate_left(30);
1247            b = a;
1248            a = temp;
1249        }
1250        state[0] = state[0].wrapping_add(a);
1251        state[1] = state[1].wrapping_add(b);
1252        state[2] = state[2].wrapping_add(c);
1253        state[3] = state[3].wrapping_add(d);
1254        state[4] = state[4].wrapping_add(e);
1255    }
1256
1257    let mut digest = [0u8; 20];
1258    for (index, word) in state.iter().enumerate() {
1259        digest[index * 4..index * 4 + 4].copy_from_slice(&word.to_be_bytes());
1260    }
1261    digest
1262}
1263
1264fn base64(data: &[u8]) -> String {
1265    const ALPHABET: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
1266    let mut text = String::with_capacity(data.len().div_ceil(3) * 4);
1267    for chunk in data.chunks(3) {
1268        let a = chunk[0];
1269        let b = chunk.get(1).copied().unwrap_or(0);
1270        let c = chunk.get(2).copied().unwrap_or(0);
1271        text.push(ALPHABET[(a >> 2) as usize] as char);
1272        text.push(ALPHABET[(((a & 0x03) << 4) | (b >> 4)) as usize] as char);
1273        if chunk.len() > 1 {
1274            text.push(ALPHABET[(((b & 0x0F) << 2) | (c >> 6)) as usize] as char);
1275        } else {
1276            text.push('=');
1277        }
1278        if chunk.len() > 2 {
1279            text.push(ALPHABET[(c & 0x3F) as usize] as char);
1280        } else {
1281            text.push('=');
1282        }
1283    }
1284    text
1285}
1286
1287#[cfg(test)]
1288mod tests {
1289    use super::*;
1290    use std::time::Instant;
1291
1292    fn scratch(tag: &str) -> PathBuf {
1293        static NEXT: AtomicU64 = AtomicU64::new(0);
1294        let n = NEXT.fetch_add(1, Ordering::Relaxed);
1295        let dir = std::env::temp_dir().join(format!("litz-link-{}-{n}-{tag}", std::process::id()));
1296        let _ = std::fs::remove_dir_all(&dir);
1297        std::fs::create_dir_all(&dir).unwrap();
1298        dir
1299    }
1300
1301    #[test]
1302    fn sha1_matches_the_rfc_vectors() {
1303        assert_eq!(
1304            hex(&sha1(b"abc")),
1305            "a9993e364706816aba3e25717850c26c9cd0d89d"
1306        );
1307        assert_eq!(
1308            hex(&sha1(b"The quick brown fox jumps over the lazy dog")),
1309            "2fd4e1c67a2d28fced849ee1bb76e7391b93eb12"
1310        );
1311    }
1312
1313    #[test]
1314    fn the_accept_key_matches_the_rfc_example() {
1315        let accept = base64(&sha1(
1316            b"dGhlIHNhbXBsZSBub25jZQ==258EAFA5-E914-47DA-95CA-C5AB0DC85B11",
1317        ));
1318        assert_eq!(accept, "s3pPLMBiTxaQ9kYGzzhZRbK+xOo=");
1319    }
1320
1321    #[test]
1322    fn a_token_is_four_groups_of_hex() {
1323        let first = token();
1324        assert_eq!(first.len(), 19, "{first}");
1325        let groups: Vec<&str> = first.split('-').collect();
1326        assert_eq!(groups.len(), 4);
1327        for group in groups {
1328            assert_eq!(group.len(), 4);
1329            assert!(group.chars().all(|c| c.is_ascii_hexdigit()), "{first}");
1330        }
1331        assert_ne!(first, token());
1332    }
1333
1334    #[test]
1335    fn frames_round_trip_a_masked_client_frame() {
1336        let dir = scratch("frames");
1337        let listener = TcpListener::bind(("127.0.0.1", 0)).unwrap();
1338        let port = listener.local_addr().unwrap().port();
1339        let handle = std::thread::spawn(move || {
1340            let (mut server, _) = listener.accept().unwrap();
1341            read_frame(&mut server, true).unwrap()
1342        });
1343        let mut client = TcpStream::connect(("127.0.0.1", port)).unwrap();
1344        write_frame(&mut client, 0x1, b"{\"type\":\"ping\"}", true).unwrap();
1345        let frame = handle.join().unwrap();
1346        assert_eq!(frame.opcode, 0x1);
1347        assert_eq!(frame.payload, b"{\"type\":\"ping\"}");
1348        let _ = std::fs::remove_dir_all(&dir);
1349    }
1350
1351    #[test]
1352    fn a_lock_file_round_trips() {
1353        let dir = scratch("lock");
1354        write_lock(&dir, 4317, "ABCD-EF01-2345-6789").unwrap();
1355        let (port, token) = read_lock(&dir).unwrap();
1356        assert_eq!(port, 4317);
1357        assert_eq!(token, "ABCD-EF01-2345-6789");
1358        let _ = std::fs::remove_dir_all(&dir);
1359    }
1360
1361    #[test]
1362    fn a_build_streams_output_and_publishes_the_image() {
1363        let dir = scratch("build");
1364        std::fs::write(
1365            dir.join("litz.build.toml"),
1366            "[build]\nfirmware = \"out/app.bin\"\n\n[[step]]\nrun = \"mkdir -p out && printf hello > out/app.bin\"\n",
1367        )
1368        .unwrap();
1369
1370        let options = Options {
1371            directory: dir.clone(),
1372            port: 0,
1373            host: "127.0.0.1".into(),
1374            origins: Vec::new(),
1375            assets: None,
1376        };
1377        let (listener, token) = listen(&options).unwrap();
1378        let port = listener.local_addr().unwrap().port();
1379        let state = Arc::new(state(&options, token.clone()));
1380        let running = state.clone();
1381        std::thread::spawn(move || accept_loop(listener, running));
1382
1383        let mut stream = TcpStream::connect(("127.0.0.1", port)).unwrap();
1384        stream
1385            .set_read_timeout(Some(Duration::from_secs(20)))
1386            .unwrap();
1387        client_handshake(&mut stream, port, &token).unwrap();
1388        write_frame(&mut stream, 0x1, br#"{"type":"build"}"#, true).unwrap();
1389
1390        let mut artifact = None;
1391        let started = Instant::now();
1392        while started.elapsed() < Duration::from_secs(20) {
1393            let message = read_text(&mut stream, false).unwrap();
1394            match message.get("type").and_then(|kind| kind.as_str()) {
1395                Some("artifact") => {
1396                    artifact = Some(message);
1397                    break;
1398                }
1399                Some("build.failed") => panic!("build failed: {message}"),
1400                _ => {}
1401            }
1402        }
1403        let artifact = artifact.expect("the build published no image");
1404        let sha = artifact
1405            .get("sha256")
1406            .and_then(|value| value.as_str())
1407            .unwrap();
1408        assert_eq!(artifact["size"], 5);
1409        let (_, _, bytes) = state.artifact(sha).expect("the image is kept");
1410        assert_eq!(&bytes[..], b"hello");
1411        let _ = std::fs::remove_dir_all(&dir);
1412    }
1413
1414    #[test]
1415    fn the_library_keeps_one_file_per_project() {
1416        let dir = scratch("library");
1417        let path = project_path(&dir, " Blinky ").unwrap();
1418        assert_eq!(
1419            path,
1420            dir.join(".litz")
1421                .join("projects")
1422                .join("Blinky.litzproject.json")
1423        );
1424        let body = r#"{"format":"litz-project"}"#;
1425        write_project(&path, body).unwrap();
1426        assert_eq!(read_project(&path).unwrap(), body);
1427        // The staging file is renamed away, so a save leaves one file.
1428        assert!(!path.with_extension("json.tmp").exists());
1429
1430        let items = list_projects(&dir);
1431        assert_eq!(items.len(), 1);
1432        assert_eq!(items[0]["key"], "Blinky");
1433        assert_eq!(items[0]["size"].as_u64(), Some(body.len() as u64));
1434        assert!(items[0]["modified"].as_u64().unwrap() > 0);
1435
1436        std::fs::write(dir.join(".litz/projects/notes.txt"), "kept").unwrap();
1437        assert_eq!(
1438            list_projects(&dir).len(),
1439            1,
1440            "only project files are listed"
1441        );
1442
1443        std::fs::remove_file(&path).unwrap();
1444        assert!(list_projects(&dir).is_empty());
1445        let _ = std::fs::remove_dir_all(&dir);
1446    }
1447
1448    #[test]
1449    fn a_project_name_cannot_address_another_directory() {
1450        for name in ["", "  ", "../escape", "a/b", "a\\b", ".hidden", "x\ny"] {
1451            assert!(
1452                project_path(Path::new("."), name).is_none(),
1453                "{name:?} was accepted"
1454            );
1455        }
1456        assert!(project_name(&"long".repeat(31)).is_none());
1457        assert_eq!(project_name("Blinky 1"), Some("Blinky 1"));
1458    }
1459
1460    #[test]
1461    fn the_code_can_arrive_in_a_header_instead_of_the_query() {
1462        let dir = scratch("header-token");
1463        let (port, token) = start(Options {
1464            directory: dir.clone(),
1465            port: 0,
1466            host: "127.0.0.1".into(),
1467            origins: Vec::new(),
1468            assets: None,
1469        });
1470        assert!(request(port, "/artifact/none", &[]).contains(" 403 "));
1471        let bearer = format!("Bearer {token}");
1472        assert!(
1473            request(port, "/artifact/none", &[("Authorization", &bearer)]).contains(" 404 "),
1474            "a header-carried code is the same credential"
1475        );
1476        assert!(
1477            request(
1478                port,
1479                "/artifact/none",
1480                &[("Authorization", "Bearer 0000-0000-0000-0000")]
1481            )
1482            .contains(" 403 ")
1483        );
1484        let _ = std::fs::remove_dir_all(&dir);
1485    }
1486
1487    #[test]
1488    fn an_origin_list_keeps_other_pages_out() {
1489        let dir = scratch("origins");
1490        let (port, _) = start(Options {
1491            directory: dir.clone(),
1492            port: 0,
1493            host: "127.0.0.1".into(),
1494            origins: vec!["https://litz.example.com".into()],
1495            assets: None,
1496        });
1497        assert!(
1498            request(port, "/health", &[("Origin", "https://elsewhere.example")]).contains(" 403 ")
1499        );
1500        assert!(
1501            request(port, "/health", &[("Origin", "https://litz.example.com")]).contains(" 200 ")
1502        );
1503        // A client with no Origin is still welcome: curl and `--push` have none.
1504        assert!(request(port, "/health", &[]).contains(" 200 "));
1505        let _ = std::fs::remove_dir_all(&dir);
1506    }
1507
1508    #[test]
1509    fn the_editor_build_is_served_beside_the_link() {
1510        let dir = scratch("assets");
1511        let assets = dir.join("site");
1512        std::fs::create_dir_all(&assets).unwrap();
1513        std::fs::write(assets.join("index.html"), "<!doctype html>").unwrap();
1514        std::fs::write(assets.join("app.js"), "export {}").unwrap();
1515        let (port, _) = start(Options {
1516            directory: dir.clone(),
1517            port: 0,
1518            host: "127.0.0.1".into(),
1519            origins: Vec::new(),
1520            assets: Some(assets),
1521        });
1522        assert!(request(port, "/", &[]).contains(" 200 "));
1523        assert!(request(port, "/app.js", &[]).contains(" 200 "));
1524        // A client route has no file behind it; the page answers it.
1525        assert!(request(port, "/editor", &[]).contains(" 200 "));
1526        assert!(request(port, "/../Cargo.toml", &[]).contains(" 403 "));
1527        let _ = std::fs::remove_dir_all(&dir);
1528    }
1529
1530    /// Run a link on a system-chosen port and hand back what it bound.
1531    fn start(options: Options) -> (u16, String) {
1532        let dir = options.directory.clone();
1533        std::thread::spawn(move || {
1534            let _ = serve(&options);
1535        });
1536        let started = Instant::now();
1537        while started.elapsed() < Duration::from_secs(5) {
1538            if let Ok((port, token)) = read_lock(&dir)
1539                && TcpStream::connect(("127.0.0.1", port)).is_ok()
1540            {
1541                return (port, token);
1542            }
1543            std::thread::sleep(Duration::from_millis(20));
1544        }
1545        panic!("the link did not claim its lock file");
1546    }
1547
1548    fn request(port: u16, target: &str, headers: &[(&str, &str)]) -> String {
1549        let mut stream = TcpStream::connect(("127.0.0.1", port)).unwrap();
1550        let mut head =
1551            format!("GET {target} HTTP/1.1\r\nHost: 127.0.0.1:{port}\r\nConnection: close\r\n");
1552        for (name, value) in headers {
1553            head.push_str(&format!("{name}: {value}\r\n"));
1554        }
1555        head.push_str("\r\n");
1556        stream.write_all(head.as_bytes()).unwrap();
1557        let mut body = String::new();
1558        stream.read_to_string(&mut body).unwrap();
1559        body.lines().next().unwrap_or("").to_string()
1560    }
1561}