frame-host 0.3.0

Frame host server and embedding seam — boots an application's frame-core component tree with an embedded liminal bus, announces the host's real application events on the bus, and serves the built frame page
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
//! Static shell server for the browser client bundle.
//!
//! Serves exactly one directory of static files (the demo client's `dist/`:
//! `index.html` at the root plus hashed bundle files, typically under
//! `assets/`, including the `GraphMother` `.wasm`). Resolution is exact:
//!
//! - `GET /` serves `index.html`; every other path must name a real file.
//! - A missing asset is a typed, loud 404 page — NEVER an index.html
//!   fallback. SPA fallbacks silently mask broken asset paths (a `.wasm`
//!   request answered with HTML burned this exact demo once already).
//! - Traversal (`..`, absolute components, NUL) and malformed encodings are
//!   refused with typed 400 pages; symlink escapes are refused by
//!   canonical-prefix checking.
//!
//! `GET /frame/config.json` surfaces the bus endpoint to the page (as
//! `busEndpoint`, plus the deprecated duplicate `liminalEndpoint` for one
//! compatibility window). Per D3 the browser connects to the bus directly as
//! a participant; this server carries no feed bytes.
//!
//! `GET /frame/app/status.json` (2026-07-21 boot-visibility fix, see
//! [`crate::truth`]) serves the process's CURRENT application-truth
//! snapshot: every lifecycle transition and announced fact observed so far,
//! in order. A client fetches this on the SAME surface as `/frame/config.json`
//! — reachable the instant this server binds, before the announcer pump has
//! drained a single event onto the bus — then follows the live channel for
//! what happens next.
//!
//! `GET /frame/bus/{health,ready,metrics}` are the same-origin proxy
//! routes for the embedded bus health listener ([`crate::bus_proxy`]):
//! observability HTTP only, never feed bytes, forwarded verbatim with typed
//! bounded failure. The pre-rename routes `/frame/liminal/*` answer as
//! deprecated aliases (same handlers, loud per-hit `tracing::warn!`) for the
//! same window.

use std::net::SocketAddr;
use std::path::{Path, PathBuf};
use std::sync::Arc;

use axum::Router;
use axum::body::Body;
use axum::extract::{Request, State};
use axum::http::{HeaderValue, Method, StatusCode, header};
use axum::response::{IntoResponse, Response};
use axum::routing::get;
use serde::Serialize;
use tokio::net::TcpListener;

use crate::bus_proxy::{
    BUS_HEALTH_ROUTE, BUS_METRICS_ROUTE, BUS_READY_ROUTE, LEGACY_LIMINAL_HEALTH_ROUTE,
    LEGACY_LIMINAL_METRICS_ROUTE, LEGACY_LIMINAL_READY_ROUTE, PRODUCTION_DEADLINES,
    bus_metrics_body, failure_response, forward_health_request, passthrough_response,
};
use crate::error::HostError;
use crate::truth::AppTruth;

/// Route on which the page fetches its runtime configuration.
pub const CONFIG_ROUTE: &str = "/frame/config.json";

/// Route on which a client fetches the CURRENT application-truth snapshot
/// (2026-07-21 boot-visibility fix, [`crate::truth`]): every lifecycle
/// transition and announced fact observed so far, in order. Named alongside
/// [`CONFIG_ROUTE`] under the same `/frame/` namespace, matching this
/// module's own route-naming idiom.
pub const APP_STATUS_ROUTE: &str = "/frame/app/status.json";

/// Configuration for one shell server instance. No field has a default.
#[derive(Clone, Debug)]
pub struct ShellConfig {
    /// Socket address to bind.
    pub bind: SocketAddr,
    /// Directory containing the static client bundle.
    pub asset_root: PathBuf,
    /// Bus WebSocket endpoint surfaced verbatim to the page (D3).
    pub bus_endpoint: String,
    /// Bearer token surfaced verbatim as `authToken`; empty = open server.
    pub auth_token: String,
    /// Feed channel; omitted from the served config when `None` so the shell
    /// applies the SDK's `DEFAULT_FEED_CHANNEL`. Stays the console's PRIMARY
    /// (default-selected) channel.
    pub channel: Option<String>,
    /// The FULL channel list of the embedded liminal component, served verbatim
    /// as `channels` — the console subscribes every one of them. Must be
    /// non-empty, duplicate-free, all entries non-empty, and contain `channel`
    /// when one is provided.
    pub channels: Vec<String>,
    /// The embedded bus health listener's real bound address — the target
    /// of the same-origin `/frame/bus/*` proxy routes.
    pub bus_health: SocketAddr,
    /// The optional document-service advert (IRIDIUM-A3 C2's config.json
    /// growth): served as `document` when `[document]` is configured.
    pub document: Option<DocumentAdvert>,
    /// The process's application-truth recorder (2026-07-21
    /// boot-visibility fix): backs [`APP_STATUS_ROUTE`]. See [`crate::truth`].
    pub truth: Arc<AppTruth>,
}

