shine-cli 1.7.0

Give personal automation a reviewable lifecycle
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
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
use anyhow::{Context, Result, bail};
use sha2::{Digest, Sha256};
use std::path::{Component, Path, PathBuf};
use std::time::Duration;
use tokio::fs;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::{TcpListener, TcpStream};
use tokio::process::Command;

use crate::config::Config;

const DEFAULT_HOST: &str = "127.0.0.1";
const LAUNCHD_LABEL: &str = "top.biulight.shine.http";
const MAX_HEADER_BYTES: usize = 8192;
/// Bounds how long a single connection may take end-to-end (read request + write
/// response), so a slow-loris style local client can't hold a task open forever.
const CONNECTION_TIMEOUT: Duration = Duration::from_secs(30);

// --- Trust boundary ---------------------------------------------------------------------
//
// This server binds loopback-only (`DEFAULT_HOST` = 127.0.0.1) and is never reachable from
// the network, but it has NO authentication of its own: any local OS user account on a
// shared/multi-user machine can connect to `127.0.0.1:<port>` and read any file under
// `http_root()`, bypassing the normal filesystem permissions that would otherwise keep
// other accounts out of this user's home directory. Preset authors must never route secrets
// or otherwise sensitive content through a `dest` that resolves under `~/.shine/http`.
// See docs/kb/architecture/invariants.md ยง Local HTTP server.

pub async fn handle_install(config: &Config, port: u16) -> Result<()> {
    ensure_macos_service_support()?;

    let root = http_root(config);
    fs::create_dir_all(&root)
        .await
        .with_context(|| format!("creating {}", root.display()))?;

    let plist_path = launchd_plist_path(config);
    let parent = plist_path
        .parent()
        .context("launchd plist path must have a parent directory")?;
    fs::create_dir_all(parent)
        .await
        .with_context(|| format!("creating {}", parent.display()))?;

    let log_dir = launchd_log_dir(config);
    fs::create_dir_all(&log_dir)
        .await
        .with_context(|| format!("creating {}", log_dir.display()))?;

    let executable = service_executable(config)?;
    let plist = launchd_plist(&executable, port, &log_dir);
    fs::write(&plist_path, plist)
        .await
        .with_context(|| format!("writing {}", plist_path.display()))?;

    let plist_arg = plist_path.to_string_lossy().to_string();
    let _ = launchctl(&["unload", "-w", &plist_arg]).await;
    launchctl(&["load", "-w", &plist_arg]).await?;

    println!("Installed {LAUNCHD_LABEL}");
    println!("Serving {}", root.display());
    println!("URL base: http://{DEFAULT_HOST}:{port}/");
    Ok(())
}

pub async fn handle_start(config: &Config, port: u16) -> Result<()> {
    let root = http_root(config);
    fs::create_dir_all(&root)
        .await
        .with_context(|| format!("creating {}", root.display()))?;

    let listener = TcpListener::bind((DEFAULT_HOST, port))
        .await
        .with_context(|| format!("binding {DEFAULT_HOST}:{port}"))?;
    println!("Serving {}", root.display());
    println!("URL base: http://{DEFAULT_HOST}:{port}/");

    loop {
        let (stream, _) = listener.accept().await?;
        let root = root.clone();
        tokio::spawn(async move {
            match tokio::time::timeout(CONNECTION_TIMEOUT, handle_connection(stream, root)).await {
                Ok(Ok(())) => {}
                Ok(Err(e)) => eprintln!("shine serve: connection error: {e:#}"),
                Err(_) => {
                    eprintln!("shine serve: connection timed out after {CONNECTION_TIMEOUT:?}")
                }
            }
        });
    }
}

pub async fn handle_status(config: &Config) -> Result<()> {
    ensure_macos_service_support()?;

    let plist_path = launchd_plist_path(config);
    if !plist_path.exists() {
        println!("Not installed");
        return Ok(());
    }

    match launchctl(&["list", LAUNCHD_LABEL]).await {
        Ok(()) => println!("Installed and loaded"),
        Err(_) => println!("Installed but not loaded"),
    }
    println!("Plist: {}", plist_path.display());
    Ok(())
}

pub async fn handle_uninstall(config: &Config) -> Result<()> {
    ensure_macos_service_support()?;

    let plist_path = launchd_plist_path(config);
    if plist_path.exists() {
        let plist_arg = plist_path.to_string_lossy().to_string();
        let _ = launchctl(&["unload", "-w", &plist_arg]).await;
        fs::remove_file(&plist_path)
            .await
            .with_context(|| format!("removing {}", plist_path.display()))?;
        println!("Uninstalled {LAUNCHD_LABEL}");
    } else {
        println!("Not installed");
    }
    Ok(())
}

