Protect GhostlightDungeon runtime credentials

This commit is contained in:
Meta Vens 2026-08-16 16:46:04 +02:00
commit 74177ac733
9 changed files with 220 additions and 20 deletions

109
Cargo.lock generated
View file

@ -190,7 +190,7 @@ dependencies = [
"num-traits",
"serde",
"wasm-bindgen",
"windows-link",
"windows-link 0.2.1",
]
[[package]]
@ -455,6 +455,8 @@ dependencies = [
"tracing",
"tracing-subscriber",
"uuid",
"windows",
"zeroize",
]
[[package]]
@ -580,7 +582,7 @@ dependencies = [
"js-sys",
"log",
"wasm-bindgen",
"windows-core",
"windows-core 0.62.2",
]
[[package]]
@ -856,7 +858,7 @@ dependencies = [
"libc",
"redox_syscall",
"smallvec",
"windows-link",
"windows-link 0.2.1",
]
[[package]]
@ -1908,6 +1910,41 @@ version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f"
[[package]]
name = "windows"
version = "0.61.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9babd3a767a4c1aef6900409f85f5d53ce2544ccdfaa86dad48c91782c6d6893"
dependencies = [
"windows-collections",
"windows-core 0.61.2",
"windows-future",
"windows-link 0.1.3",
"windows-numerics",
]
[[package]]
name = "windows-collections"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3beeceb5e5cfd9eb1d76b381630e82c4241ccd0d27f1a39ed41b2760b255c5e8"
dependencies = [
"windows-core 0.61.2",
]
[[package]]
name = "windows-core"
version = "0.61.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c0fdd3ddb90610c7638aa2b3a3ab2904fb9e5cdbecc643ddb3647212781c4ae3"
dependencies = [
"windows-implement",
"windows-interface",
"windows-link 0.1.3",
"windows-result 0.3.4",
"windows-strings 0.4.2",
]
[[package]]
name = "windows-core"
version = "0.62.2"
@ -1916,9 +1953,20 @@ checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb"
dependencies = [
"windows-implement",
"windows-interface",
"windows-link",
"windows-result",
"windows-strings",
"windows-link 0.2.1",
"windows-result 0.4.1",
"windows-strings 0.5.1",
]
[[package]]
name = "windows-future"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fc6a41e98427b19fe4b73c550f060b59fa592d7d686537eebf9385621bfbad8e"
dependencies = [
"windows-core 0.61.2",
"windows-link 0.1.3",
"windows-threading",
]
[[package]]
@ -1943,19 +1991,53 @@ dependencies = [
"syn 2.0.119",
]
[[package]]
name = "windows-link"
version = "0.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5e6ad25900d524eaabdbbb96d20b4311e1e7ae1699af4fb28c17ae66c80d798a"
[[package]]
name = "windows-link"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"
[[package]]
name = "windows-numerics"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9150af68066c4c5c07ddc0ce30421554771e528bde427614c61038bc2c92c2b1"
dependencies = [
"windows-core 0.61.2",
"windows-link 0.1.3",
]
[[package]]
name = "windows-result"
version = "0.3.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "56f42bd332cc6c8eac5af113fc0c1fd6a8fd2aa08a0119358686e5160d0586c6"
dependencies = [
"windows-link 0.1.3",
]
[[package]]
name = "windows-result"
version = "0.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5"
dependencies = [
"windows-link",
"windows-link 0.2.1",
]
[[package]]
name = "windows-strings"
version = "0.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "56e6c93f3a0c3b36176cb1327a4958a0353d5d166c2a35cb268ace15e91d3b57"
dependencies = [
"windows-link 0.1.3",
]
[[package]]
@ -1964,7 +2046,7 @@ version = "0.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091"
dependencies = [
"windows-link",
"windows-link 0.2.1",
]
[[package]]
@ -1991,7 +2073,7 @@ version = "0.61.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc"
dependencies = [
"windows-link",
"windows-link 0.2.1",
]
[[package]]
@ -2010,6 +2092,15 @@ dependencies = [
"windows_x86_64_msvc",
]
[[package]]
name = "windows-threading"
version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b66463ad2e0ea3bbf808b7f1d371311c80e115c0b71d60efc142cafbcfb057a6"
dependencies = [
"windows-link 0.1.3",
]
[[package]]
name = "windows_aarch64_gnullvm"
version = "0.52.6"

