diff --git a/.gitignore b/.gitignore index d772650..3c71615 100644 --- a/.gitignore +++ b/.gitignore @@ -1,6 +1,14 @@ -__pycache__/ -*.pyc -.venv/ node_modules/ -state/scratch-compaction-*.md -experiments/images/ +sidecar/claude-sdk/dist/ +target/ + +# Disposable local scaffolding. These accumulated to ~87MB of untracked debris +# once; the workspace must stay re-enterable, so they never come back. +.tmp-* +/tmp/ +--help +--help.lock +/acceptance-run* + +# Claude Code agent worktrees (Hands/Soul isolation); never source +.claude/worktrees/ diff --git a/.gitmodules b/.gitmodules deleted file mode 100644 index de7101c..0000000 --- a/.gitmodules +++ /dev/null @@ -1,3 +0,0 @@ -[submodule "vendor/cultcache-py"] - path = vendor/cultcache-py - url = https://github.com/GameCult/cultcache-py.git diff --git a/AGENTS.md b/AGENTS.md index f937d36..f0e4406 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -2,201 +2,106 @@ ## Project Purpose -Ghostlight is a research and implementation home for socially persistent -generative agents. The core problem is not "make an LLM sound like a person." -The core problem is building an architecture where personality, culture, -memory, masks, perception, and incentives can actually survive contact with -time, relationships, routine, tonal variation, and pressure. +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 (parked at +tag `parked/ghostlight-eve-surface`). `README.md` says +what exists today and what does not. -This repo exists so those organs can live somewhere cleaner than a side chamber -inside another project. +## Where State Lives -## Canonical State +- Campaign state (targets, rulings, cut specs, reports, verdicts, findings, + follow-ups) lives in the Eureka mind, not in this repo. The current campaign + is `ghostlight-verse`; query it through the `eureka-state` tools. +- `notes/ghostlight-verse-target.md` and `notes/ghostlight-verse-map.md` are the + campaign's prose target and map. Read the map for probed body facts. +- This repo has no state directory, no state CLI, and no evidence ledger. Do not + create one. History belongs in git; durable decisions belong in the mind. +- `notes/fresh-workspace-handoff.md` is a pointer: what runs, how it deploys, + where open work is queried. +- Dated cut documents and postmortems (`docs/architecture/*-cut.md`, + `*-postmortem.md`) are history. Do not edit them, including their old paths. -- Treat `state/ghostlight-state.cultcache.jsonl` as the CultCache-backed - persistence spine for machine-managed state records that have migrated. -- Treat `state/map.yaml` as the canonical human-readable project map. -- Treat `state/scratch.md` as disposable working memory for one bounded - subgoal. -- Treat `state/evidence.jsonl` and `state/branches.json` as readable export - surfaces during the persistence migration, not as the long-term direct-write - API. -- Treat `state/evidence.jsonl` as the distilled durable ledger of what was - learned, verified, rejected, or accepted. -- Treat `notes/ghostlight-implementation-plan.md` as the current implementation - plan for the larger organs. -- Update `state/map.yaml` when project understanding changes. -- Add evidence after meaningful research, implementation, verification, or - rejected paths, but keep it distilled. Routine "I just did this" proof - belongs in git history, commits, smoke artifacts, or targeted logs unless it - changes what the next session should believe. -- Do not turn notes, map, handoff, and evidence into four versions of the same - brain. Distinct jobs or bust. +## Invariants -## Important Paths +- **The kernel decides.** The kernel owns world state through its closed + operation set. Models, tools, controllers, and consumers produce proposals + only. No code outside the kernel commits world state, and no compatibility + writer exists. +- **The library is sealed.** `crates/ghostlight` exposes create/open, + immutable snapshots, command submission, typed receipts, and the runner and + port entry points. Do not publish mutable world types, an ID issuer, a reducer + entry, or a journal handle for the convenience of tests or adapters. The seal + is proven by the `compile_fail` doc-tests in `crates/ghostlight/src/lib.rs` + and by `crates/ghostlight/tests/external_admission.rs`; keep both passing and + extend them when the public surface changes. +- **Every commit is a command.** Everything enters through the mailbox + (`crates/ghostlight/src/mailbox.rs`) as a command. Do not append a commit when + reduction produces no canonical mutation. +- **A Persona never sees structured state.** Persona turns are prose; an + Interpreter lowers them to typed proposals, and anything it cannot lower + becomes a recorded gap, not invented state. +- **Typed state.** Runtime documents are CultCache `.cc`. JSON is for schema + publication and boundaries with other systems. +- **Credentials.** Ghostlight never reads, copies, forwards, or logs a model + credential. A consumer never restates a foreign owner's document shape as its + own strict struct; read the owner's published contract and test against the + real counterpart. +- **Canon flows one way.** Simulation output never writes back into AetheriaLore + or Aetheria's catalog without operator review. -- Project root: `E:\Projects\Ghostlight` -- Canonical map: `E:\Projects\Ghostlight\state\map.yaml` -- Scratch surface: `E:\Projects\Ghostlight\state\scratch.md` -- Distilled evidence ledger: `E:\Projects\Ghostlight\state\evidence.jsonl` -- Branch ledger: `E:\Projects\Ghostlight\state\branches.json` -- Handoff summary: `E:\Projects\Ghostlight\notes\fresh-workspace-handoff.md` -- System map: `E:\Projects\Ghostlight\notes\ghostlight-current-system-map.md` -- Implementation plan: `E:\Projects\Ghostlight\notes\ghostlight-implementation-plan.md` -- Architecture rationale: `E:\Projects\Ghostlight\notes\architecture-rationale.md` -- State CLI: `E:\Projects\Ghostlight\tools\ghostlight_state.py` -- CultCache state seam: `E:\Projects\Ghostlight\tools\ghostlight_state_store.py` -- CultCache-Py submodule: `E:\Projects\Ghostlight\vendor\cultcache-py` -- CultCache state store: `E:\Projects\Ghostlight\state\ghostlight-state.cultcache.jsonl` -- Pre-compaction helper: `E:\Projects\Ghostlight\tools\ghostlight_prepare_compaction.py` +## Where Things Are -## Useful Commands +- 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`. +- 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`. +- 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. -Use the bundled Python runtime if `python` is not on PATH: +## Build, Verify, Deploy -```powershell -npm run state:status -npm run state:prepare-compaction -& 'C:\Users\Meta\.cache\codex-runtimes\codex-primary-runtime\dependencies\python\python.exe' '.\tools\ghostlight_state.py' add-evidence --type research --status ok --note '...' -& 'C:\Users\Meta\.cache\codex-runtimes\codex-primary-runtime\dependencies\python\python.exe' '.\tools\ghostlight_state.py' add-branch --id branch-id --hypothesis '...' -``` +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`. -## Session Bootstrap And Re-entry Protocol - -On fresh session load, do this before wandering off into implementation: - -1. read: - - `state/map.yaml` - - `notes/fresh-workspace-handoff.md` - - `notes/ghostlight-current-system-map.md` - - `notes/ghostlight-implementation-plan.md` -2. run: - - `npm run state:status` -3. restate the current next action from the persisted state before starting - edits -4. if the user only asked to rehydrate or reorient, stop after orientation and - wait for an explicit continue instruction instead of treating the persisted - next action as permission to start coding - -After compaction, resume, or suspicious continuity loss: - -1. rerun `npm run state:status` -2. reread `state/map.yaml` and `notes/fresh-workspace-handoff.md` -3. treat the persisted next action as authoritative unless fresh repo evidence - contradicts it - -When context pressure is clearly rising: - -1. stop broad exploration -2. narrow the active move to one bounded organ -3. persist map or handoff updates, plus distilled evidence only when the lesson - changes future belief, before the blackout lands - -When the user says to prepare for imminent compaction: - -1. immediately write hot live context from memory into a new - `state/scratch-compaction-.md` file before reading files, running - status checks, or doing tidy persistence work -2. run `tools/ghostlight_prepare_compaction.py` before editing persistence - surfaces -3. use its warnings as the checklist for map, handoff, scratch, evidence, and - git hygiene -4. update only the state that actually needs to change -5. after hot context has been folded into canonical persisted state, delete the - `state/scratch-compaction-.md` file so stale emergency memory does not - linger -6. run `tools/ghostlight_prepare_compaction.py` again after edits and scratch - cleanup -7. fix errors, address warnings, and commit the completed persistence pass - unless the work is deliberately mid-surgery +For infrastructure, SSH, Idunn, Odin, or Heimdall work, consult +`F:\Projects\gamecult-ops` before acting. ## Operating Discipline -- Steward persistent state as part of the work. If a lesson changes future - behavior, update the smallest correct memory surface before moving on; if a - memory surface is stale, duplicated, or making re-entry slower, cut or - consolidate it. -- Before substantial edits, restate the current mechanism and intended change. -- Prefer one clear hypothesis per iteration. -- Verify with checks that reflect the real goal, not just proxy success. -- Revert or discard changes that do not clearly improve the target. -- If the diff grows while understanding shrinks, stop implementation and switch - to diagnosis. -- Keep maps and prose together; do not replace useful maps with prose-only - explanations. -- Commit completed work before it rots in the worktree unless the task is - deliberately mid-surgery or the user asked to leave changes uncommitted. -- Push after major completed passes when a remote exists, unless the user asked - not to or there is a concrete reason to keep the commit local for a moment. -- Before handoff, compaction, or phase boundaries, sync `state/map.yaml`, add - distilled evidence when the lesson changes future belief, refresh - `notes/fresh-workspace-handoff.md`, and make the next action explicit. -- Treat `state/map.yaml` as a working memory map, not an archive. Preserve - current mission, live seams, boundaries, and next action; let git history, - evidence, and artifact files carry chronology. -- In documentation, describe the live system and current rule directly. Do not - write victory laps, scar tours, clever autopsies, or contrastive little - boasts about what the project no longer does. If a sentence congratulates the - design for not being a previous wrong design, cut it or rewrite it as a plain - current rule. If rejected history matters, keep it short, explicit, and - decision-relevant; otherwise cut it. The docs are not a trophy case for - yesterday's wrong machine. +- Restate the current mechanism and intended change before substantial edits. + Prefer one clear hypothesis per iteration. +- Verify with checks that reflect the real goal, not proxy success. Revert + changes that do not clearly improve the target. +- If the diff grows while understanding shrinks, stop and diagnose. +- Delete obsolete authority before adding a new path. Do not keep an old writer + alive behind a shim. +- Commit completed work and push it. Merge, confirm the tip by SHA, then delete + the branch; push only after reading the test result line. +- In documentation, describe the live system and the current rule directly. No + claim of capability without a file that implements it. Keep rejected history + short and decision-relevant, or leave it in git. -## Aetheria Grounding Doctrine +## Aetheria Grounding -- Before writing or generating Aetheria scenes, check AetheriaLore for the - factions, movements, institutions, species or body types, location, and time - period involved. -- Before drafting story prose, choose an intentional tonal mode or blend for the - scene. Aetheria should support wit-with-stakes, warmth, absurdity, domestic - texture, ritual quiet, wonder, horror, noir, dour poetry, and dry systems - prose as needed. Do not default to constant crisis or procedural severity. -- Use Adams/Pratchett-style comic precision and humane levity as a useful - default touchstone when no stronger scene-specific style is called for: - jokes and absurdity should reveal stakes, not dissolve them. -- Establish ordinary life before interruption when the fixture calls for it: - routines, work texture, relationships, private jokes, rituals, small desires, - and local accommodations are part of worldbuilding, not filler. -- For illustrated Ink fixtures, segment prose into click-through visual - sections. Distinct places, focal areas, object closeups, arrivals, alarms, - pivotal one-sentence beats, and aftermath states need stable visual scene ids - and imagegen-ready prompts. -- Treat visual artifacts as illustrated replay and website collateral, not core - social-model training signal. Visual review judges the playable Ink - experience plus the visual plan, not clean-run prose receipts. -- Write visual prompts for a general image model, not a lore expert. Explain - fictional objects and body affordances in visible terms: geometry, materials, - lighting, stance, interfaces, tools, supports, cables, fluids, screens, and - crowd positions. -- Do the same for environments. A location label like "manifold line," "cavity - yard," "supervisor glass," or "anchor rail" is not a drawable scene until the - prompt describes its visible geometry, materials, interfaces, lights, and - scale. -- If a fixture has a target visual style, store that style cue once in the - sidecar and include it in every assembled image prompt. Do not rely on memory - or unstated website context to carry the look. -- Do not treat a character name as a visual description. Illustrated fixtures - need stable character visual refs for every recurring named character, and - scene prompts should either include those refs during prompt assembly or carry - enough appearance detail to stand alone. -- Include visual character refs only for characters actually visible in the - rendered frame. Do not feed imagegen refs for absent, off-frame, merely - mentioned, or object-represented characters. -- Treat visual continuity notes as tool/reviewer constraints, not prompt text. - If imagegen needs the fact, rewrite it as concrete visible description in the - base prompt, character ref, or branch/state modifier. -- Treat generated environment images as concept and material reference, not - spatial truth. Multi-angle or branch-consistent illustrated IF needs a durable - scene-set source such as a hand-built blockout, procedural scene file, layout - asset, or camera map. Imagegen can paint over camera-specific visual input; - it should not be asked to preserve room topology from a prior generated - image or text memory. -- Ground scene writing in the source's material details: habitat form, - infrastructure, law, class pressure, money, route access, surveillance, - communication channels, body affordances, and local failure costs. -- If the source is too vague for a concrete scene detail, do not bluff. Mark - the lore gap, patch the AetheriaLore source with a narrow elaboration, then - regenerate or revise the Ghostlight artifact from that patched source. -- Treat this as part of data generation. Ghostlight is expected to stress-test - Aetheria at room scale, find missing granularity, and push useful - elaborations back into the lore vault. +- Before writing or generating Aetheria material, check AetheriaLore for the + factions, institutions, species or body types, location, and time period + involved. Ground detail in the source's material facts: habitat, law, money, + route access, surveillance, communication channels, and local failure costs. +- If the source is too vague for a concrete detail, do not bluff. Mark the gap + and propose a narrow elaboration for AetheriaLore, subject to operator review. +- Choose a tonal mode on purpose. Aetheria supports wit with stakes, warmth, + absurdity, domestic texture, ritual quiet, wonder, horror, noir, and dry + systems prose; do not default to constant crisis. Comic precision in the + Adams/Pratchett manner is a good default, where jokes reveal stakes instead of + dissolving them. +- Establish ordinary life before interruption: routines, work, relationships, + small desires, and local accommodations are worldbuilding, not filler. diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 0000000..640c1a1 --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1,3 @@ +Repository doctrine for this project lives in AGENTS.md, shared with Codex. + +@AGENTS.md diff --git a/Cargo.lock b/Cargo.lock new file mode 100644 index 0000000..2895d58 --- /dev/null +++ b/Cargo.lock @@ -0,0 +1,2779 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "aead" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d122413f284cf2d62fb1b7db97e02edb8cda96d769b16e443a4f6195e35662b0" +dependencies = [ + "crypto-common", + "generic-array", +] + +[[package]] +name = "aes" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b169f7a6d4742236a0a00c541b845991d0ac43e546831af1249753ab4c3aa3a0" +dependencies = [ + "cfg-if", + "cipher", + "cpufeatures 0.2.17", +] + +[[package]] +name = "aes-gcm" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "831010a0f742e1209b3bcea8fab6a8e149051ba6099432c8cb2cc117dec3ead1" +dependencies = [ + "aead", + "aes", + "cipher", + "ctr", + "ghash", + "subtle", +] + +[[package]] +name = "aho-corasick" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba" +dependencies = [ + "memchr", +] + +[[package]] +name = "android_system_properties" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae221649c9976a6f6c56ae1facf410f3ddb33cc661c4b7b61020a912d4237fbc" +dependencies = [ + "libc", +] + +[[package]] +name = "anyhow" +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" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b5a71a6f37880a80d1d7f19efd781e4b5de42c88f0722cc13bcb6cc2cfe8476" +dependencies = [ + "async-stream-impl", + "futures-core", + "pin-project-lite", +] + +[[package]] +name = "async-stream-impl" +version = "0.3.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c7c24de15d275a1ecfd47a380fb4d5ec9bfe0933f309ed5e705b775596a3574d" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "async-trait" +version = "0.1.92" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "82f6aeea286b8eb4dd3431a1be1b59d290ace00f5bfd8e2a159bc2a05e2c1667" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.3", +] + +[[package]] +name = "atomic-waker" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" + +[[package]] +name = "autocfg" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" + +[[package]] +name = "axum" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "31b698c5f9a010f6573133b09e0de5408834d0c82f8d7475a89fc1867a71cd90" +dependencies = [ + "axum-core", + "axum-macros", + "bytes", + "form_urlencoded", + "futures-util", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-util", + "itoa", + "matchit", + "memchr", + "mime", + "percent-encoding", + "pin-project-lite", + "serde_core", + "serde_json", + "serde_path_to_error", + "serde_urlencoded", + "sync_wrapper", + "tokio", + "tower", + "tower-layer", + "tower-service", + "tracing", +] + +[[package]] +name = "axum-core" +version = "0.5.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08c78f31d7b1291f7ee735c1c6780ccde7785daae9a9206026862dab7d8792d1" +dependencies = [ + "bytes", + "futures-core", + "http", + "http-body", + "http-body-util", + "mime", + "pin-project-lite", + "sync_wrapper", + "tower-layer", + "tower-service", + "tracing", +] + +[[package]] +name = "axum-macros" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7aa268c23bfbbd2c4363b9cd302a4f504fb2a9dfe7e3451d66f35dd392e20aca" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "base64" +version = "0.22.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" + +[[package]] +name = "base64ct" +version = "1.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06" + +[[package]] +name = "bitflags" +version = "2.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b588b76d00fde79687d7646a9b5bdf3cc0f655e0bbd080335a95d7e96f3587da" + +[[package]] +name = "block-buffer" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" +dependencies = [ + "generic-array", +] + +[[package]] +name = "bumpalo" +version = "3.20.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649" + +[[package]] +name = "bytes" +version = "1.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" + +[[package]] +name = "cc" +version = "1.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "509591b7bcd67f4ef775afad7662703b4935daaa6ec0e5605cfb1090b32a2b6d" +dependencies = [ + "find-msvc-tools", + "shlex", +] + +[[package]] +name = "cfg-if" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" + +[[package]] +name = "cfg_aliases" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527" + +[[package]] +name = "chacha20" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d524456ba66e72eb8b115ff89e01e497f8e6d11d78b70b1aa13c0fbd97540a81" +dependencies = [ + "cfg-if", + "cpufeatures 0.3.0", + "rand_core 0.10.1", +] + +[[package]] +name = "chrono" +version = "0.4.45" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1aa79e62e7697b8e29b513a68abacf485adcd1fe8284a4316c5ae868e6633327" +dependencies = [ + "iana-time-zone", + "js-sys", + "num-traits", + "serde", + "wasm-bindgen", + "windows-link", +] + +[[package]] +name = "cipher" +version = "0.4.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad" +dependencies = [ + "crypto-common", + "inout", +] + +[[package]] +name = "const-oid" +version = "0.9.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2459377285ad874054d797f3ccebf984978aa39129f6eafde5cdc8315b612f8" + +[[package]] +name = "core-foundation-sys" +version = "0.8.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" + +[[package]] +name = "cpufeatures" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" +dependencies = [ + "libc", +] + +[[package]] +name = "cpufeatures" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b2a41393f66f16b0823bb79094d54ac5fbd34ab292ddafb9a0456ac9f87d201" +dependencies = [ + "libc", +] + +[[package]] +name = "crypto-common" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" +dependencies = [ + "generic-array", + "rand_core 0.6.4", + "typenum", +] + +[[package]] +name = "ctr" +version = "0.9.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0369ee1ad671834580515889b80f2ea915f23b8be8d0daa4bbaf2ac5c7590835" +dependencies = [ + "cipher", +] + +[[package]] +name = "cultcache-rs" +version = "0.1.0" +source = "git+https://github.com/GameCult/CultLib.git?rev=85f7024a35ea42cf9f0a0199a064526427150191#85f7024a35ea42cf9f0a0199a064526427150191" +dependencies = [ + "anyhow", + "chrono", + "cultcache-rs-derive 0.1.0", + "fs2", + "redb", + "rmp-serde", + "serde", + "serde_bytes", + "serde_json", + "uuid", + "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" +source = "git+https://github.com/GameCult/CultLib.git?rev=85f7024a35ea42cf9f0a0199a064526427150191#85f7024a35ea42cf9f0a0199a064526427150191" +dependencies = [ + "proc-macro2", + "quote", + "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 0.1.0", + "cultnet-rs 0.1.0", + "serde", +] + +[[package]] +name = "cultnet-rs" +version = "0.1.0" +source = "git+https://github.com/GameCult/CultLib.git?rev=85f7024a35ea42cf9f0a0199a064526427150191#85f7024a35ea42cf9f0a0199a064526427150191" +dependencies = [ + "aes-gcm", + "anyhow", + "base64", + "chrono", + "cultcache-rs 0.1.0", + "ed25519-dalek", + "hmac", + "rand 0.9.5", + "rmp-serde", + "rmpv", + "serde", + "serde_bytes", + "serde_json", + "sha2", + "socket2 0.5.10", + "uuid", + "windows-sys 0.61.2", + "zeroize", +] + +[[package]] +name = "cultnet-rs" +version = "0.2.0" +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", + "rmp-serde", + "rmpv", + "serde", + "serde_bytes", + "serde_json", + "sha2", + "socket2 0.5.10", + "uuid", + "windows-sys 0.61.2", + "zeroize", +] + +[[package]] +name = "curve25519-dalek" +version = "4.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "97fb8b7c4503de7d6ae7b42ab72a5a59857b4c937ec27a3d4539dba95b5ab2be" +dependencies = [ + "cfg-if", + "cpufeatures 0.2.17", + "curve25519-dalek-derive", + "digest", + "fiat-crypto", + "rustc_version", + "subtle", + "zeroize", +] + +[[package]] +name = "curve25519-dalek-derive" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f46882e17999c6cc590af592290432be3bce0428cb0d5f8b6715e4dc7b383eb3" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "der" +version = "0.7.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7c1832837b905bbfb5101e07cc24c8deddf52f93225eee6ead5f4d63d53ddcb" +dependencies = [ + "const-oid", + "zeroize", +] + +[[package]] +name = "deranged" +version = "0.5.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e9de72ce2ad1f90dc62fa25f0f430ef85eb4b0d8fa0be4f30373bc40a21d28e" + +[[package]] +name = "digest" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" +dependencies = [ + "block-buffer", + "crypto-common", + "subtle", +] + +[[package]] +name = "displaydoc" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8" +dependencies = [ + "proc-macro2", + "quote", + "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" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "115531babc129696a58c64a4fef0a8bf9e9698629fb97e9e40767d235cfbcd53" +dependencies = [ + "pkcs8", + "signature", +] + +[[package]] +name = "ed25519-dalek" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "70e796c081cee67dc755e1a36a0a172b897fab85fc3f6bc48307991f64e4eca9" +dependencies = [ + "curve25519-dalek", + "ed25519", + "serde", + "sha2", + "subtle", + "zeroize", +] + +[[package]] +name = "errno" +version = "0.3.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "fastrand" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" + +[[package]] +name = "fiat-crypto" +version = "0.2.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "28dea519a9695b9977216879a3ebfddf92f1c08c05d984f8996aecd6ecdc811d" + +[[package]] +name = "find-msvc-tools" +version = "0.1.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d45db016d36b838f563236e9193d0ee6ce38f3f68b6c94e914b4929c96bbb890" + +[[package]] +name = "form_urlencoded" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf" +dependencies = [ + "percent-encoding", +] + +[[package]] +name = "fs2" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9564fc758e15025b46aa6643b1b77d047d1a56a1aea6e01002ac0c7026876213" +dependencies = [ + "libc", + "winapi", +] + +[[package]] +name = "futures-channel" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1f9e3d69d39e4862ffed03ed071a76f9a13ba1d9109d355b0f0aa6b15e393c4" +dependencies = [ + "futures-core", +] + +[[package]] +name = "futures-core" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" + +[[package]] +name = "futures-io" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53c0fa8157de1303bfffdaa1cc2a673bfffb60102f76b0ef4441659124373fed" + +[[package]] +name = "futures-macro" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9fb9654ba8355388abeb8dcb4fc62f511300867002afc858860463bdd9fe0c44" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.3", +] + +[[package]] +name = "futures-sink" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1944426bf7d03f1d14f708785e4b33efd750b36d48a157b836b3efc15ede8e1d" + +[[package]] +name = "futures-task" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd" + +[[package]] +name = "futures-util" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" +dependencies = [ + "futures-core", + "futures-io", + "futures-macro", + "futures-sink", + "futures-task", + "memchr", + "pin-project-lite", + "slab", +] + +[[package]] +name = "generic-array" +version = "0.14.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" +dependencies = [ + "typenum", + "version_check", +] + +[[package]] +name = "getrandom" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" +dependencies = [ + "cfg-if", + "js-sys", + "libc", + "wasi", + "wasm-bindgen", +] + +[[package]] +name = "getrandom" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd" +dependencies = [ + "cfg-if", + "libc", + "r-efi 5.3.0", + "wasip2", +] + +[[package]] +name = "getrandom" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" +dependencies = [ + "cfg-if", + "js-sys", + "libc", + "r-efi 6.0.0", + "rand_core 0.10.1", + "wasm-bindgen", +] + +[[package]] +name = "ghash" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0d8a4362ccb29cb0b265253fb0a2728f592895ee6854fd9bc13f2ffda266ff1" +dependencies = [ + "opaque-debug", + "polyval", +] + +[[package]] +name = "ghostlight" +version = "0.1.0" +dependencies = [ + "async-trait", + "chrono", + "cultcache-rs 0.1.0", + "ghostlight-persona-projection", + "model-connector", + "reqwest", + "rmp-serde", + "rmpv", + "serde", + "serde_bytes", + "serde_json", + "sha2", + "tempfile", + "thiserror", + "tokio", + "tracing", + "unicode-normalization", + "unicode-properties", + "uuid", + "zeroize", +] + +[[package]] +name = "ghostlight-dungeon" +version = "0.1.0" +dependencies = [ + "aes-gcm", + "anyhow", + "async-stream", + "async-trait", + "axum", + "base64", + "chrono", + "cultcache-rs 0.1.0", + "cultmesh-rs", + "cultnet-rs 0.1.0", + "ghostlight", + "ghostlight-persona-projection", + "hmac", + "jsonwebtoken", + "libc", + "model-connector", + "rand 0.9.5", + "reqwest", + "rmp-serde", + "serde", + "serde_json", + "sha2", + "tempfile", + "thiserror", + "tokio", + "tower", + "tracing", + "tracing-subscriber", + "uuid", + "zeroize", +] + +[[package]] +name = "ghostlight-persona-projection" +version = "0.1.0" +dependencies = [ + "serde", + "sha2", + "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" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e" +dependencies = [ + "digest", +] + +[[package]] +name = "http" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0" +dependencies = [ + "bytes", + "itoa", +] + +[[package]] +name = "http-body" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca2a8f2913ee65f60facd6a5905613afaa448497a0230cc41ce022d93290bc2c" +dependencies = [ + "bytes", + "http", +] + +[[package]] +name = "http-body-util" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23169fe34a5fbcdd3f3862e78fb9b6fccd5f02a6dc6f732547005d45631ce71c" +dependencies = [ + "bytes", + "futures-core", + "http", + "http-body", + "pin-project-lite", +] + +[[package]] +name = "httparse" +version = "1.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" + +[[package]] +name = "httpdate" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9" + +[[package]] +name = "hyper" +version = "1.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d22053281f852e11534f5198498373cbb59295120a20771d90f7ed1897490a72" +dependencies = [ + "atomic-waker", + "bytes", + "futures-channel", + "futures-core", + "http", + "http-body", + "httparse", + "httpdate", + "itoa", + "pin-project-lite", + "smallvec", + "tokio", + "want", +] + +[[package]] +name = "hyper-rustls" +version = "0.27.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33ca68d021ef39cf6463ab54c1d0f5daf03377b70561305bb89a8f83aab66e0f" +dependencies = [ + "http", + "hyper", + "hyper-util", + "rustls", + "tokio", + "tokio-rustls", + "tower-service", + "webpki-roots", +] + +[[package]] +name = "hyper-util" +version = "0.1.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "96547c2556ec9d12fb1578c4eaf448b04993e7fb79cbaad930a656880a6bdfa0" +dependencies = [ + "base64", + "bytes", + "futures-channel", + "futures-util", + "http", + "http-body", + "hyper", + "ipnet", + "libc", + "percent-encoding", + "pin-project-lite", + "socket2 0.6.5", + "tokio", + "tower-service", + "tracing", +] + +[[package]] +name = "iana-time-zone" +version = "0.1.65" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e31bc9ad994ba00e440a8aa5c9ef0ec67d5cb5e5cb0cc7f8b744a35b389cc470" +dependencies = [ + "android_system_properties", + "core-foundation-sys", + "iana-time-zone-haiku", + "js-sys", + "log", + "wasm-bindgen", + "windows-core", +] + +[[package]] +name = "iana-time-zone-haiku" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f" +dependencies = [ + "cc", +] + +[[package]] +name = "icu_collections" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fa68d21081c4a05d5a901a1c62add574c77048b6a1c67be3b50ce0b60d4ca513" +dependencies = [ + "displaydoc", + "potential_utf", + "utf8_iter", + "yoke", + "zerofrom", + "zerovec", +] + +[[package]] +name = "icu_locale_core" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d56e28588da92eee5c3201a6eff33fabdd49b62269c8938d4ff050ce4d900deb" +dependencies = [ + "displaydoc", + "litemap", + "tinystr", + "writeable", + "zerovec", +] + +[[package]] +name = "icu_normalizer" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "12f9cf5f235641ed274641dd81c3f28d870e276763d0797aeeab72317b1c646f" +dependencies = [ + "icu_collections", + "icu_normalizer_data", + "icu_properties", + "icu_provider", + "smallvec", + "zerovec", +] + +[[package]] +name = "icu_normalizer_data" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1563da1ed3e0b3bf3d74c9b85917ac9c56464d2f57242270c09c9e752f8021a0" + +[[package]] +name = "icu_properties" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e7ca276ad3145661a65914e6daf131ca5120cd3dcee8f8f3214b8875184a148" +dependencies = [ + "displaydoc", + "icu_collections", + "icu_locale_core", + "icu_properties_data", + "icu_provider", + "zerotrie", + "zerovec", +] + +[[package]] +name = "icu_properties_data" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e590f038c1464a96894fd6d10127e90a8be4509f56ff7ecef851b15cee0b7caa" + +[[package]] +name = "icu_provider" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92a7ed671a6aad807a8651a2e1782a6598fda9ce5185dd8158549e95a91c6428" +dependencies = [ + "displaydoc", + "icu_locale_core", + "writeable", + "yoke", + "zerofrom", + "zerotrie", + "zerovec", +] + +[[package]] +name = "idna" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de" +dependencies = [ + "idna_adapter", + "smallvec", + "utf8_iter", +] + +[[package]] +name = "idna_adapter" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714" +dependencies = [ + "icu_normalizer", + "icu_properties", +] + +[[package]] +name = "inout" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "879f10e63c20629ecabbb64a8010319738c66a5cd0c29b02d63d272b03751d01" +dependencies = [ + "generic-array", +] + +[[package]] +name = "ipnet" +version = "2.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6a756c3fac73139e83f14c2d742155dd2b78d3ee56597b419a0579b7bdd6dd78" + +[[package]] +name = "itoa" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" + +[[package]] +name = "js-sys" +version = "0.3.104" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e0c1080212aad755ea003d18543e8768dd432c48819efd73a7bf1e39b7a5a3a" +dependencies = [ + "cfg-if", + "futures-util", + "wasm-bindgen", +] + +[[package]] +name = "jsonwebtoken" +version = "9.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a87cc7a48537badeae96744432de36f4be2b4a34a05a5ef32e9dd8a1c169dde" +dependencies = [ + "base64", + "js-sys", + "pem", + "ring", + "serde", + "serde_json", + "simple_asn1", +] + +[[package]] +name = "lazy_static" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb" + +[[package]] +name = "libc" +version = "0.2.189" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2" + +[[package]] +name = "linux-raw-sys" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" + +[[package]] +name = "litemap" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae" + +[[package]] +name = "lock_api" +version = "0.4.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965" +dependencies = [ + "scopeguard", +] + +[[package]] +name = "log" +version = "0.4.33" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ceec5bc11778974d1bcb055b18002eba7f4b3518b6a0081b3af5f21666da9ad" + +[[package]] +name = "lru-slab" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "112b39cec0b298b6c1999fee3e31427f74f676e4cb9879ed1a121b43661a4154" + +[[package]] +name = "matchers" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d1525a2a28c7f4fa0fc98bb91ae755d1e2d1505079e05539e35bc876b5d65ae9" +dependencies = [ + "regex-automata", +] + +[[package]] +name = "matchit" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47e1ffaa40ddd1f3ed91f717a33c8c0ee23fff369e3aa8772b9605cc1d22f4c3" + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "mime" +version = "0.3.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d5848f5a9e8117cf94f2f90faac24a87ff81600ff8628c1e3deaab572e76bfa1" + +[[package]] +name = "mio" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "30d65c71f1ce40ab09135ce117d742b9f8a19ff91a41a8b57ed50bc2de59c427" +dependencies = [ + "libc", + "wasi", + "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" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "num-bigint" +version = "0.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c89e69e7e0f03bea5ef08013795c25018e101932225a656383bd384495ecc367" +dependencies = [ + "num-integer", + "num-traits", +] + +[[package]] +name = "num-conv" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441" + +[[package]] +name = "num-integer" +version = "0.1.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7ce2d95d4b3734dc35aa2f45e1aa22cd416814592a4f9d9205e11affd5b8e10b" +dependencies = [ + "num-traits", +] + +[[package]] +name = "num-traits" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" +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" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "opaque-debug" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c08d65885ee38876c4f86fa503fb49d7b507c2b62552df7c70b2fce627e06381" + +[[package]] +name = "parking_lot" +version = "0.12.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a" +dependencies = [ + "lock_api", + "parking_lot_core", +] + +[[package]] +name = "parking_lot_core" +version = "0.9.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1" +dependencies = [ + "cfg-if", + "libc", + "redox_syscall", + "smallvec", + "windows-link", +] + +[[package]] +name = "pem" +version = "3.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d30c53c26bc5b31a98cd02d20f25a7c8567146caf63ed593a9d87b2775291be" +dependencies = [ + "base64", + "serde_core", +] + +[[package]] +name = "percent-encoding" +version = "2.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" + +[[package]] +name = "pin-project-lite" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" + +[[package]] +name = "pkcs8" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f950b2377845cebe5cf8b5165cb3cc1a5e0fa5cfa3e1f7f55707d8fd82e0a7b7" +dependencies = [ + "der", + "spki", +] + +[[package]] +name = "polyval" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9d1fe60d06143b2430aa532c94cfe9e29783047f06c0d7fd359a9a51b729fa25" +dependencies = [ + "cfg-if", + "cpufeatures 0.2.17", + "opaque-debug", + "universal-hash", +] + +[[package]] +name = "potential_utf" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d83eb9bc6d8e5cf568e7a1101d60ee05e81ed50ea106026f3d18deeb046d7661" +dependencies = [ + "zerovec", +] + +[[package]] +name = "powerfmt" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a6394b9e965e73d0a289ee54f589087e2c676aedf60885baf52c76b771e4958" + +[[package]] +name = "ppv-lite86" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9" +dependencies = [ + "zerocopy", +] + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +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" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c1a41e437b6bbd489372cd4971de128e85c855f56c57f283d20ff016cf7c0a8" +dependencies = [ + "bytes", + "cfg_aliases", + "pin-project-lite", + "quinn-proto", + "quinn-udp", + "rustc-hash", + "rustls", + "socket2 0.6.5", + "thiserror", + "tokio", + "tracing", + "web-time", +] + +[[package]] +name = "quinn-proto" +version = "0.11.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f4bfc015262b9df63c8845072ce59068853ff5872180c2ce2f13038b970e560" +dependencies = [ + "bytes", + "getrandom 0.4.3", + "lru-slab", + "rand 0.10.2", + "rand_pcg", + "ring", + "rustc-hash", + "rustls", + "rustls-pki-types", + "slab", + "thiserror", + "tinyvec", + "tracing", + "web-time", +] + +[[package]] +name = "quinn-udp" +version = "0.5.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "35a133f956daabe89a61a685c2649f13d82d5aa4bd5d12d1277e1072a21c0694" +dependencies = [ + "cfg_aliases", + "libc", + "once_cell", + "socket2 0.6.5", + "tracing", + "windows-sys 0.61.2", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "r-efi" +version = "5.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f" + +[[package]] +name = "r-efi" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" + +[[package]] +name = "rand" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9ef1d0d795eb7d84685bca4f72f3649f064e6641543d3a8c415898726a57b41" +dependencies = [ + "rand_chacha", + "rand_core 0.9.5", +] + +[[package]] +name = "rand" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c7f5fa3a058cd35567ef9bfa5e75732bee0f9e4c55fa90477bef2dfcdbc4be80" +dependencies = [ + "chacha20", + "getrandom 0.4.3", + "rand_core 0.10.1", +] + +[[package]] +name = "rand_chacha" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb" +dependencies = [ + "ppv-lite86", + "rand_core 0.9.5", +] + +[[package]] +name = "rand_core" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" +dependencies = [ + "getrandom 0.2.17", +] + +[[package]] +name = "rand_core" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c" +dependencies = [ + "getrandom 0.3.4", +] + +[[package]] +name = "rand_core" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69" + +[[package]] +name = "rand_pcg" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "caa0f4137e1c0a72f4c651489402276c8e8e1cf081f3b0ba156d2cbeef09e86a" +dependencies = [ + "rand_core 0.10.1", +] + +[[package]] +name = "redb" +version = "4.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e925444704b5f17d32bf42f5b6e2df050bceebc3dcd6e71cc73dafe8092e839" +dependencies = [ + "libc", +] + +[[package]] +name = "redox_syscall" +version = "0.5.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d" +dependencies = [ + "bitflags", +] + +[[package]] +name = "ref-cast" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +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", + "regex-syntax", +] + +[[package]] +name = "regex-syntax" +version = "0.8.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d902046e6a28a1e4c3cab97258a0ce11e994903f01c2d97a9447a0b3df85f4f6" + +[[package]] +name = "reqwest" +version = "0.12.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eddd3ca559203180a307f12d114c268abf583f59b03cb906fd0b3ff8646c1147" +dependencies = [ + "base64", + "bytes", + "futures-core", + "futures-util", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-rustls", + "hyper-util", + "js-sys", + "log", + "percent-encoding", + "pin-project-lite", + "quinn", + "rustls", + "rustls-pki-types", + "serde", + "serde_json", + "serde_urlencoded", + "sync_wrapper", + "tokio", + "tokio-rustls", + "tokio-util", + "tower", + "tower-http", + "tower-service", + "url", + "wasm-bindgen", + "wasm-bindgen-futures", + "wasm-streams", + "web-sys", + "webpki-roots", +] + +[[package]] +name = "ring" +version = "0.17.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7" +dependencies = [ + "cc", + "cfg-if", + "getrandom 0.2.17", + "libc", + "untrusted", + "windows-sys 0.52.0", +] + +[[package]] +name = "rmp" +version = "0.8.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ba8be72d372b2c9b35542551678538b562e7cf86c3315773cae48dfbfe7790c" +dependencies = [ + "num-traits", +] + +[[package]] +name = "rmp-serde" +version = "1.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72f81bee8c8ef9b577d1681a70ebbc962c232461e397b22c208c43c04b67a155" +dependencies = [ + "rmp", + "serde", +] + +[[package]] +name = "rmpv" +version = "1.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7a4e1d4b9b938a26d2996af33229f0ca0956c652c1375067f0b45291c1df8417" +dependencies = [ + "rmp", + "serde", + "serde_bytes", +] + +[[package]] +name = "rustc-hash" +version = "2.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d" + +[[package]] +name = "rustc_version" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92" +dependencies = [ + "semver", +] + +[[package]] +name = "rustix" +version = "1.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6fe4565b9518b83ef4f91bb47ce29620ca828bd32cb7e408f0062e9930ba190" +dependencies = [ + "bitflags", + "errno", + "libc", + "linux-raw-sys", + "windows-sys 0.61.2", +] + +[[package]] +name = "rustls" +version = "0.23.43" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0283386ce02abc0151e1761d08802dfe86c173b0b494af5cbc086574e453da06" +dependencies = [ + "once_cell", + "ring", + "rustls-pki-types", + "rustls-webpki", + "subtle", + "zeroize", +] + +[[package]] +name = "rustls-pki-types" +version = "1.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f4925028c7eb5d1fcdaf196971378ed9d2c1c4efc7dc5d011256f76c99c0a96" +dependencies = [ + "web-time", + "zeroize", +] + +[[package]] +name = "rustls-webpki" +version = "0.103.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0527518605e68109d875e248ea259b6758801cf165e4b2c2733ae3b51f12535a" +dependencies = [ + "ring", + "rustls-pki-types", + "untrusted", +] + +[[package]] +name = "rustversion" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" + +[[package]] +name = "ryu" +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" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" + +[[package]] +name = "semver" +version = "1.0.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_bytes" +version = "0.11.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a5d440709e79d88e51ac01c4b72fc6cb7314017bb7da9eeff678aa94c10e3ea8" +dependencies = [ + "serde", + "serde_core", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "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" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c841b55ecdae098c80dcae9cf767f6f8a0c2cdb3416bbef72181df4d0fe73f14" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "serde_path_to_error" +version = "0.1.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10a9ff822e371bb5403e391ecd83e182e0e77ba7f6fe0160b795797109d1b457" +dependencies = [ + "itoa", + "serde", + "serde_core", +] + +[[package]] +name = "serde_stacker" +version = "0.1.14" +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" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd" +dependencies = [ + "form_urlencoded", + "itoa", + "ryu", + "serde", +] + +[[package]] +name = "sha2" +version = "0.10.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" +dependencies = [ + "cfg-if", + "cpufeatures 0.2.17", + "digest", +] + +[[package]] +name = "sharded-slab" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f40ca3c46823713e0d4209592e8d6e826aa57e928f09752619fc696c499637f6" +dependencies = [ + "lazy_static", +] + +[[package]] +name = "shlex" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" + +[[package]] +name = "signal-hook-registry" +version = "1.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b" +dependencies = [ + "errno", + "libc", +] + +[[package]] +name = "signature" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77549399552de45a898a580c1b41d445bf730df867cc44e6c0233bbc4b8329de" +dependencies = [ + "rand_core 0.6.4", +] + +[[package]] +name = "simple_asn1" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d585997b0ac10be3c5ee635f1bab02d512760d14b7c468801ac8a01d9ae5f1d" +dependencies = [ + "num-bigint", + "num-traits", + "thiserror", + "time", +] + +[[package]] +name = "slab" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" + +[[package]] +name = "smallvec" +version = "1.15.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ed6a63f02c8539c91a8685a86f4099661ba3da017932f6ebbea6de3f0fa7c90" + +[[package]] +name = "socket2" +version = "0.5.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e22376abed350d73dd1cd119b57ffccad95b4e585a7cda43e286245ce23c0678" +dependencies = [ + "libc", + "windows-sys 0.52.0", +] + +[[package]] +name = "socket2" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "spki" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d91ed6c858b01f942cd56b37a94b3e0a1798290327d1236e4d9cf4eaca44d29d" +dependencies = [ + "base64ct", + "der", +] + +[[package]] +name = "stable_deref_trait" +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" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" + +[[package]] +name = "syn" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "3.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53e9bae58849f64dfa4f5d5ae372c8341f7305f82a3868709269343628b659a3" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "sync_wrapper" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263" +dependencies = [ + "futures-core", +] + +[[package]] +name = "synstructure" +version = "0.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "728a70f3dbaf5bab7f0c4b1ac8d7ae5ea60a4b5549c8a5914361c99147a709d2" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "tempfile" +version = "3.27.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" +dependencies = [ + "fastrand", + "getrandom 0.4.3", + "once_cell", + "rustix", + "windows-sys 0.61.2", +] + +[[package]] +name = "thiserror" +version = "2.0.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec86235f5fcc2a73650310756d2ac5b138a5780bbbdfae3eeccec992c435ba4f" +dependencies = [ + "thiserror-impl", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bc04cd3e1236dd4a98afca4569f2deb3f120e5422a4023be2cb683f8486292af" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.3", +] + +[[package]] +name = "thread_local" +version = "1.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ad99c4c6d32803332c548b1af0540b357b3f5fc0be8f6c6bfe8b2e6ae784070" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "time" +version = "0.3.55" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cdb87b95ec50ddfa440816d227a17b2ccbdda963a316a727fda0fc4334f7d134" +dependencies = [ + "deranged", + "num-conv", + "powerfmt", + "serde_core", + "time-core", + "time-macros", +] + +[[package]] +name = "time-core" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e1c906769ad99c88eaa54e728060edef082f8e358ff32030cb7c7d315e81109" + +[[package]] +name = "time-macros" +version = "0.2.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e689342a48d2ea927c87ea50cabf8594854bf940e9310208848d680d668ed85" +dependencies = [ + "num-conv", + "time-core", +] + +[[package]] +name = "tinystr" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1e27c91459209c2986af3dcf603a5a74a4368754ce37414f59acc971167f643" +dependencies = [ + "displaydoc", + "zerovec", +] + +[[package]] +name = "tinyvec" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb4ebadaa0af04fab11ae01eb5f9fdb5f9c5b875506e210e71c07873528baa7f" +dependencies = [ + "tinyvec_macros", +] + +[[package]] +name = "tinyvec_macros" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20" + +[[package]] +name = "tokio" +version = "1.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "202caea871b69668250d242070849eb495be178ed697a3e98aebce5bc81a0bed" +dependencies = [ + "bytes", + "libc", + "mio", + "parking_lot", + "pin-project-lite", + "signal-hook-registry", + "socket2 0.6.5", + "tokio-macros", + "windows-sys 0.61.2", +] + +[[package]] +name = "tokio-macros" +version = "2.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78773a2a397f451582ce068015985c33193cf6dea8b74d2a639fe457b2f07b0e" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.3", +] + +[[package]] +name = "tokio-rustls" +version = "0.26.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1729aa945f29d91ba541258c8df89027d5792d85a8841fb65e8bf0f4ede4ef61" +dependencies = [ + "rustls", + "tokio", +] + +[[package]] +name = "tokio-util" +version = "0.7.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "494815d09bf52b5548659851081238f0ca39ff638363907596da739561c62c52" +dependencies = [ + "bytes", + "futures-core", + "futures-sink", + "pin-project-lite", + "tokio", +] + +[[package]] +name = "tower" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebe5ef63511595f1344e2d5cfa636d973292adc0eec1f0ad45fae9f0851ab1d4" +dependencies = [ + "futures-core", + "futures-util", + "pin-project-lite", + "sync_wrapper", + "tokio", + "tower-layer", + "tower-service", + "tracing", +] + +[[package]] +name = "tower-http" +version = "0.6.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4cfcf7e2740e6fc6d4d688b4ef00650406bb94adf4731e43c096c3a19fe40840" +dependencies = [ + "bitflags", + "bytes", + "futures-util", + "http", + "http-body", + "pin-project-lite", + "tower", + "tower-layer", + "tower-service", + "url", +] + +[[package]] +name = "tower-layer" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "121c2a6cda46980bb0fcd1647ffaf6cd3fc79a013de288782836f6df9c48780e" + +[[package]] +name = "tower-service" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3" + +[[package]] +name = "tracing" +version = "0.1.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" +dependencies = [ + "log", + "pin-project-lite", + "tracing-attributes", + "tracing-core", +] + +[[package]] +name = "tracing-attributes" +version = "0.1.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "tracing-core" +version = "0.1.36" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" +dependencies = [ + "once_cell", + "valuable", +] + +[[package]] +name = "tracing-log" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee855f1f400bd0e5c02d150ae5de3840039a3f54b025156404e34c23c03f47c3" +dependencies = [ + "log", + "once_cell", + "tracing-core", +] + +[[package]] +name = "tracing-subscriber" +version = "0.3.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb7f578e5945fb242538965c2d0b04418d38ec25c79d160cd279bf0731c8d319" +dependencies = [ + "matchers", + "nu-ansi-term", + "once_cell", + "regex-automata", + "sharded-slab", + "smallvec", + "thread_local", + "tracing", + "tracing-core", + "tracing-log", +] + +[[package]] +name = "try-lock" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" + +[[package]] +name = "typenum" +version = "1.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" + +[[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" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6f5d3c3b1bf09027a88a6bc961fc00497d651009560b5463668dc81b0fa87a8" + +[[package]] +name = "universal-hash" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc1de2c688dc15305988b563c3854064043356019f97a4b46276fe734c4f07ea" +dependencies = [ + "crypto-common", + "subtle", +] + +[[package]] +name = "untrusted" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" + +[[package]] +name = "url" +version = "2.5.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed" +dependencies = [ + "form_urlencoded", + "idna", + "percent-encoding", + "serde", +] + +[[package]] +name = "utf8_iter" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be" + +[[package]] +name = "uuid" +version = "1.24.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2cefc03fd367c0c6d4305de1b312cf00248c4114f4a0418ce6a6af769e3b0bd9" +dependencies = [ + "getrandom 0.4.3", + "js-sys", + "serde_core", + "wasm-bindgen", +] + +[[package]] +name = "valuable" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba73ea9cf16a25df0c8caa16c51acb937d5712a8429db78a3ee29d5dcacd3a65" + +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + +[[package]] +name = "want" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bfa7760aed19e106de2c7c0b581b509f2f25d3dacaf737cb82ac61bc6d760b0e" +dependencies = [ + "try-lock", +] + +[[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + +[[package]] +name = "wasip2" +version = "1.0.4+wasi-0.2.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b67efb37e106e55ce722a510d6b5f9c17f083e5fc79afc2badeb12cc313d9487" +dependencies = [ + "wit-bindgen", +] + +[[package]] +name = "wasm-bindgen" +version = "0.2.127" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1b70935747edd64d89de3efa29d73789b806c15798f8e7dca4d8ac356b50ce70" +dependencies = [ + "cfg-if", + "once_cell", + "rustversion", + "wasm-bindgen-macro", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-futures" +version = "0.4.77" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6b7777d5cc23d0e91404e53ce2d5e8ec7acae3026b16233dba62cd3246457950" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.127" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77775f8f3f7217702089053b94958f8f54061a3f663417df76e19cbdcca29bc1" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.127" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e11d33f857dc2fb11b8bc75aee111aa9cbeb12cd9f25efd3d4c2a3dd4e235284" +dependencies = [ + "bumpalo", + "proc-macro2", + "quote", + "syn 2.0.119", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.127" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7ef64dbcc55df09c7e5a46182d181c2cfa3e925f3da937ea764728b4bbb9dcbf" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "wasm-streams" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "15053d8d85c7eccdbefef60f06769760a563c7f0a9d6902a13d35c7800b0ad65" +dependencies = [ + "futures-util", + "js-sys", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", +] + +[[package]] +name = "web-sys" +version = "0.3.104" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c435338968042f4f59a557f690a253676d47ce13ceb55d70100e7facf6620a30" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "web-time" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a6580f308b1fad9207618087a65c04e7a10bc77e02c8e84e9b00dd4b12fa0bb" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "webpki-roots" +version = "1.0.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7dcd9d09a39985f5344844e66b0c530a33843579125f23e21e9f0f220850f22a" +dependencies = [ + "rustls-pki-types", +] + +[[package]] +name = "winapi" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" +dependencies = [ + "winapi-i686-pc-windows-gnu", + "winapi-x86_64-pc-windows-gnu", +] + +[[package]] +name = "winapi-i686-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" + +[[package]] +name = "winapi-x86_64-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" + +[[package]] +name = "windows-core" +version = "0.62.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb" +dependencies = [ + "windows-implement", + "windows-interface", + "windows-link", + "windows-result", + "windows-strings", +] + +[[package]] +name = "windows-implement" +version = "0.60.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "windows-interface" +version = "0.59.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-result" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-strings" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-sys" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" +dependencies = [ + "windows-targets", +] + +[[package]] +name = "windows-sys" +version = "0.59.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b" +dependencies = [ + "windows-targets", +] + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-targets" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" +dependencies = [ + "windows_aarch64_gnullvm", + "windows_aarch64_msvc", + "windows_i686_gnu", + "windows_i686_gnullvm", + "windows_i686_msvc", + "windows_x86_64_gnu", + "windows_x86_64_gnullvm", + "windows_x86_64_msvc", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" + +[[package]] +name = "windows_i686_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" + +[[package]] +name = "windows_i686_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" + +[[package]] +name = "wit-bindgen" +version = "0.57.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e" + +[[package]] +name = "writeable" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc" + +[[package]] +name = "yoke" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "709fe23a0424b6a435d82152b1bd3fdfb0833487d5fa90d05d42762a9891fef5" +dependencies = [ + "stable_deref_trait", + "yoke-derive", + "zerofrom", +] + +[[package]] +name = "yoke-derive" +version = "0.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "de844c262c8848816172cef550288e7dc6c7b7814b4ee56b3e1553f275f1858e" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", + "synstructure", +] + +[[package]] +name = "zerocopy" +version = "0.8.66" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cba8a86aee14fc8cc6c208af60854b3d4ab7185a9a369a12c648faa2716ff42a" +dependencies = [ + "zerocopy-derive", +] + +[[package]] +name = "zerocopy-derive" +version = "0.8.66" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f89bca3b96ceb3cfcb4572790402f977442270d252b9a8504ebc258760c55f94" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "zerofrom" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272" +dependencies = [ + "zerofrom-derive", +] + +[[package]] +name = "zerofrom-derive" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "11532158c46691caf0f2593ea8358fed6bbf68a0315e80aae9bd41fbade684a1" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", + "synstructure", +] + +[[package]] +name = "zeroize" +version = "1.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e13c156562582aa81c60cb29407084cdb54c4164760106ab78e6c5b0858cf64e" + +[[package]] +name = "zerotrie" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ea269c3bd32f0a32c321907a2ae912ba6f4649bb0fc764a15627e99a7095a3f" +dependencies = [ + "displaydoc", + "yoke", + "zerofrom", +] + +[[package]] +name = "zerovec" +version = "0.11.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94b5c6b5976d66c1d703c4fd17d3f5e43c8cedaacf604961b171adc7130896d8" +dependencies = [ + "yoke", + "zerofrom", + "zerovec-derive", +] + +[[package]] +name = "zerovec-derive" +version = "0.11.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47402523226a02bfe5230160dc3ccc089aa6f6f19e7fcbb4e6f824bbb1b4aa62" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.3", +] + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..0f5ed13 --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,41 @@ +[workspace] +members = [ + "crates/ghostlight", + "crates/ghostlight-dungeon", + "crates/ghostlight-persona-projection", + "crates/ghostlight-verse", +] +resolver = "2" + +[workspace.package] +edition = "2024" +license = "MIT" +version = "0.1.0" + +[workspace.dependencies] +anyhow = "1" +aes-gcm = "0.10" +async-trait = "0.1" +async-stream = "0.3" +axum = { version = "0.8", features = ["macros"] } +chrono = { version = "0.4", features = ["serde"] } +base64 = "0.22" +model-connector = { git = "https://eureka.gamecult.org/forge/GameCult/ModelConnector.git", rev = "edf2f8e03cbb61df385b9b145b46f676ce3b70d5" } +cultcache-rs = { git = "https://github.com/GameCult/CultLib.git", rev = "85f7024a35ea42cf9f0a0199a064526427150191", package = "cultcache-rs" } +cultnet-rs = { git = "https://github.com/GameCult/CultLib.git", rev = "85f7024a35ea42cf9f0a0199a064526427150191", package = "cultnet-rs" } +cultmesh-rs = { git = "https://github.com/GameCult/CultLib.git", rev = "85f7024a35ea42cf9f0a0199a064526427150191", package = "cultmesh-rs" } +jsonwebtoken = "9" +hmac = "0.12" +rand = "0.9" +reqwest = { version = "0.12", default-features = false, features = ["json", "rustls-tls", "stream"] } +rmp-serde = "1.3" +serde = { version = "1", features = ["derive"] } +serde_json = "1" +sha2 = "0.10" +thiserror = "2" +tokio = { version = "1", features = ["full"] } +tracing = "0.1" +tracing-subscriber = { version = "0.3", features = ["env-filter"] } +unicode-segmentation = "1" +uuid = { version = "1", features = ["v4", "serde"] } +zeroize = "1.8" diff --git a/README.md b/README.md index 4d891f8..ff4a893 100644 --- a/README.md +++ b/README.md @@ -1,151 +1,121 @@ # Ghostlight -Ghostlight is a research and implementation home for socially persistent -generative agents. +**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). -The project is about characters and simulated people who remain coherent across -time, routine, pressure, memory, culture, misreading, masks, incentives, and -changing relationships. The aim is not to make a language model sound charming -for one scene. The aim is to build machinery that can track who someone is, -what they believe, what they hide, how they see other people, how they live when -nothing is exploding, and how their behavior changes when the world leans on -them. +**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. -In practical terms, Ghostlight is building the state and projection layer for -character-driven generation: +**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. -- durable canonical character state -- observer-specific perceived state -- directional relationship stance -- cultural and institutional pressure -- memory and goal selection -- speaker-local prompt projection -- evaluation targets for emergent verbal behavior -- a future path for training smaller specialist projection models +- `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 first concrete consumer is Aetheria authoring support, especially Call of -the Void content generation, dialogue scaffolding, and procedural drama for -narrated stories in the Aetheria timeline. +Start with those two documents, then `cargo doc -p ghostlight --open`. -## Core Idea +**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. -Ghostlight separates three things that are easy to blur together: +## Elaborators -1. **Canonical state** - What is true about a character, relationship, event, memory, or scene. +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. -2. **Perceived state** - What a particular observer thinks is true, including misreadings, - attribution bias, suspicion, trust, projection, and partial knowledge. +## Direction (planned, not built) -3. **Prompt projection** - A temporary speaker-local prompt surface for one scene or turn. +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 prompt is not the character. The prompt is a rendered slice of state. +## Ghostlight Dungeon (parked) -That distinction matters because believable dialogue should come from character -circumstance, not vibes. Sometimes that circumstance is acute pressure. Often it -is habit, boredom, affection, work rhythm, class embarrassment, ritual memory, -professional competence, petty irritation, or ordinary warmth trying to survive -inside a bleak system. Cat being sarcastic should fall out of shame sensitivity, -distance seeking, suspicion, relationship tension, scene stakes, and voice. -Oz withholding information should fall out of mask rigidity, privacy pressure, -relationship fear, and the need to stay useful. A quiet joke, a domestic aside, -or a moment of tenderness should be just as explainable in state terms as a -threat. The system should be able to show its work without making every scene -sound like Greg Egan having a panic attack in a server closet. +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. -## Current Status +## Repo map -Ghostlight is early architecture plus executable schema seams. +| 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. | -Currently present: +`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. -- v0 canonical agent-state schema -- required variable lists for state families and relationship stance -- Call of the Void-flavored Cat/Oz fixture -- dependency-free fixture validator -- prompt projection contract -- projection distillation plan for teacher/student projector training -- persistence surfaces for re-entry, evidence, planning, and compaction hygiene +## Build and test -Not present yet: +Nothing deploys from this repo. Linux verification runs on Yggdrasil, not on a +workstation: -- runtime prompt renderer -- projection training dataset -- student projection model -- event/classifier pipeline -- simulation loop -- relationship update engine -- culture prior engine - -## How Projection Is Supposed To Work - -For one speaker in one scene, Ghostlight should gather speaker-local state: - -- what the speaker knows -- what they believe -- what they want -- what they are protecting -- what memories are active -- how they read the listener -- what the relationship currently feels like -- what circumstance the scene creates: routine, desire, scarcity, humor, - tenderness, danger, institutional friction, or open crisis -- what voice surface is active - -The projection layer turns that into compact character-local prose and prompt -sections. The dialogue model then writes from the active circumstance and tonal -mode, not from a universal crisis register. - -Longer term, a frontier model can act as a teacher projector that generates -reviewed projection artifacts. Those artifacts can train a smaller student -projector once the projection schema, deterministic input slicer, and evaluator -are stable. - -## Repo Tour - -- `AGENTS.md`: operating discipline for humans and agents -- `state/map.yaml`: canonical project map and current next action -- `state/scratch.md`: disposable working memory for one bounded subgoal -- `state/evidence.jsonl`: distilled belief-changing evidence -- `notes/fresh-workspace-handoff.md`: compact re-entry packet -- `notes/ghostlight-current-system-map.md`: current repo machinery -- `notes/ghostlight-implementation-plan.md`: larger implementation sequence -- `notes/architecture-rationale.md`: why the persistence and state split exists -- `docs/research/`: research backlog and modeling notes -- `docs/aetheria/`: Aetheria source material used by Ghostlight -- `docs/architecture/`: state, projection, and authoring architecture -- `docs/architecture/verse-service-contract.md`: GameCult Verse service contract - for Ghostlight's missing Eve GUI/TUI state and authoring surface -- `schemas/`: JSON schema contracts and required field lists -- `examples/`: schema fixtures and future projection examples -- `tools/ghostlight_state.py`: state inspection and evidence helper -- `tools/ghostlight_prepare_compaction.py`: pre-compaction audit helper -- `tools/validate_agent_state.py`: focused fixture validator - -## Useful Commands - -```powershell -npm run state:status -npm run state:prepare-compaction -npm run schema:validate +```sh +cargo build --locked --workspace +cargo test --locked -p ghostlight-persona-projection +cargo test --locked -p ghostlight +cargo test --locked -p ghostlight-verse ``` -To add distilled evidence: +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. -```powershell -& 'C:\Users\Meta\.cache\codex-runtimes\codex-primary-runtime\dependencies\python\python.exe' '.\tools\ghostlight_state.py' add-evidence --type design --status accepted --note '...' -``` +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. -## Best Starting Points - -- `docs/architecture/canonical-agent-state-schema.md` -- `docs/architecture/cultnet-shared-agent-state-contract.md` -- `docs/architecture/agent-state-variable-glossary.md` -- `docs/architecture/prompt-projection-contract.md` -- `docs/architecture/projection-distillation-plan.md` -- `examples/agent-state.call-of-the-void.json` - -For Codex-driven work, read `AGENTS.md` before changing the repo. It contains -the working rules that keep the project state coherent between sessions. +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 new file mode 100644 index 0000000..39babbb --- /dev/null +++ b/crates/ghostlight-dungeon/Cargo.toml @@ -0,0 +1,46 @@ +[package] +name = "ghostlight-dungeon" +version.workspace = true +edition.workspace = true +license.workspace = true +autobins = false + +[[bin]] +name = "ghostlight-dungeon" +path = "src/main.rs" + +[dependencies] +anyhow.workspace = true +aes-gcm.workspace = true +async-trait.workspace = true +async-stream.workspace = true +axum.workspace = true +chrono.workspace = true +base64.workspace = true +cultcache-rs.workspace = true +model-connector.workspace = true +cultnet-rs.workspace = true +cultmesh-rs.workspace = true +jsonwebtoken.workspace = true +libc = "0.2" +hmac.workspace = true +ghostlight = { path = "../ghostlight" } +ghostlight-persona-projection = { path = "../ghostlight-persona-projection" } +rand.workspace = true +reqwest.workspace = true +rmp-serde.workspace = true +serde.workspace = true +serde_json.workspace = true +sha2.workspace = true +thiserror.workspace = true +tokio.workspace = true +tracing.workspace = true +tracing-subscriber.workspace = true +uuid.workspace = true +zeroize.workspace = true + +[dev-dependencies] +ghostlight = { path = "../ghostlight", features = ["test-support"] } +tempfile = "3" +tokio = { workspace = true, features = ["test-util"] } +tower = { version = "0.5", features = ["util"] } diff --git a/crates/ghostlight-dungeon/build.rs b/crates/ghostlight-dungeon/build.rs new file mode 100644 index 0000000..9eaf054 --- /dev/null +++ b/crates/ghostlight-dungeon/build.rs @@ -0,0 +1,65 @@ +use std::{env, path::Path, process::Command}; + +fn main() { + println!("cargo:rerun-if-env-changed=GHOSTLIGHT_BUILD_COMMIT"); + let manifest_dir = + env::var("CARGO_MANIFEST_DIR").expect("Cargo must supply CARGO_MANIFEST_DIR"); + let repo_root = Path::new(&manifest_dir).join("../.."); + emit_git_rerun_paths(&repo_root); + // Release tooling injects the clean-tree commit. Git discovery is only a + // convenience for local builds. The exact ref and reflog dependencies above + // keep that convenience from silently publishing stale provenance. + let commit = env::var("GHOSTLIGHT_BUILD_COMMIT") + .ok() + .filter(|value| is_commit(value)) + .or_else(|| git_commit(&repo_root)) + .expect("GhostlightDungeon builds require an exact 40-hex source commit"); + println!("cargo:rustc-env=GHOSTLIGHT_BUILD_COMMIT={commit}"); +} + +fn emit_git_rerun_paths(repo_root: &Path) { + for git_path in ["HEAD", "logs/HEAD", "packed-refs"] { + if let Some(path) = git_output(repo_root, &["rev-parse", "--git-path", git_path]) { + emit_rerun_path(repo_root, &path); + } + } + + if let Some(reference) = git_output(repo_root, &["symbolic-ref", "-q", "HEAD"]) + && let Some(path) = git_output(repo_root, &["rev-parse", "--git-path", &reference]) + { + emit_rerun_path(repo_root, &path); + } +} + +fn emit_rerun_path(repo_root: &Path, git_path: &str) { + let path = Path::new(git_path); + let resolved = if path.is_absolute() { + path.to_path_buf() + } else { + repo_root.join(path) + }; + println!("cargo:rerun-if-changed={}", resolved.display()); +} + +fn git_commit(repo_root: &Path) -> Option { + git_output(repo_root, &["rev-parse", "HEAD"]).filter(|value| is_commit(value)) +} + +fn git_output(repo_root: &Path, args: &[&str]) -> Option { + let output = Command::new("git") + .args(args) + .current_dir(repo_root) + .output() + .ok()?; + if !output.status.success() { + return None; + } + String::from_utf8(output.stdout) + .ok() + .map(|value| value.trim().to_owned()) + .filter(|value| !value.is_empty()) +} + +fn is_commit(value: &str) -> bool { + value.len() == 40 && value.bytes().all(|byte| byte.is_ascii_hexdigit()) +} diff --git a/crates/ghostlight-dungeon/page/index.html b/crates/ghostlight-dungeon/page/index.html new file mode 100644 index 0000000..4284902 --- /dev/null +++ b/crates/ghostlight-dungeon/page/index.html @@ -0,0 +1,25 @@ + + + + + + + +Ghostlight Dungeon + + + +
+ +
+ + + + +
+
+