pub fn handle_url(path: &str, port: u16) -> Result<()> {
    println!("{}", public_url(path, port)?);
    Ok(())
}

pub fn public_url(path: &str, port: u16) -> Result<String> {
    let rel = normalize_resource_path(path)?;
    Ok(format!(
        "http://{DEFAULT_HOST}:{port}/{}",
        rel.to_string_lossy()
    ))
}

pub fn http_root(config: &Config) -> PathBuf {
    config.shine_dir().join("http")
}

/// Directory for the launchd service's stdout/stderr logs. Deliberately kept out of
/// `http_root()` (`shine_dir/http`) so log contents are never servable over HTTP, and kept
/// under the user's own `shine_dir` (not a shared path like `/tmp`) so two OS user accounts
/// running `shine serve install` never collide on the same log file.
fn launchd_log_dir(config: &Config) -> PathBuf {
    config.shine_dir().join("run").join("http")
}

fn ensure_macos_service_support() -> Result<()> {
    if !cfg!(target_os = "macos") {
        bail!("shine serve install is currently supported on macOS only");
    }
    Ok(())
}

fn service_executable(config: &Config) -> Result<PathBuf> {
    if let Some(dest) = &config.self_install_dest {
        return Ok(dest.clone());
    }
    std::env::current_exe().context("failed to resolve current executable path")
}

fn launchd_plist_path(config: &Config) -> PathBuf {
    config
        .home_dir
        .join("Library")
        .join("LaunchAgents")
        .join(format!("{LAUNCHD_LABEL}.plist"))
}

fn launchd_plist(executable: &Path, port: u16, log_dir: &Path) -> String {
    let executable = xml_escape(&executable.display().to_string());
    let out_log = xml_escape(&log_dir.join("serve.out.log").display().to_string());
    let err_log = xml_escape(&log_dir.join("serve.err.log").display().to_string());
    format!(
        r#"<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
  <key>Label</key>
  <string>{LAUNCHD_LABEL}</string>
  <key>ProgramArguments</key>
  <array>
    <string>{executable}</string>
    <string>serve</string>
    <string>start</string>
    <string>--port</string>
    <string>{port}</string>
  </array>
  <key>RunAtLoad</key>
  <true/>
  <key>KeepAlive</key>
  <true/>
  <key>StandardOutPath</key>
  <string>{out_log}</string>
  <key>StandardErrorPath</key>
  <string>{err_log}</string>
</dict>
</plist>
"#
    )
}

fn xml_escape(value: &str) -> String {
    value
        .replace('&', "&amp;")
        .replace('<', "&lt;")
        .replace('>', "&gt;")
        .replace('"', "&quot;")
        .replace('\'', "&apos;")
}

async fn launchctl(args: &[&str]) -> Result<()> {
    let output = Command::new("launchctl")
        .args(args)
        .output()
        .await
        .with_context(|| format!("running launchctl {}", args.join(" ")))?;
    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        let stdout = String::from_utf8_lossy(&output.stdout);
        let detail = stderr.trim();
        let detail = if detail.is_empty() {
            stdout.trim()
        } else {
            detail
        };
        if detail.is_empty() {
            bail!("launchctl {} failed with {}", args.join(" "), output.status);
        }
        bail!(
            "launchctl {} failed with {}: {detail}",
            args.join(" "),
            output.status
        );
    }
    Ok(())
}

