diff --git a/doc/2026-11-02T00-53-51Z_feature_world_host_view/2026-11-02T00-53-51Z_feature_world_host_view.md b/doc/2026-11-02T00-53-51Z_feature_world_host_view/2026-11-02T00-53-51Z_feature_world_host_view.md new file mode 100644 index 0000000000..04b69763f4 --- /dev/null +++ b/doc/2026-11-02T00-53-51Z_feature_world_host_view/2026-11-02T00-53-51Z_feature_world_host_view.md @@ -0,0 +1,21 @@ +# Authenticated, read-only world host view + +## Request + +Issue [#3378](https://github.com/developing-today/code/issues/3378) asks for an explicitly authenticated host to inspect the current authoritative world view and records without joining as a guest or creating, minting, or consuming a guest capability. The existing guest-capability flow must remain unchanged. The existing Wasm/Roc installation controls should be distinct and discoverable from the empty-program state. + +## Initial design + +- Use the existing world-admin secret, sent only in the `x-world-admin-token` HTTP header, to authorize a web-only read endpoint. Do not put credentials in a URL or add a new shell-protocol frame: `shell-contract.v1.json` explicitly defers new frame kinds. +- Add an actor-serialized admin view/snapshot operation. The program's existing `view(Participant)` interface needs a view context, so use a reserved host viewer (`id = 0`, display name `Host`) only for rendering; do not register it, include it in the participant list, emit presence, or allow it to send events. +- Return a bounded page of records and a continuation key. The browser fetches pages using the same admin header, renders the host view as read-only, and can refresh it explicitly. +- Keep the guest socket/join and its capability authorization intact. Host mode closes any guest session and disables chat/input/paste/keyboard sends. +- Move installation controls into a separate “Install or update program” host section. Use `active_module_hash` to show an actionable empty-program state. + +## Trade-offs and checks + +The web-only endpoint avoids changing the shared QUIC/WebSocket shell contract. The admin secret is already used by the web host tools and is the authority boundary for this operation. The reserved viewer is never a guest or participant; this preserves the roster/presence invariant while reusing the current program presentation interface. Verify authorization denial, no host participant/presence, unchanged guest join, bounded record pagination, and disabled host input. + +## Change log + +- 2026-11-02: Initial design before implementation for queue task 5190. diff --git a/pkgs/id/src/web/templates.rs b/pkgs/id/src/web/templates.rs index 37b047bfa1..e29b11b114 100644 --- a/pkgs/id/src/web/templates.rs +++ b/pkgs/id/src/web/templates.rs @@ -798,29 +798,33 @@ pub fn render_world_page(assets: &AssetUrls) -> String {
+
-
- Host: create a guest invite -
+
+

Host controls

+
- +
-
+
+
+

Install or update program

+
-
+

Choose main.roc and up to 7 additional .roc files. Each file is limited to 128 KiB and all sources together to 256 KiB. Compilation runs on the host (up to 120 seconds).

Uploads run in the host's import-free Wasmtime sandbox. The current world restarts at its module seed.

