csaf-crud 1.5.26

CSAF 2.0 / 2.1 advisory CRUD server with HATEOAS JSON API and HTML UI (TLS 1.3, HTTP/1.1 + HTTP/2 + HTTP/3)
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
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
// SPDX-License-Identifier: Apache-2.0
// Copyright (c) 2026 Pierre Gronau, ndaal in Cologne

//! Shared HTML layout for all server-side rendered pages.
//!
//! Provides a single `wrap_page()` function so that branding, theme handling,
//! and navigation markup live in one place.

use crate::i18n::{Lang, t};
use crate::routes::ui::{ASSET_VERSION, icon};

/// Per-request rendering context: theme choice and language.
///
/// Resolved once per request and needed by every `wrap_page` call, so they
/// travel together as one argument rather than as two more positional
/// parameters (the project's own >4-parameter threshold: see
/// `skills/code-quality`, Pattern 3 "Options Object").
#[derive(Debug, Clone, Copy)]
pub struct PageContext<'a> {
    /// `"system"`, `"light"` or `"dark"`: the visitor's cookie, else the
    /// settings default (see [`theme_for`]).
    pub theme: &'a str,
    /// The resolved UI language for this request.
    pub lang: Lang,
}

/// Active navigation section, used to highlight the current menu entry.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Nav {
    /// Dashboard / root page.
    Home,
    /// CSAF document CRUD pages.
    Csaf,
    /// Administration → Import page.
    Import,
    /// Administration → Export page.
    Export,
    /// Settings page.
    Settings,
    /// Info (About/License/System/Privacy/Security) pages.
    Info,
}

impl Nav {
    /// The icon shown before the page title of this section.
    const fn title_icon(self) -> &'static str {
        match self {
            Self::Home => "speedometer2",
            Self::Csaf => "file-earmark-text",
            Self::Import => "box-arrow-in-down",
            Self::Export => "box-arrow-up",
            Self::Settings => "sliders",
            Self::Info => "info-circle",
        }
    }

    const fn as_str(self) -> &'static str {
        match self {
            Self::Home => "home",
            Self::Csaf => "csaf",
            Self::Import => "import",
            Self::Export => "export",
            Self::Settings => "settings",
            Self::Info => "info",
        }
    }
}

/// Cookie holding the visitor's theme choice (`system`, `light` or `dark`).
///
/// Not `HttpOnly`: `csaf-ui.js` writes it when a theme is picked, so the
/// choice applies at once without a round trip.
pub const THEME_COOKIE: &str = "csaf_theme";

/// The theme a visitor can choose.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ThemeChoice {
    /// Follow the operating system (`prefers-color-scheme`).
    System,
    /// Always light.
    Light,
    /// Always dark.
    Dark,
}

impl ThemeChoice {
    /// The value stored in the cookie and carried in `PageContext::theme`.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::System => "system",
            Self::Light => "light",
            Self::Dark => "dark",
        }
    }

    /// Parse a stored or submitted value; anything unknown is rejected.
    #[must_use]
    pub fn from_value(value: &str) -> Option<Self> {
        match value {
            "system" => Some(Self::System),
            "light" => Some(Self::Light),
            "dark" => Some(Self::Dark),
            _ => None,
        }
    }
}

/// Find the `csaf_theme` choice in a `Cookie` header value.
fn theme_from_cookie(header: &str) -> Option<ThemeChoice> {
    header.split(';').find_map(|pair| {
        let (name, value) = pair.split_once('=')?;
        (name.trim() == THEME_COOKIE).then(|| ThemeChoice::from_value(value.trim()))?
    })
}

/// Resolve the theme for one request.
///
/// The visitor's own cookie wins. Without one, the server default from the
/// settings applies (`light`, `dark` or `system`; anything else is `light`,
/// the historical default). The result feeds [`PageContext::theme`].
#[must_use]
pub fn theme_for(parts: &http::request::Parts, default_theme: &str) -> &'static str {
    // HTTP/2 clients may send each cookie pair as its own `cookie` field
    // (RFC 9113 §8.2.3), so the choice can sit in any of them, not only the
    // first. The language resolver reads every field for the same reason.
    let from_cookie = parts
        .headers
        .get_all(http::header::COOKIE)
        .iter()
        .filter_map(|value| value.to_str().ok())
        .find_map(theme_from_cookie);
    from_cookie
        .or_else(|| ThemeChoice::from_value(default_theme))
        .unwrap_or(ThemeChoice::Light)
        .as_str()
}

/// Render the Language control's dropdown: one link per [`Lang::all`] entry.
///
/// Extracted out of `wrap_page` to keep that function's line count down;
/// iterates the language list rather than hand-writing links, so a new
/// language needs no change here. The markup stays a flat loop — the
/// columns-of-ten desktop layout lives entirely in the `.lang-menu` CSS
/// (`static/css/csaf-ui.css`). Each link carries its own `lang`/`hreflang` so
/// assistive tech announces every endonym in its own language
/// (`skills/ndaal-design` §12.4).
fn language_switcher(lang: Lang) -> String {
    use std::fmt::Write as _;

    let items = Lang::all()
        .into_iter()
        .fold(String::new(), |mut acc, choice| {
            let current = if choice == lang {
                r#" aria-current="true""#
            } else {
                ""
            };
            let _ = writeln!(
                acc,
                r#"      <a href="/lang/{code}" lang="{code}" hreflang="{code}" class="menu-link"{current}>{endonym}</a>"#,
                code = choice.code(),
                endonym = choice.endonym(),
            );
            acc
        });
    format!(
        r#"  <details class="nav-dropdown">
    <summary class="menu-summary">{globe}<span>{label}</span>{caret}</summary>
    <div class="dropdown-menu dropdown-menu-end lang-menu">
{items}    </div>
  </details>
"#,
        globe = icon("translate"),
        caret = icon("chevron-down"),
        label = t(lang, "nav.language"),
    )
}

