diff --git a/pkgs/id/src/web/app_interface.rs b/pkgs/id/src/web/app_interface.rs new file mode 100644 index 0000000000..83e3a8b097 --- /dev/null +++ b/pkgs/id/src/web/app_interface.rs @@ -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, +} + +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, +} + +#[derive(Deserialize)] +struct Interfaces { + web: Option, +} + +#[derive(Deserialize)] +struct WebSection { + mode: Option, + route: Option, + socket: Option, +} + +/// 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 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, 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(_)) + )); + } +} diff --git a/pkgs/id/src/web/home.rs b/pkgs/id/src/web/home.rs index 1dfb083962..6df44371cf 100644 --- a/pkgs/id/src/web/home.rs +++ b/pkgs/id/src/web/home.rs @@ -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); @@ -183,7 +184,7 @@ pub(super) fn render_home( let _ = std::fmt::Write::write_fmt( &mut html, format_args!( - "
  • {world_name} (default world)
  • " + "
  • {world_name} (default world)
  • " ), ); } else { @@ -198,7 +199,7 @@ pub(super) fn render_home( let _ = std::fmt::Write::write_fmt( &mut html, format_args!( - "
  • {name} {state}
  • " + "
  • {name} {state}
  • " ), ); } @@ -208,7 +209,7 @@ pub(super) fn render_home( let _ = std::fmt::Write::write_fmt( &mut html, format_args!( - "

    Global chat

    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.

    " + "

    Global chat

    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.

    " ), ); } else { @@ -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")); @@ -326,6 +327,9 @@ mod tests { assert!(!html.contains(">, /// Optional hosted world (and its invite secret) for the WebSocket bridge. pub world: Option, + /// 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, /// Mark the directory explorer's session cookies `Secure`. pub cookie_secure: bool, } @@ -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, }) } diff --git a/pkgs/id/src/web/routes.rs b/pkgs/id/src/web/routes.rs index e8a6a7ea7c..62be4c1af6 100644 --- a/pkgs/id/src/web/routes.rs +++ b/pkgs/id/src/web/routes.rs @@ -256,11 +256,31 @@ const fn is_leap_year(year: u64) -> bool { /// Create the main router with all web routes. pub fn create_router(state: AppState) -> Router { - Router::new() + create_router_for_app(state, &super::app_interface::WebInterface::world_app()) +} + +/// Create the main router for one packaged app, binding the world +/// page at the app's [interfaces.web] route and the live channel at +/// its socket (#2325, adapter mode). With the world app's own +/// interface the result is byte-identical to create_router: same +/// routes, same handlers, same state. +pub fn create_router_for_app( + mut state: AppState, + interface: &super::app_interface::WebInterface, +) -> Router { + state.web_route = interface.route.clone(); + state.web_socket = interface.socket.clone(); + create_router_inner(state) +} + +fn create_router_inner(state: AppState) -> Router { + let world_route = state.web_route.clone(); + let world_socket = state.web_socket.clone(); + let router = Router::new() // Page routes (return full HTML pages) .route("/", get(index_handler)) .route("/files", get(files_page_handler)) - .route("/world", get(world_page_handler)) + .route(&world_route, get(world_page_handler)) .route("/settings", get(settings_handler)) .route("/peers", get(peers_handler)) .route("/edit/{*name}", get(file_by_name_handler)) @@ -308,14 +328,23 @@ pub fn create_router(state: AppState) -> Router { // WebSocket for live tag updates .route("/ws/tags", get(super::tags_ws::ws_tags_handler)) // Static assets - .route("/assets/{*path}", get(assets_handler)) - // Optional authoritative in-memory world session bridge - .merge( - super::world_ws::world_routes().with_state(super::world_ws::WorldWebState { - hub: state.world.clone(), - cookie_secure: state.cookie_secure, - }), - ) + .route("/assets/{*path}", get(assets_handler)); + // Optional authoritative in-memory world session bridge, bound + // at the app's socket when it declares one (#2325). The shared + // world HTTP surface (invite, metrics, directory, explore) is + // merged either way: an app that declares no live channel still + // serves those routes (Codex P2 on #3894). + let world_state = super::world_ws::WorldWebState { + hub: state.world.clone(), + cookie_secure: state.cookie_secure, + }; + let router = match &world_socket { + Some(socket) => { + router.merge(super::world_ws::world_routes_at(socket).with_state(world_state)) + } + None => router.merge(super::world_ws::world_http_routes().with_state(world_state)), + }; + router .layer(DefaultBodyLimit::max(DEFAULT_BODY_LIMIT)) .with_state(state) } @@ -324,7 +353,11 @@ async fn world_page_handler(State(state): State) -> Response { if state.world.is_none() { return StatusCode::NOT_FOUND.into_response(); } - Html(super::templates::render_world_page(&state.assets)).into_response() + Html(super::templates::render_world_page( + &state.assets, + state.web_socket.as_deref(), + )) + .into_response() } /// Check if this is a partial request (SPA navigation, returns fragment not full page). @@ -341,7 +374,12 @@ async fn index_handler(State(state): State, headers: HeaderMap) -> imp .world .as_ref() .map_or("lobby", |hub| hub.default_world()); - let content = super::home::render_home(&worlds, default_world, state.world.is_some()); + let content = super::home::render_home( + &worlds, + default_world, + state.world.is_some(), + &state.web_route, + ); if is_partial_request(&headers) { Html(render_main_page_wrapper(&content)) } else { @@ -2484,6 +2522,42 @@ mod upload_router_tests { (create_router(state.clone()), state, dir, endpoint, docs) } + #[tokio::test] + async fn public_entry_point_honours_a_configured_binding() { + // A host that has already read its app manifest selects the + // binding through the public API alone (Codex P2 on PR #3894): + // parse [interfaces.web] with the re-exported parser and build + // the app router with the re-exported constructor. + let (_, state, _dir, _endpoint, _docs) = router_with_state().await; + let interface = crate::web::web_interface_from_app_toml( + "[interfaces.web]\nmode = \"adapter\"\nroute = \"/arena\"\nsocket = \"/ws/arena\"\n", + ) + .unwrap() + .unwrap(); + let app = crate::web::create_router_for_app(state, &interface); + let arena = app + .clone() + .oneshot( + Request::builder() + .uri("/arena") + .body(Body::empty()) + .unwrap(), + ) + .await + .unwrap(); + assert_ne!(arena.status(), axum::http::StatusCode::NOT_FOUND); + let world = app + .oneshot( + Request::builder() + .uri("/world") + .body(Body::empty()) + .unwrap(), + ) + .await + .unwrap(); + assert_eq!(world.status(), axum::http::StatusCode::NOT_FOUND); + } + fn multipart_body(file_bytes: &[u8]) -> Vec { multipart_body_named("photo.png", "image/png", file_bytes) } @@ -2616,23 +2690,51 @@ mod upload_router_tests { assert_ne!(images[0]["name"], images[1]["name"]); assert_ne!(images[0]["hash"], images[1]["hash"]); let listed = list_images(router.clone()).await; - for (image, bytes) in images.iter().zip([b"first-bytes".as_slice(), b"second-bytes".as_slice()]) { + for (image, bytes) in images + .iter() + .zip([b"first-bytes".as_slice(), b"second-bytes".as_slice()]) + { let name = image["name"].as_str().unwrap(); let hash = image["hash"].as_str().unwrap(); - assert_eq!(upload_name_owner(&state.store, name).await.unwrap().unwrap().to_string(), hash); - assert!(listed.iter().any(|entry| entry["name"] == name && entry["hash"] == hash)); + assert_eq!( + upload_name_owner(&state.store, name) + .await + .unwrap() + .unwrap() + .to_string(), + hash + ); + assert!( + listed + .iter() + .any(|entry| entry["name"] == name && entry["hash"] == hash) + ); let url = image["url"].as_str().unwrap(); assert!(url.contains(&format!("filename={name}"))); let (status, _, actual) = get_blob(router.clone(), url).await; assert_eq!(status, StatusCode::OK); assert_eq!(actual, bytes); - for (key, expected) in [(b"content-type".as_slice(), Some("image/png")), (b"created".as_slice(), None)] { - let tags = state.tag_store.get_by_key(&state.tag_store.global, name.as_bytes(), key).await.unwrap(); - let value = tags.first().and_then(|tag| tag.value.as_ref()).and_then(|value| value.as_str()).unwrap(); + for (key, expected) in [ + (b"content-type".as_slice(), Some("image/png")), + (b"created".as_slice(), None), + ] { + let tags = state + .tag_store + .get_by_key(&state.tag_store.global, name.as_bytes(), key) + .await + .unwrap(); + let value = tags + .first() + .and_then(|tag| tag.value.as_ref()) + .and_then(|value| value.as_str()) + .unwrap(); if let Some(expected) = expected { assert_eq!(value, expected); } else { - assert!(value.parse::().is_ok(), "invalid creation timestamp: {value}"); + assert!( + value.parse::().is_ok(), + "invalid creation timestamp: {value}" + ); } } } diff --git a/pkgs/id/src/web/templates.rs b/pkgs/id/src/web/templates.rs index 37b047bfa1..85c464b8b6 100644 --- a/pkgs/id/src/web/templates.rs +++ b/pkgs/id/src/web/templates.rs @@ -767,7 +767,7 @@ pub fn render_settings(node_id: &str) -> String { } /// Render a browser presentation for the optional multiplayer world. -pub fn render_world_page(assets: &AssetUrls) -> String { +pub fn render_world_page(assets: &AssetUrls, world_socket: Option<&str>) -> String { let content = r#"
    "#; - render_page("World", content, "", assets) + // The frontend connects to the app's configured live channel: + // the socket travels on the root element as a data attribute + // (data-world-socket), which world.ts reads instead of a + // hardcoded path (Codex P1 on #3894). No socket declared: no + // attribute, and the frontend keeps its historical default. + let content = match world_socket { + Some(socket) => content.replacen( + "data-world-app", + &format!( + "data-world-app data-world-socket=\"{}\"", + html_escape(socket) + ), + 1, + ), + None => content.to_owned(), + }; + render_page("World", &content, "", assets) } /// Render the peers page showing discovered peers. @@ -1072,7 +1088,8 @@ mod tests { #[test] fn test_render_world_page_exposes_presentation_controls() { - let html = render_world_page(&AssetUrls::default()); + let html = render_world_page(&AssetUrls::default(), Some("/ws/arena")); + assert!(html.contains("data-world-socket=\"/ws/arena\"")); assert!(html.contains("data-world-app")); assert!(html.contains("data-world-invite")); assert!(html.contains("data-world-join")); diff --git a/pkgs/id/src/web/world_ws.rs b/pkgs/id/src/web/world_ws.rs index 70ebb3d4f5..3a4fac884e 100644 --- a/pkgs/id/src/web/world_ws.rs +++ b/pkgs/id/src/web/world_ws.rs @@ -47,8 +47,26 @@ pub struct WorldWebState { /// Routes for the world session bridge; merge into any `Router` with /// [`WorldWebState`] as the provided state. pub fn world_routes() -> axum::Router { + world_routes_at("/ws/world") +} + +/// Routes for the world session bridge with the live channel bound +/// at `socket` - the [interfaces.web] parameterisation (#2325). +/// Every other route is the shared world API surface, unchanged. +/// Two apps bound at different sockets can be merged into one +/// server (or served side by side) without either seeing the +/// other's channel. +pub fn world_routes_at(socket: &str) -> axum::Router { + world_http_routes().route(socket, axum::routing::get(handler)) +} + +/// The shared world HTTP surface - invite, metrics, directory and +/// the script-free explore/invite pages - with no live channel. +/// An app whose `[interfaces.web]` section declares no socket still +/// serves these routes; only the websocket bridge is socket-bound +/// (Codex P2 on #3894). +pub fn world_http_routes() -> axum::Router { axum::Router::new() - .route("/ws/world", axum::routing::get(handler)) .route("/api/world/invite", axum::routing::post(invite_handler)) .route("/api/world/metrics", axum::routing::get(metrics_handler)) .merge(super::explore::explore_routes()) @@ -1440,4 +1458,75 @@ mod tests { // revoked, which demonstrates revocation didn't poison the world. assert_eq!(world.chat(bob, "still here").await.unwrap().sequence, 1); } + + #[tokio::test] + async fn two_apps_bind_distinct_sockets() { + // App A keeps the historical binding; app B binds its own + // socket from its [interfaces.web] section (#2325). + let addr_a = serve(world_routes().with_state(WorldWebState { + hub: None, + cookie_secure: false, + })) + .await; + let addr_b = serve(world_routes_at("/ws/arena").with_state(WorldWebState { + hub: None, + cookie_secure: false, + })) + .await; + + // Each app answers a websocket handshake on its own socket... + let (mut client_a, _) = tokio_tungstenite::connect_async(format!("ws://{addr_a}/ws/world")) + .await + .unwrap(); + let (mut client_b, _) = tokio_tungstenite::connect_async(format!("ws://{addr_b}/ws/arena")) + .await + .unwrap(); + // ...and neither answers on the other's: the bindings are + // distinct, not aliased. + assert!( + tokio_tungstenite::connect_async(format!("ws://{addr_a}/ws/arena")) + .await + .is_err() + ); + assert!( + tokio_tungstenite::connect_async(format!("ws://{addr_b}/ws/world")) + .await + .is_err() + ); + let _ = client_a.close(None).await; + let _ = client_b.close(None).await; + } + + #[tokio::test] + async fn http_routes_serve_without_a_socket() { + // The shared HTTP surface is served even when an app binds + // no live channel (Codex P2 on #3894): metrics answers 401 + // (route present, no token) rather than 404 (route absent), + // and the script-free explore page renders. + let router = world_http_routes().with_state(WorldWebState { + hub: Some(WorldHub::single(WorldService::new(lobby(), None))), + cookie_secure: false, + }); + let metrics = router + .clone() + .oneshot( + Request::builder() + .uri("/api/world/metrics") + .body(Body::empty()) + .unwrap(), + ) + .await + .unwrap(); + assert_eq!(metrics.status(), StatusCode::UNAUTHORIZED); + let explore = router + .oneshot( + Request::builder() + .uri("/explore") + .body(Body::empty()) + .unwrap(), + ) + .await + .unwrap(); + assert_eq!(explore.status(), StatusCode::OK); + } } diff --git a/pkgs/id/web/src/world.ts b/pkgs/id/web/src/world.ts index 2b7d63efb5..06d8acdfeb 100644 --- a/pkgs/id/web/src/world.ts +++ b/pkgs/id/web/src/world.ts @@ -107,6 +107,10 @@ function initWorld(): void { ) return; + // The live channel this page's app bound, rendered by the server + // as a data attribute on the root element (#2325); the historical + // /ws/world remains the default for pages rendered without one. + const worldSocketPath = root.dataset.worldSocket ?? "/ws/world"; // `/world?world=arena` opens the page on that world. worldInput.value = new URLSearchParams(window.location.search).get("world") ?? ""; // The world a request is addressed to; `null` means the server's default. @@ -304,7 +308,7 @@ function initWorld(): void { // async close event (dispatched after a rejoin had already replaced // it) scheduled a duplicate reconnect, and a stale socket's open // sent its join frame on the newer socket. - const ws = new WebSocket(`${scheme}//${location.host}/ws/world`); + const ws = new WebSocket(`${scheme}//${location.host}${worldSocketPath}`); socket = ws; setStatus("Connecting…"); ws.addEventListener("open", () => { @@ -390,7 +394,7 @@ function initWorld(): void { installButton.disabled = true; setStatus(`Uploading ${file.name} (${file.size} bytes)…`); const scheme = location.protocol === "https:" ? "wss:" : "ws:"; - const upload = new WebSocket(`${scheme}//${location.host}/ws/world`); + const upload = new WebSocket(`${scheme}//${location.host}${worldSocketPath}`); let uploadStarted = false; upload.addEventListener("open", () => { upload.send( @@ -512,7 +516,7 @@ function initWorld(): void { compileButton.disabled = true; setStatus(`Reading ${files.length} Roc source file${files.length === 1 ? "" : "s"} (${totalBytes} bytes)…`); const scheme = location.protocol === "https:" ? "wss:" : "ws:"; - const compiler = new WebSocket(`${scheme}//${location.host}/ws/world`); + const compiler = new WebSocket(`${scheme}//${location.host}${worldSocketPath}`); compiler.addEventListener("open", () => { setStatus("Sources sent; compiling and installing on the host…"); compiler.send(