zorto-webapp 0.22.0

HTMX CMS webapp for zorto
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
use std::sync::Arc;

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

use crate::{AppState, app};

/// Create a minimal zorto site structure in a tempdir and return (app, tmpdir).
fn test_app(tmp: &TempDir) -> axum::Router {
    let root = tmp.path().join("site");
    let content = root.join("content");
    let templates = root.join("templates");
    let static_dir = root.join("static");
    let output = root.join("public");

    std::fs::create_dir_all(&content).unwrap();
    std::fs::create_dir_all(content.join("posts")).unwrap();
    std::fs::create_dir_all(&templates).unwrap();
    std::fs::create_dir_all(&static_dir).unwrap();
    std::fs::create_dir_all(&output).unwrap();

    // Config
    std::fs::write(
        root.join("config.toml"),
        "base_url = \"https://example.com\"\ntitle = \"Test Site\"\n",
    )
    .unwrap();

    // Root section
    std::fs::write(
        content.join("_index.md"),
        "+++\ntitle = \"Home\"\n+++\nWelcome",
    )
    .unwrap();

    // Posts section
    std::fs::write(
        content.join("posts/_index.md"),
        "+++\ntitle = \"Blog\"\nsort_by = \"date\"\n+++\n",
    )
    .unwrap();

    // A page
    std::fs::write(
        content.join("posts/hello.md"),
        "+++\ntitle = \"Hello World\"\ndate = \"2025-01-01\"\n+++\nHello content",
    )
    .unwrap();

    // A draft page
    std::fs::write(
        content.join("posts/draft.md"),
        "+++\ntitle = \"Draft Post\"\ndraft = true\n+++\nDraft content",
    )
    .unwrap();

    // Templates
    std::fs::write(
        templates.join("base.html"),
        "<!DOCTYPE html><html><body>{% block content %}{% endblock %}</body></html>",
    )
    .unwrap();
    std::fs::write(
        templates.join("index.html"),
        r#"{% extends "base.html" %}{% block content %}{{ section.title }}{% endblock %}"#,
    )
    .unwrap();
    std::fs::write(
        templates.join("section.html"),
        r#"{% extends "base.html" %}{% block content %}{{ section.title }}{% endblock %}"#,
    )
    .unwrap();
    std::fs::write(
        templates.join("page.html"),
        r#"{% extends "base.html" %}{% block content %}{{ page.title }}{{ page.content | safe }}{% endblock %}"#,
    )
    .unwrap();

    // Static file
    std::fs::write(static_dir.join("style.css"), "body {}").unwrap();

    let (reload_tx, _) = broadcast::channel::<()>(16);
    let state = Arc::new(AppState {
        root,
        output_dir: output,
        sandbox: None,
        reload_tx,
    });

    app(state)
}

async fn get(app: &axum::Router, uri: &str) -> (StatusCode, String) {
    let req = Request::builder().uri(uri).body(Body::empty()).unwrap();
    let resp = app.clone().oneshot(req).await.unwrap();
    let status = resp.status();
    let body = resp.into_body().collect().await.unwrap().to_bytes();
    (status, String::from_utf8_lossy(&body).to_string())
}

async fn post_form(app: &axum::Router, uri: &str, body: &str) -> (StatusCode, String) {
    let req = Request::builder()
        .method("POST")
        .uri(uri)
        .header("content-type", "application/x-www-form-urlencoded")
        .body(Body::from(body.to_string()))
        .unwrap();
    let resp = app.clone().oneshot(req).await.unwrap();
    let status = resp.status();
    let body = resp.into_body().collect().await.unwrap().to_bytes();
    (status, String::from_utf8_lossy(&body).to_string())
}

