webadev 0.10.0

A web dev server with live reload
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
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
//! HTTP layer: serves the static folder over axum with live reload over SSE.
//!
//! - [`Server::new`] serves statically only.
//! - [`Server::bind`] also drives reloads from a `broadcast` channel.
//! - [`bind`] + [`serve`] split binding from serving, so you can merge the
//!   router with your own axum routes.

use std::{
    convert::Infallible,
    net::IpAddr,
    path::{Component, Path, PathBuf},
    str::FromStr,
    sync::Arc,
    time::Duration,
};

use axum::{
    Router,
    body::{Body, Bytes},
    extract::{Path as UrlPath, State},
    http::{HeaderName, HeaderValue, Request, StatusCode, Uri, header},
    middleware::{self, Next},
    response::{
        Response,
        sse::{Event, KeepAlive, Sse},
    },
    routing::get,
};
use futures_util::stream::{Stream, unfold};
use tokio::{
    net::TcpListener,
    sync::broadcast::{self, Sender, error::RecvError},
};

use crate::{ReloadType, base_normalize};

struct AppState {
    dir: PathBuf,
    tx: Sender<(ReloadType, Vec<PathBuf>)>,
    headers: Vec<(HeaderName, HeaderValue)>,
    index: String,
    // Normalized url path prefix: empty (root) or `/prefix` without a trailing slash
    base: String,
}

/// Configuration for the server
#[derive(Clone, Debug)]
pub struct Config {
    /// Directory to serve and watch
    pub dir: PathBuf,
    /// IP address to bind to
    pub ip: IpAddr,
    /// Port to listen on
    pub port: u16,
    /// Additional HTTP headers, as `Name: value` strings
    pub headers: Vec<String>,
    /// Default file served for directory requests
    pub index: String,
    /// URL path prefix (e.g. `/app`)
    /// Empty or `/` serves at the root (default); any other value must start with `/`
    pub base: String,
}

/// A bound server, ready to run.
/// `run` starts serving only when awaited, so the `url` can be shown first.
#[derive(Debug)]
pub struct Server {
    /// URL to open in the browser
    pub url: String,
    listener: TcpListener,
    router: Router,
}

impl Server {
    /// Bind `config` with a custom reload channel.
    ///
    /// # Examples
    ///
    /// ```
    /// use std::net::IpAddr;
    /// use tempfile::tempdir;
    /// use tokio::sync::broadcast;
    /// use webadev::{Config, Server, watch};
    ///
    /// #[tokio::main]
    /// async fn main() {
    ///     let dir = tempdir().unwrap();
    ///     std::fs::write(dir.path().join("index.html"), "<h1>hi</h1>").unwrap();
    ///
    ///     let (tx, _rx) = broadcast::channel(100); // Keep a receiver alive so watch() can send
    ///     watch(tx.clone(), dir.path()).unwrap();
    ///
    ///     let config = Config {
    ///         dir: dir.path().to_path_buf(),
    ///         ip: IpAddr::from([127, 0, 0, 1]),
    ///         port: 0, // Let the OS pick a free port
    ///         headers: vec![],
    ///         index: "index.html".into(),
    ///         base: String::new(),
    ///     };
    ///
    ///     let server = Server::bind(tx, config).await.unwrap();
    ///     let url = server.url.clone();
    ///     tokio::spawn(async move { let _ = server.run().await; });
    ///
    ///     let body = reqwest::get(format!("{url}/"))
    ///         .await
    ///         .unwrap()
    ///         .text()
    ///         .await
    ///         .unwrap();
    ///     assert!(body.contains("hi"));
    /// }
    /// ```
    pub async fn bind(
        tx: Sender<(ReloadType, Vec<PathBuf>)>,
        config: Config,
    ) -> Result<Self, String> {
        let (url, listener, router) = bind(tx, config).await?;

        Ok(Self {
            url,
            listener,
            router,
        })
    }

