diff --git a/Cargo.lock b/Cargo.lock index 584c27c..2895d58 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -37,6 +37,15 @@ dependencies = [ "subtle", ] +[[package]] +name = "aho-corasick" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba" +dependencies = [ + "memchr", +] + [[package]] name = "android_system_properties" version = "0.1.6" @@ -61,6 +70,28 @@ dependencies = [ "object", ] +[[package]] +name = "async-stream" +version = "0.3.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b5a71a6f37880a80d1d7f19efd781e4b5de42c88f0722cc13bcb6cc2cfe8476" +dependencies = [ + "async-stream-impl", + "futures-core", + "pin-project-lite", +] + +[[package]] +name = "async-stream-impl" +version = "0.3.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c7c24de15d275a1ecfd47a380fb4d5ec9bfe0933f309ed5e705b775596a3574d" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "async-trait" version = "0.1.92" @@ -84,6 +115,70 @@ version = "1.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" +[[package]] +name = "axum" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "31b698c5f9a010f6573133b09e0de5408834d0c82f8d7475a89fc1867a71cd90" +dependencies = [ + "axum-core", + "axum-macros", + "bytes", + "form_urlencoded", + "futures-util", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-util", + "itoa", + "matchit", + "memchr", + "mime", + "percent-encoding", + "pin-project-lite", + "serde_core", + "serde_json", + "serde_path_to_error", + "serde_urlencoded", + "sync_wrapper", + "tokio", + "tower", + "tower-layer", + "tower-service", + "tracing", +] + +[[package]] +name = "axum-core" +version = "0.5.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08c78f31d7b1291f7ee735c1c6780ccde7785daae9a9206026862dab7d8792d1" +dependencies = [ + "bytes", + "futures-core", + "http", + "http-body", + "http-body-util", + "mime", + "pin-project-lite", + "sync_wrapper", + "tower-layer", + "tower-service", + "tracing", +] + +[[package]] +name = "axum-macros" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7aa268c23bfbbd2c4363b9cd302a4f504fb2a9dfe7e3451d66f35dd392e20aca" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "base64" version = "0.22.1" @@ -288,6 +383,42 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "cultmesh-rs" +version = "0.1.0" +source = "git+https://github.com/GameCult/CultLib.git?rev=85f7024a35ea42cf9f0a0199a064526427150191#85f7024a35ea42cf9f0a0199a064526427150191" +dependencies = [ + "anyhow", + "cultcache-rs 0.1.0", + "cultnet-rs 0.1.0", + "serde", +] + +[[package]] +name = "cultnet-rs" +version = "0.1.0" +source = "git+https://github.com/GameCult/CultLib.git?rev=85f7024a35ea42cf9f0a0199a064526427150191#85f7024a35ea42cf9f0a0199a064526427150191" +dependencies = [ + "aes-gcm", + "anyhow", + "base64", + "chrono", + "cultcache-rs 0.1.0", + "ed25519-dalek", + "hmac", + "rand 0.9.5", + "rmp-serde", + "rmpv", + "serde", + "serde_bytes", + "serde_json", + "sha2", + "socket2 0.5.10", + "uuid", + "windows-sys 0.61.2", + "zeroize", +] + [[package]] name = "cultnet-rs" version = "0.2.0" @@ -350,6 +481,12 @@ dependencies = [ "zeroize", ] +[[package]] +name = "deranged" +version = "0.5.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e9de72ce2ad1f90dc62fa25f0f430ef85eb4b0d8fa0be4f30373bc40a21d28e" + [[package]] name = "digest" version = "0.10.7" @@ -594,6 +731,42 @@ dependencies = [ "zeroize", ] +[[package]] +name = "ghostlight-dungeon" +version = "0.1.0" +dependencies = [ + "aes-gcm", + "anyhow", + "async-stream", + "async-trait", + "axum", + "base64", + "chrono", + "cultcache-rs 0.1.0", + "cultmesh-rs", + "cultnet-rs 0.1.0", + "ghostlight", + "ghostlight-persona-projection", + "hmac", + "jsonwebtoken", + "libc", + "model-connector", + "rand 0.9.5", + "reqwest", + "rmp-serde", + "serde", + "serde_json", + "sha2", + "tempfile", + "thiserror", + "tokio", + "tower", + "tracing", + "tracing-subscriber", + "uuid", + "zeroize", +] + [[package]] name = "ghostlight-persona-projection" version = "0.1.0" @@ -663,6 +836,12 @@ version = "1.10.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" +[[package]] +name = "httpdate" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9" + [[package]] name = "hyper" version = "1.11.0" @@ -676,6 +855,7 @@ dependencies = [ "http", "http-body", "httparse", + "httpdate", "itoa", "pin-project-lite", "smallvec", @@ -882,6 +1062,27 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "jsonwebtoken" +version = "9.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a87cc7a48537badeae96744432de36f4be2b4a34a05a5ef32e9dd8a1c169dde" +dependencies = [ + "base64", + "js-sys", + "pem", + "ring", + "serde", + "serde_json", + "simple_asn1", +] + +[[package]] +name = "lazy_static" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb" + [[package]] name = "libc" version = "0.2.189" @@ -921,12 +1122,33 @@ version = "0.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "112b39cec0b298b6c1999fee3e31427f74f676e4cb9879ed1a121b43661a4154" +[[package]] +name = "matchers" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d1525a2a28c7f4fa0fc98bb91ae755d1e2d1505079e05539e35bc876b5d65ae9" +dependencies = [ + "regex-automata", +] + +[[package]] +name = "matchit" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47e1ffaa40ddd1f3ed91f717a33c8c0ee23fff369e3aa8772b9605cc1d22f4c3" + [[package]] name = "memchr" version = "2.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" +[[package]] +name = "mime" +version = "0.3.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d5848f5a9e8117cf94f2f90faac24a87ff81600ff8628c1e3deaab572e76bfa1" + [[package]] name = "mio" version = "1.2.2" @@ -945,7 +1167,7 @@ source = "git+https://eureka.gamecult.org/forge/GameCult/ModelConnector.git?rev= dependencies = [ "aes-gcm", "base64", - "cultnet-rs", + "cultnet-rs 0.2.0", "rand_core 0.6.4", "rmp-serde", "rmpv", @@ -958,6 +1180,40 @@ dependencies = [ "zeroize", ] +[[package]] +name = "nu-ansi-term" +version = "0.50.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "num-bigint" +version = "0.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c89e69e7e0f03bea5ef08013795c25018e101932225a656383bd384495ecc367" +dependencies = [ + "num-integer", + "num-traits", +] + +[[package]] +name = "num-conv" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441" + +[[package]] +name = "num-integer" +version = "0.1.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7ce2d95d4b3734dc35aa2f45e1aa22cd416814592a4f9d9205e11affd5b8e10b" +dependencies = [ + "num-traits", +] + [[package]] name = "num-traits" version = "0.2.19" @@ -1011,6 +1267,16 @@ dependencies = [ "windows-link", ] +[[package]] +name = "pem" +version = "3.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d30c53c26bc5b31a98cd02d20f25a7c8567146caf63ed593a9d87b2775291be" +dependencies = [ + "base64", + "serde_core", +] + [[package]] name = "percent-encoding" version = "2.3.2" @@ -1054,6 +1320,12 @@ dependencies = [ "zerovec", ] +[[package]] +name = "powerfmt" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a6394b9e965e73d0a289ee54f589087e2c676aedf60885baf52c76b771e4958" + [[package]] name = "ppv-lite86" version = "0.2.21" @@ -1261,6 +1533,23 @@ dependencies = [ "syn 3.0.3", ] +[[package]] +name = "regex-automata" +version = "0.4.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41d60ef07df457506a0a1a2073112eb4aae5733dbd2813c3da77d1b0fd441158" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax", +] + +[[package]] +name = "regex-syntax" +version = "0.8.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d902046e6a28a1e4c3cab97258a0ce11e994903f01c2d97a9447a0b3df85f4f6" + [[package]] name = "reqwest" version = "0.12.28" @@ -1522,6 +1811,17 @@ dependencies = [ "zmij", ] +[[package]] +name = "serde_path_to_error" +version = "0.1.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10a9ff822e371bb5403e391ecd83e182e0e77ba7f6fe0160b795797109d1b457" +dependencies = [ + "itoa", + "serde", + "serde_core", +] + [[package]] name = "serde_stacker" version = "0.1.14" @@ -1556,6 +1856,15 @@ dependencies = [ "digest", ] +[[package]] +name = "sharded-slab" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f40ca3c46823713e0d4209592e8d6e826aa57e928f09752619fc696c499637f6" +dependencies = [ + "lazy_static", +] + [[package]] name = "shlex" version = "2.0.1" @@ -1581,6 +1890,18 @@ dependencies = [ "rand_core 0.6.4", ] +[[package]] +name = "simple_asn1" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d585997b0ac10be3c5ee635f1bab02d512760d14b7c468801ac8a01d9ae5f1d" +dependencies = [ + "num-bigint", + "num-traits", + "thiserror", + "time", +] + [[package]] name = "slab" version = "0.4.12" @@ -1723,6 +2044,45 @@ dependencies = [ "syn 3.0.3", ] +[[package]] +name = "thread_local" +version = "1.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ad99c4c6d32803332c548b1af0540b357b3f5fc0be8f6c6bfe8b2e6ae784070" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "time" +version = "0.3.55" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cdb87b95ec50ddfa440816d227a17b2ccbdda963a316a727fda0fc4334f7d134" +dependencies = [ + "deranged", + "num-conv", + "powerfmt", + "serde_core", + "time-core", + "time-macros", +] + +[[package]] +name = "time-core" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e1c906769ad99c88eaa54e728060edef082f8e358ff32030cb7c7d315e81109" + +[[package]] +name = "time-macros" +version = "0.2.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e689342a48d2ea927c87ea50cabf8594854bf940e9310208848d680d668ed85" +dependencies = [ + "num-conv", + "time-core", +] + [[package]] name = "tinystr" version = "0.8.4" @@ -1812,6 +2172,7 @@ dependencies = [ "tokio", "tower-layer", "tower-service", + "tracing", ] [[package]] @@ -1850,6 +2211,7 @@ version = "0.1.44" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" dependencies = [ + "log", "pin-project-lite", "tracing-attributes", "tracing-core", @@ -1873,6 +2235,36 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" dependencies = [ "once_cell", + "valuable", +] + +[[package]] +name = "tracing-log" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee855f1f400bd0e5c02d150ae5de3840039a3f54b025156404e34c23c03f47c3" +dependencies = [ + "log", + "once_cell", + "tracing-core", +] + +[[package]] +name = "tracing-subscriber" +version = "0.3.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb7f578e5945fb242538965c2d0b04418d38ec25c79d160cd279bf0731c8d319" +dependencies = [ + "matchers", + "nu-ansi-term", + "once_cell", + "regex-automata", + "sharded-slab", + "smallvec", + "thread_local", + "tracing", + "tracing-core", + "tracing-log", ] [[package]] @@ -1960,6 +2352,12 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "valuable" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba73ea9cf16a25df0c8caa16c51acb937d5712a8429db78a3ee29d5dcacd3a65" + [[package]] name = "version_check" version = "0.9.5" diff --git a/Cargo.toml b/Cargo.toml index 4af483e..0f5ed13 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,7 @@ [workspace] members = [ "crates/ghostlight", + "crates/ghostlight-dungeon", "crates/ghostlight-persona-projection", "crates/ghostlight-verse", ] @@ -13,10 +14,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" model-connector = { git = "https://eureka.gamecult.org/forge/GameCult/ModelConnector.git", rev = "edf2f8e03cbb61df385b9b145b46f676ce3b70d5" } cultcache-rs = { git = "https://github.com/GameCult/CultLib.git", rev = "85f7024a35ea42cf9f0a0199a064526427150191", package = "cultcache-rs" } +cultnet-rs = { git = "https://github.com/GameCult/CultLib.git", rev = "85f7024a35ea42cf9f0a0199a064526427150191", package = "cultnet-rs" } +cultmesh-rs = { git = "https://github.com/GameCult/CultLib.git", rev = "85f7024a35ea42cf9f0a0199a064526427150191", package = "cultmesh-rs" } +jsonwebtoken = "9" +hmac = "0.12" +rand = "0.9" reqwest = { version = "0.12", default-features = false, features = ["json", "rustls-tls", "stream"] } rmp-serde = "1.3" serde = { version = "1", features = ["derive"] } @@ -25,6 +35,7 @@ sha2 = "0.10" thiserror = "2" tokio = { version = "1", features = ["full"] } tracing = "0.1" +tracing-subscriber = { version = "0.3", features = ["env-filter"] } unicode-segmentation = "1" uuid = { version = "1", features = ["v4", "serde"] } zeroize = "1.8" diff --git a/crates/ghostlight-dungeon/Cargo.toml b/crates/ghostlight-dungeon/Cargo.toml new file mode 100644 index 0000000..39babbb --- /dev/null +++ b/crates/ghostlight-dungeon/Cargo.toml @@ -0,0 +1,46 @@ +[package] +name = "ghostlight-dungeon" +version.workspace = true +edition.workspace = true +license.workspace = true +autobins = false + +[[bin]] +name = "ghostlight-dungeon" +path = "src/main.rs" + +[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-rs.workspace = true +model-connector.workspace = true +cultnet-rs.workspace = true +cultmesh-rs.workspace = true +jsonwebtoken.workspace = true +libc = "0.2" +hmac.workspace = true +ghostlight = { path = "../ghostlight" } +ghostlight-persona-projection = { path = "../ghostlight-persona-projection" } +rand.workspace = true +reqwest.workspace = true +rmp-serde.workspace = true +serde.workspace = true +serde_json.workspace = true +sha2.workspace = true +thiserror.workspace = true +tokio.workspace = true +tracing.workspace = true +tracing-subscriber.workspace = true +uuid.workspace = true +zeroize.workspace = true + +[dev-dependencies] +ghostlight = { path = "../ghostlight", features = ["test-support"] } +tempfile = "3" +tokio = { workspace = true, features = ["test-util"] } +tower = { version = "0.5", features = ["util"] } diff --git a/crates/ghostlight-dungeon/build.rs b/crates/ghostlight-dungeon/build.rs new file mode 100644 index 0000000..9eaf054 --- /dev/null +++ b/crates/ghostlight-dungeon/build.rs @@ -0,0 +1,65 @@ +use std::{env, path::Path, process::Command}; + +fn main() { + println!("cargo:rerun-if-env-changed=GHOSTLIGHT_BUILD_COMMIT"); + let manifest_dir = + env::var("CARGO_MANIFEST_DIR").expect("Cargo must supply CARGO_MANIFEST_DIR"); + let repo_root = Path::new(&manifest_dir).join("../.."); + emit_git_rerun_paths(&repo_root); + // Release tooling injects the clean-tree commit. Git discovery is only a + // convenience for local builds. The exact ref and reflog dependencies above + // keep that convenience from silently publishing stale provenance. + let commit = env::var("GHOSTLIGHT_BUILD_COMMIT") + .ok() + .filter(|value| is_commit(value)) + .or_else(|| git_commit(&repo_root)) + .expect("GhostlightDungeon builds require an exact 40-hex source commit"); + println!("cargo:rustc-env=GHOSTLIGHT_BUILD_COMMIT={commit}"); +} + +fn emit_git_rerun_paths(repo_root: &Path) { + for git_path in ["HEAD", "logs/HEAD", "packed-refs"] { + if let Some(path) = git_output(repo_root, &["rev-parse", "--git-path", git_path]) { + emit_rerun_path(repo_root, &path); + } + } + + if let Some(reference) = git_output(repo_root, &["symbolic-ref", "-q", "HEAD"]) + && let Some(path) = git_output(repo_root, &["rev-parse", "--git-path", &reference]) + { + emit_rerun_path(repo_root, &path); + } +} + +fn emit_rerun_path(repo_root: &Path, git_path: &str) { + let path = Path::new(git_path); + let resolved = if path.is_absolute() { + path.to_path_buf() + } else { + repo_root.join(path) + }; + println!("cargo:rerun-if-changed={}", resolved.display()); +} + +fn git_commit(repo_root: &Path) -> Option { + git_output(repo_root, &["rev-parse", "HEAD"]).filter(|value| is_commit(value)) +} + +fn git_output(repo_root: &Path, args: &[&str]) -> Option { + let output = Command::new("git") + .args(args) + .current_dir(repo_root) + .output() + .ok()?; + if !output.status.success() { + return None; + } + String::from_utf8(output.stdout) + .ok() + .map(|value| value.trim().to_owned()) + .filter(|value| !value.is_empty()) +} + +fn is_commit(value: &str) -> bool { + value.len() == 40 && value.bytes().all(|byte| byte.is_ascii_hexdigit()) +} diff --git a/crates/ghostlight-dungeon/page/index.html b/crates/ghostlight-dungeon/page/index.html new file mode 100644 index 0000000..4284902 --- /dev/null +++ b/crates/ghostlight-dungeon/page/index.html @@ -0,0 +1,25 @@ + + + + + + + +Ghostlight Dungeon + + + +
+ +
+ + + + +
+
+

