@@ -0,0 +1,115 @@
1+//! Dev notes: with `devnotes.js` loaded in a project's app in dev mode, Ctrl+click any element
2+//! and say what you want; it becomes a ticket in that project, as Ctrl+click does in conveyor.
3+//! A tiny HTTP server on loopback serves the script and takes the notes. Only pages on
4+//! localhost may post, since a ticket runs an agent that holds the user's keys.
5+use crate::{library, store};
6+use serde_json::{Value, json};
7+use std::{io::{BufRead, BufReader, Read, Write}, net::{TcpListener, TcpStream}, time::Duration};
8+
9+pub const PORT: u16 = 7717;
10+const SCRIPT: &str = include_str!("devnotes.js");
11+const SEED: &str = include_str!("devnotes.md");
12+
13+pub fn serve() {
14+ let srv = match TcpListener::bind(("127.0.0.1", PORT)) {
15+ Ok(s) => s,
16+ Err(e) => return eprintln!("dev notes: can't listen on 127.0.0.1:{PORT}: {e}"),
17+ };
18+ for c in srv.incoming().flatten() {
19+ std::thread::spawn(move || { let _ = session(c); });
20+ }
21+}
22+
23+/// The draft a new project starts with: load the script in its app's dev build.
24+pub fn seed(slug: &str) {
25+ let body = SEED.replace("{slug}", slug).replace("{port}", &PORT.to_string());
26+ store::create(slug, "Dev notes: Ctrl+click the running app to file tickets", &body, "draft");
27+}
28+
29+fn session(mut c: TcpStream) -> std::io::Result<()> {
30+ c.set_read_timeout(Some(Duration::from_secs(5)))?;
31+ let mut r = BufReader::new(c.try_clone()?);
32+ let mut line = String::new();
33+ r.read_line(&mut line)?;
34+ let mut words = line.split_whitespace();
35+ let (method, path) = (words.next().unwrap_or("").to_owned(), words.next().unwrap_or("").to_owned());
36+ let (mut host, mut origin, mut len) = (String::new(), None, 0usize);
37+ loop {
38+ let mut h = String::new();
39+ if r.read_line(&mut h)? == 0 || h.trim_end().is_empty() { break; }
40+ let Some((k, v)) = h.trim_end().split_once(':') else { continue };
41+ match k.to_ascii_lowercase().as_str() {
42+ "host" => host = v.trim().into(),
43+ "origin" => origin = Some(v.trim().to_owned()),
44+ "content-length" => len = v.trim().parse().unwrap_or(0),
45+ _ => {}
46+ }
47+ }
48+ // A loopback Host stops DNS rebinding; a localhost Origin stops any other site posting.
49+ if !local_host(&host) { return reply(&mut c, "421 Misdirected Request", "text/plain", None, "not a loopback host"); }
50+ if origin.as_deref().is_some_and(|o| !local_origin(o)) {
51+ return reply(&mut c, "403 Forbidden", "text/plain", None, "only pages on localhost can file dev notes");
52+ }
53+ let o = origin.as_deref();
54+ match (method.as_str(), path.split('?').next().unwrap_or("")) {
55+ ("GET", "/devnotes.js") => reply(&mut c, "200 OK", "text/javascript", o, SCRIPT),
56+ ("OPTIONS", "/note") => reply(&mut c, "204 No Content", "text/plain", o, ""),
57+ ("POST", "/note") if len <= 64 << 10 => {
58+ let mut body = vec![0; len];
59+ r.read_exact(&mut body)?;
60+ let res = note(&serde_json::from_slice(&body).unwrap_or(Value::Null)).unwrap_or_else(|e| json!({"error": e}));
61+ reply(&mut c, "200 OK", "application/json", o, &res.to_string())
62+ }
63+ _ => reply(&mut c, "404 Not Found", "text/plain", o, "not found"),
64+ }
65+}
66+
67+fn reply(c: &mut TcpStream, status: &str, kind: &str, origin: Option<&str>, body: &str) -> std::io::Result<()> {
68+ let cors = origin.map_or(String::new(), |o| format!(
69+ "Access-Control-Allow-Origin: {o}\r\nAccess-Control-Allow-Methods: POST\r\nAccess-Control-Allow-Headers: content-type\r\n\
70+ Access-Control-Allow-Private-Network: true\r\nVary: Origin\r\n"));
71+ write!(c, "HTTP/1.1 {status}\r\nContent-Type: {kind}; charset=utf-8\r\nContent-Length: {}\r\n{cors}Connection: close\r\n\r\n{body}", body.len())
72+}
73+
74+/// A note from a page: a ticket in its project, ready or draft, with what was clicked below `---`.
75+fn note(v: &Value) -> Result<Value, String> {
76+ let s = |k: &str, max: usize| v[k].as_str().unwrap_or("").trim().chars().take(max).collect::<String>();
77+ let (project, words) = (s("project", 64), s("note", 8000));
78+ let p = store::project(&project).filter(|p| !p.library).ok_or(format!("no project `{project}` in conveyor: check the script tag's data-project"))?;
79+ if words.is_empty() { return Err("the note is empty".into()); }
80+ let context = format!(
81+ "The user clicked their running app, in dev mode, and wrote the words above about what they clicked.\n\n\
82+ - Page: {}\n- Element: `{}`, at ({}) inside it\n- Its text: \"{}\"\n- Window: {}\n\n\
83+ To see it, run the app's dev server and open that page, with the window at that size. The port in your VM may differ.",
84+ s("url", 2000), s("selector", 500), s("point", 40), s("text", 200), s("viewport", 40));
85+ let state = if v["ready"] == true { "ready" } else { "draft" };
86+ let id = store::create(&p.slug, &library::title(&words), &format!("{words}\n\n---\n\n{context}"), state);
87+ Ok(json!({"id": id, "state": state}))
88+}
89+
90+/// `127.0.0.1:7717`, `localhost:7717`, `[::1]:7717`.
91+fn local_host(h: &str) -> bool {
92+ let name = h.rsplit_once(':').filter(|(_, port)| port.parse::<u16>().is_ok()).map_or(h, |(n, _)| n);
93+ ["127.0.0.1", "localhost", "[::1]"].contains(&name)
94+}
95+
96+/// A page served from this machine by name: `http://localhost:8080`, `https://app.localhost`.
97+fn local_origin(o: &str) -> bool {
98+ let Some(rest) = o.strip_prefix("http://").or(o.strip_prefix("https://")) else { return false };
99+ let name = rest.rsplit_once(':').filter(|(_, port)| port.parse::<u16>().is_ok()).map_or(rest, |(n, _)| n);
100+ ["127.0.0.1", "localhost", "[::1]"].contains(&name) || name.ends_with(".localhost")
101+}
102+
103+#[cfg(test)]
104+mod tests {
105+ use super::*;
106+
107+ #[test]
108+ fn guards() {
109+ assert!(local_host("127.0.0.1:7717") && local_host("localhost:7717") && local_host("[::1]:7717"));
110+ assert!(!local_host("evil.com:7717") && !local_host("127.0.0.1.evil.com") && !local_host(""));
111+ assert!(local_origin("http://localhost:8080") && local_origin("http://127.0.0.1") && local_origin("https://game.localhost:3000"));
112+ assert!(!local_origin("https://evil.com") && !local_origin("null") && !local_origin("http://localhost.evil.com")
113+ && !local_origin("http://evil.localhost.com") && !local_origin("file://"));
114+ }
115+}