/// One header page link: the `Nav` key it highlights for, its target and its
/// translation key.
struct NavEntry {
    key: &'static str,
    href: &'static str,
    label_key: &'static str,
    icon: &'static str,
}

/// The four primary page links, in header order.
const PAGE_LINKS: [NavEntry; 4] = [
    NavEntry {
        key: "home",
        href: "/",
        label_key: "nav.dashboard",
        icon: "house",
    },
    NavEntry {
        key: "csaf",
        href: "/csaf",
        label_key: "nav.csaf",
        icon: "file-earmark-text",
    },
    NavEntry {
        key: "import",
        href: "/admin/import",
        label_key: "nav.import",
        icon: "box-arrow-in-down",
    },
    NavEntry {
        key: "export",
        href: "/admin/export",
        label_key: "nav.export",
        icon: "box-arrow-up",
    },
];

/// Settings stays a link to its full page, first in the control cluster.
const SETTINGS_LINK: NavEntry = NavEntry {
    key: "settings",
    href: "/settings",
    label_key: "nav.settings",
    icon: "gear",
};

/// One header link, marked `aria-current="page"` when it is the active page.
fn nav_link(lang: Lang, active_key: &str, entry: &NavEntry) -> String {
    let current = if active_key == entry.key {
        r#" aria-current="page""#
    } else {
        ""
    };
    format!(
        "  <a href=\"{href}\" class=\"nav-link\"{current}>{icon}<span>{label}</span></a>\n",
        href = entry.href,
        icon = icon(entry.icon),
        label = t(lang, entry.label_key),
    )
}

/// Render the four primary page links (Dashboard/CSAF/Import/Export).
fn nav_links(lang: Lang, active_key: &str) -> String {
    PAGE_LINKS
        .iter()
        .map(|entry| nav_link(lang, active_key, entry))
        .collect()
}

/// Render the Theme control: a three-way choice that works without
/// JavaScript (it posts to `/preferences/theme`); `csaf-ui.js` applies the
/// choice on change and removes the then-redundant button.
fn theme_menu(lang: Lang, theme: &str) -> String {
    let radio = |value: &str, label_key: &'static str, icon_name: &'static str| {
        let checked = if theme == value { " checked" } else { "" };
        format!(
            r#"          <label class="check-row" for="theme-{value}"><input type="radio" id="theme-{value}" name="theme" value="{value}"{checked}> {icon}<span>{label}</span></label>
"#,
            icon = icon(icon_name),
            label = t(lang, label_key),
        )
    };
    format!(
        r#"  <details class="nav-dropdown">
    <summary class="menu-summary">{theme_icon}<span>{label}</span>{caret}</summary>
    <div class="dropdown-menu dropdown-menu-end">
      <form method="post" action="/preferences/theme" class="theme-form">
        <fieldset class="theme-fieldset">
          <legend class="theme-legend">{label}</legend>
{system}{light}{dark}        </fieldset>
        <button type="submit" class="btn theme-apply">{apply}</button>
      </form>
    </div>
  </details>
"#,
        theme_icon = icon("circle-half"),
        caret = icon("chevron-down"),
        label = t(lang, "nav.theme"),
        system = radio("system", "nav.theme_system", "circle-half"),
        light = radio("light", "nav.theme_light", "sun"),
        dark = radio("dark", "nav.theme_dark", "moon"),
        apply = t(lang, "nav.theme_apply"),
    )
}

/// Render the Info control's dropdown (About/License/System/.../User Guide).
fn info_menu(lang: Lang, active_key: &str) -> String {
    let current = if active_key == "info" {
        r#" aria-current="page""#
    } else {
        ""
    };
    format!(
        r#"  <details class="nav-dropdown">
    <summary class="menu-summary"{current}>{info_icon}<span>{nav_info}</span>{caret}</summary>
    <div class="dropdown-menu dropdown-menu-end">
      <a href="/info/about" class="menu-link">{info_about}</a>
      <a href="/info/license" class="menu-link">{info_license}</a>
      <a href="/info/system" class="menu-link">{info_system}</a>
      <a href="/info/privacy" class="menu-link">{info_privacy}</a>
      <a href="/info/security" class="menu-link">{info_security}</a>
      <hr class="dropdown-divider">
      <a href="/changelog" class="menu-link">{info_changelog}</a>
      <a href="/readme" class="menu-link">{info_readme}</a>
      <a href="/administrator" class="menu-link">{info_administrator}</a>
      <a href="/user" class="menu-link">{info_user}</a>
    </div>
  </details>
"#,
        info_icon = icon("info-circle"),
        caret = icon("chevron-down"),
        nav_info = t(lang, "nav.info"),
        info_about = t(lang, "nav.info_about"),
        info_license = t(lang, "nav.info_license"),
        info_system = t(lang, "nav.info_system"),
        info_privacy = t(lang, "nav.info_privacy"),
        info_security = t(lang, "nav.info_security"),
        info_changelog = t(lang, "nav.info_changelog"),
        info_readme = t(lang, "nav.info_readme"),
        info_administrator = t(lang, "nav.info_administrator"),
        info_user = t(lang, "nav.info_user"),
    )
}

