Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
198 changes: 198 additions & 0 deletions pkgs/id/src/web/app_interface.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,198 @@
//! The `[interfaces.web]` section of an app's `app.toml` (#2026 §2,
//! #2325): how a packaged app binds the host's generic web surfaces.
//!
//! In adapter mode (§4.1) the app ships no web code of its own; the
//! host's world page and websocket bridge serve it, parameterised by
//! this section — `route` is the page route, `socket` the
//! live-channel route. In direct mode (§4.2) the app ships its own
//! frontend; parsing accepts the declaration, but the adapter
//! binding in `routes` / `world_ws` applies to adapter mode only.
//!
//! This is the binding layer only: discovering app folders and
//! reading their `app.toml` files is the host-discovery work (#2324).

use serde::Deserialize;

/// How an app's web interface is rendered (#2026 §4).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum WebMode {
/// The host's generic surfaces render the app (§4.1).
Adapter,
/// The app ships its own frontend (§4.2).
Direct,
}

/// A parsed `[interfaces.web]` section: the binding for one app.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct WebInterface {
/// Adapter or direct.
pub mode: WebMode,
/// Page route when the app is active.
pub route: String,
/// Live-channel (websocket) route, if the app has one.
pub socket: Option<String>,
}

impl WebInterface {
/// The binding the built-in world app has always used: adapter
/// mode, page at `/world`, live channel at `/ws/world`. Routers
/// built with this interface are byte-identical to the routers
/// built before parameterisation existed.
#[must_use]
pub fn world_app() -> Self {
Self {
mode: WebMode::Adapter,
route: "/world".to_owned(),
socket: Some("/ws/world".to_owned()),
}
}

/// Whether the adapter binding applies to this interface.
#[must_use]
pub fn is_adapter(&self) -> bool {
self.mode == WebMode::Adapter
}
}

#[derive(Deserialize)]
struct AppToml {
interfaces: Option<Interfaces>,
}

#[derive(Deserialize)]
struct Interfaces {
web: Option<WebSection>,
}

#[derive(Deserialize)]
struct WebSection {
mode: Option<String>,
route: Option<String>,
socket: Option<String>,
}

/// Why an `[interfaces.web]` section could not be read.
#[derive(Debug)]
pub enum WebInterfaceError {
/// The TOML did not parse as an app manifest.
Toml(toml::de::Error),
/// `mode` named something other than `adapter` or `direct`.
UnknownMode(String),
}

impl std::fmt::Display for WebInterfaceError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Toml(err) => write!(f, "app.toml did not parse: {err}"),
Self::UnknownMode(mode) => {
write!(
f,
"[interfaces.web] mode {mode:?} is not \"adapter\" or \"direct\""
)
}
}
}
}

impl std::error::Error for WebInterfaceError {}

impl From<toml::de::Error> for WebInterfaceError {
fn from(err: toml::de::Error) -> Self {
Self::Toml(err)
}
}

/// Reads the `[interfaces.web]` section from an `app.toml` document.
///
/// Returns `Ok(None)` when the document declares no web interface
/// (a pure CLI app is valid, #2026 §2). Defaults inside a present
/// section: `mode` defaults to `adapter`, `route` to `/world`;
/// `socket` has no default — a section without one binds no live
/// channel.
///
/// # Errors
///
/// Returns [`WebInterfaceError`] when the TOML is malformed or the
/// mode is neither `adapter` nor `direct`.
pub fn web_interface_from_app_toml(
source: &str,
) -> Result<Option<WebInterface>, WebInterfaceError> {
let parsed: AppToml = toml::from_str(source)?;
let Some(section) = parsed.interfaces.and_then(|i| i.web) else {
return Ok(None);
};
let mode = match section.mode.as_deref() {
None | Some("adapter") => WebMode::Adapter,
Some("direct") => WebMode::Direct,
Some(other) => return Err(WebInterfaceError::UnknownMode(other.to_owned())),
};
Ok(Some(WebInterface {
mode,
route: section.route.unwrap_or_else(|| "/world".to_owned()),
socket: section.socket,
}))
}

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

#[test]
fn parses_an_adapter_binding_with_custom_routes() {
let source = r#"
id = "arena"

[interfaces.web]
mode = "adapter"
route = "/arena"
socket = "/ws/arena"
"#;
let iface = web_interface_from_app_toml(source)
.expect("parses")
.expect("web section present");
assert_eq!(iface.mode, WebMode::Adapter);
assert_eq!(iface.route, "/arena");
assert_eq!(iface.socket.as_deref(), Some("/ws/arena"));
assert!(iface.is_adapter());
}

#[test]
fn defaults_apply_inside_a_present_section() {
let iface = web_interface_from_app_toml("[interfaces.web]\n")
.expect("parses")
.expect("web section present");
assert_eq!(
iface,
WebInterface {
mode: WebMode::Adapter,
route: "/world".to_owned(),
socket: None,
}
);
}

#[test]
fn no_web_section_is_none_not_an_error() {
let source = "id = \"cli-only\"\n\n[interfaces.cli]\ncommands = [\"world\"]\n";
assert_eq!(web_interface_from_app_toml(source).expect("parses"), None);
}

#[test]
fn direct_mode_parses_and_is_not_adapter() {
let source = "[interfaces.web]\nmode = \"direct\"\nroute = \"/app\"\n";
let iface = web_interface_from_app_toml(source)
.expect("parses")
.expect("web section present");
assert_eq!(iface.mode, WebMode::Direct);
assert!(!iface.is_adapter());
}

