unifier-cli 0.4.0

Filesystem postbox for inter-process communication via a Unix tree
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
//! Temp static file store + minimal localhost HTTP server.
//!
//! Jan (and other tools) pipe HTML into `unifier serve`; the daemon serves it
//! from `.daemon/www/` on `127.0.0.1` so reports open in a browser without a
//! separate static-file stack.
//!
//! Layout:
//! ```text
//! .daemon/www/<name>           — raw body bytes
//! .daemon/www/<name>.meta.json — { content_type, created_at, expires_at? }
//! .daemon/http.port            — bound TCP port
//! ```

use std::fs;
use std::io::{Read, Write};
use std::net::{SocketAddr, TcpListener, TcpStream};
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use std::thread;
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};

use serde::{Deserialize, Serialize};

use crate::daemon::paths::{http_port_path, www_dir};
use crate::error::{Error, Result};
use crate::home::UnifierHome;
use crate::scope::resolve_under_root;

const DEFAULT_CONTENT_TYPE: &str = "text/html; charset=utf-8";
const DEFAULT_PORT_ENV: &str = "UNIFIER_HTTP_PORT";
/// Prefer a stable localhost port when free; fall back to ephemeral.
const PREFERRED_PORT: u16 = 17355;

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WwwMeta {
    pub name: String,
    pub content_type: String,
    pub created_at: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub expires_at: Option<String>,
    pub bytes: u64,
}

/// Validate a publish name: no slashes, no `..`, printable path segment.
pub fn validate_name(name: &str) -> Result<()> {
    if name.is_empty() {
        return Err(Error::msg("web name must not be empty"));
    }
    if name.contains('/') || name.contains('\\') || name.contains('\0') {
        return Err(Error::msg("web name must not contain path separators"));
    }
    if name == "." || name == ".." || name.ends_with(".meta.json") {
        return Err(Error::msg(format!("invalid web name: {name}")));
    }
    if !name
        .chars()
        .all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.'))
    {
        return Err(Error::msg(
            "web name may only contain [A-Za-z0-9._-] characters",
        ));
    }
    Ok(())
}

fn meta_path(www: &Path, name: &str) -> PathBuf {
    www.join(format!("{name}.meta.json"))
}

fn body_path(www: &Path, name: &str) -> PathBuf {
    www.join(name)
}

fn now_rfc3339() -> String {
    chrono::Utc::now().to_rfc3339()
}

fn expires_rfc3339(ttl_secs: u64) -> String {
    let when = SystemTime::now() + Duration::from_secs(ttl_secs);
    let secs = when
        .duration_since(UNIX_EPOCH)
        .unwrap_or_default()
        .as_secs() as i64;
    chrono::DateTime::from_timestamp(secs, 0)
        .unwrap_or_else(chrono::Utc::now)
        .to_rfc3339()
}

fn is_expired(meta: &WwwMeta) -> bool {
    let Some(exp) = &meta.expires_at else {
        return false;
    };
    match chrono::DateTime::parse_from_rfc3339(exp) {
        Ok(dt) => dt.with_timezone(&chrono::Utc) < chrono::Utc::now(),
        Err(_) => false,
    }
}

/// Write body + meta under `.daemon/www/<name>`.
pub fn publish(
    home: &UnifierHome,
    name: &str,
    body: &[u8],
    content_type: Option<&str>,
    ttl_secs: Option<u64>,
) -> Result<WwwMeta> {
    validate_name(name)?;
    let www = www_dir(home);
    fs::create_dir_all(&www)?;
    // Confine writes under www/
    let dest = resolve_under_root(&www, name)?;
    let tmp = www.join(format!(".{name}.tmp"));
    fs::write(&tmp, body)?;
    fs::rename(&tmp, &dest)?;

    let meta = WwwMeta {
        name: name.to_string(),
        content_type: content_type
            .unwrap_or(DEFAULT_CONTENT_TYPE)
            .to_string(),
        created_at: now_rfc3339(),
        expires_at: ttl_secs.map(expires_rfc3339),
        bytes: body.len() as u64,
    };
    let meta_json = serde_json::to_string_pretty(&meta)?;
    let meta_tmp = www.join(format!(".{name}.meta.tmp"));
    fs::write(&meta_tmp, &meta_json)?;
    fs::rename(meta_tmp, meta_path(&www, name))?;
    Ok(meta)
}