async fn post_body(app: &axum::Router, uri: &str, body: &str) -> (StatusCode, String) {
    let req = Request::builder()
        .method("POST")
        .uri(uri)
        .header("content-type", "text/plain")
        .body(Body::from(body.to_string()))
        .unwrap();
    let resp = app.clone().oneshot(req).await.unwrap();
    let status = resp.status();
    let body = resp.into_body().collect().await.unwrap().to_bytes();
    (status, String::from_utf8_lossy(&body).to_string())
}

// ── Dashboard ──────────────────────────────────────────────────────

#[tokio::test]
async fn dashboard_returns_ok() {
    let tmp = TempDir::new().unwrap();
    let app = test_app(&tmp);
    let (status, body) = get(&app, "/").await;
    assert_eq!(status, StatusCode::OK);
    assert!(body.contains("Dashboard"));
    assert!(body.contains("Test Site"));
}

// ── Pages ──────────────────────────────────────────────────────────

#[tokio::test]
async fn page_list_shows_pages() {
    let tmp = TempDir::new().unwrap();
    let app = test_app(&tmp);
    let (status, body) = get(&app, "/pages").await;
    assert_eq!(status, StatusCode::OK);
    assert!(body.contains("Hello World"));
    assert!(body.contains("Draft Post"));
    assert!(body.contains("draft")); // draft badge
}

#[tokio::test]
async fn page_edit_returns_editor() {
    let tmp = TempDir::new().unwrap();
    let app = test_app(&tmp);
    let (status, body) = get(&app, "/pages/posts/hello.md").await;
    assert_eq!(status, StatusCode::OK);
    assert!(body.contains("Hello World"));
    assert!(body.contains("2025-01-01"));
    assert!(body.contains("Hello content"));
}

#[tokio::test]
async fn page_save_updates_file() {
    let tmp = TempDir::new().unwrap();
    let app = test_app(&tmp);

    let form = "title=Updated+Title&date=2025-06-01&description=new+desc&draft=false&tags=rust%2C+web&body=New+body+content&extra_frontmatter=";
    let (status, body) = post_form(&app, "/pages/posts/hello.md", form).await;
    assert_eq!(status, StatusCode::OK);
    assert!(body.contains("Updated Title"));

    // Verify file on disk
    let file = std::fs::read_to_string(tmp.path().join("site/content/posts/hello.md")).unwrap();
    assert!(file.contains("Updated Title"));
    assert!(file.contains("2025-06-01"));
    assert!(file.contains("New body content"));
    assert!(file.contains("rust"));
}

#[tokio::test]
async fn page_create_makes_new_file() {
    let tmp = TempDir::new().unwrap();
    let app = test_app(&tmp);

    let form = "title=My+New+Page&section=posts&date=2025-03-15&description=A+test&draft=false&tags=test&body=Some+content";
    let (status, _body) = post_form(&app, "/pages/new", form).await;
    // Should redirect (303 or 302)
    assert!(
        status == StatusCode::SEE_OTHER || status == StatusCode::FOUND,
        "expected redirect, got {status}"
    );

    // Verify file was created
    let file_path = tmp.path().join("site/content/posts/my-new-page.md");
    assert!(file_path.exists(), "new page file should exist");
    let content = std::fs::read_to_string(&file_path).unwrap();
    assert!(content.contains("My New Page"));
    assert!(content.contains("2025-03-15"));
    assert!(content.contains("Some content"));
}

#[tokio::test]
async fn page_create_as_draft() {
    let tmp = TempDir::new().unwrap();
    let app = test_app(&tmp);

    let form = "title=Draft+Page&section=posts&date=2025-03-15&description=&draft=true&tags=&body=Draft+body";
    let (status, _) = post_form(&app, "/pages/new", form).await;
    assert!(status == StatusCode::SEE_OTHER || status == StatusCode::FOUND);

    let file_path = tmp.path().join("site/content/posts/draft-page.md");
    let content = std::fs::read_to_string(&file_path).unwrap();
    assert!(content.contains("draft = true"));
}