    /// Bind `config` without sending reload events (static serving).
    ///
    /// # Examples
    ///
    /// ```
    /// use std::net::IpAddr;
    /// use tempfile::tempdir;
    /// use webadev::{Config, Server};
    ///
    /// #[tokio::main]
    /// async fn main() {
    ///     let dir = tempdir().unwrap();
    ///     std::fs::write(dir.path().join("index.html"), "<h1>hi</h1>").unwrap();
    ///
    ///     let config = Config {
    ///         dir: dir.path().to_path_buf(),
    ///         ip: IpAddr::from([127, 0, 0, 1]),
    ///         port: 0, // Let the OS pick a free port
    ///         headers: vec![],
    ///         index: "index.html".into(),
    ///         base: String::new(),
    ///     };
    ///
    ///     let server = Server::new(config).await.unwrap();
    ///     let url = server.url.clone();
    ///     tokio::spawn(async move { let _ = server.run().await; });
    ///
    ///     let body = reqwest::get(format!("{url}/"))
    ///         .await
    ///         .unwrap()
    ///         .text()
    ///         .await
    ///         .unwrap();
    ///     assert!(body.contains("hi"));
    /// }
    /// ```
    pub async fn new(config: Config) -> Result<Self, String> {
        let (tx, _rx) = broadcast::channel(100);

        Self::bind(tx, config).await
    }

    /// Serve until the server stops. lazy: starts only when awaited.
    /// the `url` is consumed along with `self`, so read it before calling.
    pub async fn run(self) -> Result<(), String> {
        serve(self.listener, self.router).await
    }
}

/// Bind to `config.ip:config.port` and build the router.
/// Returns the url, the bound listener and the router.
/// Use `0` as `config.port` to let the OS pick a free port (the real one is in the url).
///
/// # Examples
///
/// ```
/// use std::net::IpAddr;
/// use axum::{Router, routing::get};
/// use tempfile::tempdir;
/// use tokio::sync::broadcast;
/// use webadev::{Config, bind, serve};
///
/// #[tokio::main]
/// async fn main() {
///     let dir = tempdir().unwrap();
///     std::fs::write(dir.path().join("index.html"), "<h1>hi</h1>").unwrap();
///
///     let (tx, _rx) = broadcast::channel(100);
///     let config = Config {
///         dir: dir.path().to_path_buf(),
///         ip: IpAddr::from([127, 0, 0, 1]),
///         port: 0,
///         headers: vec![],
///         index: "index.html".into(),
///         base: String::new(),
///     };
///
///     let (url, listener, router) = bind(tx, config).await.unwrap();
///     // Here you can tweak the axum router
///     let router = router.route("/health", get(|| async { "ok" }));
///
///     let url = url.clone();
///     tokio::spawn(async move { let _ = serve(listener, router).await; });
///
///     let body = reqwest::get(format!("{url}/health"))
///         .await
///         .unwrap()
///         .text()
///         .await
///         .unwrap();
///     assert_eq!(body, "ok");
/// }
/// ```
pub async fn bind(
    tx: Sender<(ReloadType, Vec<PathBuf>)>,
    config: Config,
) -> Result<(String, TcpListener, Router), String> {
    let headers =
        headers_parse(&config.headers).map_err(|err| format!("Invalid --header: {err}"))?;

    index_validate(&config.index).map_err(|err| format!("Invalid --index: {err}"))?;

    let base = base_normalize(&config.base).map_err(|err| format!("Invalid --base: {err}"))?;

    let listener = TcpListener::bind((config.ip, config.port))
        .await
        .map_err(|err| format!("Failed to bind address: {err}"))?;
    let addr = listener
        .local_addr()
        .map_err(|err| format!("Failed to get bound address: {err}"))?;

    let url = if config.ip.is_unspecified() {
        format!("http://127.0.0.1:{}{base}", addr.port())
    } else {
        format!("http://{}:{}{base}", config.ip, addr.port())
    };

    let app = app_build(AppState {
        dir: config.dir,
        tx,
        headers,
        index: config.index,
        base,
    });

    Ok((url, listener, app))
}

/// Serve files from the already-bound `listener` with the given `router`,
/// with live-reload over SSE.
///
/// Usually paired with [`bind`]: [`bind`] returns the listener and the router,
/// [`serve`] runs them.
pub async fn serve(listener: TcpListener, router: Router) -> Result<(), String> {
    axum::serve(listener, router)
        .await
        .map_err(|err| format!("{err}"))?;

    Ok(())
}

fn app_build(state: AppState) -> Router {
    let state = Arc::new(state);
    let base = state.base.clone();

    let mut router = Router::new()
        .route(&format!("{base}/livereload"), get(livereload))
        .route(&format!("{base}/"), get(root_serve))
        .route(&format!("{base}/{{*path}}"), get(files_serve));

    // A page served at `/app` would resolve relative URLs against `/`.
    // Redirect to `/app/` instead so they resolve under the base.
    if !base.is_empty() {
        router = router.route(&base, get(base_redirect));
    }

    router
        .with_state(state.clone())
        .layer(middleware::from_fn_with_state(state, headers_middleware))
}

