rustio-core 0.3.1

Runtime core for RustIO: HTTP server, router, middleware, ORM, admin, and migrations.
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
//! Auto-generated CRUD admin backed by [`crate::orm`].
//!
//! Build an [`Admin`] by chaining `.model::<T>()` calls, then mount it with
//! [`Admin::register`]. This attaches list / create / edit / delete routes
//! at `/admin/<admin_name>` for each model and an index page at `/admin`
//! listing every registered model.
//!
//! For a single-model app, [`register`] is a convenience wrapper.

use std::sync::Arc;

use bytes::Bytes;
use http_body_util::{BodyExt, Full};

use crate::error::Error;
use crate::http::{html, Request, Response};
use crate::orm::{Db, Model};
use crate::router::Router;

// `FormData` lives in `http` and is re-exported here so that the
// `#[derive(RustioAdmin)]`-generated code referencing
// `::rustio_core::admin::FormData` continues to work.
pub use crate::http::FormData;

#[derive(Debug, Clone, Copy)]
pub enum FieldType {
    I32,
    I64,
    String,
    Bool,
}

#[derive(Debug, Clone, Copy)]
pub struct AdminField {
    pub name: &'static str,
    pub ty: FieldType,
    pub editable: bool,
}

pub trait AdminModel: Model {
    const ADMIN_NAME: &'static str;
    const DISPLAY_NAME: &'static str;
    const FIELDS: &'static [AdminField];

    fn field_display(&self, name: &str) -> Option<String>;
    fn from_form(form: &FormData, id: Option<i64>) -> Result<Self, Error>;

    /// Singular form of the display name. Used for labels like "New X" and
    /// "Edit X". Defaults to [`DISPLAY_NAME`]; the `#[derive(RustioAdmin)]`
    /// macro generates a proper singular form.
    fn singular_name() -> &'static str {
        Self::DISPLAY_NAME
    }
}

/// Metadata about one registered admin model.
#[derive(Debug, Clone)]
pub struct AdminEntry {
    pub admin_name: &'static str,
    pub display_name: &'static str,
    pub singular_name: &'static str,
}

type ModelRegistrar = Box<dyn FnOnce(Router, &Db) -> Router + Send + Sync>;

/// Builder that collects admin models and mounts them with a shared
/// `/admin` index page.
///
/// ```no_run
/// use rustio_core::admin::Admin;
/// # use rustio_core::{Db, Router};
/// # fn demo(router: Router, db: &Db) -> Router {
/// # struct Post; struct User;
/// # impl rustio_core::Model for Post {
/// #   const TABLE: &'static str = "posts";
/// #   const COLUMNS: &'static [&'static str] = &[];
/// #   const INSERT_COLUMNS: &'static [&'static str] = &[];
/// #   fn id(&self) -> i64 { 0 }
/// #   fn from_row(_: rustio_core::Row<'_>) -> Result<Self, rustio_core::Error> { unimplemented!() }
/// #   fn insert_values(&self) -> Vec<rustio_core::Value> { vec![] }
/// # }
/// # impl rustio_core::Model for User {
/// #   const TABLE: &'static str = "users";
/// #   const COLUMNS: &'static [&'static str] = &[];
/// #   const INSERT_COLUMNS: &'static [&'static str] = &[];
/// #   fn id(&self) -> i64 { 0 }
/// #   fn from_row(_: rustio_core::Row<'_>) -> Result<Self, rustio_core::Error> { unimplemented!() }
/// #   fn insert_values(&self) -> Vec<rustio_core::Value> { vec![] }
/// # }
/// # impl rustio_core::admin::AdminModel for Post {
/// #   const ADMIN_NAME: &'static str = "posts"; const DISPLAY_NAME: &'static str = "Posts";
/// #   const FIELDS: &'static [rustio_core::admin::AdminField] = &[];
/// #   fn field_display(&self, _: &str) -> Option<String> { None }
/// #   fn from_form(_: &rustio_core::admin::FormData, _: Option<i64>) -> Result<Self, rustio_core::Error> { unimplemented!() }
/// # }
/// # impl rustio_core::admin::AdminModel for User {
/// #   const ADMIN_NAME: &'static str = "users"; const DISPLAY_NAME: &'static str = "Users";
/// #   const FIELDS: &'static [rustio_core::admin::AdminField] = &[];
/// #   fn field_display(&self, _: &str) -> Option<String> { None }
/// #   fn from_form(_: &rustio_core::admin::FormData, _: Option<i64>) -> Result<Self, rustio_core::Error> { unimplemented!() }
/// # }
/// Admin::new()
///     .model::<Post>()
///     .model::<User>()
///     .register(router, db)
/// # }
/// ```
pub struct Admin {
    entries: Vec<AdminEntry>,
    registrars: Vec<ModelRegistrar>,
}