/// What the authoring page needs to bind the `frame:code-editor@v1`
/// component: the document id, the component instance, and the two
/// channels (C2: feed + authoring per document).
#[derive(Clone, Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct DocumentAdvert {
    /// The bound document id.
    pub id: String,
    /// The component instance id on every feed envelope.
    pub component_id: String,
    /// The feed channel (service publishes; pages subscribe).
    pub feed_channel: String,
    /// The authoring channel (pages publish; the service subscribes).
    pub authoring_channel: String,
    /// The component's declared cursor-blink interval (T4), milliseconds.
    pub blink_interval_ms: u64,
}

/// Runtime configuration served to the page at [`CONFIG_ROUTE`], matching
/// the shell's validation in `examples/frame-demo/src/config.ts` exactly:
/// non-empty `busEndpoint`, string `authToken` (empty = open server),
/// `channel` present only when the operator provided one, and `channels` —
/// the embedded bus's full configured channel list — always present.
#[derive(Clone, Debug, Serialize)]
#[serde(rename_all = "camelCase")]
struct ShellRuntimeConfig {
    /// The embedded bus's WebSocket endpoint — the primary field.
    bus_endpoint: String,
    /// DEPRECATED duplicate of `bus_endpoint`, served as `liminalEndpoint`
    /// for one compatibility window; remove with the `[liminal]` config alias.
    liminal_endpoint: String,
    auth_token: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    channel: Option<String>,
    channels: Vec<String>,
    /// The document-service advert; absent when no `[document]` is
    /// configured (the page fails loudly if it needs one).
    #[serde(skip_serializing_if = "Option::is_none")]
    document: Option<DocumentAdvert>,
}

struct ShellState {
    asset_root: PathBuf,
    config: ShellRuntimeConfig,
    bus_health: SocketAddr,
    truth: Arc<AppTruth>,
}

/// A bound-but-not-yet-serving shell server.
pub struct ShellServer {
    listener: TcpListener,
    router: Router,
    addr: SocketAddr,
}

impl ShellServer {
    /// Validates the asset root and the served config contract, then binds
    /// the listener.
    ///
    /// # Errors
    ///
    /// Refuses an unreadable or non-directory asset root, a root without
    /// `index.html`, a config the shell's contract would refuse (empty
    /// `busEndpoint`, empty provided `channel`), and any bind failure —
    /// all typed. Serving a config the shell will refuse at parse time is a
    /// composition error the host catches here, not in the browser.
    pub async fn bind(config: ShellConfig) -> Result<Self, HostError> {
        let bind_addr = config.bind;
        let router = Self::prepare(config)?;
        let listener = TcpListener::bind(bind_addr)
            .await
            .map_err(|source| HostError::Bind {
                addr: bind_addr,
                source,
            })?;
        let addr = listener.local_addr().map_err(|source| HostError::Bind {
            addr: bind_addr,
            source,
        })?;
        Ok(Self {
            listener,
            router,
            addr,
        })
    }

