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.
This commit is contained in:
2026-11-10 09:53:06 +07:00
parent 60ba8fed88
commit 95778d54e4
46 changed files with 2311 additions and 415 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/

299
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"
@@ -1356,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"
@@ -1418,6 +1595,8 @@ dependencies = [
"anyhow", "anyhow",
"base64", "base64",
"clap", "clap",
"rustls",
"rustls-pemfile",
"serde", "serde",
"serde_json", "serde_json",
"tessera-core", "tessera-core",
@@ -1483,17 +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-demo",
"tessera-providers", "tessera-providers",
"tessera-store", "tessera-store",
"tokio", "tokio",
"tokio-rustls",
"tower",
"tower-http", "tower-http",
"tracing", "tracing",
"tracing-subscriber", "tracing-subscriber",
@@ -1521,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",
@@ -1567,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"
@@ -1596,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"
@@ -1745,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"
@@ -2023,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"
@@ -2043,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,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

@@ -37,7 +37,8 @@ async fn run_orbit_row(state: &HubState, orbit: OrbitRow) -> Result<Option<Uuid>
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)?;

View File

@@ -1,7 +1,8 @@
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, HeaderMap, HeaderValue, StatusCode, Uri}, http::{header, HeaderMap, HeaderValue, StatusCode, Uri},
response::IntoResponse, response::IntoResponse,
routing::{get, post}, routing::{get, post},
@@ -9,8 +10,11 @@ use axum::{
}; };
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;
@@ -109,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))
@@ -141,7 +153,12 @@ 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
@@ -158,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()
@@ -169,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,
@@ -190,19 +215,26 @@ async fn create_orbit(
#[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")))))] #[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, HeaderMap), StatusCode> { ) -> Result<(StatusCode, HeaderMap), (StatusCode, String)> {
require_admin(&state, peer, &headers).map_err(|status| (status, "unauthorized".into()))?;
let snapshot_id = crate::api::run_orbit_internal(state, id) let snapshot_id = crate::api::run_orbit_internal(state, id)
.await .await
.map_err(|error| { .map_err(|error| {
tracing::warn!(orbit_id = %id, %error, "capture did not complete"); tracing::warn!(orbit_id = %id, %error, "capture did not complete");
StatusCode::INTERNAL_SERVER_ERROR (StatusCode::INTERNAL_SERVER_ERROR, error.to_string())
})?; })?;
let mut headers = HeaderMap::new(); let mut headers = HeaderMap::new();
if let Some(snapshot_id) = snapshot_id { if let Some(snapshot_id) = snapshot_id {
let value = HeaderValue::from_str(&snapshot_id.to_string()) let value = HeaderValue::from_str(&snapshot_id.to_string()).map_err(|_| {
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; (
StatusCode::INTERNAL_SERVER_ERROR,
"snapshot id header".into(),
)
})?;
headers.insert("x-tessera-snapshot-id", value); headers.insert("x-tessera-snapshot-id", value);
} }
Ok((StatusCode::NO_CONTENT, headers)) Ok((StatusCode::NO_CONTENT, headers))
@@ -210,9 +242,12 @@ async fn trigger_orbit(
#[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,
@@ -273,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!(
@@ -298,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;
@@ -312,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)))]
@@ -327,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,
})) }))
} }
@@ -354,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 })))
} }
@@ -373,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,10 +1,10 @@
use crate::admin::AdminGate;
use crate::db::Db; use crate::db::Db;
use anyhow::Result; use anyhow::Result;
use std::collections::{HashMap, HashSet}; 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::{Mutex, RwLock}; use tokio::sync::{Mutex, RwLock};
use uuid::Uuid; use uuid::Uuid;
@@ -15,18 +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 active_orbits: Arc<Mutex<HashSet<Uuid>>>,
} pub admin: AdminGate,
pub wormhole_mtls: bool,
#[derive(Clone)] /// Token uploads are accepted on this listener. Plain HTTP turns this off
pub struct PairingEntry { /// when wormhole mTLS is required, so those routes are not a bypass.
pub code: String, pub accept_plain_upload: bool,
pub expires_at: chrono::DateTime<chrono::Utc>,
pub state: PairingState,
pub outpost_id: Uuid,
pub upload_token: String,
} }
impl HubState { impl HubState {
@@ -49,14 +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())), 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 mut salt = [0u8; SALT_LEN]; let marker = salt_path.with_file_name("kdf.json");
rand::thread_rng().fill_bytes(&mut salt); if marker.exists() {
if let Some(parent) = salt_path.parent() { let spec: KdfSpec = serde_json::from_slice(&fs::read(&marker)?)?;
fs::create_dir_all(parent)?; let salt = fs::read(salt_path)?;
} restrict_secret_file(salt_path)?;
fs::write(salt_path, &salt)?; return derive_marked(passphrase, &salt, &spec);
salt.to_vec() }
}; 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 key = [0u8; 32]; let mut salt = [0u8; SALT_LEN];
pbkdf2::<Hmac<Sha256>>(passphrase.as_bytes(), &salt, 100_000, &mut key); rand::thread_rng().fill_bytes(&mut salt);
if let Some(parent) = salt_path.parent() {
let cipher = fs::create_dir_all(parent)?;
Aes256Gcm::new_from_slice(&key).map_err(|e| anyhow!("cipher key: {e}"))?; }
Ok(Self { cipher }) fs::write(salt_path, &salt)?;
restrict_secret_file(salt_path)?;
let spec = KdfSpec::argon2id();
fs::write(&marker, serde_json::to_vec_pretty(&spec)?)?;
restrict_secret_file(&marker)?;
derive_marked(passphrase, &salt, &spec)
} }
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;
if path.exists() { for suffix in [".json.enc", ".json"] {
fs::remove_file(&path)?; let path = self.root.join("snapshots").join(format!("{id}{suffix}"));
if path.exists() {
fs::remove_file(&path)?;
gone = true;
}
}
if gone {
removed += 1; removed += 1;
} }
} }
@@ -236,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::*;
@@ -315,4 +355,69 @@ mod tests {
.iter() .iter()
.any(|s| s.manifest.orbit_id == other_id)); .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