#[tokio::test]
async fn page_delete_removes_file() {
    let tmp = TempDir::new().unwrap();
    let app = test_app(&tmp);

    let file = tmp.path().join("site/content/posts/hello.md");
    assert!(file.exists());

    let (status, _) = post_form(&app, "/pages/delete/posts/hello.md", "").await;
    assert!(
        status == StatusCode::SEE_OTHER || status == StatusCode::FOUND,
        "expected redirect, got {status}"
    );
    assert!(!file.exists(), "file should be deleted");
}

#[tokio::test]
async fn page_list_excludes_index_files() {
    let tmp = TempDir::new().unwrap();
    let app = test_app(&tmp);
    let (_, body) = get(&app, "/pages").await;
    // _index.md files should not appear in the page list
    assert!(!body.contains("_index.md"));
}

// ── Page path traversal defense ────────────────────────────────────

#[tokio::test]
async fn page_edit_traversal_blocked() {
    let tmp = TempDir::new().unwrap();
    let app = test_app(&tmp);

    // Attempt to read /etc/passwd via traversal
    let (status, body) = get(&app, "/pages/../../etc/passwd").await;
    assert_eq!(status, StatusCode::OK); // returns error page, not 500
    assert!(body.contains("Invalid path"));
}

#[tokio::test]
async fn page_save_traversal_blocked() {
    let tmp = TempDir::new().unwrap();
    let app = test_app(&tmp);

    let form = "title=Hacked&date=&description=&draft=false&tags=&body=pwned&extra_frontmatter=";
    let (status, body) = post_form(&app, "/pages/../../etc/evil.md", form).await;
    assert_eq!(status, StatusCode::OK);
    assert!(body.contains("Invalid path"));
}

#[tokio::test]
async fn page_delete_traversal_blocked() {
    let tmp = TempDir::new().unwrap();
    let app = test_app(&tmp);

    // Create a file outside content dir to ensure it survives
    let outside = tmp.path().join("site/outside.txt");
    std::fs::write(&outside, "safe").unwrap();

    let (status, _) = post_form(&app, "/pages/delete/../../outside.txt", "").await;
    // Should redirect without deleting
    assert!(status == StatusCode::SEE_OTHER || status == StatusCode::FOUND);
    assert!(
        outside.exists(),
        "file outside content dir must not be deleted"
    );
}

#[tokio::test]
async fn page_create_traversal_in_section_blocked() {
    let tmp = TempDir::new().unwrap();
    let app = test_app(&tmp);

    let form = "title=Evil&section=../../etc&date=&description=&draft=false&tags=&body=pwned";
    let (status, _) = post_form(&app, "/pages/new", form).await;
    // Should redirect to /pages without creating file outside content
    assert!(status == StatusCode::SEE_OTHER || status == StatusCode::FOUND);

    // Ensure no file was created outside content dir
    assert!(
        !tmp.path().join("etc").exists(),
        "traversal should not create dirs outside site"
    );
}

// ── Sections ───────────────────────────────────────────────────────

#[tokio::test]
async fn section_list_shows_sections() {
    let tmp = TempDir::new().unwrap();
    let app = test_app(&tmp);
    let (status, body) = get(&app, "/sections").await;
    assert_eq!(status, StatusCode::OK);
    assert!(body.contains("Blog")); // posts section title
    assert!(body.contains("Home")); // root section title
}

#[tokio::test]
async fn section_list_shows_page_counts() {
    let tmp = TempDir::new().unwrap();
    let app = test_app(&tmp);
    let (_, body) = get(&app, "/sections").await;
    // posts/ has hello.md and draft.md = 2 pages
    assert!(body.contains("2 pages"));
}

#[tokio::test]
async fn section_edit_returns_editor() {
    let tmp = TempDir::new().unwrap();
    let app = test_app(&tmp);
    let (status, body) = get(&app, "/sections/posts/_index.md").await;
    assert_eq!(status, StatusCode::OK);
    assert!(body.contains("Blog"));
    assert!(body.contains("sort_by") || body.contains("Sort By"));
}

