csaf-crud 1.4.16

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
// 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};

/// Per-request rendering context: theme 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> {
    /// `"light"` or `"dark"`, from the persisted user settings.
    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 {
    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",
        }
    }
}

/// Inline stylesheet for every rendered page.
///
/// Hoisted out of `wrap_page`, which was 312 lines and almost entirely this
/// block. It stays INLINE rather than moving to `/static`: the product ships as
/// a single binary, and a separate stylesheet would add a request and a second
/// thing to keep in step with the markup for no gain here.
///
/// Braces are single here. Inside the `format!` they had to be doubled, which
/// is why every CSS rule read as `{{` and made the block harder to scan than
/// the CSS actually is.
const PAGE_STYLE: &str = r#"  @font-face {
    font-family: "Roboto";
    font-style: normal;
    font-weight: 400;
    font-display: swap;
    src: url("/static/fonts/roboto/roboto-regular.ttf") format("truetype");
  }
  @font-face {
    font-family: "Roboto";
    font-style: normal;
    font-weight: 700;
    font-display: swap;
    src: url("/static/fonts/roboto/roboto-bold.ttf") format("truetype");
  }
  @font-face {
    font-family: "Roboto Mono";
    font-style: normal;
    font-weight: 400;
    font-display: swap;
    src: url("/static/fonts/roboto-mono/roboto-mono-regular.ttf") format("truetype");
  }
  @font-face {
    font-family: "Roboto Mono";
    font-style: normal;
    font-weight: 700;
    font-display: swap;
    src: url("/static/fonts/roboto-mono/roboto-mono-bold.ttf") format("truetype");
  }
  :root {
    --bg: #f5f5f5;
    --surface: #ffffff;
    --text: #1a1a1a;
    --muted: #555555;
    --border: #e0e0e0;
    --primary: #8b1a1a;
    --primary-hover: #a0252a;
    --primary-contrast: #ffffff;
    --link: #8b1a1a;
    --row-hover: #f7f7f9;
    --input-bg: #ffffff;
    --input-border: #bdbdbd;
    --shadow: 0 1px 3px rgba(0,0,0,0.08);
    --badge-create-bg: #e8f5e9; --badge-create-fg: #2e7d32;
    --badge-update-bg: #fff3e0; --badge-update-fg: #e65100;
    --badge-delete-bg: #fce4ec; --badge-delete-fg: #c62828;
    --badge-import-bg: #f3e5f5; --badge-import-fg: #6a1b9a;
    --badge-export-bg: #ede7f6; --badge-export-fg: #4527a0;
    --sev-critical: #b71c1c; --sev-high: #ef6c00; --sev-medium: #f9a825;
    --sev-low: #2e7d32; --sev-none: #616161;
  }
  html[data-bs-theme="dark"] {
    --bg: #0f1115;
    --surface: #181b22;
    --text: #e9ecef;
    --muted: #9aa0a6;
    --border: #2a2f3a;
    --primary: #c44545;
    --primary-hover: #d85c5c;
    --primary-contrast: #ffffff;
    --link: #e89696;
    --row-hover: #1f232c;
    --input-bg: #12151b;
    --input-border: #394150;
    --shadow: 0 1px 3px rgba(0,0,0,0.5);
    --badge-create-bg: #1b3a24; --badge-create-fg: #9ef5b6;
    --badge-update-bg: #4a2e10; --badge-update-fg: #ffc889;
    --badge-delete-bg: #4a1c29; --badge-delete-fg: #ff98b3;
    --badge-import-bg: #3a1f4d; --badge-import-fg: #d9a6ff;
    --badge-export-bg: #221a4a; --badge-export-fg: #b2a4ff;
  }
  * { box-sizing: border-box; }
  html, body {
    font-family: "Roboto", system-ui, -apple-system, "Segoe UI", sans-serif;
  }
  code, pre, kbd, samp, tt {
    font-family: "Roboto Mono", "SF Mono", Menlo, Consolas, monospace;
  }
  body {
    margin: 0; padding: 0; background: var(--bg); color: var(--text);
    line-height: 1.5;
    font-weight: 400;
  }
  .skip-link {
    position: absolute; left: -9999px; top: 0; z-index: 100;
    background: var(--surface); color: var(--text);
    padding: 0.6rem 1rem; border-radius: 0 0 4px 0;
  }
  .skip-link:focus { left: 0; }
  nav.primary {
    background: var(--primary); color: var(--primary-contrast);
    padding: 0.6rem 1.5rem; display: flex; align-items: center;
    gap: 1.25rem; flex-wrap: wrap;
    border-bottom: 3px solid rgba(0,0,0,0.15);
  }
  nav.primary a {
    color: var(--primary-contrast); text-decoration: none;
    font-size: 0.9rem; padding: 0.35rem 0.6rem; border-radius: 4px;
  }
  nav.primary a:hover { background: rgba(255,255,255,0.14); }
  nav.primary a.active { background: rgba(255,255,255,0.22); font-weight: 600; }
  nav.primary .brand {
    display: flex; align-items: center; gap: 0.6rem;
    margin-right: 0.75rem; text-decoration: none;
  }
  nav.primary .brand img {
    height: 36px; width: auto; display: block;
    background: #ffffff; padding: 4px 8px; border-radius: 4px;
  }
  nav.primary .brand .brand-text {
    font-weight: 700; font-size: 1.2rem; letter-spacing: 0.02em;
    color: var(--primary-contrast);
  }
  nav.primary .spacer { flex: 1; }
  nav.primary .theme-toggle {
    background: transparent; border: 1px solid rgba(255,255,255,0.5);
    color: var(--primary-contrast); padding: 0.35rem 0.75rem; border-radius: 4px;
    cursor: pointer; font-size: 0.85rem; font-family: inherit;
  }
  nav.primary .theme-toggle:hover { background: rgba(255,255,255,0.14); }
  nav.primary details.nav-dropdown { position: relative; }
  nav.primary details.nav-dropdown summary {
    color: var(--primary-contrast); text-decoration: none;
    font-size: 0.9rem; padding: 0.35rem 0.6rem; border-radius: 4px;
    cursor: pointer; list-style: none;
  }
  nav.primary details.nav-dropdown summary::-webkit-details-marker { display: none; }
  nav.primary details.nav-dropdown summary:hover { background: rgba(255,255,255,0.14); }
  nav.primary details.nav-dropdown[open] summary,
  nav.primary details.nav-dropdown summary.active {
    background: rgba(255,255,255,0.22); font-weight: 600;
  }
  nav.primary details.nav-dropdown .dropdown-menu {
    position: absolute; top: 100%; left: 0; margin-top: 0.25rem;
    background: var(--surface); color: var(--text);
    border: 1px solid rgba(0,0,0,0.15); border-radius: 6px;
    box-shadow: 0 4px 12px rgba(0,0,0,0.25); min-width: 190px;
    padding: 0.4rem 0; z-index: 20;
  }
  nav.primary details.nav-dropdown .dropdown-menu a {
    display: block; color: inherit; padding: 0.4rem 0.9rem;
    border-radius: 0; font-size: 0.9rem;
  }
  nav.primary details.nav-dropdown .dropdown-menu a:hover { background: rgba(128,128,128,0.15); }
  nav.primary details.nav-dropdown .dropdown-divider {
    border: none; border-top: 1px solid rgba(128,128,128,0.3); margin: 0.35rem 0;
  }
  /* The 46-entry language menu: right-anchored so the wide grid grows into
     the page, single scrollable column on narrow viewports, and columns of
     ten on desktop (grid-auto-flow: column fills each 10-row column top to
     bottom, then starts the next -> 46 languages render as 10/10/10/10/6). */
  nav.primary details.nav-dropdown .dropdown-menu.lang-menu {
    right: 0; left: auto;
    max-height: 70vh; overflow-y: auto;
  }
  @media (min-width: 992px) {
    nav.primary details.nav-dropdown .dropdown-menu.lang-menu {
      display: grid;
      grid-auto-flow: column;
      grid-template-rows: repeat(10, auto);
      grid-auto-columns: max-content;
      max-height: none; overflow-y: visible;
      padding-inline: 0.25rem;
    }
  }
  main { max-width: 1200px; margin: 2rem auto; padding: 0 1.5rem; }
  h1, h2, h3 { color: var(--text); }
  h1 { margin-top: 0; }
  a { color: var(--link); }
  .card {
    background: var(--surface); border: 1px solid var(--border);
    border-radius: 8px; padding: 1.5rem; margin-bottom: 1.5rem;
    box-shadow: var(--shadow);
  }
  .stats { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 1rem; }
  .stat { text-align: center; }
  .stat .number { font-size: 2rem; font-weight: bold; color: var(--primary); }
  .stat .label { font-size: 0.85rem; color: var(--muted); margin-top: 0.25rem; }
  table { width: 100%; border-collapse: collapse; }
  th, td {
    text-align: left; padding: 0.55rem 0.75rem;
    border-bottom: 1px solid var(--border); font-size: 0.9rem;
  }
  th { background: var(--row-hover); font-weight: 600; color: var(--muted); }
  tr:hover td { background: var(--row-hover); }
  label { display: block; margin-bottom: 0.35rem; font-weight: 500; font-size: 0.9rem; }
  input[type=text], input[type=number], input[type=url], input[type=email],
  select, textarea {
    width: 100%; padding: 0.5rem 0.65rem; border: 1px solid var(--input-border);
    border-radius: 4px; background: var(--input-bg); color: var(--text);
    font-family: inherit; font-size: 0.9rem;
  }
  textarea { font-family: "Roboto Mono", "SF Mono", Menlo, monospace; font-size: 0.85rem; }
  .form-row { display: grid; grid-template-columns: 1fr 1fr; gap: 1rem; margin-bottom: 1rem; }
  .form-row.single { grid-template-columns: 1fr; }
  .btn {
    display: inline-block; padding: 0.55rem 1.1rem; border: none; border-radius: 4px;
    background: var(--primary); color: var(--primary-contrast); font-size: 0.9rem;
    font-weight: 500; cursor: pointer; text-decoration: none;
  }
  .btn:hover { filter: brightness(1.1); }
  .btn.secondary { background: transparent; color: var(--link); border: 1px solid var(--border); }
  .btn.danger { background: #c62828; }
  .badge { display: inline-block; padding: 0.15rem 0.5rem; border-radius: 4px; font-size: 0.8rem; font-weight: 500; }
  .badge-create { background: var(--badge-create-bg); color: var(--badge-create-fg); }
  .badge-update { background: var(--badge-update-bg); color: var(--badge-update-fg); }
  .badge-delete { background: var(--badge-delete-bg); color: var(--badge-delete-fg); }
  .badge-import { background: var(--badge-import-bg); color: var(--badge-import-fg); }
  .badge-export { background: var(--badge-export-bg); color: var(--badge-export-fg); }
  .sev-critical { color: var(--sev-critical); font-weight: 600; }
  .sev-high     { color: var(--sev-high); font-weight: 600; }
  .sev-medium   { color: var(--sev-medium); font-weight: 600; }
  .sev-low      { color: var(--sev-low); font-weight: 600; }
  .sev-none     { color: var(--sev-none); }
  .flash        { padding: 0.75rem 1rem; border-radius: 4px; margin-bottom: 1rem; }
  .flash.success { background: var(--badge-create-bg); color: var(--badge-create-fg); }
  .flash.error   { background: var(--badge-delete-bg); color: var(--badge-delete-fg); }
  .muted { color: var(--muted); font-size: 0.85rem; }
  /* TLP 2.0 color-coding per https://www.first.org/tlp/
     Background + font colours taken from the FIRST spec. */
  .tlp-select                            { font-weight: 600; }
  .tlp-select.tlp-red                    { background: #FF2B2B; color: #000; }
  .tlp-select.tlp-amber,
  .tlp-select.tlp-amber-strict           { background: #FFC000; color: #000; }
  .tlp-select.tlp-green                  { background: #33FF00; color: #000; }
  .tlp-select.tlp-clear                  { background: #FFFFFF; color: #000;
                                              border: 1px solid var(--input-border); }
  .tlp-select.tlp-unknown                { background: var(--input-bg); color: var(--text); }
  .tlp-select option[value="RED"]            { background: #FF2B2B; color: #000; }
  .tlp-select option[value="AMBER"],
  .tlp-select option[value="AMBER+STRICT"]   { background: #FFC000; color: #000; }
  .tlp-select option[value="GREEN"]          { background: #33FF00; color: #000; }
  .tlp-select option[value="CLEAR"]          { background: #FFFFFF; color: #000; }
  footer { text-align: center; padding: 2rem 1rem; color: var(--muted); font-size: 0.8rem; }"#;

/// Inline script for every rendered page (theme toggle and nav behaviour).
const PAGE_SCRIPT: &str = r#"  // Sync the background colour of every .tlp-select to the current value.
  // Accepted labels: CLEAR, GREEN, AMBER, AMBER+STRICT, RED. Anything
  // else maps to `tlp-unknown` so hostile document values cannot inject
  // arbitrary class names.
  document.addEventListener("DOMContentLoaded", function() {
    var allowed = {
      "CLEAR": "tlp-clear",
      "GREEN": "tlp-green",
      "AMBER": "tlp-amber",
      "AMBER+STRICT": "tlp-amber-strict",
      "RED": "tlp-red"
    };
    document.querySelectorAll(".tlp-select").forEach(function(sel) {
      var sync = function() {
        var key = allowed[sel.value] ? allowed[sel.value] : "tlp-unknown";
        sel.className = "tlp-select " + key;
      };
      sel.addEventListener("change", sync);
      sync();
    });
  });"#;

/// 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
/// (46 languages -> five columns), per `skills/languages-europe-rust` ยง5.
/// 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 cls = if choice == lang { "active" } else { "" };
            let current = if choice == lang {
                r#" aria-current="true""#
            } else {
                ""
            };
            let _ = writeln!(
                acc,
                r#"      <a href="/lang/{code}" lang="{code}" hreflang="{code}" class="{cls}"{current}>{endonym}</a>"#,
                code = choice.code(),
                endonym = choice.endonym(),
            );
            acc
        });
    format!(
        r#"  <details class="nav-dropdown">
    <summary>{label}</summary>
    <div class="dropdown-menu lang-menu">
{items}    </div>
  </details>
"#,
        label = t(lang, "nav.language"),
    )
}

/// Render the five primary nav links (Dashboard/CSAF/Import/Export/Settings).
fn nav_links(lang: Lang, active_key: &str) -> String {
    let cls = |key: &str| if active_key == key { "active" } else { "" };
    format!(
        r#"  <a href="/" class="{home_cls}">{nav_dashboard}</a>
  <a href="/csaf" class="{csaf_cls}">{nav_csaf}</a>
  <a href="/admin/import" class="{import_cls}">{nav_import}</a>
  <a href="/admin/export" class="{export_cls}">{nav_export}</a>
  <a href="/settings" class="{settings_cls}">{nav_settings}</a>
"#,
        home_cls = cls("home"),
        csaf_cls = cls("csaf"),
        import_cls = cls("import"),
        export_cls = cls("export"),
        settings_cls = cls("settings"),
        nav_dashboard = t(lang, "nav.dashboard"),
        nav_csaf = t(lang, "nav.csaf"),
        nav_import = t(lang, "nav.import"),
        nav_export = t(lang, "nav.export"),
        nav_settings = t(lang, "nav.settings"),
    )
}

/// Render the theme-toggle form/button.
fn theme_toggle_button(lang: Lang, theme: &str) -> String {
    let icon_label = if theme == "dark" {
        format!("โ˜€ {}", t(lang, "nav.theme_light"))
    } else {
        format!("โ˜พ {}", t(lang, "nav.theme_dark"))
    };
    format!(
        r#"  <form method="post" action="/settings/toggle-theme" style="margin:0">
    <button type="submit" class="theme-toggle" title="{title}">
      {icon_label}
    </button>
  </form>
"#,
        title = t(lang, "nav.theme_toggle"),
    )
}

/// Render the Info control's dropdown (About/License/System/.../User Guide).
fn info_menu(lang: Lang, active_key: &str) -> String {
    let info_cls = if active_key == "info" { "active" } else { "" };
    format!(
        r#"  <details class="nav-dropdown">
    <summary class="{info_cls}">{nav_info}</summary>
    <div class="dropdown-menu">
      <a href="/info/about">{info_about}</a>
      <a href="/info/license">{info_license}</a>
      <a href="/info/system">{info_system}</a>
      <a href="/info/privacy">{info_privacy}</a>
      <a href="/info/security">{info_security}</a>
      <hr class="dropdown-divider">
      <a href="/changelog">{info_changelog}</a>
      <a href="/readme">{info_readme}</a>
      <a href="/administrator">{info_administrator}</a>
      <a href="/user">{info_user}</a>
    </div>
  </details>
"#,
        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"),
    )
}

/// Wrap page content in the shared HTML layout.
///
/// `ctx.theme` must be either `"light"` or `"dark"` and comes from the
/// persisted user settings; it drives the `data-bs-theme` attribute the CSS
/// rules above react to. `ctx.lang` drives `<html lang>` and every
/// translated chrome label.
///
/// The header's right-edge control cluster is ordered Theme -> Language ->
/// Info, Info rightmost, per `skills/ndaal-design` ยง12 โ€” matching the
/// identical cluster in the sibling grundschutz app. `Settings` stays a
/// primary nav link on the left here rather than joining that cluster: this
/// app's Settings is a full page, not a quick-toggle panel like
/// grundschutz's, so it belongs with the other page links.
#[must_use]
pub fn wrap_page(title: &str, ctx: PageContext<'_>, active: Nav, content: &str) -> String {
    let theme = if ctx.theme == "dark" { "dark" } else { "light" };
    let lang = ctx.lang;
    let active_key = active.as_str();
    let nav_links = nav_links(lang, active_key);
    let theme_toggle = theme_toggle_button(lang, theme);
    let lang_switcher = language_switcher(lang);
    let info_menu = info_menu(lang, active_key);
    format!(
        r##"<!DOCTYPE html>
<html lang="{lang_code}" dir="{lang_dir}" data-bs-theme="{theme}">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>{title} โ€” CSAF</title>
<style>
{PAGE_STYLE}
</style>
<script>
{PAGE_SCRIPT}
</script>
</head>
<body>
<a href="#main-content" class="skip-link">{skip_main}</a>
<nav class="primary">
  <a href="/" class="brand" aria-label="{brand_label}">
    <img src="/static/img/logo.png" alt="{logo_alt}">
    <span class="brand-text">CSAF</span>
  </a>
{nav_links}  <span class="spacer"></span>
{theme_toggle}{lang_switcher}{info_menu}</nav>
<main id="main-content">
{content}
</main>
<footer>
  CSAF ยท Pierre Gronau โ€” ndaal Gesellschaft fรผr Sicherheit in der Informationstechnik mbH &amp; Co KG, Cologne ยท Apache-2.0
</footer>
</body>
</html>"##,
        title = title,
        theme = theme,
        lang_code = lang.code(),
        lang_dir = lang.dir(),
        content = content,
        skip_main = t(lang, "nav.skip_main"),
        brand_label = t(lang, "nav.brand_label"),
        logo_alt = t(lang, "nav.logo_alt"),
    )
}

/// 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::*;

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

    #[test]
    fn test_wrap_page_light_theme_attribute() {
        let html = wrap_page("Test", ctx("light"), Nav::Home, "<p>body</p>");
        assert!(html.contains(r#"data-bs-theme="light""#));
        assert!(html.contains("โ˜พ Dark"));
    }

    #[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-bs-theme="dark""#));
        assert!(html.contains("โ˜€ Light"));
    }

    #[test]
    fn test_wrap_page_invalid_theme_falls_back_to_light() {
        let html = wrap_page("Test", ctx("gibberish"), Nav::Home, "");
        assert!(html.contains(r#"data-bs-theme="light""#));
    }

    #[test]
    fn test_wrap_page_highlights_active_nav() {
        let html = wrap_page("Settings", ctx("light"), Nav::Settings, "");
        assert!(html.contains(r#"href="/settings" class="active""#));
        assert!(html.contains(r#"href="/" class="""#));
    }

    #[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_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_layout_uses_burgundy_red_not_blue() {
        let html = wrap_page("Test", ctx("light"), Nav::Home, "");
        assert!(
            html.contains("#8b1a1a"),
            "Should use burgundy red from logo"
        );
        assert!(!html.contains("#1a237e"), "Should not contain old blue");
    }

    #[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_wrap_page_includes_tlp_color_css() {
        let html = wrap_page("Test", ctx("light"), Nav::Home, "");
        assert!(html.contains(".tlp-select.tlp-red"));
        assert!(html.contains(".tlp-select.tlp-amber"));
        assert!(html.contains(".tlp-select.tlp-green"));
        assert!(html.contains(".tlp-select.tlp-clear"));
        // And the accompanying JS syncs on change + DOMContentLoaded.
        assert!(html.contains("DOMContentLoaded"));
        assert!(html.contains(r#""AMBER+STRICT": "tlp-amber-strict""#));
    }

    #[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_theme_language_info() {
        // skills/ndaal-design ยง12: Theme -> Language -> Info, Info rightmost,
        // matching the sibling grundschutz app's identical cluster.
        let html = wrap_page("Test", ctx("light"), Nav::Home, "");
        let theme_pos = html.find("theme-toggle").expect("theme control present");
        let lang_pos = html
            .find(r#"href="/lang/en""#)
            .expect("language control present");
        let info_pos = html
            .find(r#"href="/info/about""#)
            .expect("info control present");
        assert!(theme_pos < lang_pos, "theme must precede language");
        assert!(lang_pos < info_pos, "language must precede info");
    }

    #[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="active" aria-current="true""#
        ));
        assert!(!html.contains(r#"hreflang="en" class="active""#));
    }

    #[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`).
        insta::assert_snapshot!(language_switcher(Lang::En));
    }

    #[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">"#));
    }

    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('\''));
        }
    }
}