/// The shared confirmation dialog `csaf-ui.js` opens for `data-confirm` forms.
///
/// Closed (and therefore invisible) until the script calls `showModal()`, so
/// without JavaScript a destructive form simply submits, as it always did.
fn confirm_dialog(lang: Lang) -> String {
    format!(
        r#"<dialog id="confirm-dialog" class="confirm-dialog" aria-labelledby="confirm-dialog-message">
  <form method="dialog" class="confirm-form">
    <p id="confirm-dialog-message" class="confirm-message">{message}</p>
    <div class="confirm-actions">
      <button type="submit" value="cancel" class="btn secondary">{cancel}</button>
      <button type="submit" value="confirm" class="btn danger confirm-ok">{ok}</button>
    </div>
  </form>
</dialog>
"#,
        message = t(lang, "ui.confirm_message"),
        cancel = t(lang, "csaf.form_cancel"),
        ok = t(lang, "ui.confirm_ok"),
    )
}

/// The stylesheet `<link>` tags every page loads, in cascade order.
///
/// Tokens first, then the product's token layer, then element defaults, then
/// components. The one script follows the page content (see `wrap_page`). No
/// inline `<style>` or `<script>` exists: the response carries a
/// Content-Security-Policy without `unsafe-inline`.
fn asset_tags() -> String {
    let link = |path: &str| {
        format!(
            r#"<link rel="stylesheet" href="/static/css/{path}?v={ASSET_VERSION}">
"#
        )
    };
    format!(
        "{}{}{}{}",
        link("tokens/ndaal-tokens.css"),
        link("tokens/csaf-tokens.css"),
        link("base/base.css"),
        link("csaf-ui.css"),
    )
}

/// Give the page's first `<h1>` the `page-title` class and a leading icon.
///
/// Every page template writes a plain `<h1>`; this one transform styles them
/// all the same way instead of repeating the markup in about 26 places. An
/// `<h1>` that already has a `class` is left alone, so a template can opt
/// out. The content is server-generated, never request data.
fn decorate_page_title(content: &str, icon_name: &'static str) -> String {
    let Some(start) = content.find("<h1") else {
        return content.to_owned();
    };
    let Some(open_len) = content[start..].find('>') else {
        return content.to_owned();
    };
    let open_end = start + open_len;
    let open_tag = &content[start..open_end];
    if open_tag.contains("class=") || open_tag[3..].chars().next().is_some_and(|c| c != ' ') {
        return content.to_owned();
    }
    format!(
        "{before}{open_tag} class=\"page-title\">{icon}{after}",
        before = &content[..start],
        icon = icon(icon_name),
        after = &content[open_end + 1..],
    )
}

/// The `<header>` landmark: brand, hamburger, page links and control cluster.
fn header_html(lang: Lang, theme: ThemeChoice, active_key: &str) -> String {
    format!(
        r#"<header class="site-header">
<nav class="primary" aria-label="{main_label}">
  <a href="/" class="brand" aria-label="{brand_label}">
    <img src="/static/img/logo.png" alt="{logo_alt}" class="brand-logo" width="640" height="259">
    <span class="brand-text">CSAF</span>
  </a>
  <details class="nav-collapse">
    <summary class="nav-toggle" aria-label="{nav_toggle}" title="{nav_toggle}">{menu_icon}</summary>
    <div class="nav-group">
{nav_links}    <span class="spacer"></span>
{settings_link}{theme_menu}{lang_switcher}{info_menu}    </div>
  </details>
</nav>
</header>
"#,
        main_label = t(lang, "nav.main_label"),
        brand_label = t(lang, "nav.brand_label"),
        logo_alt = html_escape(t(lang, "nav.logo_alt")),
        nav_toggle = t(lang, "nav.toggle"),
        menu_icon = icon("list"),
        nav_links = nav_links(lang, active_key),
        settings_link = nav_link(lang, active_key, &SETTINGS_LINK),
        theme_menu = theme_menu(lang, theme.as_str()),
        lang_switcher = language_switcher(lang),
        info_menu = info_menu(lang, active_key),
    )
}