@@ -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

@@ -4,12 +4,14 @@ The persistent viewport maps backup jobs and recovery points. The black hole rep
## Viewport and consoles ## Viewport and consoles
- **Flowing** animates the projected orbits and the black hole's accretion disk. **Locked** freezes their motion and prioritizes labels for the selected, failed, and running orbits. Pause or resume from the map toolbar. Selecting an orbit locks the map. Reduced motion starts in Locked mode. - **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. - 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.
- 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. - 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.
- 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. - 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. - 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. - **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.
## Data and rendering ## Data and rendering
@@ -18,6 +20,14 @@ The persistent viewport maps backup jobs and recovery points. The black hole rep
- 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. - 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. - 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.
## Animation guideline
- 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.
## Local verification ## Local verification
Build the web UI before building the hub, which embeds the generated assets. Build the web UI before building the hub, which embeds the generated assets.

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,6 +2,7 @@
"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",

View File

@@ -1,4 +1,5 @@
import { useEffect, useLayoutEffect, useMemo, useRef, 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, fetchHealth, fetchOrbits, fetchSnapshots, pollReconstitute, abortReconstitute, fetchHealth, fetchOrbits, fetchSnapshots, pollReconstitute,
@@ -14,6 +15,7 @@ import { ReconstituteWizard } from "./components/reconstitute/ReconstituteWizard
import { VaultScene } from "./components/scene/VaultScene"; import { VaultScene } from "./components/scene/VaultScene";
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 { SnapshotSheet } from "./components/vault/SnapshotSheet";
import { useReducedMotion } from "./hooks/useReducedMotion"; import { useReducedMotion } from "./hooks/useReducedMotion";
import { orbitStatus } from "./lib/format"; import { orbitStatus } from "./lib/format";
@@ -38,6 +40,7 @@ export default function App() {
const workspaceScroll = useRef<number>(undefined); const workspaceScroll = useRef<number>(undefined);
const [bigScreen, setBigScreen] = useState(false); const [bigScreen, setBigScreen] = useState(false);
const [mode, setMode] = useState<HUDMode>("scene"); const [mode, setMode] = useState<HUDMode>("scene");
const panelOpen = mode !== "scene";
const [orbitId, setOrbitId] = useState<string>(); const [orbitId, setOrbitId] = useState<string>();
const [snapshotId, setSnapshotId] = useState<string | null>(null); 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);
@@ -169,14 +172,14 @@ export default function App() {
</svg> </svg>
<div><strong>Tessera</strong><span>Backup control</span></div> <div><strong>Tessera</strong><span>Backup control</span></div>
</div> </div>
<HUDRail active={mode === "snapshot" ? "scene" : mode} onSelect={openConsole} /> <HUDRail active={mode === "snapshot" ? "scene" : mode} floating={bigScreen} panelOpen={panelOpen} reducedMotion={reducedMotion} onSelect={openConsole} />
<p className="hub-link" role="status"> <p className="hub-link" role="status">
<span className={`register-signal signal-${online ? "green" : "grey"}`} /> <span className={`register-signal signal-${online ? "green" : "grey"}`} />
{online ? "Hub online" : health.isPending ? "Connecting" : "Hub offline"} {online ? "Hub online" : health.isPending ? "Connecting" : "Hub offline"}
</p> </p>
</header> </header>
<main className="vault-main"> <main className="vault-main" inert={panelOpen}>
<div className="vault-overview"> <div className="vault-overview">
<div> <div>
<p className="instrument-label overview-label"><span aria-hidden="true">◈</span> Vault / 01</p> <p className="instrument-label overview-label"><span aria-hidden="true">◈</span> Vault / 01</p>
@@ -227,22 +230,34 @@ export default function App() {
</main> </main>
<HUDPanel <HUDPanel
open={mode !== "scene"} open={panelOpen}
title={panelTitles[mode]} title={panelTitles[mode]}
subtitle={mode === "reconstitute" ? "Review the destination before starting the restore." : undefined} subtitle={mode === "reconstitute" ? "Review the destination before starting the restore." : undefined}
onClose={() => setMode("scene")} onClose={() => setMode("scene")}
> >
{mode === "orbits" && ( <AnimatePresence initial={false}>
<QueryGate query={orbits}> {mode === "orbits" && (
{() => <OrbitsView orbits={sceneOrbits} onRun={runCapture} captureDisabled={!online || capture.isPending} notice={captureNotice} />} <SpringPane key="orbits">
</QueryGate> <QueryGate query={orbits}>
)} {() => <OrbitsView orbits={sceneOrbits} onRun={runCapture} captureDisabled={!online || capture.isPending} notice={captureNotice} />}
{mode === "wormhole" && <WormholeView pairing={pairing} onPaired={setPairing} />} </QueryGate>
{mode === "decay" && <DecayView appliedPresets={sceneOrbits.map((orbit) => orbit.decay_preset ?? "week-of-dailies")} />} </SpringPane>
{mode === "snapshot" && (snapshot ? ( )}
<SnapshotSheet snap={snapshot} onReconstitute={() => openConsole("reconstitute", snapshot.id)} /> {mode === "wormhole" && (
) : <EmptyState title="Snapshot unavailable" body="It may have expired under the retention policy." />)} <SpringPane key="wormhole"><WormholeView pairing={pairing} onPaired={setPairing} /></SpringPane>
<div hidden={mode !== "reconstitute"}> )}
{mode === "decay" && (
<SpringPane key="decay"><DecayView appliedPresets={sceneOrbits.map((orbit) => orbit.decay_preset ?? "week-of-dailies")} /></SpringPane>
)}
{mode === "snapshot" && (
<SpringPane key="snapshot">
{snapshot
? <SnapshotSheet snap={snapshot} onReconstitute={() => openConsole("reconstitute", snapshot.id)} />
: <EmptyState title="Snapshot unavailable" body="It may have expired under the retention policy." />}
</SpringPane>
)}
</AnimatePresence>
<SpringPane active={mode === "reconstitute"}>
{restoreTarget && (snaps.data?.length || restoreBusy ? ( {restoreTarget && (snaps.data?.length || restoreBusy ? (
<ReconstituteWizard <ReconstituteWizard
key={restoreTarget.id ?? "manual"} key={restoreTarget.id ?? "manual"}
@@ -254,7 +269,7 @@ export default function App() {
{() => null} {() => null}
</QueryGate> </QueryGate>
))} ))}
</div> </SpringPane>
</HUDPanel> </HUDPanel>
</div> </div>
); );

View File

@@ -1,6 +1,9 @@
import { AnimatePresence, motion } from "motion/react";
import type { KeyboardEvent, ReactNode } from "react"; import type { KeyboardEvent, ReactNode } from "react";
import type { Orbit, Snapshot } from "../../api"; import type { Orbit, Snapshot } from "../../api";
import { useReducedMotion } from "../../hooks/useReducedMotion";
import { formatBytes, formatWhen, orbitStatus, schedulePhrase } from "../../lib/format"; import { formatBytes, formatWhen, orbitStatus, schedulePhrase } from "../../lib/format";
import { SpringPane } from "../ui/SpringPane";
export function TelemetryStrip({ export function TelemetryStrip({
orbitCount, failedCount, snapCount, totalBytes, orbitCount, failedCount, snapCount, totalBytes,
@@ -29,6 +32,7 @@ export function OrbitRegister({
onSelect: (id: string) => void; onSelect: (id: string) => void;
onManage: () => void; onManage: () => void;
}) { }) {
const reducedMotion = useReducedMotion();
const active = orbits.some(({ id }) => id === selected) ? selected : orbits[0]?.id; const active = orbits.some(({ id }) => id === selected) ? selected : orbits[0]?.id;
function moveFocus(event: KeyboardEvent<HTMLButtonElement>, index: number) { function moveFocus(event: KeyboardEvent<HTMLButtonElement>, index: number) {
@@ -47,11 +51,11 @@ export function OrbitRegister({
<h2 id="register-title">Orbits</h2> <h2 id="register-title">Orbits</h2>
</header> </header>
{message && <p className="console-empty" role="status">{message}</p>} {message && <p className="console-empty" role="status">{message}</p>}
<ul className="register-list"> <motion.ul className="register-list" layoutScroll>
{orbits.map((orbit, index) => { {orbits.map((orbit, index) => {
const status = orbitStatus(orbit.last_status); const status = orbitStatus(orbit.last_status);
return ( return (
<li key={orbit.id}> <motion.li key={orbit.id} layout={reducedMotion ? false : "position"}>
<button <button
type="button" type="button"
id={`register-${orbit.id}`} id={`register-${orbit.id}`}
@@ -68,10 +72,10 @@ export function OrbitRegister({
</span> </span>
<span className={`register-state tone-${status.tone}`}>{status.label}</span> <span className={`register-state tone-${status.tone}`}>{status.label}</span>
</button> </button>
</li> </motion.li>
); );
})} })}
</ul> </motion.ul>
<div className="console-bottom"> <div className="console-bottom">
<button type="button" className="console-control" onClick={onManage}> <button type="button" className="console-control" onClick={onManage}>
{orbits.length ? "Manage orbits" : "Set up an orbit"} <span aria-hidden="true">↗</span> {orbits.length ? "Manage orbits" : "Set up an orbit"} <span aria-hidden="true">↗</span>
@@ -98,35 +102,41 @@ export function OrbitInspector({
<h2 id="inspector-title">{orbit?.name ?? "Select an orbit"}</h2> <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>} {orbit && <p className={`inspector-state tone-${status.tone}`}><span className={`register-signal signal-${status.tone}`} />{status.label}</p>}
</header> </header>
{orbit ? ( <div className="spring-stack inspector-stack">
<> <AnimatePresence initial={false}>
<p className="inspector-schedule">{schedulePhrase(orbit.schedule, orbit.dry_run)}</p> {orbit ? (
<div className="inspector-capture">{capture}</div> <SpringPane key={orbit.id}>
<section className="inspector-history" aria-labelledby="history-title"> <p className="inspector-schedule">{schedulePhrase(orbit.schedule, orbit.dry_run)}</p>
<header> <div className="inspector-capture">{capture}</div>
<h3 id="history-title">Snapshot history</h3> <section className="inspector-history" aria-label="Snapshot history">
<span>{snapshots.length.toString().padStart(2, "0")}</span> <header>
</header> <h3>Snapshot history</h3>
{snapshotMessage && <p className="console-empty" role="status">{snapshotMessage}</p>} <span>{snapshots.length.toString().padStart(2, "0")}</span>
<ul> </header>
{snapshots.map((snapshot, index) => ( {snapshotMessage && <p className="console-empty" role="status">{snapshotMessage}</p>}
<li key={snapshot.id}> <ul>
<button id={`snapshot-${snapshot.id}`} type="button" className="snapshot-row" onClick={() => onSelectSnapshot(snapshot.id)}> {snapshots.map((snapshot, index) => (
<span className="snapshot-glyph" aria-hidden="true">◇</span> <li key={snapshot.id}>
<span> <button id={`snapshot-${snapshot.id}`} type="button" className="snapshot-row" onClick={() => onSelectSnapshot(snapshot.id)}>
<strong>{formatWhen(snapshot.taken_at)}</strong> <span className="snapshot-glyph" aria-hidden="true">◇</span>
<small>{formatBytes(snapshot.size_bytes)}{index === 0 ? " · Latest" : ""}</small> <span>
</span> <strong>{formatWhen(snapshot.taken_at)}</strong>
<span className="snapshot-arrow" aria-hidden="true">›</span> <small>{formatBytes(snapshot.size_bytes)}{index === 0 ? " · Latest" : ""}</small>
</button> </span>
</li> <span className="snapshot-arrow" aria-hidden="true">›</span>
))} </button>
</ul> </li>
</section> ))}
</> </ul>
) : ( </section>
<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>
)} ) : (
<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> </section>
); );
} }

View File

@@ -1,4 +1,5 @@
import { useId, useLayoutEffect, useRef, type ReactNode } from "react"; import { motion } from "motion/react";
import { useEffect, useId, useLayoutEffect, useRef, type ReactNode } from "react";
export function HUDPanel({ export function HUDPanel({
open, title, subtitle, onClose, children, open, title, subtitle, onClose, children,
@@ -9,46 +10,73 @@ export function HUDPanel({
onClose: () => void; onClose: () => void;
children: ReactNode; children: ReactNode;
}) { }) {
const dialog = useRef<HTMLDialogElement>(null); const panel = useRef<HTMLElement>(null);
const heading = useRef<HTMLHeadingElement>(null); const heading = useRef<HTMLHeadingElement>(null);
const returnFocus = useRef<HTMLElement>(null);
const lastHeading = useRef({ title, subtitle });
const labelId = useId(); const labelId = useId();
const descriptionId = useId(); const descriptionId = useId();
useLayoutEffect(() => { useLayoutEffect(() => {
const panel = dialog.current; const focused = document.activeElement;
if (!open || !panel) return; if (open) {
panel.showModal(); returnFocus.current = focused instanceof HTMLElement ? focused : null;
return () => panel.close(); 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]); }, [open]);
useLayoutEffect(() => { useLayoutEffect(() => {
if (open) heading.current?.focus(); if (open) {
}, [open, title]); 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 (
<dialog <div className="vault-overlay">
ref={dialog} <motion.div className="vault-scrim" aria-hidden="true" initial={false} animate={{ opacity: open ? 1 : 0 }} />
className="vault-dialog" <motion.aside
aria-labelledby={labelId} ref={panel}
aria-describedby={subtitle ? descriptionId : undefined} className="vault-dialog"
onCancel={(event) => { role="dialog"
event.preventDefault(); aria-labelledby={labelId}
onClose(); aria-describedby={display.subtitle ? descriptionId : undefined}
}} aria-hidden={!open}
> inert={!open}
{open && ( initial={false}
animate={{ x: open ? "0%" : "100%" }}
>
<header className="dialog-heading"> <header className="dialog-heading">
<div> <div>
<p className="instrument-label">Vault console</p> <p className="instrument-label">Vault console</p>
<h2 id={labelId} ref={heading} tabIndex={-1}>{title}</h2> <h2 id={labelId} ref={heading} tabIndex={-1}>{display.title}</h2>
{subtitle && <p id={descriptionId}>{subtitle}</p>} {display.subtitle && <p id={descriptionId}>{display.subtitle}</p>}
</div> </div>
<button type="button" className="console-control" onClick={onClose}> <button type="button" className="console-control" onClick={onClose}>
Close <span aria-hidden="true">×</span> Close <span aria-hidden="true">×</span>
</button> </button>
</header> </header>
)} <div className="dialog-content"><div className="spring-stack">{children}</div></div>
<div className="dialog-content">{children}</div> </motion.aside>
</dialog> </div>
); );
} }

View File

@@ -1,31 +1,189 @@
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" | "snapshot"; export type HUDMode = "scene" | "orbits" | "wormhole" | "decay" | "reconstitute" | "snapshot";
const items = [ const items = [
{ id: "scene", label: "Vault" }, { 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" }, { 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: "Outposts" }, { 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: "Retention" }, { id: "decay", label: "Retention", icon: "M6 4h12 M6 20h12 M8 4v3l4 5-4 5v3 M16 4v3l-4 5 4 5v3" },
{ id: "reconstitute", label: "Restore" }, { id: "reconstitute", label: "Restore", icon: "M4 12a8 8 0 1 1 2.3 5.7 M4 6v6h6 M12 8v4l3 2" },
] as const; ] 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, onSelect, active, floating, panelOpen, reducedMotion, onSelect,
}: { }: {
active: HUDMode; active: HUDMode;
floating: boolean;
panelOpen: boolean;
reducedMotion: boolean;
onSelect: (mode: HUDMode) => void; onSelect: (mode: HUDMode) => void;
}) { }) {
const nav = useRef<HTMLElement>(null);
const slots = useRef<Slot[]>([]);
const gesture = useRef<Gesture>(undefined);
const suppressClick = useRef(false);
const center = useMotionValue(0);
const width = useMotionValue(0);
const velocity = useVelocity(center);
const tail = useTransform(() => center.get() - Math.max(-22, Math.min(22, velocity.get() * 0.032)));
const id = useId();
const activeIndex = Math.max(0, items.findIndex(item => item.id === active));
const snap = useCallback((index: number, immediate = false) => {
const slot = slots.current[index];
if (!slot) return;
if (immediate || reducedMotion) {
center.jump(slot.center);
width.jump(slot.width);
} else {
animate(center, slot.center, uiSpring);
animate(width, slot.width, uiSpring);
}
}, [center, reducedMotion, width]);
useLayoutEffect(() => () => {
center.stop();
width.stop();
}, [center, width]);
useLayoutEffect(() => {
const element = nav.current!;
const buttons = Array.from(element.querySelectorAll("button"));
const measure = () => {
const left = element.getBoundingClientRect().left + element.clientLeft;
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;
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 ( return (
<nav className="vault-nav" aria-label="Vault systems"> <motion.nav
{items.map(({ id, label }) => ( 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 <button
key={id} key={id}
type="button" type="button"
aria-label={floating ? label : undefined}
title={floating ? label : undefined}
onClick={() => onSelect(id)} onClick={() => onSelect(id)}
aria-current={active === id ? "page" : undefined} aria-current={active === id ? "page" : undefined}
> >
{label} {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> </button>
))} ))}
</nav> </motion.nav>
); );
} }

View File

@@ -1,4 +1,5 @@
import { useState, type ReactNode } 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 } from "../../api"; import { createOrbit } from "../../api";
@@ -7,6 +8,7 @@ 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({ export function OrbitsView({
orbits, onRun, captureDisabled, notice, orbits, onRun, captureDisabled, notice,
@@ -80,74 +82,82 @@ export function OrbitsView({
))} ))}
</div> </div>
{editing ? ( <div className="spring-stack">
<div className="rounded-2xl border border-wormhole-violet/30 bg-space-900 p-4 space-y-3"> <AnimatePresence initial={false}>
<h3 className="font-medium text-star-100">New orbit</h3> {editing ? (
<label className="block text-sm"> <SpringPane key="form">
<span className="text-star-400">Name</span> <div className="rounded-2xl border border-wormhole-violet/30 bg-space-900 p-4 space-y-3">
<input <h3 className="font-medium text-star-100">New orbit</h3>
className="mt-1 w-full rounded-xl bg-space-950 border border-space-700 px-3 py-2" <label className="block text-sm">
value={name} <span className="text-star-400">Name</span>
onChange={(e) => setName(e.target.value)} <input
/> className="mt-1 w-full rounded-xl bg-space-950 border border-space-700 px-3 py-2"
</label> value={name}
<label className="block text-sm"> onChange={(e) => setName(e.target.value)}
<span className="text-star-400">Folder path</span> />
<input </label>
className="mt-1 w-full rounded-xl bg-space-950 border border-space-700 px-3 py-2 font-mono text-xs" <label className="block text-sm">
value={path} <span className="text-star-400">Folder path</span>
onChange={(e) => setPath(e.target.value)} <input
/> className="mt-1 w-full rounded-xl bg-space-950 border border-space-700 px-3 py-2 font-mono text-xs"
</label> value={path}
<label className="block text-sm"> onChange={(e) => setPath(e.target.value)}
<span className="text-star-400">Schedule (cron)</span> />
<input </label>
className="mt-1 w-full rounded-xl bg-space-950 border border-space-700 px-3 py-2 font-mono text-xs" <label className="block text-sm">
value={schedule} <span className="text-star-400">Schedule (cron)</span>
onChange={(e) => setSchedule(e.target.value)} <input
/> className="mt-1 w-full rounded-xl bg-space-950 border border-space-700 px-3 py-2 font-mono text-xs"
</label> value={schedule}
<label className="block text-sm"> onChange={(e) => setSchedule(e.target.value)}
<span className="text-star-400">Decay</span> />
<select </label>
className="mt-1 w-full rounded-xl bg-space-950 border border-space-700 px-3 py-2" <label className="block text-sm">
value={preset} <span className="text-star-400">Decay</span>
onChange={(e) => setPreset(e.target.value)} <select
> className="mt-1 w-full rounded-xl bg-space-950 border border-space-700 px-3 py-2"
{DECAY_PRESETS.map((p) => ( value={preset}
<option key={p.id} value={p.id}> onChange={(e) => setPreset(e.target.value)}
{p.title} >
</option> {DECAY_PRESETS.map((p) => (
))} <option key={p.id} value={p.id}>
</select> {p.title}
</label> </option>
<label className="flex items-center gap-2 text-sm text-star-300"> ))}
<input type="checkbox" checked={rehearse} onChange={(e) => setRehearse(e.target.checked)} /> </select>
Rehearse only (dry run) </label>
</label> <label className="flex items-center gap-2 text-sm text-star-300">
<Hint> <input type="checkbox" checked={rehearse} onChange={(e) => setRehearse(e.target.checked)} />
Rehearse orbits prove the path without writing to the vault — status shows amber “rehearsed”. Rehearse only (dry run)
</Hint> </label>
{create.isError && <p role="alert" className="text-sm text-orbit-red">The orbit could not be saved.</p>} <Hint>
<div className="flex gap-2"> Rehearse orbits prove the path without writing to the vault — status shows amber “rehearsed”.
<Button className="flex-1" onClick={() => setEditing(false)}> </Hint>
Cancel {create.isError && <p role="alert" className="text-sm text-orbit-red">The orbit could not be saved.</p>}
</Button> <div className="flex gap-2">
<Button <Button className="flex-1" onClick={() => setEditing(false)}>
variant="primary" Cancel
className="flex-1" </Button>
disabled={create.isPending} <Button
onClick={() => create.mutate()} variant="primary"
> className="flex-1"
Save orbit disabled={create.isPending}
</Button> onClick={() => create.mutate()}
</div> >
</div> Save orbit
) : ( </Button>
<Button variant="primary" className="w-full" onClick={() => setEditing(true)}> </div>
Add an orbit </div>
</Button> </SpringPane>
)} ) : (
<SpringPane key="add">
<Button variant="primary" className="w-full" onClick={() => setEditing(true)}>
Add an orbit
</Button>
</SpringPane>
)}
</AnimatePresence>
</div>
</div> </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

@@ -1,4 +1,5 @@
import { useEffect, useState } from "react"; import { useEffect, useState } from "react";
import { motion } from "motion/react";
import type { Snapshot } from "../../api"; import type { Snapshot } from "../../api";
import { formatBytes, formatWhen } from "../../lib/format"; import { formatBytes, formatWhen } from "../../lib/format";
import { Button } from "../ui/Button"; import { Button } from "../ui/Button";
@@ -108,21 +109,23 @@ export function ReconstituteWizard({
</label> </label>
{inCountdown && ( {inCountdown && (
<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"
initial={{ opacity: 0 }}
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">
@@ -132,7 +135,7 @@ export function ReconstituteWizard({
<p className="mt-3 text-orbit-amber text-sm font-medium"> <p className="mt-3 text-orbit-amber text-sm font-medium">
Reconstituting in {remaining}s — abort restores nothing. Reconstituting in {remaining}s — abort restores nothing.
</p> </p>
</div> </motion.div>
)} )}
<div className="flex gap-2"> <div className="flex gap-2">

View File

@@ -1,4 +1,5 @@
import { useCallback, useLayoutEffect, useMemo, useRef, useState } from "react"; import { useCallback, useLayoutEffect, useMemo, useRef, useState } from "react";
import { animate, spring, useMotionValue } from "motion/react";
import type { Orbit, Snapshot } from "../../api"; import type { Orbit, Snapshot } from "../../api";
import { orbitStatus } from "../../lib/format"; import { orbitStatus } from "../../lib/format";
import { LABEL_HEIGHT, placeLabels, type Rect } from "../../lib/galaxyLabelLayout"; import { LABEL_HEIGHT, placeLabels, type Rect } from "../../lib/galaxyLabelLayout";
@@ -7,6 +8,7 @@ import {
SCENE_HEIGHT, SCENE_WIDTH, spiralPoint, type Vec2, SCENE_HEIGHT, SCENE_WIDTH, spiralPoint, type Vec2,
} from "../../lib/galaxyLayout"; } from "../../lib/galaxyLayout";
import { useGalaxyMotion } from "../../hooks/useGalaxyMotion"; import { useGalaxyMotion } from "../../hooks/useGalaxyMotion";
import { uiSpring } from "../../lib/motion";
import { VaultCore } from "./VaultCore"; import { VaultCore } from "./VaultCore";
export type CaptureArrival = { orbitId: string; snapshotId: string }; export type CaptureArrival = { orbitId: string; snapshotId: string };
@@ -16,6 +18,7 @@ type Props = {
selectedOrbitId?: string; selectedOrbitId?: string;
recentSnapshots: Snapshot[]; recentSnapshots: Snapshot[];
flowing: boolean; flowing: boolean;
reducedMotion: boolean;
arrival?: CaptureArrival; arrival?: CaptureArrival;
onSelectOrbit: (id: string) => void; onSelectOrbit: (id: string) => void;
onSelectSnapshot: (id: string) => void; onSelectSnapshot: (id: string) => void;
@@ -25,22 +28,38 @@ const HALF_WIDTH = SCENE_WIDTH / 2;
const HALF_HEIGHT = SCENE_HEIGHT / 2; const HALF_HEIGHT = SCENE_HEIGHT / 2;
const labelFont = "500 11px ui-monospace, monospace"; const labelFont = "500 11px ui-monospace, monospace";
const MAX_LABELS = 12; const MAX_LABELS = 12;
const METEOR_SECONDS = 1.4;
const ACCRETION_SECONDS = 6.4; const ACCRETION_SECONDS = 6.4;
export function BlackholeGalaxy({ export function BlackholeGalaxy({
orbits, selectedOrbitId, recentSnapshots, flowing, arrival, onSelectOrbit, onSelectSnapshot, orbits, selectedOrbitId, recentSnapshots, flowing, reducedMotion, arrival, onSelectOrbit, onSelectSnapshot,
}: Props) { }: Props) {
const frame = useRef<HTMLDivElement>(null); const frame = useRef<HTMLDivElement>(null);
const bodyNodes = useRef(new Map<SVGGElement, { id: string; far: boolean }>()); const bodyNodes = useRef(new Map<SVGGElement, { id: string; far: boolean }>());
const slotsBefore = useRef<ReturnType<typeof assignOrbitSlots>>(undefined); const slotsBefore = useRef<ReturnType<typeof assignOrbitSlots>>(undefined);
const elapsed = useRef(0); const elapsed = useRef(0);
const core = useRef<SVGGElement>(null); const core = useRef<SVGGElement>(null);
const meteor = useRef<{ id: string; time: number; source: Vec2 }>(undefined); const meteor = useRef<{ id: string; time: number; source: Vec2; progress: ReturnType<typeof spring> }>(undefined);
const trail = useRef<SVGPathElement>(null); const trail = useRef<SVGPathElement>(null);
const head = useRef<SVGCircleElement>(null); const head = useRef<SVGCircleElement>(null);
const effect = useRef<SVGGElement>(null); const effect = useRef<SVGGElement>(null);
const [width, setWidth] = useState(0); const [width, setWidth] = useState(0);
const [coasting, setCoasting] = useState(false);
const rate = useMotionValue(flowing && !reducedMotion ? 1 : 0);
const moving = !reducedMotion && (flowing || coasting);
useLayoutEffect(() => () => rate.stop(), [rate]);
useLayoutEffect(() => {
if (reducedMotion) {
rate.jump(0);
setCoasting(false);
return;
}
const target = flowing ? 1 : 0;
if (rate.get() === target && !rate.isAnimating()) return;
setCoasting(!flowing);
animate(rate, target, { ...uiSpring, onComplete: () => setCoasting(false) });
}, [flowing, rate, reducedMotion]);
const slots = useMemo( const slots = useMemo(
() => assignOrbitSlots(orbits.map(({ id }) => id), slotsBefore.current, selectedOrbitId), () => assignOrbitSlots(orbits.map(({ id }) => id), slotsBefore.current, selectedOrbitId),
@@ -58,8 +77,8 @@ export function BlackholeGalaxy({
}, []); }, []);
const draw = useCallback((delta: number) => { const draw = useCallback((delta: number) => {
if (flowing && delta > 0) { if (moving && delta > 0) {
elapsed.current += delta; elapsed.current += delta * Math.max(0, rate.get());
const phase = (elapsed.current % ACCRETION_SECONDS) / ACCRETION_SECONDS; const phase = (elapsed.current % ACCRETION_SECONDS) / ACCRETION_SECONDS;
core.current?.style.setProperty("--accretion-offset", String(-100 * phase)); core.current?.style.setProperty("--accretion-offset", String(-100 * phase));
} }
@@ -74,37 +93,42 @@ export function BlackholeGalaxy({
node.setAttribute("transform", `translate(${x} ${y})`); node.setAttribute("transform", `translate(${x} ${y})`);
} }
if (!arrival) { if (!arrival || reducedMotion) {
effect.current?.setAttribute("opacity", "0"); effect.current?.setAttribute("opacity", "0");
return flowing; return moving;
} }
const slot = slots.get(arrival.orbitId); const slot = slots.get(arrival.orbitId);
if (meteor.current?.id !== arrival.snapshotId && slot) { if (meteor.current?.id !== arrival.snapshotId && slot) {
const source = orbitPose(slot, elapsed.current); const source = orbitPose(slot, elapsed.current);
meteor.current = { id: arrival.snapshotId, time: 0, source }; meteor.current = {
id: arrival.snapshotId,
time: 0,
source,
progress: spring({ ...uiSpring, stiffness: 36, damping: 12, keyframes: [0, 1], restDelta: 0.002 }),
};
const points = Array.from({ length: 36 }, (_, i) => spiralPoint(source, i / 35)); 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(" ")); trail.current?.setAttribute("d", points.map(({ x, y }, i) => `${i ? "L" : "M"} ${x} ${y}`).join(" "));
} }
const current = meteor.current; const current = meteor.current;
if (!current || current.id !== arrival.snapshotId) return flowing; if (!current || current.id !== arrival.snapshotId) return moving;
current.time += delta; current.time += delta * 1000;
const progress = Math.min(1, current.time / METEOR_SECONDS); const { value: progress, done } = current.progress.next(current.time);
const { x, y } = spiralPoint(current.source, progress); const { x, y } = spiralPoint(current.source, progress);
head.current?.setAttribute("cx", String(x)); head.current?.setAttribute("cx", String(x));
head.current?.setAttribute("cy", String(y)); head.current?.setAttribute("cy", String(y));
trail.current?.setAttribute("stroke-dashoffset", String(0.2 - progress)); trail.current?.setAttribute("stroke-dashoffset", String(0.2 - progress));
effect.current?.setAttribute("opacity", String(progress >= 1 ? 0 : Math.min(1, (1 - progress) * 6))); effect.current?.setAttribute("opacity", String(progress >= 1 ? 0 : Math.min(1, (1 - progress) * 6)));
return flowing || progress < 1; return moving || !done;
}, [arrival, flowing, slots]); }, [arrival, moving, rate, reducedMotion, slots]);
useGalaxyMotion(flowing || !!arrival, draw); useGalaxyMotion(moving || (!reducedMotion && !!arrival), draw);
const scale = width / SCENE_WIDTH; const scale = width / SCENE_WIDTH;
const height = SCENE_HEIGHT * scale; const height = SCENE_HEIGHT * scale;
const hitRadius = Math.max(12, scale ? 12 / scale : 12); const hitRadius = Math.max(12, scale ? 12 / scale : 12);
const selectedSlot = selectedOrbitId ? slots.get(selectedOrbitId) : undefined; const selectedSlot = selectedOrbitId ? slots.get(selectedOrbitId) : undefined;
const selectedPosition = !flowing && selectedSlot ? orbitPose(selectedSlot, elapsed.current) : undefined; const selectedPosition = !moving && selectedSlot ? orbitPose(selectedSlot, elapsed.current) : undefined;
const positions = !flowing ? [...slots.values()].map((slot) => orbitPose(slot, elapsed.current)) : []; const positions = !moving ? [...slots.values()].map((slot) => orbitPose(slot, elapsed.current)) : [];
const moons = selectedPosition const moons = selectedPosition
? moonPoses(selectedPosition, recentSnapshots.length, 2 * hitRadius + 3, positions) ? moonPoses(selectedPosition, recentSnapshots.length, 2 * hitRadius + 3, positions)
: []; : [];
@@ -122,7 +146,7 @@ export function BlackholeGalaxy({
}; };
let labels: ReturnType<typeof placeLabels> = []; let labels: ReturnType<typeof placeLabels> = [];
if (!flowing && width && labelCandidates.length) { if (!moving && width && labelCandidates.length) {
const measure = document.createElement("canvas").getContext("2d"); const measure = document.createElement("canvas").getContext("2d");
if (measure) measure.font = labelFont; if (measure) measure.font = labelFont;
const markers = positions.map((point) => box(point, 7)); const markers = positions.map((point) => box(point, 7));

View File

@@ -63,6 +63,7 @@ export function VaultScene({
selectedOrbitId={selectedOrbitId} selectedOrbitId={selectedOrbitId}
recentSnapshots={recentSnapshots} recentSnapshots={recentSnapshots}
flowing={flowing} flowing={flowing}
reducedMotion={reducedMotion}
arrival={arrival} arrival={arrival}
onSelectOrbit={onSelectOrbit} onSelectOrbit={onSelectOrbit}
onSelectSnapshot={onSelectSnapshot} onSelectSnapshot={onSelectSnapshot}

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

@@ -36,11 +36,22 @@ body {
button:enabled { cursor: pointer; } button:enabled { cursor: pointer; }
button:disabled { cursor: default; } button:disabled { cursor: default; }
.vault-button {
background-color: color-mix(
in oklab,
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%)
);
}
:focus-visible { outline: 2px solid var(--accent); outline-offset: -2px; } :focus-visible { outline: 2px solid var(--accent); outline-offset: -2px; }
.scrollbar-none { scrollbar-width: none; } .scrollbar-none { scrollbar-width: none; }
.vault-app { --vault-header-height: 70px; }
.vault-topbar { .vault-topbar {
min-height: 70px; position: sticky;
top: 0;
z-index: 30;
min-height: var(--vault-header-height);
padding: 0 clamp(16px, 3vw, 44px); padding: 0 clamp(16px, 3vw, 44px);
display: grid; display: grid;
grid-template-columns: 1fr auto 1fr; grid-template-columns: 1fr auto 1fr;
@@ -60,17 +71,58 @@ button:disabled { cursor: default; }
} }
.vault-brand span { display: block; margin-top: 5px; font-size: 9px; } .vault-brand span { display: block; margin-top: 5px; font-size: 9px; }
.vault-nav { display: flex; align-self: stretch; gap: clamp(8px, 2vw, 27px); } .vault-nav { position: relative; display: flex; align-self: stretch; gap: clamp(8px, 2vw, 27px); }
.vault-nav button { .vault-nav button {
position: relative; position: relative;
z-index: 1;
min-height: 44px; min-height: 44px;
padding: 0 6px; padding: 0 6px;
color: var(--quiet); color: var(--quiet);
font-size: 13px; font-size: 13px;
white-space: nowrap; 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:hover, .vault-nav button[aria-current] { color: var(--color-star-100); }
.vault-nav button[aria-current]::after { position: absolute; inset: auto 5px -1px; height: 2px; content: ""; background: var(--accent); } .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; } .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-main { max-width: 1720px; padding: 30px clamp(16px, 3vw, 44px) 10px; margin-inline: auto; }
@@ -234,26 +286,34 @@ button:disabled { cursor: default; }
.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 { 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); } .capture-notice.tone-red { color: var(--color-orbit-red); }
.vault-dialog { .vault-overlay {
position: fixed; position: fixed;
inset: 0 0 0 auto; inset: 0;
margin: 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%); width: min(440px, 100%);
height: 100dvh;
max-width: none;
max-height: none;
overflow: auto; overflow: auto;
padding: 0; overscroll-behavior: contain;
pointer-events: auto;
background: #121519; background: #121519;
color: var(--color-star-100); color: var(--color-star-100);
border-left: 1px solid #3b4048; border-left: 1px solid #3b4048;
} }
.vault-dialog::backdrop { background: #030508b3; } .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 { 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 { font-size: 23px; font-weight: 550; letter-spacing: -.035em; margin-top: 3px; }
.dialog-heading h2:focus { outline: none; } .dialog-heading h2:focus { outline: none; }
.dialog-heading h2 + p { margin-top: 4px; color: var(--quiet); font-size: 13px; } .dialog-heading h2 + p { margin-top: 4px; color: var(--quiet); font-size: 13px; }
.dialog-content { padding: 18px 20px; } .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 { .big-screen {
--screen-gutter: clamp(12px, 2vw, 30px); --screen-gutter: clamp(12px, 2vw, 30px);
@@ -266,6 +326,7 @@ button:disabled { cursor: default; }
} }
.big-screen .vault-topbar { display: contents; } .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 :is(.vault-brand, .hub-link, .vault-console, .vault-footer, .scene-footer) { display: none; }
.big-screen .vault-main { padding: 0; } .big-screen .vault-main { padding: 0; }
.big-screen .vault-workspace, .big-screen .vault-workspace,
@@ -308,20 +369,25 @@ button:disabled { cursor: default; }
.big-screen .vault-telemetry { border-radius: 8px; padding-block: 8px; } .big-screen .vault-telemetry { border-radius: 8px; padding-block: 8px; }
.big-screen .vault-nav { .big-screen .vault-nav {
position: absolute; position: absolute;
z-index: 2; z-index: 30;
bottom: var(--screen-bottom); bottom: var(--screen-bottom);
left: 50%; left: 50%;
transform: translateX(-50%); transform: translateX(-50%);
gap: 3px; gap: 4px;
max-width: calc(100% - 2 * var(--screen-gutter)); max-width: calc(100% - 2 * var(--screen-gutter));
margin: 0; margin: 0;
padding: 4px; padding: 5px 7px;
border-radius: 999px; border-radius: 999px;
box-shadow: 0 8px 30px #0006; box-shadow: inset 0 1px #ffffff12, 0 8px 30px #0008;
} }
.big-screen .vault-nav button { border-radius: 999px; padding-inline: clamp(8px, 1.65vw, 23px); } .big-screen .vault-nav button {
.big-screen .vault-nav button[aria-current] { background: #30251f; color: #ffd0a9; } display: grid;
.big-screen .vault-nav button[aria-current]::after { display: none; } place-items: center;
width: 46px;
border-radius: 999px;
padding: 0;
}
.big-screen .vault-nav button[aria-current] { color: #ffe2c9; }
@media (max-width: 1060px) { @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-workspace { grid-template-areas: "map map" "register inspector"; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); height: auto; }
@@ -329,6 +395,7 @@ button:disabled { cursor: default; }
} }
@media (max-width: 640px) { @media (max-width: 640px) {
.vault-app { --vault-header-height: 105px; }
.vault-topbar { grid-template-columns: 1fr auto; gap: 0 10px; padding-top: 11px; } .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 { 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-nav button { padding-inline: 5px; font-size: 12px; }
@@ -340,7 +407,7 @@ button:disabled { cursor: default; }
.vault-console { min-height: 0; } .vault-console { min-height: 0; }
.register-list { max-height: 196px; } .register-list { max-height: 196px; }
.orbit-inspector { max-height: 480px; padding-bottom: 8px; } .orbit-inspector { max-height: 480px; padding-bottom: 8px; }
.orbit-inspector > .console-empty { padding-bottom: 8px; } .inspector-stack .console-empty { padding-bottom: 8px; }
.galaxy-frame { max-width: none; } .galaxy-frame { max-width: none; }
.scene-toolbar, .scene-footer { padding: 9px; } .scene-toolbar, .scene-footer { padding: 9px; }
.scene-footer > p { display: none; } .scene-footer > p { display: none; }
@@ -370,14 +437,5 @@ button:disabled { cursor: default; }
@media (max-width: 380px) { @media (max-width: 380px) {
.big-screen .vault-nav { gap: 2px; } .big-screen .vault-nav { gap: 2px; }
.big-screen .vault-nav button { padding-inline: 6px; }
.big-screen .vault-telemetry > div { padding-inline: 7px; } .big-screen .vault-telemetry > div { padding-inline: 7px; }
} }
@media (prefers-reduced-motion: reduce) {
*, *::before, *::after {
animation-duration: .01ms !important;
animation-iteration-count: 1 !important;
transition-duration: .01ms !important;
}
}

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>,
); );