Compare commits

..

6 Commits

Author SHA1 Message Date
95778d54e4 fix: harden the vault before release
Require a private passphrase and loopback-or-token admin auth. New vaults use Argon2id; existing PBKDF2 vaults still open, and new snapshot metadata is encrypted. Wormhole tokens survive restart, offset uploads seal into the vault, and client-certificate uploads are real. Reject the command provider and keep Postgres passwords off the process arguments. Keep the interruptible canvas motion.
2026-11-10 09:53:06 +07:00
60ba8fed88 feat: add immersive big screen mode 2026-11-09 22:48:21 +07:00
3a0259cbdd feat: animate the vault accretion disk 2026-11-09 22:40:09 +07:00
34154b2ef1 feat: seed production-like backup histories 2026-11-09 22:23:03 +07:00
fba4a1e628 feat: rebuild the orbital vault as an operational map 2026-11-09 22:01:14 +07:00
2129e80c38 fix: report verified orbit capture outcomes 2026-11-09 22:01:14 +07:00
61 changed files with 3926 additions and 1688 deletions

12
.dockerignore Normal file
View File

@@ -0,0 +1,12 @@
.git
target
data
graft
node_modules
web/node_modules
web/dist
**/.DS_Store
*.db
*.part
.env
.env.*

3
.gitignore vendored
View File

@@ -8,3 +8,6 @@ web/dist/
*.db *.db
*.part *.part
.DS_Store .DS_Store
# graft's local graph cache — regenerable, not committed (run `graft build`).
/graft/

5
.ignore Normal file
View File

@@ -0,0 +1,5 @@
# graft's cards are gitignored but should stay greppable: ripgrep reads
# .ignore before .gitignore, so this re-admits the tree to search only.
!graft/
graft/.cache/
graft/.graph/

323
Cargo.lock generated
View File

@@ -19,30 +19,30 @@ checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa"
[[package]] [[package]]
name = "aead" name = "aead"
version = "0.4.3" version = "0.5.2"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0b613b8e1e3cf911a086f53f03bf286f52fd7a7258e4fa606f0ef220d39d8877" checksum = "d122413f284cf2d62fb1b7db97e02edb8cda96d769b16e443a4f6195e35662b0"
dependencies = [ dependencies = [
"crypto-common",
"generic-array", "generic-array",
] ]
[[package]] [[package]]
name = "aes" name = "aes"
version = "0.7.5" version = "0.8.4"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9e8b47f52ea9bae42228d07ec09eb676433d7c4ed1ebdf0f1d1c29ed446f1ab8" checksum = "b169f7a6d4742236a0a00c541b845991d0ac43e546831af1249753ab4c3aa3a0"
dependencies = [ dependencies = [
"cfg-if", "cfg-if",
"cipher", "cipher",
"cpufeatures", "cpufeatures",
"opaque-debug",
] ]
[[package]] [[package]]
name = "aes-gcm" name = "aes-gcm"
version = "0.9.4" version = "0.10.3"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "df5f85a83a7d8b0442b6aa7b504b8212c1733da07b98aae43d4bc21b2cb3cdf6" checksum = "831010a0f742e1209b3bcea8fab6a8e149051ba6099432c8cb2cc117dec3ead1"
dependencies = [ dependencies = [
"aead", "aead",
"aes", "aes",
@@ -138,6 +138,18 @@ version = "1.0.104"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470"
[[package]]
name = "argon2"
version = "0.5.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3c3610892ee6e0cbce8ae2700349fcf8f98adb0dbfbee85aec3c9179d29cc072"
dependencies = [
"base64ct",
"blake2",
"cpufeatures",
"password-hash",
]
[[package]] [[package]]
name = "async-trait" name = "async-trait"
version = "0.1.92" version = "0.1.92"
@@ -161,6 +173,29 @@ version = "1.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"
[[package]]
name = "aws-lc-rs"
version = "1.19.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "048006790404103c488e6c5616b3e7e702a71292aadda08e8f7698a9e0d2eb53"
dependencies = [
"aws-lc-sys",
"zeroize",
]
[[package]]
name = "aws-lc-sys"
version = "0.47.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8bfbe32ac36b3c428696ce315464181bc4029d689fd58e3f2a4e58c252242f52"
dependencies = [
"cc",
"cmake",
"dunce",
"fs_extra",
"pkg-config",
]
[[package]] [[package]]
name = "axum" name = "axum"
version = "0.7.9" version = "0.7.9"
@@ -250,6 +285,15 @@ version = "2.13.2"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06"
[[package]]
name = "blake2"
version = "0.10.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "46502ad458c9a52b69d4d4d32775c788b7a1b85e8bc9d482d92250fc0e3f8efe"
dependencies = [
"digest",
]
[[package]] [[package]]
name = "block-buffer" name = "block-buffer"
version = "0.10.4" version = "0.10.4"
@@ -278,6 +322,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4ff2a8126fff0f8c839080d619675a585e61720bb12d2baceae45769fd66f155" checksum = "4ff2a8126fff0f8c839080d619675a585e61720bb12d2baceae45769fd66f155"
dependencies = [ dependencies = [
"find-msvc-tools", "find-msvc-tools",
"jobserver",
"libc",
"shlex", "shlex",
] ]
@@ -303,11 +349,12 @@ dependencies = [
[[package]] [[package]]
name = "cipher" name = "cipher"
version = "0.3.0" version = "0.4.4"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7ee52072ec15386f770805afd189a01c8841be8696bed250fa2f13c4c0d6dfb7" checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad"
dependencies = [ dependencies = [
"generic-array", "crypto-common",
"inout",
] ]
[[package]] [[package]]
@@ -350,6 +397,15 @@ version = "0.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "702fc72eb24e5a1e48ce58027a675bc24edd52096d5397d4aea7c6dd9eca0bd1" checksum = "702fc72eb24e5a1e48ce58027a675bc24edd52096d5397d4aea7c6dd9eca0bd1"
[[package]]
name = "cmake"
version = "0.1.58"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c0f78a02292a74a88ac736019ab962ece0bc380e3f977bf72e376c5d78ff0678"
dependencies = [
"cc",
]
[[package]] [[package]]
name = "colorchoice" name = "colorchoice"
version = "1.0.5" version = "1.0.5"
@@ -395,18 +451,25 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a"
dependencies = [ dependencies = [
"generic-array", "generic-array",
"rand_core",
"typenum", "typenum",
] ]
[[package]] [[package]]
name = "ctr" name = "ctr"
version = "0.8.0" version = "0.9.2"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "049bb91fb4aaf0e3c7efa6cd5ef877dbbbd15b39dad06d9948de4ec8a75761ea" checksum = "0369ee1ad671834580515889b80f2ea915f23b8be8d0daa4bbaf2ac5c7590835"
dependencies = [ dependencies = [
"cipher", "cipher",
] ]
[[package]]
name = "deranged"
version = "0.5.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9e9de72ce2ad1f90dc62fa25f0f430ef85eb4b0d8fa0be4f30373bc40a21d28e"
[[package]] [[package]]
name = "digest" name = "digest"
version = "0.10.7" version = "0.10.7"
@@ -418,6 +481,12 @@ dependencies = [
"subtle", "subtle",
] ]
[[package]]
name = "dunce"
version = "1.0.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "92773504d58c093f6de2459af4af33faa518c13451eb8f2b5698ed3d36e7c813"
[[package]] [[package]]
name = "encoding_rs" name = "encoding_rs"
version = "0.8.44" version = "0.8.44"
@@ -481,6 +550,12 @@ dependencies = [
"percent-encoding", "percent-encoding",
] ]
[[package]]
name = "fs_extra"
version = "1.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "42703706b716c37f96a77aea830392ad231f44c9e9a67872fa5548707e11b11c"
[[package]] [[package]]
name = "futures-core" name = "futures-core"
version = "0.3.34" version = "0.3.34"
@@ -545,9 +620,9 @@ dependencies = [
[[package]] [[package]]
name = "ghash" name = "ghash"
version = "0.4.4" version = "0.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1583cc1656d7839fd3732b80cf4f38850336cdb9b8ded1cd399ca62958de3c99" checksum = "f0d8a4362ccb29cb0b265253fb0a2728f592895ee6854fd9bc13f2ffda266ff1"
dependencies = [ dependencies = [
"opaque-debug", "opaque-debug",
"polyval", "polyval",
@@ -737,6 +812,15 @@ dependencies = [
"serde", "serde",
] ]
[[package]]
name = "inout"
version = "0.1.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "879f10e63c20629ecabbb64a8010319738c66a5cd0c29b02d63d272b03751d01"
dependencies = [
"generic-array",
]
[[package]] [[package]]
name = "is_terminal_polyfill" name = "is_terminal_polyfill"
version = "1.70.2" version = "1.70.2"
@@ -749,6 +833,16 @@ version = "1.0.19"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4" checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4"
[[package]]
name = "jobserver"
version = "0.1.35"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1c00acbd29eabad4a2392fa0e921c874934dbbf4194312ad20f04a0ed67a3cb3"
dependencies = [
"getrandom 0.4.3",
"libc",
]
[[package]] [[package]]
name = "js-sys" name = "js-sys"
version = "0.3.107" version = "0.3.107"
@@ -909,6 +1003,12 @@ dependencies = [
"windows-sys 0.61.2", "windows-sys 0.61.2",
] ]
[[package]]
name = "num-conv"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441"
[[package]] [[package]]
name = "num-traits" name = "num-traits"
version = "0.2.19" version = "0.2.19"
@@ -970,9 +1070,9 @@ dependencies = [
[[package]] [[package]]
name = "password-hash" name = "password-hash"
version = "0.3.2" version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1d791538a6dcc1e7cb7fe6f6b58aca40e7f79403c45b2bc274008b5e647af1d8" checksum = "346f04948ba92c43e8469c1ee6736c7563d71012b17d40745260fe106aac2166"
dependencies = [ dependencies = [
"base64ct", "base64ct",
"rand_core", "rand_core",
@@ -980,15 +1080,13 @@ dependencies = [
] ]
[[package]] [[package]]
name = "pbkdf2" name = "pem"
version = "0.10.1" version = "3.0.6"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "271779f35b581956db91a3e55737327a03aa051e90b1c47aeb189508533adfd7" checksum = "1d30c53c26bc5b31a98cd02d20f25a7c8567146caf63ed593a9d87b2775291be"
dependencies = [ dependencies = [
"digest", "base64",
"hmac", "serde_core",
"password-hash",
"sha2",
] ]
[[package]] [[package]]
@@ -1011,9 +1109,9 @@ checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548"
[[package]] [[package]]
name = "polyval" name = "polyval"
version = "0.5.3" version = "0.6.2"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8419d2b623c7c0896ff2d5d96e2cb4ede590fed28fcc34934f4c33c036e620a1" checksum = "9d1fe60d06143b2430aa532c94cfe9e29783047f06c0d7fd359a9a51b729fa25"
dependencies = [ dependencies = [
"cfg-if", "cfg-if",
"cpufeatures", "cpufeatures",
@@ -1021,6 +1119,12 @@ dependencies = [
"universal-hash", "universal-hash",
] ]
[[package]]
name = "powerfmt"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4a6394b9e965e73d0a289ee54f589087e2c676aedf60885baf52c76b771e4958"
[[package]] [[package]]
name = "ppv-lite86" name = "ppv-lite86"
version = "0.2.21" version = "0.2.21"
@@ -1108,6 +1212,19 @@ dependencies = [
"getrandom 0.2.17", "getrandom 0.2.17",
] ]
[[package]]
name = "rcgen"
version = "0.13.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "75e669e5202259b5314d1ea5397316ad400819437857b90861765f24c4cf80a2"
dependencies = [
"pem",
"ring",
"rustls-pki-types",
"time",
"yasna",
]
[[package]] [[package]]
name = "redox_syscall" name = "redox_syscall"
version = "0.5.18" version = "0.5.18"
@@ -1146,6 +1263,20 @@ version = "0.8.11"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4"
[[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]] [[package]]
name = "rusqlite" name = "rusqlite"
version = "0.31.0" version = "0.31.0"
@@ -1179,6 +1310,52 @@ dependencies = [
"windows-sys 0.61.2", "windows-sys 0.61.2",
] ]
[[package]]
name = "rustls"
version = "0.23.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "47796c98c480fce5406ef69d1c76378375492c3b0a0de587be0c1d9feb12f395"
dependencies = [
"aws-lc-rs",
"log",
"once_cell",
"ring",
"rustls-pki-types",
"rustls-webpki",
"subtle",
"zeroize",
]
[[package]]
name = "rustls-pemfile"
version = "2.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dce314e5fee3f39953d46bb63bb8a46d40c2f8fb7cc5a3b6cab2bde9721d6e50"
dependencies = [
"rustls-pki-types",
]
[[package]]
name = "rustls-pki-types"
version = "1.15.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2f4925028c7eb5d1fcdaf196971378ed9d2c1c4efc7dc5d011256f76c99c0a96"
dependencies = [
"zeroize",
]
[[package]]
name = "rustls-webpki"
version = "0.102.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "64ca1bc8749bd4cf37b5ce386cc146580777b4e8572c7b97baf22c83f444bee9"
dependencies = [
"aws-lc-rs",
"ring",
"rustls-pki-types",
"untrusted",
]
[[package]] [[package]]
name = "rustversion" name = "rustversion"
version = "1.0.23" version = "1.0.23"
@@ -1272,6 +1449,12 @@ dependencies = [
"serde", "serde",
] ]
[[package]]
name = "sha1_smol"
version = "1.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bbfa15b3dddfee50a0fff136974b3e1bde555604ba463834a7eb7deb6417705d"
[[package]] [[package]]
name = "sha2" name = "sha2"
version = "0.10.8" version = "0.10.8"
@@ -1350,9 +1533,9 @@ checksum = "73473c0e59e6d5812c5dfe2a064a6444949f089e20eec9a2e5506596494e4623"
[[package]] [[package]]
name = "subtle" name = "subtle"
version = "2.4.1" version = "2.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6bdef32e8150c2a081110b42772ffe7d7c9032b606bc226c8260fd97e0976601" checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292"
[[package]] [[package]]
name = "syn" name = "syn"
@@ -1412,6 +1595,8 @@ dependencies = [
"anyhow", "anyhow",
"base64", "base64",
"clap", "clap",
"rustls",
"rustls-pemfile",
"serde", "serde",
"serde_json", "serde_json",
"tessera-core", "tessera-core",
@@ -1431,6 +1616,7 @@ dependencies = [
"serde", "serde",
"serde_json", "serde_json",
"tessera-core", "tessera-core",
"tessera-demo",
"tessera-providers", "tessera-providers",
"tessera-store", "tessera-store",
"uuid", "uuid",
@@ -1451,6 +1637,21 @@ dependencies = [
"uuid", "uuid",
] ]
[[package]]
name = "tessera-demo"
version = "0.1.0"
dependencies = [
"anyhow",
"chrono",
"rusqlite",
"serde",
"serde_json",
"tessera-core",
"tessera-store",
"tracing",
"uuid",
]
[[package]] [[package]]
name = "tessera-hub" name = "tessera-hub"
version = "0.1.0" version = "0.1.0"
@@ -1461,16 +1662,25 @@ dependencies = [
"chrono", "chrono",
"cron", "cron",
"hex", "hex",
"hyper",
"hyper-util",
"include_dir", "include_dir",
"indexmap", "indexmap",
"rand", "rand",
"rcgen",
"rusqlite", "rusqlite",
"rustls",
"rustls-pemfile",
"serde", "serde",
"serde_json", "serde_json",
"tempfile",
"tessera-core", "tessera-core",
"tessera-demo",
"tessera-providers", "tessera-providers",
"tessera-store", "tessera-store",
"tokio", "tokio",
"tokio-rustls",
"tower",
"tower-http", "tower-http",
"tracing", "tracing",
"tracing-subscriber", "tracing-subscriber",
@@ -1498,10 +1708,10 @@ version = "0.1.0"
dependencies = [ dependencies = [
"aes-gcm", "aes-gcm",
"anyhow", "anyhow",
"argon2",
"chrono", "chrono",
"hex", "hex",
"hmac", "hmac",
"pbkdf2",
"rand", "rand",
"serde", "serde",
"serde_json", "serde_json",
@@ -1544,6 +1754,25 @@ dependencies = [
"cfg-if", "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",
]
[[package]]
name = "time-core"
version = "0.1.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9e1c906769ad99c88eaa54e728060edef082f8e358ff32030cb7c7d315e81109"
[[package]] [[package]]
name = "tokio" name = "tokio"
version = "1.40.0" version = "1.40.0"
@@ -1573,6 +1802,16 @@ dependencies = [
"syn 2.0.119", "syn 2.0.119",
] ]
[[package]]
name = "tokio-rustls"
version = "0.26.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8e727b36a1a0e8b74c376ac2211e40c2c8af09fb4013c60d910495810f008e9b"
dependencies = [
"rustls",
"tokio",
]
[[package]] [[package]]
name = "tokio-util" name = "tokio-util"
version = "0.7.17" version = "0.7.17"
@@ -1722,14 +1961,20 @@ checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563"
[[package]] [[package]]
name = "universal-hash" name = "universal-hash"
version = "0.4.1" version = "0.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9f214e8f697e925001e66ec2c6e37a4ef93f0f78c2eed7814394e10c62025b05" checksum = "fc1de2c688dc15305988b563c3854064043356019f97a4b46276fe734c4f07ea"
dependencies = [ dependencies = [
"generic-array", "crypto-common",
"subtle", "subtle",
] ]
[[package]]
name = "untrusted"
version = "0.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1"
[[package]] [[package]]
name = "utf8parse" name = "utf8parse"
version = "0.2.2" version = "0.2.2"
@@ -1769,6 +2014,7 @@ checksum = "81dfa00651efa65069b0b6b651f4aaa31ba9e3c3ce0137aaad053604ee7e0314"
dependencies = [ dependencies = [
"getrandom 0.2.17", "getrandom 0.2.17",
"serde", "serde",
"sha1_smol",
] ]
[[package]] [[package]]
@@ -1999,6 +2245,15 @@ version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec"
[[package]]
name = "yasna"
version = "0.5.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e17bb3549cc1321ae1296b9cdc2698e2b6cb1992adfa19a8c72e5b7a738f44cd"
dependencies = [
"time",
]
[[package]] [[package]]
name = "zerocopy" name = "zerocopy"
version = "0.8.63" version = "0.8.63"
@@ -2019,6 +2274,12 @@ dependencies = [
"syn 2.0.119", "syn 2.0.119",
] ]
[[package]]
name = "zeroize"
version = "1.9.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e13084392c5e4bc371903e2935a5eaeed24905a7511356b883835e18a78f6879"
[[package]] [[package]]
name = "zmij" name = "zmij"
version = "1.0.23" version = "1.0.23"

View File

@@ -39,8 +39,8 @@ tracing = "0.1"
tracing-subscriber = { version = "0.3", features = ["env-filter"] } tracing-subscriber = { version = "0.3", features = ["env-filter"] }
utoipa = { version = "4.2", features = ["axum_extras", "chrono"] } utoipa = { version = "4.2", features = ["axum_extras", "chrono"] }
uuid = { version = "=1.10.0", features = ["v4", "serde"] } uuid = { version = "=1.10.0", features = ["v4", "serde"] }
aes-gcm = "=0.9.4" aes-gcm = "=0.10.3"
pbkdf2 = { version = "=0.10.1", features = ["simple"] } argon2 = "=0.5.3"
hmac = "0.12" hmac = "0.12"
tempfile = "3.12" tempfile = "3.12"
walkdir = "2.5" walkdir = "2.5"

View File

@@ -1,7 +1,7 @@
FROM node:22-bookworm AS web FROM node:22-bookworm AS web
WORKDIR /build WORKDIR /build
COPY web/package.json web/package-lock.json* ./ COPY web/package.json web/package-lock.json* ./
RUN npm ci 2>/dev/null || npm install RUN npm ci
COPY web/ ./ COPY web/ ./
RUN npm run build RUN npm run build
@@ -13,7 +13,7 @@ COPY --from=web /build/dist ./web/dist
RUN cargo build --release -p tessera-hub RUN cargo build --release -p tessera-hub
FROM debian:bookworm-slim FROM debian:bookworm-slim
RUN apt-get update && apt-get install -y ca-certificates && rm -rf /var/lib/apt/lists/* RUN apt-get update && apt-get install -y --no-install-recommends ca-certificates postgresql-client && rm -rf /var/lib/apt/lists/*
COPY --from=rust /build/target/release/tessera-hub /usr/local/bin/ COPY --from=rust /build/target/release/tessera-hub /usr/local/bin/
ENV TESSERA_LISTEN=0.0.0.0:8787 ENV TESSERA_LISTEN=0.0.0.0:8787
ENV TESSERA_DATA_DIR=/data ENV TESSERA_DATA_DIR=/data

View File

@@ -10,24 +10,28 @@ cd web && npm ci && npm run build && cd ..
cargo build --release -p tessera-hub cargo build --release -p tessera-hub
export TESSERA_DATA_DIR=./data export TESSERA_DATA_DIR=./data
export TESSERA_VAULT_PASSPHRASE=dev-vault-key export TESSERA_VAULT_PASSPHRASE='choose a long private passphrase'
./target/release/tessera-hub ./target/release/tessera-hub
``` ```
Open [http://127.0.0.1:8787](http://127.0.0.1:8787) — API docs at `/swagger-ui`. The hub listens on **127.0.0.1:8787** unless `TESSERA_LISTEN` is set. Open [http://127.0.0.1:8787](http://127.0.0.1:8787). The OpenAPI document is at `/api-doc/openapi.json`. There is no default passphrase, and new vaults refuse the old published value `dev-vault-key`. Leave `TESSERA_SEED_DEMO` unset; `TESSERA_SEED_DEMO=1` writes demo backup history into the data directory.
`TESSERA_ADMIN_TOKEN` is optional. When it is unset, the hub logs that snapshot, orbit, reconstitute, and pairing routes are open to loopback clients only. When it is set, every client, including loopback, must send `Authorization: Bearer <token>` or `X-Tessera-Admin-Token`. `/health`, the OpenAPI document, wormhole claim, and wormhole upload stay outside that check: claim uses the pairing code, and upload uses the upload token. The canvas does not send an admin token. A Docker-published connection is not loopback inside the container, so those backup routes answer 401 there until you set a token and call them with it.
### Docker Compose ### Docker Compose
```bash ```bash
export TESSERA_VAULT_PASSPHRASE='choose a long private passphrase'
docker compose up --build docker compose up --build
``` ```
Hub listens on **8787**. Compose publishes **127.0.0.1:8787** only. The process inside the container listens on `0.0.0.0:8787` so that published port can reach it. The image includes `pg_dump` via `postgresql-client`.
### CLI ### CLI
```bash ```bash
cargo build --release -p tessera-cli cargo build --release -p tessera-cli
export TESSERA_VAULT_PASSPHRASE='choose a long private passphrase'
./target/release/tessera init ./target/release/tessera init
./target/release/tessera orbit nightly --path ./docs --dry-run ./target/release/tessera orbit nightly --path ./docs --dry-run
./target/release/tessera snap ./target/release/tessera snap
@@ -41,9 +45,12 @@ See [docs/SPEC.md](docs/SPEC.md). Rust workspace crates: `tessera-core`, `tesser
## Limitations (v1) ## Limitations (v1)
- Vault engine uses a **restic-compatible directory layout** with Tessera’s own chunk encryption (Rust 1.83 cannot yet depend on `rustic_core` 0.13+). Emergency tooling may use external `rustic`/`restic` as formats converge. - Vault engine uses a **restic-compatible directory layout** with Tessera’s own chunk encryption (Rust 1.83 cannot yet depend on `rustic_core` 0.13+). Emergency tooling may use external `rustic`/`restic` as formats converge.
- Wormhole uploads are **token-authenticated**; mTLS is optional via env hook (`TESSERA_WORMHOLE_MTLS`) without bundled CA generation. - New vaults derive the key with Argon2id (19 MiB, 2 iterations, parallelism 1) and record `keys/kdf.json`. A vault that already has a salt and no `kdf.json` still opens with PBKDF2-HMAC-SHA256, 100,000 iterations. New snapshot metadata is written as `{id}.json.enc`. Existing `{id}.json` files still list and restore.
- Postgres provider requires `pg_dump` on `PATH`. - Wormhole pairing codes and upload tokens are stored in SQLite and survive a hub restart. Chunks are written at the given offset. When the bytes cover `total_bytes`, the hub seals them into the vault and deletes the `.part` file. `total_bytes` is required.
- OIDC admin auth is stubbed; v1 uses open local API when hub is bound to localhost. - Set `TESSERA_WORMHOLE_MTLS` to `1` or `true` to open a client-certificate listener. It also needs `TESSERA_WORMHOLE_CERT`, `TESSERA_WORMHOLE_KEY`, and `TESSERA_WORMHOLE_CLIENT_CA`. `TESSERA_WORMHOLE_LISTEN` defaults to `127.0.0.1:8788`. While that listener is up, plain HTTP upload routes answer 403. An agent that uses `https://` needs `TESSERA_WORMHOLE_CA`, `TESSERA_WORMHOLE_CLIENT_CERT`, and `TESSERA_WORMHOLE_CLIENT_KEY`.
- Postgres capture shells out to `pg_dump`. The connection URL is parsed and the password is written to a mode `0600` pgpass file (`PGPASSFILE`); it is not placed on the process argument list. The release image installs `pg_dump`; a hub built from source needs it on `PATH`.
- The command provider is outside this release. Creating a command orbit and running it returns `command provider is outside this release; use filesystem or postgres`.
- OIDC is not implemented. The canvas does not attach `TESSERA_ADMIN_TOKEN`.
## License ## License

View File

@@ -2,11 +2,11 @@ services:
tessera-hub: tessera-hub:
build: . build: .
ports: ports:
- "8787:8787" - "127.0.0.1:8787:8787"
environment: environment:
TESSERA_LISTEN: "0.0.0.0:8787" TESSERA_LISTEN: "0.0.0.0:8787"
TESSERA_DATA_DIR: /data TESSERA_DATA_DIR: /data
TESSERA_VAULT_PASSPHRASE: ${TESSERA_VAULT_PASSPHRASE:-dev-vault-key} TESSERA_VAULT_PASSPHRASE: ${TESSERA_VAULT_PASSPHRASE:?Set TESSERA_VAULT_PASSPHRASE}
RUST_LOG: tessera_hub=info RUST_LOG: tessera_hub=info
volumes: volumes:
- tessera-data:/data - tessera-data:/data

View File

@@ -20,3 +20,5 @@ tracing.workspace = true
tracing-subscriber.workspace = true tracing-subscriber.workspace = true
uuid.workspace = true uuid.workspace = true
base64 = "0.22" base64 = "0.22"
rustls = { version = "=0.23.23", default-features = false, features = ["ring", "std"] }
rustls-pemfile = "=2.2.0"

View File

@@ -1,7 +1,11 @@
use anyhow::{Context, Result}; use anyhow::{Context, Result};
use rustls::pki_types::ServerName;
use rustls::{ClientConfig, ClientConnection, RootCertStore, StreamOwned};
use std::collections::HashMap; use std::collections::HashMap;
use std::io::{Read, Write}; use std::fs::File;
use std::io::{BufReader, Read, Write};
use std::net::TcpStream; use std::net::TcpStream;
use std::sync::Arc;
pub fn post_json(url: &str, body: &serde_json::Value, headers: &[(&str, &str)]) -> Result<String> { pub fn post_json(url: &str, body: &serde_json::Value, headers: &[(&str, &str)]) -> Result<String> {
let payload = serde_json::to_string(body)?; let payload = serde_json::to_string(body)?;
@@ -15,8 +19,12 @@ fn request(
content_type: Option<&str>, content_type: Option<&str>,
headers: &[(&str, &str)], headers: &[(&str, &str)],
) -> Result<String> { ) -> Result<String> {
let (host, port, path) = parse_url(url)?; let (https, host, port, path) = parse_url(url)?;
let mut stream = TcpStream::connect((host.as_str(), port)).context("connect")?; let mut stream: Box<dyn ReadWrite> = if https {
Box::new(connect_mtls(&host, port)?)
} else {
Box::new(TcpStream::connect((host.as_str(), port)).context("connect")?)
};
let mut req = format!("{method} {path} HTTP/1.1\r\nHost: {host}\r\nConnection: close\r\n"); let mut req = format!("{method} {path} HTTP/1.1\r\nHost: {host}\r\nConnection: close\r\n");
for (k, v) in headers { for (k, v) in headers {
req.push_str(&format!("{k}: {v}\r\n")); req.push_str(&format!("{k}: {v}\r\n"));
@@ -38,20 +46,65 @@ fn request(
Ok(buf[body_start..].trim().to_string()) Ok(buf[body_start..].trim().to_string())
} }
fn parse_url(url: &str) -> Result<(String, u16, String)> { trait ReadWrite: Read + Write {}
let url = url.strip_prefix("http://").context("only http supported")?; impl<T: Read + Write> ReadWrite for T {}
let (host_port, path) = url.split_once('/').unwrap_or((url, ""));
fn parse_url(url: &str) -> Result<(bool, String, u16, String)> {
let (https, rest) = if let Some(rest) = url.strip_prefix("https://") {
(true, rest)
} else if let Some(rest) = url.strip_prefix("http://") {
(false, rest)
} else {
anyhow::bail!("hub url must start with http:// or https://");
};
let (host_port, path) = rest.split_once('/').unwrap_or((rest, ""));
let path = if path.is_empty() { let path = if path.is_empty() {
"/".to_string() "/".to_string()
} else { } else {
format!("/{path}") format!("/{path}")
}; };
let (host, port) = if let Some((h, p)) = host_port.split_once(':') { let (host, port) = if let Some((host, port)) = host_port.split_once(':') {
(h.to_string(), p.parse()?) (host.to_string(), port.parse()?)
} else { } else {
(host_port.to_string(), 80) (host_port.to_string(), if https { 443 } else { 80 })
}; };
Ok((host, port, path)) Ok((https, host, port, path))
}
fn connect_mtls(host: &str, port: u16) -> Result<StreamOwned<ClientConnection, TcpStream>> {
let _ = rustls::crypto::ring::default_provider().install_default();
let ca = std::env::var("TESSERA_WORMHOLE_CA")
.context("TESSERA_WORMHOLE_CA is required for an https hub")?;
let cert = std::env::var("TESSERA_WORMHOLE_CLIENT_CERT")
.context("TESSERA_WORMHOLE_CLIENT_CERT is required for an https hub")?;
let key = std::env::var("TESSERA_WORMHOLE_CLIENT_KEY")
.context("TESSERA_WORMHOLE_CLIENT_KEY is required for an https hub")?;
let mut roots = RootCertStore::empty();
for ca_cert in load_certs(&ca)? {
roots.add(ca_cert).map_err(|error| anyhow::anyhow!("hub CA: {error}"))?;
}
let client = ClientConfig::builder()
.with_root_certificates(roots)
.with_client_auth_cert(load_certs(&cert)?, load_key(&key)?)
.map_err(|error| anyhow::anyhow!("client certificate: {error}"))?;
let name = ServerName::try_from(host.to_string()).context("hub hostname")?;
let connection = ClientConnection::new(Arc::new(client), name)?;
let tcp = TcpStream::connect((host, port)).context("connect")?;
Ok(StreamOwned::new(connection, tcp))
}
fn load_certs(path: &str) -> Result<Vec<rustls::pki_types::CertificateDer<'static>>> {
let mut reader = BufReader::new(File::open(path).with_context(|| format!("open {path}"))?);
rustls_pemfile::certs(&mut reader)
.collect::<Result<Vec<_>, _>>()
.context("parse certificate")
}
fn load_key(path: &str) -> Result<rustls::pki_types::PrivateKeyDer<'static>> {
let mut reader = BufReader::new(File::open(path).with_context(|| format!("open {path}"))?);
rustls_pemfile::private_key(&mut reader)
.context("parse private key")?
.context("no private key in client key file")
} }
#[allow(dead_code)] #[allow(dead_code)]

View File

@@ -12,8 +12,9 @@ struct Cli {
command: Commands, command: Commands,
#[arg(long, env = "TESSERA_DATA_DIR", default_value = "./data")] #[arg(long, env = "TESSERA_DATA_DIR", default_value = "./data")]
data_dir: String, data_dir: String,
#[arg(long, env = "TESSERA_VAULT_PASSPHRASE", default_value = "dev-vault-key")] /// Required for vault commands. No default; the published example passphrase is rejected for new vaults.
vault_pass: String, #[arg(long, env = "TESSERA_VAULT_PASSPHRASE")]
vault_pass: Option<String>,
#[arg(long, env = "TESSERA_HUB_URL", default_value = "http://127.0.0.1:8787")] #[arg(long, env = "TESSERA_HUB_URL", default_value = "http://127.0.0.1:8787")]
hub_url: String, hub_url: String,
} }
@@ -98,14 +99,24 @@ fn main() -> Result<()> {
Ok(()) Ok(())
} }
fn require_passphrase(cli: &Cli) -> Result<&str> {
match cli.vault_pass.as_deref() {
Some(pass) if !pass.is_empty() => Ok(pass),
_ => anyhow::bail!(
"Set TESSERA_VAULT_PASSPHRASE or pass --vault-pass. Tessera does not ship a default passphrase."
),
}
}
fn cmd_seed_demo(cli: &Cli, force: bool, reset: bool) -> Result<()> { fn cmd_seed_demo(cli: &Cli, force: bool, reset: bool) -> Result<()> {
let data = std::path::Path::new(&cli.data_dir); let data = std::path::Path::new(&cli.data_dir);
let vault_pass = require_passphrase(cli)?;
if reset { if reset {
tessera_demo::clear_demo(data, &cli.vault_pass)?; tessera_demo::clear_demo(data, vault_pass)?;
println!("Demo seed cleared."); println!("Demo seed cleared.");
return Ok(()); return Ok(());
} }
let report = tessera_demo::apply(data, &cli.vault_pass, force)?; let report = tessera_demo::apply(data, vault_pass, force)?;
if report.skipped { if report.skipped {
println!( println!(
"Demo seed already applied ({} orbits, {} snapshots). Use --force to re-seed.", "Demo seed already applied ({} orbits, {} snapshots). Use --force to re-seed.",
@@ -130,7 +141,7 @@ fn cmd_init(cli: &Cli) -> Result<()> {
println!("Vault already initialized."); println!("Vault already initialized.");
return Ok(()); return Ok(());
} }
Vault::init(&vp, &cli.vault_pass).context("init vault")?; Vault::init(&vp, require_passphrase(cli)?).context("init vault")?;
println!("Vault initialized at {}", vp.display()); println!("Vault initialized at {}", vp.display());
Ok(()) Ok(())
} }
@@ -142,7 +153,7 @@ fn cmd_status(cli: &Cli) -> Result<()> {
} }
let vp = vault_path(&cli.data_dir); let vp = vault_path(&cli.data_dir);
if vp.join("config").exists() { if vp.join("config").exists() {
let vault = Vault::open(&vp, &cli.vault_pass)?; let vault = Vault::open(&vp, require_passphrase(cli)?)?;
let n = vault.list_snapshots()?.len(); let n = vault.list_snapshots()?.len();
println!("Vault: online — {n} snapshots"); println!("Vault: online — {n} snapshots");
} else { } else {
@@ -197,7 +208,7 @@ fn cmd_snap(cli: &Cli, orbit_name: Option<String>) -> Result<()> {
} }
fn cmd_list(cli: &Cli) -> Result<()> { fn cmd_list(cli: &Cli) -> Result<()> {
let vault = Vault::open(&vault_path(&cli.data_dir), &cli.vault_pass)?; let vault = Vault::open(&vault_path(&cli.data_dir), require_passphrase(cli)?)?;
for s in vault.list_snapshots()? { for s in vault.list_snapshots()? {
println!( println!(
"{} {} {} bytes orbit={}", "{} {} {} bytes orbit={}",
@@ -211,14 +222,14 @@ fn cmd_list(cli: &Cli) -> Result<()> {
} }
fn cmd_reconstitute(cli: &Cli, snapshot_id: Uuid, target: String) -> Result<()> { fn cmd_reconstitute(cli: &Cli, snapshot_id: Uuid, target: String) -> Result<()> {
let vault = Vault::open(&vault_path(&cli.data_dir), &cli.vault_pass)?; let vault = Vault::open(&vault_path(&cli.data_dir), require_passphrase(cli)?)?;
let n = vault.restore_snapshot(snapshot_id, std::path::Path::new(&target))?; let n = vault.restore_snapshot(snapshot_id, std::path::Path::new(&target))?;
println!("Reconstituted {n} bytes to {target}"); println!("Reconstituted {n} bytes to {target}");
Ok(()) Ok(())
} }
fn cmd_decay(cli: &Cli, preset: &str) -> Result<()> { fn cmd_decay(cli: &Cli, preset: &str) -> Result<()> {
let mut vault = Vault::open(&vault_path(&cli.data_dir), &cli.vault_pass)?; let mut vault = Vault::open(&vault_path(&cli.data_dir), require_passphrase(cli)?)?;
let pruned = vault.prune_with_decay(preset)?; let pruned = vault.prune_with_decay(preset)?;
println!("{} snapshots decayed.", pruned.len()); println!("{} snapshots decayed.", pruned.len());
Ok(()) Ok(())

View File

@@ -18,7 +18,7 @@ pub struct HubConfig {
impl Default for HubConfig { impl Default for HubConfig {
fn default() -> Self { fn default() -> Self {
Self { Self {
listen: "0.0.0.0:8787".into(), listen: "127.0.0.1:8787".into(),
data_dir: "./data".into(), data_dir: "./data".into(),
admin_password_hash: None, admin_password_hash: None,
} }

View File

@@ -31,9 +31,28 @@ struct DemoOrbit {
dry_run: bool, dry_run: bool,
status: &'static str, status: &'static str,
snap_count: usize, snap_count: usize,
interval_hours: i64,
base_size_kb: u32, base_size_kb: u32,
} }
impl DemoOrbit {
fn snapshot_age(&self, index: usize) -> Duration {
let since_last_success = if self.status == "failed" {
self.interval_hours * 3
} else {
self.interval_hours / 3
};
let jitter = ((index * 13 + self.slug.len() * 7) % 45) as i64;
Duration::hours(since_last_success + index as i64 * self.interval_hours)
+ Duration::minutes(jitter)
}
fn snapshot_size_kb(&self, index: usize) -> u32 {
let variation = 84 + ((index * 7 + self.slug.len() * 3) % 33) as u32;
self.base_size_kb * variation / 100
}
}
fn demo_id(kind: &str, name: &str) -> Uuid { fn demo_id(kind: &str, name: &str) -> Uuid {
Uuid::new_v5(&Uuid::NAMESPACE_OID, format!("{DEMO_NS}:{kind}:{name}").as_bytes()) Uuid::new_v5(&Uuid::NAMESPACE_OID, format!("{DEMO_NS}:{kind}:{name}").as_bytes())
} }
@@ -98,8 +117,8 @@ pub fn apply(data_dir: &Path, vault_pass: &str, force: bool) -> Result<SeedRepor
for i in 0..o.snap_count { for i in 0..o.snap_count {
let snap_id = demo_id("snap", &format!("{}:{}", o.slug, i)); let snap_id = demo_id("snap", &format!("{}:{}", o.slug, i));
let taken_at = now - Duration::hours((i as i64 + 1) * 9 + (o.slug.len() as i64 % 5)); let taken_at = now - o.snapshot_age(i);
let payload = synthetic_payload(o.slug, o.base_size_kb + (i as u32) * 17); let payload = synthetic_payload(o.slug, o.snapshot_size_kb(i));
let manifest = SnapshotManifest { let manifest = SnapshotManifest {
snapshot_id: snap_id, snapshot_id: snap_id,
orbit_id, orbit_id,
@@ -236,134 +255,169 @@ fn demo_orbits() -> Vec<DemoOrbit> {
DemoOrbit { DemoOrbit {
slug: "prod-api", slug: "prod-api",
provider: "postgres", provider: "postgres",
config: serde_json::json!({ "connection_url": "postgres://demo/prod" }), config: serde_json::json!({ "connection_url": "postgres://postgres.demo.invalid/prod" }),
schedule: "0 2 * * *", schedule: "0 2 * * *",
decay: "year-of-monthlies", decay: "year-of-monthlies",
dry_run: false, dry_run: false,
status: "completed", status: "completed",
snap_count: 4, snap_count: 24,
base_size_kb: 420, interval_hours: 24,
base_size_kb: 2560,
}, },
DemoOrbit { DemoOrbit {
slug: "wiki", slug: "wiki",
provider: "filesystem", provider: "filesystem",
config: serde_json::json!({ "paths": ["/data/wiki"] }), config: serde_json::json!({ "paths": ["/_tessera_demo/wiki"] }),
schedule: "0 3 * * *", schedule: "0 3 * * *",
decay: "week-of-dailies", decay: "week-of-dailies",
dry_run: false, dry_run: false,
status: "completed", status: "completed",
snap_count: 3, snap_count: 14,
base_size_kb: 88, interval_hours: 24,
base_size_kb: 256,
}, },
DemoOrbit { DemoOrbit {
slug: "gitea", slug: "gitea",
provider: "filesystem", provider: "filesystem",
config: serde_json::json!({ "paths": ["/var/gitea"] }), config: serde_json::json!({ "paths": ["/_tessera_demo/gitea"] }),
schedule: "0 1 * * *", schedule: "0 1 * * *",
decay: "month-of-weeklies", decay: "month-of-weeklies",
dry_run: false, dry_run: false,
status: "running", status: "running",
snap_count: 3, snap_count: 18,
base_size_kb: 220, interval_hours: 24,
base_size_kb: 1024,
}, },
DemoOrbit { DemoOrbit {
slug: "monitoring", slug: "monitoring",
provider: "filesystem", provider: "filesystem",
config: serde_json::json!({ "paths": ["/etc/prometheus", "/var/lib/grafana"] }), config: serde_json::json!({ "paths": ["/_tessera_demo/prometheus", "/_tessera_demo/grafana"] }),
schedule: "0 */6 * * *", schedule: "0 */6 * * *",
decay: "week-of-dailies", decay: "week-of-dailies",
dry_run: false, dry_run: false,
status: "completed", status: "completed",
snap_count: 3, snap_count: 28,
base_size_kb: 64, interval_hours: 6,
base_size_kb: 96,
}, },
DemoOrbit { DemoOrbit {
slug: "staging-db", slug: "staging-db",
provider: "postgres", provider: "postgres",
config: serde_json::json!({ "connection_url": "postgres://demo/staging" }), config: serde_json::json!({ "connection_url": "postgres://postgres.demo.invalid/staging" }),
schedule: "0 4 * * 0", schedule: "0 4 * * 0",
decay: "week-of-dailies", decay: "week-of-dailies",
dry_run: false, dry_run: false,
status: "failed", status: "failed",
snap_count: 2, snap_count: 8,
base_size_kb: 310, interval_hours: 168,
base_size_kb: 640,
}, },
DemoOrbit { DemoOrbit {
slug: "legal-docs", slug: "legal-docs",
provider: "filesystem", provider: "filesystem",
config: serde_json::json!({ "paths": ["/vault/legal"] }), config: serde_json::json!({ "paths": ["/_tessera_demo/legal"] }),
schedule: "0 0 * * 1", schedule: "0 0 * * 1",
decay: "year-of-monthlies", decay: "year-of-monthlies",
dry_run: false, dry_run: false,
status: "completed", status: "completed",
snap_count: 2, snap_count: 12,
base_size_kb: 1200, interval_hours: 168,
base_size_kb: 3072,
}, },
DemoOrbit { DemoOrbit {
slug: "matrix-synapse", slug: "matrix-synapse",
provider: "filesystem", provider: "filesystem",
config: serde_json::json!({ "paths": ["/var/matrix"] }), config: serde_json::json!({ "paths": ["/_tessera_demo/matrix"] }),
schedule: "0 2 * * *", schedule: "0 2 * * *",
decay: "month-of-weeklies", decay: "month-of-weeklies",
dry_run: false, dry_run: false,
status: "completed", status: "completed",
snap_count: 3, snap_count: 16,
base_size_kb: 540, interval_hours: 24,
base_size_kb: 768,
}, },
DemoOrbit { DemoOrbit {
slug: "home-assistant", slug: "home-assistant",
provider: "filesystem", provider: "filesystem",
config: serde_json::json!({ "paths": ["/config"] }), config: serde_json::json!({ "paths": ["/_tessera_demo/home-assistant"] }),
schedule: "0 */12 * * *", schedule: "0 */12 * * *",
decay: "week-of-dailies", decay: "week-of-dailies",
dry_run: false, dry_run: false,
status: "completed", status: "completed",
snap_count: 2, snap_count: 21,
base_size_kb: 45, interval_hours: 12,
base_size_kb: 64,
}, },
DemoOrbit { DemoOrbit {
slug: "deno-api", slug: "deno-api",
provider: "filesystem", provider: "filesystem",
config: serde_json::json!({ "paths": ["/app/deno"] }), config: serde_json::json!({ "paths": ["/_tessera_demo/deno"] }),
schedule: "0 5 * * *", schedule: "0 5 * * *",
decay: "week-of-dailies", decay: "week-of-dailies",
dry_run: false, dry_run: false,
status: "completed", status: "completed",
snap_count: 3, snap_count: 14,
base_size_kb: 96, interval_hours: 24,
base_size_kb: 192,
}, },
DemoOrbit { DemoOrbit {
slug: "mail-archive", slug: "mail-archive",
provider: "filesystem", provider: "filesystem",
config: serde_json::json!({ "paths": ["/mail/archive"] }), config: serde_json::json!({ "paths": ["/_tessera_demo/mail"] }),
schedule: "0 3 * * 6", schedule: "0 3 * * 6",
decay: "year-of-monthlies", decay: "year-of-monthlies",
dry_run: false, dry_run: false,
status: "completed", status: "failed",
snap_count: 2, snap_count: 12,
base_size_kb: 890, interval_hours: 168,
base_size_kb: 1792,
}, },
DemoOrbit { DemoOrbit {
slug: "rehearse-nightly", slug: "rehearse-nightly",
provider: "filesystem", provider: "filesystem",
config: serde_json::json!({ "paths": ["/tmp/rehearse"] }), config: serde_json::json!({ "paths": ["/_tessera_demo/rehearse"] }),
schedule: "0 2 * * *", schedule: "0 2 * * *",
decay: "week-of-dailies", decay: "week-of-dailies",
dry_run: true, dry_run: true,
status: "rehearsed", status: "rehearsed",
snap_count: 0, snap_count: 0,
interval_hours: 24,
base_size_kb: 0, base_size_kb: 0,
}, },
DemoOrbit { DemoOrbit {
slug: "observability-pg", slug: "observability-pg",
provider: "postgres", provider: "postgres",
config: serde_json::json!({ "connection_url": "postgres://demo/metrics" }), config: serde_json::json!({ "connection_url": "postgres://postgres.demo.invalid/metrics" }),
schedule: "0 1 * * *", schedule: "0 1 * * *",
decay: "month-of-weeklies", decay: "month-of-weeklies",
dry_run: false, dry_run: false,
status: "completed", status: "completed",
snap_count: 3, snap_count: 18,
base_size_kb: 180, interval_hours: 24,
base_size_kb: 896,
}, },
] ]
} }
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn demo_history_has_volume_and_preserves_capture_cadence() {
let orbits = demo_orbits();
assert_eq!(orbits.iter().filter(|orbit| !orbit.dry_run).count(), 11);
assert!(orbits.iter().map(|orbit| orbit.snap_count).sum::<usize>() >= 180);
for orbit in orbits {
if orbit.dry_run {
assert_eq!(orbit.snap_count, 0);
continue;
}
assert!(orbit.snapshot_age(0) > Duration::zero());
for index in 1..orbit.snap_count {
let gap = orbit.snapshot_age(index) - orbit.snapshot_age(index - 1);
assert!((gap - Duration::hours(orbit.interval_hours)).num_minutes().abs() < 45);
}
}
}
}