/// Wrap page content in the shared HTML layout.
///
/// `ctx.theme` is `"system"`, `"light"` or `"dark"` (see [`theme_for`]); light
/// and dark set `data-theme` on `<html>` for the token CSS, `"system"` leaves
/// it off so `prefers-color-scheme` decides. `ctx.lang` drives `<html lang>`
/// and every translated chrome label.
///
/// The header's right-edge control cluster is ordered Settings -> Theme ->
/// Language -> Info, Info rightmost, per `skills/ndaal-design` §12. Settings
/// stays a link to its full page here (the skill's dialog with a density
/// toggle does not fit this app's fifteen-field Settings page); that
/// divergence is recorded in the Developer Guide.
#[must_use]
pub fn wrap_page(title: &str, ctx: PageContext<'_>, active: Nav, content: &str) -> String {
    let lang = ctx.lang;
    let theme = ThemeChoice::from_value(ctx.theme).unwrap_or(ThemeChoice::System);
    let theme_attr = match theme {
        ThemeChoice::System => String::new(),
        explicit => format!(r#" data-theme="{}""#, explicit.as_str()),
    };
    format!(
        r##"<!DOCTYPE html>
<html lang="{lang_code}" dir="{lang_dir}"{theme_attr}>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>{title} — CSAF</title>
{assets}</head>
<body>
<a href="#main-content" class="skip-link">{skip_main}</a>
{header}<main id="main-content" class="page">
{content}
</main>
<footer class="site-footer">
  CSAF · Pierre Gronau — ndaal Gesellschaft für Sicherheit in der Informationstechnik mbH &amp; Co KG, Cologne · Apache-2.0
</footer>
<div id="live-status" class="sr-only" role="status"></div>
{dialog}<script src="/static/js/csaf-ui.js?v={ASSET_VERSION}" defer></script>
</body>
</html>"##,
        title = html_escape(title),
        lang_code = lang.code(),
        lang_dir = lang.dir(),
        assets = asset_tags(),
        skip_main = t(lang, "nav.skip_main"),
        header = header_html(lang, theme, active.as_str()),
        dialog = confirm_dialog(lang),
        content = decorate_page_title(content, active.title_icon()),
    )
}

/// Map a TLP 2.0 label to its CSS class name.
///
/// Returns one of the five fixed classes (`tlp-clear`, `tlp-green`,
/// `tlp-amber`, `tlp-amber-strict`, `tlp-red`) for a known label, or
/// `tlp-unknown` for anything else. This is the server-side mirror of
/// the inline script injected by [`wrap_page`] and guarantees that a
/// hostile document cannot produce an HTML-injectable class name.
#[must_use]
pub fn tlp_color_class(label: &str) -> &'static str {
    match label {
        "CLEAR" => "tlp-clear",
        "GREEN" => "tlp-green",
        "AMBER" => "tlp-amber",
        "AMBER+STRICT" => "tlp-amber-strict",
        "RED" => "tlp-red",
        _ => "tlp-unknown",
    }
}

