Route Ghostlight through Eve and Heimdall authorities

This commit is contained in:
Meta Vens 2026-08-22 02:04:56 +02:00
commit 62e5f05d9a
9 changed files with 3367 additions and 1334 deletions

3
Cargo.lock generated
View file

@ -787,16 +787,19 @@ dependencies = [
name = "ghostlight-dungeon"
version = "0.1.0"
dependencies = [
"aes-gcm",
"anyhow",
"async-stream",
"async-trait",
"axum",
"base64",
"chrono",
"cultcache-rs 0.1.0",
"cultcache-rs 0.1.0 (git+https://github.com/GameCult/cultcache-rs.git?rev=0ba87453115e3d44e8fcb7419866cd7dd70fb096)",
"cultmesh-rs",
"cultnet-rs",
"ghostlight-persona-projection",
"hmac",
"jsonschema",
"jsonwebtoken",
"rand 0.9.5",

View file

@ -16,16 +16,19 @@ version = "0.1.0"
[workspace.dependencies]
anyhow = "1"
aes-gcm = "0.10"
async-trait = "0.1"
async-stream = "0.3"
axum = { version = "0.8", features = ["macros"] }
chrono = { version = "0.4", features = ["serde"] }
base64 = "0.22"
cultcache-legacy = { package = "cultcache-rs", git = "https://github.com/GameCult/cultcache-rs.git", rev = "0ba87453115e3d44e8fcb7419866cd7dd70fb096" }
cultcache-rs = { path = "vendor/cultcache-rs" }
cultnet-rs = { path = "vendor/cultnet-rs" }
cultmesh-rs = { path = "vendor/cultmesh-rs" }
jsonschema = { version = "0.49", default-features = false }
jsonwebtoken = "9"
hmac = "0.12"
rand = "0.9"
reqwest = { version = "0.12", default-features = false, features = ["json", "rustls-tls", "stream"] }
rmp-serde = "1.3"

View file

@ -6,16 +6,19 @@ license.workspace = true
[dependencies]
anyhow.workspace = true
aes-gcm.workspace = true
async-trait.workspace = true
async-stream.workspace = true
axum.workspace = true
chrono.workspace = true
base64.workspace = true
cultcache-legacy.workspace = true
cultcache-rs.workspace = true
cultnet-rs.workspace = true
cultmesh-rs.workspace = true
jsonschema.workspace = true
jsonwebtoken.workspace = true
hmac.workspace = true
ghostlight-persona-projection = { path = "../ghostlight-persona-projection" }
rand.workspace = true
reqwest.workspace = true

View file

@ -0,0 +1,575 @@
use aes_gcm::{Aes256Gcm, KeyInit, aead::Aead};
use anyhow::{Context, bail};
use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD};
use chrono::{DateTime, Utc};
use ghostlight_dungeon::persistence::CampaignStore;
use rand::RngCore;
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use std::{collections::BTreeMap, path::Path};
#[derive(Clone, Serialize, Deserialize)]
pub struct AppSessionState {
pub schema: String,
pub sessions: BTreeMap<String, AppSession>,
pub account_preferences: BTreeMap<String, AccountPreferences>,
#[serde(default)]
pub command_receipts: BTreeMap<String, EveCommandCacheEntry>,
}
#[derive(Clone, Serialize, Deserialize)]
pub struct EveCommandCacheEntry {
pub schema: String,
pub account_subject_hash: String,
pub idempotency_key: String,
pub operation_id: String,
#[serde(default)]
pub command_result_messagepack: Option<Vec<u8>>,
pub created_at: DateTime<Utc>,
}
pub enum CommandReservation {
Reserved,
Pending,
Cached(serde_json::Value),
}
pub struct RefreshCandidate {
pub cookie_hash: String,
pub account_subject_hash: String,
pub heimdall_session_id: String,
pub access_revision: u64,
pub refresh_claim: String,
}
pub struct RefreshedSession<'a> {
pub expected_access_revision: u64,
pub access_revision: u64,
pub capabilities: Vec<String>,
pub access_expires_at: DateTime<Utc>,
pub refresh_expires_at: DateTime<Utc>,
pub refresh_claim: &'a str,
}
#[derive(Clone, Serialize, Deserialize)]
pub struct AppSession {
pub schema: String,
pub cookie_hash: String,
pub account_subject_hash: String,
pub heimdall_session_id: String,
pub access_revision: u64,
pub verified_capabilities: Vec<String>,
pub access_expires_at: DateTime<Utc>,
pub refresh_expires_at: DateTime<Utc>,
pub encrypted_refresh_claim: String,
pub created_at: DateTime<Utc>,
pub last_refresh_at: DateTime<Utc>,
pub revoked_at: Option<DateTime<Utc>>,
}
#[derive(Clone, Serialize, Deserialize)]
pub struct AccountPreferences {
pub schema: String,
pub account_subject_hash: String,
pub selected_campaign_id: Option<uuid::Uuid>,
pub updated_at: DateTime<Utc>,
}
pub struct NewSession<'a> {
pub account_id: &'a str,
pub heimdall_session_id: &'a str,
pub access_revision: u64,
pub capabilities: Vec<String>,
pub access_expires_at: DateTime<Utc>,
pub refresh_expires_at: DateTime<Utc>,
pub refresh_claim: &'a str,
}
pub struct AppSessionOwner {
store: CampaignStore,
row: cultcache_legacy::CultCacheEnvelope,
state: AppSessionState,
wrapping_key: [u8; 32],
}
impl AppSessionOwner {
pub fn open(
store_path: impl AsRef<Path>,
wrapping_key_path: impl AsRef<Path>,
) -> anyhow::Result<Self> {
let store = CampaignStore::open(store_path)?;
let (row, state) = match store.load::<AppSessionState>("app_session_store.v1", "primary")? {
Some(value) => value,
None => {
let state = AppSessionState {
schema: "ghostlight.app_session_store.v1".into(),
sessions: BTreeMap::new(),
account_preferences: BTreeMap::new(),
command_receipts: BTreeMap::new(),
};
let row = store.insert(
"app_session_store.v1",
"ghostlight.app_session_store.v1",
"primary",
&state,
)?;
(row, state)
}
};
Ok(Self {
store,
row,
state,
wrapping_key: read_wrapping_key(wrapping_key_path.as_ref())?,
})
}
pub fn create_session(&mut self, input: NewSession<'_>) -> anyhow::Result<String> {
if !input.capabilities.iter().any(|value| value == "app_access") {
bail!("Heimdall session lacks app_access");
}
let mut cookie = [0_u8; 32];
rand::rng().fill_bytes(&mut cookie);
let raw_cookie = URL_SAFE_NO_PAD.encode(cookie);
let cookie_hash = secret_hash(&raw_cookie);
let account_subject_hash = secret_hash(&format!("heimdall-account:{}", input.account_id));
let now = Utc::now();
let session = AppSession {
schema: "ghostlight.app_session.v1".into(),
cookie_hash: cookie_hash.clone(),
account_subject_hash: account_subject_hash.clone(),
heimdall_session_id: input.heimdall_session_id.into(),
access_revision: input.access_revision,
verified_capabilities: input.capabilities,
access_expires_at: input.access_expires_at,
refresh_expires_at: input.refresh_expires_at,
encrypted_refresh_claim: wrap_refresh(
&self.wrapping_key,
&account_subject_hash,
input.heimdall_session_id,
input.refresh_claim,
)?,
created_at: now,
last_refresh_at: now,
revoked_at: None,
};
let mut next = self.state.clone();
next.sessions.insert(cookie_hash, session);
next.account_preferences
.entry(account_subject_hash.clone())
.or_insert(AccountPreferences {
schema: "ghostlight.account_preferences.v1".into(),
account_subject_hash,
selected_campaign_id: None,
updated_at: now,
});
self.commit(next)?;
Ok(raw_cookie)
}
pub fn account_for_cookie(&self, raw_cookie: &str, now: DateTime<Utc>) -> Option<String> {
let session = self.state.sessions.get(&secret_hash(raw_cookie))?;
(session.revoked_at.is_none()
&& session.access_expires_at > now
&& session
.verified_capabilities
.iter()
.any(|value| value == "app_access"))
.then(|| session.account_subject_hash.clone())
}
pub fn revoke_cookie(&mut self, raw_cookie: &str) -> anyhow::Result<bool> {
let hash = secret_hash(raw_cookie);
let mut next = self.state.clone();
let Some(session) = next.sessions.get_mut(&hash) else {
return Ok(false);
};
session.revoked_at = Some(Utc::now());
self.commit(next)?;
Ok(true)
}
pub fn revoke_cookie_hash(&mut self, cookie_hash: &str) -> anyhow::Result<bool> {
let mut next = self.state.clone();
let Some(session) = next.sessions.get_mut(cookie_hash) else {
return Ok(false);
};
session.revoked_at = Some(Utc::now());
self.commit(next)?;
Ok(true)
}
pub fn sessions_due_for_refresh(
&self,
now: DateTime<Utc>,
refresh_before: chrono::Duration,
) -> anyhow::Result<Vec<RefreshCandidate>> {
self.state
.sessions
.values()
.filter(|session| {
session.revoked_at.is_none()
&& session.refresh_expires_at > now
&& session.access_expires_at <= now + refresh_before
})
.map(|session| {
Ok(RefreshCandidate {
cookie_hash: session.cookie_hash.clone(),
account_subject_hash: session.account_subject_hash.clone(),
heimdall_session_id: session.heimdall_session_id.clone(),
access_revision: session.access_revision,
refresh_claim: unwrap_refresh(
&self.wrapping_key,
&session.account_subject_hash,
&session.heimdall_session_id,
&session.encrypted_refresh_claim,
)?,
})
})
.collect()
}
pub fn session_for_logout(&self, raw_cookie: &str) -> anyhow::Result<Option<RefreshCandidate>> {
let Some(session) = self.state.sessions.get(&secret_hash(raw_cookie)) else {
return Ok(None);
};
if session.revoked_at.is_some() {
return Ok(None);
}
Ok(Some(RefreshCandidate {
cookie_hash: session.cookie_hash.clone(),
account_subject_hash: session.account_subject_hash.clone(),
heimdall_session_id: session.heimdall_session_id.clone(),
access_revision: session.access_revision,
refresh_claim: unwrap_refresh(
&self.wrapping_key,
&session.account_subject_hash,
&session.heimdall_session_id,
&session.encrypted_refresh_claim,
)?,
}))
}
pub fn apply_refresh(
&mut self,
cookie_hash: &str,
input: RefreshedSession<'_>,
) -> anyhow::Result<()> {
if !input.capabilities.iter().any(|value| value == "app_access") {
bail!("refreshed Heimdall session lacks app_access");
}
let mut next = self.state.clone();
let session = next
.sessions
.get_mut(cookie_hash)
.context("local session vanished during refresh")?;
if session.revoked_at.is_some() || session.access_revision != input.expected_access_revision
{
bail!("local session changed during refresh");
}
session.access_revision = input.access_revision;
session.verified_capabilities = input.capabilities;
session.access_expires_at = input.access_expires_at;
session.refresh_expires_at = input.refresh_expires_at;
session.encrypted_refresh_claim = wrap_refresh(
&self.wrapping_key,
&session.account_subject_hash,
&session.heimdall_session_id,
input.refresh_claim,
)?;
session.last_refresh_at = Utc::now();
self.commit(next)
}
pub fn selected_campaign(&self, account_subject_hash: &str) -> Option<uuid::Uuid> {
self.state
.account_preferences
.get(account_subject_hash)?
.selected_campaign_id
}
pub fn select_campaign(
&mut self,
account_subject_hash: &str,
campaign_id: uuid::Uuid,
) -> anyhow::Result<()> {
let mut next = self.state.clone();
let preferences = next
.account_preferences
.entry(account_subject_hash.into())
.or_insert(AccountPreferences {
schema: "ghostlight.account_preferences.v1".into(),
account_subject_hash: account_subject_hash.into(),
selected_campaign_id: None,
updated_at: Utc::now(),
});
preferences.selected_campaign_id = Some(campaign_id);
preferences.updated_at = Utc::now();
self.commit(next)
}
pub fn migrate_preference(
&mut self,
account_subject_hash: &str,
campaign_id: uuid::Uuid,
) -> anyhow::Result<()> {
if self.selected_campaign(account_subject_hash).is_none() {
self.select_campaign(account_subject_hash, campaign_id)?;
}
Ok(())
}
pub fn reserve_command(
&mut self,
account_subject_hash: &str,
idempotency_key: &str,
operation_id: &str,
) -> anyhow::Result<CommandReservation> {
let key = command_cache_key(account_subject_hash, idempotency_key);
if let Some(entry) = self.state.command_receipts.get(&key) {
if entry.operation_id != operation_id
|| entry.account_subject_hash != account_subject_hash
{
bail!("idempotency key is already bound to another operation");
}
return match &entry.command_result_messagepack {
Some(bytes) => Ok(CommandReservation::Cached(rmp_serde::from_slice(bytes)?)),
None => Ok(CommandReservation::Pending),
};
}
let mut next = self.state.clone();
next.command_receipts.insert(
key,
EveCommandCacheEntry {
schema: "ghostlight.eve_command_cache_entry.v1".into(),
account_subject_hash: account_subject_hash.into(),
idempotency_key: idempotency_key.into(),
operation_id: operation_id.into(),
command_result_messagepack: None,
created_at: Utc::now(),
},
);
self.commit(next)?;
Ok(CommandReservation::Reserved)
}
pub fn record_command_result(
&mut self,
account_subject_hash: &str,
idempotency_key: &str,
operation_id: &str,
result: &serde_json::Value,
) -> anyhow::Result<()> {
let key = command_cache_key(account_subject_hash, idempotency_key);
let mut next = self.state.clone();
let entry = next
.command_receipts
.get_mut(&key)
.ok_or_else(|| anyhow::anyhow!("command result has no reservation"))?;
if entry.operation_id != operation_id || entry.account_subject_hash != account_subject_hash
{
bail!("command result disagrees with its reservation");
}
entry.command_result_messagepack = Some(rmp_serde::to_vec_named(result)?);
self.commit(next)
}
fn commit(&mut self, next: AppSessionState) -> anyhow::Result<()> {
let next_row = self
.store
.replace(&self.row, "ghostlight.app_session_store.v1", &next)?;
self.row = next_row;
self.state = next;
Ok(())
}
}
fn command_cache_key(account_subject_hash: &str, idempotency_key: &str) -> String {
secret_hash(&format!(
"eve-command:{account_subject_hash}:{idempotency_key}"
))
}
pub fn secret_hash(value: &str) -> String {
format!("sha256:{:x}", Sha256::digest(value.as_bytes()))
}
fn read_wrapping_key(path: &Path) -> anyhow::Result<[u8; 32]> {
let source =
std::fs::read(path).with_context(|| format!("failed to read {}", path.display()))?;
let decoded = if source.len() == 32 {
source
} else {
let text = std::str::from_utf8(&source)?.trim();
URL_SAFE_NO_PAD
.decode(text)
.context("session wrapping key must be 32 raw bytes or base64url")?
};
decoded
.try_into()
.map_err(|_| anyhow::anyhow!("session wrapping key must be exactly 32 bytes"))
}
fn wrap_refresh(
key: &[u8; 32],
account_hash: &str,
session_id: &str,
claim: &str,
) -> anyhow::Result<String> {
let mut iv = [0_u8; 12];
rand::rng().fill_bytes(&mut iv);
let aad = format!("ghostlight.app_session.refresh.v1\n{account_hash}\n{session_id}");
let ciphertext = Aes256Gcm::new_from_slice(key)?
.encrypt(
(&iv).into(),
aes_gcm::aead::Payload {
msg: claim.as_bytes(),
aad: aad.as_bytes(),
},
)
.map_err(|_| anyhow::anyhow!("failed to wrap Heimdall refresh claim"))?;
Ok(format!(
"{}.{}",
URL_SAFE_NO_PAD.encode(iv),
URL_SAFE_NO_PAD.encode(ciphertext)
))
}
fn unwrap_refresh(
key: &[u8; 32],
account_hash: &str,
session_id: &str,
wrapped: &str,
) -> anyhow::Result<String> {
let (iv, ciphertext) = wrapped
.split_once('.')
.context("wrapped refresh claim is malformed")?;
let iv = URL_SAFE_NO_PAD.decode(iv)?;
let iv: [u8; 12] = iv
.try_into()
.map_err(|_| anyhow::anyhow!("wrapped refresh IV is invalid"))?;
let ciphertext = URL_SAFE_NO_PAD.decode(ciphertext)?;
let aad = format!("ghostlight.app_session.refresh.v1\n{account_hash}\n{session_id}");
let plaintext = Aes256Gcm::new_from_slice(key)?
.decrypt(
(&iv).into(),
aes_gcm::aead::Payload {
msg: &ciphertext,
aad: aad.as_bytes(),
},
)
.map_err(|_| anyhow::anyhow!("failed to unwrap Heimdall refresh claim"))?;
String::from_utf8(plaintext).context("Heimdall refresh claim is not UTF-8")
}
#[cfg(test)]
mod tests {
use super::*;
use tempfile::tempdir;
#[test]
fn app_session_persists_cookie_hash_and_selected_campaign_without_campaign_lists() {
let directory = tempdir().unwrap();
let key = directory.path().join("session.key");
std::fs::write(&key, [7_u8; 32]).unwrap();
let store = directory.path().join("app-sessions.cc");
let mut owner = AppSessionOwner::open(&store, &key).unwrap();
let cookie = owner
.create_session(NewSession {
account_id: "account-1",
heimdall_session_id: "heimdall-session-1",
access_revision: 3,
capabilities: vec!["app_access".into()],
access_expires_at: Utc::now() + chrono::Duration::minutes(5),
refresh_expires_at: Utc::now() + chrono::Duration::days(7),
refresh_claim: "private-refresh-claim",
})
.unwrap();
let account = owner.account_for_cookie(&cookie, Utc::now()).unwrap();
assert!(!store.to_string_lossy().contains(&cookie));
let campaign = uuid::Uuid::new_v4();
owner.select_campaign(&account, campaign).unwrap();
drop(owner);
let reopened = AppSessionOwner::open(&store, &key).unwrap();
assert_eq!(
reopened.account_for_cookie(&cookie, Utc::now()),
Some(account.clone())
);
assert_eq!(reopened.selected_campaign(&account), Some(campaign));
drop(reopened);
let bytes = std::fs::read(&store).unwrap();
assert!(
!bytes
.windows(cookie.len())
.any(|window| window == cookie.as_bytes())
);
assert!(
!bytes
.windows("private-refresh-claim".len())
.any(|window| window == b"private-refresh-claim")
);
}
#[test]
fn refresh_is_exact_session_cas_and_rotates_private_claim() {
let directory = tempdir().unwrap();
let key = directory.path().join("session.key");
std::fs::write(&key, [11_u8; 32]).unwrap();
let mut owner =
AppSessionOwner::open(directory.path().join("app-sessions.cc"), &key).unwrap();
let now = Utc::now();
let cookie = owner
.create_session(NewSession {
account_id: "account-1",
heimdall_session_id: "session-1",
access_revision: 4,
capabilities: vec!["app_access".into()],
access_expires_at: now + chrono::Duration::minutes(2),
refresh_expires_at: now + chrono::Duration::days(7),
refresh_claim: "refresh-before",
})
.unwrap();
let due = owner
.sessions_due_for_refresh(now, chrono::Duration::minutes(5))
.unwrap();
assert_eq!(due.len(), 1);
assert_eq!(due[0].refresh_claim, "refresh-before");
owner
.apply_refresh(
&due[0].cookie_hash,
RefreshedSession {
expected_access_revision: 4,
access_revision: 5,
capabilities: vec!["app_access".into()],
access_expires_at: now + chrono::Duration::hours(1),
refresh_expires_at: now + chrono::Duration::days(7),
refresh_claim: "refresh-after",
},
)
.unwrap();
assert!(
owner
.apply_refresh(
&due[0].cookie_hash,
RefreshedSession {
expected_access_revision: 4,
access_revision: 6,
capabilities: vec!["app_access".into()],
access_expires_at: now + chrono::Duration::hours(1),
refresh_expires_at: now + chrono::Duration::days(7),
refresh_claim: "stale-refresh",
}
)
.is_err()
);
assert_eq!(
owner
.session_for_logout(&cookie)
.unwrap()
.unwrap()
.refresh_claim,
"refresh-after"
);
}
}