#[tokio::test]
async fn section_save_updates_file() {
    let tmp = TempDir::new().unwrap();
    let app = test_app(&tmp);

    let form = "title=Updated+Blog&description=My+blog&sort_by=title&paginate_by=5&body=Section+body&extra_frontmatter=";
    let (status, body) = post_form(&app, "/sections/posts/_index.md", form).await;
    assert_eq!(status, StatusCode::OK);
    assert!(body.contains("Updated Blog"));

    let file = std::fs::read_to_string(tmp.path().join("site/content/posts/_index.md")).unwrap();
    assert!(file.contains("Updated Blog"));
    assert!(file.contains("sort_by = \"title\""));
    assert!(file.contains("paginate_by = 5"));
    assert!(file.contains("Section body"));
}

#[tokio::test]
async fn section_edit_traversal_blocked() {
    let tmp = TempDir::new().unwrap();
    let app = test_app(&tmp);
    let (status, body) = get(&app, "/sections/../../etc/passwd").await;
    assert_eq!(status, StatusCode::OK);
    assert!(body.contains("Invalid path"));
}

#[tokio::test]
async fn section_save_traversal_blocked() {
    let tmp = TempDir::new().unwrap();
    let app = test_app(&tmp);

    let form = "title=Evil&description=&sort_by=date&paginate_by=&body=pwned&extra_frontmatter=";
    let (status, body) = post_form(&app, "/sections/../../etc/evil", form).await;
    assert_eq!(status, StatusCode::OK);
    assert!(body.contains("Invalid path"));
}

// ── Assets ─────────────────────────────────────────────────────────

#[tokio::test]
async fn asset_list_shows_files() {
    let tmp = TempDir::new().unwrap();
    let app = test_app(&tmp);
    let (status, body) = get(&app, "/assets").await;
    assert_eq!(status, StatusCode::OK);
    assert!(body.contains("style.css"));
}

#[tokio::test]
async fn asset_upload_saves_file() {
    let tmp = TempDir::new().unwrap();
    let app = test_app(&tmp);

    let boundary = "----TestBoundary123";
    let body = format!(
        "--{boundary}\r\n\
         Content-Disposition: form-data; name=\"subdir\"\r\n\r\n\
         \r\n\
         --{boundary}\r\n\
         Content-Disposition: form-data; name=\"file\"; filename=\"test.txt\"\r\n\
         Content-Type: text/plain\r\n\r\n\
         hello world\r\n\
         --{boundary}--\r\n"
    );

    let req = Request::builder()
        .method("POST")
        .uri("/assets/upload")
        .header(
            "content-type",
            format!("multipart/form-data; boundary={boundary}"),
        )
        .body(Body::from(body))
        .unwrap();
    let resp = app.clone().oneshot(req).await.unwrap();
    assert_eq!(resp.status(), StatusCode::OK);

    let uploaded = tmp.path().join("site/static/test.txt");
    assert!(uploaded.exists(), "uploaded file should exist");
    assert_eq!(std::fs::read_to_string(&uploaded).unwrap(), "hello world");
}

#[tokio::test]
async fn asset_upload_with_subdir() {
    let tmp = TempDir::new().unwrap();
    let app = test_app(&tmp);

    let boundary = "----TestBoundary456";
    let body = format!(
        "--{boundary}\r\n\
         Content-Disposition: form-data; name=\"subdir\"\r\n\r\n\
         img\r\n\
         --{boundary}\r\n\
         Content-Disposition: form-data; name=\"file\"; filename=\"logo.png\"\r\n\
         Content-Type: image/png\r\n\r\n\
         PNG_DATA\r\n\
         --{boundary}--\r\n"
    );

    let req = Request::builder()
        .method("POST")
        .uri("/assets/upload")
        .header(
            "content-type",
            format!("multipart/form-data; boundary={boundary}"),
        )
        .body(Body::from(body))
        .unwrap();
    let resp = app.clone().oneshot(req).await.unwrap();
    assert_eq!(resp.status(), StatusCode::OK);

    let uploaded = tmp.path().join("site/static/img/logo.png");
    assert!(uploaded.exists(), "uploaded file in subdir should exist");
}