Loading…

+ + + + diff --git a/crates/ghostlight-dungeon/page/page.css b/crates/ghostlight-dungeon/page/page.css new file mode 100644 index 0000000..3e098d5 --- /dev/null +++ b/crates/ghostlight-dungeon/page/page.css @@ -0,0 +1,73 @@ +/* Presentation only. Text size and theme are the two variables below. */ +:root { + --fs: 1.125rem; + --bg: #07111a; --panel: #16212c; --line: #263646; --muted: #8fa1b5; + --text: #eef5ff; --accent: #ff8a2a; --link: #59b7ff; + --bad: #ff6b5e; --badbg: #2a1614; --ok: #6fd08c; --focus: #59b7ff; + --head: Montserrat, "Segoe UI", system-ui, sans-serif; + --body: Georgia, "Iowan Old Style", "Palatino Linotype", serif; +} +:root[data-theme="light"] { + --bg: #f7f4ee; --panel: #ffffff; --line: #d8d2c4; --muted: #5d6a78; + --text: #17202a; --accent: #b4510a; --link: #0b5fa8; + --bad: #a3231a; --badbg: #fdeceb; --ok: #1d7a3c; --focus: #0b5fa8; +} +* { box-sizing: border-box; } +html { -webkit-text-size-adjust: 100%; } +body { margin: 0; background: var(--bg); color: var(--text); font: var(--fs)/1.65 var(--body); overflow-wrap: anywhere; } +.bar { position: sticky; top: 0; z-index: 5; display: flex; justify-content: space-between; align-items: center; gap: .5rem; + padding: .4rem max(.75rem, env(safe-area-inset-left)); background: var(--bg); border-bottom: 1px solid var(--line); } +.brand { white-space: nowrap; background: none; border: 0; color: var(--accent); font: 600 1.05rem var(--head); letter-spacing: .06em; text-transform: uppercase; min-height: 44px; padding: 0 .25rem; cursor: pointer; } +.tools { display: flex; gap: .2rem; justify-content: flex-end; } +.tool { background: none; border: 1px solid var(--line); color: var(--muted); font: 500 .8rem var(--head); border-radius: .5rem; min-height: 44px; min-width: 44px; padding: 0 .5rem; cursor: pointer; } +main { max-width: 44rem; margin: 0 auto; padding: .75rem max(.75rem, env(safe-area-inset-left)) 10rem; } +h1, h2 { font-family: var(--head); font-weight: 300; line-height: 1.2; margin: .5rem 0 .75rem; } +h1 { font-size: 1.6rem; } h2 { font-size: 1.25rem; } +.note, .small { color: var(--muted); font-size: .9rem; line-height: 1.5; } +a { color: var(--link); } +button, input, textarea { font: inherit; color: inherit; } +:focus-visible { outline: 3px solid var(--focus); outline-offset: 2px; } +.card { background: var(--panel); border: 1px solid var(--line); border-radius: .75rem; padding: .9rem 1rem; margin: .75rem 0; } +.row { display: flex; gap: .6rem; flex-wrap: wrap; align-items: center; } +.btn { background: var(--accent); color: #07111a; border: 0; border-radius: .6rem; min-height: 48px; padding: 0 1.1rem; font: 600 1rem var(--head); cursor: pointer; } +.btn.alt { background: none; color: var(--text); border: 1px solid var(--line); } +.btn[disabled] { opacity: .5; cursor: default; } +.btn.wide { width: 100%; } +label { display: block; font: 600 .85rem var(--head); letter-spacing: .04em; margin: 1rem 0 .3rem; color: var(--muted); text-transform: uppercase; } +input[type=text], textarea { width: 100%; background: var(--bg); border: 1px solid var(--line); border-radius: .6rem; padding: .7rem .8rem; min-height: 48px; } +textarea { resize: vertical; line-height: 1.5; } +.choice { display: flex; gap: .7rem; align-items: center; min-height: 48px; padding: .4rem .6rem; border: 1px solid var(--line); border-radius: .6rem; margin: .4rem 0; cursor: pointer; background: var(--bg); } +.choice input { width: 1.4rem; height: 1.4rem; accent-color: var(--accent); flex: none; } +.chip { font: 600 .72rem var(--head); text-transform: uppercase; letter-spacing: .06em; padding: .15rem .5rem; border-radius: 1rem; border: 1px solid var(--line); color: var(--muted); } +.chip.ready { color: var(--ok); border-color: var(--ok); } .chip.seeding { color: var(--accent); border-color: var(--accent); } .chip.failed { color: var(--bad); border-color: var(--bad); } +.tl { display: block; width: 100%; text-align: left; background: var(--panel); border: 1px solid var(--line); border-radius: .75rem; padding: .8rem 1rem; margin: .5rem 0; min-height: 56px; cursor: pointer; } +.tl.current { border-color: var(--accent); } +.tl .t { font: 600 1.05rem var(--head); display: block; } +.line { border-left: 4px solid var(--bad); background: var(--badbg); border-radius: .4rem; padding: .6rem .8rem; margin: .75rem 0; } +.line.info { border-color: var(--accent); background: var(--panel); } +.turn { margin: 1.4rem 0; } +.you { color: var(--muted); font-style: italic; border-left: 3px solid var(--line); padding-left: .8rem; margin: .8rem 0; white-space: pre-wrap; } +.story { white-space: pre-wrap; margin: 0; } +.ask { border: 1px solid var(--accent); border-radius: .6rem; padding: .6rem .8rem; margin: .8rem 0; } +.status { color: var(--muted); font: 500 .85rem var(--head); } +.pulse::after { content: ""; display: inline-block; width: .5rem; height: .5rem; margin-left: .5rem; border-radius: 50%; background: var(--accent); animation: p 1.2s ease-in-out infinite; } +@keyframes p { 50% { opacity: .2; } } +@media (prefers-reduced-motion: reduce) { .pulse::after { animation: none; } } +.bar2 { height: .4rem; background: var(--line); border-radius: .3rem; overflow: hidden; margin: .6rem 0; } +.bar2 i { display: block; height: 100%; width: 40%; background: var(--accent); animation: s 1.6s ease-in-out infinite alternate; } +@keyframes s { to { margin-left: 60%; } } +@media (prefers-reduced-motion: reduce) { .bar2 i { animation: none; width: 100%; } } +.compose { position: fixed; left: 0; right: 0; bottom: 0; background: var(--bg); border-top: 1px solid var(--line); padding: .5rem max(.75rem, env(safe-area-inset-left)) max(.5rem, env(safe-area-inset-bottom)); } +.compose .in { max-width: 44rem; margin: 0 auto; } +.compose textarea { min-height: 2.8rem; max-height: 30vh; } +.compose .row { margin-top: .4rem; } +.compose .btn { flex: 1 1 8rem; } +@media (min-width: 700px) { :root { --fs: 1.2rem; } main { padding-top: 1.25rem; } } +.blk { display: block; } .bad { color: var(--bad); } .gap { margin-top: .6rem; margin-bottom: .2rem; } +label.choice { text-transform: none; letter-spacing: 0; font: inherit; color: var(--text); margin: .4rem 0; } +.older { text-align: center; } +.older .btn { margin: .4rem 0; } +.lens { display: flex; gap: .5rem; align-items: center; padding: .35rem 0; border-bottom: 1px solid var(--line); } +.lens .what { flex: 1 1 auto; min-width: 0; } +.lens .n { min-width: 1.5rem; text-align: center; font: 600 1.05rem var(--head); } +.step { background: none; border: 1px solid var(--line); color: var(--text); border-radius: .5rem; min-width: 44px; min-height: 44px; font: 600 1.2rem var(--head); cursor: pointer; flex: none; } diff --git a/crates/ghostlight-dungeon/page/page.js b/crates/ghostlight-dungeon/page/page.js new file mode 100644 index 0000000..964b08f --- /dev/null +++ b/crates/ghostlight-dungeon/page/page.js @@ -0,0 +1,410 @@ +// Presentation only. The daemon owns every command and every fact; this page +// shows what the API returns and sends what the player types. The only state it +// keeps on the device is the unsent draft, the text size and the theme. The +// scrollback is the server's turn log, loaded on open and paged on scroll-up, +// so a reload or another device shows the same story. +"use strict"; + +const $view = document.getElementById("view"); +const LS = { + get(k) { try { return localStorage.getItem(k); } catch { return null; } }, + set(k, v) { try { if (v === null || v === "") localStorage.removeItem(k); else localStorage.setItem(k, v); } catch { /* storage may be blocked */ } }, +}; +const uuid = () => (crypto.randomUUID ? crypto.randomUUID() + : "10000000-1000-4000-8000-100000000000".replace(/[018]/g, (c) => (c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4).toString(16))); + +function el(tag, attrs, ...kids) { + const node = document.createElement(tag); + for (const [k, v] of Object.entries(attrs || {})) { + if (k === "class") node.className = v; + else if (k.startsWith("on")) node.addEventListener(k.slice(2), v); + else if (v === true) node.setAttribute(k, ""); + else if (v !== false && v != null) node.setAttribute(k, v); + } + for (const kid of kids.flat()) if (kid != null) node.append(kid); + return node; +} + +async function api(path, options) { + let response; + try { + response = await fetch("api/" + path, { credentials: "same-origin", ...options, + headers: options && options.body ? { "content-type": "application/json" } : undefined }); + } catch { + return { status: 0, body: { error: "The server could not be reached." } }; + } + let body = null; + try { body = await response.json(); } catch { body = null; } + return { status: response.status, body: body || {} }; +} +const post = (path, body) => api(path, { method: "POST", body: JSON.stringify(body) }); + +// ---- text size and theme ------------------------------------------------- +const root = document.documentElement; +function applySize(rem) { root.style.setProperty("--fs", rem + "rem"); LS.set("fs", String(rem)); } +const savedSize = parseFloat(LS.get("fs")); +if (savedSize >= 0.9 && savedSize <= 1.9) root.style.setProperty("--fs", savedSize + "rem"); +function currentSize() { return parseFloat(getComputedStyle(root).getPropertyValue("--fs")) || 1.125; } +document.getElementById("smaller").onclick = () => applySize(Math.max(0.9, +(currentSize() - 0.1).toFixed(2))); +document.getElementById("larger").onclick = () => applySize(Math.min(1.9, +(currentSize() + 0.1).toFixed(2))); +function applyTheme(name) { + if (name === "light" || name === "dark") root.dataset.theme = name; else delete root.dataset.theme; +} +applyTheme(LS.get("theme")); +document.getElementById("theme").onclick = () => { + const next = root.dataset.theme === "light" ? "dark" : "light"; + applyTheme(next); LS.set("theme", next); +}; + +// ---- state --------------------------------------------------------------- +const S = { me: null, timeline: null, history: [], older: null, live: null, echo: null, keyed: null, tailTried: null, stream: null, poll: null, signIn: null }; + +function stopLive() { + if (S.stream) { S.stream.close(); S.stream = null; } + if (S.poll) { clearTimeout(S.poll); S.poll = null; } +} +function show(...nodes) { document.querySelector(".compose")?.remove(); $view.replaceChildren(...nodes.flat()); window.scrollTo(0, 0); } +function inviteFromHash() { + const m = /(?:^#|&)invite=([A-Za-z0-9_\-]{8,200})/.exec(location.hash); + return m ? m[1] : ""; +} + +async function boot() { + stopLive(); + const { status, body } = await api("me"); + if (status !== 200) return show(el("h1", {}, "Ghostlight"), errorLine(body.error || "The server answered with an error (" + status + ")."), retryButton(boot)); + S.me = body; + document.getElementById("signout").hidden = !body.signedIn; + if (!body.signedIn) return signInView(); + if (body.currentTimeline) return openTimeline(body.currentTimeline); + return listView(); +} +function errorLine(text) { return el("p", { class: "line", role: "alert" }, text); } +function retryButton(fn) { return el("button", { class: "btn", type: "button", onclick: fn }, "Try again"); } + +// ---- sign in ------------------------------------------------------------- +function signInView(message) { + stopLive(); + const providers = (S.me && S.me.providers) || []; + const invite = el("input", { type: "text", id: "invite", autocomplete: "off", autocapitalize: "off", spellcheck: "false", value: inviteFromHash() }); + const out = el("div", {}); + if (message) out.append(errorLine(message)); + const buttons = providers.map((name) => el("button", { class: "btn wide gap", type: "button", onclick: () => beginSignIn(name, invite.value.trim(), out) }, + "Sign in with " + name[0].toUpperCase() + name.slice(1))); + show(el("h1", {}, "Sign in"), + el("p", { class: "note" }, "Only people on the allowlist can play. A first sign-in needs the invite you were given; after that, signing in is enough."), + el("div", { class: "card" }, + el("label", { for: "invite" }, "Invite (first time only)"), invite, + el("p", { class: "small" }, "A link that ends in #invite=… fills this in."), + providers.length ? buttons : el("p", { class: "line" }, "This server offers no sign-in provider.")), + out); + if (S.signIn && S.signIn.until > Date.now()) resumeSignIn(out, invite); +} + +async function beginSignIn(provider, invite, out) { + out.replaceChildren(el("p", { class: "note pulse" }, "Asking " + provider + " for a sign-in")); + const { status, body } = await post("auth/begin", invite ? { key: uuid(), provider, invite } : { key: uuid(), provider }); + if (status !== 200) return out.replaceChildren(errorLine(body.error || "Sign-in could not begin (" + status + ").")); + let target = null; + try { + const url = new URL(body.url, location.href); + if ((body.allowedOrigins || []).includes(url.origin) && url.protocol === "https:") target = url.href; + } catch { target = null; } + if (!target) return out.replaceChildren(errorLine("The sign-in address was not one this page will open.")); + S.signIn = { handle: body.handle, target, until: Date.now() + 9 * 60 * 1000 }; + window.open(target, "_blank", "noopener"); + resumeSignIn(out); +} + +async function resumeSignIn(out) { + const attempt = S.signIn; + out.replaceChildren( + el("p", { class: "note pulse" }, "Waiting for you to finish signing in on the other tab."), + el("p", {}, el("a", { href: attempt.target, target: "_blank", rel: "noopener noreferrer" }, "Open the sign-in page again"))); + while (S.signIn === attempt && Date.now() < attempt.until) { + await new Promise((r) => setTimeout(r, 2500)); + if (S.signIn !== attempt) return; + const { status, body } = await post("auth/complete", { handle: attempt.handle, key: uuid() }); + if (status === 202) continue; + S.signIn = null; + if (status === 200 && body.status === "authenticated") { history.replaceState(null, "", location.pathname); return boot(); } + if (status === 429) return out.replaceChildren(errorLine(body.error || "Too many attempts; wait a minute.")); + return out.replaceChildren(errorLine(body.error || "Sign-in was refused (" + status + ").")); + } + if (S.signIn === attempt) { S.signIn = null; out.replaceChildren(errorLine("The sign-in expired. Start again.")); } +} + +document.getElementById("signout").onclick = async () => { + stopLive(); + const { status, body } = await post("auth/logout", {}); + if (status !== 200) return show(errorLine(body.error || "Sign-out was not confirmed."), retryButton(boot)); + S.history = []; S.timeline = null; + boot(); +}; +document.getElementById("home").onclick = () => { if (S.me && S.me.signedIn) listView(); }; + +// ---- timelines ----------------------------------------------------------- +async function listView() { + stopLive(); + S.timeline = null; + const { status, body } = await api("timelines"); + if (status === 401) return boot(); + if (status !== 200) return show(el("h1", {}, "Your worlds"), errorLine(body.error || "Could not list your worlds."), retryButton(listView)); + const rows = body.timelines || []; + const seeding = rows.some((r) => r.status === "seeding"); + show(el("h1", {}, "Your worlds"), + el("button", { class: "btn wide", type: "button", onclick: beginView }, "Begin a new world"), + rows.length ? rows.map(timelineRow) : el("p", { class: "note" }, "No worlds yet."), + el("p", { class: "small" }, "Each fork of a world is its own timeline. Older timelines stay.")); + if (seeding) S.poll = setTimeout(listView, 4000); +} +function timelineRow(row) { + const when = row.createdAt ? new Date(row.createdAt).toLocaleString() : ""; + return el("button", { class: "tl" + (row.current ? " current" : ""), type: "button", onclick: () => openTimeline(row.timeline) }, + el("span", { class: "t" }, row.title || "Untitled"), + el("span", { class: "chip " + row.status }, row.status), " ", + row.parent ? el("span", { class: "small" }, " fork") : "", + el("span", { class: "small blk" }, (row.current ? "Current. " : "") + when), + row.status === "failed" ? el("span", { class: "small blk bad" }, row.reason || "Seeding failed.") : ""); +} + +// ---- begin --------------------------------------------------------------- +let beginKey = null; +async function beginView() { + stopLive(); + beginKey = beginKey || uuid(); + const { status, body } = await api("vaults"); + if (status === 401) return boot(); + const vaults = status === 200 ? body.vaults || [] : []; + const msg = el("div", {}); + if (status !== 200) msg.append(errorLine(body.error || "The lore list could not be read.")); + const lenses = status === 200 ? body.lenses || [] : []; + let vault = vaults.length ? vaults[0].name : ""; + let era = null; + // The era picker follows the vault choice; a vault with one era offers none. + const eraBox = el("div", {}); + const drawEras = () => { + const chosen = vaults.find((v) => v.name === vault); + era = chosen ? chosen.default_era : null; + eraBox.replaceChildren(...(chosen && chosen.eras.length > 1 ? [el("label", {}, "Era"), + ...chosen.eras.map((e) => el("label", { class: "choice" }, + el("input", { type: "radio", name: "era", value: e.id, checked: e.id === era, onchange: () => { era = e.id; } }), + el("span", {}, e.label, el("span", { class: "small blk" }, e.description))))] : [])); + }; + const choices = vaults.map((v, i) => el("label", { class: "choice" }, + el("input", { type: "radio", name: "vault", value: v.name, checked: i === 0, onchange: () => { vault = v.name; drawEras(); } }), v.name)); + drawEras(); + // Each lens weighs what the world reaches for: 0 never, 5 most. + const weights = Object.fromEntries(lenses.map((l) => [l.id, 1])); + const lensRows = lenses.map((l) => { + const shown = el("span", { class: "n", "aria-live": "polite" }, "1"); + const step = (by) => { weights[l.id] = Math.max(0, Math.min(5, weights[l.id] + by)); shown.textContent = String(weights[l.id]); }; + return el("div", { class: "lens" }, + el("span", { class: "what" }, el("b", {}, l.name), el("span", { class: "small blk" }, l.reaches_for)), + el("button", { class: "step", type: "button", "aria-label": "Less " + l.name, onclick: () => step(-1) }, "−"), shown, + el("button", { class: "step", type: "button", "aria-label": "More " + l.name, onclick: () => step(1) }, "+")); + }); + const title = el("input", { type: "text", id: "title", autocomplete: "off", value: LS.get("begin-title") || "" }); + const name = el("input", { type: "text", id: "name", autocomplete: "off", value: LS.get("begin-name") || "" }); + const brief = el("textarea", { id: "brief", rows: "3" }); + const go = el("button", { class: "btn wide gap", type: "button" }, "Begin"); + go.onclick = async () => { + if (!title.value.trim() || !name.value.trim()) return msg.replaceChildren(errorLine("A world needs a title and your name in it.")); + go.disabled = true; msg.replaceChildren(el("p", { class: "note pulse" }, "Starting the world")); + const { status: s, body: b } = await post("begin", { key: beginKey, title: title.value.trim(), name: name.value.trim(), brief: brief.value.trim() || null, vault: vault || null, era: vault ? era : null, lenses: lenses.length ? weights : null }); + go.disabled = false; + if (s === 200) { beginKey = null; LS.set("begin-title", title.value.trim()); LS.set("begin-name", name.value.trim()); return openTimeline(b.timeline); } + const unknown = b.outcome === "unknown" || s === 0; + msg.replaceChildren(errorLine((b.error || "The world could not begin (" + s + ").") + (b.step ? " (step: " + b.step + ")" : "") + + (unknown ? " The outcome is unknown: check Your worlds before beginning again. Pressing Begin again is safe; it carries the same request key." : ""))); + }; + show(el("h1", {}, "Begin a world"), + el("label", {}, "1. Lore"), + vaults.length ? choices : el("p", { class: "line info" }, "No vault has been imported on this server, so a world would start with no lore. Ask the host to import one."), + eraBox, + el("label", { for: "title" }, "2. Name the world"), title, + el("label", { for: "name" }, "3. What you are called in it"), name, + el("label", { for: "brief" }, "4. Anything the storyteller should know (optional)"), brief, + lenses.length ? [el("label", {}, "5. What the world reaches for"), ...lensRows] : "", + go, msg, + el("p", { class: "small" }, "A world seeded from lore takes a few minutes. You can leave this page; it carries on.")); +} + +// ---- play ---------------------------------------------------------------- +// The scrollback is the server's turn log: S.history holds the entries fetched +// so far (oldest first), S.live the open turn's view from the stream. Nothing +// here is kept on the device but the unsent draft. +async function openTimeline(id) { + stopLive(); + S.timeline = id; S.history = []; S.older = null; S.live = null; S.echo = null; S.keyed = null; S.tailTried = null; + const { status, body } = await api("timelines"); + if (status !== 200) return show(errorLine(body.error || "Could not open that world."), retryButton(() => openTimeline(id))); + const row = (body.timelines || []).find((r) => r.timeline === id); + if (!row) return listView(); + if (row.status === "seeding") { + show(el("h1", {}, row.title), el("p", { class: "status pulse" }, "Seeding the world from the lore"), + el("div", { class: "bar2" }, el("i", {})), + el("p", { class: "note" }, "Elaborators are writing the people and places. You can leave and come back; this updates by itself.")); + S.poll = setTimeout(() => openTimeline(id), 4000); + return; + } + if (row.status === "failed") { + return show(el("h1", {}, row.title), errorLine("Seeding failed: " + (row.reason || "no reason was recorded.")), + el("button", { class: "btn", type: "button", onclick: beginView }, "Begin another world")); + } + playView(row); +} + +let $log, $status, $text, $send, $retryRow, $older; +async function playView(row) { + const id = S.timeline; + $older = el("div", { class: "older small" }); + $log = el("div", { id: "log" }); + $status = el("p", { class: "status", role: "status" }); + $retryRow = el("div", { class: "row" }); + show(el("h1", {}, row.title), $older, $log, $status, $retryRow); + $text = el("textarea", { id: "say", rows: "2", "aria-label": "What do you do?", placeholder: "What do you do? (Empty Send carries on an unfinished turn.)" }); + $text.value = LS.get("draft:" + id) || ""; + $text.addEventListener("input", () => LS.set("draft:" + id, $text.value)); + $send = el("button", { class: "btn", type: "button", onclick: () => send($text.value) }, "Send"); + document.body.append(el("div", { class: "compose" }, el("div", { class: "in" }, $text, el("div", { class: "row" }, $send, + el("button", { class: "btn alt", type: "button", title: "Carry on an unfinished turn", onclick: () => send("") }, "Continue")) + ))); + const ok = await loadHistory(null); + if (S.timeline !== id) return; + if (ok) window.scrollTo(0, document.documentElement.scrollHeight); + connect(); +} + +// Reads one page of the log. `before` null reads the newest page and merges it +// into what is held; a number reads the page older than that entry. +async function loadHistory(before) { + const id = S.timeline; + const { status, body } = await api("history/" + encodeURIComponent(id) + (before ? "?before=" + before : "")); + if (S.timeline !== id) return false; + if (status !== 200) { + $older.replaceChildren(errorLine(body.error || "The earlier turns could not be loaded."), retryButton(() => loadHistory(before))); + return false; + } + const first = !S.history.length; + const have = new Map(S.history.map((e) => [e.seq, e])); + for (const entry of body.entries || []) have.set(entry.seq, entry); + S.history = [...have.values()].sort((a, b) => a.seq - b.seq); + // Only a read at the old edge moves the edge; a refresh of the newest page leaves it. + if (before || first) S.older = body.older; + render(); + return true; +} + +let loadingOlder = false; +window.addEventListener("scroll", async () => { + if (!S.timeline || !$log || !S.older || loadingOlder || window.scrollY > 160) return; + loadingOlder = true; + const height = document.documentElement.scrollHeight; + if (await loadHistory(S.older)) window.scrollTo(0, window.scrollY + document.documentElement.scrollHeight - height); + loadingOlder = false; +}, { passive: true }); + +function connect() { + const id = S.timeline; + if (S.stream) S.stream.close(); + const stream = new EventSource("api/turn/" + encodeURIComponent(id) + "/stream"); + S.stream = stream; + stream.addEventListener("turn", (event) => { if (S.timeline === id) { try { onTurn(JSON.parse(event.data)); } catch { /* ignore a torn event */ } } }); + stream.onerror = () => { if (S.timeline === id && $status) $status.textContent = "Reconnecting…"; }; +} +document.addEventListener("visibilitychange", async () => { + if (document.hidden || !S.timeline || !$log) return; + const { status, body } = await api("turn/" + encodeURIComponent(S.timeline)); + if (status === 200 && body.timeline === S.timeline) onTurn(body); + if (S.stream && S.stream.readyState === 2) connect(); +}); + +// Whether the log already holds what the open turn shows. +function logged(turn) { + return S.history.some((e) => e.turn_id === turn.id && + (turn.state === "awaiting_player" ? e.status === "asked" && turn.question && e.question === turn.question.text : e.status !== "asked")); +} + +async function onTurn(view) { + const turn = view.turn; + S.live = turn; + if (S.echo && (!turn || turn.revision !== S.echo.revision)) S.echo = null; + render(); + if (turn && turn.state !== "running" && !logged(turn)) { + const mark = turn.id + ":" + turn.revision; + if (S.tailTried !== mark) { S.tailTried = mark; await loadHistory(null); } + } +} + +function render() { + const nearBottom = window.innerHeight + window.scrollY >= document.documentElement.scrollHeight - 240; + const turn = S.live; + $older.replaceChildren(S.older ? el("button", { class: "btn alt", type: "button", onclick: () => loadHistory(S.older) }, "Load earlier turns") : ""); + const nodes = S.history.map(entryNode); + const running = turn && turn.state === "running"; + if (running || S.echo) { + const text = running ? turn.text : S.echo.text; + nodes.push(el("section", { class: "turn" }, text ? el("p", { class: "you" }, text) : "")); + } + if (!nodes.length) nodes.push(el("p", { class: "note" }, "The world is ready. Say what you do.")); + $log.replaceChildren(...nodes); + $retryRow.replaceChildren(); + $status.className = "status"; + $status.textContent = ""; + if (running) { + if (turn.resolving) { $status.className = "status pulse"; $status.textContent = "The storyteller is resolving your turn"; } + else $status.textContent = turn.continue_hint || "This turn is unfinished."; + } else if (S.echo) { + $status.className = "status pulse"; $status.textContent = "Sent"; + } else if (turn && turn.state === "awaiting_player") { + $status.textContent = "The storyteller is waiting for your answer."; + } + const last = S.history[S.history.length - 1]; + if (last && !running && !S.echo && turn && logged(turn)) { + if (last.status === "faulted" && !last.superseded_by) { + $retryRow.append( + el("button", { class: "btn", type: "button", onclick: () => send(last.text, last.seq) }, "Retry"), + el("button", { class: "btn alt", type: "button", onclick: () => editAgain(last.text) }, "Edit and resend")); + } else if (last.status === "refused") { + $retryRow.append(el("button", { class: "btn alt", type: "button", onclick: () => editAgain(last.text) }, "Edit and resend")); + } + } + if (nearBottom) window.scrollTo(0, document.documentElement.scrollHeight); +} + +function entryNode(entry) { + const parts = []; + if (entry.text) parts.push(el("p", { class: "you" }, entry.text)); + if (entry.narration) parts.push(el("p", { class: "story" }, entry.narration)); + if (entry.refusal) parts.push(el("p", { class: "line", role: "alert" }, entry.refusal)); + if (entry.fault) parts.push(el("p", { class: "line", role: "alert" }, entry.fault)); + if (entry.superseded_by) parts.push(el("p", { class: "small" }, "Sent again below.")); + if (entry.question) parts.push(el("div", { class: "ask" }, el("strong", {}, "The storyteller asks"), el("p", { class: "story" }, entry.question))); + return el("section", { class: "turn" }, parts); +} + +function editAgain(text) { $text.value = text; LS.set("draft:" + S.timeline, text); $text.focus(); } + +async function send(text, retryOf) { + if (!S.timeline) return; + const turn = S.live; + const answers = turn && turn.state === "awaiting_player" && turn.question ? turn.question.token : null; + // The same text resent after a lost reply reuses its key, so it cannot play twice. + if (!S.keyed || S.keyed.text !== text || retryOf) S.keyed = { text, key: uuid() }; + $send.disabled = true; + // The echo is placed before the request: the stream can deliver the new turn before the reply returns. + if (text) { S.echo = { text, revision: turn ? turn.revision : null }; render(); } + const { status, body } = await post("play", { timeline: S.timeline, key: S.keyed.key, text, answers, retry_of: retryOf || null }); + $send.disabled = false; + if (status === 202 || status === 200) { + S.keyed = null; + $text.value = ""; LS.set("draft:" + S.timeline, ""); + if (!text) { $status.className = "status pulse"; $status.textContent = "Sent"; } + return; + } + S.echo = null; render(); + $retryRow.replaceChildren(errorLine(status === 0 ? "The server could not be reached. Your text is kept; Send resends it safely." : (body.error || "The turn was refused (" + status + ")."))); +} + +boot(); diff --git a/crates/ghostlight-dungeon/playtest/plan.json b/crates/ghostlight-dungeon/playtest/plan.json new file mode 100644 index 0000000..84eebf3 --- /dev/null +++ b/crates/ghostlight-dungeon/playtest/plan.json @@ -0,0 +1,86 @@ +{ + "turns_per_character": 12, + "wall_minutes": 240, + "turn_timeout_minutes": 15, + "character_model": "claude-sonnet-5-5", + "critic_model": "claude-opus-5-5", + "prices": { + "opus": { "input": 4.0, "output": 20.0, "cache_read": 0.2 }, + "sonnet": { "input": 2.0, "output": 10.0, "cache_read": 0.1 }, + "haiku": { "input": 0.1, "output": 0.5 } + }, + "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..ecdcd28 --- /dev/null +++ b/crates/ghostlight-dungeon/src/api.rs @@ -0,0 +1,2172 @@ +//! The Deru API: JSON over HTTPS behind the Heimdall session cookie. +//! +//! Handlers hold no game state and call no model. They read the catalog and +//! the turn record, and every command goes through `begin` or +//! `PlayTable::admit`/`execute`, the only writers. + +use crate::{ + auth_guard::{BEGIN_COOKIE, BEGIN_TTL_SECONDS}, + heimdall::AuthBeginReceipt, + begin::{BeginRequest, begin}, + catalog::SeedStatus, + run_ahead::{evidence_of, run_ahead}, + play::{Admission, OpenQuestion, PlayError, PlayRequest, PlayTurnState, PlayTurnView}, + runtime::AppState, +}; +use axum::{ + Json, Router, + extract::{DefaultBodyLimit, Path, Query, State}, + http::{HeaderMap, HeaderValue, StatusCode, header}, + response::{ + IntoResponse, Response, + sse::{Event as SseEvent, KeepAlive, Sse}, + }, + routing::{get, post}, +}; +use chrono::{DateTime, Utc}; +use ghostlight::{CommandId, Lens, VerifiedPrincipalEvidence, WorldPhase}; +use serde::Deserialize; +use serde_json::{Value, json}; +use std::{convert::Infallible, time::Duration}; +use tokio::sync::broadcast; + +pub(crate) const COOKIE_NAME: &str = "ghostlight_session"; +const BODY_LIMIT: usize = 64 * 1024; + +/// What a player sees of a turn that died on its model: one fixed line. The +/// fault's own detail stays in the store and the log. +pub(crate) const PLAY_FAULT_LINE: &str = + "The storyteller lost the thread and your turn ended. Write again to start a new turn."; + +const CONTINUE_HINT: &str = + "Your last turn did not finish. If nothing arrives, submit an empty message to continue it."; + +pub(crate) fn router() -> Router { + Router::new() + .route("/api/me", get(me)) + .route("/api/timelines", get(timelines)) + .route("/api/vaults", get(vaults)) + .route("/api/begin", post(begin_world)) + .route("/api/play", post(play)) + .route("/api/turn/{timeline}", get(turn)) + .route("/api/turn/{timeline}/stream", get(turn_stream)) + .route("/api/history/{timeline}", get(history)) + .route("/api/auth/begin", post(auth_begin)) + .route("/api/auth/complete", post(auth_complete)) + .route("/api/auth/logout", post(auth_logout)) + .layer(DefaultBodyLimit::max(BODY_LIMIT)) +} + +fn reply(status: StatusCode, body: Value) -> Response { + (status, Json(body)).into_response() +} + +fn refuse(status: StatusCode, message: impl std::fmt::Display) -> Response { + reply(status, json!({"error": message.to_string()})) +} + +fn unauthorized() -> Response { + refuse(StatusCode::UNAUTHORIZED, "sign in first") +} + +/// The refusal of a play on a world that is not Active: 409 with the status +/// the page shows (`seeding`, `failed` with its reason, or `draft`). +fn unplayable(status: &str, reason: Option<&str>) -> Response { + let error = match status { + "seeding" => "this world is still being seeded", + "failed" => "this world's seed did not finish", + _ => "this world is not active yet", + }; + reply(StatusCode::CONFLICT, json!({"error": error, "status": status, "reason": reason})) +} + +/// The turn as the player sees it: narration, the open question, the refusal +/// of their own act and the fault line. It is derived from the turn record +/// and is display-only; nothing reads it back. +pub(crate) fn turn_view_json(timeline: &str, view: Option<&PlayTurnView>) -> Value { + let Some(view) = view else { + return json!({"timeline": timeline, "turn": null}); + }; + let question = view.question.as_ref().map(|question: &OpenQuestion| { + json!({"text": question.text, "token": question.token}) + }); + json!({ + "timeline": timeline, + "turn": { + "id": view.turn_id, + "state": match view.state { + PlayTurnState::Running => "running", + PlayTurnState::AwaitingPlayer => "awaiting_player", + PlayTurnState::Closed => "closed", + }, + "revision": view.revision, + "narration": view.narration, + "question": question, + "refusal": view.refusal, + "fault": view.fault.then_some(PLAY_FAULT_LINE), + "text": view.player_text, + "resolving": view.run_in_progress, + "continue_hint": (view.state == PlayTurnState::Running && !view.run_in_progress) + .then_some(CONTINUE_HINT), + } + }) +} + +/// The one door an answer's token is judged by: admits only when both sides +/// are present and equal. An unminted token never matches anything. +fn answer_token_admits(given: Option<&str>, expected: Option<&str>) -> bool { + matches!((given, expected), (Some(given), Some(expected)) if given == expected) +} + +pub(crate) fn cookie_value(headers: &HeaderMap) -> Option<&str> { + named_cookie(headers, COOKIE_NAME) +} + +fn named_cookie<'a>(headers: &'a HeaderMap, name: &str) -> Option<&'a str> { + let prefix = format!("{name}="); + headers + .get(header::COOKIE)? + .to_str() + .ok()? + .split(';') + .map(str::trim) + .find_map(|cookie| cookie.strip_prefix(&prefix)) +} + +fn session_cookie(raw: &str, expires_at: DateTime, now: DateTime) -> HeaderValue { + HeaderValue::from_str(&format!( + "{COOKIE_NAME}={raw}; Max-Age={}; HttpOnly; Secure; SameSite=Lax; Path=/ghostlight/", + (expires_at - now).num_seconds().max(0) + )) + .expect("generated session cookie must be valid") +} + +pub(crate) fn signal_fatal(state: &AppState, organ: &str, error: &impl std::fmt::Display) { + let detail = format!("{organ}: {error}"); + tracing::error!(%detail, "runtime owner can no longer uphold its invariant"); + let _ = state.fatal.send(detail); +} + +async fn authenticated_principal( + headers: &HeaderMap, + state: &AppState, +) -> Option { + let raw = cookie_value(headers)?; + match state + .sessions + .lock() + .await + .account_for_cookie(raw, Utc::now()) + { + Ok(account) => account, + Err(error) => { + signal_fatal(state, "app-session custody", &error); + None + } + } +} + +/// The sign-in providers this daemon offers, for the page's buttons. +fn offered_providers(state: &AppState) -> Vec<&'static str> { + ["discord", "google", "twitch"] + .into_iter() + .filter(|name| state.heimdall.offered(name).is_some()) + .collect() +} + +async fn me(headers: HeaderMap, State(state): State) -> Response { + let providers = offered_providers(&state); + let Some(principal) = authenticated_principal(&headers, &state).await else { + return reply(StatusCode::OK, json!({"signedIn": false, "providers": providers})); + }; + let catalog = state.catalog.lock().await; + let player = catalog.player(principal.account_subject_hash()); + reply( + StatusCode::OK, + json!({ + "signedIn": true, + "providers": providers, + "currentTimeline": player.and_then(|player| player.timeline.as_deref()), + "destination": player.and_then(|player| player.destination.as_deref()), + }), + ) +} + +async fn timelines(headers: HeaderMap, State(state): State) -> Response { + let Some(principal) = authenticated_principal(&headers, &state).await else { + return unauthorized(); + }; + let account = principal.account_subject_hash(); + let catalog = state.catalog.lock().await; + let current = catalog.player(account).and_then(|player| player.timeline.clone()); + let rows: Vec = catalog + .timelines_of(account) + .into_iter() + .map(|(timeline, world)| { + let (status, reason) = match catalog.seed_status(&timeline.id) { + None => ("ready", None), + Some(SeedStatus::Seeding) => ("seeding", None), + Some(SeedStatus::Failed(reason)) => ("failed", Some(reason.as_str())), + }; + json!({ + "timeline": timeline.id, + "status": status, + "reason": reason, + "worldId": world.world_id, + "title": world.title, + "parent": timeline.parent, + "snapshotId": world.snapshot_id, + "createdAt": world.created_at, + "current": current.as_deref() == Some(timeline.id.as_str()), + }) + }) + .collect(); + reply(StatusCode::OK, json!({"timelines": rows})) +} + +async fn vaults(headers: HeaderMap, State(state): State) -> Response { + if authenticated_principal(&headers, &state).await.is_none() { + return unauthorized(); + } + let vaults: Vec<_> = state + .vaults + .offers() + .into_iter() + .map(|offer| json!({"name": offer.name, "default_era": offer.default_era, "eras": offer.eras.iter().map(|era| json!({"id": era.id, "label": era.label, "description": era.description})).collect::>()})) + .collect(); + let lenses: Vec<_> = Lens::ALL + .into_iter() + .map(|lens| json!({"id": lens, "name": lens.name(), "reaches_for": lens.reaches_for()})) + .collect(); + reply(StatusCode::OK, json!({"vaults": vaults, "lenses": lenses})) +} + +#[derive(Debug, Deserialize)] +#[serde(deny_unknown_fields)] +struct BeginBody { + key: String, + title: String, + name: String, + #[serde(default)] + brief: Option, + #[serde(default)] + vault: Option, + #[serde(default)] + era: Option, + /// Lens id (snake_case) to weight; omitted is every lens at one. + #[serde(default)] + lenses: Option>, +} + +async fn begin_world( + headers: HeaderMap, + State(state): State, + Json(body): Json, +) -> Response { + let Some(principal) = authenticated_principal(&headers, &state).await else { + return unauthorized(); + }; + let outcome = begin( + &state.catalog, + &state.timelines, + state.vaults.as_ref(), + &state.scale, + &principal, + BeginRequest { + key: body.key, + title: body.title, + name: body.name, + brief: body.brief, + vault: body.vault, + era: body.era, + lenses: body.lenses, + }, + ) + .await; + match outcome { + Ok(begun) => reply( + StatusCode::OK, + json!({"timeline": begun.timeline, "reached": begun.reached}), + ), + Err(error) if error.unknown => reply( + StatusCode::INTERNAL_SERVER_ERROR, + json!({"error": error.to_string(), "outcome": "unknown"}), + ), + Err(error) => reply( + StatusCode::CONFLICT, + json!({"error": error.to_string(), "step": error.step}), + ), + } +} + +#[derive(Debug, Deserialize)] +#[serde(deny_unknown_fields)] +struct PlayBody { + timeline: String, + key: String, + text: String, + /// The token of the question this text answers, as the turn view showed it. + #[serde(default)] + answers: Option, + /// The log entry (`seq`) this text retries. The new entry names it; the + /// old one stays. + #[serde(default)] + retry_of: Option, +} + +async fn play( + headers: HeaderMap, + State(state): State, + Json(body): Json, +) -> Response { + let Some(principal) = authenticated_principal(&headers, &state).await else { + return unauthorized(); + }; + if CommandId::parse_uuid(&body.key).is_err() { + return refuse(StatusCode::BAD_REQUEST, "the play key is not a uuid"); + } + let account = principal.account_subject_hash().to_owned(); + { + let mut catalog = state.catalog.lock().await; + if catalog.owned_timeline(&account, &body.timeline).is_none() { + return refuse(StatusCode::NOT_FOUND, "no such timeline"); + } + match catalog.seed_status(&body.timeline) { + Some(SeedStatus::Seeding) => return unplayable("seeding", None), + Some(SeedStatus::Failed(reason)) => return unplayable("failed", Some(reason.as_str())), + None => {} + } + let current = catalog.player(&account).and_then(|player| player.timeline.as_deref()); + if current != Some(body.timeline.as_str()) + && let Err(error) = catalog.set_current(&account, &body.timeline) + { + tracing::warn!(%error, "the player's pointer could not move"); + } + } + let timeline = body.timeline.clone(); + let host = match state.timelines.host(&body.timeline).await { + Ok(host) => host, + Err(error) => { + tracing::error!(%error, timeline = %body.timeline, "the timeline could not open"); + return refuse(StatusCode::INTERNAL_SERVER_ERROR, "the timeline could not open"); + } + }; + // The seed's status explains a refusal; the world's phase is what decides + // it, so a Draft with no recorded seed is not playable either. + match host.world.snapshot().await { + Ok(world) if world.phase == WorldPhase::Active => {} + Ok(_) => return unplayable("draft", None), + Err(error) => { + tracing::error!(%error, timeline = %body.timeline, "the world could not be read"); + return refuse(StatusCode::INTERNAL_SERVER_ERROR, "the timeline could not open"); + } + } + // The server resolves the open question itself; the client proves it saw + // it by its token. A token with no open question, or not that question's, + // is stale and never reaches the table. + let view = host.play.current_turn_view().await; + let awaiting = view + .as_ref() + .is_some_and(|view| view.state == PlayTurnState::AwaitingPlayer); + if body.answers.is_some() && !awaiting { + return refuse(StatusCode::CONFLICT, "that question is closed"); + } + let answers = match view + .as_ref() + .and_then(|view| view.question.as_ref()) + .filter(|_| awaiting) + { + None => None, + Some(question) => { + if !answer_token_admits(body.answers.as_deref(), question.token.as_deref()) { + return refuse( + StatusCode::CONFLICT, + format!( + "the answer is stale: its token does not name the question \"{}\" currently open", + question.text + ), + ); + } + Some(question.id.clone()) + } + }; + if let Some(seq) = body.retry_of + && !host.play.logged(seq).await + { + return refuse(StatusCode::CONFLICT, "that turn is not in the history"); + } + let retry_of = body.retry_of; + let admission = match host + .play + .admit(body.key, PlayRequest { text: body.text, answers }) + .await + { + Ok(admission) => admission, + Err( + error @ (PlayError::Poisoned + | PlayError::World(_) + | PlayError::Controller(_) + | PlayError::Store(_)), + ) => { + tracing::error!(%error, "a play turn could not be admitted"); + return refuse(StatusCode::INTERNAL_SERVER_ERROR, "the storyteller could not take that turn"); + } + Err(error) => return refuse(StatusCode::CONFLICT, error), + }; + let admitted = match admission { + Admission::Replayed { .. } => return reply(StatusCode::OK, json!({"outcome": "replayed"})), + Admission::Spawn(admitted) => admitted, + }; + if let Some(seq) = retry_of { + host.play.note_retry(&admitted, seq); + } + let _ = host.changes.send(()); + let spawned = host.clone(); + let state = state.clone(); + tokio::spawn(async move { + let ran = spawned.play.execute(admitted, &principal).await; + if let Err(error) = &ran { + let turn_id = spawned.play.current_turn_view().await.map(|view| view.turn_id); + tracing::warn!(%error, ?turn_id, "a play turn ended in error"); + } + let _ = spawned.changes.send(()); + // The turn is closed: answer some of the world's deficit ahead of play. + let closed = ran.is_ok() + && spawned + .play + .current_turn_view() + .await + .is_some_and(|view| view.state == PlayTurnState::Closed); + if closed + && let Some(evidence) = evidence_of(&state.catalog, state.vaults.as_ref(), &spawned, &timeline).await + { + run_ahead(&spawned, evidence, &state.scale).await; + } + }); + reply(StatusCode::ACCEPTED, json!({"outcome": "accepted"})) +} + +/// The host of a timeline the caller owns, or the refusal to send. +async fn owned_host( + headers: &HeaderMap, + state: &AppState, + timeline: &str, +) -> Result, Response> { + let Some(principal) = authenticated_principal(headers, state).await else { + return Err(unauthorized()); + }; + if state + .catalog + .lock() + .await + .owned_timeline(principal.account_subject_hash(), timeline) + .is_none() + { + return Err(refuse(StatusCode::NOT_FOUND, "no such timeline")); + } + state.timelines.host(timeline).await.map_err(|error| { + tracing::error!(%error, timeline, "the timeline could not open"); + refuse(StatusCode::INTERNAL_SERVER_ERROR, "the timeline could not open") + }) +} + +async fn turn( + Path(timeline): Path, + headers: HeaderMap, + State(state): State, +) -> Response { + match owned_host(&headers, &state, &timeline).await { + Ok(host) => { + let view = host.play.current_turn_view().await; + reply(StatusCode::OK, turn_view_json(&timeline, view.as_ref())) + } + Err(response) => response, + } +} + + +#[derive(Debug, Deserialize)] +struct HistoryQuery { + /// Read the entries older than this `seq`; the newest page when absent. + before: Option, + limit: Option, +} + +const HISTORY_PAGE: usize = 30; +const HISTORY_PAGE_MAX: usize = 100; + +/// The signed-in account's own turn log for one timeline, a page at a time, +/// oldest first so the newest entry is last. `owned_host` refuses any +/// timeline the account does not own, so another account's log is unreachable. +async fn history( + Path(timeline): Path, + Query(query): Query, + headers: HeaderMap, + State(state): State, +) -> Response { + let host = match owned_host(&headers, &state, &timeline).await { + Ok(host) => host, + Err(response) => return response, + }; + let limit = query.limit.unwrap_or(HISTORY_PAGE).clamp(1, HISTORY_PAGE_MAX); + let page = match host.play.history(query.before, limit).await { + Ok(page) => page, + Err(error) => { + tracing::error!(%error, %timeline, "the turn log could not be read"); + return refuse(StatusCode::INTERNAL_SERVER_ERROR, "the turn history could not be read"); + } + }; + let entries: Vec = page + .entries + .into_iter() + .map(|(entry, superseded_by)| { + let mut value = serde_json::to_value(entry).expect("a log entry is plain data"); + value["superseded_by"] = json!(superseded_by); + value + }) + .collect(); + reply(StatusCode::OK, json!({"timeline": timeline, "entries": entries, "older": page.older})) +} + +async fn turn_stream( + Path(timeline): Path, + headers: HeaderMap, + State(state): State, +) -> Response { + let host = match owned_host(&headers, &state, &timeline).await { + Ok(host) => host, + Err(response) => return response, + }; + // Subscribe before the first read so a change between the two is not lost. + let mut changes = host.changes.subscribe(); + let stream = async_stream::stream! { + let mut last: Option = None; + loop { + let view = host.play.current_turn_view().await; + let json = turn_view_json(&timeline, view.as_ref()).to_string(); + if last.as_deref() != Some(json.as_str()) { + yield Ok::(SseEvent::default().event("turn").data(json.clone())); + last = Some(json); + } + tokio::select! { + woke = changes.recv() => match woke { + Ok(()) | Err(broadcast::error::RecvError::Lagged(_)) => {} + Err(broadcast::error::RecvError::Closed) => break, + }, + // A wake can be missed across a restart of the browser's own + // connection; re-reading is cheap. + _ = tokio::time::sleep(Duration::from_secs(15)) => {} + } + } + }; + Sse::new(stream).keep_alive(KeepAlive::default()).into_response() +} + +#[derive(Debug, Deserialize)] +#[serde(deny_unknown_fields)] +struct AuthBeginBody { + key: String, + /// One of the providers the daemon offers (`GHOSTLIGHT_AUTH_PROVIDERS`). + provider: String, + /// The invite the browser presents for a first sign-in, if any. Checked + /// against the catalog now, bound to this attempt, spent at complete. + #[serde(default)] + invite: Option, +} + +/// The throttle's key: the address nginx sets in `X-Real-IP`. Behind the proxy +/// the TCP peer is always loopback, so it names no one. +fn client_key(headers: &HeaderMap) -> &str { + headers + .get("x-real-ip") + .and_then(|value| value.to_str().ok()) + .map(str::trim) + .filter(|value| !value.is_empty()) + .unwrap_or("direct") +} + +fn throttled() -> Response { + refuse(StatusCode::TOO_MANY_REQUESTS, "too many sign-in requests; wait a minute") +} + +fn begin_cookie(secret: &str, max_age: i64) -> HeaderValue { + HeaderValue::from_str(&format!( + "{BEGIN_COOKIE}={secret}; Max-Age={max_age}; HttpOnly; Secure; SameSite=Lax; Path=/ghostlight/" + )) + .expect("generated begin cookie must be valid") +} + +/// A pending Heimdall attempt's expiry, or `None` for a receipt that is not a +/// live pending attempt. +fn pending_expiry(receipt: &AuthBeginReceipt, now: DateTime) -> Option> { + let expiry = receipt.expires_at.parse::>().ok()?; + (receipt.status == "pending" && !receipt.handle.is_empty() && expiry > now).then_some(expiry) +} + +async fn auth_begin( + headers: HeaderMap, + State(state): State, + Json(body): Json, +) -> Response { + let now = Utc::now(); + if !state.auth.allow(client_key(&headers), now) { + return throttled(); + } + let Some(provider) = state.heimdall.offered(&body.provider) else { + return refuse(StatusCode::BAD_REQUEST, "that sign-in provider is not offered"); + }; + let invite = body.invite.map(|token| token.trim().to_owned()).filter(|token| !token.is_empty()); + if let Some(token) = &invite + && !state.catalog.lock().await.invite_is_live(token, now) + { + return refuse(StatusCode::FORBIDDEN, "that invite is spent or expired"); + } + let receipt = match state.heimdall.begin(provider, invite.is_some(), &body.key).await { + Ok(receipt) => receipt, + Err(error) => { + tracing::warn!(%error, "Heimdall refused to begin a sign-in"); + return refuse(StatusCode::BAD_GATEWAY, "Heimdall could not begin the sign-in."); + } + }; + let Some(expiry) = pending_expiry(&receipt, now) else { + return refuse(StatusCode::BAD_GATEWAY, "Heimdall returned an invalid authentication attempt."); + }; + let expiry = expiry.min(now + chrono::Duration::seconds(BEGIN_TTL_SECONDS)); + let Some(secret) = state.auth.start(&receipt.handle, invite, expiry, now) else { + return refuse(StatusCode::SERVICE_UNAVAILABLE, "too many sign-ins are open; try again shortly"); + }; + let mut response = reply( + StatusCode::OK, + json!({ + "handle": receipt.handle, + "url": receipt.navigation.url, + "allowedOrigins": receipt.navigation.allowed_origins, + }), + ); + response.headers_mut().insert( + header::SET_COOKIE, + begin_cookie(&secret, (expiry - now).num_seconds().max(0)), + ); + response +} + +#[derive(Debug, Deserialize)] +#[serde(deny_unknown_fields)] +struct AuthCompleteBody { + handle: String, + key: String, +} + +async fn auth_complete( + headers: HeaderMap, + State(state): State, + Json(body): Json, +) -> Response { + let now = Utc::now(); + if !state.auth.allow(client_key(&headers), now) { + return throttled(); + } + if body.handle.is_empty() { + return refuse(StatusCode::BAD_REQUEST, "Authentication completion omitted its opaque handle."); + } + // Only the browser that began the attempt may complete it. + let Some(secret) = named_cookie(&headers, BEGIN_COOKIE) + .filter(|secret| state.auth.matches(&body.handle, secret, now)) + else { + return refuse(StatusCode::FORBIDDEN, "this browser did not begin that sign-in"); + }; + let completion = match state.heimdall.complete(&body.handle, &body.key).await { + Ok(value) => value, + Err(error) => { + tracing::warn!(%error, "Heimdall refused to complete a sign-in"); + return refuse(StatusCode::FORBIDDEN, "Heimdall could not complete the sign-in."); + } + }; + if completion.status == "pending" { + return reply(StatusCode::ACCEPTED, json!({"status": "pending"})); + } + // Any other outcome ends the attempt: the binding is spent here, once. + let Some(invite) = state.auth.consume(&body.handle, secret, now) else { + return refuse(StatusCode::FORBIDDEN, "this browser did not begin that sign-in"); + }; + let spent = |mut response: Response| { + response.headers_mut().append(header::SET_COOKIE, begin_cookie("", 0)); + response + }; + if completion.status != "authenticated" || completion.handle.as_deref() != Some(body.handle.as_str()) { + let message = completion + .error + .clone() + .unwrap_or_else(|| "Heimdall denied access.".into()); + return spent(reply(StatusCode::FORBIDDEN, json!({"status": "denied", "error": message}))); + } + let admission = match state.heimdall.verify_completion(completion).await { + Ok(admission) => admission, + Err(error) => { + tracing::warn!(%error, "a Heimdall completion failed verification"); + return spent(reply( + StatusCode::FORBIDDEN, + json!({"status": "denied", "error": "Heimdall's answer could not be verified."}), + )); + } + }; + // No account and no live invite: refused, never enrolled. The invite is + // consumed only with the account it creates. + let principal = match state + .catalog + .lock() + .await + .sign_in(admission.account_id(), invite.as_deref(), Utc::now()) + { + Ok(Ok(principal)) => principal, + Ok(Err(refusal)) => { + return spent(reply( + StatusCode::FORBIDDEN, + json!({"status": "refused", "error": refusal.to_string()}), + )); + } + Err(error) => { + tracing::error!(%error, "the account catalog could not record a sign-in"); + return refuse(StatusCode::INTERNAL_SERVER_ERROR, "the sign-in could not be recorded"); + } + }; + // The session plays as the account's principal, which is the identity the + // account was first made from. A session minted as another identity would + // split one account across two worlds sets, so it is refused until a + // second-identity link decides the principal (ruling + // dungeon-account-principal-answer). + if principal != admission.account_id() { + return spent(reply( + StatusCode::FORBIDDEN, + json!({"status": "refused", "error": "this identity is linked to an account whose principal it does not carry"}), + )); + } + let expires_at = admission.refresh_expires_at(); + let token = { + let mut sessions = state.sessions.lock().await; + let result = sessions.create_session(admission); + if let Err(error) = &result + && !sessions.is_healthy() + { + signal_fatal(&state, "app-session authentication adoption", error); + } + match result { + Ok(token) => token, + Err(error) => { + tracing::warn!(%error, "an authenticated sign-in could not become a session"); + return spent(reply( + StatusCode::FORBIDDEN, + json!({"status": "denied", "error": "the session could not be created"}), + )); + } + } + }; + let mut response = spent(reply(StatusCode::OK, json!({"status": "authenticated"}))); + response + .headers_mut() + .append(header::SET_COOKIE, session_cookie(&token, expires_at, Utc::now())); + response +} + +async fn auth_logout(headers: HeaderMap, State(state): State) -> Response { + let raw_cookie = cookie_value(&headers).unwrap_or_default(); + let local = { + let mut sessions = state.sessions.lock().await; + sessions + .session_for_logout(raw_cookie) + .and_then(|remote| sessions.revoke_cookie(raw_cookie).map(|_| remote)) + }; + let remote = match local { + Ok(remote) => remote, + Err(error) => { + signal_fatal(&state, "app-session logout", &error); + return reply( + StatusCode::INTERNAL_SERVER_ERROR, + json!({"status": "unknown", "error": "Local session revocation was not confirmed."}), + ); + } + }; + if let Some(session) = remote { + let heimdall = state.heimdall.clone(); + tokio::spawn(async move { + let idempotency = format!( + "logout:{}:{}", + session.heimdall_session_id, session.access_revision + ); + if let Err(error) = heimdall.logout(&session.refresh_claim, &idempotency).await { + tracing::warn!(%error, "local logout succeeded but Heimdall logout was unavailable"); + } + }); + } + let mut response = reply(StatusCode::OK, json!({"status": "anonymous"})); + response.headers_mut().insert( + header::SET_COOKIE, + HeaderValue::from_static( + "ghostlight_session=; Max-Age=0; HttpOnly; Secure; SameSite=Lax; Path=/ghostlight/", + ), + ); + response +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::{ + 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. + #[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("