impl Admin {
    pub fn new() -> Self {
        Self {
            entries: Vec::new(),
            registrars: Vec::new(),
        }
    }

    /// Register a model on this admin. Adds its metadata to the index
    /// and queues its CRUD routes for mounting.
    pub fn model<T: AdminModel>(mut self) -> Self {
        self.entries.push(AdminEntry {
            admin_name: T::ADMIN_NAME,
            display_name: T::DISPLAY_NAME,
            singular_name: T::singular_name(),
        });
        self.registrars
            .push(Box::new(|router, db| mount_model::<T>(router, db)));
        self
    }

    /// Number of registered models.
    pub fn len(&self) -> usize {
        self.entries.len()
    }

    pub fn is_empty(&self) -> bool {
        self.entries.is_empty()
    }

    /// Metadata for inspection.
    pub fn entries(&self) -> &[AdminEntry] {
        &self.entries
    }

    /// Mount the admin onto a router: installs `/admin` (index) and
    /// CRUD routes for every registered model. Admin-only; handlers
    /// return 401/403 via [`require_admin`].
    pub fn register(self, mut router: Router, db: &Db) -> Router {
        let entries = Arc::new(self.entries);
        let index_entries = entries.clone();
        router = router.get("/admin", move |req, _params| {
            let entries = index_entries.clone();
            async move {
                if let Err(resp) = admin_guard(req.ctx()) {
                    return Ok(resp);
                }
                Ok::<Response, Error>(html(admin_layout("Admin", &index_page(&entries))))
            }
        });

        // Login + logout routes. These run without admin_guard: unauthenticated
        // users *need* to reach /admin/login, and logout should work from any
        // state (idempotent cookie expiry).
        router = router.post("/admin/login", |req, _params| async move {
            handle_login(req).await
        });
        router = router.post("/admin/logout", |_req, _params| async move {
            Ok::<Response, Error>(handle_logout())
        });

        for registrar in self.registrars {
            router = registrar(router, db);
        }
        router
    }
}

impl Default for Admin {
    fn default() -> Self {
        Self::new()
    }
}

/// Convenience: mount CRUD routes and an `/admin` index for a single model.
/// Equivalent to `Admin::new().model::<T>().register(router, db)`.
pub fn register<T>(router: Router, db: &Db) -> Router
where
    T: AdminModel + Model,
{
    Admin::new().model::<T>().register(router, db)
}

fn mount_model<T>(mut router: Router, db: &Db) -> Router
where
    T: AdminModel + Model,
{
    let base = format!("/admin/{}", T::ADMIN_NAME);
    let create_path = format!("{base}/create");
    let edit_path = format!("{base}/:id/edit");
    let delete_path = format!("{base}/:id/delete");

    let list_db = db.clone();
    router = router.get(&base, move |req, _params| {
        let db = list_db.clone();
        async move {
            if let Err(resp) = admin_guard(req.ctx()) {
                return Ok(resp);
            }
            let items = T::all(&db).await?;
            Ok::<Response, Error>(html(admin_layout(T::DISPLAY_NAME, &list_page::<T>(&items))))
        }
    });

    router = router.get(&create_path, |req, _params| async move {
        if let Err(resp) = admin_guard(req.ctx()) {
            return Ok(resp);
        }
        Ok::<Response, Error>(html(admin_layout(
            &format!("New {}", T::DISPLAY_NAME),
            &form_page::<T>(None, &format!("/admin/{}/create", T::ADMIN_NAME)),
        )))
    });

    let create_db = db.clone();
    router = router.post(&create_path, move |req, _params| {
        let db = create_db.clone();
        async move {
            if let Err(resp) = admin_guard(req.ctx()) {
                return Ok(resp);
            }
            let form = read_form(req).await?;
            let item = T::from_form(&form, None)?;
            item.create(&db).await?;
            Ok::<Response, Error>(redirect(&format!("/admin/{}", T::ADMIN_NAME)))
        }
    });

    let edit_db = db.clone();
    router = router.get(&edit_path, move |req, params| {
        let db = edit_db.clone();
        async move {
            if let Err(resp) = admin_guard(req.ctx()) {
                return Ok(resp);
            }
            let id = parse_id_param(&params)?;
            let item = T::find(&db, id).await?.ok_or(Error::NotFound)?;
            Ok::<Response, Error>(html(admin_layout(
                &format!("Edit {}", T::DISPLAY_NAME),
                &form_page::<T>(
                    Some(&item),
                    &format!("/admin/{}/{}/edit", T::ADMIN_NAME, id),
                ),
            )))
        }
    });

    let update_db = db.clone();
    router = router.post(&edit_path, move |req, params| {
        let db = update_db.clone();
        async move {
            if let Err(resp) = admin_guard(req.ctx()) {
                return Ok(resp);
            }
            let id = parse_id_param(&params)?;
            let form = read_form(req).await?;
            let item = T::from_form(&form, Some(id))?;
            item.update(&db).await?;
            Ok::<Response, Error>(redirect(&format!("/admin/{}", T::ADMIN_NAME)))
        }
    });

    let delete_db = db.clone();
    router = router.post(&delete_path, move |req, params| {
        let db = delete_db.clone();
        async move {
            if let Err(resp) = admin_guard(req.ctx()) {
                return Ok(resp);
            }
            let id = parse_id_param(&params)?;
            T::delete(&db, id).await?;
            Ok::<Response, Error>(redirect(&format!("/admin/{}", T::ADMIN_NAME)))
        }
    });

    router
}