pub fn remove(home: &UnifierHome, name: &str) -> Result<bool> {
    validate_name(name)?;
    let www = www_dir(home);
    let body = body_path(&www, name);
    let meta = meta_path(&www, name);
    let had = body.exists() || meta.exists();
    let _ = fs::remove_file(&body);
    let _ = fs::remove_file(&meta);
    Ok(had)
}

pub fn load_meta(home: &UnifierHome, name: &str) -> Result<Option<WwwMeta>> {
    validate_name(name)?;
    let path = meta_path(&www_dir(home), name);
    if !path.is_file() {
        return Ok(None);
    }
    let text = fs::read_to_string(&path)?;
    let meta: WwwMeta = serde_json::from_str(&text)?;
    if is_expired(&meta) {
        let _ = remove(home, name);
        return Ok(None);
    }
    Ok(Some(meta))
}

pub fn list(home: &UnifierHome) -> Result<Vec<WwwMeta>> {
    let www = www_dir(home);
    if !www.is_dir() {
        return Ok(vec![]);
    }
    let mut out = Vec::new();
    for entry in fs::read_dir(&www)? {
        let entry = entry?;
        let fname = entry.file_name().to_string_lossy().into_owned();
        let Some(name) = fname.strip_suffix(".meta.json") else {
            continue;
        };
        if let Ok(Some(meta)) = load_meta(home, name) {
            out.push(meta);
        }
    }
    out.sort_by(|a, b| a.name.cmp(&b.name));
    Ok(out)
}

pub fn read_port(home: &UnifierHome) -> Option<u16> {
    let text = fs::read_to_string(http_port_path(home)).ok()?;
    text.trim().parse().ok()
}

pub fn base_url(home: &UnifierHome) -> Option<String> {
    read_port(home).map(|p| format!("http://127.0.0.1:{p}"))
}

pub fn entry_url(home: &UnifierHome, name: &str) -> Result<String> {
    validate_name(name)?;
    let base = base_url(home).ok_or_else(|| Error::msg("web server port not available"))?;
    Ok(format!("{base}/{name}"))
}