#[tokio::test]
async fn asset_upload_traversal_in_subdir_blocked() {
    let tmp = TempDir::new().unwrap();
    let app = test_app(&tmp);

    let boundary = "----TestBoundary789";
    let body = format!(
        "--{boundary}\r\n\
         Content-Disposition: form-data; name=\"subdir\"\r\n\r\n\
         ../../etc\r\n\
         --{boundary}\r\n\
         Content-Disposition: form-data; name=\"file\"; filename=\"evil.txt\"\r\n\
         Content-Type: text/plain\r\n\r\n\
         pwned\r\n\
         --{boundary}--\r\n"
    );

    let req = Request::builder()
        .method("POST")
        .uri("/assets/upload")
        .header(
            "content-type",
            format!("multipart/form-data; boundary={boundary}"),
        )
        .body(Body::from(body))
        .unwrap();
    let resp = app.clone().oneshot(req).await.unwrap();
    let resp_body = resp.into_body().collect().await.unwrap().to_bytes();
    let resp_str = String::from_utf8_lossy(&resp_body);
    assert!(
        resp_str.contains("Upload error") || resp_str.contains("Invalid"),
        "traversal in subdir should be rejected"
    );

    assert!(
        !tmp.path().join("etc/evil.txt").exists(),
        "file must not be written outside static dir"
    );
}

#[tokio::test]
async fn asset_upload_traversal_in_filename_blocked() {
    let tmp = TempDir::new().unwrap();
    let app = test_app(&tmp);

    let boundary = "----TestBoundaryABC";
    let body = format!(
        "--{boundary}\r\n\
         Content-Disposition: form-data; name=\"subdir\"\r\n\r\n\
         \r\n\
         --{boundary}\r\n\
         Content-Disposition: form-data; name=\"file\"; filename=\"../evil.txt\"\r\n\
         Content-Type: text/plain\r\n\r\n\
         pwned\r\n\
         --{boundary}--\r\n"
    );

    let req = Request::builder()
        .method("POST")
        .uri("/assets/upload")
        .header(
            "content-type",
            format!("multipart/form-data; boundary={boundary}"),
        )
        .body(Body::from(body))
        .unwrap();
    let resp = app.clone().oneshot(req).await.unwrap();
    let resp_body = resp.into_body().collect().await.unwrap().to_bytes();
    let resp_str = String::from_utf8_lossy(&resp_body);
    assert!(
        resp_str.contains("Invalid filename") || resp_str.contains("Upload error"),
        "traversal in filename should be rejected"
    );
}

// ── Config ─────────────────────────────────────────────────────────

#[tokio::test]
async fn config_edit_shows_config() {
    let tmp = TempDir::new().unwrap();
    let app = test_app(&tmp);
    let (status, body) = get(&app, "/config").await;
    assert_eq!(status, StatusCode::OK);
    assert!(body.contains("base_url"));
    assert!(body.contains("https://example.com"));
}

#[tokio::test]
async fn config_save_valid_toml() {
    let tmp = TempDir::new().unwrap();
    let app = test_app(&tmp);

    let new_config =
        "content=base_url+%3D+%22https%3A%2F%2Fnew.example.com%22%0Atitle+%3D+%22New+Title%22%0A";
    let (status, _body) = post_form(&app, "/config", new_config).await;
    assert_eq!(status, StatusCode::OK);

    let file = std::fs::read_to_string(tmp.path().join("site/config.toml")).unwrap();
    assert!(file.contains("new.example.com"));
}