fn parse_id_param(params: &crate::router::Params) -> Result<i64, Error> {
    params
        .get("id")
        .and_then(|s| s.parse::<i64>().ok())
        .ok_or_else(|| Error::BadRequest(String::from("invalid id")))
}

async fn read_form(req: Request) -> Result<FormData, Error> {
    let (_, body, _) = req.into_parts();
    let collected = body
        .collect()
        .await
        .map_err(|e| Error::BadRequest(e.to_string()))?
        .to_bytes();
    let body_str = std::str::from_utf8(&collected).map_err(|e| Error::BadRequest(e.to_string()))?;
    Ok(FormData::parse(body_str))
}

fn redirect(to: &str) -> Response {
    hyper::Response::builder()
        .status(303)
        .header("location", to)
        .body(Full::new(Bytes::new()))
        .expect("valid redirect")
}

fn admin_layout(title: &str, content: &str) -> String {
    format!(
        r#"<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>{title} — RustIO Admin</title>
<style>{css}</style>
</head>
<body>
<header>
<h1><a href="/admin">RustIO Admin</a></h1>
<form method="post" action="/admin/logout" class="header-logout">
<button type="submit">Sign out</button>
</form>
</header>
<main>{content}</main>
</body>
</html>"#,
        title = escape_html(title),
        css = ADMIN_CSS,
        content = content,
    )
}

fn index_page(entries: &[AdminEntry]) -> String {
    if entries.is_empty() {
        return String::from(
            r#"<h2>Admin</h2>
<p class="empty">No models are registered. Add one with
<code>Admin::new().model::&lt;YourModel&gt;()</code> or scaffold an app
via <code>rustio new app &lt;name&gt;</code>.</p>"#,
        );
    }
    let rows: String = entries
        .iter()
        .map(|e| {
            format!(
                r#"<li><a href="/admin/{name}"><span class="label">{display}</span><span class="path">/admin/{name}</span></a></li>"#,
                name = escape_html(e.admin_name),
                display = escape_html(e.display_name),
            )
        })
        .collect();
    format!(
        r#"<h2>Admin</h2>
<ul class="admin-index">{rows}</ul>"#
    )
}

fn list_page<T: AdminModel>(items: &[T]) -> String {
    let headers: String = T::FIELDS
        .iter()
        .map(|f| format!("<th>{}</th>", escape_html(f.name)))
        .collect();
    let rows: String = items
        .iter()
        .map(|item| {
            let cells: String = T::FIELDS
                .iter()
                .map(|f| {
                    let v = item.field_display(f.name).unwrap_or_default();
                    format!("<td>{}</td>", escape_html(&v))
                })
                .collect();
            let id = item.id();
            let actions = format!(
                r#"<td class="actions">
<a href="/admin/{name}/{id}/edit">edit</a>
<form method="post" action="/admin/{name}/{id}/delete">
<button type="submit" class="danger">delete</button>
</form>
</td>"#,
                name = T::ADMIN_NAME,
                id = id,
            );
            format!("<tr>{cells}{actions}</tr>")
        })
        .collect();

    format!(
        r#"<div class="toolbar">
<h2>{title}</h2>
<a class="button" href="/admin/{name}/create">New {singular}</a>
</div>
<table>
<thead><tr>{headers}<th>actions</th></tr></thead>
<tbody>{rows}</tbody>
</table>"#,
        title = escape_html(T::DISPLAY_NAME),
        singular = escape_html(T::singular_name()),
        name = T::ADMIN_NAME,
    )
}