View File

@@ -31,3 +31,14 @@ uuid.workspace = true
hex.workspace = true hex.workspace = true
base64 = "0.22" base64 = "0.22"
indexmap = "=2.2.6" indexmap = "=2.2.6"
hyper = { version = "=1.12.0", features = ["server", "http1"] }
hyper-util = { version = "=0.1.21", features = ["tokio"] }
rustls = { version = "=0.23.23", default-features = false, features = ["ring", "std"] }
rustls-pemfile = "=2.2.0"
tokio-rustls = "=0.26.2"
tower = { workspace = true }
[dev-dependencies]
rcgen = "=0.13.2"
tempfile.workspace = true
tokio.workspace = true

View File

@@ -0,0 +1,135 @@
use axum::http::{HeaderMap, StatusCode};
use std::net::SocketAddr;
#[derive(Clone, Debug)]
pub struct AdminGate {
pub token: Option<String>,
}
impl AdminGate {
pub fn from_env() -> Self {
let token = std::env::var("TESSERA_ADMIN_TOKEN")
.ok()
.map(|value| value.trim().to_string())
.filter(|value| !value.is_empty());
Self { token }
}
pub fn log_policy(&self) {
if self.token.is_none() {
tracing::warn!(
"TESSERA_ADMIN_TOKEN is unset; snapshot, orbit, reconstitute, and pairing APIs are open to loopback clients only"
);
} else {
tracing::info!(
"TESSERA_ADMIN_TOKEN is set; backup APIs require that token from every client"
);
}
}
pub fn authorize(&self, peer: SocketAddr, headers: &HeaderMap) -> Result<(), StatusCode> {
let presented = presented_token(headers);
match &self.token {
Some(expected) => {
if presented.is_some_and(|value| tokens_match(expected, value)) {
Ok(())
} else {
Err(StatusCode::UNAUTHORIZED)
}
}
None if peer.ip().is_loopback() => Ok(()),
None => Err(StatusCode::UNAUTHORIZED),
}
}
}
fn presented_token(headers: &HeaderMap) -> Option<&str> {
if let Some(value) = headers
.get("x-tessera-admin-token")
.and_then(|value| value.to_str().ok())
{
let value = value.trim();
if !value.is_empty() {
return Some(value);
}
}
let header = headers.get("authorization")?.to_str().ok()?;
let token = header
.strip_prefix("Bearer ")
.or_else(|| header.strip_prefix("bearer "))?
.trim();
if token.is_empty() {
None
} else {
Some(token)
}
}
fn tokens_match(expected: &str, presented: &str) -> bool {
let expected = expected.as_bytes();
let presented = presented.as_bytes();
let mut diff = expected.len() ^ presented.len();
for (left, right) in expected.iter().zip(presented.iter()) {
diff |= (*left ^ *right) as usize;
}
diff == 0
}
#[cfg(test)]
mod tests {
use super::*;
use axum::http::HeaderValue;
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
fn peer(ip: IpAddr) -> SocketAddr {
SocketAddr::new(ip, 9)
}
#[test]
fn loopback_without_a_token_is_the_only_open_path() {
let gate = AdminGate { token: None };
let headers = HeaderMap::new();
assert!(gate
.authorize(peer(IpAddr::V4(Ipv4Addr::LOCALHOST)), &headers)
.is_ok());
assert!(gate
.authorize(peer(IpAddr::V6(Ipv6Addr::LOCALHOST)), &headers)
.is_ok());
assert!(gate
.authorize(peer(IpAddr::V4(Ipv4Addr::new(10, 1, 0, 4))), &headers)
.is_err());
}
#[test]
fn a_configured_token_is_required_on_loopback() {
let gate = AdminGate {
token: Some("secret-token".into()),
};
let mut headers = HeaderMap::new();
assert!(gate
.authorize(peer(IpAddr::V4(Ipv4Addr::LOCALHOST)), &headers)
.is_err());
headers.insert(
"authorization",
HeaderValue::from_static("Bearer secret-token"),
);
assert!(gate
.authorize(peer(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 8))), &headers)
.is_ok());
headers.remove("authorization");
headers.insert(
"x-tessera-admin-token",
HeaderValue::from_static("secret-token"),
);
assert!(gate
.authorize(peer(IpAddr::V4(Ipv4Addr::LOCALHOST)), &headers)
.is_ok());
headers.insert(
"x-tessera-admin-token",
HeaderValue::from_static("secret-tokem"),
);
assert!(gate
.authorize(peer(IpAddr::V4(Ipv4Addr::LOCALHOST)), &headers)
.is_err());
}
}

View File