async fn handle_connection(mut stream: TcpStream, root: PathBuf) -> Result<()> {
    let request = match read_request(&mut stream).await {
        Ok(request) => request,
        Err(_) => {
            write_response(
                &mut stream,
                400,
                "Bad Request",
                "text/plain",
                b"",
                false,
                None,
            )
            .await?;
            return Ok(());
        }
    };

    if request.method != "GET" && request.method != "HEAD" {
        write_response(
            &mut stream,
            405,
            "Method Not Allowed",
            "text/plain",
            b"",
            false,
            None,
        )
        .await?;
        return Ok(());
    }

    let rel = match normalize_resource_path(&request.path) {
        Ok(rel) => rel,
        Err(_) => {
            write_response(
                &mut stream,
                404,
                "Not Found",
                "text/plain",
                b"",
                false,
                None,
            )
            .await?;
            return Ok(());
        }
    };
    let root_canon = fs::canonicalize(&root).await?;
    let candidate = root.join(rel);
    let file_canon = match fs::canonicalize(&candidate).await {
        Ok(path) => path,
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
            write_response(
                &mut stream,
                404,
                "Not Found",
                "text/plain",
                b"",
                false,
                None,
            )
            .await?;
            return Ok(());
        }
        Err(e) => return Err(e.into()),
    };
    if !file_canon.starts_with(&root_canon) || !file_canon.is_file() {
        write_response(
            &mut stream,
            404,
            "Not Found",
            "text/plain",
            b"",
            false,
            None,
        )
        .await?;
        return Ok(());
    }

    let bytes = fs::read(&file_canon).await?;
    let etag = entity_tag(&bytes);
    if request
        .if_none_match
        .as_deref()
        .is_some_and(|value| etag_matches(value, &etag))
    {
        write_response(
            &mut stream,
            304,
            "Not Modified",
            content_type(&file_canon),
            b"",
            true,
            Some(&etag),
        )
        .await?;
        return Ok(());
    }
    write_response(
        &mut stream,
        200,
        "OK",
        content_type(&file_canon),
        &bytes,
        request.method == "HEAD",
        Some(&etag),
    )
    .await?;
    Ok(())
}

struct Request {
    method: String,
    path: String,
    if_none_match: Option<String>,
}

async fn read_request(stream: &mut TcpStream) -> Result<Request> {
    let mut data = Vec::new();
    let mut buf = [0u8; 1024];
    loop {
        let n = stream.read(&mut buf).await?;
        if n == 0 {
            break;
        }
        data.extend_from_slice(&buf[..n]);
        if data.windows(4).any(|w| w == b"\r\n\r\n") {
            break;
        }
        if data.len() > MAX_HEADER_BYTES {
            bail!("request header too large");
        }
    }

    let header = std::str::from_utf8(&data).context("request header must be utf-8")?;
    let line = header.lines().next().context("missing request line")?;
    let mut parts = line.split_whitespace();
    let method = parts.next().context("missing method")?.to_string();
    let target = parts.next().context("missing path")?;
    let path = target
        .split_once('?')
        .map(|(path, _)| path)
        .unwrap_or(target)
        .to_string();
    let if_none_match = header.lines().skip(1).find_map(|line| {
        let (name, value) = line.split_once(':')?;
        name.eq_ignore_ascii_case("if-none-match")
            .then(|| value.trim().to_string())
    });
    Ok(Request {
        method,
        path,
        if_none_match,
    })
}

async fn write_response(
    stream: &mut TcpStream,
    status: u16,
    reason: &str,
    content_type: &str,
    body: &[u8],
    head_only: bool,
    etag: Option<&str>,
) -> Result<()> {
    let cache_headers = cache_headers(etag);
    let headers = format!(
        "HTTP/1.1 {status} {reason}\r\nContent-Length: {}\r\nContent-Type: {content_type}\r\n{cache_headers}Connection: close\r\n\r\n",
        body.len(),
    );
    stream.write_all(headers.as_bytes()).await?;
    if !head_only {
        stream.write_all(body).await?;
    }
    Ok(())
}

fn cache_headers(etag: Option<&str>) -> String {
    let mut headers =
        "Cache-Control: no-cache, max-age=0, must-revalidate\r\nPragma: no-cache\r\n".to_string();
    if let Some(etag) = etag {
        headers.push_str(&format!("ETag: {etag}\r\n"));
    }
    headers
}

fn entity_tag(bytes: &[u8]) -> String {
    format!("\"sha256-{:x}\"", Sha256::digest(bytes))
}

fn etag_matches(if_none_match: &str, etag: &str) -> bool {
    if_none_match
        .split(',')
        .map(str::trim)
        .any(|candidate| candidate == "*" || candidate.trim_start_matches("W/") == etag)
}

fn normalize_resource_path(path: &str) -> Result<PathBuf> {
    let path = path.trim_start_matches('/');
    if path.is_empty() {
        bail!("resource path must not be empty");
    }
    let decoded = percent_decode(path)?;
    let rel = Path::new(&decoded);
    if rel.is_absolute() {
        bail!("resource path must be relative");
    }
    if rel.components().any(|c| !matches!(c, Component::Normal(_))) {
        bail!("resource path must not contain traversal");
    }
    Ok(rel.to_path_buf())
}

