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