#[test]
fn unknown_mode_is_an_error() {
let source = "[interfaces.web]\nmode = \"telepathic\"\n";
assert!(matches!(
web_interface_from_app_toml(source),
Err(WebInterfaceError::UnknownMode(_))
));
}
}
14 changes: 9 additions & 5 deletions pkgs/id/src/web/home.rs
Original file line number Diff line number Diff line change
Expand Up @@ -172,6 +172,7 @@ pub(super) fn render_home(
worlds: &[crate::world_hub::WorldInfo],
default_world: &str,
world_enabled: bool,
world_route: &str,
) -> String {
let world_name = html_escape(default_world);
let world_href = urlencoding::encode(default_world);
Expand All @@ -183,7 +184,7 @@ pub(super) fn render_home(
let _ = std::fmt::Write::write_fmt(
&mut html,
format_args!(
"<li><a href=\"/world?world={world_href}\">{world_name}</a> (default world)</li>"
"<li><a href=\"{world_route}?world={world_href}\">{world_name}</a> (default world)</li>"
),
);
} else {
Expand All @@ -198,7 +199,7 @@ pub(super) fn render_home(
let _ = std::fmt::Write::write_fmt(
&mut html,
format_args!(
"<li><a href=\"/world?world={href}\">{name}</a> <span>{state}</span></li>"
"<li><a href=\"{world_route}?world={href}\">{name}</a> <span>{state}</span></li>"
),
);
}
Expand All @@ -208,7 +209,7 @@ pub(super) fn render_home(
let _ = std::fmt::Write::write_fmt(
&mut html,
format_args!(
"<section class=\"card bg-base-200 border border-base-300 p-4\"><h2>Global chat</h2><p>This is the authenticated default world ({world_name}). Join with a guest capability to participate. Messages use the existing bounded world chat and are live only within this server.</p><iframe title=\"Live global chat in {world_name}\" src=\"/world?world={world_href}\" loading=\"lazy\" class=\"w-full min-h-[36rem] border border-base-300\"></iframe></section>"
"<section class=\"card bg-base-200 border border-base-300 p-4\"><h2>Global chat</h2><p>This is the authenticated default world ({world_name}). Join with a guest capability to participate. Messages use the existing bounded world chat and are live only within this server.</p><iframe title=\"Live global chat in {world_name}\" src=\"{world_route}?world={world_href}\" loading=\"lazy\" class=\"w-full min-h-[36rem] border border-base-300\"></iframe></section>"
),
);
} else {
Expand Down Expand Up @@ -317,7 +318,7 @@ mod tests {

#[test]
fn homepage_has_world_explorer_live_chat_and_discovery_feed() {
let html = render_home(&[], "lobby", true);
let html = render_home(&[], "lobby", true, "/world");
assert!(html.contains("World explorer"));
assert!(html.contains("Global chat"));
assert!(html.contains("Recent documents"));
Expand All @@ -326,6 +327,9 @@ mod tests {
assert!(!html.contains("<main"));
assert!(html.contains("Popular documents"));
assert!(html.contains("/world?world=lobby"));
let custom = render_home(&[], "lobby", true, "/arena");
assert!(custom.contains("/arena?world=lobby"));
assert!(!custom.contains("/world?world=lobby"));
assert!(html.contains("this server"));
assert!(html.contains("/files"));
}
Expand Down Expand Up @@ -494,7 +498,7 @@ mod tests {

#[test]
fn global_chat_embeds_existing_authenticated_world_chat() {
let html = render_home(&[], "lobby", true);
let html = render_home(&[], "lobby", true, "/world");
assert!(html.contains("/world?world=lobby"));
assert!(html.contains("authenticated default world"));
assert!(html.contains("guest capability"));
Expand Down
15 changes: 14 additions & 1 deletion pkgs/id/src/web/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@
//! id serve --web
//! ```

mod app_interface;
mod assets;
mod collab;
mod content_mode;
Expand Down Expand Up @@ -78,7 +79,8 @@ pub use collab::CollabState;
pub use identity::IdentityStore;
#[doc(hidden)]
pub use identity::crash_gate;
pub use routes::create_router;
pub use app_interface::{WebInterface, WebInterfaceError, WebMode, web_interface_from_app_toml};
pub use routes::{create_router, create_router_for_app};
pub use security::WebSecurity;
pub use templates::{AssetUrls, render_page};

Expand Down Expand Up @@ -169,6 +171,15 @@ pub struct AppState {
pub(crate) local_events: Arc<Mutex<crate::local_events::LocalEvents>>,
/// Optional hosted world (and its invite secret) for the WebSocket bridge.
pub world: Option<crate::world_hub::WorldHub>,
/// The `[interfaces.web]` page route this state's router binds
/// the world page at (#2325). Defaults to the world app's own
/// `/world`; `create_router_for_app` overwrites it from the
/// app's declared interface.
pub web_route: String,
/// The `[interfaces.web]` live-channel route, if the app
/// declares one (#2325). Defaults to the world app's
/// `/ws/world`.
pub web_socket: Option<String>,
/// Mark the directory explorer's session cookies `Secure`.
pub cookie_secure: bool,
}
Expand Down Expand Up @@ -246,6 +257,8 @@ impl AppState {
identity: IdentityStore::new(secret_key, identity_db_path).await?,
local_events,
world: None,
web_route: "/world".to_owned(),
web_socket: Some("/ws/world".to_owned()),
cookie_secure: false,
})
}
Expand Down
Loading
Loading