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
Original file line number Diff line number Diff line change
@@ -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.
20 changes: 13 additions & 7 deletions pkgs/id/src/web/templates.rs
Original file line number Diff line number Diff line change
Expand Up @@ -798,29 +798,33 @@ pub fn render_world_page(assets: &AssetUrls) -> String {
</label>
<div class="flex flex-wrap gap-2">
<button data-world-join class="btn btn-primary" type="button">Join world</button>
<button data-world-host-view class="btn btn-secondary" type="button">View as host (read-only)</button>
<button data-world-copy class="btn btn-ghost" type="button">Copy capability</button>
</div>
<div data-world-invite-output hidden>
<p class="text-sm">This bearer capability grants guest access. Share it privately.</p>
</div>
<details>
<summary class="cursor-pointer text-sm">Host: create a guest invite</summary>
<div class="mt-3 flex flex-wrap gap-2">
<section class="rounded border border-base-300 p-3 space-y-3">
<h2 class="font-bold">Host controls</h2>
<div class="flex flex-wrap gap-2">
<input data-world-admin class="input input-bordered font-mono" type="password" autocomplete="off" aria-label="World admin token" placeholder="World admin token">
<button data-world-invite class="btn btn-secondary" type="button">Create invite</button>
<button data-world-invite class="btn btn-secondary" type="button">Create guest invite</button>
</div>
<div class="mt-3 flex flex-wrap items-center gap-2">
</section>
<section class="rounded border border-base-300 p-3 space-y-3">
<h2 class="font-bold">Install or update program</h2>
<div class="flex flex-wrap items-center gap-2">
<input data-world-module class="file-input file-input-bordered" type="file" accept=".wasm,application/wasm" aria-label="Wasm world module">
<input data-world-seed class="input input-bordered w-24" type="number" value="1" aria-label="World seed">
<button data-world-install class="btn btn-warning" type="button">Install Wasm module</button>
</div>
<div class="mt-3 flex flex-wrap items-center gap-2">
<div class="flex flex-wrap items-center gap-2">
<input data-world-source class="file-input file-input-bordered" type="file" accept=".roc,text/plain" multiple aria-label="Roc world sources">
<button data-world-compile class="btn btn-warning" type="button">Compile &amp; install Roc sources</button>
</div>
<p class="text-xs opacity-60">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).</p>
<p class="text-xs opacity-60">Uploads run in the host's import-free Wasmtime sandbox. The current world restarts at its module seed.</p>
</details>
</section>
</section>

<section class="grid gap-4 md:grid-cols-2">
Expand Down Expand Up @@ -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"));
Expand Down
177 changes: 175 additions & 2 deletions pkgs/id/src/web/world_ws.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};
Expand Down Expand Up @@ -50,6 +50,10 @@ pub fn world_routes() -> axum::Router<WorldWebState> {
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(
Expand All @@ -58,6 +62,125 @@ pub fn world_routes() -> axum::Router<WorldWebState> {
)
}

#[derive(Debug, Deserialize)]
struct HostViewQuery {
world: Option<String>,
after: Option<String>,
}

#[derive(Debug, Serialize)]
struct HostViewResponse {
snapshot: Option<crate::world::WorldSnapshot>,
view: Option<String>,
surface: Option<crate::world_presentation::WorldSurface>,
records_sequence: u64,
records: crate::world::Records,
next_after: Option<String>,
}

/// 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<WorldWebState>,
headers: HeaderMap,
Query(query): Query<HostViewQuery>,
) -> 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(&current_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).
Expand Down Expand Up @@ -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};
Expand Down Expand Up @@ -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<Option<String>> {
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>,
Expand Down
33 changes: 33 additions & 0 deletions pkgs/id/src/world/actor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down Expand Up @@ -106,6 +107,12 @@ pub(crate) enum WorldCommand {
token: JoinCapability,
reply: oneshot::Sender<Result<WorldSnapshot>>,
},
/// 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<Result<(WorldSnapshot, Option<String>)>>,
},
EventsAfter {
token: JoinCapability,
sequence: u64,
Expand Down Expand Up @@ -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,
Expand Down
13 changes: 13 additions & 0 deletions pkgs/id/src/world/handle.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<String>)> {
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
Expand Down
Loading
Loading