View file

@ -1,37 +1,84 @@
use aes_gcm::{
Aes256Gcm, KeyInit,
aead::{Aead, Payload},
};
use anyhow::{Context, bail};
use base64::{
Engine,
engine::general_purpose::{STANDARD, URL_SAFE_NO_PAD},
};
use chrono::{DateTime, SecondsFormat, Utc};
use cultnet_rs::{
CULTNET_OPERATION_CONNECTION_ID, CultNetMessage, CultNetRudpSocketTransportConnection,
CultNetRudpSocketTransportOptions,
};
use hmac::{Hmac, Mac};
use jsonwebtoken::{Algorithm, DecodingKey, Validation, decode, decode_header, jwk::JwkSet};
use rand::RngCore;
use reqwest::Client;
use serde::{Deserialize, Serialize};
use serde::{Deserialize, Serialize, de::DeserializeOwned};
use sha2::{Digest, Sha256};
use std::{
net::{SocketAddr, UdpSocket},
path::PathBuf,
time::{Duration, Instant},
};
const APP_SLUG: &str = "ghostlight";
const PRIVATE_SERVICE: &str = "heimdall.private.commands";
const PRIVATE_ENVELOPE_SCHEMA: &str = "heimdall.private_command_envelope.v1";
#[derive(Clone)]
pub struct HeimdallClient {
client: Client,
base_url: String,
http: Client,
issuer: String,
public_app_url: String,
callback_url: String,
discord_guild_id: String,
discord_role_id: String,
private_endpoint: SocketAddr,
runtime_id: String,
shared_secret: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
struct PrivateEnvelope {
schema: String,
app_slug: String,
operation: String,
content_schema: String,
issued_at: String,
expires_at: String,
nonce: String,
idempotency_key: String,
iv: String,
ciphertext: String,
auth_tag: String,
signature: String,
}
#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
struct StartRequest<'a> {
app_slug: &'a str,
struct BeginCommand<'a> {
provider: &'a str,
mode: &'a str,
return_to: &'a str,
handoff: Handoff<'a>,
requested_scopes: [&'a str; 2],
entitlement_policy: DiscordRolePolicy<'a>,
}
#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
struct Handoff<'a> {
kind: &'a str,
attempt_id: &'a str,
callback_url: &'a str,
struct RefreshCommand<'a> {
schema: &'static str,
refresh_token: &'a str,
entitlement_policy: DiscordRolePolicy<'a>,
}
#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
struct LogoutCommand<'a> {
schema: &'static str,
refresh_token: &'a str,
}
#[derive(Serialize)]
@ -42,35 +89,77 @@ struct DiscordRolePolicy<'a> {
allowed_role_ids: [&'a str; 1],
}
#[derive(Deserialize)]
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct StartResponse {
pub authorization_url: String,
pub struct AuthBeginReceipt {
pub status: String,
pub handle: String,
pub expires_at: String,
pub navigation: AuthNavigation,
}
#[derive(Deserialize)]
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BackendCallback {
pub source: String,
pub kind: String,
pub handoff_kind: String,
pub attempt_id: String,
pub struct AuthNavigation {
pub url: String,
pub allowed_origins: Vec<String>,
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AuthCompletionReceipt {
pub status: String,
pub provider: String,
pub app_slug: String,
pub mode: String,
pub return_to: String,
pub access_token: Option<String>,
pub handle: Option<String>,
pub error: Option<String>,
pub error_description: Option<String>,
pub account: Option<AccountSummary>,
pub session: Option<HeimdallSession>,
pub access_token: Option<String>,
pub refresh_token: Option<String>,
pub refresh: Option<RefreshSummary>,
#[serde(default)]
pub shared_capabilities: Vec<String>,
}
#[derive(Debug, Deserialize)]
pub struct AccountSummary {
pub id: String,
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct HeimdallSession {
pub account_id: String,
pub session_id: String,
pub app_slug: String,
pub access_revision: u64,
pub expires_at: String,
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RefreshSummary {
pub expires_at: String,
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AuthLogoutReceipt {
pub status: String,
pub session_id: String,
pub access_revision: u64,
pub revoked_at: String,
}
#[derive(Debug, Deserialize)]
pub struct AccessClaims {
pub iss: String,
pub aud: String,
pub sub: String,
pub sid: String,
pub exp: u64,
pub typ: String,
pub account_id: String,
pub access_revision: u64,
pub capabilities: Vec<String>,
pub app: AppClaim,
}
@ -82,103 +171,173 @@ pub struct AppClaim {
impl HeimdallClient {
pub fn from_env() -> anyhow::Result<Self> {
let private_endpoint = std::env::var("GHOSTLIGHT_HEIMDALL_PRIVATE_RUDP")
.unwrap_or_else(|_| "rudp://127.0.0.1:4101".into());
let private_endpoint = private_endpoint
.strip_prefix("rudp://")
.unwrap_or(&private_endpoint)
.parse()
.context("GHOSTLIGHT_HEIMDALL_PRIVATE_RUDP is not a socket address")?;
let secret_path = std::env::var_os("GHOSTLIGHT_HEIMDALL_APP_SECRET_FILE")
.map(PathBuf::from)
.context("GHOSTLIGHT_HEIMDALL_APP_SECRET_FILE is required")?;
let shared_secret = std::fs::read_to_string(&secret_path)
.with_context(|| format!("failed to read {}", secret_path.display()))?
.trim()
.to_owned();
if shared_secret.is_empty() {
bail!("Ghostlight's Heimdall app secret is empty");
}
Ok(Self {
client: Client::builder()
.timeout(std::time::Duration::from_secs(10))
.build()?,
base_url: std::env::var("GHOSTLIGHT_HEIMDALL_BASE_URL")
http: Client::builder().timeout(Duration::from_secs(10)).build()?,
issuer: std::env::var("GHOSTLIGHT_HEIMDALL_BASE_URL")
.unwrap_or_else(|_| "https://heimdall.gamecult.org".into())
.trim_end_matches('/')
.into(),
public_app_url: std::env::var("GHOSTLIGHT_PUBLIC_APP_URL")
.unwrap_or_else(|_| "https://yggdrasil.gamecult.org/ghostlight/".into()),
callback_url: std::env::var("GHOSTLIGHT_HEIMDALL_CALLBACK_URL").unwrap_or_else(|_| {
"https://yggdrasil.gamecult.org/ghostlight/api/auth/heimdall/callback".into()
}),
discord_guild_id: required_env("GHOSTLIGHT_DISCORD_GUILD_ID")?,
discord_role_id: required_env("GHOSTLIGHT_DISCORD_ROLE_ID")?,
private_endpoint,
runtime_id: std::env::var("GHOSTLIGHT_RUNTIME_ID")
.unwrap_or_else(|_| "yggdrasil-ghostlight".into()),
shared_secret,
})
}
#[cfg(test)]
pub fn fixture() -> Self {
Self {
client: Client::new(),
base_url: "https://heimdall.invalid".into(),
http: Client::new(),
issuer: "https://heimdall.invalid".into(),
public_app_url: "https://ghostlight.invalid/".into(),
callback_url: "https://ghostlight.invalid/api/auth/heimdall/callback".into(),
discord_guild_id: "guild-kltst".into(),
discord_role_id: "role-kltst".into(),
private_endpoint: "127.0.0.1:9".parse().unwrap(),
runtime_id: "yggdrasil-ghostlight".into(),
shared_secret: "fixture-secret".into(),
}
}
pub async fn start(&self, attempt_id: &str) -> anyhow::Result<StartResponse> {
self.client
.post(format!("{}/v1/oauth/discord/start", self.base_url))
.json(&StartRequest {
app_slug: APP_SLUG,
mode: "sign_in",
return_to: &self.public_app_url,
handoff: Handoff {
kind: "backend_callback",
attempt_id,
callback_url: &self.callback_url,
},
requested_scopes: ["identify", "guilds.members.read"],
entitlement_policy: DiscordRolePolicy {
kind: "discord_role_access",
guild_id: &self.discord_guild_id,
allowed_role_ids: [&self.discord_role_id],
},
})
.send()
.await?
.error_for_status()?
.json()
.await
.context("Heimdall start response was malformed")
}
pub async fn verify_callback(
&self,
callback: &BackendCallback,
) -> anyhow::Result<AccessClaims> {
self.validate_callback_envelope(callback)?;
if callback.status != "success" {
bail!("Heimdall callback did not grant Ghostlight access");
}
self.verify(
callback
.access_token
.as_deref()
.context("Heimdall success callback omitted its access token")?,
pub async fn begin(&self, idempotency_key: &str) -> anyhow::Result<AuthBeginReceipt> {
let payload = BeginCommand {
provider: "discord",
mode: "sign_in",
return_to: &self.public_app_url,
entitlement_policy: DiscordRolePolicy {
kind: "discord_role_access",
guild_id: &self.discord_guild_id,
allowed_role_ids: [&self.discord_role_id],
},
};
self.invoke(
"heimdall.auth.begin",
"heimdall.auth_begin_command.v1",
idempotency_key,
&payload,
"heimdall.auth_begin_receipt.v1",
)
.await
}
pub fn validate_callback_envelope(&self, callback: &BackendCallback) -> anyhow::Result<()> {
if callback.source != "heimdall"
|| callback.kind != "oauth_result"
|| callback.handoff_kind != "backend_callback"
|| callback.provider != "discord"
|| callback.app_slug != APP_SLUG
|| callback.mode != "sign_in"
|| callback.return_to != self.public_app_url
{
bail!("Heimdall callback did not match the Ghostlight login contract");
}
Ok(())
pub async fn complete(
&self,
handle: &str,
idempotency_key: &str,
) -> anyhow::Result<AuthCompletionReceipt> {
self.invoke(
"heimdall.auth.complete",
"heimdall.auth_complete_command.v1",
idempotency_key,
&serde_json::json!({"handle": handle}),
"heimdall.auth_completion_receipt.v1",
)
.await
}
async fn verify(&self, token: &str) -> anyhow::Result<AccessClaims> {
pub async fn refresh(
&self,
refresh_token: &str,
idempotency_key: &str,
) -> anyhow::Result<AuthCompletionReceipt> {
let payload = RefreshCommand {
schema: "heimdall.auth_refresh_command.v1",
refresh_token,
entitlement_policy: DiscordRolePolicy {
kind: "discord_role_access",
guild_id: &self.discord_guild_id,
allowed_role_ids: [&self.discord_role_id],
},
};
self.invoke(
"heimdall.auth.refresh",
"heimdall.auth_refresh_command.v1",
idempotency_key,
&payload,
"heimdall.auth_refresh_receipt.v1",
)
.await
}
pub async fn logout(
&self,
refresh_token: &str,
idempotency_key: &str,
) -> anyhow::Result<AuthLogoutReceipt> {
let payload = LogoutCommand {
schema: "heimdall.auth_logout_command.v1",
refresh_token,
};
self.invoke(
"heimdall.auth.logout",
"heimdall.auth_logout_command.v1",
idempotency_key,
&payload,
"heimdall.auth_logout_receipt.v1",
)
.await
}
pub async fn verify_completion(
&self,
completion: &AuthCompletionReceipt,
) -> anyhow::Result<AccessClaims> {
if completion.status != "authenticated" {
bail!("Heimdall completion is not authenticated");
}
let token = completion
.access_token
.as_deref()
.context("Heimdall omitted the access token")?;
let claims = self.verify_access(token).await?;
let account = completion
.account
.as_ref()
.context("Heimdall omitted the account")?;
let session = completion
.session
.as_ref()
.context("Heimdall omitted the session")?;
if account.id != claims.account_id
|| session.account_id != claims.account_id
|| session.session_id != claims.sid
|| session.access_revision != claims.access_revision
|| session.app_slug != APP_SLUG
{
bail!("Heimdall completion fields disagree with its signed claim");
}
Ok(claims)
}
async fn verify_access(&self, token: &str) -> anyhow::Result<AccessClaims> {
let header = decode_header(token)?;
if header.alg != Algorithm::EdDSA {
bail!("Heimdall used an unsupported signing algorithm");
}
let kid = header.kid.context("Heimdall token omitted kid")?;
let jwks: JwkSet = self
.client
.get(format!("{}/.well-known/jwks.json", self.base_url))
.http
.get(format!("{}/.well-known/jwks.json", self.issuer))
.send()
.await?
.error_for_status()?
@ -187,21 +346,252 @@ impl HeimdallClient {
let jwk = jwks
.find(&kid)
.context("Heimdall signing key was not published")?;
let key = DecodingKey::from_jwk(jwk)?;
let mut validation = Validation::new(Algorithm::EdDSA);
validation.set_audience(&[APP_SLUG]);
validation.set_issuer(&[self.base_url.as_str()]);
let claims = decode::<AccessClaims>(token, &key, &validation)?.claims;
validation.set_issuer(&[self.issuer.as_str()]);
let claims =
decode::<AccessClaims>(token, &DecodingKey::from_jwk(jwk)?, &validation)?.claims;
if claims.typ != "heimdall_access"
|| claims.aud != APP_SLUG
|| claims.iss != self.base_url
|| claims.iss != self.issuer
|| claims.sub != claims.account_id
|| claims.app.slug != APP_SLUG
|| !claims.capabilities.iter().any(|v| v == "app_access")
|| !claims
.capabilities
.iter()
.any(|value| value == "app_access")
{
bail!("Heimdall claim did not grant Ghostlight app_access");
}
Ok(claims)
}
async fn invoke<T: DeserializeOwned>(
&self,
operation: &str,
content_schema: &str,
idempotency_key: &str,
payload: &impl Serialize,
expected_schema: &str,
) -> anyhow::Result<T> {
let envelope = seal_envelope(
operation,
content_schema,
idempotency_key,
&self.shared_secret,
payload,
)?;
let endpoint = self.private_endpoint;
let runtime_id = self.runtime_id.clone();
let operation = operation.to_owned();
let request_payload = STANDARD.encode(rmp_serde::to_vec_named(&envelope)?);
let transport_operation = operation.clone();
let response = tokio::task::spawn_blocking(move || {
invoke_operation(endpoint, &runtime_id, &transport_operation, request_payload)
})
.await??;
let CultNetMessage::OperationResponse {
status,
payload_schema,
payload_encoding,
payload,
diagnostics,
..
} = response
else {
bail!("Heimdall returned a non-operation response");
};
if status == "denied" {
bail!(
"Heimdall denied the private command: {}",
diagnostics.join("; ")
);
}
if payload_schema != PRIVATE_ENVELOPE_SCHEMA || payload_encoding != "messagepack-base64" {
bail!("Heimdall returned the wrong private response contract");
}
let sealed: PrivateEnvelope = rmp_serde::from_slice(&STANDARD.decode(payload)?)?;
if sealed.operation != operation || sealed.content_schema != expected_schema {
bail!("Heimdall private response disagrees with the requested operation");
}
open_envelope(&sealed, &self.shared_secret)
}
}
fn invoke_operation(
endpoint: SocketAddr,
runtime_id: &str,
operation: &str,
payload: String,
) -> anyhow::Result<CultNetMessage> {
let socket = UdpSocket::bind("127.0.0.1:0")?;
socket.set_read_timeout(Some(Duration::from_millis(25)))?;
let mut options = CultNetRudpSocketTransportOptions::client(
runtime_id.to_owned(),
socket,
endpoint,
CULTNET_OPERATION_CONNECTION_ID,
);
options.max_fragment_bytes = Some(2_048);
let mut transport = CultNetRudpSocketTransportConnection::new(options)?;
transport.connect(Vec::new())?;
let deadline = Instant::now() + Duration::from_secs(10);
while !transport.connected() && Instant::now() < deadline {
let _ = transport.receive_once()?;
transport.poll_resends()?;
}
if !transport.connected() {
bail!("Heimdall private 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: PRIVATE_SERVICE.into(),
operation: operation.into(),
payload_schema: PRIVATE_ENVELOPE_SCHEMA.into(),
payload_encoding: "messagepack-base64".into(),
payload,
source_runtime_id: Some(runtime_id.into()),
target_runtime_id: Some("yggdrasil-heimdall".into()),
})?;
while Instant::now() < deadline {
if let Some(response) = transport.receive_schema_message_once()? {
if matches!(&response, CultNetMessage::OperationResponse { message_id: value, .. } if value == &message_id)
{
return Ok(response);
}
}
transport.poll_resends()?;
}
bail!("Heimdall private command timed out")
}
fn seal_envelope(
operation: &str,
content_schema: &str,
idempotency_key: &str,
secret: &str,
payload: &impl Serialize,
) -> anyhow::Result<PrivateEnvelope> {
let issued = Utc::now();
let expires = issued + chrono::Duration::seconds(30);
let mut nonce_bytes = [0_u8; 16];
let mut iv = [0_u8; 12];
rand::rng().fill_bytes(&mut nonce_bytes);
rand::rng().fill_bytes(&mut iv);
let mut envelope = PrivateEnvelope {
schema: PRIVATE_ENVELOPE_SCHEMA.into(),
app_slug: APP_SLUG.into(),
operation: operation.into(),
content_schema: content_schema.into(),
issued_at: issued.to_rfc3339_opts(SecondsFormat::Millis, true),
expires_at: expires.to_rfc3339_opts(SecondsFormat::Millis, true),
nonce: URL_SAFE_NO_PAD.encode(nonce_bytes),
idempotency_key: idempotency_key.into(),
iv: URL_SAFE_NO_PAD.encode(iv),
ciphertext: String::new(),
auth_tag: String::new(),
signature: String::new(),
};
let key = Sha256::digest(
[
b"heimdall.private-command.v1\0".as_slice(),
secret.as_bytes(),
]
.concat(),
);
let ciphertext_and_tag = Aes256Gcm::new_from_slice(&key)?
.encrypt(
(&iv).into(),
Payload {
msg: &rmp_serde::to_vec_named(payload)?,
aad: envelope.aad().as_bytes(),
},
)
.map_err(|_| anyhow::anyhow!("failed to encrypt Heimdall private command"))?;
let split = ciphertext_and_tag
.len()
.checked_sub(16)
.context("AES-GCM output omitted its tag")?;
envelope.ciphertext = URL_SAFE_NO_PAD.encode(&ciphertext_and_tag[..split]);
envelope.auth_tag = URL_SAFE_NO_PAD.encode(&ciphertext_and_tag[split..]);
envelope.signature = sign(&envelope, secret)?;
Ok(envelope)
}
fn open_envelope<T: DeserializeOwned>(
envelope: &PrivateEnvelope,
secret: &str,
) -> anyhow::Result<T> {
if envelope.schema != PRIVATE_ENVELOPE_SCHEMA {
bail!("unsupported Heimdall private envelope");
}
let now = Utc::now();
let issued: DateTime<Utc> = envelope.issued_at.parse()?;
let expires: DateTime<Utc> = envelope.expires_at.parse()?;
if issued > now + chrono::Duration::seconds(30)
|| expires <= now
|| expires <= issued
|| expires - issued > chrono::Duration::seconds(120)
{
bail!("Heimdall private response is outside its accepted clock window");
}
let mut mac = <Hmac<Sha256> as Mac>::new_from_slice(secret.as_bytes())?;
mac.update(envelope.authenticated_fields().as_bytes());
mac.verify_slice(&URL_SAFE_NO_PAD.decode(&envelope.signature)?)
.map_err(|_| anyhow::anyhow!("Heimdall private response signature is invalid"))?;
let key = Sha256::digest(
[
b"heimdall.private-command.v1\0".as_slice(),
secret.as_bytes(),
]
.concat(),
);
let iv = URL_SAFE_NO_PAD.decode(&envelope.iv)?;
let mut ciphertext = URL_SAFE_NO_PAD.decode(&envelope.ciphertext)?;
ciphertext.extend(URL_SAFE_NO_PAD.decode(&envelope.auth_tag)?);
let plaintext = Aes256Gcm::new_from_slice(&key)?
.decrypt(
iv.as_slice().into(),
Payload {
msg: &ciphertext,
aad: envelope.aad().as_bytes(),
},
)
.map_err(|_| anyhow::anyhow!("failed to decrypt Heimdall private response"))?;
Ok(rmp_serde::from_slice(&plaintext)?)
}
fn sign(envelope: &PrivateEnvelope, secret: &str) -> anyhow::Result<String> {
let mut mac = <Hmac<Sha256> as Mac>::new_from_slice(secret.as_bytes())?;
mac.update(envelope.authenticated_fields().as_bytes());
Ok(URL_SAFE_NO_PAD.encode(mac.finalize().into_bytes()))
}
impl PrivateEnvelope {
fn aad(&self) -> String {
[
self.schema.as_str(),
self.app_slug.as_str(),
self.operation.as_str(),
self.content_schema.as_str(),
self.issued_at.as_str(),
self.expires_at.as_str(),
self.nonce.as_str(),
self.idempotency_key.as_str(),
]
.join("\n")
}
fn authenticated_fields(&self) -> String {
[
self.aad(),
self.iv.clone(),
self.ciphertext.clone(),
self.auth_tag.clone(),
]
.join("\n")
}
}
fn required_env(name: &str) -> anyhow::Result<String> {

File diff suppressed because it is too large Load diff

View file

@ -37,6 +37,9 @@ use std::{
};
pub const PROVIDER_ID: &str = "gamecult.ghostlight.dungeon";
pub const SURFACE_ID: &str = "ghostlight.play";
pub const COMMAND_BOUNDARY: &str = "ghostlight.eve.commands";
pub const COMMAND_RESULT_SCHEMA: &str = "gamecult.eve.command_result.v1";
pub const HEALTH_KEY: &str = "ghostlight:dungeon:health";
pub const ADVERTISEMENT_KEY: &str = "eve:provider:gamecult.ghostlight.dungeon";
@ -188,6 +191,59 @@ impl MeshPublisher {
})
}
pub fn identity(&self) -> &MeshRuntimeIdentity {
&self.identity
}
pub fn provider_advertisement(&self, updated_at: &str) -> Value {
json!({
"schema":"gamecult.eve.provider_advertisement.v1",
"providerId":PROVIDER_ID,
"serviceId":self.identity.service_id.as_str(),
"verseId":"gamecult.private",
"rootVerse":"gamecult",
"canonicalService":"ghostlight-dungeon",
"locatedService":self.identity.located_service.as_str(),
"cultMeshAddress":"cultmesh://gamecult.private/ghostlight/providers/dungeon",
"title":"Ghostlight Dungeon",
"kind":"narrative.simulation",
"updatedAtUtc":updated_at,
"freshness":{"state":"live","lastSeenAtUtc":updated_at,"maxAgeMs":360000},
"schemas":[
"gamecult.eve.surface.v1",
"gamecult.eve.command_invocation.v1",
COMMAND_RESULT_SCHEMA,
"gamecult.eve.command_receipt.v1",
"heimdall.access_gate_state.v1"
],
"witnesses":[{"kind":"source-commit","ref":option_env!("GHOSTLIGHT_BUILD_COMMIT").unwrap_or("development")}],
"surfaces":[{
"surfaceId":SURFACE_ID,
"schema":"gamecult.eve.surface.v1",
"url":"/api/eve/surfaces/ghostlight.play",
"transport":"https-json",
"status":"available",
"surfaceKind":"subject-scoped-narrative",
"interactionModel":"typed-command-receipts",
"worldInteraction":{
"projectionKind":"actor-filtered-authoritative",
"stateSchemas":["ghostlight.session_zero.v1","ghostlight.campaign.v1"],
"commandBoundary":COMMAND_BOUNDARY,
"receiptSchema":COMMAND_RESULT_SCHEMA,
"loweringTargets":["browser","eve-native","tui"],
"ownership":"Ghostlight kernels own state; Eve lowers projections and commands."
},
"requiresPlugins":[{
"pluginId":"gamecult.heimdall.access",
"versionRange":"^1.0.0",
"availability":"required",
"requiredCapabilities":["auth.gate","auth.begin","auth.complete","auth.logout"]
}]
}],
"commands":[{"command":COMMAND_BOUNDARY,"transport":"https-json","summary":"Canonical Ghostlight Eve command boundary."}]
})
}
pub fn publish_snapshot(
&self,
campaigns: &[CampaignMeshSnapshot],
@ -207,111 +263,13 @@ impl MeshPublisher {
"runtime":self.identity.runtime_id.as_str(),
"commit":option_env!("GHOSTLIGHT_BUILD_COMMIT").unwrap_or("development")
});
let schema_ids = vec![
"gamecult.eve.surface.v1",
"gamecult.eve.surface_state.v1",
"gamecult.eve.provider_advertisement.v1",
"ghostlight.service_health.v1",
"ghostlight.schema_catalog.v1",
"ghostlight.campaign.v1",
"ghostlight.player_action_assessment.v1",
"ghostlight.roll_receipt.v1",
"ghostlight.world_commit_receipt.v1",
"ghostlight.persona_stage_receipt.v1",
"ghostlight.actor_state_delta.v1",
"ghostlight.world_action_proposal.v1",
"ghostlight.strategic_tick.v1",
"ghostlight.gestalt_migration.v1",
"ghostlight.member_migration.v1",
"ghostlight.news_issue.v1",
"ghostlight.canon_candidate.v1",
"ghostlight.session_zero.v1",
"ghostlight.session_zero_member.v1",
"ghostlight.session_zero_message.v1",
"ghostlight.session_zero_channel.v1",
"ghostlight.campaign_contract.v1",
"ghostlight.character_draft.v1",
"ghostlight.content_boundary.v1",
"ghostlight.active_contract_boundary_policy.v1",
"ghostlight.session_zero_decision.v1",
"ghostlight.session_zero_delta.v1",
"ghostlight.session_zero_approval.v1",
"ghostlight.approved_campaign_brief.v1",
"ghostlight.campaign_dm_persona.v1",
"ghostlight.campaign_membership.v1",
"ghostlight.campaign_governance.v1",
"ghostlight.extraordinary_permission.v1",
"ghostlight.time_advance_proposal.v1",
"ghostlight.group_travel_proposal.v1",
"ghostlight.cell_budget_proposal.v1",
];
let catalog = json!({
"schema":"ghostlight.schema_catalog.v1",
"providerId":PROVIDER_ID,
"schemas":schema_catalog(),
"updatedAtUtc":updated_at
});
let mut surfaces = campaigns
.iter()
.flat_map(|snapshot| {
let campaign = &snapshot.campaign;
let mut values = snapshot.membership.as_ref().map_or_else(
|| vec![json!({
"schema":"gamecult.eve.surface.v1",
"surfaceId":format!("ghostlight.campaign.{}",campaign.id),
"key":format!("eve:surface:ghostlight.campaign.{}",campaign.id),
"transport":"cultmesh-record","status":"available",
"audience":"legacy-owner","mode":"interactive",
"surfaceKind":"interactive-world","interactionModel":"provider-command-receipts"
})],
|membership| membership.members.values().filter(|member|member.active).map(|member|json!({
"schema":"gamecult.eve.surface.v1",
"surfaceId":format!("ghostlight.campaign.{}.{}",campaign.id,member.member_id),
"key":format!("eve:surface:ghostlight.campaign.{}.{}",campaign.id,member.member_id),
"transport":"cultmesh-record","status":"available",
"audience":member.member_id,"mode":"interactive",
"surfaceKind":"actor-filtered-interactive-world","interactionModel":"provider-command-receipts"
})).collect()
);
values.push(json!({
"schema":"gamecult.eve.surface.v1",
"surfaceId":format!("ghostlight.operator.{}",campaign.id),
"key":format!("eve:operator:ghostlight.campaign.{}",campaign.id),
"transport":"cultmesh-record",
"status":"available",
"audience":"authenticated-operator",
"mode":"inspect",
"surfaceKind":"operator-inspector",
"interactionModel":"read-only-receipt-inspection"
}));
values
})
.collect::<Vec<_>>();
surfaces.extend(session_zeros.iter().map(|snapshot| json!({
"schema":"gamecult.eve.surface.v1",
"surfaceId":format!("ghostlight.session-zero.{}.{}",snapshot.session_zero_id,snapshot.member_id),
"key":format!("eve:surface:ghostlight.session-zero.{}.{}",snapshot.session_zero_id,snapshot.member_id),
"transport":"cultmesh-record","status":"available",
"audience":snapshot.member_id,"mode":"interactive",
"surfaceKind":"actor-filtered-session-zero","interactionModel":"provider-command-receipts"
})));
let advertisement = json!({
"schema":"gamecult.eve.provider_advertisement.v1",
"providerId":PROVIDER_ID,
"serviceId":self.identity.service_id.as_str(),
"verseId":"gamecult.private",
"rootVerse":"gamecult",
"canonicalService":"ghostlight-dungeon",
"locatedService":self.identity.located_service.as_str(),
"cultMeshAddress":"cultmesh://gamecult.private/ghostlight/providers/dungeon",
"title":"GhostlightDungeon",
"kind":"narrative.simulation",
"updatedAtUtc":updated_at,
"freshness":{"state":"live","lastSeenAtUtc":updated_at,"maxAgeMs":360000},
"schemas":schema_ids,
"surfaces":surfaces,
"commands":[{"command":"ghostlight.world.commands","schema":"gamecult.eve.command.v1","transport":"cultmesh","summary":"Revision-bound world command intents; WorldKernel owns receipts."}]
});
let advertisement = self.provider_advertisement(&updated_at);
let mut node = self
.node
@ -736,4 +694,40 @@ mod tests {
.is_ok()
);
}
#[test]
fn public_provider_advertises_one_subject_scoped_surface_and_heimdall_plugin() {
let temp = tempdir().unwrap();
let publisher = MeshPublisher::open_with_identity(
temp.path().join("mesh.cc"),
None,
MeshRuntimeIdentity {
runtime_id: "ghostlight-test".into(),
service_id: "ghostlight-test".into(),
located_service: "fixture".into(),
},
)
.unwrap();
let advertisement = publisher.provider_advertisement("2026-08-22T00:00:00Z");
let surfaces = advertisement["surfaces"].as_array().unwrap();
assert_eq!(surfaces.len(), 1);
assert_eq!(surfaces[0]["surfaceId"], SURFACE_ID);
assert_eq!(
surfaces[0]["worldInteraction"]["commandBoundary"],
COMMAND_BOUNDARY
);
assert_eq!(
surfaces[0]["worldInteraction"]["receiptSchema"],
COMMAND_RESULT_SCHEMA
);
assert_eq!(
surfaces[0]["requiresPlugins"][0]["pluginId"],
"gamecult.heimdall.access"
);
assert!(
advertisement.to_string().find("account_hash").is_none(),
"public advertisement must remain subject-agnostic"
);
}
}

View file

@ -1481,13 +1481,180 @@ pub fn session_zero_surface(
character.obligations.join(", "),
character.vulnerabilities.join(", ")
);
let shared_channel_id = state
.channels
.values()
.find(|channel| channel.kind == SessionZeroChannelKind::SharedTable)
.map(|channel| channel.id.clone())
.ok_or_else(|| anyhow!("shared Session Zero channel is missing"))?;
let private_channel_id = state
.channels
.values()
.find(|channel| channel.member_id.as_deref() == Some(member.id.as_str()))
.map(|channel| channel.id.clone());
let transcript = channels
.iter()
.flat_map(|channel| {
let channel_label = if channel["kind"] == "shared_table" { "Table" } else { "Private DM" };
channel["messages"].as_array().into_iter().flatten().filter_map(move |message| {
Some(serde_json::json!({
"id":format!("session-zero.message.{}", message["id"].as_str()?),
"kind":"text.dialogue",
"props":{"value":format!("{channel_label} · {}: {}", message["speaker"].as_str().unwrap_or("system"), message["text"].as_str().unwrap_or(""))},
"children":[]
}))
})
})
.collect::<Vec<_>>();
let mut children = vec![
serde_json::json!({"id":"session-zero.status","kind":"card","props":{"title":format!("{} · revision {}", session_status_label(&state.status), state.revision)},"children":[]}),
serde_json::json!({"id":"session-zero.roster","kind":"card","props":{"title":format!("Roster · {} pooled cells",state.pooled_cell_allowance())},"children":[{"id":"session-zero.roster.text","kind":"text","props":{"value":roster_summary},"children":[]}]}),
serde_json::json!({"id":"session-zero.contract","kind":"card","props":{"title":"Campaign contract"},"children":[{"id":"session-zero.contract.text","kind":"text","props":{"value":contract_summary},"children":[]}]}),
serde_json::json!({"id":"session-zero.character","kind":"card","props":{"title":"Your private character"},"children":[{"id":"session-zero.character.text","kind":"text","props":{"value":character_summary},"children":[]}]}),
serde_json::json!({"id":"session-zero.conversation","kind":"card","props":{"title":"Session Zero conversation"},"children":transcript}),
serde_json::json!({
"id":"session-zero.channel","kind":"control.select","props":{"label":"Speak at","value":shared_channel_id},
"stateBindings":[local_draft_binding("channel_id", "choice")],
"children":[
{"id":"channel.shared","kind":"control.option","props":{"value":shared_channel_id,"label":"Shared table"},"children":[]},
{"id":"channel.private","kind":"control.option","props":{"value":private_channel_id.clone().unwrap_or_default(),"label":"Private DM","disabled":private_channel_id.is_none()},"children":[]}
]
}),
serde_json::json!({
"id":"session-zero.message.draft","kind":"control.input.textarea","props":{"label":"Tell the DM or table","rows":4,"placeholder":"Describe what you want, ask a question, or counter a proposal."},
"stateBindings":[local_draft_binding("text", "string")],"children":[]
}),
command_control(
"session-zero.message.send",
"Send",
"session_zero.message.send",
serde_json::json!({"expected_revision":state.revision}),
&["channel_id", "text"],
),
serde_json::json!({"id":"session-zero.boundary.topic","kind":"control.input.text","props":{"label":"Private boundary topic","placeholder":"What should the campaign avoid, veil, or ask about first?"},"stateBindings":[local_draft_binding("topic", "string")],"children":[]}),
serde_json::json!({"id":"session-zero.boundary.level","kind":"control.select","props":{"label":"Boundary level","value":"ask_first"},"stateBindings":[local_draft_binding("level", "choice")],"children":[
{"id":"boundary.ask-first","kind":"control.option","props":{"value":"ask_first","label":"Ask first"},"children":[]},
{"id":"boundary.veil","kind":"control.option","props":{"value":"veil","label":"Veil"},"children":[]},
{"id":"boundary.line","kind":"control.option","props":{"value":"line","label":"Line"},"children":[]}
]}),
command_control(
"session-zero.boundary.set",
"Add private boundary",
"session_zero.boundary.set",
serde_json::json!({"expected_revision":state.revision}),
&["topic", "level"],
),
serde_json::json!({"id":"session-zero.decision.counter","kind":"control.input.textarea","props":{"label":"Counterproposal","rows":3,"placeholder":"State the replacement you want the table or DM to consider."},"stateBindings":[local_draft_binding("counter", "string")],"children":[]}),
];
for boundary in &private_boundaries {
children.push(serde_json::json!({
"id":format!("session-zero.boundary.{}",boundary.id),
"kind":"card",
"props":{"title":format!("Your boundary · {:?}",boundary.level)},
"children":[
{"id":format!("session-zero.boundary.{}.topic",boundary.id),"kind":"text","props":{"value":boundary.topic},"children":[]},
command_control(&format!("session-zero.boundary.{}.remove",boundary.id), "Remove boundary", "session_zero.boundary.remove", serde_json::json!({"expected_revision":state.revision,"target":boundary.id}), &[])
]
}));
}
for decision in visible_decisions
.iter()
.filter(|decision| !decision.resolved)
{
children.push(serde_json::json!({
"id":format!("session-zero.decision.{}",decision.id),"kind":"card","props":{"title":decision.prompt},"children":[
{"id":format!("session-zero.decision.{}.proposal",decision.id),"kind":"text","props":{"value":decision.proposed_resolution},"children":[]},
command_control(&format!("session-zero.decision.{}.accept",decision.id), "Accept", "session_zero.decision.resolve", serde_json::json!({"expected_revision":state.revision,"decision_id":decision.id,"accept":true,"counter":null}), &[]),
command_control(&format!("session-zero.decision.{}.counter",decision.id), "Counter", "session_zero.decision.resolve", serde_json::json!({"expected_revision":state.revision,"decision_id":decision.id,"accept":false}), &["counter"]),
command_control(&format!("session-zero.decision.{}.discuss",decision.id), "Discuss", "session_zero.message.send", serde_json::json!({"expected_revision":state.revision,"text":format!("I want to discuss this proposal before deciding: {}",decision.prompt)}), &["channel_id"])
]
}));
}
if member.is_host && !state.roster_locked {
children.push(serde_json::json!({"id":"session-zero.invite-count","kind":"control.input.number","props":{"label":"Invitations","value":1,"min":1,"max":7},"stateBindings":[local_draft_binding("count", "number")],"children":[]}));
children.push(command_control(
"session-zero.invites.create",
"Create invitations",
"session_zero.invites.create",
serde_json::json!({}),
&["count"],
));
children.push(command_control(
"session-zero.roster.lock",
"Lock roster",
"session_zero.roster.lock",
serde_json::json!({"expected_revision":state.revision}),
&[],
));
for candidate in state
.members
.values()
.filter(|candidate| candidate.active && candidate.id != member.id)
{
children.push(command_control(
&format!("session-zero.member.{}.remove", candidate.id),
&format!("Remove {}", candidate.display_name),
"session_zero.member.remove",
serde_json::json!({"expected_revision":state.revision,"target":candidate.id}),
&[],
));
}
}
if !member.is_host && !state.roster_locked {
children.push(command_control(
"session-zero.leave",
"Leave Session Zero",
"session_zero.leave",
serde_json::json!({"expected_revision":state.revision}),
&[],
));
}
if member.is_host && state.roster_locked && state.status == SessionZeroStatus::RosterLocked {
children.push(command_control(
"session-zero.compile",
"Compile campaign preview",
"session_zero.compile",
serde_json::json!({"expected_revision":state.revision}),
&[],
));
}
if state.status == SessionZeroStatus::Review {
children.push(command_control(
"session-zero.approve",
if state.approvals.contains_key(&member.id) {
"Approved"
} else {
"Approve shared and private drafts"
},
"session_zero.approve",
serde_json::json!({"expected_revision":state.revision}),
&[],
));
if member.is_host && state.approved_brief().is_ok() {
children.push(command_control(
"session-zero.publish",
"Publish campaign",
"session_zero.publish",
serde_json::json!({"expected_revision":state.revision}),
&[],
));
}
}
children.push(command_control(
"ghostlight.logout",
"Sign out",
"app.auth.logout",
serde_json::json!({}),
&[],
));
Ok(serde_json::json!({
"type": "surface-state",
"schema": "gamecult.eve.surface.v1",
"providerId": "gamecult.ghostlight.dungeon.session-zero",
"providerId": "gamecult.ghostlight.dungeon",
"providerKind": "narrative.session-zero",
"title": state.name,
"version": state.revision,
"updatedAtUtc": Utc::now().to_rfc3339(),
"session_zero": {
"id": state.id,
"status": state.status,
@ -1511,17 +1678,12 @@ pub fn session_zero_surface(
"publish_ready": state.approved_brief().is_ok(),
},
"surface": {
"id": format!("ghostlight.session-zero.{}", state.id),
"id": "ghostlight.play",
"root": {
"id": "session-zero.root",
"kind": "surface",
"props": {},
"children": [
{"id":"session-zero.status","kind":"card","props":{"title":format!("{} · revision {}", session_status_label(&state.status), state.revision)},"children":[]},
{"id":"session-zero.roster","kind":"card","props":{"title":format!("Roster · {} pooled cells",state.pooled_cell_allowance())},"children":[{"id":"session-zero.roster.text","kind":"text","props":{"value":roster_summary},"children":[]}]},
{"id":"session-zero.contract","kind":"card","props":{"title":"Campaign contract"},"children":[{"id":"session-zero.contract.text","kind":"text","props":{"value":contract_summary},"children":[]}]},
{"id":"session-zero.character","kind":"card","props":{"title":"Your private character"},"children":[{"id":"session-zero.character.text","kind":"text","props":{"value":character_summary},"children":[]}]}
]
"children": children
},
"styles": {"tokens": {
"colorBackground": "#0c1110",
@ -1532,14 +1694,66 @@ pub fn session_zero_surface(
}}
},
"commands": [
{"id":"session-zero.message","schema":"gamecult.eve.command.v1"},
{"id":"session-zero.boundary","schema":"gamecult.eve.command.v1"},
{"id":"session-zero.decision","schema":"gamecult.eve.command.v1"},
{"id":"session-zero.approve","schema":"gamecult.eve.command.v1"}
eve_command("session_zero.message.send", "ghostlight.session_zero_message_send.v1", &["channel_id","text"]),
eve_command("session_zero.boundary.set", "ghostlight.session_zero_boundary_set.v1", &["topic","level"]),
eve_command("session_zero.boundary.remove", "ghostlight.session_zero_boundary_remove.v1", &[]),
eve_command("session_zero.decision.resolve", "ghostlight.session_zero_decision_resolve.v1", &[]),
eve_command("session_zero.invites.create", "ghostlight.session_zero_invites_create.v1", &["count"]),
eve_command("session_zero.leave", "ghostlight.session_zero_revision_command.v1", &[]),
eve_command("session_zero.member.remove", "ghostlight.session_zero_member_remove.v1", &[]),
eve_command("session_zero.roster.lock", "ghostlight.session_zero_revision_command.v1", &[]),
eve_command("session_zero.compile", "ghostlight.session_zero_revision_command.v1", &[]),
eve_command("session_zero.approve", "ghostlight.session_zero_revision_command.v1", &[]),
eve_command("session_zero.publish", "ghostlight.session_zero_revision_command.v1", &[]),
eve_command("app.auth.logout", "ghostlight.app_logout.v1", &[])
]
}))
}
fn local_draft_binding(name: &str, value_kind: &str) -> serde_json::Value {
serde_json::json!({
"targetProp":"value",
"pointerId":format!("draft:{name}"),
"sourceId":"renderer",
"schemaId":"gamecult.eve.local_draft.v1",
"routeKind":"local",
"bindingName":name,
"documentId":"ghostlight.play.drafts",
"fieldPath":name,
"valueKind":value_kind,
"accessMode":"local-draft",
"authority":"renderer-ephemeral"
})
}
fn command_control(
id: &str,
label: &str,
command: &str,
action: serde_json::Value,
bindings: &[&str],
) -> serde_json::Value {
let mut action = action.as_object().cloned().unwrap_or_default();
action.insert("command".into(), serde_json::Value::String(command.into()));
serde_json::json!({
"id":id,
"kind":"control.button",
"props":{"label":label,"command":command,"action":action,"captureBindings":bindings},
"children":[]
})
}
fn eve_command(command: &str, payload_schema: &str, bindings: &[&str]) -> serde_json::Value {
serde_json::json!({
"schema":"gamecult.eve.command.v1",
"command":command,
"payloadSchema":payload_schema,
"captureBindings":bindings,
"transport":"https-json",
"authority":"SessionZeroKernel"
})
}
fn session_status_label(status: &SessionZeroStatus) -> &'static str {
match status {
SessionZeroStatus::Drafting => "Drafting",
@ -2738,6 +2952,52 @@ mod tests {
assert!(!member_schema.contains("account_hash"));
}
#[test]
fn session_zero_surface_exposes_accept_counter_discuss_and_owned_boundary_controls_as_bindings()
{
let mut draft = state();
let host = draft.host_member_id.clone();
draft.boundaries.insert(
"boundary:host".into(),
ContentBoundary {
schema: "ghostlight.content_boundary.v1".into(),
id: "boundary:host".into(),
owner_member_id: host,
topic: "medical horror".into(),
normalized_topic: "medical horror".into(),
level: BoundaryLevel::Veil,
created_at: Utc::now(),
updated_at: Utc::now(),
},
);
draft.decisions.insert(
"decision:tone".into(),
SessionZeroDecision {
schema: "ghostlight.session_zero_decision.v1".into(),
id: "decision:tone".into(),
owner_member_id: None,
prompt: "How severe should consequences be?".into(),
proposed_resolution: "Consequences are durable but rarely lethal.".into(),
proposed_extraordinary_permission: None,
proposed_contract_patch: None,
proposed_character_patch: None,
evidence_receipt_ids: vec![],
material: true,
resolved: false,
},
);
let encoded =
serde_json::to_string(&session_zero_surface(&draft, "account:host").unwrap()).unwrap();
assert!(encoded.contains("Accept"));
assert!(encoded.contains("Counter"));
assert!(encoded.contains("Discuss"));
assert!(encoded.contains("session_zero.boundary.remove"));
assert!(encoded.contains("\"bindingName\":\"counter\""));
assert!(!encoded.contains("payload.fields"));
assert!(!encoded.contains("\"kind\":\"form\""));
}
#[tokio::test]
async fn independent_private_dm_outputs_commit_across_unrelated_global_revisions() {
let dir = tempdir().unwrap();

View file

@ -79,9 +79,104 @@ pub fn player_surface_for_actor(
.as_ref()
.map(|cover| cover.effective_budget)
.unwrap_or(campaign.resolution_policy.active_cell_budget);
let mut children = vec![
json!({"id":"dungeon.status","kind":"card","props":{"title":format!("{} · revision {} · {}",campaign.name,campaign.revision,campaign.world_time)},"children":[]}),
json!({"id":"dungeon.location","kind":"card","props":{"title":format!("{} · {}",location.name,player.name)},"children":[]}),
json!({"id":"dungeon.ledger","kind":"card","props":{"title":"Character ledger"},"children":[{"id":"dungeon.ledger.text","kind":"text","props":{"value":ledger},"children":[]}]}),
json!({"id":"dungeon.resolution","kind":"card","props":{"title":format!("World resolution · {} configured / {} effective",campaign.resolution_policy.active_cell_budget,effective_budget)},"children":[{"id":"dungeon.resolution.text","kind":"text","props":{"value":format!("Resolution epoch {} · {} pins · {} temporary overage",campaign.resolution_policy.resolution_epoch,campaign.resolution_pins.len(),campaign.resolution_cover.as_ref().map(|cover| cover.mandatory_overage).unwrap_or(0))},"children":[]}]}),
json!({"id":"dungeon.news","kind":"card","props":{"title":"Accessible news and rumors"},"children":news}),
json!({"id":"dungeon.transcript","kind":"card","props":{"title":"Story"},"children":story}),
json!({"id":"dungeon.speech","kind":"control.input.textarea","props":{"label":"Say something","rows":3,"placeholder":"Your character's exact words"},"stateBindings":[local_draft("text","string")],"children":[]}),
command_control(
"dungeon.speak",
"Speak",
"world.speak",
json!({"expected_revision":campaign.revision}),
&["text"],
),
json!({"id":"dungeon.attempt.description","kind":"control.input.textarea","props":{"label":"What do you try?","rows":4,"placeholder":"Describe the attempt, not a completed fact."},"stateBindings":[local_draft("description","string")],"children":[]}),
json!({"id":"dungeon.attempt.effect","kind":"control.input.text","props":{"label":"What effect do you want?","placeholder":"The concrete outcome you are trying to cause"},"stateBindings":[local_draft("intended_effect","string")],"children":[]}),
command_control(
"dungeon.assess",
"Assess stakes",
"world.assess",
json!({"expected_revision":campaign.revision}),
&["description", "intended_effect"],
),
json!({"id":"dungeon.wait.minutes","kind":"control.input.number","props":{"label":"Wait minutes","value":30,"min":1,"max":1440},"stateBindings":[local_draft("minutes","number")],"children":[]}),
command_control(
"dungeon.wait",
"Wait",
"world.wait",
json!({"expected_revision":campaign.revision}),
&["minutes"],
),
json!({"id":"dungeon.time.minutes","kind":"control.input.number","props":{"label":"Proposed group time advance (minutes)","value":30,"min":1,"max":1440},"stateBindings":[local_draft("time_advance_minutes","number")],"children":[]}),
command_control(
"dungeon.time.propose",
"Propose group time advance",
"governance.time.propose",
json!({"expected_revision":campaign.revision}),
&["time_advance_minutes"],
),
json!({"id":"dungeon.cells.budget","kind":"control.input.number","props":{"label":"Active Persona-cell budget","value":campaign.resolution_policy.active_cell_budget,"min":1,"max":128},"stateBindings":[local_draft("active_cell_budget","number")],"children":[]}),
command_control(
"dungeon.cells.propose",
"Propose cell budget",
"governance.cells.propose",
json!({"expected_revision":campaign.revision,"expected_resolution_epoch":campaign.resolution_policy.resolution_epoch}),
&["active_cell_budget"],
),
command_control(
"dungeon.contract-review",
"Review campaign contract",
"campaign.contract_review.begin",
json!({}),
&[],
),
command_control(
"dungeon.logout",
"Sign out",
"app.auth.logout",
json!({}),
&[],
),
];
if location.routes.is_empty() {
children.push(json!({"id":"dungeon.travel.none","kind":"text","props":{"value":"No compiled route leaves this location yet."},"children":[]}));
} else {
children.push(json!({
"id":"dungeon.travel.destination",
"kind":"control.select",
"props":{"label":"Group destination"},
"stateBindings":[local_draft("destination_location_id","choice")],
"children":location.routes.iter().filter_map(|(destination_id,route)|campaign.locations.get(destination_id).map(|destination|json!({
"id":format!("dungeon.travel.option.{destination_id}"),
"kind":"control.option",
"props":{"value":destination_id,"label":format!("{} · {} minutes · {}",destination.name,route.travel_minutes,route.distance)},
"children":[]
}))).collect::<Vec<_>>()
}));
children.push(command_control(
"dungeon.travel.propose",
"Propose group travel",
"governance.travel.propose",
json!({"expected_revision":campaign.revision}),
&["destination_location_id"],
));
}
children.push(json!({"id":"dungeon.destination.name","kind":"control.input.text","props":{"label":"Compile a new destination","placeholder":"Describe where you want to go"},"stateBindings":[local_draft("destination","string")],"children":[]}));
children.push(command_control(
"dungeon.destination.compile",
"Compile destination preview",
"world.destination.compile",
json!({}),
&["destination"],
));
json!({
"type":"surface-state", "schema":"gamecult.eve.surface.v1", "providerId":"gamecult.ghostlight.dungeon",
"providerKind":"narrative.simulation", "title":campaign.name, "version":interface_version,
"updatedAtUtc":chrono::Utc::now().to_rfc3339(),
"world_revision":campaign.revision,
"viewer_actor_id":viewer_actor_id,
"player_location_id":player.location_id,
@ -93,19 +188,46 @@ pub fn player_surface_for_actor(
"pin_count":campaign.resolution_pins.len(),
"fission_targets":campaign.agency_profiles.values().filter(|profile| profile.active_leaf && profile.subject_kind == crate::domain::AgencySubjectKind::Gestalt).filter_map(|profile| campaign.gestalts.get(&profile.subject_id)).filter(|gestalt|gestalt.home_location_id==player.location_id).map(|gestalt| json!({"id":gestalt.id,"name":gestalt.name})).collect::<Vec<_>>()
},
"surface":{"id":format!("ghostlight.campaign.{}",campaign.id),"root":{"id":"dungeon.root","kind":"surface","props":{},"children":[
{"id":"dungeon.status","kind":"card","props":{"title":format!("{} · revision {} · {}",campaign.name,campaign.revision,campaign.world_time)},"children":[]},
{"id":"dungeon.location","kind":"card","props":{"title":format!("{} · {}",location.name,player.name)},"children":[]},
{"id":"dungeon.ledger","kind":"card","props":{"title":"Character ledger"},"children":[{"id":"dungeon.ledger.text","kind":"text","props":{"value":ledger},"children":[]}]},
{"id":"dungeon.resolution","kind":"card","props":{"title":format!("World resolution · {} configured / {} effective",campaign.resolution_policy.active_cell_budget,effective_budget)},"children":[{"id":"dungeon.resolution.text","kind":"text","props":{"value":format!("Resolution epoch {} · {} pins · {} temporary overage",campaign.resolution_policy.resolution_epoch,campaign.resolution_pins.len(),campaign.resolution_cover.as_ref().map(|cover| cover.mandatory_overage).unwrap_or(0))},"children":[]}]},
{"id":"dungeon.news","kind":"card","props":{"title":"Accessible news and rumors"},"children":news},
{"id":"dungeon.transcript","kind":"card","props":{"title":"Story"},"children":story},
{"id":"dungeon.composer","kind":"text-input","props":{"label":"What do you attempt?","commandId":"attempt.assess"},"children":[]}
]},"styles":{"tokens":{"colorBackground":"#0c1110","colorPanel":"#17201d","colorText":"#e8e1cf","colorMuted":"#9aa69f","colorAccent":"#d49b58"}}},
"commands":[{"id":"attempt.assess","schema":"gamecult.eve.command.v1","receiptSchema":"ghostlight.player_action_assessment.v1"}]
"surface":{"id":"ghostlight.play","root":{"id":"dungeon.root","kind":"surface","props":{},"children":children},"styles":{"tokens":{"colorBackground":"#0c1110","colorPanel":"#17201d","colorText":"#e8e1cf","colorMuted":"#9aa69f","colorAccent":"#d49b58"}}},
"commands":[
eve_command("world.speak","ghostlight.world_speak.v1", &["text"], "WorldKernel"),
eve_command("world.assess","ghostlight.player_action_assess.v1", &["description","intended_effect"], "WorldKernel"),
eve_command("world.attempt","ghostlight.player_action_attempt.v1", &[], "WorldKernel"),
eve_command("world.wait","ghostlight.world_wait.v1", &["minutes"], "WorldKernel"),
eve_command("governance.cells.propose","ghostlight.cell_budget_proposal.v1", &["active_cell_budget"], "WorldKernel"),
eve_command("governance.cells.approve","ghostlight.cell_budget_approval.v1", &[], "WorldKernel"),
eve_command("governance.time.propose","ghostlight.time_advance_proposal.v1", &["time_advance_minutes"], "WorldKernel"),
eve_command("governance.time.approve","ghostlight.time_advance_approval.v1", &[], "WorldKernel"),
eve_command("governance.travel.propose","ghostlight.group_travel_proposal.v1", &["destination_location_id"], "WorldKernel"),
eve_command("governance.travel.approve","ghostlight.group_travel_approval.v1", &[], "WorldKernel"),
eve_command("world.destination.compile","ghostlight.destination_compile.v1", &["destination"], "WorldCompiler"),
eve_command("world.destination.approve","ghostlight.destination_approval.v1", &[], "WorldKernel"),
eve_command("campaign.contract_review.begin","ghostlight.contract_review_begin.v1", &[], "SessionZeroKernel"),
eve_command("app.auth.logout","ghostlight.app_logout.v1", &[], "ghostlight.app_session.v1")
]
})
}
fn local_draft(name: &str, value_kind: &str) -> Value {
json!({"targetProp":"value","pointerId":format!("draft:{name}"),"sourceId":"renderer","schemaId":"gamecult.eve.local_draft.v1","routeKind":"local","bindingName":name,"documentId":"ghostlight.play.drafts","fieldPath":name,"valueKind":value_kind,"accessMode":"local-draft","authority":"renderer-ephemeral"})
}
fn command_control(
id: &str,
label: &str,
command: &str,
action: Value,
bindings: &[&str],
) -> Value {
let mut action = action.as_object().cloned().unwrap_or_default();
action.insert("command".into(), Value::String(command.into()));
json!({"id":id,"kind":"control.button","props":{"label":label,"command":command,"action":action,"captureBindings":bindings},"children":[]})
}
fn eve_command(command: &str, payload_schema: &str, bindings: &[&str], authority: &str) -> Value {
json!({"schema":"gamecult.eve.command.v1","command":command,"payloadSchema":payload_schema,"captureBindings":bindings,"transport":"https-json","authority":authority})
}
fn story_nodes(campaign: &Campaign, narrations: &[NarrationProjection]) -> Vec<Value> {
let narrated_revisions = narrations
.iter()
@ -434,4 +556,40 @@ mod tests {
assert!(encoded.contains("Local neighbors"));
assert!(!encoded.contains("SECRET_REMOTE_POPULATION"));
}
#[test]
fn player_surface_uses_bound_eve_controls_for_time_travel_and_destination_compilation() {
let mut campaign = crate::resolution::tests::campaign(1, 1);
campaign.locations.insert(
"harbor".into(),
crate::domain::Location {
id: "harbor".into(),
name: "Harbor".into(),
container_id: None,
routes: Default::default(),
persistent_features: vec![],
},
);
campaign.locations.get_mut("center").unwrap().routes.insert(
"harbor".into(),
crate::domain::Route {
destination_id: "harbor".into(),
distance: "nearby".into(),
travel_minutes: 20,
},
);
let encoded = serde_json::to_string(&player_surface(&campaign, &[])).unwrap();
for binding in [
"time_advance_minutes",
"destination_location_id",
"destination",
] {
assert!(encoded.contains(&format!("\"bindingName\":\"{binding}\"")));
}
assert!(encoded.contains("governance.travel.propose"));
assert!(encoded.contains("world.destination.compile"));
assert!(!encoded.contains("payload.fields"));
assert!(!encoded.contains("\"kind\":\"form\""));
}
}