/// Wrap a report body in Unifier chrome for interactive Jan HTML export.
pub fn wrap_html(title: &str, body: &str) -> String {
    format!(
        r#"<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>{title}</title>
<style>
  :root {{ color-scheme: light; --ink:#1a1f1c; --muted:#5c6b63; --bg:#f3f6f2; --accent:#2f6f4e; --card:#fff; }}
  * {{ box-sizing: border-box; }}
  body {{ margin:0; font:16px/1.55 "IBM Plex Sans","Source Sans 3",system-ui,sans-serif;
         background:
           radial-gradient(900px 480px at 0% 0%, #d7e8de 0%, transparent 60%),
           radial-gradient(700px 420px at 100% 10%, #e8efe4 0%, transparent 55%),
           var(--bg);
         color:var(--ink); min-height:100vh; }}
  header {{ padding:1.25rem 1.5rem; border-bottom:1px solid #d5ddd7;
            backdrop-filter: blur(6px); background:rgba(243,246,242,0.85);
            display:flex; align-items:baseline; gap:0.75rem; }}
  header .brand {{ font-family:"IBM Plex Serif","Source Serif 4",Georgia,serif;
                   font-size:1.35rem; font-weight:600; letter-spacing:-0.02em; }}
  header .title {{ color:var(--muted); font-size:0.95rem; }}
  header a {{ color:var(--accent); text-decoration:none; margin-left:auto; font-size:0.9rem; }}
  main {{ max-width:56rem; margin:1.5rem auto 3rem; padding:1.25rem 1.5rem;
          background:var(--card); border:1px solid #d5ddd7; border-radius:10px;
          box-shadow:0 10px 30px rgba(26,31,28,0.04); }}
</style>
</head>
<body>
<header>
  <div class="brand">Unifier</div>
  <div class="title">{title}</div>
  <a href="/">all reports</a>
</header>
<main>
{body}
</main>
</body>
</html>
"#,
        title = html_escape(title),
        body = body
    )
}

fn preferred_port() -> u16 {
    std::env::var(DEFAULT_PORT_ENV)
        .ok()
        .and_then(|s| s.parse().ok())
        .unwrap_or(PREFERRED_PORT)
}

/// Spawn the localhost HTTP listener. Returns the bound port.
/// `http_activity` is set true on each accepted request so the daemon idle
/// timer stays fresh while browsers are hitting temp reports.
pub fn spawn(
    home: UnifierHome,
    shutdown: Arc<AtomicBool>,
    http_activity: Arc<AtomicBool>,
) -> Result<u16> {
    let preferred = preferred_port();
    let listener = match TcpListener::bind(SocketAddr::from(([127, 0, 0, 1], preferred))) {
        Ok(l) => l,
        Err(_) => TcpListener::bind(SocketAddr::from(([127, 0, 0, 1], 0)))?,
    };
    listener.set_nonblocking(true)?;
    let port = listener.local_addr()?.port();
    fs::create_dir_all(crate::daemon::paths::daemon_dir(&home))?;
    fs::write(http_port_path(&home), format!("{port}\n"))?;
    fs::create_dir_all(www_dir(&home))?;

    thread::spawn(move || {
        let mut last_gc = Instant::now();
        while !shutdown.load(Ordering::Relaxed) {
            match listener.accept() {
                Ok((stream, _)) => {
                    http_activity.store(true, Ordering::Relaxed);
                    if let Err(e) = handle_http(stream, &home) {
                        eprintln!("www http error: {e}");
                    }
                }
                Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {
                    if last_gc.elapsed() > Duration::from_secs(30) {
                        let _ = gc_expired(&home);
                        last_gc = Instant::now();
                    }
                    thread::sleep(Duration::from_millis(25));
                }
                Err(e) => {
                    eprintln!("www accept error: {e}");
                    thread::sleep(Duration::from_millis(100));
                }
            }
        }
        let _ = fs::remove_file(http_port_path(&home));
    });

    Ok(port)
}

fn gc_expired(home: &UnifierHome) -> Result<()> {
    for meta in list(home)? {
        // list() already drops expired via load_meta
        let _ = meta;
    }
    Ok(())
}

fn handle_http(mut stream: TcpStream, home: &UnifierHome) -> Result<()> {
    stream.set_read_timeout(Some(Duration::from_secs(5)))?;
    stream.set_write_timeout(Some(Duration::from_secs(5)))?;

    let mut buf = [0u8; 4096];
    let n = stream.read(&mut buf)?;
    if n == 0 {
        return Ok(());
    }
    let req = String::from_utf8_lossy(&buf[..n]);
    let mut lines = req.lines();
    let request_line = lines.next().unwrap_or("");
    let mut parts = request_line.split_whitespace();
    let method = parts.next().unwrap_or("");
    let path = parts.next().unwrap_or("/");

    if method != "GET" && method != "HEAD" {
        write_response(&mut stream, 405, "text/plain; charset=utf-8", b"method not allowed")?;
        return Ok(());
    }

    if path == "/" || path == "/index.html" {
        let body = index_html(home)?;
        write_response(
            &mut stream,
            200,
            "text/html; charset=utf-8",
            if method == "HEAD" { b"" } else { body.as_bytes() },
        )?;
        return Ok(());
    }

    let name = path.trim_start_matches('/');
    if name.contains('/') || validate_name(name).is_err() {
        write_response(&mut stream, 404, "text/plain; charset=utf-8", b"not found")?;
        return Ok(());
    }

    let Some(meta) = load_meta(home, name)? else {
        write_response(&mut stream, 404, "text/plain; charset=utf-8", b"not found")?;
        return Ok(());
    };

    let body_path = body_path(&www_dir(home), name);
    let body = fs::read(&body_path).unwrap_or_default();
    write_response(
        &mut stream,
        200,
        &meta.content_type,
        if method == "HEAD" { b"" } else { &body },
    )?;
    Ok(())
}

fn index_html(home: &UnifierHome) -> Result<String> {
    let entries = list(home)?;
    let mut items = String::new();
    for e in &entries {
        items.push_str(&format!(
            "<li><a href=\"/{}\">{}</a> <span class=\"meta\">{} · {} bytes</span></li>\n",
            html_escape(&e.name),
            html_escape(&e.name),
            html_escape(&e.content_type),
            e.bytes
        ));
    }
    if items.is_empty() {
        items.push_str("<li class=\"empty\">No files yet. Pipe HTML with <code>unifier serve</code>.</li>\n");
    }
    Ok(format!(
        r#"<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>Unifier</title>
<style>
  :root {{ color-scheme: light; --ink:#1a1f1c; --muted:#5c6b63; --bg:#f3f6f2; --accent:#2f6f4e; }}
  body {{ margin:0; font:16px/1.5 "IBM Plex Sans", "Source Sans 3", system-ui, sans-serif;
         background: radial-gradient(1200px 600px at 10% -10%, #dfece4, var(--bg)); color:var(--ink); }}
  main {{ max-width:42rem; margin:3rem auto; padding:0 1.25rem; }}
  h1 {{ font-family:"IBM Plex Serif","Source Serif 4",Georgia,serif; font-weight:600; letter-spacing:-0.02em; }}
  a {{ color:var(--accent); }}
  ul {{ list-style:none; padding:0; }}
  li {{ padding:0.55rem 0; border-bottom:1px solid #d5ddd7; }}
  .meta {{ color:var(--muted); font-size:0.85rem; margin-left:0.5rem; }}
  .empty {{ color:var(--muted); border:0; }}
  code {{ font-family:ui-monospace,monospace; font-size:0.9em; }}
</style>
</head>
<body>
<main>
  <h1>Unifier</h1>
  <p>Temp files served from this daemon.</p>
  <ul>
{items}  </ul>
</main>
</body>
</html>
"#
    ))
}

fn html_escape(s: &str) -> String {
    s.replace('&', "&amp;")
        .replace('<', "&lt;")
        .replace('>', "&gt;")
        .replace('"', "&quot;")
}

fn write_response(stream: &mut TcpStream, status: u16, content_type: &str, body: &[u8]) -> Result<()> {
    let reason = match status {
        200 => "OK",
        404 => "Not Found",
        405 => "Method Not Allowed",
        _ => "Error",
    };
    let header = format!(
        "HTTP/1.1 {status} {reason}\r\n\
         Content-Type: {content_type}\r\n\
         Content-Length: {}\r\n\
         Connection: close\r\n\
         Cache-Control: no-store\r\n\
         Access-Control-Allow-Origin: *\r\n\
         \r\n",
        body.len()
    );
    stream.write_all(header.as_bytes())?;
    if !body.is_empty() {
        stream.write_all(body)?;
    }
    stream.flush()?;
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use tempfile::tempdir;

    fn home(dir: &Path) -> UnifierHome {
        UnifierHome::resolve(Some(dir.to_path_buf()), None).unwrap()
    }

    #[test]
    fn publish_list_remove() {
        let tmp = tempdir().unwrap();
        let h = home(tmp.path());
        publish(&h, "report", b"<h1>hi</h1>", None, None).unwrap();
        let entries = list(&h).unwrap();
        assert_eq!(entries.len(), 1);
        assert_eq!(entries[0].name, "report");
        assert!(remove(&h, "report").unwrap());
        assert!(list(&h).unwrap().is_empty());
    }

    #[test]
    fn rejects_bad_names() {
        assert!(validate_name("../x").is_err());
        assert!(validate_name("a/b").is_err());
        assert!(validate_name("").is_err());
    }

    #[test]
    fn ttl_expires() {
        let tmp = tempdir().unwrap();
        let h = home(tmp.path());
        let mut meta = publish(&h, "old", b"x", Some("text/plain"), Some(1)).unwrap();
        // Force expiry in the past
        meta.expires_at = Some("2000-01-01T00:00:00Z".into());
        let www = www_dir(&h);
        fs::write(meta_path(&www, "old"), serde_json::to_string(&meta).unwrap()).unwrap();
        assert!(load_meta(&h, "old").unwrap().is_none());
    }
}