    /// Adopts an ALREADY-BOUND listener (from [`crate::page::PageServer`])
    /// instead of binding its own, then validates the served config contract
    /// exactly as [`Self::bind`] does.
    ///
    /// The page-server port is resolved and BOUND up front (prefer-and-walk, or
    /// stated-and-exact) before the embedded bus boots, so its real address can
    /// seed the bus's derived origin allow-list. Handing the held listener
    /// straight here — rather than probing a port, dropping it, and re-binding
    /// — is what makes that resolution race-free: no other process can claim
    /// the port in between. `config.bind` is ignored (the listener is already
    /// bound); the real bound address is read from the listener itself.
    ///
    /// # Errors
    ///
    /// Refuses the same config-contract and asset-root violations as
    /// [`Self::bind`], and any failure converting the adopted std listener to a
    /// non-blocking async listener.
    pub fn adopt(listener: std::net::TcpListener, config: ShellConfig) -> Result<Self, HostError> {
        let router = Self::prepare(config)?;
        listener.set_nonblocking(true).map_err(|source| {
            let addr = listener
                .local_addr()
                .unwrap_or_else(|_| std::net::SocketAddr::from(([127, 0, 0, 1], 0)));
            HostError::Bind { addr, source }
        })?;
        let addr = listener.local_addr().map_err(|source| HostError::Bind {
            addr: std::net::SocketAddr::from(([127, 0, 0, 1], 0)),
            source,
        })?;
        let listener =
            TcpListener::from_std(listener).map_err(|source| HostError::Bind { addr, source })?;
        Ok(Self {
            listener,
            router,
            addr,
        })
    }

    /// Validates the served config contract and asset root, then builds the
    /// router — the shared body of [`Self::bind`] and [`Self::adopt`], which
    /// differ only in where the listener comes from.
    fn prepare(config: ShellConfig) -> Result<Router, HostError> {
        if config.bus_endpoint.is_empty() {
            return Err(HostError::ConfigContract {
                detail: "the bus endpoint is empty: it is derived from the embedded \
                         WebSocket listener's bound address, which must never be empty — this is \
                         an internal error, not an operator one"
                    .to_owned(),
            });
        }
        if let Some(channel) = &config.channel
            && channel.is_empty()
        {
            return Err(HostError::ConfigContract {
                detail: "[frame].channel, when set, must be non-empty: the console refuses an \
                         empty channel with CONFIG_INVALID; omit the key to use the SDK's default \
                         channel"
                    .to_owned(),
            });
        }
        validate_channels_contract(&config.channels, config.channel.as_deref())?;
        let asset_root =
            config
                .asset_root
                .canonicalize()
                .map_err(|error| HostError::AssetRoot {
                    path: config.asset_root.clone(),
                    detail: error.to_string(),
                })?;
        if !asset_root.is_dir() {
            return Err(HostError::AssetRoot {
                path: config.asset_root.clone(),
                detail: "not a directory".to_owned(),
            });
        }
        if !asset_root.join("index.html").is_file() {
            return Err(HostError::MissingIndex {
                path: config.asset_root.clone(),
            });
        }
        let state = Arc::new(ShellState {
            asset_root,
            config: ShellRuntimeConfig {
                bus_endpoint: config.bus_endpoint.clone(),
                // Deprecated duplicate, same value — one compatibility window.
                liminal_endpoint: config.bus_endpoint,
                auth_token: config.auth_token,
                channel: config.channel,
                channels: config.channels,
                document: config.document,
            },
            bus_health: config.bus_health,
            truth: config.truth,
        });
        Ok(Router::new()
            .route(CONFIG_ROUTE, get(serve_config))
            .route(APP_STATUS_ROUTE, get(serve_app_status))
            .route(BUS_HEALTH_ROUTE, get(proxy_bus_health))
            .route(BUS_READY_ROUTE, get(proxy_bus_ready))
            .route(BUS_METRICS_ROUTE, get(proxy_bus_metrics))
            // DEPRECATED aliases (compatibility window): same handlers, loud
            // per-hit deprecation warning — never a silent legacy acceptance.
            .route(LEGACY_LIMINAL_HEALTH_ROUTE, get(proxy_legacy_health))
            .route(LEGACY_LIMINAL_READY_ROUTE, get(proxy_legacy_ready))
            .route(LEGACY_LIMINAL_METRICS_ROUTE, get(proxy_legacy_metrics))
            .fallback(serve_asset)
            .with_state(state))
    }

    /// The address actually bound (resolves an ephemeral port request).
    #[must_use]
    pub const fn local_addr(&self) -> SocketAddr {
        self.addr
    }

    /// Serves until `shutdown` resolves.
    ///
    /// # Errors
    ///
    /// Propagates accept-loop failures as typed serve errors.
    pub async fn serve(
        self,
        shutdown: impl Future<Output = ()> + Send + 'static,
    ) -> Result<(), HostError> {
        axum::serve(self.listener, self.router)
            .with_graceful_shutdown(shutdown)
            .await
            .map_err(|source| HostError::Serve { source })
    }
}