@@ -6,22 +6,39 @@ use tessera_core::manifest::SnapshotManifest;
use tessera_providers::provider_from_config; use tessera_providers::provider_from_config;
use uuid::Uuid; use uuid::Uuid;
pub async fn run_orbit_internal(state: HubState, orbit_id: Uuid) -> Result<()> { pub async fn run_orbit_internal(state: HubState, orbit_id: Uuid) -> Result<Option<Uuid>> {
let orbits = state.db.list_orbits().await?; let orbits = state.db.list_orbits().await?;
let orbit = orbits let orbit = orbits
.into_iter() .into_iter()
.find(|o| o.id == orbit_id) .find(|o| o.id == orbit_id)
.context("orbit not found")?; .context("orbit not found")?;
run_orbit_row(state, orbit).await anyhow::ensure!(
state.active_orbits.lock().await.insert(orbit_id),
"orbit already running"
);
// Keep capture and its status update together if the requesting client disconnects.
tokio::spawn(async move {
let result = run_orbit_row(&state, orbit).await;
if result.is_err() {
if let Err(error) = state.db.set_orbit_status(orbit_id, "failed").await {
tracing::error!(%orbit_id, %error, "could not record failed capture");
}
}
state.active_orbits.lock().await.remove(&orbit_id);
result
})
.await?
} }
pub async fn run_orbit_row(state: HubState, orbit: OrbitRow) -> Result<()> { async fn run_orbit_row(state: &HubState, orbit: OrbitRow) -> Result<Option<Uuid>> {
state.db.set_orbit_status(orbit.id, "running").await?; state.db.set_orbit_status(orbit.id, "running").await?;
let provider_kind = match orbit.provider.as_str() { let provider_kind = match orbit.provider.as_str() {
"filesystem" => ProviderKind::Filesystem, "filesystem" => ProviderKind::Filesystem,
"postgres" => ProviderKind::Postgres, "postgres" => ProviderKind::Postgres,
_ => ProviderKind::Command, "command" => ProviderKind::Command,
other => anyhow::bail!("unknown provider '{other}'"),
}; };
let config: serde_json::Value = serde_json::from_str(&orbit.provider_config)?; let config: serde_json::Value = serde_json::from_str(&orbit.provider_config)?;
let provider = provider_from_config(&provider_kind, &config)?; let provider = provider_from_config(&provider_kind, &config)?;
@@ -42,13 +59,16 @@ pub async fn run_orbit_row(state: HubState, orbit: OrbitRow) -> Result<()> {
.snapshot(manifest, &capture.payload, orbit.dry_run) .snapshot(manifest, &capture.payload, orbit.dry_run)
.context("vault snapshot")?; .context("vault snapshot")?;
if !orbit.dry_run { let retained_snapshot = if orbit.dry_run {
let _pruned = vault.prune_with_decay(&orbit.decay_preset)?; None
} else {
let pruned = vault.prune_orbit_with_decay(orbit.id, &orbit.decay_preset)?;
state state
.db .db
.audit("decay.pruned", &format!("orbit={}", orbit.name)) .audit("decay.pruned", &format!("orbit={}", orbit.name))
.await?; .await?;
} (!pruned.contains(&snap.id)).then_some(snap.id)
};
let status = if orbit.dry_run { let status = if orbit.dry_run {
"rehearsed" "rehearsed"
@@ -67,5 +87,5 @@ pub async fn run_orbit_row(state: HubState, orbit: OrbitRow) -> Result<()> {
&format!("snapshot={}", snap.id), &format!("snapshot={}", snap.id),
) )
.await?; .await?;
Ok(()) Ok(retained_snapshot)
} }

View File

@@ -1,16 +1,20 @@
use crate::db::OrbitRow; use crate::db::OrbitRow;
use crate::state::{HubState, PairingEntry}; use crate::state::HubState;
use crate::upload::write_at;
use axum::{ use axum::{
extract::{Path, State}, extract::{ConnectInfo, Path, State},
http::{header, StatusCode, Uri}, http::{header, HeaderMap, HeaderValue, StatusCode, Uri},
response::IntoResponse, response::IntoResponse,
routing::{delete, get, post}, routing::{get, post},
Json, Router, Json, Router,
}; };
use base64::Engine; use base64::Engine;
use include_dir::{include_dir, Dir}; use include_dir::{include_dir, Dir};
use std::fs::OpenOptions;
use std::io::{Read, Seek, SeekFrom};
use std::net::SocketAddr;
use tessera_core::manifest::SnapshotManifest;
use tessera_core::reconstitute::{ReconstituteSession, ReconstituteState, RECONSTITUTE_GRACE_SECS}; use tessera_core::reconstitute::{ReconstituteSession, ReconstituteState, RECONSTITUTE_GRACE_SECS};
use tessera_core::wormhole::PairingState;
use tower_http::trace::TraceLayer; use tower_http::trace::TraceLayer;
use utoipa::OpenApi; use utoipa::OpenApi;
use uuid::Uuid; use uuid::Uuid;
@@ -49,6 +53,7 @@ struct ApiDoc;
#[derive(serde::Serialize, utoipa::ToSchema)] #[derive(serde::Serialize, utoipa::ToSchema)]
struct SnapshotSummary { struct SnapshotSummary {
id: Uuid, id: Uuid,
orbit_id: Uuid,
taken_at: chrono::DateTime<chrono::Utc>, taken_at: chrono::DateTime<chrono::Utc>,
orbit_name: String, orbit_name: String,
size_bytes: u64, size_bytes: u64,
@@ -108,6 +113,14 @@ struct ReconstituteStartResponse {
session: ReconstituteSession, session: ReconstituteSession,
} }
fn require_admin(
state: &HubState,
peer: SocketAddr,
headers: &HeaderMap,
) -> Result<(), StatusCode> {
state.admin.authorize(peer, headers)
}
pub fn router(state: HubState) -> Router { pub fn router(state: HubState) -> Router {
let api = Router::new() let api = Router::new()
.route("/health", get(health)) .route("/health", get(health))
@@ -140,13 +153,19 @@ async fn health() -> &'static str {
} }
#[utoipa::path(get, path = "/api/v1/snapshots", responses((status = 200, body = [SnapshotSummary])))] #[utoipa::path(get, path = "/api/v1/snapshots", responses((status = 200, body = [SnapshotSummary])))]
async fn list_snapshots(State(state): State<HubState>) -> Result<Json<Vec<SnapshotSummary>>, StatusCode> { async fn list_snapshots(
ConnectInfo(peer): ConnectInfo<SocketAddr>,
State(state): State<HubState>,
headers: HeaderMap,
) -> Result<Json<Vec<SnapshotSummary>>, StatusCode> {
require_admin(&state, peer, &headers)?;
let vault = state.vault.read().await; let vault = state.vault.read().await;
let snaps = vault.list_snapshots().map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; let snaps = vault.list_snapshots().map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
let out = snaps let out = snaps
.into_iter() .into_iter()
.map(|s| SnapshotSummary { .map(|s| SnapshotSummary {
id: s.id, id: s.id,
orbit_id: s.manifest.orbit_id,
taken_at: s.taken_at, taken_at: s.taken_at,
orbit_name: s.manifest.orbit_name, orbit_name: s.manifest.orbit_name,
size_bytes: s.size_bytes, size_bytes: s.size_bytes,
@@ -156,7 +175,12 @@ async fn list_snapshots(State(state): State<HubState>) -> Result<Json<Vec<Snapsh
} }
#[utoipa::path(get, path = "/api/v1/orbits", responses((status = 200, body = [OrbitRow])))] #[utoipa::path(get, path = "/api/v1/orbits", responses((status = 200, body = [OrbitRow])))]
async fn list_orbits(State(state): State<HubState>) -> Result<Json<Vec<OrbitRow>>, StatusCode> { async fn list_orbits(
ConnectInfo(peer): ConnectInfo<SocketAddr>,
State(state): State<HubState>,
headers: HeaderMap,
) -> Result<Json<Vec<OrbitRow>>, StatusCode> {
require_admin(&state, peer, &headers)?;
state state
.db .db
.list_orbits() .list_orbits()
@@ -167,9 +191,12 @@ async fn list_orbits(State(state): State<HubState>) -> Result<Json<Vec<OrbitRow>
#[utoipa::path(post, path = "/api/v1/orbits", request_body = CreateOrbitRequest, responses((status = 200, body = OrbitRow)))] #[utoipa::path(post, path = "/api/v1/orbits", request_body = CreateOrbitRequest, responses((status = 200, body = OrbitRow)))]
async fn create_orbit( async fn create_orbit(
ConnectInfo(peer): ConnectInfo<SocketAddr>,
State(state): State<HubState>, State(state): State<HubState>,
headers: HeaderMap,
Json(req): Json<CreateOrbitRequest>, Json(req): Json<CreateOrbitRequest>,
) -> Result<Json<OrbitRow>, StatusCode> { ) -> Result<Json<OrbitRow>, StatusCode> {
require_admin(&state, peer, &headers)?;
let row = OrbitRow { let row = OrbitRow {
id: Uuid::new_v4(), id: Uuid::new_v4(),
name: req.name, name: req.name,
@@ -186,22 +213,41 @@ async fn create_orbit(
Ok(Json(row)) Ok(Json(row))
} }
#[utoipa::path(post, path = "/api/v1/orbits/{id}/run", params(("id" = Uuid, Path, description = "orbit id")), responses((status = 204)))] #[utoipa::path(post, path = "/api/v1/orbits/{id}/run", params(("id" = Uuid, Path, description = "orbit id")), responses((status = 204, headers(("X-Tessera-Snapshot-Id" = Uuid, description = "New retained snapshot ID when a capture writes to the vault")))))]
async fn trigger_orbit( async fn trigger_orbit(
ConnectInfo(peer): ConnectInfo<SocketAddr>,
State(state): State<HubState>, State(state): State<HubState>,
headers: HeaderMap,
Path(id): Path<Uuid>, Path(id): Path<Uuid>,
) -> Result<StatusCode, StatusCode> { ) -> Result<(StatusCode, HeaderMap), (StatusCode, String)> {
crate::api::run_orbit_internal(state, id) require_admin(&state, peer, &headers).map_err(|status| (status, "unauthorized".into()))?;
let snapshot_id = crate::api::run_orbit_internal(state, id)
.await .await
.map(|_| StatusCode::NO_CONTENT) .map_err(|error| {
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR) tracing::warn!(orbit_id = %id, %error, "capture did not complete");
(StatusCode::INTERNAL_SERVER_ERROR, error.to_string())
})?;
let mut headers = HeaderMap::new();
if let Some(snapshot_id) = snapshot_id {
let value = HeaderValue::from_str(&snapshot_id.to_string()).map_err(|_| {
(
StatusCode::INTERNAL_SERVER_ERROR,
"snapshot id header".into(),
)
})?;
headers.insert("x-tessera-snapshot-id", value);
}
Ok((StatusCode::NO_CONTENT, headers))
} }
#[utoipa::path(post, path = "/api/v1/reconstitute", request_body = ReconstituteRequest, responses((status = 200, body = ReconstituteStartResponse)))] #[utoipa::path(post, path = "/api/v1/reconstitute", request_body = ReconstituteRequest, responses((status = 200, body = ReconstituteStartResponse)))]
async fn start_reconstitute( async fn start_reconstitute(
ConnectInfo(peer): ConnectInfo<SocketAddr>,
State(state): State<HubState>, State(state): State<HubState>,
headers: HeaderMap,
Json(req): Json<ReconstituteRequest>, Json(req): Json<ReconstituteRequest>,
) -> Result<Json<ReconstituteStartResponse>, StatusCode> { ) -> Result<Json<ReconstituteStartResponse>, StatusCode> {
require_admin(&state, peer, &headers)?;
let session_id = Uuid::new_v4(); let session_id = Uuid::new_v4();
let session = ReconstituteSession { let session = ReconstituteSession {
snapshot_id: req.snapshot_id, snapshot_id: req.snapshot_id,
@@ -230,22 +276,15 @@ async fn start_reconstitute(
} }
tokio::time::sleep(std::time::Duration::from_secs(1)).await; tokio::time::sleep(std::time::Duration::from_secs(1)).await;
} }
let aborted = {
let map = state_bg.reconstitute_sessions.read().await;
map.get(&session_id)
.map(|s| s.state == ReconstituteState::Aborted)
.unwrap_or(true)
};
if aborted {
return;
}
{ {
let mut map = state_bg.reconstitute_sessions.write().await; let mut map = state_bg.reconstitute_sessions.write().await;
if let Some(s) = map.get_mut(&session_id) { let Some(s) = map.get_mut(&session_id) else { return };
if s.state == ReconstituteState::Aborted {
return;
}
s.state = ReconstituteState::Restoring; s.state = ReconstituteState::Restoring;
s.seconds_remaining = 0; s.seconds_remaining = 0;
} }
}
let dest = std::path::PathBuf::from(&target); let dest = std::path::PathBuf::from(&target);
let result = { let result = {
let vault = state_bg.vault.read().await; let vault = state_bg.vault.read().await;
@@ -269,17 +308,23 @@ async fn start_reconstitute(
} }
async fn reconstitute_status( async fn reconstitute_status(
ConnectInfo(peer): ConnectInfo<SocketAddr>,
State(state): State<HubState>, State(state): State<HubState>,
headers: HeaderMap,
Path(id): Path<Uuid>, Path(id): Path<Uuid>,
) -> Result<Json<ReconstituteSession>, StatusCode> { ) -> Result<Json<ReconstituteSession>, StatusCode> {
require_admin(&state, peer, &headers)?;
let map = state.reconstitute_sessions.read().await; let map = state.reconstitute_sessions.read().await;
map.get(&id).cloned().map(Json).ok_or(StatusCode::NOT_FOUND) map.get(&id).cloned().map(Json).ok_or(StatusCode::NOT_FOUND)
} }
async fn abort_reconstitute( async fn abort_reconstitute(
ConnectInfo(peer): ConnectInfo<SocketAddr>,
State(state): State<HubState>, State(state): State<HubState>,
headers: HeaderMap,
Path(id): Path<Uuid>, Path(id): Path<Uuid>,
) -> Result<StatusCode, StatusCode> { ) -> Result<StatusCode, StatusCode> {
require_admin(&state, peer, &headers)?;
let mut map = state.reconstitute_sessions.write().await; let mut map = state.reconstitute_sessions.write().await;
if let Some(s) = map.get_mut(&id) { if let Some(s) = map.get_mut(&id) {
if matches!( if matches!(
@@ -294,7 +339,12 @@ async fn abort_reconstitute(
} }
#[utoipa::path(post, path = "/api/v1/wormhole/pairing", responses((status = 200, body = PairingResponse)))] #[utoipa::path(post, path = "/api/v1/wormhole/pairing", responses((status = 200, body = PairingResponse)))]
async fn pairing_start(State(state): State<HubState>) -> Json<PairingResponse> { async fn pairing_start(
ConnectInfo(peer): ConnectInfo<SocketAddr>,
State(state): State<HubState>,
headers: HeaderMap,
) -> Result<Json<PairingResponse>, StatusCode> {
require_admin(&state, peer, &headers)?;
let code: String = (0..6) let code: String = (0..6)
.map(|_| { .map(|_| {
let n = rand::random::<u8>() % 36; let n = rand::random::<u8>() % 36;
@@ -308,14 +358,16 @@ async fn pairing_start(State(state): State<HubState>) -> Json<PairingResponse> {
let expires = chrono::Utc::now() + chrono::Duration::minutes(10); let expires = chrono::Utc::now() + chrono::Duration::minutes(10);
let outpost_id = Uuid::new_v4(); let outpost_id = Uuid::new_v4();
let upload_token = hex::encode(Uuid::new_v4().as_bytes()); let upload_token = hex::encode(Uuid::new_v4().as_bytes());
state.pairing_codes.write().await.push(PairingEntry { state
code: code.clone(), .db
expires_at: expires, .insert_wormhole_token(
state: PairingState::CodeShown, &upload_token,
outpost_id, &outpost_id.to_string(),
upload_token: upload_token.clone(), &code,
}); &expires.to_rfc3339(),
Json(PairingResponse { code, expires_at: expires }) )
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
Ok(Json(PairingResponse { code, expires_at: expires }))
} }
#[utoipa::path(post, path = "/api/v1/wormhole/claim", request_body = ClaimRequest, responses((status = 200, body = ClaimResponse)))] #[utoipa::path(post, path = "/api/v1/wormhole/claim", request_body = ClaimRequest, responses((status = 200, body = ClaimResponse)))]
@@ -323,23 +375,28 @@ async fn pairing_claim(
State(state): State<HubState>, State(state): State<HubState>,
Json(req): Json<ClaimRequest>, Json(req): Json<ClaimRequest>,
) -> Result<Json<ClaimResponse>, StatusCode> { ) -> Result<Json<ClaimResponse>, StatusCode> {
let mut codes = state.pairing_codes.write().await; let now = chrono::Utc::now().to_rfc3339();
let now = chrono::Utc::now(); let claimed = state
let entry = codes .db
.iter_mut() .claim_wormhole_code(&req.code, &req.outpost_name, &now)
.find(|c| c.code == req.code && c.expires_at > now) .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?
.ok_or(StatusCode::GONE)?; .ok_or(StatusCode::GONE)?;
entry.state = PairingState::Active; let hub_url = std::env::var("TESSERA_PUBLIC_URL").unwrap_or_else(|_| {
let hub_url = if state.wormhole_mtls {
std::env::var("TESSERA_PUBLIC_URL").unwrap_or_else(|_| "http://127.0.0.1:8787".into()); "https://127.0.0.1:8788".into()
} else {
"http://127.0.0.1:8787".into()
}
});
state state
.db .db
.audit("wormhole.paired", &req.outpost_name) .audit("wormhole.paired", &req.outpost_name)
.await .await
.ok(); .ok();
let outpost_id = Uuid::parse_str(&claimed.1).map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
Ok(Json(ClaimResponse { Ok(Json(ClaimResponse {
outpost_id: entry.outpost_id, outpost_id,
upload_token: entry.upload_token.clone(), upload_token: claimed.0,
hub_url, hub_url,
})) }))
} }
@@ -350,16 +407,26 @@ async fn wormhole_upload_init(
headers: axum::http::HeaderMap, headers: axum::http::HeaderMap,
Json(body): Json<UploadInit>, Json(body): Json<UploadInit>,
) -> Result<Json<serde_json::Value>, StatusCode> { ) -> Result<Json<serde_json::Value>, StatusCode> {
verify_upload_token(&state, &headers).await?; verify_upload_token(&state, &headers)?;
let total = body.total_bytes.ok_or(StatusCode::BAD_REQUEST)?;
let session_id = Uuid::new_v4(); let session_id = Uuid::new_v4();
state state
.db .db
.insert_upload_session( .insert_upload_session(
&session_id.to_string(), &session_id.to_string(),
&body.orbit_id.to_string(), &body.orbit_id.to_string(),
body.total_bytes.map(|t| t as i64), Some(i64::try_from(total).map_err(|_| StatusCode::BAD_REQUEST)?),
) )
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
if total == 0 {
let seal = state
.db
.record_range(&session_id.to_string(), 0, 0, 0)
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
if seal {
seal_upload(&state, session_id, body.orbit_id, Vec::new()).await?;
}
}
Ok(Json(serde_json::json!({ "session_id": session_id }))) Ok(Json(serde_json::json!({ "session_id": session_id })))
} }
@@ -369,39 +436,141 @@ async fn wormhole_upload_chunk(
headers: axum::http::HeaderMap, headers: axum::http::HeaderMap,
Json(body): Json<UploadChunk>, Json(body): Json<UploadChunk>,
) -> Result<StatusCode, StatusCode> { ) -> Result<StatusCode, StatusCode> {
verify_upload_token(&state, &headers).await?; verify_upload_token(&state, &headers)?;
let session = state
.db
.upload_session(&body.session_id.to_string())
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?
.ok_or(StatusCode::NOT_FOUND)?;
if session.sealed {
return Err(StatusCode::CONFLICT);
}
let data = base64::engine::general_purpose::STANDARD let data = base64::engine::general_purpose::STANDARD
.decode(&body.data_b64) .decode(&body.data_b64)
.map_err(|_| StatusCode::BAD_REQUEST)?; .map_err(|_| StatusCode::BAD_REQUEST)?;
let tmp = state.data_dir.join("wormhole").join(format!("{}.part", body.session_id)); let path = upload_part_path(&state, body.session_id);
if let Some(parent) = tmp.parent() { if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent).ok(); std::fs::create_dir_all(parent).map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
} }
use std::io::Write; let mut file = OpenOptions::new()
let mut file = std::fs::OpenOptions::new()
.create(true) .create(true)
.append(true) .read(true)
.open(&tmp) .write(true)
.open(&path)
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
file.write_all(&data).map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; restrict_part(&path);
let range = write_at(&mut file, body.offset, &data, session.total).map_err(|error| {
if error.kind() == std::io::ErrorKind::InvalidInput {
StatusCode::BAD_REQUEST
} else {
StatusCode::INTERNAL_SERVER_ERROR
}
})?;
let seal = state
.db
.record_range(
&body.session_id.to_string(),
range.start,
range.end,
session.total,
)
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
if seal {
let mut bytes = Vec::new();
file.seek(SeekFrom::Start(0))
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
file.read_to_end(&mut bytes)
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
if (bytes.len() as u64) < session.total {
let _ = state.db.mark_upload_unsealed(&body.session_id.to_string());
return Err(StatusCode::INTERNAL_SERVER_ERROR);
}
bytes.truncate(session.total as usize);
if let Err(status) = seal_upload(&state, body.session_id, session.orbit_id, bytes).await {
let _ = state.db.mark_upload_unsealed(&body.session_id.to_string());
return Err(status);
}
let _ = std::fs::remove_file(&path);
}
Ok(StatusCode::NO_CONTENT) Ok(StatusCode::NO_CONTENT)
} }
async fn verify_upload_token( fn upload_part_path(state: &HubState, session_id: Uuid) -> std::path::PathBuf {
state: &HubState, state
headers: &axum::http::HeaderMap, .data_dir
) -> Result<(), StatusCode> { .join("wormhole")
.join(format!("{session_id}.part"))
}
fn restrict_part(path: &std::path::Path) {
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
let _ = std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600));
}
#[cfg(not(unix))]
let _ = path;
}
fn verify_upload_token(state: &HubState, headers: &HeaderMap) -> Result<(), StatusCode> {
if !state.accept_plain_upload {
return Err(StatusCode::FORBIDDEN);
}
let token = headers let token = headers
.get("x-tessera-upload-token") .get("x-tessera-upload-token")
.and_then(|v| v.to_str().ok()) .and_then(|v| v.to_str().ok())
.ok_or(StatusCode::UNAUTHORIZED)?; .ok_or(StatusCode::UNAUTHORIZED)?;
if state.upload_token_valid(token).await { if state.upload_token_valid(token) {
Ok(()) Ok(())
} else { } else {
Err(StatusCode::UNAUTHORIZED) Err(StatusCode::UNAUTHORIZED)
} }
} }
async fn seal_upload(
state: &HubState,
session_id: Uuid,
orbit_id: Uuid,
bytes: Vec<u8>,
) -> Result<(), StatusCode> {
let orbits = state
.db
.list_orbits()
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
let orbit = orbits.into_iter().find(|orbit| orbit.id == orbit_id);
let orbit_name = orbit
.as_ref()
.map(|orbit| orbit.name.clone())
.unwrap_or_else(|| orbit_id.to_string());
let decay = orbit
.as_ref()
.map(|orbit| orbit.decay_preset.clone())
.unwrap_or_else(|| "week-of-dailies".into());
let manifest = SnapshotManifest {
snapshot_id: Uuid::new_v4(),
orbit_id,
orbit_name,
labels: vec!["wormhole".into()],
provider: "wormhole".into(),
paths: vec![],
restore_hints: serde_json::json!({ "session_id": session_id }),
};
let snap_id = {
let mut vault = state.vault.write().await;
let snap = vault
.snapshot(manifest, &bytes, false)
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
let _ = vault.prune_orbit_with_decay(orbit_id, &decay);
snap.id
};
let _ = state
.db
.audit("wormhole.sealed", &format!("snapshot={snap_id}"))
.await;
Ok(())
}
async fn spa_fallback(uri: Uri) -> impl IntoResponse { async fn spa_fallback(uri: Uri) -> impl IntoResponse {
let mut path = uri.path().trim_start_matches('/').to_string(); let mut path = uri.path().trim_start_matches('/').to_string();
if path.is_empty() { if path.is_empty() {

View File

@@ -66,8 +66,22 @@ impl Db {
total INTEGER, total INTEGER,
created_at TEXT NOT NULL created_at TEXT NOT NULL
); );
CREATE TABLE IF NOT EXISTS wormhole_tokens (
token TEXT PRIMARY KEY,
outpost_id TEXT NOT NULL,
code TEXT NOT NULL,
state TEXT NOT NULL,
expires_at TEXT NOT NULL,
outpost_name TEXT
);
CREATE TABLE IF NOT EXISTS upload_ranges (
session_id TEXT NOT NULL,
start_off INTEGER NOT NULL,
end_off INTEGER NOT NULL
);
"#, "#,
)?; )?;
ensure_column(&conn, "upload_sessions", "sealed", "INTEGER NOT NULL DEFAULT 0")?;
Ok(()) Ok(())
} }
@@ -137,9 +151,156 @@ impl Db {
) -> Result<()> { ) -> Result<()> {
let conn = self.conn.lock().unwrap(); let conn = self.conn.lock().unwrap();
conn.execute( conn.execute(
"INSERT INTO upload_sessions (id, orbit_id, offset, total, created_at) VALUES (?1, ?2, 0, ?3, datetime('now'))", "INSERT INTO upload_sessions (id, orbit_id, offset, total, sealed, created_at) VALUES (?1, ?2, 0, ?3, 0, datetime('now'))",
params![id, orbit_id, total], params![id, orbit_id, total],
)?; )?;
Ok(()) Ok(())
} }
pub fn insert_wormhole_token(
&self,
token: &str,
outpost_id: &str,
code: &str,
expires_at: &str,
) -> Result<()> {
let conn = self.conn.lock().unwrap();
conn.execute(
"INSERT INTO wormhole_tokens (token, outpost_id, code, state, expires_at) VALUES (?1, ?2, ?3, 'code_shown', ?4)",
params![token, outpost_id, code, expires_at],
)?;
Ok(())
}
pub fn claim_wormhole_code(
&self,
code: &str,
outpost_name: &str,
now: &str,
) -> Result<Option<(String, String)>> {
let conn = self.conn.lock().unwrap();
let changed = conn.execute(
"UPDATE wormhole_tokens SET state = 'active', outpost_name = ?2 WHERE code = ?1 AND state = 'code_shown' AND expires_at > ?3",
params![code, outpost_name, now],
)?;
if changed != 1 {
return Ok(None);
}
let mut stmt = conn.prepare(
"SELECT token, outpost_id FROM wormhole_tokens WHERE code = ?1 AND state = 'active'",
)?;
let mut rows = stmt.query(params![code])?;
let Some(row) = rows.next()? else {
return Ok(None);
};
Ok(Some((row.get(0)?, row.get(1)?)))
}
pub fn upload_token_active(&self, token: &str) -> Result<bool> {
let conn = self.conn.lock().unwrap();
let mut stmt = conn.prepare(
"SELECT 1 FROM wormhole_tokens WHERE token = ?1 AND state = 'active' LIMIT 1",
)?;
Ok(stmt.query_row(params![token], |_| Ok(())).is_ok())
}
pub fn upload_session(&self, id: &str) -> Result<Option<UploadSession>> {
let conn = self.conn.lock().unwrap();
let mut stmt = conn.prepare(
"SELECT orbit_id, total, sealed FROM upload_sessions WHERE id = ?1",
)?;
let mut rows = stmt.query(params![id])?;
let Some(row) = rows.next()? else {
return Ok(None);
};
let orbit_id: String = row.get(0)?;
let total: Option<i64> = row.get(1)?;
let sealed: i64 = row.get(2)?;
Ok(Some(UploadSession {
orbit_id: Uuid::parse_str(&orbit_id).map_err(|e| anyhow::anyhow!(e))?,
total: total.unwrap_or(0).max(0) as u64,
sealed: sealed != 0,
}))
}
/// Records a received range. Returns whether this call won the right to seal.
pub fn record_range(&self, session_id: &str, start: u64, end: u64, total: u64) -> Result<bool> {
let conn = self.conn.lock().unwrap();
conn.execute_batch("BEGIN IMMEDIATE")?;
let outcome = (|| -> Result<bool> {
let sealed: i64 = conn.query_row(
"SELECT sealed FROM upload_sessions WHERE id = ?1",
params![session_id],
|row| row.get(0),
)?;
if sealed != 0 {
return Ok(false);
}
conn.execute(
"INSERT INTO upload_ranges (session_id, start_off, end_off) VALUES (?1, ?2, ?3)",
params![session_id, start as i64, end as i64],
)?;
let mut stmt =
conn.prepare("SELECT start_off, end_off FROM upload_ranges WHERE session_id = ?1")?;
let ranges = stmt
.query_map(params![session_id], |row| {
Ok(crate::upload::ByteRange {
start: row.get::<_, i64>(0)? as u64,
end: row.get::<_, i64>(1)? as u64,
})
})?
.collect::<Result<Vec<_>, _>>()?;
let covered = crate::upload::contiguous_from_zero(&ranges);
conn.execute(
"UPDATE upload_sessions SET offset = ?2 WHERE id = ?1",
params![session_id, covered as i64],
)?;
if covered >= total {
conn.execute(
"UPDATE upload_sessions SET sealed = 1 WHERE id = ?1 AND sealed = 0",
params![session_id],
)?;
return Ok(true);
}
Ok(false)
})();
match outcome {
Ok(value) => {
conn.execute_batch("COMMIT")?;
Ok(value)
}
Err(error) => {
let _ = conn.execute_batch("ROLLBACK");
Err(error)
}
}
}
pub fn mark_upload_unsealed(&self, session_id: &str) -> Result<()> {
let conn = self.conn.lock().unwrap();
conn.execute(
"UPDATE upload_sessions SET sealed = 0 WHERE id = ?1",
params![session_id],
)?;
Ok(())
}
}
#[derive(Debug, Clone)]
pub struct UploadSession {
pub orbit_id: Uuid,
pub total: u64,
pub sealed: bool,
}
fn ensure_column(conn: &Connection, table: &str, column: &str, decl: &str) -> Result<()> {
let mut stmt = conn.prepare(&format!("PRAGMA table_info({table})"))?;
let names = stmt.query_map([], |row| row.get::<_, String>(1))?;
for name in names {
if name? == column {
return Ok(());
}
}
conn.execute(&format!("ALTER TABLE {table} ADD COLUMN {column} {decl}"), [])?;
Ok(())
} }

View File

@@ -1,7 +1,10 @@
mod admin;
mod api; mod api;
mod db; mod db;
mod mtls;
mod scheduler; mod scheduler;
mod state; mod state;
mod upload;
use anyhow::Result; use anyhow::Result;
use state::HubState; use state::HubState;
@@ -15,10 +18,22 @@ async fn main() -> Result<()> {
.init(); .init();
let data_dir = std::env::var("TESSERA_DATA_DIR").unwrap_or_else(|_| "./data".into()); let data_dir = std::env::var("TESSERA_DATA_DIR").unwrap_or_else(|_| "./data".into());
let listen = std::env::var("TESSERA_LISTEN").unwrap_or_else(|_| "0.0.0.0:8787".into()); let listen = std::env::var("TESSERA_LISTEN").unwrap_or_else(|_| "127.0.0.1:8787".into());
let vault_pass = std::env::var("TESSERA_VAULT_PASSPHRASE").unwrap_or_else(|_| "dev-vault-key".into()); let vault_pass = std::env::var("TESSERA_VAULT_PASSPHRASE")
.ok()
.filter(|value| !value.is_empty())
.ok_or_else(|| {
anyhow::anyhow!(
"TESSERA_VAULT_PASSPHRASE is required and must be non-empty. Tessera does not ship a default passphrase."
)
})?;
if vault_pass == "dev-vault-key" {
tracing::warn!(
"TESSERA_VAULT_PASSPHRASE is the old published example. New vaults refuse it; set a private passphrase."
);
}
let state = HubState::bootstrap(&data_dir, &vault_pass).await?; let mut state = HubState::bootstrap(&data_dir, &vault_pass).await?;
if std::env::var("TESSERA_SEED_DEMO") if std::env::var("TESSERA_SEED_DEMO")
.map(|v| v == "1" || v == "true") .map(|v| v == "1" || v == "true")
@@ -26,8 +41,9 @@ async fn main() -> Result<()> {
{ {
match tessera_demo::apply(std::path::Path::new(&data_dir), &vault_pass, false) { match tessera_demo::apply(std::path::Path::new(&data_dir), &vault_pass, false) {
Ok(r) if !r.skipped => { Ok(r) if !r.skipped => {
tracing::info!( tracing::warn!(
"demo seed: {} orbits, {} snapshots", "TESSERA_SEED_DEMO wrote demo backup history into {}: {} orbits, {} snapshots",
data_dir,
r.orbits, r.orbits,
r.snapshots r.snapshots
); );
@@ -41,11 +57,37 @@ async fn main() -> Result<()> {
} }
scheduler::start_orbit_scheduler(state.clone()).await?; scheduler::start_orbit_scheduler(state.clone()).await?;
state.admin.log_policy();
if let Some(wormhole) = mtls::from_env()? {
state.wormhole_mtls = true;
state.accept_plain_upload = false;
let mut tls_state = state.clone();
tls_state.accept_plain_upload = true;
let listen_addr = wormhole.listen;
let tls_app = api::router(tls_state);
tokio::spawn(async move {
if let Err(error) = mtls::serve(wormhole, tls_app).await {
tracing::error!("wormhole mTLS stopped: {error:#}");
}
});
tracing::info!("plain HTTP uploads are closed; wormhole clients use {listen_addr}");
}
let admin_token_unset = state.admin.token.is_none();
let app = api::router(state); let app = api::router(state);
let addr: SocketAddr = listen.parse()?; let addr: SocketAddr = listen.parse()?;
if addr.ip().is_unspecified() && admin_token_unset {
tracing::warn!(
"listening on {addr}; backup APIs reject non-loopback clients until TESSERA_ADMIN_TOKEN is set"
);
}
tracing::info!("Tessera hub listening on {addr}"); tracing::info!("Tessera hub listening on {addr}");
let listener = tokio::net::TcpListener::bind(addr).await?; let listener = tokio::net::TcpListener::bind(addr).await?;
axum::serve(listener, app).await?; axum::serve(
listener,
app.into_make_service_with_connect_info::<SocketAddr>(),
)
.await?;
Ok(()) Ok(())
} }

View File

@@ -0,0 +1,145 @@
use anyhow::{Context, Result};
use axum::body::Body;
use axum::extract::Request;
use axum::response::Response;
use axum::Router;
use hyper::body::Incoming;
use hyper_util::rt::TokioIo;
use hyper_util::service::TowerToHyperService;
use rustls::pki_types::{CertificateDer, PrivateKeyDer};
use rustls::server::WebPkiClientVerifier;
use rustls::RootCertStore;
use rustls::ServerConfig;
use std::convert::Infallible;
use std::fs::File;
use std::future::Future;
use std::io::BufReader;
use std::net::SocketAddr;
use std::path::Path;
use std::pin::Pin;
use std::sync::Arc;
use std::task::{Context as TaskContext, Poll};
use tokio::net::TcpListener;
use tokio_rustls::TlsAcceptor;
use tower::{Service, ServiceExt};
pub struct WormholeMtls {
pub listen: SocketAddr,
cert: Vec<CertificateDer<'static>>,
key: PrivateKeyDer<'static>,
client_ca: RootCertStore,
}
pub fn from_env() -> Result<Option<WormholeMtls>> {
let raw = std::env::var("TESSERA_WORMHOLE_MTLS").unwrap_or_default();
let enabled = raw == "1" || raw.eq_ignore_ascii_case("true");
if !enabled {
return Ok(None);
}
let cert = std::env::var("TESSERA_WORMHOLE_CERT").context(
"TESSERA_WORMHOLE_CERT is required when TESSERA_WORMHOLE_MTLS is enabled",
)?;
let key = std::env::var("TESSERA_WORMHOLE_KEY").context(
"TESSERA_WORMHOLE_KEY is required when TESSERA_WORMHOLE_MTLS is enabled",
)?;
let ca = std::env::var("TESSERA_WORMHOLE_CLIENT_CA").context(
"TESSERA_WORMHOLE_CLIENT_CA is required when TESSERA_WORMHOLE_MTLS is enabled",
)?;
let listen = std::env::var("TESSERA_WORMHOLE_LISTEN")
.unwrap_or_else(|_| "127.0.0.1:8788".into())
.parse()
.context("TESSERA_WORMHOLE_LISTEN")?;
install_provider();
Ok(Some(WormholeMtls {
listen,
cert: load_certs(Path::new(&cert))?,
key: load_key(Path::new(&key))?,
client_ca: load_ca(Path::new(&ca))?,
}))
}
pub fn install_provider() {
let _ = rustls::crypto::ring::default_provider().install_default();
}
pub async fn serve(mtls: WormholeMtls, app: Router) -> Result<()> {
install_provider();
let verifier = WebPkiClientVerifier::builder(Arc::new(mtls.client_ca))
.build()
.map_err(|error| anyhow::anyhow!("wormhole client CA: {error}"))?;
let server = ServerConfig::builder()
.with_client_cert_verifier(verifier)
.with_single_cert(mtls.cert, mtls.key)
.map_err(|error| anyhow::anyhow!("wormhole certificate: {error}"))?;
let acceptor = TlsAcceptor::from(Arc::new(server));
let listener = TcpListener::bind(mtls.listen)
.await
.with_context(|| format!("bind wormhole mTLS {}", mtls.listen))?;
tracing::info!(
"wormhole mTLS listening on {}; a client certificate is required",
mtls.listen
);
loop {
let (tcp, _) = listener.accept().await.context("accept wormhole mTLS")?;
let acceptor = acceptor.clone();
let app = app.clone();
tokio::spawn(async move {
let Ok(tls) = acceptor.accept(tcp).await else {
return;
};
let io = TokioIo::new(tls);
let service = TowerToHyperService::new(HyperApp(app));
let _ = hyper::server::conn::http1::Builder::new()
.serve_connection(io, service)
.await;
});
}
}
#[derive(Clone)]
struct HyperApp(Router);
impl Service<Request<Incoming>> for HyperApp {
type Response = Response;
type Error = Infallible;
type Future = Pin<Box<dyn Future<Output = Result<Response, Infallible>> + Send>>;
fn poll_ready(&mut self, _cx: &mut TaskContext<'_>) -> Poll<Result<(), Infallible>> {
Poll::Ready(Ok(()))
}
fn call(&mut self, request: Request<Incoming>) -> Self::Future {
let app = self.0.clone();
Box::pin(async move {
Ok(app
.oneshot(request.map(Body::new))
.await
.unwrap_or_else(|error| match error {}))
})
}
}
pub fn load_certs(path: &Path) -> Result<Vec<CertificateDer<'static>>> {
let mut reader = BufReader::new(File::open(path).with_context(|| format!("open {}", path.display()))?);
rustls_pemfile::certs(&mut reader)
.collect::<Result<Vec<_>, _>>()
.context("parse certificate")
}
pub fn load_key(path: &Path) -> Result<PrivateKeyDer<'static>> {
let mut reader = BufReader::new(File::open(path).with_context(|| format!("open {}", path.display()))?);
rustls_pemfile::private_key(&mut reader)
.context("parse private key")?
.context("certificate file has no private key")
}
pub fn load_ca(path: &Path) -> Result<RootCertStore> {
let mut roots = RootCertStore::empty();
for cert in load_certs(path)? {
roots.add(cert).map_err(|error| anyhow::anyhow!("client CA: {error}"))?;
}
if roots.is_empty() {
anyhow::bail!("client CA file contained no certificates");
}
Ok(roots)
}

View File

@@ -1,12 +1,12 @@
use crate::admin::AdminGate;
use crate::db::Db; use crate::db::Db;
use anyhow::Result; use anyhow::Result;
use std::collections::HashMap; use std::collections::{HashMap, HashSet};
use std::path::PathBuf; use std::path::PathBuf;
use std::sync::Arc; use std::sync::Arc;
use tessera_core::reconstitute::ReconstituteSession; use tessera_core::reconstitute::ReconstituteSession;
use tessera_core::wormhole::PairingState;
use tessera_store::Vault; use tessera_store::Vault;
use tokio::sync::RwLock; use tokio::sync::{Mutex, RwLock};
use uuid::Uuid; use uuid::Uuid;
#[derive(Clone)] #[derive(Clone)]
@@ -15,17 +15,13 @@ pub struct HubState {
pub data_dir: PathBuf, pub data_dir: PathBuf,
pub vault_passphrase: String, pub vault_passphrase: String,
pub vault: Arc<RwLock<Vault>>, pub vault: Arc<RwLock<Vault>>,
pub pairing_codes: Arc<RwLock<Vec<PairingEntry>>>,
pub reconstitute_sessions: Arc<RwLock<HashMap<Uuid, ReconstituteSession>>>, pub reconstitute_sessions: Arc<RwLock<HashMap<Uuid, ReconstituteSession>>>,
} pub active_orbits: Arc<Mutex<HashSet<Uuid>>>,
pub admin: AdminGate,
#[derive(Clone)] pub wormhole_mtls: bool,
pub struct PairingEntry { /// Token uploads are accepted on this listener. Plain HTTP turns this off
pub code: String, /// when wormhole mTLS is required, so those routes are not a bypass.
pub expires_at: chrono::DateTime<chrono::Utc>, pub accept_plain_upload: bool,
pub state: PairingState,
pub outpost_id: Uuid,
pub upload_token: String,
} }
impl HubState { impl HubState {
@@ -48,13 +44,15 @@ impl HubState {
data_dir, data_dir,
vault_passphrase: vault_pass.to_string(), vault_passphrase: vault_pass.to_string(),
vault: Arc::new(RwLock::new(vault)), vault: Arc::new(RwLock::new(vault)),
pairing_codes: Arc::new(RwLock::new(Vec::new())),
reconstitute_sessions: Arc::new(RwLock::new(HashMap::new())), reconstitute_sessions: Arc::new(RwLock::new(HashMap::new())),
active_orbits: Arc::new(Mutex::new(HashSet::new())),
admin: AdminGate::from_env(),
wormhole_mtls: false,
accept_plain_upload: true,
}) })
} }
pub async fn upload_token_valid(&self, token: &str) -> bool { pub fn upload_token_valid(&self, token: &str) -> bool {
let codes = self.pairing_codes.read().await; self.db.upload_token_active(token).unwrap_or(false)
codes.iter().any(|c| c.upload_token == token && c.state == PairingState::Active)
} }
} }

View File

@@ -0,0 +1,79 @@
use std::fs::File;
use std::io::{self, Seek, SeekFrom, Write};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct ByteRange {
pub start: u64,
pub end: u64,
}
/// Bytes covered from offset 0 with no gap. Overlaps are merged.
pub fn contiguous_from_zero(ranges: &[ByteRange]) -> u64 {
let mut ordered: Vec<ByteRange> = ranges
.iter()
.copied()
.filter(|range| range.end > range.start)
.collect();
ordered.sort_by_key(|range| (range.start, range.end));
let mut covered = 0u64;
for range in ordered {
if range.start > covered {
break;
}
covered = covered.max(range.end);
}
covered
}
pub fn write_at(file: &mut File, offset: u64, data: &[u8], total: u64) -> io::Result<ByteRange> {
let end = offset.checked_add(data.len() as u64).ok_or_else(|| {
io::Error::new(io::ErrorKind::InvalidInput, "chunk offset overflows")
})?;
if end > total {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"chunk exceeds the declared upload size",
));
}
file.seek(SeekFrom::Start(offset))?;
file.write_all(data)?;
Ok(ByteRange { start: offset, end })
}
#[cfg(test)]
mod tests {
use super::*;
use tempfile::NamedTempFile;
#[test]
fn out_of_order_chunks_cover_the_object() {
assert_eq!(
contiguous_from_zero(&[ByteRange { start: 4, end: 8 }]),
0
);
assert_eq!(
contiguous_from_zero(&[
ByteRange { start: 4, end: 8 },
ByteRange { start: 0, end: 4 },
]),
8
);
assert_eq!(
contiguous_from_zero(&[
ByteRange { start: 0, end: 3 },
ByteRange { start: 2, end: 5 },
]),
5
);
}
#[test]
fn writes_honor_offset() {
let mut file = NamedTempFile::new().unwrap();
write_at(file.as_file_mut(), 3, b"def", 6).unwrap();
write_at(file.as_file_mut(), 0, b"abc", 6).unwrap();
assert!(write_at(file.as_file_mut(), 4, b"xyz", 6).is_err());
let bytes = std::fs::read(file.path()).unwrap();
assert_eq!(&bytes[..6], b"abcdef");
}
}

View File

@@ -26,6 +26,8 @@ pub fn provider_from_config(kind: &ProviderKind, config: &Value) -> Result<Box<d
match kind { match kind {
ProviderKind::Filesystem => Ok(Box::new(FilesystemProvider::from_config(config)?)), ProviderKind::Filesystem => Ok(Box::new(FilesystemProvider::from_config(config)?)),
ProviderKind::Postgres => Ok(Box::new(PostgresProvider::from_config(config)?)), ProviderKind::Postgres => Ok(Box::new(PostgresProvider::from_config(config)?)),
ProviderKind::Command => anyhow::bail!("command provider not implemented in v1"), ProviderKind::Command => anyhow::bail!(
"command provider is outside this release; use filesystem or postgres"
),
} }
} }

View File

@@ -3,6 +3,9 @@ use anyhow::{Context, Result};
use async_trait::async_trait; use async_trait::async_trait;
use serde::Deserialize; use serde::Deserialize;
use serde_json::json; use serde_json::json;
use std::fs::{self, OpenOptions};
use std::io::Write;
use std::path::{Path, PathBuf};
use std::process::Stdio; use std::process::Stdio;
use tessera_core::config::ProviderKind; use tessera_core::config::ProviderKind;
use tokio::process::Command; use tokio::process::Command;
@@ -22,6 +25,25 @@ pub struct PostgresProvider {
config: PostgresConfig, config: PostgresConfig,
} }
#[derive(Debug)]
struct PgTarget {
host: String,
port: String,
user: String,
password: String,
dbname: String,
}
struct PgpassFile {
path: PathBuf,
}
impl Drop for PgpassFile {
fn drop(&mut self) {
let _ = fs::remove_file(&self.path);
}
}
impl PostgresProvider { impl PostgresProvider {
pub fn from_config(config: &serde_json::Value) -> Result<Self> { pub fn from_config(config: &serde_json::Value) -> Result<Self> {
let config: PostgresConfig = serde_json::from_value(config.clone())?; let config: PostgresConfig = serde_json::from_value(config.clone())?;
@@ -29,6 +51,110 @@ impl PostgresProvider {
} }
} }
fn percent_decode(input: &str) -> Result<String> {
let bytes = input.as_bytes();
let mut out = Vec::with_capacity(bytes.len());
let mut index = 0;
while index < bytes.len() {
if bytes[index] == b'%' && index + 2 < bytes.len() {
let hex = std::str::from_utf8(&bytes[index + 1..index + 3]).ok();
if let Some(hex) = hex {
if let Ok(value) = u8::from_str_radix(hex, 16) {
out.push(value);
index += 3;
continue;
}
}
}
out.push(bytes[index]);
index += 1;
}
String::from_utf8(out).context("connection url is not utf-8")
}
fn parse_postgres_url(url: &str) -> Result<PgTarget> {
let rest = url
.strip_prefix("postgres://")
.or_else(|| url.strip_prefix("postgresql://"))
.context("postgres connection_url must start with postgres:// or postgresql://")?;
let (userinfo, hostpart) = rest.split_once('@').context("connection url is missing userinfo")?;
let (user, password) = userinfo
.split_once(':')
.context("connection url is missing a password")?;
let (hostport, dbpath) = hostpart.split_once('/').context("connection url is missing a database")?;
let dbname = dbpath.split('?').next().unwrap_or(dbpath);
let (host, port) = if let Some(host) = hostport.strip_prefix('[') {
let (host, port) = host
.split_once("]:")
.context("ipv6 connection url is missing a port")?;
(host.to_string(), port.to_string())
} else if let Some((host, port)) = hostport.split_once(':') {
(host.to_string(), port.to_string())
} else {
(hostport.to_string(), "5432".into())
};
if host.is_empty() || dbname.is_empty() {
anyhow::bail!("connection url is missing a host or database");
}
Ok(PgTarget {
host,
port,
user: percent_decode(user)?,
password: percent_decode(password)?,
dbname: percent_decode(dbname)?,
})
}
fn escape_pgpass(value: &str) -> String {
value.replace('\\', "\\\\").replace(':', "\\:")
}
fn write_pgpass(target: &PgTarget) -> Result<PgpassFile> {
let path = std::env::temp_dir().join(format!(
"tessera-pgpass-{}-{}",
std::process::id(),
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_nanos())
.unwrap_or(0)
));
let mut file = OpenOptions::new()
.write(true)
.create_new(true)
.open(&path)
.context("create pgpass file")?;
restrict_secret_file(&path)?;
let line = format!(
"{}:{}:{}:{}:{}\n",
escape_pgpass(&target.host),
escape_pgpass(&target.port),
escape_pgpass(&target.dbname),
escape_pgpass(&target.user),
escape_pgpass(&target.password)
);
file.write_all(line.as_bytes())?;
Ok(PgpassFile { path })
}
fn restrict_secret_file(path: &Path) -> Result<()> {
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
fs::set_permissions(path, fs::Permissions::from_mode(0o600))?;
}
#[cfg(not(unix))]
let _ = path;
Ok(())
}
fn dump_args(format: &str) -> Result<Vec<String>> {
match format {
"custom" => Ok(vec!["-Fc".into(), "-w".into()]),
"plain" => Ok(vec!["-w".into()]),
other => anyhow::bail!("unknown pg format: {other}"),
}
}
#[async_trait] #[async_trait]
impl BackupProvider for PostgresProvider { impl BackupProvider for PostgresProvider {
fn kind(&self) -> ProviderKind { fn kind(&self) -> ProviderKind {
@@ -36,17 +162,20 @@ impl BackupProvider for PostgresProvider {
} }
async fn capture(&self) -> Result<CaptureResult> { async fn capture(&self) -> Result<CaptureResult> {
let target = parse_postgres_url(&self.config.connection_url)?;
let args = dump_args(&self.config.format)?;
let pgpass = write_pgpass(&target)?;
let mut cmd = Command::new("pg_dump"); let mut cmd = Command::new("pg_dump");
cmd.arg(&self.config.connection_url); cmd.args(&args);
match self.config.format.as_str() { cmd.env("PGPASSFILE", &pgpass.path);
"custom" => { cmd.env("PGHOST", &target.host);
cmd.arg("-Fc"); cmd.env("PGPORT", &target.port);
} cmd.env("PGUSER", &target.user);
"plain" => {} cmd.env("PGDATABASE", &target.dbname);
other => anyhow::bail!("unknown pg format: {other}"), cmd.env_remove("PGPASSWORD");
}
cmd.stdout(Stdio::piped()).stderr(Stdio::piped()); cmd.stdout(Stdio::piped()).stderr(Stdio::piped());
let output = cmd.output().await.context("pg_dump failed to start")?; let output = cmd.output().await.context("pg_dump failed to start")?;
drop(pgpass);
if !output.status.success() { if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr); let stderr = String::from_utf8_lossy(&output.stderr);
anyhow::bail!("pg_dump failed: {stderr}"); anyhow::bail!("pg_dump failed: {stderr}");
@@ -56,8 +185,30 @@ impl BackupProvider for PostgresProvider {
labels: vec!["postgres".into()], labels: vec!["postgres".into()],
restore_hints: json!({ restore_hints: json!({
"format": self.config.format, "format": self.config.format,
"restore_command_hint": "pg_restore -d $DATABASE_URL dump.file" "restore_command_hint": "pg_restore -d \"$DATABASE_URL\" dump.file"
}), }),
}) })
} }
} }
#[cfg(test)]
mod tests {
use super::*;
use std::os::unix::fs::PermissionsExt;
#[test]
fn pg_dump_keeps_the_url_out_of_argv() {
let target = parse_postgres_url("postgres://migrator:s%3Acret@db.internal:5433/billing").unwrap();
assert_eq!(target.password, "s:cret");
let args = dump_args("custom").unwrap();
let pgpass = write_pgpass(&target).unwrap();
let rendered = fs::read_to_string(&pgpass.path).unwrap();
assert!(rendered.contains("s\\:cret"));
assert!(!args.iter().any(|arg| arg.contains("s:cret") || arg.contains("postgres://")));
let mode = fs::metadata(&pgpass.path).unwrap().permissions().mode() & 0o777;
assert_eq!(mode, 0o600);
let joined = args.join(" ");
assert!(!joined.contains(&target.password));
assert!(!joined.contains(&target.user));
}
}

View File

@@ -8,7 +8,7 @@ license.workspace = true
tessera-core = { path = "../tessera-core" } tessera-core = { path = "../tessera-core" }
anyhow.workspace = true anyhow.workspace = true
aes-gcm.workspace = true aes-gcm.workspace = true
pbkdf2.workspace = true argon2.workspace = true
hmac.workspace = true hmac.workspace = true
sha2.workspace = true sha2.workspace = true
chrono.workspace = true chrono.workspace = true

View File