// Parse `Name: value` header strings into axum header pairs
// - `:` separator
// - Empty names/values and control chars are rejected (header-injection guard)
fn headers_parse(raw: &[String]) -> Result<Vec<(HeaderName, HeaderValue)>, String> {
    raw.iter()
        .map(|item| {
            let (name, value) = item
                .split_once(':')
                .ok_or_else(|| format!("missing ':' separator in `{item}`"))?;
            let name = name.trim();
            let value = value.trim();
            if name.is_empty() {
                return Err(format!("empty header name in `{item}`"));
            }
            let name = HeaderName::from_str(name)
                .map_err(|_| format!("invalid header name in `{item}`"))?;
            let value = HeaderValue::from_str(value)
                .map_err(|_| format!("invalid header value in `{item}`"))?;
            Ok((name, value))
        })
        .collect()
}

// Validate the `--index` value: a bare filename only.
// Rejects empty, `.`/`..`, any `/` or `\` and a leading `.`
// So that `dir.join(index)` can never escape the docroot.
fn index_validate(index: &str) -> Result<(), String> {
    if index.is_empty() {
        return Err("empty index filename".into());
    }
    if index == "." || index == ".." {
        return Err(format!("invalid index filename `{index}`"));
    }
    if index.starts_with('.') {
        return Err(format!("invalid index filename `{index}`"));
    }
    if index.contains('/') || index.contains('\\') {
        return Err(format!("index must be a bare filename, got `{index}`"));
    }
    Ok(())
}

// Attach user-supplied `--header`s to every response
async fn headers_middleware(
    State(state): State<Arc<AppState>>,
    request: Request<Body>,
    next: Next,
) -> Response {
    let mut response = next.run(request).await;
    for (name, value) in &state.headers {
        response.headers_mut().insert(name.clone(), value.clone());
    }
    response
}

async fn livereload(
    State(state): State<Arc<AppState>>,
) -> Sse<impl Stream<Item = Result<Event, Infallible>>> {
    let rx = state.tx.subscribe();
    Sse::new(unfold(rx, |mut rx| async move {
        let reload_type = match rx.recv().await {
            Ok((reload_type, _)) => reload_type,
            Err(RecvError::Lagged(_)) => ReloadType::Page,
            Err(RecvError::Closed) => return None,
        };
        let message = reload_type.as_str();
        // A `data:` line is required:
        // - SSE specs (WHATWG HTML §9.2.6): events whith no `data:` line are dropped; the line's value could be empty
        // - Axum's `Event::data` silently skips empty input, so the field is never emitted
        Some((Ok(Event::default().event(message).data(message)), rx))
    }))
    .keep_alive(
        KeepAlive::new()
            .interval(Duration::from_secs(15))
            .text("keep-alive"),
    )
}

async fn root_serve(State(state): State<Arc<AppState>>) -> Response {
    file_serve(&state.dir, "", &state.index, &state.base).await
}

async fn files_serve(
    State(state): State<Arc<AppState>>,
    UrlPath(path): UrlPath<String>,
) -> Response {
    file_serve(&state.dir, &path, &state.index, &state.base).await
}

// `/app` → `/app/`, keeping the query string.
// Only registered when a base is set.
async fn base_redirect(State(state): State<Arc<AppState>>, uri: Uri) -> Response {
    let location = match uri.query() {
        Some(query) => format!("{}/?{query}", state.base),
        None => format!("{}/", state.base),
    };
    Response::builder()
        .status(StatusCode::PERMANENT_REDIRECT)
        .header(header::LOCATION, location)
        .body(Body::empty())
        .expect("failed to build response")
}

// Reject any path that could escape the docroot.
// The catch-all capture can keep a leading `/` (`GET //foo` captures `/foo`),
// and `Path::join` replaces the docroot when given an absolute path.
// Rooted paths, drive prefixes, `..` and `\` (a separator on Windows) are rejected.
fn path_validate(path: &str) -> bool {
    if path.contains('\\') {
        return false;
    }
    !Path::new(path).components().any(|component| {
        matches!(
            component,
            Component::ParentDir | Component::RootDir | Component::Prefix(_)
        )
    })
}