fn percent_decode(input: &str) -> Result<String> {
    let bytes = input.as_bytes();
    let mut out = Vec::with_capacity(bytes.len());
    let mut i = 0;
    while i < bytes.len() {
        if bytes[i] == b'%' {
            if i + 2 >= bytes.len() {
                bail!("invalid percent encoding");
            }
            let hex = std::str::from_utf8(&bytes[i + 1..i + 3])?;
            out.push(u8::from_str_radix(hex, 16).context("invalid percent encoding")?);
            i += 3;
        } else {
            out.push(bytes[i]);
            i += 1;
        }
    }
    String::from_utf8(out).context("decoded path must be utf-8")
}

fn content_type(path: &Path) -> &'static str {
    match path.extension().and_then(|ext| ext.to_str()) {
        Some("html") => "text/html; charset=utf-8",
        Some("json") => "application/json",
        Some("sgmodule" | "txt" | "toml") => "text/plain; charset=utf-8",
        _ => "application/octet-stream",
    }
}

#[cfg(test)]
mod tests {
    use super::{
        cache_headers, entity_tag, etag_matches, launchd_log_dir, launchd_plist,
        launchd_plist_path, normalize_resource_path, public_url,
    };
    use crate::config::Config;
    use std::path::{Path, PathBuf};

    #[test]
    fn public_url_uses_single_local_server_root() {
        assert_eq!(
            public_url("/app/surge/custom-rules.sgmodule", 6174).unwrap(),
            "http://127.0.0.1:6174/app/surge/custom-rules.sgmodule"
        );
    }

    #[test]
    fn resource_paths_reject_traversal() {
        assert!(normalize_resource_path("../secret").is_err());
        assert!(normalize_resource_path("app/../secret").is_err());
        assert!(normalize_resource_path("/app/surge/custom-rules.sgmodule").is_ok());
        assert_eq!(
            normalize_resource_path("app/surge/custom-rules.sgmodule").unwrap(),
            Path::new("app/surge/custom-rules.sgmodule")
        );
    }

    #[test]
    fn resource_responses_require_revalidation_and_offer_an_etag() {
        let etag = entity_tag(b"current rules");
        let headers = cache_headers(Some(&etag));
        assert!(headers.contains("Cache-Control: no-cache, max-age=0, must-revalidate"));
        assert!(headers.contains("Pragma: no-cache"));
        assert!(headers.contains(&format!("ETag: {etag}")));
        assert!(etag_matches(&etag, &etag));
        assert!(etag_matches(&format!("W/{etag}, \"older\""), &etag));
        assert!(!etag_matches("\"older\"", &etag));
    }

    #[test]
    fn launchd_plist_runs_the_single_foreground_server() {
        let log_dir = Path::new("/Users/tester/.shine/run/http");
        let plist = launchd_plist(Path::new("/opt/shine & tools/shine"), 6188, log_dir);
        assert!(plist.contains("<string>top.biulight.shine.http</string>"));
        assert!(plist.contains("<string>/opt/shine &amp; tools/shine</string>"));
        assert!(plist.contains("<string>serve</string>"));
        assert!(plist.contains("<string>start</string>"));
        assert!(plist.contains("<string>--port</string>"));
        assert!(plist.contains("<string>6188</string>"));
    }

    #[test]
    fn launchd_plist_logs_are_scoped_under_the_user_shine_dir_not_shared_tmp() {
        let log_dir = Path::new("/Users/tester/.shine/run/http");
        let plist = launchd_plist(Path::new("/opt/shine/shine"), 6188, log_dir);
        assert!(plist.contains("<string>/Users/tester/.shine/run/http/serve.out.log</string>"));
        assert!(plist.contains("<string>/Users/tester/.shine/run/http/serve.err.log</string>"));
        assert!(!plist.contains("/tmp/"));
    }

    #[test]
    fn launchd_plist_path_lives_under_user_launch_agents() {
        let root = PathBuf::from("/tmp/shine-home");
        let config = Config::new_for_test(&root);
        assert_eq!(
            launchd_plist_path(&config),
            root.join("Library/LaunchAgents/top.biulight.shine.http.plist")
        );
    }

    #[test]
    fn launchd_log_dir_lives_under_shine_dir_run_not_shared_tmp() {
        let root = PathBuf::from("/tmp/shine-home");
        let config = Config::new_for_test(&root);
        assert_eq!(launchd_log_dir(&config), root.join("run").join("http"));
    }
}