#[tokio::test]
async fn config_save_invalid_toml_rejected() {
    let tmp = TempDir::new().unwrap();
    let app = test_app(&tmp);

    // Send invalid TOML
    let bad_config = "content=%5Binvalid+toml";
    let (status, body) = post_form(&app, "/config", bad_config).await;
    assert_eq!(status, StatusCode::OK);
    assert!(body.contains("error") || body.contains("Error"));

    // Original config should be preserved
    let file = std::fs::read_to_string(tmp.path().join("site/config.toml")).unwrap();
    assert!(file.contains("https://example.com"));
}

// ── Build ──────────────────────────────────────────────────────────

#[tokio::test]
async fn build_trigger_succeeds() {
    let tmp = TempDir::new().unwrap();
    let app = test_app(&tmp);
    let (status, body) = post_form(&app, "/build", "").await;
    assert_eq!(status, StatusCode::OK);
    assert!(body.contains("Built successfully"));
}

// ── Preview rendering ──────────────────────────────────────────────

#[tokio::test]
async fn preview_renders_markdown() {
    let tmp = TempDir::new().unwrap();
    let app = test_app(&tmp);
    let (status, body) = post_body(&app, "/preview/render", "# Hello\n\nWorld").await;
    assert_eq!(status, StatusCode::OK, "body: {body}");
    assert!(body.contains("<h1"), "expected <h1 in: {body}");
    assert!(body.contains("Hello"));
    assert!(body.contains("World"));
}

#[tokio::test]
async fn preview_strips_frontmatter() {
    let tmp = TempDir::new().unwrap();
    let app = test_app(&tmp);
    let content = "+++\ntitle = \"Test\"\n+++\n# Heading\n\nBody text";
    let (status, body) = post_body(&app, "/preview/render", content).await;
    assert_eq!(status, StatusCode::OK);
    assert!(body.contains("<h1"), "expected <h1 in: {body}");
    assert!(body.contains("Heading"));
    assert!(body.contains("Body text"));
    // Frontmatter should not appear in rendered output
    assert!(!body.contains("title = "));
}

// ── New page form ──────────────────────────────────────────────────

#[tokio::test]
async fn new_page_form_lists_sections() {
    let tmp = TempDir::new().unwrap();
    let app = test_app(&tmp);
    let (status, body) = get(&app, "/pages/new").await;
    assert_eq!(status, StatusCode::OK);
    assert!(body.contains("posts")); // section option
    assert!(body.contains("(root)")); // root option
}

// ── Page create at root ────────────────────────────────────────────

#[tokio::test]
async fn page_create_at_root_section() {
    let tmp = TempDir::new().unwrap();
    let app = test_app(&tmp);

    let form =
        "title=About+Me&section=&date=2025-01-01&description=&draft=false&tags=&body=About+page";
    let (status, _) = post_form(&app, "/pages/new", form).await;
    assert!(status == StatusCode::SEE_OTHER || status == StatusCode::FOUND);

    let file_path = tmp.path().join("site/content/about-me.md");
    assert!(file_path.exists(), "root page should be created");
    let content = std::fs::read_to_string(&file_path).unwrap();
    assert!(content.contains("About Me"));
}

// ── Page save preserves extra frontmatter ──────────────────────────

#[tokio::test]
async fn page_save_preserves_extra_frontmatter() {
    let tmp = TempDir::new().unwrap();
    let app = test_app(&tmp);

    let form = "title=Hello+World&date=2025-01-01&description=&draft=false&tags=&body=Updated&extra_frontmatter=custom_key+%3D+%22value%22%0A";
    let (status, _) = post_form(&app, "/pages/posts/hello.md", form).await;
    assert_eq!(status, StatusCode::OK);

    let file = std::fs::read_to_string(tmp.path().join("site/content/posts/hello.md")).unwrap();
    assert!(file.contains("custom_key = \"value\""));
}

// ── Section save preserves extra frontmatter ───────────────────────

