Gate Ghostlight playtests through Heimdall Discord roles
This commit is contained in:
parent
92c3e81d92
commit
b7259a4eda
8 changed files with 367 additions and 206 deletions
|
|
@ -10,6 +10,9 @@ pub struct HeimdallClient {
|
|||
client: Client,
|
||||
base_url: String,
|
||||
public_app_url: String,
|
||||
callback_url: String,
|
||||
discord_guild_id: String,
|
||||
discord_role_id: String,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
|
|
@ -19,12 +22,24 @@ struct StartRequest<'a> {
|
|||
mode: &'a str,
|
||||
return_to: &'a str,
|
||||
handoff: Handoff<'a>,
|
||||
requested_scopes: [&'a str; 1],
|
||||
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,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct DiscordRolePolicy<'a> {
|
||||
kind: &'a str,
|
||||
guild_id: &'a str,
|
||||
allowed_role_ids: [&'a str; 1],
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
|
|
@ -33,17 +48,21 @@ pub struct StartResponse {
|
|||
pub authorization_url: String,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct RedeemRequest<'a> {
|
||||
completion_code: &'a str,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct RedeemResponse {
|
||||
access_token: String,
|
||||
shared_capabilities: Vec<String>,
|
||||
pub struct BackendCallback {
|
||||
pub source: String,
|
||||
pub kind: String,
|
||||
pub handoff_kind: String,
|
||||
pub attempt_id: String,
|
||||
pub status: String,
|
||||
pub provider: String,
|
||||
pub app_slug: String,
|
||||
pub mode: String,
|
||||
pub return_to: String,
|
||||
pub access_token: Option<String>,
|
||||
pub error: Option<String>,
|
||||
pub error_description: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
|
|
@ -62,7 +81,7 @@ pub struct AppClaim {
|
|||
}
|
||||
|
||||
impl HeimdallClient {
|
||||
pub fn public_demo() -> anyhow::Result<Self> {
|
||||
pub fn from_env() -> anyhow::Result<Self> {
|
||||
Ok(Self {
|
||||
client: Client::builder()
|
||||
.timeout(std::time::Duration::from_secs(10))
|
||||
|
|
@ -73,6 +92,11 @@ impl HeimdallClient {
|
|||
.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")?,
|
||||
})
|
||||
}
|
||||
|
||||
|
|
@ -82,10 +106,13 @@ impl HeimdallClient {
|
|||
client: Client::new(),
|
||||
base_url: "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(),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn start(&self) -> anyhow::Result<StartResponse> {
|
||||
pub async fn start(&self, attempt_id: &str) -> anyhow::Result<StartResponse> {
|
||||
self.client
|
||||
.post(format!("{}/v1/oauth/discord/start", self.base_url))
|
||||
.json(&StartRequest {
|
||||
|
|
@ -93,9 +120,16 @@ impl HeimdallClient {
|
|||
mode: "sign_in",
|
||||
return_to: &self.public_app_url,
|
||||
handoff: Handoff {
|
||||
kind: "browser_completion",
|
||||
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],
|
||||
},
|
||||
requested_scopes: ["identify"],
|
||||
})
|
||||
.send()
|
||||
.await?
|
||||
|
|
@ -105,28 +139,35 @@ impl HeimdallClient {
|
|||
.context("Heimdall start response was malformed")
|
||||
}
|
||||
|
||||
pub async fn redeem(&self, completion_code: &str) -> anyhow::Result<AccessClaims> {
|
||||
let redeemed: RedeemResponse = self
|
||||
.client
|
||||
.post(format!(
|
||||
"{}/v1/apps/{APP_SLUG}/auth-completions/redeem",
|
||||
self.base_url
|
||||
))
|
||||
.json(&RedeemRequest { completion_code })
|
||||
.send()
|
||||
.await?
|
||||
.error_for_status()?
|
||||
.json()
|
||||
.await
|
||||
.context("Heimdall redeem response was malformed")?;
|
||||
if !redeemed
|
||||
.shared_capabilities
|
||||
.iter()
|
||||
.any(|value| value == "app_access")
|
||||
{
|
||||
bail!("Heimdall did not grant Ghostlight app_access");
|
||||
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(&redeemed.access_token).await
|
||||
self.verify(
|
||||
callback
|
||||
.access_token
|
||||
.as_deref()
|
||||
.context("Heimdall success callback omitted its access token")?,
|
||||
)
|
||||
.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(())
|
||||
}
|
||||
|
||||
async fn verify(&self, token: &str) -> anyhow::Result<AccessClaims> {
|
||||
|
|
@ -162,3 +203,12 @@ impl HeimdallClient {
|
|||
Ok(claims)
|
||||
}
|
||||
}
|
||||
|
||||
fn required_env(name: &str) -> anyhow::Result<String> {
|
||||
let value = std::env::var(name).with_context(|| format!("{name} is required"))?;
|
||||
let value = value.trim();
|
||||
if value.is_empty() {
|
||||
bail!("{name} must not be empty");
|
||||
}
|
||||
Ok(value.to_owned())
|
||||
}
|
||||
|
|
|
|||
|
|
@ -4,11 +4,9 @@ use axum::{
|
|||
http::{HeaderMap, HeaderValue, StatusCode, header},
|
||||
middleware,
|
||||
middleware::Next,
|
||||
response::{IntoResponse, Redirect, Response},
|
||||
response::{IntoResponse, Response},
|
||||
routing::{get, post},
|
||||
};
|
||||
#[cfg(windows)]
|
||||
use ghostlight_dungeon::windows_secret::unprotect_machine_utf8;
|
||||
use ghostlight_dungeon::{
|
||||
assessor::ActionAssessor,
|
||||
compiler::{
|
||||
|
|
@ -46,7 +44,7 @@ use tower_http::services::ServeDir;
|
|||
use tracing_subscriber::EnvFilter;
|
||||
|
||||
mod heimdall;
|
||||
use heimdall::HeimdallClient;
|
||||
use heimdall::{BackendCallback, HeimdallClient};
|
||||
|
||||
#[derive(Clone)]
|
||||
struct AppState {
|
||||
|
|
@ -129,17 +127,9 @@ struct ProviderParallelismRequest {
|
|||
provider_parallelism: u8,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct HeimdallRedeemRequest {
|
||||
completion_code: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Serialize, Deserialize)]
|
||||
struct AuthState {
|
||||
schema: String,
|
||||
unused_invite_hashes: BTreeSet<String>,
|
||||
#[serde(default)]
|
||||
provisioned_invite_hashes: BTreeSet<String>,
|
||||
session_hashes: BTreeSet<String>,
|
||||
#[serde(default)]
|
||||
session_aliases: BTreeMap<String, String>,
|
||||
|
|
@ -147,6 +137,16 @@ struct AuthState {
|
|||
session_campaigns: BTreeMap<String, uuid::Uuid>,
|
||||
#[serde(default)]
|
||||
session_campaign_ids: BTreeMap<String, BTreeSet<uuid::Uuid>>,
|
||||
#[serde(default)]
|
||||
heimdall_attempts: BTreeMap<String, HeimdallAuthAttempt>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Serialize, Deserialize)]
|
||||
struct HeimdallAuthAttempt {
|
||||
expires_at_unix: u64,
|
||||
status: String,
|
||||
account_session_hash: Option<String>,
|
||||
error: Option<String>,
|
||||
}
|
||||
|
||||
struct AuthOwner {
|
||||
|
|
@ -176,21 +176,6 @@ impl AuthOwner {
|
|||
}
|
||||
}
|
||||
|
||||
fn provision_invite_hashes(state: &mut AuthState, supplied: &BTreeSet<String>) -> bool {
|
||||
let new_hashes: BTreeSet<String> = supplied
|
||||
.difference(&state.provisioned_invite_hashes)
|
||||
.cloned()
|
||||
.collect();
|
||||
if new_hashes.is_empty() {
|
||||
return false;
|
||||
}
|
||||
state.unused_invite_hashes.extend(new_hashes);
|
||||
state
|
||||
.provisioned_invite_hashes
|
||||
.extend(supplied.iter().cloned());
|
||||
true
|
||||
}
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> anyhow::Result<()> {
|
||||
tracing_subscriber::fmt()
|
||||
|
|
@ -202,55 +187,18 @@ async fn main() -> anyhow::Result<()> {
|
|||
migrate_default_campaign(&runtime_root)?;
|
||||
let registry = CampaignRegistry::new(runtime_root.join("campaigns"))?;
|
||||
registry.load_existing().await?;
|
||||
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.is_empty() || invite_tokens.len() > 128 {
|
||||
return Err(anyhow::anyhow!(
|
||||
"GhostlightDungeon requires between 1 and 128 distinct invite tokens"
|
||||
));
|
||||
}
|
||||
let supplied_invite_hashes: BTreeSet<String> = invite_tokens
|
||||
.iter()
|
||||
.map(|token| secret_hash(token))
|
||||
.collect();
|
||||
std::fs::create_dir_all(runtime_root.join("service"))?;
|
||||
let auth_store = CampaignStore::open(runtime_root.join("service/auth.cc"))?;
|
||||
let (auth_row, auth_state) = match auth_store.load::<AuthState>("auth_state.v1", "primary")? {
|
||||
Some((row, mut state)) => {
|
||||
if !provision_invite_hashes(&mut state, &supplied_invite_hashes) {
|
||||
(row, state)
|
||||
} else {
|
||||
let next_row = auth_store.replace(&row, "ghostlight.auth_state.v1", &state)?;
|
||||
(next_row, state)
|
||||
}
|
||||
}
|
||||
Some((row, state)) => (row, state),
|
||||
None => {
|
||||
let state = AuthState {
|
||||
schema: "ghostlight.auth_state.v1".into(),
|
||||
unused_invite_hashes: supplied_invite_hashes.clone(),
|
||||
provisioned_invite_hashes: supplied_invite_hashes,
|
||||
session_hashes: BTreeSet::new(),
|
||||
session_aliases: BTreeMap::new(),
|
||||
session_campaigns: BTreeMap::new(),
|
||||
session_campaign_ids: BTreeMap::new(),
|
||||
heimdall_attempts: BTreeMap::new(),
|
||||
};
|
||||
let row = auth_store.insert(
|
||||
"auth_state.v1",
|
||||
|
|
@ -309,7 +257,7 @@ async fn main() -> anyhow::Result<()> {
|
|||
row: auth_row,
|
||||
state: auth_state,
|
||||
})),
|
||||
heimdall: Arc::new(HeimdallClient::public_demo()?),
|
||||
heimdall: Arc::new(HeimdallClient::from_env()?),
|
||||
deepseek_status,
|
||||
compiler,
|
||||
assessor,
|
||||
|
|
@ -389,39 +337,163 @@ fn app_router(state: AppState, web_root: PathBuf) -> Router {
|
|||
|
||||
Router::new()
|
||||
.route("/health", get(health))
|
||||
.route("/invite/{token}", get(invite))
|
||||
.route("/api/auth/heimdall/start", post(heimdall_start))
|
||||
.route("/api/auth/heimdall/redeem", post(heimdall_redeem))
|
||||
.route("/api/auth/heimdall/callback", post(heimdall_callback))
|
||||
.route(
|
||||
"/api/auth/heimdall/attempt/{attempt_id}",
|
||||
get(heimdall_attempt),
|
||||
)
|
||||
.route(
|
||||
"/api/auth/heimdall/attempt/{attempt_id}/adopt",
|
||||
post(heimdall_adopt),
|
||||
)
|
||||
.merge(protected_api)
|
||||
.fallback_service(ServeDir::new(web_root).append_index_html_on_directories(true))
|
||||
.with_state(state)
|
||||
}
|
||||
|
||||
async fn heimdall_start(State(state): State<AppState>) -> Response {
|
||||
match state.heimdall.start().await {
|
||||
Ok(start) => {
|
||||
Json(serde_json::json!({"authorization_url": start.authorization_url})).into_response()
|
||||
let attempt_id = uuid::Uuid::new_v4().simple().to_string();
|
||||
let now = unix_time_seconds();
|
||||
{
|
||||
let mut auth = state.auth.lock().await;
|
||||
let mut next_state = auth.state.clone();
|
||||
prune_heimdall_attempts(&mut next_state, now);
|
||||
next_state.heimdall_attempts.insert(
|
||||
attempt_id.clone(),
|
||||
HeimdallAuthAttempt {
|
||||
expires_at_unix: now + 600,
|
||||
status: "pending".into(),
|
||||
account_session_hash: None,
|
||||
error: None,
|
||||
},
|
||||
);
|
||||
if let Err(error) = auth.commit(next_state) {
|
||||
return (StatusCode::INTERNAL_SERVER_ERROR, error.to_string()).into_response();
|
||||
}
|
||||
}
|
||||
match state.heimdall.start(&attempt_id).await {
|
||||
Ok(start) => Json(serde_json::json!({
|
||||
"attempt_id": attempt_id,
|
||||
"authorization_url": start.authorization_url
|
||||
}))
|
||||
.into_response(),
|
||||
Err(error) => {
|
||||
let message = error.to_string();
|
||||
let mut auth = state.auth.lock().await;
|
||||
let mut next_state = auth.state.clone();
|
||||
if let Some(attempt) = next_state.heimdall_attempts.get_mut(&attempt_id) {
|
||||
attempt.status = "failed".into();
|
||||
attempt.error = Some("Heimdall could not start Discord sign-in".into());
|
||||
}
|
||||
if let Err(commit_error) = auth.commit(next_state) {
|
||||
return (StatusCode::INTERNAL_SERVER_ERROR, commit_error.to_string())
|
||||
.into_response();
|
||||
}
|
||||
(StatusCode::BAD_GATEWAY, message).into_response()
|
||||
}
|
||||
Err(error) => (StatusCode::BAD_GATEWAY, error.to_string()).into_response(),
|
||||
}
|
||||
}
|
||||
|
||||
async fn heimdall_redeem(
|
||||
async fn heimdall_callback(
|
||||
State(state): State<AppState>,
|
||||
Json(request): Json<HeimdallRedeemRequest>,
|
||||
Json(callback): Json<BackendCallback>,
|
||||
) -> Response {
|
||||
if request.completion_code.len() > 1024 || request.completion_code.trim().is_empty() {
|
||||
return (StatusCode::BAD_REQUEST, "invalid completion code").into_response();
|
||||
if callback.attempt_id.len() > 128 || callback.attempt_id.trim().is_empty() {
|
||||
return (StatusCode::BAD_REQUEST, "invalid Heimdall attempt id").into_response();
|
||||
}
|
||||
let claims = match state.heimdall.redeem(request.completion_code.trim()).await {
|
||||
if let Err(error) = state.heimdall.validate_callback_envelope(&callback) {
|
||||
return (StatusCode::UNAUTHORIZED, error.to_string()).into_response();
|
||||
}
|
||||
let now = unix_time_seconds();
|
||||
{
|
||||
let auth = state.auth.lock().await;
|
||||
let Some(attempt) = auth.state.heimdall_attempts.get(&callback.attempt_id) else {
|
||||
return (StatusCode::NOT_FOUND, "unknown Heimdall attempt").into_response();
|
||||
};
|
||||
if attempt.expires_at_unix < now || attempt.status != "pending" {
|
||||
return (StatusCode::CONFLICT, "Heimdall attempt is not pending").into_response();
|
||||
}
|
||||
}
|
||||
if callback.status != "success" {
|
||||
let mut auth = state.auth.lock().await;
|
||||
let mut next_state = auth.state.clone();
|
||||
if let Some(attempt) = next_state.heimdall_attempts.get_mut(&callback.attempt_id) {
|
||||
attempt.status = "failed".into();
|
||||
attempt.error = Some(
|
||||
callback
|
||||
.error_description
|
||||
.clone()
|
||||
.or(callback.error.clone())
|
||||
.unwrap_or_else(|| "Discord membership was not admitted".into()),
|
||||
);
|
||||
}
|
||||
return match auth.commit(next_state) {
|
||||
Ok(()) => StatusCode::NO_CONTENT.into_response(),
|
||||
Err(error) => (StatusCode::INTERNAL_SERVER_ERROR, error.to_string()).into_response(),
|
||||
};
|
||||
}
|
||||
let claims = match state.heimdall.verify_callback(&callback).await {
|
||||
Ok(claims) => claims,
|
||||
Err(error) => return (StatusCode::UNAUTHORIZED, error.to_string()).into_response(),
|
||||
};
|
||||
let account_session = secret_hash(&format!("heimdall-account:{}", claims.account_id));
|
||||
let mut auth = state.auth.lock().await;
|
||||
let mut next_state = auth.state.clone();
|
||||
let Some(attempt) = next_state.heimdall_attempts.get_mut(&callback.attempt_id) else {
|
||||
return (StatusCode::NOT_FOUND, "unknown Heimdall attempt").into_response();
|
||||
};
|
||||
if attempt.expires_at_unix < now || attempt.status != "pending" {
|
||||
return (StatusCode::CONFLICT, "Heimdall attempt is not pending").into_response();
|
||||
}
|
||||
attempt.status = "succeeded".into();
|
||||
attempt.account_session_hash = Some(account_session);
|
||||
match auth.commit(next_state) {
|
||||
Ok(()) => StatusCode::NO_CONTENT.into_response(),
|
||||
Err(error) => (StatusCode::INTERNAL_SERVER_ERROR, error.to_string()).into_response(),
|
||||
}
|
||||
}
|
||||
|
||||
async fn heimdall_attempt(
|
||||
Path(attempt_id): Path<String>,
|
||||
State(state): State<AppState>,
|
||||
) -> Response {
|
||||
let auth = state.auth.lock().await;
|
||||
let Some(attempt) = auth.state.heimdall_attempts.get(&attempt_id) else {
|
||||
return StatusCode::NOT_FOUND.into_response();
|
||||
};
|
||||
if attempt.expires_at_unix < unix_time_seconds() {
|
||||
return StatusCode::GONE.into_response();
|
||||
}
|
||||
Json(serde_json::json!({
|
||||
"status": attempt.status,
|
||||
"error": attempt.error,
|
||||
}))
|
||||
.into_response()
|
||||
}
|
||||
|
||||
async fn heimdall_adopt(Path(attempt_id): Path<String>, State(state): State<AppState>) -> Response {
|
||||
let now = unix_time_seconds();
|
||||
let raw_session = uuid::Uuid::new_v4().to_string();
|
||||
let alias_hash = secret_hash(&raw_session);
|
||||
let mut auth = state.auth.lock().await;
|
||||
let mut next_state = auth.state.clone();
|
||||
let Some(attempt) = next_state.heimdall_attempts.remove(&attempt_id) else {
|
||||
return StatusCode::NOT_FOUND.into_response();
|
||||
};
|
||||
if attempt.expires_at_unix < now {
|
||||
return StatusCode::GONE.into_response();
|
||||
}
|
||||
if attempt.status != "succeeded" {
|
||||
return (StatusCode::CONFLICT, "Heimdall attempt has not succeeded").into_response();
|
||||
}
|
||||
let Some(account_session) = attempt.account_session_hash else {
|
||||
return (
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
"Heimdall attempt lost account authority",
|
||||
)
|
||||
.into_response();
|
||||
};
|
||||
next_state.session_hashes.insert(account_session.clone());
|
||||
next_state
|
||||
.session_aliases
|
||||
|
|
@ -440,6 +512,19 @@ async fn heimdall_redeem(
|
|||
response
|
||||
}
|
||||
|
||||
fn unix_time_seconds() -> u64 {
|
||||
std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.unwrap_or_default()
|
||||
.as_secs()
|
||||
}
|
||||
|
||||
fn prune_heimdall_attempts(state: &mut AuthState, now: u64) {
|
||||
state
|
||||
.heimdall_attempts
|
||||
.retain(|_, attempt| attempt.expires_at_unix >= now);
|
||||
}
|
||||
|
||||
async fn require_api_authentication(
|
||||
State(state): State<AppState>,
|
||||
headers: HeaderMap,
|
||||
|
|
@ -459,34 +544,6 @@ async fn health(State(state): State<AppState>) -> Response {
|
|||
}
|
||||
}
|
||||
|
||||
async fn invite(Path(token): Path<String>, State(state): State<AppState>) -> Response {
|
||||
let mut auth = state.auth.lock().await;
|
||||
let invite_hash = secret_hash(&token);
|
||||
if !auth.state.unused_invite_hashes.contains(&invite_hash) {
|
||||
return (StatusCode::UNAUTHORIZED, "invalid or consumed invite").into_response();
|
||||
}
|
||||
let session = uuid::Uuid::new_v4().to_string();
|
||||
let mut next_state = auth.state.clone();
|
||||
next_state.unused_invite_hashes.remove(&invite_hash);
|
||||
next_state.session_hashes.insert(secret_hash(&session));
|
||||
match auth.commit(next_state) {
|
||||
Ok(()) => {}
|
||||
Err(error) => {
|
||||
return (StatusCode::INTERNAL_SERVER_ERROR, error.to_string()).into_response();
|
||||
}
|
||||
}
|
||||
drop(auth);
|
||||
let mut response = Redirect::to("/").into_response();
|
||||
response.headers_mut().insert(
|
||||
header::SET_COOKIE,
|
||||
HeaderValue::from_str(&format!(
|
||||
"ghostlight_session={session}; HttpOnly; SameSite=Strict; Path=/"
|
||||
))
|
||||
.unwrap(),
|
||||
);
|
||||
response
|
||||
}
|
||||
|
||||
async fn surface(headers: HeaderMap, State(state): State<AppState>) -> Response {
|
||||
let session = match authenticated_session(&headers, &state).await {
|
||||
Some(value) => value,
|
||||
|
|
@ -2566,12 +2623,11 @@ mod tests {
|
|||
let auth_store = CampaignStore::open(root.join("auth.cc")).unwrap();
|
||||
let auth_state = AuthState {
|
||||
schema: "ghostlight.auth_state.v1".into(),
|
||||
unused_invite_hashes: BTreeSet::new(),
|
||||
provisioned_invite_hashes: BTreeSet::new(),
|
||||
session_hashes: BTreeSet::new(),
|
||||
session_aliases: BTreeMap::new(),
|
||||
session_campaigns: BTreeMap::new(),
|
||||
session_campaign_ids: BTreeMap::new(),
|
||||
heimdall_attempts: BTreeMap::new(),
|
||||
};
|
||||
let row = auth_store
|
||||
.insert(
|
||||
|
|
@ -2676,6 +2732,77 @@ mod tests {
|
|||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn completed_heimdall_attempt_is_single_use_session_authority() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let state = empty_app_state(dir.path());
|
||||
{
|
||||
let mut auth = state.auth.lock().await;
|
||||
let mut next = auth.state.clone();
|
||||
next.heimdall_attempts.insert(
|
||||
"attempt-one".into(),
|
||||
HeimdallAuthAttempt {
|
||||
expires_at_unix: unix_time_seconds() + 60,
|
||||
status: "succeeded".into(),
|
||||
account_session_hash: Some("account-authority".into()),
|
||||
error: None,
|
||||
},
|
||||
);
|
||||
auth.commit(next).unwrap();
|
||||
}
|
||||
|
||||
let router = app_router(state.clone(), dir.path().join("web"));
|
||||
let adopted = router
|
||||
.clone()
|
||||
.oneshot(
|
||||
Request::builder()
|
||||
.method("POST")
|
||||
.uri("/api/auth/heimdall/attempt/attempt-one/adopt")
|
||||
.body(Body::empty())
|
||||
.unwrap(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(adopted.status(), StatusCode::OK);
|
||||
let cookie = adopted.headers()[header::SET_COOKIE].to_str().unwrap();
|
||||
assert!(cookie.contains("HttpOnly"));
|
||||
assert!(cookie.contains("Secure"));
|
||||
assert!(
|
||||
state
|
||||
.auth
|
||||
.lock()
|
||||
.await
|
||||
.state
|
||||
.session_hashes
|
||||
.contains("account-authority")
|
||||
);
|
||||
|
||||
let replay = router
|
||||
.clone()
|
||||
.oneshot(
|
||||
Request::builder()
|
||||
.method("POST")
|
||||
.uri("/api/auth/heimdall/attempt/attempt-one/adopt")
|
||||
.body(Body::empty())
|
||||
.unwrap(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(replay.status(), StatusCode::NOT_FOUND);
|
||||
|
||||
let retired_invite = router
|
||||
.oneshot(
|
||||
Request::builder()
|
||||
.uri("/invite/old-authority")
|
||||
.body(Body::empty())
|
||||
.unwrap(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_ne!(retired_invite.status(), StatusCode::OK);
|
||||
assert!(retired_invite.headers().get(header::SET_COOKIE).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn generated_start_selection_uses_only_server_owned_ids() {
|
||||
let opening = OpeningSuggestion {
|
||||
|
|
@ -2948,8 +3075,6 @@ mod tests {
|
|||
let auth_store = CampaignStore::open(dir.path().join("auth.cc")).unwrap();
|
||||
let auth_state = AuthState {
|
||||
schema: "ghostlight.auth_state.v1".into(),
|
||||
unused_invite_hashes: BTreeSet::new(),
|
||||
provisioned_invite_hashes: BTreeSet::new(),
|
||||
session_hashes: BTreeSet::from(["left".into(), "right".into()]),
|
||||
session_aliases: BTreeMap::new(),
|
||||
session_campaigns: BTreeMap::from([
|
||||
|
|
@ -2960,6 +3085,7 @@ mod tests {
|
|||
("left".into(), BTreeSet::from([left.id])),
|
||||
("right".into(), BTreeSet::from([right.id])),
|
||||
]),
|
||||
heimdall_attempts: BTreeMap::new(),
|
||||
};
|
||||
let row = auth_store
|
||||
.insert(
|
||||
|
|
@ -3009,12 +3135,11 @@ mod tests {
|
|||
let store = CampaignStore::open(dir.path().join("auth.cc")).unwrap();
|
||||
let original = AuthState {
|
||||
schema: "ghostlight.auth_state.v1".into(),
|
||||
unused_invite_hashes: BTreeSet::from(["invite".into()]),
|
||||
provisioned_invite_hashes: BTreeSet::from(["invite".into()]),
|
||||
session_hashes: BTreeSet::new(),
|
||||
session_aliases: BTreeMap::new(),
|
||||
session_campaigns: BTreeMap::new(),
|
||||
session_campaign_ids: BTreeMap::new(),
|
||||
heimdall_attempts: BTreeMap::new(),
|
||||
};
|
||||
let row = store
|
||||
.insert(
|
||||
|
|
@ -3037,36 +3162,12 @@ mod tests {
|
|||
.unwrap();
|
||||
|
||||
let mut rejected = original.clone();
|
||||
rejected.unused_invite_hashes.clear();
|
||||
rejected.session_hashes.insert("phantom".into());
|
||||
assert!(owner.commit(rejected).is_err());
|
||||
assert_eq!(
|
||||
owner.state.unused_invite_hashes,
|
||||
original.unused_invite_hashes
|
||||
);
|
||||
assert_eq!(owner.state.session_hashes, original.session_hashes);
|
||||
assert_eq!(owner.row, row);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invite_provisioning_adds_new_hashes_without_resurrecting_consumed_ones() {
|
||||
let mut state = AuthState {
|
||||
schema: "ghostlight.auth_state.v1".into(),
|
||||
unused_invite_hashes: BTreeSet::new(),
|
||||
provisioned_invite_hashes: BTreeSet::from(["consumed".into()]),
|
||||
session_hashes: BTreeSet::new(),
|
||||
session_aliases: BTreeMap::new(),
|
||||
session_campaigns: BTreeMap::new(),
|
||||
session_campaign_ids: BTreeMap::new(),
|
||||
};
|
||||
let supplied = BTreeSet::from(["consumed".into(), "fresh".into()]);
|
||||
|
||||
assert!(provision_invite_hashes(&mut state, &supplied));
|
||||
assert_eq!(state.unused_invite_hashes, BTreeSet::from(["fresh".into()]));
|
||||
assert!(!provision_invite_hashes(&mut state, &supplied));
|
||||
assert_eq!(state.unused_invite_hashes, BTreeSet::from(["fresh".into()]));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn campaign_selection_reloads_stale_auth_without_losing_concurrent_state() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
|
|
|
|||
|
|
@ -51,11 +51,13 @@ institutions, two clocks, explicit gaps, and branch assumptions. It remained
|
|||
an uncommitted revision-0 preview with `requires_approval: true` until the
|
||||
tester explicitly approved it.
|
||||
|
||||
Heimdall owns public identity and Discord OAuth. The browser receives a
|
||||
one-time completion code rather than a provider token. Ghostlight redeems that
|
||||
code server-to-server, verifies the EdDSA `aud=ghostlight` access claim against
|
||||
Heimdall's published JWKS, and maps the account to stable app-local campaign
|
||||
authority. Only hashed local session aliases enter `service/auth.cc`.
|
||||
Heimdall owns public identity, Discord OAuth, and the KLTST guild-role decision.
|
||||
Ghostlight creates a short-lived login attempt and asks Heimdall for a trusted
|
||||
backend callback. Heimdall returns the result and token directly to Ghostlight;
|
||||
the browser can only poll and adopt that completed attempt. Ghostlight verifies
|
||||
the EdDSA `aud=ghostlight` access claim against Heimdall's published JWKS, maps
|
||||
the account to stable app-local campaign authority, and discards the provider
|
||||
token. Only hashed local session aliases enter `service/auth.cc`.
|
||||
|
||||
## Body and faculty map
|
||||
|
||||
|
|
|
|||
|
|
@ -324,8 +324,10 @@ session authority; an invalid session receives `401` before JSON parsing,
|
|||
schema rejection, campaign lookup, inference, or mutation. Handlers repeat the
|
||||
session lookup where they need the session identity, so revocation between the
|
||||
perimeter check and a handler cannot leave stale authority alive. Public
|
||||
`/health`, single-use `/invite/{token}`, and static browser assets remain
|
||||
outside this middleware. Regressions prove malformed anonymous JSON is refused
|
||||
`/health`, the Heimdall login-attempt boundary, and static browser assets remain
|
||||
outside this middleware. Login attempts carry no campaign authority: only a
|
||||
JWKS-verified successful Heimdall callback can bind one to an account, and only
|
||||
one browser adoption can mint its HttpOnly session alias. Regressions prove malformed anonymous JSON is refused
|
||||
at the perimeter while the same malformed body under a valid session reaches
|
||||
the ordinary `400` extractor response.
|
||||
|
||||
|
|
|
|||
|
|
@ -69,9 +69,9 @@ impossible and receipted d20 actions, grounded narration, strategic cells, and a
|
|||
cover used 20,760 prompt tokens and 14.38 seconds, with 13 of 13 stages valid on
|
||||
their first attempt, two material institutional consequences, exact constituent
|
||||
authority, and no player mutation. Authenticated surface and lifecycle
|
||||
acceptance now cover spoiler-safe literal HTTP responses, separate invite
|
||||
ownership, single-use invite rejection, fork/reset/export, four persisted
|
||||
campaigns, and exact-commit restart. Live priority cancels in-flight scheduler
|
||||
acceptance now cover spoiler-safe literal HTTP responses, Heimdall-account
|
||||
campaign isolation, fork/reset/export, four persisted campaigns, and
|
||||
exact-commit restart. Live priority cancels in-flight scheduler
|
||||
inference and excludes its commit gate.
|
||||
|
||||
The revised provider-backed Gestalt golden now passes across four waves and
|
||||
|
|
@ -85,10 +85,10 @@ inert outcome resolver.
|
|||
|
||||
Release truth, authenticated compiler/player HTTP journeys, restart continuity,
|
||||
and the strict multiresolution refugee-return golden now pass against immutable
|
||||
builds. The next gate is visual browser inspection of the served interface with
|
||||
a temporary invite, followed by supervised human play. Browser credential
|
||||
transmission requires explicit operator approval and must end with invitation
|
||||
rotation. Treat player confusion, dramatic flatness, composite consequences,
|
||||
builds. The next gate is visual browser inspection through Heimdall's KLTST
|
||||
Discord-role admission, followed by supervised human play. The browser never
|
||||
receives the Heimdall access token; it adopts a server-verified login attempt
|
||||
into an HttpOnly Ghostlight session. Treat player confusion, dramatic flatness, composite consequences,
|
||||
and token-heavy low-consequence stages as evidence about missing context or
|
||||
misplaced authority. Keep the independent semantic outcome verifier selective:
|
||||
it checks custody transfers, relation shifts, and named-member private deltas,
|
||||
|
|
|
|||
File diff suppressed because one or more lines are too long
2
web/dist/index.html
vendored
2
web/dist/index.html
vendored
|
|
@ -1,5 +1,5 @@
|
|||
<!doctype html>
|
||||
<html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>GhostlightDungeon</title> <script type="module" crossorigin src="/assets/index-CngTndFJ.js"></script>
|
||||
<html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>GhostlightDungeon</title> <script type="module" crossorigin src="/assets/index-BdgXKt11.js"></script>
|
||||
<link rel="stylesheet" crossorigin href="/assets/index-B7Qh0xAi.css">
|
||||
</head>
|
||||
<body><header><p class="eyebrow">STARFIRE / PRIVATE VERSE</p><h1>GhostlightDungeon</h1><p id="status" role="status" aria-live="polite">Reading the world…</p></header><main>
|
||||
|
|
|
|||
|
|
@ -133,7 +133,7 @@ function renderCommandReceipt(body: any) {
|
|||
}
|
||||
|
||||
function showAuthenticationGate() {
|
||||
const message = "Sign in through Heimdall to enter the public demo.";
|
||||
const message = "Sign in through Heimdall to enter the KLTST playtest.";
|
||||
status.textContent = message;
|
||||
compiler.hidden = true;
|
||||
composer.hidden = true;
|
||||
|
|
@ -143,9 +143,9 @@ function showAuthenticationGate() {
|
|||
host.hidden = false;
|
||||
const gate = node("article", undefined, "card");
|
||||
gate.append(
|
||||
node("h2", "Ghostlight Dungeon public demo"),
|
||||
node("h2", "Ghostlight Dungeon playtest"),
|
||||
node("p", message),
|
||||
node("p", "Heimdall uses Discord only to establish your GameCult identity. Ghostlight keeps your campaigns isolated from every other account.", "quiet"),
|
||||
node("p", "Access requires membership in the KLTST Discord role. Heimdall checks that role, then Ghostlight keeps your campaigns isolated from every other account.", "quiet"),
|
||||
);
|
||||
const login = node("button", "Continue with Discord") as HTMLButtonElement;
|
||||
login.type = "button";
|
||||
|
|
@ -157,24 +157,30 @@ function showAuthenticationGate() {
|
|||
async function startHeimdallLogin() {
|
||||
const response = await fetch("/api/auth/heimdall/start", { method: "POST" });
|
||||
const body = await decodeResponse(response);
|
||||
if (!response.ok || typeof body?.authorization_url !== "string") {
|
||||
if (!response.ok || typeof body?.authorization_url !== "string" || typeof body?.attempt_id !== "string") {
|
||||
throw new ServerResponseFailure(responseError(body, "Heimdall could not start Discord sign-in."));
|
||||
}
|
||||
window.location.assign(body.authorization_url);
|
||||
const popup = window.open(body.authorization_url, "ghostlight-heimdall", "popup,width=560,height=760");
|
||||
if (!popup) throw new Error("Allow pop-ups for Ghostlight so Heimdall can complete Discord sign-in.");
|
||||
await pollHeimdallAttempt(body.attempt_id);
|
||||
}
|
||||
|
||||
async function redeemHeimdallReturn() {
|
||||
const fragment = new URLSearchParams(window.location.hash.slice(1));
|
||||
const completionCode = fragment.get("heimdall_completion_code");
|
||||
if (!completionCode) return;
|
||||
const response = await fetch("/api/auth/heimdall/redeem", {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({ completion_code: completionCode }),
|
||||
});
|
||||
const body = await decodeResponse(response);
|
||||
history.replaceState(null, "", `${window.location.pathname}${window.location.search}`);
|
||||
if (!response.ok) throw new ServerResponseFailure(responseError(body, "Heimdall sign-in could not be adopted."));
|
||||
async function pollHeimdallAttempt(attemptId: string) {
|
||||
const deadline = Date.now() + 10 * 60_000;
|
||||
while (Date.now() < deadline) {
|
||||
await new Promise(resolve => window.setTimeout(resolve, 900));
|
||||
const response = await fetch(`/api/auth/heimdall/attempt/${encodeURIComponent(attemptId)}`, { cache: "no-store" });
|
||||
const body = await decodeResponse(response);
|
||||
if (!response.ok) throw new ServerResponseFailure(responseError(body, "Heimdall sign-in expired."));
|
||||
if (body?.status === "pending") continue;
|
||||
if (body?.status !== "succeeded") throw new Error(String(body?.error ?? "Your Discord account does not have Ghostlight playtest access."));
|
||||
const adopted = await fetch(`/api/auth/heimdall/attempt/${encodeURIComponent(attemptId)}/adopt`, { method: "POST" });
|
||||
const adoptedBody = await decodeResponse(adopted);
|
||||
if (!adopted.ok) throw new ServerResponseFailure(responseError(adoptedBody, "Ghostlight could not adopt the Heimdall session."));
|
||||
await refresh();
|
||||
return;
|
||||
}
|
||||
throw new Error("Heimdall sign-in timed out. Try again when you are ready.");
|
||||
}
|
||||
|
||||
async function refresh() {
|
||||
|
|
@ -483,4 +489,4 @@ document.querySelector<HTMLButtonElement>("#load-operator")!.addEventListener("c
|
|||
renderEveSurface(surface, document.querySelector<HTMLElement>("#operator-output")!, { body: document.body, clientId: "ghostlight.operator", statusElement: status });
|
||||
});
|
||||
});
|
||||
void redeemHeimdallReturn().then(refresh).catch(reportClientFailure);
|
||||
void refresh().catch(reportClientFailure);
|
||||
|
|
|
|||
Loading…
Reference in a new issue