/// HTML-escape a string for safe inclusion in element text or attribute values.
#[must_use]
pub fn html_escape(s: &str) -> String {
    s.replace('&', "&amp;")
        .replace('<', "&lt;")
        .replace('>', "&gt;")
        .replace('"', "&quot;")
        .replace('\'', "&#39;")
}

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

    /// The vendored skill tokens, read from the same file the server embeds.
    const SKILL_TOKENS: &str = include_str!("../../static/css/tokens/ndaal-tokens.css");
    /// The product's token layer, read from the same file the server embeds.
    const CSAF_TOKENS: &str = include_str!("../../static/css/tokens/csaf-tokens.css");
    /// The component stylesheet, read from the same file the server embeds.
    const CSAF_UI_CSS: &str = include_str!("../../static/css/csaf-ui.css");
    /// The page script, read from the same file the server embeds.
    const CSAF_UI_JS: &str = include_str!("../../static/js/csaf-ui.js");

    fn ctx(theme: &str) -> PageContext<'_> {
        PageContext {
            theme,
            lang: Lang::En,
        }
    }

    fn parts_with_cookie(cookie: Option<&str>) -> http::request::Parts {
        let mut builder = http::Request::builder().uri("/");
        if let Some(cookie) = cookie {
            builder = builder.header("cookie", cookie);
        }
        builder.body(()).expect("request builds").into_parts().0
    }

    #[test]
    fn test_wrap_page_light_theme_attribute() {
        let html = wrap_page("Test", ctx("light"), Nav::Home, "<p>body</p>");
        assert!(html.contains(r#"<html lang="en" dir="ltr" data-theme="light">"#));
        assert!(html.contains(r#"value="light" checked"#));
    }

    #[test]
    fn test_wrap_page_dark_theme_attribute() {
        let html = wrap_page("Test", ctx("dark"), Nav::Home, "<p>body</p>");
        assert!(html.contains(r#"data-theme="dark""#));
        assert!(html.contains(r#"value="dark" checked"#));
    }

    #[test]
    fn test_wrap_page_system_theme_leaves_the_attribute_off() {
        // No attribute means the CSS follows prefers-color-scheme.
        let html = wrap_page("Test", ctx("system"), Nav::Home, "");
        assert!(!html.contains("data-theme="), "{html}");
        assert!(html.contains(r#"value="system" checked"#));
    }

    #[test]
    fn test_wrap_page_unknown_theme_falls_back_to_system() {
        // A garbage value must never reach the attribute (it is user input
        // once it has traveled through a cookie).
        let html = wrap_page("Test", ctx(r#"x" onload="evil"#), Nav::Home, "");
        assert!(!html.contains("data-theme="), "{html}");
        assert!(!html.contains("evil"), "{html}");
    }

    #[test]
    fn test_theme_for_prefers_the_cookie_over_the_settings_default() {
        let parts = parts_with_cookie(Some("csaf_lang=de; csaf_theme=dark; other=1"));
        assert_eq!(theme_for(&parts, "light"), "dark");
        let parts = parts_with_cookie(Some("csaf_theme=system"));
        assert_eq!(theme_for(&parts, "dark"), "system");
    }

    #[test]
    fn test_theme_for_uses_the_settings_default_without_a_valid_cookie() {
        assert_eq!(theme_for(&parts_with_cookie(None), "dark"), "dark");
        assert_eq!(theme_for(&parts_with_cookie(None), "system"), "system");
        // An invalid cookie is ignored, not trusted.
        let parts = parts_with_cookie(Some("csaf_theme=purple"));
        assert_eq!(theme_for(&parts, "dark"), "dark");
        // A garbage default degrades to the historical light theme.
        assert_eq!(theme_for(&parts_with_cookie(None), "chartreuse"), "light");
    }

    #[test]
    fn test_theme_choice_round_trips_and_rejects_unknown_values() {
        for choice in [ThemeChoice::System, ThemeChoice::Light, ThemeChoice::Dark] {
            assert_eq!(ThemeChoice::from_value(choice.as_str()), Some(choice));
        }
        for bad in ["", "DARK", " dark", "dark;", "auto"] {
            assert_eq!(ThemeChoice::from_value(bad), None, "{bad:?}");
        }
    }

    #[test]
    fn test_wrap_page_marks_the_active_page_for_assistive_tech() {
        let html = wrap_page("Settings", ctx("light"), Nav::Settings, "");
        assert!(html.contains(r#"href="/settings" class="nav-link" aria-current="page""#));
        assert!(html.contains(r#"href="/" class="nav-link">"#));
        // Exactly one link carries aria-current="page".
        assert_eq!(html.matches(r#"aria-current="page""#).count(), 1);
    }

    #[test]
    fn test_wrap_page_uses_csaf_branding_not_csaf_crud() {
        let html = wrap_page("Test", ctx("light"), Nav::Home, "");
        assert!(html.contains(r#"class="brand-text">CSAF</span>"#));
        assert!(!html.contains("CSAF CRUD"));
        assert!(html.contains("Test — CSAF</title>"));
    }

    #[test]
    fn test_wrap_page_escapes_the_ampersand_in_the_logo_alt_text() {
        // The English alt text is "ndaal — information security & compliance".
        // A bare `&` in an attribute is a parse ambiguity (markuplint
        // character-reference) and the first step towards an injection.
        let html = wrap_page("Test", ctx("light"), Nav::Home, "");
        assert!(html.contains(r#"alt="ndaal — information security &amp; compliance""#));
    }

    #[test]
    fn test_theme_cookie_in_a_later_cookie_field_is_found() {
        // REGRESSION (found by tests/proptest_ui.rs): `theme_for` read only the
        // first `cookie` field, so over HTTP/2 — where each pair may be its own
        // field — a visitor's choice was ignored whenever another cookie came
        // first. This is the shrunk counterexample, pinned as an example.
        let (mut parts, ()) = http::Request::builder()
            .uri("/")
            .body(())
            .expect("request builds")
            .into_parts();
        parts.headers.append(
            http::header::COOKIE,
            http::HeaderValue::from_static("other=1"),
        );
        parts.headers.append(
            http::header::COOKIE,
            http::HeaderValue::from_static("csaf_theme=dark"),
        );
        assert_eq!(theme_for(&parts, "light"), "dark");
    }

    #[test]
    fn test_wrap_page_escapes_the_title() {
        // REGRESSION (found by tests/proptest_ui.rs): the title went into
        // `<title>` verbatim, so `&` was a bare ampersand and `</title><…>`
        // closed the element. A tracking id from the URL reaches this slot.
        let html = wrap_page("a & b </title><b>", ctx("light"), Nav::Home, "");
        assert!(html.contains("<title>a &amp; b &lt;/title&gt;&lt;b&gt; — CSAF</title>"));
    }

    #[test]
    fn test_wrap_page_logo_declares_its_intrinsic_size() {
        // width/height let the browser reserve the space before the image
        // arrives (no layout shift); CSS still sets the displayed height.
        let html = wrap_page("Test", ctx("light"), Nav::Home, "");
        assert!(html.contains(r#"width="640" height="259""#));
    }

    #[test]
    fn test_wrap_page_loads_the_script_after_the_content() {
        // A script in <head> blocks nothing here (it is deferred), but the
        // repo's htmlhint rule keeps scripts out of the head, and the end of
        // <body> is where the page's own markup is already parsed.
        let html = wrap_page("Test", ctx("light"), Nav::Home, "");
        let script = html.find("<script src").expect("script tag present");
        assert!(
            script > html.find("</main>").expect("main closes"),
            "{script}"
        );
        assert!(script > html.find("</head>").expect("head closes"));
    }

    #[test]
    fn test_theme_radios_are_bound_to_their_labels_by_id() {
        let html = wrap_page("Test", ctx("light"), Nav::Home, "");
        for value in ["system", "light", "dark"] {
            assert!(html.contains(&format!(r#"id="theme-{value}""#)), "{value}");
            assert!(
                html.contains(&format!(r#"<label class="check-row" for="theme-{value}">"#)),
                "{value}"
            );
        }
    }

    #[test]
    fn test_confirmation_dialog_has_text_before_the_script_fills_it() {
        // The dialog is named by its message and offers a confirm button. Both
        // hold a default so neither is an empty control in the markup; the
        // script replaces them with the form's own wording.
        let html = wrap_page("Test", ctx("light"), Nav::Home, "");
        assert!(!html.contains(r#"class="confirm-message"></p>"#));
        assert!(!html.contains(r#"confirm-ok"></button>"#));
    }

    #[test]
    fn test_wrap_page_includes_logo_image() {
        let html = wrap_page("Test", ctx("light"), Nav::Home, "");
        assert!(html.contains(r#"<img src="/static/img/logo.png""#));
        assert!(html.contains("alt=\"ndaal"));
    }

    #[test]
    fn test_primary_is_the_skills_measured_blue_with_no_local_override() {
        // The UI follows skills/ndaal-design (and sbom.ndaal.eu): the primary
        // is the skill's measured ndaal blue. Our token layer must NOT
        // override it, or the product drifts from the other ndaal products.
        assert!(
            SKILL_TOKENS.contains("--ndaal-primary:            #0A4DA6;"),
            "the vendored skill tokens define the blue primary"
        );
        assert!(
            !CSAF_TOKENS.contains("--ndaal-primary"),
            "no primary override"
        );
        assert!(
            !CSAF_TOKENS.contains("#8B1A1A"),
            "the old burgundy theme must not return"
        );
        assert!(
            !CSAF_TOKENS.contains("#1a237e"),
            "the pre-ndaal blue must not return"
        );
    }

    #[test]
    fn test_wrap_page_loads_the_four_stylesheets_in_cascade_order() {
        let html = wrap_page("Test", ctx("light"), Nav::Home, "");
        let order = [
            "/static/css/tokens/ndaal-tokens.css",
            "/static/css/tokens/csaf-tokens.css",
            "/static/css/base/base.css",
            "/static/css/csaf-ui.css",
        ];
        let positions: Vec<usize> = order
            .iter()
            .map(|path| {
                html.find(path)
                    .unwrap_or_else(|| panic!("{path} not linked"))
            })
            .collect();
        assert!(
            positions.windows(2).all(|pair| pair[0] < pair[1]),
            "tokens must load before the layers that override them: {positions:?}"
        );
        // The version suffix makes a release refetch the one-day-cached files.
        assert!(html.contains(&format!("csaf-ui.css?v={}", env!("CARGO_PKG_VERSION"))));
        assert!(html.contains(r#"<script src="/static/js/csaf-ui.js?v="#));
    }

    #[test]
    fn test_wrap_page_is_compatible_with_a_strict_content_security_policy() {
        // The server sends a CSP without 'unsafe-inline'. Any inline script,
        // inline style, style attribute, event-handler attribute or
        // javascript: URL would be blocked silently, so fail here instead.
        let html = wrap_page("Test", ctx("dark"), Nav::Csaf, "<p>x</p>");
        assert!(!html.contains("<style"), "inline <style> found");
        assert!(!html.contains(" style=\""), "style attribute found");
        assert!(!html.contains("javascript:"), "javascript: URL found");
        for attr in ["onclick=", "onsubmit=", "onload=", "onchange=", "onerror="] {
            assert!(!html.contains(attr), "inline handler {attr} found");
        }
        let scripts = html.matches("<script").count();
        let external = html.matches("<script src=").count();
        assert_eq!(scripts, external, "every <script> must have a src");
    }

    #[test]
    fn test_html_escape_special_chars() {
        assert_eq!(html_escape("<script>"), "&lt;script&gt;");
        assert_eq!(html_escape("a & b"), "a &amp; b");
        assert_eq!(html_escape(r#"'"<>&"#), "&#39;&quot;&lt;&gt;&amp;");
    }

    #[test]
    fn test_tlp_color_class_whitelist() {
        assert_eq!(tlp_color_class("CLEAR"), "tlp-clear");
        assert_eq!(tlp_color_class("GREEN"), "tlp-green");
        assert_eq!(tlp_color_class("AMBER"), "tlp-amber");
        assert_eq!(tlp_color_class("AMBER+STRICT"), "tlp-amber-strict");
        assert_eq!(tlp_color_class("RED"), "tlp-red");
    }

    #[test]
    fn test_tlp_color_class_rejects_untrusted() {
        // Hostile strings must never produce an HTML-injectable class.
        for bad in [
            "",
            "clear",
            "red\"><script>alert(1)</script>",
            " CLEAR ",
            "WHITE",
            "  ",
        ] {
            let class = tlp_color_class(bad);
            assert_eq!(class, "tlp-unknown", "bad={bad:?} -> {class}");
            // Class name is ASCII-only, no spaces, no quotes.
            assert!(
                class
                    .bytes()
                    .all(|b| b.is_ascii_alphanumeric() || b == b'-')
            );
        }
    }

    #[test]
    fn test_tlp_colours_and_script_stay_in_step_with_the_server_whitelist() {
        // The colours are in the component stylesheet, the label->class map
        // is in the page script; both must keep matching tlp_color_class().
        for class in ["tlp-red", "tlp-amber", "tlp-green", "tlp-clear"] {
            assert!(
                CSAF_UI_CSS.contains(&format!(".tlp-select.{class}")),
                "{class} missing from csaf-ui.css"
            );
        }
        for label in ["CLEAR", "GREEN", "AMBER", "AMBER+STRICT", "RED"] {
            let want = format!(r#""{label}": "{}""#, tlp_color_class(label));
            assert!(CSAF_UI_JS.contains(&want), "{want} missing from csaf-ui.js");
        }
        assert!(CSAF_UI_JS.contains(
            r#"select.classList.add(known ? TLP_CLASSES[select.value] : "tlp-unknown")"#
        ));
    }

    #[test]
    fn test_wrap_page_sets_html_lang_from_context() {
        let html = wrap_page(
            "Test",
            PageContext {
                theme: "light",
                lang: Lang::De,
            },
            Nav::Home,
            "",
        );
        assert!(html.contains(r#"<html lang="de""#));
        // German is left-to-right.
        assert!(html.contains(r#"<html lang="de" dir="ltr""#));
        assert!(html.contains("Einstellungen")); // nav.settings, DE
    }

    #[test]
    fn test_wrap_page_sets_html_dir_rtl_for_urdu() {
        // Urdu (Perso-Arabic) is right-to-left; `<html dir="rtl">` flips the
        // whole document in one place (skills/languages-asia §3).
        let html = wrap_page(
            "Test",
            PageContext {
                theme: "light",
                lang: Lang::Ur,
            },
            Nav::Home,
            "",
        );
        assert!(html.contains(r#"<html lang="ur" dir="rtl""#));
    }

    #[test]
    fn test_wrap_page_header_cluster_order_is_settings_theme_language_info() {
        // skills/ndaal-design §12: Settings -> Theme -> Language -> Info,
        // Info rightmost, the same on every page.
        let html = wrap_page("Test", ctx("light"), Nav::Home, "");
        let at = |needle: &str| {
            html.find(needle)
                .unwrap_or_else(|| panic!("{needle} missing"))
        };
        let settings_pos = at(r#"href="/settings""#);
        let theme_pos = at(r#"action="/preferences/theme""#);
        let lang_pos = at(r#"href="/lang/en""#);
        let info_pos = at(r#"href="/info/about""#);
        assert!(settings_pos < theme_pos, "settings must precede theme");
        assert!(theme_pos < lang_pos, "theme must precede language");
        assert!(lang_pos < info_pos, "language must precede info");
    }

    #[test]
    fn test_theme_menu_is_a_real_form_with_three_radios_and_a_fallback_button() {
        let html = wrap_page("Test", ctx("light"), Nav::Home, "");
        assert!(
            html.contains(r#"<form method="post" action="/preferences/theme" class="theme-form">"#)
        );
        for value in ["system", "light", "dark"] {
            assert!(
                html.contains(&format!(
                    r#"<input type="radio" id="theme-{value}" name="theme" value="{value}""#
                )),
                "radio {value} missing"
            );
        }
        // Without JavaScript the button is what applies the choice.
        assert!(html.contains(r#"class="btn theme-apply""#));
    }

    #[test]
    fn test_wrap_page_has_a_live_region_and_a_confirmation_dialog() {
        let html = wrap_page("Test", ctx("light"), Nav::Home, "");
        assert!(html.contains(r#"<div id="live-status" class="sr-only" role="status"></div>"#));
        assert!(html.contains(r#"<dialog id="confirm-dialog""#));
        assert!(html.contains(r#"aria-labelledby="confirm-dialog-message""#));
    }

    #[test]
    fn test_wrap_page_landmarks_are_labelled() {
        let html = wrap_page("Test", ctx("light"), Nav::Home, "");
        assert!(html.contains(r#"<nav class="primary" aria-label="Main navigation">"#));
        assert!(html.contains("<header class=\"site-header\">"));
        assert!(html.contains("<footer class=\"site-footer\">"));
    }

    #[test]
    fn test_wrap_page_language_switcher_lists_all_49_with_current_marked() {
        let html = wrap_page(
            "Test",
            PageContext {
                theme: "light",
                lang: Lang::Fr,
            },
            Nav::Home,
            "",
        );
        for choice in Lang::all() {
            let code = choice.code();
            assert!(
                html.contains(&format!(
                    r#"href="/lang/{code}" lang="{code}" hreflang="{code}""#
                )),
                "missing switcher link (with lang/hreflang) for {code}"
            );
            assert!(
                html.contains(choice.endonym()),
                "missing endonym for {code}"
            );
        }
        assert!(html.contains(
            r#"href="/lang/fr" lang="fr" hreflang="fr" class="menu-link" aria-current="true""#
        ));
        assert!(!html.contains(r#"hreflang="en" class="menu-link" aria-current"#));
    }

    #[test]
    fn test_language_switcher_html_matches_snapshot() {
        // Pins the exact 46-item order, the lang/hreflang attributes, and
        // the active-language marking as a reviewable diff. Accept an
        // intentional change with `cargo insta review` (or `INSTA_UPDATE`).
        //
        // The icon URLs carry the crate version as a cache-buster
        // (`?v=<version>`). Normalise it, so a release bump does not turn
        // the snapshot red for a reason that has nothing to do with markup.
        let html =
            language_switcher(Lang::En).replace(&format!("?v={ASSET_VERSION}#"), "?v=VERSION#");
        insta::assert_snapshot!(html);
    }

    #[test]
    fn test_language_switcher_orders_the_pinned_five_before_the_tail() {
        // The historical En/De/Fr/Es/It front order is a UI contract; the
        // 41-language tail follows alphabetically by English name.
        let html = language_switcher(Lang::En);
        let pos = |code: &str| {
            html.find(&format!(r#"href="/lang/{code}""#))
                .unwrap_or_else(|| panic!("no link for {code}"))
        };
        let order = ["en", "de", "fr", "es", "it", "sq"];
        for pair in order.windows(2) {
            assert!(
                pos(pair[0]) < pos(pair[1]),
                "{} must precede {}",
                pair[0],
                pair[1]
            );
        }
        assert!(pos("sq") < pos("ur"), "tail runs Albanian..Urdu");
    }

    #[test]
    fn test_wrap_page_includes_skip_link_targeting_main() {
        let html = wrap_page("Test", ctx("light"), Nav::Home, "");
        assert!(html.contains(r##"<a href="#main-content" class="skip-link">"##));
        assert!(html.contains(r#"<main id="main-content" class="page">"#));
        // The skip link is the first focusable element in the body.
        let skip = html.find("skip-link").expect("skip link");
        let first_link = html.find("<a href=\"/\"").expect("brand link");
        assert!(skip < first_link, "skip link must come first");
    }

    #[test]
    fn test_decorate_page_title_adds_class_and_leading_icon() {
        let out = decorate_page_title("<h1>Dashboard</h1><p>x</p>", "house");
        assert!(
            out.starts_with(r#"<h1 class="page-title"><svg class="icon""#),
            "{out}"
        );
        assert!(out.contains("#house"), "{out}");
        assert!(out.ends_with("Dashboard</h1><p>x</p>"), "{out}");
    }

    #[test]
    fn test_decorate_page_title_keeps_an_existing_id() {
        let out = decorate_page_title(r#"<h1 id="documents-heading">Docs</h1>"#, "gear");
        assert!(
            out.starts_with(r#"<h1 id="documents-heading" class="page-title"><svg"#),
            "{out}"
        );
    }

    #[test]
    fn test_decorate_page_title_leaves_a_classed_or_missing_heading_alone() {
        let classed = r#"<h1 class="custom">Own</h1>"#;
        assert_eq!(decorate_page_title(classed, "gear"), classed);
        let none = "<h2>Section</h2><p>no top heading</p>";
        assert_eq!(decorate_page_title(none, "gear"), none);
        assert_eq!(decorate_page_title("", "gear"), "");
    }

    #[test]
    fn test_decorate_page_title_only_touches_the_first_h1_and_real_h1_tags() {
        let two = "<h1>One</h1><h1>Two</h1>";
        assert_eq!(
            decorate_page_title(two, "gear")
                .matches("page-title")
                .count(),
            1
        );
        // A look-alike element must not be treated as a heading.
        let lookalike = "<h10>x</h10><h1x>y</h1x>";
        assert_eq!(decorate_page_title(lookalike, "gear"), lookalike);
    }

    #[test]
    fn test_wrap_page_gives_each_section_its_own_title_icon() {
        for (nav, symbol) in [
            (Nav::Home, "#speedometer2"),
            (Nav::Csaf, "#file-earmark-text"),
            (Nav::Import, "#box-arrow-in-down"),
            (Nav::Export, "#box-arrow-up"),
            (Nav::Settings, "#sliders"),
            (Nav::Info, "#info-circle"),
        ] {
            let html = wrap_page("T", ctx("light"), nav, "<h1>Title</h1>");
            let main = html
                .split(r#"<main id="main-content""#)
                .nth(1)
                .expect("main present");
            assert!(main.contains(r#"<h1 class="page-title">"#), "{nav:?}");
            assert!(main.contains(symbol), "{nav:?} should use {symbol}");
        }
    }

    use proptest::prelude::*;

    proptest! {
        /// `html_escape` is the XSS guard used when embedding untrusted
        /// CSAF-document fields into rendered HTML pages. Over arbitrary
        /// Unicode input, the output must never contain a raw `<`, `>`,
        /// `"`, or `'` — every occurrence must have been escaped to its
        /// HTML entity.
        #[test]
        fn prop_html_escape_never_leaves_unescaped_markup_chars(s in ".*") {
            let escaped = html_escape(&s);
            prop_assert!(!escaped.contains('<'));
            prop_assert!(!escaped.contains('>'));
            prop_assert!(!escaped.contains('"'));
            prop_assert!(!escaped.contains('\''));
        }

        /// Whatever a cookie contains, the theme that reaches the page is one
        /// of the three fixed values: a hostile cookie can never inject
        /// markup through `data-theme`.
        #[test]
        fn prop_theme_for_only_ever_returns_a_fixed_value(cookie in ".*", default in ".*") {
            let parts = parts_with_cookie(
                http::HeaderValue::from_str(&cookie).ok().map(|_| cookie.as_str()),
            );
            let theme = theme_for(&parts, &default);
            prop_assert!(["system", "light", "dark"].contains(&theme));
        }
    }

    /// Strings that look like page content: plain text, `<h1>` openers in
    /// several shapes, and multi-byte characters around them, so the byte
    /// slicing in `decorate_page_title` meets a char boundary.
    fn page_like() -> impl Strategy<Value = String> {
        proptest::collection::vec(
            prop_oneof![
                Just("<h1>".to_owned()),
                Just("<h1 id=\"x\">".to_owned()),
                Just("<h1 class=\"own\">".to_owned()),
                Just("<h10>".to_owned()),
                Just("<h1".to_owned()),
                Just("</h1>".to_owned()),
                "[ -~]{0,8}",
                "[äöü߀日本語<>&\"]{0,4}",
            ],
            0..8,
        )
        .prop_map(|parts| parts.concat())
    }

    proptest! {
        /// Total over any text: no panic, and a page without an `<h1` is
        /// returned exactly as it came.
        #[test]
        fn prop_decorate_page_title_is_total_and_leaves_h1_less_pages_alone(
            content in prop_oneof![page_like(), ".*"],
        ) {
            let out = decorate_page_title(&content, "house");
            if !content.contains("<h1") {
                prop_assert_eq!(out, content);
            }
        }

        /// Decorating twice is decorating once: the first `<h1` carries a
        /// `class` after the first pass, so the second pass leaves it alone.
        #[test]
        fn prop_decorate_page_title_is_idempotent(content in page_like()) {
            let once = decorate_page_title(&content, "house");
            prop_assert_eq!(decorate_page_title(&once, "house"), once);
        }

        /// The transform only inserts: taking the class and the icon back out
        /// restores the input byte for byte, so no template text is lost.
        #[test]
        fn prop_decorate_page_title_only_inserts(content in page_like()) {
            let out = decorate_page_title(&content, "house");
            if out != content {
                let inserted = format!(" class=\"page-title\">{}", icon("house"));
                prop_assert_eq!(out.replacen(&inserted, ">", 1), content);
            }
        }
    }
}