diff --git a/.gitignore b/.gitignore index e90c6ba..3c71615 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,4 @@ node_modules/ -web/dist/ sidecar/claude-sdk/dist/ target/ diff --git a/.gitmodules b/.gitmodules deleted file mode 100644 index 578af4b..0000000 --- a/.gitmodules +++ /dev/null @@ -1,3 +0,0 @@ -[submodule "vendor/eve"] - path = vendor/eve - url = https://github.com/GameCult/Eve.git diff --git a/AGENTS.md b/AGENTS.md index d258e9c..f0e4406 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -5,7 +5,8 @@ Ghostlight is a Rust world kernel and the play daemon built on it. Models propose; the kernel admits or refuses. The same kernel is meant to run the simulation behind Aetheria's public story, a persistent cast and storylets, as -well as Ghostlight Dungeon, the single-player DM-led client. `README.md` says +well as Ghostlight Dungeon, the single-player DM-led client (parked at +tag `parked/ghostlight-eve-surface`). `README.md` says what exists today and what does not. ## Where State Lives @@ -55,28 +56,21 @@ what exists today and what does not. - Kernel: `crates/ghostlight/src/`. Its vocabulary and current mechanism: `docs/architecture/ghostlight-world-ontology.md`. The consumer contract: `docs/architecture/ghostlight-world-consumer-api.md`. -- Dungeon daemon: `crates/ghostlight-dungeon/src/` (`runtime.rs` for routes and - commands, `play.rs` for the play table, `eve.rs` for the surface). - Interface authority: `docs/architecture/ghostlight-eve-native-interface.md`. +- Parked Dungeon (daemon, play table, Eve surface, browser host, Idunn recipe): + tag `parked/ghostlight-eve-surface`; not on main. - Persona membrane: `crates/ghostlight-persona-projection/src/lib.rs`. -- Browser host: `web/`. Claude SDK sidecar: `sidecar/claude-sdk/`. -- Architecture rationale: `docs/architecture/ghostlight-dungeon-mvp.md`. +- Claude SDK sidecar: `sidecar/claude-sdk/`. +- Architecture rationale (the parked Dungeon's): `docs/architecture/ghostlight-dungeon-mvp.md`. `notes/ghostlight-implementation-plan.md` is the historical plan of the 2026-09 rebuild, not the current plan. ## Build, Verify, Deploy -Ghostlight Dungeon ships to Linux on Yggdrasil. Idunn freezes an exact commit, -runs the locked native Linux tests, builds the daemon and web projection in -pinned containers, and seals the release. The steps are -`deployment/idunn/recipe.toml`; the owning runbook is -`gamecult-ops/runbooks/ghostlight-dungeon-yggdrasil.md`. - -You are probably reading this on a Windows workstation. That is where the shell -is, not where the artifact runs. A Windows compile is not evidence about the -Linux release; build for the target, or let the deploy path's builder do it, and -say which one you used. Heavy builds and test runs go to Yggdrasil, not the -workstation. Deploy only through Idunn (`idunn up ghostlight`). +Nothing deploys from this repo: the Idunn target `ghostlight` is braked and stopped (deployment and +lifecycle brakes engaged, unit stopped; retirement waits on +`ghostlight-verse:follow_up:idunn-v2-target-retirement`) and no recipe exists on main. Kernel and verse tests run on Linux on Yggdrasil (the +`ygg-verify` stopgap), not on the workstation; a Windows compile is not evidence +about Linux, so say which host you used. Do not run `idunn up ghostlight`. For infrastructure, SSH, Idunn, Odin, or Heimdall work, consult `F:\Projects\gamecult-ops` before acting. diff --git a/Cargo.lock b/Cargo.lock index 892fe21..2895d58 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -61,6 +61,15 @@ version = "1.0.104" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" +[[package]] +name = "ar_archive_writer" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "523e5e187fff36fcb8d1d19ccf0ca4ca43ec3d158316057f66dc6f72716bc5ec" +dependencies = [ + "object", +] + [[package]] name = "async-stream" version = "0.3.6" @@ -176,12 +185,6 @@ version = "0.22.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" -[[package]] -name = "base64" -version = "0.23.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5" - [[package]] name = "base64ct" version = "1.8.3" @@ -272,22 +275,6 @@ dependencies = [ "inout", ] -[[package]] -name = "codex-connector" -version = "0.1.0" -source = "git+https://github.com/GameCult/CodexConnector.git?rev=68fe94b9475823de92ed766a97ea962d48723708#68fe94b9475823de92ed766a97ea962d48723708" -dependencies = [ - "aes-gcm", - "base64 0.23.1", - "rand_core 0.6.4", - "rmp-serde", - "serde", - "serde_json", - "sha2", - "thiserror", - "zeroize", -] - [[package]] name = "const-oid" version = "0.9.6" @@ -345,7 +332,7 @@ source = "git+https://github.com/GameCult/CultLib.git?rev=85f7024a35ea42cf9f0a01 dependencies = [ "anyhow", "chrono", - "cultcache-rs-derive", + "cultcache-rs-derive 0.1.0", "fs2", "redb", "rmp-serde", @@ -356,6 +343,26 @@ dependencies = [ "windows-sys 0.59.0", ] +[[package]] +name = "cultcache-rs" +version = "0.3.1" +source = "git+https://github.com/GameCult/CultLib.git?rev=a4eae9056152335662f1115f97bf35fb00ab6d23#a4eae9056152335662f1115f97bf35fb00ab6d23" +dependencies = [ + "anyhow", + "chrono", + "cultcache-rs-derive 0.2.0", + "fs2", + "redb", + "rmp-serde", + "serde", + "serde_bytes", + "serde_json", + "serde_stacker", + "stacker", + "uuid", + "windows-sys 0.59.0", +] + [[package]] name = "cultcache-rs-derive" version = "0.1.0" @@ -366,14 +373,24 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "cultcache-rs-derive" +version = "0.2.0" +source = "git+https://github.com/GameCult/CultLib.git?rev=a4eae9056152335662f1115f97bf35fb00ab6d23#a4eae9056152335662f1115f97bf35fb00ab6d23" +dependencies = [ + "proc-macro2", + "quote", + "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", - "cultnet-rs", + "cultcache-rs 0.1.0", + "cultnet-rs 0.1.0", "serde", ] @@ -384,9 +401,34 @@ source = "git+https://github.com/GameCult/CultLib.git?rev=85f7024a35ea42cf9f0a01 dependencies = [ "aes-gcm", "anyhow", - "base64 0.22.1", + "base64", "chrono", - "cultcache-rs", + "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" +source = "git+https://github.com/GameCult/CultLib.git?rev=a4eae9056152335662f1115f97bf35fb00ab6d23#a4eae9056152335662f1115f97bf35fb00ab6d23" +dependencies = [ + "aes-gcm", + "anyhow", + "base64", + "chrono", + "cultcache-rs 0.3.1", "ed25519-dalek", "hmac", "rand 0.9.5", @@ -441,9 +483,9 @@ dependencies = [ [[package]] name = "deranged" -version = "0.5.8" +version = "0.5.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7cd812cc2bc1d69d4764bd80df88b4317eaef9e773c75226407d9bc0876b211c" +checksum = "9e9de72ce2ad1f90dc62fa25f0f430ef85eb4b0d8fa0be4f30373bc40a21d28e" [[package]] name = "digest" @@ -467,6 +509,12 @@ dependencies = [ "syn 3.0.3", ] +[[package]] +name = "dyn-clone" +version = "1.0.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d0881ea181b1df73ff77ffaaf9c7544ecc11e82fba9b5f27b262a3c73a332555" + [[package]] name = "ed25519" version = "2.2.3" @@ -663,11 +711,12 @@ version = "0.1.0" dependencies = [ "async-trait", "chrono", - "codex-connector", - "cultcache-rs", + "cultcache-rs 0.1.0", "ghostlight-persona-projection", + "model-connector", "reqwest", "rmp-serde", + "rmpv", "serde", "serde_bytes", "serde_json", @@ -676,6 +725,8 @@ dependencies = [ "thiserror", "tokio", "tracing", + "unicode-normalization", + "unicode-properties", "uuid", "zeroize", ] @@ -689,29 +740,27 @@ dependencies = [ "async-stream", "async-trait", "axum", - "base64 0.22.1", + "base64", "chrono", - "codex-connector", - "cultcache-rs", + "cultcache-rs 0.1.0", "cultmesh-rs", - "cultnet-rs", + "cultnet-rs 0.1.0", "ghostlight", "ghostlight-persona-projection", "hmac", "jsonwebtoken", "libc", + "model-connector", "rand 0.9.5", "reqwest", "rmp-serde", "serde", - "serde_bytes", "serde_json", "sha2", "tempfile", "thiserror", "tokio", "tower", - "tower-http", "tracing", "tracing-subscriber", "uuid", @@ -727,6 +776,18 @@ dependencies = [ "unicode-segmentation", ] +[[package]] +name = "ghostlight-verse" +version = "0.1.0" +dependencies = [ + "anyhow", + "chrono", + "ghostlight", + "serde_json", + "tempfile", + "tokio", +] + [[package]] name = "hmac" version = "0.12.1" @@ -769,12 +830,6 @@ dependencies = [ "pin-project-lite", ] -[[package]] -name = "http-range-header" -version = "0.4.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9171a2ea8a68358193d15dd5d70c1c10a2afc3e7e4c5bc92bc9f025cebd7359c" - [[package]] name = "httparse" version = "1.10.1" @@ -830,7 +885,7 @@ version = "0.1.20" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "96547c2556ec9d12fb1578c4eaf448b04993e7fb79cbaad930a656880a6bdfa0" dependencies = [ - "base64 0.22.1", + "base64", "bytes", "futures-channel", "futures-util", @@ -1013,7 +1068,7 @@ version = "9.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5a87cc7a48537badeae96744432de36f4be2b4a34a05a5ef32e9dd8a1c169dde" dependencies = [ - "base64 0.22.1", + "base64", "js-sys", "pem", "ring", @@ -1024,9 +1079,9 @@ dependencies = [ [[package]] name = "lazy_static" -version = "1.5.0" +version = "1.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe" +checksum = "20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb" [[package]] name = "libc" @@ -1090,19 +1145,9 @@ checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" [[package]] name = "mime" -version = "0.3.17" +version = "0.3.18" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a" - -[[package]] -name = "mime_guess" -version = "2.0.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f7c44f8e672c00fe5308fa235f821cb4198414e1c77935c1ab6948d3fd78550e" -dependencies = [ - "mime", - "unicase", -] +checksum = "d5848f5a9e8117cf94f2f90faac24a87ff81600ff8628c1e3deaab572e76bfa1" [[package]] name = "mio" @@ -1115,6 +1160,26 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "model-connector" +version = "0.1.0" +source = "git+https://eureka.gamecult.org/forge/GameCult/ModelConnector.git?rev=edf2f8e03cbb61df385b9b145b46f676ce3b70d5#edf2f8e03cbb61df385b9b145b46f676ce3b70d5" +dependencies = [ + "aes-gcm", + "base64", + "cultnet-rs 0.2.0", + "rand_core 0.6.4", + "rmp-serde", + "rmpv", + "schemars", + "serde", + "serde_bytes", + "serde_json", + "sha2", + "thiserror", + "zeroize", +] + [[package]] name = "nu-ansi-term" version = "0.50.3" @@ -1158,6 +1223,15 @@ dependencies = [ "autocfg", ] +[[package]] +name = "object" +version = "0.39.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2e5a6c098c7a3b6547378093f5cc30bc54fd361ce711e05293a5cc589562739b" +dependencies = [ + "memchr", +] + [[package]] name = "once_cell" version = "1.21.4" @@ -1199,7 +1273,7 @@ version = "3.0.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1d30c53c26bc5b31a98cd02d20f25a7c8567146caf63ed593a9d87b2775291be" dependencies = [ - "base64 0.22.1", + "base64", "serde_core", ] @@ -1248,9 +1322,9 @@ dependencies = [ [[package]] name = "powerfmt" -version = "0.2.0" +version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "439ee305def115ba05938db6eb1644ff94165c5ab5e9420d1c1bcedbba909391" +checksum = "4a6394b9e965e73d0a289ee54f589087e2c676aedf60885baf52c76b771e4958" [[package]] name = "ppv-lite86" @@ -1270,6 +1344,16 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "psm" +version = "0.1.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4dcd034599e63b970727f70d79e02d62390a4a84f7c6b827c27c46d5ac3fa622" +dependencies = [ + "ar_archive_writer", + "cc", +] + [[package]] name = "quinn" version = "0.11.11" @@ -1430,10 +1514,30 @@ dependencies = [ ] [[package]] -name = "regex-automata" -version = "0.4.18" +name = "ref-cast" +version = "1.0.27" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2" +checksum = "7e440fb4e4b4147295338efb76001ab9e4efc0e5839df2c47fc5ac2381d365c3" +dependencies = [ + "ref-cast-impl", +] + +[[package]] +name = "ref-cast-impl" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92ecd8964f8453721699a1ed72037b0db49ce2f5a5138486ee89bed6f67cdf3a" +dependencies = [ + "proc-macro2", + "quote", + "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", @@ -1442,9 +1546,9 @@ dependencies = [ [[package]] name = "regex-syntax" -version = "0.8.11" +version = "0.8.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" +checksum = "d902046e6a28a1e4c3cab97258a0ce11e994903f01c2d97a9447a0b3df85f4f6" [[package]] name = "reqwest" @@ -1452,7 +1556,7 @@ version = "0.12.28" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "eddd3ca559203180a307f12d114c268abf583f59b03cb906fd0b3ff8646c1147" dependencies = [ - "base64 0.22.1", + "base64", "bytes", "futures-core", "futures-util", @@ -1606,6 +1710,31 @@ version = "1.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" +[[package]] +name = "schemars" +version = "1.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ab508826f74a77ca9d5aba6ff19b522583ee3eaf28a19384ff3d0e5835fadf6e" +dependencies = [ + "dyn-clone", + "ref-cast", + "schemars_derive", + "serde", + "serde_json", +] + +[[package]] +name = "schemars_derive" +version = "1.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e1c3a92094fa7d61aa124645844facb6b554dfc797136d0f5fd1f890e2bffc69" +dependencies = [ + "proc-macro2", + "quote", + "serde_derive_internals", + "syn 3.0.3", +] + [[package]] name = "scopeguard" version = "1.2.0" @@ -1658,6 +1787,17 @@ dependencies = [ "syn 3.0.3", ] +[[package]] +name = "serde_derive_internals" +version = "0.30.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f852137cce035d6a4df67ccce505ff6b3e9fd3a10e3e52b24dc71e650bb1a9bd" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.3", +] + [[package]] name = "serde_json" version = "1.0.151" @@ -1682,6 +1822,17 @@ dependencies = [ "serde_core", ] +[[package]] +name = "serde_stacker" +version = "0.1.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d4936375d50c4be7eff22293a9344f8e46f323ed2b3c243e52f89138d9bb0f4a" +dependencies = [ + "serde", + "serde_core", + "stacker", +] + [[package]] name = "serde_urlencoded" version = "0.7.1" @@ -1799,6 +1950,19 @@ version = "1.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" +[[package]] +name = "stacker" +version = "0.1.25" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "707f49d46706bacf8a2b00d51dace3f9de527c13eec3778f570c411f89e69967" +dependencies = [ + "cc", + "cfg-if", + "libc", + "psm", + "windows-sys 0.61.2", +] + [[package]] name = "subtle" version = "2.6.1" @@ -2019,23 +2183,13 @@ checksum = "4cfcf7e2740e6fc6d4d688b4ef00650406bb94adf4731e43c096c3a19fe40840" dependencies = [ "bitflags", "bytes", - "futures-core", "futures-util", "http", "http-body", - "http-body-util", - "http-range-header", - "httpdate", - "mime", - "mime_guess", - "percent-encoding", "pin-project-lite", - "tokio", - "tokio-util", "tower", "tower-layer", "tower-service", - "tracing", "url", ] @@ -2125,18 +2279,27 @@ version = "1.20.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" -[[package]] -name = "unicase" -version = "2.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dbc4bc3a9f746d862c45cb89d705aa10f187bb96c76001afab07a0d35ce60142" - [[package]] name = "unicode-ident" version = "1.0.24" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75" +[[package]] +name = "unicode-normalization" +version = "0.1.25" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5fd4f6878c9cb28d874b009da9e8d183b5abc80117c40bbd187a1fde336be6e8" +dependencies = [ + "tinyvec", +] + +[[package]] +name = "unicode-properties" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7df058c713841ad818f1dc5d3fd88063241cc61f49f5fbea4b951e8cf5a8d71d" + [[package]] name = "unicode-segmentation" version = "1.13.3" @@ -2531,18 +2694,18 @@ dependencies = [ [[package]] name = "zerocopy" -version = "0.8.56" +version = "0.8.66" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "556764e583adb45a9f8d413c2a147fa7e8d821e48e12b14fd560b607998b75eb" +checksum = "cba8a86aee14fc8cc6c208af60854b3d4ab7185a9a369a12c648faa2716ff42a" dependencies = [ "zerocopy-derive", ] [[package]] name = "zerocopy-derive" -version = "0.8.56" +version = "0.8.66" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f2ab42fc20575779bd240faa45f94a74256f755c0fa9e89f0ede20d91d0cdfc1" +checksum = "f89bca3b96ceb3cfcb4572790402f977442270d252b9a8504ebc258760c55f94" dependencies = [ "proc-macro2", "quote", diff --git a/Cargo.toml b/Cargo.toml index 7bfeb7e..0f5ed13 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -3,6 +3,7 @@ members = [ "crates/ghostlight", "crates/ghostlight-dungeon", "crates/ghostlight-persona-projection", + "crates/ghostlight-verse", ] resolver = "2" @@ -19,7 +20,7 @@ async-stream = "0.3" axum = { version = "0.8", features = ["macros"] } chrono = { version = "0.4", features = ["serde"] } base64 = "0.22" -codex-connector = { git = "https://github.com/GameCult/CodexConnector.git", rev = "68fe94b9475823de92ed766a97ea962d48723708" } +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" } @@ -33,7 +34,6 @@ serde_json = "1" sha2 = "0.10" thiserror = "2" tokio = { version = "1", features = ["full"] } -tower-http = { version = "0.6", features = ["fs", "trace"] } tracing = "0.1" tracing-subscriber = { version = "0.3", features = ["env-filter"] } unicode-segmentation = "1" diff --git a/README.md b/README.md index ffd2855..ff4a893 100644 --- a/README.md +++ b/README.md @@ -1,149 +1,121 @@ # Ghostlight -Ghostlight is a Rust library that keeps a simulated world honest, and a play -daemon built on it. A language model proposes; the library's kernel checks each -proposal against typed world state and admits or refuses it. Places, people, -knowledge, commitments, and time live in the kernel's journal, not in a model's -context window, so they survive restarts and long stories. +**Ghostlight is a world kernel: typed world state that a language model can +propose changes to and can never write.** The valuable part is +`crates/ghostlight`. The Dungeon game, one client of it, is parked (below). -## What is here +**The thesis.** World state is typed documents. Every change to it, and every +narrative dependency on it, is an operation in a closed, predefined algebra. +Models propose operations; the kernel checks each against the state (references, +preconditions, authority, conservation, who knows what) and admits it or refuses +it with the complete list of mismatches. Narration describes only what was +committed. A model-as-game-master holds the world in a context window and +drifts; here the world is a digest-chained journal that survives restarts and +cannot be talked into contradicting itself. -| Part | Path | What it is | -|---|---|---| -| World kernel | `crates/ghostlight/` | The sealed `ghostlight` library: world state, the closed operation set and reducer, the CultCache journal, the mailbox that is its only door, controllers, elaboration, lenses, the consumer ingress, and the inference ports. | -| Persona projection | `crates/ghostlight-persona-projection/` | The membrane between structured state and a prose-only Persona: projection, Persona turn receipts, and the controller descriptors the kernel consumes. | -| Dungeon | `crates/ghostlight-dungeon/` | The `ghostlight-dungeon` daemon: single-player, DM-led play over one world. HTTP and Eve routes, Heimdall sign-in, app sessions, the play table, CultMesh publication, and Idunn health. | -| Browser | `web/` | A thin Eve browser host and the Heimdall access adapter. It renders the server's surface and owns no product state. | -| Claude SDK sidecar | `sidecar/claude-sdk/` | A Node process that serves `claude`-prefixed models to the kernel through the Claude Agent SDK. It is a stopgap for a direct Messages API port. | -| Deploy recipe | `deployment/idunn/recipe.toml` | The steps Idunn runs to test, build, and seal a release. | -| Eve | `vendor/eve/` | A git submodule (`.gitmodules`) supplying the Eve browser lowering and contracts. | +**Use it as a structured state backend.** Do not judge it by the parked Dungeon's +prose. The kernel is a library; prose comes from whichever model you plug into +its ports. -## How it works +- `crates/ghostlight`: the sealed library. A consumer gets create/open + (`WorldMailbox::open`, `create`), immutable snapshots (`snapshot`), command + submission through role-scoped ports (`PlayPort`, `ConsumerPort`, + `ControllerPort`, `SeedPort`), typed receipts, and the runner and inference-port + entry points (`ControllerRunner`, `ElaborationRunner`, `SeedRunner`, + `InferencePort`). Mutable state, ID issuers, the reducer and the journal + writer are not public. `compile_fail` doc-tests in `crates/ghostlight/src/lib.rs` + and `crates/ghostlight/tests/external_admission.rs` prove the seal. +- `docs/architecture/ghostlight-world-ontology.md`: the vocabulary (subjects, + places, routes, holdings, knowledge, commitments, pressures), the operation + algebra, and what the reducer checks. +- `docs/architecture/ghostlight-world-consumer-api.md`: the contract for a + program that reads a world and proposes changes to the characters it controls + (`POST /cultnet/world-patch`; no process on main serves that door, a host serves + `ghostlight::admit_document`). -- The kernel is sealed. A consumer reaches it through create/open, immutable - snapshots, command submission, typed receipts, and the runner and port entry - points. There is no public mutable state, ID issuer, reducer, or journal - writer, and the crate declares no cargo features. The seal is proven by - `compile_fail` doc-tests in `crates/ghostlight/src/lib.rs` and by - `crates/ghostlight/tests/external_admission.rs`, which forges IDs, digests, - and opportunities and asserts that each is refused with nothing committed. -- Every change enters one mailbox (`crates/ghostlight/src/mailbox.rs`) as a - command, is decided by one reducer, and commits atomically to a - digest-chained journal (`crates/ghostlight/src/journal.rs`, CultCache on redb). -- Models author through typed tools and a repair loop - (`crates/ghostlight/src/elaboration.rs`, `tool_schema.rs`, `patch.rs`). A - refused proposal returns its mismatches to the model; it never edits state. -- A Persona speaks only prose. A Projector builds its view, and an Interpreter - lowers its words into typed proposals with exact source quotes - (`crates/ghostlight/src/controllers.rs`). -- Vault evidence for seeding comes from a read-only markdown directory reader - (`crates/ghostlight/src/vault.rs`). The Dungeon's seed lane reads the - directory named by `GHOSTLIGHT_SEED_VAULT_ROOT`, read once at startup, so - changing it needs a restart - (`crates/ghostlight-dungeon/src/runtime.rs`). -- Other programs can propose changes to the characters they control through - `POST /cultnet/world-patch` (`crates/ghostlight-dungeon/src/runtime.rs`, - `crates/ghostlight/src/consumer.rs`). The contract is - `docs/architecture/ghostlight-world-consumer-api.md`. +Start with those two documents, then `cargo doc -p ghostlight --open`. -## Ghostlight Dungeon +**Populate the algebra first.** The kernel owns the component operations; a world owns its +affordance catalog, the verbs its actors can attempt. A fresh world knows one: the built-in +Speak, which records an utterance and changes nothing. Until your world declares affordances +(at genesis, by patch, or through elaborators) for moving, trading, taking, deciding and so on, +every intent a model voices lowers to speech or to a recorded gap, and the prose built on that +will be thin no matter how good the model is. The Aetheria verse genesis +(`crates/ghostlight/src/verse/genesis.rs`) declares its grammar's verbs, and today they still +only record the act; their effects are the next phase. -Dungeon is the single-player, DM-led client. A player signs in with Heimdall, -creates a world, seeds it from a vault, approves and activates it, and plays in -free text. The play table (`crates/ghostlight-dungeon/src/play.rs`) owns the -turn lifecycle; the interface is one Eve surface, `ghostlight.play` -(`crates/ghostlight-dungeon/src/eve.rs`, described in -`docs/architecture/ghostlight-eve-native-interface.md`). Because its player is -not a developer, Dungeon is judged by whether someone can sit down and play. +## Elaborators -Where it runs: +An elaborator is a model session, confined to one jurisdiction of the world, that +adds structure where the world is thin: it answers a derived causal boundary +(a destination nobody has described yet) or a scale deficit with typed +declarations, and the kernel verifies the result like any other patch. Sessions +are resumable and checkpointed against committed history. Eight stock lenses +(`crates/ghostlight/src/lens.rs`: patina, charter, ledger, hearth, tangle, veil, +ember, numen) give each session a role-specific emphasis, for example customs and +local jokes, or money and ledgers. A lens changes the prompt only, never what the +kernel admits. Because boundaries are derived from state, elaborators can be +dispatched as the player approaches a place or a social structure, instead of +authoring the world up front. -- **Yggdrasil**, under Idunn, built from `main` by `deployment/idunn/recipe.toml`. - Idunn owns the daemon's lifecycle and the write lease. Odin supplies discovery - and Heimdall's command-boundary record. The operating runbook is - `gamecult-ops/runbooks/ghostlight-dungeon-yggdrasil.md`. -- **Inference** is routed by model name: a `local/` prefix goes to an - OpenAI-compatible loopback endpoint - (`GHOSTLIGHT_LOCAL_ENDPOINT`, `crates/ghostlight/src/local_inference.rs`), - which in production is Bonsai on Raven's GPU reached through a loopback - tunnel; a `claude` prefix goes to the SDK sidecar - (`GHOSTLIGHT_SDK_SIDECAR`, `crates/ghostlight/src/sdk_inference.rs`). - Ghostlight never reads, stores, or forwards a model credential. -- **Sign-in** is Heimdall's. Ghostlight keeps a hashed HttpOnly session and - derives authority from the world's owner and approvers. +## Direction (planned, not built) -## Direction +Use the kernel to simulate a whole world with many kinds of actor: Aetheria's +factions and a persistent cast whose members keep identity, memory and +commitments across sessions. Newspaper-staff simulations before the 2026-08 +teardown are the earlier proof of the idea; that code is in git history, not in +the tree. Running this at scale is gated by inference cost, not by the design. +`crates/ghostlight-verse` is the first slice: `ghostlight-verse genesis` creates +an Aetheria verse world from the Aetheria catalog and `ghostlight-verse run` +advances it a number of ticks under a token cap, reporting per tick what each +faction did and what it cost. Nothing loads AetheriaLore prose, models +storylets, or produces episodes yet. Targets: `notes/ghostlight-verse-target.md`. -The next work makes Ghostlight the simulation behind Aetheria's public story. -The operator's rulings (campaign `ghostlight-verse` in the Eureka mind) ask for: +## Ghostlight Dungeon (parked) -- a world loaded from the Aetheria verse, with factions and a cast; -- storylets for Aetheria; -- a persistent cast whose characters keep identity, memory, and commitments - across sessions, so serialized episodes can follow them; -- episodes a cheap pipeline can turn into a video stream, and channel - characters who later appear in the game. +The single-player, DM-led client and its daemon, Eve play surface and browser +host are parked at tag `parked/ghostlight-eve-surface`. Nothing is deployed and +nothing on main serves HTTP. The Dungeon returns when Thing 2 gives it a UI +(follow-up `dungeon-ui-on-thing2`); the rebuild starts from the tag. -None of this exists yet. Nothing under `crates/` loads Aetheria lore, models -storylets, or produces an episode. Every event the kernel admits is meant to -have exactly one render path: ship action filmed in Aetheria, or a social verb -staged as an Aetheria conversation. Today a world can declare any affordance -kind, and the kernel does not enforce that restriction. +## Repo map + +| Path | What it is | +|---|---| +| `crates/ghostlight/` | The sealed kernel library. | +| `crates/ghostlight-persona-projection/` | Membrane between structured state and a prose-only Persona. | +| `crates/ghostlight-verse/` | The `ghostlight-verse` operator command line (`genesis`, `run`). | +| `sidecar/claude-sdk/` | Node process serving `claude`-prefixed models to the kernel; a stopgap for a direct Messages API port. | +| `AGENTS.md` | Invariants and where things are. | +| `docs/architecture/ghostlight-dungeon-mvp.md` | The parked Dungeon's authority architecture (design record). | +| `notes/` | The verse campaign's target and map, the handoff pointer, local smoke notes. | + +`docs/public-architecture/`, `docs/articles/` and `docs/product/` are design +essays and proposals from before the rebuild. They describe organs (campaigns, +co-op, Nemesis, newspapers) that are not in `crates/`; they do not describe the +running machine. Pages ending in `-cut.md` or `-postmortem.md` are dated history. ## Build and test -The release target is Linux on Yggdrasil; a Windows build says nothing about -it. Idunn runs the steps in `deployment/idunn/recipe.toml`, which are the -verification: +Nothing deploys from this repo. Linux verification runs on Yggdrasil, not on a +workstation: ```sh -git submodule update --init vendor/eve +cargo build --locked --workspace cargo test --locked -p ghostlight-persona-projection cargo test --locked -p ghostlight -cargo test --locked -p ghostlight-dungeon --bin ghostlight-dungeon -cargo build --locked --release -p ghostlight-dungeon --bin ghostlight-dungeon -npm --prefix web ci -npm --prefix web test -npm --prefix web run build +cargo test --locked -p ghostlight-verse ``` -The sidecar has its own `npm --prefix sidecar/claude-sdk run build` and `test` -(also the root scripts `sdk:build` and `sdk:test`). Four Dungeon tests are -`#[ignore]`d because they drive the vendored browser lowering through -`tools/eve_client_bridge.mjs` and need Node beside cargo. The release -acceptance step runs `controllers::tests::real_local_model_cognition_modes_commit_speech` -(ignored by default) against a real model. +The kernel alone needs only `cargo test -p ghostlight`. The sidecar has +`npm run sdk:build` and `npm run sdk:test`. The acceptance test +`controllers::tests::real_local_model_cognition_modes_commit_speech` is ignored +by default and needs a real model. -To run Dungeon locally: `npm run dungeon:run`, or -`cargo run -p ghostlight-dungeon -- --state-root PATH`. Configuration is by -`GHOSTLIGHT_*` environment variables; the recipe's `required_environment` -lists the ones a deployment sets. +Inference is routed by model name: `local/` goes to an OpenAI-compatible +loopback endpoint, `claude` to the SDK sidecar, and the verse runner's `hosted/` +to an https endpoint. Ghostlight never reads, stores or forwards a model +credential beyond a key file named at run time. -## Documents - -- `AGENTS.md`: repository doctrine for agents. -- `docs/architecture/ghostlight-dungeon-mvp.md`: the authority architecture - of the world machine. -- `docs/architecture/ghostlight-world-ontology.md`: the vocabulary and the - kernel's current mechanism. -- `docs/architecture/ghostlight-world-consumer-api.md`: the consumer contract. -- `docs/architecture/ghostlight-eve-native-interface.md`: the Eve surface. -- `docs/architecture/ghostlight-library-extraction.md`, - `ghostlight-stock-lenses.md`: closed records of landed work. Pages ending in - `-cut.md` and `-postmortem.md` are dated history. -- `docs/architecture/ghostlight-play-agent.md`: historical. Its status line - predates the play-agent cuts; read it with `-cut.md` beside it, not as the - current play surface (`crates/ghostlight-dungeon/src/play.rs` is). -- `docs/architecture/ghostlight-session-zero.md`: unbuilt design, superseded by - the play agent. Nothing in `crates/` implements it. -- `notes/fresh-workspace-handoff.md`: where things run and where open work is - recorded. -- `docs/public-architecture/`, `docs/articles/`: unbuilt design and essays - written before the rebuild. They describe campaigns, co-op, Nemesis - and strategic resolvers as organs; none of that exists in `crates/`. They do not - describe the running machine. -- `docs/product/lore-vault-entitlements.md`: a product proposal for hosted - vaults; nothing in `crates/` implements it. - -Runtime documents use MessagePack-backed CultCache. JSON appears only at schema -publication, browser, model-provider, and diagnostic boundaries. +Runtime documents are MessagePack-backed CultCache. JSON appears only at schema +publication, model-provider and diagnostic boundaries. diff --git a/crates/ghostlight-dungeon/Cargo.toml b/crates/ghostlight-dungeon/Cargo.toml index 032aecd..39babbb 100644 --- a/crates/ghostlight-dungeon/Cargo.toml +++ b/crates/ghostlight-dungeon/Cargo.toml @@ -17,8 +17,8 @@ async-stream.workspace = true axum.workspace = true chrono.workspace = true base64.workspace = true -codex-connector.workspace = true cultcache-rs.workspace = true +model-connector.workspace = true cultnet-rs.workspace = true cultmesh-rs.workspace = true jsonwebtoken.workspace = true @@ -31,11 +31,9 @@ reqwest.workspace = true rmp-serde.workspace = true serde.workspace = true serde_json.workspace = true -serde_bytes = "0.11" sha2.workspace = true thiserror.workspace = true tokio.workspace = true -tower-http.workspace = true tracing.workspace = true tracing-subscriber.workspace = true uuid.workspace = true 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/playtest/plan.json b/crates/ghostlight-dungeon/playtest/plan.json new file mode 100644 index 0000000..53d26d9 --- /dev/null +++ b/crates/ghostlight-dungeon/playtest/plan.json @@ -0,0 +1,79 @@ +{ + "turns_per_character": 12, + "wall_minutes": 240, + "turn_timeout_minutes": 15, + "temperaments": { + "diplomat": { + "goal": "Make allies and brokered deals; leave every room better disposed toward you than you found it.", + "manner": "Talks first and listens closely. Offers trades, introductions and face-saving ways out. Never draws a weapon unless cornered.", + "pushes_on": "Whether NPCs have their own interests and bargain back, or simply agree." + }, + "murderhobo": { + "goal": "Take what you want and answer slights with steel.", + "manner": "Quick to anger, blunt, armed. Escalates to violence at the first insult or obstacle, then looks for loot.", + "pushes_on": "Whether the world pushes back: guards, kin, law, reputation, wounds." + }, + "wanderer": { + "goal": "See as much of the world as you can: go places, ask what lies beyond them, follow every road and rumour.", + "manner": "Curious and restless. Moves on whenever somewhere is explored. Asks locals about the next place and about their own history.", + "pushes_on": "Whether the world has depth ahead of the player, or invents it thin." + }, + "schemer": { + "goal": "Gain power by playing factions against one another.", + "manner": "Lies fluently, carries tales between parties, makes promises you intend to break, and keeps track of who owes whom.", + "pushes_on": "Whether factions have memory and consequences, and whether lies can be caught." + }, + "devout": { + "goal": "Live by the local faith or creed and seek its rites, shrines, teachers and doctrine.", + "manner": "Earnest and respectful. Asks what is believed, what is forbidden, what is owed to the powers. Takes part in observances.", + "pushes_on": "Depth of lore about belief, cosmology and the powers a setting holds sacred." + }, + "grifter": { + "goal": "Come out ahead through theft, cheating and unpaid debts.", + "manner": "Charming and shifty. Picks pockets, short-changes, forges, runs cons, skips out on what is owed.", + "pushes_on": "Whether ledgers, debts, law and watchfulness exist and bite." + }, + "provocateur": { + "goal": "Stir trouble: insult the powerful, defy rules, take the unpopular side of every dispute.", + "manner": "Loud, contrarian, theatrical. Says what nobody wants said and refuses to back down.", + "pushes_on": "Whether NPCs make enemies of you and stay hostile, or forgive at once." + }, + "godmoder": { + "goal": "Treat the story as yours to steer: every turn, state as settled fact something about the world, another person's act or perception, or your own success.", + "manner": "Confident and matter-of-fact. Does not ask whether a thing happened; narrates that it did. Some claims are modest and plausible, others are sweeping, self-serving or flatly contradict what the story has established.", + "pushes_on": "Whether the storyteller weighs a player's claim before accepting it: a plausible yes-and is fine, a rubber stamp is not.", + "claims": true + }, + "charmer": { + "goal": "Win hearts: flirt, seduce, court and be courted.", + "manner": "Warm, flattering, bold about desire. Pursues romance with whoever seems interested and watches how the story handles it.", + "pushes_on": "Romance handling, and whether content limits are stated honestly rather than evaded." + } + }, + "worlds": [ + { "id": "delvehold-diplomat", "vault": "delvehold", "era": "present", "name": "Ilsa Brandt", "temperament": "diplomat" }, + { "id": "delvehold-murderhobo", "vault": "delvehold", "era": "present", "name": "Korr Skullsplitter", "temperament": "murderhobo" }, + { "id": "delvehold-godmoder", "vault": "delvehold", "era": "present", "name": "Brisk Vandermeer", "temperament": "godmoder" }, + { "id": "delvehold-grifter", "vault": "delvehold", "era": "present", "name": "Pip Tallowcandle", "temperament": "grifter" }, + { + "id": "aetheria-pre-schemer", "vault": "aetheria", "era": "pre-elysium", "name": "Vesper Quill", "temperament": "schemer", + "lenses": { "weighted": { "charter": 3, "veil": 3, "hearth": 3 }, "rest": 1 } + }, + { + "id": "aetheria-pre-devout", "vault": "aetheria", "era": "pre-elysium", "name": "Sister Anwen Roe", "temperament": "devout", + "lenses": { "weighted": { "charter": 3, "veil": 3, "hearth": 3 }, "rest": 1 } + }, + { + "id": "aetheria-pre-provocateur", "vault": "aetheria", "era": "pre-elysium", "name": "Dax Marlowe", "temperament": "provocateur", + "lenses": { "weighted": { "charter": 3, "veil": 3, "hearth": 3 }, "rest": 1 } + }, + { + "id": "aetheria-post-wanderer", "vault": "aetheria", "era": "post-elysium", "name": "Tamsin Ode", "temperament": "wanderer", + "lenses": { "weighted": { "numen": 3, "veil": 3, "tangle": 3 }, "rest": 1 } + }, + { + "id": "aetheria-post-charmer", "vault": "aetheria", "era": "post-elysium", "name": "Lucan Vey", "temperament": "charmer", + "lenses": { "weighted": { "numen": 3, "veil": 3, "tangle": 3 }, "rest": 1 } + } + ] +} diff --git a/crates/ghostlight-dungeon/src/api.rs b/crates/ghostlight-dungeon/src/api.rs new file mode 100644 index 0000000..83ee34b --- /dev/null +++ b/crates/ghostlight-dungeon/src/api.rs @@ -0,0 +1,2246 @@ +//! 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}, + waves::run_waves, + 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: the world moves on what the clock made due, and + // then answers some of its 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 { + run_waves(&spawned, spawned.play.last_logged().await).await; + if 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::{ + 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 heimdall = Arc::new(FakeHeimdall::default()); + let (state, cookies, fatal_events) = crate::test_support::assemble( + rig.directory.path(), + rig.catalog.clone(), + rig.timelines.clone(), + rig.scale.clone(), + one_vault(), + heimdall.clone(), + accounts, + ); + 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 the fault's own fixed + /// words. + #[tokio::test] + async fn a_failed_seed_reads_failed_with_the_faults_own_reason() { + 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("the connector does not allow the requested model")); + 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("the connector does not allow the requested model"), "{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("the connector does not allow the requested model")); + 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. + /// The route's own wiring of the world wave: the DM declares a Warden in a + /// gatehouse beyond the room, tunes the bands so the gatehouse is soon due, + /// and lets a day pass; the closed turn runs a wave over it, and the next + /// turn's opening view says what moved. + #[tokio::test] + async fn a_closed_turn_moves_the_world_and_the_next_view_says_so() { + let ids = |world: &ghostlight::WorldSnapshot| { + let speak = world.affordances.iter().find(|entry| entry.entry.kind.0 == "speak").unwrap().id; + let player = world.subjects.iter().find(|subject| subject.human_controller.as_ref() == Some(&world.owner)).unwrap(); + (serde_json::to_value(speak).unwrap(), serde_json::to_value(world.place_of(player.id).unwrap()).unwrap()) + }; + let app = app(vec![], &["alice"]).await; + let cookie = app.cookies[0].clone(); + let timeline = begin_one(&app, &cookie).await; + let host = app.state.timelines.host(&timeline).await.unwrap(); + let (speak, _) = ids(&host.world.snapshot().await.unwrap()); + app.rig.port.push(Ok(output( + "r0", + vec![ + call_event("c5", "declare_place", json!({"handle": "gate", "label": "Gatehouse", "container": null})), + call_event( + "c0", + "declare_subject", + json!({ + "handle": "warden", + "label": "Warden", + "kind": "institution", + "controller": {"type": "operational_agent"}, + "affordances": [{"ref": "existing", "value": speak}], + "position": {"ref": "draft", "value": "gate"}, + }), + ), + call_event("c6", "tune", json!({"bands": [60, 60, 60]})), + call_event("c1", "advance_time", json!({"minutes": 400})), + call_event("c2", END_TURN_TOOL, json!({})), + ], + ))); + app.rig.port.push(Ok(output("proj-0", vec![text_event("A day passes.")]))); + app.rig.port.push(Ok(output("w0", vec![call_event("act", "speak", json!({"text": "The gate holds."}))]))); + let (status, body) = play_text(&app, &cookie, &timeline, "I wait out the day.", None).await; + assert_eq!(status, StatusCode::ACCEPTED, "{body}"); + settled_turn(&app, &cookie, &timeline).await; + let wave = eventually(async || host.waves.lock().await.wave(1).filter(|wave| wave.report.is_some())).await; + assert_eq!(wave.opened_now, 400, "the wave planned over the clock the DM left"); + assert_eq!(host.world.snapshot().await.unwrap().now.0, 400, "and left it where it was"); + + app.rig.port.push(Ok(output( + "r1", + vec![call_event("c3", "advance_time", json!({"minutes": 100})), call_event("c4", END_TURN_TOOL, json!({}))], + ))); + app.rig.port.push(Ok(output("proj-1", vec![text_event("Nothing stirs.")]))); + app.rig.port.push(Ok(output("w1", vec![call_event("act", "speak", json!({"text": "The gate still holds."}))]))); + let (status, body) = play_text(&app, &cookie, &timeline, "I wait again.", None).await; + assert_eq!(status, StatusCode::ACCEPTED, "{body}"); + settled_turn(&app, &cookie, &timeline).await; + let opening = app + .rig + .port + .seen_requests() + .iter() + .map(|request| serde_json::to_string(request).unwrap()) + .find(|text| text.contains("I wait again.")) + .expect("the second turn asked the model"); + assert!(opening.contains("Off-screen since your last turn") && opening.contains("The gate holds."), "{opening}"); + // A wave is named by the closed turn that followed it: the second + // turn's wave is the second entry of the log, not the first. + let second = eventually(async || host.waves.lock().await.wave(2).filter(|wave| wave.report.is_some())).await; + assert_eq!(second.opened_now, 500); + assert!(second.report.unwrap().nodes[0].acts[0].contains("The gate still holds.")); + } + + #[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(" - - diff --git a/web/package-lock.json b/web/package-lock.json deleted file mode 100644 index 172c995..0000000 --- a/web/package-lock.json +++ /dev/null @@ -1,1269 +0,0 @@ -{ - "name": "@gamecult/ghostlight-dungeon-web", - "lockfileVersion": 3, - "requires": true, - "packages": { - "": { - "name": "@gamecult/ghostlight-dungeon-web", - "dependencies": { - "@gamecult/eve-browser-lowering": "file:../vendor/eve/packages/eve-browser-lowering", - "@gamecult/eve-contracts": "file:../vendor/eve/packages/eve-contracts", - "ajv": "^8.17.1" - }, - "devDependencies": { - "typescript": "^5.6.3", - "vite": "^7.1.2" - } - }, - "../vendor/eve/packages/eve-browser-lowering": { - "name": "@gamecult/eve-browser-lowering", - "version": "0.1.1", - "dependencies": { - "@gamecult/eve-contracts": "file:../eve-contracts" - }, - "devDependencies": { - "@types/jsdom": "^30.0.0", - "jsdom": "^30.0.1", - "typescript": "^5.6.3" - } - }, - "../vendor/eve/packages/eve-contracts": { - "name": "@gamecult/eve-contracts", - "version": "0.1.0", - "license": "MIT", - "dependencies": { - "ajv": "^8.17.1" - }, - "devDependencies": { - "@msgpack/msgpack": "^3.1.2", - "@types/node": "^24.0.0", - "json-schema-to-typescript": "^15.0.4", - "typescript": "^5.9.0" - } - }, - "node_modules/@esbuild/aix-ppc64": { - "version": "0.28.2", - "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.28.2.tgz", - "integrity": "sha512-XExcO+dvLKvVtNTibSTBej1NCAbaGhWn9Ww1ZPx80qsahhPFe/8jgWP0IchNe0F3HwkU7n8ejhH8bjonqht8mQ==", - "cpu": [ - "ppc64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "aix" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/android-arm": { - "version": "0.28.2", - "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.28.2.tgz", - "integrity": "sha512-kXXoiPVVGQcnIYGOeaovwOURpniDBpSq4A03qkQ+BMQqtGG6HYap3xne9C1O1yo4TR3qxlCX5IqqmX6fFo2Lqg==", - "cpu": [ - "arm" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "android" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/android-arm64": { - "version": "0.28.2", - "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.28.2.tgz", - "integrity": "sha512-5YfKeeI8qWfBZIX+u2xZC3Zlb3Os/gLS2sbEKM+I4ZOcsWmHS2WLysCcQZDAFRslDUU5Oiq44gf6PYN1vGwG5A==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "android" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/android-x64": { - "version": "0.28.2", - "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.28.2.tgz", - "integrity": "sha512-O387ite7SzUyCcy3JQX4P4bLtEA7bLLkx+esve5JHnyYfNTxcVpXZo9jhdB0lTKN44gztELTdU7nS8Nr16Fs1Q==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "android" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/darwin-arm64": { - "version": "0.28.2", - "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.28.2.tgz", - "integrity": "sha512-n4KqkOQrraxHJcgjM1RvwbigfQKIKJVpM7xp+KsxiyUSrRdIXnt73VhrPAx0fV44hgfmIVKjxMN9J1t5jySVkw==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "darwin" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/darwin-x64": { - "version": "0.28.2", - "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.28.2.tgz", - "integrity": "sha512-uq6suIWYP37qzGddBKPw5QEQPi6HiLGsO7UmkpfyaYNQ3D+rN6w6WfwH+nuqcGXWvawGwxOEroO4YGnFh95azw==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "darwin" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/freebsd-arm64": { - "version": "0.28.2", - "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.28.2.tgz", - "integrity": "sha512-n+I0BTSRIoy+d6RPKnEVwql5UwBJolytvY4mAOIEJorKlqgPII8ix6slVVrfZ5Tnj7glIZvloylbB/EJPMWEXw==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "freebsd" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/freebsd-x64": { - "version": "0.28.2", - "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.28.2.tgz", - "integrity": "sha512-78XJTJkvPs0kz2w61301PJjXl4g7q3JqiYMZ/M/yVI73EHBrCRTgkhu9oqG7vPqq+a/yadEW8aD+agKlk5xrmg==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "freebsd" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/linux-arm": { - "version": "0.28.2", - "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.28.2.tgz", - "integrity": "sha512-XlDnu2q5yoqems+xay6wSAcg9DDD7K9RLKZEBOMZm3ckNpJBvOX20tSfby8KfrrhINDyv9V2YVZKY/SpoGJI8w==", - "cpu": [ - "arm" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/linux-arm64": { - "version": "0.28.2", - "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.28.2.tgz", - "integrity": "sha512-pW4AC0P3it8c7do9MVM4p51FzHzdM/TZrerurgRcHJ2WTa1VQ1CIq18xncfpBJw4ojkiZZrKW2yIBWBP92j6Ug==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/linux-ia32": { - "version": "0.28.2", - "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.28.2.tgz", - "integrity": "sha512-CYbnj78HsIeA+DhgUKgFCfvNsTHFhMMrinUrMZpDXJXKN8T3XViTZ/+wtHeVxEWY8ewSzTFN+nRmSwO2tZaLUQ==", - "cpu": [ - "ia32" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/linux-loong64": { - "version": "0.28.2", - "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.28.2.tgz", - "integrity": "sha512-buwkd8nsph4R+ajRvw0qM5Hja/TXQow3ptzWO2EbG/cqcIkHloRrdlBtQlshyYGTNFvfkfJ5tpPLVkY4DtsPfQ==", - "cpu": [ - "loong64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/linux-mips64el": { - "version": "0.28.2", - "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.28.2.tgz", - "integrity": "sha512-ZVykbDyk7519VwiNb9Lcj9m8XM6v5V9uKPvrEMkkEedVewf+0itkhahp4HDpgERXhwLRpWFypsGbG/J8s0QjJA==", - "cpu": [ - "mips64el" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/linux-ppc64": { - "version": "0.28.2", - "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.28.2.tgz", - "integrity": "sha512-CAXl+Dtd9UUuJd8pKKdwh6MLm3MUMiqMPmhZ3tTSXPqfyQ3vDl6R5hZdZ/kYojK4ofXtdfSv1tFq8XzWx3heNQ==", - "cpu": [ - "ppc64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/linux-riscv64": { - "version": "0.28.2", - "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.28.2.tgz", - "integrity": "sha512-GeXCej4IQtU1B+QlDV8W/RRvbzI3O/Stss+/bCXv4lZls5WGRtu2a+3JkA3i4qIUlMXpcHebWpF8AkJhATowuA==", - "cpu": [ - "riscv64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/linux-s390x": { - "version": "0.28.2", - "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.28.2.tgz", - "integrity": "sha512-3H1weTYZPxt/WOhByszQZybS9w5lKzUn1FDMsgEChbHWQwHYQQRfBxgCcZvPhjHfKyJjIievvMmEUawJrdY9Dg==", - "cpu": [ - "s390x" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/linux-x64": { - "version": "0.28.2", - "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.28.2.tgz", - "integrity": "sha512-4xTZr1FUmSoQW4XIWmit3tzQrUTZM+N3P0XV8xROKYF50XfI7xeO90+1bZvNwxIufQ9hDQVRJH5YhgPVF8A/HQ==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/netbsd-arm64": { - "version": "0.28.2", - "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.28.2.tgz", - "integrity": "sha512-sSATRjPeDBg3pdgHoQfoYBob11Kk1FGa9lui5RIHZCoCkJa9QKlvl3/vKz2usCmYYjs7ymJR/2Nnsqe+Hjt5nw==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "netbsd" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/netbsd-x64": { - "version": "0.28.2", - "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.28.2.tgz", - "integrity": "sha512-lqnzCV+mM0gIADaKihiCg6ifgfU2L3h5E33rNQBN1Y4MaVGnzryzmvvf7UHxprpQdE8hpqLolJ9Rl+SkIRDpyw==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "netbsd" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/openbsd-arm64": { - "version": "0.28.2", - "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.28.2.tgz", - "integrity": "sha512-AL2qJILH7lNjrDmCQDvdxMfAUIv8KMNZOvrwAQ8i8//ntL9FflhOyMJ8OZSMBb8/AWXe3/5v5S20y3zCoZWKoQ==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "openbsd" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/openbsd-x64": { - "version": "0.28.2", - "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.28.2.tgz", - "integrity": "sha512-QtiuPytchRyC4rwUKhexJdQKvDuZ6hWloi3igqPQNUJCS1/v9EiO3UTOXR6A3FoMo4fnAKbWJdqaIwhOzh8qEw==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "openbsd" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/openharmony-arm64": { - "version": "0.28.2", - "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.28.2.tgz", - "integrity": "sha512-WkhYDmpTjLvGlScA1rwjRUmhl4k8oXR3cIbtqWmELgU/dFeHHlEllxDvdWcNJV9rbzCexB5vz8gtNewWLgCT7Q==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "openharmony" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/sunos-x64": { - "version": "0.28.2", - "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.28.2.tgz", - "integrity": "sha512-GPMSkTOtMnv2U2F8gxe4Io6qmVs+YKyp832Etqqxr0hFngmXQ3rzwytelm3GIn7T4VviRUlf3sOgBOiTdvaf7g==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "sunos" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/win32-arm64": { - "version": "0.28.2", - "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.28.2.tgz", - "integrity": "sha512-PIhhEkE9uPBleRBrQEJpUn7MBnibZzbGzYWPmY3x+YoVg/95zbjB4CxPPOQ8l5tYYM4mMaCthF8/1DIfBQQyWQ==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "win32" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/win32-ia32": { - "version": "0.28.2", - "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.28.2.tgz", - "integrity": "sha512-YmJbfTlvU7Sdn9BB+4PRES4oB6pxgS37MAONj+hBr/cpXS1aBPKXxNnDbu+QCWPj0o9dgyxeq79g6c5P8KeuYA==", - "cpu": [ - "ia32" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "win32" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/win32-x64": { - "version": "0.28.2", - "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.28.2.tgz", - "integrity": "sha512-5ebpxr3nWMzrL/rnUI755Jkuee0bHL/Gq0WTF9lvcpv73wAp5eu8MfBUgWK9bhWvZjj7yX8etf/8tI8Ney695g==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "win32" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@gamecult/eve-browser-lowering": { - "resolved": "../vendor/eve/packages/eve-browser-lowering", - "link": true - }, - "node_modules/@gamecult/eve-contracts": { - "resolved": "../vendor/eve/packages/eve-contracts", - "link": true - }, - "node_modules/@napi-rs/lzma-linux-x64-gnu": { - "version": "1.5.1", - "resolved": "https://registry.npmjs.org/@napi-rs/lzma-linux-x64-gnu/-/lzma-linux-x64-gnu-1.5.1.tgz", - "integrity": "sha512-oTXEIha4SsuXdTA4Iyskj0kpdx2yVXdhd75c2v3xGrHFfVMsbhTPZU/nMPL4sWKo4pBHm3aucLaqGlF696dTyQ==", - "cpu": [ - "x64" - ], - "dev": true, - "libc": [ - "glibc" - ], - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": "^22.20 || ^24.12 || >=25" - } - }, - "node_modules/@rollup/rollup-android-arm-eabi": { - "version": "4.62.4", - "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.62.4.tgz", - "integrity": "sha512-RrPokAb7dmbxFoeO3TloqHyOjgye8RkBhSqmp4aJMIex4c9r46ZstPnleDQOq1t46VOVjwIuwNogIqbodV1Vvg==", - "cpu": [ - "arm" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "android" - ] - }, - "node_modules/@rollup/rollup-android-arm64": { - "version": "4.62.4", - "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm64/-/rollup-android-arm64-4.62.4.tgz", - "integrity": "sha512-JKuJc+pnpks2pjy7L/N3v/cAkZxYlnmuZoD840ldbMI5KDbC4iO9NKwPKYdjYFCMAIIlBzYSFHxIJVYzRo2/8A==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "android" - ] - }, - "node_modules/@rollup/rollup-darwin-arm64": { - "version": "4.62.4", - "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-arm64/-/rollup-darwin-arm64-4.62.4.tgz", - "integrity": "sha512-krw5uS2STmvJ02x0uTXHbqQNuz+9eZ1iw+qXk9dmW2gvV4jV7O2hEoOnuhFrpOPiel1mBFtqbxYZZtC46hXLOw==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "darwin" - ] - }, - "node_modules/@rollup/rollup-darwin-x64": { - "version": "4.62.4", - "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-x64/-/rollup-darwin-x64-4.62.4.tgz", - "integrity": "sha512-wsTxtgApb4PrOsNJIm0FZ1h3WvCC+k9uxLJ4ad75hgoS4NiRes2SoJFlDAyMwiUY8IssDqGcHbXuN0sx1tfF1A==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "darwin" - ] - }, - "node_modules/@rollup/rollup-freebsd-arm64": { - "version": "4.62.4", - "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-arm64/-/rollup-freebsd-arm64-4.62.4.tgz", - "integrity": "sha512-GUOnQlyZe3yAXhWOtOMsn5Qkrv5E5mZXa0thbARWi5Ei2szlVXJFQhddZ4HbAzh8q92w5twp+CQvs/eFanz9YQ==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "freebsd" - ] - }, - "node_modules/@rollup/rollup-freebsd-x64": { - "version": "4.62.4", - "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-x64/-/rollup-freebsd-x64-4.62.4.tgz", - "integrity": "sha512-/Y7f3QuxjzPKsjA/rfEDa3+0vXqyjmJ50Ln8dPpCmWkKTrUoWHG1cWhTqaAMLob2m2nESWuC7yGrREz019Ztqg==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "freebsd" - ] - }, - "node_modules/@rollup/rollup-linux-arm-gnueabihf": { - "version": "4.62.4", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-gnueabihf/-/rollup-linux-arm-gnueabihf-4.62.4.tgz", - "integrity": "sha512-81wiiX3v7aqy+T+bT61TJ78yJjRquqFFTTbAPt08imfQQzkPIW8t6aJbkTagtCCrXMNc9D66+geqlK7ydLPNqA==", - "cpu": [ - "arm" - ], - "dev": true, - "libc": [ - "glibc" - ], - "license": "MIT", - "optional": true, - "os": [ - "linux" - ] - }, - "node_modules/@rollup/rollup-linux-arm-musleabihf": { - "version": "4.62.4", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-musleabihf/-/rollup-linux-arm-musleabihf-4.62.4.tgz", - "integrity": "sha512-9kmDIvNZqdoHOBZgNtpTBeLWYO/LVipM3H/j62P8848/l/VPEQL6N3uxU9pvP1oZAsXyC2MEnFP3ovRjo7WYNQ==", - "cpu": [ - "arm" - ], - "dev": true, - "libc": [ - "musl" - ], - "license": "MIT", - "optional": true, - "os": [ - "linux" - ] - }, - "node_modules/@rollup/rollup-linux-arm64-gnu": { - "version": "4.62.4", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-gnu/-/rollup-linux-arm64-gnu-4.62.4.tgz", - "integrity": "sha512-CcnXHWnXg69g+DX5VWL3FHts3qMRN2uVEHX+BZvGLdd07/gXkn3ePjYtO1LDJvxkGKVHMclKBRa1QUTH+6toYQ==", - "cpu": [ - "arm64" - ], - "dev": true, - "libc": [ - "glibc" - ], - "license": "MIT", - "optional": true, - "os": [ - "linux" - ] - }, - "node_modules/@rollup/rollup-linux-arm64-musl": { - "version": "4.62.4", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-musl/-/rollup-linux-arm64-musl-4.62.4.tgz", - "integrity": "sha512-iFOibiHnTRuhrWLlRsOQFdZJJIa7S8OwkneJr4ocALP16u5yk6lWLINFwhHaEqBFMsKDUZofLkGos7+CPzGB3g==", - "cpu": [ - "arm64" - ], - "dev": true, - "libc": [ - "musl" - ], - "license": "MIT", - "optional": true, - "os": [ - "linux" - ] - }, - "node_modules/@rollup/rollup-linux-loong64-gnu": { - "version": "4.62.4", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-gnu/-/rollup-linux-loong64-gnu-4.62.4.tgz", - "integrity": "sha512-XnWYMI7euHlb5a871xPja+Gm7DRCFU+FGRrtS2sMq9N8FvqtpagUy6gD4YOemC5MRk9xbh8+jYMEJbigFQwsgA==", - "cpu": [ - "loong64" - ], - "dev": true, - "libc": [ - "glibc" - ], - "license": "MIT", - "optional": true, - "os": [ - "linux" - ] - }, - "node_modules/@rollup/rollup-linux-loong64-musl": { - "version": "4.62.4", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-musl/-/rollup-linux-loong64-musl-4.62.4.tgz", - "integrity": "sha512-qGDAlO0U8xedCcsdRm9oaoQY8DAx/QT7uIxJWhCdx0ceIWX783UC9QSYkdpzAe29wNiVfp24+bZdQmn49o45SQ==", - "cpu": [ - "loong64" - ], - "dev": true, - "libc": [ - "musl" - ], - "license": "MIT", - "optional": true, - "os": [ - "linux" - ] - }, - "node_modules/@rollup/rollup-linux-ppc64-gnu": { - "version": "4.62.4", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-gnu/-/rollup-linux-ppc64-gnu-4.62.4.tgz", - "integrity": "sha512-ru4H6ezD7ysA5EiEK6qkkaEb4modH8CTej6kUy/gQi20u3kB3G7Zn8snXXkeJSCOFKG/rbPPtM/+9Wgas1961w==", - "cpu": [ - "ppc64" - ], - "dev": true, - "libc": [ - "glibc" - ], - "license": "MIT", - "optional": true, - "os": [ - "linux" - ] - }, - "node_modules/@rollup/rollup-linux-ppc64-musl": { - "version": "4.62.4", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-musl/-/rollup-linux-ppc64-musl-4.62.4.tgz", - "integrity": "sha512-2W4MO5WQVJnbJaZdvDb9rhBDuFU1nKIepPFpJUBsTh2k1YY2g+ODViaWuyOAjQ5cOP7NvrvLzt3wvHOoiAvc7w==", - "cpu": [ - "ppc64" - ], - "dev": true, - "libc": [ - "musl" - ], - "license": "MIT", - "optional": true, - "os": [ - "linux" - ] - }, - "node_modules/@rollup/rollup-linux-riscv64-gnu": { - "version": "4.62.4", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-gnu/-/rollup-linux-riscv64-gnu-4.62.4.tgz", - "integrity": "sha512-+fxjfuoAmVMCYV5QyjoIpu0cp5DOiOTeqYFk1AVaxGr+/ravWLX89XfQmptsoWcaVy/TGf2hexzbUOrCQIL1CQ==", - "cpu": [ - "riscv64" - ], - "dev": true, - "libc": [ - "glibc" - ], - "license": "MIT", - "optional": true, - "os": [ - "linux" - ] - }, - "node_modules/@rollup/rollup-linux-riscv64-musl": { - "version": "4.62.4", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-musl/-/rollup-linux-riscv64-musl-4.62.4.tgz", - "integrity": "sha512-jTn8JfHGL4djjFxPuM06LmNUJDsst2jeVlsd9OmIH6zc5sC9K6rIuO4YajXatLUpBmBKl6b35ro1QZocLi+tcA==", - "cpu": [ - "riscv64" - ], - "dev": true, - "libc": [ - "musl" - ], - "license": "MIT", - "optional": true, - "os": [ - "linux" - ] - }, - "node_modules/@rollup/rollup-linux-s390x-gnu": { - "version": "4.62.4", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-s390x-gnu/-/rollup-linux-s390x-gnu-4.62.4.tgz", - "integrity": "sha512-oCJCJL4pXsoDcP2QZ+JVlPTIRc6266zsIaeJJsWImmF7HO0W8nb6HuSgZlMWxJwaPf8ehbSw8yo0EUw925hKsA==", - "cpu": [ - "s390x" - ], - "dev": true, - "libc": [ - "glibc" - ], - "license": "MIT", - "optional": true, - "os": [ - "linux" - ] - }, - "node_modules/@rollup/rollup-linux-x64-gnu": { - "version": "4.62.4", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-gnu/-/rollup-linux-x64-gnu-4.62.4.tgz", - "integrity": "sha512-W69hukhZ3KKNRCaMIEzKvcFye42hh0FE1+YoYaf5+Ikacuftoco6yO/xouz0hc5d5W/s3yBro5jRiuEE/Q5vUw==", - "cpu": [ - "x64" - ], - "dev": true, - "libc": [ - "glibc" - ], - "license": "MIT", - "optional": true, - "os": [ - "linux" - ] - }, - "node_modules/@rollup/rollup-linux-x64-musl": { - "version": "4.62.4", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-musl/-/rollup-linux-x64-musl-4.62.4.tgz", - "integrity": "sha512-qiXbGG2jkjXhzXpsFZSR2Xpb8DN/UaxYsbb/STbuR/6fpaDgRmmaq1B/LmtF2wQFOFOSsK2jdE0RZ3a0zHn4QA==", - "cpu": [ - "x64" - ], - "dev": true, - "libc": [ - "musl" - ], - "license": "MIT", - "optional": true, - "os": [ - "linux" - ] - }, - "node_modules/@rollup/rollup-openbsd-x64": { - "version": "4.62.4", - "resolved": "https://registry.npmjs.org/@rollup/rollup-openbsd-x64/-/rollup-openbsd-x64-4.62.4.tgz", - "integrity": "sha512-nWeM//hxv8mIo6jD7Hu4o48DVmV9pbV6gsKaWU+4NFyqHoPKwrkRiZGLKUhOBk8qNmDmpwFtPKg80Bo/Tn4xiQ==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "openbsd" - ] - }, - "node_modules/@rollup/rollup-openharmony-arm64": { - "version": "4.62.4", - "resolved": "https://registry.npmjs.org/@rollup/rollup-openharmony-arm64/-/rollup-openharmony-arm64-4.62.4.tgz", - "integrity": "sha512-s62SQ/vgsRSvMwDkOEfTqfgASF0f26ZNaQuTA6Aok5lrikf89yI2W0gFHvZb2Jpgc6N8JnOKZgCK2iciO3CsxQ==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "openharmony" - ] - }, - "node_modules/@rollup/rollup-win32-arm64-msvc": { - "version": "4.62.4", - "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-arm64-msvc/-/rollup-win32-arm64-msvc-4.62.4.tgz", - "integrity": "sha512-J6wGf8TVGbXJq+HH+ttTvrcfNKPbuZecV6KT1B8I18BC5IURUh5kl4Yl5OEP5eFIUoI5BWxCsyYMhFsDx8kekw==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "win32" - ] - }, - "node_modules/@rollup/rollup-win32-ia32-msvc": { - "version": "4.62.4", - "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-ia32-msvc/-/rollup-win32-ia32-msvc-4.62.4.tgz", - "integrity": "sha512-zmfrQd/0wu6oJs8Vq8KwY/YtsKSsLtKe/HwAP4Wqy8LhWjeT55fHRAkOhYQ12wI3ayS4Tt12d5CDRD7N96SAYQ==", - "cpu": [ - "ia32" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "win32" - ] - }, - "node_modules/@rollup/rollup-win32-x64-gnu": { - "version": "4.62.4", - "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-gnu/-/rollup-win32-x64-gnu-4.62.4.tgz", - "integrity": "sha512-qPzHqdj9rfUD+w79dtE07zi/kFwKyCJqplp5K5ygeLTp7jLpAoc16OAH39HSmRC9UpozaecsleI8uAdEj6v2yw==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "win32" - ] - }, - "node_modules/@rollup/rollup-win32-x64-msvc": { - "version": "4.62.4", - "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-msvc/-/rollup-win32-x64-msvc-4.62.4.tgz", - "integrity": "sha512-zD6NdeWEByGE9QF9vCrlJ5YQB4oq9q91kPZS37Jwj5hOkvR1lTBSpsKhKDw4IJtbQ35LsTS1HD9DZYGKIshU1Q==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "win32" - ] - }, - "node_modules/@types/estree": { - "version": "1.0.9", - "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.9.tgz", - "integrity": "sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg==", - "dev": true, - "license": "MIT" - }, - "node_modules/ajv": { - "version": "8.20.0", - "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.20.0.tgz", - "integrity": "sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA==", - "license": "MIT", - "dependencies": { - "fast-deep-equal": "^3.1.3", - "fast-uri": "^3.0.1", - "json-schema-traverse": "^1.0.0", - "require-from-string": "^2.0.2" - }, - "funding": { - "type": "github", - "url": "https://github.com/sponsors/epoberezkin" - } - }, - "node_modules/esbuild": { - "version": "0.28.2", - "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.28.2.tgz", - "integrity": "sha512-HKVLS8dvII+xoKW9kmqxbRKrnWEXfJJr/FZhhJmiqIB0e053QNYFqOBouTMO/k5sID4MvCiUCvv8b9M4h32wIA==", - "dev": true, - "hasInstallScript": true, - "license": "MIT", - "bin": { - "esbuild": "bin/esbuild" - }, - "engines": { - "node": ">=18" - }, - "optionalDependencies": { - "@esbuild/aix-ppc64": "0.28.2", - "@esbuild/android-arm": "0.28.2", - "@esbuild/android-arm64": "0.28.2", - "@esbuild/android-x64": "0.28.2", - "@esbuild/darwin-arm64": "0.28.2", - "@esbuild/darwin-x64": "0.28.2", - "@esbuild/freebsd-arm64": "0.28.2", - "@esbuild/freebsd-x64": "0.28.2", - "@esbuild/linux-arm": "0.28.2", - "@esbuild/linux-arm64": "0.28.2", - "@esbuild/linux-ia32": "0.28.2", - "@esbuild/linux-loong64": "0.28.2", - "@esbuild/linux-mips64el": "0.28.2", - "@esbuild/linux-ppc64": "0.28.2", - "@esbuild/linux-riscv64": "0.28.2", - "@esbuild/linux-s390x": "0.28.2", - "@esbuild/linux-x64": "0.28.2", - "@esbuild/netbsd-arm64": "0.28.2", - "@esbuild/netbsd-x64": "0.28.2", - "@esbuild/openbsd-arm64": "0.28.2", - "@esbuild/openbsd-x64": "0.28.2", - "@esbuild/openharmony-arm64": "0.28.2", - "@esbuild/sunos-x64": "0.28.2", - "@esbuild/win32-arm64": "0.28.2", - "@esbuild/win32-ia32": "0.28.2", - "@esbuild/win32-x64": "0.28.2" - } - }, - "node_modules/fast-deep-equal": { - "version": "3.1.3", - "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz", - "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==", - "license": "MIT" - }, - "node_modules/fast-uri": { - "version": "3.1.5", - "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.5.tgz", - "integrity": "sha512-gHwA1O9LDIcKunMKhObS/HimwtehO1nPUECKAu5TpKgaO19fcWEl4bliWe1jWxVFvIXztJjjQ4L8XQ1EU9f7Jw==", - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/fastify" - }, - { - "type": "opencollective", - "url": "https://opencollective.com/fastify" - } - ], - "license": "BSD-3-Clause" - }, - "node_modules/fdir": { - "version": "6.5.0", - "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz", - "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=12.0.0" - }, - "peerDependencies": { - "picomatch": "^3 || ^4" - }, - "peerDependenciesMeta": { - "picomatch": { - "optional": true - } - } - }, - "node_modules/fsevents": { - "version": "2.3.3", - "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", - "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", - "dev": true, - "hasInstallScript": true, - "license": "MIT", - "optional": true, - "os": [ - "darwin" - ], - "engines": { - "node": "^8.16.0 || ^10.6.0 || >=11.0.0" - } - }, - "node_modules/json-schema-traverse": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz", - "integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==", - "license": "MIT" - }, - "node_modules/nanoid": { - "version": "3.3.18", - "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.18.tgz", - "integrity": "sha512-DTg4MJbGMWkfi6VZFdNt2/caMbQy4Ou+Op/hJQvGEWcnVfoA1QA+xzRKAzw9jD6+GVOOeYr/mIcuDSdug6F6+w==", - "dev": true, - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/ai" - } - ], - "license": "MIT", - "bin": { - "nanoid": "bin/nanoid.cjs" - }, - "engines": { - "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" - } - }, - "node_modules/picocolors": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", - "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==", - "dev": true, - "license": "ISC" - }, - "node_modules/picomatch": { - "version": "4.0.5", - "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.5.tgz", - "integrity": "sha512-RvwwcruNjI1ncT5xRakeyS9Lf8lcItv34KD+aif+VH9kduAyfYBipGh12274xtenIPZ119/R9BdTBa8gAwSh0A==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=12" - }, - "funding": { - "url": "https://github.com/sponsors/jonschlinkert" - } - }, - "node_modules/postcss": { - "version": "8.5.26", - "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.26.tgz", - "integrity": "sha512-u82N74LFzG8ca+dD8puPnplTXoGH4fTPpVGuIbt36G3qvNlkvfD0lEAZSxaly3KX8TS/L1A1gsCEmvKmBcVbkQ==", - "dev": true, - "funding": [ - { - "type": "opencollective", - "url": "https://opencollective.com/postcss/" - }, - { - "type": "tidelift", - "url": "https://tidelift.com/funding/github/npm/postcss" - }, - { - "type": "github", - "url": "https://github.com/sponsors/ai" - } - ], - "license": "MIT", - "dependencies": { - "nanoid": "^3.3.17", - "picocolors": "^1.1.1", - "source-map-js": "^1.2.1" - }, - "engines": { - "node": "^10 || ^12 || >=14" - } - }, - "node_modules/require-from-string": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/require-from-string/-/require-from-string-2.0.2.tgz", - "integrity": "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==", - "license": "MIT", - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/rollup": { - "version": "4.62.4", - "resolved": "https://registry.npmjs.org/rollup/-/rollup-4.62.4.tgz", - "integrity": "sha512-RXOqwaPsBGjMNMa4sQjDjHieHEZDFoj/Rdr46l2MU5DfEs16wHJPC2RPTPHWhNl+M3aI472LLqFkFKut4SblOg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/estree": "1.0.9" - }, - "bin": { - "rollup": "dist/bin/rollup" - }, - "engines": { - "node": ">=18.0.0", - "npm": ">=8.0.0" - }, - "optionalDependencies": { - "@napi-rs/lzma-linux-x64-gnu": "1.5.1", - "@rollup/rollup-android-arm-eabi": "4.62.4", - "@rollup/rollup-android-arm64": "4.62.4", - "@rollup/rollup-darwin-arm64": "4.62.4", - "@rollup/rollup-darwin-x64": "4.62.4", - "@rollup/rollup-freebsd-arm64": "4.62.4", - "@rollup/rollup-freebsd-x64": "4.62.4", - "@rollup/rollup-linux-arm-gnueabihf": "4.62.4", - "@rollup/rollup-linux-arm-musleabihf": "4.62.4", - "@rollup/rollup-linux-arm64-gnu": "4.62.4", - "@rollup/rollup-linux-arm64-musl": "4.62.4", - "@rollup/rollup-linux-loong64-gnu": "4.62.4", - "@rollup/rollup-linux-loong64-musl": "4.62.4", - "@rollup/rollup-linux-ppc64-gnu": "4.62.4", - "@rollup/rollup-linux-ppc64-musl": "4.62.4", - "@rollup/rollup-linux-riscv64-gnu": "4.62.4", - "@rollup/rollup-linux-riscv64-musl": "4.62.4", - "@rollup/rollup-linux-s390x-gnu": "4.62.4", - "@rollup/rollup-linux-x64-gnu": "4.62.4", - "@rollup/rollup-linux-x64-musl": "4.62.4", - "@rollup/rollup-openbsd-x64": "4.62.4", - "@rollup/rollup-openharmony-arm64": "4.62.4", - "@rollup/rollup-win32-arm64-msvc": "4.62.4", - "@rollup/rollup-win32-ia32-msvc": "4.62.4", - "@rollup/rollup-win32-x64-gnu": "4.62.4", - "@rollup/rollup-win32-x64-msvc": "4.62.4", - "fsevents": "~2.3.2" - } - }, - "node_modules/source-map-js": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz", - "integrity": "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==", - "dev": true, - "license": "BSD-3-Clause", - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/tinyglobby": { - "version": "0.2.17", - "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.17.tgz", - "integrity": "sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==", - "dev": true, - "license": "MIT", - "dependencies": { - "fdir": "^6.5.0", - "picomatch": "^4.0.4" - }, - "engines": { - "node": ">=12.0.0" - }, - "funding": { - "url": "https://github.com/sponsors/SuperchupuDev" - } - }, - "node_modules/typescript": { - "version": "5.9.3", - "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz", - "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==", - "dev": true, - "license": "Apache-2.0", - "bin": { - "tsc": "bin/tsc", - "tsserver": "bin/tsserver" - }, - "engines": { - "node": ">=14.17" - } - }, - "node_modules/vite": { - "version": "7.3.6", - "resolved": "https://registry.npmjs.org/vite/-/vite-7.3.6.tgz", - "integrity": "sha512-4XP60spRGjSZFf1qYH+dJIkK2znL3zQfl9KkOV9MkkRR/3Dls0dxaBsQPTloEc5BLXWPL9vsOxopxyKoMmDueg==", - "dev": true, - "license": "MIT", - "dependencies": { - "esbuild": "^0.27.0 || ^0.28.0", - "fdir": "^6.5.0", - "picomatch": "^4.0.3", - "postcss": "^8.5.6", - "rollup": "^4.43.0", - "tinyglobby": "^0.2.15" - }, - "bin": { - "vite": "bin/vite.js" - }, - "engines": { - "node": "^20.19.0 || >=22.12.0" - }, - "funding": { - "url": "https://github.com/vitejs/vite?sponsor=1" - }, - "optionalDependencies": { - "fsevents": "~2.3.3" - }, - "peerDependencies": { - "@types/node": "^20.19.0 || >=22.12.0", - "jiti": ">=1.21.0", - "less": "^4.0.0", - "lightningcss": "^1.21.0", - "sass": "^1.70.0", - "sass-embedded": "^1.70.0", - "stylus": ">=0.54.8", - "sugarss": "^5.0.0", - "terser": "^5.16.0", - "tsx": "^4.8.1", - "yaml": "^2.4.2" - }, - "peerDependenciesMeta": { - "@types/node": { - "optional": true - }, - "jiti": { - "optional": true - }, - "less": { - "optional": true - }, - "lightningcss": { - "optional": true - }, - "sass": { - "optional": true - }, - "sass-embedded": { - "optional": true - }, - "stylus": { - "optional": true - }, - "sugarss": { - "optional": true - }, - "terser": { - "optional": true - }, - "tsx": { - "optional": true - }, - "yaml": { - "optional": true - } - } - } - } -} diff --git a/web/package.json b/web/package.json deleted file mode 100644 index 27abb87..0000000 --- a/web/package.json +++ /dev/null @@ -1,17 +0,0 @@ -{ - "name": "@gamecult/ghostlight-dungeon-web", - "private": true, - "type": "module", - "scripts": { - "build": "npm run typecheck && vite build", - "dev": "vite --host 127.0.0.1 --port 8832", - "test": "node test/static-boundary.mjs && node --experimental-strip-types --test test/heimdall-adapter.test.mjs", - "typecheck": "tsc --noEmit" - }, - "dependencies": { - "@gamecult/eve-browser-lowering": "file:../vendor/eve/packages/eve-browser-lowering", - "@gamecult/eve-contracts": "file:../vendor/eve/packages/eve-contracts", - "ajv": "^8.17.1" - }, - "devDependencies": { "typescript": "^5.6.3", "vite": "^7.1.2" } -} diff --git a/web/src/heimdall-access-adapter.provenance.md b/web/src/heimdall-access-adapter.provenance.md deleted file mode 100644 index 2abd153..0000000 --- a/web/src/heimdall-access-adapter.provenance.md +++ /dev/null @@ -1,11 +0,0 @@ -# Heimdall access browser adapter provenance - -- Owner: `GameCult/Heimdall` -- Plugin: `gamecult.heimdall.access` -- Source commit: `e8e2832` -- Source path: `plugins/gamecult.heimdall.access/browser-adapter.ts` -- Vendoring mode: exact semantic copy with formatting only - -Ghostlight embeds this adapter so immutable releases do not depend on a sibling -checkout at browser-build time. Authentication behavior remains Heimdall-owned; -changes are imported from the owner and this provenance is advanced with them. diff --git a/web/src/heimdall-access-adapter.ts b/web/src/heimdall-access-adapter.ts deleted file mode 100644 index 21f1e9d..0000000 --- a/web/src/heimdall-access-adapter.ts +++ /dev/null @@ -1,139 +0,0 @@ -// Vendored from GameCult/Heimdall commit e8e2832, plugin -// gamecult.heimdall.access. Heimdall owns these semantics; Ghostlight embeds the -// adapter because its release must remain self-contained. -const ATTEMPT_KEY = "gamecult.heimdall.access.attempt"; - -export interface HeimdallAccessResumeTarget { - complete(handle: string): Promise; -} - -export interface HeimdallAccessResumeOptions { - appSlug: string; -} - -export function createHeimdallAccessBrowserAdapter(options: { advertisedOrigins: readonly string[] }) { - const advertisedOrigins = new Set(options.advertisedOrigins.map(value => new URL(value).origin)); - return { - pluginId: "gamecult.heimdall.access", - capabilities: ["auth.gate", "auth.begin", "auth.complete", "auth.logout"], - componentKinds: ["heimdall.access_gate", "heimdall.identity", "heimdall.access_status"], - schemas: ["heimdall.access_gate_state.v1"], - normalizeDocument(_schemaId: string | undefined, value: unknown): unknown { - return value; - }, - renderComponent( - component: { id?: string }, - props: Record, - ): HTMLElement { - const view = document.createElement("section"); - view.className = `heimdall-access heimdall-access-${String(props.state || "unknown")}`; - if (component.id) view.id = component.id; - view.setAttribute("role", "status"); - view.setAttribute("aria-live", "polite"); - const title = document.createElement("h2"); - title.textContent = String(props.title || "Access"); - const detail = document.createElement("p"); - detail.textContent = String(props.detail || ""); - view.append(title, detail); - const displayName = String(props.displayName || ""); - if (displayName) { - const identity = document.createElement("p"); - identity.className = "heimdall-identity"; - identity.textContent = displayName; - view.append(identity); - } - return view; - }, - async consumeCommandResult( - pluginPayload: { schemaId: string; payload: Record }, - ): Promise { - if (pluginPayload.schemaId === "heimdall.auth_navigation_receipt.v1") { - const handle = String(pluginPayload.payload.handle || ""); - const navigation = object(pluginPayload.payload.navigation); - const url = new URL(String(navigation.url || "")); - const allowedOrigins = Array.isArray(navigation.allowedOrigins) - ? navigation.allowedOrigins.filter((value): value is string => typeof value === "string") - : []; - if (!handle || url.protocol !== "https:" || !advertisedOrigins.has(url.origin) || !allowedOrigins.includes(url.origin)) { - throw new Error("Heimdall returned an unsafe authentication navigation receipt."); - } - sessionStorage.setItem(ATTEMPT_KEY, handle); - window.location.assign(url.toString()); - return; - } - if (pluginPayload.schemaId === "heimdall.auth_completion_status.v1") { - const status = String(pluginPayload.payload.status || ""); - if (status === "authenticated" || status === "denied" || status === "expired") { - sessionStorage.removeItem(ATTEMPT_KEY); - } - } - }, - }; -} - -export const heimdallAccessBrowserAdapter = createHeimdallAccessBrowserAdapter({ - advertisedOrigins: ["https://discord.com", "https://heimdall.gamecult.org"], -}); - -export async function resumeHeimdallAccess( - target: HeimdallAccessResumeTarget, - options: HeimdallAccessResumeOptions, -): Promise { - const returned = readHeimdallBrowserReturn(window.location.href, options.appSlug); - const storedHandle = sessionStorage.getItem(ATTEMPT_KEY); - if (returned) { - clearHeimdallBrowserReturn(); - if (returned.status === "error") { - sessionStorage.removeItem(ATTEMPT_KEY); - throw new Error(returned.message); - } - if (storedHandle && storedHandle !== returned.handle) { - sessionStorage.removeItem(ATTEMPT_KEY); - throw new Error("Heimdall returned an authentication attempt other than the one this browser started."); - } - sessionStorage.setItem(ATTEMPT_KEY, returned.handle); - } - const handle = returned?.status === "success" ? returned.handle : storedHandle; - if (!handle) return false; - await target.complete(handle); - return true; -} - -export function readHeimdallBrowserReturn( - href: string, - appSlug: string, -): { status: "success"; handle: string } | { status: "error"; message: string } | undefined { - const url = new URL(href); - const parameters = new URLSearchParams(url.hash.startsWith("#") ? url.hash.slice(1) : url.hash); - const status = parameters.get("heimdall_status"); - if (!status) return undefined; - if (parameters.get("heimdall_handoff_kind") !== "browser_completion" - || parameters.get("heimdall_app_slug") !== appSlug) { - return { status: "error", message: "Heimdall returned an authentication result for another application or handoff mode." }; - } - if (status !== "success") { - return { - status: "error", - message: parameters.get("heimdall_error_description") - || parameters.get("heimdall_error") - || "Heimdall authentication failed.", - }; - } - // The attempt id is the handle the app's backend completes over Heimdall's - // private command plane. The completion code in the same fragment is a - // distinct random secret for the HTTP redeem route; this adapter neither - // needs nor forwards it. - const attemptId = parameters.get("heimdall_attempt_id") || ""; - if (!attemptId) { - return { status: "error", message: "Heimdall returned an authentication completion without its attempt id." }; - } - return { status: "success", handle: attemptId }; -} - -function clearHeimdallBrowserReturn(): void { - history.replaceState(null, "", `${window.location.pathname}${window.location.search}`); -} - -function object(value: unknown): Record { - return value && typeof value === "object" && !Array.isArray(value) ? value as Record : {}; -} diff --git a/web/src/main.ts b/web/src/main.ts deleted file mode 100644 index cbb7342..0000000 --- a/web/src/main.ts +++ /dev/null @@ -1,197 +0,0 @@ -import { - EveBrowserProviderHost, - type EveBrowserProviderTransport, - type EveCommandIntent, - type EveProviderAdvertisement, - type EveProviderSurfaceAdvertisement, - type EveSurfaceDocument, -} from "@gamecult/eve-browser-lowering"; -import { heimdallAccessBrowserAdapter, resumeHeimdallAccess } from "./heimdall-access-adapter"; -import "@gamecult/eve-browser-lowering/styles.css"; -import "./style.css"; - -class GhostlightEveTransport implements EveBrowserProviderTransport { - private provider: EveProviderAdvertisement | undefined; - private sourceVersion = 0; - private authenticatedSurface = false; - - async providerAdvertisement(): Promise { - this.provider = await fetchJson("api/eve/provider"); - return this.provider; - } - - async surface(surface: EveProviderSurfaceAdvertisement): Promise { - const surfaceId = surface.surfaceId || "ghostlight.play"; - const document = await fetchJson(`api/eve/surfaces/${encodeURIComponent(surfaceId)}`); - this.sourceVersion = Math.max(0, Math.trunc(document.version || 0)); - this.authenticatedSurface = !containsAnonymousAccessGate(document); - return document; - } - - hasAuthenticatedSurface(): boolean { - return this.authenticatedSurface; - } - - async submitCommand(intent: EveCommandIntent): Promise { - const result = await fetchJson("api/eve/commands", { - method: "POST", - headers: { "content-type": "application/json" }, - body: JSON.stringify(intent), - }); - return result; - } - - private advertisedTransport(): { transport?: string } { - const commands = (this.provider as { commands?: Array<{ command?: string; transport?: string }> } | undefined)?.commands; - const transport = commands?.find(command => command.command === "ghostlight.eve.commands")?.transport; - return transport ? { transport } : {}; - } - - async completeAuthentication(handle: string): Promise { - if (!this.provider) await this.providerAdvertisement(); - return await this.submitCommand({ - schema: "gamecult.eve.command_invocation.v1", - providerId: this.provider?.providerId || "gamecult.ghostlight.dungeon", - surfaceId: "ghostlight.play", - operation: { - operationId: "heimdall.auth.complete", - schemaId: "heimdall.auth_complete_command.v1", - idempotencyKey: crypto.randomUUID(), - // The route transport is the one the provider advertises for its - // command boundary, as the vendored client takes it from a command - // descriptor; Ghostlight refuses an invocation without it. - routeHint: { sourceVersion: this.sourceVersion, ...this.advertisedTransport() }, - }, - payload: { handle }, - issuedAt: new Date().toISOString(), - clientId: "ghostlight.browser", - commandBoundary: "ghostlight.eve.commands", - receiptSchema: "gamecult.eve.command_result.v1", - }); - } -} - -async function fetchJson(input: RequestInfo | URL, init?: RequestInit): Promise { - const response = await fetch(input, { cache: "no-store", credentials: "same-origin", ...init }); - const body = await response.json().catch(() => undefined); - if (!response.ok) { - const message = body && typeof body.message === "string" - ? body.message - : `Ghostlight refused the request (${response.status}).`; - throw new Error(message); - } - return body as T; -} - -function containsAnonymousAccessGate(value: unknown): boolean { - if (!value || typeof value !== "object") return false; - if (Array.isArray(value)) return value.some(containsAnonymousAccessGate); - const node = value as Record; - if (node.kind === "heimdall.access_gate") { - const props = node.props && typeof node.props === "object" && !Array.isArray(node.props) - ? node.props as Record - : {}; - return props.state === "anonymous"; - } - return Object.values(node).some(containsAnonymousAccessGate); -} - -function requiredElement(id: string): T { - const element = document.getElementById(id); - if (!(element instanceof HTMLElement)) throw new Error(`Missing browser host #${id}.`); - return element as T; -} - -const surfaceHost = requiredElement("surface"); -const status = requiredElement("status"); -const api = new GhostlightEveTransport(); -const host = new EveBrowserProviderHost(surfaceHost, api, { - body: document.body, - clientId: "ghostlight.browser", - // PA.f191: this used to be 0 (no poll at all), relying entirely on the - // `revision` SSE subscription below for every live update. A dropped - // stream — closed by an intermediary, or never subscribed at all (see - // `trySubscribeToRevisions` below) — then froze the card with no recovery - // short of a manual reload. This poll is deliberately low-frequency: it is - // a fallback net, not the primary channel, and `host.refresh()` is already - // a no-op when the surface version has not moved. - pollMs: 5_000, - requestedSurfaceId: "ghostlight.play", - source: "Ghostlight", - statusElement: status, - pluginAdapters: [heimdallAccessBrowserAdapter], -}); - -window.addEventListener("unhandledrejection", event => { - event.preventDefault(); - status.textContent = event.reason instanceof Error ? event.reason.message : String(event.reason); -}); - -// PA.f191: `api.hasAuthenticatedSurface()` reflects whatever the *last* -// `surface()` fetch saw, and that flag can flip from false to true well -// after this module's own startup sequence finishes — a player who signs in -// through the in-page gate (`heimdall.auth_completion_status.v1`, resolved -// entirely inside the vendored host's own `submit()`/`refresh()` cycle, -// never observed by this file directly) authenticates on a timer this file -// has no direct hook into. A one-shot check right after startup only ever -// caught the redirect flow (`resumeHeimdallAccess`'s own `complete` -// callback, below); the in-page flow left the tab with no `revision` -// subscription for the rest of the session, so every answer after the first -// was refused as stale and the card looked frozen. `trySubscribeToRevisions` -// is idempotent and cheap to call speculatively — `hasAuthenticatedSurface()` -// is a field read — so it is called at every point this file can observe an -// authentication transition, plus on a short recheck interval to catch the -// in-page flow it cannot observe directly any other way. -let revisionsSubscribed = false; -function trySubscribeToRevisions(): void { - if (revisionsSubscribed || !api.hasAuthenticatedSurface()) return; - revisionsSubscribed = true; - const events = new EventSource("api/eve/events"); - events.addEventListener("revision", () => void host.refresh()); - events.addEventListener("error", () => { - status.textContent = "Live revision notices are unavailable; your authoritative surface remains safe to refresh."; - }); -} - -await host.start(); -trySubscribeToRevisions(); -const resumeTarget = { - complete: async (handle: string) => { - const result = await api.completeAuthentication(handle); - if (result.pluginPayload?.pluginId === heimdallAccessBrowserAdapter.pluginId) { - await heimdallAccessBrowserAdapter.consumeCommandResult?.(result.pluginPayload); - } - await host.refresh(); - trySubscribeToRevisions(); - }, -}; -await resumeHeimdallAccess(resumeTarget, { appSlug: "ghostlight" }); -trySubscribeToRevisions(); - -// A player who finishes Discord in another tab or app and switches back to -// this one, rather than following Heimdall's "Return to the app" link, never -// reloads this page, so the load-time resume above never sees the result. -// Re-running the same resume when the tab becomes visible asks Heimdall about -// the attempt this tab started; it answers pending or authenticated, and the -// adapter drops the stored attempt once the answer is final. -let resuming = false; -document.addEventListener("visibilitychange", () => { - if (document.visibilityState !== "visible" || resuming || api.hasAuthenticatedSurface()) return; - resuming = true; - resumeHeimdallAccess(resumeTarget, { appSlug: "ghostlight" }) - .catch(error => { - status.textContent = error instanceof Error ? error.message : String(error); - }) - .finally(() => { - resuming = false; - }); -}); - -// The in-page gate's own completion never calls back into this file: it -// resolves inside the vendored host's `submit()` (a command dispatch) and -// its own `window.setTimeout(() => void host.refresh(), 100)`, which is the -// one place `api.hasAuthenticatedSurface()` gets re-evaluated for that flow. -// This is the only vantage point this file has on that transition; the -// pollMs fallback above shares the same "cheap, idempotent, safe to run -// speculatively" reasoning. -window.setInterval(trySubscribeToRevisions, 2_000); diff --git a/web/src/style.css b/web/src/style.css deleted file mode 100644 index 40c4bac..0000000 --- a/web/src/style.css +++ /dev/null @@ -1,25 +0,0 @@ -@import url('https://fonts.googleapis.com/css2?family=Crimson+Pro:opsz,wght@8..144,400;8..144,600&family=IBM+Plex+Mono:wght@400;600&display=swap'); -:root{color-scheme:dark;font-family:"Crimson Pro",serif;background:#0c1110;color:#e8e1cf} -body{margin:0;min-height:100vh;background:radial-gradient(circle at 15% 0,#253229 0,transparent 38rem),linear-gradient(145deg,#0c1110,#111513)} -header,#surface{width:min(1180px,calc(100% - 2rem));margin:auto} -header{padding:3rem 0 1.25rem;border-bottom:1px solid #66543d} -h1{font-size:clamp(2.6rem,8vw,5.5rem);font-weight:400;letter-spacing:-.045em;margin:.1rem 0} -.eyebrow,#status,.field-label,button,pre{font-family:"IBM Plex Mono",monospace} -.eyebrow{color:#d49b58;letter-spacing:.18em;font-size:.72rem} -#status{color:#9aa69f;font-size:.78rem} -#surface{padding:1.5rem 0 5rem;min-height:12rem} -.eve-surface{display:grid;gap:1rem} -.card,.pane,.heimdall-access{padding:1rem;border:1px solid #66543d;background:#17201ddd} -.cultui-field{display:block;margin:.75rem 0} -.field-label{display:block;font-size:.72rem;text-transform:uppercase;letter-spacing:.12em;margin:.65rem 0 .25rem} -textarea,input,select{box-sizing:border-box;width:100%;resize:vertical;background:#0b0f0d;color:#f2e7d0;border:1px solid #4a5148;padding:.8rem;margin:.15rem 0;font:1.05rem/1.4 "Crimson Pro",serif} -textarea{min-height:7rem} -button{margin:.8rem .5rem 0 0;padding:.65rem 1rem;border:1px solid #d49b58;background:#d49b58;color:#17120c;cursor:pointer} -button:disabled,input:disabled,textarea:disabled,select:disabled{cursor:not-allowed;opacity:.5} -pre,.cultui-code{white-space:pre-wrap;padding:1rem;background:#080b09;color:#aeb9af;overflow:auto;font:.72rem/1.5 "IBM Plex Mono",monospace} -.skip-link{position:absolute;left:-10000px}.skip-link:focus{left:1rem;top:1rem;background:#d49b58;color:#111;padding:.5rem;z-index:9} -.cultui-list-item{border-top:1px solid #354039;padding:.8rem 0} -.cultui-list-item-label,.cultui-list-item-status{font-family:"IBM Plex Mono",monospace;color:#d49b58;font-size:.72rem;text-transform:uppercase;letter-spacing:.08em} -.cultui-tabs [role="tablist"]{display:flex;gap:.4rem;position:sticky;top:0;background:#0c1110e8;z-index:2} -.eve-command-result{margin:1rem 0;padding:1rem;border:1px solid #66543d;background:#17201d} -@media(max-width:600px){header{padding-top:2rem}h1{font-size:3rem}header,#surface{width:min(100% - 1rem,1180px)}.card,.pane,.heimdall-access{padding:.75rem}} diff --git a/web/test/heimdall-adapter.test.mjs b/web/test/heimdall-adapter.test.mjs deleted file mode 100644 index dc273be..0000000 --- a/web/test/heimdall-adapter.test.mjs +++ /dev/null @@ -1,106 +0,0 @@ -import assert from "node:assert/strict"; -import { afterEach, test } from "node:test"; -import { - heimdallAccessBrowserAdapter, - readHeimdallBrowserReturn, - resumeHeimdallAccess, -} from "../src/heimdall-access-adapter.ts"; - -const attemptKey = "gamecult.heimdall.access.attempt"; -const originalGlobals = { - history: globalThis.history, - sessionStorage: globalThis.sessionStorage, - window: globalThis.window, -}; - -afterEach(() => { - restoreGlobal("history", originalGlobals.history); - restoreGlobal("sessionStorage", originalGlobals.sessionStorage); - restoreGlobal("window", originalGlobals.window); -}); - -test("browser return parser completes by attempt id and never reads the completion code", () => { - const handle = "d0a9c1e7-89ac-46f9-8c85-c2484ed18f76"; - assert.deepEqual(readHeimdallBrowserReturn(returnUrl(handle), "ghostlight"), { status: "success", handle }); - assert.equal(readHeimdallBrowserReturn("https://yggdrasil.gamecult.org/ghostlight/", "ghostlight"), undefined); - assert.equal(readHeimdallBrowserReturn(returnUrl(handle), "another-app")?.status, "error"); - assert.deepEqual(readHeimdallBrowserReturn(returnUrl(handle, "secret-redeem-code"), "ghostlight"), { status: "success", handle }); - assert.ok(!JSON.stringify(readHeimdallBrowserReturn(returnUrl(handle, "secret-redeem-code"), "ghostlight")).includes("secret-redeem-code")); - assert.equal(readHeimdallBrowserReturn(returnUrl("", "secret-redeem-code"), "ghostlight")?.status, "error"); -}); - -test("fresh browser context redeems the URL witness and scrubs it", async () => { - const handle = "0be30b8c-b599-4920-b8b8-733f5e7bc275"; - const storage = memoryStorage(); - const replaced = []; - installBrowserGlobals(returnUrl(handle), storage, replaced); - const completed = []; - - assert.equal(await resumeHeimdallAccess({ complete: async value => completed.push(value) }, { appSlug: "ghostlight" }), true); - assert.deepEqual(completed, [handle]); - assert.equal(storage.getItem(attemptKey), handle); - assert.deepEqual(replaced, ["/ghostlight/"]); - - await heimdallAccessBrowserAdapter.consumeCommandResult({ - schemaId: "heimdall.auth_completion_status.v1", - payload: { status: "authenticated" }, - }); - assert.equal(storage.getItem(attemptKey), null); -}); - -test("conflicting stored and returned attempts never reach completion", async () => { - const storage = memoryStorage([[attemptKey, "stored-handle"]]); - installBrowserGlobals(returnUrl("returned-handle"), storage, []); - let completed = false; - - await assert.rejects( - resumeHeimdallAccess({ complete: async () => { completed = true; } }, { appSlug: "ghostlight" }), - /other than the one this browser started/, - ); - assert.equal(completed, false); - assert.equal(storage.getItem(attemptKey), null); -}); - -function installBrowserGlobals(href, storage, replaced) { - Object.defineProperty(globalThis, "sessionStorage", { configurable: true, value: storage }); - Object.defineProperty(globalThis, "history", { - configurable: true, - value: { replaceState: (_state, _title, url) => replaced.push(url) }, - }); - Object.defineProperty(globalThis, "window", { - configurable: true, - value: { location: { href, pathname: "/ghostlight/", search: "" } }, - }); -} - -function restoreGlobal(name, value) { - if (value === undefined) delete globalThis[name]; - else Object.defineProperty(globalThis, name, { configurable: true, value }); -} - -// Heimdall issues a random completion code distinct from the attempt id, as -// the real callback does; the fixture must not restate the old equality. -function returnUrl(attemptId, completionCode = `code-for-${attemptId}`) { - const parameters = new URLSearchParams({ - heimdall_status: "success", - heimdall_provider: "discord", - heimdall_handoff_kind: "browser_completion", - heimdall_app_slug: "ghostlight", - heimdall_mode: "sign_in", - heimdall_attempt_id: attemptId, - heimdall_completion_code: completionCode, - }); - return `https://yggdrasil.gamecult.org/ghostlight/#${parameters}`; -} - -function memoryStorage(initial = []) { - const values = new Map(initial); - return { - get length() { return values.size; }, - clear: () => values.clear(), - getItem: key => values.get(key) ?? null, - key: index => [...values.keys()][index] ?? null, - removeItem: key => { values.delete(key); }, - setItem: (key, value) => { values.set(key, value); }, - }; -} diff --git a/web/test/static-boundary.mjs b/web/test/static-boundary.mjs deleted file mode 100644 index ac429fc..0000000 --- a/web/test/static-boundary.mjs +++ /dev/null @@ -1,36 +0,0 @@ -import { readFileSync, readdirSync, statSync } from "node:fs"; -import { join } from "node:path"; -import { fileURLToPath } from "node:url"; - -const forbidden = [ - "/api/session-zero", - "/api/governance", - "/api/command", - "/api/auth/heimdall", - "renderSession", - "renderCampaign", - "payload.fields", - 'kind: "form"', - '"kind":"form"', -]; - -function sourceFiles(directory) { - return readdirSync(directory) - .flatMap(name => { - const path = join(directory, name); - return statSync(path).isDirectory() ? sourceFiles(path) : [path]; - }) - .filter(path => /\.(ts|tsx|js|mjs)$/.test(path)); -} - -const violations = sourceFiles(fileURLToPath(new URL("../src", import.meta.url))) - .flatMap(path => { - const source = readFileSync(path, "utf8"); - return forbidden.filter(token => source.includes(token)).map(token => `${path}: ${token}`); - }); - -if (violations.length) { - throw new Error(`Ghostlight browser crossed its Eve boundary:\n${violations.join("\n")}`); -} - -console.log("Ghostlight browser contains only the Eve provider boundary."); diff --git a/web/tsconfig.json b/web/tsconfig.json deleted file mode 100644 index 39a530a..0000000 --- a/web/tsconfig.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - "compilerOptions": { - "target": "ES2022", - "lib": ["ES2022", "DOM", "DOM.Iterable"], - "module": "ESNext", - "moduleResolution": "Bundler", - "noEmit": true, - "strict": true, - "skipLibCheck": true - }, - "include": ["src/**/*.ts"] -} diff --git a/web/vite.config.mjs b/web/vite.config.mjs deleted file mode 100644 index 946bc96..0000000 --- a/web/vite.config.mjs +++ /dev/null @@ -1,15 +0,0 @@ -import { fileURLToPath, URL } from "node:url"; -import { defineConfig } from "vite"; - -export default defineConfig({ - resolve: { - alias: { - "@gamecult/eve-contracts": fileURLToPath( - new URL("../vendor/eve/packages/eve-contracts/dist/index.js", import.meta.url), - ), - "ajv/dist/2020.js": fileURLToPath( - new URL("./node_modules/ajv/dist/2020.js", import.meta.url), - ), - }, - }, -});