From 9b2dd482950a7bdd80cb6a86a8e7ec49e6ebe4f4 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 06:18:51 +0000 Subject: [PATCH] id: program gallery read surface (list, fetch, search) and --gallery-dir The gallery's public read surface (#10003, v3 design G1, G3, G7) over the registry core from #11500. - Bundle manifests gain signed discovery metadata: an optional description and up to 8 portable categories, bounded and checked at export and decode. - id-worlds program_gallery: a SearchIndex rebuildable from registry records alone, with the documented deterministic order (exact name, then category, then most recent version; no engagement ranking), and a Gallery that keeps the index in step with publish, unpublish and remove. - id-web /api/gallery/records, /bundles/{hash} and /search, cacheable (bundles immutable by content hash), 404 when no gallery is wired. - id serve --gallery-dir (requires --web) verifies every stored bundle at start and serves them. Closes #10003 Co-Authored-By: Claude Opus 5.5 --- pkgs/id/crates/id-cli/src/cli/mod.rs | 8 + pkgs/id/crates/id-cli/src/cli/tests.rs | 16 + pkgs/id/crates/id-cli/src/commands/serve.rs | 29 + pkgs/id/crates/id-web/src/gallery.rs | 323 +++++++++++ pkgs/id/crates/id-web/src/lib.rs | 16 + pkgs/id/crates/id-web/src/routes.rs | 3 + pkgs/id/crates/id-worlds/src/lib.rs | 1 + .../id/crates/id-worlds/src/program_bundle.rs | 119 ++++ .../crates/id-worlds/src/program_gallery.rs | 530 ++++++++++++++++++ .../crates/id-worlds/src/program_registry.rs | 4 + pkgs/id/crates/id-worlds/src/world/tests.rs | 2 + .../id-worlds/src/world_session/tests.rs | 2 + pkgs/id/src/main.rs | 2 + 13 files changed, 1055 insertions(+) create mode 100644 pkgs/id/crates/id-web/src/gallery.rs create mode 100644 pkgs/id/crates/id-worlds/src/program_gallery.rs diff --git a/pkgs/id/crates/id-cli/src/cli/mod.rs b/pkgs/id/crates/id-cli/src/cli/mod.rs index 6d819434de..f9f06fae66 100644 --- a/pkgs/id/crates/id-cli/src/cli/mod.rs +++ b/pkgs/id/crates/id-cli/src/cli/mod.rs @@ -470,6 +470,14 @@ pub struct ServeArgs { /// Browsers drop `Secure` cookies over plain HTTP, except on localhost. #[arg(long, env = "ID_WEB_COOKIE_SECURE")] pub web_cookie_secure: bool, + /// Serve the program gallery stored in this directory (#10003). + /// + /// The web interface answers `/api/gallery/records`, + /// `/api/gallery/bundles/` and `/api/gallery/search` from the + /// verified bundle files (`.idpb`) in the directory. + /// Every file is verified when the server starts. + #[arg(long, env = "ID_GALLERY_DIR", requires = "web")] + pub gallery_dir: Option, /// Host a multiplayer world over Iroh (and `/ws/world` with `--web`). #[arg(long, requires = "world_admin_token")] pub world: bool, diff --git a/pkgs/id/crates/id-cli/src/cli/tests.rs b/pkgs/id/crates/id-cli/src/cli/tests.rs index 20b425725a..b6d307edff 100644 --- a/pkgs/id/crates/id-cli/src/cli/tests.rs +++ b/pkgs/id/crates/id-cli/src/cli/tests.rs @@ -2065,6 +2065,22 @@ fn test_cli_parse_web_cookie_secure() { } } +#[test] +fn test_cli_parse_gallery_dir_requires_web() { + match Cli::parse_from(["id", "serve", "--web", "--gallery-dir", "/srv/gallery"]).command { + Some(Command::Serve(args)) => assert_eq!( + args.gallery_dir.as_deref(), + Some(std::path::Path::new("/srv/gallery")) + ), + _ => panic!("Expected Serve command"), + } + match Cli::parse_from(["id", "serve", "--web"]).command { + Some(Command::Serve(args)) => assert!(args.gallery_dir.is_none()), + _ => panic!("Expected Serve command"), + } + assert!(Cli::try_parse_from(["id", "serve", "--gallery-dir", "/srv/gallery"]).is_err()); +} + #[test] fn test_cli_parse_world_boot_window() { let cli = Cli::parse_from([ diff --git a/pkgs/id/crates/id-cli/src/commands/serve.rs b/pkgs/id/crates/id-cli/src/commands/serve.rs index dd76569e65..1d6d8885f7 100644 --- a/pkgs/id/crates/id-cli/src/commands/serve.rs +++ b/pkgs/id/crates/id-cli/src/commands/serve.rs @@ -320,6 +320,8 @@ pub struct ServeOptions { pub web_token: Option, /// Mark the directory explorer's session cookies `Secure` (HTTPS in front). pub web_cookie_secure: bool, + /// Serve the program gallery stored in this directory (#10003). + pub gallery_dir: Option, /// Host a multiplayer world (durable unless `ephemeral`). pub world: bool, /// Admin secret required to mint world guest capabilities. @@ -1108,6 +1110,7 @@ pub async fn cmd_serve(opts: ServeOptions) -> Result<()> { port_explicit, web_token, web_cookie_secure, + gallery_dir, world, world_admin_token, world_module, @@ -1152,6 +1155,8 @@ pub async fn cmd_serve(opts: ServeOptions) -> Result<()> { rebuild with `--features web` to serve it" ); } + #[cfg(not(feature = "web"))] + let _ = &gallery_dir; validate_world_options( world, world_admin_token.as_deref(), @@ -1982,6 +1987,29 @@ pub async fn cmd_serve(opts: ServeOptions) -> Result<()> { }); minter }; + // #10003: the program gallery's read surface, from verified + // bundle files in --gallery-dir. A file that no longer verifies + // stops the start rather than being served or skipped. + let gallery = match &gallery_dir { + Some(dir) => { + let registry = id_worlds::program_registry::Registry::open_dir( + dir, + id_worlds::program_registry::AdmitAll, + ) + .map_err(|error| { + anyhow::anyhow!("open the gallery in {}: {error}", dir.display()) + })?; + status!( + "gallery: {} program bundles from {}", + registry.len(), + dir.display() + ); + Some(std::sync::Arc::new(std::sync::RwLock::new( + id_worlds::program_gallery::Gallery::new(registry), + ))) + } + None => None, + }; let (web_routers, surface) = id_web::web_routers_with_surface( store_handle.clone(), Some(peer_discovery.clone()), @@ -1998,6 +2026,7 @@ pub async fn cmd_serve(opts: ServeOptions) -> Result<()> { seitan_state, Some(endpoint.clone()), Some(std::sync::Arc::clone(&transport_ad_minter)), + gallery, ) .await?; publication_surface = Some(surface); diff --git a/pkgs/id/crates/id-web/src/gallery.rs b/pkgs/id/crates/id-web/src/gallery.rs new file mode 100644 index 0000000000..d2421d2e16 --- /dev/null +++ b/pkgs/id/crates/id-web/src/gallery.rs @@ -0,0 +1,323 @@ +//! The program gallery's public read surface (#10003; v3 design +//! `doc/2026-11-14T13-33-00Z_design_id_program_ecosystem_v3/`, G1, G3, G7). +//! +//! Three routes over a [`Gallery`], answered as JSON records and bundle +//! bytes exactly as the registry holds them: +//! +//! - `GET /api/gallery/records?author=&name=`: the registry's list. +//! - `GET /api/gallery/bundles/{content_hash}`: the registry's fetch. +//! - `GET /api/gallery/search?q=&category=&limit=`: search over the +//! rebuildable index, in its documented order (exact name, then +//! category, then most recent version). +//! +//! Records are signed and bundles are content-addressed, so every answer +//! is cacheable at any tier without trust implications (G7): a cache cannot +//! forge a record that verifies. A fetched bundle never changes, so it is +//! marked immutable. With no gallery wired in, every route answers 404. + +use std::sync::{Arc, RwLock}; + +use axum::{ + Json, Router, + extract::{Path, Query, State}, + http::{HeaderValue, StatusCode, header}, + response::{IntoResponse, Response}, + routing::get, +}; +use serde::{Deserialize, Serialize}; + +use id_worlds::program_bundle::BundleRecord; +use id_worlds::program_gallery::{Gallery, SearchQuery}; +use id_worlds::program_registry::ListQuery; + +/// A gallery shared between the web routes and whatever publishes to it. +pub type SharedGallery = Arc>; + +/// How long list and search answers may be cached, in seconds. They change +/// when someone publishes; the records in them never do. +const LISTING_MAX_AGE: &str = "public, max-age=60"; + +/// A bundle is content-addressed, so its bytes never change. +const BUNDLE_CACHE: &str = "public, max-age=31536000, immutable"; + +/// The order search results come in, stated in every search answer. +pub const SEARCH_ORDER: &str = "exact-name, category, most-recent-version"; + +/// The gallery routes, for merging into a router. +pub fn gallery_routes() -> Router> { + Router::new() + .route("/api/gallery/records", get(records_handler)) + .route("/api/gallery/bundles/{content_hash}", get(bundle_handler)) + .route("/api/gallery/search", get(search_handler)) +} + +/// A list or search answer. +#[derive(Debug, Serialize, Deserialize)] +pub struct RecordsAnswer { + /// The signed records, each verifiable without its payload. + pub records: Vec, + /// For a search, the documented result order. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub order: Option, +} + +#[derive(Debug, Deserialize)] +struct ListParams { + author: Option, + name: Option, +} + +#[derive(Debug, Deserialize)] +struct SearchParams { + #[serde(default)] + q: String, + category: Option, + limit: Option, +} + +async fn records_handler( + State(gallery): State>, + Query(params): Query, +) -> Response { + let Some(gallery) = gallery else { + return StatusCode::NOT_FOUND.into_response(); + }; + let query = ListQuery { + author: params.author, + name: params.name, + }; + let records = match gallery.read() { + Ok(gallery) => gallery.list(&query), + Err(_) => return StatusCode::INTERNAL_SERVER_ERROR.into_response(), + }; + listing(RecordsAnswer { + records, + order: None, + }) +} + +async fn bundle_handler( + State(gallery): State>, + Path(content_hash): Path, +) -> Response { + let Some(gallery) = gallery else { + return StatusCode::NOT_FOUND.into_response(); + }; + let well_formed = content_hash.len() == 64 + && content_hash + .bytes() + .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)); + if !well_formed { + return ( + StatusCode::BAD_REQUEST, + "a content hash is 64 lower-case hex digits", + ) + .into_response(); + } + let bytes = match gallery.read() { + Ok(gallery) => gallery.fetch(&content_hash), + Err(_) => return StatusCode::INTERNAL_SERVER_ERROR.into_response(), + }; + let Some(bytes) = bytes else { + return StatusCode::NOT_FOUND.into_response(); + }; + let mut response = bytes.into_response(); + let headers = response.headers_mut(); + headers.insert( + header::CONTENT_TYPE, + HeaderValue::from_static("application/octet-stream"), + ); + headers.insert( + header::CACHE_CONTROL, + HeaderValue::from_static(BUNDLE_CACHE), + ); + if let Ok(etag) = HeaderValue::from_str(&format!("\"{content_hash}\"")) { + headers.insert(header::ETAG, etag); + } + response +} + +async fn search_handler( + State(gallery): State>, + Query(params): Query, +) -> Response { + let Some(gallery) = gallery else { + return StatusCode::NOT_FOUND.into_response(); + }; + let query = SearchQuery { + text: params.q, + category: params.category, + limit: params.limit, + }; + let found = match gallery.read() { + Ok(gallery) => gallery.search(&query), + Err(_) => return StatusCode::INTERNAL_SERVER_ERROR.into_response(), + }; + match found { + Ok(records) => listing(RecordsAnswer { + records, + order: Some(SEARCH_ORDER.to_owned()), + }), + Err(error) => (StatusCode::BAD_REQUEST, error.to_string()).into_response(), + } +} + +fn listing(answer: RecordsAnswer) -> Response { + let mut response = Json(answer).into_response(); + response.headers_mut().insert( + header::CACHE_CONTROL, + HeaderValue::from_static(LISTING_MAX_AGE), + ); + response +} + +#[cfg(test)] +#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] +mod tests { + use axum::body::Body; + use axum::http::Request; + use ed25519_dalek::SigningKey; + use tower::ServiceExt as _; + + use id_worlds::program_bundle::{ProgramBundle, ProgramSpec, export}; + use id_worlds::program_registry::{AdmitAll, Registry}; + + use super::*; + + fn bundle(name: &str, version: u64, description: &str, categories: &[&str]) -> ProgramBundle { + export( + format!("{name} {version}").into_bytes(), + ProgramSpec { + name, + version, + licence: None, + description: Some(description), + categories, + }, + &SigningKey::from_bytes(&[7; 32]), + ) + .unwrap() + } + + fn app(gallery: Option) -> Router { + gallery_routes().with_state(gallery) + } + + fn populated() -> (Router, ProgramBundle) { + let registry = Registry::open_dir(tempfile::tempdir().unwrap().keep(), AdmitAll).unwrap(); + let mut gallery = Gallery::new(registry); + let chess = bundle("chess", 2, "The classic board game.", &["board"]); + for published in [ + bundle("chess", 1, "The classic board game.", &["board"]), + chess.clone(), + bundle("go", 1, "Stones on a board.", &["board"]), + bundle("racer", 4, "Arcade driving.", &["arcade"]), + ] { + gallery.publish(&published.to_bytes()).unwrap(); + } + (app(Some(Arc::new(RwLock::new(gallery)))), chess) + } + + async fn get(app: &Router, uri: &str) -> (StatusCode, axum::http::HeaderMap, Vec) { + let response = app + .clone() + .oneshot(Request::get(uri).body(Body::empty()).unwrap()) + .await + .unwrap(); + let status = response.status(); + let headers = response.headers().clone(); + let body = axum::body::to_bytes(response.into_body(), 64 << 20) + .await + .unwrap(); + (status, headers, body.to_vec()) + } + + fn names(body: &[u8]) -> Vec<(String, u64)> { + let answer: RecordsAnswer = serde_json::from_slice(body).unwrap(); + answer + .records + .iter() + .map(|record| { + let manifest = record.verify().expect("served records verify"); + (manifest.name, manifest.version) + }) + .collect() + } + + #[tokio::test] + async fn list_serves_verifiable_records_and_filters() { + let (app, _) = populated(); + let (status, headers, body) = get(&app, "/api/gallery/records").await; + assert_eq!(status, StatusCode::OK); + assert_eq!(headers[header::CACHE_CONTROL], LISTING_MAX_AGE); + assert_eq!(names(&body).len(), 4); + let (_, _, body) = get(&app, "/api/gallery/records?name=chess").await; + assert_eq!( + names(&body), + vec![("chess".to_owned(), 1), ("chess".to_owned(), 2)] + ); + } + + #[tokio::test] + async fn fetch_serves_the_exact_bundle_as_immutable() { + let (app, chess) = populated(); + let hash = &chess.manifest().content_hash; + let (status, headers, body) = get(&app, &format!("/api/gallery/bundles/{hash}")).await; + assert_eq!(status, StatusCode::OK); + assert_eq!(body, chess.to_bytes()); + assert!( + ProgramBundle::decode(&body).is_ok(), + "a fetched bundle verifies" + ); + assert_eq!(headers[header::CACHE_CONTROL], BUNDLE_CACHE); + assert_eq!(headers[header::ETAG], format!("\"{hash}\"").as_str()); + + let missing = "0".repeat(64); + let (status, _, _) = get(&app, &format!("/api/gallery/bundles/{missing}")).await; + assert_eq!(status, StatusCode::NOT_FOUND); + let (status, _, _) = get(&app, "/api/gallery/bundles/not-a-hash").await; + assert_eq!(status, StatusCode::BAD_REQUEST); + } + + #[tokio::test] + async fn search_answers_in_the_documented_order() { + let (app, _) = populated(); + let (status, _, body) = get(&app, "/api/gallery/search?q=chess").await; + assert_eq!(status, StatusCode::OK); + let answer: RecordsAnswer = serde_json::from_slice(&body).unwrap(); + assert_eq!(answer.order.as_deref(), Some(SEARCH_ORDER)); + assert_eq!( + names(&body), + vec![("chess".to_owned(), 2), ("chess".to_owned(), 1)] + ); + let (_, _, body) = get(&app, "/api/gallery/search?q=board").await; + assert_eq!( + names(&body), + vec![ + ("chess".to_owned(), 2), + ("chess".to_owned(), 1), + ("go".to_owned(), 1) + ], + "category matches, most recent version first" + ); + let (_, _, body) = get(&app, "/api/gallery/search?category=arcade").await; + assert_eq!(names(&body), vec![("racer".to_owned(), 4)]); + let (_, _, body) = get(&app, "/api/gallery/search?limit=1").await; + assert_eq!(names(&body), vec![("racer".to_owned(), 4)]); + let long = "a".repeat(id_worlds::program_gallery::MAX_QUERY_BYTES + 1); + let (status, _, _) = get(&app, &format!("/api/gallery/search?q={long}")).await; + assert_eq!(status, StatusCode::BAD_REQUEST); + } + + #[tokio::test] + async fn without_a_gallery_every_route_is_not_found() { + let app = app(None); + for uri in [ + "/api/gallery/records", + "/api/gallery/search?q=chess", + &format!("/api/gallery/bundles/{}", "0".repeat(64)), + ] { + assert_eq!(get(&app, uri).await.0, StatusCode::NOT_FOUND, "{uri}"); + } + } +} diff --git a/pkgs/id/crates/id-web/src/lib.rs b/pkgs/id/crates/id-web/src/lib.rs index 0b2b688102..6aedde0b13 100644 --- a/pkgs/id/crates/id-web/src/lib.rs +++ b/pkgs/id/crates/id-web/src/lib.rs @@ -49,6 +49,7 @@ mod assets; mod collab; mod content_mode; mod explore; +pub mod gallery; mod groups; mod home; mod identity; @@ -643,6 +644,10 @@ pub struct AppState { /// built anywhere else — the handler then answers 404 rather /// than inventing an ad. pub transport_ad: Option>, + /// The program gallery whose public read surface (list, fetch, search) + /// this node serves under `/api/gallery` (#10003). `None` unless the + /// serving process wires one in; every gallery route then answers 404. + pub gallery: Option, /// State for collaborative editing sessions. pub collab: Arc, /// Asset URLs (with cache-busting hashes). @@ -720,6 +725,7 @@ impl std::fmt::Debug for AppState { .field("groups_log", &self.groups_log) .field("seitan", &self.seitan) .field("transport_ad", &self.transport_ad.is_some()) + .field("gallery", &self.gallery.is_some()) .finish() } } @@ -771,6 +777,7 @@ impl AppState { store, transfer_endpoint: None, transport_ad: None, + gallery: None, collab: Arc::new(CollabState::new()), assets: load_asset_urls(), peers, @@ -817,6 +824,12 @@ impl AppState { ) { self.transport_ad = minter; } + + /// Serve this program gallery's read surface under `/api/gallery` + /// (#10003); see [`AppState::gallery`]. + pub fn set_gallery(&mut self, gallery: Option) { + self.gallery = gallery; + } } /// Load asset URLs from the embedded manifest. @@ -993,6 +1006,7 @@ pub async fn web_routers( seitan, None, None, + None, ) .await?; Ok(routers) @@ -1073,6 +1087,7 @@ pub async fn web_routers_with_surface( seitan: SeitanState, transfer_endpoint: Option, transport_ad: Option>, + gallery: Option, ) -> anyhow::Result<(Vec, WebSurfaceFactory)> { let mut state = match local_events { Some(events) => { @@ -1101,6 +1116,7 @@ pub async fn web_routers_with_surface( }; state.set_transfer_endpoint(transfer_endpoint); state.set_transport_ad(transport_ad); + state.set_gallery(gallery); let surface = WebSurfaceFactory { state: state.clone(), world: world.clone(), diff --git a/pkgs/id/crates/id-web/src/routes.rs b/pkgs/id/crates/id-web/src/routes.rs index 5ace3f79df..d884ed0a80 100644 --- a/pkgs/id/crates/id-web/src/routes.rs +++ b/pkgs/id/crates/id-web/src/routes.rs @@ -669,6 +669,9 @@ fn create_router_inner(state: AppState) -> Router { } None => router.merge(super::world_ws::world_http_routes().with_state(world_state)), }; + // The program gallery's read surface (#10003): 404 on every route + // unless the serving process wired a gallery in. + let router = router.merge(super::gallery::gallery_routes().with_state(state.gallery.clone())); let router = router .layer(DefaultBodyLimit::max(DEFAULT_BODY_LIMIT)) .with_state(state.clone()); diff --git a/pkgs/id/crates/id-worlds/src/lib.rs b/pkgs/id/crates/id-worlds/src/lib.rs index 4e57af21d5..f535d49a68 100644 --- a/pkgs/id/crates/id-worlds/src/lib.rs +++ b/pkgs/id/crates/id-worlds/src/lib.rs @@ -47,6 +47,7 @@ pub use id_core::port; pub mod blob_gate; pub mod groups; pub mod program_bundle; +pub mod program_gallery; pub mod program_registry; #[cfg(feature = "sandbox")] pub mod sandbox; diff --git a/pkgs/id/crates/id-worlds/src/program_bundle.rs b/pkgs/id/crates/id-worlds/src/program_bundle.rs index 911f86f679..1fec7fe362 100644 --- a/pkgs/id/crates/id-worlds/src/program_bundle.rs +++ b/pkgs/id/crates/id-worlds/src/program_bundle.rs @@ -66,6 +66,16 @@ pub const MAX_NAME_BYTES: usize = 128; /// Longest licence statement, in bytes. pub const MAX_LICENCE_BYTES: usize = 4096; +/// Longest discovery description, in bytes. +pub const MAX_DESCRIPTION_BYTES: usize = 4096; + +/// Most categories one manifest may assert. +pub const MAX_CATEGORIES: usize = 8; + +/// Longest category, in bytes. A category is lower-case ASCII letters, +/// digits and `-`, so it reads the same in every registry's taxonomy. +pub const MAX_CATEGORY_BYTES: usize = 64; + /// The guest ABI family programs target today (F12.7, `examples/roc-world/ABI.md`). pub const PLAZA_ABI_FAMILY: &str = "plaza"; @@ -128,6 +138,14 @@ pub struct BundleManifest { /// The author's licence statement, recorded but not adjudicated (D3). #[serde(default, skip_serializing_if = "Option::is_none")] pub licence: Option, + /// Discovery metadata: the author's description, signed with the + /// manifest, so a registry may index it but never alter it (v2 §1). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub description: Option, + /// Discovery metadata: the author's categories, signed with the + /// manifest. An operator's own tags are a separate overlay (v3 G2). + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub categories: Vec, } impl BundleManifest { @@ -166,6 +184,10 @@ pub struct ProgramSpec<'a> { pub version: u64, /// An optional licence statement. pub licence: Option<&'a str>, + /// An optional discovery description. + pub description: Option<&'a str>, + /// Discovery categories, each lower-case ASCII letters, digits and `-`. + pub categories: &'a [&'a str], } /// The check a bundle failed. Every refusal names exactly one. @@ -480,6 +502,8 @@ fn seal( abi: AbiDescriptor::plaza_v1(), lineage, licence: spec.licence.map(str::to_owned), + description: spec.description.map(str::to_owned), + categories: spec.categories.iter().map(|c| (*c).to_owned()).collect(), }; check_manifest(&manifest)?; check_payload(&payload)?; @@ -593,6 +617,7 @@ fn check_manifest(manifest: &BundleManifest) -> Result Result Result<(), String> { + if let Some(description) = &manifest.description + && description.len() > MAX_DESCRIPTION_BYTES + { + return Err(format!( + "description is {} bytes; the limit is {MAX_DESCRIPTION_BYTES}", + description.len() + )); + } + if manifest.categories.len() > MAX_CATEGORIES { + return Err(format!( + "{} categories; the limit is {MAX_CATEGORIES}", + manifest.categories.len() + )); + } + for (index, category) in manifest.categories.iter().enumerate() { + let portable = !category.is_empty() + && category.len() <= MAX_CATEGORY_BYTES + && category + .bytes() + .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-'); + if !portable { + return Err(format!( + "category {index} must be 1 to {MAX_CATEGORY_BYTES} lower-case ASCII letters, digits or '-'" + )); + } + if manifest.categories[..index].contains(category) { + return Err(format!("category {category:?} is repeated")); + } + } + Ok(()) +} + fn check_payload(payload: &[u8]) -> Result<(), BundleError> { if payload.is_empty() { return Err(BundleError::Payload("the payload is empty".to_owned())); @@ -651,6 +712,8 @@ mod tests { name, version, licence: Some("MIT"), + description: None, + categories: &[], } } @@ -843,6 +906,60 @@ mod tests { assert_eq!(check(&huge, spec("chess", 1)), "payload"); } + #[test] + fn discovery_metadata_is_signed_and_bounded() { + let key = alice(); + let with = |description: Option<&str>, categories: &[&str]| { + export( + PAYLOAD.to_vec(), + ProgramSpec { + description, + categories, + ..spec("chess", 1) + }, + &key, + ) + }; + let bundle = with(Some("The classic board game."), &["board", "two-player"]).unwrap(); + let decoded = ProgramBundle::decode(&bundle.to_bytes()).unwrap(); + assert_eq!( + decoded.manifest().description.as_deref(), + Some("The classic board game.") + ); + assert_eq!(decoded.manifest().categories, ["board", "two-player"]); + let bytes = bundle.to_bytes(); + let edited = String::from_utf8_lossy(&bytes).replacen("two-player", "one-player", 1); + assert_eq!( + ProgramBundle::decode(edited.as_bytes()) + .unwrap_err() + .check(), + "bundle_signature", + "a registry cannot alter signed discovery metadata" + ); + assert!( + !String::from_utf8_lossy(&spec_bundle_bytes()).contains("categories"), + "absent metadata is not serialised" + ); + + let check = |description: Option<&str>, categories: &[&str]| { + with(description, categories).unwrap_err().check() + }; + let long = "x".repeat(MAX_DESCRIPTION_BYTES + 1); + assert_eq!(check(Some(&long), &[]), "manifest"); + assert_eq!(check(None, &["Board"]), "manifest"); + assert_eq!(check(None, &[""]), "manifest"); + assert_eq!(check(None, &["board", "board"]), "manifest"); + let many: Vec = (0..=MAX_CATEGORIES).map(|i| format!("c{i}")).collect(); + let many: Vec<&str> = many.iter().map(String::as_str).collect(); + assert_eq!(check(None, &many), "manifest"); + } + + fn spec_bundle_bytes() -> Vec { + export(PAYLOAD.to_vec(), spec("chess", 1), &alice()) + .unwrap() + .to_bytes() + } + #[test] fn a_fork_of_a_fork_carries_the_whole_ordered_chain() { let parent = original(); @@ -853,6 +970,8 @@ mod tests { name: "chess-variant", version: 1, licence: None, + description: None, + categories: &[], }, &bob(), ) diff --git a/pkgs/id/crates/id-worlds/src/program_gallery.rs b/pkgs/id/crates/id-worlds/src/program_gallery.rs new file mode 100644 index 0000000000..a7863d4671 --- /dev/null +++ b/pkgs/id/crates/id-worlds/src/program_gallery.rs @@ -0,0 +1,530 @@ +//! The gallery read surface over a program registry (#10003; v3 design +//! `doc/2026-11-14T13-33-00Z_design_id_program_ecosystem_v3/`, G1, G3, G7). +//! +//! A [`Gallery`] is a [`Registry`] plus a full-text [`SearchIndex`] over the +//! records' signed discovery metadata (name, description, categories, +//! author key). The index is a cache, not a source: [`SearchIndex::rebuild`] +//! recreates it from registry records at any time, and it holds nothing a +//! record does not (G3). List and fetch are the registry's own operations, +//! unchanged (G1). +//! +//! Search order is deterministic and documented (G3): records whose name +//! equals the query come first, then records with a category equal to a +//! query word, then everything else; within each group the most recent +//! version comes first, then name, author and content hash break ties. +//! There is no engagement ranking. + +use std::collections::BTreeMap; + +use crate::program_bundle::{BundleManifest, BundleRecord}; +use crate::program_registry::{ListQuery, Registry, RegistryError}; + +/// Most results one search returns, whatever the caller asks for. +pub const MAX_SEARCH_RESULTS: usize = 200; + +/// Longest query text, in bytes. +pub const MAX_QUERY_BYTES: usize = 512; + +/// One search request. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct SearchQuery { + /// Free text. Every word must appear in the record's name, description, + /// categories or author key; empty text matches every record. + pub text: String, + /// Only records whose signed categories include this one. + pub category: Option, + /// Most results wanted; capped at [`MAX_SEARCH_RESULTS`]. + pub limit: Option, +} + +/// Why a search was refused. +#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)] +pub enum SearchError { + /// The query text is longer than [`MAX_QUERY_BYTES`]. + #[error("the query is {0} bytes; the limit is {MAX_QUERY_BYTES}")] + QueryTooLong(usize), +} + +#[derive(Clone, Debug)] +struct Indexed { + record: BundleRecord, + manifest: BundleManifest, + text: String, +} + +/// A rebuildable full-text index over verified records' discovery metadata. +#[derive(Clone, Debug, Default)] +pub struct SearchIndex { + entries: BTreeMap, +} + +impl SearchIndex { + /// An index of `records`. A record that does not verify is left out: it + /// is not a record anyone may serve (v2 §1). + #[must_use] + pub fn rebuild(records: impl IntoIterator) -> Self { + let mut index = Self::default(); + for record in records { + index.insert(record); + } + index + } + + /// Index one record, replacing any with the same content hash. Returns + /// whether it verified and was indexed. + pub fn insert(&mut self, record: BundleRecord) -> bool { + let Ok(manifest) = record.verify() else { + return false; + }; + let text = searchable_text(&manifest); + self.entries.insert( + manifest.content_hash.clone(), + Indexed { + record, + manifest, + text, + }, + ); + true + } + + /// Drop the record with this content hash, if indexed. + pub fn remove(&mut self, content_hash: &str) { + self.entries.remove(content_hash); + } + + /// How many records are indexed. + #[must_use] + pub fn len(&self) -> usize { + self.entries.len() + } + + /// Whether nothing is indexed. + #[must_use] + pub fn is_empty(&self) -> bool { + self.entries.is_empty() + } + + /// The records matching `query`, in the documented order. + /// + /// # Errors + /// + /// The query text is too long. + pub fn search(&self, query: &SearchQuery) -> Result, SearchError> { + if query.text.len() > MAX_QUERY_BYTES { + return Err(SearchError::QueryTooLong(query.text.len())); + } + let words = words(&query.text); + let phrase = words.join(" "); + let mut hits: Vec<(Rank, &Indexed)> = self + .entries + .values() + .filter(|entry| { + query + .category + .as_ref() + .is_none_or(|wanted| entry.manifest.categories.contains(wanted)) + }) + .filter(|entry| words.iter().all(|word| entry.text.contains(word.as_str()))) + .map(|entry| (rank(&entry.manifest, &phrase, &words), entry)) + .collect(); + hits.sort_by(|(a, _), (b, _)| a.cmp(b)); + let limit = query + .limit + .unwrap_or(MAX_SEARCH_RESULTS) + .min(MAX_SEARCH_RESULTS); + Ok(hits + .into_iter() + .take(limit) + .map(|(_, entry)| entry.record.clone()) + .collect()) + } +} + +/// A sort key: smaller sorts first. +#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)] +struct Rank { + /// 0 for an exact-name match, 1 otherwise. + exact_name: u8, + /// 0 for a category match, 1 otherwise. + category: u8, + /// The version, reversed so the most recent sorts first. + newest: std::cmp::Reverse, + name: String, + author: String, + content_hash: String, +} + +fn rank(manifest: &BundleManifest, phrase: &str, words: &[String]) -> Rank { + let exact_name = !phrase.is_empty() && manifest.name.to_lowercase() == phrase; + let category = manifest + .categories + .iter() + .any(|category| words.iter().any(|word| word == category)); + Rank { + exact_name: u8::from(!exact_name), + category: u8::from(!category), + newest: std::cmp::Reverse(manifest.version), + name: manifest.name.clone(), + author: manifest.author.clone(), + content_hash: manifest.content_hash.clone(), + } +} + +/// The lower-cased words of `text`: runs of letters, digits and `-`. +fn words(text: &str) -> Vec { + text.to_lowercase() + .split(|c: char| !(c.is_alphanumeric() || c == '-')) + .filter(|word| !word.is_empty()) + .map(str::to_owned) + .collect() +} + +fn searchable_text(manifest: &BundleManifest) -> String { + let mut text = manifest.name.to_lowercase(); + if let Some(description) = &manifest.description { + text.push('\n'); + text.push_str(&description.to_lowercase()); + } + for category in &manifest.categories { + text.push('\n'); + text.push_str(category); + } + text.push('\n'); + text.push_str(&manifest.author); + text +} + +/// A registry with its search index kept in step. +#[derive(Debug)] +pub struct Gallery { + registry: Registry, + index: SearchIndex, +} + +impl Gallery { + /// Serve `registry`, indexing every record it lists. + #[must_use] + pub fn new(registry: Registry) -> Self { + let index = SearchIndex::rebuild(registry.list(&ListQuery::default())); + Self { registry, index } + } + + /// The registry behind this gallery. + #[must_use] + pub const fn registry(&self) -> &Registry { + &self.registry + } + + /// The current search index. + #[must_use] + pub const fn index(&self) -> &SearchIndex { + &self.index + } + + /// Throw the index away and rebuild it from the registry's records. + pub fn rebuild_index(&mut self) { + self.index = SearchIndex::rebuild(self.registry.list(&ListQuery::default())); + } + + /// Publish through the registry and index the new record. + /// + /// # Errors + /// + /// Whatever [`Registry::publish`] refuses. + pub fn publish(&mut self, bytes: &[u8]) -> Result { + let record = self.registry.publish(bytes)?; + self.index.insert(record.clone()); + Ok(record) + } + + /// Withdraw on the author's signed request and drop it from the index. + /// + /// # Errors + /// + /// Whatever [`Registry::unpublish`] refuses. + pub fn unpublish( + &mut self, + content_hash: &str, + signature: &str, + ) -> Result { + let record = self.registry.unpublish(content_hash, signature)?; + self.index.remove(content_hash); + Ok(record) + } + + /// Delist on the operator's authority and drop it from the index. + /// + /// # Errors + /// + /// Whatever [`Registry::remove`] refuses. + pub fn remove(&mut self, content_hash: &str) -> Result { + let record = self.registry.remove(content_hash)?; + self.index.remove(content_hash); + Ok(record) + } + + /// The registry's list operation, unchanged. + #[must_use] + pub fn list(&self, query: &ListQuery) -> Vec { + self.registry.list(query) + } + + /// The registry's fetch operation, unchanged. + #[must_use] + pub fn fetch(&self, content_hash: &str) -> Option> { + self.registry.fetch(content_hash) + } + + /// Search the index. + /// + /// # Errors + /// + /// The query text is too long. + pub fn search(&self, query: &SearchQuery) -> Result, SearchError> { + self.index.search(query) + } +} + +#[cfg(test)] +#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] +mod tests { + use ed25519_dalek::SigningKey; + + use super::*; + use crate::program_bundle::{ProgramBundle, ProgramSpec, export}; + use crate::program_registry::{AdmitAll, sign_unpublish}; + + fn alice() -> SigningKey { + SigningKey::from_bytes(&[1; 32]) + } + + fn bob() -> SigningKey { + SigningKey::from_bytes(&[2; 32]) + } + + fn program( + author: &SigningKey, + name: &str, + version: u64, + description: &str, + categories: &[&str], + ) -> ProgramBundle { + export( + format!("{name} v{version}").into_bytes(), + ProgramSpec { + name, + version, + licence: None, + description: Some(description), + categories, + }, + author, + ) + .unwrap() + } + + fn names(records: &[BundleRecord]) -> Vec<(String, u64)> { + records + .iter() + .map(|record| { + let manifest = record.verify().unwrap(); + (manifest.name, manifest.version) + }) + .collect() + } + + fn gallery() -> Gallery { + let mut gallery = Gallery::new(Registry::in_memory(AdmitAll)); + for bundle in [ + program(&alice(), "chess", 1, "The classic board game.", &["board"]), + program( + &alice(), + "chess", + 2, + "The classic board game, faster.", + &["board"], + ), + program( + &bob(), + "chess-puzzles", + 3, + "Daily chess problems.", + &["puzzle"], + ), + program( + &bob(), + "go", + 1, + "Stones on a grid; a board classic.", + &["board"], + ), + program(&alice(), "board", 1, "A blank board to draw on.", &["art"]), + program(&bob(), "racer", 5, "Arcade driving.", &["arcade"]), + ] { + gallery.publish(&bundle.to_bytes()).unwrap(); + } + gallery + } + + fn search(gallery: &Gallery, text: &str) -> Vec<(String, u64)> { + names( + &gallery + .search(&SearchQuery { + text: text.to_owned(), + ..SearchQuery::default() + }) + .unwrap(), + ) + } + + #[test] + fn exact_name_comes_first_then_newest_version() { + assert_eq!( + search(&gallery(), "chess"), + vec![ + ("chess".to_owned(), 2), + ("chess".to_owned(), 1), + ("chess-puzzles".to_owned(), 3), + ] + ); + } + + #[test] + fn exact_name_then_category_match_then_the_rest() { + assert_eq!( + search(&gallery(), "Board"), + vec![ + ("board".to_owned(), 1), + ("chess".to_owned(), 2), + ("chess".to_owned(), 1), + ("go".to_owned(), 1), + ], + "the program named board, then the board category newest first" + ); + } + + #[test] + fn every_word_must_match_and_description_counts() { + assert_eq!( + search(&gallery(), "classic faster"), + vec![("chess".to_owned(), 2)] + ); + assert_eq!(search(&gallery(), "stones"), vec![("go".to_owned(), 1)]); + assert!(search(&gallery(), "nothing-like-this").is_empty()); + } + + #[test] + fn empty_text_lists_everything_newest_first_and_the_limit_caps_it() { + let gallery = gallery(); + let all = search(&gallery, ""); + assert_eq!(all.len(), 6); + assert_eq!(all[0], ("racer".to_owned(), 5)); + let two = gallery + .search(&SearchQuery { + limit: Some(2), + ..SearchQuery::default() + }) + .unwrap(); + assert_eq!(names(&two), all[..2].to_vec()); + } + + #[test] + fn a_category_filter_keeps_only_that_signed_category() { + let gallery = gallery(); + let board = gallery + .search(&SearchQuery { + category: Some("board".to_owned()), + ..SearchQuery::default() + }) + .unwrap(); + assert_eq!( + names(&board), + vec![ + ("chess".to_owned(), 2), + ("chess".to_owned(), 1), + ("go".to_owned(), 1), + ] + ); + let author = alice().verifying_key(); + let hex = crate::world_session::encode_hex(&author.to_bytes()); + assert_eq!( + search(&gallery, &hex).len(), + 3, + "the author key is searchable" + ); + } + + #[test] + fn the_order_does_not_depend_on_publish_order() { + let records = gallery().list(&ListQuery::default()); + let forward = SearchIndex::rebuild(records.clone()); + let backward = SearchIndex::rebuild(records.into_iter().rev()); + for text in ["", "chess", "board", "classic"] { + let query = SearchQuery { + text: text.to_owned(), + ..SearchQuery::default() + }; + assert_eq!( + forward.search(&query).unwrap(), + backward.search(&query).unwrap() + ); + } + } + + #[test] + fn the_index_rebuilds_from_records_alone_and_tracks_withdrawals() { + let mut gallery = gallery(); + let before = search(&gallery, "board"); + gallery.rebuild_index(); + assert_eq!(search(&gallery, "board"), before); + let rebuilt = SearchIndex::rebuild(gallery.list(&ListQuery::default())); + assert_eq!(rebuilt.len(), gallery.index().len()); + + let go = gallery + .list(&ListQuery { + author: None, + name: Some("go".to_owned()), + }) + .remove(0); + let hash = go.verify().unwrap().content_hash; + gallery + .unpublish(&hash, &sign_unpublish(&hash, &bob())) + .unwrap(); + assert!(search(&gallery, "stones").is_empty()); + let racer = gallery + .list(&ListQuery { + author: None, + name: Some("racer".to_owned()), + }) + .remove(0) + .verify() + .unwrap() + .content_hash; + gallery.remove(&racer).unwrap(); + assert!(search(&gallery, "arcade").is_empty()); + assert_eq!(gallery.index().len(), 4); + } + + #[test] + fn an_unverifiable_record_is_never_indexed() { + let record = program(&alice(), "chess", 1, "x", &[]).record(); + let forged = BundleRecord { + manifest: record.manifest.replace("\"x\"", "\"y\""), + ..record + }; + let index = SearchIndex::rebuild([forged]); + assert!(index.is_empty()); + } + + #[test] + fn an_overlong_query_is_refused() { + let error = gallery() + .search(&SearchQuery { + text: "a".repeat(MAX_QUERY_BYTES + 1), + ..SearchQuery::default() + }) + .unwrap_err(); + assert_eq!(error, SearchError::QueryTooLong(MAX_QUERY_BYTES + 1)); + } +} diff --git a/pkgs/id/crates/id-worlds/src/program_registry.rs b/pkgs/id/crates/id-worlds/src/program_registry.rs index 4bbc026e7d..d6702cc89b 100644 --- a/pkgs/id/crates/id-worlds/src/program_registry.rs +++ b/pkgs/id/crates/id-worlds/src/program_registry.rs @@ -494,6 +494,8 @@ mod tests { name, version, licence: None, + description: None, + categories: &[], }, author, ) @@ -706,6 +708,8 @@ mod tests { name: "chess", version: 1, licence: None, + description: None, + categories: &[], }, &bob(), ) diff --git a/pkgs/id/crates/id-worlds/src/world/tests.rs b/pkgs/id/crates/id-worlds/src/world/tests.rs index 21ce8abc60..b359fd78ed 100644 --- a/pkgs/id/crates/id-worlds/src/world/tests.rs +++ b/pkgs/id/crates/id-worlds/src/world/tests.rs @@ -2715,6 +2715,8 @@ mod tests { name: "chess", version: 1, licence: None, + description: None, + categories: &[], }, &author, ) diff --git a/pkgs/id/crates/id-worlds/src/world_session/tests.rs b/pkgs/id/crates/id-worlds/src/world_session/tests.rs index f36a38b8cf..e4dd0d5e0c 100644 --- a/pkgs/id/crates/id-worlds/src/world_session/tests.rs +++ b/pkgs/id/crates/id-worlds/src/world_session/tests.rs @@ -3382,6 +3382,8 @@ mod tests { name, version: 1, licence: Some("MIT"), + description: None, + categories: &[], }; let parent = export(wasm.clone(), spec("counter"), &original_author).unwrap(); let bundle = fork(&parent, wasm.clone(), spec("counter-plus"), &forker).unwrap(); diff --git a/pkgs/id/src/main.rs b/pkgs/id/src/main.rs index 383128378f..83b1af3823 100644 --- a/pkgs/id/src/main.rs +++ b/pkgs/id/src/main.rs @@ -306,6 +306,7 @@ async fn main() -> Result<()> { web_listen, web_token, web_cookie_secure, + gallery_dir, world, world_admin_token, world_module, @@ -356,6 +357,7 @@ async fn main() -> Result<()> { port_explicit, web_token, web_cookie_secure, + gallery_dir, world, world_admin_token, world_module,