async fn file_serve(dir: &Path, path: &str, index: &str, base: &str) -> Response {
    if !path_validate(path) {
        return html_not_found_build();
    }

    let mut file_path = dir.join(path);
    let is_dir = tokio::fs::metadata(&file_path)
        .await
        .is_ok_and(|m| m.is_dir());
    if is_dir {
        file_path = file_path.join(index);
    }

    let bytes = match tokio::fs::read(&file_path).await {
        Ok(bytes) => bytes,
        Err(_) => return html_not_found_build(),
    };

    let is_html = file_path.extension().and_then(|e| e.to_str()) == Some("html");
    if is_html {
        match String::from_utf8(bytes) {
            Ok(html) => html_response_build(js_script_inject(&html, base)),
            Err(err) => html_response_build(err.into_bytes()),
        }
    } else {
        let mime = mime_guess::from_path(&file_path).first_or_octet_stream();
        Response::builder()
            .status(StatusCode::OK)
            .header(header::CONTENT_TYPE, mime.as_ref())
            .header(header::CACHE_CONTROL, "no-cache")
            .body(Body::from(bytes))
            .expect("failed to build response")
    }
}

fn html_response_build(body: impl Into<Bytes>) -> Response {
    Response::builder()
        .status(StatusCode::OK)
        .header(header::CONTENT_TYPE, "text/html; charset=utf-8")
        .header(header::CACHE_CONTROL, "no-cache")
        .body(Body::from(body.into()))
        .expect("failed to build response")
}

fn html_not_found_build() -> Response {
    Response::builder()
        .status(StatusCode::NOT_FOUND)
        .body(Body::empty())
        .expect("failed to build response")
}