@@ -1,10 +1,11 @@
use aes_gcm::aead::generic_array::GenericArray; use aes_gcm::aead::generic_array::GenericArray;
use aes_gcm::aead::{Aead, NewAead}; use aes_gcm::aead::Aead;
use aes_gcm::Aes256Gcm; use aes_gcm::{Aes256Gcm, KeyInit};
use anyhow::{anyhow, Result}; use anyhow::{anyhow, Result};
use hmac::Hmac; use argon2::{Algorithm, Argon2, Params, Version};
use pbkdf2::pbkdf2; use hmac::{Hmac, Mac};
use rand::RngCore; use rand::RngCore;
use serde::{Deserialize, Serialize};
use sha2::Sha256; use sha2::Sha256;
use std::fs; use std::fs;
use std::path::Path; use std::path::Path;
@@ -17,25 +18,37 @@ pub struct VaultKey {
} }
impl VaultKey { impl VaultKey {
/// Opens an existing key or creates one. A salt with no `kdf.json` stays
/// PBKDF2 so vaults created before Argon2id still open. A missing salt is a
/// new vault and uses Argon2id.
pub fn derive_from_passphrase(passphrase: &str, salt_path: &Path) -> Result<Self> { pub fn derive_from_passphrase(passphrase: &str, salt_path: &Path) -> Result<Self> {
let salt = if salt_path.exists() { if passphrase.is_empty() {
fs::read(salt_path)? anyhow::bail!("vault passphrase is required");
} else { }
let marker = salt_path.with_file_name("kdf.json");
if marker.exists() {
let spec: KdfSpec = serde_json::from_slice(&fs::read(&marker)?)?;
let salt = fs::read(salt_path)?;
restrict_secret_file(salt_path)?;
return derive_marked(passphrase, &salt, &spec);
}
if salt_path.exists() {
restrict_secret_file(salt_path)?;
let salt = fs::read(salt_path)?;
return cipher_from_key(&pbkdf2_key(passphrase, &salt));
}
let mut salt = [0u8; SALT_LEN]; let mut salt = [0u8; SALT_LEN];
rand::thread_rng().fill_bytes(&mut salt); rand::thread_rng().fill_bytes(&mut salt);
if let Some(parent) = salt_path.parent() { if let Some(parent) = salt_path.parent() {
fs::create_dir_all(parent)?; fs::create_dir_all(parent)?;
} }
fs::write(salt_path, &salt)?; fs::write(salt_path, &salt)?;
salt.to_vec() restrict_secret_file(salt_path)?;
}; let spec = KdfSpec::argon2id();
fs::write(&marker, serde_json::to_vec_pretty(&spec)?)?;
let mut key = [0u8; 32]; restrict_secret_file(&marker)?;
pbkdf2::<Hmac<Sha256>>(passphrase.as_bytes(), &salt, 100_000, &mut key); derive_marked(passphrase, &salt, &spec)
let cipher =
Aes256Gcm::new_from_slice(&key).map_err(|e| anyhow!("cipher key: {e}"))?;
Ok(Self { cipher })
} }
pub fn encrypt(&self, plaintext: &[u8]) -> Result<Vec<u8>> { pub fn encrypt(&self, plaintext: &[u8]) -> Result<Vec<u8>> {
@@ -63,6 +76,100 @@ impl VaultKey {
} }
} }
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
struct KdfSpec {
kdf: String,
#[serde(default = "default_m_kib")]
m_kib: u32,
#[serde(default = "default_t")]
t: u32,
#[serde(default = "default_p")]
p: u32,
}
fn default_m_kib() -> u32 {
19_456
}
fn default_t() -> u32 {
2
}
fn default_p() -> u32 {
1
}
impl KdfSpec {
fn argon2id() -> Self {
Self {
kdf: "argon2id".into(),
m_kib: default_m_kib(),
t: default_t(),
p: default_p(),
}
}
}
fn pbkdf2_key(passphrase: &str, salt: &[u8]) -> [u8; 32] {
pbkdf2_hmac_sha256(passphrase.as_bytes(), salt, 100_000)
}
fn pbkdf2_hmac_sha256(password: &[u8], salt: &[u8], iterations: u32) -> [u8; 32] {
// RFC 8018 PBKDF2-HMAC-SHA256, one block (dkLen = 32). This is the historical
// vault KDF, so existing salt files still open.
type HmacSha256 = Hmac<Sha256>;
let mut block = {
let mut mac =
<HmacSha256 as Mac>::new_from_slice(password).expect("hmac accepts any key length");
mac.update(salt);
mac.update(&1u32.to_be_bytes());
mac.finalize().into_bytes()
};
let mut derived = block;
for _ in 1..iterations {
let mut mac =
<HmacSha256 as Mac>::new_from_slice(password).expect("hmac accepts any key length");
mac.update(&block);
block = mac.finalize().into_bytes();
for (slot, byte) in derived.iter_mut().zip(block.iter()) {
*slot ^= *byte;
}
}
derived.into()
}
fn derive_marked(passphrase: &str, salt: &[u8], spec: &KdfSpec) -> Result<VaultKey> {
let key = match spec.kdf.as_str() {
"argon2id" => {
let params = Params::new(spec.m_kib, spec.t, spec.p, Some(32))
.map_err(|e| anyhow!("argon2 params: {e}"))?;
let argon = Argon2::new(Algorithm::Argon2id, Version::V0x13, params);
let mut key = [0u8; 32];
argon
.hash_password_into(passphrase.as_bytes(), salt, &mut key)
.map_err(|e| anyhow!("argon2id: {e}"))?;
key
}
"pbkdf2" => pbkdf2_key(passphrase, salt),
other => anyhow::bail!("unknown vault kdf: {other}"),
};
cipher_from_key(&key)
}
fn cipher_from_key(key: &[u8; 32]) -> Result<VaultKey> {
let cipher = Aes256Gcm::new_from_slice(key).map_err(|e| anyhow!("cipher key: {e}"))?;
Ok(VaultKey { cipher })
}
fn restrict_secret_file(path: &Path) -> Result<()> {
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
fs::set_permissions(path, fs::Permissions::from_mode(0o600))?;
}
#[cfg(not(unix))]
let _ = path;
Ok(())
}
pub fn content_id(data: &[u8]) -> String { pub fn content_id(data: &[u8]) -> String {
use sha2::Digest; use sha2::Digest;
hex::encode(Sha256::digest(data)) hex::encode(Sha256::digest(data))
@@ -76,6 +183,9 @@ pub fn pack_path(data_dir: &Path, id: &str) -> std::path::PathBuf {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
use aes_gcm::aead::generic_array::GenericArray;
use aes_gcm::aead::Aead;
use aes_gcm::{Aes256Gcm, KeyInit};
use tempfile::tempdir; use tempfile::tempdir;
#[test] #[test]
@@ -87,4 +197,63 @@ mod tests {
let plain = key.decrypt(&enc).unwrap(); let plain = key.decrypt(&enc).unwrap();
assert_eq!(plain, b"stardust"); assert_eq!(plain, b"stardust");
} }
#[test]
fn rejects_empty_passphrase() {
let dir = tempdir().unwrap();
let err = VaultKey::derive_from_passphrase("", &dir.path().join("salt"));
assert!(err.is_err());
}
#[cfg(unix)]
#[test]
fn salt_file_is_owner_only() {
use std::os::unix::fs::PermissionsExt;
let dir = tempdir().unwrap();
let salt = dir.path().join("salt");
VaultKey::derive_from_passphrase("test-vault", &salt).unwrap();
let mode = fs::metadata(&salt).unwrap().permissions().mode() & 0o777;
assert_eq!(mode, 0o600);
}
#[test]
fn new_vault_uses_argon2id() {
let dir = tempdir().unwrap();
let salt = dir.path().join("tessera.salt");
let key = VaultKey::derive_from_passphrase("test-vault", &salt).unwrap();
let marker: serde_json::Value =
serde_json::from_slice(&fs::read(dir.path().join("kdf.json")).unwrap()).unwrap();
assert_eq!(marker["kdf"], "argon2id");
let enc = key.encrypt(b"stardust").unwrap();
let raw_salt = fs::read(&salt).unwrap();
let legacy = pbkdf2_key("test-vault", &raw_salt);
let legacy_cipher = Aes256Gcm::new_from_slice(&legacy).unwrap();
let nonce = GenericArray::from_slice(&enc[..NONCE_LEN]);
assert!(legacy_cipher.decrypt(nonce, &enc[NONCE_LEN..]).is_err());
assert_eq!(key.decrypt(&enc).unwrap(), b"stardust");
}
#[test]
fn pbkdf2_matches_the_rfc_vector() {
let key = super::pbkdf2_hmac_sha256(b"password", b"salt", 4096);
assert_eq!(
hex::encode(key),
"c5e478d59288c841aa530db6845c4c8d962893a001ce4e11a4963873aa98134a"
);
}
#[test]
fn existing_pbkdf2_salt_still_opens() {
let dir = tempdir().unwrap();
let salt = dir.path().join("tessera.salt");
fs::write(&salt, b"0123456789abcdef").unwrap();
let key = VaultKey::derive_from_passphrase("test-vault", &salt).unwrap();
assert!(!dir.path().join("kdf.json").exists());
let enc = key.encrypt(b"legacy").unwrap();
let legacy = pbkdf2_key("test-vault", b"0123456789abcdef");
let legacy_cipher = Aes256Gcm::new_from_slice(&legacy).unwrap();
let nonce = GenericArray::from_slice(&enc[..NONCE_LEN]);
let plain = legacy_cipher.decrypt(nonce, &enc[NONCE_LEN..]).unwrap();
assert_eq!(plain, b"legacy");
}
} }

View File