-
+
@@ -1076,6 +1080,8 @@ mod tests { assert!(html.contains("data-world-app")); assert!(html.contains("data-world-invite")); assert!(html.contains("data-world-join")); + assert!(html.contains("data-world-host-view")); + assert!(html.contains("Install or update program")); assert!(html.contains("data-world-world")); assert!(html.contains("data-world-chat-form")); assert!(html.contains("data-world-input-form")); diff --git a/pkgs/id/src/web/world_ws.rs b/pkgs/id/src/web/world_ws.rs index 70ebb3d4f5..643e2acede 100644 --- a/pkgs/id/src/web/world_ws.rs +++ b/pkgs/id/src/web/world_ws.rs @@ -17,7 +17,7 @@ use futures::{ SinkExt, StreamExt, stream::{SplitSink, SplitStream}, }; -use serde::Deserialize; +use serde::{Deserialize, Serialize}; use crate::directory::Refusal; use crate::directory_auth::{Caller, Signed}; @@ -50,6 +50,10 @@ pub fn world_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/host-view", + axum::routing::get(host_view_handler), + ) .route("/api/world/metrics", axum::routing::get(metrics_handler)) .merge(super::explore::explore_routes()) .route( @@ -58,6 +62,125 @@ pub fn world_routes() -> axum::Router { ) } +#[derive(Debug, Deserialize)] +struct HostViewQuery { + world: Option, + after: Option, +} + +#[derive(Debug, Serialize)] +struct HostViewResponse { + snapshot: Option, + view: Option, + surface: Option, + records_sequence: u64, + records: crate::world::Records, + next_after: Option, +} + +/// A revision identifying the exact records snapshot, for the host view's +/// cross-page consistency check. The watch channel's event sequence cannot +/// serve: host-originated record changes republish records under an +/// unchanged event sequence (`WorldActor::deliver`), so pages validated +/// against it could silently mix snapshots. FNV-1a over the canonical +/// (BTreeMap-ordered) JSON encoding, folded to 53 bits so the value +/// survives JSON number round-trips in the browser exactly. +fn records_revision(records: &crate::world::Records) -> u64 { + let bytes = serde_json::to_vec(records).unwrap_or_default(); + let mut hash: u64 = 0xcbf2_9ce4_8422_2325; + for byte in bytes { + hash ^= u64::from(byte); + hash = hash.wrapping_mul(0x0000_0100_0000_01b3); + } + hash & ((1 << 53) - 1) +} + +/// The host view uses the existing admin secret, not a guest capability. It +/// is deliberately an HTTP read so the shared shell frame protocol is unchanged. +async fn host_view_handler( + State(state): State, + headers: HeaderMap, + Query(query): Query, +) -> Response { + let Some(hub) = state.hub else { + return StatusCode::NOT_FOUND.into_response(); + }; + let Some(token) = headers + .get("x-world-admin-token") + .and_then(|value| value.to_str().ok()) + else { + return StatusCode::UNAUTHORIZED.into_response(); + }; + if !hub.admin_ok(token) { + return StatusCode::UNAUTHORIZED.into_response(); + } + // Resolve without the admin creation path: viewing a typo must not create + // a new world as a side effect. + let lease = match hub.lease(query.world.as_deref(), None).await { + Ok(lease) => lease, + Err(ResolveError::Busy | ResolveError::TooManyWorlds) => { + return StatusCode::SERVICE_UNAVAILABLE.into_response(); + } + Err(_) => return StatusCode::NOT_FOUND.into_response(), + }; + let world = lease.service().world(); + let (snapshot, view) = if query.after.is_none() { + match world.host_view().await { + Ok((snapshot, view)) => (Some(snapshot), view), + Err(_) => return StatusCode::INTERNAL_SERVER_ERROR.into_response(), + } + } else { + (None, None) + }; + let (_, current_records) = world.records(); + let records_sequence = records_revision(¤t_records); + let mut records = crate::world::Records::new(); + let mut used = 0usize; + let mut last_included = None; + let mut more = false; + for (key, value) in current_records.iter() { + if query + .after + .as_deref() + .is_some_and(|after| key.as_str() <= after) + { + continue; + } + let size = key.len() + serde_json::to_vec(value).map_or(0, |bytes| bytes.len()) + 8; + if used + size > crate::world_session::MAX_RECORDS_PAGE_BYTES { + if records.is_empty() { + return StatusCode::PAYLOAD_TOO_LARGE.into_response(); + } + more = true; + break; + } + used += size; + last_included = Some(key.clone()); + records.insert(key.clone(), value.clone()); + } + let next_after = more.then_some(last_included).flatten(); + let surface = match view + .as_deref() + .map(crate::world_presentation::parse_surface) + { + Some(Ok(surface)) => surface, + Some(Err(_)) => return StatusCode::INTERNAL_SERVER_ERROR.into_response(), + None => None, + }; + ( + [(header::CACHE_CONTROL, "no-store")], + Json(HostViewResponse { + snapshot, + view, + surface, + records_sequence, + records, + next_after, + }), + ) + .into_response() +} + #[derive(Debug, Deserialize)] pub(super) struct DirectoryQuery { /// World to read (default world if absent). @@ -459,7 +582,9 @@ impl SessionIo for WsIo { #[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] mod tests { use super::*; - use crate::world::{JoinCapability, WorldCore, WorldHandle, WorldLimits}; + use crate::world::{ + JoinCapability, Participant, WorldCore, WorldHandle, WorldLimits, WorldProgram, + }; use crate::world_session::WorldService; use axum::http::StatusCode; use axum::{body::Body, http::Request}; @@ -532,6 +657,54 @@ mod tests { assert_eq!(response.status(), StatusCode::OK); } + #[tokio::test] + async fn host_view_requires_admin_and_does_not_register_a_guest() { + struct HostViewerProgram; + impl WorldProgram for HostViewerProgram { + fn view(&mut self, viewer: &Participant) -> anyhow::Result> { + Ok(Some(viewer.display_name.clone())) + } + } + let core = WorldCore::new("lobby", WorldLimits::default()).unwrap(); + let world = WorldHandle::spawn_with_program(core, Box::new(HostViewerProgram)); + let router = app(Some(world), Some("s3cret")); + for request in [ + Request::get("/api/world/host-view") + .body(Body::empty()) + .unwrap(), + Request::get("/api/world/host-view") + .header("x-world-admin-token", "wrong") + .body(Body::empty()) + .unwrap(), + ] { + let response = router.clone().oneshot(request).await.unwrap(); + assert_eq!(response.status(), StatusCode::UNAUTHORIZED); + } + + let response = router + .oneshot( + Request::get("/api/world/host-view") + .header("x-world-admin-token", "s3cret") + .body(Body::empty()) + .unwrap(), + ) + .await + .unwrap(); + assert_eq!(response.status(), StatusCode::OK); + assert_eq!( + response.headers().get(header::CACHE_CONTROL).unwrap(), + "no-store" + ); + let body = axum::body::to_bytes(response.into_body(), usize::MAX) + .await + .unwrap(); + let value: serde_json::Value = serde_json::from_slice(&body).unwrap(); + assert_eq!(value["snapshot"]["participants"], serde_json::json!([])); + assert!(value["snapshot"]["active_module_hash"].is_null()); + assert_eq!(value["view"], "Host"); + assert_eq!(value["records"], serde_json::json!({})); + } + fn directory_request( method: &str, admin: Option<&str>, diff --git a/pkgs/id/src/world/actor.rs b/pkgs/id/src/world/actor.rs index c27352dde2..0b607b4523 100644 --- a/pkgs/id/src/world/actor.rs +++ b/pkgs/id/src/world/actor.rs @@ -22,6 +22,7 @@ impl WorldCommand { Self::Chat { .. } => "Chat", Self::Input { .. } => "Input", Self::Snapshot { .. } => "Snapshot", + Self::HostView { .. } => "HostView", Self::EventsAfter { .. } => "EventsAfter", Self::ProjectEvent { .. } => "ProjectEvent", Self::View { .. } => "View", @@ -106,6 +107,12 @@ pub(crate) enum WorldCommand { token: JoinCapability, reply: oneshot::Sender>, }, + /// Admin-authorized web rendering; the caller must validate the admin + /// secret before requesting this view. The synthetic viewer is not a + /// registered participant and never receives presence or event rights. + HostView { + reply: oneshot::Sender)>>, + }, EventsAfter { token: JoinCapability, sequence: u64, @@ -1173,6 +1180,32 @@ impl WorldActor { WorldCommand::Snapshot { token, reply } => { let _ = reply.send(self.core.snapshot(&token)); } + WorldCommand::HostView { reply } => { + let result = if self.program_healthy { + let viewer = Participant { + id: 0, + display_name: "Host".to_owned(), + }; + self.program.view(&viewer).and_then(|view| { + if view + .as_ref() + .is_some_and(|text| text.len() > self.core.limits.presentation_bytes) + { + self.view_failures = self.view_failures.saturating_add(1); + anyhow::bail!( + "world presentation exceeds {} bytes", + self.core.limits.presentation_bytes + ); + } + Ok((self.core.snapshot_unchecked(WorldScopes::ALL), view)) + }) + } else { + Err(anyhow::anyhow!( + "world program is unavailable after a previous failure" + )) + }; + let _ = reply.send(result); + } WorldCommand::EventsAfter { token, sequence, diff --git a/pkgs/id/src/world/handle.rs b/pkgs/id/src/world/handle.rs index ed33d591c5..2a9d8d9a3f 100644 --- a/pkgs/id/src/world/handle.rs +++ b/pkgs/id/src/world/handle.rs @@ -633,6 +633,19 @@ impl WorldHandle { .context("world actor dropped snapshot response")? } + /// Return the admin-only snapshot and presentation for a read-only host + /// view. The caller must authenticate the world admin before invoking it. + pub(crate) async fn host_view(&self) -> Result<(WorldSnapshot, Option)> { + let (reply, response) = oneshot::channel(); + self.commands + .send(WorldCommand::HostView { reply }) + .await + .map_err(|_| anyhow::anyhow!("world actor is closed"))?; + response + .await + .context("world actor dropped host-view response")? + } + /// What the holder of `token` may see of a live `event` (from /// [`WorldHandle::subscribe`]): `Ok(None)` if the event is not for this /// viewer, `Err` if the capability no longer joins. Judged by the diff --git a/pkgs/id/web/src/world-rejoin.test.ts b/pkgs/id/web/src/world-rejoin.test.ts index 2385841aee..e2022c6ba3 100644 --- a/pkgs/id/web/src/world-rejoin.test.ts +++ b/pkgs/id/web/src/world-rejoin.test.ts @@ -168,4 +168,47 @@ describe("world page rejoin (ghost WebSocket, #1461)", () => { reconnected.open(); expect(reconnected.sent("join")).toHaveLength(1); }); + + it("host view uses the admin header, shows an empty-program action, and blocks guest input", async () => { + const realFetch = globalThis.fetch; + const fetchMock = vi.fn(async (_input: RequestInfo | URL, _init?: RequestInit) => + new Response( + JSON.stringify({ + snapshot: { + world_id: "lobby", + current_sequence: 0, + active_module_hash: null, + participants: [], + }, + view: null, + surface: null, + records_sequence: 0, + records: {}, + next_after: null, + }), + { status: 200, headers: { "content-type": "application/json" } }, + ), + ); + vi.stubGlobal("fetch", fetchMock); + try { + q("[data-world-admin]").value = "admin-secret"; + const previousCount = FakeSocket.all.length; + q("[data-world-host-view]").click(); + await flushAsync(); + + expect(fetchMock).toHaveBeenCalledOnce(); + const [url, options] = fetchMock.mock.calls[0]; + expect(String(url)).not.toContain("admin-secret"); + expect((options?.headers as Record)["x-world-admin-token"]).toBe("admin-secret"); + expect(q("[data-world-view]").textContent).toContain("No program is installed"); + expect(q("[data-world-chat-form]").hidden).toBe(true); + expect(q("[data-world-input-form]").hidden).toBe(true); + q("[data-world-view]").dispatchEvent(new KeyboardEvent("keydown", { key: "ArrowUp", bubbles: true })); + expect(status()).toBe("Host view is read-only"); + await flushAsync(); + expect(FakeSocket.all).toHaveLength(previousCount); + } finally { + vi.stubGlobal("fetch", realFetch); + } + }); }); diff --git a/pkgs/id/web/src/world.ts b/pkgs/id/web/src/world.ts index 965961996c..6de9758291 100644 --- a/pkgs/id/web/src/world.ts +++ b/pkgs/id/web/src/world.ts @@ -18,6 +18,7 @@ type WorldFrame = { snapshot?: { world_id: string; current_sequence: number; + active_module_hash?: string | null; participants: Array<{ id: number; display_name: string }>; }; event?: { @@ -70,6 +71,7 @@ function initWorld(): void { const installButton = element(root, "[data-world-install]"); const compileButton = element(root, "[data-world-compile]"); const joinButton = element(root, "[data-world-join]"); + const hostViewButton = element(root, "[data-world-host-view]"); const chatForm = element(root, "[data-world-chat-form]"); const chatInput = element(root, "[data-world-chat]"); const inputForm = element(root, "[data-world-input-form]"); @@ -95,6 +97,7 @@ function initWorld(): void { !installButton || !compileButton || !joinButton || + !hostViewButton || !chatForm || !chatInput || !inputForm || @@ -127,6 +130,13 @@ function initWorld(): void { let recordsRefetch = false; let reconnects = 0; let intentionalClose = false; + let hostMode = false; + // Bumped when a host-view load starts and when the user leaves host + // mode (Join world): a host response that lands after a mode switch is + // stale and must not overwrite the guest session (same discipline as + // the #1461 socket identity guard, for the HTTP path). + let hostViewGeneration = 0; + let refreshHostView: () => Promise = async () => {}; const setStatus = (text: string, state: "idle" | "good" | "error" = "idle") => { status.textContent = text; @@ -161,7 +171,7 @@ function initWorld(): void { } appendLine(log, `Connected to ${frame.snapshot.world_id} at event ${cursor}`); setStatus("Connected", "good"); - requestRecords(); + if (!hostMode) requestRecords(); break; } case "event": { @@ -249,6 +259,10 @@ function initWorld(): void { }; const requestRecords = () => { + if (hostMode) { + void refreshHostView(); + return; + } if (socket?.readyState !== WebSocket.OPEN) { setStatus("Join the world before reading records", "error"); return; @@ -276,6 +290,10 @@ function initWorld(): void { }; const sendInputBytes = (bytes: Uint8Array) => { + if (hostMode) { + setStatus("Host view is read-only", "error"); + return false; + } if (socket?.readyState !== WebSocket.OPEN) { setStatus("Join the world before sending game input", "error"); return false; @@ -291,6 +309,10 @@ function initWorld(): void { if (sendInputBytes(bytes)) event.preventDefault(); }); view.addEventListener("paste", (event: ClipboardEvent) => { + if (hostMode) { + event.preventDefault(); + return; + } const text = event.clipboardData?.getData("text/plain"); if (text === undefined || !text) return; if (new TextEncoder().encode(text).length > 4096) { @@ -305,7 +327,7 @@ function initWorld(): void { }); const sendViewport = () => { - if (socket?.readyState !== WebSocket.OPEN) return; + if (hostMode || socket?.readyState !== WebSocket.OPEN) return; const fontSize = Number.parseFloat(getComputedStyle(view).fontSize) || 16; const width = Math.max(1, Math.min(500, Math.floor(view.clientWidth / (fontSize * 0.6)))); const height = Math.max(1, Math.min(200, Math.floor(view.clientHeight / fontSize))); @@ -316,6 +338,97 @@ function initWorld(): void { recordsRefresh.addEventListener("click", requestRecords); + refreshHostView = async () => { + const secret = admin.value.trim(); + if (!secret) { + setStatus("Enter the world admin token to view as host", "error"); + return; + } + if (socket) { + intentionalClose = true; + const retired = socket; + socket = null; + retired.close(); + } + const generation = ++hostViewGeneration; + hostMode = true; + chatForm.hidden = true; + inputForm.hidden = true; + view.tabIndex = -1; + hostViewButton.disabled = true; + setStatus("Loading read-only host view…"); + renderedSurface = null; + renderedViewRevision = null; + const world = selectedWorld(); + let after: string | null = null; + let recordsSequence: number | null = null; + const allRecords: Record = {}; + let firstPage = true; + try { + do { + const params = new URLSearchParams(); + if (world) params.set("world", world); + if (after) params.set("after", after); + const response = await fetch(`/api/world/host-view?${params}`, { + headers: { "x-world-admin-token": secret }, + cache: "no-store", + }); + if (!response.ok) { + throw new Error( + response.status === 401 ? "Host authorization denied" : "Host view unavailable", + ); + } + if (generation !== hostViewGeneration || !hostMode) return; + const result = (await response.json()) as { + snapshot?: NonNullable; + view?: string | null; + surface?: ScreenSurface | null; + records_sequence: number; + records: Record; + next_after: string | null; + }; + if (recordsSequence !== null && recordsSequence !== result.records_sequence) { + throw new Error("World records changed while paging; refresh the host view"); + } + recordsSequence = result.records_sequence; + Object.assign(allRecords, result.records); + if (firstPage) { + firstPage = false; + cursor = result.snapshot?.current_sequence ?? 0; + participants.replaceChildren(); + for (const participant of result.snapshot?.participants ?? []) { + const tag = document.createElement("span"); + tag.className = "badge badge-outline mr-2"; + tag.textContent = participant.display_name; + participants.append(tag); + } + renderedSurface = null; + renderedViewRevision = null; + if (result.surface && renderWorldSurface(view, result.surface)) { + renderedSurface = result.surface; + } else if (result.view) { + view.textContent = result.view; + } else if (!result.snapshot?.active_module_hash) { + view.textContent = "No program is installed. Use Install or update program below."; + } else { + view.textContent = "The active program has no text view."; + } + appendLine(log, `Viewing ${result.snapshot?.world_id ?? world ?? "default world"} as host (read-only)`); + } + after = result.next_after; + } while (after !== null); + recordsView.textContent = JSON.stringify(allRecords, null, 2); + setStatus("Read-only host view", "good"); + } catch (error) { + if (generation === hostViewGeneration && hostMode) { + setStatus(error instanceof Error ? error.message : "Host view unavailable", "error"); + } + } finally { + hostViewButton.disabled = false; + } + }; + hostViewButton.addEventListener("click", () => void refreshHostView()); + const connect = () => { const token = capability.value.trim(); if (!token) { @@ -595,6 +708,11 @@ function initWorld(): void { }); joinButton.addEventListener("click", () => { + hostViewGeneration += 1; + hostMode = false; + chatForm.hidden = false; + inputForm.hidden = false; + view.tabIndex = 0; if (socket) { // #1461: retire the old socket BEFORE closing it - clear the // current-socket reference first, so when its close event fires @@ -615,6 +733,10 @@ function initWorld(): void { chatForm.addEventListener("submit", (event) => { event.preventDefault(); + if (hostMode) { + setStatus("Host view is read-only", "error"); + return; + } const text = chatInput.value.trim(); if (!text) return; if (socket?.readyState !== WebSocket.OPEN) {