/// Refuses a served `channels` roster the console's own config contract would
/// reject: it must be non-empty (the console subscribes every entry), every
/// entry must be non-empty, entries must be unique (a duplicate would open two
/// identical subscriptions — liminal's own validator refuses the same shape),
/// and it must contain `channel` when one is provided (the console refuses a
/// roster that omits its primary channel with `CONFIG_INVALID`).
fn validate_channels_contract(channels: &[String], channel: Option<&str>) -> Result<(), HostError> {
    if channels.is_empty() {
        return Err(HostError::ConfigContract {
            detail: "the served channels roster is empty: the console subscribes every entry of \
                     `channels`, so an empty roster leaves it with no feed — it is derived from \
                     [bus].channels, which must declare at least one channel"
                .to_owned(),
        });
    }
    let mut seen = std::collections::HashSet::new();
    for entry in channels {
        if entry.is_empty() {
            return Err(HostError::ConfigContract {
                detail: "the served channels roster contains an empty channel name: the console \
                         refuses an empty channel with CONFIG_INVALID"
                    .to_owned(),
            });
        }
        if !seen.insert(entry.as_str()) {
            return Err(HostError::ConfigContract {
                detail: format!(
                    "the served channels roster names \"{entry}\" more than once: a duplicate \
                     would open two identical subscriptions, and liminal's own config validation \
                     refuses duplicate channel names"
                ),
            });
        }
    }
    if let Some(channel) = channel
        && !channels.iter().any(|entry| entry == channel)
    {
        return Err(HostError::ConfigContract {
            detail: format!(
                "the served channels roster [{roster}] does not contain the primary channel \
                 \"{channel}\": the console refuses that pair with CONFIG_INVALID",
                roster = channels.join(", ")
            ),
        });
    }
    Ok(())
}

async fn serve_config(State(state): State<Arc<ShellState>>) -> Response {
    tracing::info!(route = CONFIG_ROUTE, "serving shell runtime configuration");
    axum::Json(state.config.clone()).into_response()
}

/// Serves the CURRENT application-truth snapshot (2026-07-21
/// boot-visibility fix, [`crate::truth`]): every lifecycle transition and
/// announced fact this process has produced so far, in order. Reachable the
/// instant this server binds — before the announcer pump has drained a
/// single event onto the bus — so a client can observe the full boot
/// history without racing the bus at all.
async fn serve_app_status(State(state): State<Arc<ShellState>>) -> Response {
    let snapshot = state.truth.snapshot();
    tracing::info!(
        route = APP_STATUS_ROUTE,
        transitions = snapshot.transitions.len(),
        facts = snapshot.facts.len(),
        "serving application-truth snapshot"
    );
    axum::Json(snapshot).into_response()
}

async fn proxy_bus_health(State(state): State<Arc<ShellState>>) -> Response {
    proxy_bus(&state, BUS_HEALTH_ROUTE, "/health").await
}

async fn proxy_bus_ready(State(state): State<Arc<ShellState>>) -> Response {
    proxy_bus(&state, BUS_READY_ROUTE, "/ready").await
}

async fn proxy_bus_metrics(State(state): State<Arc<ShellState>>) -> Response {
    proxy_bus(&state, BUS_METRICS_ROUTE, "/metrics").await
}

async fn proxy_legacy_health(State(state): State<Arc<ShellState>>) -> Response {
    warn_legacy_route(LEGACY_LIMINAL_HEALTH_ROUTE, BUS_HEALTH_ROUTE);
    proxy_bus(&state, LEGACY_LIMINAL_HEALTH_ROUTE, "/health").await
}

async fn proxy_legacy_ready(State(state): State<Arc<ShellState>>) -> Response {
    warn_legacy_route(LEGACY_LIMINAL_READY_ROUTE, BUS_READY_ROUTE);
    proxy_bus(&state, LEGACY_LIMINAL_READY_ROUTE, "/ready").await
}

async fn proxy_legacy_metrics(State(state): State<Arc<ShellState>>) -> Response {
    warn_legacy_route(LEGACY_LIMINAL_METRICS_ROUTE, BUS_METRICS_ROUTE);
    proxy_bus(&state, LEGACY_LIMINAL_METRICS_ROUTE, "/metrics").await
}