View file

@ -26,4 +26,5 @@ tower-http = { version = "0.6", features = ["fs", "trace"] }
tracing = "0.1"
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
uuid = { version = "1", features = ["v4", "serde"] }
windows = { version = "0.61", features = ["Win32_Foundation", "Win32_Security_Cryptography"] }
zeroize = "1.8"

View file

@ -23,7 +23,8 @@ tower-http.workspace = true
tracing.workspace = true
tracing-subscriber.workspace = true
uuid.workspace = true
windows.workspace = true
zeroize.workspace = true
[dev-dependencies]
tempfile = "3"

View file

@ -6,5 +6,7 @@ pub mod persistence;
pub mod persona;
pub mod surface;
pub mod vault;
#[cfg(windows)]
pub mod windows_secret;
pub use kernel::{KernelError, WorldKernel};

View file

@ -5,9 +5,12 @@ use axum::{
response::{IntoResponse, Redirect, Response},
routing::{get, post},
};
#[cfg(windows)]
use ghostlight_dungeon::windows_secret::unprotect_machine_utf8;
use ghostlight_dungeon::{
WorldKernel,
domain::{Campaign, WorldCommand},
model::{DeepSeekPort, ModelStageRequest, run_validated_stage},
persistence::CampaignStore,
surface::player_surface,
};
@ -28,6 +31,7 @@ struct AppState {
store: CampaignStore,
invites: Arc<Mutex<BTreeSet<String>>>,
sessions: Arc<Mutex<BTreeSet<String>>>,
deepseek_status: String,
}
#[tokio::main]
@ -48,20 +52,63 @@ async fn main() -> anyhow::Result<()> {
})
.await?;
}
let invite_tokens = std::env::var("GHOSTLIGHT_INVITES")
.unwrap_or_else(|_| "tester-one,tester-two".into())
let invite_blob = runtime_root.join("secrets/invites.dpapi");
#[cfg(windows)]
let invite_material = if invite_blob.is_file() {
unprotect_machine_utf8(&invite_blob)?
} else {
std::env::var("GHOSTLIGHT_INVITES").map_err(|_| {
anyhow::anyhow!(
"protected invite blob is missing; run the privileged GhostlightDungeon setup"
)
})?
};
#[cfg(not(windows))]
let invite_material = std::env::var("GHOSTLIGHT_INVITES")
.map_err(|_| anyhow::anyhow!("GHOSTLIGHT_INVITES is required outside Windows"))?;
let invite_tokens: BTreeSet<String> = invite_material
.split(',')
.map(str::trim)
.filter(|s| !s.is_empty())
.map(str::to_owned)
.collect();
if invite_tokens.len() != 2 {
return Err(anyhow::anyhow!(
"GhostlightDungeon requires exactly two unused invite tokens"
));
}
let secret_path = runtime_root.join("secrets/deepseek.dpapi");
let deepseek_status = if secret_path.is_file() {
let provider = DeepSeekPort::from_machine_dpapi(&secret_path)?;
let probe = run_validated_stage(
&provider,
&ModelStageRequest {
stage: "startup_probe".into(),
model: "deepseek-v4-flash".into(),
snapshot_binding: "service-startup".into(),
lived_stream: "Reply with the single word ready.".into(),
output_schema: None,
source_receipt_ids: vec![],
},
)
.await?;
format!("ready:{}", probe.receipt.output_hash)
} else {
"missing-secret".into()
};
let state = AppState {
kernel,
store,
invites: Arc::new(Mutex::new(invite_tokens)),
sessions: Arc::new(Mutex::new(BTreeSet::new())),
deepseek_status,
};
let web_root = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../web/dist");
let release_web_root = std::env::current_exe()?
.parent()
.map(|parent| parent.join("web"));
let web_root = release_web_root
.filter(|path| path.join("index.html").is_file())
.unwrap_or_else(|| PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../web/dist"));
let app = Router::new()
.route("/health", get(health))
.route("/invite/{token}", get(invite))
@ -78,7 +125,7 @@ async fn main() -> anyhow::Result<()> {
async fn health(State(state): State<AppState>) -> Json<serde_json::Value> {
Json(
serde_json::json!({"schema":"ghostlight.service_health.v1","status":"ok","storeIdentity":state.store.identity()}),
serde_json::json!({"schema":"ghostlight.service_health.v1","status":"ok","storeIdentity":state.store.identity(),"deepseek":state.deepseek_status}),
)
}

View file

@ -3,6 +3,7 @@ use async_trait::async_trait;
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use std::time::Instant;
use zeroize::Zeroizing;
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
pub struct ModelStageRequest {
@ -99,20 +100,26 @@ impl ModelPort for FixtureModel {
}
}
#[derive(Clone)]
pub struct DeepSeekPort {
client: reqwest::Client,
api_key: String,
api_key: Zeroizing<String>,
endpoint: String,
}
impl DeepSeekPort {
pub fn new(api_key: String) -> Self {
Self {
client: reqwest::Client::new(),
api_key,
api_key: Zeroizing::new(api_key),
endpoint: "https://api.deepseek.com/chat/completions".into(),
}
}
#[cfg(windows)]
pub fn from_machine_dpapi(path: impl AsRef<std::path::Path>) -> Result<Self> {
Ok(Self::new(crate::windows_secret::unprotect_machine_utf8(
path,
)?))
}
}
#[async_trait]
impl ModelPort for DeepSeekPort {
@ -124,7 +131,7 @@ impl ModelPort for DeepSeekPort {
let value: serde_json::Value = self
.client
.post(&self.endpoint)
.bearer_auth(&self.api_key)
.bearer_auth(self.api_key.as_str())
.json(&body)
.send()
.await?

View file

@ -0,0 +1,49 @@
use anyhow::{Context, Result, anyhow};
use std::{fs, path::Path, slice};
use windows::Win32::{
Foundation::{HLOCAL, LocalFree},
Security::Cryptography::{CRYPT_INTEGER_BLOB, CryptUnprotectData},
};
use zeroize::Zeroizing;
/// Decrypts a machine-scoped DPAPI blob. DPAPI authenticates the blob and
/// Windows owns the returned allocation; the plaintext is copied once into a
/// zeroizing UTF-8 buffer and the Windows allocation is immediately released.
pub fn unprotect_machine_utf8(path: impl AsRef<Path>) -> Result<String> {
let mut protected = fs::read(path.as_ref())
.with_context(|| format!("read DPAPI secret {}", path.as_ref().display()))?;
if protected.is_empty() {
return Err(anyhow!("DPAPI secret blob is empty"));
}
let input = CRYPT_INTEGER_BLOB {
cbData: u32::try_from(protected.len()).context("DPAPI blob is too large")?,
pbData: protected.as_mut_ptr(),
};
let mut output = CRYPT_INTEGER_BLOB::default();
unsafe {
CryptUnprotectData(&input, None, None, None, None, 0, &mut output)
.context("CryptUnprotectData failed")?;
}
if output.pbData.is_null() || output.cbData == 0 {
return Err(anyhow!("DPAPI returned no plaintext"));
}
let plaintext = unsafe { slice::from_raw_parts(output.pbData, output.cbData as usize) };
let zeroizing = Zeroizing::new(plaintext.to_vec());
unsafe {
let _ = LocalFree(Some(HLOCAL(output.pbData.cast())));
}
let value = String::from_utf8(zeroizing.to_vec()).context("DPAPI secret is not UTF-8")?;
if value.trim().is_empty() {
return Err(anyhow!("DPAPI secret plaintext is empty"));
}
Ok(value)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn rejects_absent_blob_without_secret_material() {
assert!(unprotect_machine_utf8("definitely-absent.dpapi").is_err());
}
}

View file

@ -67,4 +67,5 @@
{"note": "CultCache wire contract clarified: DatabaseEntry payloads must be MessagePack arrays indexed by explicit field keys with nil gaps for reserved/deleted slots; cultcache-py now exposes define_database_entry_type for that contract and CultLib generator was patched to preserve sparse key slots.", "status": "accepted", "ts": "2026-05-06T03:57:10+00:00", "type": "architecture"}
{"note": "Ghostlight agent-state schema is now the first shared cross-runtime payload contract. CultNet clients should carry ghostlight.agent_state.v0 unchanged inside typed document envelopes, with CultLib-style auth/session semantics handled by the transport layer rather than bespoke per-repo glue.", "status": "accepted", "ts": "2026-05-06T04:49:20+00:00", "type": "architecture"}
{"note": "GhostlightDungeon ownership map accepted: Ghostlight owns generalized Projector-Persona-Interpreter machinery; consuming Personas such as Epiphany retain canonical mind and commit authority through narrow adapters. WorldKernel is the sole campaign writer.", "status": "accepted", "ts": "2026-08-16T14:26:32+00:00", "type": "architecture"}
{"ts": "2026-08-16T14:28:19+00:00", "type": "architecture", "status": "accepted", "note": "Epiphany extraction map grounded in persona_turn.rs, persona_executor.rs, persona-service, conversation, and Discord crossing: shared orchestration moves to Ghostlight; Epiphany Mind/state/mouth stay; narrow slicer, transport, receipt, schema, and permit ports split; strict v1 removes second-channel state from Persona turn."}
{"note": "Epiphany extraction map grounded in persona_turn.rs, persona_executor.rs, persona-service, conversation, and Discord crossing: shared orchestration moves to Ghostlight; Epiphany Mind/state/mouth stay; narrow slicer, transport, receipt, schema, and permit ports split; strict v1 removes second-channel state from Persona turn.", "status": "accepted", "ts": "2026-08-16T14:28:19+00:00", "type": "architecture"}
{"ts": "2026-08-16T14:46:04+00:00", "type": "verification", "status": "ok", "note": "DeepSeek credential validated and migrated from plaintext ops ingress to machine-scoped DPAPI at the runtime root; native Rust DPAPI loading and live deepseek-v4-flash startup probe passed without persisting or displaying secret or reasoning content. Service ACL and protected invite generation remain in the elevated ops install."}

View file

@ -69,3 +69,4 @@
{"key": "2026-05-06T044920Z0000-0067-d18749ed9b85", "payload": "eyJub3RlIjogIkdob3N0bGlnaHQgYWdlbnQtc3RhdGUgc2NoZW1hIGlzIG5vdyB0aGUgZmlyc3Qgc2hhcmVkIGNyb3NzLXJ1bnRpbWUgcGF5bG9hZCBjb250cmFjdC4gQ3VsdE5ldCBjbGllbnRzIHNob3VsZCBjYXJyeSBnaG9zdGxpZ2h0LmFnZW50X3N0YXRlLnYwIHVuY2hhbmdlZCBpbnNpZGUgdHlwZWQgZG9jdW1lbnQgZW52ZWxvcGVzLCB3aXRoIEN1bHRMaWItc3R5bGUgYXV0aC9zZXNzaW9uIHNlbWFudGljcyBoYW5kbGVkIGJ5IHRoZSB0cmFuc3BvcnQgbGF5ZXIgcmF0aGVyIHRoYW4gYmVzcG9rZSBwZXItcmVwbyBnbHVlLiIsICJzdGF0dXMiOiAiYWNjZXB0ZWQiLCAidHMiOiAiMjAyNi0wNS0wNlQwNDo0OToyMCswMDowMCIsICJ0eXBlIjogImFyY2hpdGVjdHVyZSJ9", "stored_at": "2026-05-06T04:49:20.304695+00:00", "type": "ghostlight.evidence_record.v0"}
{"key": "2026-08-16T142632Z0000-0068-b7da3122b5e8", "payload": "eyJub3RlIjogIkdob3N0bGlnaHREdW5nZW9uIG93bmVyc2hpcCBtYXAgYWNjZXB0ZWQ6IEdob3N0bGlnaHQgb3ducyBnZW5lcmFsaXplZCBQcm9qZWN0b3ItUGVyc29uYS1JbnRlcnByZXRlciBtYWNoaW5lcnk7IGNvbnN1bWluZyBQZXJzb25hcyBzdWNoIGFzIEVwaXBoYW55IHJldGFpbiBjYW5vbmljYWwgbWluZCBhbmQgY29tbWl0IGF1dGhvcml0eSB0aHJvdWdoIG5hcnJvdyBhZGFwdGVycy4gV29ybGRLZXJuZWwgaXMgdGhlIHNvbGUgY2FtcGFpZ24gd3JpdGVyLiIsICJzdGF0dXMiOiAiYWNjZXB0ZWQiLCAidHMiOiAiMjAyNi0wOC0xNlQxNDoyNjozMiswMDowMCIsICJ0eXBlIjogImFyY2hpdGVjdHVyZSJ9", "stored_at": "2026-08-16T14:26:32.332252+00:00", "type": "ghostlight.evidence_record.v0"}
{"key": "2026-08-16T142819Z0000-0069-97f4de27c74a", "payload": "eyJub3RlIjogIkVwaXBoYW55IGV4dHJhY3Rpb24gbWFwIGdyb3VuZGVkIGluIHBlcnNvbmFfdHVybi5ycywgcGVyc29uYV9leGVjdXRvci5ycywgcGVyc29uYS1zZXJ2aWNlLCBjb252ZXJzYXRpb24sIGFuZCBEaXNjb3JkIGNyb3NzaW5nOiBzaGFyZWQgb3JjaGVzdHJhdGlvbiBtb3ZlcyB0byBHaG9zdGxpZ2h0OyBFcGlwaGFueSBNaW5kL3N0YXRlL21vdXRoIHN0YXk7IG5hcnJvdyBzbGljZXIsIHRyYW5zcG9ydCwgcmVjZWlwdCwgc2NoZW1hLCBhbmQgcGVybWl0IHBvcnRzIHNwbGl0OyBzdHJpY3QgdjEgcmVtb3ZlcyBzZWNvbmQtY2hhbm5lbCBzdGF0ZSBmcm9tIFBlcnNvbmEgdHVybi4iLCAic3RhdHVzIjogImFjY2VwdGVkIiwgInRzIjogIjIwMjYtMDgtMTZUMTQ6Mjg6MTkrMDA6MDAiLCAidHlwZSI6ICJhcmNoaXRlY3R1cmUifQ==", "stored_at": "2026-08-16T14:28:19.728049+00:00", "type": "ghostlight.evidence_record.v0"}
{"key": "2026-08-16T144604Z0000-0070-b7d6330d1d5c", "payload": "eyJub3RlIjogIkRlZXBTZWVrIGNyZWRlbnRpYWwgdmFsaWRhdGVkIGFuZCBtaWdyYXRlZCBmcm9tIHBsYWludGV4dCBvcHMgaW5ncmVzcyB0byBtYWNoaW5lLXNjb3BlZCBEUEFQSSBhdCB0aGUgcnVudGltZSByb290OyBuYXRpdmUgUnVzdCBEUEFQSSBsb2FkaW5nIGFuZCBsaXZlIGRlZXBzZWVrLXY0LWZsYXNoIHN0YXJ0dXAgcHJvYmUgcGFzc2VkIHdpdGhvdXQgcGVyc2lzdGluZyBvciBkaXNwbGF5aW5nIHNlY3JldCBvciByZWFzb25pbmcgY29udGVudC4gU2VydmljZSBBQ0wgYW5kIHByb3RlY3RlZCBpbnZpdGUgZ2VuZXJhdGlvbiByZW1haW4gaW4gdGhlIGVsZXZhdGVkIG9wcyBpbnN0YWxsLiIsICJzdGF0dXMiOiAib2siLCAidHMiOiAiMjAyNi0wOC0xNlQxNDo0NjowNCswMDowMCIsICJ0eXBlIjogInZlcmlmaWNhdGlvbiJ9", "stored_at": "2026-08-16T14:46:04.295343+00:00", "type": "ghostlight.evidence_record.v0"}