#[tokio::test]
async fn section_save_preserves_extra_frontmatter() {
    let tmp = TempDir::new().unwrap();
    let app = test_app(&tmp);

    let form = "title=Blog&description=&sort_by=date&paginate_by=&body=&extra_frontmatter=template+%3D+%22custom.html%22%0A";
    let (status, _) = post_form(&app, "/sections/posts/_index.md", form).await;
    assert_eq!(status, StatusCode::OK);

    let file = std::fs::read_to_string(tmp.path().join("site/content/posts/_index.md")).unwrap();
    assert!(file.contains("template = \"custom.html\""));
}

// ── Onboarding ────────────────────────────────────────────────────

#[tokio::test]
async fn dashboard_redirects_when_no_site() {
    let tmp = TempDir::new().unwrap();
    // Create an app with no config.toml — empty dir
    let root = tmp.path().join("empty");
    std::fs::create_dir_all(&root).unwrap();
    let output = root.join("public");
    std::fs::create_dir_all(&output).unwrap();

    let (reload_tx, _) = broadcast::channel::<()>(16);
    let state = Arc::new(AppState {
        root,
        output_dir: output,
        sandbox: None,
        reload_tx,
    });
    let app = app(state);

    let (status, _) = get(&app, "/").await;
    // Should redirect to /setup
    assert!(
        status == StatusCode::SEE_OTHER || status == StatusCode::FOUND,
        "expected redirect to setup, got {status}"
    );
}

#[tokio::test]
async fn setup_welcome_returns_ok() {
    let tmp = TempDir::new().unwrap();
    let root = tmp.path().join("empty");
    std::fs::create_dir_all(&root).unwrap();
    let output = root.join("public");
    std::fs::create_dir_all(&output).unwrap();

    let (reload_tx, _) = broadcast::channel::<()>(16);
    let state = Arc::new(AppState {
        root,
        output_dir: output,
        sandbox: None,
        reload_tx,
    });
    let app = app(state);

    let (status, body) = get(&app, "/setup").await;
    assert_eq!(status, StatusCode::OK);
    assert!(body.contains("Create your site"));
}

#[tokio::test]
async fn setup_template_page_returns_ok() {
    let tmp = TempDir::new().unwrap();
    let root = tmp.path().join("empty");
    std::fs::create_dir_all(&root).unwrap();
    let output = root.join("public");
    std::fs::create_dir_all(&output).unwrap();

    let (reload_tx, _) = broadcast::channel::<()>(16);
    let state = Arc::new(AppState {
        root,
        output_dir: output,
        sandbox: None,
        reload_tx,
    });
    let app = app(state);

    let (status, body) = get(&app, "/setup/template").await;
    assert_eq!(status, StatusCode::OK);
    assert!(body.contains("Choose a template"));
    assert!(body.contains("blog"));
    assert!(body.contains("docs"));
}

// ── Asset delete ──────────────────────────────────────────────────

#[tokio::test]
async fn asset_delete_removes_file() {
    let tmp = TempDir::new().unwrap();
    let app = test_app(&tmp);

    let file = tmp.path().join("site/static/style.css");
    assert!(file.exists());

    let (status, body) = post_form(&app, "/assets/delete", "path=style.css").await;
    assert_eq!(status, StatusCode::OK);
    assert!(body.contains("File deleted"));
    assert!(!file.exists(), "file should be deleted");
}

#[tokio::test]
async fn asset_delete_traversal_blocked() {
    let tmp = TempDir::new().unwrap();
    let app = test_app(&tmp);

    // Try to delete a file outside static dir
    let outside = tmp.path().join("site/config.toml");
    assert!(outside.exists());

    let (status, body) = post_form(&app, "/assets/delete", "path=../config.toml").await;
    assert_eq!(status, StatusCode::OK);
    assert!(
        body.contains("Invalid path") || body.contains("error"),
        "traversal should be blocked"
    );
    assert!(outside.exists(), "config.toml must not be deleted");
}

// ── HTMX served from webapp ──────────────────────────────────────