fn form_page<T: AdminModel>(item: Option<&T>, action: &str) -> String {
    let fields: String = T::FIELDS
        .iter()
        .filter(|f| f.editable)
        .map(|f| render_field::<T>(f, item))
        .collect();
    let heading = if item.is_some() {
        format!("Edit {}", T::singular_name())
    } else {
        format!("New {}", T::singular_name())
    };
    format!(
        r#"<h2>{heading}</h2>
<form method="post" action="{action}">
{fields}
<div class="form-actions">
<button type="submit">Save</button>
<a class="cancel" href="/admin/{name}">Cancel</a>
</div>
</form>"#,
        heading = escape_html(&heading),
        action = escape_html(action),
        name = T::ADMIN_NAME,
    )
}

fn render_field<T: AdminModel>(f: &AdminField, item: Option<&T>) -> String {
    let current = item
        .and_then(|i| i.field_display(f.name))
        .unwrap_or_default();
    let input = match f.ty {
        FieldType::Bool => format!(
            r#"<input type="checkbox" name="{n}" {checked}>"#,
            n = escape_html(f.name),
            checked = if current == "true" { "checked" } else { "" },
        ),
        FieldType::I32 | FieldType::I64 => format!(
            r#"<input type="number" name="{n}" value="{v}">"#,
            n = escape_html(f.name),
            v = escape_html(&current),
        ),
        FieldType::String => format!(
            r#"<input type="text" name="{n}" value="{v}">"#,
            n = escape_html(f.name),
            v = escape_html(&current),
        ),
    };
    format!(
        r#"<label><span>{label}</span>{input}</label>"#,
        label = escape_html(f.name),
        input = input,
    )
}

/// Gate every admin request behind [`require_admin`], but convert the
/// resulting `Error::Unauthorized` / `Error::Forbidden` into a friendly
/// HTML response instead of the default `text/plain` body.
///
/// Returns `Ok(())` when the caller is admin and should continue.
/// Returns `Err(Response)` with a ready-made HTML error page otherwise.
//
// `Response` is moderately large; clippy's `result_large_err` would
// rather we box it. Each call site only constructs one per request and
// the call count per request is at most one, so the nominal size cost
// is irrelevant — boxing would only add noise.
#[allow(clippy::result_large_err)]
fn admin_guard(ctx: &crate::context::Context) -> Result<(), Response> {
    // 401 renders a login form (so browser users can actually sign in).
    // 403 renders a static "forbidden" page (the user is authenticated
    // but not admin — there's nothing to type into a form that would
    // change that).
    match crate::auth::require_admin(ctx) {
        Ok(_) => Ok(()),
        Err(Error::Unauthorized) => Err(login_page(401, None)),
        Err(Error::Forbidden) => Err(forbidden_page()),
        Err(other) => Err(other.into_response()),
    }
}

