diff --git a/crates/ghostlight-dungeon/src/bin/ghostlight-native-client.rs b/crates/ghostlight-dungeon/src/bin/ghostlight-native-client.rs new file mode 100644 index 0000000..8629f59 --- /dev/null +++ b/crates/ghostlight-dungeon/src/bin/ghostlight-native-client.rs @@ -0,0 +1,348 @@ +use anyhow::{Context, Result, bail}; +use base64::{Engine, engine::general_purpose::STANDARD}; +use chrono::Utc; +use cultnet_rs::{ + CULTNET_OPERATION_CONNECTION_ID, CultNetMessage, CultNetRudpSocketTransportConnection, + CultNetRudpSocketTransportOptions, +}; +use ghostlight_dungeon::persistence::CampaignStore; +use serde::{Deserialize, Serialize, de::DeserializeOwned}; +use serde_json::json; +use std::{ + io::Read, + net::{SocketAddr, UdpSocket}, + path::{Path, PathBuf}, + time::{Duration, Instant}, +}; + +const SERVICE_ID: &str = "ghostlight.native.player"; +const TARGET_RUNTIME_ID: &str = "ghostlight-dungeon-yggdrasil"; +const DEFAULT_ENDPOINT: &str = "127.0.0.1:4102"; + +#[derive(Clone, Debug, Serialize, Deserialize)] +struct NativeClientState { + schema: String, + pending_handle: Option, + session_token: Option, + refresh_expires_at: Option, + updated_at: String, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase")] +struct AuthBeginReceipt { + status: String, + handle: String, + expires_at: String, + navigation: AuthNavigation, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase")] +struct AuthNavigation { + url: String, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase")] +struct AuthCompletionReceipt { + status: String, + message: String, + session_token: Option, + refresh_expires_at: Option, +} + +struct ClientStore { + store: CampaignStore, + row: Option, + state: NativeClientState, + path: PathBuf, +} + +impl ClientStore { + fn open(path: impl AsRef) -> Result { + let path = path.as_ref().to_path_buf(); + if let Some(parent) = path.parent() { + std::fs::create_dir_all(parent)?; + } + let store = CampaignStore::open(&path)?; + let loaded = store.load::("native_client_state.v1", "primary")?; + let (row, state) = loaded.map_or_else( + || { + ( + None, + NativeClientState { + schema: "ghostlight.native_client_state.v1".into(), + pending_handle: None, + session_token: None, + refresh_expires_at: None, + updated_at: Utc::now().to_rfc3339(), + }, + ) + }, + |(row, state)| (Some(row), state), + ); + let client = Self { + store, + row, + state, + path, + }; + client.restrict_permissions()?; + Ok(client) + } + + fn commit(&mut self) -> Result<()> { + self.state.updated_at = Utc::now().to_rfc3339(); + self.row = Some(match &self.row { + Some(row) => { + self.store + .replace(row, "ghostlight.native_client_state.v1", &self.state)? + } + None => self.store.insert( + "native_client_state.v1", + "ghostlight.native_client_state.v1", + "primary", + &self.state, + )?, + }); + self.restrict_permissions() + } + + fn restrict_permissions(&self) -> Result<()> { + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + for path in [&self.path, &self.path.with_extension("cc.lock")] { + if path.exists() { + std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600))?; + } + } + } + Ok(()) + } +} + +fn main() -> Result<()> { + let (endpoint, state_path, command, rest) = parse_args()?; + let mut state = ClientStore::open(state_path)?; + match command.as_str() { + "auth-begin" => { + let receipt: AuthBeginReceipt = invoke( + endpoint, + "ghostlight.auth.begin", + "ghostlight.native_auth_begin.v1", + &json!({"schema":"ghostlight.native_auth_begin.v1"}), + )?; + if receipt.status != "pending" || receipt.handle.is_empty() { + bail!("Ghostlight returned an invalid native authentication attempt"); + } + state.state.pending_handle = Some(receipt.handle); + state.state.session_token = None; + state.state.refresh_expires_at = None; + state.commit()?; + println!( + "{}", + serde_json::to_string_pretty(&json!({ + "status":"pending", + "authorizationUrl":receipt.navigation.url, + "expiresAt":receipt.expires_at + }))? + ); + } + "auth-complete" => { + let handle = state + .state + .pending_handle + .clone() + .context("No pending native authentication attempt. Run auth-begin first.")?; + let receipt: AuthCompletionReceipt = invoke( + endpoint, + "ghostlight.auth.complete", + "ghostlight.native_auth_complete.v1", + &json!({"schema":"ghostlight.native_auth_complete.v1","handle":handle}), + )?; + if receipt.status == "authenticated" { + state.state.session_token = Some( + receipt + .session_token + .context("Authenticated native receipt omitted its session token")?, + ); + state.state.refresh_expires_at = receipt.refresh_expires_at; + state.state.pending_handle = None; + state.commit()?; + } + println!( + "{}", + serde_json::to_string_pretty(&json!({ + "status":receipt.status, + "message":receipt.message, + "refreshExpiresAt":state.state.refresh_expires_at + }))? + ); + } + "surface" => { + let session = state + .state + .session_token + .as_deref() + .context("Native Ghostlight client is not authenticated")?; + let value: serde_json::Value = invoke( + endpoint, + "ghostlight.surface.get", + "ghostlight.native_surface_get.v1", + &json!({"schema":"ghostlight.native_surface_get.v1","sessionToken":session,"invite":null}), + )?; + println!("{}", serde_json::to_string_pretty(&value)?); + } + "invoke" => { + if rest.len() != 3 { + bail!("invoke requires "); + } + let session = state + .state + .session_token + .as_deref() + .context("Native Ghostlight client is not authenticated")?; + let source_version = rest[2].parse::()?; + let mut input = String::new(); + std::io::stdin().read_to_string(&mut input)?; + let payload: serde_json::Value = if input.trim().is_empty() { + json!({}) + } else { + serde_json::from_str(&input).context("decode invocation payload from stdin")? + }; + let invocation = json!({ + "schema":"gamecult.eve.command_invocation.v1", + "providerId":"gamecult.ghostlight.dungeon", + "surfaceId":"ghostlight.play", + "operation":{ + "operationId":rest[0], + "schemaId":rest[1], + "idempotencyKey":uuid::Uuid::new_v4().to_string(), + "routeHint":{"sourceVersion":source_version,"transport":"cultnet-rudp"} + }, + "payload":payload, + "issuedAt":Utc::now().to_rfc3339(), + "clientId":"ghostlight-native-client", + "commandBoundary":"ghostlight.eve.commands", + "receiptSchema":"gamecult.eve.command_result.v1" + }); + let value: serde_json::Value = invoke( + endpoint, + "ghostlight.eve.invoke", + "ghostlight.native_eve_invocation.v1", + &json!({ + "schema":"ghostlight.native_eve_invocation.v1", + "sessionToken":session, + "invocation":invocation + }), + )?; + if rest[0] == "app.auth.logout" && value["receipt"]["state"] == "accepted" { + state.state.session_token = None; + state.state.refresh_expires_at = None; + state.commit()?; + } + println!("{}", serde_json::to_string_pretty(&value)?); + } + _ => bail!("unknown native client command {command}"), + } + Ok(()) +} + +fn parse_args() -> Result<(SocketAddr, PathBuf, String, Vec)> { + let mut args = std::env::args().skip(1).collect::>(); + let mut endpoint = DEFAULT_ENDPOINT.parse()?; + let mut state = None; + let mut index = 0; + while index < args.len() { + match args[index].as_str() { + "--endpoint" => { + let value = args.get(index + 1).context("--endpoint requires a value")?; + endpoint = value.parse()?; + args.drain(index..=index + 1); + } + "--state" => { + let value = args.get(index + 1).context("--state requires a value")?; + state = Some(PathBuf::from(value)); + args.drain(index..=index + 1); + } + _ => index += 1, + } + } + let state = state.context("--state is required")?; + let command = args.first().cloned().context( + "usage: ghostlight-native-client --state [--endpoint host:port] auth-begin|auth-complete|surface|invoke", + )?; + Ok((endpoint, state, command, args.into_iter().skip(1).collect())) +} + +fn invoke( + endpoint: SocketAddr, + operation: &str, + payload_schema: &str, + payload: &impl Serialize, +) -> Result { + let socket = UdpSocket::bind("127.0.0.1:0")?; + socket.set_read_timeout(Some(Duration::from_millis(25)))?; + let runtime_id = format!("ghostlight-native-client:{}", std::process::id()); + let mut options = CultNetRudpSocketTransportOptions::client( + runtime_id.clone(), + socket, + endpoint, + CULTNET_OPERATION_CONNECTION_ID, + ); + options.max_fragment_bytes = Some(2_048); + options.max_pending_reliable_packets = Some(4_096); + let mut transport = CultNetRudpSocketTransportConnection::new(options)?; + transport.connect(Vec::new())?; + let deadline = Instant::now() + Duration::from_secs(120); + while !transport.connected() && Instant::now() < deadline { + let _ = transport.receive_once()?; + transport.poll_resends()?; + } + if !transport.connected() { + bail!("Ghostlight native CultNet connection timed out"); + } + let message_id = uuid::Uuid::new_v4().to_string(); + transport.send_schema_message(&CultNetMessage::OperationRequest { + message_id: message_id.clone(), + service_id: SERVICE_ID.into(), + operation: operation.into(), + payload_schema: payload_schema.into(), + payload_encoding: "messagepack-base64".into(), + payload: STANDARD.encode(rmp_serde::to_vec_named(payload)?), + source_runtime_id: Some(runtime_id), + target_runtime_id: Some(TARGET_RUNTIME_ID.into()), + })?; + while Instant::now() < deadline { + if let Some(response) = transport.receive_schema_message_once()? { + let CultNetMessage::OperationResponse { + message_id: response_id, + status, + payload_encoding, + payload, + diagnostics, + .. + } = response + else { + continue; + }; + if response_id != message_id { + continue; + } + if status != "accepted" { + bail!( + "Ghostlight denied the native operation: {}", + diagnostics.join("; ") + ); + } + if payload_encoding != "messagepack-base64" { + bail!("Ghostlight returned an unsupported native payload encoding"); + } + return Ok(rmp_serde::from_slice(&STANDARD.decode(payload)?)?); + } + transport.poll_resends()?; + } + bail!("Ghostlight native operation timed out") +} diff --git a/crates/ghostlight-dungeon/src/heimdall.rs b/crates/ghostlight-dungeon/src/heimdall.rs index 5de58a1..9798d76 100644 --- a/crates/ghostlight-dungeon/src/heimdall.rs +++ b/crates/ghostlight-dungeon/src/heimdall.rs @@ -148,7 +148,7 @@ struct DiscordRolePolicy<'a> { allowed_role_ids: [&'a str; 1], } -#[derive(Debug, Deserialize)] +#[derive(Debug, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct AuthBeginReceipt { pub status: String, @@ -157,7 +157,7 @@ pub struct AuthBeginReceipt { pub navigation: AuthNavigation, } -#[derive(Debug, Deserialize)] +#[derive(Debug, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct AuthNavigation { pub url: String, diff --git a/crates/ghostlight-dungeon/src/main.rs b/crates/ghostlight-dungeon/src/main.rs index d426efd..0dacc8f 100644 --- a/crates/ghostlight-dungeon/src/main.rs +++ b/crates/ghostlight-dungeon/src/main.rs @@ -62,8 +62,10 @@ use tracing_subscriber::EnvFilter; mod app_session; mod heimdall; +mod native_cultmesh; use app_session::{AppSessionOwner, CommandReservation, NewSession, RefreshedSession, secret_hash}; use heimdall::HeimdallClient; +use native_cultmesh::NativeAuthCompletionReceipt; #[derive(Clone)] struct AppState { @@ -418,6 +420,7 @@ async fn main() -> anyhow::Result<()> { live_commit_gate: Arc::new(RwLock::new(())), mesh, }; + native_cultmesh::start(state.clone())?; refresh_mesh(&state).await?; tokio::spawn(scheduler_loop(state.clone())); tokio::spawn(app_session_refresh_loop(state.clone())); @@ -473,7 +476,7 @@ fn app_router(state: AppState, web_root: PathBuf) -> Router { .with_state(state) } -#[derive(Deserialize)] +#[derive(Clone, Debug, Serialize, Deserialize)] #[serde(deny_unknown_fields)] struct EveCommandInvocation { schema: String, @@ -493,7 +496,7 @@ struct EveCommandInvocation { receipt_schema: String, } -#[derive(Deserialize)] +#[derive(Clone, Debug, Serialize, Deserialize)] #[serde(deny_unknown_fields, rename_all = "camelCase")] struct EveOperation { operation_id: String, @@ -503,7 +506,7 @@ struct EveOperation { route_hint: EveRouteHint, } -#[derive(Default, Deserialize)] +#[derive(Clone, Debug, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] struct EveRouteHint { source_version: Option, @@ -567,7 +570,16 @@ async fn eve_command( State(state): State, Json(invocation): Json, ) -> Response { - if let Err(error) = validate_eve_invocation(&invocation) { + eve_command_for_transport(headers, state, invocation, "https-json").await +} + +async fn eve_command_for_transport( + headers: HeaderMap, + state: AppState, + invocation: EveCommandInvocation, + transport: &str, +) -> Response { + if let Err(error) = validate_eve_invocation(&invocation, transport) { return Json(eve_result( &invocation, "denied", @@ -865,80 +877,13 @@ async fn complete_eve_authentication( None, )).into_response(); } - if completion.handle.as_deref() != Some(handle) { - return Json(eve_result( - &invocation, - "denied", - "Heimdall completion handle did not match the browser-held attempt.".into(), - None, - None, - None, - )) - .into_response(); - } - let claims = match state.heimdall.verify_completion(&completion).await { + let adopted = match adopt_heimdall_completion(&state, handle, completion).await { Ok(value) => value, Err(error) => return Json(eve_result(&invocation, "denied", error.to_string(), None, Some(serde_json::json!({ "pluginId":"gamecult.heimdall.access","schemaId":"heimdall.auth_completion_status.v1", "payload":{"schema":"heimdall.auth_completion_status.v1","status":"denied"} })), None)).into_response(), }; - let session = completion.session.as_ref().unwrap(); - if !completion - .shared_capabilities - .iter() - .any(|value| value == "app_access") - { - return Json(eve_result( - &invocation, - "denied", - "Heimdall completion did not expose Ghostlight app_access.".into(), - None, - None, - None, - )) - .into_response(); - } - let refresh = completion - .refresh - .as_ref() - .map(|value| value.expires_at.as_str()) - .unwrap_or(&session.expires_at); - let refresh_token = completion.refresh_token.as_deref().unwrap_or(""); - if refresh_token.is_empty() { - return Json(eve_result( - &invocation, - "denied", - "Heimdall omitted its refresh claim.".into(), - None, - None, - None, - )) - .into_response(); - } - let refresh_expires_at = refresh.parse().unwrap_or_else(|_| Utc::now()); - let raw_cookie = match state.auth.lock().await.create_session(NewSession { - account_id: &claims.account_id, - heimdall_session_id: &claims.sid, - access_revision: claims.access_revision, - capabilities: claims.capabilities.clone(), - access_expires_at: DateTime::from_timestamp(claims.exp as i64, 0).unwrap_or_else(Utc::now), - refresh_expires_at, - refresh_claim: refresh_token, - }) { - Ok(value) => value, - Err(error) => { - return Json(eve_result( - &invocation, - "denied", - error.to_string(), - None, - None, - None, - )) - .into_response(); - } - }; let mut response = Json(eve_result( &invocation, "accepted", @@ -953,11 +898,104 @@ async fn complete_eve_authentication( .into_response(); response.headers_mut().insert( header::SET_COOKIE, - app_session_cookie(&raw_cookie, refresh_expires_at, Utc::now()), + app_session_cookie( + &adopted.session_token, + adopted.refresh_expires_at, + Utc::now(), + ), ); response } +struct AdoptedAppSession { + session_token: String, + refresh_expires_at: DateTime, +} + +async fn adopt_heimdall_completion( + state: &AppState, + expected_handle: &str, + completion: heimdall::AuthCompletionReceipt, +) -> anyhow::Result { + if completion.status != "authenticated" || completion.handle.as_deref() != Some(expected_handle) + { + anyhow::bail!("Heimdall completion did not match the pending Ghostlight attempt"); + } + let claims = state.heimdall.verify_completion(&completion).await?; + let session = completion + .session + .as_ref() + .context("Heimdall omitted its authenticated session")?; + if !completion + .shared_capabilities + .iter() + .any(|value| value == "app_access") + { + anyhow::bail!("Heimdall completion did not expose Ghostlight app_access"); + } + let refresh_expires_at = completion + .refresh + .as_ref() + .map(|value| value.expires_at.as_str()) + .unwrap_or(&session.expires_at) + .parse()?; + let refresh_token = completion + .refresh_token + .as_deref() + .context("Heimdall omitted its refresh claim")?; + let session_token = state.auth.lock().await.create_session(NewSession { + account_id: &claims.account_id, + heimdall_session_id: &claims.sid, + access_revision: claims.access_revision, + capabilities: claims.capabilities, + access_expires_at: DateTime::from_timestamp(claims.exp as i64, 0) + .context("Heimdall access expiry is invalid")?, + refresh_expires_at, + refresh_claim: refresh_token, + })?; + Ok(AdoptedAppSession { + session_token, + refresh_expires_at, + }) +} + +async fn complete_native_authentication( + state: &AppState, + handle: &str, + idempotency_key: &str, +) -> anyhow::Result { + let completion = state.heimdall.complete(handle, idempotency_key).await?; + match completion.status.as_str() { + "pending" => Ok(NativeAuthCompletionReceipt { + schema: "ghostlight.native_auth_completion_receipt.v1".into(), + status: "pending".into(), + message: "Heimdall is waiting for Discord authorization.".into(), + session_token: None, + refresh_expires_at: None, + }), + "denied" => Ok(NativeAuthCompletionReceipt { + schema: "ghostlight.native_auth_completion_receipt.v1".into(), + status: "denied".into(), + message: completion + .error + .unwrap_or_else(|| "Heimdall denied access.".into()), + session_token: None, + refresh_expires_at: None, + }), + "authenticated" => { + let adopted = adopt_heimdall_completion(state, handle, completion).await?; + Ok(NativeAuthCompletionReceipt { + schema: "ghostlight.native_auth_completion_receipt.v1".into(), + status: "authenticated".into(), + message: "Authenticated native Ghostlight client.".into(), + session_token: Some(adopted.session_token), + refresh_expires_at: Some(adopted.refresh_expires_at.to_rfc3339()), + }) + } + _ => anyhow::bail!("Heimdall returned an invalid authentication state"), + } +} + fn app_session_cookie( raw_cookie: &str, refresh_expires_at: DateTime, @@ -970,7 +1008,10 @@ fn app_session_cookie( .expect("Ghostlight generated an invalid app-session cookie") } -fn validate_eve_invocation(invocation: &EveCommandInvocation) -> anyhow::Result<()> { +fn validate_eve_invocation( + invocation: &EveCommandInvocation, + expected_transport: &str, +) -> anyhow::Result<()> { if invocation.schema != "gamecult.eve.command_invocation.v1" || invocation.provider_id != EVE_PROVIDER_ID || invocation.surface_id != EVE_SURFACE_ID @@ -996,18 +1037,10 @@ fn validate_eve_invocation(invocation: &EveCommandInvocation) -> anyhow::Result< anyhow::bail!("Invocation metadata is incomplete"); } if contains_authority_field(&invocation.payload) { - anyhow::bail!("Browser payloads may not supply actor, member, or account authority"); + anyhow::bail!("Player payloads may not supply actor, member, or account authority"); } - if invocation - .operation - .route_hint - .transport - .as_deref() - .is_some_and(|value| value != "https-json") - { - anyhow::bail!( - "Ghostlight's browser boundary accepts only its advertised HTTPS Eve transport" - ); + if invocation.operation.route_hint.transport.as_deref() != Some(expected_transport) { + anyhow::bail!("Eve invocation does not match the admitted transport boundary"); } let expected_schema = eve_operation_schema(&invocation.operation.operation_id) .ok_or_else(|| anyhow::anyhow!("Eve operation is not advertised by Ghostlight"))?; @@ -6002,6 +6035,81 @@ mod tests { ); } + #[tokio::test] + async fn native_cultmesh_surface_uses_the_same_heimdall_backed_app_session() { + use base64::{Engine, engine::general_purpose::STANDARD}; + use cultnet_rs::CultNetMessage; + + let dir = tempfile::tempdir().unwrap(); + let state = empty_app_state(dir.path()); + let (session_token, account_hash) = fixture_session(&state, "native-owner").await; + let request = CultNetMessage::OperationRequest { + message_id: "native-surface-1".into(), + service_id: native_cultmesh::NATIVE_SERVICE_ID.into(), + operation: native_cultmesh::NATIVE_SURFACE_GET.into(), + payload_schema: "ghostlight.native_surface_get.v1".into(), + payload_encoding: "messagepack-base64".into(), + payload: STANDARD.encode( + rmp_serde::to_vec_named(&native_cultmesh::NativeSurfaceGetCommand { + schema: "ghostlight.native_surface_get.v1".into(), + session_token, + invite: None, + }) + .unwrap(), + ), + source_runtime_id: Some("native-test".into()), + target_runtime_id: None, + }; + + let response = native_cultmesh::handle_operation(state, request).await; + let CultNetMessage::OperationResponse { + status, + payload_schema, + payload, + .. + } = response + else { + panic!("native boundary returned a non-operation response"); + }; + assert_eq!(status, "accepted"); + assert_eq!(payload_schema, "gamecult.eve.surface.v1"); + let surface: serde_json::Value = + rmp_serde::from_slice(&STANDARD.decode(payload).unwrap()).unwrap(); + assert_eq!(surface["schema"], "gamecult.eve.surface.v1"); + let encoded = serde_json::to_string(&surface).unwrap(); + assert!(!encoded.contains(&account_hash)); + assert!(!encoded.contains("sessionToken")); + } + + #[test] + fn eve_ingress_binds_each_transport_without_changing_command_semantics() { + let invocation = EveCommandInvocation { + schema: "gamecult.eve.command_invocation.v1".into(), + provider_id: EVE_PROVIDER_ID.into(), + surface_id: EVE_SURFACE_ID.into(), + operation: EveOperation { + operation_id: "world.speak".into(), + schema_id: Some("ghostlight.world_speak.v1".into()), + idempotency_key: Some("native-transport-witness".into()), + route_hint: EveRouteHint { + source_version: Some(1), + transport: Some("cultnet-rudp".into()), + }, + }, + payload: serde_json::json!({ + "expected_revision":1, + "text":"Hello from a native client." + }), + issued_at: Utc::now().to_rfc3339(), + client_id: "native-test".into(), + command_boundary: EVE_COMMAND_BOUNDARY.into(), + receipt_schema: EVE_RESULT_SCHEMA.into(), + }; + + assert!(validate_eve_invocation(&invocation, "cultnet-rudp").is_ok()); + assert!(validate_eve_invocation(&invocation, "https-json").is_err()); + } + #[test] fn each_refresh_attempt_has_a_distinct_command_identity() { let first = refresh_idempotency_key("heimdall-session"); diff --git a/crates/ghostlight-dungeon/src/mesh.rs b/crates/ghostlight-dungeon/src/mesh.rs index c64dd56..1d81603 100644 --- a/crates/ghostlight-dungeon/src/mesh.rs +++ b/crates/ghostlight-dungeon/src/mesh.rs @@ -216,6 +216,14 @@ impl MeshPublisher { "projectionKind":"actor-filtered-authoritative", "stateSchemas":["ghostlight.session_zero.v1","ghostlight.campaign.v1"], "commandBoundary":COMMAND_BOUNDARY, + "nativeCommandBoundary":{ + "serviceId":"ghostlight.native.player", + "transport":"cultnet.transport.rudp.v0", + "endpoint":"127.0.0.1:4102", + "exposure":"loopback-only", + "authentication":"Heimdall-backed Ghostlight app session", + "operations":["ghostlight.auth.begin","ghostlight.auth.complete","ghostlight.surface.get","ghostlight.eve.invoke"] + }, "receiptSchema":COMMAND_RESULT_SCHEMA, "loweringTargets":["browser","eve-native","tui"], "ownership":"Ghostlight kernels own state; Eve lowers projections and commands." @@ -227,7 +235,10 @@ impl MeshPublisher { "requiredCapabilities":["auth.gate","auth.begin","auth.complete","auth.logout"] }] }], - "commands":[{"command":COMMAND_BOUNDARY,"transport":"https-json","summary":"Canonical Ghostlight Eve command boundary."}] + "commands":[ + {"command":COMMAND_BOUNDARY,"transport":"https-json","summary":"Canonical Ghostlight Eve command boundary."}, + {"command":"ghostlight.native.player","transport":"cultnet.transport.rudp.v0","summary":"Loopback native access to the same actor-filtered surface and Eve command authority."} + ] }) } @@ -679,6 +690,14 @@ mod tests { surfaces[0]["worldInteraction"]["receiptSchema"], COMMAND_RESULT_SCHEMA ); + assert_eq!( + surfaces[0]["worldInteraction"]["nativeCommandBoundary"]["endpoint"], + "127.0.0.1:4102" + ); + assert_eq!( + surfaces[0]["worldInteraction"]["nativeCommandBoundary"]["exposure"], + "loopback-only" + ); assert_eq!( surfaces[0]["requiresPlugins"][0]["pluginId"], "gamecult.heimdall.access" diff --git a/crates/ghostlight-dungeon/src/native_cultmesh.rs b/crates/ghostlight-dungeon/src/native_cultmesh.rs new file mode 100644 index 0000000..4245497 --- /dev/null +++ b/crates/ghostlight-dungeon/src/native_cultmesh.rs @@ -0,0 +1,401 @@ +use super::{ + AppState, EveCommandInvocation, complete_native_authentication, eve_command_for_transport, + surface, +}; +use anyhow::{Context, Result, bail}; +use axum::{ + extract::State, + http::{HeaderMap, HeaderValue, header}, + response::Response, +}; +use base64::{Engine, engine::general_purpose::STANDARD}; +use cultnet_rs::{ + CULTNET_OPERATION_CONNECTION_ID, CultNetMessage, CultNetRudpServerEvent, CultNetRudpServerHub, + CultNetRudpServerHubOptions, CultNetRudpServerSessionContext, CultNetWireContract, + decode_cultnet_message_from_slice, +}; +use serde::{Deserialize, Serialize, de::DeserializeOwned}; +use std::{ + net::{SocketAddr, UdpSocket}, + sync::{ + Arc, + atomic::{AtomicUsize, Ordering}, + mpsc, + }, + time::Duration, +}; + +pub const NATIVE_ENDPOINT: &str = "127.0.0.1:4102"; +pub const NATIVE_SERVICE_ID: &str = "ghostlight.native.player"; +pub const NATIVE_RUNTIME_ID: &str = "ghostlight-dungeon-yggdrasil"; +pub const NATIVE_AUTH_BEGIN: &str = "ghostlight.auth.begin"; +pub const NATIVE_AUTH_COMPLETE: &str = "ghostlight.auth.complete"; +pub const NATIVE_SURFACE_GET: &str = "ghostlight.surface.get"; +pub const NATIVE_EVE_INVOKE: &str = "ghostlight.eve.invoke"; +const MAX_IN_FLIGHT: usize = 64; + +#[derive(Debug, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct NativeAuthBeginCommand { + pub schema: String, +} + +#[derive(Debug, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct NativeAuthCompleteCommand { + pub schema: String, + pub handle: String, +} + +#[derive(Debug, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct NativeSurfaceGetCommand { + pub schema: String, + pub session_token: String, + pub invite: Option, +} + +#[derive(Debug, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct NativeEveInvokeCommand { + pub schema: String, + pub session_token: String, + pub invocation: serde_json::Value, +} + +#[derive(Debug, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct NativeAuthCompletionReceipt { + pub schema: String, + pub status: String, + pub message: String, + pub session_token: Option, + pub refresh_expires_at: Option, +} + +#[derive(Debug, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +struct NativeFailure { + schema: String, + code: String, + message: String, +} + +struct CompletedResponse { + session: CultNetRudpServerSessionContext, + response: CultNetMessage, +} + +pub fn start(state: AppState) -> Result<()> { + let address: SocketAddr = NATIVE_ENDPOINT.parse()?; + let socket = UdpSocket::bind(address) + .with_context(|| format!("bind Ghostlight native CultNet boundary at {address}"))?; + socket.set_nonblocking(true)?; + let mut options = CultNetRudpServerHubOptions::new( + state.mesh.identity().runtime_id.clone(), + socket, + CULTNET_OPERATION_CONNECTION_ID, + ); + options.max_fragment_bytes = Some(2_048); + options.max_pending_reliable_packets = Some(4_096); + let hub = CultNetRudpServerHub::new(options)?; + let runtime = tokio::runtime::Handle::current(); + std::thread::Builder::new() + .name("ghostlight-native-cultmesh".into()) + .spawn(move || { + if let Err(error) = run_server(hub, state, runtime) { + tracing::error!(%error, "Ghostlight native CultMesh boundary stopped"); + std::process::exit(1); + } + })?; + Ok(()) +} + +fn run_server( + mut hub: CultNetRudpServerHub, + state: AppState, + runtime: tokio::runtime::Handle, +) -> Result<()> { + let (completed_tx, completed_rx) = mpsc::channel::(); + let in_flight = Arc::new(AtomicUsize::new(0)); + loop { + while let Ok(completed) = completed_rx.try_recv() { + in_flight.fetch_sub(1, Ordering::SeqCst); + if hub + .session(completed.session.remote_addr) + .is_some_and(|active| { + active.session_generation == completed.session.session_generation + }) + { + hub.send_schema_message(&completed.session, &completed.response)?; + } + } + if let Some(event) = hub.receive_event_once()? { + let CultNetRudpServerEvent::Frame { session, frame } = event else { + hub.poll_resends()?; + continue; + }; + if frame.channel_id != "schema" { + continue; + } + let request = match decode_cultnet_message_from_slice( + &frame.payload, + CultNetWireContract::CultNetSchemaV0, + ) { + Ok(request @ CultNetMessage::OperationRequest { .. }) => request, + Ok(_) => continue, + Err(error) => { + tracing::warn!(%error, "Ghostlight native boundary rejected malformed CultNet payload"); + continue; + } + }; + if in_flight.load(Ordering::SeqCst) >= MAX_IN_FLIGHT { + let response = failure_response( + &request, + "busy", + "Ghostlight is already processing the maximum native command pressure.", + )?; + hub.send_schema_message(&session, &response)?; + continue; + } + in_flight.fetch_add(1, Ordering::SeqCst); + let tx = completed_tx.clone(); + let request_state = state.clone(); + runtime.spawn(async move { + let response = handle_operation(request_state, request).await; + let _ = tx.send(CompletedResponse { session, response }); + }); + } + hub.poll_resends()?; + std::thread::sleep(Duration::from_millis(5)); + } +} + +pub(super) async fn handle_operation(state: AppState, request: CultNetMessage) -> CultNetMessage { + match handle_operation_inner(state, &request).await { + Ok(response) => response, + Err(error) => { + tracing::warn!(%error, "Ghostlight denied a native CultMesh operation"); + failure_response( + &request, + "command-denied", + "Ghostlight denied the typed native operation without changing world state.", + ) + .unwrap_or_else(|_| bare_failure_response(&request)) + } + } +} + +async fn handle_operation_inner( + state: AppState, + request: &CultNetMessage, +) -> Result { + let CultNetMessage::OperationRequest { + service_id, + operation, + payload_schema, + payload_encoding, + target_runtime_id, + .. + } = request + else { + bail!("native boundary accepts only operation requests"); + }; + if service_id != NATIVE_SERVICE_ID || payload_encoding != "messagepack-base64" { + bail!("native request does not match the advertised service contract"); + } + if target_runtime_id + .as_deref() + .is_some_and(|target| target != state.mesh.identity().runtime_id) + { + bail!("native request targets another runtime"); + } + match operation.as_str() { + NATIVE_AUTH_BEGIN => { + require_schema(payload_schema, "ghostlight.native_auth_begin.v1")?; + let command: NativeAuthBeginCommand = decode_request(request)?; + require_schema(&command.schema, "ghostlight.native_auth_begin.v1")?; + let receipt = state.heimdall.begin(message_id(request)?).await?; + success_response(request, "heimdall.auth_begin_receipt.v1", &receipt) + } + NATIVE_AUTH_COMPLETE => { + require_schema(payload_schema, "ghostlight.native_auth_complete.v1")?; + let command: NativeAuthCompleteCommand = decode_request(request)?; + require_schema(&command.schema, "ghostlight.native_auth_complete.v1")?; + if command.handle.trim().is_empty() { + bail!("native auth completion omitted its opaque handle"); + } + let receipt = + complete_native_authentication(&state, &command.handle, message_id(request)?) + .await?; + success_response( + request, + "ghostlight.native_auth_completion_receipt.v1", + &receipt, + ) + } + NATIVE_SURFACE_GET => { + require_schema(payload_schema, "ghostlight.native_surface_get.v1")?; + let command: NativeSurfaceGetCommand = decode_request(request)?; + require_schema(&command.schema, "ghostlight.native_surface_get.v1")?; + let headers = session_headers(&command.session_token)?; + let response = surface(headers, State(state), command.invite.as_deref()).await; + let value = response_json(response).await?; + success_response(request, "gamecult.eve.surface.v1", &value) + } + NATIVE_EVE_INVOKE => { + require_schema(payload_schema, "ghostlight.native_eve_invocation.v1")?; + let command: NativeEveInvokeCommand = decode_request(request)?; + require_schema(&command.schema, "ghostlight.native_eve_invocation.v1")?; + let headers = session_headers(&command.session_token)?; + let invocation: EveCommandInvocation = serde_json::from_value(command.invocation)?; + let response = + eve_command_for_transport(headers, state, invocation, "cultnet-rudp").await; + let value = response_json(response).await?; + success_response(request, "gamecult.eve.command_result.v1", &value) + } + _ => bail!("native operation is not advertised by Ghostlight"), + } +} + +fn require_schema(actual: &str, expected: &str) -> Result<()> { + if actual != expected { + bail!("native payload schema does not match the operation"); + } + Ok(()) +} + +fn session_headers(session_token: &str) -> Result { + if session_token.trim().is_empty() || session_token.len() > 256 { + bail!("native session token is malformed"); + } + let mut headers = HeaderMap::new(); + headers.insert( + header::COOKIE, + HeaderValue::from_str(&format!("ghostlight_session={session_token}"))?, + ); + Ok(headers) +} + +async fn response_json(response: Response) -> Result { + if !response.status().is_success() { + bail!("Ghostlight product boundary rejected the authenticated request"); + } + let bytes = axum::body::to_bytes(response.into_body(), 4 * 1024 * 1024).await?; + Ok(serde_json::from_slice(&bytes)?) +} + +fn decode_request(request: &CultNetMessage) -> Result { + let CultNetMessage::OperationRequest { payload, .. } = request else { + bail!("expected operation request"); + }; + Ok(rmp_serde::from_slice(&STANDARD.decode(payload)?)?) +} + +fn success_response( + request: &CultNetMessage, + payload_schema: &str, + payload: &impl Serialize, +) -> Result { + operation_response(request, "accepted", payload_schema, payload, Vec::new()) +} + +fn failure_response(request: &CultNetMessage, code: &str, message: &str) -> Result { + operation_response( + request, + "denied", + "ghostlight.native_failure.v1", + &NativeFailure { + schema: "ghostlight.native_failure.v1".into(), + code: code.into(), + message: message.into(), + }, + vec![message.into()], + ) +} + +fn bare_failure_response(request: &CultNetMessage) -> CultNetMessage { + let (message_id, operation) = match request { + CultNetMessage::OperationRequest { + message_id, + operation, + .. + } => (message_id.clone(), operation.clone()), + _ => (uuid::Uuid::new_v4().to_string(), "unknown".into()), + }; + CultNetMessage::OperationResponse { + message_id, + service_id: NATIVE_SERVICE_ID.into(), + operation, + status: "denied".into(), + payload_schema: "ghostlight.native_failure.v1".into(), + payload_encoding: "messagepack-base64".into(), + payload: String::new(), + diagnostics: vec!["Ghostlight denied the malformed native request.".into()], + source_runtime_id: Some(NATIVE_RUNTIME_ID.into()), + } +} + +fn operation_response( + request: &CultNetMessage, + status: &str, + payload_schema: &str, + payload: &impl Serialize, + diagnostics: Vec, +) -> Result { + let CultNetMessage::OperationRequest { + message_id, + service_id, + operation, + .. + } = request + else { + bail!("expected operation request"); + }; + Ok(CultNetMessage::OperationResponse { + message_id: message_id.clone(), + service_id: service_id.clone(), + operation: operation.clone(), + status: status.into(), + payload_schema: payload_schema.into(), + payload_encoding: "messagepack-base64".into(), + payload: STANDARD.encode(rmp_serde::to_vec_named(payload)?), + diagnostics, + source_runtime_id: Some(NATIVE_RUNTIME_ID.into()), + }) +} + +fn message_id(request: &CultNetMessage) -> Result<&str> { + let CultNetMessage::OperationRequest { message_id, .. } = request else { + bail!("expected operation request"); + }; + Ok(message_id) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn native_session_payload_rejects_authority_fields() { + let payload = serde_json::json!({ + "schema":"ghostlight.native_eve_invocation.v1", + "sessionToken":"opaque", + "invocation":{ + "schema":"gamecult.eve.command_invocation.v1", + "providerId":"gamecult.ghostlight.dungeon", + "surfaceId":"ghostlight.play", + "operation":{"operationId":"world.speak","schemaId":"ghostlight.world_speak.v1","idempotencyKey":"one","routeHint":{"sourceVersion":1,"transport":"cultnet-rudp"}}, + "payload":{"actor_id":"npc"}, + "issuedAt":"2026-08-23T00:00:00Z", + "clientId":"native-test", + "commandBoundary":"ghostlight.eve.commands", + "receiptSchema":"gamecult.eve.command_result.v1" + } + }); + let command = serde_json::from_value::(payload).unwrap(); + assert!(super::super::contains_authority_field( + &command.invocation["payload"] + )); + } +}