/// The loud, per-hit deprecation on a legacy `/frame/liminal/*` alias — a
/// legacy-name acceptance is never silent.
fn warn_legacy_route(route: &'static str, replacement: &'static str) {
    tracing::warn!(
        route,
        replacement,
        "DEPRECATED route served: /frame/liminal/* is the legacy alias of /frame/bus/*; update \
         the client to the bus route — the alias is removed after one compatibility window"
    );
}

/// Forwards one same-origin health-proxy request to the embedded bus
/// health listener, passing the upstream response through verbatim (the
/// metrics body alone is re-vocabularied by [`bus_metrics_body`]) and
/// rendering any forwarding failure as its typed, bounded 502 body.
async fn proxy_bus(state: &ShellState, route: &'static str, upstream_path: &str) -> Response {
    match forward_health_request(state.bus_health, upstream_path, PRODUCTION_DEADLINES).await {
        Ok(mut upstream) => {
            if upstream_path == "/metrics" {
                upstream.body = bus_metrics_body(&upstream.body);
            }
            tracing::info!(
                route,
                upstream_path,
                status = upstream.status,
                bytes = upstream.body.len(),
                "proxied bus health route"
            );
            passthrough_response(upstream)
        }
        Err(failure) => {
            tracing::error!(
                route,
                upstream_path,
                code = failure.code(),
                detail = failure.detail(),
                "bus health proxy failed typed"
            );
            failure_response(upstream_path, &failure)
        }
    }
}

async fn serve_asset(State(state): State<Arc<ShellState>>, request: Request) -> Response {
    let method = request.method().clone();
    let raw_path = request.uri().path().to_owned();
    if method != Method::GET && method != Method::HEAD {
        tracing::warn!(%method, path = %raw_path, "method not allowed on static shell");
        return error_page(
            StatusCode::METHOD_NOT_ALLOWED,
            "METHOD NOT ALLOWED",
            &format!("The static shell serves GET and HEAD only; {method} was refused."),
        );
    }
    let relative = match sanitize_request_path(&raw_path) {
        Ok(relative) => relative,
        Err(refusal) => {
            tracing::warn!(path = %raw_path, %refusal, "refusing malformed asset path");
            return error_page(StatusCode::BAD_REQUEST, "BAD ASSET PATH", &refusal);
        }
    };
    let candidate = state.asset_root.join(&relative);
    let resolved = match candidate.canonicalize() {
        Ok(resolved) => resolved,
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
            tracing::warn!(path = %raw_path, "asset not found");
            return not_found_page(&raw_path, &state.asset_root);
        }
        Err(error) => {
            tracing::error!(path = %raw_path, %error, "asset resolution failed");
            return error_page(
                StatusCode::INTERNAL_SERVER_ERROR,
                "ASSET RESOLUTION FAILED",
                &format!("Resolving {raw_path} failed: {error}"),
            );
        }
    };
    if !resolved.starts_with(&state.asset_root) {
        tracing::warn!(path = %raw_path, resolved = %resolved.display(), "asset escapes the asset root");
        return error_page(
            StatusCode::BAD_REQUEST,
            "BAD ASSET PATH",
            "The requested path resolves outside the configured asset directory.",
        );
    }
    if !resolved.is_file() {
        tracing::warn!(path = %raw_path, "asset path is not a file");
        return not_found_page(&raw_path, &state.asset_root);
    }
    match tokio::fs::read(&resolved).await {
        Ok(bytes) => {
            let mime = mime_for(&resolved);
            tracing::info!(path = %raw_path, bytes = bytes.len(), mime, "served asset");
            let mut response = Response::new(Body::from(bytes));
            response
                .headers_mut()
                .insert(header::CONTENT_TYPE, HeaderValue::from_static(mime));
            response
        }
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
            tracing::warn!(path = %raw_path, "asset vanished between resolution and read");
            not_found_page(&raw_path, &state.asset_root)
        }
        Err(error) => {
            tracing::error!(path = %raw_path, %error, "asset read failed");
            error_page(
                StatusCode::INTERNAL_SERVER_ERROR,
                "ASSET READ FAILED",
                &format!("Reading {raw_path} failed: {error}"),
            )
        }
    }
}