#[tokio::test]
async fn htmx_js_served() {
    let tmp = TempDir::new().unwrap();
    let app = test_app(&tmp);

    let (status, body) = get(&app, "/static/htmx.min.js").await;
    assert_eq!(status, StatusCode::OK);
    assert!(body.contains("htmx"), "should serve htmx library");
}

// ── Dashboard with welcome ────────────────────────────────────────

#[tokio::test]
async fn dashboard_shows_welcome_flash() {
    let tmp = TempDir::new().unwrap();
    let app = test_app(&tmp);

    let (status, body) = get(&app, "/?welcome=1").await;
    assert_eq!(status, StatusCode::OK);
    assert!(body.contains("Site created successfully"));
}

#[tokio::test]
async fn dashboard_shows_recent_pages() {
    let tmp = TempDir::new().unwrap();
    let app = test_app(&tmp);

    let (status, body) = get(&app, "/").await;
    assert_eq!(status, StatusCode::OK);
    assert!(body.contains("Recent Pages"));
    assert!(body.contains("Hello World"));
}

// ── Config visual mode ────────────────────────────────────────────

#[tokio::test]
async fn config_shows_visual_form() {
    let tmp = TempDir::new().unwrap();
    let app = test_app(&tmp);

    let (status, body) = get(&app, "/config").await;
    assert_eq!(status, StatusCode::OK);
    assert!(body.contains("Settings"));
    assert!(body.contains("Theme"));
    assert!(body.contains("Raw Config"));
}

// ── Validation & error path coverage ─────────────────────────────

#[tokio::test]
async fn page_create_empty_title_rejected() {
    let tmp = TempDir::new().unwrap();
    let app = test_app(&tmp);

    let form =
        "title=&section=posts&date=2025-03-15&description=&draft=false&tags=&body=Some+content";
    let (status, body) = post_form(&app, "/pages/new", form).await;
    // Should NOT redirect — should return an error page
    assert_eq!(status, StatusCode::OK);
    assert!(
        body.contains("Title is required"),
        "expected title validation error in: {body}"
    );
}

#[tokio::test]
async fn page_edit_nonexistent_returns_empty_editor() {
    let tmp = TempDir::new().unwrap();
    let app = test_app(&tmp);

    // Request a page that doesn't exist on disk
    let (status, body) = get(&app, "/pages/posts/does-not-exist.md").await;
    assert_eq!(status, StatusCode::OK);
    // Should return the editor (with empty content), not panic
    assert!(body.contains("Edit:"), "expected editor page, got: {body}");
}

#[tokio::test]
async fn preview_render_empty_body() {
    let tmp = TempDir::new().unwrap();
    let app = test_app(&tmp);

    let (status, body) = post_body(&app, "/preview/render", "").await;
    assert_eq!(status, StatusCode::OK);
    // Empty input should produce empty (or minimal) output, not error
    assert!(
        !body.contains("panic") && !body.contains("500"),
        "empty preview should not error: {body}"
    );
}

#[tokio::test]
async fn config_save_visual_mode_updates_fields() {
    let tmp = TempDir::new().unwrap();
    let app = test_app(&tmp);

    let form = "mode=visual&content=&title=New+Title&base_url=https%3A%2F%2Fnew.example.com&description=A+great+site&theme=ocean&generate_feed=true&generate_sitemap=true";
    let (status, body) = post_form(&app, "/config", form).await;
    assert_eq!(status, StatusCode::OK);
    assert!(
        body.contains("saved") || body.contains("success") || body.contains("New Title"),
        "expected success feedback: {body}"
    );

    let file = std::fs::read_to_string(tmp.path().join("site/config.toml")).unwrap();
    assert!(file.contains("New Title"), "title should be updated");
    assert!(
        file.contains("new.example.com"),
        "base_url should be updated"
    );
    assert!(file.contains("ocean"), "theme should be set");
    assert!(
        file.contains("generate_feed = true"),
        "feed flag should be set"
    );
}