/// Render the login page. Status is 401 on a pure auth-gate hit and
/// 400 on failed submissions (with `error` set to an explanation).
fn login_page(status: u16, error: Option<&str>) -> Response {
    let error_html = match error {
        Some(msg) => format!(r#"<p class="error">{}</p>"#, escape_html(msg)),
        None => String::new(),
    };

    // In production the dev-token hint is suppressed. The form is still
    // shown — the developer might have wired a different `authenticate`
    // middleware that accepts other tokens via the same cookie.
    let hint = if crate::auth::in_production() {
        String::new()
    } else {
        String::from(
            r#"<p class="hint">Development tokens: <code>dev-admin</code> (full access) · <code>dev-user</code> (non-admin, to preview 403).</p>"#,
        )
    };

    let body = format!(
        r#"<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Sign in — RustIO Admin</title>
<style>{css}</style>
</head>
<body>
<header><h1><a href="/admin">RustIO Admin</a></h1></header>
<main class="auth-card">
<h2>Sign in</h2>
<form method="post" action="/admin/login" autocomplete="off">
<label><span>Token</span>
<input type="password" name="token" autofocus required>
</label>
{error}
<button type="submit">Sign in</button>
</form>
{hint}
</main>
</body>
</html>"#,
        css = ADMIN_CSS,
        error = error_html,
        hint = hint,
    );

    hyper::Response::builder()
        .status(status)
        .header("content-type", "text/html; charset=utf-8")
        .body(Full::new(Bytes::from(body)))
        .expect("valid response")
}

fn forbidden_page() -> Response {
    let body = format!(
        r#"<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>403 Forbidden — RustIO Admin</title>
<style>{css}</style>
</head>
<body>
<header><h1><a href="/admin">RustIO Admin</a></h1></header>
<main class="auth-error">
<div class="status">403</div>
<p class="heading">Forbidden</p>
<p class="hint">You are signed in but your account isn't an admin.</p>
<form method="post" action="/admin/logout" class="inline">
<button type="submit" class="secondary">Sign out</button>
</form>
</main>
</body>
</html>"#,
        css = ADMIN_CSS,
    );

    hyper::Response::builder()
        .status(403)
        .header("content-type", "text/html; charset=utf-8")
        .body(Full::new(Bytes::from(body)))
        .expect("valid response")
}

/// `POST /admin/login` — validate the submitted token against
/// `authenticate`'s dev token mapping (when RUSTIO_ENV != production)
/// and set the `rustio_token` cookie so subsequent requests carry it
/// automatically.
async fn handle_login(req: Request) -> Result<Response, Error> {
    let form = read_form(req).await?;
    let token = form.get("token").unwrap_or("").trim().to_string();

    if token.is_empty() {
        return Ok(login_page(400, Some("Token is required.")));
    }

    // Production mode disables dev tokens entirely. A real deployment
    // would replace `authenticate` with its own middleware that recognises
    // production tokens via the same cookie; this branch is the safe
    // default when no such middleware is installed.
    if crate::auth::in_production() {
        return Ok(login_page(
            401,
            Some("Sign-in is disabled in production until a real auth middleware is installed."),
        ));
    }

    if crate::auth::dev_identity(&token).is_none() {
        return Ok(login_page(401, Some("That token is not recognised.")));
    }

    // Success: drop a cookie scoped to the site and redirect to /admin.
    // HttpOnly prevents JS read (XSS hardening), SameSite=Strict prevents
    // cross-site submission (CSRF hardening for this cookie).
    let mut resp = redirect("/admin");
    crate::http::set_cookie(
        &mut resp,
        &format!("rustio_token={token}; Path=/; HttpOnly; SameSite=Strict"),
    );
    Ok(resp)
}

/// `POST /admin/logout` — clear the cookie and send the user back to
/// `/admin` (which will re-render the login page).
fn handle_logout() -> Response {
    let mut resp = redirect("/admin");
    crate::http::set_cookie(
        &mut resp,
        "rustio_token=; Path=/; HttpOnly; SameSite=Strict; Max-Age=0",
    );
    resp
}

fn escape_html(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    for ch in s.chars() {
        match ch {
            '&' => out.push_str("&amp;"),
            '<' => out.push_str("&lt;"),
            '>' => out.push_str("&gt;"),
            '"' => out.push_str("&quot;"),
            '\'' => out.push_str("&#39;"),
            c => out.push(c),
        }
    }
    out
}

const ADMIN_CSS: &str = r#"
*, *::before, *::after { box-sizing: border-box; }
body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
  background: #fafafa; color: #222; margin: 0; }
header { background: #222; color: white; padding: 1rem 2rem; display: flex; align-items: center; justify-content: space-between; }
header h1 { margin: 0; font-size: 1.1rem; font-weight: 600; letter-spacing: 0.02em; }
header h1 a { color: inherit; text-decoration: none; }
header h1 a:hover { opacity: 0.9; }
header .header-logout { margin: 0; }
header .header-logout button { background: transparent; color: #d8d8dc; border: 1px solid #444; padding: 0.35rem 0.75rem; font-size: 0.85rem; border-radius: 4px; cursor: pointer; }
header .header-logout button:hover { background: #2f2f33; color: white; }
ul.admin-index { list-style: none; padding: 0; margin: 0; display: grid; gap: 0.5rem; }
ul.admin-index li { background: white; border-radius: 6px; box-shadow: 0 1px 3px rgba(0,0,0,0.04); }
ul.admin-index li a { display: flex; justify-content: space-between; align-items: center; padding: 0.9rem 1.1rem; text-decoration: none; color: #222; }
ul.admin-index li a:hover { background: #f4f4f5; }
ul.admin-index li .label { font-weight: 600; }
ul.admin-index li .path { color: #888; font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: 0.85rem; }
p.empty { color: #666; }
p.empty code { background: #f0f0f2; padding: 0.1rem 0.35rem; border-radius: 3px; font-size: 0.9em; }
.auth-error { text-align: center; padding: 3rem 2rem; max-width: 36rem; margin: 0 auto; }
.auth-error .status { font-size: 3rem; font-weight: 700; color: #b42318; line-height: 1; }
.auth-error .heading { font-size: 1.15rem; margin: 0.5rem 0 1.5rem; font-weight: 600; color: #222; }
.auth-error .hint { background: #fff7ed; border: 1px solid #fed7aa; color: #9a3412; padding: 0.85rem 1rem; border-radius: 6px; text-align: left; font-size: 0.92rem; line-height: 1.5; }
.auth-error .hint code { background: #fdefe0; color: #7c2d12; padding: 0.1rem 0.35rem; border-radius: 3px; font-size: 0.9em; display: inline-block; }
.auth-error form.inline { margin-top: 1rem; }
.auth-error form.inline button.secondary { background: transparent; border: 1px solid #d0d0d4; color: #222; }
.auth-card { max-width: 22rem; margin: 2.5rem auto; padding: 2rem; background: white; border-radius: 8px; box-shadow: 0 4px 20px rgba(0,0,0,0.05); }
.auth-card h2 { margin: 0 0 1.25rem; font-size: 1.25rem; }
.auth-card label { display: block; margin: 0 0 0.9rem; }
.auth-card label span { display: block; font-weight: 500; margin-bottom: 0.25rem; font-size: 0.9rem; }
.auth-card input[type=password] { width: 100%; padding: 0.55rem 0.75rem; border: 1px solid #d0d0d4; border-radius: 4px; font: inherit; }
.auth-card button[type=submit] { width: 100%; padding: 0.6rem 1rem; background: #222; color: white; border: none; border-radius: 4px; font: inherit; cursor: pointer; }
.auth-card button[type=submit]:hover { background: #000; }
.auth-card .error { background: #fef2f2; color: #991b1b; border: 1px solid #fecaca; padding: 0.6rem 0.8rem; border-radius: 4px; margin: 0 0 0.9rem; font-size: 0.9rem; }
.auth-card .hint { color: #666; font-size: 0.85rem; margin: 1rem 0 0; line-height: 1.5; }
.auth-card .hint code { background: #f0f0f2; padding: 0.1rem 0.3rem; border-radius: 3px; font-size: 0.85em; }
main { padding: 2rem; max-width: 60rem; margin: 0 auto; }
h2 { margin: 0; }
.toolbar { display: flex; align-items: center; justify-content: space-between; margin-bottom: 1.5rem; }
table { border-collapse: collapse; width: 100%; background: white; border-radius: 6px; overflow: hidden;
  box-shadow: 0 1px 3px rgba(0,0,0,0.04); }
th, td { text-align: left; padding: 0.6rem 0.9rem; border-bottom: 1px solid #eee; font-size: 0.95rem; }
th { background: #f4f4f5; font-weight: 600; }
tbody tr:last-child td { border-bottom: none; }
td.actions { display: flex; gap: 0.5rem; align-items: center; }
td.actions form { margin: 0; display: inline; }
a { color: #0366d6; text-decoration: none; }
a:hover { text-decoration: underline; }
label { display: block; margin-bottom: 1rem; }
label span { display: block; font-weight: 500; margin-bottom: 0.25rem; font-size: 0.9rem; }
input[type=text], input[type=number] { padding: 0.5rem 0.75rem; border: 1px solid #d0d0d4;
  border-radius: 4px; width: 24rem; max-width: 100%; font: inherit; }
input[type=checkbox] { transform: scale(1.1); }
button, .button { padding: 0.5rem 1rem; background: #222; color: white; border: none;
  border-radius: 4px; cursor: pointer; font: inherit; text-decoration: none; display: inline-block; }
button:hover, .button:hover { background: #000; text-decoration: none; }
button.danger { background: #b42318; }
button.danger:hover { background: #8a1c12; }
.form-actions { display: flex; gap: 0.5rem; align-items: center; margin-top: 1rem; }
.form-actions .cancel { color: #666; }
"#;

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

    #[test]
    fn escape_html_escapes_dangerous_chars() {
        assert_eq!(
            escape_html("<script>alert(\"xss\")</script>"),
            "&lt;script&gt;alert(&quot;xss&quot;)&lt;/script&gt;"
        );
        assert_eq!(escape_html("a & b"), "a &amp; b");
        assert_eq!(escape_html("it's"), "it&#39;s");
    }
}