/// Decodes and validates a request path into a root-relative file path.
///
/// `/` maps to `index.html`. Every component must be a plain name: empty,
/// `.`, `..`, NUL-bearing, and backslash-bearing components are refused, as
/// is any malformed percent-encoding.
fn sanitize_request_path(raw: &str) -> Result<PathBuf, String> {
    let decoded = percent_decode(raw)?;
    let Some(stripped) = decoded.strip_prefix('/') else {
        return Err("request path must start with '/'".to_owned());
    };
    if stripped.is_empty() {
        return Ok(PathBuf::from("index.html"));
    }
    let mut relative = PathBuf::new();
    for component in stripped.split('/') {
        if component.is_empty() {
            return Err("empty path component (doubled or trailing '/')".to_owned());
        }
        if component == "." || component == ".." {
            return Err("relative path components are refused".to_owned());
        }
        if component.contains('\0') || component.contains('\\') {
            return Err("path component contains a refused character".to_owned());
        }
        relative.push(component);
    }
    Ok(relative)
}

/// Strict RFC 3986 percent-decoding: every `%` must head two hex digits and
/// the decoded bytes must be valid UTF-8.
fn percent_decode(raw: &str) -> Result<String, String> {
    if !raw.contains('%') {
        return Ok(raw.to_owned());
    }
    let bytes = raw.as_bytes();
    let mut decoded = Vec::with_capacity(bytes.len());
    let mut index = 0;
    while index < bytes.len() {
        if bytes[index] == b'%' {
            let (Some(high), Some(low)) = (
                bytes.get(index + 1).and_then(|byte| hex_value(*byte)),
                bytes.get(index + 2).and_then(|byte| hex_value(*byte)),
            ) else {
                return Err("malformed percent-encoding".to_owned());
            };
            decoded.push(high * 16 + low);
            index += 3;
        } else {
            decoded.push(bytes[index]);
            index += 1;
        }
    }
    String::from_utf8(decoded).map_err(|_| "percent-encoding decodes to invalid UTF-8".to_owned())
}

const fn hex_value(byte: u8) -> Option<u8> {
    match byte {
        b'0'..=b'9' => Some(byte - b'0'),
        b'a'..=b'f' => Some(byte - b'a' + 10),
        b'A'..=b'F' => Some(byte - b'A' + 10),
        _ => None,
    }
}

/// Explicit MIME map. `application/wasm` is load-bearing: browsers refuse
/// `WebAssembly.instantiateStreaming` on anything else.
fn mime_for(path: &Path) -> &'static str {
    let extension = path
        .extension()
        .and_then(|extension| extension.to_str())
        .map(str::to_ascii_lowercase);
    match extension.as_deref() {
        Some("html") => "text/html; charset=utf-8",
        Some("js" | "mjs") => "text/javascript; charset=utf-8",
        Some("css") => "text/css; charset=utf-8",
        Some("wasm") => "application/wasm",
        Some("json" | "map") => "application/json; charset=utf-8",
        Some("svg") => "image/svg+xml",
        Some("png") => "image/png",
        Some("jpg" | "jpeg") => "image/jpeg",
        Some("gif") => "image/gif",
        Some("webp") => "image/webp",
        Some("ico") => "image/x-icon",
        Some("txt") => "text/plain; charset=utf-8",
        Some("woff") => "font/woff",
        Some("woff2") => "font/woff2",
        Some("ttf") => "font/ttf",
        Some("otf") => "font/otf",
        _ => "application/octet-stream",
    }
}

fn not_found_page(raw_path: &str, asset_root: &Path) -> Response {
    error_page(
        StatusCode::NOT_FOUND,
        "ASSET NOT FOUND",
        &format!(
            "No file named {raw_path} exists under the configured asset directory \
             {root}. This host never falls back to index.html: a missing asset is \
             this loud page, not a silently mis-served shell.",
            root = asset_root.display()
        ),
    )
}

fn error_page(status: StatusCode, title: &str, detail: &str) -> Response {
    let body = format!(
        "<!doctype html>\n<html lang=\"en\">\n<head><meta charset=\"utf-8\">\
         <title>frame-host: {status} {title}</title></head>\n<body style=\"font-family: monospace; \
         background: #1a0505; color: #ffb4b4; padding: 2rem;\">\n<h1>FRAME HOST — {status} {title}</h1>\n\
         <p>{detail}</p>\n</body>\n</html>\n",
        status = status.as_u16(),
    );
    let mut response = Response::new(Body::from(body));
    *response.status_mut() = status;
    response.headers_mut().insert(
        header::CONTENT_TYPE,
        HeaderValue::from_static("text/html; charset=utf-8"),
    );
    response
}