fn js_script_inject(html: &str, base: &str) -> String {
    // `format!` would require escaping every brace in the JS; substitute the base instead.
    let script = r#"<script>
        const es = new EventSource('__BASE__/livereload');
        let first = true;
        es.addEventListener('open', () => {
            if (first) {
                first = false;
                console.log('[webadev] live reload connected');
            } else {
                // Server restarted: reload to resync
                location.reload();
            }
        });
        es.addEventListener('page', () => location.reload());
        es.addEventListener('css', () => {
            document.querySelectorAll('link[rel="stylesheet"]').forEach(link => {
                const url = new URL(link.href, location.href);
                url.searchParams.set('t', Date.now());
                link.href = url.toString();
            });
            console.log('[webadev] css hot-reloaded');
        });
        es.addEventListener('error', () => console.warn('[webadev] live reload connection lost', es.readyState));
    </script>"#;
    let script = script.replace("__BASE__", base);

    if html.contains("</body>") {
        html.replace("</body>", &format!("{}\n</body>", script))
    } else if html.contains("</html>") {
        html.replace("</html>", &format!("{}\n</html>", script))
    } else {
        format!("{}\n{}", html, script)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs::{create_dir_all, write};
    use std::net::IpAddr;

    use axum::{
        body::Body,
        http::{HeaderMap, Request, StatusCode},
    };
    use http_body_util::BodyExt;
    use tempfile::tempdir;
    use tokio::sync::broadcast;
    use tower::ServiceExt;

    fn test_app(dir: &Path) -> Router {
        test_app_with_index(dir, "index.html")
    }

    fn test_app_with_index(dir: &Path, index: &str) -> Router {
        test_app_with_headers_and_index(dir, &[], index)
    }

    fn test_app_with_headers(dir: &Path, headers: &[&str]) -> Router {
        test_app_with_headers_and_index(dir, headers, "index.html")
    }

    fn test_app_with_headers_and_index(dir: &Path, headers: &[&str], index: &str) -> Router {
        test_app_full(dir, headers, index, "")
    }

    fn test_app_with_base(dir: &Path, base: &str) -> Router {
        test_app_full(dir, &[], "index.html", base)
    }

    fn test_app_full(dir: &Path, headers: &[&str], index: &str, base: &str) -> Router {
        let (tx, _rx) = broadcast::channel(8);
        let headers = headers.iter().map(|s| s.to_string()).collect::<Vec<_>>();
        app_build(AppState {
            dir: dir.to_path_buf(),
            tx,
            headers: headers_parse(&headers).unwrap(),
            index: index.to_string(),
            base: base_normalize(base).unwrap(),
        })
    }

    async fn get(app: &Router, uri: &str) -> (StatusCode, Vec<u8>) {
        let resp = app
            .clone()
            .oneshot(Request::builder().uri(uri).body(Body::empty()).unwrap())
            .await
            .unwrap();
        let status = resp.status();
        let bytes = resp.into_body().collect().await.unwrap().to_bytes();
        (status, bytes.to_vec())
    }

    fn html_write(dir: &Path, rel: &str, content: &str) {
        let full = dir.join(rel);
        create_dir_all(full.parent().unwrap()).unwrap();
        write(full, content).unwrap();
    }

    #[tokio::test]
    async fn serves_root_index_with_injected_script() {
        let dir = tempdir().unwrap();
        html_write(dir.path(), "index.html", "<html><body>hi</body></html>");
        let app = test_app(dir.path());
        let (status, body) = get(&app, "/").await;
        assert_eq!(status, 200);
        let html = String::from_utf8(body).unwrap();
        assert!(html.contains("hi"));
        assert!(html.contains("EventSource"));
        assert!(html.contains("EventSource('/livereload')"));
        assert!(html.contains("reload"));
    }

    #[tokio::test]
    async fn serves_nested_directory_index() {
        let dir = tempdir().unwrap();
        html_write(dir.path(), "sub/index.html", "<html>sub</html>");
        let app = test_app(dir.path());
        let (status, body) = get(&app, "/sub").await;
        assert_eq!(status, 200);
        assert!(String::from_utf8(body).unwrap().contains("sub"));
    }

    #[tokio::test]
    async fn missing_file_is_404() {
        let dir = tempdir().unwrap();
        let app = test_app(dir.path());
        let (status, _) = get(&app, "/nope.html").await;
        assert_eq!(status, 404);
    }

    #[tokio::test]
    async fn path_traversal_is_rejected() {
        let dir = tempdir().unwrap();
        html_write(dir.path(), "index.html", "<html></html>");
        let app = test_app(dir.path());
        let (status, _) = get(&app, "/../../etc/passwd").await;
        assert_eq!(status, 404);
    }

    #[tokio::test]
    async fn rooted_path_is_rejected() {
        let dir = tempdir().unwrap();
        html_write(dir.path(), "index.html", "<html></html>");

        // A file outside the docroot must never be served, even if `path`
        // is an absolute path as captured from `GET //<absolute>`.
        let outside = tempdir().unwrap();
        let secret = outside.path().join("secret.txt");
        write(&secret, "secret").unwrap();

        let resp = file_serve(dir.path(), secret.to_str().unwrap(), "index.html", "").await;
        assert_eq!(resp.status(), StatusCode::NOT_FOUND);
    }

    #[tokio::test]
    async fn parent_and_backslash_paths_are_rejected() {
        let dir = tempdir().unwrap();
        html_write(dir.path(), "index.html", "<html></html>");

        for path in [
            "../index.html",
            "sub/../../index.html",
            "sub\\..\\index.html",
        ] {
            let resp = file_serve(dir.path(), path, "index.html", "").await;
            assert_eq!(
                resp.status(),
                StatusCode::NOT_FOUND,
                "path `{path}` must be rejected"
            );
        }
    }

    #[tokio::test]
    async fn encoded_rooted_path_is_rejected() {
        let dir = tempdir().unwrap();
        html_write(dir.path(), "index.html", "<html></html>");
        let app = test_app(dir.path());

        for uri in ["/%2Fetc/passwd", "/%2e%2e/etc/passwd"] {
            let (status, _) = get(&app, uri).await;
            assert_eq!(status, 404, "uri `{uri}` must be rejected");
        }
    }

    #[tokio::test]
    async fn css_is_served_without_script() {
        let dir = tempdir().unwrap();
        html_write(dir.path(), "style.css", "body {}");
        let app = test_app(dir.path());
        let (status, body) = get(&app, "/style.css").await;
        assert_eq!(status, 200);
        assert_eq!(String::from_utf8(body).unwrap(), "body {}");
    }

    #[tokio::test]
    async fn non_utf8_html_is_served_raw() {
        let dir = tempdir().unwrap();
        let raw: Vec<u8> = vec![0xff, 0xfe, 0xfd];
        write(dir.path().join("index.html"), &raw).unwrap();
        let app = test_app(dir.path());
        let (status, body) = get(&app, "/").await;
        assert_eq!(status, 200);
        assert_eq!(body, raw);
    }

    #[tokio::test]
    async fn serves_under_base_prefix() {
        let dir = tempdir().unwrap();
        html_write(dir.path(), "index.html", "<html><body>hi</body></html>");
        html_write(dir.path(), "sub/index.html", "<html>sub</html>");
        let app = test_app_with_base(dir.path(), "/app");

        let (status, body) = get(&app, "/app/").await;
        assert_eq!(status, 200);
        let html = String::from_utf8(body).unwrap();
        assert!(html.contains("hi"));
        assert!(html.contains("EventSource('/app/livereload')"));

        let (status, body) = get(&app, "/app/sub").await;
        assert_eq!(status, 200);
        assert!(String::from_utf8(body).unwrap().contains("sub"));
    }

    #[tokio::test]
    async fn base_redirects_to_trailing_slash() {
        let dir = tempdir().unwrap();
        html_write(dir.path(), "index.html", "<html>hi</html>");
        let app = test_app_with_base(dir.path(), "/app");

        let resp = app
            .clone()
            .oneshot(Request::builder().uri("/app").body(Body::empty()).unwrap())
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::PERMANENT_REDIRECT);
        assert_eq!(resp.headers()["location"], "/app/");

        let resp = app
            .clone()
            .oneshot(
                Request::builder()
                    .uri("/app?x=1")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.headers()["location"], "/app/?x=1");
    }

    #[tokio::test]
    async fn base_does_not_serve_outside_prefix() {
        let dir = tempdir().unwrap();
        html_write(dir.path(), "index.html", "<html>hi</html>");
        html_write(dir.path(), "style.css", "body {}");
        let app = test_app_with_base(dir.path(), "/app");

        for uri in ["/", "/index.html", "/style.css", "/appfoo/", "/app2/"] {
            let (status, _) = get(&app, uri).await;
            assert_eq!(status, 404, "uri `{uri}` must be outside the base");
        }
    }

    #[tokio::test]
    async fn base_rejects_rooted_and_traversal_paths() {
        let dir = tempdir().unwrap();
        html_write(dir.path(), "index.html", "<html>hi</html>");
        let app = test_app_with_base(dir.path(), "/app");

        for uri in [
            "/app//etc/passwd",
            "/app/%2Fetc/passwd",
            "/app/%2e%2e/etc/passwd",
        ] {
            let (status, _) = get(&app, uri).await;
            assert_eq!(status, 404, "uri `{uri}` must be rejected");
        }
    }

    #[tokio::test]
    async fn base_serves_with_custom_headers() {
        let dir = tempdir().unwrap();
        html_write(dir.path(), "index.html", "<html>hi</html>");
        let app = test_app_full(dir.path(), &["X-Custom: yes"], "index.html", "/app");
        let headers = headers_get(&app, "/app/").await;
        assert_eq!(headers["X-Custom"], "yes");
    }

    #[tokio::test]
    async fn server_url_includes_base() {
        let dir = tempdir().unwrap();
        html_write(dir.path(), "index.html", "<html>hi</html>");
        let (tx, _rx) = broadcast::channel(8);
        let mut config = test_config(dir.path());
        config.base = "/app".into();
        let server = Server::bind(tx, config).await.unwrap();
        assert!(server.url.ends_with("/app"), "url: {}", server.url);
    }

    #[tokio::test]
    async fn invalid_base_is_rejected_at_bind() {
        let dir = tempdir().unwrap();
        let (tx, _rx) = broadcast::channel(8);
        let mut config = test_config(dir.path());
        config.base = "/{*x}".into();
        let err = Server::bind(tx, config).await.unwrap_err();
        assert!(err.contains("Invalid --base"), "error: {err}");
    }

    async fn headers_get(app: &Router, uri: &str) -> HeaderMap {
        let resp = app
            .clone()
            .oneshot(Request::builder().uri(uri).body(Body::empty()).unwrap())
            .await
            .unwrap();
        resp.into_parts().0.headers
    }

    #[tokio::test]
    async fn custom_header_is_applied_to_html() {
        let dir = tempdir().unwrap();
        html_write(dir.path(), "index.html", "<html>hi</html>");
        let app = test_app_with_headers(dir.path(), &["X-Custom: yes"]);
        let headers = headers_get(&app, "/").await;
        assert_eq!(headers["X-Custom"], "yes");
    }

    #[tokio::test]
    async fn custom_header_is_applied_to_static_file() {
        let dir = tempdir().unwrap();
        write(dir.path().join("app.js"), "let x = 1;").unwrap();
        let app = test_app_with_headers(dir.path(), &["X-Custom: yes"]);
        let headers = headers_get(&app, "/app.js").await;
        assert_eq!(headers["X-Custom"], "yes");
    }

    #[tokio::test]
    async fn multiple_custom_headers_are_all_applied() {
        let dir = tempdir().unwrap();
        html_write(dir.path(), "index.html", "<html>hi</html>");
        let app = test_app_with_headers(dir.path(), &["X-A: 1", "X-B: 2"]);
        let headers = headers_get(&app, "/").await;
        assert_eq!(headers["X-A"], "1");
        assert_eq!(headers["X-B"], "2");
    }

    #[tokio::test]
    async fn custom_header_overrides_existing_value() {
        let dir = tempdir().unwrap();
        html_write(dir.path(), "index.html", "<html>hi</html>");
        let app = test_app_with_headers(dir.path(), &["Cache-Control: max-age=60"]);
        let headers = headers_get(&app, "/").await;
        assert_eq!(headers["Cache-Control"], "max-age=60");
    }

    #[test]
    fn invalid_header_is_rejected() {
        assert!(headers_parse(&["Bad\nHeader: x".to_string()]).is_err());
        assert!(headers_parse(&["NoSeparator".to_string()]).is_err());
        assert!(headers_parse(&[": novalue".to_string()]).is_err());
        assert!(headers_parse(&["X-Foo:".to_string()]).is_ok());
    }

    fn test_config(dir: &Path) -> Config {
        Config {
            dir: dir.to_path_buf(),
            ip: IpAddr::from([127, 0, 0, 1]),
            port: 0,
            headers: vec![],
            index: "index.html".into(),
            base: String::new(),
        }
    }

    #[tokio::test]
    async fn server_bind_reports_real_port() {
        let dir = tempdir().unwrap();
        html_write(dir.path(), "index.html", "<html>hi</html>");
        let (tx, _rx) = broadcast::channel(8);
        let server = Server::bind(tx, test_config(dir.path())).await.unwrap();
        assert!(server.url.starts_with("http://127.0.0.1:"));
        assert!(!server.url.ends_with(":0"));
    }

    #[tokio::test]
    async fn custom_index_is_served_at_root() {
        let dir = tempdir().unwrap();
        html_write(dir.path(), "about.html", "<html>about</html>");
        let app = test_app_with_index(dir.path(), "about.html");
        let (status, body) = get(&app, "/").await;
        assert_eq!(status, 200);
        assert!(String::from_utf8(body).unwrap().contains("about"));
    }

    #[tokio::test]
    async fn custom_index_is_404_when_absent() {
        let dir = tempdir().unwrap();
        let app = test_app_with_index(dir.path(), "about.html");
        let (status, _) = get(&app, "/").await;
        assert_eq!(status, 404);
    }

    #[tokio::test]
    async fn custom_index_works_for_subdirectories() {
        let dir = tempdir().unwrap();
        html_write(dir.path(), "sub/about.html", "<html>sub about</html>");
        let app = test_app_with_index(dir.path(), "about.html");
        let (status, body) = get(&app, "/sub").await;
        assert_eq!(status, 200);
        assert!(String::from_utf8(body).unwrap().contains("sub about"));
    }

    #[tokio::test]
    async fn non_html_index_is_served_raw() {
        let dir = tempdir().unwrap();
        html_write(dir.path(), "index.md", "# readme");
        let app = test_app_with_index(dir.path(), "index.md");
        let (status, body) = get(&app, "/").await;
        assert_eq!(status, 200);
        assert_eq!(String::from_utf8(body).unwrap(), "# readme");
    }

    #[test]
    fn invalid_index_is_rejected() {
        assert!(index_validate("").is_err());
        assert!(index_validate(".").is_err());
        assert!(index_validate("..").is_err());
        assert!(index_validate("./x").is_err());
        assert!(index_validate("../x").is_err());
        assert!(index_validate("/etc/passwd").is_err());
        assert!(index_validate("a/b").is_err());
        assert!(index_validate("a\\b").is_err());
        assert!(index_validate(".hidden").is_err());
        assert!(index_validate("index.html").is_ok());
        assert!(index_validate("about.html").is_ok());
    }
}