@@ -28,11 +28,17 @@ pub struct Vault {
impl Vault { impl Vault {
pub fn init(root: impl AsRef<Path>, passphrase: &str) -> Result<Self> { pub fn init(root: impl AsRef<Path>, passphrase: &str) -> Result<Self> {
if passphrase == "dev-vault-key" {
anyhow::bail!(
"refusing to initialize a vault with the published dev passphrase; choose a private passphrase"
);
}
let root = root.as_ref().to_path_buf(); let root = root.as_ref().to_path_buf();
fs::create_dir_all(root.join("data"))?; fs::create_dir_all(root.join("data"))?;
fs::create_dir_all(root.join("snapshots"))?; fs::create_dir_all(root.join("snapshots"))?;
fs::create_dir_all(root.join("index"))?; fs::create_dir_all(root.join("index"))?;
fs::create_dir_all(root.join("keys"))?; fs::create_dir_all(root.join("keys"))?;
restrict_dir(&root.join("keys"))?;
let config_path = root.join("config"); let config_path = root.join("config");
if !config_path.exists() { if !config_path.exists() {
@@ -56,6 +62,7 @@ impl Vault {
if !root.join("config").exists() { if !root.join("config").exists() {
anyhow::bail!("vault not initialized"); anyhow::bail!("vault not initialized");
} }
restrict_dir(&root.join("keys"))?;
let salt = root.join("keys/tessera.salt"); let salt = root.join("keys/tessera.salt");
let key = VaultKey::derive_from_passphrase(passphrase, &salt)?; let key = VaultKey::derive_from_passphrase(passphrase, &salt)?;
let index = Self::load_index(&root)?; let index = Self::load_index(&root)?;
@@ -150,14 +157,28 @@ impl Vault {
tree_root: chunk_id, tree_root: chunk_id,
}; };
let plain = serde_json::to_vec(&snap)?;
let enc = self.key.encrypt(&plain)?;
let path = self let path = self
.root .root
.join("snapshots") .join("snapshots")
.join(format!("{}.json", snap.id)); .join(format!("{}.json.enc", snap.id));
fs::write(&path, serde_json::to_string_pretty(&snap)?)?; fs::write(&path, &enc)?;
Ok(snap) Ok(snap)
} }
fn read_snapshot_file(&self, path: &Path) -> Result<StoredSnapshot> {
let name = path.file_name().and_then(|s| s.to_str()).unwrap_or("");
if name.ends_with(".json.enc") {
let plain = self.key.decrypt(&fs::read(path)?)?;
Ok(serde_json::from_slice(&plain)?)
} else if name.ends_with(".json") {
Ok(serde_json::from_str(&fs::read_to_string(path)?)?)
} else {
anyhow::bail!("not a snapshot file");
}
}
pub fn list_snapshots(&self) -> Result<Vec<StoredSnapshot>> { pub fn list_snapshots(&self) -> Result<Vec<StoredSnapshot>> {
let dir = self.root.join("snapshots"); let dir = self.root.join("snapshots");
if !dir.exists() { if !dir.exists() {
@@ -166,21 +187,21 @@ impl Vault {
let mut out = Vec::new(); let mut out = Vec::new();
for entry in fs::read_dir(&dir)? { for entry in fs::read_dir(&dir)? {
let path = entry?.path(); let path = entry?.path();
if path.extension().and_then(|e| e.to_str()) != Some("json") { let name = path.file_name().and_then(|s| s.to_str()).unwrap_or("");
if !(name.ends_with(".json") || name.ends_with(".json.enc")) {
continue; continue;
} }
let data = fs::read_to_string(&path)?; out.push(self.read_snapshot_file(&path)?);
let snap: StoredSnapshot = serde_json::from_str(&data)?;
out.push(snap);
} }
out.sort_by(|a, b| b.taken_at.cmp(&a.taken_at)); out.sort_by(|a, b| b.taken_at.cmp(&a.taken_at));
Ok(out) Ok(out)
} }
pub fn restore_snapshot(&self, id: Uuid, dest: &Path) -> Result<u64> { pub fn restore_snapshot(&self, id: Uuid, dest: &Path) -> Result<u64> {
let path = self.root.join("snapshots").join(format!("{id}.json")); let enc = self.root.join("snapshots").join(format!("{id}.json.enc"));
let data = fs::read_to_string(&path).context("snapshot metadata")?; let plain = self.root.join("snapshots").join(format!("{id}.json"));
let snap: StoredSnapshot = serde_json::from_str(&data)?; let path = if enc.exists() { enc } else { plain };
let snap = self.read_snapshot_file(&path).context("snapshot metadata")?;
let bytes = self.read_chunk(&snap.tree_root)?; let bytes = self.read_chunk(&snap.tree_root)?;
if let Some(parent) = dest.parent() { if let Some(parent) = dest.parent() {
fs::create_dir_all(parent)?; fs::create_dir_all(parent)?;
@@ -192,9 +213,15 @@ impl Vault {
pub fn forget(&mut self, ids: &[Uuid]) -> Result<usize> { pub fn forget(&mut self, ids: &[Uuid]) -> Result<usize> {
let mut removed = 0; let mut removed = 0;
for id in ids { for id in ids {
let path = self.root.join("snapshots").join(format!("{id}.json")); let mut gone = false;
for suffix in [".json.enc", ".json"] {
let path = self.root.join("snapshots").join(format!("{id}{suffix}"));
if path.exists() { if path.exists() {
fs::remove_file(&path)?; fs::remove_file(&path)?;
gone = true;
}
}
if gone {
removed += 1; removed += 1;
} }
} }
@@ -202,10 +229,25 @@ impl Vault {
} }
pub fn prune_with_decay(&mut self, preset: &str) -> Result<Vec<Uuid>> { pub fn prune_with_decay(&mut self, preset: &str) -> Result<Vec<Uuid>> {
let policy = DecayPolicy::from_preset(preset);
let snaps = self.list_snapshots()?; let snaps = self.list_snapshots()?;
let refs: Vec<SnapshotRef> = snaps self.prune_snapshots(preset, snaps.into_iter())
.iter() }
pub fn prune_orbit_with_decay(&mut self, orbit_id: Uuid, preset: &str) -> Result<Vec<Uuid>> {
let snaps = self.list_snapshots()?;
self.prune_snapshots(
preset,
snaps.into_iter().filter(|s| s.manifest.orbit_id == orbit_id),
)
}
fn prune_snapshots(
&mut self,
preset: &str,
snapshots: impl Iterator<Item = StoredSnapshot>,
) -> Result<Vec<Uuid>> {
let policy = DecayPolicy::from_preset(preset);
let refs = snapshots
.map(|s| SnapshotRef { .map(|s| SnapshotRef {
id: s.id, id: s.id,
taken_at: s.taken_at, taken_at: s.taken_at,
@@ -221,6 +263,19 @@ impl Vault {
} }
} }
fn restrict_dir(path: &Path) -> Result<()> {
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
if path.exists() {
fs::set_permissions(path, fs::Permissions::from_mode(0o700))?;
}
}
#[cfg(not(unix))]
let _ = path;
Ok(())
}
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
@@ -268,4 +323,101 @@ mod tests {
vault.snapshot(manifest, b"x", true).unwrap(); vault.snapshot(manifest, b"x", true).unwrap();
assert!(vault.list_snapshots().unwrap().is_empty()); assert!(vault.list_snapshots().unwrap().is_empty());
} }
#[test]
fn orbit_decay_keeps_other_orbits_recoverable() {
let dir = tempdir().unwrap();
let mut vault = Vault::init(dir.path(), "secret").unwrap();
let orbit_id = Uuid::new_v4();
let other_id = Uuid::new_v4();
let now = DateTime::from_timestamp(1_730_000_000, 0).unwrap();
for (index, id) in [orbit_id, orbit_id, other_id].into_iter().enumerate() {
let manifest = SnapshotManifest {
snapshot_id: Uuid::new_v4(),
orbit_id: id,
orbit_name: "same name".into(),
labels: vec![],
provider: "filesystem".into(),
paths: vec![],
restore_hints: serde_json::json!({}),
};
vault
.snapshot_at(manifest, b"x", false, now - chrono::Duration::seconds(index as i64))
.unwrap();
}
let pruned = vault
.prune_orbit_with_decay(orbit_id, "month-of-weeklies")
.unwrap();
assert_eq!(pruned.len(), 1);
assert!(vault
.list_snapshots()
.unwrap()
.iter()
.any(|s| s.manifest.orbit_id == other_id));
}
#[test]
fn new_snapshots_are_encrypted_and_legacy_json_still_reads() {
let dir = tempdir().unwrap();
let mut vault = Vault::init(dir.path(), "secret").unwrap();
let legacy_id = Uuid::new_v4();
let legacy = StoredSnapshot {
id: legacy_id,
taken_at: DateTime::from_timestamp(1_700_000_000, 0).unwrap(),
manifest: SnapshotManifest {
snapshot_id: legacy_id,
orbit_id: Uuid::new_v4(),
orbit_name: "legacy".into(),
labels: vec![],
provider: "filesystem".into(),
paths: vec![],
restore_hints: serde_json::json!({}),
},
size_bytes: 4,
tree_root: "missing".into(),
};
fs::write(
dir.path().join("snapshots").join(format!("{legacy_id}.json")),
serde_json::to_string(&legacy).unwrap(),
)
.unwrap();
let manifest = SnapshotManifest {
snapshot_id: Uuid::new_v4(),
orbit_id: Uuid::new_v4(),
orbit_name: "new".into(),
labels: vec![],
provider: "filesystem".into(),
paths: vec![],
restore_hints: serde_json::json!({}),
};
let snap = vault.snapshot(manifest, b"cipher", false).unwrap();
assert!(dir
.path()
.join("snapshots")
.join(format!("{}.json.enc", snap.id))
.exists());
assert!(!dir
.path()
.join("snapshots")
.join(format!("{}.json", snap.id))
.exists());
let names: Vec<_> = vault
.list_snapshots()
.unwrap()
.into_iter()
.map(|s| s.manifest.orbit_name)
.collect();
assert!(names.contains(&"legacy".to_string()));
assert!(names.contains(&"new".to_string()));
let out = dir.path().join("restored.bin");
assert_eq!(vault.restore_snapshot(snap.id, &out).unwrap(), 6);
}
#[test]
fn init_rejects_published_dev_passphrase() {
let dir = tempdir().unwrap();
assert!(Vault::init(dir.path(), "dev-vault-key").is_err());
assert!(Vault::init(dir.path(), "").is_err());
}
} }

View File

@@ -64,7 +64,7 @@ Tessera is a self-hosted backup vault. This document is the contract for metapho
**Invariants** **Invariants**
- Only one active capture per orbit per vault at a time (hub enforces lock). - Only one active capture per orbit per vault at a time (hub enforces lock).
- Decay runs only after a **successful** non-dry-run seal. - Automatic decay runs only after a **successful** non-dry-run seal and applies to the captured orbit.
- Dry-run (“rehearse”) never writes snapshot metadata to the vault store. - Dry-run (“rehearse”) never writes snapshot metadata to the vault store.
--- ---
@@ -112,7 +112,7 @@ Tessera is a self-hosted backup vault. This document is the contract for metapho
│ issue device token + id │ │ issue device token + id │
│───────────────────────────────►│ │───────────────────────────────►│
│ │ │ │
│ mTLS or Bearer on upload API │ │ Bearer upload token on upload API │
│◄───────────────────────────────│ │◄───────────────────────────────│
``` ```
@@ -139,12 +139,13 @@ Tone: short sentences, metaphor in headings, facts in telemetry panels.
## Security baseline ## Security baseline
1. **Vault key:** Argon2id-derived key from passphrase; key file `keys/tessera.key` (mode 0600). Never logged. 1. **Vault key:** New vaults use Argon2id (19 MiB, time cost 2, parallelism 1). The salt is `keys/tessera.salt` (mode 0600) and the parameters are `keys/kdf.json`. A salt with no `kdf.json` stays PBKDF2-HMAC-SHA256, 100,000 iterations, so vaults created before Argon2id still open. The derived key is not stored. Never log the passphrase. New vaults refuse the published passphrase `dev-vault-key`. New snapshot metadata is AES-GCM ciphertext in `{id}.json.enc`. Existing plaintext `{id}.json` files still list and restore. Chunk index JSON stays plaintext.
2. **Hub auth (v1):** Local admin password → HTTP-only session cookie; hook point for OIDC later. 2. **Hub auth:** `TESSERA_ADMIN_TOKEN` is optional and local. When it is unset, the hub logs that snapshot, orbit list/create/run, reconstitute, and pairing routes are open to loopback peers only; every other peer gets 401. When it is set, every peer, including loopback, must send `Authorization: Bearer <token>` or `X-Tessera-Admin-Token`. The compare is constant time. `/health`, OpenAPI, wormhole claim, and wormhole upload are not on this gate. The default listen address is `127.0.0.1:8787`. The canvas does not send the token, so a token-protected hub and a Docker-published port (the peer inside the container is not loopback) will 401 those routes from the page. OIDC is not implemented.
3. **Agents:** No vault master key. Hub issues **scoped upload tokens** per outpost/orbit after pairing. 3. **Agents:** No vault master key. After pairing, the hub issues an upload token stored in SQLite. The token survives a hub restart. Claim is an atomic update of a pairing code that has not expired.
4. **Wormhole:** v1 token-based HTTPS upload; mTLS optional when `TESSERA_WORMHOLE_MTLS=1` and certs present. 4. **Wormhole:** Uploads require `total_bytes`. Chunks are written at `offset` into a mode `0600` `.part` file. When the recorded ranges cover the object from byte 0, the hub seals the bytes with `Vault::snapshot` (encrypted metadata), prunes decay, and deletes the `.part`. A later chunk on a sealed session is 409. `TESSERA_WORMHOLE_MTLS=1` (or `true`) starts a separate rustls listener that requires a client certificate. It needs `TESSERA_WORMHOLE_CERT`, `TESSERA_WORMHOLE_KEY`, and `TESSERA_WORMHOLE_CLIENT_CA`. `TESSERA_WORMHOLE_LISTEN` defaults to `127.0.0.1:8788`. While that listener is running, the plain HTTP upload routes return 403. An `https://` agent needs `TESSERA_WORMHOLE_CA`, `TESSERA_WORMHOLE_CLIENT_CERT`, and `TESSERA_WORMHOLE_CLIENT_KEY`.
5. **Control plane:** SQLite (`data/tessera.db`) holds metadata only—no backup payloads. 5. **Providers:** Filesystem and Postgres are in this release. The command provider is rejected with `command provider is outside this release; use filesystem or postgres`. Postgres parses `postgres://` or `postgresql://`, writes the password to a mode `0600` pgpass file, and passes `PGPASSFILE`, `PGHOST`, `PGPORT`, `PGUSER`, and `PGDATABASE`. The URL and password are not process arguments.
6. **Audit:** Pairing, reconstitute start/complete, decay prune logged to `audit_log` table. 6. **Control plane:** SQLite (`data/tessera.db`) holds metadata, pairing codes, upload tokens, and upload ranges — no backup payloads.
7. **Audit:** Pairing, wormhole seal, reconstitute start/complete, and decay prune are logged to `audit_log`.
--- ---

View File

@@ -1,32 +1,48 @@
# Tessera canvas — galaxy vault (Space Engine mode) # Tessera orbital vault
Diegetic **cockpit HUD** over a persistent **galaxy viewport**. The vault is a **black hole** at center; each **orbit** is a **star** on an elliptical path; **snapshots** are **moons** around that star (when locked). The persistent viewport maps backup jobs and recovery points. The black hole represents the vault. Stars represent orbits, and moons represent the latest snapshots of the selected orbit.
## Viewport modes ## Viewport and consoles
| Mode | Behavior | - **Flowing** animates the projected orbits and the black hole's accretion disk. Pause or resume from the map toolbar. The map eases to a stop before showing labels and moons in **Locked** mode. Selecting an orbit also locks the map. Reduced motion locks it immediately.
|------|----------| - Select a star or use the orbit register. The register prioritizes failed and active jobs and supports the up/down arrow keys. The inspector includes the capture action and full snapshot history.
| **Flowing** (default) | Stars orbit the singularity; accretion disk spins; moons hidden; targets not clickable | - The first three recovery points of the selected orbit appear as moons when the map has room. Select a moon or history entry to review the snapshot and start a restore. Escape closes the console. Restore countdown and polling continue if the console closes.
| **Locked** | Click **black hole** once — bodies ease into spaced slots and **stop**; star opens orbit console; moon opens snapshot tile | - Hub connectivity is separate from backup health. Capture targets the named orbit. An incoming meteor represents a confirmed new snapshot. Failures and rehearsals show text feedback.
- The map shows up to 55 overview orbits and reserves one slot for inspecting an orbit beyond that limit. The register provides access to every orbit. On narrow screens the map, register, and inspector stack vertically.
- **Big Screen** expands the map and keeps summary counts, motion controls, and a floating navigation dock. The browser can show it in native fullscreen. Use **Exit big screen** or Escape to return to the workspace.
- Drag the active navbar item sideways and release to open the destination. The regular navbar uses text and a sliding underline. The Big Screen dock uses labeled icons and a liquid highlight.
- The navbar stays available above the side panel so you can switch directly between consoles. In the regular workspace it becomes a floating text dock in the same top position. Big Screen keeps its icon dock at the bottom.
Click the **black hole** again to resume flow. HUD line under telemetry: green “flowing” / amber “locked”. ## Data and rendering
## HUD rail - The map preserves each orbit's assigned slot across polling updates. Layout and snapshot grouping live in `web/src/lib/galaxyLayout.ts`.
- Snapshot summaries carry `orbit_id`. When connected to an older hub, the UI groups by name only if the name is unique.
- Successful capture preserves HTTP 204 and supplies `X-Tessera-Snapshot-Id` when it retained a new snapshot. Automatic decay applies to that orbit's history.
- The scene uses SVG with static artwork and one animation clock. The clock pauses when the tab is hidden. Labels are laid out in screen coordinates.
Unchanged — ◎ ⟳ ◉ ◇ ↩ consoles; **Esc** dismisses. ## Animation guideline
## Data - Use the installed Framer Motion API from `motion/react`. Declarative `motion` components inherit the physics spring from `MotionConfig` in `web/src/main.tsx`. Imperative animations share `uiSpring` from `web/src/lib/motion.ts`. Tune stiffness, damping, and mass for the interaction.
- Keep the element, its React key, and its MotionValues stable while a target can change. Update the scalar `animate` target, call `animate(value, nextTarget, uiSpring)` on the same MotionValue, or call `.set(nextTarget)` on a `useSpring` value. Motion automatically replaces the active animation and inherits the live value and velocity. Leave `from`, `velocity`, and fixed timing options unset for these retargets. For colors and other compound styles, spring a numeric mix amount or progress value and derive the visual property from it.
- Keep `AnimatePresence` mounted and use a stable child key so a reopening element can reverse its exit. Make an exiting overlay inert and release its hit area immediately. Track direct manipulation one-to-one and seed the spring with release velocity when handing control over from an external gesture.
- Keep CSS state changes immediate. Use Motion springs for visual transitions, including hover and loading feedback. Reserve repeating springs for ambient indicators and give them a static state under reduced motion. For continuous simulation, keep the path on its existing clock and spring its speed or progress. A new event can start a distinct path at its own origin.
- Honor live changes to `prefers-reduced-motion`. The app applies declarative targets immediately. Imperative effects must stop and jump to the appropriate static state themselves. Verify reversals before settling, the final target, and reduced motion in a browser.
- Stars: `GET /api/v1/orbits` (status → star color) ## Local verification
- Moons: `GET /api/v1/snapshots` grouped by `orbit_name`, max 6 per star
## Demo Build the web UI before building the hub, which embeds the generated assets.
`TESSERA_DATA_DIR=... tessera seed-demo --force` for 12+ stars. ```sh
cd web
## Build npm ci
npm run typecheck
```bash npm test
cd web && npm run build npm run build
cargo build --release -p tessera-hub cd ..
cargo test --workspace --locked
cargo build --locked -p tessera-hub
``` ```
To preview a populated scene, start the hub with `TESSERA_SEED_DEMO=1` and a fresh temporary `TESSERA_DATA_DIR`. Open the vault and select an orbit with snapshots to review the locked layout.
The optional `web/scripts/capture-galaxy.mjs` screenshot helper uses a local Playwright and Chromium installation. It captures Flowing and Locked into the system temporary directory by default.

3
web/AGENTS.md Normal file
View File

@@ -0,0 +1,3 @@
# Web animation
Follow the [animation guideline](../docs/UI.md#animation-guideline) for component transitions and scene motion. Use the shared Framer Motion physics spring and retarget the same element or MotionValue so interruption preserves velocity.

View File

@@ -2,10 +2,13 @@
"name": "tessera-web", "name": "tessera-web",
"private": true, "private": true,
"version": "0.1.0", "version": "0.1.0",
"license": "AGPL-3.0-or-later",
"type": "module", "type": "module",
"scripts": { "scripts": {
"dev": "vite", "dev": "vite",
"build": "vite build", "build": "vite build",
"test": "node --experimental-strip-types --test scripts/galaxy.test.mjs",
"typecheck": "tsc --noEmit",
"preview": "vite preview" "preview": "vite preview"
}, },
"dependencies": { "dependencies": {

View File

@@ -1,21 +1,27 @@
import { tmpdir } from "node:os";
import { join } from "node:path";
import { chromium } from "playwright"; import { chromium } from "playwright";
const base = process.env.TESSERA_URL ?? "http://127.0.0.1:8787/"; const base = process.env.TESSERA_URL ?? "http://127.0.0.1:8787/";
const outFlow = const outFlow = process.env.FLOW_SHOT ?? join(tmpdir(), "tessera-galaxy-flowing.png");
process.env.FLOW_SHOT ?? "/cursor/stores/self/media/tessera-galaxy-flow-polish.png"; const outLock = process.env.LOCK_SHOT ?? join(tmpdir(), "tessera-galaxy-locked.png");
const outLock =
process.env.LOCK_SHOT ?? "/cursor/stores/self/media/tessera-galaxy-locked-polish.png";
const browser = await chromium.launch({ headless: true }); const browser = await chromium.launch({ headless: true });
const page = await browser.newPage({ viewport: { width: 1440, height: 900 } }); try {
await page.goto(base, { waitUntil: "networkidle", timeout: 30_000 }); const page = await browser.newPage({ viewport: { width: 1440, height: 900 } });
await page.waitForTimeout(2500); const [orbitResponse] = await Promise.all([
await page.screenshot({ path: outFlow, fullPage: false }); page.waitForResponse((response) => new URL(response.url()).pathname === "/api/v1/orbits" && response.ok()),
const svg = page.locator('[aria-label="Galaxy vault viewport"]'); page.goto(base),
const box = await svg.boundingBox(); ]);
if (!box) throw new Error("galaxy svg not found"); await page.getByText("Hub online", { exact: true }).waitFor();
await page.mouse.click(box.x + box.width / 2, box.y + box.height / 2); await page.screenshot({ path: outFlow });
await page.waitForTimeout(1400);
await page.screenshot({ path: outLock, fullPage: false }); const firstOrbit = page.locator(".register-row").first();
await browser.close(); if ((await orbitResponse.json()).length) await firstOrbit.click();
console.log("saved", outFlow, outLock); else await page.getByRole("button", { name: "Pause motion" }).click();
await page.getByRole("button", { name: "Resume motion" }).waitFor();
await page.screenshot({ path: outLock });
console.log("saved", outFlow, outLock);
} finally {
await browser.close();
}

View File

@@ -0,0 +1,64 @@
import assert from "node:assert/strict";
import test from "node:test";
import { assignOrbitSlots, orbitPose, groupSnapshots, moonPoses } from "../src/lib/galaxyLayout.ts";
import { placeLabels } from "../src/lib/galaxyLabelLayout.ts";
test("slot identities survive reordering, insertion and removal", () => {
const first = assignOrbitSlots(["a", "b", "c"]);
const next = assignOrbitSlots(["new", "c", "a"], first);
assert.equal(next.get("a"), first.get("a"));
assert.equal(next.get("c"), first.get("c"));
assert.equal(next.get("new"), first.get("b"));
});
test("overview fits 50 distinct orbits and promotes a selected orbit beyond capacity", () => {
const ids = Array.from({ length: 75 }, (_, i) => String(i));
const slots = assignOrbitSlots(ids);
assert.ok(slots.size >= 50);
assert.equal(new Set(slots.values()).size, slots.size);
const promoted = assignOrbitSlots(ids, slots, "74");
assert.ok(promoted.has("74"));
assert.equal(promoted.get("0"), slots.get("0"));
for (const slot of promoted.values()) {
const point = orbitPose(slot, 7);
assert.ok(Math.abs(point.x) < 320 && Math.abs(point.y) < 220);
}
});
test("snapshot ownership uses IDs and only falls back to an unambiguous name", () => {
const orbits = [
{ id: "a", name: "daily" }, { id: "b", name: "daily" }, { id: "c", name: "archive" },
];
const snapshot = (id, orbit_name, taken_at, orbit_id) =>
({ id, orbit_name, taken_at, orbit_id, size_bytes: 1 });
const groups = groupSnapshots(orbits, [
snapshot("old", "renamed", "2026-10-01", "a"),
snapshot("ambiguous", "daily", "2026-10-03"),
snapshot("new", "daily", "2026-10-03", "a"),
snapshot("legacy", "archive", "2026-10-02"),
snapshot("orphan", "archive", "2026-10-02", "deleted"),
]);
assert.deepEqual(groups.get("a").map((s) => s.id), ["new", "old"]);
assert.equal(groups.has("b"), false);
assert.deepEqual(groups.get("c").map((s) => s.id), ["legacy"]);
});
test("moon fan opens away from the vault and separates touch targets", () => {
const moons = moonPoses({ x: 150, y: 0 }, 3, 55);
assert.equal(moons.length, 3);
assert.ok(moons.every((p) => p.x > 150));
assert.ok(Math.hypot(moons[0].x - moons[1].x, moons[0].y - moons[1].y) >= 55);
const shifted = moonPoses({ x: 150, y: 0 }, 3, 55, moons);
assert.equal(shifted.length, 3);
assert.ok(shifted.every((moon) => moons.every((star) => Math.hypot(star.x - moon.x, star.y - moon.y) >= 14)));
});
test("labels respect screen bounds and preserve priority in a crowded scene", () => {
const candidates = [
{ id: "focused", x: 70, y: 60, width: 72 },
{ id: "other", x: 70, y: 60, width: 200 },
];
const labels = placeLabels(candidates, 140, 120, []);
assert.deepEqual(labels.map((l) => l.id), ["focused"]);
assert.ok(labels[0].x >= 0 && labels[0].x + 72 <= 140);
});

View File

@@ -1,209 +1,276 @@
import { useEffect, useMemo, useState } from "react"; import { useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
import { AnimatePresence } from "motion/react";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { import {
abortReconstitute, abortReconstitute, fetchHealth, fetchOrbits, fetchSnapshots, pollReconstitute,
fetchHealth, runOrbit, startReconstitute, type Orbit,
fetchOrbits,
fetchSnapshots,
pollReconstitute,
runOrbit,
startReconstitute,
} from "./api"; } from "./api";
import { vaultStatusFromOrbits } from "./lib/format";
import { DecayView } from "./components/decay/DecayView"; import { DecayView } from "./components/decay/DecayView";
import { OrbitInspector, OrbitRegister, TelemetryStrip } from "./components/hud/DiegeticHUD";
import { HUDPanel } from "./components/hud/HUDPanel";
import { HUDRail, type HUDMode } from "./components/hud/HUDRail";
import { OrbitsView } from "./components/orbits/OrbitsView"; import { OrbitsView } from "./components/orbits/OrbitsView";
import { WormholeView } from "./components/outposts/WormholeView"; import { WormholeView } from "./components/outposts/WormholeView";
import { ReconstituteWizard } from "./components/reconstitute/ReconstituteWizard"; import { ReconstituteWizard } from "./components/reconstitute/ReconstituteWizard";
import { VaultScene } from "./components/scene/VaultScene"; import { VaultScene } from "./components/scene/VaultScene";
import { SnapshotSheet } from "./components/vault/SnapshotSheet";
import {
CockpitFrame,
SnapshotsMiniList,
TelemetryStrip,
} from "./components/hud/DiegeticHUD";
import { HUDPanel, SceneAction } from "./components/hud/HUDPanel";
import { HUDRail, type HUDMode } from "./components/hud/HUDRail";
import { EmptyState } from "./components/ui/EmptyState"; import { EmptyState } from "./components/ui/EmptyState";
import { QueryGate } from "./components/ui/QueryGate"; import { QueryGate } from "./components/ui/QueryGate";
import { SpringPane } from "./components/ui/SpringPane";
import { SnapshotSheet } from "./components/vault/SnapshotSheet";
import { useReducedMotion } from "./hooks/useReducedMotion";
import { orbitStatus } from "./lib/format";
import { groupSnapshots } from "./lib/galaxyLayout";
const panelTitles: Record<HUDMode, string> = {
scene: "Vault",
orbits: "Orbit management",
wormhole: "Wormhole uplink",
decay: "Snapshot retention",
reconstitute: "Restore snapshot",
snapshot: "Snapshot detail",
};
function priority(orbit: Orbit) {
if (orbit.last_status === "failed") return 0;
return orbitStatus(orbit.last_status).busy ? 1 : 2;
}
export default function App() { export default function App() {
const app = useRef<HTMLDivElement>(null);
const workspaceScroll = useRef<number>(undefined);
const [bigScreen, setBigScreen] = useState(false);
const [mode, setMode] = useState<HUDMode>("scene"); const [mode, setMode] = useState<HUDMode>("scene");
const [selectedSnap, setSelectedSnap] = useState<string | null>(null); const panelOpen = mode !== "scene";
const [orbitId, setOrbitId] = useState<string>();
const [snapshotId, setSnapshotId] = useState<string | null>(null);
const [pairing, setPairing] = useState<{ code: string; expires_at: string } | null>(null); const [pairing, setPairing] = useState<{ code: string; expires_at: string } | null>(null);
const [galaxyFlowing, setGalaxyFlowing] = useState(true); const [play, setPlay] = useState(true);
const [capturePulse, setCapturePulse] = useState(0); const [restoreBusy, setRestoreBusy] = useState(false);
const [restoreTarget, setRestoreTarget] = useState<{ id: string | null }>();
const reducedMotion = useReducedMotion();
const qc = useQueryClient(); const qc = useQueryClient();
const health = useQuery({ useEffect(() => {
queryKey: ["health"], const root = app.current;
queryFn: fetchHealth, if (!root) return;
refetchInterval: 30_000, const syncFullscreen = () => setBigScreen(document.fullscreenElement === root);
retry: 1, root.addEventListener("fullscreenchange", syncFullscreen);
}); return () => root.removeEventListener("fullscreenchange", syncFullscreen);
const snaps = useQuery({ }, []);
queryKey: ["snapshots"],
queryFn: fetchSnapshots,
refetchInterval: 8_000,
});
const orbits = useQuery({
queryKey: ["orbits"],
queryFn: fetchOrbits,
refetchInterval: 8_000,
});
const vaultStatus = vaultStatusFromOrbits(orbits.data ?? []);
const hubOnline = health.isSuccess;
const totalBytes = useMemo(
() => (snaps.data ?? []).reduce((a, s) => a + s.size_bytes, 0),
[snaps.data],
);
const capturing =
orbits.data?.some((o) => o.last_status === "running") ?? false;
const capture = useMutation({
mutationFn: async () => {
const target = orbits.data?.[0];
if (!target) throw new Error("no-orbit");
await runOrbit(target.id);
},
onSuccess: () => qc.invalidateQueries({ queryKey: ["snapshots", "orbits"] }),
});
const selectedSnapshot = snaps.data?.find((s) => s.id === selectedSnap);
useEffect(() => { useEffect(() => {
const onKey = (e: KeyboardEvent) => { if (!bigScreen || mode !== "scene") return;
if (e.key === "Escape" && mode !== "scene") setMode("scene"); const exitOnEscape = (event: KeyboardEvent) => {
if (event.key === "Escape" && !event.defaultPrevented && !document.fullscreenElement) {
setBigScreen(false);
}
}; };
window.addEventListener("keydown", onKey); window.addEventListener("keydown", exitOnEscape);
return () => window.removeEventListener("keydown", onKey); return () => window.removeEventListener("keydown", exitOnEscape);
}, [mode]); }, [bigScreen, mode]);
const snapshotPanel = selectedSnapshot && mode === "scene"; useLayoutEffect(() => {
if (bigScreen || workspaceScroll.current === undefined) return;
window.scrollTo(0, workspaceScroll.current);
workspaceScroll.current = undefined;
}, [bigScreen]);
function toggleBigScreen() {
const root = app.current;
if (bigScreen) {
if (document.fullscreenElement === root) {
void document.exitFullscreen().catch(() => {});
} else {
setBigScreen(false);
}
return;
}
workspaceScroll.current = window.scrollY;
setBigScreen(true);
// The viewport layout also works when the browser declines native fullscreen.
if (document.fullscreenEnabled) void root?.requestFullscreen?.().catch(() => {});
}
const health = useQuery({ queryKey: ["health"], queryFn: fetchHealth, refetchInterval: 15_000, retry: 1 });
const snaps = useQuery({ queryKey: ["snapshots"], queryFn: fetchSnapshots, refetchInterval: 8_000, retry: 1 });
const orbits = useQuery({ queryKey: ["orbits"], queryFn: fetchOrbits, refetchInterval: 8_000, retry: 1 });
const capture = useMutation({
mutationFn: (target: Orbit) => runOrbit(target.id),
onSettled: () => {
void qc.invalidateQueries({ queryKey: ["orbits"] });
void qc.invalidateQueries({ queryKey: ["snapshots"] });
},
});
const online = health.isSuccess;
const activeId = capture.isPending ? capture.variables.id : undefined;
const sceneOrbits = useMemo(() => (orbits.data ?? []).map((orbit) =>
orbit.id === activeId ? { ...orbit, last_status: orbit.dry_run ? "rehearsing" : "running" } : orbit,
), [orbits.data, activeId]);
const register = useMemo(() => [...sceneOrbits].sort((a, b) => priority(a) - priority(b)), [sceneOrbits]);
const grouped = useMemo(() => groupSnapshots(orbits.data ?? [], snaps.data ?? []), [orbits.data, snaps.data]);
const totalBytes = useMemo(() => (snaps.data ?? []).reduce((sum, snap) => sum + snap.size_bytes, 0), [snaps.data]);
const selected = sceneOrbits.find(({ id }) => id === orbitId);
const history = (selected && grouped.get(selected.id)) ?? [];
const snapshot = snaps.data?.find(({ id }) => id === snapshotId);
const completedOrbitId = capture.isSuccess ? capture.variables.id : undefined;
const arrival = useMemo(() => !reducedMotion && completedOrbitId && capture.data
? { orbitId: completedOrbitId, snapshotId: capture.data }
: undefined, [reducedMotion, completedOrbitId, capture.data]);
const failedCount = sceneOrbits.filter(({ last_status }) => last_status === "failed").length;
const orbitMessage = orbits.isPending ? "Receiving orbit telemetry…" : orbits.isError
? orbits.data ? "Live telemetry unavailable. Showing last known orbits." : "Orbit telemetry unavailable."
: register.length ? undefined : "No backup jobs yet. Set up an orbit to begin.";
const snapshotMessage = snaps.isPending ? "Loading snapshot history…" : snaps.isError
? snaps.data ? "Showing last known snapshots." : "Snapshot history unavailable."
: history.length ? undefined : "This orbit has no snapshots yet.";
const captureLabel = capture.isPending ? capture.variables.dry_run ? "Rehearsing" : "Capturing"
: capture.isError ? "Capture failed for"
: capture.variables?.dry_run ? "Rehearsal complete for"
: capture.data ? "Snapshot secured from" : "Capture finished for";
const captureNotice = capture.variables && (
<p className={`capture-notice${capture.isError ? " tone-red" : ""}`} role="status">
{captureLabel} {capture.variables.name}{capture.isPending ? "…" : "."}
</p>
);
const noticeInInspector = !!selected && selected.id === capture.variables?.id;
function selectOrbit(id: string) {
setOrbitId(id);
setPlay(false);
}
function openSnapshot(id: string) {
document.getElementById(`snapshot-${id}`)?.focus({ preventScroll: true });
setSnapshotId(id);
setMode("snapshot");
}
function runCapture(target: Orbit) {
selectOrbit(target.id);
capture.mutate(target);
}
function openConsole(next: HUDMode, target: string | null = null) {
if (next === "reconstitute" && !restoreBusy &&
(!restoreTarget || (target !== null && target !== restoreTarget.id))) {
setRestoreTarget({ id: target });
}
setMode(next);
}
return ( return (
<div className="h-[100dvh] w-full overflow-hidden bg-space-950 text-star-100 relative"> <div ref={app} className={`vault-app${bigScreen ? " big-screen" : ""}`}>
<VaultScene <header className="vault-topbar">
orbits={orbits.data ?? []} <div className="vault-brand">
snapshots={snaps.data ?? []} <svg viewBox="0 0 38 38" width="34" height="34" aria-hidden="true">
flowing={galaxyFlowing} <circle cx="19" cy="19" r="10.5" fill="none" stroke="currentColor" opacity=".5" />
onToggleFlow={() => setGalaxyFlowing((f) => !f)} <ellipse cx="19" cy="19" rx="17" ry="5.8" transform="rotate(-32 19 19)" fill="none" stroke="currentColor" />
capturing={capturing || capture.isPending} <circle cx="19" cy="19" r="3" fill="currentColor" />
capturePulse={capturePulse} </svg>
selectedSnapshotId={selectedSnap} <div><strong>Tessera</strong><span>Backup control</span></div>
onSelect={(id) => setSelectedSnap(id)} </div>
onSelectOrbit={() => { <HUDRail active={mode === "snapshot" ? "scene" : mode} floating={bigScreen} panelOpen={panelOpen} reducedMotion={reducedMotion} onSelect={openConsole} />
setGalaxyFlowing(false); <p className="hub-link" role="status">
setMode("orbits"); <span className={`register-signal signal-${online ? "green" : "grey"}`} />
}} {online ? "Hub online" : health.isPending ? "Connecting" : "Hub offline"}
/> </p>
</header>
<CockpitFrame> <main className="vault-main" inert={panelOpen}>
<TelemetryStrip <div className="vault-overview">
status={vaultStatus} <div>
online={hubOnline} <p className="instrument-label overview-label"><span aria-hidden="true">◈</span> Vault / 01</p>
snapCount={snaps.data?.length ?? 0} <h1>Orbital vault</h1>
totalBytes={totalBytes} <p className="overview-copy">Backup jobs and recovery points</p>
/> </div>
<SnapshotsMiniList <TelemetryStrip orbitCount={orbits.data?.length} failedCount={failedCount} snapCount={snaps.data?.length} totalBytes={totalBytes} />
snapshots={snaps.data ?? []}
selected={selectedSnap}
onSelect={(id) => setSelectedSnap(id)}
/>
</CockpitFrame>
<div className="absolute bottom-24 left-1/2 -translate-x-1/2 z-30 flex gap-3 pointer-events-none">
<SceneAction
label={capture.isPending ? "ORBIT ACTIVE…" : "CAPTURE NOW"}
disabled={capture.isPending}
onClick={() => {
if (!(orbits.data?.length ?? 0)) setMode("orbits");
else {
setCapturePulse((n) => n + 1);
capture.mutate();
}
}}
/>
</div> </div>
<HUDRail active={mode} onSelect={setMode} capturing={capturing} /> <div className="vault-workspace">
<VaultScene
<HUDPanel orbits={sceneOrbits} selectedOrbitId={selected?.id} recentSnapshots={history.slice(0, 3)}
open={!!snapshotPanel} flowing={play && !reducedMotion} reducedMotion={reducedMotion} arrival={arrival}
title="Snapshot tile" bigScreen={bigScreen} onToggleBigScreen={toggleBigScreen}
subtitle="Point-in-time mass on the ring" onToggleFlow={() => setPlay((value) => !value)}
side="left" onSelectOrbit={(id) => {
onClose={() => setSelectedSnap(null)} selectOrbit(id);
> document.getElementById(`register-${id}`)?.focus({ preventScroll: true });
{selectedSnapshot && ( }}
<SnapshotSheet onSelectSnapshot={openSnapshot}
snap={selectedSnapshot}
onReconstitute={() => setMode("reconstitute")}
/> />
<OrbitRegister
orbits={register} selected={selected?.id} message={orbitMessage}
onSelect={selectOrbit} onManage={() => setMode("orbits")}
/>
<OrbitInspector
orbit={selected} snapshots={history} snapshotMessage={snapshotMessage}
onSelectSnapshot={openSnapshot}
capture={selected && (
<>
<button
type="button" className="console-control capture-button"
onClick={() => runCapture(selected)}
disabled={!online || capture.isPending || orbitStatus(selected.last_status).busy}
>
<span aria-hidden="true">↘</span>
<span>{selected.dry_run ? "Rehearse" : "Capture"} {selected.name}</span>
</button>
{noticeInInspector && mode !== "orbits" && captureNotice}
</>
)} )}
</HUDPanel> />
</div>
<footer className="vault-footer">
{(!noticeInInspector && mode !== "orbits" && captureNotice) || <p>Vault telemetry</p>}
<p role="status">{restoreBusy ? "Restore active · open Restore to monitor" : "Local backup station"}</p>
</footer>
</main>
<HUDPanel <HUDPanel
open={mode === "orbits"} open={panelOpen}
title="Orbit console" title={panelTitles[mode]}
subtitle="Schedule circles — not a spreadsheet" subtitle={mode === "reconstitute" ? "Review the destination before starting the restore." : undefined}
onClose={() => setMode("scene")} onClose={() => setMode("scene")}
> >
<QueryGate query={orbits} empty={<OrbitsView orbits={[]} />}> <AnimatePresence initial={false}>
{(data) => <OrbitsView orbits={data} />} {mode === "orbits" && (
<SpringPane key="orbits">
<QueryGate query={orbits}>
{() => <OrbitsView orbits={sceneOrbits} onRun={runCapture} captureDisabled={!online || capture.isPending} notice={captureNotice} />}
</QueryGate> </QueryGate>
</HUDPanel> </SpringPane>
<HUDPanel
open={mode === "wormhole"}
title="Wormhole uplink"
subtitle="Pair an outpost once"
onClose={() => setMode("scene")}
>
<WormholeView pairing={pairing} onPaired={setPairing} />
</HUDPanel>
<HUDPanel
open={mode === "decay"}
title="Decay field"
subtitle="What fades, on purpose"
onClose={() => setMode("scene")}
>
<DecayView
appliedPresets={(orbits.data ?? []).map(
(o) => o.decay_preset ?? "week-of-dailies",
)} )}
/> {mode === "wormhole" && (
</HUDPanel> <SpringPane key="wormhole"><WormholeView pairing={pairing} onPaired={setPairing} /></SpringPane>
)}
<HUDPanel {mode === "decay" && (
open={mode === "reconstitute"} <SpringPane key="decay"><DecayView appliedPresets={sceneOrbits.map((orbit) => orbit.decay_preset ?? "week-of-dailies")} /></SpringPane>
title="Reconstitute" )}
subtitle="12s grace — abort restores nothing" {mode === "snapshot" && (
side="bottom" <SpringPane key="snapshot">
onClose={() => setMode("scene")} {snapshot
> ? <SnapshotSheet snap={snapshot} onReconstitute={() => openConsole("reconstitute", snapshot.id)} />
{(snaps.data?.length ?? 0) === 0 ? ( : <EmptyState title="Snapshot unavailable" body="It may have expired under the retention policy." />}
<EmptyState </SpringPane>
title="No tiles to restore" )}
body="Capture an orbit first, then return here." </AnimatePresence>
<SpringPane active={mode === "reconstitute"}>
{restoreTarget && (snaps.data?.length || restoreBusy ? (
<ReconstituteWizard
key={restoreTarget.id ?? "manual"}
snapshots={snaps.data ?? []} selected={restoreTarget.id}
onStart={startReconstitute} onPoll={pollReconstitute} onAbort={abortReconstitute} onBusyChange={setRestoreBusy}
/> />
) : ( ) : (
<ReconstituteWizard <QueryGate query={snaps} empty={<EmptyState title="No snapshots to restore" body="Capture an orbit to create a recovery point." />}>
snapshots={snaps.data ?? []} {() => null}
selected={selectedSnap} </QueryGate>
onStart={startReconstitute} ))}
onPoll={pollReconstitute} </SpringPane>
onAbort={abortReconstitute}
/>
)}
</HUDPanel> </HUDPanel>
{capture.isError && (
<p className="absolute top-24 inset-x-0 text-center text-[10px] font-mono text-orbit-amber z-30">
NO ORBIT — OPEN ⟳ CONSOLE
</p>
)}
</div> </div>
); );
} }

View File

@@ -1,5 +1,6 @@
export type Snapshot = { export type Snapshot = {
id: string; id: string;
orbit_id?: string;
taken_at: string; taken_at: string;
orbit_name: string; orbit_name: string;
size_bytes: number; size_bytes: number;
@@ -25,12 +26,17 @@ export type CreateOrbitInput = {
dry_run: boolean; dry_run: boolean;
}; };
async function api<T>(path: string, init?: RequestInit): Promise<T> { async function request(path: string, init?: RequestInit): Promise<Response> {
const r = await fetch(path, init); const r = await fetch(path, init);
if (!r.ok) { if (!r.ok) {
const text = await r.text().catch(() => ""); const text = await r.text().catch(() => "");
throw new Error(text || `${path} failed`); throw new Error(text || `${path} failed`);
} }
return r;
}
async function api<T>(path: string, init?: RequestInit): Promise<T> {
const r = await request(path, init);
if (r.status === 204) return undefined as T; if (r.status === 204) return undefined as T;
return r.json(); return r.json();
} }
@@ -68,9 +74,9 @@ export async function startPairing(): Promise<{ code: string; expires_at: string
return api("/api/v1/wormhole/pairing", { method: "POST" }); return api("/api/v1/wormhole/pairing", { method: "POST" });
} }
export async function runOrbit(id: string, rehearse = false): Promise<void> { export async function runOrbit(id: string): Promise<string | null> {
await api(`/api/v1/orbits/${id}/run`, { method: "POST" }); const response = await request(`/api/v1/orbits/${id}/run`, { method: "POST" });
if (rehearse) return; return response.headers.get("X-Tessera-Snapshot-Id");
} }
export async function startReconstitute( export async function startReconstitute(
@@ -92,7 +98,8 @@ export async function abortReconstitute(sessionId: string): Promise<void> {
} }
export async function pollReconstitute(sessionId: string) { export async function pollReconstitute(sessionId: string) {
return api<{ state: string; seconds_remaining: number }>( const response = await fetch(`/api/v1/reconstitute/${sessionId}`);
`/api/v1/reconstitute/${sessionId}`, if (response.status === 404) return { state: "unavailable", seconds_remaining: 0 };
); if (!response.ok) throw new Error("Could not read restore status");
return response.json() as Promise<{ state: string; seconds_remaining: number }>;
} }

View File

@@ -1,89 +1,142 @@
import type { ReactNode } from "react"; import { AnimatePresence, motion } from "motion/react";
import type { VaultStatus } from "../../lib/format"; import type { KeyboardEvent, ReactNode } from "react";
import { StatusDot } from "../ui/StatusDot"; import type { Orbit, Snapshot } from "../../api";
import { formatBytes } from "../../lib/format"; import { useReducedMotion } from "../../hooks/useReducedMotion";
import type { Snapshot } from "../../api"; import { formatBytes, formatWhen, orbitStatus, schedulePhrase } from "../../lib/format";
import { SpringPane } from "../ui/SpringPane";
export function CockpitFrame({ children }: { children: ReactNode }) {
return (
<div className="absolute inset-0 pointer-events-none z-20">
<motionBorder />
<p className="absolute top-3 left-4 text-[10px] font-mono tracking-[0.35em] text-star-400/80 uppercase">
Tessera · orbital vault
</p>
<p className="absolute top-3 right-4 text-[10px] font-mono text-star-400/60">
SYS // VAULT-01
</p>
<div className="absolute bottom-3 left-4 right-4 h-px bg-gradient-to-r from-transparent via-wormhole-violet/40 to-transparent" />
<div className="vignette" />
<div className="scanlines" />
{children}
</div>
);
}
function motionBorder() {
return (
<>
<span className="absolute top-8 left-6 w-12 h-12 border-l-2 border-t-2 border-wormhole-violet/50 rounded-tl" />
<span className="absolute top-8 right-6 w-12 h-12 border-r-2 border-t-2 border-wormhole-violet/50 rounded-tr" />
<span className="absolute bottom-16 left-6 w-16 h-10 border-l-2 border-b-2 border-star-400/25 rounded-bl" />
<span className="absolute bottom-16 right-6 w-16 h-10 border-r-2 border-b-2 border-star-400/25 rounded-br" />
</>
);
}
export function TelemetryStrip({ export function TelemetryStrip({
status, orbitCount, failedCount, snapCount, totalBytes,
online,
snapCount,
totalBytes,
}: { }: {
status: VaultStatus; orbitCount?: number;
online: boolean; failedCount: number;
snapCount: number; snapCount?: number;
totalBytes: number; totalBytes: number;
}) { }) {
return ( return (
<div className="pointer-events-none absolute top-12 left-4 right-4 flex justify-between items-start gap-2 text-[11px] font-mono"> <dl className="vault-telemetry">
<div className="flex items-center gap-2 bg-space-950/50 backdrop-blur-sm border border-space-700/50 rounded px-2 py-1"> <div><dt>Orbits</dt><dd>{orbitCount ?? "—"}</dd></div>
<StatusDot status={online ? status : "grey"} size="sm" /> <div><dt>Failed</dt><dd className={failedCount ? "telemetry-alert" : ""}>{orbitCount === undefined ? "—" : failedCount}</dd></div>
<span className="text-star-300">{online ? "LINK OK" : "NO LINK"}</span> <div><dt>Snapshots</dt><dd>{snapCount ?? "—"}</dd></div>
</div> <div><dt>Payload</dt><dd>{snapCount === undefined ? "—" : formatBytes(totalBytes)}</dd></div>
<div className="text-right text-star-400/90 bg-space-950/40 px-2 py-1 rounded border border-space-800/40"> </dl>
<div>TILES {snapCount}</div>
<div className="text-[10px] opacity-70">{formatBytes(totalBytes)} mass</div>
</div>
</div>
); );
} }
export function SnapshotsMiniList({ export function OrbitRegister({
snapshots, orbits, selected, message, onSelect, onManage,
selected,
onSelect,
}: { }: {
snapshots: Snapshot[]; orbits: Orbit[];
selected: string | null; selected?: string;
message?: string;
onSelect: (id: string) => void; onSelect: (id: string) => void;
onManage: () => void;
}) { }) {
if (!snapshots.length) return null; const reducedMotion = useReducedMotion();
const active = orbits.some(({ id }) => id === selected) ? selected : orbits[0]?.id;
function moveFocus(event: KeyboardEvent<HTMLButtonElement>, index: number) {
const next = { ArrowUp: index - 1, ArrowDown: index + 1, Home: 0, End: orbits.length - 1 }[event.key];
if (next === undefined) return;
event.preventDefault();
const target = orbits[Math.min(orbits.length - 1, Math.max(0, next))];
onSelect(target.id);
document.getElementById(`register-${target.id}`)?.focus();
}
return ( return (
<div className="pointer-events-auto absolute left-4 bottom-24 max-w-[140px] space-y-1"> <section className="vault-console orbit-register" aria-labelledby="register-title">
{snapshots.slice(0, 4).map((s, i) => ( <header className="console-heading">
<p className="instrument-label">Flight register</p>
<h2 id="register-title">Orbits</h2>
</header>
{message && <p className="console-empty" role="status">{message}</p>}
<motion.ul className="register-list" layoutScroll>
{orbits.map((orbit, index) => {
const status = orbitStatus(orbit.last_status);
return (
<motion.li key={orbit.id} layout={reducedMotion ? false : "position"}>
<button <button
key={s.id}
type="button" type="button"
onClick={() => onSelect(s.id)} id={`register-${orbit.id}`}
className={`w-full text-left text-[10px] font-mono px-2 py-1 rounded border transition-colors ${ className="register-row"
selected === s.id aria-pressed={selected === orbit.id}
? "border-orbit-green/60 bg-orbit-green/10 text-orbit-green" tabIndex={active === orbit.id ? 0 : -1}
: "border-space-700/50 bg-space-950/60 text-star-400 hover:border-star-400/40" onClick={() => onSelect(orbit.id)}
}`} onKeyDown={(event) => moveFocus(event, index)}
> >
{String(i + 1).padStart(2, "0")} · {s.orbit_name.slice(0, 12)} <span className={`register-signal signal-${status.tone}`} aria-hidden="true" />
<span className="register-content">
<span title={orbit.name}>{orbit.name}</span>
<small>{orbit.provider}</small>
</span>
<span className={`register-state tone-${status.tone}`}>{status.label}</span>
</button>
</motion.li>
);
})}
</motion.ul>
<div className="console-bottom">
<button type="button" className="console-control" onClick={onManage}>
{orbits.length ? "Manage orbits" : "Set up an orbit"} <span aria-hidden="true">↗</span>
</button> </button>
))}
</div> </div>
</section>
);
}
export function OrbitInspector({
orbit, snapshots, snapshotMessage, capture, onSelectSnapshot,
}: {
orbit?: Orbit;
snapshots: Snapshot[];
snapshotMessage?: string;
capture?: ReactNode;
onSelectSnapshot: (id: string) => void;
}) {
const status = orbitStatus(orbit?.last_status ?? "idle");
return (
<section className="vault-console orbit-inspector" aria-labelledby="inspector-title">
<header className="console-heading">
<p className="instrument-label">Orbit detail</p>
<h2 id="inspector-title">{orbit?.name ?? "Select an orbit"}</h2>
{orbit && <p className={`inspector-state tone-${status.tone}`}><span className={`register-signal signal-${status.tone}`} />{status.label}</p>}
</header>
<div className="spring-stack inspector-stack">
<AnimatePresence initial={false}>
{orbit ? (
<SpringPane key={orbit.id}>
<p className="inspector-schedule">{schedulePhrase(orbit.schedule, orbit.dry_run)}</p>
<div className="inspector-capture">{capture}</div>
<section className="inspector-history" aria-label="Snapshot history">
<header>
<h3>Snapshot history</h3>
<span>{snapshots.length.toString().padStart(2, "0")}</span>
</header>
{snapshotMessage && <p className="console-empty" role="status">{snapshotMessage}</p>}
<ul>
{snapshots.map((snapshot, index) => (
<li key={snapshot.id}>
<button id={`snapshot-${snapshot.id}`} type="button" className="snapshot-row" onClick={() => onSelectSnapshot(snapshot.id)}>
<span className="snapshot-glyph" aria-hidden="true">◇</span>
<span>
<strong>{formatWhen(snapshot.taken_at)}</strong>
<small>{formatBytes(snapshot.size_bytes)}{index === 0 ? " · Latest" : ""}</small>
</span>
<span className="snapshot-arrow" aria-hidden="true">›</span>
</button>
</li>
))}
</ul>
</section>
</SpringPane>
) : (
<SpringPane key="empty">
<p className="console-empty">Choose a star on the map or an orbit in the register to inspect its status and recovery points.</p>
</SpringPane>
)}
</AnimatePresence>
</div>
</section>
); );
} }

View File

@@ -1,96 +1,82 @@
import { motion, AnimatePresence } from "motion/react"; import { motion } from "motion/react";
import type { ReactNode } from "react"; import { useEffect, useId, useLayoutEffect, useRef, type ReactNode } from "react";
export function HUDPanel({ export function HUDPanel({
open, open, title, subtitle, onClose, children,
title,
subtitle,
onClose,
children,
side = "right",
}: { }: {
open: boolean; open: boolean;
title: string; title: string;
subtitle?: string; subtitle?: string;
onClose: () => void; onClose: () => void;
children: ReactNode; children: ReactNode;
side?: "left" | "right" | "bottom";
}) { }) {
const pos = const panel = useRef<HTMLElement>(null);
side === "left" const heading = useRef<HTMLHeadingElement>(null);
? "left-0 top-12 bottom-20 w-[min(100%,380px)] border-r" const returnFocus = useRef<HTMLElement>(null);
: side === "bottom" const lastHeading = useRef({ title, subtitle });
? "inset-x-0 bottom-20 top-auto max-h-[55dvh] border-t" const labelId = useId();
: "right-0 top-12 bottom-20 w-[min(100%,400px)] border-l"; const descriptionId = useId();
useLayoutEffect(() => {
const focused = document.activeElement;
if (open) {
returnFocus.current = focused instanceof HTMLElement ? focused : null;
if (!focused?.closest(".vault-nav")) heading.current?.focus({ preventScroll: true });
} else if (returnFocus.current && (panel.current?.contains(focused) || focused === document.body)) {
const previous = returnFocus.current;
const target = previous.isConnected && previous !== document.body
? previous
: document.querySelector<HTMLElement>(".vault-nav button[aria-current]");
target?.focus({ preventScroll: true });
}
}, [open]);
useLayoutEffect(() => {
if (open) {
lastHeading.current = { title, subtitle };
panel.current?.scrollTo(0, 0);
}
}, [open, title, subtitle]);
useEffect(() => {
if (!open) return;
const closeOnEscape = (event: KeyboardEvent) => {
if (event.key !== "Escape" || event.defaultPrevented || event.repeat) return;
event.preventDefault();
onClose();
};
window.addEventListener("keydown", closeOnEscape);
return () => window.removeEventListener("keydown", closeOnEscape);
}, [open, onClose]);
const display = open ? { title, subtitle } : lastHeading.current;
return ( return (
<AnimatePresence> <div className="vault-overlay">
{open && ( <motion.div className="vault-scrim" aria-hidden="true" initial={false} animate={{ opacity: open ? 1 : 0 }} />
<>
<motion.button
type="button"
aria-label="Dismiss overlay"
className="fixed inset-0 z-40 bg-space-950/50 backdrop-blur-[2px]"
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={{ opacity: 0 }}
onClick={onClose}
/>
<motion.aside <motion.aside
className={`fixed z-50 ${pos} border-wormhole-violet/20 bg-space-900/92 backdrop-blur-xl overflow-y-auto scrollbar-none`} ref={panel}
initial={{ opacity: 0, x: side === "right" ? 40 : side === "left" ? -40 : 0, y: side === "bottom" ? 40 : 0 }} className="vault-dialog"
animate={{ opacity: 1, x: 0, y: 0 }} role="dialog"
exit={{ opacity: 0, x: side === "right" ? 20 : 0, y: side === "bottom" ? 20 : 0 }} aria-labelledby={labelId}
transition={{ type: "spring", damping: 26, stiffness: 280 }} aria-describedby={display.subtitle ? descriptionId : undefined}
aria-hidden={!open}
inert={!open}
initial={false}
animate={{ x: open ? "0%" : "100%" }}
> >
<header className="sticky top-0 bg-space-900/95 border-b border-space-700/60 px-4 py-3 flex items-start justify-between gap-3"> <header className="dialog-heading">
<div> <div>
<p className="text-[10px] font-mono text-wormhole-violet tracking-widest uppercase"> <p className="instrument-label">Vault console</p>
Console <h2 id={labelId} ref={heading} tabIndex={-1}>{display.title}</h2>
</p> {display.subtitle && <p id={descriptionId}>{display.subtitle}</p>}
<h2 className="text-lg font-semibold text-star-100">{title}</h2>
{subtitle && <p className="text-xs text-star-400 mt-0.5">{subtitle}</p>}
</div> </div>
<button <button type="button" className="console-control" onClick={onClose}>
type="button" Close <span aria-hidden="true">×</span>
onClick={onClose}
className="font-mono text-xs text-star-400 border border-space-700 rounded px-2 py-1 hover:text-star-200"
>
ESC
</button> </button>
</header> </header>
<div className="p-4 pb-8">{children}</div> <div className="dialog-content"><div className="spring-stack">{children}</div></div>
</motion.aside> </motion.aside>
</> </div>
)}
</AnimatePresence>
);
}
export function SceneAction({
label,
onClick,
disabled,
variant = "primary",
}: {
label: string;
onClick: () => void;
disabled?: boolean;
variant?: "primary" | "ghost";
}) {
return (
<motion.button
type="button"
disabled={disabled}
onClick={onClick}
className={`pointer-events-auto font-mono text-xs tracking-wide px-5 py-2.5 rounded border ${
variant === "primary"
? "border-orbit-green/50 text-orbit-green bg-orbit-green/10 hover:bg-orbit-green/20"
: "border-star-400/30 text-star-300 bg-space-950/60"
} disabled:opacity-40`}
whileTap={{ scale: 0.97 }}
>
{label}
</motion.button>
); );
} }

View File

@@ -1,60 +1,189 @@
import { motion } from "motion/react"; import { animate, motion, useMotionValue, useTransform, useVelocity } from "motion/react";
import { useCallback, useId, useLayoutEffect, useRef, type PointerEvent } from "react";
import { uiSpring } from "../../lib/motion";
export type HUDMode = "scene" | "orbits" | "wormhole" | "decay" | "reconstitute"; export type HUDMode = "scene" | "orbits" | "wormhole" | "decay" | "reconstitute" | "snapshot";
const items: { id: HUDMode; label: string; glyph: string; hint: string }[] = [ const items = [
{ id: "scene", label: "Viewport", glyph: "◎", hint: "Vault ring" }, { id: "scene", label: "Vault", icon: "M4 9l8-4 8 4v6l-8 4-8-4z M4 9l8 4 8-4 M12 13v6" },
{ id: "orbits", label: "Orbits", glyph: "⟳", hint: "Flight paths" }, { id: "orbits", label: "Orbits", icon: "M21 12a9 5 0 1 1-18 0 9 5 0 1 1 18 0z M12 10.5a1.5 1.5 0 1 1 0 3 1.5 1.5 0 1 1 0-3z M18 5h.01" },
{ id: "wormhole", label: "Wormhole", glyph: "◉", hint: "Outpost link" }, { id: "wormhole", label: "Outposts", icon: "M12 3v3 M4.2 7.5l2.6 1.5 M4.2 16.5 6.8 15 M12 18v3 M17.2 15l2.6 1.5 M17.2 9l2.6-1.5 M15.5 12a3.5 3.5 0 1 1-7 0 3.5 3.5 0 1 1 7 0z" },
{ id: "decay", label: "Decay", glyph: "◇", hint: "Fade policy" }, { id: "decay", label: "Retention", icon: "M6 4h12 M6 20h12 M8 4v3l4 5-4 5v3 M16 4v3l-4 5 4 5v3" },
{ id: "reconstitute", label: "Restore", glyph: "↩", hint: "Reconstitute" }, { id: "reconstitute", label: "Restore", icon: "M4 12a8 8 0 1 1 2.3 5.7 M4 6v6h6 M12 8v4l3 2" },
]; ] as const;
type Slot = { center: number; width: number };
type Gesture = { pointer: number; x: number; y: number; origin?: number };
export function HUDRail({ export function HUDRail({
active, active, floating, panelOpen, reducedMotion, onSelect,
onSelect,
capturing,
}: { }: {
active: HUDMode; active: HUDMode;
onSelect: (m: HUDMode) => void; floating: boolean;
capturing?: boolean; panelOpen: boolean;
reducedMotion: boolean;
onSelect: (mode: HUDMode) => void;
}) { }) {
return ( const nav = useRef<HTMLElement>(null);
<nav const slots = useRef<Slot[]>([]);
className="pointer-events-auto absolute bottom-6 left-1/2 -translate-x-1/2 z-30 flex gap-1 px-2 py-1.5 rounded-full border border-wormhole-violet/25 bg-space-950/75 backdrop-blur-xl shadow-[0_0_40px_rgba(5,6,15,0.8)]" const gesture = useRef<Gesture>(undefined);
aria-label="Ship systems" const suppressClick = useRef(false);
> const center = useMotionValue(0);
{items.map((item) => { const width = useMotionValue(0);
const on = active === item.id; const velocity = useVelocity(center);
return ( const tail = useTransform(() => center.get() - Math.max(-22, Math.min(22, velocity.get() * 0.032)));
<motion.button const id = useId();
key={item.id} const activeIndex = Math.max(0, items.findIndex(item => item.id === active));
type="button"
title={item.hint} const snap = useCallback((index: number, immediate = false) => {
onClick={() => onSelect(item.id)} const slot = slots.current[index];
className={`relative px-3 py-2 rounded-full text-xs font-mono transition-colors ${ if (!slot) return;
on if (immediate || reducedMotion) {
? "text-wormhole-violet bg-wormhole-violet/15" center.jump(slot.center);
: "text-star-400 hover:text-star-200" width.jump(slot.width);
}`} } else {
whileTap={{ scale: 0.94 }} animate(center, slot.center, uiSpring);
> animate(width, slot.width, uiSpring);
<span className="sr-only">{item.label}</span> }
<span aria-hidden className="text-sm"> }, [center, reducedMotion, width]);
{item.glyph}
</span> useLayoutEffect(() => () => {
{on && ( center.stop();
<motion.span width.stop();
layoutId="hud-pip" }, [center, width]);
className="absolute -bottom-1 left-1/2 w-1 h-1 -translate-x-1/2 rounded-full bg-orbit-green"
/> useLayoutEffect(() => {
)} const element = nav.current!;
{item.id === "orbits" && capturing && ( const buttons = Array.from(element.querySelectorAll("button"));
<span className="absolute -top-0.5 -right-0.5 w-2 h-2 rounded-full bg-orbit-amber animate-pulse" /> const measure = () => {
)} const left = element.getBoundingClientRect().left + element.clientLeft;
</motion.button> const next = buttons.map(button => {
const rect = button.getBoundingClientRect();
return { center: rect.left + rect.width / 2 - left, width: rect.width - 10 };
});
const changed = next.some((slot, index) =>
slot.center !== slots.current[index]?.center || slot.width !== slots.current[index]?.width,
); );
})} slots.current = next;
</nav> if (changed) gesture.current = undefined;
return changed;
};
snap(activeIndex, measure());
const observer = new ResizeObserver(() => {
if (measure()) snap(activeIndex, true);
});
observer.observe(element);
buttons.forEach(button => observer.observe(button));
return () => observer.disconnect();
}, [activeIndex, floating, snap]);
function start(event: PointerEvent<HTMLElement>) {
if (!event.isPrimary || event.button !== 0) return;
suppressClick.current = false;
const button = (event.target as Element).closest("button");
if (button?.hasAttribute("aria-current")) {
gesture.current = { pointer: event.pointerId, x: event.clientX, y: event.clientY };
}
}
function move(event: PointerEvent<HTMLElement>) {
const drag = gesture.current;
if (drag?.pointer !== event.pointerId) return;
const dx = event.clientX - drag.x;
if (drag.origin === undefined) {
if (Math.abs(dx) < 5 || Math.abs(dx) < Math.abs(event.clientY - drag.y)) return;
center.stop();
drag.origin = center.get();
suppressClick.current = true;
event.currentTarget.setPointerCapture(event.pointerId);
}
center.set(Math.max(slots.current[0].center, Math.min(slots.current.at(-1)!.center, drag.origin + dx)));
}
function finish(event: PointerEvent<HTMLElement>) {
const drag = gesture.current;
if (drag?.pointer !== event.pointerId) return;
gesture.current = undefined;
if (drag.origin === undefined) return;
if (event.type !== "pointerup") {
snap(activeIndex);
return;
}
const projected = center.get() + Math.max(-18, Math.min(18, center.getVelocity() * 0.1));
const next = slots.current.reduce((nearest, slot, index) =>
Math.abs(slot.center - projected) < Math.abs(slots.current[nearest].center - projected) ? index : nearest,
0);
if (next === activeIndex) snap(activeIndex);
else onSelect(items[next].id);
}
return (
<motion.nav
ref={nav}
className="vault-nav"
aria-label="Vault systems"
initial={false}
animate={{ "--dock-morph": panelOpen && !floating ? 1 : 0 }}
onPointerDown={start}
onPointerMove={move}
onPointerUp={finish}
onPointerCancel={finish}
onLostPointerCapture={event => {
if (event.target === event.currentTarget) finish(event);
}}
onPointerLeave={event => {
if (gesture.current?.pointer === event.pointerId && gesture.current.origin === undefined) {
gesture.current = undefined;
}
}}
onClickCapture={event => {
if (event.detail > 0 && suppressClick.current) {
event.preventDefault();
event.stopPropagation();
}
}}
>
{floating ? (
<svg className="nav-liquid" aria-hidden="true">
<defs>
<filter id={`${id}-goo`} x="-25%" y="-50%" width="150%" height="200%">
<feGaussianBlur in="SourceGraphic" stdDeviation="3.5" result="blur" />
<feColorMatrix in="blur" type="matrix" values="1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 20 -8" result="goo" />
<feComposite in="SourceGraphic" in2="goo" operator="atop" />
</filter>
<linearGradient id={`${id}-fill`} x2="0%" y2="100%">
<stop stopColor="#724a34" />
<stop offset="100%" stopColor="#38251e" />
</linearGradient>
</defs>
<g filter={`url(#${id}-goo)`} fill={`url(#${id}-fill)`}>
<motion.ellipse cx={reducedMotion ? center : tail} cy="50%" rx="17" ry="13" />
<motion.ellipse cx={center} cy="50%" rx="21" ry="17" />
</g>
</svg>
) : (
<>
<span aria-hidden="true" className="nav-text-dock" />
<motion.span aria-hidden="true" className="nav-underline" style={{ x: center, width }} />
</>
)}
{items.map(({ id, label, icon }) => (
<button
key={id}
type="button"
aria-label={floating ? label : undefined}
title={floating ? label : undefined}
onClick={() => onSelect(id)}
aria-current={active === id ? "page" : undefined}
>
{floating ? (
<svg viewBox="0 0 24 24" width="22" height="22" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
<path d={icon} />
</svg>
) : label}
</button>
))}
</motion.nav>
); );
} }

View File

@@ -1,55 +0,0 @@
import type { ReactNode } from "react";
export type Tab = "vault" | "orbits" | "outposts" | "decay";
const tabs: { id: Tab; label: string }[] = [
{ id: "vault", label: "Vault" },
{ id: "orbits", label: "Orbits" },
{ id: "outposts", label: "Wormhole" },
{ id: "decay", label: "Decay" },
];
export function NavBar({
active,
onChange,
}: {
active: Tab;
onChange: (t: Tab) => void;
}) {
return (
<nav className="shrink-0 flex border-t border-space-800 bg-space-900/90 backdrop-blur-md safe-area-pb">
{tabs.map((t) => (
<button
key={t.id}
type="button"
onClick={() => onChange(t.id)}
className={`flex-1 py-3 text-xs font-medium transition-colors ${
active === t.id
? "text-wormhole-violet border-t-2 border-wormhole-violet -mt-px"
: "text-star-400"
}`}
>
{t.label}
</button>
))}
</nav>
);
}
export function AppHeader({
statusDot,
subtitle,
}: {
statusDot: ReactNode;
subtitle: string;
}) {
return (
<header className="shrink-0 px-4 py-3 flex items-center justify-between border-b border-space-800/80 bg-space-950/80 backdrop-blur-sm z-10">
<div>
<h1 className="text-lg font-semibold tracking-tight text-star-100">Tessera</h1>
<p className="text-xs text-star-400">{subtitle}</p>
</div>
{statusDot}
</header>
);
}

View File

@@ -1,19 +1,28 @@
import { useState } from "react"; import { useState, type ReactNode } from "react";
import { AnimatePresence } from "motion/react";
import { useMutation, useQueryClient } from "@tanstack/react-query"; import { useMutation, useQueryClient } from "@tanstack/react-query";
import type { Orbit } from "../../api"; import type { Orbit } from "../../api";
import { createOrbit, runOrbit } from "../../api"; import { createOrbit } from "../../api";
import { DECAY_PRESETS, schedulePhrase } from "../../lib/format"; import { DECAY_PRESETS, orbitStatus, schedulePhrase } from "../../lib/format";
import { Button } from "../ui/Button"; import { Button } from "../ui/Button";
import { OrbitStatusDot } from "../ui/StatusDot"; import { OrbitStatusDot } from "../ui/StatusDot";
import { TelemetryPanel } from "../ui/Telemetry"; import { TelemetryPanel } from "../ui/Telemetry";
import { Hint } from "../ui/EmptyState"; import { Hint } from "../ui/EmptyState";
import { SpringPane } from "../ui/SpringPane";
export function OrbitsView({ orbits }: { orbits: Orbit[] }) { export function OrbitsView({
orbits, onRun, captureDisabled, notice,
}: {
orbits: Orbit[];
onRun: (orbit: Orbit) => void;
captureDisabled: boolean;
notice?: ReactNode;
}) {
const [editing, setEditing] = useState(false); const [editing, setEditing] = useState(false);
const qc = useQueryClient(); const qc = useQueryClient();
const [name, setName] = useState("nightly-docs"); const [name, setName] = useState("nightly-docs");
const [path, setPath] = useState("./docs"); const [path, setPath] = useState("./docs");
const [preset, setPreset] = useState(DECAY_PRESETS[0].id); const [preset, setPreset] = useState<string>(DECAY_PRESETS[0].id);
const [rehearse, setRehearse] = useState(false); const [rehearse, setRehearse] = useState(false);
const [schedule, setSchedule] = useState("0 2 * * *"); const [schedule, setSchedule] = useState("0 2 * * *");
@@ -33,19 +42,9 @@ export function OrbitsView({ orbits }: { orbits: Orbit[] }) {
}, },
}); });
const run = useMutation({
mutationFn: (id: string) => runOrbit(id),
onSuccess: () => qc.invalidateQueries({ queryKey: ["orbits", "snapshots"] }),
});
return ( return (
<div className="h-full overflow-y-auto px-4 py-4 pb-28 scrollbar-none"> <div>
<header className="mb-4"> {notice}
<h2 className="text-2xl font-semibold text-star-100">Orbits</h2>
<p className="text-sm text-star-300 mt-1">
Scheduled circles around your vault — not cron jargon in the headline.
</p>
</header>
<div className="space-y-3 mb-6"> <div className="space-y-3 mb-6">
{orbits.map((o) => ( {orbits.map((o) => (
@@ -57,6 +56,7 @@ export function OrbitsView({ orbits }: { orbits: Orbit[] }) {
<OrbitStatusDot status={o.last_status} /> <OrbitStatusDot status={o.last_status} />
<div className="flex-1 min-w-0"> <div className="flex-1 min-w-0">
<h3 className="font-semibold text-star-100 truncate">{o.name}</h3> <h3 className="font-semibold text-star-100 truncate">{o.name}</h3>
<p className="text-sm text-star-300">{orbitStatus(o.last_status).label}</p>
<p className="text-xs text-star-400 mt-0.5">{schedulePhrase(o.schedule, o.dry_run)}</p> <p className="text-xs text-star-400 mt-0.5">{schedulePhrase(o.schedule, o.dry_run)}</p>
{o.dry_run && ( {o.dry_run && (
<span className="inline-block mt-2 text-[10px] uppercase tracking-wider text-orbit-amber border border-orbit-amber/30 rounded px-2 py-0.5"> <span className="inline-block mt-2 text-[10px] uppercase tracking-wider text-orbit-amber border border-orbit-amber/30 rounded px-2 py-0.5">
@@ -69,10 +69,10 @@ export function OrbitsView({ orbits }: { orbits: Orbit[] }) {
<Button <Button
variant="success" variant="success"
className="flex-1 text-xs py-2" className="flex-1 text-xs py-2"
disabled={run.isPending || o.last_status === "running"} disabled={captureDisabled || orbitStatus(o.last_status).busy}
onClick={() => run.mutate(o.id)} onClick={() => onRun(o)}
> >
Capture now {o.dry_run ? "Rehearse" : "Capture now"}
</Button> </Button>
</div> </div>
<TelemetryPanel> <TelemetryPanel>
@@ -82,7 +82,10 @@ export function OrbitsView({ orbits }: { orbits: Orbit[] }) {
))} ))}
</div> </div>
<div className="spring-stack">
<AnimatePresence initial={false}>
{editing ? ( {editing ? (
<SpringPane key="form">
<div className="rounded-2xl border border-wormhole-violet/30 bg-space-900 p-4 space-y-3"> <div className="rounded-2xl border border-wormhole-violet/30 bg-space-900 p-4 space-y-3">
<h3 className="font-medium text-star-100">New orbit</h3> <h3 className="font-medium text-star-100">New orbit</h3>
<label className="block text-sm"> <label className="block text-sm">
@@ -130,6 +133,7 @@ export function OrbitsView({ orbits }: { orbits: Orbit[] }) {
<Hint> <Hint>
Rehearse orbits prove the path without writing to the vault — status shows amber “rehearsed”. Rehearse orbits prove the path without writing to the vault — status shows amber “rehearsed”.
</Hint> </Hint>
{create.isError && <p role="alert" className="text-sm text-orbit-red">The orbit could not be saved.</p>}
<div className="flex gap-2"> <div className="flex gap-2">
<Button className="flex-1" onClick={() => setEditing(false)}> <Button className="flex-1" onClick={() => setEditing(false)}>
Cancel Cancel
@@ -144,13 +148,16 @@ export function OrbitsView({ orbits }: { orbits: Orbit[] }) {
</Button> </Button>
</div> </div>
</div> </div>
</SpringPane>
) : ( ) : (
<SpringPane key="add">
<Button variant="primary" className="w-full" onClick={() => setEditing(true)}> <Button variant="primary" className="w-full" onClick={() => setEditing(true)}>
Add an orbit Add an orbit
</Button> </Button>
</SpringPane>
)} )}
</AnimatePresence>
</div>
</div> </div>
); );
} }
// fix motion.collapse - use div

View File

@@ -1,6 +1,8 @@
import { useMutation } from "@tanstack/react-query"; import { useMutation } from "@tanstack/react-query";
import { motion } from "motion/react"; import { motion } from "motion/react";
import { startPairing } from "../../api"; import { startPairing } from "../../api";
import { useReducedMotion } from "../../hooks/useReducedMotion";
import { ambientPulse } from "../../lib/motion";
import { Button } from "../ui/Button"; import { Button } from "../ui/Button";
import { Hint } from "../ui/EmptyState"; import { Hint } from "../ui/EmptyState";
import { TelemetryPanel } from "../ui/Telemetry"; import { TelemetryPanel } from "../ui/Telemetry";
@@ -16,6 +18,7 @@ export function WormholeView({
mutationFn: startPairing, mutationFn: startPairing,
onSuccess: onPaired, onSuccess: onPaired,
}); });
const reducedMotion = useReducedMotion();
const expires = pairing ? new Date(pairing.expires_at).toLocaleTimeString() : ""; const expires = pairing ? new Date(pairing.expires_at).toLocaleTimeString() : "";
@@ -31,7 +34,7 @@ export function WormholeView({
) : ( ) : (
<motion.div <motion.div
className="rounded-2xl border border-wormhole-violet/35 bg-gradient-to-b from-wormhole-violet/10 to-space-900 p-6 text-center" className="rounded-2xl border border-wormhole-violet/35 bg-gradient-to-b from-wormhole-violet/10 to-space-900 p-6 text-center"
initial={{ scale: 0.95, opacity: 0 }} initial={reducedMotion ? false : { scale: 0.95, opacity: 0 }}
animate={{ scale: 1, opacity: 1 }} animate={{ scale: 1, opacity: 1 }}
> >
<p className="text-xs uppercase tracking-[0.2em] text-wormhole-violet mb-4"> <p className="text-xs uppercase tracking-[0.2em] text-wormhole-violet mb-4">
@@ -73,15 +76,19 @@ function EmptyWormhole({
onGenerate: () => void; onGenerate: () => void;
loading: boolean; loading: boolean;
}) { }) {
const reducedMotion = useReducedMotion();
return ( return (
<div className="text-center py-8"> <div className="text-center py-8">
<motion.div <div className="relative mx-auto w-24 h-24 rounded-full border border-wormhole-violet/30 flex items-center justify-center text-3xl">
className="mx-auto w-24 h-24 rounded-full border border-wormhole-violet/30 flex items-center justify-center text-3xl" <motion.span
animate={{ boxShadow: ["0 0 0 rgba(167,139,250,0)", "0 0 32px rgba(167,139,250,0.25)", "0 0 0 rgba(167,139,250,0)"] }} aria-hidden="true"
transition={{ duration: 3, repeat: Infinity }} className="pointer-events-none absolute inset-0 rounded-full shadow-[0_0_32px_rgba(167,139,250,0.25)]"
> initial={{ opacity: 0 }}
animate={{ opacity: reducedMotion ? 0 : [0, 1] }}
transition={reducedMotion ? { type: false } : ambientPulse}
/>
◉ ◉
</motion.div> </div>
<p className="mt-4 text-star-300 text-sm max-w-xs mx-auto"> <p className="mt-4 text-star-300 text-sm max-w-xs mx-auto">
Open a wormhole when you&apos;re ready to claim an outpost. Open a wormhole when you&apos;re ready to claim an outpost.
</p> </p>

View File

@@ -14,6 +14,7 @@ export function ReconstituteWizard({
onStart, onStart,
onPoll, onPoll,
onAbort, onAbort,
onBusyChange,
}: { }: {
snapshots: Snapshot[]; snapshots: Snapshot[];
selected: string | null; selected: string | null;
@@ -23,35 +24,55 @@ export function ReconstituteWizard({
}>; }>;
onPoll: (id: string) => Promise<{ state: string; seconds_remaining: number }>; onPoll: (id: string) => Promise<{ state: string; seconds_remaining: number }>;
onAbort: (id: string) => Promise<void>; onAbort: (id: string) => Promise<void>;
onBusyChange: (busy: boolean) => void;
}) { }) {
const [snapId, setSnapId] = useState(selected ?? snapshots[0]?.id ?? ""); const [snapId, setSnapId] = useState(selected ?? snapshots[0]?.id ?? "");
const [target, setTarget] = useState("./restore/out"); const [target, setTarget] = useState("./restore/out");
const [sessionId, setSessionId] = useState<string | null>(null); const [sessionId, setSessionId] = useState<string | null>(null);
const [remaining, setRemaining] = useState(GRACE); const [remaining, setRemaining] = useState(GRACE);
const [state, setState] = useState("idle"); const [state, setState] = useState("idle");
const [action, setAction] = useState<"starting" | "aborting">();
const [error, setError] = useState<string>();
const [reconnecting, setReconnecting] = useState(false);
const snap = snapshots.find((s) => s.id === snapId); const snap = snapshots.find((s) => s.id === snapId);
const inCountdown = state === "countdown" || state === "confirming";
const busy = !!action || inCountdown || state === "restoring";
useEffect(() => { onBusyChange(busy); }, [busy, onBusyChange]);
useEffect(() => { useEffect(() => {
if (!sessionId) return; if (!sessionId) return;
const t = setInterval(async () => { let cancelled = false;
let timer: number;
const poll = async () => {
try { try {
const s = await onPoll(sessionId); const s = await onPoll(sessionId);
if (cancelled) return;
setReconnecting(false);
setState(s.state); setState(s.state);
setRemaining(s.seconds_remaining ?? 0); setRemaining(s.seconds_remaining ?? 0);
} catch { if (["completed", "aborted", "failed", "unavailable"].includes(s.state)) {
/* hub may clear session */ setAction(undefined);
return;
} }
}, 400); } catch {
return () => clearInterval(t); if (cancelled) return;
setReconnecting(true);
}
timer = window.setTimeout(poll, 400);
};
timer = window.setTimeout(poll, 400);
return () => {
cancelled = true;
clearTimeout(timer);
};
}, [sessionId, onPoll]); }, [sessionId, onPoll]);
const inCountdown = state === "countdown";
return ( return (
<div className="space-y-4"> <div className="space-y-4">
<p className="text-sm text-star-300"> <p className="text-sm text-star-300">
Pick a snapshot, choose where it lands, then wait through the grace window. Choose a snapshot and a destination on the hub.
</p> </p>
{snap && ( {snap && (
@@ -67,11 +88,11 @@ export function ReconstituteWizard({
className="mt-1 w-full rounded-xl bg-space-950 border border-space-700 px-3 py-2.5" className="mt-1 w-full rounded-xl bg-space-950 border border-space-700 px-3 py-2.5"
value={snapId} value={snapId}
onChange={(e) => setSnapId(e.target.value)} onChange={(e) => setSnapId(e.target.value)}
disabled={inCountdown || state === "restoring"} disabled={busy}
> >
{snapshots.map((s) => ( {snapshots.map((s) => (
<option key={s.id} value={s.id}> <option key={s.id} value={s.id}>
{s.orbit_name} — {new Date(s.taken_at).toLocaleDateString()} {s.orbit_name} · {formatWhen(s.taken_at)} · {formatBytes(s.size_bytes)}
</option> </option>
))} ))}
</select> </select>
@@ -83,28 +104,28 @@ export function ReconstituteWizard({
className="mt-1 w-full rounded-xl bg-space-950 border border-space-700 px-3 py-2.5 font-mono text-xs" className="mt-1 w-full rounded-xl bg-space-950 border border-space-700 px-3 py-2.5 font-mono text-xs"
value={target} value={target}
onChange={(e) => setTarget(e.target.value)} onChange={(e) => setTarget(e.target.value)}
disabled={inCountdown || state === "restoring"} disabled={busy}
/> />
</label> </label>
{inCountdown && ( {inCountdown && (
<motion.div <motion.div
className="relative rounded-2xl border border-orbit-amber/40 bg-orbit-amber/10 p-6 text-center" className="relative rounded-2xl border border-orbit-amber/40 bg-orbit-amber/10 p-6 text-center"
animate={{ opacity: [1, 0.85, 1] }} initial={{ opacity: 0 }}
transition={{ duration: 1.2, repeat: Infinity }} animate={{ opacity: 1 }}
> >
<div className="relative mx-auto w-20 h-20"> <div className="relative mx-auto w-20 h-20">
<svg viewBox="0 0 36 36" className="w-full h-full -rotate-90"> <svg viewBox="0 0 36 36" className="w-full h-full -rotate-90">
<circle cx="18" cy="18" r="16" fill="none" stroke="#1e2647" strokeWidth="3" /> <circle cx="18" cy="18" r="16" fill="none" stroke="#1e2647" strokeWidth="3" />
<circle <motion.circle
cx="18" cx="18"
cy="18" cy="18"
r="16" r="16"
fill="none" fill="none"
stroke="#f0c468" stroke="#f0c468"
strokeWidth="3" strokeWidth="3"
strokeDasharray={`${(remaining / GRACE) * 100} 100`} initial={false}
pathLength={100} animate={{ pathLength: Math.max(0, Math.min(1, remaining / GRACE)) }}
/> />
</svg> </svg>
<span className="absolute inset-0 flex items-center justify-center text-2xl font-semibold text-orbit-amber"> <span className="absolute inset-0 flex items-center justify-center text-2xl font-semibold text-orbit-amber">
@@ -121,26 +142,50 @@ export function ReconstituteWizard({
<Button <Button
variant="danger" variant="danger"
className="flex-1" className="flex-1"
disabled={!sessionId || state === "completed"} disabled={!sessionId || !inCountdown || !!action}
onClick={() => sessionId && onAbort(sessionId)} onClick={async () => {
if (!sessionId) return;
setAction("aborting");
setError(undefined);
try {
await onAbort(sessionId);
} catch {
setAction(undefined);
setError("Could not cancel the restore. Check the current session status.");
}
}}
> >
Abort Abort
</Button> </Button>
<Button <Button
variant="warn" variant="warn"
className="flex-1" className="flex-1"
disabled={!snapId || inCountdown || state === "restoring"} disabled={!snap || !target.trim() || busy}
onClick={async () => { onClick={async () => {
setAction("starting");
setError(undefined);
try {
const res = await onStart(snapId, target); const res = await onStart(snapId, target);
setSessionId(res.session_id); setSessionId(res.session_id);
setState(res.session.state); setState(res.session.state);
setRemaining(res.session.seconds_remaining); setRemaining(res.session.seconds_remaining);
} catch {
setError("Could not confirm that the hub started the restore.");
} finally {
setAction(undefined);
}
}} }}
> >
Begin reconstitute Begin restore
</Button> </Button>
</div> </div>
{error && <p role="alert" className="text-orbit-red text-sm">{error}</p>}
{reconnecting && <p role="status" className="text-orbit-amber text-sm">Reconnecting to the restore session…</p>}
{state === "restoring" && <p role="status" className="text-orbit-amber text-sm">Restoring snapshot…</p>}
{state === "unavailable" && (
<p role="alert" className="text-orbit-red text-sm">The hub no longer has this restore session. Check the destination before retrying.</p>
)}
{state === "completed" && ( {state === "completed" && (
<p className="text-orbit-green text-sm text-center">Reconstitute complete.</p> <p className="text-orbit-green text-sm text-center">Reconstitute complete.</p>
)} )}
@@ -151,7 +196,7 @@ export function ReconstituteWizard({
<p className="text-orbit-red text-sm text-center">Reconstitute failed — check telemetry.</p> <p className="text-orbit-red text-sm text-center">Reconstitute failed — check telemetry.</p>
)} )}
<Hint>Destructive-capable. Evidence above is what we&apos;ll write to disk after the timer.</Hint> <Hint>The hub writes after the countdown. An existing file at the destination may be overwritten.</Hint>
{sessionId && ( {sessionId && (
<TelemetryPanel label="Session"> <TelemetryPanel label="Session">

View File

@@ -1,283 +1,232 @@
import { useEffect, useMemo, useRef, useState, type RefObject } from "react"; import { useCallback, useLayoutEffect, useMemo, useRef, useState } from "react";
import type { Orbit } from "../../api"; import { animate, spring, useMotionValue } from "motion/react";
import type { Orbit, Snapshot } from "../../api";
import { orbitStatus } from "../../lib/format";
import { LABEL_HEIGHT, placeLabels, type Rect } from "../../lib/galaxyLabelLayout";
import { import {
assignShells, assignOrbitSlots, moonPoses, orbitCapacity, orbitPose, orbitRadii, ORBIT_TILT,
shellPose, SCENE_HEIGHT, SCENE_WIDTH, spiralPoint, type Vec2,
spiralPoint,
type Vec2,
} from "../../lib/galaxyLayout"; } from "../../lib/galaxyLayout";
import { useGalaxyTime } from "../../hooks/useGalaxyMotion"; import { useGalaxyMotion } from "../../hooks/useGalaxyMotion";
import { uiSpring } from "../../lib/motion";
import { VaultCore } from "./VaultCore";
const METEOR_MS = 2600; export type CaptureArrival = { orbitId: string; snapshotId: string };
function shorten(name: string) { type Props = {
return name.length > 16 ? `${name.slice(0, 14)}…` : name; orbits: Orbit[];
} selectedOrbitId?: string;
recentSnapshots: Snapshot[];
flowing: boolean;
reducedMotion: boolean;
arrival?: CaptureArrival;
onSelectOrbit: (id: string) => void;
onSelectSnapshot: (id: string) => void;
};
const HALF_WIDTH = SCENE_WIDTH / 2;
const HALF_HEIGHT = SCENE_HEIGHT / 2;
const labelFont = "500 11px ui-monospace, monospace";
const MAX_LABELS = 12;
const ACCRETION_SECONDS = 6.4;
export function BlackholeGalaxy({ export function BlackholeGalaxy({
orbits, orbits, selectedOrbitId, recentSnapshots, flowing, reducedMotion, arrival, onSelectOrbit, onSelectSnapshot,
flowing, }: Props) {
capturing, const frame = useRef<HTMLDivElement>(null);
capturePulse = 0, const bodyNodes = useRef(new Map<SVGGElement, { id: string; far: boolean }>());
onToggleFlow, const slotsBefore = useRef<ReturnType<typeof assignOrbitSlots>>(undefined);
onSelectOrbit, const elapsed = useRef(0);
}: { const core = useRef<SVGGElement>(null);
orbits: Orbit[]; const meteor = useRef<{ id: string; time: number; source: Vec2; progress: ReturnType<typeof spring> }>(undefined);
snapshots?: unknown; const trail = useRef<SVGPathElement>(null);
flowing: boolean; const head = useRef<SVGCircleElement>(null);
capturing?: boolean; const effect = useRef<SVGGElement>(null);
capturePulse?: number; const [width, setWidth] = useState(0);
onToggleFlow: () => void; const [coasting, setCoasting] = useState(false);
onSelectSnapshot?: (id: string) => void; const rate = useMotionValue(flowing && !reducedMotion ? 1 : 0);
onSelectOrbit: (id: string) => void; const moving = !reducedMotion && (flowing || coasting);
selectedSnapshotId?: string | null;
}) {
const t = useGalaxyTime(!flowing);
const shells = useMemo(() => assignShells(orbits.length), [orbits.length]);
const poses = shells.map((body) => shellPose(body, t)); useLayoutEffect(() => () => rate.stop(), [rate]);
const poseRef = useRef(poses); useLayoutEffect(() => {
poseRef.current = poses; if (reducedMotion) {
const meteor = useMeteor(capturePulse, poseRef); rate.jump(0);
setCoasting(false);
return;
}
return ( const target = flowing ? 1 : 0;
<div className="absolute inset-0 flex items-center justify-center pt-14 pb-24 px-4 pointer-events-none"> if (rate.get() === target && !rate.isAnimating()) return;
<svg setCoasting(!flowing);
viewBox="-300 -300 600 600" animate(rate, target, { ...uiSpring, onComplete: () => setCoasting(false) });
className="h-full w-full max-h-[min(86dvh,920px)] max-w-[min(96vw,1100px)] pointer-events-auto" }, [flowing, rate, reducedMotion]);
role="img"
aria-label="Vault orrery"
>
<defs>
<linearGradient id="diskBand" x1="0%" y1="0%" x2="100%" y2="0%">
<stop offset="0%" stopColor="#6a3414" stopOpacity="0" />
<stop offset="18%" stopColor="#c4622a" stopOpacity="0.55" />
<stop offset="42%" stopColor="#ffb15e" stopOpacity="0.95" />
<stop offset="58%" stopColor="#fff1d4" stopOpacity="1" />
<stop offset="78%" stopColor="#ff8a3a" stopOpacity="0.85" />
<stop offset="100%" stopColor="#6a3414" stopOpacity="0" />
</linearGradient>
<linearGradient id="topArc" x1="0%" y1="0%" x2="100%" y2="0%">
<stop offset="0%" stopColor="#ff9a4a" stopOpacity="0" />
<stop offset="50%" stopColor="#ffd7a4" stopOpacity="0.95" />
<stop offset="100%" stopColor="#ff9a4a" stopOpacity="0" />
</linearGradient>
<radialGradient id="warmBody" cx="36%" cy="32%" r="68%">
<stop offset="0%" stopColor="#fff6ea" />
<stop offset="42%" stopColor="#ffb15a" />
<stop offset="100%" stopColor="#c4621e" />
</radialGradient>
<radialGradient id="coolBody" cx="36%" cy="32%" r="68%">
<stop offset="0%" stopColor="#ffffff" />
<stop offset="45%" stopColor="#e7eefc" />
<stop offset="100%" stopColor="#9aa6c4" />
</radialGradient>
<filter id="softGlow" x="-40%" y="-40%" width="180%" height="180%">
<feGaussianBlur stdDeviation="2.2" />
</filter>
<filter id="diskGlow" x="-20%" y="-80%" width="140%" height="260%">
<feGaussianBlur stdDeviation="1.4" />
</filter>
</defs>
<LensedHole t={t} onToggle={onToggleFlow} /> const slots = useMemo(
() => assignOrbitSlots(orbits.map(({ id }) => id), slotsBefore.current, selectedOrbitId),
[orbits, selectedOrbitId],
);
useLayoutEffect(() => { slotsBefore.current = slots; }, [slots]);
useLayoutEffect(() => {
const element = frame.current;
if (!element) return;
const measure = () => setWidth(element.clientWidth);
const observer = new ResizeObserver(measure);
observer.observe(element);
measure();
return () => observer.disconnect();
}, []);
{shells.map((body, i) => { const draw = useCallback((delta: number) => {
const pose = poses[i]; if (moving && delta > 0) {
const behind = pose.angle - 0.28; elapsed.current += delta * Math.max(0, rate.get());
const wake = { const phase = (elapsed.current % ACCRETION_SECONDS) / ACCRETION_SECONDS;
x: Math.cos(behind) * body.radius, core.current?.style.setProperty("--accretion-offset", String(-100 * phase));
y: Math.sin(behind) * body.radius, }
for (const [node, { id, far }] of bodyNodes.current) {
const slot = slots.get(id);
if (!slot) continue;
const { x, y } = orbitPose(slot, elapsed.current);
const visible = far === (y < 0);
const display = visible ? "" : "none";
if (node.style.display !== display) node.style.display = display;
if (!visible) continue;
node.setAttribute("transform", `translate(${x} ${y})`);
}
if (!arrival || reducedMotion) {
effect.current?.setAttribute("opacity", "0");
return moving;
}
const slot = slots.get(arrival.orbitId);
if (meteor.current?.id !== arrival.snapshotId && slot) {
const source = orbitPose(slot, elapsed.current);
meteor.current = {
id: arrival.snapshotId,
time: 0,
source,
progress: spring({ ...uiSpring, stiffness: 36, damping: 12, keyframes: [0, 1], restDelta: 0.002 }),
}; };
const color = body.warm ? "#ffb15a" : "#d5def4"; const points = Array.from({ length: 36 }, (_, i) => spiralPoint(source, i / 35));
trail.current?.setAttribute("d", points.map(({ x, y }, i) => `${i ? "L" : "M"} ${x} ${y}`).join(" "));
}
const current = meteor.current;
if (!current || current.id !== arrival.snapshotId) return moving;
current.time += delta * 1000;
const { value: progress, done } = current.progress.next(current.time);
const { x, y } = spiralPoint(current.source, progress);
head.current?.setAttribute("cx", String(x));
head.current?.setAttribute("cy", String(y));
trail.current?.setAttribute("stroke-dashoffset", String(0.2 - progress));
effect.current?.setAttribute("opacity", String(progress >= 1 ? 0 : Math.min(1, (1 - progress) * 6)));
return moving || !done;
}, [arrival, moving, rate, reducedMotion, slots]);
useGalaxyMotion(moving || (!reducedMotion && !!arrival), draw);
const scale = width / SCENE_WIDTH;
const height = SCENE_HEIGHT * scale;
const hitRadius = Math.max(12, scale ? 12 / scale : 12);
const selectedSlot = selectedOrbitId ? slots.get(selectedOrbitId) : undefined;
const selectedPosition = !moving && selectedSlot ? orbitPose(selectedSlot, elapsed.current) : undefined;
const positions = !moving ? [...slots.values()].map((slot) => orbitPose(slot, elapsed.current)) : [];
const moons = selectedPosition
? moonPoses(selectedPosition, recentSnapshots.length, 2 * hitRadius + 3, positions)
: [];
const screen = ({ x, y }: Vec2) => ({ x: (x + HALF_WIDTH) * scale, y: (y + HALF_HEIGHT) * scale });
const visible = orbits.filter(({ id }) => slots.has(id));
const byPriority = (orbit: Orbit) =>
orbit.id === selectedOrbitId ? 0 : orbit.last_status === "failed" ? 1 : orbitStatus(orbit.last_status).busy ? 2 : 3;
const labelCandidates = [...visible].sort((a, b) => byPriority(a) - byPriority(b))
.filter((orbit) => width >= 530 || orbit.id === selectedOrbitId)
.slice(0, MAX_LABELS);
const box = (point: Vec2, r: number): Rect => {
const { x, y } = screen(point);
return { x: x - r, y: y - r, width: r * 2, height: r * 2 };
};
let labels: ReturnType<typeof placeLabels> = [];
if (!moving && width && labelCandidates.length) {
const measure = document.createElement("canvas").getContext("2d");
if (measure) measure.font = labelFont;
const markers = positions.map((point) => box(point, 7));
const core = box({ x: 0, y: 0 }, 65 * scale);
labels = placeLabels(labelCandidates.map(({ id, name }) => {
const point = screen(orbitPose(slots.get(id)!, elapsed.current));
return { id, ...point, width: Math.min(146, Math.ceil(measure?.measureText(name).width ?? name.length * 7) + 16) };
}), width, height, [core, ...markers, ...moons.map((moon) => box(moon, 12))]);
}
const focusLabel = labels.find(({ id }) => id === selectedOrbitId);
const renderOrbits = (far: boolean) => visible.map((orbit) => {
const point = orbitPose(slots.get(orbit.id)!, elapsed.current);
// Each marker switches layers when it crosses the orbital plane.
const selected = orbit.id === selectedOrbitId;
const status = orbitStatus(orbit.last_status);
return ( return (
<g key={orbits[i].id}> <g
<line key={orbit.id}
x1={wake.x} ref={(node) => {
y1={wake.y} if (!node) return;
x2={pose.x} bodyNodes.current.set(node, { id: orbit.id, far });
y2={pose.y} return () => { bodyNodes.current.delete(node); };
stroke={color}
strokeWidth={body.warm ? 2.4 : 1.5}
strokeLinecap="round"
opacity={0.45}
/>
<circle
cx={pose.x}
cy={pose.y}
r={body.size * 2.1}
fill={color}
opacity={0.16}
filter="url(#softGlow)"
/>
<circle
cx={pose.x}
cy={pose.y}
r={body.size}
fill={body.warm ? "url(#warmBody)" : "url(#coolBody)"}
className={!flowing ? "cursor-pointer" : undefined}
onClick={(e) => {
e.stopPropagation();
if (!flowing) onSelectOrbit(orbits[i].id);
}} }}
/> transform={`translate(${point.x} ${point.y})`}
{!flowing && ( style={{ display: far === (point.y < 0) ? "" : "none" }}
<text data-orbit-marker={orbit.id}
x={pose.x + Math.cos(pose.angle) * (body.size + 14)} className={`orbit-marker orbit-marker--${status.tone}${selected ? " orbit-marker--selected" : ""}`}
y={pose.y + Math.sin(pose.angle) * (body.size + 14)}
textAnchor="middle"
fill="#c9d4ea"
fontSize="10"
className="font-mono pointer-events-none"
> >
{shorten(orbits[i].name)} <circle className="orbit-halo" r={selected ? 16 : 10} />
</text> {status.tone === "red" && <path className="orbit-alert" d="M0 -8 8 0 0 8 -8 0Z" />}
)} {status.busy && <circle className="orbit-busy" r="8.5" />}
{selected && <circle className="orbit-selection" r="13" />}
<circle className="orbit-light" r="4.6" />
<circle className="orbit-hit" r={hitRadius} onClick={() => onSelectOrbit(orbit.id)} />
</g>
);
});
return (
<div ref={frame} className="galaxy-frame" data-flowing={flowing}>
<svg viewBox={`${-HALF_WIDTH} ${-HALF_HEIGHT} ${SCENE_WIDTH} ${SCENE_HEIGHT}`} aria-hidden="true">
<g className="orbit-tracks" pointerEvents="none">
{orbitRadii.map((radius) => (
<ellipse key={radius} rx={radius} ry={radius * ORBIT_TILT} className={selectedSlot?.radius === radius ? "is-selected" : ""} />
))}
</g>
<g className="orbit-layer orbit-layer--far">{renderOrbits(true)}</g>
<VaultCore ref={core} />
<g className="orbit-layer orbit-layer--near">{renderOrbits(false)}</g>
{selectedPosition && moons.map(({ x, y }, index) => {
const snapshot = recentSnapshots[index];
return (
<g key={snapshot.id} data-snapshot-marker={snapshot.id} className="snapshot-marker">
<line x1={selectedPosition.x} y1={selectedPosition.y} x2={x} y2={y} />
<rect className="snapshot-light" x={x - 4} y={y - 4} width="8" height="8" rx="1" transform={`rotate(45 ${x} ${y})`} />
<circle className="orbit-hit" cx={x} cy={y} r={hitRadius} onClick={() => onSelectSnapshot(snapshot.id)} />
</g> </g>
); );
})} })}
{selectedPosition && focusLabel && (
{meteor && <InboundMeteor source={meteor.source} u={meteor.u} />} <line className="focus-leader"
x1={selectedPosition.x} y1={selectedPosition.y}
x2={(focusLabel.x + focusLabel.width / 2) / scale - HALF_WIDTH}
y2={(focusLabel.y + LABEL_HEIGHT / 2) / scale - HALF_HEIGHT}
/>
)}
<g ref={effect} className="capture-arrival" opacity="0" pointerEvents="none">
<path ref={trail} pathLength="1" strokeDasharray=".2 1" fill="none" />
<circle ref={head} r="3.5" />
</g>
</svg> </svg>
<div aria-hidden="true" className="scene-labels" style={{ font: labelFont }}>
{labels.map(({ id, x, y, width: labelWidth }) => (
<span key={id} style={{ left: x, top: y, width: labelWidth }} className={id === selectedOrbitId ? "is-selected" : ""}>
{labelCandidates.find((orbit) => orbit.id === id)?.name}
</span>
))}
</div>
{orbits.length >= orbitCapacity && <p className="scene-density">Select an orbit in the list to inspect it</p>}
</div> </div>
); );
} }
function LensedHole({ t, onToggle }: { t: number; onToggle: () => void }) {
const shimmer = 0.82 + 0.18 * Math.sin(t * 0.8);
return (
<g>
<ellipse
cx="0"
cy="0"
rx="168"
ry="22"
fill="none"
stroke="url(#diskBand)"
strokeWidth="16"
opacity={0.55 * shimmer}
filter="url(#diskGlow)"
/>
<ellipse
cx="18"
cy="0"
rx="150"
ry="11"
fill="none"
stroke="url(#diskBand)"
strokeWidth="5"
opacity="0.95"
/>
<path
d="M -120,10 Q 10,28 168,6"
fill="none"
stroke="url(#diskBand)"
strokeWidth="4.5"
strokeLinecap="round"
opacity="0.8"
/>
<circle cx="0" cy="0" r="38" fill="#000" />
<circle
cx="0"
cy="0"
r="41"
fill="none"
stroke="#fff4e4"
strokeWidth="1.7"
opacity="0.95"
/>
<circle
cx="0"
cy="0"
r="45"
fill="none"
stroke="#ffb15a"
strokeWidth="3.2"
opacity="0.55"
/>
<path
d="M -108,-6 C -46,-102 46,-102 108,-6"
fill="none"
stroke="url(#topArc)"
strokeWidth="10"
strokeLinecap="round"
opacity={0.95 * shimmer}
filter="url(#diskGlow)"
/>
<circle
cx="0"
cy="0"
r="48"
fill="transparent"
className="cursor-pointer"
onClick={onToggle}
/>
</g>
);
}
function InboundMeteor({ source, u }: { source: Vec2; u: number }) {
const head = spiralPoint(source, u);
const samples = Array.from({ length: 14 }, (_, i) => {
const k = u - (i / 13) * 0.42;
return spiralPoint(source, Math.max(0, k));
});
const fade = u > 0.88 ? 1 - (u - 0.88) / 0.12 : 1;
const trail = [...samples].reverse();
const d = trail
.map((p, i) => `${i === 0 ? "M" : "L"} ${p.x.toFixed(1)} ${p.y.toFixed(1)}`)
.join(" ");
return (
<g opacity={Math.max(0, fade)} pointerEvents="none">
<path
d={d}
fill="none"
stroke="#ffb15a"
strokeWidth="5"
strokeLinecap="round"
opacity="0.4"
filter="url(#softGlow)"
/>
<path
d={d}
fill="none"
stroke="#ffe6c4"
strokeWidth="1.7"
strokeLinecap="round"
/>
<circle cx={head.x} cy={head.y} r="4.2" fill="#fffaf3" />
</g>
);
}
function useMeteor(
pulse: number,
poseRef: RefObject<{ x: number; y: number }[]>,
) {
const [run, setRun] = useState<{ started: number; source: Vec2 } | null>(null);
const [now, setNow] = useState(0);
useEffect(() => {
if (!pulse) return;
const live = poseRef.current?.[0];
if (!live) return;
setNow(0);
setRun({ started: performance.now(), source: { x: live.x, y: live.y } });
}, [pulse, poseRef]);
useEffect(() => {
if (!run) return;
let raf = 0;
const tick = () => {
const u = (performance.now() - run.started) / METEOR_MS;
setNow(u);
if (u < 1) raf = requestAnimationFrame(tick);
else setRun(null);
};
raf = requestAnimationFrame(tick);
return () => cancelAnimationFrame(raf);
}, [run]);
if (!run || now >= 1) return null;
return { source: run.source, u: now };
}

View File

@@ -1,69 +1,35 @@
import { useMemo } from "react";
function rand(seed: number) { function rand(seed: number) {
let a = seed >>> 0; let state = seed >>> 0;
return () => { return () => {
a = (a + 0x6d2b79f5) | 0; state = (Math.imul(state, 1664525) + 1013904223) >>> 0;
let t = Math.imul(a ^ (a >>> 15), 1 | a); return state / 2 ** 32;
t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
}; };
} }
/** Deep starfield and a soft dust lane. Nothing here is clickable. */ const next = rand(0x51e11a);
export function SpaceBackdrop() { const stars = Array.from({ length: 120 }, (_, id) => ({
const stars = useMemo(() => { id,
const next = rand(0x51e11a); x: next() * 1000,
return Array.from({ length: 170 }, (_, i) => { y: next() * 650,
const bright = next() > 0.92; radius: 0.35 + next() ** 3 * 1.05,
return { opacity: 0.17 + next() * 0.48,
id: i, }));
left: `${next() * 100}%`,
top: `${next() * 100}%`,
size: bright ? 1.7 : next() > 0.7 ? 1.15 : 0.8,
opacity: bright ? 0.75 : 0.18 + next() * 0.38,
warm: next() > 0.82,
};
});
}, []);
export function SpaceBackdrop() {
return ( return (
<div <div className="space-backdrop" aria-hidden="true">
className="pointer-events-none absolute inset-0 overflow-hidden select-none" <svg width="100%" height="100%" viewBox="0 0 1000 650" preserveAspectRatio="xMidYMid slice">
aria-hidden <defs>
> <radialGradient id="vault-dust">
<div className="absolute inset-0 bg-[#05060c]" /> <stop stopColor="#6a4a36" stopOpacity=".25" />
<div className="absolute inset-0 bg-[radial-gradient(ellipse_at_center,rgba(16,18,32,0.2)_0%,rgba(5,6,12,0.92)_68%)]" /> <stop offset="1" stopColor="#332931" stopOpacity="0" />
<div </radialGradient>
className="absolute left-1/2 top-1/2 h-[38vh] w-[160vw] -translate-x-1/2 -translate-y-1/2 -rotate-[24deg] opacity-70" </defs>
style={{ <ellipse cx="500" cy="328" rx="480" ry="148" fill="url(#vault-dust)" transform="rotate(-13 500 328)" />
background: {stars.map(({ id, x, y, radius, opacity }) => (
"radial-gradient(ellipse at center, rgba(90,78,70,0.28) 0%, rgba(40,34,32,0.14) 36%, transparent 68%)", <circle key={id} cx={x} cy={y} r={radius} opacity={opacity} fill="#cbd4e4" />
filter: "blur(10px)",
}}
/>
<div
className="absolute left-1/2 top-1/2 h-[8vh] w-[120vw] -translate-x-1/2 -translate-y-1/2 -rotate-[16deg]"
style={{
background:
"linear-gradient(90deg, transparent 0%, rgba(180,140,100,0.16) 38%, rgba(220,190,160,0.22) 52%, rgba(140,100,80,0.12) 70%, transparent 100%)",
filter: "blur(10px)",
}}
/>
{stars.map((s) => (
<span
key={s.id}
className="absolute rounded-full"
style={{
left: s.left,
top: s.top,
width: s.size,
height: s.size,
opacity: s.opacity,
background: s.warm ? "#f0d2b0" : "#e7ecff",
}}
/>
))} ))}
</svg>
</div> </div>
); );
} }

View File

@@ -1,46 +0,0 @@
import { useMemo } from "react";
export function Starfield() {
const stars = useMemo(
() =>
Array.from({ length: 48 }, (_, i) => ({
id: i,
left: `${(i * 17 + 7) % 100}%`,
top: `${(i * 23 + 11) % 100}%`,
size: i % 3 === 0 ? 2 : 1,
opacity: 0.2 + (i % 5) * 0.12,
delay: `${(i % 8) * 0.4}s`,
})),
[],
);
return (
<div
className="pointer-events-none absolute inset-0 overflow-hidden opacity-60"
aria-hidden
>
<div className="stars-drift absolute inset-0 -top-[120px] h-[calc(100%+240px)]">
{stars.map((s) => (
<span
key={s.id}
className="absolute rounded-full bg-star-200"
style={{
left: s.left,
top: s.top,
width: s.size,
height: s.size,
opacity: s.opacity,
animation: `twinkle 4s ease-in-out ${s.delay} infinite alternate`,
}}
/>
))}
</div>
<style>{`
@keyframes twinkle {
from { opacity: 0.2; }
to { opacity: 0.9; }
}
`}</style>
</div>
);
}

View File

@@ -0,0 +1,87 @@
import { memo, useId, type Ref } from "react";
const LENS_ARC = "M-115 12 C-68 9 -67 -66 -9 -68 C52 -71 61 -10 111 6";
const streams = [
{ rx: 122, ry: 19, y: 10, width: 0.7, opacity: 0.30 },
{ rx: 116, ry: 19, y: 11, width: 1.1, opacity: 0.52 },
{ rx: 106, ry: 17, y: 12, width: 2.4, opacity: 0.72 },
{ rx: 92, ry: 15, y: 13, width: 3.6, opacity: 1 },
{ rx: 79, ry: 14, y: 14, width: 2.3, opacity: 0.9 },
{ rx: 66, ry: 12, y: 15, width: 0.9, opacity: 0.75 },
];
export const VaultCore = memo(function VaultCore({ ref }: { ref: Ref<SVGGElement> }) {
const id = useId();
const paint = (name: string) => `url(#${id}-${name})`;
return (
<g ref={ref} data-vault-core pointerEvents="none">
<defs>
<radialGradient id={`${id}-halo`}>
<stop stopColor="#e78347" stopOpacity=".2" />
<stop offset=".42" stopColor="#ac572e" stopOpacity=".17" />
<stop offset="1" stopColor="#7a3925" stopOpacity="0" />
</radialGradient>
<linearGradient id={`${id}-disk`}>
<stop stopColor="#923b1d" stopOpacity="0" />
<stop offset=".18" stopColor="#bc5f34" stopOpacity=".62" />
<stop offset=".42" stopColor="#d47c4a" />
<stop offset=".65" stopColor="#ffe6bb" />
<stop offset=".82" stopColor="#ffc38a" />
<stop offset="1" stopColor="#8b4328" stopOpacity="0" />
</linearGradient>
<linearGradient id={`${id}-lens`} x1="5%" y1="100%" x2="82%" y2="0%">
<stop stopColor="#b6532d" stopOpacity=".26" />
<stop offset=".46" stopColor="#d1885c" stopOpacity=".86" />
<stop offset=".72" stopColor="#ffe2b3" />
<stop offset="1" stopColor="#e49767" stopOpacity=".25" />
</linearGradient>
<filter id={`${id}-bloom`} x="-30%" y="-65%" width="160%" height="230%">
<feGaussianBlur stdDeviation="4.5" />
</filter>
<filter id={`${id}-soft`} x="-22%" y="-70%" width="144%" height="240%">
<feGaussianBlur stdDeviation="1.25" />
</filter>
</defs>
<ellipse rx="162" ry="81" cy="6" fill={paint("halo")} />
<g transform="rotate(-11)">
<path
d={`${LENS_ARC} M-114 13 C-62 38 -28 53 13 51 C54 48 89 27 111 6`}
fill="none" stroke={paint("lens")} strokeWidth="11" opacity=".42" filter={paint("bloom")}
/>
<path
d={LENS_ARC}
fill="none" stroke={paint("lens")} strokeWidth="3.4" filter={paint("soft")}
/>
<path
d="M-103 12 C-59 5 -61 -61 -8 -63 C42 -66 55 -12 99 7"
fill="none" stroke={paint("lens")} strokeWidth="1.2" opacity=".8"
/>
<path
className="accretion-flow" d={LENS_ARC} pathLength="100" strokeDasharray="8 37 11 44"
fill="none" stroke={paint("lens")} strokeWidth="2.5" strokeLinecap="round" opacity=".8"
/>
<ellipse cy="12" rx="115" ry="17" fill="none" stroke={paint("disk")} strokeWidth="6" opacity=".35" />
<circle r="49" fill="#030405" />
<circle r="49.6" fill="none" stroke={paint("lens")} strokeWidth="1.15" opacity=".78" />
<path d="M-92 17 C-60 39 43 48 106 14" fill="none" stroke={paint("disk")} strokeWidth="14" opacity=".5" filter={paint("bloom")} />
{streams.map(({ rx, ry, y, width, opacity }) => (
<path
key={rx}
d={`M${-rx} ${y} A${rx} ${ry} 0 0 0 ${rx} ${y}`}
fill="none" stroke={paint("disk")} strokeWidth={width} opacity={opacity}
/>
))}
<path
className="accretion-flow" d="M-116 11 A116 19 0 0 0 116 11" pathLength="100"
strokeDasharray="17 28 9 46" fill="none" stroke={paint("disk")} strokeWidth="2.8" strokeLinecap="round"
/>
<path
className="accretion-flow accretion-flow--inner" d="M-79 14 A79 14 0 0 0 79 14" pathLength="100"
strokeDasharray="12 24 19 45" fill="none" stroke={paint("disk")} strokeWidth="2" strokeLinecap="round"
/>
<path d="M-76 20 C-39 34 32 39 82 21" fill="none" stroke={paint("disk")} strokeWidth=".85" opacity=".7" />
</g>
</g>
);
});

View File

@@ -1,44 +1,81 @@
import type { Orbit, Snapshot } from "../../api"; import { BlackholeGalaxy, type CaptureArrival } from "./BlackholeGalaxy";
import { SpaceBackdrop } from "./SpaceBackdrop"; import { SpaceBackdrop } from "./SpaceBackdrop";
import { BlackholeGalaxy } from "./BlackholeGalaxy"; import type { Orbit, Snapshot } from "../../api";
export function VaultScene({ export function VaultScene({
orbits, orbits, selectedOrbitId, recentSnapshots, flowing, reducedMotion, arrival,
snapshots, bigScreen, onToggleBigScreen, onToggleFlow, onSelectOrbit, onSelectSnapshot,
flowing,
onToggleFlow,
onSelect,
onSelectOrbit,
selectedSnapshotId,
capturing,
capturePulse = 0,
}: { }: {
orbits: Orbit[]; orbits: Orbit[];
snapshots: Snapshot[]; selectedOrbitId?: string;
recentSnapshots: Snapshot[];
flowing: boolean; flowing: boolean;
reducedMotion: boolean;
arrival?: CaptureArrival;
bigScreen: boolean;
onToggleBigScreen: () => void;
onToggleFlow: () => void; onToggleFlow: () => void;
onSelect: (id: string) => void;
onSelectOrbit: (id: string) => void; onSelectOrbit: (id: string) => void;
selectedSnapshotId?: string | null; onSelectSnapshot: (id: string) => void;
capturing?: boolean;
capturePulse?: number;
}) { }) {
const selected = orbits.find(({ id }) => id === selectedOrbitId);
const screenLabel = bigScreen ? "Exit big screen" : "Big screen";
return ( return (
<div className="absolute inset-0 overflow-hidden bg-space-950"> <section className="vault-scene" aria-label="Orbital map">
<SpaceBackdrop /> <SpaceBackdrop />
<div className="relative z-10 h-full w-full"> <div className="scene-toolbar">
<div>
<p className="instrument-label">Vault map</p>
<p className="scene-mode">
<span className={`mode-signal${flowing ? " is-live" : ""}`} />
{flowing ? "Flowing" : "Locked"}
{!flowing && selected && <span className="scene-focus" title={selected.name}>· {selected.name}</span>}
</p>
</div>
<div className="scene-controls">
<button className="console-control" onClick={onToggleFlow} disabled={reducedMotion} type="button">
<svg viewBox="0 0 16 16" width="15" height="15" aria-hidden="true">
{flowing
? <path d="M6 3v10M10 3v10" stroke="currentColor" strokeWidth="1.5" />
: <path d="m6 3 7 5-7 5Z" fill="none" stroke="currentColor" strokeLinejoin="round" />}
</svg>
{reducedMotion ? "Reduced motion" : flowing ? "Pause motion" : "Resume motion"}
</button>
<button
className="console-control scene-screen-control"
onClick={onToggleBigScreen}
aria-label={screenLabel}
title={screenLabel}
type="button"
>
<svg viewBox="0 0 16 16" width="15" height="15" aria-hidden="true" fill="none"
stroke="currentColor" strokeWidth="1.25" strokeLinecap="round" strokeLinejoin="round">
{bigScreen
? <path d="M2 5h3V2m9 3h-3V2M2 11h3v3m9-3h-3v3" />
: <path d="M5 2H2v3m9-3h3v3M5 14H2v-3m9 3h3v-3" />}
</svg>
<span>{screenLabel}</span>
</button>
</div>
</div>
<BlackholeGalaxy <BlackholeGalaxy
orbits={orbits} orbits={orbits}
snapshots={snapshots} selectedOrbitId={selectedOrbitId}
recentSnapshots={recentSnapshots}
flowing={flowing} flowing={flowing}
capturing={capturing} reducedMotion={reducedMotion}
capturePulse={capturePulse} arrival={arrival}
onToggleFlow={onToggleFlow}
onSelectSnapshot={onSelect}
onSelectOrbit={onSelectOrbit} onSelectOrbit={onSelectOrbit}
selectedSnapshotId={selectedSnapshotId} onSelectSnapshot={onSelectSnapshot}
/> />
<div className="scene-footer">
<p>01 <span>·</span> Orbital projection</p>
<div className="scene-legend" aria-label="Map legend">
<span><i className="legend-orbit" /> Orbit</span>
<span><i className="legend-failed" /> Failed</span>
<span><i className="legend-snapshot" /> Snapshot</span>
</div> </div>
</div> </div>
</section>
); );
} }

View File

@@ -1,25 +1,28 @@
import type { ButtonHTMLAttributes } from "react"; import { motion, type HTMLMotionProps } from "motion/react";
const variants = { const variants = {
primary: primary:
"bg-wormhole-violet/25 text-star-100 border-wormhole-violet/40 hover:bg-wormhole-violet/35", "text-star-100 border-wormhole-violet/40 [--button-color:var(--color-wormhole-violet)] [--button-rest:25%] [--button-hover:35%]",
ghost: "bg-space-800/60 text-star-200 border-space-700 hover:bg-space-800", ghost: "text-star-200 border-space-700 [--button-color:var(--color-space-800)] [--button-rest:60%] [--button-hover:100%]",
danger: "bg-orbit-red/15 text-orbit-red border-orbit-red/35 hover:bg-orbit-red/25", danger: "text-orbit-red border-orbit-red/35 [--button-color:var(--color-orbit-red)]",
success: "bg-orbit-green/15 text-orbit-green border-orbit-green/35 hover:bg-orbit-green/25", success: "text-orbit-green border-orbit-green/35 [--button-color:var(--color-orbit-green)]",
warn: "bg-orbit-amber/15 text-orbit-amber border-orbit-amber/40 hover:bg-orbit-amber/25", warn: "text-orbit-amber border-orbit-amber/40 [--button-color:var(--color-orbit-amber)]",
}; };
export function Button({ export function Button({
variant = "ghost", variant = "ghost",
className = "", className = "",
...props ...props
}: ButtonHTMLAttributes<HTMLButtonElement> & { }: HTMLMotionProps<"button"> & {
variant?: keyof typeof variants; variant?: keyof typeof variants;
}) { }) {
return ( return (
<button <motion.button
type="button" type="button"
className={`px-4 py-2.5 rounded-xl text-sm font-medium border transition-colors disabled:opacity-40 ${variants[variant]} ${className}`} className={`vault-button px-4 py-2.5 rounded-xl text-sm font-medium border disabled:opacity-40 ${variants[variant]} ${className}`}
initial={false}
animate={{ "--button-mix": "0%" }}
whileHover={{ "--button-mix": "100%" }}
{...props} {...props}
/> />
); );

View File

@@ -1,5 +1,8 @@
import type { UseQueryResult } from "@tanstack/react-query"; import type { UseQueryResult } from "@tanstack/react-query";
import type { ReactNode } from "react"; import type { ReactNode } from "react";
import { motion } from "motion/react";
import { useReducedMotion } from "../../hooks/useReducedMotion";
import { ambientPulse } from "../../lib/motion";
import { Button } from "./Button"; import { Button } from "./Button";
export function QueryGate<T>({ export function QueryGate<T>({
@@ -11,10 +14,17 @@ export function QueryGate<T>({
empty?: ReactNode; empty?: ReactNode;
children: (data: T) => ReactNode; children: (data: T) => ReactNode;
}) { }) {
const reducedMotion = useReducedMotion();
if (query.isLoading) { if (query.isLoading) {
return ( return (
<div className="flex flex-col items-center justify-center py-16 text-star-400"> <div className="flex flex-col items-center justify-center py-16 text-star-400" role="status">
<div className="w-10 h-10 rounded-full border-2 border-wormhole-violet/40 border-t-wormhole-violet animate-spin" /> <motion.div
aria-hidden="true"
className="w-10 h-10 rounded-full border-2 border-wormhole-violet"
initial={{ opacity: reducedMotion ? 1 : 0.4 }}
animate={{ opacity: reducedMotion ? 1 : [0.4, 1] }}
transition={reducedMotion ? { type: false } : ambientPulse}
/>
<p className="mt-3 text-sm">Pulling telemetry from the vault…</p> <p className="mt-3 text-sm">Pulling telemetry from the vault…</p>
</div> </div>
); );

View File

@@ -1,21 +1,31 @@
import { motion } from "motion/react"; import { AnimatePresence, motion, useIsPresent } from "motion/react";
import type { ReactNode } from "react"; import type { ReactNode } from "react";
import { useReducedMotion } from "../../hooks/useReducedMotion";
export function Sheet({ type SheetContentProps = {
open,
onClose,
title,
children,
}: {
open: boolean;
onClose: () => void; onClose: () => void;
title: string; title: string;
children: ReactNode; children: ReactNode;
}) { };
if (!open) return null;
export function Sheet({ open, ...content }: SheetContentProps & { open: boolean }) {
return (
<AnimatePresence>
{open && <SheetContent key="sheet" {...content} />}
</AnimatePresence>
);
}
function SheetContent({ onClose, title, children }: SheetContentProps) {
const present = useIsPresent();
const reducedMotion = useReducedMotion();
const closedY = reducedMotion ? "0%" : "100%";
return ( return (
<motion.div <motion.div
className="fixed inset-0 z-40 flex flex-col justify-end" className="fixed inset-0 z-40 flex flex-col justify-end"
inert={!present}
style={{ pointerEvents: present ? undefined : "none" }}
initial={{ opacity: 0 }} initial={{ opacity: 0 }}
animate={{ opacity: 1 }} animate={{ opacity: 1 }}
exit={{ opacity: 0 }} exit={{ opacity: 0 }}
@@ -28,10 +38,9 @@ export function Sheet({
/> />
<motion.aside <motion.aside
className="relative z-10 max-h-[78dvh] overflow-y-auto rounded-t-3xl border-t border-space-700 bg-space-900/98 px-5 pt-4 pb-8 shadow-2xl" className="relative z-10 max-h-[78dvh] overflow-y-auto rounded-t-3xl border-t border-space-700 bg-space-900/98 px-5 pt-4 pb-8 shadow-2xl"
initial={{ y: "100%" }} initial={{ y: closedY }}
animate={{ y: 0 }} animate={{ y: "0%" }}
exit={{ y: "100%" }} exit={{ y: closedY }}
transition={{ type: "spring", damping: 28, stiffness: 320 }}
> >
<div className="mx-auto mb-3 h-1 w-10 rounded-full bg-space-700" /> <div className="mx-auto mb-3 h-1 w-10 rounded-full bg-space-700" />
<div className="flex items-center justify-between gap-3 mb-4"> <div className="flex items-center justify-between gap-3 mb-4">

View File

@@ -0,0 +1,25 @@
import { motion, useIsPresent } from "motion/react";
import type { ReactNode } from "react";
import { useReducedMotion } from "../../hooks/useReducedMotion";
export function SpringPane({ active = true, children }: { active?: boolean; children: ReactNode }) {
const present = useIsPresent();
const reducedMotion = useReducedMotion();
const visible = active && present;
const offset = reducedMotion ? 0 : 8;
return (
<motion.div
className="spring-pane"
aria-hidden={!visible}
inert={!visible}
initial={active && !reducedMotion ? { opacity: 0, y: offset } : false}
animate={active
? { opacity: 1, y: 0, visibility: "visible" }
: { opacity: 0, y: offset, transitionEnd: { visibility: "hidden" } }}
exit={{ opacity: 0, y: offset }}
>
{children}
</motion.div>
);
}

View File

@@ -13,18 +13,16 @@ export function SnapshotSheet({
return ( return (
<div className="space-y-4"> <div className="space-y-4">
<p className="text-sm text-star-300"> <p className="text-sm text-star-300">
A point-in-time tile on the vault ring — from orbit{" "} Recovery point for <strong className="text-star-100">{snap.orbit_name}</strong>.
<strong className="text-star-100">{snap.orbit_name}</strong>.
</p> </p>
<div className="rounded-xl bg-space-800/60 p-3 border border-space-700 text-sm"> <div className="rounded-xl bg-space-800/60 p-3 border border-space-700 text-sm">
<p className="text-star-400 text-xs">Captured</p> <p className="text-star-400 text-xs">Captured</p>
<p className="text-star-100 mt-1">{formatWhen(snap.taken_at)}</p> <p className="text-star-100 mt-1">{formatWhen(snap.taken_at)}</p>
<p className="text-star-400 text-xs mt-3">Payload</p> <p className="text-star-400 text-xs mt-3">Payload</p>
<p className="text-star-100">{formatBytes(snap.size_bytes)}</p> <p className="text-star-100">{formatBytes(snap.size_bytes)}</p>
<p className="text-star-400 text-xs mt-2 italic">Only stardust that changed</p>
</div> </div>
<Button variant="warn" className="w-full" onClick={onReconstitute}> <Button variant="warn" className="w-full" onClick={onReconstitute}>
Reconstitute this snapshot… Restore this snapshot
</Button> </Button>
<TelemetryPanel label="Snapshot ID">{snap.id}</TelemetryPanel> <TelemetryPanel label="Snapshot ID">{snap.id}</TelemetryPanel>
</div> </div>

View File

@@ -1,126 +0,0 @@
import { motion } from "motion/react";
import type { Snapshot } from "../../api";
import { formatBytes, formatWhen } from "../../lib/format";
export function VaultRing({
snapshots,
onSelect,
onCapture,
capturing,
}: {
snapshots: Snapshot[];
onSelect: (id: string) => void;
onCapture?: () => void;
capturing?: boolean;
}) {
const count = Math.max(snapshots.length, 1);
const radius = 128;
const tiles = snapshots.slice(0, 16);
return (
<div className="relative h-full w-full flex flex-col items-center justify-center px-4">
<div className="relative w-full max-w-[min(100vw,420px)] aspect-square flex items-center justify-center">
<svg
viewBox="-220 -220 440 440"
className="w-full h-full drop-shadow-[0_0_40px_rgba(167,139,250,0.12)]"
role="img"
aria-label="Orbital vault ring of snapshots"
>
<defs>
<radialGradient id="vaultGlow" cx="50%" cy="50%" r="50%">
<stop offset="0%" stopColor="#1e2647" stopOpacity="0.9" />
<stop offset="100%" stopColor="#04050c" stopOpacity="0" />
</radialGradient>
</defs>
<circle cx="0" cy="0" r="200" fill="url(#vaultGlow)" />
<circle
cx="0"
cy="0"
r={radius + 28}
fill="none"
stroke="#2d3a6b"
strokeWidth="1.5"
strokeDasharray="6 10"
opacity="0.7"
/>
<motion.circle
cx="0"
cy="0"
r={radius + 28}
fill="none"
stroke="#a78bfa"
strokeWidth="1"
strokeDasharray="40 200"
strokeLinecap="round"
opacity="0.35"
animate={{ rotate: 360 }}
transition={{ duration: 90, repeat: Infinity, ease: "linear" }}
style={{ transformOrigin: "0px 0px" }}
/>
<text
x="0"
y="-6"
textAnchor="middle"
fill="#94a3d4"
fontSize="13"
fontWeight="500"
>
Vault
</text>
<text x="0" y="14" textAnchor="middle" fill="#6b7ab8" fontSize="9">
{snapshots.length} snapshot{tiles.length === 1 ? "" : "s"}
</text>
{tiles.length === 0 && (
<text x="0" y="50" textAnchor="middle" fill="#6b7ab8" fontSize="10">
Capture your first orbit
</text>
)}
{tiles.map((snap, i) => {
const angle = (i / Math.max(count, tiles.length)) * Math.PI * 2 - Math.PI / 2;
const x = Math.cos(angle) * radius;
const y = Math.sin(angle) * radius;
return (
<motion.g
key={snap.id}
initial={{ scale: 0, opacity: 0 }}
animate={{ scale: 1, opacity: 1 }}
transition={{ delay: i * 0.04 }}
style={{ cursor: "pointer" }}
onClick={() => onSelect(snap.id)}
>
<circle cx={x} cy={y} r="22" fill="#141a36" stroke="#4ade9a" strokeWidth="2" />
<circle cx={x} cy={y} r="14" fill="#1e2647" opacity="0.8" />
<title>
{snap.orbit_name} · {formatWhen(snap.taken_at)}
</title>
</motion.g>
);
})}
</svg>
</div>
{onCapture && (
<motion.button
type="button"
disabled={capturing}
onClick={onCapture}
className="mt-2 px-6 py-3 rounded-full bg-orbit-green/20 border border-orbit-green/45 text-orbit-green font-medium text-sm disabled:opacity-50"
whileTap={{ scale: 0.96 }}
>
{capturing ? "Orbit in progress…" : "Capture now"}
</motion.button>
)}
<p className="mt-2 text-[10px] font-mono text-star-400/80 max-w-xs text-center uppercase tracking-wider">
Select tile · stardust delta only
</p>
</div>
);
}
export function SnapshotSummaryRow({ snap }: { snap: Snapshot }) {
return (
<div className="flex justify-between text-sm py-2 border-b border-space-700/50">
<span className="text-star-200">{snap.orbit_name}</span>
<span className="text-star-400 text-xs">{formatBytes(snap.size_bytes)}</span>
</div>
);
}

View File

@@ -1,34 +1,25 @@
import { useEffect, useRef, useState } from "react"; import { useLayoutEffect } from "react";
/** Seconds since mount, frozen while paused. */ export function useGalaxyMotion(active: boolean, draw: (elapsed: number) => boolean) {
export function useGalaxyTime(paused: boolean): number { useLayoutEffect(() => {
const [t, setT] = useState(0); let frame = 0;
const start = useRef(performance.now()); let previous: number | undefined;
const frozen = useRef(0); const tick = (now: number) => {
const wasPaused = useRef(paused); const keepDrawing = draw(previous === undefined ? 0 : (now - previous) / 1000);
previous = now;
useEffect(() => { if (keepDrawing) frame = requestAnimationFrame(tick);
if (paused) {
frozen.current = (performance.now() - start.current) / 1000;
wasPaused.current = true;
return;
}
if (wasPaused.current) {
start.current = performance.now() - frozen.current * 1000;
wasPaused.current = false;
}
let raf = 0;
const tick = () => {
setT((performance.now() - start.current) / 1000);
raf = requestAnimationFrame(tick);
}; };
raf = requestAnimationFrame(tick); const sync = () => {
return () => cancelAnimationFrame(raf); cancelAnimationFrame(frame);
}, [paused]); previous = undefined;
if (!document.hidden && active) frame = requestAnimationFrame(tick);
return paused ? frozen.current : t; };
} draw(0);
sync();
export function easeOutCubic(x: number): number { document.addEventListener("visibilitychange", sync);
return 1 - Math.pow(1 - x, 3); return () => {
cancelAnimationFrame(frame);
document.removeEventListener("visibilitychange", sync);
};
}, [active, draw]);
} }

View File

@@ -0,0 +1,12 @@
import { useSyncExternalStore } from "react";
const query = "(prefers-reduced-motion: reduce)";
function subscribe(change: () => void) {
const media = window.matchMedia(query);
media.addEventListener("change", change);
return () => media.removeEventListener("change", change);
}
export function useReducedMotion() {
return useSyncExternalStore(subscribe, () => window.matchMedia(query).matches);
}

View File

@@ -2,76 +2,440 @@
@import "tailwindcss"; @import "tailwindcss";
@theme { @theme {
--color-space-950: #04050c; --color-space-950: #090b0e;
--color-space-900: #0a0e1f; --color-space-900: #111418;
--color-space-800: #141a36; --color-space-800: #191d22;
--color-space-700: #1e2647; --color-space-700: #2b3138;
--color-star-100: #eef1ff; --color-star-100: #f0f0ec;
--color-star-200: #c9d2f5; --color-star-200: #d9dad6;
--color-star-300: #94a3d4; --color-star-300: #b6b9bc;
--color-star-400: #6b7ab8; --color-star-400: #9298a0;
--color-orbit-amber: #f0c468; --color-orbit-amber: #e8b57e;
--color-orbit-green: #4ade9a; --color-orbit-green: #8bcbb3;
--color-orbit-red: #f87171; --color-orbit-red: #ffa29c;
--color-wormhole-violet: #a78bfa; --color-wormhole-violet: #b4b9e1;
--font-sans: "DM Sans", system-ui, sans-serif; --font-sans: "DM Sans", system-ui, sans-serif;
--font-mono: "JetBrains Mono", ui-monospace, monospace; --font-mono: "JetBrains Mono", ui-monospace, monospace;
} }
html { :root {
font-family: var(--font-sans); color-scheme: dark;
--line: #282c31;
--quiet: #a0a6ad;
--accent: #f1bc90;
--panel: #111418;
} }
html, body {
body,
#root {
height: 100%;
margin: 0; margin: 0;
min-width: 0;
font-family: var(--font-sans);
color: var(--color-star-100);
background: var(--color-space-950);
} }
@layer utilities { button:enabled { cursor: pointer; }
.font-mono { button:disabled { cursor: default; }
font-family: var(--font-mono); .vault-button {
} background-color: color-mix(
.scrollbar-none { in oklab,
scrollbar-width: none; color-mix(in oklab, var(--button-color) var(--button-rest, 15%), transparent),
} color-mix(in oklab, var(--button-color) var(--button-hover, 25%), transparent) var(--button-mix, 0%)
.scrollbar-none::-webkit-scrollbar {
display: none;
}
}
.stars-drift {
animation: drift 120s linear infinite;
}
@keyframes drift {
from {
transform: translateY(0);
}
to {
transform: translateY(-120px);
}
}
.vignette::after {
content: "";
position: absolute;
inset: 0;
pointer-events: none;
box-shadow: inset 0 0 120px rgba(0, 0, 0, 0.65);
}
.scanlines::before {
content: "";
position: absolute;
inset: 0;
pointer-events: none;
opacity: 0.04;
background: repeating-linear-gradient(
0deg,
transparent,
transparent 2px,
rgba(255, 255, 255, 0.15) 3px
); );
} }
:focus-visible { outline: 2px solid var(--accent); outline-offset: -2px; }
.scrollbar-none { scrollbar-width: none; }
.vault-app { --vault-header-height: 70px; }
.vault-topbar {
position: sticky;
top: 0;
z-index: 30;
min-height: var(--vault-header-height);
padding: 0 clamp(16px, 3vw, 44px);
display: grid;
grid-template-columns: 1fr auto 1fr;
align-items: center;
border-bottom: 1px solid var(--line);
background: #0e1013;
}
.vault-brand { display: flex; align-items: center; gap: 11px; }
.vault-brand svg { flex: none; color: var(--accent); }
.vault-brand strong { display: block; font-size: 18px; font-weight: 650; line-height: 1.05; letter-spacing: -.035em; }
.vault-brand span, .instrument-label, .vault-telemetry dt, .scene-footer, .vault-footer {
font: 500 10px/1.5 var(--font-mono);
letter-spacing: .105em;
text-transform: uppercase;
color: var(--quiet);
}
.vault-brand span { display: block; margin-top: 5px; font-size: 9px; }
.vault-nav { position: relative; display: flex; align-self: stretch; gap: clamp(8px, 2vw, 27px); }
.vault-nav button {
position: relative;
z-index: 1;
min-height: 44px;
padding: 0 6px;
color: var(--quiet);
font-size: 13px;
white-space: nowrap;
touch-action: pan-y;
user-select: none;
}
.vault-nav button:hover, .vault-nav button[aria-current] { color: var(--color-star-100); }
.vault-nav button[aria-current] { cursor: grab; }
.vault-nav:active button[aria-current] { cursor: grabbing; }
.nav-text-dock {
position: absolute;
inset: 50% -8px auto;
height: 54px;
translate: 0 -50%;
scale: calc(0.94 + var(--dock-morph, 0) * 0.06) calc(0.83 + var(--dock-morph, 0) * 0.17);
opacity: var(--dock-morph, 0);
border: 1px solid #3a3d44;
border-radius: 999px;
background: #111418d9;
backdrop-filter: blur(14px);
box-shadow: inset 0 1px #ffffff12, 0 8px 24px #0005;
pointer-events: none;
}
.nav-underline {
position: absolute;
left: 0;
bottom: calc(-1px + var(--dock-morph, 0) * (50% - 16px));
height: calc(2px + var(--dock-morph, 0) * 32px);
translate: -50% 0;
pointer-events: none;
}
.nav-underline::before {
content: "";
position: absolute;
inset: 0 calc(-8px * var(--dock-morph, 0));
border-radius: 999px;
background: color-mix(in oklab, #4a3225 calc(var(--dock-morph, 0) * 100%), var(--accent));
}
.nav-liquid {
position: absolute;
inset: 0;
width: 100%;
height: 100%;
overflow: visible;
pointer-events: none;
}
.hub-link { justify-self: end; display: flex; align-items: center; gap: 8px; color: var(--color-star-300); font: 500 11px var(--font-mono); white-space: nowrap; }
.vault-main { max-width: 1720px; padding: 30px clamp(16px, 3vw, 44px) 10px; margin-inline: auto; }
.vault-overview { display: flex; align-items: end; justify-content: space-between; gap: 18px; margin-bottom: 25px; }
.overview-label span { color: var(--accent); margin-right: 5px; }
.vault-overview h1 { font-weight: 550; letter-spacing: -.055em; font-size: clamp(34px, 4vw, 55px); line-height: 1.02; margin: 7px 0; }
.overview-copy { font-size: 14px; color: var(--quiet); }
.vault-telemetry { display: grid; grid-template-columns: repeat(4, minmax(78px, auto)); border-block: 1px solid var(--line); padding-block: 10px; }
.vault-telemetry > div { padding-inline: clamp(8px, 1.5vw, 20px); }
.vault-telemetry > div + div { border-left: 1px solid var(--line); }
.vault-telemetry dd { font: 500 17px/1.6 var(--font-mono); white-space: nowrap; }
.vault-telemetry .telemetry-alert { color: var(--color-orbit-red); }
.vault-workspace {
--workspace-height: clamp(480px, calc(100dvh - 288px), 760px);
display: grid;
grid-template-columns: minmax(190px, .91fr) minmax(0, 3.1fr) minmax(224px, 1fr);
grid-template-areas: "register map inspector";
gap: 12px;
height: var(--workspace-height);
}
.vault-console, .vault-scene { position: relative; min-width: 0; border: 1px solid var(--line); border-radius: 10px; }
.vault-console { background: var(--panel); display: flex; flex-direction: column; min-height: 0; }
.orbit-register { grid-area: register; }
.orbit-inspector { grid-area: inspector; }
.console-heading { padding: 17px 16px 14px; }
.console-heading h2 { margin-top: 5px; font-weight: 600; font-size: 18px; line-height: 1.18; letter-spacing: -.025em; overflow-wrap: anywhere; }
.orbit-register .console-heading { border-bottom: 1px solid var(--line); }
.console-empty { padding: 0 16px; color: var(--quiet); font-size: 13px; line-height: 1.6; }
.orbit-register > .console-empty { padding-block: 12px; }
.register-list, .inspector-history ul { min-height: 0; overflow: auto; scrollbar-width: thin; scrollbar-color: #454952 transparent; }
.register-list { flex: 1; }
.register-list li + li, .inspector-history li + li { border-top: 1px solid #24282c; }
.register-row {
position: relative;
width: 100%;
min-height: 48px;
display: grid;
grid-template-columns: 9px minmax(0, 1fr) auto;
align-items: center;
gap: 8px;
padding: 7px 10px;
text-align: left;
}
.register-row:hover, .snapshot-row:hover { background: #1b1e23; }
.register-row[aria-pressed="true"] { background: #222025; box-shadow: inset 2px 0 var(--accent); }
.register-content { min-width: 0; }
.register-content span { display: block; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-size: 12px; }
.register-content small { display: block; margin-top: 2px; font: 10px/1.3 var(--font-mono); color: var(--quiet); }
.register-state { font: 10px/1.3 var(--font-mono); }
.tone-red { color: var(--color-orbit-red); }
.tone-amber { color: var(--color-orbit-amber); }
.tone-green { color: var(--color-orbit-green); }
.tone-grey { color: var(--quiet); }
.register-signal { flex: none; display: inline-block; width: 7px; height: 7px; background: var(--quiet); border-radius: 50%; }
.signal-red { border-radius: 1px; transform: rotate(45deg); background: var(--color-orbit-red); }
.signal-amber { background: transparent; border: 1px solid var(--color-orbit-amber); }
.signal-green { background: var(--color-orbit-green); }
.console-bottom { margin-top: auto; padding: 9px 10px; border-top: 1px solid var(--line); }
.console-bottom button { width: 100%; justify-content: space-between; }
.console-control {
display: inline-flex;
align-items: center;
gap: 8px;
min-height: 44px;
border: 1px solid #393e45;
border-radius: 6px;
padding: 0 11px;
background: #16191d;
color: var(--color-star-100);
font-size: 12px;
font-weight: 550;
text-align: left;
}
.console-control:enabled:hover { border-color: #74777b; background: #20242a; }
.console-control:disabled { color: var(--quiet); }
.console-control svg { color: var(--accent); }
.inspector-state { display: flex; align-items: center; gap: 7px; margin-top: 10px; font-size: 12px; }
.inspector-schedule { padding: 0 16px; color: var(--quiet); font-size: 13px; }
.inspector-capture { padding: 12px 16px 17px; }
.inspector-capture .capture-notice { margin-top: 8px; }
.capture-button { width: 100%; padding-block: 8px; background: #31241d; border-color: #76533d; color: #ffd0a9; }
.capture-button span:last-child { min-width: 0; overflow-wrap: anywhere; }
.capture-button:enabled:hover { background: #483125; border-color: var(--accent); }
.capture-button:disabled { background: #191a1d; }
.inspector-history { display: flex; flex-direction: column; min-height: 0; }
.inspector-history header { display: flex; justify-content: space-between; align-items: center; border-block: 1px solid var(--line); padding: 10px 16px; }
.inspector-history h3 { font-size: 12px; font-weight: 550; }
.inspector-history header span { color: var(--quiet); font: 11px var(--font-mono); }
.inspector-history .console-empty { padding-top: 10px; }
.snapshot-row { width: 100%; min-height: 52px; display: grid; grid-template-columns: 17px minmax(0, 1fr) 12px; align-items: center; gap: 8px; padding: 7px 13px; text-align: left; }
.snapshot-row strong { display: block; font-size: 12px; font-weight: 550; }
.snapshot-row small { display: block; margin-top: 3px; font: 10px/1.3 var(--font-mono); color: var(--quiet); }
.snapshot-glyph { color: #c6d2e6; font-size: 18px; }
.snapshot-arrow { color: var(--quiet); }
.vault-scene {
grid-area: map;
isolation: isolate;
display: grid;
grid-template-rows: auto 1fr auto;
background: #0a0c10;
overflow: hidden;
}
.vault-scene > :not(.space-backdrop) { position: relative; }
.space-backdrop { position: absolute; inset: 0; overflow: hidden; pointer-events: none; }
.space-backdrop::after {
position: absolute;
inset: 0;
content: "";
background: radial-gradient(ellipse at 48% 52%, transparent 42%, #080a0dd9 100%);
}
.scene-toolbar, .scene-footer { display: flex; align-items: center; justify-content: space-between; gap: 8px; padding: 14px; }
.scene-toolbar { z-index: 1; }
.scene-toolbar > div { min-width: 0; }
.scene-controls { display: flex; align-items: center; gap: 6px; }
.scene-toolbar button { flex: none; }
.scene-mode { display: flex; align-items: center; gap: 7px; margin-top: 3px; font-size: 13px; }
.mode-signal { flex: none; width: 6px; height: 6px; background: var(--accent); transform: rotate(45deg); border-radius: 1px; }
.mode-signal.is-live { background: var(--color-orbit-green); border-radius: 50%; transform: none; }
.scene-focus { min-width: 0; overflow: hidden; white-space: nowrap; text-overflow: ellipsis; color: var(--quiet); }
.scene-footer { border-top: 1px solid #24282c; background: #0a0c10bb; }
.scene-footer > p span { color: var(--accent); }
.scene-legend { display: flex; flex-wrap: wrap; gap: 6px 12px; color: var(--color-star-300); }
.scene-legend span { display: inline-flex; align-items: center; gap: 6px; }
.scene-legend i { width: 6px; height: 6px; display: inline-block; }
.legend-orbit { background: #dfe4ef; border-radius: 50%; }
.legend-failed { border: 1px solid var(--color-orbit-red); transform: rotate(45deg); }
.legend-snapshot { border: 1px solid #dfe4ef; transform: rotate(45deg); }
.galaxy-frame { width: 100%; max-width: calc((var(--workspace-height) - 120px) * 1.375); aspect-ratio: 11 / 8; align-self: center; justify-self: center; }
.galaxy-frame > svg { display: block; width: 100%; height: 100%; overflow: hidden; }
.orbit-tracks { fill: none; stroke: #949eaa; stroke-width: .75; opacity: .28; }
.orbit-tracks .is-selected { stroke: #eebf92; stroke-dasharray: 3 4; stroke-width: 1.6; }
.orbit-marker { color: #c3c9d0; }
.orbit-marker--red { color: var(--color-orbit-red); }
.orbit-marker--amber { color: var(--color-orbit-amber); }
.orbit-marker--green { color: var(--color-orbit-green); }
.orbit-light, .orbit-halo { fill: currentColor; pointer-events: none; }
.orbit-halo { opacity: .08; }
.orbit-alert, .orbit-selection, .orbit-busy { fill: none; stroke: currentColor; stroke-width: 1.15; pointer-events: none; }
.orbit-selection { stroke: #f8eadc; stroke-width: 1; }
.orbit-busy { stroke-dasharray: 3 3; }
.orbit-layer--far .orbit-marker:not(.orbit-marker--red, .orbit-marker--selected) { opacity: .76; }
.orbit-hit { fill: transparent; cursor: pointer; }
.orbit-marker:hover .orbit-halo { opacity: .3; }
.snapshot-marker line { stroke: #bdc4ce; opacity: .58; stroke-dasharray: 2 3; pointer-events: none; }
.snapshot-light { fill: #dce5f7; stroke: #272c35; stroke-width: 1.1; pointer-events: none; }
.snapshot-marker:hover .snapshot-light { fill: #fff; }
.focus-leader { stroke: var(--accent); opacity: .65; pointer-events: none; }
.accretion-flow { stroke-dashoffset: var(--accretion-offset, 0); }
.accretion-flow--inner { stroke-dashoffset: calc(32 + 2 * var(--accretion-offset, 0)); }
.capture-arrival path { stroke: #ffce9b; stroke-width: 2.3; stroke-linecap: round; }
.capture-arrival circle { fill: #fff0d9; }
.scene-labels { position: absolute; inset: 0; pointer-events: none; }
.scene-labels span { display: block; position: absolute; height: 24px; overflow: hidden; white-space: nowrap; text-overflow: ellipsis; line-height: 22px; color: #dde0e6; background: #111519ed; border: 1px solid #353c46; border-radius: 4px; padding-inline: 7px; }
.scene-labels span.is-selected { color: #ffe5cb; border-color: #8b6349; }
.scene-density { position: absolute; inset: auto 10px 0; color: var(--quiet); font-size: 11px; text-align: center; pointer-events: none; }
.vault-footer { min-height: 44px; display: flex; justify-content: space-between; align-items: center; gap: 12px; }
.capture-notice { margin-block: 4px; font: 500 12px/1.5 var(--font-mono); color: var(--color-star-200); text-transform: none; letter-spacing: 0; }
.capture-notice.tone-red { color: var(--color-orbit-red); }
.vault-overlay {
position: fixed;
inset: 0;
z-index: 20;
overflow: hidden;
pointer-events: none;
}
.vault-scrim { position: absolute; inset: 0; background: #030508b3; }
.vault-dialog {
position: absolute;
inset: var(--vault-header-height) 0 0 auto;
width: min(440px, 100%);
overflow: auto;
overscroll-behavior: contain;
pointer-events: auto;
background: #121519;
color: var(--color-star-100);
border-left: 1px solid #3b4048;
}
.vault-dialog[inert] { pointer-events: none; }
.dialog-heading { display: flex; gap: 12px; justify-content: space-between; align-items: start; padding: 18px 20px; position: sticky; top: 0; z-index: 1; background: #121519; border-bottom: 1px solid var(--line); }
.dialog-heading h2 { font-size: 23px; font-weight: 550; letter-spacing: -.035em; margin-top: 3px; }
.dialog-heading h2:focus { outline: none; }
.dialog-heading h2 + p { margin-top: 4px; color: var(--quiet); font-size: 13px; }
.dialog-content { padding: 18px 20px; }
.spring-stack { position: relative; min-width: 0; }
.spring-stack > .spring-pane[inert] { position: absolute; inset: 0 0 auto; pointer-events: none; }
.inspector-stack, .inspector-stack > .spring-pane { display: flex; flex: 1; flex-direction: column; min-height: 0; }
.big-screen {
--screen-gutter: clamp(12px, 2vw, 30px);
--screen-top: max(var(--screen-gutter), env(safe-area-inset-top));
--screen-bottom: max(var(--screen-gutter), env(safe-area-inset-bottom));
position: fixed;
inset: 0;
overflow: hidden;
background: #0a0c10;
}
.big-screen .vault-topbar { display: contents; }
.big-screen .vault-dialog { top: var(--screen-top); bottom: calc(var(--screen-bottom) + 64px); }
.big-screen :is(.vault-brand, .hub-link, .vault-console, .vault-footer, .scene-footer) { display: none; }
.big-screen .vault-main { padding: 0; }
.big-screen .vault-workspace,
.big-screen .vault-scene { position: absolute; inset: 0; display: grid; }
.big-screen .vault-workspace { grid-template: 1fr / 1fr; height: auto; }
.big-screen .vault-scene {
grid-template-rows: minmax(0, 1fr);
padding-block: 78px;
border: 0;
border-radius: 0;
}
.big-screen .galaxy-frame { max-width: calc((100dvh - 156px) * 1.375); }
.big-screen .vault-scene > .scene-toolbar {
position: absolute;
inset: var(--screen-top) auto auto max(var(--screen-gutter), env(safe-area-inset-left));
padding: 0;
}
.big-screen .scene-toolbar > div:first-child { max-width: 160px; margin-right: 8px; }
.big-screen .scene-toolbar .instrument-label { display: none; }
.big-screen .scene-mode { margin-top: 0; }
.big-screen .vault-overview {
position: absolute;
z-index: 2;
inset: var(--screen-top) max(var(--screen-gutter), env(safe-area-inset-right)) auto auto;
margin: 0;
}
.big-screen .vault-overview > div:first-child {
position: absolute;
width: 1px;
height: 1px;
overflow: hidden;
clip-path: inset(50%);
white-space: nowrap;
}
.big-screen :is(.vault-nav, .vault-telemetry) {
border: 1px solid #3a3d44;
background: #111418d9;
backdrop-filter: blur(14px);
}
.big-screen .vault-telemetry { border-radius: 8px; padding-block: 8px; }
.big-screen .vault-nav {
position: absolute;
z-index: 30;
bottom: var(--screen-bottom);
left: 50%;
transform: translateX(-50%);
gap: 4px;
max-width: calc(100% - 2 * var(--screen-gutter));
margin: 0;
padding: 5px 7px;
border-radius: 999px;
box-shadow: inset 0 1px #ffffff12, 0 8px 30px #0008;
}
.big-screen .vault-nav button {
display: grid;
place-items: center;
width: 46px;
border-radius: 999px;
padding: 0;
}
.big-screen .vault-nav button[aria-current] { color: #ffe2c9; }
@media (max-width: 1060px) {
.vault-workspace { grid-template-areas: "map map" "register inspector"; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); height: auto; }
.vault-console { min-height: 240px; max-height: 420px; }
}
@media (max-width: 640px) {
.vault-app { --vault-header-height: 105px; }
.vault-topbar { grid-template-columns: 1fr auto; gap: 0 10px; padding-top: 11px; }
.vault-nav { grid-row: 2; grid-column: 1 / -1; justify-content: space-between; margin-top: 7px; gap: 3px; }
.vault-nav button { padding-inline: 5px; font-size: 12px; }
.vault-main { padding: 19px 12px 9px; }
.vault-overview { align-items: stretch; flex-direction: column; gap: 14px; margin-bottom: 14px; }
.vault-telemetry { grid-template-columns: repeat(3, minmax(0, 1fr)) minmax(76px, auto); }
.vault-telemetry dd { font-size: 14px; }
.vault-workspace { grid-template-areas: "map" "register" "inspector"; grid-template-columns: minmax(0, 1fr); gap: 10px; }
.vault-console { min-height: 0; }
.register-list { max-height: 196px; }
.orbit-inspector { max-height: 480px; padding-bottom: 8px; }
.inspector-stack .console-empty { padding-bottom: 8px; }
.galaxy-frame { max-width: none; }
.scene-toolbar, .scene-footer { padding: 9px; }
.scene-footer > p { display: none; }
.scene-footer { justify-content: center; }
.vault-footer > p:last-child { text-align: right; }
}
@media (max-width: 740px) {
.big-screen .vault-scene { padding-block: 120px 70px; }
.big-screen .galaxy-frame { max-width: calc((100dvh - 190px) * 1.375); }
.big-screen .vault-overview { top: calc(var(--screen-top) + 54px); }
.big-screen .vault-telemetry { grid-template-columns: repeat(4, auto); }
.big-screen .vault-telemetry dd { font-size: 14px; }
.big-screen .scene-toolbar > div:first-child { display: none; }
}
@media (max-height: 480px) and (orientation: landscape) and (min-width: 560px) {
.big-screen .vault-scene { padding-block: 56px; }
.big-screen .galaxy-frame { max-width: calc((100dvh - 112px) * 1.375); }
.big-screen .vault-overview { top: var(--screen-top); }
}
@media (max-width: 520px) {
.vault-app:not(.big-screen) .scene-screen-control { min-width: 44px; justify-content: center; }
.vault-app:not(.big-screen) .scene-screen-control span { display: none; }
}
@media (max-width: 380px) {
.big-screen .vault-nav { gap: 2px; }
.big-screen .vault-telemetry > div { padding-inline: 7px; }
}

View File

@@ -22,6 +22,18 @@ export function schedulePhrase(cron?: string | null, dryRun?: boolean): string {
export type VaultStatus = "green" | "amber" | "grey" | "red"; export type VaultStatus = "green" | "amber" | "grey" | "red";
export function orbitStatus(status: string): { label: string; tone: VaultStatus; busy?: boolean } {
switch (status) {
case "failed": return { label: "Failed", tone: "red" };
case "running": return { label: "Running", tone: "amber", busy: true };
case "rehearsing": return { label: "Rehearsing", tone: "amber", busy: true };
case "rehearsed": return { label: "Rehearsed", tone: "amber" };
case "completed": return { label: "Completed", tone: "green" };
case "idle": return { label: "Idle", tone: "grey" };
default: return { label: status || "Unknown", tone: "grey" };
}
}
export function vaultStatusFromOrbits( export function vaultStatusFromOrbits(
orbits: { last_status: string }[], orbits: { last_status: string }[],
): VaultStatus { ): VaultStatus {

View File

@@ -1,137 +1,38 @@
import type { Vec2 } from "./galaxyLayout"; export type Rect = { x: number; y: number; width: number; height: number };
type Label = { id: string; x: number; y: number; width: number };
export const LABEL_HEIGHT = 24;
const GAP = 4;
export type LabelPlacement = { function overlaps(a: Rect, b: Rect) {
x: number; return a.x < b.x + b.width + GAP && a.x + a.width + GAP > b.x &&
y: number; a.y < b.y + b.height + GAP && a.y + a.height + GAP > b.y;
};
const CHAR_W = 6.4;
const LABEL_H = 14;
const LABEL_PAD = 6;
function labelWidth(name: string): number {
const n = name.length > 16 ? 15 : name.length;
return n * CHAR_W;
} }
function dist(a: LabelPlacement, b: LabelPlacement): number { export function placeLabels(
return Math.hypot(a.x - b.x, a.y - b.y); candidates: Label[],
} width: number,
height: number,
/** Radial outward labels with simple bbox separation (lock mode). */ obstacles: Rect[],
export function layoutLockLabels( ): Label[] {
starPositions: Vec2[], const occupied = [...obstacles];
names: string[], const placed: Label[] = [];
starR: number, for (const label of candidates) {
): LabelPlacement[] { const { x, y, width: w } = label;
const vaultPad = 108; const offsets = [12, 28, 44].flatMap((gap) => [
const labels: LabelPlacement[] = starPositions.map((p, i) => { [gap, -LABEL_HEIGHT / 2], [-w - gap, -LABEL_HEIGHT / 2],
const ang = Math.atan2(p.y, p.x); [-w / 2, -LABEL_HEIGHT - gap], [-w / 2, gap],
const base = starR + 28; [gap, -LABEL_HEIGHT - gap / 2], [-w - gap, gap / 2],
return { ]);
x: p.x + Math.cos(ang) * base, for (const [dx, dy] of offsets) {
y: p.y + Math.sin(ang) * base, const rect = { x: x + dx, y: y + dy, width: w, height: LABEL_HEIGHT };
}; if (rect.x < GAP || rect.y < GAP || rect.x + w > width - GAP ||
}); rect.y + LABEL_HEIGHT > height - GAP || occupied.some((other) => overlaps(rect, other))) {
continue;
for (let iter = 0; iter < 48; iter++) { }
for (let i = 0; i < labels.length; i++) { occupied.push(rect);
const p = starPositions[i]; placed.push({ id: label.id, ...rect });
const r = dist(labels[i], { x: 0, y: 0 }); break;
if (r < vaultPad) { }
const ang = Math.atan2(labels[i].y, labels[i].x); }
labels[i].x = Math.cos(ang) * vaultPad; return placed;
labels[i].y = Math.sin(ang) * vaultPad;
}
for (let j = i + 1; j < labels.length; j++) {
const wi = labelWidth(names[i]);
const wj = labelWidth(names[j]);
const dx = labels[j].x - labels[i].x;
const dy = labels[j].y - labels[i].y;
const needX = (wi + wj) / 2 + LABEL_PAD;
const needY = LABEL_H + LABEL_PAD;
if (Math.abs(dx) < needX && Math.abs(dy) < needY) {
const push = (needX - Math.abs(dx) + needY - Math.abs(dy)) * 0.35;
const ang = Math.atan2(dy, dx) || 0;
labels[i].x -= Math.cos(ang) * push;
labels[i].y -= Math.sin(ang) * push;
labels[j].x += Math.cos(ang) * push;
labels[j].y += Math.sin(ang) * push;
}
}
const outward = Math.atan2(
labels[i].y - starPositions[i].y,
labels[i].x - starPositions[i].x,
);
const minDist = starR + 26;
const dStar = dist(labels[i], starPositions[i]);
if (dStar < minDist) {
labels[i].x = starPositions[i].x + Math.cos(outward) * minDist;
labels[i].y = starPositions[i].y + Math.sin(outward) * minDist;
}
}
}
const yMin = -160;
const yMax = 108;
const xMin = -230;
const xMax = 230;
for (let i = 0; i < labels.length; i++) {
const star = starPositions[i];
const hitsChrome =
labels[i].y < yMin ||
labels[i].y > yMax ||
labels[i].x < xMin ||
labels[i].x > xMax;
const hitsNeighbor = starPositions.some(
(other, k) => k !== i && dist(labels[i], other) < starR + 20,
);
if (hitsChrome || hitsNeighbor) {
const ang = Math.atan2(star.y, star.x);
labels[i] = {
x: star.x - Math.cos(ang) * (starR + 34),
y: star.y - Math.sin(ang) * (starR + 34),
};
}
labels[i].x = Math.max(xMin, Math.min(xMax, labels[i].x));
labels[i].y = Math.max(yMin, Math.min(yMax, labels[i].y));
const gap = dist(labels[i], star);
if (gap < starR + 16) {
const ang = Math.atan2(labels[i].y - star.y, labels[i].x - star.x) || 0;
labels[i].x = star.x + Math.cos(ang) * (starR + 18);
labels[i].y = Math.max(
yMin,
Math.min(yMax, star.y + Math.sin(ang) * (starR + 18)),
);
}
}
for (let iter = 0; iter < 24; iter++) {
for (let i = 0; i < labels.length; i++) {
for (let j = i + 1; j < labels.length; j++) {
const wi = labelWidth(names[i]);
const wj = labelWidth(names[j]);
const dx = labels[j].x - labels[i].x;
const dy = labels[j].y - labels[i].y;
const needX = (wi + wj) / 2 + 8;
const needY = LABEL_H + 6;
if (Math.abs(dx) < needX && Math.abs(dy) < needY) {
const push = (needX - Math.abs(dx)) * 0.55 + 1;
const dir = dx === 0 ? (i % 2 === 0 ? -1 : 1) : Math.sign(dx);
labels[i].x -= dir * push;
labels[j].x += dir * push;
}
}
labels[i].x = Math.max(xMin, Math.min(xMax, labels[i].x));
labels[i].y = Math.max(yMin, Math.min(yMax, labels[i].y));
}
}
return labels;
}
export function shortenOrbitName(name: string): string {
return name.length > 16 ? `${name.slice(0, 14)}…` : name;
} }

View File

@@ -1,68 +1,105 @@
/** Face-on orrery: two even shells around the vault. */ import type { Orbit, Snapshot } from "../api";
export type Vec2 = { x: number; y: number }; export type Vec2 = { x: number; y: number };
type OrbitSlot = { radius: number; angle: number; speed: number };
export type ShellBody = { export const SCENE_WIDTH = 660;
index: number; export const SCENE_HEIGHT = 480;
shell: "inner" | "outer"; export const ORBIT_TILT = 0.68;
radius: number;
baseAngle: number;
size: number;
warm: boolean;
};
const INNER_R = 112; const shells = [
const OUTER_R = 178; { radius: 128, count: 10, step: 3, speed: 0.047 },
{ radius: 190, count: 18, step: 7, speed: 0.033 },
{ radius: 260, count: 28, step: 11, speed: 0.023 },
];
/** Inner shell is fewer, larger, warmer. Outer shell is the rest. */ const slots = Array.from({ length: 28 }, (_, index) =>
export function assignShells(count: number): ShellBody[] { shells.flatMap(({ radius, count, step, speed }, shell) =>
if (count <= 0) return []; index < count
let innerCount = Math.max(1, Math.round(count * 0.38)); ? [{ radius, speed, angle: ((index * step) / count) * 2 * Math.PI - 1.2 + shell * 0.9 }]
if (count > 4) innerCount = Math.max(3, innerCount); : [],
innerCount = Math.min(innerCount, count); ),
const outerCount = count - innerCount; ).flat();
const bodies: ShellBody[] = [];
for (let i = 0; i < innerCount; i++) { export const orbitRadii = shells.map(({ radius }) => radius);
bodies.push({ export const orbitCapacity = slots.length;
index: i,
shell: "inner", export function assignOrbitSlots(
radius: INNER_R, ids: string[],
baseAngle: -Math.PI / 2 + (i / innerCount) * Math.PI * 2, previous = new Map<string, OrbitSlot>(),
size: 11, selected?: string,
warm: true, ): Map<string, OrbitSlot> {
}); const currentIds = new Set(ids);
const next = new Map([...previous].filter(([id]) => currentIds.has(id)));
const occupied = new Set(next.values());
const free = slots.filter((slot) => !occupied.has(slot));
// shortcut: overview has a fixed number of slots, add level of detail if dense fleets need spatial navigation.
// Reserve the final slot for inspection when the overview is full.
const selectedSlot = slots[slots.length - 1];
for (const [id, slot] of next) {
if (slot === selectedSlot && id !== selected) next.delete(id);
} }
for (let i = 0; i < outerCount; i++) { const available = free.filter((slot) => slot !== selectedSlot);
bodies.push({ for (const id of ids) {
index: innerCount + i, if (next.has(id)) continue;
shell: "outer", const slot = available.shift();
radius: OUTER_R, if (!slot) break;
baseAngle: -Math.PI / 2 + ((i + 0.5) / outerCount) * Math.PI * 2, next.set(id, slot);
size: 6.4,
warm: false,
});
} }
return bodies; if (selected && currentIds.has(selected) && !next.has(selected)) {
next.set(selected, selectedSlot);
}
return next;
} }
export function shellPose(body: ShellBody, time: number): Vec2 & { angle: number } { export function orbitPose(slot: OrbitSlot, time: number): Vec2 {
const speed = body.shell === "inner" ? 0.18 : 0.11; const angle = slot.angle + time * slot.speed;
const angle = body.baseAngle + time * speed;
return { return {
angle, x: Math.cos(angle) * slot.radius,
x: Math.cos(angle) * body.radius, y: Math.sin(angle) * slot.radius * ORBIT_TILT,
y: Math.sin(angle) * body.radius,
}; };
} }
/** Point on a smooth inward spiral. u = 0 is the source; u = 1 is the shadow. */ export function moonPoses(star: Vec2, count: number, distance: number, obstacles: Vec2[] = []): Vec2[] {
export function spiralPoint(source: Vec2, u: number): Vec2 { const direction = Math.atan2(star.y, star.x);
const clamped = Math.min(1, Math.max(0, u)); const margin = distance / 2;
const a0 = Math.atan2(source.y, source.x); for (const offset of [0, Math.PI / 4, -Math.PI / 4, Math.PI / 2, -Math.PI / 2, Math.PI]) {
const r0 = Math.hypot(source.x, source.y); const positions = Array.from({ length: count }, (_, index) => {
const fall = 1 - Math.pow(clamped, 0.92); const angle = direction + offset + (index - (count - 1) / 2) * Math.PI / 3;
const spin = clamped * Math.PI * 1.05; return { x: star.x + Math.cos(angle) * distance, y: star.y + Math.sin(angle) * distance };
const r = r0 * fall; });
const a = a0 + spin; if (positions.every(({ x, y }) =>
return { x: Math.cos(a) * r, y: Math.sin(a) * r }; Math.abs(x) < SCENE_WIDTH / 2 - margin && Math.abs(y) < SCENE_HEIGHT / 2 - margin &&
obstacles.every((point) => Math.hypot(point.x - x, point.y - y) >= 14),
)) return positions;
}
return [];
}
export function groupSnapshots(orbits: Orbit[], snapshots: Snapshot[]): Map<string, Snapshot[]> {
const ids = new Set(orbits.map(({ id }) => id));
const names = new Map<string, string | null>();
for (const { id, name } of orbits) {
names.set(name, names.has(name) ? null : id);
}
const groups = new Map<string, Snapshot[]>();
for (const snapshot of snapshots) {
const id = snapshot.orbit_id ?? names.get(snapshot.orbit_name);
if (!id || !ids.has(id)) continue;
const group = groups.get(id) ?? [];
group.push(snapshot);
groups.set(id, group);
}
for (const group of groups.values()) {
group.sort((a, b) => Date.parse(b.taken_at) - Date.parse(a.taken_at));
}
return groups;
}
export function spiralPoint(source: Vec2, progress: number): Vec2 {
const u = Math.min(1, Math.max(0, progress));
const angle = Math.atan2(source.y, source.x) + u * Math.PI * 1.15;
const radius = Math.hypot(source.x, source.y) * (1 - u ** 1.4);
return { x: Math.cos(angle) * radius, y: Math.sin(angle) * radius };
} }

16
web/src/lib/motion.ts Normal file
View File

@@ -0,0 +1,16 @@
import type { Transition } from "motion/react";
export const uiSpring = {
type: "spring",
stiffness: 320,
damping: 36,
mass: 1,
} as const satisfies Transition;
export const ambientPulse = {
...uiSpring,
stiffness: 40,
damping: 13,
repeat: Infinity,
repeatType: "mirror",
} as const satisfies Transition;

View File

@@ -1,15 +1,27 @@
import { StrictMode } from "react"; import { StrictMode } from "react";
import { createRoot } from "react-dom/client"; import { createRoot } from "react-dom/client";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { MotionConfig } from "motion/react";
import App from "./App"; import App from "./App";
import { useReducedMotion } from "./hooks/useReducedMotion";
import { uiSpring } from "./lib/motion";
import "./index.css"; import "./index.css";
const queryClient = new QueryClient(); const queryClient = new QueryClient();
function MotionApp() {
const reducedMotion = useReducedMotion();
return (
<MotionConfig reducedMotion={reducedMotion ? "always" : "never"} transition={reducedMotion ? { type: false } : uiSpring}>
<App />
</MotionConfig>
);
}
createRoot(document.getElementById("root")!).render( createRoot(document.getElementById("root")!).render(
<StrictMode> <StrictMode>
<QueryClientProvider client={queryClient}> <QueryClientProvider client={queryClient}>
<App /> <MotionApp />
</QueryClientProvider> </QueryClientProvider>
</StrictMode>, </StrictMode>,
); );