#[cfg(test)]
mod tests {
    use super::{mime_for, percent_decode, sanitize_request_path, validate_channels_contract};
    use crate::error::HostError;
    use std::path::{Path, PathBuf};

    fn roster(entries: &[&str]) -> Vec<String> {
        entries.iter().map(|entry| (*entry).to_owned()).collect()
    }

    /// The channels contract: non-empty roster, non-empty unique entries, and
    /// primary-channel membership — each refusal typed and loud.
    #[test]
    fn channels_contract_accepts_valid_rosters() {
        assert!(validate_channels_contract(&roster(&["telemetry.stream"]), None).is_ok());
        assert!(
            validate_channels_contract(
                &roster(&["telemetry.stream", "telemetry.east"]),
                Some("telemetry.east"),
            )
            .is_ok()
        );
    }

    #[test]
    fn channels_contract_refuses_empty_roster() {
        let refusal = validate_channels_contract(&[], None);
        assert!(matches!(refusal, Err(HostError::ConfigContract { .. })));
    }

    #[test]
    fn channels_contract_refuses_empty_and_duplicate_entries()
    -> Result<(), Box<dyn std::error::Error>> {
        let empty_entry = validate_channels_contract(&roster(&["telemetry.stream", ""]), None);
        assert!(matches!(empty_entry, Err(HostError::ConfigContract { .. })));

        let duplicate = validate_channels_contract(
            &roster(&["telemetry.stream", "telemetry.stream"]),
            Some("telemetry.stream"),
        );
        let Err(HostError::ConfigContract { detail }) = duplicate else {
            return Err("expected ConfigContract for a duplicate entry".into());
        };
        assert!(
            detail.contains("more than once"),
            "duplicate refusal must state the duplication: {detail}"
        );
        Ok(())
    }

    #[test]
    fn channels_contract_refuses_a_primary_outside_the_roster()
    -> Result<(), Box<dyn std::error::Error>> {
        let refusal = validate_channels_contract(
            &roster(&["telemetry.stream", "telemetry.east"]),
            Some("telemetry.west"),
        );
        let Err(HostError::ConfigContract { detail }) = refusal else {
            return Err("expected ConfigContract for a foreign primary".into());
        };
        assert!(
            detail.contains("telemetry.west"),
            "refusal must name the missing primary: {detail}"
        );
        Ok(())
    }

    #[test]
    fn root_maps_to_index_only() {
        assert_eq!(
            sanitize_request_path("/").ok(),
            Some(PathBuf::from("index.html"))
        );
        assert_eq!(
            sanitize_request_path("/assets/app.js").ok(),
            Some(PathBuf::from("assets/app.js"))
        );
    }

    #[test]
    fn traversal_and_malformed_paths_are_refused() {
        assert!(sanitize_request_path("/../secret").is_err());
        assert!(sanitize_request_path("/a/../b").is_err());
        assert!(sanitize_request_path("/%2e%2e/secret").is_err());
        assert!(sanitize_request_path("//double").is_err());
        assert!(sanitize_request_path("/a/./b").is_err());
        assert!(sanitize_request_path("/a%00b").is_err());
        assert!(sanitize_request_path("/a%zz").is_err());
        assert!(sanitize_request_path("no-leading-slash").is_err());
    }

    #[test]
    fn percent_decoding_is_strict() {
        assert_eq!(percent_decode("/plain").ok().as_deref(), Some("/plain"));
        assert_eq!(percent_decode("/a%20b").ok().as_deref(), Some("/a b"));
        assert!(percent_decode("/broken%2").is_err());
        assert!(percent_decode("/broken%").is_err());
        assert!(percent_decode("/bad%ff%fe").is_err());
    }

    #[test]
    fn wasm_and_core_types_map_exactly() {
        assert_eq!(mime_for(Path::new("a/app.wasm")), "application/wasm");
        assert_eq!(
            mime_for(Path::new("index.html")),
            "text/html; charset=utf-8"
        );
        assert_eq!(
            mime_for(Path::new("assets/index-abc.js")),
            "text/javascript; charset=utf-8"
        );
        assert_eq!(mime_for(Path::new("noext")), "application/octet-stream");
    }
}