Loading…

+ + + + diff --git a/crates/ghostlight-dungeon/page/page.css b/crates/ghostlight-dungeon/page/page.css new file mode 100644 index 0000000..3e098d5 --- /dev/null +++ b/crates/ghostlight-dungeon/page/page.css @@ -0,0 +1,73 @@ +/* Presentation only. Text size and theme are the two variables below. */ +:root { + --fs: 1.125rem; + --bg: #07111a; --panel: #16212c; --line: #263646; --muted: #8fa1b5; + --text: #eef5ff; --accent: #ff8a2a; --link: #59b7ff; + --bad: #ff6b5e; --badbg: #2a1614; --ok: #6fd08c; --focus: #59b7ff; + --head: Montserrat, "Segoe UI", system-ui, sans-serif; + --body: Georgia, "Iowan Old Style", "Palatino Linotype", serif; +} +:root[data-theme="light"] { + --bg: #f7f4ee; --panel: #ffffff; --line: #d8d2c4; --muted: #5d6a78; + --text: #17202a; --accent: #b4510a; --link: #0b5fa8; + --bad: #a3231a; --badbg: #fdeceb; --ok: #1d7a3c; --focus: #0b5fa8; +} +* { box-sizing: border-box; } +html { -webkit-text-size-adjust: 100%; } +body { margin: 0; background: var(--bg); color: var(--text); font: var(--fs)/1.65 var(--body); overflow-wrap: anywhere; } +.bar { position: sticky; top: 0; z-index: 5; display: flex; justify-content: space-between; align-items: center; gap: .5rem; + padding: .4rem max(.75rem, env(safe-area-inset-left)); background: var(--bg); border-bottom: 1px solid var(--line); } +.brand { white-space: nowrap; background: none; border: 0; color: var(--accent); font: 600 1.05rem var(--head); letter-spacing: .06em; text-transform: uppercase; min-height: 44px; padding: 0 .25rem; cursor: pointer; } +.tools { display: flex; gap: .2rem; justify-content: flex-end; } +.tool { background: none; border: 1px solid var(--line); color: var(--muted); font: 500 .8rem var(--head); border-radius: .5rem; min-height: 44px; min-width: 44px; padding: 0 .5rem; cursor: pointer; } +main { max-width: 44rem; margin: 0 auto; padding: .75rem max(.75rem, env(safe-area-inset-left)) 10rem; } +h1, h2 { font-family: var(--head); font-weight: 300; line-height: 1.2; margin: .5rem 0 .75rem; } +h1 { font-size: 1.6rem; } h2 { font-size: 1.25rem; } +.note, .small { color: var(--muted); font-size: .9rem; line-height: 1.5; } +a { color: var(--link); } +button, input, textarea { font: inherit; color: inherit; } +:focus-visible { outline: 3px solid var(--focus); outline-offset: 2px; } +.card { background: var(--panel); border: 1px solid var(--line); border-radius: .75rem; padding: .9rem 1rem; margin: .75rem 0; } +.row { display: flex; gap: .6rem; flex-wrap: wrap; align-items: center; } +.btn { background: var(--accent); color: #07111a; border: 0; border-radius: .6rem; min-height: 48px; padding: 0 1.1rem; font: 600 1rem var(--head); cursor: pointer; } +.btn.alt { background: none; color: var(--text); border: 1px solid var(--line); } +.btn[disabled] { opacity: .5; cursor: default; } +.btn.wide { width: 100%; } +label { display: block; font: 600 .85rem var(--head); letter-spacing: .04em; margin: 1rem 0 .3rem; color: var(--muted); text-transform: uppercase; } +input[type=text], textarea { width: 100%; background: var(--bg); border: 1px solid var(--line); border-radius: .6rem; padding: .7rem .8rem; min-height: 48px; } +textarea { resize: vertical; line-height: 1.5; } +.choice { display: flex; gap: .7rem; align-items: center; min-height: 48px; padding: .4rem .6rem; border: 1px solid var(--line); border-radius: .6rem; margin: .4rem 0; cursor: pointer; background: var(--bg); } +.choice input { width: 1.4rem; height: 1.4rem; accent-color: var(--accent); flex: none; } +.chip { font: 600 .72rem var(--head); text-transform: uppercase; letter-spacing: .06em; padding: .15rem .5rem; border-radius: 1rem; border: 1px solid var(--line); color: var(--muted); } +.chip.ready { color: var(--ok); border-color: var(--ok); } .chip.seeding { color: var(--accent); border-color: var(--accent); } .chip.failed { color: var(--bad); border-color: var(--bad); } +.tl { display: block; width: 100%; text-align: left; background: var(--panel); border: 1px solid var(--line); border-radius: .75rem; padding: .8rem 1rem; margin: .5rem 0; min-height: 56px; cursor: pointer; } +.tl.current { border-color: var(--accent); } +.tl .t { font: 600 1.05rem var(--head); display: block; } +.line { border-left: 4px solid var(--bad); background: var(--badbg); border-radius: .4rem; padding: .6rem .8rem; margin: .75rem 0; } +.line.info { border-color: var(--accent); background: var(--panel); } +.turn { margin: 1.4rem 0; } +.you { color: var(--muted); font-style: italic; border-left: 3px solid var(--line); padding-left: .8rem; margin: .8rem 0; white-space: pre-wrap; } +.story { white-space: pre-wrap; margin: 0; } +.ask { border: 1px solid var(--accent); border-radius: .6rem; padding: .6rem .8rem; margin: .8rem 0; } +.status { color: var(--muted); font: 500 .85rem var(--head); } +.pulse::after { content: ""; display: inline-block; width: .5rem; height: .5rem; margin-left: .5rem; border-radius: 50%; background: var(--accent); animation: p 1.2s ease-in-out infinite; } +@keyframes p { 50% { opacity: .2; } } +@media (prefers-reduced-motion: reduce) { .pulse::after { animation: none; } } +.bar2 { height: .4rem; background: var(--line); border-radius: .3rem; overflow: hidden; margin: .6rem 0; } +.bar2 i { display: block; height: 100%; width: 40%; background: var(--accent); animation: s 1.6s ease-in-out infinite alternate; } +@keyframes s { to { margin-left: 60%; } } +@media (prefers-reduced-motion: reduce) { .bar2 i { animation: none; width: 100%; } } +.compose { position: fixed; left: 0; right: 0; bottom: 0; background: var(--bg); border-top: 1px solid var(--line); padding: .5rem max(.75rem, env(safe-area-inset-left)) max(.5rem, env(safe-area-inset-bottom)); } +.compose .in { max-width: 44rem; margin: 0 auto; } +.compose textarea { min-height: 2.8rem; max-height: 30vh; } +.compose .row { margin-top: .4rem; } +.compose .btn { flex: 1 1 8rem; } +@media (min-width: 700px) { :root { --fs: 1.2rem; } main { padding-top: 1.25rem; } } +.blk { display: block; } .bad { color: var(--bad); } .gap { margin-top: .6rem; margin-bottom: .2rem; } +label.choice { text-transform: none; letter-spacing: 0; font: inherit; color: var(--text); margin: .4rem 0; } +.older { text-align: center; } +.older .btn { margin: .4rem 0; } +.lens { display: flex; gap: .5rem; align-items: center; padding: .35rem 0; border-bottom: 1px solid var(--line); } +.lens .what { flex: 1 1 auto; min-width: 0; } +.lens .n { min-width: 1.5rem; text-align: center; font: 600 1.05rem var(--head); } +.step { background: none; border: 1px solid var(--line); color: var(--text); border-radius: .5rem; min-width: 44px; min-height: 44px; font: 600 1.2rem var(--head); cursor: pointer; flex: none; } diff --git a/crates/ghostlight-dungeon/page/page.js b/crates/ghostlight-dungeon/page/page.js new file mode 100644 index 0000000..964b08f --- /dev/null +++ b/crates/ghostlight-dungeon/page/page.js @@ -0,0 +1,410 @@ +// Presentation only. The daemon owns every command and every fact; this page +// shows what the API returns and sends what the player types. The only state it +// keeps on the device is the unsent draft, the text size and the theme. The +// scrollback is the server's turn log, loaded on open and paged on scroll-up, +// so a reload or another device shows the same story. +"use strict"; + +const $view = document.getElementById("view"); +const LS = { + get(k) { try { return localStorage.getItem(k); } catch { return null; } }, + set(k, v) { try { if (v === null || v === "") localStorage.removeItem(k); else localStorage.setItem(k, v); } catch { /* storage may be blocked */ } }, +}; +const uuid = () => (crypto.randomUUID ? crypto.randomUUID() + : "10000000-1000-4000-8000-100000000000".replace(/[018]/g, (c) => (c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4).toString(16))); + +function el(tag, attrs, ...kids) { + const node = document.createElement(tag); + for (const [k, v] of Object.entries(attrs || {})) { + if (k === "class") node.className = v; + else if (k.startsWith("on")) node.addEventListener(k.slice(2), v); + else if (v === true) node.setAttribute(k, ""); + else if (v !== false && v != null) node.setAttribute(k, v); + } + for (const kid of kids.flat()) if (kid != null) node.append(kid); + return node; +} + +async function api(path, options) { + let response; + try { + response = await fetch("api/" + path, { credentials: "same-origin", ...options, + headers: options && options.body ? { "content-type": "application/json" } : undefined }); + } catch { + return { status: 0, body: { error: "The server could not be reached." } }; + } + let body = null; + try { body = await response.json(); } catch { body = null; } + return { status: response.status, body: body || {} }; +} +const post = (path, body) => api(path, { method: "POST", body: JSON.stringify(body) }); + +// ---- text size and theme ------------------------------------------------- +const root = document.documentElement; +function applySize(rem) { root.style.setProperty("--fs", rem + "rem"); LS.set("fs", String(rem)); } +const savedSize = parseFloat(LS.get("fs")); +if (savedSize >= 0.9 && savedSize <= 1.9) root.style.setProperty("--fs", savedSize + "rem"); +function currentSize() { return parseFloat(getComputedStyle(root).getPropertyValue("--fs")) || 1.125; } +document.getElementById("smaller").onclick = () => applySize(Math.max(0.9, +(currentSize() - 0.1).toFixed(2))); +document.getElementById("larger").onclick = () => applySize(Math.min(1.9, +(currentSize() + 0.1).toFixed(2))); +function applyTheme(name) { + if (name === "light" || name === "dark") root.dataset.theme = name; else delete root.dataset.theme; +} +applyTheme(LS.get("theme")); +document.getElementById("theme").onclick = () => { + const next = root.dataset.theme === "light" ? "dark" : "light"; + applyTheme(next); LS.set("theme", next); +}; + +// ---- state --------------------------------------------------------------- +const S = { me: null, timeline: null, history: [], older: null, live: null, echo: null, keyed: null, tailTried: null, stream: null, poll: null, signIn: null }; + +function stopLive() { + if (S.stream) { S.stream.close(); S.stream = null; } + if (S.poll) { clearTimeout(S.poll); S.poll = null; } +} +function show(...nodes) { document.querySelector(".compose")?.remove(); $view.replaceChildren(...nodes.flat()); window.scrollTo(0, 0); } +function inviteFromHash() { + const m = /(?:^#|&)invite=([A-Za-z0-9_\-]{8,200})/.exec(location.hash); + return m ? m[1] : ""; +} + +async function boot() { + stopLive(); + const { status, body } = await api("me"); + if (status !== 200) return show(el("h1", {}, "Ghostlight"), errorLine(body.error || "The server answered with an error (" + status + ")."), retryButton(boot)); + S.me = body; + document.getElementById("signout").hidden = !body.signedIn; + if (!body.signedIn) return signInView(); + if (body.currentTimeline) return openTimeline(body.currentTimeline); + return listView(); +} +function errorLine(text) { return el("p", { class: "line", role: "alert" }, text); } +function retryButton(fn) { return el("button", { class: "btn", type: "button", onclick: fn }, "Try again"); } + +// ---- sign in ------------------------------------------------------------- +function signInView(message) { + stopLive(); + const providers = (S.me && S.me.providers) || []; + const invite = el("input", { type: "text", id: "invite", autocomplete: "off", autocapitalize: "off", spellcheck: "false", value: inviteFromHash() }); + const out = el("div", {}); + if (message) out.append(errorLine(message)); + const buttons = providers.map((name) => el("button", { class: "btn wide gap", type: "button", onclick: () => beginSignIn(name, invite.value.trim(), out) }, + "Sign in with " + name[0].toUpperCase() + name.slice(1))); + show(el("h1", {}, "Sign in"), + el("p", { class: "note" }, "Only people on the allowlist can play. A first sign-in needs the invite you were given; after that, signing in is enough."), + el("div", { class: "card" }, + el("label", { for: "invite" }, "Invite (first time only)"), invite, + el("p", { class: "small" }, "A link that ends in #invite=… fills this in."), + providers.length ? buttons : el("p", { class: "line" }, "This server offers no sign-in provider.")), + out); + if (S.signIn && S.signIn.until > Date.now()) resumeSignIn(out, invite); +} + +async function beginSignIn(provider, invite, out) { + out.replaceChildren(el("p", { class: "note pulse" }, "Asking " + provider + " for a sign-in")); + const { status, body } = await post("auth/begin", invite ? { key: uuid(), provider, invite } : { key: uuid(), provider }); + if (status !== 200) return out.replaceChildren(errorLine(body.error || "Sign-in could not begin (" + status + ").")); + let target = null; + try { + const url = new URL(body.url, location.href); + if ((body.allowedOrigins || []).includes(url.origin) && url.protocol === "https:") target = url.href; + } catch { target = null; } + if (!target) return out.replaceChildren(errorLine("The sign-in address was not one this page will open.")); + S.signIn = { handle: body.handle, target, until: Date.now() + 9 * 60 * 1000 }; + window.open(target, "_blank", "noopener"); + resumeSignIn(out); +} + +async function resumeSignIn(out) { + const attempt = S.signIn; + out.replaceChildren( + el("p", { class: "note pulse" }, "Waiting for you to finish signing in on the other tab."), + el("p", {}, el("a", { href: attempt.target, target: "_blank", rel: "noopener noreferrer" }, "Open the sign-in page again"))); + while (S.signIn === attempt && Date.now() < attempt.until) { + await new Promise((r) => setTimeout(r, 2500)); + if (S.signIn !== attempt) return; + const { status, body } = await post("auth/complete", { handle: attempt.handle, key: uuid() }); + if (status === 202) continue; + S.signIn = null; + if (status === 200 && body.status === "authenticated") { history.replaceState(null, "", location.pathname); return boot(); } + if (status === 429) return out.replaceChildren(errorLine(body.error || "Too many attempts; wait a minute.")); + return out.replaceChildren(errorLine(body.error || "Sign-in was refused (" + status + ").")); + } + if (S.signIn === attempt) { S.signIn = null; out.replaceChildren(errorLine("The sign-in expired. Start again.")); } +} + +document.getElementById("signout").onclick = async () => { + stopLive(); + const { status, body } = await post("auth/logout", {}); + if (status !== 200) return show(errorLine(body.error || "Sign-out was not confirmed."), retryButton(boot)); + S.history = []; S.timeline = null; + boot(); +}; +document.getElementById("home").onclick = () => { if (S.me && S.me.signedIn) listView(); }; + +// ---- timelines ----------------------------------------------------------- +async function listView() { + stopLive(); + S.timeline = null; + const { status, body } = await api("timelines"); + if (status === 401) return boot(); + if (status !== 200) return show(el("h1", {}, "Your worlds"), errorLine(body.error || "Could not list your worlds."), retryButton(listView)); + const rows = body.timelines || []; + const seeding = rows.some((r) => r.status === "seeding"); + show(el("h1", {}, "Your worlds"), + el("button", { class: "btn wide", type: "button", onclick: beginView }, "Begin a new world"), + rows.length ? rows.map(timelineRow) : el("p", { class: "note" }, "No worlds yet."), + el("p", { class: "small" }, "Each fork of a world is its own timeline. Older timelines stay.")); + if (seeding) S.poll = setTimeout(listView, 4000); +} +function timelineRow(row) { + const when = row.createdAt ? new Date(row.createdAt).toLocaleString() : ""; + return el("button", { class: "tl" + (row.current ? " current" : ""), type: "button", onclick: () => openTimeline(row.timeline) }, + el("span", { class: "t" }, row.title || "Untitled"), + el("span", { class: "chip " + row.status }, row.status), " ", + row.parent ? el("span", { class: "small" }, " fork") : "", + el("span", { class: "small blk" }, (row.current ? "Current. " : "") + when), + row.status === "failed" ? el("span", { class: "small blk bad" }, row.reason || "Seeding failed.") : ""); +} + +// ---- begin --------------------------------------------------------------- +let beginKey = null; +async function beginView() { + stopLive(); + beginKey = beginKey || uuid(); + const { status, body } = await api("vaults"); + if (status === 401) return boot(); + const vaults = status === 200 ? body.vaults || [] : []; + const msg = el("div", {}); + if (status !== 200) msg.append(errorLine(body.error || "The lore list could not be read.")); + const lenses = status === 200 ? body.lenses || [] : []; + let vault = vaults.length ? vaults[0].name : ""; + let era = null; + // The era picker follows the vault choice; a vault with one era offers none. + const eraBox = el("div", {}); + const drawEras = () => { + const chosen = vaults.find((v) => v.name === vault); + era = chosen ? chosen.default_era : null; + eraBox.replaceChildren(...(chosen && chosen.eras.length > 1 ? [el("label", {}, "Era"), + ...chosen.eras.map((e) => el("label", { class: "choice" }, + el("input", { type: "radio", name: "era", value: e.id, checked: e.id === era, onchange: () => { era = e.id; } }), + el("span", {}, e.label, el("span", { class: "small blk" }, e.description))))] : [])); + }; + const choices = vaults.map((v, i) => el("label", { class: "choice" }, + el("input", { type: "radio", name: "vault", value: v.name, checked: i === 0, onchange: () => { vault = v.name; drawEras(); } }), v.name)); + drawEras(); + // Each lens weighs what the world reaches for: 0 never, 5 most. + const weights = Object.fromEntries(lenses.map((l) => [l.id, 1])); + const lensRows = lenses.map((l) => { + const shown = el("span", { class: "n", "aria-live": "polite" }, "1"); + const step = (by) => { weights[l.id] = Math.max(0, Math.min(5, weights[l.id] + by)); shown.textContent = String(weights[l.id]); }; + return el("div", { class: "lens" }, + el("span", { class: "what" }, el("b", {}, l.name), el("span", { class: "small blk" }, l.reaches_for)), + el("button", { class: "step", type: "button", "aria-label": "Less " + l.name, onclick: () => step(-1) }, "−"), shown, + el("button", { class: "step", type: "button", "aria-label": "More " + l.name, onclick: () => step(1) }, "+")); + }); + const title = el("input", { type: "text", id: "title", autocomplete: "off", value: LS.get("begin-title") || "" }); + const name = el("input", { type: "text", id: "name", autocomplete: "off", value: LS.get("begin-name") || "" }); + const brief = el("textarea", { id: "brief", rows: "3" }); + const go = el("button", { class: "btn wide gap", type: "button" }, "Begin"); + go.onclick = async () => { + if (!title.value.trim() || !name.value.trim()) return msg.replaceChildren(errorLine("A world needs a title and your name in it.")); + go.disabled = true; msg.replaceChildren(el("p", { class: "note pulse" }, "Starting the world")); + const { status: s, body: b } = await post("begin", { key: beginKey, title: title.value.trim(), name: name.value.trim(), brief: brief.value.trim() || null, vault: vault || null, era: vault ? era : null, lenses: lenses.length ? weights : null }); + go.disabled = false; + if (s === 200) { beginKey = null; LS.set("begin-title", title.value.trim()); LS.set("begin-name", name.value.trim()); return openTimeline(b.timeline); } + const unknown = b.outcome === "unknown" || s === 0; + msg.replaceChildren(errorLine((b.error || "The world could not begin (" + s + ").") + (b.step ? " (step: " + b.step + ")" : "") + + (unknown ? " The outcome is unknown: check Your worlds before beginning again. Pressing Begin again is safe; it carries the same request key." : ""))); + }; + show(el("h1", {}, "Begin a world"), + el("label", {}, "1. Lore"), + vaults.length ? choices : el("p", { class: "line info" }, "No vault has been imported on this server, so a world would start with no lore. Ask the host to import one."), + eraBox, + el("label", { for: "title" }, "2. Name the world"), title, + el("label", { for: "name" }, "3. What you are called in it"), name, + el("label", { for: "brief" }, "4. Anything the storyteller should know (optional)"), brief, + lenses.length ? [el("label", {}, "5. What the world reaches for"), ...lensRows] : "", + go, msg, + el("p", { class: "small" }, "A world seeded from lore takes a few minutes. You can leave this page; it carries on.")); +} + +// ---- play ---------------------------------------------------------------- +// The scrollback is the server's turn log: S.history holds the entries fetched +// so far (oldest first), S.live the open turn's view from the stream. Nothing +// here is kept on the device but the unsent draft. +async function openTimeline(id) { + stopLive(); + S.timeline = id; S.history = []; S.older = null; S.live = null; S.echo = null; S.keyed = null; S.tailTried = null; + const { status, body } = await api("timelines"); + if (status !== 200) return show(errorLine(body.error || "Could not open that world."), retryButton(() => openTimeline(id))); + const row = (body.timelines || []).find((r) => r.timeline === id); + if (!row) return listView(); + if (row.status === "seeding") { + show(el("h1", {}, row.title), el("p", { class: "status pulse" }, "Seeding the world from the lore"), + el("div", { class: "bar2" }, el("i", {})), + el("p", { class: "note" }, "Elaborators are writing the people and places. You can leave and come back; this updates by itself.")); + S.poll = setTimeout(() => openTimeline(id), 4000); + return; + } + if (row.status === "failed") { + return show(el("h1", {}, row.title), errorLine("Seeding failed: " + (row.reason || "no reason was recorded.")), + el("button", { class: "btn", type: "button", onclick: beginView }, "Begin another world")); + } + playView(row); +} + +let $log, $status, $text, $send, $retryRow, $older; +async function playView(row) { + const id = S.timeline; + $older = el("div", { class: "older small" }); + $log = el("div", { id: "log" }); + $status = el("p", { class: "status", role: "status" }); + $retryRow = el("div", { class: "row" }); + show(el("h1", {}, row.title), $older, $log, $status, $retryRow); + $text = el("textarea", { id: "say", rows: "2", "aria-label": "What do you do?", placeholder: "What do you do? (Empty Send carries on an unfinished turn.)" }); + $text.value = LS.get("draft:" + id) || ""; + $text.addEventListener("input", () => LS.set("draft:" + id, $text.value)); + $send = el("button", { class: "btn", type: "button", onclick: () => send($text.value) }, "Send"); + document.body.append(el("div", { class: "compose" }, el("div", { class: "in" }, $text, el("div", { class: "row" }, $send, + el("button", { class: "btn alt", type: "button", title: "Carry on an unfinished turn", onclick: () => send("") }, "Continue")) + ))); + const ok = await loadHistory(null); + if (S.timeline !== id) return; + if (ok) window.scrollTo(0, document.documentElement.scrollHeight); + connect(); +} + +// Reads one page of the log. `before` null reads the newest page and merges it +// into what is held; a number reads the page older than that entry. +async function loadHistory(before) { + const id = S.timeline; + const { status, body } = await api("history/" + encodeURIComponent(id) + (before ? "?before=" + before : "")); + if (S.timeline !== id) return false; + if (status !== 200) { + $older.replaceChildren(errorLine(body.error || "The earlier turns could not be loaded."), retryButton(() => loadHistory(before))); + return false; + } + const first = !S.history.length; + const have = new Map(S.history.map((e) => [e.seq, e])); + for (const entry of body.entries || []) have.set(entry.seq, entry); + S.history = [...have.values()].sort((a, b) => a.seq - b.seq); + // Only a read at the old edge moves the edge; a refresh of the newest page leaves it. + if (before || first) S.older = body.older; + render(); + return true; +} + +let loadingOlder = false; +window.addEventListener("scroll", async () => { + if (!S.timeline || !$log || !S.older || loadingOlder || window.scrollY > 160) return; + loadingOlder = true; + const height = document.documentElement.scrollHeight; + if (await loadHistory(S.older)) window.scrollTo(0, window.scrollY + document.documentElement.scrollHeight - height); + loadingOlder = false; +}, { passive: true }); + +function connect() { + const id = S.timeline; + if (S.stream) S.stream.close(); + const stream = new EventSource("api/turn/" + encodeURIComponent(id) + "/stream"); + S.stream = stream; + stream.addEventListener("turn", (event) => { if (S.timeline === id) { try { onTurn(JSON.parse(event.data)); } catch { /* ignore a torn event */ } } }); + stream.onerror = () => { if (S.timeline === id && $status) $status.textContent = "Reconnecting…"; }; +} +document.addEventListener("visibilitychange", async () => { + if (document.hidden || !S.timeline || !$log) return; + const { status, body } = await api("turn/" + encodeURIComponent(S.timeline)); + if (status === 200 && body.timeline === S.timeline) onTurn(body); + if (S.stream && S.stream.readyState === 2) connect(); +}); + +// Whether the log already holds what the open turn shows. +function logged(turn) { + return S.history.some((e) => e.turn_id === turn.id && + (turn.state === "awaiting_player" ? e.status === "asked" && turn.question && e.question === turn.question.text : e.status !== "asked")); +} + +async function onTurn(view) { + const turn = view.turn; + S.live = turn; + if (S.echo && (!turn || turn.revision !== S.echo.revision)) S.echo = null; + render(); + if (turn && turn.state !== "running" && !logged(turn)) { + const mark = turn.id + ":" + turn.revision; + if (S.tailTried !== mark) { S.tailTried = mark; await loadHistory(null); } + } +} + +function render() { + const nearBottom = window.innerHeight + window.scrollY >= document.documentElement.scrollHeight - 240; + const turn = S.live; + $older.replaceChildren(S.older ? el("button", { class: "btn alt", type: "button", onclick: () => loadHistory(S.older) }, "Load earlier turns") : ""); + const nodes = S.history.map(entryNode); + const running = turn && turn.state === "running"; + if (running || S.echo) { + const text = running ? turn.text : S.echo.text; + nodes.push(el("section", { class: "turn" }, text ? el("p", { class: "you" }, text) : "")); + } + if (!nodes.length) nodes.push(el("p", { class: "note" }, "The world is ready. Say what you do.")); + $log.replaceChildren(...nodes); + $retryRow.replaceChildren(); + $status.className = "status"; + $status.textContent = ""; + if (running) { + if (turn.resolving) { $status.className = "status pulse"; $status.textContent = "The storyteller is resolving your turn"; } + else $status.textContent = turn.continue_hint || "This turn is unfinished."; + } else if (S.echo) { + $status.className = "status pulse"; $status.textContent = "Sent"; + } else if (turn && turn.state === "awaiting_player") { + $status.textContent = "The storyteller is waiting for your answer."; + } + const last = S.history[S.history.length - 1]; + if (last && !running && !S.echo && turn && logged(turn)) { + if (last.status === "faulted" && !last.superseded_by) { + $retryRow.append( + el("button", { class: "btn", type: "button", onclick: () => send(last.text, last.seq) }, "Retry"), + el("button", { class: "btn alt", type: "button", onclick: () => editAgain(last.text) }, "Edit and resend")); + } else if (last.status === "refused") { + $retryRow.append(el("button", { class: "btn alt", type: "button", onclick: () => editAgain(last.text) }, "Edit and resend")); + } + } + if (nearBottom) window.scrollTo(0, document.documentElement.scrollHeight); +} + +function entryNode(entry) { + const parts = []; + if (entry.text) parts.push(el("p", { class: "you" }, entry.text)); + if (entry.narration) parts.push(el("p", { class: "story" }, entry.narration)); + if (entry.refusal) parts.push(el("p", { class: "line", role: "alert" }, entry.refusal)); + if (entry.fault) parts.push(el("p", { class: "line", role: "alert" }, entry.fault)); + if (entry.superseded_by) parts.push(el("p", { class: "small" }, "Sent again below.")); + if (entry.question) parts.push(el("div", { class: "ask" }, el("strong", {}, "The storyteller asks"), el("p", { class: "story" }, entry.question))); + return el("section", { class: "turn" }, parts); +} + +function editAgain(text) { $text.value = text; LS.set("draft:" + S.timeline, text); $text.focus(); } + +async function send(text, retryOf) { + if (!S.timeline) return; + const turn = S.live; + const answers = turn && turn.state === "awaiting_player" && turn.question ? turn.question.token : null; + // The same text resent after a lost reply reuses its key, so it cannot play twice. + if (!S.keyed || S.keyed.text !== text || retryOf) S.keyed = { text, key: uuid() }; + $send.disabled = true; + // The echo is placed before the request: the stream can deliver the new turn before the reply returns. + if (text) { S.echo = { text, revision: turn ? turn.revision : null }; render(); } + const { status, body } = await post("play", { timeline: S.timeline, key: S.keyed.key, text, answers, retry_of: retryOf || null }); + $send.disabled = false; + if (status === 202 || status === 200) { + S.keyed = null; + $text.value = ""; LS.set("draft:" + S.timeline, ""); + if (!text) { $status.className = "status pulse"; $status.textContent = "Sent"; } + return; + } + S.echo = null; render(); + $retryRow.replaceChildren(errorLine(status === 0 ? "The server could not be reached. Your text is kept; Send resends it safely." : (body.error || "The turn was refused (" + status + ")."))); +} + +boot(); diff --git a/crates/ghostlight-dungeon/src/api.rs b/crates/ghostlight-dungeon/src/api.rs new file mode 100644 index 0000000..96c89eb --- /dev/null +++ b/crates/ghostlight-dungeon/src/api.rs @@ -0,0 +1,2198 @@ +//! The Deru API: JSON over HTTPS behind the Heimdall session cookie. +//! +//! Handlers hold no game state and call no model. They read the catalog and +//! the turn record, and every command goes through `begin` or +//! `PlayTable::admit`/`execute`, the only writers. + +use crate::{ + auth_guard::{BEGIN_COOKIE, BEGIN_TTL_SECONDS}, + heimdall::AuthBeginReceipt, + begin::{BeginRequest, begin}, + catalog::SeedStatus, + run_ahead::{evidence_of, run_ahead}, + play::{Admission, OpenQuestion, PlayError, PlayRequest, PlayTurnState, PlayTurnView}, + runtime::AppState, +}; +use axum::{ + Json, Router, + extract::{DefaultBodyLimit, Path, Query, State}, + http::{HeaderMap, HeaderValue, StatusCode, header}, + response::{ + IntoResponse, Response, + sse::{Event as SseEvent, KeepAlive, Sse}, + }, + routing::{get, post}, +}; +use chrono::{DateTime, Utc}; +use ghostlight::{CommandId, Lens, VerifiedPrincipalEvidence, WorldPhase}; +use serde::Deserialize; +use serde_json::{Value, json}; +use std::{convert::Infallible, time::Duration}; +use tokio::sync::broadcast; + +pub(crate) const COOKIE_NAME: &str = "ghostlight_session"; +const BODY_LIMIT: usize = 64 * 1024; + +/// What a player sees of a turn that died on its model: one fixed line. The +/// fault's own detail stays in the store and the log. +pub(crate) const PLAY_FAULT_LINE: &str = + "The storyteller lost the thread and your turn ended. Write again to start a new turn."; + +const CONTINUE_HINT: &str = + "Your last turn did not finish. If nothing arrives, submit an empty message to continue it."; + +pub(crate) fn router() -> Router { + Router::new() + .route("/api/me", get(me)) + .route("/api/timelines", get(timelines)) + .route("/api/vaults", get(vaults)) + .route("/api/begin", post(begin_world)) + .route("/api/play", post(play)) + .route("/api/turn/{timeline}", get(turn)) + .route("/api/turn/{timeline}/stream", get(turn_stream)) + .route("/api/history/{timeline}", get(history)) + .route("/api/auth/begin", post(auth_begin)) + .route("/api/auth/complete", post(auth_complete)) + .route("/api/auth/logout", post(auth_logout)) + .layer(DefaultBodyLimit::max(BODY_LIMIT)) +} + +fn reply(status: StatusCode, body: Value) -> Response { + (status, Json(body)).into_response() +} + +fn refuse(status: StatusCode, message: impl std::fmt::Display) -> Response { + reply(status, json!({"error": message.to_string()})) +} + +fn unauthorized() -> Response { + refuse(StatusCode::UNAUTHORIZED, "sign in first") +} + +/// The refusal of a play on a world that is not Active: 409 with the status +/// the page shows (`seeding`, `failed` with its reason, or `draft`). +fn unplayable(status: &str, reason: Option<&str>) -> Response { + let error = match status { + "seeding" => "this world is still being seeded", + "failed" => "this world's seed did not finish", + _ => "this world is not active yet", + }; + reply(StatusCode::CONFLICT, json!({"error": error, "status": status, "reason": reason})) +} + +/// The turn as the player sees it: narration, the open question, the refusal +/// of their own act and the fault line. It is derived from the turn record +/// and is display-only; nothing reads it back. +pub(crate) fn turn_view_json(timeline: &str, view: Option<&PlayTurnView>) -> Value { + let Some(view) = view else { + return json!({"timeline": timeline, "turn": null}); + }; + let question = view.question.as_ref().map(|question: &OpenQuestion| { + json!({"text": question.text, "token": question.token}) + }); + json!({ + "timeline": timeline, + "turn": { + "id": view.turn_id, + "state": match view.state { + PlayTurnState::Running => "running", + PlayTurnState::AwaitingPlayer => "awaiting_player", + PlayTurnState::Closed => "closed", + }, + "revision": view.revision, + "narration": view.narration, + "question": question, + "refusal": view.refusal, + "fault": view.fault.then_some(PLAY_FAULT_LINE), + "text": view.player_text, + "resolving": view.run_in_progress, + "continue_hint": (view.state == PlayTurnState::Running && !view.run_in_progress) + .then_some(CONTINUE_HINT), + } + }) +} + +/// The one door an answer's token is judged by: admits only when both sides +/// are present and equal. An unminted token never matches anything. +fn answer_token_admits(given: Option<&str>, expected: Option<&str>) -> bool { + matches!((given, expected), (Some(given), Some(expected)) if given == expected) +} + +pub(crate) fn cookie_value(headers: &HeaderMap) -> Option<&str> { + named_cookie(headers, COOKIE_NAME) +} + +fn named_cookie<'a>(headers: &'a HeaderMap, name: &str) -> Option<&'a str> { + let prefix = format!("{name}="); + headers + .get(header::COOKIE)? + .to_str() + .ok()? + .split(';') + .map(str::trim) + .find_map(|cookie| cookie.strip_prefix(&prefix)) +} + +fn session_cookie(raw: &str, expires_at: DateTime, now: DateTime) -> HeaderValue { + HeaderValue::from_str(&format!( + "{COOKIE_NAME}={raw}; Max-Age={}; HttpOnly; Secure; SameSite=Lax; Path=/ghostlight/", + (expires_at - now).num_seconds().max(0) + )) + .expect("generated session cookie must be valid") +} + +pub(crate) fn signal_fatal(state: &AppState, organ: &str, error: &impl std::fmt::Display) { + let detail = format!("{organ}: {error}"); + tracing::error!(%detail, "runtime owner can no longer uphold its invariant"); + let _ = state.fatal.send(detail); +} + +async fn authenticated_principal( + headers: &HeaderMap, + state: &AppState, +) -> Option { + let raw = cookie_value(headers)?; + match state + .sessions + .lock() + .await + .account_for_cookie(raw, Utc::now()) + { + Ok(account) => account, + Err(error) => { + signal_fatal(state, "app-session custody", &error); + None + } + } +} + +/// The sign-in providers this daemon offers, for the page's buttons. +fn offered_providers(state: &AppState) -> Vec<&'static str> { + ["discord", "google", "twitch"] + .into_iter() + .filter(|name| state.heimdall.offered(name).is_some()) + .collect() +} + +async fn me(headers: HeaderMap, State(state): State) -> Response { + let providers = offered_providers(&state); + let Some(principal) = authenticated_principal(&headers, &state).await else { + return reply(StatusCode::OK, json!({"signedIn": false, "providers": providers})); + }; + let catalog = state.catalog.lock().await; + let player = catalog.player(principal.account_subject_hash()); + reply( + StatusCode::OK, + json!({ + "signedIn": true, + "providers": providers, + "currentTimeline": player.and_then(|player| player.timeline.as_deref()), + "destination": player.and_then(|player| player.destination.as_deref()), + }), + ) +} + +async fn timelines(headers: HeaderMap, State(state): State) -> Response { + let Some(principal) = authenticated_principal(&headers, &state).await else { + return unauthorized(); + }; + let account = principal.account_subject_hash(); + let catalog = state.catalog.lock().await; + let current = catalog.player(account).and_then(|player| player.timeline.clone()); + let rows: Vec = catalog + .timelines_of(account) + .into_iter() + .map(|(timeline, world)| { + let (status, reason) = match catalog.seed_status(&timeline.id) { + None => ("ready", None), + Some(SeedStatus::Seeding) => ("seeding", None), + Some(SeedStatus::Failed(reason)) => ("failed", Some(reason.as_str())), + }; + json!({ + "timeline": timeline.id, + "status": status, + "reason": reason, + "worldId": world.world_id, + "title": world.title, + "parent": timeline.parent, + "snapshotId": world.snapshot_id, + "createdAt": world.created_at, + "current": current.as_deref() == Some(timeline.id.as_str()), + }) + }) + .collect(); + reply(StatusCode::OK, json!({"timelines": rows})) +} + +async fn vaults(headers: HeaderMap, State(state): State) -> Response { + if authenticated_principal(&headers, &state).await.is_none() { + return unauthorized(); + } + let vaults: Vec<_> = state + .vaults + .offers() + .into_iter() + .map(|offer| json!({"name": offer.name, "default_era": offer.default_era, "eras": offer.eras.iter().map(|era| json!({"id": era.id, "label": era.label, "description": era.description})).collect::>()})) + .collect(); + let lenses: Vec<_> = Lens::ALL + .into_iter() + .map(|lens| json!({"id": lens, "name": lens.name(), "reaches_for": lens.reaches_for()})) + .collect(); + reply(StatusCode::OK, json!({"vaults": vaults, "lenses": lenses})) +} + +#[derive(Debug, Deserialize)] +#[serde(deny_unknown_fields)] +struct BeginBody { + key: String, + title: String, + name: String, + #[serde(default)] + brief: Option, + #[serde(default)] + vault: Option, + #[serde(default)] + era: Option, + /// Lens id (snake_case) to weight; omitted is every lens at one. + #[serde(default)] + lenses: Option>, +} + +async fn begin_world( + headers: HeaderMap, + State(state): State, + Json(body): Json, +) -> Response { + let Some(principal) = authenticated_principal(&headers, &state).await else { + return unauthorized(); + }; + let outcome = begin( + &state.catalog, + &state.timelines, + state.vaults.as_ref(), + &state.scale, + &principal, + BeginRequest { + key: body.key, + title: body.title, + name: body.name, + brief: body.brief, + vault: body.vault, + era: body.era, + lenses: body.lenses, + }, + ) + .await; + match outcome { + Ok(begun) => reply( + StatusCode::OK, + json!({"timeline": begun.timeline, "reached": begun.reached}), + ), + Err(error) if error.unknown => reply( + StatusCode::INTERNAL_SERVER_ERROR, + json!({"error": error.to_string(), "outcome": "unknown"}), + ), + Err(error) => reply( + StatusCode::CONFLICT, + json!({"error": error.to_string(), "step": error.step}), + ), + } +} + +#[derive(Debug, Deserialize)] +#[serde(deny_unknown_fields)] +struct PlayBody { + timeline: String, + key: String, + text: String, + /// The token of the question this text answers, as the turn view showed it. + #[serde(default)] + answers: Option, + /// The log entry (`seq`) this text retries. The new entry names it; the + /// old one stays. + #[serde(default)] + retry_of: Option, +} + +async fn play( + headers: HeaderMap, + State(state): State, + Json(body): Json, +) -> Response { + let Some(principal) = authenticated_principal(&headers, &state).await else { + return unauthorized(); + }; + if CommandId::parse_uuid(&body.key).is_err() { + return refuse(StatusCode::BAD_REQUEST, "the play key is not a uuid"); + } + let account = principal.account_subject_hash().to_owned(); + { + let mut catalog = state.catalog.lock().await; + if catalog.owned_timeline(&account, &body.timeline).is_none() { + return refuse(StatusCode::NOT_FOUND, "no such timeline"); + } + match catalog.seed_status(&body.timeline) { + Some(SeedStatus::Seeding) => return unplayable("seeding", None), + Some(SeedStatus::Failed(reason)) => return unplayable("failed", Some(reason.as_str())), + None => {} + } + let current = catalog.player(&account).and_then(|player| player.timeline.as_deref()); + if current != Some(body.timeline.as_str()) + && let Err(error) = catalog.set_current(&account, &body.timeline) + { + tracing::warn!(%error, "the player's pointer could not move"); + } + } + let timeline = body.timeline.clone(); + let host = match state.timelines.host(&body.timeline).await { + Ok(host) => host, + Err(error) => { + tracing::error!(%error, timeline = %body.timeline, "the timeline could not open"); + return refuse(StatusCode::INTERNAL_SERVER_ERROR, "the timeline could not open"); + } + }; + // The seed's status explains a refusal; the world's phase is what decides + // it, so a Draft with no recorded seed is not playable either. + match host.world.snapshot().await { + Ok(world) if world.phase == WorldPhase::Active => {} + Ok(_) => return unplayable("draft", None), + Err(error) => { + tracing::error!(%error, timeline = %body.timeline, "the world could not be read"); + return refuse(StatusCode::INTERNAL_SERVER_ERROR, "the timeline could not open"); + } + } + // The server resolves the open question itself; the client proves it saw + // it by its token. A token with no open question, or not that question's, + // is stale and never reaches the table. + let view = host.play.current_turn_view().await; + let awaiting = view + .as_ref() + .is_some_and(|view| view.state == PlayTurnState::AwaitingPlayer); + if body.answers.is_some() && !awaiting { + return refuse(StatusCode::CONFLICT, "that question is closed"); + } + let answers = match view + .as_ref() + .and_then(|view| view.question.as_ref()) + .filter(|_| awaiting) + { + None => None, + Some(question) => { + if !answer_token_admits(body.answers.as_deref(), question.token.as_deref()) { + return refuse( + StatusCode::CONFLICT, + format!( + "the answer is stale: its token does not name the question \"{}\" currently open", + question.text + ), + ); + } + Some(question.id.clone()) + } + }; + if let Some(seq) = body.retry_of + && !host.play.logged(seq).await + { + return refuse(StatusCode::CONFLICT, "that turn is not in the history"); + } + let retry_of = body.retry_of; + let admission = match host + .play + .admit(body.key, PlayRequest { text: body.text, answers }) + .await + { + Ok(admission) => admission, + Err( + error @ (PlayError::Poisoned + | PlayError::World(_) + | PlayError::Controller(_) + | PlayError::Store(_)), + ) => { + tracing::error!(%error, "a play turn could not be admitted"); + return refuse(StatusCode::INTERNAL_SERVER_ERROR, "the storyteller could not take that turn"); + } + Err(error) => return refuse(StatusCode::CONFLICT, error), + }; + let admitted = match admission { + Admission::Replayed { .. } => return reply(StatusCode::OK, json!({"outcome": "replayed"})), + Admission::Spawn(admitted) => admitted, + }; + if let Some(seq) = retry_of { + host.play.note_retry(&admitted, seq); + } + let _ = host.changes.send(()); + let spawned = host.clone(); + let state = state.clone(); + tokio::spawn(async move { + let ran = spawned.play.execute(admitted, &principal).await; + if let Err(error) = &ran { + let turn_id = spawned.play.current_turn_view().await.map(|view| view.turn_id); + tracing::warn!(%error, ?turn_id, "a play turn ended in error"); + } + let _ = spawned.changes.send(()); + // The turn is closed: answer some of the world's deficit ahead of play. + let closed = ran.is_ok() + && spawned + .play + .current_turn_view() + .await + .is_some_and(|view| view.state == PlayTurnState::Closed); + if closed + && let Some(evidence) = evidence_of(&state.catalog, state.vaults.as_ref(), &spawned, &timeline).await + { + run_ahead(&spawned, evidence, &state.scale).await; + } + }); + reply(StatusCode::ACCEPTED, json!({"outcome": "accepted"})) +} + +/// The host of a timeline the caller owns, or the refusal to send. +async fn owned_host( + headers: &HeaderMap, + state: &AppState, + timeline: &str, +) -> Result, Response> { + let Some(principal) = authenticated_principal(headers, state).await else { + return Err(unauthorized()); + }; + if state + .catalog + .lock() + .await + .owned_timeline(principal.account_subject_hash(), timeline) + .is_none() + { + return Err(refuse(StatusCode::NOT_FOUND, "no such timeline")); + } + state.timelines.host(timeline).await.map_err(|error| { + tracing::error!(%error, timeline, "the timeline could not open"); + refuse(StatusCode::INTERNAL_SERVER_ERROR, "the timeline could not open") + }) +} + +async fn turn( + Path(timeline): Path, + headers: HeaderMap, + State(state): State, +) -> Response { + match owned_host(&headers, &state, &timeline).await { + Ok(host) => { + let view = host.play.current_turn_view().await; + reply(StatusCode::OK, turn_view_json(&timeline, view.as_ref())) + } + Err(response) => response, + } +} + + +#[derive(Debug, Deserialize)] +struct HistoryQuery { + /// Read the entries older than this `seq`; the newest page when absent. + before: Option, + limit: Option, +} + +const HISTORY_PAGE: usize = 30; +const HISTORY_PAGE_MAX: usize = 100; + +/// The signed-in account's own turn log for one timeline, a page at a time, +/// oldest first so the newest entry is last. `owned_host` refuses any +/// timeline the account does not own, so another account's log is unreachable. +async fn history( + Path(timeline): Path, + Query(query): Query, + headers: HeaderMap, + State(state): State, +) -> Response { + let host = match owned_host(&headers, &state, &timeline).await { + Ok(host) => host, + Err(response) => return response, + }; + let limit = query.limit.unwrap_or(HISTORY_PAGE).clamp(1, HISTORY_PAGE_MAX); + let page = match host.play.history(query.before, limit).await { + Ok(page) => page, + Err(error) => { + tracing::error!(%error, %timeline, "the turn log could not be read"); + return refuse(StatusCode::INTERNAL_SERVER_ERROR, "the turn history could not be read"); + } + }; + let entries: Vec = page + .entries + .into_iter() + .map(|(entry, superseded_by)| { + let mut value = serde_json::to_value(entry).expect("a log entry is plain data"); + value["superseded_by"] = json!(superseded_by); + value + }) + .collect(); + reply(StatusCode::OK, json!({"timeline": timeline, "entries": entries, "older": page.older})) +} + +async fn turn_stream( + Path(timeline): Path, + headers: HeaderMap, + State(state): State, +) -> Response { + let host = match owned_host(&headers, &state, &timeline).await { + Ok(host) => host, + Err(response) => return response, + }; + // Subscribe before the first read so a change between the two is not lost. + let mut changes = host.changes.subscribe(); + let stream = async_stream::stream! { + let mut last: Option = None; + loop { + let view = host.play.current_turn_view().await; + let json = turn_view_json(&timeline, view.as_ref()).to_string(); + if last.as_deref() != Some(json.as_str()) { + yield Ok::(SseEvent::default().event("turn").data(json.clone())); + last = Some(json); + } + tokio::select! { + woke = changes.recv() => match woke { + Ok(()) | Err(broadcast::error::RecvError::Lagged(_)) => {} + Err(broadcast::error::RecvError::Closed) => break, + }, + // A wake can be missed across a restart of the browser's own + // connection; re-reading is cheap. + _ = tokio::time::sleep(Duration::from_secs(15)) => {} + } + } + }; + Sse::new(stream).keep_alive(KeepAlive::default()).into_response() +} + +#[derive(Debug, Deserialize)] +#[serde(deny_unknown_fields)] +struct AuthBeginBody { + key: String, + /// One of the providers the daemon offers (`GHOSTLIGHT_AUTH_PROVIDERS`). + provider: String, + /// The invite the browser presents for a first sign-in, if any. Checked + /// against the catalog now, bound to this attempt, spent at complete. + #[serde(default)] + invite: Option, +} + +/// The throttle's key: the address nginx sets in `X-Real-IP`. Behind the proxy +/// the TCP peer is always loopback, so it names no one. +fn client_key(headers: &HeaderMap) -> &str { + headers + .get("x-real-ip") + .and_then(|value| value.to_str().ok()) + .map(str::trim) + .filter(|value| !value.is_empty()) + .unwrap_or("direct") +} + +fn throttled() -> Response { + refuse(StatusCode::TOO_MANY_REQUESTS, "too many sign-in requests; wait a minute") +} + +fn begin_cookie(secret: &str, max_age: i64) -> HeaderValue { + HeaderValue::from_str(&format!( + "{BEGIN_COOKIE}={secret}; Max-Age={max_age}; HttpOnly; Secure; SameSite=Lax; Path=/ghostlight/" + )) + .expect("generated begin cookie must be valid") +} + +/// A pending Heimdall attempt's expiry, or `None` for a receipt that is not a +/// live pending attempt. +fn pending_expiry(receipt: &AuthBeginReceipt, now: DateTime) -> Option> { + let expiry = receipt.expires_at.parse::>().ok()?; + (receipt.status == "pending" && !receipt.handle.is_empty() && expiry > now).then_some(expiry) +} + +async fn auth_begin( + headers: HeaderMap, + State(state): State, + Json(body): Json, +) -> Response { + let now = Utc::now(); + if !state.auth.allow(client_key(&headers), now) { + return throttled(); + } + let Some(provider) = state.heimdall.offered(&body.provider) else { + return refuse(StatusCode::BAD_REQUEST, "that sign-in provider is not offered"); + }; + let invite = body.invite.map(|token| token.trim().to_owned()).filter(|token| !token.is_empty()); + if let Some(token) = &invite + && !state.catalog.lock().await.invite_is_live(token, now) + { + return refuse(StatusCode::FORBIDDEN, "that invite is spent or expired"); + } + let receipt = match state.heimdall.begin(provider, invite.is_some(), &body.key).await { + Ok(receipt) => receipt, + Err(error) => { + tracing::warn!(%error, "Heimdall refused to begin a sign-in"); + return refuse(StatusCode::BAD_GATEWAY, "Heimdall could not begin the sign-in."); + } + }; + let Some(expiry) = pending_expiry(&receipt, now) else { + return refuse(StatusCode::BAD_GATEWAY, "Heimdall returned an invalid authentication attempt."); + }; + let expiry = expiry.min(now + chrono::Duration::seconds(BEGIN_TTL_SECONDS)); + let Some(secret) = state.auth.start(&receipt.handle, invite, expiry, now) else { + return refuse(StatusCode::SERVICE_UNAVAILABLE, "too many sign-ins are open; try again shortly"); + }; + let mut response = reply( + StatusCode::OK, + json!({ + "handle": receipt.handle, + "url": receipt.navigation.url, + "allowedOrigins": receipt.navigation.allowed_origins, + }), + ); + response.headers_mut().insert( + header::SET_COOKIE, + begin_cookie(&secret, (expiry - now).num_seconds().max(0)), + ); + response +} + +#[derive(Debug, Deserialize)] +#[serde(deny_unknown_fields)] +struct AuthCompleteBody { + handle: String, + key: String, +} + +async fn auth_complete( + headers: HeaderMap, + State(state): State, + Json(body): Json, +) -> Response { + let now = Utc::now(); + if !state.auth.allow(client_key(&headers), now) { + return throttled(); + } + if body.handle.is_empty() { + return refuse(StatusCode::BAD_REQUEST, "Authentication completion omitted its opaque handle."); + } + // Only the browser that began the attempt may complete it. + let Some(secret) = named_cookie(&headers, BEGIN_COOKIE) + .filter(|secret| state.auth.matches(&body.handle, secret, now)) + else { + return refuse(StatusCode::FORBIDDEN, "this browser did not begin that sign-in"); + }; + let completion = match state.heimdall.complete(&body.handle, &body.key).await { + Ok(value) => value, + Err(error) => { + tracing::warn!(%error, "Heimdall refused to complete a sign-in"); + return refuse(StatusCode::FORBIDDEN, "Heimdall could not complete the sign-in."); + } + }; + if completion.status == "pending" { + return reply(StatusCode::ACCEPTED, json!({"status": "pending"})); + } + // Any other outcome ends the attempt: the binding is spent here, once. + let Some(invite) = state.auth.consume(&body.handle, secret, now) else { + return refuse(StatusCode::FORBIDDEN, "this browser did not begin that sign-in"); + }; + let spent = |mut response: Response| { + response.headers_mut().append(header::SET_COOKIE, begin_cookie("", 0)); + response + }; + if completion.status != "authenticated" || completion.handle.as_deref() != Some(body.handle.as_str()) { + let message = completion + .error + .clone() + .unwrap_or_else(|| "Heimdall denied access.".into()); + return spent(reply(StatusCode::FORBIDDEN, json!({"status": "denied", "error": message}))); + } + let admission = match state.heimdall.verify_completion(completion).await { + Ok(admission) => admission, + Err(error) => { + tracing::warn!(%error, "a Heimdall completion failed verification"); + return spent(reply( + StatusCode::FORBIDDEN, + json!({"status": "denied", "error": "Heimdall's answer could not be verified."}), + )); + } + }; + // No account and no live invite: refused, never enrolled. The invite is + // consumed only with the account it creates. + let principal = match state + .catalog + .lock() + .await + .sign_in(admission.account_id(), invite.as_deref(), Utc::now()) + { + Ok(Ok(principal)) => principal, + Ok(Err(refusal)) => { + return spent(reply( + StatusCode::FORBIDDEN, + json!({"status": "refused", "error": refusal.to_string()}), + )); + } + Err(error) => { + tracing::error!(%error, "the account catalog could not record a sign-in"); + return refuse(StatusCode::INTERNAL_SERVER_ERROR, "the sign-in could not be recorded"); + } + }; + // The session plays as the account's principal, which is the identity the + // account was first made from. A session minted as another identity would + // split one account across two worlds sets, so it is refused until a + // second-identity link decides the principal (ruling + // dungeon-account-principal-answer). + if principal != admission.account_id() { + return spent(reply( + StatusCode::FORBIDDEN, + json!({"status": "refused", "error": "this identity is linked to an account whose principal it does not carry"}), + )); + } + let expires_at = admission.refresh_expires_at(); + let token = { + let mut sessions = state.sessions.lock().await; + let result = sessions.create_session(admission); + if let Err(error) = &result + && !sessions.is_healthy() + { + signal_fatal(&state, "app-session authentication adoption", error); + } + match result { + Ok(token) => token, + Err(error) => { + tracing::warn!(%error, "an authenticated sign-in could not become a session"); + return spent(reply( + StatusCode::FORBIDDEN, + json!({"status": "denied", "error": "the session could not be created"}), + )); + } + } + }; + let mut response = spent(reply(StatusCode::OK, json!({"status": "authenticated"}))); + response + .headers_mut() + .append(header::SET_COOKIE, session_cookie(&token, expires_at, Utc::now())); + response +} + +async fn auth_logout(headers: HeaderMap, State(state): State) -> Response { + let raw_cookie = cookie_value(&headers).unwrap_or_default(); + let local = { + let mut sessions = state.sessions.lock().await; + sessions + .session_for_logout(raw_cookie) + .and_then(|remote| sessions.revoke_cookie(raw_cookie).map(|_| remote)) + }; + let remote = match local { + Ok(remote) => remote, + Err(error) => { + signal_fatal(&state, "app-session logout", &error); + return reply( + StatusCode::INTERNAL_SERVER_ERROR, + json!({"status": "unknown", "error": "Local session revocation was not confirmed."}), + ); + } + }; + if let Some(session) = remote { + let heimdall = state.heimdall.clone(); + tokio::spawn(async move { + let idempotency = format!( + "logout:{}:{}", + session.heimdall_session_id, session.access_revision + ); + if let Err(error) = heimdall.logout(&session.refresh_claim, &idempotency).await { + tracing::warn!(%error, "local logout succeeded but Heimdall logout was unavailable"); + } + }); + } + let mut response = reply(StatusCode::OK, json!({"status": "anonymous"})); + response.headers_mut().insert( + header::SET_COOKIE, + HeaderValue::from_static( + "ghostlight_session=; Max-Age=0; HttpOnly; Secure; SameSite=Lax; Path=/ghostlight/", + ), + ); + response +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::{ + app_session::AppSessionOwner, + begin::tests::{Rig, author, deferred_rig, eventually, one_vault, principal, rig}, + heimdall::{ + AccountSummary, AuthBeginReceipt, AuthCompletionReceipt, AuthNavigation, AuthProvider, + HeimdallPort, SessionRefresher, VerifiedSessionAdmission, VerifiedSessionRefresh, + }, + play::{ + ASK_PLAYER_TOOL, END_TURN_TOOL, + tests::{call_event, output, text_event}, + }, + runtime::service_router, + }; + use axum::{ + body::{Body, to_bytes}, + http::{Method, Request}, + }; + use std::sync::Arc; + use tokio::sync::Mutex; + use tower::ServiceExt; + use uuid::Uuid; + + /// A scripted Heimdall: it offers google and discord, hands out numbered + /// handles, answers `complete` from what the test authenticated, and + /// counts every call. + #[derive(Default)] + struct FakeHeimdall { + begun: std::sync::Mutex>, + /// Whether each begin carried the first-login grant, in order. + grants: std::sync::Mutex>, + completed: std::sync::Mutex, + authenticated: std::sync::Mutex>, + /// Overrides the next begin: an invalid receipt or a failure. + begin_override: std::sync::Mutex>>, + fail_complete: std::sync::Mutex, + } + + impl FakeHeimdall { + fn receipt(handle: &str, status: &str, expires_in: chrono::Duration) -> AuthBeginReceipt { + AuthBeginReceipt { + status: status.into(), + handle: handle.into(), + expires_at: (Utc::now() + expires_in).to_rfc3339(), + navigation: AuthNavigation { + url: "https://provider.invalid/authorize".into(), + allowed_origins: vec!["https://provider.invalid".into()], + }, + } + } + + /// The user finished the provider's page: `complete` now answers + /// `status` for the handle, as `account`. + fn finish(&self, handle: &str, status: &str, account: &str) { + self.authenticated + .lock() + .unwrap() + .insert(handle.into(), (status.into(), account.into())); + } + } + + #[async_trait::async_trait] + impl SessionRefresher for FakeHeimdall { + async fn refresh(&self, _: &str, _: &str) -> anyhow::Result { + unreachable!("the API tests run no refresh loop") + } + + async fn verify_refresh(&self, _: AuthCompletionReceipt) -> anyhow::Result { + unreachable!("the API tests run no refresh loop") + } + } + + #[async_trait::async_trait] + impl HeimdallPort for FakeHeimdall { + fn offered(&self, name: &str) -> Option { + AuthProvider::parse(name).filter(|provider| *provider != AuthProvider::Twitch) + } + + async fn begin(&self, provider: AuthProvider, grant: bool, _: &str) -> anyhow::Result { + let mut begun = self.begun.lock().unwrap(); + begun.push(provider); + self.grants.lock().unwrap().push(grant); + if let Some(forced) = self.begin_override.lock().unwrap().take() { + return forced; + } + Ok(Self::receipt(&format!("handle-{}", begun.len()), "pending", chrono::Duration::minutes(15))) + } + + async fn complete(&self, handle: &str, _: &str) -> anyhow::Result { + *self.completed.lock().unwrap() += 1; + if *self.fail_complete.lock().unwrap() { + anyhow::bail!("private socket 10.0.0.7 refused"); + } + let finished = self.authenticated.lock().unwrap().get(handle).cloned(); + let (status, account) = finished.unwrap_or(("pending".into(), String::new())); + Ok(AuthCompletionReceipt { + error: (status == "denied").then(|| "the role is missing".to_owned()), + handle: Some(handle.into()), + account: (status == "authenticated").then(|| AccountSummary { id: account }), + status, + session: None, + access_token: None, + refresh_token: None, + refresh: None, + shared_capabilities: vec![], + }) + } + + async fn verify_completion( + &self, + completion: AuthCompletionReceipt, + ) -> anyhow::Result { + Ok(VerifiedSessionAdmission::fixture( + completion.account.unwrap().id, + "heimdall-session-fresh", + 1, + Utc::now() + chrono::Duration::hours(1), + Utc::now() + chrono::Duration::days(1), + "fixture-refresh", + )) + } + + async fn logout(&self, _: &str, _: &str) -> anyhow::Result { + anyhow::bail!("Heimdall is unreachable") + } + } + + struct App { + router: Router, + state: AppState, + heimdall: Arc, + fatal_events: std::sync::Mutex>, + rig: Rig, + cookies: Vec, + } + + /// An app over a scripted model with one signed-in session per entry of + /// `accounts` (the same account twice is the same player on two devices). + async fn app(script: Vec, accounts: &[&str]) -> App { + app_over(rig(script), accounts).await + } + + async fn app_over(rig: Rig, accounts: &[&str]) -> App { + let key = rig.directory.path().join("session.key"); + std::fs::write(&key, [17_u8; 32]).unwrap(); + let mut sessions = + AppSessionOwner::open(rig.directory.path().join("service/app-sessions-v2.cc"), &key) + .unwrap(); + let cookies = accounts + .iter() + .enumerate() + .map(|(index, account)| { + sessions + .create_session(VerifiedSessionAdmission::fixture( + *account, + format!("heimdall-session-{index}"), + 1, + Utc::now() + chrono::Duration::hours(1), + Utc::now() + chrono::Duration::days(1), + "fixture-refresh", + )) + .unwrap() + }) + .collect(); + let heimdall = Arc::new(FakeHeimdall::default()); + let (fatal, fatal_events) = tokio::sync::mpsc::unbounded_channel(); + let state = AppState { + catalog: rig.catalog.clone(), + timelines: rig.timelines.clone(), + vaults: one_vault(), + scale: rig.scale.clone(), + sessions: Arc::new(Mutex::new(sessions)), + heimdall: heimdall.clone(), + auth: Arc::default(), + runtime_id: "ghostlight-test".into(), + runtime_health: None, + fatal, + }; + App { + router: service_router(state.clone()), + state, + heimdall, + fatal_events: std::sync::Mutex::new(fatal_events), + rig, + cookies, + } + } + + async fn call( + app: &App, + method: Method, + uri: &str, + cookie: Option<&str>, + body: Option, + ) -> (StatusCode, HeaderMap, Value) { + let mut request = Request::builder().method(method).uri(uri); + if let Some(cookie) = cookie { + request = request.header(header::COOKIE, format!("{COOKIE_NAME}={cookie}")); + } + let request = match body { + Some(body) => request + .header(header::CONTENT_TYPE, "application/json") + .body(Body::from(body.to_string())), + None => request.body(Body::empty()), + } + .unwrap(); + let response = app.router.clone().oneshot(request).await.unwrap(); + let status = response.status(); + let headers = response.headers().clone(); + let bytes = to_bytes(response.into_body(), 1 << 20).await.unwrap(); + (status, headers, serde_json::from_slice(&bytes).unwrap_or(Value::Null)) + } + + async fn begin_one(app: &App, cookie: &str) -> String { + let (status, _, body) = call( + app, + Method::POST, + "/api/begin", + Some(cookie), + Some(json!({"key": Uuid::new_v4(), "title": "Ashfall", "name": "Deru"})), + ) + .await; + assert_eq!(status, StatusCode::OK, "{body}"); + body["timeline"].as_str().unwrap().to_owned() + } + + async fn play_text(app: &App, cookie: &str, timeline: &str, text: &str, answers: Option<&str>) -> (StatusCode, Value) { + let (status, _, body) = call( + app, + Method::POST, + "/api/play", + Some(cookie), + Some(json!({"timeline": timeline, "key": Uuid::new_v4(), "text": text, "answers": answers})), + ) + .await; + (status, body) + } + + async fn history_of(app: &App, cookie: &str, timeline: &str, query: &str) -> (StatusCode, Value) { + let (status, _, body) = call(app, Method::GET, &format!("/api/history/{timeline}{query}"), Some(cookie), None).await; + (status, body) + } + + async fn play_and_settle(app: &App, cookie: &str, timeline: &str, text: &str, answers: Option<&str>) -> Value { + let (status, body) = play_text(app, cookie, timeline, text, answers).await; + assert_eq!(status, StatusCode::ACCEPTED, "{body}"); + settled_turn(app, cookie, timeline).await + } + + #[tokio::test] + async fn the_history_keeps_every_turn_newest_last_and_pages_backwards() { + let mut script = vec![]; + for n in 0..3 { + script.push(output(&format!("r{n}"), vec![call_event(&format!("c{n}"), END_TURN_TOOL, json!({}))])); + script.push(output(&format!("p{n}"), vec![text_event(&format!("Story number {n}."))])); + } + let app = app(script, &["alice"]).await; + let cookie = app.cookies[0].clone(); + let timeline = begin_one(&app, &cookie).await; + let (_, empty) = history_of(&app, &cookie, &timeline, "").await; + assert_eq!(empty["entries"].as_array().unwrap().len(), 0); + let texts = [" I open the door. ", "I step in.", "I light a lamp."]; + for text in texts { + play_and_settle(&app, &cookie, &timeline, text, None).await; + } + let (status, all) = history_of(&app, &cookie, &timeline, "").await; + assert_eq!(status, StatusCode::OK); + let entries = all["entries"].as_array().unwrap(); + assert_eq!(entries.len(), 3); + for (n, entry) in entries.iter().enumerate() { + assert_eq!(entry["seq"], n as u64 + 1, "oldest first, newest last"); + assert_eq!(entry["text"], texts[n], "the text exactly as sent"); + assert_eq!(entry["narration"], format!("Story number {n}.")); + assert_eq!(entry["status"], "committed"); + assert!(entry["world_revision"].is_u64(), "{entry}"); + assert!(entry["retry_of"].is_null() && entry["superseded_by"].is_null()); + } + assert!(all["older"].is_null()); + let (_, newest) = history_of(&app, &cookie, &timeline, "?limit=2").await; + let seqs: Vec = newest["entries"].as_array().unwrap().iter().map(|e| e["seq"].as_u64().unwrap()).collect(); + assert_eq!(seqs, [2, 3]); + let (_, oldest) = history_of(&app, &cookie, &timeline, &format!("?limit=2&before={}", newest["older"])).await; + assert_eq!(oldest["entries"].as_array().unwrap().len(), 1); + assert_eq!(oldest["entries"][0]["text"], texts[0]); + assert!(oldest["older"].is_null()); + } + + #[tokio::test] + async fn a_question_and_its_answer_are_two_entries() { + let script = vec![ + output("r0", vec![call_event("c0", ASK_PLAYER_TOOL, json!({"question": "Which way?"}))]), + output("r1", vec![call_event("c1", END_TURN_TOOL, json!({}))]), + output("proj-0", vec![text_event("You choose.")]), + ]; + let app = app(script, &["alice"]).await; + let cookie = app.cookies[0].clone(); + let timeline = begin_one(&app, &cookie).await; + let view = play_and_settle(&app, &cookie, &timeline, "A crossroads.", None).await; + let token = view["turn"]["question"]["token"].as_str().unwrap().to_owned(); + play_and_settle(&app, &cookie, &timeline, "left", Some(&token)).await; + let (_, log) = history_of(&app, &cookie, &timeline, "").await; + let entries = log["entries"].as_array().unwrap(); + assert_eq!(entries.len(), 2, "{log}"); + assert_eq!((entries[0]["status"].as_str(), entries[0]["question"].as_str()), (Some("asked"), Some("Which way?"))); + assert_eq!(entries[0]["text"], "A crossroads."); + assert_eq!((entries[1]["status"].as_str(), entries[1]["text"].as_str()), (Some("committed"), Some("left"))); + assert_eq!(entries[1]["narration"], "You choose."); + assert_eq!(entries[0]["turn_id"], entries[1]["turn_id"]); + } + + #[tokio::test] + async fn a_retry_is_a_new_entry_and_the_faulted_one_stays_marked_superseded() { + let app = app(vec![], &["alice"]).await; + let cookie = app.cookies[0].clone(); + let timeline = begin_one(&app, &cookie).await; + play_and_settle(&app, &cookie, &timeline, "I knock.", None).await; + let (status, _, body) = call( + &app, + Method::POST, + "/api/play", + Some(&cookie), + Some(json!({"timeline": timeline, "key": Uuid::new_v4(), "text": "x", "retry_of": 99})), + ) + .await; + assert_eq!(status, StatusCode::CONFLICT, "{body}"); + let (status, _, _) = call( + &app, + Method::POST, + "/api/play", + Some(&cookie), + Some(json!({"timeline": timeline, "key": Uuid::new_v4(), "text": "I knock.", "retry_of": 1})), + ) + .await; + assert_eq!(status, StatusCode::ACCEPTED); + for _ in 0..200 { + if history_of(&app, &cookie, &timeline, "").await.1["entries"].as_array().unwrap().len() == 2 { + break; + } + tokio::time::sleep(Duration::from_millis(25)).await; + } + let (_, log) = history_of(&app, &cookie, &timeline, "").await; + let entries = log["entries"].as_array().unwrap(); + assert_eq!(entries.len(), 2, "{log}"); + assert_eq!(entries[0]["status"], "faulted"); + assert_eq!(entries[0]["fault"], PLAY_FAULT_LINE); + assert_eq!(entries[0]["superseded_by"], 2, "the old entry stays, marked"); + assert_eq!(entries[1]["retry_of"], 1); + assert_eq!(entries[1]["text"], "I knock."); + } + + #[tokio::test] + async fn another_accounts_history_is_unreadable() { + let script = vec![ + output("r0", vec![call_event("c0", END_TURN_TOOL, json!({}))]), + output("p0", vec![text_event("A private story.")]), + ]; + let app = app(script, &["alice", "mallory"]).await; + let (alice, mallory) = (app.cookies[0].clone(), app.cookies[1].clone()); + let timeline = begin_one(&app, &alice).await; + play_and_settle(&app, &alice, &timeline, "A private act.", None).await; + let (status, body) = history_of(&app, &mallory, &timeline, "").await; + assert_eq!(status, StatusCode::NOT_FOUND); + assert!(!body.to_string().contains("private"), "{body}"); + let (status, _, body) = call(&app, Method::GET, &format!("/api/history/{timeline}"), None, None).await; + assert_eq!(status, StatusCode::UNAUTHORIZED, "{body}"); + let (status, _) = history_of(&app, &alice, &timeline, "").await; + assert_eq!(status, StatusCode::OK); + // Mallory's own timeline holds none of Alice's entries. + let theirs = begin_one(&app, &mallory).await; + let (status, own) = history_of(&app, &mallory, &theirs, "").await; + assert_eq!(status, StatusCode::OK); + assert_eq!(own["entries"].as_array().unwrap().len(), 0); + } + + async fn settled_turn(app: &App, cookie: &str, timeline: &str) -> Value { + for _ in 0..200 { + let (_, _, view) = call(app, Method::GET, &format!("/api/turn/{timeline}"), Some(cookie), None).await; + if view["turn"]["state"] != "running" && !view["turn"].is_null() { + return view; + } + tokio::time::sleep(Duration::from_millis(25)).await; + } + panic!("the turn never settled"); + } + + #[tokio::test] + async fn every_route_refuses_a_missing_or_unknown_cookie() { + let app = app(vec![], &["alice"]).await; + let timeline = begin_one(&app, &app.cookies[0].clone()).await; + let play = json!({"timeline": timeline, "key": Uuid::new_v4(), "text": "hi"}); + let begin = json!({"key": Uuid::new_v4(), "title": "T", "name": "N"}); + for cookie in [None, Some("bogus-cookie")] { + for (method, uri, body) in [ + (Method::GET, "/api/timelines".to_owned(), None), + (Method::GET, "/api/vaults".to_owned(), None), + (Method::GET, format!("/api/turn/{timeline}"), None), + (Method::GET, format!("/api/turn/{timeline}/stream"), None), + (Method::POST, "/api/begin".to_owned(), Some(begin.clone())), + (Method::POST, "/api/play".to_owned(), Some(play.clone())), + ] { + let (status, _, _) = call(&app, method, &uri, cookie, body).await; + assert_eq!(status, StatusCode::UNAUTHORIZED, "{uri} with {cookie:?}"); + } + let (_, _, me) = call(&app, Method::GET, "/api/me", cookie, None).await; + assert_eq!(me["signedIn"], false); + } + assert!(app.rig.catalog.lock().await.timelines_of("nobody").is_empty()); + } + + #[tokio::test] + async fn an_expired_session_is_refused() { + let app = app(vec![], &[]).await; + let cookie = { + let mut sessions = app.state.sessions.lock().await; + sessions + .create_session(VerifiedSessionAdmission::fixture( + "alice", + "heimdall-session-old", + 1, + Utc::now() - chrono::Duration::minutes(1), + Utc::now() + chrono::Duration::days(1), + "fixture-refresh", + )) + .unwrap() + }; + let (status, _, _) = call(&app, Method::GET, "/api/timelines", Some(&cookie), None).await; + assert_eq!(status, StatusCode::UNAUTHORIZED); + } + + async fn timeline_status(app: &App, cookie: &str, timeline: &str) -> Option<(String, Value)> { + let (status, _, body) = call(app, Method::GET, "/api/timelines", Some(cookie), None).await; + assert_eq!(status, StatusCode::OK); + body["timelines"] + .as_array() + .unwrap() + .iter() + .find(|row| row["timeline"] == timeline) + .map(|row| (row["status"].as_str().unwrap().to_owned(), row["reason"].clone())) + } + + async fn begin_vault_over_http(app: &App, cookie: &str) -> String { + let body = json!({"key": Uuid::new_v4(), "title": "Ashfall", "name": "Deru", "vault": "delvehold"}); + let (code, _, body) = call(app, Method::POST, "/api/begin", Some(cookie), Some(body)).await; + assert_eq!(code, StatusCode::OK, "{body}"); + assert_eq!(body["reached"], "seeding"); + body["timeline"].as_str().unwrap().to_owned() + } + + /// Spec test: GET /api/vaults lists each vault with its eras and default + /// and all eight lenses with their reach; POST /api/begin with an era and + /// lenses pins both in the world, and a field the body does not know is + /// refused. + #[tokio::test] + async fn the_vault_list_and_a_begin_with_era_and_lenses_over_http() { + let app = app_over(deferred_rig(), &["alice"]).await; + let cookie = app.cookies[0].clone(); + let (code, _, listed) = call(&app, Method::GET, "/api/vaults", Some(&cookie), None).await; + assert_eq!(code, StatusCode::OK, "{listed}"); + let vault = &listed["vaults"][0]; + assert_eq!((vault["name"].as_str(), vault["default_era"].as_str()), (Some("delvehold"), Some("a"))); + assert_eq!(vault["eras"].as_array().unwrap().len(), 2); + assert_eq!(vault["eras"][1]["id"], "b"); + assert!(vault["eras"][1]["description"].as_str().is_some_and(|text| !text.is_empty())); + let lenses = listed["lenses"].as_array().unwrap(); + assert_eq!(lenses.len(), 8); + assert!(lenses.iter().all(|lens| lens["reaches_for"].as_str().is_some_and(|text| !text.is_empty()))); + assert!(lenses.iter().any(|lens| lens["id"] == "charter")); + + let body = json!({"key": Uuid::new_v4(), "title": "Ashfall", "name": "Deru", "vault": "delvehold", + "era": "b", "lenses": {"charter": 3, "veil": 3, "hearth": 3}}); + let (code, _, begun) = call(&app, Method::POST, "/api/begin", Some(&cookie), Some(body)).await; + assert_eq!(code, StatusCode::OK, "{begun}"); + let host = app.rig.timelines.host(begun["timeline"].as_str().unwrap()).await.unwrap(); + let world = host.world.snapshot().await.unwrap(); + assert_eq!(world.era.unwrap().id, "b"); + assert_eq!((world.lens_weights.get(Lens::Charter), world.lens_weights.get(Lens::Ember)), (3, 0)); + + let unknown = json!({"key": Uuid::new_v4(), "title": "Ashfall", "name": "Deru", "tier": "x"}); + let (code, _, _) = call(&app, Method::POST, "/api/begin", Some(&cookie), Some(unknown)).await; + assert!(code.is_client_error()); + } + + /// Spec test: POST /api/begin on a vault returns the timeline before the + /// seed has finished, and the timeline list reads Seeding, then Ready. + #[tokio::test] + async fn a_vault_begin_returns_at_once_and_the_timeline_reads_seeding_then_ready() { + let app = app_over(deferred_rig(), &["alice"]).await; + let cookie = app.cookies[0].clone(); + let timeline = begin_vault_over_http(&app, &cookie).await; + assert_eq!(timeline_status(&app, &cookie, &timeline).await.unwrap().0, "seeding"); + + let host = app.state.timelines.host(&timeline).await.unwrap(); + let draft = host.world.snapshot().await.unwrap(); + app.rig.port.push(Ok(author("seed-1", &draft, &["a", "b"]))); + app.rig.port.push(Ok(author("seed-2", &draft, &["c", "d"]))); + eventually(async || { + (timeline_status(&app, &cookie, &timeline).await.unwrap().0 == "ready").then_some(()) + }) + .await; + } + + /// Spec test: a scripted seed fault reads Failed with a reason and no + /// endpoint text. + #[tokio::test] + async fn a_failed_seed_reads_failed_with_a_reason_and_no_endpoint() { + let app = app_over(deferred_rig(), &["alice"]).await; + let cookie = app.cookies[0].clone(); + let timeline = begin_vault_over_http(&app, &cookie).await; + app.rig.port.push(Err("http://10.0.0.7:9/secret endpoint down")); + let (_, reason) = eventually(async || { + timeline_status(&app, &cookie, &timeline).await.filter(|(state, _)| state == "failed") + }) + .await; + let reason = reason.as_str().unwrap(); + assert!(reason.contains("seed") && !reason.contains("10.0.0.7"), "{reason}"); + } + + + /// A world that is seeding, failed or a Draft is not played: the refusal + /// is a 409 that names the status, and no model is asked. + #[tokio::test] + async fn play_on_a_world_that_is_not_ready_is_refused_with_its_status() { + let app = app_over(deferred_rig(), &["alice"]).await; + let cookie = app.cookies[0].clone(); + let timeline = begin_vault_over_http(&app, &cookie).await; + let asked = app.rig.port.seen_requests().len(); + + let (status, body) = play_text(&app, &cookie, &timeline, "I look around.", None).await; + assert_eq!((status, body["status"].as_str()), (StatusCode::CONFLICT, Some("seeding")), "{body}"); + assert_eq!(body["error"], "this world is still being seeded"); + + app.rig.port.push(Err("http://10.0.0.7:9/secret endpoint down")); + eventually(async || timeline_status(&app, &cookie, &timeline).await.filter(|(state, _)| state == "failed")).await; + let (status, body) = play_text(&app, &cookie, &timeline, "I look around.", None).await; + assert_eq!((status, body["status"].as_str()), (StatusCode::CONFLICT, Some("failed")), "{body}"); + assert_eq!(body["error"], "this world's seed did not finish"); + assert!(body["reason"].as_str().unwrap().contains("seed"), "{body}"); + + // A Draft the catalog calls Ready is still not played. + app.rig.catalog.lock().await.settle_seed(&timeline, None).unwrap(); + let (status, body) = play_text(&app, &cookie, &timeline, "I look around.", None).await; + assert_eq!((status, body["status"].as_str()), (StatusCode::CONFLICT, Some("draft")), "{body}"); + assert_eq!(app.rig.port.seen_requests().len(), asked + 1, "only the seed's own request reached the model"); + let (_, _, view) = call(&app, Method::GET, &format!("/api/turn/{timeline}"), Some(&cookie), None).await; + assert!(view["turn"].is_null(), "no turn was admitted: {view}"); + } + + /// A turn that closes runs the world ahead; a turn that stops to ask the + /// player does not. + #[tokio::test] + async fn only_a_closed_turn_runs_the_world_ahead() { + let app = app_over(deferred_rig(), &["alice"]).await; + let cookie = app.cookies[0].clone(); + let timeline = begin_vault_over_http(&app, &cookie).await; + let host = app.state.timelines.host(&timeline).await.unwrap(); + let draft = host.world.snapshot().await.unwrap(); + app.rig.port.push(Ok(author("seed-1", &draft, &["a", "b"]))); + app.rig.port.push(Ok(author("seed-2", &draft, &["c", "d"]))); + eventually(async || (timeline_status(&app, &cookie, &timeline).await.unwrap().0 == "ready").then_some(())).await; + // The sweep that follows activation meets a model that is down. + let mut answered = 0; + eventually(async || { + let seen = app.rig.port.seen_requests().len(); + if seen > 2 && seen > answered { + answered = seen; + app.rig.port.push(Err("down")); + } + (seen > 2 && host.sweeping.try_lock().is_ok()).then_some(()) + }) + .await; + let elaborations = |app: &App| { + app.rig + .port + .seen_requests() + .iter() + .filter(|request| serde_json::to_string(request).unwrap().contains(crate::begin::tests::NOTE)) + .count() + }; + let before = elaborations(&app); + + app.rig.port.push(Ok(output("r0", vec![call_event("c0", ASK_PLAYER_TOOL, json!({"question": "Which way?"}))]))); + let (status, body) = play_text(&app, &cookie, &timeline, "A crossroads.", None).await; + assert_eq!(status, StatusCode::ACCEPTED, "{body}"); + let view = settled_turn(&app, &cookie, &timeline).await; + assert_eq!(view["turn"]["state"], "awaiting_player"); + tokio::time::sleep(Duration::from_millis(300)).await; + assert_eq!(elaborations(&app), before, "an open question runs nothing ahead"); + + let token = view["turn"]["question"]["token"].as_str().unwrap().to_owned(); + app.rig.port.push(Ok(output("r1", vec![call_event("c1", END_TURN_TOOL, json!({}))]))); + app.rig.port.push(Ok(output("proj-0", vec![text_event("You choose.")]))); + let (status, body) = play_text(&app, &cookie, &timeline, "left", Some(&token)).await; + assert_eq!(status, StatusCode::ACCEPTED, "{body}"); + eventually(async || (elaborations(&app) > before).then_some(())).await; + } + #[tokio::test] + async fn logout_revokes_the_cookie_even_when_heimdall_is_unreachable() { + let app = app(vec![], &["alice"]).await; + let cookie = app.cookies[0].clone(); + let (status, _, _) = call(&app, Method::GET, "/api/timelines", Some(&cookie), None).await; + assert_eq!(status, StatusCode::OK); + let (status, headers, _) = call(&app, Method::POST, "/api/auth/logout", Some(&cookie), None).await; + assert_eq!(status, StatusCode::OK); + assert!(headers[header::SET_COOKIE].to_str().unwrap().contains("Max-Age=0")); + let (status, _, _) = call(&app, Method::GET, "/api/timelines", Some(&cookie), None).await; + assert_eq!(status, StatusCode::UNAUTHORIZED); + } + + const A_BROWSER: &str = "203.0.113.9"; + const BEGIN_FLAGS: [&str; 5] = ["HttpOnly", "Secure", "SameSite=Lax", "Path=/ghostlight/", "Max-Age="]; + + /// One request to an auth route as a browser behind nginx: its cookie jar + /// and the `X-Real-IP` nginx stamps. + async fn auth_call( + app: &App, + uri: &str, + jar: &[(&str, &str)], + real_ip: &str, + body: Value, + ) -> (StatusCode, Vec, Value) { + let cookie = jar + .iter() + .map(|(name, value)| format!("{name}={value}")) + .collect::>() + .join("; "); + let mut request = Request::builder() + .method(Method::POST) + .uri(uri) + .header(header::CONTENT_TYPE, "application/json") + .header("x-real-ip", real_ip); + if !cookie.is_empty() { + request = request.header(header::COOKIE, cookie); + } + let response = app + .router + .clone() + .oneshot(request.body(Body::from(body.to_string())).unwrap()) + .await + .unwrap(); + let status = response.status(); + let cookies = response + .headers() + .get_all(header::SET_COOKIE) + .iter() + .map(|value| value.to_str().unwrap().to_owned()) + .collect(); + let bytes = to_bytes(response.into_body(), 1 << 20).await.unwrap(); + (status, cookies, serde_json::from_slice(&bytes).unwrap_or(Value::Null)) + } + + fn cookie_named<'a>(set_cookies: &'a [String], name: &str) -> Option<&'a String> { + set_cookies.iter().find(|cookie| cookie.starts_with(&format!("{name}="))) + } + + fn cookie_secret(set_cookie: &str) -> String { + set_cookie.split(';').next().unwrap().split_once('=').unwrap().1.to_owned() + } + + /// Begins a sign-in from a browser; returns its handle and begin secret. + async fn begin_sign_in(app: &App, provider: &str, real_ip: &str) -> (String, String) { + begin_with_invite(app, provider, real_ip, None).await + } + + /// Begins a sign-in presenting `invite`, the way the page does at begin. + async fn begin_with_invite(app: &App, provider: &str, real_ip: &str, invite: Option<&str>) -> (String, String) { + let (status, cookies, body) = auth_call( + app, + "/api/auth/begin", + &[], + real_ip, + json!({"key": Uuid::new_v4(), "provider": provider, "invite": invite}), + ) + .await; + assert_eq!(status, StatusCode::OK, "{body}"); + let secret = cookie_secret(cookie_named(&cookies, "ghostlight_auth").expect("a begin cookie")); + (body["handle"].as_str().unwrap().to_owned(), secret) + } + + async fn complete(app: &App, handle: &str, jar: &[(&str, &str)]) -> (StatusCode, Vec, Value) { + auth_call( + app, + "/api/auth/complete", + jar, + A_BROWSER, + json!({"handle": handle, "key": Uuid::new_v4()}), + ) + .await + } + + async fn invite(app: &App) -> String { + app.state + .catalog + .lock() + .await + .mint_invite(Utc::now(), chrono::Duration::hours(1)) + .unwrap() + } + + #[tokio::test] + async fn begin_returns_the_attempt_and_binds_it_to_this_browser_with_a_private_cookie() { + let app = app(vec![], &[]).await; + let (status, cookies, body) = auth_call( + &app, + "/api/auth/begin", + &[], + A_BROWSER, + json!({"key": Uuid::new_v4(), "provider": "google"}), + ) + .await; + assert_eq!(status, StatusCode::OK, "{body}"); + assert_eq!(body["handle"], "handle-1"); + assert_eq!(body["url"], "https://provider.invalid/authorize"); + assert_eq!(body["allowedOrigins"], json!(["https://provider.invalid"])); + assert_eq!(*app.heimdall.begun.lock().unwrap(), vec![AuthProvider::Google]); + let cookie = cookie_named(&cookies, "ghostlight_auth").expect("a begin cookie"); + for flag in BEGIN_FLAGS { + assert!(cookie.contains(flag), "{flag} missing from {cookie}"); + } + let max_age: i64 = cookie.split("Max-Age=").nth(1).unwrap().split(';').next().unwrap().parse().unwrap(); + assert!((1..=BEGIN_TTL_SECONDS).contains(&max_age), "{cookie}"); + assert_eq!(cookie_secret(cookie).len(), 64); + assert!(!body.to_string().contains(&cookie_secret(cookie)), "the secret stays in the cookie"); + } + + #[tokio::test] + async fn begin_refuses_a_provider_the_daemon_does_not_offer_and_asks_heimdall_nothing() { + let app = app(vec![], &[]).await; + for provider in ["twitch", "github", "GOOGLE", "", "discord,google"] { + let (status, cookies, _) = auth_call( + &app, + "/api/auth/begin", + &[], + A_BROWSER, + json!({"key": Uuid::new_v4(), "provider": provider}), + ) + .await; + assert_eq!(status, StatusCode::BAD_REQUEST, "{provider:?}"); + assert!(cookies.is_empty()); + } + let (status, _, _) = + auth_call(&app, "/api/auth/begin", &[], A_BROWSER, json!({"key": Uuid::new_v4()})).await; + assert!(status.is_client_error(), "the provider is required"); + assert!(app.heimdall.begun.lock().unwrap().is_empty()); + } + + #[tokio::test] + async fn begin_refuses_a_receipt_that_is_not_a_live_pending_attempt_and_leaks_no_error_text() { + let app = app(vec![], &[]).await; + let bad = [ + Ok(FakeHeimdall::receipt("h", "authenticated", chrono::Duration::minutes(5))), + Ok(FakeHeimdall::receipt("", "pending", chrono::Duration::minutes(5))), + Ok(FakeHeimdall::receipt("h", "pending", chrono::Duration::minutes(-1))), + Ok(AuthBeginReceipt { + expires_at: "not a time".into(), + ..FakeHeimdall::receipt("h", "pending", chrono::Duration::minutes(5)) + }), + Err(anyhow::anyhow!("odin refused 10.0.0.7:17877")), + ]; + for forced in bad { + *app.heimdall.begin_override.lock().unwrap() = Some(forced); + let (status, cookies, body) = auth_call( + &app, + "/api/auth/begin", + &[], + A_BROWSER, + json!({"key": Uuid::new_v4(), "provider": "discord"}), + ) + .await; + assert_eq!(status, StatusCode::BAD_GATEWAY, "{body}"); + assert!(cookies.is_empty()); + assert!(!body.to_string().contains("10.0.0.7"), "{body}"); + } + } + + #[tokio::test] + async fn a_handle_begun_in_one_browser_cannot_be_completed_from_another() { + let app = app(vec![], &[]).await; + let invite = invite(&app).await; + let (handle, victim_secret) = begin_with_invite(&app, "google", "198.51.100.1", Some(&invite)).await; + let (_, attacker_secret) = begin_sign_in(&app, "google", "198.51.100.2").await; + app.heimdall.finish(&handle, "authenticated", "victim"); + for jar in [ + vec![], + vec![("ghostlight_auth", "")], + vec![("ghostlight_auth", attacker_secret.as_str())], + vec![("ghostlight_session", victim_secret.as_str())], + ] { + let (status, cookies, _) = complete(&app, &handle, &jar).await; + assert_eq!(status, StatusCode::FORBIDDEN, "{jar:?}"); + assert!(cookies.is_empty(), "no session for {jar:?}"); + } + assert_eq!(*app.heimdall.completed.lock().unwrap(), 0, "Heimdall is not even asked"); + assert!(app.state.catalog.lock().await.invite_is_live(&invite, Utc::now()), "a refused completion spends no invite"); + let (status, cookies, body) = + complete(&app, &handle, &[("ghostlight_auth", &victim_secret)]).await; + assert_eq!(status, StatusCode::OK, "{body}"); + assert!(cookie_named(&cookies, "ghostlight_session").is_some()); + } + + #[tokio::test] + async fn a_binding_is_single_use_and_spent_with_the_attempt() { + let app = app(vec![], &[]).await; + let invite = invite(&app).await; + let (handle, secret) = begin_with_invite(&app, "discord", A_BROWSER, Some(&invite)).await; + let jar = [("ghostlight_auth", secret.as_str())]; + let (status, cookies, _) = complete(&app, &handle, &jar).await; + assert_eq!(status, StatusCode::ACCEPTED, "Heimdall says pending"); + assert!(cookies.is_empty()); + assert_eq!(complete(&app, &handle, &jar).await.0, StatusCode::ACCEPTED, "pending keeps the binding"); + app.heimdall.finish(&handle, "authenticated", "deru"); + let (status, cookies, body) = complete(&app, &handle, &jar).await; + assert_eq!(status, StatusCode::OK, "{body}"); + let session = cookie_named(&cookies, "ghostlight_session").unwrap(); + for flag in ["HttpOnly", "Secure", "SameSite=Lax", "Path=/ghostlight/"] { + assert!(session.contains(flag), "{session}"); + } + let spent = cookie_named(&cookies, "ghostlight_auth").expect("the begin cookie is cleared"); + assert!(spent.contains("Max-Age=0"), "{spent}"); + let (status, cookies, _) = complete(&app, &handle, &jar).await; + assert_eq!(status, StatusCode::FORBIDDEN, "replay"); + assert!(cookies.is_empty()); + let (_, _, me) = call(&app, Method::GET, "/api/me", Some(&cookie_secret(session)), None).await; + assert_eq!(me["signedIn"], true); + } + + #[tokio::test] + async fn a_denied_or_mismatched_completion_mints_no_session_and_spends_the_binding() { + let app = app(vec![], &[]).await; + let (handle, secret) = begin_sign_in(&app, "discord", A_BROWSER).await; + let jar = [("ghostlight_auth", secret.as_str())]; + app.heimdall.finish(&handle, "denied", ""); + let (status, cookies, body) = complete(&app, &handle, &jar).await; + assert_eq!(status, StatusCode::FORBIDDEN); + assert_eq!(body["status"], "denied"); + assert_eq!(body["error"], "the role is missing", "Heimdall's own denial reaches the player"); + assert!(cookie_named(&cookies, "ghostlight_session").is_none()); + app.heimdall.finish(&handle, "authenticated", "deru"); + assert_eq!(complete(&app, &handle, &jar).await.0, StatusCode::FORBIDDEN, "spent"); + } + + #[tokio::test] + async fn a_failed_heimdall_completion_names_nothing_of_the_failure() { + let app = app(vec![], &[]).await; + let (handle, secret) = begin_sign_in(&app, "discord", A_BROWSER).await; + *app.heimdall.fail_complete.lock().unwrap() = true; + let (status, _, body) = complete(&app, &handle, &[("ghostlight_auth", &secret)]).await; + assert_eq!(status, StatusCode::FORBIDDEN); + assert!(!body.to_string().contains("10.0.0.7"), "{body}"); + let (status, _, _) = complete(&app, "", &[("ghostlight_auth", &secret)]).await; + assert_eq!(status, StatusCode::BAD_REQUEST); + } + + #[tokio::test] + async fn an_unknown_identity_needs_a_live_invite_and_a_known_one_does_not() { + let app = app(vec![], &[]).await; + let (handle, secret) = begin_sign_in(&app, "google", A_BROWSER).await; + app.heimdall.finish(&handle, "authenticated", "deru"); + let (status, cookies, body) = complete(&app, &handle, &[("ghostlight_auth", &secret)]).await; + assert_eq!(status, StatusCode::FORBIDDEN); + assert_eq!(body["status"], "refused"); + assert!(cookie_named(&cookies, "ghostlight_session").is_none()); + let invite = invite(&app).await; + let (handle, secret) = begin_with_invite(&app, "google", A_BROWSER, Some(&invite)).await; + app.heimdall.finish(&handle, "authenticated", "deru"); + let jar = [("ghostlight_auth", secret.as_str())]; + assert_eq!(complete(&app, &handle, &jar).await.0, StatusCode::OK); + assert!(!app.state.catalog.lock().await.invite_is_live(&invite, Utc::now()), "complete spent the invite"); + let (handle, secret) = begin_sign_in(&app, "google", A_BROWSER).await; + app.heimdall.finish(&handle, "authenticated", "deru"); + let (status, _, _) = complete(&app, &handle, &[("ghostlight_auth", &secret)]).await; + assert_eq!(status, StatusCode::OK, "the second device needs no invite"); + assert_eq!(*app.heimdall.grants.lock().unwrap().last().unwrap(), false, "and asks for no grant"); + let mut catalog = app.state.catalog.lock().await; + assert_eq!(catalog.sign_in("deru", None, Utc::now()).unwrap().unwrap(), "deru", "the same account, whichever device"); + } + + #[tokio::test] + async fn begin_with_a_live_invite_grants_and_consumes_nothing_and_without_one_does_not() { + let app = app(vec![], &[]).await; + let invite = invite(&app).await; + begin_with_invite(&app, "google", "198.51.100.1", Some(&invite)).await; + begin_with_invite(&app, "google", "198.51.100.2", Some(&format!(" {invite} "))).await; + begin_with_invite(&app, "discord", "198.51.100.3", Some("")).await; + begin_sign_in(&app, "google", "198.51.100.4").await; + assert_eq!(*app.heimdall.grants.lock().unwrap(), vec![true, true, false, false]); + assert!(app.state.catalog.lock().await.invite_is_live(&invite, Utc::now()), "begin spends nothing"); + } + + #[tokio::test] + async fn a_dead_invite_is_refused_at_begin_before_heimdall_is_asked() { + let app = app(vec![], &[]).await; + let spent = invite(&app).await; + let (handle, secret) = begin_with_invite(&app, "google", A_BROWSER, Some(&spent)).await; + app.heimdall.finish(&handle, "authenticated", "deru"); + assert_eq!(complete(&app, &handle, &[("ghostlight_auth", &secret)]).await.0, StatusCode::OK); + let expired = app + .state + .catalog + .lock() + .await + .mint_invite(Utc::now() - chrono::Duration::hours(2), chrono::Duration::hours(1)) + .unwrap(); + let asked = app.heimdall.begun.lock().unwrap().len(); + for dead in [spent.as_str(), expired.as_str(), "never-minted"] { + let (status, cookies, body) = auth_call( + &app, + "/api/auth/begin", + &[], + A_BROWSER, + json!({"key": Uuid::new_v4(), "provider": "google", "invite": dead}), + ) + .await; + assert_eq!(status, StatusCode::FORBIDDEN, "{dead}"); + assert_eq!(body["error"], "that invite is spent or expired"); + assert!(cookies.is_empty()); + } + assert_eq!(app.heimdall.begun.lock().unwrap().len(), asked, "Heimdall saw no begin"); + } + + #[tokio::test] + async fn a_first_google_login_with_no_live_invite_is_refused_and_a_complete_body_cannot_carry_one() { + let app = app(vec![], &[]).await; + let invite = invite(&app).await; + let (handle, secret) = begin_sign_in(&app, "google", A_BROWSER).await; + app.heimdall.finish(&handle, "authenticated", "stranger"); + let jar = [("ghostlight_auth", secret.as_str())]; + let (status, _, body) = auth_call( + &app, + "/api/auth/complete", + &jar, + A_BROWSER, + json!({"handle": handle, "key": Uuid::new_v4(), "invite": invite}), + ) + .await; + assert!(status.is_client_error(), "an invite at complete is not a field: {status}"); + assert_ne!(body["status"], "authenticated"); + let (status, cookies, body) = complete(&app, &handle, &jar).await; + assert_eq!(status, StatusCode::FORBIDDEN); + assert_eq!(body["status"], "refused"); + assert!(cookie_named(&cookies, "ghostlight_session").is_none()); + assert!(app.state.catalog.lock().await.invite_is_live(&invite, Utc::now()), "the live invite was not redeemed by a browser that never presented it"); + } + + #[tokio::test] + async fn an_identity_linked_to_another_principal_gets_no_session() { + let app = app(vec![], &[]).await; + let invite = invite(&app).await; + { + let mut catalog = app.state.catalog.lock().await; + catalog.sign_in("first", Some(&invite), Utc::now()).unwrap().unwrap(); + catalog.link_identity("first", "second").unwrap(); + } + let (handle, secret) = begin_sign_in(&app, "google", A_BROWSER).await; + app.heimdall.finish(&handle, "authenticated", "second"); + let (status, cookies, body) = complete(&app, &handle, &[("ghostlight_auth", &secret)]).await; + assert_eq!(status, StatusCode::FORBIDDEN, "{body}"); + assert!(cookie_named(&cookies, "ghostlight_session").is_none()); + } + + #[tokio::test] + async fn the_auth_routes_throttle_a_client_by_its_real_ip_alone() { + let app = app(vec![], &[]).await; + let begin = |ip: &'static str| { + auth_call(&app, "/api/auth/begin", &[], ip, json!({"key": Uuid::new_v4(), "provider": "discord"})) + }; + let mut throttled = None; + for attempt in 0..70 { + if begin("198.51.100.7").await.0 == StatusCode::TOO_MANY_REQUESTS { + throttled = Some(attempt); + break; + } + } + assert!(throttled.is_some_and(|attempt| attempt >= 30), "{throttled:?}"); + assert_eq!(begin("198.51.100.8").await.0, StatusCode::OK, "another address is not throttled"); + let (status, _, _) = complete(&app, "x", &[]).await; + assert_ne!(status, StatusCode::TOO_MANY_REQUESTS, "A_BROWSER has its own count"); + } + + #[test] + fn the_throttle_key_is_the_real_ip_header_or_a_shared_direct_bucket() { + let mut headers = HeaderMap::new(); + assert_eq!(client_key(&headers), "direct"); + headers.insert("x-real-ip", HeaderValue::from_static(" ")); + assert_eq!(client_key(&headers), "direct"); + headers.insert("x-real-ip", HeaderValue::from_static(" 203.0.113.9 ")); + assert_eq!(client_key(&headers), "203.0.113.9"); + } + + #[tokio::test] + async fn a_body_over_the_limit_is_refused_and_one_under_it_is_not() { + let app = app(vec![], &[]).await; + let key = |len: usize| json!({"key": "k".repeat(len), "provider": "google"}); + let (status, _, _) = auth_call(&app, "/api/auth/begin", &[], "198.51.100.3", key(5_000)).await; + assert_eq!(status, StatusCode::OK, "a few kilobytes is an ordinary body"); + let (status, _, _) = auth_call(&app, "/api/auth/begin", &[], "198.51.100.3", key(BODY_LIMIT + 1)).await; + assert_eq!(status, StatusCode::PAYLOAD_TOO_LARGE); + } + + #[tokio::test] + async fn a_fatal_custody_signal_reaches_the_runtime_owner_with_its_organ() { + let app = app(vec![], &[]).await; + signal_fatal(&app.state, "app-session custody", &"the store moved"); + assert_eq!( + app.fatal_events.lock().unwrap().try_recv().unwrap(), + "app-session custody: the store moved" + ); + } + + #[tokio::test] + async fn playing_an_older_timeline_moves_the_pointer_to_it() { + let app = app(vec![], &["alice"]).await; + let cookie = app.cookies[0].clone(); + let first = begin_one(&app, &cookie).await; + let second = begin_one(&app, &cookie).await; + let (_, _, me) = call(&app, Method::GET, "/api/me", Some(&cookie), None).await; + assert_eq!(me["currentTimeline"], second.as_str()); + play_text(&app, &cookie, &first, "back to the start", None).await; + let (_, _, me) = call(&app, Method::GET, "/api/me", Some(&cookie), None).await; + assert_eq!(me["currentTimeline"], first.as_str()); + play_text(&app, &cookie, &first, "and again", None).await; + let (_, _, me) = call(&app, Method::GET, "/api/me", Some(&cookie), None).await; + assert_eq!(me["currentTimeline"], first.as_str(), "playing the current timeline leaves it"); + } + + #[tokio::test] + async fn only_the_owner_reaches_a_timeline() { + let app = app(vec![], &["alice", "mallory"]).await; + let timeline = begin_one(&app, &app.cookies[0].clone()).await; + let mallory = app.cookies[1].clone(); + let (status, _, _) = call(&app, Method::GET, &format!("/api/turn/{timeline}"), Some(&mallory), None).await; + assert_eq!(status, StatusCode::NOT_FOUND); + let (status, _) = play_text(&app, &mallory, &timeline, "hello", None).await; + assert_eq!(status, StatusCode::NOT_FOUND); + let (_, _, listed) = call(&app, Method::GET, "/api/timelines", Some(&mallory), None).await; + assert_eq!(listed["timelines"].as_array().unwrap().len(), 0); + } + + #[tokio::test] + async fn a_played_turn_shows_its_narration_in_the_turn_view() { + let script = vec![ + output("r0", vec![call_event("c0", END_TURN_TOOL, json!({}))]), + output("proj-0", vec![text_event("The room settles into quiet.")]), + ]; + let app = app(script, &["alice"]).await; + let cookie = app.cookies[0].clone(); + let timeline = begin_one(&app, &cookie).await; + let (status, body) = play_text(&app, &cookie, &timeline, "I look around.", None).await; + assert_eq!(status, StatusCode::ACCEPTED, "{body}"); + let view = settled_turn(&app, &cookie, &timeline).await; + assert_eq!(view["turn"]["state"], "closed"); + assert_eq!(view["turn"]["narration"], "The room settles into quiet."); + assert!(view["turn"]["fault"].is_null()); + assert!(view["turn"]["question"].is_null()); + } + + #[tokio::test] + async fn a_question_shows_and_only_its_own_token_answers_it() { + let script = vec![ + output("r0", vec![call_event("c0", ASK_PLAYER_TOOL, json!({"question": "Which way?"}))]), + output("r1", vec![call_event("c1", END_TURN_TOOL, json!({}))]), + output("proj-0", vec![text_event("You choose.")]), + ]; + let app = app(script, &["alice"]).await; + let cookie = app.cookies[0].clone(); + let timeline = begin_one(&app, &cookie).await; + play_text(&app, &cookie, &timeline, "A crossroads.", None).await; + let view = settled_turn(&app, &cookie, &timeline).await; + assert_eq!(view["turn"]["state"], "awaiting_player"); + assert_eq!(view["turn"]["question"]["text"], "Which way?"); + let token = view["turn"]["question"]["token"].as_str().unwrap().to_owned(); + let (status, _) = play_text(&app, &cookie, &timeline, "left", Some("forged")).await; + assert_eq!(status, StatusCode::CONFLICT); + let (status, _) = play_text(&app, &cookie, &timeline, "left", None).await; + assert_eq!(status, StatusCode::CONFLICT, "an answer must carry its question's token"); + let (status, _) = play_text(&app, &cookie, &timeline, "left", Some(&token)).await; + assert_eq!(status, StatusCode::ACCEPTED); + let view = settled_turn(&app, &cookie, &timeline).await; + assert_eq!(view["turn"]["state"], "closed"); + // The spent token names nothing now. + let (status, _) = play_text(&app, &cookie, &timeline, "again", Some(&token)).await; + assert_eq!(status, StatusCode::CONFLICT); + } + + /// PA.f212: a turn that died on its model says so, with a fixed line and + /// no endpoint text. PA.f214: an empty message with no turn open is refused. + #[tokio::test] + async fn a_model_fault_shows_a_fault_line_and_an_empty_play_on_no_turn_is_refused() { + let app = app(vec![], &["alice"]).await; + let cookie = app.cookies[0].clone(); + let timeline = begin_one(&app, &cookie).await; + let (status, _) = play_text(&app, &cookie, &timeline, "", None).await; + assert_eq!(status, StatusCode::CONFLICT, "an empty opening has nothing to continue"); + let (status, _) = play_text(&app, &cookie, &timeline, "Hello?", None).await; + assert_eq!(status, StatusCode::ACCEPTED); + let view = settled_turn(&app, &cookie, &timeline).await; + assert_eq!(view["turn"]["fault"], PLAY_FAULT_LINE); + let encoded = view.to_string(); + assert!(!encoded.contains("scripted port exhausted"), "{encoded}"); + } + + #[tokio::test] + async fn two_timelines_isolate() { + let script = vec![ + output("r0", vec![call_event("c0", END_TURN_TOOL, json!({}))]), + output("proj-0", vec![text_event("Only here.")]), + ]; + let app = app(script, &["alice"]).await; + let cookie = app.cookies[0].clone(); + let a = begin_one(&app, &cookie).await; + let b = begin_one(&app, &cookie).await; + assert_ne!(a, b); + let host_a = app.state.timelines.host(&a).await.unwrap(); + let host_b = app.state.timelines.host(&b).await.unwrap(); + let before_b = host_b.world.snapshot().await.unwrap(); + let before_a = host_a.world.snapshot().await.unwrap(); + // A real kernel commit on A. + let owner = principal(&crate::app_session::secret_hash("heimdall-account:alice")); + host_a + .world + .submit_principal( + ghostlight::PrincipalCommandIntent { + id: ghostlight::CommandId::new(), + world_id: before_a.world_id, + expected_revision: before_a.revision, + body: ghostlight::CommandBody::AdvanceTime { + minutes: ghostlight::TickMinutes::new(5).unwrap(), + }, + }, + &owner, + ) + .await + .unwrap(); + play_text(&app, &cookie, &a, "I wait.", None).await; + settled_turn(&app, &cookie, &a).await; + let after_b = host_b.world.snapshot().await.unwrap(); + assert_eq!(before_b.revision, after_b.revision); + assert_eq!(before_b.state_digest, after_b.state_digest); + assert!(host_a.world.snapshot().await.unwrap().revision > before_a.revision); + let (_, _, view_b) = call(&app, Method::GET, &format!("/api/turn/{b}"), Some(&cookie), None).await; + assert!(view_b["turn"].is_null(), "a turn on A must not appear on B"); + } + + #[tokio::test] + async fn one_pointer_across_devices() { + let script = vec![output("r0", vec![call_event("c0", ASK_PLAYER_TOOL, json!({"question": "Which way?"}))])]; + let app = app(script, &["alice", "alice", "mallory"]).await; + let (phone, pc) = (app.cookies[0].clone(), app.cookies[1].clone()); + let timeline = begin_one(&app, &phone).await; + let (_, _, me) = call(&app, Method::GET, "/api/me", Some(&pc), None).await; + assert_eq!(me["currentTimeline"], timeline.as_str()); + play_text(&app, &phone, &timeline, "A crossroads.", None).await; + let on_phone = settled_turn(&app, &phone, &timeline).await; + let (_, _, on_pc) = call(&app, Method::GET, &format!("/api/turn/{timeline}"), Some(&pc), None).await; + assert_eq!(on_phone["turn"]["question"], on_pc["turn"]["question"]); + assert_eq!(on_pc["turn"]["state"], "awaiting_player"); + let (_, _, other) = call(&app, Method::GET, "/api/me", Some(&app.cookies[2]), None).await; + assert!(other["currentTimeline"].is_null()); + } + + #[tokio::test] + async fn the_stream_serves_only_the_owner() { + let app = app(vec![], &["alice", "mallory"]).await; + let timeline = begin_one(&app, &app.cookies[0].clone()).await; + let uri = format!("/api/turn/{timeline}/stream"); + let (status, _, _) = call(&app, Method::GET, &uri, Some(&app.cookies[1]), None).await; + assert_eq!(status, StatusCode::NOT_FOUND); + let response = app + .router + .clone() + .oneshot( + Request::builder() + .uri(&uri) + .header(header::COOKIE, format!("{COOKIE_NAME}={}", app.cookies[0])) + .body(Body::empty()) + .unwrap(), + ) + .await + .unwrap(); + assert_eq!(response.status(), StatusCode::OK); + assert_eq!(response.headers()[header::CONTENT_TYPE], "text/event-stream"); + } + + /// Invites are minted on the operator's socket; the HTTP router has no + /// invite path, from any peer, so the reverse proxy has nothing to forward. + #[tokio::test] + async fn no_http_path_mints_an_invite_even_from_loopback() { + let app = app(vec![], &[]).await; + for peer in ["127.0.0.1:1234", "203.0.113.9:1234"] { + for uri in ["/admin/invite", "/invite", "/api/invite", "/api/admin/invite", "/admin"] { + for method in [Method::POST, Method::GET] { + let mut request = Request::builder() + .method(method.clone()) + .uri(uri) + .header(header::CONTENT_TYPE, "application/json") + .body(Body::from(json!({"hours": 2}).to_string())) + .unwrap(); + request.extensions_mut().insert(axum::extract::ConnectInfo( + peer.parse::().unwrap(), + )); + let response = app.router.clone().oneshot(request).await.unwrap(); + assert_eq!(response.status(), StatusCode::NOT_FOUND, "{method} {uri} from {peer}"); + } + } + } + } + + async fn raw(app: &App, method: Method, uri: &str, peer: &str, proxy_header: Option<(&str, &str)>) -> (StatusCode, HeaderMap, String) { + let mut request = Request::builder().method(method).uri(uri); + if let Some((name, value)) = proxy_header { + request = request.header(name, value); + } + let mut request = request.body(Body::empty()).unwrap(); + request + .extensions_mut() + .insert(axum::extract::ConnectInfo(peer.parse::().unwrap())); + let response = app.router.clone().oneshot(request).await.unwrap(); + let (status, headers) = (response.status(), response.headers().clone()); + let bytes = to_bytes(response.into_body(), 1 << 20).await.unwrap(); + (status, headers, String::from_utf8_lossy(&bytes).into_owned()) + } + + /// `/cultnet/snapshot` is Idunn's route observation: it answers a direct + /// loopback caller and finds no route for anything that came through the + /// reverse proxy, which reaches the daemon from loopback too. + #[tokio::test] + async fn the_route_observation_is_not_reachable_through_the_proxy() { + let app = app(vec![], &[]).await; + for header in ["x-real-ip", "x-forwarded-for", "x-forwarded-proto", "x-forwarded-host", "forwarded"] { + let (status, _, _) = + raw(&app, Method::POST, "/cultnet/snapshot", "127.0.0.1:1", Some((header, "203.0.113.9"))).await; + assert_eq!(status, StatusCode::NOT_FOUND, "{header} from the proxy on loopback"); + } + let (status, _, _) = raw(&app, Method::POST, "/cultnet/snapshot", "203.0.113.9:1", None).await; + assert_eq!(status, StatusCode::NOT_FOUND, "a non-loopback peer"); + let (status, _, _) = raw(&app, Method::POST, "/cultnet/snapshot", "127.0.0.1:1", None).await; + assert_eq!(status, StatusCode::UNSUPPORTED_MEDIA_TYPE, "a direct loopback caller reaches the handler"); + } + + /// The page is three embedded files with a script-free policy. Its script + /// renders server text only as text, and no file names the connector key. + #[tokio::test] + async fn the_page_is_served_unauthenticated_under_a_strict_policy() { + let app = app(vec![], &[]).await; + for (uri, kind) in [("/", "text/html"), ("/page.css", "text/css"), ("/page.js", "text/javascript")] { + let (status, headers, body) = raw(&app, Method::GET, uri, "203.0.113.9:1", Some(("x-real-ip", "203.0.113.9"))).await; + assert_eq!(status, StatusCode::OK, "{uri}"); + assert!(headers[header::CONTENT_TYPE].to_str().unwrap().starts_with(kind), "{uri}"); + let policy = headers[header::CONTENT_SECURITY_POLICY].to_str().unwrap(); + assert!(policy.contains("script-src 'self'") && !policy.contains("unsafe-"), "{policy}"); + assert!(!body.contains("connection-ghostlight") && !body.contains("CREDENTIALS_DIRECTORY"), "{uri}"); + if uri == "/" { + assert!(!body.contains("