diff --git a/Cargo.lock b/Cargo.lock
index 76ea7d2..cabd477 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -2,6 +2,41 @@
# It is not intended for manual editing.
version = 4
+[[package]]
+name = "aead"
+version = "0.6.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1973cfbc1a2daf9cf550e74e1f088c28e7f7d8c1e1418fb6c9dc5184b7e84c99"
+dependencies = [
+ "crypto-common 0.2.2",
+ "inout",
+]
+
+[[package]]
+name = "aes"
+version = "0.9.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "fc0fc36d7440d015b45468ba08a21e80e056ebbd014c611c6298bb7503e04bd1"
+dependencies = [
+ "cipher",
+ "cpubits",
+ "cpufeatures 0.3.1",
+]
+
+[[package]]
+name = "aes-gcm"
+version = "0.11.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7f2b8006a0c83f52b62ba44a97b58bf76fe2f70a329e588f67f89691d93d498f"
+dependencies = [
+ "aead",
+ "aes",
+ "cipher",
+ "ctr",
+ "ctutils",
+ "ghash",
+]
+
[[package]]
name = "ahash"
version = "0.8.12"
@@ -281,6 +316,12 @@ version = "0.23.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5"
+[[package]]
+name = "base64ct"
+version = "1.8.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06"
+
[[package]]
name = "bit-vec"
version = "0.9.1"
@@ -302,7 +343,7 @@ version = "0.10.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "46502ad458c9a52b69d4d4d32775c788b7a1b85e8bc9d482d92250fc0e3f8efe"
dependencies = [
- "digest",
+ "digest 0.10.7",
]
[[package]]
@@ -314,6 +355,24 @@ dependencies = [
"generic-array",
]
+[[package]]
+name = "block-buffer"
+version = "0.12.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d2f6c7dbe95a6ed67ad9f18e57daf93a2f034c524b99fd2b76d18fdfeb6660aa"
+dependencies = [
+ "hybrid-array",
+]
+
+[[package]]
+name = "block-padding"
+version = "0.4.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "710f1dd022ef4e93f8a438b4ba958de7f64308434fa6a87104481645cc30068b"
+dependencies = [
+ "hybrid-array",
+]
+
[[package]]
name = "brotli"
version = "3.5.0"
@@ -352,6 +411,15 @@ version = "1.12.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04"
+[[package]]
+name = "cbc"
+version = "0.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ce2dc9ee5f88d11e0beb842c88b33c8a5cf0d1329c4b19494af42b07dbfe8896"
+dependencies = [
+ "cipher",
+]
+
[[package]]
name = "cc"
version = "1.11.1"
@@ -376,6 +444,17 @@ version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527"
+[[package]]
+name = "chacha20"
+version = "0.10.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06"
+dependencies = [
+ "cfg-if",
+ "cpufeatures 0.3.1",
+ "rand_core 0.10.1",
+]
+
[[package]]
name = "chrono"
version = "0.4.45"
@@ -385,6 +464,17 @@ dependencies = [
"num-traits",
]
+[[package]]
+name = "cipher"
+version = "0.5.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e8cf2a2c93cd704877c0858356ed03480ff301ee950b43f1cbe4573b088bfa6c"
+dependencies = [
+ "block-buffer 0.12.1",
+ "crypto-common 0.2.2",
+ "inout",
+]
+
[[package]]
name = "clap"
version = "4.6.7"
@@ -434,6 +524,24 @@ dependencies = [
"cc",
]
+[[package]]
+name = "cmov"
+version = "0.5.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0c9ea0ac24bc397ab3c98583a3c9ba74fa56b09a4449bbe172b9b1ddb016027a"
+
+[[package]]
+name = "cms"
+version = "0.3.0-rc.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6e99ff55bfffd019bf15e3f0d5edef2ca1e3af5ade276ed100e3c0c3455050c2"
+dependencies = [
+ "const-oid",
+ "der",
+ "spki",
+ "x509-cert",
+]
+
[[package]]
name = "colorchoice"
version = "1.0.5"
@@ -459,6 +567,12 @@ dependencies = [
"crossbeam-utils",
]
+[[package]]
+name = "const-oid"
+version = "0.10.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a6ef517f0926dd24a1582492c791b6a4818a4d94e789a334894aa15b0d12f55c"
+
[[package]]
name = "const-random"
version = "0.1.18"
@@ -505,6 +619,12 @@ version = "0.8.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b"
+[[package]]
+name = "cpubits"
+version = "0.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "15b85f9c39137c3a891689859392b1bd49812121d0d61c9caf00d46ed5ce06ae"
+
[[package]]
name = "cpufeatures"
version = "0.2.17"
@@ -514,6 +634,15 @@ dependencies = [
"libc",
]
+[[package]]
+name = "cpufeatures"
+version = "0.3.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566"
+dependencies = [
+ "libc",
+]
+
[[package]]
name = "crc32fast"
version = "1.5.4"
@@ -554,6 +683,33 @@ dependencies = [
"typenum",
]
+[[package]]
+name = "crypto-common"
+version = "0.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453"
+dependencies = [
+ "hybrid-array",
+]
+
+[[package]]
+name = "ctr"
+version = "0.10.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "baaca1c4b237092596f64d571e9db6ce4109c4ef9742e27590f1709594461f21"
+dependencies = [
+ "cipher",
+]
+
+[[package]]
+name = "ctutils"
+version = "0.4.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "261af4dc7a06ea8a527a8717d8cbba3417530d6ea14e1edb3de6b67806be474f"
+dependencies = [
+ "cmov",
+]
+
[[package]]
name = "daemonix"
version = "0.1.0"
@@ -591,6 +747,19 @@ version = "2.11.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4583a4551df46e2792f82ceeac45e850d2e2d5debba0b91f102385cda5b11f06"
+[[package]]
+name = "der"
+version = "0.8.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6a996a108feb8b427a6e12fcf6af4aa83409b79d72c15337d7741368131ee004"
+dependencies = [
+ "const-oid",
+ "der_derive",
+ "flagset",
+ "pem-rfc7468",
+ "zeroize",
+]
+
[[package]]
name = "der-parser"
version = "9.0.0"
@@ -619,6 +788,17 @@ dependencies = [
"rusticata-macros",
]
+[[package]]
+name = "der_derive"
+version = "0.8.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "59600e2c2d636fde9b65e99cc6445ac770c63d3628195ff39932b8d6d7409903"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.119",
+]
+
[[package]]
name = "deranged"
version = "0.5.9"
@@ -636,17 +816,38 @@ dependencies = [
"syn 1.0.109",
]
+[[package]]
+name = "des"
+version = "0.9.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "916a94e407b54f9034d71dd748234cd1e516ced6284009906ae246f177eafe5a"
+dependencies = [
+ "cipher",
+]
+
[[package]]
name = "digest"
version = "0.10.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"
dependencies = [
- "block-buffer",
- "crypto-common",
+ "block-buffer 0.10.4",
+ "crypto-common 0.1.7",
"subtle",
]
+[[package]]
+name = "digest"
+version = "0.11.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2"
+dependencies = [
+ "block-buffer 0.12.1",
+ "const-oid",
+ "crypto-common 0.2.2",
+ "ctutils",
+]
+
[[package]]
name = "displaydoc"
version = "0.2.7"
@@ -706,6 +907,12 @@ version = "0.5.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1d674e81391d1e1ab681a28d99df07927c6d4aa5b027d7da16ba32d1d21ecd99"
+[[package]]
+name = "flagset"
+version = "0.4.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b7ac824320a75a52197e8f2d787f6a38b6718bb6897a35142d749af3c0e8f4fe"
+
[[package]]
name = "flate2"
version = "1.1.11"
@@ -879,6 +1086,16 @@ dependencies = [
"cfg-if",
"libc",
"r-efi 6.0.0",
+ "rand_core 0.10.1",
+]
+
+[[package]]
+name = "ghash"
+version = "0.6.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2eecf2d5dc9b66b732b97707a0210906b1d30523eb773193ab777c0c84b3e8d5"
+dependencies = [
+ "polyval",
]
[[package]]
@@ -947,6 +1164,15 @@ version = "0.4.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70"
+[[package]]
+name = "hmac"
+version = "0.13.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6303bc9732ae41b04cb554b844a762b4115a61bfaa81e3e83050991eeb56863f"
+dependencies = [
+ "digest 0.11.3",
+]
+
[[package]]
name = "http"
version = "1.5.0"
@@ -992,6 +1218,15 @@ version = "1.0.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9"
+[[package]]
+name = "hybrid-array"
+version = "0.4.15"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "27f864f10dfb56725ce5ce5472bc52252c8f93a4ab86327122cebf62c5f59a17"
+dependencies = [
+ "typenum",
+]
+
[[package]]
name = "hyper"
version = "1.12.0"
@@ -1064,13 +1299,17 @@ dependencies = [
"ianitor-edge",
"ianitor-testkit",
"log",
- "rcgen",
+ "p12-keystore",
+ "qrcode",
"ring",
+ "rpassword",
"rustls",
+ "rustls-pki-types",
"serde",
"serde_json",
"thiserror 2.0.21",
"tokio",
+ "tokio-rustls",
"toml",
"utoipa",
]
@@ -1080,13 +1319,18 @@ name = "ianitor-core"
version = "0.1.0"
dependencies = [
"base64 0.22.1",
+ "rcgen",
"ring",
+ "rustls-pki-types",
+ "rustls-webpki",
"serde",
"serde_json",
"thiserror 2.0.21",
+ "time",
"toml",
"unicode-normalization",
"url",
+ "x509-parser 0.18.1",
]
[[package]]
@@ -1097,6 +1341,7 @@ dependencies = [
"ianitor-core",
"ianitor-edge",
"ianitor-testkit",
+ "rcgen",
"rustls",
"serde_json",
"tokio",
@@ -1119,6 +1364,7 @@ dependencies = [
"instant-acme",
"log",
"pingora",
+ "rcgen",
"ring",
"rustls",
"rustls-pki-types",
@@ -1274,6 +1520,16 @@ dependencies = [
"serde_core",
]
+[[package]]
+name = "inout"
+version = "0.2.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3a580c13f0ffc335ef42dd3f6b1a41b726051c5e1656d9a3aa6fddb3c5dfbbf9"
+dependencies = [
+ "block-padding",
+ "hybrid-array",
+]
+
[[package]]
name = "instant-acme"
version = "0.8.5"
@@ -1606,6 +1862,29 @@ dependencies = [
"syn 2.0.119",
]
+[[package]]
+name = "p12-keystore"
+version = "0.4.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5c2ed4fa0ec7ec58b657d4184680c57da9e203e97771d29a566028869a5193e0"
+dependencies = [
+ "cbc",
+ "cms",
+ "der",
+ "des",
+ "hex",
+ "hmac",
+ "pkcs12",
+ "pkcs5",
+ "pkcs8",
+ "rand 0.10.3",
+ "rc2",
+ "sha1 0.11.0",
+ "sha2",
+ "thiserror 2.0.21",
+ "x509-parser 0.18.1",
+]
+
[[package]]
name = "parking"
version = "2.2.1"
@@ -1635,6 +1914,16 @@ dependencies = [
"windows-link",
]
+[[package]]
+name = "pbkdf2"
+version = "0.13.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "112d82ceb8c5bf524d9af484d4e4970c9fd5a0cc15ba14ad93dccd28873b0629"
+dependencies = [
+ "digest 0.11.3",
+ "hmac",
+]
+
[[package]]
name = "pem"
version = "4.0.0"
@@ -1645,6 +1934,15 @@ dependencies = [
"serde_core",
]
+[[package]]
+name = "pem-rfc7468"
+version = "1.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a6305423e0e7738146434843d1694d621cce767262b2a86910beab705e4493d9"
+dependencies = [
+ "base64ct",
+]
+
[[package]]
name = "percent-encoding"
version = "2.3.2"
@@ -1935,12 +2233,64 @@ dependencies = [
"tokio",
]
+[[package]]
+name = "pkcs12"
+version = "0.2.0-rc.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9fd993500a1de8a428a2e6cc9a2ec942c99a801a88d58a24fb986c5ad3b767ca"
+dependencies = [
+ "cms",
+ "const-oid",
+ "der",
+ "digest 0.11.3",
+ "spki",
+ "x509-cert",
+ "zeroize",
+]
+
+[[package]]
+name = "pkcs5"
+version = "0.8.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "63d440a804ec8d6fafbb6b84471e013286658d373248927692ab3366686220ca"
+dependencies = [
+ "aes",
+ "aes-gcm",
+ "cbc",
+ "der",
+ "pbkdf2",
+ "scrypt",
+ "sha2",
+ "spki",
+]
+
+[[package]]
+name = "pkcs8"
+version = "0.11.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "451913da69c775a56034ea8d9003d27ee8948e12443eae7c038ba100a4f21cb7"
+dependencies = [
+ "der",
+ "spki",
+]
+
[[package]]
name = "pkg-config"
version = "0.3.34"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548"
+[[package]]
+name = "polyval"
+version = "0.7.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f0fa31d631f2b2cb2a544d0aa321ce847a94764d701ca2becc411138b93d49cd"
+dependencies = [
+ "cpubits",
+ "cpufeatures 0.3.1",
+ "universal-hash",
+]
+
[[package]]
name = "potential_utf"
version = "0.1.6"
@@ -1987,6 +2337,12 @@ dependencies = [
"yansi",
]
+[[package]]
+name = "qrcode"
+version = "0.14.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d68782463e408eb1e668cf6152704bd856c78c5b6417adaee3203d8f4c1fc9ec"
+
[[package]]
name = "quote"
version = "1.0.47"
@@ -2029,6 +2385,17 @@ dependencies = [
"rand_core 0.9.5",
]
+[[package]]
+name = "rand"
+version = "0.10.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "65c9fb96cbc91e3478eaae79a69fcd3f1ae4ad052e471fe6732fff548984b4af"
+dependencies = [
+ "chacha20",
+ "getrandom 0.4.3",
+ "rand_core 0.10.1",
+]
+
[[package]]
name = "rand_chacha"
version = "0.3.1"
@@ -2067,6 +2434,21 @@ dependencies = [
"getrandom 0.3.4",
]
+[[package]]
+name = "rand_core"
+version = "0.10.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69"
+
+[[package]]
+name = "rc2"
+version = "0.9.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ceda21af1ae61033b63175653a1af86cae399d79cd03ca80ba347eb3a6c4a7fe"
+dependencies = [
+ "cipher",
+]
+
[[package]]
name = "rcgen"
version = "0.14.10"
@@ -2152,6 +2534,27 @@ dependencies = [
"serde",
]
+[[package]]
+name = "rpassword"
+version = "7.5.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2da316a15f47e3d053de9cb2c439650bd8fa4aaeb9365f2e5f27f492ff73c196"
+dependencies = [
+ "libc",
+ "rtoolbox",
+ "windows-sys 0.61.2",
+]
+
+[[package]]
+name = "rtoolbox"
+version = "0.0.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9a1efe12a1469752d0e6ff5ebec0b6ef4924cc5c4c71046b0ec730040535819d"
+dependencies = [
+ "libc",
+ "windows-sys 0.61.2",
+]
+
[[package]]
name = "rust_decimal"
version = "1.43.0"
@@ -2288,6 +2691,16 @@ version = "1.0.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f"
+[[package]]
+name = "salsa20"
+version = "0.11.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2f874456e72520ff1375a06c588eaf074b0f01f9e9e1aada45bd9b7954a6e42c"
+dependencies = [
+ "cfg-if",
+ "cipher",
+]
+
[[package]]
name = "same-file"
version = "1.0.6"
@@ -2312,6 +2725,18 @@ version = "1.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"
+[[package]]
+name = "scrypt"
+version = "0.12.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d87af57419b594aa23fa95f09f0e06d80d84ba01c26148c43844cad6ff4485f0"
+dependencies = [
+ "cfg-if",
+ "pbkdf2",
+ "salsa20",
+ "sha2",
+]
+
[[package]]
name = "security-framework"
version = "2.11.1"
@@ -2466,8 +2891,30 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a978451301f4db1d02937a4ab3ccce137717b81826e79b7d49ffe3244a13c3b8"
dependencies = [
"cfg-if",
- "cpufeatures",
- "digest",
+ "cpufeatures 0.2.17",
+ "digest 0.10.7",
+]
+
+[[package]]
+name = "sha1"
+version = "0.11.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "aacc4cc499359472b4abe1bf11d0b12e688af9a805fa5e3016f9a386dc2d0214"
+dependencies = [
+ "cfg-if",
+ "cpufeatures 0.3.1",
+ "digest 0.11.3",
+]
+
+[[package]]
+name = "sha2"
+version = "0.11.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "47d7069beb7d6ac7b9acd1039986e73443f24234f41074da099d6f994ac9ad19"
+dependencies = [
+ "cfg-if",
+ "cpufeatures 0.3.1",
+ "digest 0.11.3",
]
[[package]]
@@ -2524,6 +2971,16 @@ dependencies = [
"windows-sys 0.61.2",
]
+[[package]]
+name = "spki"
+version = "0.8.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7ef958a98b9d5da290cfc78946e9f3e61e1e62a18db0d92cac0b83cc161491a9"
+dependencies = [
+ "base64ct",
+ "der",
+]
+
[[package]]
name = "stable_deref_trait"
version = "1.2.1"
@@ -2924,7 +3381,7 @@ dependencies = [
"httparse",
"log",
"rand 0.9.5",
- "sha1",
+ "sha1 0.10.7",
"thiserror 2.0.21",
]
@@ -2955,6 +3412,16 @@ dependencies = [
"tinyvec",
]
+[[package]]
+name = "universal-hash"
+version = "0.6.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f4987bdc12753382e0bec4a65c50738ffaabc998b9cdd1f952fb5f39b0048a96"
+dependencies = [
+ "crypto-common 0.2.2",
+ "ctutils",
+]
+
[[package]]
name = "unsafe-libyaml"
version = "0.2.11"
@@ -3196,6 +3663,17 @@ version = "0.6.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc"
+[[package]]
+name = "x509-cert"
+version = "0.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "105ef4642d9cb137ef83d623d0e4bf08b8adf69e9918ca904a174adb6d3d038b"
+dependencies = [
+ "const-oid",
+ "der",
+ "spki",
+]
+
[[package]]
name = "x509-parser"
version = "0.16.0"
diff --git a/apps/web/index.html b/apps/web/index.html
new file mode 100644
index 0000000..d0f2f85
--- /dev/null
+++ b/apps/web/index.html
@@ -0,0 +1,17 @@
+
+
+
+
+
+
+
+
+ Hosts — Ianitor Domi
+
+
+
+
+
+
diff --git a/apps/web/package.json b/apps/web/package.json
index 591d4d1..77afe14 100644
--- a/apps/web/package.json
+++ b/apps/web/package.json
@@ -1,10 +1,29 @@
{
"name": "web",
- "version": "0.0.0",
+ "version": "0.1.0",
"private": true,
"license": "MPL-2.0",
- "description": "Ianitor Domi web UI (Svelte 5). Placeholder until phase 3.",
+ "description": "Ianitor Domi web UI (Svelte 5, runes, TypeScript strict). A pure client of the control API.",
+ "type": "module",
"scripts": {
- "dev": "node -e \"console.log('web: placeholder, the UI arrives in phase 3; nothing is listening')\""
+ "dev": "vite",
+ "build": "vite build",
+ "check": "svelte-check --tsconfig ./tsconfig.json --fail-on-warnings",
+ "test": "vitest run"
+ },
+ "dependencies": {
+ "@ianitor/ui": "workspace:*"
+ },
+ "devDependencies": {
+ "@sveltejs/vite-plugin-svelte": "^5.0.3",
+ "@testing-library/svelte": "^5.2.6",
+ "@testing-library/user-event": "^14.6.1",
+ "@tsconfig/svelte": "^5.0.4",
+ "jsdom": "^26.0.0",
+ "svelte": "^5.20.0",
+ "svelte-check": "^4.1.4",
+ "typescript": "^5.7.3",
+ "vite": "^6.1.0",
+ "vitest": "^3.0.5"
}
}
diff --git a/apps/web/src/App.svelte b/apps/web/src/App.svelte
new file mode 100644
index 0000000..f073ddc
--- /dev/null
+++ b/apps/web/src/App.svelte
@@ -0,0 +1,175 @@
+
+
+
+{#if route.view === "signed-in"}
+
+{:else}
+ Skip to content
+
+
+
IANITOR DOMI {#if app.phone} {/if}
+
+
+ {#if route.view === "hosts"}
+
+ {:else if route.view === "history"}
+ {#key route.host} {/key}
+ {:else if route.view === "certs"}
+
+ {:else if route.view === "renew"}
+
+ {:else if route.view === "settings"}
+
+ {/if}
+
+
+ {#each NAV as n (n.href)}
+ go(e, n.href)}>{n.label}
+ {/each}
+
+
+
+ {#if app.panel?.kind === "engine"}
+ {
+ app.panel = null;
+ document.querySelector("[data-engine-chip]")?.focus();
+ }} />
+ {/if}
+
+
+ {#each app.toasts as t (t.id)}
{t.text}
{/each}
+
+
+ {#if app.signedOut}
+ {}}>
+ Sign in again; this page keeps what you typed.
+ {#snippet footer()}
+ I have signed in
+ Sign in
+ {/snippet}
+
+ {/if}
+{/if}
+
+
diff --git a/apps/web/src/components/ApplyProgress.svelte b/apps/web/src/components/ApplyProgress.svelte
new file mode 100644
index 0000000..0659c19
--- /dev/null
+++ b/apps/web/src/components/ApplyProgress.svelte
@@ -0,0 +1,80 @@
+
+
+
+{#if apply.state === "queued"}
+
+
+
+ Waiting for "{apply.queue?.waiting_for?.summary ?? "another change"}" to finish{apply.queue?.waiting_for?.seconds_left != null
+ ? `, about ${apply.queue.waiting_for.seconds_left} s`
+ : ""}.
+ {#if (apply.queue?.position ?? 1) > 1}{(apply.queue?.position ?? 1) - 1} other changes are ahead of this one.{/if}
+
+
+ {#if oncancel}Cancel
{/if}
+{:else}
+
+ {#each rows as r, i (i)}
+
+ {#if r.s === "done"} {:else if r.s === "running"} {:else if r.s === "failed"} {:else} {/if}
+ {prefix[r.s]} {r.t[r.s as keyof typeof r.t]}
+
+ {/each}
+ {#if st("watch") === "failed" && !final}
+ Now: Undoing the change
+ {/if}
+
+ {#if apply.state === "watching"}
+
+ You can leave this screen. Other changes wait their turn; only one apply runs at a time.
+ {/if}
+{/if}
+
+
diff --git a/apps/web/src/components/ChangeBar.svelte b/apps/web/src/components/ChangeBar.svelte
new file mode 100644
index 0000000..c7c2dcc
--- /dev/null
+++ b/apps/web/src/components/ChangeBar.svelte
@@ -0,0 +1,165 @@
+
+
+
+{#if last && (last.state === "reverted" || last.state === "failed") && !app.dismissed.includes(dismissKey)}
+ {@const parts = firstSentence(last.reason?.message ?? "")}
+ (app.dismissed = [...app.dismissed, dismissKey])}>
+ {#snippet title()}{last.state === "failed" ? "not applied" : "reverted"} {parts[0]} {/snippet}
+ {#if parts[1]}Reason: {parts[1]}{/if}
+ {#if last.reason?.detail && last.reason.code.startsWith("apply.failed.")} {/if}
+ {#snippet actions()}
+ {#if offer} onedit(last, offer?.field)}>{offer.label} {/if}
+ {/snippet}
+
+{/if}
+
+{#if last || active}
+
+ {#if active}
+
+
{active.state === "queued" ? "waiting" : active.state === "watching" ? "watching" : "applying"}
+ {runningHeading(active.summary, active.kind ? active : null)}
+
{active.state === "queued" ? "Waiting for another change to finish" : active.state === "watching" ? `${watchLeft ?? 0} s left` : "Checking and loading the change"}
+ {#if active.state === "watching" && watchLeft != null}
+ {@const total = o?.site?.watch_seconds ?? 60}
+
+ {/if}
+
+ {#if active.state === "queued"} cancel(active.id)}>Cancel {:else} onshowsteps(active.id)}>Show steps {/if}
+ {:else if last}
+
+ {#if last.state === "kept"}
+
kept {last.summary}
+
{pushFailed ? pushLine : keptLine}
+ {:else if undo?.target}
+
Undo: {undo.target.summary}
+ {/if}
+ {#if undo?.effect && (last.state !== "kept" || undo?.target?.change_id !== last.change_id)}
{undo.effect}
{/if}
+ {#if moved}
{moved}
{/if}
+ {#if undoReason}
{undoReason}
{/if}
+ {#if !undo?.target}
Nothing to undo yet.
{/if}
+
+ {#if canPushNow}Try now {/if}
+ {#if undo?.target}
+ Undo
+ {/if}
+ {/if}
+
+{/if}
+
+
diff --git a/apps/web/src/components/EngineChip.svelte b/apps/web/src/components/EngineChip.svelte
new file mode 100644
index 0000000..ddf194b
--- /dev/null
+++ b/apps/web/src/components/EngineChip.svelte
@@ -0,0 +1,29 @@
+
+
+
+{#if o}
+ (app.panel = app.panel?.kind === "engine" ? null : { kind: "engine" })}>
+ {#if o.engine.state === "switching"} Engine Switching…{:else}
+
+ Engine {engineName}{#if o.engine.running === "caddy"} (fallback) {/if}{/if}
+
+
+{/if}
+
+
diff --git a/apps/web/src/components/EnginePopover.svelte b/apps/web/src/components/EnginePopover.svelte
new file mode 100644
index 0000000..2d28610
--- /dev/null
+++ b/apps/web/src/components/EnginePopover.svelte
@@ -0,0 +1,121 @@
+
+
+
+
+ Engine
+ {#if e?.state === "stopped"}
+ Visitors may not reach any host. Switching to {other} is the quickest way back.
+ {:else}
+
+ {#if e?.since}Since {whenInline(e.since, app.now)}. {/if}
+ {#if running === "pingora"}
+ {#if notReady}Caddy is not ready: its settings have not been built yet.{:else if differs > 0}Caddy was built {whenInline(fr?.built_at, app.now)} with the same routes, but {differs} of {fr?.compared} {fr?.compared === 1 ? "host" : "hosts"} {differs === 1 ? "behaves" : "behave"} differently on it.{:else}Caddy is ready with the same routes: built {whenInline(fr?.built_at, app.now)}{fr?.compared ? (fr.compared === 1 ? ", and the host behaves the same" : `, and all ${fr.compared} hosts behave the same`) : ""}.{/if}
+ {#if !notReady && !fr?.current} It is rebuilt from the current routes when you switch.{/if}
+ {:else}Pingora is ready with the same routes.{/if}
+
+ {#if running === "pingora" && !notReady && fr?.differences.length}
+
+ {/if}
+ {/if}
+
+
What happens
+
+ {name} stops and {other} starts. New visits reach {other} in about 2 seconds.
+ Open connections close; videos and uploads in progress restart.
+ Hosts and certificates stay the same.
+ {#if running === "pingora"}
+ Share links stop working while Caddy serves: visitors with a link get the normal sign-in. They work again when you switch back.{#if activeLinks}{" "}{activeLinks === 1 ? "1 share link is" : `${activeLinks} share links are`} active.{/if}
+ Changes keep working: Ianitor tries each one on Caddy and undoes it if a host stops answering.
+ {:else}
+ Share links work again.
+ {/if}
+ This page may lose contact for a few seconds.
+
+
+ {#if switching}
+ Switching to {other}
+
+ {/if}
+ {#if problem}{#snippet title()}{problem}{/snippet} {/if}
+ {#if disabledReason}{disabledReason}
{/if}
+ {#snippet footer()}
+ Cancel
+ Switch to {other}
+ {/snippet}
+
+
+
diff --git a/apps/web/src/components/HostList.svelte b/apps/web/src/components/HostList.svelte
new file mode 100644
index 0000000..94a4554
--- /dev/null
+++ b/apps/web/src/components/HostList.svelte
@@ -0,0 +1,142 @@
+
+
+
+
+
+ Status
+ Host
+ Sends traffic to
+ More
+
+ {#each sorted as h (h.hostname)}
+ {@const [k, w] = kind(h)}
+ {@const s = sub(h)}
+
+
+
+
+ {h.hostname}
+ {#each chips(h) as c (c)}{c} {/each}
+ {w}{phoneDetail(h) ? ` · ${phoneDetail(h)}` : ""}
+
+
+ {h.upstreams[0] ?? ""} {#if h.upstreams.length > 1}{" "}+{h.upstreams.length - 1} more {/if}
+ {running.includes(h.hostname) ? "Changing now · " : ""}{s.text}
+ {#if h.certificate.state === "pending"}Waiting for Let's Encrypt to issue the certificate. {/if}
+ {#if h.certificate.state === "failed"}
+ Let's Encrypt could not confirm {h.hostname} . The name must point to this server, and port 80 must be open from the internet.
+ onretry(h.hostname)}>Try again
+ {/if}
+
+
+ onshare(h.hostname) },
+ { label: "Edit host", icon: "pencil", reason: blocked, run: () => onedit(h.hostname) },
+ { label: "Show in history", icon: "history", run: () => onhistory(h.hostname) },
+ { label: "Remove host", icon: "trash", danger: true, divider: true, reason: blocked, run: () => onremove(h.hostname) },
+ ]} />
+
+
+ {/each}
+
+
+
diff --git a/apps/web/src/components/HostMenu.svelte b/apps/web/src/components/HostMenu.svelte
new file mode 100644
index 0000000..9fcad4a
--- /dev/null
+++ b/apps/web/src/components/HostMenu.svelte
@@ -0,0 +1,88 @@
+
+
+
+
+
+
+
+
diff --git a/apps/web/src/components/HostPanel.svelte b/apps/web/src/components/HostPanel.svelte
new file mode 100644
index 0000000..961825d
--- /dev/null
+++ b/apps/web/src/components/HostPanel.svelte
@@ -0,0 +1,538 @@
+
+
+
+
+ {#if loading}
+ Loading…
+ {:else if notFound}
+ {#snippet title()}{notFound}{/snippet}
+ {#snippet actions()}Back to hosts {/snippet}
+
+ {:else if phase === "progress" && apply}
+
+ {#if apply.state === "queued"}Waiting for another change to finish.{:else if apply.state === "watching"}Watching health checks.{:else if apply.state === "kept"}Kept. {apply.reason?.message}{:else if apply.state === "reverted"}Reverted. {apply.reason?.message}{:else if apply.state === "failed"}Not applied. {apply.reason?.message}{/if}
+
+
+ {#if apply.state === "kept"}
+
+ {#snippet title()}kept {apply?.hosts[0] ?? name} {apply?.kind === "remove" ? "is removed." : "is live."}{/snippet}
+ {(apply.reason?.message ?? "").replace(/^\S+ is (live|removed)\.\s*/, "")}{#if apply.commit_short} Saved as commit {apply.commit_short}{apply.push?.state === "pushed" ? " and pushed to Gitea" : ""}.{/if}
+
+ {:else if apply.state === "reverted" || apply.state === "failed"}
+ {@const parts = firstSentence(apply.reason?.message ?? "")}
+
+ {#snippet title()}{apply?.state === "failed" ? "not applied" : "reverted"} {parts[0]} {/snippet}
+ {#if parts[1]}Reason: {parts[1]}{/if}
+ {#snippet actions()}
+ {#if reasonOffer}
+ (reasonOffer?.field === "" ? (editAgain(), submit()) : editAgain(reasonOffer?.field))}>{reasonOffer.label}
+ {/if}
+ {/snippet}
+
+ {#if apply.reason?.detail} {/if}
+ Your form is kept. History records the attempt as {apply.state === "failed" ? "not applied" : "reverted"}.
+ {:else if apply.state === "needs_attention"}
+ {#snippet title()}Ianitor could not undo a failed change. {/snippet}{apply.reason?.message}
+ {#if restoreProblem}{restoreProblem}
{/if}
+ {#snippet actions()}
+ {#if app.overview?.undo?.target} { restoring = true; restoreProblem = await restoreLastKept(); restoring = false; }}>Restore the last kept version {/if}
+ {/snippet}
+
+ {/if}
+ {:else}
+
+ {/if}
+
+ {#snippet footer()}
+ {#if phase === "form" && !loading && !notFound}
+ {#if underFooter}{underFooter}
{/if}
+ {#if blocked}{blocked}
{/if}
+ Cancel
+ Apply
+ {:else if phase === "progress" && apply && FINAL.includes(apply.state)}
+ Close
+ {/if}
+ {/snippet}
+
+
+
diff --git a/apps/web/src/components/IntermediateBanner.svelte b/apps/web/src/components/IntermediateBanner.svelte
new file mode 100644
index 0000000..f11bf7c
--- /dev/null
+++ b/apps/web/src/components/IntermediateBanner.svelte
@@ -0,0 +1,65 @@
+
+
+
+{#if app.renewedUntil}
+ (app.renewedUntil = null)}>
+ {#snippet title()}Renewed. The Domi intermediate certificate is now valid until {longDate(app.renewedUntil, false)}.{/snippet}
+
+{:else if i?.renewal}
+ {@const r = i.renewal}
+
+ {#snippet title()}
+ Sign the renewal on the offline computer. The next page has the files, the command and a fingerprint to check.
+ {/snippet}
+ The request stays open for {duration(secondsLeft(r.expires_at))}. {#if problem}{problem}{/if}
+ {#snippet actions()}
+ navigate("/certificates/renew-by-hand")}>Sign it by hand
+ cancel(r.request_id)}>Cancel request
+ {/snippet}
+
+{:else if i?.banner}
+
+ {#snippet title()}{i.banner?.message} {/snippet}
+ {i.state === "missing" ? "Setting it up makes a request that the Domi root signs on the offline computer." : "Renewing makes a request that the Domi root signs on the offline computer."}
+ {#if problem} {problem}{/if}
+ {#snippet actions()}{i.state === "missing" ? "Set up" : "Renew"} {/snippet}
+
+{/if}
+
diff --git a/apps/web/src/components/ShareDialog.svelte b/apps/web/src/components/ShareDialog.svelte
new file mode 100644
index 0000000..4923ade
--- /dev/null
+++ b/apps/web/src/components/ShareDialog.svelte
@@ -0,0 +1,163 @@
+
+
+
+
+ {#if !on}
+ {#if turning}
+
+ {#if turning.state === "reverted" || turning.state === "failed"}
+ {#snippet title()}Share links were not turned on. {turning?.reason?.message}{/snippet}
+ {/if}
+ {:else}
+ Share links are off for {hostname}.
+ Turning them on is a change to the host, checked like any other.
+ {#if problem} {problem}
{/if}
+ Turn on share links
+ {/if}
+ {:else}
+ Anyone with this link can open the site without signing in, until it expires.
+ {#if underCaddy}
+ {#snippet title()}Caddy is serving right now, so share links do not work: visitors with this link get the normal sign-in. The link works after switching back to Pingora, until it expires.{/snippet}
+ {/if}
+ {#if link?.warning}{link.warning.message}
{/if}
+ {#if problem}{#snippet title()}{problem}{/snippet} {/if}
+ {#if link}
+
+ {:else if minting}
+ Making the link…
+ {/if}
+ {#if copied}
+ Copied
+ Expires on {longDate(link?.expires_at)}. To stop it sooner: Settings, Share links, Stop this link.
+ {:else}
+ Copy link
+ {/if}
+ {#if refused}Your browser did not allow copying. Press Ctrl+C to copy the selected link.
{/if}
+ {#if copiedBefore && !copied}The link you copied before is stopped. Copy this one.
{/if}
+
+ mint()}
+ options={[{ value: "1", label: "1 day" }, { value: "7", label: "7 days" }, { value: "30", label: "30 days" }]} />
+
+
Only addresses starting with
+
mint()} onkeydown={(e) => { if (e.key === "Enter") { e.preventDefault(); void mint(); } }}
+ aria-invalid={fieldErr?.field === "path_prefix" ? "true" : undefined} />
+ {#if fieldErr?.field === "path_prefix"}
{fieldErr.message}
{/if}
+
/ shares the whole site. Try /share/summer-2026 for one album.
+
+ {#if usingPassword}
+ This link asks for the password.
+ { usingPassword = false; password = ""; void mint(); }}>Remove the password
+ {:else if showPassword}
+
+
Password
+
+ {#if fieldErr?.field === "password"}
{fieldErr.message}
{/if}
+
At least 8 characters. Send it to them separately.
+
{ usingPassword = true; void mint(); }}>Use this password
+
+ {:else}
+ (showPassword = true)}>Add a password
+ {/if}
+ {/if}
+
diff --git a/apps/web/src/components/TopBanners.svelte b/apps/web/src/components/TopBanners.svelte
new file mode 100644
index 0000000..de8492a
--- /dev/null
+++ b/apps/web/src/components/TopBanners.svelte
@@ -0,0 +1,86 @@
+
+
+
+{#if o?.paused}
+
+ {#snippet title()}{o.paused_reason === "apply.needs_attention" ? "needs attention" : "paused"} {pause.bold} {/snippet}
+ {#if pause.line2}{pause.line2} {/if}
+ {#if restorable && o.undo?.target}Goes back to "{o.undo.target.summary}" from {whenInline(o.undo.target.kept_at, app.now)}. It is checked like any change.
{/if}
+ {#if problem}{problem}
{/if}
+ {#if pauseDetail} {/if}
+ {#snippet actions()}
+ {#if restorable}Restore the last kept version {/if}
+ {/snippet}
+
+{/if}
+
+{#if app.lostContact}
+
+ {#snippet title()}{typeof navigator !== "undefined" && navigator.onLine === false ? "This device is offline. Ianitor keeps running." : "Ianitor's control service is not answering."} {/snippet}
+ Traffic keeps flowing; changes wait until it is back.{#if app.lastUpdated} Last updated {atTime(new Date(app.lastUpdated).toISOString(), app.now)}.{/if}
+ {#snippet actions()}Try again now {/snippet}
+
+{/if}
+
+{#if o?.health_error}
+ {#snippet title()}{o.health_error?.message}{/snippet}
+{/if}
+
+{#if app.switchResult}
+ {@const r = app.switchResult}
+ (app.switchResult = null)}>
+ {#snippet title()}{r.title} {/snippet}
+ {r.text}
+ {#if r.detail} {/if}
+
+{/if}
+
+{#if o?.engine.running === "caddy" && (o.hosts.some((h) => h.share_links) ?? false)}
+ {#snippet title()}Caddy is serving (the fallback), so share links do not work until you switch back.{/snippet}
+{/if}
diff --git a/apps/web/src/lib/api.ts b/apps/web/src/lib/api.ts
new file mode 100644
index 0000000..5eedc8f
--- /dev/null
+++ b/apps/web/src/lib/api.ts
@@ -0,0 +1,184 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at https://mozilla.org/MPL/2.0/.
+
+// The one typed API client (handoff §0, §10, §11). It owns the base path, the UI header (CSRF),
+// redirect: "manual" (sign-out detection), Idempotency-Keys, the error envelope, the server
+// clock offset, rate-limit and in-progress retries, and lost-contact detection. It decides
+// nothing about the data.
+
+import type { ErrorBody, ErrorEnvelope } from "./types";
+
+export const BASE = "/api/v1";
+
+/** A refusal from control, with its envelope. */
+export class ApiError extends Error {
+ constructor(
+ public status: number,
+ public body: ErrorBody,
+ public errors: ErrorBody[],
+ public requestId: string,
+ ) {
+ super(body.message);
+ }
+ get code(): string {
+ return this.body.code;
+ }
+}
+
+/** Authelia's portal redirect, or a 401 without Ianitor's envelope. */
+export class SignedOut extends Error {}
+
+/** No answer (network, or a proxy error without an envelope). */
+export class LostContact extends Error {}
+
+type Listener = () => void;
+
+export interface ClientEvents {
+ onSignedOut?: Listener;
+ onContact?: (ok: boolean) => void;
+ onServerTime?: (offsetMs: number) => void;
+}
+
+let events: ClientEvents = {};
+export function setClientEvents(e: ClientEvents): void {
+ events = e;
+}
+
+/** A key for one click; reused by every retry of that click (§11.3). */
+export function newKey(): string {
+ if (typeof crypto !== "undefined" && "randomUUID" in crypto) return crypto.randomUUID();
+ return Math.random().toString(36).slice(2) + Date.now().toString(36);
+}
+
+export interface CallOptions {
+ idem?: string;
+ etag?: string;
+ /** Do not count a failure as lost contact (engine switch, §9.2). */
+ quiet?: boolean;
+ keepalive?: boolean;
+}
+
+export interface Answer {
+ status: number;
+ data: T | null;
+ etag: string | null;
+}
+
+const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
+
+function envelope(v: unknown): v is ErrorEnvelope {
+ return typeof v === "object" && v !== null && "error" in v && typeof (v as ErrorEnvelope).error === "object";
+}
+
+export async function call(
+ method: string,
+ path: string,
+ body?: unknown,
+ opts: CallOptions = {},
+): Promise> {
+ let rateRetried = false;
+ for (let attempt = 0; attempt < 12; attempt++) {
+ const headers: Record = { "X-Ianitor-UI": "1", Accept: "application/json" };
+ if (body !== undefined) headers["Content-Type"] = "application/json";
+ if (opts.idem) headers["Idempotency-Key"] = opts.idem;
+ if (opts.etag) headers["If-None-Match"] = opts.etag;
+ let res: Response;
+ try {
+ res = await fetch(BASE + path, {
+ method,
+ headers,
+ body: body === undefined ? undefined : JSON.stringify(body),
+ redirect: "manual",
+ credentials: "same-origin",
+ keepalive: opts.keepalive,
+ });
+ } catch {
+ if (!opts.quiet) events.onContact?.(false);
+ throw new LostContact("no answer");
+ }
+ if (res.type === "opaqueredirect" || (res.status >= 300 && res.status < 400 && res.status !== 304)) {
+ events.onSignedOut?.();
+ throw new SignedOut("signed out");
+ }
+ if (res.status === 304) {
+ events.onContact?.(true);
+ return { status: 304, data: null, etag: opts.etag ?? null };
+ }
+ let json: unknown = null;
+ const text = await res.text();
+ try {
+ json = text ? JSON.parse(text) : null;
+ } catch {
+ json = null;
+ }
+ if (json && typeof json === "object" && "server_time" in json) {
+ const t = Date.parse(String((json as { server_time: string }).server_time));
+ if (!Number.isNaN(t)) events.onServerTime?.(t - Date.now());
+ }
+ if (!envelope(json)) {
+ if (res.status === 401) {
+ events.onSignedOut?.();
+ throw new SignedOut("signed out");
+ }
+ if (res.status >= 502 && res.status <= 504) {
+ if (!opts.quiet) events.onContact?.(false);
+ throw new LostContact(`proxy answered ${res.status}`);
+ }
+ events.onContact?.(true);
+ return { status: res.status, data: json as T, etag: res.headers.get("ETag") };
+ }
+ events.onContact?.(true);
+ const env = json;
+ if (env.error.code === "request.in_progress") {
+ await sleep(1000);
+ continue;
+ }
+ if (env.error.code === "rate.limited" && !rateRetried) {
+ rateRetried = true;
+ await sleep(Math.min(60, env.error.retry_after_s ?? 1) * 1000);
+ continue;
+ }
+ if (res.status === 401 && env.error.code.startsWith("token.")) {
+ // The UI holds no token: a token refusal means the sign-in did not reach control.
+ events.onSignedOut?.();
+ throw new SignedOut(env.error.message);
+ }
+ throw new ApiError(res.status, env.error, env.errors ?? [], env.request_id ?? "");
+ }
+ throw new ApiError(
+ 409,
+ {
+ code: "request.in_progress",
+ message: "The first request with this Idempotency-Key is still being handled. Try again in a moment.",
+ field: null,
+ params: {},
+ retry_after_s: 1,
+ detail: null,
+ },
+ [],
+ "",
+ );
+}
+
+export const get = (path: string, opts?: CallOptions) => call("GET", path, undefined, opts).then((a) => a.data as T);
+export const post = (path: string, body: unknown = {}, opts?: CallOptions) =>
+ call("POST", path, body, { idem: newKey(), ...opts }).then((a) => a.data as T);
+export const put = (path: string, body: unknown, opts?: CallOptions) =>
+ call("PUT", path, body, { idem: newKey(), ...opts }).then((a) => a.data as T);
+export const patch = (path: string, body: unknown, opts?: CallOptions) =>
+ call("PATCH", path, body, { idem: newKey(), ...opts }).then((a) => a.data as T);
+export const del = (path: string, opts?: CallOptions) => call("DELETE", path, undefined, opts).then(() => undefined);
+
+/** A UI sentence for request.* codes (handoff §12.4): bugs or a stale page, not user mistakes. */
+export function sentence(e: unknown): string {
+ if (e instanceof ApiError) {
+ if (e.code.startsWith("request.") && e.code !== "request.in_progress") {
+ return "Ianitor refused this request from the page. Reload the page and try again.";
+ }
+ return e.body.message;
+ }
+ if (e instanceof LostContact) return "Ianitor's control service is not answering. Traffic keeps flowing; changes wait until it is back.";
+ if (e instanceof SignedOut) return "Your sign-in has ended. Sign in again; this page keeps what you typed.";
+ return "Something went wrong.";
+}
diff --git a/apps/web/src/lib/app.svelte.ts b/apps/web/src/lib/app.svelte.ts
new file mode 100644
index 0000000..be2af13
--- /dev/null
+++ b/apps/web/src/lib/app.svelte.ts
@@ -0,0 +1,180 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at https://mozilla.org/MPL/2.0/.
+
+// Shared UI state: the overview (polled, handoff §3), the route, contact and sign-in state,
+// the server clock offset and toasts. No business logic: everything shown comes from control.
+
+import { call, newKey, sentence, setClientEvents } from "./api";
+import type { Overview } from "./types";
+
+export interface Toast {
+ id: number;
+ text: string;
+}
+
+export const app = $state({
+ overview: null as Overview | null,
+ etag: null as string | null,
+ loadError: false,
+ lostContact: false,
+ lostSince: 0,
+ lastUpdated: 0,
+ signedOut: false,
+ offset: 0,
+ now: Date.now(),
+ path: typeof location === "undefined" ? "/" : location.pathname + location.search,
+ toasts: [] as Toast[],
+ /** Dismissed banner keys (reverted outcome, renewed, switched). */
+ dismissed: [] as string[],
+ /** The outcome of the last engine switch, until dismissed (handoff §9.2). */
+ switchResult: null as null | { ok: boolean; title: string; text: string; detail?: string | null },
+ /** A renewal just installed (handoff §13.5). */
+ renewedUntil: null as null | string,
+ /** After a kept add or edit: the row whose More button gets focus (§7.5). */
+ focusHost: null as string | null,
+ /** Narrower than 720 px (the phone layout, handoff §5.2). */
+ phone: false,
+ /** Panels the main screen opens (add/edit host, share, engine). */
+ panel: null as null | { kind: "host"; hostname?: string; resume?: string } | { kind: "share"; hostname: string } | { kind: "engine" },
+});
+
+let failures = 0;
+let firstFailure = 0;
+
+setClientEvents({
+ onSignedOut: () => {
+ app.signedOut = true;
+ },
+ onContact: (ok) => {
+ if (ok) {
+ failures = 0;
+ app.lostContact = false;
+ return;
+ }
+ if (failures === 0) firstFailure = Date.now();
+ failures++;
+ // Retry quietly for 10 s (a reload takes about 2 s), then say so (§11.1).
+ if (Date.now() - firstFailure >= 10_000) {
+ if (!app.lostContact) app.lostSince = Date.now();
+ app.lostContact = true;
+ }
+ },
+ onServerTime: (o) => {
+ app.offset = o;
+ },
+});
+
+/** Server time now, in ms (all countdowns use it, §7.2). */
+export function serverNow(): number {
+ return app.now + app.offset;
+}
+
+/** Seconds left until an ISO time, on the server's clock. */
+export function secondsLeft(iso: string | null | undefined): number {
+ if (!iso) return 0;
+ return Math.max(0, Math.ceil((Date.parse(iso) - serverNow()) / 1000));
+}
+
+export async function refresh(): Promise {
+ if (app.signedOut) return;
+ try {
+ const a = await call("GET", "/overview", undefined, { etag: app.etag ?? undefined });
+ if (a.status === 200 && a.data) {
+ app.overview = a.data;
+ app.etag = a.etag;
+ }
+ app.loadError = false;
+ app.lastUpdated = Date.now();
+ } catch {
+ if (!app.overview) app.loadError = true;
+ }
+}
+
+let timer: ReturnType | undefined;
+let hiddenSince = 0;
+
+/** Poll every 5 s while visible, 30 s when hidden, stop after 15 min hidden (Q9). */
+export function startPolling(): () => void {
+ let stopped = false;
+ const tick = async () => {
+ if (stopped) return;
+ const hidden = typeof document !== "undefined" && document.visibilityState === "hidden";
+ if (hidden && !hiddenSince) hiddenSince = Date.now();
+ if (!hidden) hiddenSince = 0;
+ if (!(hidden && Date.now() - hiddenSince > 15 * 60_000)) await refresh();
+ const every = app.lostContact ? 5000 : hidden ? 30_000 : 5000;
+ timer = setTimeout(tick, every);
+ };
+ const vis = () => {
+ if (document.visibilityState === "visible" && hiddenSince) {
+ hiddenSince = 0;
+ clearTimeout(timer);
+ void tick();
+ }
+ };
+ document.addEventListener("visibilitychange", vis);
+ const clock = setInterval(() => (app.now = Date.now()), 1000);
+ void tick();
+ return () => {
+ stopped = true;
+ clearTimeout(timer);
+ clearInterval(clock);
+ document.removeEventListener("visibilitychange", vis);
+ };
+}
+
+let toastId = 0;
+export function toast(text: string): void {
+ const id = ++toastId;
+ app.toasts = [...app.toasts.slice(-2), { id, text }];
+ setTimeout(() => {
+ app.toasts = app.toasts.filter((t) => t.id !== id);
+ }, 6000);
+}
+
+export function navigate(path: string): void {
+ if (path === app.path) return;
+ history.pushState({}, "", path);
+ app.path = path;
+}
+
+if (typeof window !== "undefined" && typeof window.matchMedia === "function") {
+ const mq = window.matchMedia("(max-width: 719.98px)");
+ app.phone = mq.matches;
+ mq.addEventListener?.("change", (e) => (app.phone = e.matches));
+}
+
+if (typeof window !== "undefined") {
+ window.addEventListener("popstate", () => {
+ app.path = location.pathname + location.search;
+ });
+}
+
+/** Is a change allowed now? (Paused, or no contact.) */
+export function changesBlocked(): string | null {
+ const o = app.overview;
+ if (app.lostContact) return "Ianitor's control service is not answering.";
+ if (o?.paused) return "Changes are paused.";
+ return null;
+}
+
+/** "Restore the last kept version" (handoff §7.6): start it and show its progress in a panel.
+ * Returns the sentence to show when it could not start. */
+export async function restoreLastKept(): Promise {
+ const o = app.overview;
+ if (!o?.undo?.target) return null;
+ try {
+ const a = await call<{ apply: { id: string } }>("POST", "/restore", { change_id: o.undo.target.change_id, base_rev: o.rev }, { idem: newKey() });
+ if (a.data) app.panel = { kind: "host", resume: a.data.apply.id };
+ return null;
+ } catch (e) {
+ return sentence(e);
+ }
+}
+
+/** Whether the pause can be cleared by restoring the last kept version. */
+export function restorable(): boolean {
+ const o = app.overview;
+ return !!o?.paused && ["apply.needs_attention", "control.files_unwritten"].includes(o.paused_reason ?? "") && !!o.undo?.target;
+}
diff --git a/apps/web/src/lib/applies.ts b/apps/web/src/lib/applies.ts
new file mode 100644
index 0000000..d724450
--- /dev/null
+++ b/apps/web/src/lib/applies.ts
@@ -0,0 +1,63 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at https://mozilla.org/MPL/2.0/.
+
+// Following an apply (handoff §2.2 of ui-api, §3 here): GET /applies/{id} every second while it
+// runs; quiet retries while edge reloads; the id kept in sessionStorage so a reload resumes it.
+
+import { get } from "./api";
+import { app, refresh } from "./app.svelte";
+import type { ApplyView } from "./types";
+
+export const FINAL = ["kept", "reverted", "failed", "needs_attention"];
+const KEY = "ianitor.activeApply";
+
+export function remember(id: string | null): void {
+ try {
+ if (id) sessionStorage.setItem(KEY, id);
+ else sessionStorage.removeItem(KEY);
+ } catch {
+ /* storage may be off; the bar still shows the running apply */
+ }
+}
+
+export function remembered(): string | null {
+ try {
+ return sessionStorage.getItem(KEY);
+ } catch {
+ return null;
+ }
+}
+
+/** Poll until the apply ends. Returns a stop function. */
+export function follow(id: string, onupdate: (a: ApplyView) => void, every = 1000): () => void {
+ let stopped = false;
+ let timer: ReturnType | undefined;
+ remember(id);
+ const tick = async () => {
+ if (stopped) return;
+ if (app.signedOut) {
+ // No requests while signed out (the overview poll stops too); look again shortly.
+ timer = setTimeout(tick, every);
+ return;
+ }
+ try {
+ const a = await get(`/applies/${encodeURIComponent(id)}`);
+ if (stopped) return;
+ onupdate(a);
+ if (FINAL.includes(a.state)) {
+ remember(null);
+ void refresh();
+ return;
+ }
+ } catch {
+ /* lost contact or a reload in progress: keep trying (the banner says so after 10 s) */
+ }
+ timer = setTimeout(tick, every);
+ };
+ void tick();
+ return () => {
+ stopped = true;
+ clearTimeout(timer);
+ };
+}
diff --git a/apps/web/src/lib/format.ts b/apps/web/src/lib/format.ts
new file mode 100644
index 0000000..9e7dfbb
--- /dev/null
+++ b/apps/web/src/lib/format.ts
@@ -0,0 +1,115 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at https://mozilla.org/MPL/2.0/.
+
+// Formatting only (handoff §3): times in the browser's zone, 24-hour clock, counts sentences.
+
+const MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
+const LONG = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
+
+const two = (n: number) => String(n).padStart(2, "0");
+
+/** "Today 14:02", "Yesterday 21:14", "5 Nov 21:14", "5 Nov 2025". */
+export function when(iso: string | null | undefined, now = Date.now()): string {
+ if (!iso) return "";
+ const d = new Date(iso);
+ if (Number.isNaN(d.getTime())) return "";
+ const n = new Date(now);
+ const hm = `${two(d.getHours())}:${two(d.getMinutes())}`;
+ const sameDay = (a: Date, b: Date) => a.getFullYear() === b.getFullYear() && a.getMonth() === b.getMonth() && a.getDate() === b.getDate();
+ if (sameDay(d, n)) return `Today ${hm}`;
+ const y = new Date(n);
+ y.setDate(n.getDate() - 1);
+ if (sameDay(d, y)) return `Yesterday ${hm}`;
+ if (d.getFullYear() !== n.getFullYear()) return `${d.getDate()} ${MONTHS[d.getMonth()]} ${d.getFullYear()}`;
+ return `${d.getDate()} ${MONTHS[d.getMonth()]} ${hm}`;
+}
+
+/** Inside a sentence: "today 14:02", "yesterday 21:14", "5 Nov 21:14". */
+export function whenInline(iso: string | null | undefined, now = Date.now()): string {
+ return when(iso, now).replace(/^(Today|Yesterday)/, (s) => s.toLowerCase());
+}
+
+/** After "at" / "on": "at 14:03", "yesterday at 21:14", "on 5 Nov at 21:14", "on 5 Nov 2025". */
+export function atTime(iso: string | null | undefined, now = Date.now()): string {
+ const w = when(iso, now);
+ if (!w) return "";
+ if (w.startsWith("Today ")) return `at ${w.slice(6)}`;
+ if (w.startsWith("Yesterday ")) return `yesterday at ${w.slice(10)}`;
+ const m = /^(\d+ \w+) (\d\d:\d\d)$/.exec(w);
+ return m ? `on ${m[1]} at ${m[2]}` : `on ${w}`;
+}
+
+/** "14 November 2026 at 14:20". */
+export function longDate(iso: string | null | undefined, withTime = true): string {
+ if (!iso) return "";
+ const d = new Date(iso);
+ if (Number.isNaN(d.getTime())) return "";
+ const s = `${d.getDate()} ${LONG[d.getMonth()]} ${d.getFullYear()}`;
+ return withTime ? `${s} at ${two(d.getHours())}:${two(d.getMinutes())}` : s;
+}
+
+/** "2 Mar 2027". */
+export function shortDate(iso: string | null | undefined): string {
+ if (!iso) return "";
+ const d = new Date(iso);
+ return `${d.getDate()} ${MONTHS[d.getMonth()]} ${d.getFullYear()}`;
+}
+
+/** "8 s", "6 minutes", "2 hours", "3 days". */
+export function duration(secs: number): string {
+ if (secs < 60) return `${Math.max(0, Math.round(secs))} s`;
+ const m = Math.round(secs / 60);
+ if (m < 60) return m === 1 ? "1 minute" : `${m} minutes`;
+ const h = Math.round(secs / 3600);
+ if (h < 48) return h === 1 ? "1 hour" : `${h} hours`;
+ const days = Math.round(secs / 86400);
+ return `${days} days`;
+}
+
+export function ago(iso: string | null | undefined, now: number): string {
+ if (!iso) return "";
+ return duration((now - Date.parse(iso)) / 1000) + " ago";
+}
+
+/** "7 hosts · 5 healthy, 1 degraded, 1 down" (handoff §5.1); short (phone, §5.2): "5 healthy, 1 degraded, 1 down". */
+export function countsSentence(c: { hosts: number; healthy: number; degraded: number; down: number; unknown: number }, short = false): string {
+ const parts = [`${c.healthy} healthy`];
+ if (c.degraded) parts.push(`${c.degraded} degraded`);
+ if (c.down) parts.push(`${c.down} down`);
+ if (c.unknown) parts.push(`${c.unknown} not checked`);
+ if (short) return parts.join(", ");
+ return `${c.hosts} ${c.hosts === 1 ? "host" : "hosts"} · ${parts.join(", ")}`;
+}
+
+/** Split a server message on its first sentence (handoff §7.5). */
+export function firstSentence(m: string): [string, string] {
+ const i = m.indexOf(". ");
+ return i < 0 ? [m, ""] : [m.slice(0, i + 1), m.slice(i + 2)];
+}
+
+/** Field labels in sentences (handoff §6.5). */
+export const FIELD_LABEL: Record = {
+ hostname: "address",
+ upstreams: "sends traffic to",
+ tls: "certificate",
+ auth: "who can open it",
+ "health_check.path": "health check address",
+ "health_check.interval_secs": "checks every",
+ share_links: "share links",
+ device_certs: "device certificates",
+ access_log: "visit log",
+ websockets: "websockets",
+ headers: "header rules",
+};
+
+export function fieldValue(field: string, v: string): string {
+ if (v === "") return "none";
+ if (field === "tls") return v === "domi" ? "Domi certificate" : "Let's Encrypt";
+ if (field === "auth") return v === "forward-auth" ? "sign in first" : "anyone";
+ if (field === "access_log") return v === "truncated" ? "on" : "off";
+ if (v === "true") return "on";
+ if (v === "false") return "off";
+ if (field === "health_check.interval_secs") return `${v} s`;
+ return v;
+}
diff --git a/apps/web/src/lib/types.ts b/apps/web/src/lib/types.ts
new file mode 100644
index 0000000..73bffda
--- /dev/null
+++ b/apps/web/src/lib/types.ts
@@ -0,0 +1,251 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at https://mozilla.org/MPL/2.0/.
+
+// The shapes the UI reads from control (docs/api.md, docs/ui-api.md, GET /api/v1/openapi.json).
+// Only the fields the UI uses are typed.
+
+export interface ErrorBody {
+ code: string;
+ message: string;
+ field: string | null;
+ params: Record;
+ retry_after_s: number | null;
+ detail: string | null;
+}
+
+export interface ErrorEnvelope {
+ error: ErrorBody;
+ errors: ErrorBody[];
+ request_id: string;
+}
+
+export interface Blocked {
+ code: string;
+ message: string;
+}
+
+export interface Reason {
+ code: string;
+ message: string;
+ hostname?: string | null;
+ upstream?: string | null;
+ field?: string | null;
+ detail?: string | null;
+ params?: Record;
+}
+
+export interface Step {
+ key: "validate" | "compile" | "write" | "reload" | "watch" | "push";
+ state: "pending" | "running" | "done" | "failed" | "skipped";
+}
+
+export interface ApplyView {
+ id: string;
+ change_id: string;
+ kind: "add" | "edit" | "remove" | "undo" | "restore" | "share_links";
+ summary: string;
+ hosts: string[];
+ state: "queued" | "validating" | "applying" | "watching" | "kept" | "reverted" | "failed" | "needs_attention";
+ created_at: string;
+ finished_at: string | null;
+ steps: Step[];
+ queue: { position: number; waiting_for: { apply_id: string; summary: string; seconds_left: number | null } | null } | null;
+ watch: { ends_at: string; seconds_left: number; hosts: { hostname: string; passed: number; failed: number; total: number }[] } | null;
+ reason: Reason | null;
+ errors: ErrorBody[];
+ commit_short: string | null;
+ push: { state: "pushed" | "pending" | "failed"; at: string | null; error_code: string | null; next_try_at: string | null } | null;
+ attempted_host?: HostSpec | null;
+}
+
+export interface HeaderRule {
+ action: "set" | "remove";
+ name: string;
+ value?: string;
+ secret?: string;
+}
+
+export interface HostSpec {
+ hostname: string;
+ upstreams: string[];
+ tls: "domi" | "letsencrypt";
+ auth: "none" | "forward-auth";
+ websockets: boolean;
+ share_links: boolean;
+ device_certs?: boolean;
+ access_log: "off" | "truncated";
+ health_check?: { path: string; interval_secs: number } | null;
+ request_headers?: HeaderRule[];
+ response_headers?: HeaderRule[];
+}
+
+export interface HealthView {
+ state: "healthy" | "degraded" | "down" | "unknown" | "pending";
+ last_check_at: string | null;
+ latency_ms: number | null;
+ since: string | null;
+ failure: { kind: string; upstream: string | null; count: number; of: number } | null;
+ upstreams: { url: string; state: string; last_check_at: string | null; latency_ms: number | null; failure_kind: string | null }[];
+}
+
+export interface HostRow {
+ hostname: string;
+ upstreams: string[];
+ tls: string;
+ auth: string;
+ websockets: boolean;
+ share_links: boolean;
+ device_certs: boolean;
+ added_at: string | null;
+ health: HealthView;
+ certificate: { state: "ok" | "pending" | "failed"; not_after: string | null; error_code: string | null };
+}
+
+export interface PkiRequest {
+ request_id: string;
+ kind: "device" | "intermediate";
+ state: "waiting" | "approved" | "denied" | "expired" | "cancelled" | "failed";
+ match_code: string;
+ created_at: string;
+ expires_at: string;
+ approved_at: string | null;
+ device_id: string | null;
+ name: string | null;
+ csr_pem: string | null;
+ csr_sha256?: string | null;
+ not_after: string | null;
+ message_code: string;
+ message: string;
+ approve_command: string | null;
+ file_base?: string | null;
+ problem: string | null;
+}
+
+export interface IntermediateView {
+ state: "ok" | "due" | "urgent" | "expired" | "missing";
+ subject: string | null;
+ not_after: string | null;
+ days_left: number | null;
+ renewal: PkiRequest | null;
+ banner: Blocked | null;
+}
+
+export interface EngineView {
+ running: "pingora" | "caddy";
+ state: "running" | "switching" | "stopped";
+ since: string | null;
+ target: string | null;
+ switchable: boolean;
+ fallback_ready: { built_at: string | null; current: boolean; compared: number; matched: number; differences: string[] } | null;
+ last_error: Reason | null;
+ notes: Blocked[];
+}
+
+export interface UndoView {
+ available: boolean;
+ target: { change_id: string; summary: string; kept_at: string | null; commit_short: string | null } | null;
+ effect: string | null;
+ blocked: Blocked | null;
+}
+
+export interface Overview {
+ counts: { hosts: number; healthy: number; degraded: number; down: number; unknown: number };
+ hosts: HostRow[];
+ engine: EngineView;
+ last_apply: ApplyView | null;
+ undo: UndoView;
+ active_apply: { id: string; state: string; summary: string; seconds_left: number | null; kind: string; hosts: string[]; watch_ends_at: string | null; queued: number } | null;
+ repo: { name: string; last_push_at: string | null; unpushed: number; push_error_code: string | null } | null;
+ intermediate: IntermediateView | null;
+ site: { forward_auth_configured: boolean; acme_configured: boolean; secrets: string[]; watch_seconds: number; share_links_available: boolean; auth_logout_url?: string | null } | null;
+ paused: Blocked | null;
+ paused_reason: string | null;
+ paused_detail?: string | null;
+ health_error: Blocked | null;
+ rev: string | null;
+ viewer?: { name: string; via: string } | null;
+ server_time: string;
+}
+
+export interface HistoryEntry {
+ change_id: string;
+ summary: string;
+ kind: string;
+ state: string;
+ at: string;
+ commit_short: string | null;
+ hosts: string[];
+ reason_short: string | null;
+}
+
+export interface RestorePreview {
+ restorable: boolean;
+ same_as_current: boolean;
+ changes: { hostname: string; effect: "added" | "removed" | "changed"; fields: { field: string; from: string; to: string }[] }[];
+ blocked: Blocked | null;
+}
+
+export interface ShareLink {
+ id: string;
+ hostname: string;
+ path_prefix: string;
+ created_at: string;
+ expires_at: string;
+ has_password: boolean;
+ state: "active" | "expired" | "stopped";
+}
+
+export interface MintedLink {
+ id: string;
+ url: string;
+ expires_at: string;
+ path_prefix: string;
+ has_password: boolean;
+ warning: Blocked | null;
+}
+
+export interface TokenRow {
+ id: string;
+ name: string;
+ created_at: string;
+ last_used_at: string | null;
+ expires_at: string | null;
+ revoked_at?: string | null;
+}
+
+export interface CreatedToken {
+ id: string;
+ name: string;
+ token: string;
+ expires_at: string | null;
+}
+
+export interface DeviceRow {
+ id: string;
+ name: string;
+ kind: "phone" | "computer" | "app";
+ created_at: string;
+ not_after: string;
+ state: "valid" | "revoked" | "expired";
+ revoked_at: string | null;
+}
+
+export interface CertsView {
+ intermediate: IntermediateView | null;
+ root: { offline: boolean; subject: string; not_after: string; sha256: string };
+ devices: DeviceRow[];
+ device_lifetime_days: number;
+ device_valid_until: string | null;
+ server_lifetime_days: number;
+ approval: string;
+ requests: PkiRequest[];
+}
+
+export interface Bundle {
+ download_url: string;
+ one_time_password: string;
+ expires_at: string;
+ filename: string;
+ qr_svg: string | null;
+}
diff --git a/apps/web/src/main.ts b/apps/web/src/main.ts
new file mode 100644
index 0000000..fcd4afc
--- /dev/null
+++ b/apps/web/src/main.ts
@@ -0,0 +1,11 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at https://mozilla.org/MPL/2.0/.
+
+import "@ianitor/ui/tokens.css";
+import "@ianitor/ui/components.css";
+import { mount } from "svelte";
+import App from "./App.svelte";
+
+const target = document.getElementById("app");
+if (target) mount(App, { target });
diff --git a/apps/web/src/views/Certificates.svelte b/apps/web/src/views/Certificates.svelte
new file mode 100644
index 0000000..cea22c1
--- /dev/null
+++ b/apps/web/src/views/Certificates.svelte
@@ -0,0 +1,257 @@
+
+
+
+
+
Certificates
+ navigate("/certificates/new")}>Device
+
+
+
+{#if problem} (problem = null)}>{#snippet title()}{problem}{/snippet} {/if}
+
+{#if certs}
+
+ Domi intermediate
+ {#if certs.intermediate?.not_after}expires {shortDate(certs.intermediate.not_after)}{/if}
+ Root stays offline ({certs.root.subject}, until {shortDate(certs.root.not_after)}).
+
+
+ Devices
+ {#if certs.devices.length === 0}
+ No device certificates yet A device certificate lets a phone, computer or Domi app into hosts that ask for one.
+ {:else}
+
+ {#each certs.devices as d (d.id)}
+
+
+ {d.name}
+ until {shortDate(d.not_after)}
+ {#if d.state === "revoked"} {:else if d.state === "expired"} {:else if Date.parse(d.not_after) - app.now < 30 * 86_400_000} {/if}
+ {#if confirmRevoke === d.id}
+ Revoke the certificate of "{d.name}"? It can no longer get in.
+ (confirmRevoke = null)} data-autofocus>Cancel
+ revoke(d)}>Revoke
+ {:else if d.state === "valid"}
+ install(d, d.kind === "computer" ? "p12" : "qr") },
+ { label: "Revoke", icon: "trash", danger: true, divider: true, run: () => (confirmRevoke = d.id) },
+ ]} />
+ {/if}
+
+ {/each}
+
+ {/if}
+{/if}
+
+{#if newDevice}
+
+ {#if !request}
+
+ {:else if request.state === "waiting"}
+ Waiting for approval
+ Custos cannot approve device certificates yet, so approve it on the server, and only if it shows the same code:
+ {request.match_code}
+ {#if request.approve_command}Run on the server:
{request.approve_command} {/if}
+ The request stays open for 10 minutes ({Math.floor(secondsLeft(request.expires_at) / 60)}:{String(secondsLeft(request.expires_at) % 60).padStart(2, "0")} left). Nothing is issued until it is approved.
+ Cancel request
+ Waiting for approval. Code {request.match_code}.
+ {:else if issuedDevice}
+ {#snippet title()}{issuedDevice.name} has a certificate. Approved {atTime(request?.approved_at, app.now)}.{/snippet}
+
+ install(issuedDevice, "qr")}>Show QR code
+ install(issuedDevice, "p12")}>Download file (.p12)
+
+ The file is protected with a one-time password shown next to the QR code.
+ {:else}
+ {#snippet title()}{request?.message}{/snippet}
+ {#snippet actions()} { request = null; void issue(); }}>Try again {/snippet}
+ {/if}
+ {#snippet footer()}
+ {#if !request}
+ Cancel
+ Issue
+ {:else if request.state !== "waiting"}
+ { request = null; closeForm(); void load(); }}>Close
+ {/if}
+ {/snippet}
+
+{/if}
+
+{#if bundle}
+ { bundle = null; void refresh(); }}>
+
+ {#if bundle.b.qr_svg}
+
{@html bundle.b.qr_svg}
+ {/if}
+
+
Password for the file
+
{bundle.b.one_time_password}
+
Works once, for 10 minutes ({Math.floor(secondsLeft(bundle.b.expires_at) / 60)}:{String(secondsLeft(bundle.b.expires_at) % 60).padStart(2, "0")} left).
+
+
+
+ {#if bundle.device.kind === "computer"}Open the downloaded file and enter the password when it asks.
+ {:else if bundle.device.kind === "app"}In the app, choose Import certificate, pick the file, and enter the password.
+ {:else}Scan the code with the device's camera, open the link, and enter the password when it asks. Then allow the certificate in the device's settings.{/if}
+
+
+{/if}
+
+
diff --git a/apps/web/src/views/History.svelte b/apps/web/src/views/History.svelte
new file mode 100644
index 0000000..5431572
--- /dev/null
+++ b/apps/web/src/views/History.svelte
@@ -0,0 +1,178 @@
+
+
+
+{host ? `History of ${host}` : "History"}
+{#if host} navigate("/history")}>Show all changes
{/if}
+{#if problem}{#snippet title()}{problem}{/snippet} {/if}
+
+
+
+ {#if loaded && entries.length === 0}
+
No changes yet Every change you apply is listed here, newest first.
+ {/if}
+
+ {#each entries as e, i (e.change_id)}
+ {@const [k, w] = stateOf(e)}
+
+ choose(e.change_id)} onkeydown={(ev) => key(ev, i)}>
+ {e.summary}
+ {when(e.at, app.now)} · {e.state === "kept" ? (e.commit_short ?? "") : (e.reason_short ?? "")}
+
+
+ {/each}
+
+ {#if next}
load(next ?? undefined)}>Show older changes {/if}
+
+
+ {#if chosen && preview}
+
+ Version of {when(entry?.at, app.now)}
+ {#if preview.blocked?.code === "restore.not_kept"}
+ This change did not stay
+ {#if attempt?.reason}{attempt.reason.message}
{/if}
+ This change was undone at the time, so there is nothing to go back to.
+ {#if attempt?.attempted_host} (editFrom = attempt?.attempted_host ?? null)}>Edit and try again
{/if}
+ {:else if preview.blocked?.code === "restore.same"}
+ Go back to this version?
+ This version is the same as the current one. Nothing to restore.
+ (chosen = null)}>Close
+ {:else}
+ Go back to this version?
+ {n === 1 ? "Restoring puts 1 host back to how it was then:" : `Restoring puts ${n} hosts back to how they were then:`}
+
+ {#each preview.changes as c (c.hostname)}
+ {#if c.effect === "added"}{c.hostname} is added back
+ {:else if c.effect === "removed"}{c.hostname} is removed
+ {:else}
+ {#each c.fields as f (f.field)}
+ {c.hostname} : {#if f.field === "headers"}header rules change{:else}{FIELD_LABEL[f.field] ?? f.field} changes from {fieldValue(f.field, f.from)} to {fieldValue(f.field, f.to)}{/if}
+ {/each}
+ {/if}
+ {/each}
+
+ Applied as a new commit with the same {app.overview?.site?.watch_seconds ?? 60}-second watch. If health checks fail, it is undone.
+ {#if blocked}{blocked}
{/if}
+
+ (chosen = null)}>Close
+ Restore this version
+
+ {/if}
+
+ {/if}
+
+
+{#if resume}
+ { resume = null; void load(); }} />
+{/if}
+{#if editFrom}
+ { editFrom = null; void load(); }} />
+{/if}
+
+
diff --git a/apps/web/src/views/Hosts.svelte b/apps/web/src/views/Hosts.svelte
new file mode 100644
index 0000000..201656f
--- /dev/null
+++ b/apps/web/src/views/Hosts.svelte
@@ -0,0 +1,132 @@
+
+
+
+
+
+
Hosts
+ {#if o}
{countsSentence(o.counts, app.phone)}
{/if}
+
+
+ {#if !app.phone} {/if}
+ navigate("/hosts/new")}>Host
+ {#if blocked}{blocked} {/if}
+
+
+
+
+{#if problem} (problem = null)}>{#snippet title()}{problem}{/snippet} {/if}
+
+ (app.panel = { kind: "host", resume: id })} onedit={editAgain} />
+
+{#if !o && !app.loadError}
+ Loading hosts…
+ {#each [0, 1, 2] as i (i)}
{/each}
+
+{:else if app.loadError && !o}
+ {#snippet title()}This page could not load. Ianitor's control service may be restarting.{/snippet}
+ {#snippet actions()} refresh()}>Try again now {/snippet}
+{:else if o && o.hosts.length === 0}
+ No hosts yet Add the first one: the name people type, and where Ianitor should send them.
+{:else if o}
+ navigate(`/hosts/${encodeURIComponent(h)}/edit`)}
+ onremove={remove}
+ onshare={(h) => (app.panel = { kind: "share", hostname: h })}
+ onhistory={(h) => navigate(`/history?host=${encodeURIComponent(h)}`)}
+ onretry={retry} />
+{/if}
+
+{#if o?.repo}
+
+
+{/if}
+
+{#if panelOpen}
+ {#key route.edit ?? (app.panel?.kind === "host" ? app.panel.resume : "new")}
+
+ {/key}
+{/if}
+{#if app.panel?.kind === "share"}
+ { app.panel = null; void refresh(); }} />
+{/if}
+
+
diff --git a/apps/web/src/views/RenewByHand.svelte b/apps/web/src/views/RenewByHand.svelte
new file mode 100644
index 0000000..9be98c9
--- /dev/null
+++ b/apps/web/src/views/RenewByHand.svelte
@@ -0,0 +1,143 @@
+
+
+
+Sign the intermediate by hand
+Custos cannot sign certificates yet, so the Domi root signs on the offline computer. The root key never comes to this server.
+
+{#if !r}
+ {#snippet title()}There is no open renewal request.{/snippet}
+ {#snippet actions()}Start a renewal {/snippet}
+{:else}
+
+ Step 1
+ Download the request
+ This file asks the Domi root to sign a new intermediate certificate. It holds no secret.
+ Download the request (.csr) Download the signing settings (.ext)
+
+
+ Step 2
+ Sign it on the offline computer
+ Copy both files to the offline computer that holds the Domi root.
+ First check that the request is the one this server made. This prints its fingerprint:
+ {checkCmd}
+ {#if r.csr_sha256}openssl must print the same fingerprint as this page: {group(r.csr_sha256)}
{/if}
+ Then sign it:
+ {signCmd}
+ copy(signCmd)}>Copy command {#if copied} Copied {/if}
+ On a computer with Ianitor installed, ianitor-control ca sign signs it instead and shows the match code {r.match_code}.
+
+
+ Step 3
+ Upload the signed certificate
+ {#if paste}
+
+ Signed certificate
+
+
+ {:else}
+
+
Signed certificate (.crt)
+
+
(paste = true)}>Paste it instead
+
+ {/if}
+ {#if err} {err}
{/if}
+ Use this certificate
+
+{/if}
+
+
diff --git a/apps/web/src/views/Settings.svelte b/apps/web/src/views/Settings.svelte
new file mode 100644
index 0000000..2cd2f0f
--- /dev/null
+++ b/apps/web/src/views/Settings.svelte
@@ -0,0 +1,280 @@
+
+
+
+Settings
+
+ {#each TABS as t, i (t.id)}
+ navigate(`/settings/${t.id}`)} onkeydown={(e) => tabKey(e, i)}>{t.label}
+ {/each}
+
+{#if problem} (problem = null)}>{#snippet title()}{problem}{/snippet} {/if}
+
+
+ {#if tab === "general"}
+
Routes repository
+
{settings?.repo ? `${settings.repo.name} on Gitea · ${settings.repo.last_push_at ? "pushed " + whenInline(settings.repo.last_push_at, app.now) : "not pushed yet"}` : "No place to push to is set up."}
+
Health watch after apply
+
{settings?.watch_seconds ?? app.overview?.site?.watch_seconds ?? 60} seconds
+
Signed in
+
{viewer ? (viewer.via === "authelia" ? `${viewer.name} through Authelia` : `API token "${viewer.name}"`) : "Through Authelia"}
+ {#if app.overview?.site?.auth_logout_url}
Sign out
{/if}
+ {:else if tab === "api"}
+
+
API tokens
+ New token
+
+
+
The API listens on 127.0.0.1 only. Ianitor keeps a hash of each token, never the token.
+ {#if tokens.length === 0}
+
No API tokens Scripts and other Domi apps use a token to talk to Ianitor.
+ {:else}
+
+ {#each tokens as t (t.id)}
+
+
+ {t.name}
+
+ {#if revoked[t.id]}Revoked {whenInline(revoked[t.id], app.now)}{:else}Made {shortDate(t.created_at)} · {t.last_used_at ? `last used ${whenInline(t.last_used_at, app.now)}` : "never used"} · {t.expires_at ? `expires ${shortDate(t.expires_at)}` : "never expires"}{/if}
+
+
+ {#if !revoked[t.id] && !t.revoked_at}
+ {#if confirmRevoke === t.id}
+ Revoke "{t.name}"? Anything using it stops working now.
+ (confirmRevoke = null)} data-autofocus>Cancel
+ revoke(t)}>Revoke
+ {:else}
+ (confirmRevoke = t.id)}>Revoke
+ {/if}
+ {/if}
+
+ {/each}
+
+ {/if}
+ {:else if tab === "share-links"}
+
+
Share links
+ {#if active.length} (confirmStopAll = true)}>Stop all share links {/if}
+
+ {#if app.overview?.engine.running === "caddy"}
+
{#snippet title()}Caddy is serving, so these links do not work right now. They work again after switching back to Pingora.{/snippet}
+ {/if}
+ {#if confirmStopAll}
+
Stop all {active.length} active links? Every link made so far stops working. New ones work as usual.
+ (confirmStopAll = false)}>Cancel Stop all
+ {/if}
+ {#if links.length === 0}
+
No share links Make one from a host's menu (⋯), Share link.
+ {:else}
+
+ {#if ended.length}
+
Ended ({ended.length})
+ {#each ended as l (l.id)}{l.hostname}{l.path_prefix !== "/" ? l.path_prefix : ""} {l.state} {shortDate(l.expires_at)} {/each}
+
+ {/if}
+ {/if}
+ {:else}
+
Ianitor Domi 0.1.0
+
MPL-2.0
+
Built, tested and signed by Fabrica Domi
+
Source on Gitea
+ {/if}
+
+
+{#if made}
+ closeToken()}>
+ Copy it now and save it in Custos.
+ Ianitor cannot show it again; if it is lost, make a new one and revoke this one.
+ (e.currentTarget as HTMLInputElement).select()} />
+
+
+
Name
+
+ {#if nameErr}
{nameErr}
{/if}
+
Rename it now or later, so you know what uses it.
+
+
{tokenCopied ? "Copy again" : "Copy token"}
+
+ {#if tokenCopied}Copied. Paste it into Custos now. Ianitor cannot show it again.
{/if}
+ {made.expires_at ? `Expires on ${longDate(made.expires_at, false)}.` : "Never expires."}
+ {#if askClose}
+ Close without copying? The token cannot be shown again.
+ (askClose = false)}>Go back closeToken(true)}>Close anyway
+ {/if}
+ {#snippet footer()} closeToken()}>I have saved it {/snippet}
+
+{/if}
+
+
diff --git a/apps/web/src/views/SignedIn.svelte b/apps/web/src/views/SignedIn.svelte
new file mode 100644
index 0000000..8c2c16d
--- /dev/null
+++ b/apps/web/src/views/SignedIn.svelte
@@ -0,0 +1,33 @@
+
+
+
+
+ IANITOR DOMI
+ You are signed in again.
+ You can close this tab and go back to Ianitor.
+
+
+
diff --git a/apps/web/svelte.config.js b/apps/web/svelte.config.js
new file mode 100644
index 0000000..b235e46
--- /dev/null
+++ b/apps/web/svelte.config.js
@@ -0,0 +1,7 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at https://mozilla.org/MPL/2.0/.
+
+import { vitePreprocess } from "@sveltejs/vite-plugin-svelte";
+
+export default { preprocess: vitePreprocess() };
diff --git a/apps/web/tests/flows.test.ts b/apps/web/tests/flows.test.ts
new file mode 100644
index 0000000..8a21e87
--- /dev/null
+++ b/apps/web/tests/flows.test.ts
@@ -0,0 +1,245 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at https://mozilla.org/MPL/2.0/.
+
+// The smoke test of every ROADMAP §4 flow with its clicks counted (handoff §4, §15): the real
+// app against a stand-in for control's API. Typing, focus and waiting are not clicks.
+
+import { cleanup, render, screen, waitFor, within } from "@testing-library/svelte";
+import userEvent from "@testing-library/user-event";
+import { afterEach, beforeEach, describe, expect, it } from "vitest";
+import App from "../src/App.svelte";
+import { app } from "../src/lib/app.svelte";
+import { installMock, type Mock } from "./mockApi";
+
+let mock: Mock;
+let clicks = 0;
+let user: ReturnType;
+
+async function click(el: Element) {
+ clicks++;
+ await user.click(el);
+}
+
+function start(path = "/") {
+ history.replaceState({}, "", path);
+ app.path = path;
+ app.panel = null;
+ app.overview = null;
+ app.etag = null;
+ app.signedOut = false;
+ app.switchResult = null;
+ app.renewedUntil = null;
+ app.dismissed = [];
+ mock = installMock();
+ clicks = 0;
+ user = userEvent.setup();
+ render(App);
+}
+
+const called = (method: string, path: string) => mock.calls.some((c) => c.method === method && c.path.startsWith(path));
+const T = { timeout: 5000 };
+
+beforeEach(() => {
+ try {
+ sessionStorage.clear();
+ } catch {
+ /* none */
+ }
+});
+afterEach(() => cleanup());
+
+describe("ROADMAP §4 flows, clicks counted", () => {
+ it("Add host: + Host → fill → Apply = 2 clicks, auto-kept", async () => {
+ start();
+ await click(await screen.findByRole("button", { name: "Add a host" }));
+ await user.type(await screen.findByLabelText("Hostname"), "recipes.home.test");
+ await user.type(screen.getByLabelText("Send traffic to"), "http://10.0.0.5:8080");
+ await click(screen.getByRole("button", { name: "Apply" }));
+ // Kept: the panel closes by itself and the new host is in the list.
+ await waitFor(() => expect(called("GET", "/applies/ch_new")).toBe(true), T);
+ await waitFor(() => expect(document.querySelector("dialog.ia-panel")).toBeNull(), T);
+ await screen.findByRole("button", { name: "More for recipes.home.test" }, T);
+ expect(called("POST", "/hosts")).toBe(true);
+ const sent = mock.calls.find((c) => c.method === "POST" && c.path === "/hosts")?.body as { host: Record };
+ // Every field is sent explicitly, with the design's defaults.
+ expect(sent.host).toMatchObject({ hostname: "recipes.home.test", tls: "domi", auth: "forward-auth", websockets: true });
+ expect(clicks).toBe(2);
+ });
+
+ it("Undo last change = 1 click", async () => {
+ start();
+ await click(await screen.findByRole("button", { name: /^Undo: Added recipes\.home\.test/ }));
+ await waitFor(() => expect(called("POST", "/undo")).toBe(true));
+ const body = mock.calls.find((c) => c.path === "/undo" && c.method === "POST")?.body as Record;
+ expect(body.target_change_id).toBe("ch_1");
+ expect(clicks).toBe(1);
+ });
+
+ it("Restore: History → pick → Restore = 3 clicks", async () => {
+ start();
+ await screen.findByRole("button", { name: "Add a host" });
+ const nav = screen.getAllByRole("navigation", { name: "Main" })[0];
+ await click(within(nav).getByRole("link", { name: "History" }));
+ await click(await screen.findByRole("button", { name: /Changed wiki\.home\.test/ }));
+ await screen.findByText(/sends traffic to changes from/);
+ await click(await screen.findByRole("button", { name: "Restore this version" }));
+ await waitFor(() => expect(called("POST", "/restore")).toBe(true));
+ expect(clicks).toBe(3);
+ });
+
+ it("Share link: ⋯ → Share link → Copy = 3 clicks (default expiry 7 days)", async () => {
+ start();
+ await click(await screen.findByRole("button", { name: "More for wiki.home.test" }));
+ await click(await screen.findByRole("menuitem", { name: /Share link/ }));
+ const copy = await screen.findByRole("button", { name: "Copy link" });
+ await waitFor(() => expect(copy.getAttribute("aria-disabled")).toBeNull());
+ await click(copy);
+ await screen.findByText("Copied");
+ const mint = mock.calls.find((c) => c.method === "POST" && c.path.endsWith("/share-links"))?.body as Record;
+ expect(mint.expires_in_s).toBe(604800);
+ expect(await navigator.clipboard.readText()).toContain("?share=ish1.");
+ expect(clicks).toBe(3);
+ });
+
+ it("Share link on a host with links off: 4 clicks (Mark, Q1: the accepted 4th)", async () => {
+ start();
+ await click(await screen.findByRole("button", { name: "More for photos.home.test" }));
+ await click(await screen.findByRole("menuitem", { name: /Share link/ }));
+ await click(await screen.findByRole("button", { name: "Turn on share links" }));
+ const copy = await screen.findByRole("button", { name: "Copy link" }, T);
+ await waitFor(() => expect(copy.getAttribute("aria-disabled")).toBeNull());
+ await click(copy);
+ await screen.findByText("Copied");
+ expect(called("PATCH", "/hosts/photos.home.test")).toBe(true);
+ expect(clicks).toBe(4);
+ });
+
+ it("Switch engine: engine chip → Switch to Caddy = 2 clicks", async () => {
+ start();
+ await click(await screen.findByRole("button", { name: /^Engine: Pingora/ }));
+ await click(await screen.findByRole("button", { name: "Switch to Caddy" }));
+ await waitFor(() => expect(called("POST", "/engine")).toBe(true));
+ const body = mock.calls.find((c) => c.method === "POST" && c.path === "/engine")?.body as Record;
+ expect(body.target).toBe("caddy");
+ await screen.findByText("Now serving with Caddy.", {}, T);
+ expect(clicks).toBe(2);
+ });
+
+ it("Device certificate: Certificates → + Device → Issue = 3 clicks; install is the accepted 4th", async () => {
+ start();
+ await screen.findByRole("button", { name: "Add a host" });
+ const nav = screen.getAllByRole("navigation", { name: "Main" })[0];
+ await click(within(nav).getByRole("link", { name: "Certificates" }));
+ await click(await screen.findByRole("button", { name: "Add a device certificate" }));
+ await user.type(await screen.findByLabelText("Device name"), "Mark's phone");
+ await click(screen.getByRole("button", { name: "Issue" }));
+ await screen.findByLabelText("Match code 47 19 83");
+ expect(clicks).toBe(3);
+ // Approved on the server (the stand-in approves on the first poll).
+ await click(await screen.findByRole("button", { name: "Show QR code" }, T));
+ await screen.findByText("ABCD-EFGH-JKLM-NPQR");
+ expect(clicks).toBe(4);
+ });
+
+ it("Renew intermediate: banner Renew = 1 click", async () => {
+ start();
+ await click(await screen.findByRole("button", { name: "Renew" }));
+ await waitFor(() => expect(called("POST", "/certs/intermediate/renewal")).toBe(true));
+ // The renewal is waiting: the banner says where to sign it (no code to compare with openssl).
+ await screen.findByRole("button", { name: "Sign it by hand" });
+ expect(clicks).toBe(1);
+ });
+
+ it("API token: ⚙ → API → New token = 3 clicks; Copy token is the accepted 4th", async () => {
+ start();
+ await screen.findByRole("button", { name: "Add a host" });
+ const nav = screen.getAllByRole("navigation", { name: "Main" })[0];
+ await click(within(nav).getByRole("link", { name: "Settings" }));
+ await click(await screen.findByRole("tab", { name: "API" }));
+ await click(await screen.findByRole("button", { name: "New token" }));
+ const box = (await screen.findByLabelText("New API token")) as HTMLInputElement;
+ expect(box.value).toBe("ian_tk1_secretvalue");
+ expect(clicks).toBe(3);
+ await click(screen.getByRole("button", { name: "Copy token" }));
+ expect(await navigator.clipboard.readText()).toBe("ian_tk1_secretvalue");
+ expect(clicks).toBe(4);
+ // The token is never stored by the page.
+ expect(JSON.stringify({ ...sessionStorage })).not.toContain("ian_tk1");
+ expect(JSON.stringify({ ...localStorage })).not.toContain("ian_tk1");
+ });
+});
+
+describe("focus", () => {
+ it("+ Host puts the cursor in Hostname, so typing right after the click lands there", async () => {
+ start();
+ await click(await screen.findByRole("button", { name: "Add a host" }));
+ await user.keyboard("recipes.home.test");
+ expect((await screen.findByLabelText("Hostname") as HTMLInputElement).value).toBe("recipes.home.test");
+ });
+
+ it("the share dialog opens on Copy link and gives focus back to the row's More button", async () => {
+ start();
+ const more = await screen.findByRole("button", { name: "More for wiki.home.test" });
+ await click(more);
+ await click(await screen.findByRole("menuitem", { name: /Share link/ }));
+ const copy = await screen.findByRole("button", { name: "Copy link" });
+ await waitFor(() => expect(document.activeElement).toBe(copy));
+ // jsdom fires no cancel event on Esc for a modal dialog: close it with its button.
+ await click(screen.getByRole("button", { name: "Close" }));
+ await waitFor(() => expect(screen.queryByRole("button", { name: "Copy link" })).toBeNull());
+ await waitFor(() => expect(document.activeElement).toBe(more));
+ });
+
+ it("the engine popover closes with Esc and focus goes back to the chip", async () => {
+ start();
+ const chip = await screen.findByRole("button", { name: /^Engine: Pingora/ });
+ await click(chip);
+ await screen.findByRole("button", { name: "Switch to Caddy" });
+ await user.keyboard("{Escape}");
+ await waitFor(() => expect(screen.queryByRole("button", { name: "Switch to Caddy" })).toBeNull());
+ expect(document.activeElement).toBe(screen.getByRole("button", { name: /^Engine: Pingora/ }));
+ });
+
+ it("a click on the engine chip while its popover is open closes it", async () => {
+ start();
+ const chip = await screen.findByRole("button", { name: /^Engine: Pingora/ });
+ await click(chip);
+ await screen.findByRole("button", { name: "Switch to Caddy" });
+ await new Promise((r) => setTimeout(r, 10));
+ await click(chip);
+ await waitFor(() => expect(screen.queryByRole("button", { name: "Switch to Caddy" })).toBeNull());
+ });
+});
+
+describe("sign-in and contact", () => {
+ it("a 401 without Ianitor's envelope shows the signed-out dialog", async () => {
+ start();
+ await screen.findByRole("button", { name: "Add a host" });
+ globalThis.fetch = (async () => new Response("", { status: 401 })) as typeof fetch;
+ app.etag = null;
+ await click(screen.getByRole("button", { name: "Add a host" }));
+ await user.type(await screen.findByLabelText("Hostname"), "x.home.test");
+ await user.type(screen.getByLabelText("Send traffic to"), "http://10.0.0.5:8080");
+ await click(screen.getByRole("button", { name: "Apply" }));
+ await screen.findByRole("alertdialog", { name: "Your sign-in has ended" });
+ // What was typed is still there.
+ expect((screen.getByLabelText("Hostname") as HTMLInputElement).value).toBe("x.home.test");
+ });
+
+ it("every request carries the UI header and no token", async () => {
+ const seen: Headers[] = [];
+ start();
+ const inner = globalThis.fetch;
+ globalThis.fetch = (async (i: RequestInfo | URL, init?: RequestInit) => {
+ seen.push(new Headers(init?.headers));
+ return inner(i, init);
+ }) as typeof fetch;
+ await click(await screen.findByRole("button", { name: /^Undo:/ }));
+ await waitFor(() => expect(seen.length).toBeGreaterThan(0));
+ for (const h of seen) {
+ expect(h.get("X-Ianitor-UI")).toBe("1");
+ expect(h.get("Authorization")).toBeNull();
+ }
+ });
+});
diff --git a/apps/web/tests/mockApi.ts b/apps/web/tests/mockApi.ts
new file mode 100644
index 0000000..1c1228e
--- /dev/null
+++ b/apps/web/tests/mockApi.ts
@@ -0,0 +1,174 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at https://mozilla.org/MPL/2.0/.
+
+// A stateful stand-in for control's API, shaped like the real answers (docs/api.md), so the
+// smoke tests can walk every §4 flow and count its clicks.
+
+type Json = Record;
+
+export interface Mock {
+ calls: { method: string; path: string; body: unknown }[];
+ state: {
+ engine: "pingora" | "caddy";
+ switching: number;
+ intermediate: "ok" | "due";
+ renewal: boolean;
+ requestPolls: number;
+ hostsAdded: string[];
+ };
+}
+
+const now = () => new Date().toISOString();
+const later = (s: number) => new Date(Date.now() + s * 1000).toISOString();
+
+function host(hostname: string, share: boolean) {
+ return {
+ hostname,
+ upstreams: ["http://10.0.0.2:3000"],
+ tls: "domi",
+ auth: "forward-auth",
+ websockets: true,
+ share_links: share,
+ device_certs: false,
+ added_at: null,
+ health: { state: "healthy", last_check_at: now(), latency_ms: 12, since: now(), failure: null, upstreams: [] },
+ certificate: { state: "ok", not_after: later(86400 * 80), error_code: null },
+ };
+}
+
+function apply(id: string, state: string, summary: string, hosts: string[]) {
+ return {
+ id,
+ change_id: id,
+ kind: "add",
+ summary,
+ hosts,
+ state,
+ created_at: now(),
+ finished_at: state === "kept" ? now() : null,
+ steps: ["validate", "compile", "write", "reload", "watch", "push"].map((key) => ({ key, state: state === "kept" ? "done" : "pending" })),
+ queue: null,
+ watch: null,
+ reason: state === "kept" ? { code: "apply.kept", message: `${hosts[0]} is live. Health checks passed for 60 s.` } : null,
+ errors: [],
+ commit_short: "4f1c2ab",
+ push: null,
+ attempted_host: null,
+ };
+}
+
+export function installMock(): Mock {
+ const m: Mock = {
+ calls: [],
+ state: { engine: "pingora", switching: 0, intermediate: "due", renewal: false, requestPolls: 0, hostsAdded: [] },
+ };
+
+ const overview = (): Json => ({
+ counts: { hosts: 2 + m.state.hostsAdded.length, healthy: 2, degraded: 0, down: 0, unknown: 0 },
+ hosts: [host("wiki.home.test", true), host("photos.home.test", false), ...m.state.hostsAdded.map((h) => host(h, false))],
+ engine: {
+ running: m.state.engine,
+ state: m.state.switching > 0 ? "switching" : "running",
+ since: now(),
+ target: null,
+ switchable: true,
+ fallback_ready: { built_at: now(), current: true, compared: 3, matched: 3, differences: ["Every host: Caddy adds its own Server and Via headers to answers, and a Content-Type when your service sends none."] },
+ last_error: null,
+ notes: [],
+ },
+ last_apply: apply("ch_1", "kept", "Added recipes.home.test", ["recipes.home.test"]),
+ undo: {
+ available: true,
+ target: { change_id: "ch_1", summary: "Added recipes.home.test", kept_at: now(), commit_short: "4f1c2ab" },
+ effect: "Removes recipes.home.test",
+ blocked: null,
+ },
+ active_apply: null,
+ repo: { name: "ianitor-routes", last_push_at: now(), unpushed: 0, push_error_code: null },
+ intermediate:
+ m.state.intermediate === "due"
+ ? {
+ state: "due",
+ subject: "Ianitor Domi Intermediate 2025-12",
+ not_after: later(86400 * 23),
+ days_left: 23,
+ renewal: m.state.renewal
+ ? { request_id: "pr_int", kind: "intermediate", state: "waiting", match_code: "47 19 83", created_at: now(), expires_at: later(3600), approved_at: null, device_id: null, name: null, csr_pem: "-----BEGIN CERTIFICATE REQUEST-----\nx\n-----END CERTIFICATE REQUEST-----\n", not_after: null, message_code: "pki.renew.manual", message: "Sign this request…", approve_command: "ianitor-control ca sign …", problem: null }
+ : null,
+ banner: m.state.renewal ? null : { code: "pki.renew_due", message: "The Domi intermediate certificate expires in 23 days, on 30 November 2026." },
+ }
+ : { state: "ok", subject: "x", not_after: later(86400 * 300), days_left: 300, renewal: null, banner: null },
+ site: { forward_auth_configured: true, acme_configured: true, secrets: ["api_key"], watch_seconds: 60, share_links_available: true },
+ paused: null,
+ paused_reason: null,
+ health_error: null,
+ rev: "rev1",
+ viewer: { name: "mark", via: "authelia" },
+ server_time: now(),
+ });
+
+ const routes: [string, RegExp, (mm: RegExpMatchArray, body: Json) => [number, unknown]][] = [
+ ["GET", /^\/overview$/, () => [200, overview()]],
+ ["POST", /^\/hosts\/validate/, () => [200, { message: "This host can be applied." }]],
+ ["POST", /^\/hosts$/, (_, b) => {
+ const h = (b.host as Json).hostname as string;
+ m.state.hostsAdded.push(h);
+ return [202, { apply: apply("ch_new", "queued", `Added ${h}`, [h]) }];
+ }],
+ ["GET", /^\/applies\/ch_new$/, () => [200, apply("ch_new", "kept", `Added ${m.state.hostsAdded.at(-1)}`, [m.state.hostsAdded.at(-1) ?? ""])]],
+ ["GET", /^\/applies\/(.+)$/, (mm) => [200, apply(mm[1], "kept", "Done", ["x.home.test"])]],
+ ["POST", /^\/undo$/, () => [202, { apply: apply("ch_undo", "queued", "Undid: Added recipes.home.test", ["recipes.home.test"]) }]],
+ ["GET", /^\/history(\?.*)?$/, () => [200, { entries: [{ change_id: "ch_old", summary: "Changed wiki.home.test", kind: "edit", state: "kept", at: now(), commit_short: "9b20e7d", hosts: ["wiki.home.test"], reason_short: null }], next_before: null }]],
+ ["GET", /^\/history\/ch_old\/restore-preview$/, () => [200, { restorable: true, same_as_current: false, changes: [{ hostname: "wiki.home.test", effect: "changed", fields: [{ field: "upstreams", from: "http://10.0.0.2:3000", to: "http://10.0.0.9:3000" }] }], blocked: null }]],
+ ["POST", /^\/restore$/, () => [202, { apply: apply("ch_restore", "queued", "Restored the version of 5 November 2026", ["wiki.home.test"]) }]],
+ ["POST", /^\/hosts\/([^/]+)\/share-links$/, (mm) => [201, { id: "sl_1", url: `https://${decodeURIComponent(mm[1])}/?share=ish1.abc`, expires_at: later(7 * 86400), path_prefix: "/", has_password: false, warning: null }]],
+ ["PATCH", /^\/hosts\/([^/]+)$/, (mm) => [202, { apply: apply("ch_share", "queued", `Turned share links on for ${decodeURIComponent(mm[1])}`, [decodeURIComponent(mm[1])]) }]],
+ ["DELETE", /^\/share-links\/.+$/, () => [204, null]],
+ ["GET", /^\/engine$/, () => {
+ if (m.state.switching > 0) {
+ m.state.switching--;
+ if (m.state.switching === 0) m.state.engine = "caddy";
+ }
+ return [200, { running: m.state.engine, state: m.state.switching > 0 ? "switching" : "running", target: null, since: now(), switchable: true, last_error: null, notes: [] }];
+ }],
+ ["POST", /^\/engine$/, () => {
+ m.state.switching = 1;
+ return [202, { running: m.state.engine, state: "switching", target: "caddy", since: now(), switchable: true, last_error: null, notes: [] }];
+ }],
+ ["GET", /^\/certs$/, () => [200, { intermediate: overview().intermediate, root: { offline: true, subject: "Domi PKI Root", not_after: later(86400 * 3000), sha256: "ab" }, devices: [], device_lifetime_days: 365, server_lifetime_days: 90, approval: "manual", requests: [] }]],
+ ["POST", /^\/certs\/devices$/, (_, b) => [202, { request_id: "pr_dev", kind: "device", state: "waiting", match_code: "47 19 83", created_at: now(), expires_at: later(600), approved_at: null, device_id: null, name: b.name, csr_pem: null, not_after: null, message_code: "pki.waiting.manual", message: "Approve it on the server…", approve_command: "ianitor-control pki approve 47 19 83", problem: null }]],
+ ["GET", /^\/pki-requests\/pr_dev$/, () => {
+ m.state.requestPolls++;
+ return [200, { request_id: "pr_dev", kind: "device", state: "approved", match_code: "47 19 83", created_at: now(), expires_at: later(600), approved_at: now(), device_id: "dv_1", name: "Mark's phone", csr_pem: null, not_after: null, message_code: "pki.issued", message: "Mark's phone has a certificate.", approve_command: null, problem: null }];
+ }],
+ ["POST", /^\/certs\/devices\/dv_1\/bundle$/, () => [200, { download_url: "https://ui.home.test/api/v1/device-bundles/abc", one_time_password: "ABCD-EFGH-JKLM-NPQR", expires_at: later(600), filename: "domi-device.p12", qr_svg: " " }]],
+ ["POST", /^\/certs\/intermediate\/renewal$/, () => {
+ m.state.renewal = true;
+ return [202, { request_id: "pr_int", kind: "intermediate", state: "waiting", match_code: "47 19 83" }];
+ }],
+ ["GET", /^\/settings$/, () => [200, { repo: { name: "ianitor-routes", last_push_at: now() }, watch_seconds: 60 }]],
+ ["GET", /^\/tokens$/, () => [200, { items: [] }]],
+ ["POST", /^\/tokens$/, (_, b) => [201, { id: "tk_1", name: b.name, token: "ian_tk1_secretvalue", expires_at: later(365 * 86400) }]],
+ ["GET", /^\/share-links$/, () => [200, { items: [], epoch: 0 }]],
+ ];
+
+ globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {
+ const url = typeof input === "string" ? input : input instanceof URL ? input.pathname + input.search : input.url;
+ const path = url.replace(/^.*\/api\/v1/, "");
+ const method = (init?.method ?? "GET").toUpperCase();
+ const body = init?.body ? JSON.parse(String(init.body)) : {};
+ m.calls.push({ method, path, body });
+ for (const [mm, re, f] of routes) {
+ const match = path.match(re);
+ if (mm === method && match) {
+ const [status, data] = f(match, body);
+ const withTime = data && typeof data === "object" ? { ...(data as Json), server_time: now() } : data;
+ return new Response(status === 204 ? null : JSON.stringify(withTime), { status, headers: { "Content-Type": "application/json" } });
+ }
+ }
+ return new Response(JSON.stringify({ error: { code: "request.not_found", message: "There is no such API call.", field: null, params: {}, retry_after_s: null, detail: null }, errors: [], request_id: "x" }), { status: 404, headers: { "Content-Type": "application/json" } });
+ }) as typeof fetch;
+
+ return m;
+}
diff --git a/apps/web/tests/setup.ts b/apps/web/tests/setup.ts
new file mode 100644
index 0000000..4aadd80
--- /dev/null
+++ b/apps/web/tests/setup.ts
@@ -0,0 +1,39 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at https://mozilla.org/MPL/2.0/.
+
+// jsdom lacks a few browser features the UI uses.
+
+if (typeof HTMLDialogElement !== "undefined") {
+ const p = HTMLDialogElement.prototype as HTMLDialogElement & Record;
+ if (!p.showModal) {
+ p.showModal = function (this: HTMLDialogElement) {
+ this.setAttribute("open", "");
+ };
+ p.show = function (this: HTMLDialogElement) {
+ this.setAttribute("open", "");
+ };
+ p.close = function (this: HTMLDialogElement) {
+ this.removeAttribute("open");
+ };
+ }
+}
+
+const clipboard = { text: "", writeText: async (t: string) => void (clipboard.text = t) };
+Object.defineProperty(globalThis.navigator, "clipboard", { value: clipboard, configurable: true });
+(globalThis as unknown as { __clipboard: typeof clipboard }).__clipboard = clipboard;
+
+if (!("BroadcastChannel" in globalThis)) {
+ (globalThis as unknown as { BroadcastChannel: unknown }).BroadcastChannel = class {
+ onmessage: unknown = null;
+ postMessage() {}
+ close() {}
+ };
+}
+
+if (!("randomUUID" in crypto)) {
+ Object.defineProperty(crypto, "randomUUID", { value: () => Math.random().toString(36).slice(2) });
+}
+
+window.open = () => null;
+HTMLAnchorElement.prototype.click = function () {};
diff --git a/apps/web/tsconfig.json b/apps/web/tsconfig.json
new file mode 100644
index 0000000..b898d96
--- /dev/null
+++ b/apps/web/tsconfig.json
@@ -0,0 +1,19 @@
+{
+ "extends": "@tsconfig/svelte/tsconfig.json",
+ "compilerOptions": {
+ "target": "ES2022",
+ "module": "ESNext",
+ "moduleResolution": "bundler",
+ "strict": true,
+ "noUnusedLocals": true,
+ "noUnusedParameters": true,
+ "noFallthroughCasesInSwitch": true,
+ "noImplicitReturns": true,
+ "verbatimModuleSyntax": true,
+ "isolatedModules": true,
+ "skipLibCheck": true,
+ "types": ["vite/client"],
+ "lib": ["ES2022", "DOM", "DOM.Iterable"]
+ },
+ "include": ["src/**/*.ts", "src/**/*.svelte", "tests/**/*.ts", "../../packages/ui/src/**/*.ts", "../../packages/ui/src/**/*.svelte"]
+}
diff --git a/apps/web/vite.config.ts b/apps/web/vite.config.ts
new file mode 100644
index 0000000..8ce02c2
--- /dev/null
+++ b/apps/web/vite.config.ts
@@ -0,0 +1,38 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at https://mozilla.org/MPL/2.0/.
+
+import { svelte } from "@sveltejs/vite-plugin-svelte";
+import { defineConfig } from "vitest/config";
+
+// Dev server: 127.0.0.1 only (CLAUDE.md), never --host 0.0.0.0. /api goes to control's --dev on
+// 127.0.0.1:7878. In production edge sends Authelia's identity and the per-boot proof; in dev
+// there is no Authelia, so the dev proxy (never the browser) adds the dev API token from
+// $IANITOR_DEV_TOKEN, which `ianitor-control --dev` prints.
+const control = process.env.IANITOR_CONTROL ?? "http://127.0.0.1:7878";
+const token = process.env.IANITOR_DEV_TOKEN;
+
+export default defineConfig({
+ plugins: [svelte()],
+ server: {
+ host: "127.0.0.1",
+ port: 5173,
+ strictPort: true,
+ proxy: {
+ "/api": {
+ target: control,
+ changeOrigin: true,
+ headers: token ? { Authorization: `Bearer ${token}` } : {},
+ },
+ },
+ },
+ preview: { host: "127.0.0.1" },
+ build: { outDir: "dist", sourcemap: false, assetsInlineLimit: 0 },
+ resolve: process.env.VITEST ? { conditions: ["browser"] } : undefined,
+ test: {
+ environment: "jsdom",
+ setupFiles: ["./tests/setup.ts"],
+ include: ["tests/**/*.test.ts"],
+ testTimeout: 20000,
+ },
+});
diff --git a/crates/control/Cargo.toml b/crates/control/Cargo.toml
index 3929d18..bd32f97 100644
--- a/crates/control/Cargo.toml
+++ b/crates/control/Cargo.toml
@@ -15,8 +15,17 @@ path = "src/lib.rs"
name = "ianitor-control"
path = "src/main.rs"
+[features]
+# The crash and write-failure hooks of the crash-safety tests (src/crash.rs). The Nix release
+# build turns them off with --no-default-features.
+default = ["test-hooks"]
+test-hooks = []
+
[dependencies]
ianitor-core.workspace = true
+rustls.workspace = true
+rustls-pki-types.workspace = true
+tokio-rustls.workspace = true
axum = { version = "0.8.9", default-features = false, features = ["http1", "json", "query", "tokio", "matched-path"] }
utoipa = "5"
tokio.workspace = true
@@ -29,13 +38,16 @@ ring.workspace = true
base64.workspace = true
http.workspace = true
bytes.workspace = true
-# Dev mode only: a throw-away CA for the dev hosts (the Domi CA arrives in phase 3).
-rcgen.workspace = true
+# Device certificate install files (PKCS#12) and their QR codes.
+p12-keystore = "0.4"
+qrcode = { version = "0.14", default-features = false, features = ["svg"] }
+# The offline root CLI asks for its passphrase without echo.
+rpassword = "7"
[dev-dependencies]
ianitor-testkit.workspace = true
+p12-keystore = "0.4"
ianitor-edge.workspace = true
-rustls.workspace = true
[lints]
workspace = true
diff --git a/crates/control/src/api/handlers.rs b/crates/control/src/api/handlers.rs
index a6d12fe..1ab3760 100644
--- a/crates/control/src/api/handlers.rs
+++ b/crates/control/src/api/handlers.rs
@@ -124,11 +124,50 @@ fn replay(st: &AppState, s: Stored) -> Response {
// ---------------------------------------------------------------- overview and hosts
+/// What is known to differ on Caddy for these routes (decision Q3: switch allowed, the
+/// differences listed). Control cannot run the differential suite at runtime; these are the
+/// suite's known differences (tests/diff, KD-*) applied to the hosts that use the feature.
+/// Returns (hosts compared, hosts that behave the same, sentences).
+pub fn fallback_differences(m: &ianitor_core::Model) -> (u32, u32, Vec) {
+ let mut out = Vec::new();
+ let mut matched = 0u32;
+ for h in m.hosts() {
+ let before = out.len();
+ if h.share_links {
+ out.push(format!(
+ "{}: share links do not work; visitors with a link get the normal sign-in.",
+ h.hostname
+ ));
+ }
+ if h.auth == ianitor_core::AuthMode::ForwardAuth {
+ out.push(format!(
+ "{}: if Authelia's answer is broken or cut off, Pingora refuses the visit; Caddy goes by its status alone.",
+ h.hostname
+ ));
+ }
+ if out.len() == before {
+ matched += 1;
+ }
+ }
+ if !m.hosts().is_empty() {
+ out.push(
+ "Every host: Caddy adds its own Server and Via headers to answers, and a Content-Type when your service sends none."
+ .into(),
+ );
+ }
+ let n = u32::try_from(m.hosts().len()).unwrap_or(u32::MAX);
+ (n, matched, out)
+}
+
/// Everything the main screen shows, in one call. Answers 304 to a matching If-None-Match.
#[utoipa::path(get, path = "/api/v1/overview", tag = "overview",
responses((status = 200, body = Overview), (status = 304, description = "Unchanged since the ETag"), (status = 401, body = ErrorEnvelope)),
security(("bearer" = [])))]
-pub async fn overview(State(st): Shared, headers: HeaderMap) -> Result {
+pub async fn overview(
+ State(st): Shared,
+ Extension(actor): Extension,
+ headers: HeaderMap,
+) -> Result {
let c = &st.ctl;
let (status, error, since) = {
let h = c
@@ -169,6 +208,9 @@ pub async fn overview(State(st): Shared, headers: HeaderMap) -> Result Result Result {
.links
.iter()
.rev()
+ // A device install link carries its one-time token in the path: never listed. It
+ // expires within minutes, and "Stop all" stops it with the others.
+ .filter(|l| !l.path_prefix.starts_with("/api/v1/device-bundles/"))
.map(|l| ShareLinkView {
id: l.id.clone(),
hostname: l.hostname.clone(),
@@ -1278,19 +1381,26 @@ impl Modify for Bearer {
overview, list_hosts, get_host, validate_host, create_host, update_host, patch_host, delete_host,
retry_certificate, list_applies, get_apply, cancel_apply, history, history_entry, restore_preview,
get_undo, undo, restore, push_now, settings, list_tokens, create_token, rename_token, revoke_token,
- mint_share_link, list_share_links, stop_share_link, stop_all_share_links, health, openapi
+ mint_share_link, list_share_links, stop_share_link, stop_all_share_links, health, openapi,
+ super::pki::get_certs, super::pki::request_device, super::pki::get_request, super::pki::cancel_request,
+ super::pki::get_csr, super::pki::get_ext, super::pki::put_certificate, super::pki::renew, super::pki::revoke_device,
+ super::pki::make_bundle, super::pki::download_bundle, super::pki::get_engine, super::pki::switch_engine
),
components(schemas(
HostSpec, HealthCheckSpec, HeaderRuleSpec, HostWrite, HostPatch, UndoBody, RestoreBody, TokenCreate,
TokenRename, MintBody, ErrorEnvelope, ErrorBody, ApplyAccepted, ApplyView, ApplyList, Step, WatchHost,
Reason, FieldError, Overview, HostList, HostDetail, History, RestorePreview, UndoView, TokenList,
TokenView, CreatedToken, ShareLinkList, ShareLinkView, MintedLink, StoppedAll, Settings, RepoView,
- HealthReport, Done
+ HealthReport, Done, super::pki::CertsView, super::pki::PkiRequestView, super::pki::IntermediateView,
+ super::pki::RootView, super::pki::DeviceView, super::pki::DeviceRequestBody, super::pki::CertificateBody,
+ super::pki::BundleBody, super::pki::BundleView, super::pki::EngineSwitchView, super::pki::EngineBody,
+ FallbackReady
)),
modifiers(&Bearer),
tags(
(name = "overview"), (name = "hosts"), (name = "applies"), (name = "history"),
- (name = "repo"), (name = "settings"), (name = "tokens"), (name = "share-links")
+ (name = "repo"), (name = "settings"), (name = "tokens"), (name = "share-links"),
+ (name = "certs"), (name = "engine")
)
)]
pub struct ApiDoc;
diff --git a/crates/control/src/api/mod.rs b/crates/control/src/api/mod.rs
index 6edfd46..c63c84f 100644
--- a/crates/control/src/api/mod.rs
+++ b/crates/control/src/api/mod.rs
@@ -16,6 +16,8 @@
#![allow(clippy::result_large_err)]
pub mod handlers;
+pub mod pki;
+pub mod ui;
pub mod views;
use std::collections::HashMap;
@@ -317,7 +319,7 @@ fn body_error(e: &serde_json::Error) -> ApiError {
// ---------------------------------------------------------------- middleware
-fn host_allowed(ctl: &Control, headers: &HeaderMap) -> bool {
+pub(crate) fn host_allowed(ctl: &Control, headers: &HeaderMap) -> bool {
let Some(host) = headers.get(header::HOST).and_then(|h| h.to_str().ok()) else {
return false;
};
@@ -328,7 +330,14 @@ fn host_allowed(ctl: &Control, headers: &HeaderMap) -> bool {
format!("127.0.0.1:{port}"),
format!("[::1]:{port}"),
];
- ok.iter().any(|o| o.eq_ignore_ascii_case(host))
+ // The admin host edge forwards the UI on, with or without edge's HTTPS port.
+ let ui = ctl.cfg.ui.as_ref().and_then(|u| u.hostname.as_deref());
+ let ui_ok = ui.is_some_and(|u| {
+ let edge_port = ctl.cfg.compile.https_listen.port();
+ host.eq_ignore_ascii_case(u) || host.eq_ignore_ascii_case(&format!("{u}:{edge_port}"))
+ });
+ ui_ok
+ || ok.iter().any(|o| o.eq_ignore_ascii_case(host))
|| ctl
.cfg
.allowed_hosts
@@ -336,6 +345,55 @@ fn host_allowed(ctl: &Control, headers: &HeaderMap) -> bool {
.any(|a| a.eq_ignore_ascii_case(host))
}
+enum UiIdentity {
+ /// No sign-in headers: an API-token request.
+ None,
+ /// `Remote-*` or a proof header without the right proof.
+ Forged,
+ /// The right proof but no usable `Remote-User`.
+ NoUser,
+ /// The Authelia user name, and the name to show (`Remote-Name` when it is usable).
+ User(String, String),
+}
+
+fn ui_identity(ctl: &Control, headers: &HeaderMap) -> UiIdentity {
+ let names_user = headers.keys().any(|k| k.as_str().starts_with("remote-"));
+ let proof = headers.get("x-ianitor-proof");
+ if !names_user && proof.is_none() {
+ return UiIdentity::None;
+ }
+ let ok = match (proof, &ctl.ui_proof) {
+ (Some(p), Some(want)) => crate::util::ct_eq(p.as_bytes(), want),
+ _ => false,
+ };
+ if !ok {
+ return UiIdentity::Forged;
+ }
+ let users: Vec<&HeaderValue> = headers.get_all("remote-user").iter().collect();
+ match users.as_slice() {
+ [one] => match one.to_str() {
+ Ok(u)
+ if !u.is_empty()
+ && u.len() <= 64
+ && u.bytes().all(|c| c.is_ascii_graphic() && c != b':') =>
+ {
+ let display = headers
+ .get("remote-name")
+ .and_then(|v| v.to_str().ok())
+ .map(str::trim)
+ .filter(|n| {
+ !n.is_empty() && n.chars().count() <= 64 && !n.chars().any(char::is_control)
+ })
+ .unwrap_or(u)
+ .to_owned();
+ UiIdentity::User(u.to_owned(), display)
+ }
+ _ => UiIdentity::NoUser,
+ },
+ _ => UiIdentity::NoUser,
+ }
+}
+
/// Host check, CSRF check, token, rate limit; logs method, route template, status, time.
async fn guard(State(st): State>, mut req: Request, next: Next) -> Response {
let started = Instant::now();
@@ -367,6 +425,46 @@ async fn guard(State(st): State>, mut req: Request, next: Next) ->
Params::new(),
));
}
+ // The web UI, through edge on the admin host (docs/api.md, "Sign-in"): only a request
+ // with the per-boot proof edge adds is identified by its Remote-User. Any other
+ // request that names a user is refused, so a local process cannot claim to be one.
+ match ui_identity(&st.ctl, req.headers()) {
+ UiIdentity::None => {}
+ UiIdentity::Forged => {
+ return Err(ApiError::new(
+ StatusCode::UNAUTHORIZED,
+ "ui.no_proof",
+ Params::new(),
+ ));
+ }
+ UiIdentity::NoUser => {
+ return Err(ApiError::new(
+ StatusCode::UNAUTHORIZED,
+ "ui.no_user",
+ Params::new(),
+ ));
+ }
+ UiIdentity::User(user, display) => {
+ // Cookie-based sign-in: every write carries the UI header, browser or not.
+ if write && !ui {
+ return Err(ApiError::new(
+ StatusCode::FORBIDDEN,
+ "request.csrf",
+ Params::new(),
+ ));
+ }
+ st.limit(&format!("user:{user}"), RATE_PER_MINUTE, 60)
+ .map_err(|s| {
+ ApiError::new(StatusCode::TOO_MANY_REQUESTS, "rate.limited", Params::new())
+ .retry(s)
+ })?;
+ req.extensions_mut().insert(Actor {
+ token_id: format!("user:{user}"),
+ name: display,
+ });
+ return Ok(next.run(req).await);
+ }
+ }
let auth = req
.headers()
.get(header::AUTHORIZATION)
@@ -429,7 +527,7 @@ async fn finish(req: Request, next: Next) -> Response {
let out = match serde_json::from_slice::(&bytes) {
Ok(serde_json::Value::Object(mut m)) => {
m.insert("server_time".into(), rfc3339(now()).into());
- if m.contains_key("error") {
+ if m.get("error").is_some_and(serde_json::Value::is_object) {
m.insert("request_id".into(), request_id.into());
}
serde_json::to_vec(&m).unwrap_or_else(|_| bytes.to_vec())
@@ -503,14 +601,36 @@ pub fn router(st: Arc) -> Router {
post(h::stop_all_share_links),
)
.route("/api/v1/share-links/{id}", delete(h::stop_share_link))
+ .route("/api/v1/certs", get(pki::get_certs))
+ .route("/api/v1/certs/devices", post(pki::request_device))
+ .route("/api/v1/certs/devices/{id}", delete(pki::revoke_device))
+ .route("/api/v1/certs/devices/{id}/bundle", post(pki::make_bundle))
+ .route("/api/v1/certs/intermediate/renewal", post(pki::renew))
+ .route(
+ "/api/v1/pki-requests/{id}",
+ get(pki::get_request).delete(pki::cancel_request),
+ )
+ .route("/api/v1/pki-requests/{id}/csr", get(pki::get_csr))
+ .route("/api/v1/pki-requests/{id}/ext", get(pki::get_ext))
+ .route(
+ "/api/v1/pki-requests/{id}/certificate",
+ axum::routing::put(pki::put_certificate),
+ )
+ .route(
+ "/api/v1/engine",
+ get(pki::get_engine).post(pki::switch_engine),
+ )
.route("/api/v1/health", get(h::health))
.route("/api/v1/openapi.json", get(h::openapi))
.method_not_allowed_fallback(method_not_allowed)
.fallback(not_found)
.layer(middleware::from_fn_with_state(st.clone(), guard))
.layer(DefaultBodyLimit::max(MAX_BODY))
- .with_state(st);
- api.layer(middleware::from_fn(finish))
+ .with_state(st.clone());
+ // In front of the guard: the built UI (static files, no token: they hold no data) and
+ // the one-time device downloads (the link is the secret). Both still check the Host.
+ api.layer(middleware::from_fn_with_state(st, ui::front))
+ .layer(middleware::from_fn(finish))
}
/// The OpenAPI document.
diff --git a/crates/control/src/api/pki.rs b/crates/control/src/api/pki.rs
new file mode 100644
index 0000000..d3b57c7
--- /dev/null
+++ b/crates/control/src/api/pki.rs
@@ -0,0 +1,839 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at https://mozilla.org/MPL/2.0/.
+
+//! Certificates (docs/ui-api.md §1.7, §1.8, §3.6) and the engine switch (§1.9).
+
+// An error answer is built once per failed request; boxing it buys nothing.
+#![allow(clippy::result_large_err)]
+
+use std::sync::Arc;
+
+use axum::Extension;
+use axum::extract::{Path, State};
+use axum::http::{HeaderValue, StatusCode, header};
+use axum::response::{IntoResponse, Response};
+use serde::{Deserialize, Serialize};
+use utoipa::ToSchema;
+
+use super::views::Blocked;
+use super::{Actor, ApiError, AppState, Body};
+use crate::engine::Control;
+use crate::messages::{self, Params, message};
+use crate::pki::{Device, PkiFail, Request};
+use crate::pki_ctl::pki_fail;
+use crate::switch::engine_name;
+use crate::util::{now, rfc3339};
+
+type Shared = State>;
+
+fn json(status: StatusCode, v: &T) -> Response {
+ (status, axum::Json(v)).into_response()
+}
+
+fn plain_id(s: &str) -> bool {
+ !s.is_empty() && s.len() <= 64 && s.bytes().all(|c| c.is_ascii_alphanumeric() || c == b'_')
+}
+
+fn not_found(code: &str) -> ApiError {
+ ApiError::new(StatusCode::NOT_FOUND, code, Params::new())
+}
+
+/// Run blocking PKI work (key unlock, file writes) off the async threads.
+async fn blocking(
+ st: &Arc,
+ f: impl FnOnce(&Control) -> Result + Send + 'static,
+) -> Result {
+ let c = st.ctl.clone();
+ if c.pki.is_none() {
+ return Err(ApiError::new(
+ StatusCode::CONFLICT,
+ "pki.not_configured",
+ Params::new(),
+ ));
+ }
+ tokio::task::spawn_blocking(move || f(&c))
+ .await
+ .map_err(|e| ApiError::internal(e.to_string()))?
+ .map_err(|e| ApiError::from(pki_fail(e)))
+}
+
+fn pki(c: &Control) -> Result<&crate::pki::Pki, PkiFail> {
+ c.pki.as_ref().ok_or(PkiFail::Code("pki.not_configured"))
+}
+
+// ---------------------------------------------------------------- views
+
+#[derive(Debug, Clone, Serialize, ToSchema)]
+pub struct PkiRequestView {
+ pub request_id: String,
+ /// `device` or `intermediate`.
+ pub kind: String,
+ /// `waiting`, `approved`, `denied`, `expired`, `cancelled` or `failed`.
+ pub state: String,
+ pub match_code: String,
+ pub created_at: String,
+ pub expires_at: String,
+ pub approved_at: Option,
+ pub device_id: Option,
+ pub name: Option,
+ /// Renewals: the request to sign offline (also `GET /pki-requests/{id}/csr`).
+ pub csr_pem: Option,
+ /// Renewals: SHA-256 of the request (DER, lowercase hex), what
+ /// `openssl req -in X.csr -outform DER | openssl dgst -sha256` prints on the offline computer.
+ pub csr_sha256: Option,
+ /// Renewals, once installed: the new intermediate's expiry.
+ pub not_after: Option,
+ /// What to tell the user now (`pki.waiting.manual`, `pki.renew.manual`, `pki.denied`, …).
+ pub message_code: String,
+ pub message: String,
+ /// The command that approves it on the server (manual approval).
+ pub approve_command: Option,
+ /// Renewals: the base name of the files (` .csr`, ` .ext`, ` .crt`).
+ pub file_base: Option,
+ /// Why it failed, when it did.
+ pub problem: Option,
+}
+
+pub fn request_view(c: &Control, r: &Request) -> PkiRequestView {
+ let (message_code, message_text) = match r.state.as_str() {
+ "waiting" => c.waiting_message(&r.kind, &r.match_code),
+ "approved" if r.kind == "intermediate" => {
+ let date = r
+ .not_after
+ .map(|t| ianitor_core::time::long_date(t.max(0) as u64))
+ .unwrap_or_default();
+ (
+ "pki.renewed".to_owned(),
+ message("pki.renewed", &messages::params([("date", date)])),
+ )
+ }
+ "approved" => (
+ "pki.issued".to_owned(),
+ message(
+ "pki.issued",
+ &messages::params([("name", r.name.clone().unwrap_or_default())]),
+ ),
+ ),
+ "denied" => (
+ "pki.denied".to_owned(),
+ message("pki.denied", &Params::new()),
+ ),
+ "expired" => (
+ "pki.expired".to_owned(),
+ message("pki.expired", &Params::new()),
+ ),
+ "cancelled" => (
+ "pki.cancelled".to_owned(),
+ "Cancelled. Nothing was issued.".to_owned(),
+ ),
+ _ => ("internal".to_owned(), message("internal", &Params::new())),
+ };
+ let manual = c.cfg.pki.as_ref().is_none_or(|p| p.approval == "manual");
+ PkiRequestView {
+ request_id: r.id.clone(),
+ kind: r.kind.clone(),
+ state: r.state.clone(),
+ match_code: r.match_code.clone(),
+ created_at: rfc3339(r.created_at),
+ expires_at: rfc3339(r.expires_at),
+ approved_at: r.approved_at.map(rfc3339),
+ device_id: r.device_id.clone(),
+ name: r.name.clone(),
+ csr_pem: r.csr_pem.clone(),
+ csr_sha256: r
+ .csr_pem
+ .as_deref()
+ .and_then(|c| ianitor_core::pki::csr_der(c).ok())
+ .map(|d| ianitor_core::pki::sha256_hex(&d)),
+ not_after: r.not_after.map(|t| rfc3339(t.max(0) as u64)),
+ message_code,
+ message: message_text,
+ approve_command: (r.state == "waiting" && manual).then(|| {
+ if r.kind == "intermediate" {
+ ianitor_core::pki::openssl_sign_command(&file_base(r))
+ } else {
+ format!("ianitor-control pki approve {}", r.match_code)
+ }
+ }),
+ file_base: (r.kind == "intermediate").then(|| file_base(r)),
+ problem: r.error.clone(),
+ }
+}
+
+/// `domi-intermediate-2026-11-07`, from the day the request was made.
+pub fn file_base(r: &Request) -> String {
+ format!(
+ "domi-intermediate-{}",
+ rfc3339(r.created_at).get(..10).unwrap_or("request")
+ )
+}
+
+#[derive(Debug, Clone, Serialize, ToSchema)]
+pub struct IntermediateView {
+ /// `ok`, `due` (≤ 30 days), `urgent` (≤ 7 days), `expired` or `missing`.
+ pub state: String,
+ pub subject: Option,
+ pub not_after: Option,
+ pub days_left: Option,
+ pub renewal: Option,
+ /// The banner text for `due`, `urgent`, `expired` and `missing`; `null` when `ok`.
+ pub banner: Option,
+}
+
+pub fn intermediate_view(c: &Control) -> Option {
+ let p = c.pki.as_ref()?;
+ let s = p.status(now());
+ let date = s
+ .not_after
+ .map(|t| ianitor_core::time::long_date(t.max(0) as u64))
+ .unwrap_or_default();
+ let days = s.days_left.unwrap_or(0).to_string();
+ let banner = match s.state {
+ "due" => Some("pki.renew_due"),
+ "urgent" => Some("pki.renew_urgent"),
+ "expired" => Some("pki.intermediate_expired"),
+ "missing" => Some("pki.no_intermediate"),
+ _ => None,
+ }
+ .map(|code| Blocked {
+ code: code.into(),
+ message: message(
+ code,
+ &messages::params([("days", days.clone()), ("date", date.clone())]),
+ ),
+ });
+ Some(IntermediateView {
+ state: s.state.into(),
+ subject: s.subject,
+ not_after: s.not_after.map(|t| rfc3339(t.max(0) as u64)),
+ days_left: s.days_left,
+ renewal: s.renewal.as_ref().map(|r| request_view(c, r)),
+ banner,
+ })
+}
+
+#[derive(Debug, Serialize, ToSchema)]
+pub struct RootView {
+ /// The root key is never on this server.
+ pub offline: bool,
+ pub subject: String,
+ pub not_after: String,
+ pub sha256: String,
+}
+
+#[derive(Debug, Serialize, ToSchema)]
+pub struct DeviceView {
+ pub id: String,
+ pub name: String,
+ /// `phone`, `computer` or `app`.
+ pub kind: String,
+ pub created_at: String,
+ pub not_after: String,
+ /// `valid`, `revoked` or `expired`.
+ pub state: String,
+ pub revoked_at: Option,
+ pub serial: String,
+}
+
+fn device_view(d: &Device, t: u64) -> DeviceView {
+ DeviceView {
+ id: d.id.clone(),
+ name: d.name.clone(),
+ kind: d.kind.clone(),
+ created_at: rfc3339(d.created_at),
+ not_after: rfc3339(d.not_after.max(0) as u64),
+ state: d.state(t).into(),
+ revoked_at: d.revoked_at.map(rfc3339),
+ serial: d.serial.clone(),
+ }
+}
+
+#[derive(Debug, Serialize, ToSchema)]
+pub struct CertsView {
+ pub intermediate: Option,
+ pub root: RootView,
+ pub devices: Vec,
+ pub device_lifetime_days: u32,
+ /// When a device certificate issued now would end: a year, but never past the
+ /// intermediate's end (decision Q7). None without an intermediate.
+ pub device_valid_until: Option,
+ pub server_lifetime_days: u32,
+ /// `manual` (on the server, until Custos can) or `custos`.
+ pub approval: String,
+ /// Open device requests.
+ pub requests: Vec,
+ /// Set while the device list is not in force (could not be written or handed to the
+ /// proxy); Ianitor retries every few seconds.
+ pub devices_problem: Option,
+}
+
+// ---------------------------------------------------------------- handlers
+
+/// The certificates screen.
+#[utoipa::path(get, path = "/api/v1/certs", tag = "certs",
+ responses((status = 200, body = CertsView), (status = 409, body = super::views::ErrorEnvelope)), security(("bearer" = [])))]
+pub async fn get_certs(State(st): Shared) -> Result {
+ let view = blocking(&st, |c| {
+ let p = pki(c)?;
+ let t = now();
+ let root = ianitor_core::pki::inspect(p.root_pem())?;
+ let requests = p_requests(c, t)?;
+ Ok(CertsView {
+ intermediate: intermediate_view(c),
+ root: RootView {
+ offline: true,
+ subject: root.subject_cn,
+ not_after: rfc3339(root.not_after.max(0) as u64),
+ sha256: root.sha256_hex,
+ },
+ devices: p
+ .devices()?
+ .iter()
+ .rev()
+ .map(|d| device_view(d, t))
+ .collect(),
+ device_lifetime_days: ianitor_core::pki::DEVICE_DAYS,
+ device_valid_until: p.intermediate_info().map(|i| {
+ let end = (t as i64 + i64::from(ianitor_core::pki::DEVICE_DAYS) * 86_400)
+ .min(i.not_after);
+ rfc3339(end.max(0) as u64)
+ }),
+ server_lifetime_days: ianitor_core::pki::SERVER_DAYS,
+ approval: c
+ .cfg
+ .pki
+ .as_ref()
+ .map(|p| p.approval.clone())
+ .unwrap_or_default(),
+ requests,
+ devices_problem: c
+ .devices_problem
+ .lock()
+ .ok()
+ .and_then(|p| p.clone())
+ .map(|_| Blocked {
+ code: "pki.devices_unwritten".into(),
+ message: message("pki.devices_unwritten", &Params::new()),
+ }),
+ })
+ })
+ .await?;
+ Ok(json(StatusCode::OK, &view))
+}
+
+fn p_requests(c: &Control, t: u64) -> Result, PkiFail> {
+ let path = crate::pki::requests_path(&c.cfg.state_dir);
+ let rs: Vec = crate::util::read_json(&path)
+ .map_err(PkiFail::Internal)?
+ .unwrap_or_default();
+ Ok(rs
+ .iter()
+ .filter(|r| r.kind == "device" && r.state == "waiting" && r.expires_at > t)
+ .map(|r| request_view(c, r))
+ .collect())
+}
+
+#[derive(Debug, Deserialize, ToSchema)]
+#[serde(deny_unknown_fields)]
+pub struct DeviceRequestBody {
+ pub name: String,
+ /// `phone`, `computer` or `app`.
+ pub kind: String,
+}
+
+/// Ask for a device certificate; it is issued once the request is approved with its code.
+#[utoipa::path(post, path = "/api/v1/certs/devices", tag = "certs", request_body = DeviceRequestBody,
+ responses((status = 202, body = PkiRequestView), (status = 409, body = super::views::ErrorEnvelope), (status = 422, body = super::views::ErrorEnvelope)), security(("bearer" = [])))]
+pub async fn request_device(
+ State(st): Shared,
+ Extension(actor): Extension,
+ body: Body,
+) -> Result {
+ st.limit(&format!("pki:{}", actor.token_id), 20, 3600)
+ .map_err(|s| {
+ ApiError::new(StatusCode::TOO_MANY_REQUESTS, "rate.limited", Params::new()).retry(s)
+ })?;
+ let b = body.value;
+ let name_for_err = b.name.clone();
+ let r = blocking(&st, move |c| {
+ let r = pki(c)?.request_device(&b.name, &b.kind, now(), &actor.name)?;
+ Ok(request_view(c, &r))
+ })
+ .await
+ .map_err(|mut e| {
+ if e.body.code == "pki.device_name_taken" || e.body.code == "pki.device_name" {
+ e.body.field = Some("name".into());
+ e.body
+ .params
+ .insert("name".into(), name_for_err.chars().take(64).collect());
+ } else if e.body.code == "pki.device_kind" {
+ e.body.field = Some("kind".into());
+ }
+ e
+ })?;
+ log::info!(target: "ianitor::pki", "device certificate requested ({})", r.request_id);
+ Ok(json(StatusCode::ACCEPTED, &r))
+}
+
+/// One approval request.
+#[utoipa::path(get, path = "/api/v1/pki-requests/{id}", tag = "certs",
+ responses((status = 200, body = PkiRequestView), (status = 404, body = super::views::ErrorEnvelope)), security(("bearer" = [])))]
+pub async fn get_request(State(st): Shared, Path(id): Path) -> Result {
+ if !plain_id(&id) {
+ return Err(not_found("pki.request_not_found"));
+ }
+ let v = blocking(&st, move |c| {
+ let r = pki(c)?
+ .request(&id, now())?
+ .ok_or(PkiFail::Code("pki.request_not_found"))?;
+ Ok(request_view(c, &r))
+ })
+ .await?;
+ Ok(json(StatusCode::OK, &v))
+}
+
+/// Cancel a request that waits.
+#[utoipa::path(delete, path = "/api/v1/pki-requests/{id}", tag = "certs",
+ responses((status = 204), (status = 404, body = super::views::ErrorEnvelope)), security(("bearer" = [])))]
+pub async fn cancel_request(
+ State(st): Shared,
+ Path(id): Path,
+) -> Result {
+ if !plain_id(&id) {
+ return Err(not_found("pki.request_not_found"));
+ }
+ blocking(&st, move |c| {
+ pki(c)?
+ .cancel(&id)?
+ .map(|_| ())
+ .ok_or(PkiFail::Code("pki.request_not_found"))
+ })
+ .await?;
+ Ok(StatusCode::NO_CONTENT.into_response())
+}
+
+/// A renewal's CSR, as a file to carry to the offline machine.
+#[utoipa::path(get, path = "/api/v1/pki-requests/{id}/csr", tag = "certs",
+ responses((status = 200, description = "PEM PKCS#10"), (status = 404, body = super::views::ErrorEnvelope)), security(("bearer" = [])))]
+pub async fn get_csr(State(st): Shared, Path(id): Path) -> Result {
+ if !plain_id(&id) {
+ return Err(not_found("pki.request_not_found"));
+ }
+ let csr = blocking(&st, move |c| {
+ pki(c)?
+ .request(&id, now())?
+ .and_then(|r| r.csr_pem.clone().map(|c| (c, file_base(&r))))
+ .ok_or(PkiFail::Code("pki.request_not_found"))
+ })
+ .await?;
+ let (csr, base) = csr;
+ let mut r = csr.into_response();
+ r.headers_mut().insert(
+ header::CONTENT_TYPE,
+ HeaderValue::from_static("application/pkcs10"),
+ );
+ if let Ok(v) = HeaderValue::from_str(&format!("attachment; filename=\"{base}.csr\"")) {
+ r.headers_mut().insert(header::CONTENT_DISPOSITION, v);
+ }
+ Ok(r)
+}
+
+#[derive(Debug, Deserialize, ToSchema)]
+#[serde(deny_unknown_fields)]
+pub struct CertificateBody {
+ /// The intermediate certificate signed by the Domi root (PEM).
+ pub certificate_pem: String,
+}
+
+/// Install the signed intermediate for an open renewal.
+#[utoipa::path(put, path = "/api/v1/pki-requests/{id}/certificate", tag = "certs", request_body = CertificateBody,
+ responses((status = 200, body = PkiRequestView), (status = 422, body = super::views::ErrorEnvelope)), security(("bearer" = [])))]
+pub async fn put_certificate(
+ State(st): Shared,
+ Path(id): Path,
+ body: Body,
+) -> Result {
+ if !plain_id(&id) {
+ return Err(not_found("pki.request_not_found"));
+ }
+ let pem = body.value.certificate_pem;
+ if pem.len() > 16 * 1024 {
+ return Err(ApiError::new(
+ StatusCode::UNPROCESSABLE_ENTITY,
+ "pki.bad_certificate",
+ Params::new(),
+ ));
+ }
+ let v = blocking(&st, move |c| {
+ let r = pki(c)?.install_intermediate(&id, &pem, now())?;
+ Ok(request_view(c, &r))
+ })
+ .await?;
+ let c = st.ctl.clone();
+ tokio::spawn(async move { c.refresh_certificates(true).await });
+ Ok(json(StatusCode::OK, &v))
+}
+
+/// Start the renewal of the intermediate (or set up the first one).
+#[utoipa::path(post, path = "/api/v1/certs/intermediate/renewal", tag = "certs",
+ responses((status = 202, body = PkiRequestView), (status = 409, body = super::views::ErrorEnvelope)), security(("bearer" = [])))]
+pub async fn renew(
+ State(st): Shared,
+ Extension(actor): Extension,
+) -> Result {
+ let v = blocking(&st, move |c| {
+ let r = pki(c)?.request_renewal(now(), &actor.name)?;
+ Ok(request_view(c, &r))
+ })
+ .await?;
+ Ok(json(StatusCode::ACCEPTED, &v))
+}
+
+/// Revoke a device: it is off the allow list at once.
+#[utoipa::path(delete, path = "/api/v1/certs/devices/{id}", tag = "certs",
+ responses((status = 204), (status = 404, body = super::views::ErrorEnvelope)), security(("bearer" = [])))]
+pub async fn revoke_device(
+ State(st): Shared,
+ Extension(actor): Extension,
+ Path(id): Path,
+) -> Result {
+ if !plain_id(&id) {
+ return Err(not_found("pki.device_not_found"));
+ }
+ let d = blocking(&st, move |c| {
+ pki(c)?
+ .revoke(&id, now())?
+ .ok_or(PkiFail::Code("pki.device_not_found"))
+ })
+ .await?;
+ log::info!(target: "ianitor::pki", "device {} revoked by {}", d.id, actor.token_id);
+ // The revocation is recorded; it is in force only once the engines have the new list.
+ if let Err(e) = st.ctl.devices_changed().await {
+ let mut err = ApiError::new(
+ StatusCode::SERVICE_UNAVAILABLE,
+ "pki.devices_unwritten",
+ Params::new(),
+ );
+ err.body.detail = Some(e);
+ return Err(err);
+ }
+ Ok(StatusCode::NO_CONTENT.into_response())
+}
+
+#[derive(Debug, Deserialize, ToSchema)]
+#[serde(deny_unknown_fields)]
+pub struct BundleBody {
+ /// `p12` (a file to download) or `qr` (the same link as a QR code).
+ #[serde(default = "p12")]
+ pub format: String,
+}
+
+fn p12() -> String {
+ "p12".into()
+}
+
+#[derive(Debug, Serialize, ToSchema)]
+pub struct BundleView {
+ /// Works once, for 10 minutes.
+ pub download_url: String,
+ /// Asked for when the file is installed. Shown once.
+ pub one_time_password: String,
+ pub expires_at: String,
+ pub filename: String,
+ /// `format = "qr"`: the link as an SVG QR code.
+ pub qr_svg: Option,
+}
+
+/// A one-time install file for a device (G15): PKCS#12, behind a link that works once.
+#[utoipa::path(post, path = "/api/v1/certs/devices/{id}/bundle", tag = "certs", request_body = BundleBody,
+ responses((status = 200, body = BundleView), (status = 409, body = super::views::ErrorEnvelope)), security(("bearer" = [])))]
+pub async fn make_bundle(
+ State(st): Shared,
+ Path(id): Path,
+ body: Body,
+) -> Result {
+ if !plain_id(&id) {
+ return Err(not_found("pki.device_not_found"));
+ }
+ let format = body.value.format;
+ if format != "p12" && format != "qr" {
+ return Err(ApiError::new(
+ StatusCode::UNPROCESSABLE_ENTITY,
+ "request.body",
+ messages::params([("problem", "format must be \"p12\" or \"qr\".".into())]),
+ ));
+ }
+ let (token, password, expires) =
+ blocking(&st, move |c| pki(c)?.make_bundle(&id, now())).await?;
+ let url = bundle_url(&st, &token).await;
+ let qr_svg = if format == "qr" {
+ Some(crate::pki::qr_svg(&url).map_err(|e| ApiError::from(pki_fail(e)))?)
+ } else {
+ None
+ };
+ Ok(json(
+ StatusCode::OK,
+ &BundleView {
+ download_url: url,
+ one_time_password: password,
+ expires_at: rfc3339(expires),
+ filename: "domi-device.p12".into(),
+ qr_svg,
+ },
+ ))
+}
+
+/// Where a device downloads its file: through edge on the admin host when there is one
+/// (as a share link when that host has share links on, so a device without a sign-in can
+/// reach it; the link covers only this one-time path), else control's own address.
+async fn bundle_url(st: &AppState, token: &str) -> String {
+ let c = &st.ctl;
+ let path = format!("/api/v1/device-bundles/{token}");
+ let Some(ui) = c.cfg.ui.as_ref().and_then(|u| u.hostname.clone()) else {
+ return format!("http://{}{path}", c.cfg.listen);
+ };
+ let port = c.cfg.compile.https_listen.port();
+ let authority = if port == 443 {
+ ui.clone()
+ } else {
+ format!("{ui}:{port}")
+ };
+ let shares_on = c
+ .head_model()
+ .ok()
+ .and_then(|(_, _, m)| {
+ m.hosts()
+ .iter()
+ .find(|h| h.hostname.as_str() == ui)
+ .map(|h| h.share_links)
+ })
+ .unwrap_or(false);
+ if shares_on
+ && c.engine_running() != "caddy"
+ && let Some(key) = &c.share_key
+ && let Ok(m) = c.shares.mint(
+ key,
+ &ui,
+ &path,
+ crate::shares::MIN_EXPIRY,
+ None,
+ None,
+ "device install",
+ )
+ {
+ return format!(
+ "https://{authority}{}?{}={}",
+ m.record.path_prefix,
+ ianitor_core::share::QUERY_PARAM,
+ m.token
+ );
+ }
+ format!("https://{authority}{path}")
+}
+
+/// `GET` on a one-time link: a small page with a Download button that posts back. Link
+/// previews and prefetchers only ever GET, so they cannot use up the download.
+pub async fn bundle_page(st: Arc, token: String) -> Response {
+ let valid = token.len() == 64 && token.bytes().all(|c| c.is_ascii_hexdigit());
+ let name = if valid {
+ let ctl = st.ctl.clone();
+ tokio::task::spawn_blocking(move || {
+ ctl.pki.as_ref().and_then(|p| p.peek_bundle(&token, now()))
+ })
+ .await
+ .ok()
+ .flatten()
+ } else {
+ None
+ };
+ let (status, body) = match name {
+ Some(n) => (
+ StatusCode::OK,
+ format!(
+ "Install the certificate for {} \
+ This link works once. After the download, open the file and enter the \
+ one-time password shown in Ianitor.
\
+ ",
+ html_escape(&n)
+ ),
+ ),
+ None => (
+ StatusCode::GONE,
+ format!(
+ "This link has been used {}
",
+ html_escape(&message("pki.bundle_used", &Params::new()))
+ ),
+ ),
+ };
+ let page = format!(
+ " \
+ \
+ Ianitor: device certificate \
+ \
+ {body} "
+ );
+ let mut r = (status, page).into_response();
+ let h = r.headers_mut();
+ h.insert(
+ header::CONTENT_TYPE,
+ HeaderValue::from_static("text/html; charset=utf-8"),
+ );
+ h.insert(header::CACHE_CONTROL, HeaderValue::from_static("no-store"));
+ h.insert("referrer-policy", HeaderValue::from_static("no-referrer"));
+ h.insert(
+ "content-security-policy",
+ HeaderValue::from_static(
+ "default-src 'none'; style-src 'unsafe-inline'; form-action 'self'; frame-ancestors 'none'; base-uri 'none'",
+ ),
+ );
+ r
+}
+
+fn html_escape(s: &str) -> String {
+ let mut o = String::with_capacity(s.len());
+ for c in s.chars() {
+ match c {
+ '&' => o.push_str("&"),
+ '<' => o.push_str("<"),
+ '>' => o.push_str(">"),
+ '"' => o.push_str("""),
+ '\'' => o.push_str("'"),
+ c => o.push(c),
+ }
+ }
+ o
+}
+
+/// The one-time download itself (`POST`, from the link's page). The link is the secret: no
+/// token or sign-in is needed, and it works once.
+#[utoipa::path(post, path = "/api/v1/device-bundles/{token}", tag = "certs",
+ responses((status = 200, description = "application/x-pkcs12"), (status = 410, body = super::views::ErrorEnvelope)))]
+pub async fn download_bundle(
+ State(st): Shared,
+ Path(token): Path,
+) -> Result {
+ if token.len() != 64 || !token.bytes().all(|c| c.is_ascii_hexdigit()) {
+ return Err(ApiError::new(
+ StatusCode::GONE,
+ "pki.bundle_used",
+ Params::new(),
+ ));
+ }
+ let (bytes, _name) = blocking(&st, move |c| pki(c)?.take_bundle(&token, now())).await?;
+ log::info!(target: "ianitor::pki", "a device install file was downloaded");
+ let mut r = bytes.into_response();
+ let h = r.headers_mut();
+ h.insert(
+ header::CONTENT_TYPE,
+ HeaderValue::from_static("application/x-pkcs12"),
+ );
+ h.insert(
+ header::CONTENT_DISPOSITION,
+ HeaderValue::from_static("attachment; filename=\"domi-device.p12\""),
+ );
+ h.insert(header::CACHE_CONTROL, HeaderValue::from_static("no-store"));
+ h.insert("referrer-policy", HeaderValue::from_static("no-referrer"));
+ Ok(r)
+}
+
+// ---------------------------------------------------------------- engine
+
+#[derive(Debug, Serialize, ToSchema)]
+pub struct EngineSwitchView {
+ /// `pingora` or `caddy`.
+ pub running: String,
+ /// `running`, `switching` or `stopped`.
+ pub state: String,
+ pub target: Option,
+ pub since: String,
+ /// Whether this server lets control switch (an `[engine]` section and its units).
+ pub switchable: bool,
+ /// Why the last switch did not happen.
+ pub last_error: Option,
+ /// What changes while Caddy serves.
+ pub notes: Vec,
+}
+
+pub fn engine_view(c: &Control) -> EngineSwitchView {
+ let e = c.engine_state();
+ let notes = if e.running == "caddy" {
+ ["share.engine_caddy"]
+ .iter()
+ .map(|code| Blocked {
+ code: (*code).into(),
+ message: message(code, &Params::new()),
+ })
+ .collect()
+ } else {
+ Vec::new()
+ };
+ EngineSwitchView {
+ running: e.running,
+ state: e.state,
+ target: e.target,
+ since: rfc3339(e.since),
+ switchable: c.engine_cfg().is_some() && c.units.is_some(),
+ last_error: e.last_error,
+ notes,
+ }
+}
+
+/// Which engine serves.
+#[utoipa::path(get, path = "/api/v1/engine", tag = "engine",
+ responses((status = 200, body = EngineSwitchView)), security(("bearer" = [])))]
+pub async fn get_engine(State(st): Shared) -> Response {
+ json(StatusCode::OK, &engine_view(&st.ctl))
+}
+
+#[derive(Debug, Deserialize, ToSchema)]
+#[serde(deny_unknown_fields)]
+pub struct EngineBody {
+ /// `pingora` or `caddy`.
+ pub target: String,
+}
+
+/// Switch the engine. Answers at once; poll `GET /engine` until `state` is `running`.
+#[utoipa::path(post, path = "/api/v1/engine", tag = "engine", request_body = EngineBody,
+ responses((status = 202, body = EngineSwitchView), (status = 409, body = super::views::ErrorEnvelope)), security(("bearer" = [])))]
+pub async fn switch_engine(
+ State(st): Shared,
+ Extension(actor): Extension,
+ body: Body,
+) -> Result {
+ let target = body.value.target;
+ st.ctl.request_switch(&target).map_err(ApiError::from)?;
+ log::info!(target: "ianitor::engine", "switch to {} asked by {}", engine_name(&target), actor.token_id);
+ Ok(json(StatusCode::ACCEPTED, &engine_view(&st.ctl)))
+}
+
+/// The openssl extensions file for signing a renewal by hand (the same profile Custos will
+/// use; docs/pki.md).
+#[utoipa::path(get, path = "/api/v1/pki-requests/{id}/ext", tag = "certs",
+ responses((status = 200, description = "openssl -extfile"), (status = 404, body = super::views::ErrorEnvelope)), security(("bearer" = [])))]
+pub async fn get_ext(State(st): Shared, Path(id): Path) -> Result {
+ if !plain_id(&id) {
+ return Err(not_found("pki.request_not_found"));
+ }
+ let r = blocking(&st, move |c| {
+ pki(c)?
+ .request(&id, now())?
+ .filter(|r| r.kind == "intermediate")
+ .ok_or(PkiFail::Code("pki.request_not_found"))
+ })
+ .await?;
+ let mut resp = ianitor_core::pki::INTERMEDIATE_OPENSSL_EXT.into_response();
+ resp.headers_mut().insert(
+ header::CONTENT_TYPE,
+ HeaderValue::from_static("text/plain; charset=utf-8"),
+ );
+ if let Ok(v) = HeaderValue::from_str(&format!("attachment; filename=\"{}.ext\"", file_base(&r)))
+ {
+ resp.headers_mut().insert(header::CONTENT_DISPOSITION, v);
+ }
+ Ok(resp)
+}
diff --git a/crates/control/src/api/ui.rs b/crates/control/src/api/ui.rs
new file mode 100644
index 0000000..8b878c8
--- /dev/null
+++ b/crates/control/src/api/ui.rs
@@ -0,0 +1,124 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at https://mozilla.org/MPL/2.0/.
+
+//! In front of the API guard: the built web UI (`[ui] static_dir`) and the one-time device
+//! downloads. The UI's files hold no data (it reads everything from the API, which the guard
+//! protects), so they need no token; the Host check still applies against DNS rebinding.
+
+use std::path::{Component, Path, PathBuf};
+use std::sync::Arc;
+
+use axum::body::Body as AxumBody;
+use axum::extract::{Path as AxPath, Request, State};
+use axum::http::{HeaderValue, StatusCode, header};
+use axum::middleware::Next;
+use axum::response::{IntoResponse, Response};
+
+use super::{ApiError, AppState, host_allowed};
+use crate::messages::Params;
+
+const CSP: &str = "default-src 'self'; img-src 'self' data:; style-src 'self' 'unsafe-inline'; \
+ script-src 'self'; connect-src 'self'; frame-ancestors 'none'; base-uri 'none'; form-action 'self'";
+
+pub async fn front(State(st): State>, req: Request, next: Next) -> Response {
+ let path = req.uri().path().to_owned();
+ if let Some(token) = path.strip_prefix("/api/v1/device-bundles/") {
+ if !host_allowed(&st.ctl, req.headers()) {
+ return ApiError::new(StatusCode::FORBIDDEN, "request.host", Params::new())
+ .into_response();
+ }
+ let token = token.to_owned();
+ // GET shows the page; only its button (POST) uses the link up.
+ return match req.method().as_str() {
+ "GET" | "HEAD" => super::pki::bundle_page(st, token).await,
+ "POST" => super::pki::download_bundle(State(st), AxPath(token))
+ .await
+ .unwrap_or_else(IntoResponse::into_response),
+ _ => ApiError::new(
+ StatusCode::METHOD_NOT_ALLOWED,
+ "request.method",
+ Params::new(),
+ )
+ .into_response(),
+ };
+ }
+ if path.starts_with("/api/") || path == "/api" {
+ return next.run(req).await;
+ }
+ if !host_allowed(&st.ctl, req.headers()) {
+ return ApiError::new(StatusCode::FORBIDDEN, "request.host", Params::new()).into_response();
+ }
+ let Some(dir) = st.ctl.cfg.ui.as_ref().and_then(|u| u.static_dir.clone()) else {
+ return ApiError::new(StatusCode::NOT_FOUND, "request.not_found", Params::new())
+ .into_response();
+ };
+ if !matches!(req.method().as_str(), "GET" | "HEAD") {
+ return ApiError::new(
+ StatusCode::METHOD_NOT_ALLOWED,
+ "request.method",
+ Params::new(),
+ )
+ .into_response();
+ }
+ serve_static(&dir, &path).await
+}
+
+/// A file from the UI build. Paths with `..`, odd characters or hidden names are refused;
+/// a path without a file extension is the single-page app (`index.html`).
+async fn serve_static(dir: &Path, url_path: &str) -> Response {
+ let rel = url_path.trim_start_matches('/');
+ let clean = !rel.contains('\\')
+ && rel
+ .bytes()
+ .all(|c| c.is_ascii_alphanumeric() || b"-_./".contains(&c))
+ && Path::new(rel)
+ .components()
+ .all(|c| matches!(c, Component::Normal(n) if !n.to_string_lossy().starts_with('.')));
+ if !clean {
+ return ApiError::new(StatusCode::NOT_FOUND, "request.not_found", Params::new())
+ .into_response();
+ }
+ let has_ext = Path::new(rel).extension().is_some();
+ let file: PathBuf = if rel.is_empty() || !has_ext {
+ dir.join("index.html")
+ } else {
+ dir.join(rel)
+ };
+ let Ok(bytes) = tokio::fs::read(&file).await else {
+ return ApiError::new(StatusCode::NOT_FOUND, "request.not_found", Params::new())
+ .into_response();
+ };
+ let ctype = match file.extension().and_then(|e| e.to_str()).unwrap_or("") {
+ "html" => "text/html; charset=utf-8",
+ "js" | "mjs" => "text/javascript; charset=utf-8",
+ "css" => "text/css; charset=utf-8",
+ "svg" => "image/svg+xml",
+ "png" => "image/png",
+ "ico" => "image/x-icon",
+ "woff2" => "font/woff2",
+ "json" | "webmanifest" => "application/json",
+ "txt" => "text/plain; charset=utf-8",
+ _ => "application/octet-stream",
+ };
+ let immutable = rel.starts_with("assets/") || rel.starts_with("_app/immutable/");
+ let mut r = Response::new(AxumBody::from(bytes));
+ let h = r.headers_mut();
+ h.insert(header::CONTENT_TYPE, HeaderValue::from_static(ctype));
+ h.insert(
+ header::CACHE_CONTROL,
+ HeaderValue::from_static(if immutable {
+ "public, max-age=31536000, immutable"
+ } else {
+ "no-cache"
+ }),
+ );
+ h.insert("content-security-policy", HeaderValue::from_static(CSP));
+ h.insert(
+ "x-content-type-options",
+ HeaderValue::from_static("nosniff"),
+ );
+ h.insert("referrer-policy", HeaderValue::from_static("no-referrer"));
+ h.insert("x-frame-options", HeaderValue::from_static("DENY"));
+ r
+}
diff --git a/crates/control/src/api/views.rs b/crates/control/src/api/views.rs
index dfd5fc9..323efd1 100644
--- a/crates/control/src/api/views.rs
+++ b/crates/control/src/api/views.rs
@@ -406,6 +406,8 @@ pub struct HostRow {
pub auth: String,
pub websockets: bool,
pub share_links: bool,
+ /// Visitors need a Domi device certificate.
+ pub device_certs: bool,
pub added_at: Option,
pub health: HealthView,
pub certificate: CertView,
@@ -439,13 +441,34 @@ pub struct Counts {
#[derive(Debug, Clone, Serialize, ToSchema)]
pub struct EngineView {
- /// `pingora` (the Caddy switch waits on Mark, ROADMAP §10 (b)).
+ /// `pingora` or `caddy`.
pub running: String,
- /// `running` or `stopped` (control cannot reach it).
+ /// `running`, `switching` or `stopped` (control cannot reach it).
pub state: String,
pub since: Option,
- #[schema(value_type = Option)]
- pub fallback_ready: Option,
+ /// The engine a running switch goes to.
+ pub target: Option,
+ /// Whether control can switch on this server (`[engine]` in control.toml).
+ pub switchable: bool,
+ /// The fallback's config: when it was written and whether it is the current tree's.
+ pub fallback_ready: Option,
+ /// Why the last switch did not happen.
+ pub last_error: Option,
+ /// What is different while Caddy serves (`engine.caddy`, `share.engine_caddy`).
+ pub notes: Vec,
+}
+
+#[derive(Debug, Clone, Serialize, ToSchema)]
+pub struct FallbackReady {
+ pub built_at: Option,
+ /// caddy.json is the compiled current tree.
+ pub current: bool,
+ /// Hosts in the current routes, and how many of them behave the same on Caddy as far as
+ /// Ianitor knows (the differential tests' known differences, applied to these hosts).
+ pub compared: u32,
+ pub matched: u32,
+ /// What is different on Caddy, in plain English (per host first, then for every host).
+ pub differences: Vec,
}
#[derive(Debug, Clone, Serialize, ToSchema)]
@@ -477,6 +500,11 @@ pub struct ActiveApply {
pub state: String,
pub summary: String,
pub seconds_left: Option,
+ /// `add`, `edit`, `remove`, `undo`, `restore`, `share_links`: the UI writes the heading.
+ pub kind: String,
+ pub hosts: Vec,
+ /// When the health watch ends (only while watching), for a local countdown.
+ pub watch_ends_at: Option,
pub queued: usize,
}
@@ -496,6 +524,8 @@ pub struct SiteView {
pub secrets: Vec,
pub watch_seconds: u64,
pub share_links_available: bool,
+ /// Authelia's logout address, for "Sign out" (`[ui] logout_url`); `null` hides the link.
+ pub auth_logout_url: Option,
}
#[derive(Debug, Clone, Serialize, ToSchema)]
@@ -507,14 +537,27 @@ pub struct Overview {
pub undo: UndoView,
pub active_apply: Option,
pub repo: Option,
- /// The Domi intermediate; arrives in phase 3.
- #[schema(value_type = Option)]
- pub intermediate: Option,
+ /// The Domi intermediate; `null` when the Domi CA is not set up (`[pki]`).
+ pub intermediate: Option,
pub site: Option,
pub paused: Option,
+ /// Why changes are paused: the underlying code (`apply.needs_attention`, `control.files_unwritten`,
+ /// `repo.unreadable`, …), so the UI can offer the right action.
+ pub paused_reason: Option,
+ /// The technical detail behind the pause, for "Show details" (never a secret).
+ pub paused_detail: Option,
/// Set when control cannot read health from edge (`health.unavailable`).
pub health_error: Option,
pub rev: Option,
+ /// Who is looking: the Authelia user (through edge) or the API token's name.
+ pub viewer: Option,
+}
+
+#[derive(Debug, Clone, Serialize, ToSchema)]
+pub struct Viewer {
+ pub name: String,
+ /// `authelia` or `token`.
+ pub via: String,
}
pub fn added_at(c: &Control, hostname: &str) -> Option {
@@ -526,7 +569,7 @@ pub fn added_at(c: &Control, hostname: &str) -> Option {
}
pub fn undo_view(c: &Control) -> UndoView {
- let blocked = if let Some(p) = c.paused() {
+ let blocked = if let Some(p) = c.effective_pause() {
Some(Blocked {
code: "undo.paused".into(),
message: message("undo.paused", &messages::Params::new()) + " " + &p.message,
@@ -621,6 +664,7 @@ pub fn host_rows(
auth: spec.as_ref().map(|s| s.auth.clone()).unwrap_or_default(),
websockets: spec.as_ref().is_none_or(|s| s.websockets),
share_links: spec.as_ref().is_some_and(|s| s.share_links),
+ device_certs: spec.as_ref().is_some_and(|s| s.device_certs),
added_at: added_at(c, &h),
health: health_view(st, spec.as_ref(), since.get(&h).copied()),
certificate: cert_view(st, spec.as_ref()),
diff --git a/crates/control/src/caddy_guard.rs b/crates/control/src/caddy_guard.rs
new file mode 100644
index 0000000..e931672
--- /dev/null
+++ b/crates/control/src/caddy_guard.rs
@@ -0,0 +1,269 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at https://mozilla.org/MPL/2.0/.
+
+//! The deadline of a trial under Caddy (QC round 2, B2; the Phase 2 guarantee that an
+//! unconfirmed change never outlives control). Edge drops a trial by itself when control does
+//! not confirm it in time; Caddy has no such clock, so two things outside control's own process
+//! stand in for it:
+//!
+//! - `ianitor-control caddy-revert` (systemd `ExecStopPost=` of ianitor-control, so it runs
+//! after every stop, a crash included): with a trial out, Caddy goes back to caddy.json (the
+//! last good config) at once;
+//! - `ianitor-control caddy-guard` (its own unit next to caddy-fallback, so a hung control is
+//! covered too): once a second, it reverts a trial whose deadline has passed.
+//!
+//! Control *arms* the deadline (`caddy-trial.json` in its state dir) before it loads a trial,
+//! and *claims* it (an atomic rename) right after its journal says `confirmed`; the guard
+//! takes it with the same kind of rename (to `.reverting`, then `.expired` once Caddy is
+//! verified on caddy.json; given back if the load fails, so it is tried again). A crash between
+//! `confirmed` and the claim leaves both: the guard and caddy-revert see `confirmed` and leave
+//! the trial to recovery, which promotes it. Whoever renames first wins, so a trial is either confirmed by control or
+//! reverted by the guard, never both. caddy.json itself is only ever written with a confirmed
+//! config, so loading it is always safe.
+
+use std::path::{Path, PathBuf};
+
+use serde::{Deserialize, Serialize};
+
+use crate::config::Config;
+use crate::records::Journal;
+use crate::util::{read_json, write_json};
+
+pub const DEADLINE_FILE: &str = "caddy-trial.json";
+
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(deny_unknown_fields)]
+pub struct TrialDeadline {
+ pub apply_id: String,
+ /// Unix seconds.
+ pub deadline: u64,
+}
+
+fn path(state_dir: &Path, suffix: &str) -> PathBuf {
+ state_dir.join(format!("{DEADLINE_FILE}{suffix}"))
+}
+
+/// Before a trial goes into Caddy.
+pub fn arm(state_dir: &Path, apply_id: &str, deadline: u64) -> Result<(), String> {
+ write_json(
+ &path(state_dir, ""),
+ &TrialDeadline {
+ apply_id: apply_id.to_owned(),
+ deadline,
+ },
+ )
+}
+
+/// Control, before it confirms: `true` if it got the deadline first (the guard has not
+/// reverted the trial), `false` if the guard did.
+pub fn claim(state_dir: &Path) -> bool {
+ let claimed = path(state_dir, ".claimed");
+ if std::fs::rename(path(state_dir, ""), &claimed).is_err() {
+ return false;
+ }
+ let _ = std::fs::remove_file(claimed);
+ true
+}
+
+/// After a trial is reverted (or at start): nothing is out any more.
+pub fn disarm(state_dir: &Path) {
+ for s in ["", ".claimed", ".expired", ".reverting"] {
+ let _ = std::fs::remove_file(path(state_dir, s));
+ }
+}
+
+pub fn armed(state_dir: &Path) -> Option {
+ read_json(&path(state_dir, "")).ok().flatten()
+}
+
+/// Whether control's journal says the change is confirmed (then it is being promoted and
+/// caddy.json will hold it; nothing to revert).
+fn confirmed(state_dir: &Path) -> bool {
+ read_json::(&state_dir.join("journal.json"))
+ .ok()
+ .flatten()
+ .is_some_and(|j| j.stage == "confirmed" || j.stage == "promoted")
+}
+
+/// What to do now, for a deadline file as found (pure, for the tests).
+#[derive(Debug, PartialEq, Eq)]
+pub enum Verdict {
+ Nothing,
+ Revert,
+}
+
+pub fn verdict(armed: Option<&TrialDeadline>, confirmed: bool, now: u64, at_stop: bool) -> Verdict {
+ match armed {
+ Some(d) if !confirmed && (at_stop || now > d.deadline) => Verdict::Revert,
+ _ => Verdict::Nothing,
+ }
+}
+
+/// Whether Caddy is the engine that serves (the engine file; Pingora without `[engine]`).
+fn caddy_serves(cfg: &Config) -> bool {
+ cfg.engine
+ .as_ref()
+ .is_some_and(|e| crate::switch::read_engine_file(&e.file) == "caddy")
+}
+
+/// A revert that stopped half way (the guard died while loading) counts as armed again.
+fn resume_half_done(dir: &Path) {
+ let reverting = path(dir, ".reverting");
+ if reverting.exists() && !path(dir, "").exists() {
+ let _ = std::fs::rename(reverting, path(dir, ""));
+ }
+}
+
+/// Take the deadline away from control (rename to `.reverting`), load the last good
+/// caddy.json and check that Caddy runs it; only then is the deadline marked expired. If the
+/// load fails, the deadline is given back, so the next try (or control's own claim, while
+/// Caddy still runs the trial) decides.
+async fn revert(cfg: &Config, why: &str) -> Result {
+ let dir = &cfg.state_dir;
+ let reverting = path(dir, ".reverting");
+ if std::fs::rename(path(dir, ""), &reverting).is_err() {
+ // Control claimed it a moment ago: it confirms; nothing to do.
+ return Ok(false);
+ }
+ let loaded = async {
+ let sock = cfg
+ .caddy_compile()
+ .caddy_admin_socket
+ .clone()
+ .ok_or("no caddy_admin_socket is configured")?;
+ let text = std::fs::read(&cfg.caddy.config)
+ .map_err(|e| format!("cannot read {}: {e}", cfg.caddy.config.display()))?;
+ crate::caddy_link::load(Path::new(&sock), &text).await?;
+ if !crate::caddy_link::runs(Path::new(&sock), &text).await? {
+ return Err("Caddy took caddy.json but does not run it".to_owned());
+ }
+ Ok::<_, String>(())
+ }
+ .await;
+ match loaded {
+ Ok(()) => {
+ let _ = std::fs::rename(&reverting, path(dir, ".expired"));
+ log::warn!(target: "ianitor::caddy-guard", "{why}: Caddy is back on the last good config");
+ Ok(true)
+ }
+ Err(e) => {
+ let _ = std::fs::rename(&reverting, path(dir, ""));
+ Err(format!("{why}, but Caddy could not be put back yet: {e}"))
+ }
+ }
+}
+
+/// `ianitor-control caddy-revert`: after control stops, a trial still out goes back at once
+/// (retried a few times, 1, 2, 4 and 8 s apart). With another engine serving there is no
+/// Caddy trial: a deadline left behind is cleared and nothing fails.
+pub async fn revert_after_stop(cfg: &Config) -> Result {
+ let dir = &cfg.state_dir;
+ if !caddy_serves(cfg) {
+ disarm(dir);
+ return Ok(false);
+ }
+ resume_half_done(dir);
+ let mut wait = 1;
+ loop {
+ let r = match verdict(
+ armed(dir).as_ref(),
+ confirmed(dir),
+ crate::util::now(),
+ true,
+ ) {
+ Verdict::Revert => revert(cfg, "control stopped with a trial loaded into Caddy").await,
+ Verdict::Nothing => Ok(false),
+ };
+ match r {
+ Err(e) if wait <= 8 => {
+ log::error!(target: "ianitor::caddy-guard", "{e}; trying again in {wait} s");
+ tokio::time::sleep(std::time::Duration::from_secs(wait)).await;
+ wait *= 2;
+ }
+ other => return other,
+ }
+ }
+}
+
+/// One tick of `ianitor-control caddy-guard`.
+pub async fn tick(cfg: &Config) -> Result {
+ let dir = &cfg.state_dir;
+ if !caddy_serves(cfg) {
+ return Ok(false);
+ }
+ resume_half_done(dir);
+ match verdict(
+ armed(dir).as_ref(),
+ confirmed(dir),
+ crate::util::now(),
+ false,
+ ) {
+ Verdict::Revert => revert(cfg, "a trial under Caddy passed its deadline unconfirmed").await,
+ Verdict::Nothing => Ok(false),
+ }
+}
+
+/// `ianitor-control caddy-guard`: forever, once a second; after a failed revert it tries
+/// again with a growing pause (2, 4, … 30 s).
+pub async fn run(cfg: Config) -> Result<(), String> {
+ log::info!(target: "ianitor::caddy-guard", "watching {} for trials under Caddy", cfg.state_dir.display());
+ let mut pause = 1u64;
+ loop {
+ match tick(&cfg).await {
+ Ok(_) => pause = 1,
+ Err(e) => {
+ pause = (pause * 2).min(30);
+ log::error!(target: "ianitor::caddy-guard", "{e}; trying again in {pause} s");
+ }
+ }
+ tokio::time::sleep(std::time::Duration::from_secs(pause)).await;
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ #![allow(clippy::unwrap_used)]
+ use super::*;
+
+ fn d(deadline: u64) -> TrialDeadline {
+ TrialDeadline {
+ apply_id: "ch_1".into(),
+ deadline,
+ }
+ }
+
+ #[test]
+ fn the_guard_reverts_only_an_unconfirmed_trial_past_its_deadline() {
+ assert_eq!(verdict(None, false, 100, false), Verdict::Nothing);
+ assert_eq!(verdict(Some(&d(100)), false, 100, false), Verdict::Nothing);
+ assert_eq!(verdict(Some(&d(100)), false, 101, false), Verdict::Revert);
+ assert_eq!(verdict(Some(&d(100)), true, 500, false), Verdict::Nothing);
+ }
+
+ #[test]
+ fn after_a_stop_an_unconfirmed_trial_goes_back_at_once() {
+ assert_eq!(verdict(Some(&d(1000)), false, 1, true), Verdict::Revert);
+ assert_eq!(verdict(Some(&d(1000)), true, 1, true), Verdict::Nothing);
+ assert_eq!(verdict(None, false, 1, true), Verdict::Nothing);
+ }
+
+ #[test]
+ fn control_and_the_guard_cannot_both_have_the_deadline() {
+ let dir = std::env::temp_dir().join(format!("ianitor-guard-{}", std::process::id()));
+ std::fs::create_dir_all(&dir).unwrap();
+ arm(&dir, "ch_1", 10).unwrap();
+ assert_eq!(armed(&dir), Some(d(10)));
+ // The guard took it (as `revert` does): control's claim fails.
+ std::fs::rename(path(&dir, ""), path(&dir, ".expired")).unwrap();
+ assert!(!claim(&dir));
+ disarm(&dir);
+ // Control claims first: nothing is left for the guard.
+ arm(&dir, "ch_1", 10).unwrap();
+ assert!(claim(&dir));
+ assert!(armed(&dir).is_none());
+ assert!(std::fs::rename(path(&dir, ""), path(&dir, ".expired")).is_err());
+ disarm(&dir);
+ let _ = std::fs::remove_dir_all(&dir);
+ }
+}
diff --git a/crates/control/src/caddy_link.rs b/crates/control/src/caddy_link.rs
new file mode 100644
index 0000000..4dcc777
--- /dev/null
+++ b/crates/control/src/caddy_link.rs
@@ -0,0 +1,366 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at https://mozilla.org/MPL/2.0/.
+
+//! Control's side of the Caddy fallback while it serves (Mark, 2026-11-08: changes keep
+//! working under Caddy): loading a config through Caddy's admin API on its Unix socket
+//! (`POST /load`, the whole JSON) and reading back what runs (`GET /config/`), probing a host
+//! *through* Caddy ("does Caddy answer at all") and its upstreams directly (the health watch,
+//! judged like edge's), and the certificate Caddy serves.
+
+use std::net::SocketAddr;
+use std::path::Path;
+use std::sync::Arc;
+use std::time::{Duration, Instant};
+
+const TIMEOUT: Duration = Duration::from_secs(10);
+
+/// One request to Caddy's admin API (HTTP/1.0: the answer is never chunked).
+async fn admin(socket: &Path, request: &[u8]) -> Result<(u16, Vec), String> {
+ #[cfg(unix)]
+ {
+ use tokio::io::{AsyncReadExt, AsyncWriteExt};
+ let exchange = async {
+ let mut s = tokio::net::UnixStream::connect(socket).await?;
+ s.write_all(request).await?;
+ let mut buf = Vec::new();
+ s.read_to_end(&mut buf).await?;
+ Ok::<_, std::io::Error>(buf)
+ };
+ let buf = tokio::time::timeout(TIMEOUT, exchange)
+ .await
+ .map_err(|_| "Caddy's admin API did not answer within 10 s".to_owned())?
+ .map_err(|e| format!("Caddy's admin API cannot be reached: {e}"))?;
+ let split = buf
+ .windows(4)
+ .position(|w| w == b"\r\n\r\n")
+ .ok_or("no answer from Caddy's admin API")?;
+ let head = String::from_utf8_lossy(&buf[..split]);
+ let status: u16 = head
+ .split(' ')
+ .nth(1)
+ .and_then(|s| s.parse().ok())
+ .ok_or("no answer from Caddy's admin API")?;
+ Ok((status, buf[split + 4..].to_vec()))
+ }
+ #[cfg(not(unix))]
+ {
+ let _ = (socket, request);
+ Err("Caddy's admin socket needs Unix".into())
+ }
+}
+
+/// Load a full Caddy JSON config. Caddy swaps it in gracefully or refuses it (and keeps the
+/// old one). `Cache-Control: must-revalidate` makes Caddy load it even when it is the same as
+/// the running one, so certificate and device files are read again (without it an identical
+/// config is a no-op: QC round 2, B1; `qc_reloading_the_same_caddy_json_rereads_the_certificate_files`).
+pub async fn load(socket: &Path, config: &[u8]) -> Result<(), String> {
+ let mut req = format!(
+ "POST /load HTTP/1.0\r\nHost: localhost\r\nContent-Type: application/json\r\nCache-Control: must-revalidate\r\nContent-Length: {}\r\n\r\n",
+ config.len()
+ )
+ .into_bytes();
+ req.extend_from_slice(config);
+ let (status, body) = admin(socket, &req).await?;
+ if (200..300).contains(&status) {
+ Ok(())
+ } else {
+ Err(format!(
+ "Caddy refused the config ({status}): {}",
+ String::from_utf8_lossy(&body)
+ .trim()
+ .chars()
+ .take(400)
+ .collect::()
+ ))
+ }
+}
+
+/// The config Caddy runs now.
+pub async fn running_config(socket: &Path) -> Result {
+ let (status, body) = admin(socket, b"GET /config/ HTTP/1.0\r\nHost: localhost\r\n\r\n").await?;
+ if status != 200 {
+ return Err(format!(
+ "Caddy's admin API answered {status} to GET /config/"
+ ));
+ }
+ serde_json::from_slice(&body).map_err(|e| format!("Caddy's running config is not JSON: {e}"))
+}
+
+/// Whether Caddy runs exactly this config (as JSON values, so formatting does not matter).
+pub async fn runs(socket: &Path, config: &[u8]) -> Result {
+ let want: serde_json::Value =
+ serde_json::from_slice(config).map_err(|e| format!("not JSON: {e}"))?;
+ Ok(running_config(socket).await? == want)
+}
+
+/// One probe through Caddy: `GET path` on the HTTPS listener with this SNI and Host.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub enum Probe {
+ /// The status Caddy answered with (its own 502/503 when the upstream is down).
+ Status(u16),
+ /// No answer at all (connection, TLS or timeout).
+ NoAnswer(String),
+}
+
+/// The probe does not check Caddy's certificate: it talks to this machine's own listener
+/// on loopback to see whether the *upstream* answers through it, nothing else.
+#[derive(Debug)]
+struct AnyCert;
+
+impl rustls::client::danger::ServerCertVerifier for AnyCert {
+ fn verify_server_cert(
+ &self,
+ _end_entity: &rustls_pki_types::CertificateDer<'_>,
+ _intermediates: &[rustls_pki_types::CertificateDer<'_>],
+ _server_name: &rustls_pki_types::ServerName<'_>,
+ _ocsp: &[u8],
+ _now: rustls_pki_types::UnixTime,
+ ) -> Result {
+ Ok(rustls::client::danger::ServerCertVerified::assertion())
+ }
+ fn verify_tls12_signature(
+ &self,
+ _message: &[u8],
+ _cert: &rustls_pki_types::CertificateDer<'_>,
+ _dss: &rustls::DigitallySignedStruct,
+ ) -> Result {
+ Ok(rustls::client::danger::HandshakeSignatureValid::assertion())
+ }
+ fn verify_tls13_signature(
+ &self,
+ _message: &[u8],
+ _cert: &rustls_pki_types::CertificateDer<'_>,
+ _dss: &rustls::DigitallySignedStruct,
+ ) -> Result {
+ Ok(rustls::client::danger::HandshakeSignatureValid::assertion())
+ }
+ fn supported_verify_schemes(&self) -> Vec {
+ rustls::crypto::ring::default_provider()
+ .signature_verification_algorithms
+ .supported_schemes()
+ }
+}
+
+pub async fn probe(addr: SocketAddr, host: &str, path: &str) -> Probe {
+ use tokio::io::{AsyncReadExt, AsyncWriteExt};
+ let started = Instant::now();
+ let run = async {
+ let provider = Arc::new(rustls::crypto::ring::default_provider());
+ let cfg = rustls::ClientConfig::builder_with_provider(provider)
+ .with_safe_default_protocol_versions()
+ .map_err(|e| e.to_string())?
+ .dangerous()
+ .with_custom_certificate_verifier(Arc::new(AnyCert))
+ .with_no_client_auth();
+ let name =
+ rustls_pki_types::ServerName::try_from(host.to_owned()).map_err(|e| e.to_string())?;
+ let tcp = tokio::net::TcpStream::connect(addr)
+ .await
+ .map_err(|e| e.to_string())?;
+ let mut tls = tokio_rustls::TlsConnector::from(Arc::new(cfg))
+ .connect(name, tcp)
+ .await
+ .map_err(|e| e.to_string())?;
+ let req = format!(
+ "GET {path} HTTP/1.1\r\nHost: {host}\r\nUser-Agent: ianitor-watch\r\nConnection: close\r\n\r\n"
+ );
+ tls.write_all(req.as_bytes())
+ .await
+ .map_err(|e| e.to_string())?;
+ let mut head = [0u8; 64];
+ let mut n = 0;
+ while n < 13 {
+ let k = tls.read(&mut head[n..]).await.map_err(|e| e.to_string())?;
+ if k == 0 {
+ break;
+ }
+ n += k;
+ }
+ let line = String::from_utf8_lossy(&head[..n]);
+ line.split(' ')
+ .nth(1)
+ .and_then(|s| s.parse::().ok())
+ .ok_or_else(|| "no HTTP status".to_owned())
+ };
+ match tokio::time::timeout(Duration::from_secs(5), run).await {
+ Ok(Ok(s)) => Probe::Status(s),
+ Ok(Err(e)) => Probe::NoAnswer(e),
+ Err(_) => Probe::NoAnswer(format!(
+ "no answer within {} s",
+ started.elapsed().as_secs()
+ )),
+ }
+}
+
+/// SHA-256 (hex) of the leaf certificate Caddy serves for this name: after a reload, whether
+/// Caddy really read the certificate files again (the backstop for B1).
+pub async fn served_cert_sha256(addr: SocketAddr, host: &str) -> Result {
+ let run = async {
+ let provider = Arc::new(rustls::crypto::ring::default_provider());
+ let cfg = rustls::ClientConfig::builder_with_provider(provider)
+ .with_safe_default_protocol_versions()
+ .map_err(|e| e.to_string())?
+ .dangerous()
+ .with_custom_certificate_verifier(Arc::new(AnyCert))
+ .with_no_client_auth();
+ let name =
+ rustls_pki_types::ServerName::try_from(host.to_owned()).map_err(|e| e.to_string())?;
+ let tcp = tokio::net::TcpStream::connect(addr)
+ .await
+ .map_err(|e| e.to_string())?;
+ let tls = tokio_rustls::TlsConnector::from(Arc::new(cfg))
+ .connect(name, tcp)
+ .await
+ .map_err(|e| e.to_string())?;
+ let (_, conn) = tls.get_ref();
+ let leaf = conn
+ .peer_certificates()
+ .and_then(|c| c.first())
+ .ok_or("Caddy sent no certificate")?;
+ Ok::<_, String>(crate::util::sha256_hex(leaf.as_ref()))
+ };
+ tokio::time::timeout(Duration::from_secs(5), run)
+ .await
+ .map_err(|_| "Caddy did not finish the handshake within 5 s".to_owned())?
+}
+
+/// One health probe of an upstream, made by control while Caddy serves, with edge's rules
+/// (crates/edge/src/health.rs): a host with a health check gets `GET ` with the upstream
+/// address as Host and passes on 2xx; a host without one gets `GET /` with its own name as
+/// Host and passes on any answer below 500. 5 s timeout. `kind` uses edge's words.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct UpstreamProbe {
+ pub ok: bool,
+ pub kind: Option<&'static str>,
+ pub status: Option,
+ pub latency_ms: Option,
+}
+
+fn status_kind(status: u16) -> &'static str {
+ match status {
+ 300..=399 => "redirect",
+ 401 | 403 => "sign_in",
+ 404 => "not_found",
+ 500..=599 => "server_error",
+ _ => "bad_answer",
+ }
+}
+
+fn io_kind(e: &std::io::Error) -> &'static str {
+ use std::io::ErrorKind as K;
+ match e.kind() {
+ K::ConnectionRefused | K::ConnectionReset | K::ConnectionAborted | K::BrokenPipe => {
+ "refused"
+ }
+ K::TimedOut => "timeout",
+ _ if e.to_string().contains("lookup") => "name",
+ _ => "refused",
+ }
+}
+
+/// The roots an `https://` upstream is checked against: the system bundle (`SSL_CERT_FILE`,
+/// else the usual Debian/NixOS path), read once.
+fn system_roots() -> Arc {
+ static ROOTS: std::sync::OnceLock> = std::sync::OnceLock::new();
+ ROOTS
+ .get_or_init(|| {
+ let mut store = rustls::RootCertStore::empty();
+ let path = std::env::var("SSL_CERT_FILE")
+ .unwrap_or_else(|_| "/etc/ssl/certs/ca-certificates.crt".into());
+ if let Ok(pem) = std::fs::read_to_string(path) {
+ for der in ianitor_core::pki::chain_der(&pem).unwrap_or_default() {
+ let _ = store.add(rustls_pki_types::CertificateDer::from(der));
+ }
+ }
+ Arc::new(store)
+ })
+ .clone()
+}
+
+pub async fn probe_upstream(
+ u: &ianitor_core::Upstream,
+ path: &str,
+ host_header: &str,
+ watch_only: bool,
+) -> UpstreamProbe {
+ use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt};
+ let started = Instant::now();
+ let fail = |kind: &'static str| UpstreamProbe {
+ ok: false,
+ kind: Some(kind),
+ status: None,
+ latency_ms: None,
+ };
+ async fn ask(
+ mut s: S,
+ req: &[u8],
+ ) -> Result, std::io::Error> {
+ s.write_all(req).await?;
+ let mut head = [0u8; 64];
+ let mut n = 0;
+ while n < 13 {
+ let k = s.read(&mut head[n..]).await?;
+ if k == 0 {
+ break;
+ }
+ n += k;
+ }
+ Ok(String::from_utf8_lossy(&head[..n])
+ .split(' ')
+ .nth(1)
+ .and_then(|x| x.parse::().ok()))
+ }
+ let req = format!(
+ "GET {path} HTTP/1.1\r\nHost: {host_header}\r\nUser-Agent: ianitor-health\r\nConnection: close\r\n\r\n"
+ );
+ let run = async {
+ let tcp = match tokio::net::TcpStream::connect(u.authority()).await {
+ Ok(t) => t,
+ Err(e) => return Err(io_kind(&e)),
+ };
+ if u.scheme == ianitor_core::Scheme::Https {
+ let provider = Arc::new(rustls::crypto::ring::default_provider());
+ let Ok(b) = rustls::ClientConfig::builder_with_provider(provider)
+ .with_safe_default_protocol_versions()
+ else {
+ return Err("tls");
+ };
+ let cfg = b
+ .with_root_certificates(system_roots())
+ .with_no_client_auth();
+ let Ok(name) = rustls_pki_types::ServerName::try_from(u.host_str()) else {
+ return Err("name");
+ };
+ let tls = match tokio_rustls::TlsConnector::from(Arc::new(cfg))
+ .connect(name, tcp)
+ .await
+ {
+ Ok(t) => t,
+ Err(_) => return Err("tls"),
+ };
+ ask(tls, req.as_bytes()).await.map_err(|e| io_kind(&e))
+ } else {
+ ask(tcp, req.as_bytes()).await.map_err(|e| io_kind(&e))
+ }
+ };
+ match tokio::time::timeout(Duration::from_secs(5), run).await {
+ Err(_) => fail("timeout"),
+ Ok(Err(kind)) => fail(kind),
+ Ok(Ok(None)) => fail("bad_answer"),
+ Ok(Ok(Some(status))) => {
+ let latency = u64::try_from(started.elapsed().as_millis()).unwrap_or(u64::MAX);
+ let ok = if watch_only {
+ (100..500).contains(&status)
+ } else {
+ (200..300).contains(&status)
+ };
+ UpstreamProbe {
+ ok,
+ kind: (!ok).then(|| status_kind(status)),
+ status: Some(status),
+ latency_ms: Some(latency),
+ }
+ }
+ }
+}
diff --git a/crates/control/src/config.rs b/crates/control/src/config.rs
index a35e23a..ac2736e 100644
--- a/crates/control/src/config.rs
+++ b/crates/control/src/config.rs
@@ -48,6 +48,16 @@ pub struct Config {
pub compile: Compile,
/// Different facts for the Caddy output (only tests need this: both engines side by side).
pub compile_caddy: Option,
+ /// The Domi CA; without it `tls = "domi"` certificates are expected in `cert_dir` already
+ /// and the certificate screens say the CA is not set up.
+ #[serde(default)]
+ pub pki: Option,
+ /// The web UI behind edge (sign-in through Authelia, see docs/api.md).
+ #[serde(default)]
+ pub ui: Option,
+ /// Switching between Pingora and the Caddy fallback at runtime.
+ #[serde(default)]
+ pub engine: Option,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
@@ -100,6 +110,12 @@ pub struct Compile {
pub access_log: String,
pub caddy_credentials_dir: String,
pub caddy_admin: Option,
+ /// Caddy's admin API on a Unix socket: how control loads a change while Caddy serves.
+ #[serde(default)]
+ pub caddy_admin_socket: Option,
+ /// Proxies in front whose X-Forwarded-For is believed (e.g. ["127.0.0.1"] beside Caddy).
+ #[serde(default)]
+ pub trusted_proxies: Vec,
}
impl Compile {
@@ -112,6 +128,8 @@ impl Compile {
access_log: self.access_log.clone(),
caddy_credentials_dir: self.caddy_credentials_dir.clone(),
caddy_admin: self.caddy_admin,
+ caddy_admin_socket: self.caddy_admin_socket.clone(),
+ trusted_proxies: self.trusted_proxies.clone(),
}
}
}
@@ -213,6 +231,15 @@ impl Config {
"routes.push_credential must be a plain credential name".into(),
));
}
+ // The keys at rest are only as strong as this; only test builds may lower it.
+ if let Some(p) = &self.pki
+ && p.kdf_iterations < MIN_KDF_ITERATIONS
+ && !cfg!(feature = "test-hooks")
+ {
+ return Err(ConfigError::Invalid(format!(
+ "pki.kdf_iterations must be at least {MIN_KDF_ITERATIONS}"
+ )));
+ }
if let Some(m) = empty_model() {
for c in std::iter::once(&self.compile).chain(self.compile_caddy.as_ref()) {
ianitor_core::compile::edge(&m, &c.options())
@@ -280,3 +307,79 @@ fn empty_model() -> Option {
)
.ok()
}
+
+/// The PBKDF2 floor for keys at rest (OWASP 2023 for PBKDF2-HMAC-SHA256).
+pub const MIN_KDF_ITERATIONS: u32 = 600_000;
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(deny_unknown_fields)]
+pub struct PkiConfig {
+ /// The Domi root certificate (public; may be a Nix store path). The root key is never on
+ /// the server.
+ pub root_cert: PathBuf,
+ /// Credential with the password that encrypts the intermediate and device keys at rest.
+ #[serde(default = "default_pki_password")]
+ pub password_credential: String,
+ /// How requests are approved: `manual` (`ianitor-control pki approve ` on the
+ /// server) until Custos can (docs/custos-ticket.md).
+ #[serde(default = "default_approval")]
+ pub approval: String,
+ /// PBKDF2 iterations for the keys control encrypts (only tests lower it).
+ #[serde(default = "default_kdf")]
+ pub kdf_iterations: u32,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(deny_unknown_fields)]
+pub struct UiConfig {
+ /// The admin host edge serves the UI on (a host in the routes repository with
+ /// `auth = "forward-auth"`, upstream this API, and the proof header rule). Added to
+ /// `allowed_hosts`; used for device install links.
+ pub hostname: Option,
+ /// Credential holding the per-boot secret edge adds as `X-Ianitor-Proof` on the admin
+ /// host. With it, a request carrying the proof is identified by its `Remote-User`.
+ pub proof_credential: Option,
+ /// The built web UI (served at `/`).
+ pub static_dir: Option,
+ /// Authelia's logout address (e.g. `https://auth.example/logout`), shown as "Sign out".
+ #[serde(default)]
+ pub logout_url: Option,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(deny_unknown_fields)]
+pub struct EngineConfig {
+ /// Which engine runs at boot: `pingora` or `caddy` (read by the engine-select unit).
+ pub file: PathBuf,
+ /// `systemctl` (through the polkit rule for exactly the two units) or `none`.
+ #[serde(default = "default_units")]
+ pub units: String,
+ #[serde(default = "default_systemctl")]
+ pub systemctl: PathBuf,
+ #[serde(default = "default_edge_unit")]
+ pub edge_unit: String,
+ #[serde(default = "default_caddy_unit")]
+ pub caddy_unit: String,
+}
+
+fn default_pki_password() -> String {
+ "pki-password".into()
+}
+fn default_approval() -> String {
+ "manual".into()
+}
+fn default_kdf() -> u32 {
+ ianitor_core::pki::KEY_KDF_ITERATIONS
+}
+fn default_units() -> String {
+ "systemctl".into()
+}
+fn default_systemctl() -> PathBuf {
+ PathBuf::from("systemctl")
+}
+fn default_edge_unit() -> String {
+ "ianitor-edge.service".into()
+}
+fn default_caddy_unit() -> String {
+ "caddy-fallback.service".into()
+}
diff --git a/crates/control/src/crash.rs b/crates/control/src/crash.rs
index b85bbe4..22870d7 100644
--- a/crates/control/src/crash.rs
+++ b/crates/control/src/crash.rs
@@ -3,11 +3,17 @@
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
//! Crash points for the crash-safety tests: with `IANITOR_TEST_CRASH_AT=` in its
-//! environment, control aborts (no cleanup, like a kill -9) when an apply reaches that stage.
-//! Without the variable this does nothing; the NixOS unit never sets it.
+//! environment, control exits at once with status 134 (no cleanup in Ianitor's code, like a
+//! kill -9) when an apply reaches that stage. It does not raise SIGABRT: a signal would make
+//! the kernel log a register dump per crash test and could hand the process to the host's
+//! core-dump handler, and the tests must not reach into the host's systemd.
//!
//! `IANITOR_TEST_FAIL_WRITE=` makes every write of a state file with that name
//! fail, as on a full disk (fault injection for the same tests).
+//!
+//! Both exist only with the `test-hooks` cargo feature (on by default, so `cargo test` has
+//! them). The release build (`nix build .#ianitor`) is built with `--no-default-features`:
+//! there these functions do nothing and read no environment variable.
/// The stages, in order.
pub const STAGES: [&str; 9] = [
@@ -22,14 +28,23 @@ pub const STAGES: [&str; 9] = [
"reverting",
];
+/// Whether this binary has the test hooks.
+pub const ENABLED: bool = cfg!(feature = "test-hooks");
+
+#[cfg(feature = "test-hooks")]
pub fn point(stage: &str) {
if std::env::var("IANITOR_TEST_CRASH_AT").as_deref() == Ok(stage) {
- log::error!(target: "ianitor::crash", "IANITOR_TEST_CRASH_AT={stage}: aborting on purpose");
- std::process::abort();
+ log::error!(target: "ianitor::crash", "IANITOR_TEST_CRASH_AT={stage}: exiting on purpose");
+ std::process::exit(134);
}
}
+#[cfg(not(feature = "test-hooks"))]
+#[inline(always)]
+pub fn point(_stage: &str) {}
+
/// Fail a state-file write when `IANITOR_TEST_FAIL_WRITE` names this file.
+#[cfg(feature = "test-hooks")]
pub fn fail_write(path: &std::path::Path) -> Result<(), String> {
match (
std::env::var_os("IANITOR_TEST_FAIL_WRITE"),
@@ -42,3 +57,9 @@ pub fn fail_write(path: &std::path::Path) -> Result<(), String> {
_ => Ok(()),
}
}
+
+#[cfg(not(feature = "test-hooks"))]
+#[inline(always)]
+pub fn fail_write(_path: &std::path::Path) -> Result<(), String> {
+ Ok(())
+}
diff --git a/crates/control/src/dev.rs b/crates/control/src/dev.rs
index 70930e6..2b59ad6 100644
--- a/crates/control/src/dev.rs
+++ b/crates/control/src/dev.rs
@@ -18,42 +18,17 @@ use ianitor_control::repo::Repo;
use ianitor_control::tokens::Tokens;
use ianitor_control::util::{hex, random, write_atomic};
-/// Hosts that get a certificate from the dev CA, so `tls = "domi"` works for them.
-const DEV_HOSTS: [&str; 3] = ["app.dev.test", "wiki.dev.test", "photos.dev.test"];
-
-/// A throw-away CA and certificates for [`DEV_HOSTS`] in `certs/`; the CA as `dev-ca.crt`.
-fn dev_certs(dir: &Path) -> Result<(), String> {
- use rcgen::{
- BasicConstraints, CertificateParams, DnType, IsCa, Issuer, KeyPair, KeyUsagePurpose,
- };
- let e = |x: rcgen::Error| x.to_string();
- let ca_key = KeyPair::generate().map_err(e)?;
- let mut ca = CertificateParams::new(Vec::::new()).map_err(e)?;
- ca.distinguished_name
- .push(DnType::CommonName, "Ianitor dev CA");
- ca.is_ca = IsCa::Ca(BasicConstraints::Constrained(0));
- ca.key_usages = vec![
- KeyUsagePurpose::KeyCertSign,
- KeyUsagePurpose::DigitalSignature,
- ];
- let ca_cert = ca.self_signed(&ca_key).map_err(e)?;
- std::fs::write(dir.join("certs/dev-ca.crt"), ca_cert.pem()).map_err(|x| x.to_string())?;
- let issuer = Issuer::new(ca, ca_key);
- for h in DEV_HOSTS {
- let key = KeyPair::generate().map_err(e)?;
- let mut p = CertificateParams::new(vec![h.to_owned()]).map_err(e)?;
- p.distinguished_name.push(DnType::CommonName, h);
- let cert = p.signed_by(&key, &issuer).map_err(e)?;
- std::fs::write(dir.join(format!("certs/{h}.crt")), cert.pem())
- .map_err(|x| x.to_string())?;
- write_atomic(
- &dir.join(format!("certs/{h}.key")),
- key.serialize_pem().as_bytes(),
- 0o600,
- )
- .map_err(|x| x.to_string())?;
- }
- Ok(())
+/// A throw-away Domi root for dev mode, in `offline-root/` (its key stays in memory, like
+/// on the offline machine), and the PKI password credential. Control then works like
+/// production: it issues server certificates for every `tls = "domi"` host.
+fn dev_pki(dir: &Path) -> Result<(String, ianitor_core::pki::KeyPair), String> {
+ let (root, key) = ianitor_core::pki::create_root(ianitor_control::util::now() as i64)
+ .map_err(|e| e.to_string())?;
+ std::fs::write(dir.join("offline-root/domi-root.crt"), &root).map_err(|e| e.to_string())?;
+ let pass = hex(&random::<24>().map_err(|e| e.to_string())?);
+ write_atomic(&dir.join("creds/pki-password"), pass.as_bytes(), 0o600)
+ .map_err(|e| e.to_string())?;
+ Ok((root, key))
}
const SITE: &str = "# Dev site settings. Sign-in goes to an Authelia that may not run here.\n\
@@ -125,10 +100,11 @@ pub async fn run(args: &[String]) -> Result<(), String> {
"creds",
"logs",
"edge-state",
+ "offline-root",
] {
std::fs::create_dir_all(dir.join(d)).map_err(|e| e.to_string())?;
}
- dev_certs(&dir)?;
+ let (root_pem, root_key) = dev_pki(&dir)?;
let key = hex(&random::<32>().map_err(|e| e.to_string())?);
write_atomic(&dir.join("creds/share-link-key"), key.as_bytes(), 0o600)
.map_err(|e| e.to_string())?;
@@ -172,8 +148,28 @@ pub async fn run(args: &[String]) -> Result<(), String> {
access_log: s("logs/access.log"),
caddy_credentials_dir: s("creds"),
caddy_admin: None,
+ caddy_admin_socket: None,
+ trusted_proxies: Vec::new(),
},
compile_caddy: None,
+ pki: Some(ianitor_control::config::PkiConfig {
+ root_cert: dir.join("offline-root/domi-root.crt"),
+ password_credential: "pki-password".into(),
+ approval: "manual".into(),
+ // Fast in test builds; the real floor in a release build.
+ kdf_iterations: if cfg!(feature = "test-hooks") {
+ 10_000
+ } else {
+ ianitor_control::config::MIN_KDF_ITERATIONS
+ },
+ }),
+ ui: arg(args, "--ui-dir").map(|d| ianitor_control::config::UiConfig {
+ hostname: None,
+ proof_credential: None,
+ static_dir: Some(PathBuf::from(d)),
+ logout_url: None,
+ }),
+ engine: None,
};
cfg.check().map_err(|e| e.to_string())?;
Repo::open_seeded(&cfg.git, &cfg.routes.repo, &cfg.state_dir, "main", SITE)
@@ -183,6 +179,21 @@ pub async fn run(args: &[String]) -> Result<(), String> {
// Control writes edge.json first; then edge can start from it.
let ctl_cfg = cfg.clone();
let opened = ianitor_control::Control::open(ctl_cfg).await?;
+ // Dev only: sign the first intermediate with the throw-away root at once (in production
+ // this is the offline step in docs/pki.md).
+ if let Some(p) = &opened.pki {
+ let now = ianitor_control::util::now();
+ let r = p.request_renewal(now, "dev").map_err(|e| e.to_string())?;
+ let signed = ianitor_core::pki::sign_intermediate(
+ &root_pem,
+ &root_key,
+ r.csr_pem.as_deref().unwrap_or_default(),
+ now as i64,
+ )
+ .map_err(|e| e.to_string())?;
+ p.install_intermediate(&r.id, &signed, now)
+ .map_err(|e| e.to_string())?;
+ }
drop(opened);
if let Some(bin) = &edge_bin {
cleanup.edge = Some(start_edge(bin, &dir, &cfg)?);
@@ -192,16 +203,19 @@ pub async fn run(args: &[String]) -> Result<(), String> {
println!("Routes repository: {}", cfg.routes.repo.display());
match &edge_bin {
Some(b) => println!(
- "Dev proxy: {} on https://127.0.0.1:18443 (HTTP 18080). tls = \"domi\" works for {}; CA: {}",
+ "Dev proxy: {} on https://127.0.0.1:18443 (HTTP 18080). tls = \"domi\" works for any name; Domi root: {}",
b.display(),
- DEV_HOSTS.join(", "),
- dir.join("certs/dev-ca.crt").display()
+ dir.join("offline-root/domi-root.crt").display()
),
None => println!(
"No ianitor-edge found: applies are written but not loaded or watched (use --edge-bin)."
),
}
println!("API token (shown once): {token}");
+ println!(
+ "Approve a device request: ianitor-control pki approve --state-dir {}",
+ dir.join("state").display()
+ );
println!("Press Ctrl-C to stop and remove {}", dir.display());
let r = ianitor_control::serve(cfg, ianitor_control::stop_signal()).await;
drop(cleanup);
diff --git a/crates/control/src/edgelink.rs b/crates/control/src/edgelink.rs
index 5485e57..045e1f7 100644
--- a/crates/control/src/edgelink.rs
+++ b/crates/control/src/edgelink.rs
@@ -174,6 +174,13 @@ impl EdgeLink {
Ok(v["config_sha256"].as_str().unwrap_or_default().to_owned())
}
+ /// Re-read the device CA bundle and allow list (works during a trial too).
+ pub async fn reload_devices(&self) -> Result<(), EdgeLinkError> {
+ self.call("POST", "/v1/device-certs/reload", None)
+ .await
+ .map(|_| ())
+ }
+
pub async fn reload_revocations(&self) -> Result<(), EdgeLinkError> {
self.call("POST", "/v1/share-revocations/reload", None)
.await
diff --git a/crates/control/src/engine.rs b/crates/control/src/engine.rs
index 19ccbeb..e49bf61 100644
--- a/crates/control/src/engine.rs
+++ b/crates/control/src/engine.rs
@@ -15,6 +15,8 @@
// A refusal is built once per failed request or apply; boxing it buys nothing.
#![allow(clippy::result_large_err)]
+mod caddy_apply;
+
use std::collections::{BTreeMap, BTreeSet, HashMap, VecDeque};
use std::sync::{Arc, Mutex};
use std::time::Duration;
@@ -141,6 +143,14 @@ pub struct Control {
pub tokens: Tokens,
pub shares: Shares,
pub share_key: Option,
+ /// The Domi CA, when `[pki]` is configured.
+ pub pki: Option,
+ /// The per-boot secret edge adds on the admin host (`X-Ianitor-Proof`), from `[ui]`.
+ pub ui_proof: Option>,
+ /// Which engine serves (see `switch`).
+ pub engine: Mutex,
+ /// How control starts and stops the engines; `None` without `[engine]`.
+ pub units: Option>,
records: Mutex>,
queue: Mutex>,
wake: Notify,
@@ -151,7 +161,14 @@ pub struct Control {
/// False while the pause is only in memory (paused.json could not be written).
pause_saved: std::sync::atomic::AtomicBool,
/// Serialises applies with share-revocation writes and recovery.
- apply_lock: tokio::sync::Mutex<()>,
+ pub(crate) apply_lock: tokio::sync::Mutex<()>,
+ /// Held while an engine is switched or told to reload its device or certificate files.
+ pub(crate) engine_lock: tokio::sync::Mutex<()>,
+ /// Serialises reading the device records and writing the device files (never held
+ /// across an apply or a switch).
+ pub(crate) devices_lock: tokio::sync::Mutex<()>,
+ /// Why the device files are not (yet) in force, until a retry succeeds.
+ pub devices_problem: Mutex>,
}
const MAX_RECORDS: usize = 1000;
@@ -207,6 +224,21 @@ impl Control {
if share_key.is_none() {
log::warn!(target: "ianitor::control", "no usable share-link-key credential: share links cannot be made");
}
+ let keys = crate::pki::root_key_files(&cfg.state_dir);
+ if let Some(k) = keys.first() {
+ return Err(format!(
+ "{} looks like a root CA key inside the state directory; the Domi root key must never be on the server (ROADMAP §1.2). Move it to the offline machine.",
+ k.display()
+ ));
+ }
+ let pki = match &cfg.pki {
+ Some(p) => Some(crate::pki::Pki::open(
+ p,
+ &cfg.state_dir,
+ cfg.credential(&p.password_credential),
+ )?),
+ None => None,
+ };
let records: Vec =
read_json(&cfg.state_dir.join("applies.json"))?.unwrap_or_default();
let push: PushState = read_json(&cfg.state_dir.join("push.json"))?.unwrap_or_default();
@@ -217,6 +249,25 @@ impl Control {
repo,
edge,
share_key,
+ ui_proof: cfg
+ .ui
+ .as_ref()
+ .and_then(|u| u.proof_credential.as_deref())
+ .and_then(|n| cfg.credential(n))
+ .filter(|p| p.len() >= 32),
+ pki,
+ engine: Mutex::new(crate::switch::EngineState {
+ running: cfg
+ .engine
+ .as_ref()
+ .map(|e| crate::switch::read_engine_file(&e.file))
+ .unwrap_or_else(|| "pingora".into()),
+ state: "running".into(),
+ since: now(),
+ target: None,
+ last_error: None,
+ }),
+ units: crate::switch::units_for(cfg.engine.as_ref()),
records: Mutex::new(records),
queue: Mutex::new(VecDeque::new()),
wake: Notify::new(),
@@ -226,8 +277,16 @@ impl Control {
paused: Mutex::new(paused),
pause_saved: std::sync::atomic::AtomicBool::new(true),
apply_lock: tokio::sync::Mutex::new(()),
+ engine_lock: tokio::sync::Mutex::new(()),
+ devices_lock: tokio::sync::Mutex::new(()),
+ devices_problem: Mutex::new(None),
cfg,
});
+ if let Ok((_, _, m)) = c.head_model()
+ && let Err(f) = c.pki_prepare(&m)
+ {
+ log::error!(target: "ianitor::pki", "{}", f.reason.message);
+ }
c.recover().await?;
Ok(c)
}
@@ -619,6 +678,31 @@ impl Control {
errors: fe,
}
})?;
+ // The UI proof belongs to the [ui] host only (core already demands forward-auth for it).
+ let ui_host = self.cfg.ui.as_ref().and_then(|u| u.hostname.as_deref());
+ for h in model.hosts() {
+ let proof = h.request_headers.iter().any(|r| {
+ matches!(r, ianitor_core::HeaderRule::Set { value: ianitor_core::HeaderValue::Secret(s), .. } if s.as_str() == ianitor_core::UI_PROOF_SECRET)
+ });
+ if proof && ui_host != Some(h.hostname.as_str()) {
+ let p = messages::params([("hostname", h.hostname.to_string())]);
+ let fe = FieldError {
+ code: "host.header.proof_host".into(),
+ message: message("host.header.proof_host", &p),
+ field: Some("request_headers".into()),
+ params: p.clone(),
+ detail: None,
+ };
+ return Err(Fail {
+ status: 422,
+ reason: reason(
+ "apply.failed.validation",
+ messages::params([("first_error", fe.message.clone())]),
+ ),
+ errors: vec![fe],
+ });
+ }
+ }
Ok(Plan {
kind,
verb: host_verb(kind),
@@ -863,6 +947,11 @@ impl Control {
Ok(x) => x,
Err(f) => return self.finish(&id, "failed", Some(f.reason), Vec::new()),
};
+ // Domi certificates for the hosts of the new tree, before anything is committed (new
+ // files only: a certificate edge serves now is never replaced by a worse one).
+ if let Err(f) = self.pki_prepare(&plan.model) {
+ return self.finish(&id, "failed", Some(f.reason), Vec::new());
+ }
self.update(&id, |r| {
r.step("compile", "done");
r.step("write", "running");
@@ -969,6 +1058,13 @@ impl Control {
r.step("reload", "running");
});
+ // Caddy serves: load the trial into Caddy and watch through it (Mark, 2026-11-08).
+ if self.engine_running() == "caddy" {
+ return self
+ .run_under_caddy(&id, j, &plan, &caddy_text, &job.change)
+ .await;
+ }
+
// Which hosts to judge: those this change adds or changes, not those it removes.
let watch_hosts: Vec = plan
.hosts
@@ -1411,7 +1507,8 @@ impl Control {
/// The idempotent part of a revert. Returns the revert commit, if one was needed.
async fn finish_revert(&self, j: &Journal) -> Result, String> {
- if self.edge.attached() {
+ let caddy = self.engine_running() == "caddy";
+ if self.edge.attached() && !caddy {
match self.edge.abort().await {
Ok(_) => {}
// Edge down: it starts from edge.json, which is still the last good config.
@@ -1447,6 +1544,15 @@ impl Control {
for p in [self.cfg.trial_path(), self.cfg.caddy_trial_path()] {
remove_if_exists(&p).map_err(|e| e.to_string())?;
}
+ if caddy {
+ // Caddy must run caddy.json again, the last good config (with the device files as
+ // they are now); then no trial is out any more. Under the engine lock, so a device
+ // change that saw the trial and left the reload to this point is not lost.
+ let _engine = self.engine_lock.lock().await;
+ self.caddy_reload().await?;
+ crate::caddy_guard::disarm(&self.cfg.state_dir);
+ return Ok(rev);
+ }
// Edge must now run edge.json, the last good config. If it confirmed the trial after
// all (an answer lost on the way) it does not: reload it. If edge cannot be asked,
// this is not a finished revert (a restart asks again).
@@ -1605,6 +1711,16 @@ impl Control {
self.unpause();
self.sync_files().await;
}
+ if self.engine_running() == "caddy" {
+ match self.caddy_reload().await {
+ Ok(()) => crate::caddy_guard::disarm(&self.cfg.state_dir),
+ Err(e) => {
+ log::warn!(target: "ianitor::control", "Caddy did not load caddy.json at start: {e}")
+ }
+ }
+ } else {
+ crate::caddy_guard::disarm(&self.cfg.state_dir);
+ }
if let Err(e) = self.shares.ensure_revocation_file() {
log::error!(target: "ianitor::share", "{e}");
}
diff --git a/crates/control/src/engine/caddy_apply.rs b/crates/control/src/engine/caddy_apply.rs
new file mode 100644
index 0000000..9b61bee
--- /dev/null
+++ b/crates/control/src/engine/caddy_apply.rs
@@ -0,0 +1,466 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at https://mozilla.org/MPL/2.0/.
+
+//! Applies while Caddy serves (Mark, 2026-11-08: changes keep working under Caddy). The same
+//! pipeline and journal as with edge; only the trial, the watch and the revert differ:
+//!
+//! - the trial is loaded into Caddy through its admin socket, after its deadline is armed
+//! (crate::caddy_guard: a crashed or hung control cannot leave it serving);
+//! - the watch judges health the way edge does (QC round 2, M1): control probes the upstreams
+//! itself with edge's rules, and the probe *through* Caddy only asks whether Caddy answers
+//! at all (any status counts, also its auth redirect, 401, 403 or 421);
+//! - every round checks that Caddy still runs the trial (M2: a reload by anyone else drops it);
+//! - a revert loads caddy.json (the last good config) again; a confirm claims the deadline,
+//! then promotes, loads caddy.json and checks that Caddy runs it.
+
+use std::net::SocketAddr;
+
+use super::*;
+use crate::caddy_guard;
+use crate::caddy_link::{self, Probe};
+
+/// Where control reaches Caddy's HTTPS listener (its own machine).
+fn local(addr: SocketAddr) -> SocketAddr {
+ if addr.ip().is_unspecified() {
+ let ip: std::net::IpAddr = if addr.is_ipv6() {
+ std::net::Ipv6Addr::LOCALHOST.into()
+ } else {
+ std::net::Ipv4Addr::LOCALHOST.into()
+ };
+ SocketAddr::new(ip, addr.port())
+ } else {
+ addr
+ }
+}
+
+/// How one host is probed (edge's rules, crates/edge/src/health.rs).
+struct Rule {
+ upstreams: Vec,
+ path: String,
+ has_check: bool,
+}
+
+impl Control {
+ /// Caddy's admin socket, from `[compile_caddy]` (or `[compile]`).
+ pub fn caddy_socket(&self) -> Option {
+ self.cfg
+ .caddy_compile()
+ .caddy_admin_socket
+ .as_ref()
+ .map(std::path::PathBuf::from)
+ }
+
+ /// Load caddy.json (the last good config) into the running Caddy, even when it is the
+ /// config Caddy already runs (so it reads its files again), and check that it runs it.
+ pub async fn caddy_reload(&self) -> Result<(), String> {
+ let sock = self
+ .caddy_socket()
+ .ok_or("no caddy_admin_socket is configured, so Caddy cannot be told")?;
+ let text = std::fs::read(&self.cfg.caddy.config)
+ .map_err(|e| format!("cannot read {}: {e}", self.cfg.caddy.config.display()))?;
+ caddy_link::load(&sock, &text).await?;
+ if !caddy_link::runs(&sock, &text).await? {
+ return Err("Caddy took the config but does not run it".into());
+ }
+ Ok(())
+ }
+
+ /// `caddy_reload`, then the backstop for certificate and device changes: Caddy must serve
+ /// the certificate that is on disk now for a Domi host (it proves the files were read).
+ pub async fn caddy_reload_checked(&self) -> Result<(), String> {
+ self.caddy_reload().await?;
+ let Ok((_, _, model)) = self.head_model() else {
+ return Ok(());
+ };
+ let Some(h) = model
+ .hosts()
+ .iter()
+ .find(|h| h.tls == ianitor_core::TlsMode::Domi)
+ else {
+ return Ok(());
+ };
+ let file = std::path::Path::new(&self.cfg.caddy_compile().cert_dir)
+ .join(format!("{}.crt", h.hostname));
+ let want = std::fs::read_to_string(&file)
+ .ok()
+ .and_then(|pem| ianitor_core::pki::chain_der(&pem).ok())
+ .and_then(|c| c.into_iter().next())
+ .map(|der| crate::util::sha256_hex(&der))
+ .ok_or_else(|| format!("cannot read {}", file.display()))?;
+ let addr = local(self.cfg.caddy_compile().https_listen);
+ let got = caddy_link::served_cert_sha256(addr, h.hostname.as_str()).await?;
+ if got != want {
+ return Err(format!(
+ "Caddy still serves an older certificate for {} after the reload",
+ h.hostname
+ ));
+ }
+ Ok(())
+ }
+
+ fn caddy_rules(&self, plan: &Plan) -> BTreeMap {
+ plan.model
+ .hosts()
+ .iter()
+ .map(|h| {
+ (
+ h.hostname.to_string(),
+ Rule {
+ upstreams: h.upstreams.clone(),
+ path: h
+ .health_check
+ .as_ref()
+ .map_or("/".to_owned(), |c| c.path.clone()),
+ has_check: h.health_check.is_some(),
+ },
+ )
+ })
+ .collect()
+ }
+
+ /// One round of edge-style upstream probes for one host; `(address, probe)` per upstream.
+ async fn probe_host(hostname: &str, r: &Rule) -> Vec<(String, caddy_link::UpstreamProbe)> {
+ let mut out = Vec::new();
+ for u in &r.upstreams {
+ let host_header = if r.has_check {
+ u.authority()
+ } else {
+ hostname.to_owned()
+ };
+ let p = caddy_link::probe_upstream(u, &r.path, &host_header, !r.has_check).await;
+ out.push((u.authority(), p));
+ }
+ out
+ }
+
+ pub(super) async fn run_under_caddy(
+ &self,
+ id: &str,
+ mut j: Journal,
+ plan: &Plan,
+ caddy_text: &str,
+ change: &Change,
+ ) {
+ let fail = |code: &str, detail: String| {
+ let mut r = reason(code, messages::params([("engine", "Caddy".into())]));
+ r.detail = Some(detail);
+ r
+ };
+ let Some(sock) = self.caddy_socket() else {
+ let r = fail(
+ "apply.failed.reload",
+ "no caddy_admin_socket is configured".into(),
+ );
+ return self.revert(id, &j, r, "failed").await;
+ };
+ let watch_hosts: Vec = plan
+ .hosts
+ .iter()
+ .filter(|h| plan.target.host(h).is_some())
+ .cloned()
+ .collect();
+ let addr = local(self.cfg.caddy_compile().https_listen);
+ let rules = self.caddy_rules(plan);
+ // A host whose upstreams already failed before the change is no reason to revert
+ // (edge: `down_hosts`). Judged by the upstreams, as edge does.
+ let existed: BTreeSet = self
+ .repo
+ .tree(&j.base)
+ .map(|t| {
+ watch_hosts
+ .iter()
+ .filter(|h| t.host(h).is_some())
+ .cloned()
+ .collect()
+ })
+ .unwrap_or_default();
+ let mut was_down = BTreeSet::new();
+ for h in &existed {
+ if let Some(r) = rules.get(h)
+ && !Self::probe_host(h, r).await.iter().any(|(_, p)| p.ok)
+ {
+ was_down.insert(h.clone());
+ }
+ }
+
+ let window = self.cfg.watch_secs;
+ // The deadline goes out before the trial does (crate::caddy_guard).
+ let deadline = now() + window + self.cfg.trial_margin_secs + 5;
+ // Under the engine lock: a device change that looked a moment ago saw no trial and
+ // reloads caddy.json; it must not land after the trial is in.
+ let loaded = {
+ let _engine = self.engine_lock.lock().await;
+ match caddy_guard::arm(&self.cfg.state_dir, id, deadline) {
+ Err(e) => {
+ let mut r = reason("internal", Params::new());
+ r.detail = Some(e);
+ Err((r, "failed"))
+ }
+ Ok(()) => caddy_link::load(&sock, caddy_text.as_bytes())
+ .await
+ .map_err(|e| (fail("apply.failed.reload", e), "failed")),
+ }
+ };
+ if let Err((r, state)) = loaded {
+ return self.revert(id, &j, r, state).await;
+ }
+ j.stage = "trial_loaded".into();
+ if let Err(e) = self.journal(&j) {
+ let mut r = reason("internal", Params::new());
+ r.detail = Some(e);
+ return self.revert(id, &j, r, "failed").await;
+ }
+ crash::point("trial_loaded");
+ self.update(id, |r| r.step("reload", "done"));
+
+ let judged: Vec = watch_hosts
+ .iter()
+ .filter(|h| !was_down.contains(*h))
+ .cloned()
+ .collect();
+ let mut kept_reason = if watch_hosts.is_empty() {
+ reason(
+ "apply.kept.removed",
+ messages::params([("hostname", plan.hosts.join(", "))]),
+ )
+ } else {
+ reason(
+ "apply.kept",
+ messages::params([
+ ("hostname", watch_hosts.join(", ")),
+ ("seconds", window.to_string()),
+ ]),
+ )
+ };
+ let ends = now() + window;
+ if judged.is_empty() {
+ self.update(id, |r| r.step("watch", "skipped"));
+ } else {
+ self.update(id, |r| {
+ r.state = "watching".into();
+ r.step("watch", "running");
+ r.watch = Some(Watch {
+ ends,
+ hosts: judged
+ .iter()
+ .map(|h| WatchHost {
+ hostname: h.clone(),
+ ..Default::default()
+ })
+ .collect(),
+ });
+ });
+ }
+ if let Err(r) = self
+ .caddy_watch(id, &sock, caddy_text, &judged, &rules, plan, addr, ends)
+ .await
+ {
+ return self.revert(id, &j, r, "reverted").await;
+ }
+ if !judged.is_empty() {
+ let no_check: Vec = judged
+ .iter()
+ .filter(|h| rules.get(*h).is_some_and(|r| !r.has_check))
+ .cloned()
+ .collect();
+ if !no_check.is_empty() && no_check.len() == judged.len() {
+ kept_reason = reason(
+ "apply.kept.no_watch",
+ messages::params([("hostname", no_check.join(", "))]),
+ );
+ }
+ self.update(id, |r| r.step("watch", "done"));
+ }
+ crash::point("watched");
+ // Confirmed first, then the deadline is claimed (fix round 3): a crash in between
+ // leaves the deadline armed *and* the journal confirmed, so the guard and caddy-revert
+ // leave the trial alone and recovery promotes it. The other order would leave a window
+ // with nothing armed and nothing confirmed, where nobody reverts Caddy.
+ j.stage = "confirmed".into();
+ if let Err(e) = self.journal(&j) {
+ let mut r = reason("internal", Params::new());
+ r.detail = Some(e);
+ return self.revert(id, &j, r, "failed").await;
+ }
+ crash::point("confirmed");
+ // From the claim to Caddy running the promoted caddy.json, no device reload may load
+ // the old caddy.json in between.
+ let engine = self.engine_lock.lock().await;
+ // The guard may have reverted a trial that ran past its deadline (a stalled control):
+ // then this change is not kept.
+ if !caddy_guard::claim(&self.cfg.state_dir) {
+ drop(engine);
+ let mut r = reason("apply.interrupted", Params::new());
+ r.detail = Some(
+ "the trial ran past its deadline, so Caddy went back to the last good config"
+ .into(),
+ );
+ return self.revert(id, &j, r, "reverted").await;
+ }
+ if let Err(e) = self.promote() {
+ drop(engine);
+ log::error!(target: "ianitor::apply", "cannot write the config files: {e}");
+ let mut p = reason("control.files_unwritten", Params::new());
+ p.detail = Some(e.to_string());
+ p.params.insert("apply_id".into(), id.to_owned());
+ if let Err(pe) = self.pause(p) {
+ log::error!(target: "ianitor::apply", "cannot save the pause ({pe}); the journal keeps it");
+ }
+ let push_step = self.push_step();
+ self.update(id, |r| r.step("push", push_step));
+ self.finish(id, "kept", Some(kept_reason), Vec::new());
+ return;
+ }
+ crash::point("promoted");
+ // caddy.json now holds the change: Caddy loads what was written (with the device and
+ // certificate files as they are now) and must run it.
+ if let Err(e) = self.caddy_reload().await {
+ log::error!(target: "ianitor::apply", "Caddy did not load the promoted caddy.json: {e}");
+ }
+ drop(engine);
+ let push_step = self.push_step();
+ self.update(id, |r| r.step("push", push_step));
+ self.finish(id, "kept", Some(kept_reason), Vec::new());
+ self.clear_journal();
+ if self.paused().is_some() && matches!(change, Change::Restore { .. }) {
+ self.unpause();
+ }
+ self.push_wake.notify_one();
+ }
+
+ /// The watch under Caddy until `ends`: the reason to revert, if any.
+ #[allow(clippy::too_many_arguments)]
+ async fn caddy_watch(
+ &self,
+ id: &str,
+ sock: &std::path::Path,
+ trial: &str,
+ judged: &[String],
+ rules: &BTreeMap,
+ plan: &Plan,
+ addr: SocketAddr,
+ ends: u64,
+ ) -> Result<(), Reason> {
+ let mut seen: HashMap<(String, String), BTreeMap> = HashMap::new();
+ let mut seq = 0u64;
+ let mut silent: BTreeMap = BTreeMap::new();
+ let paths: HashMap = rules
+ .iter()
+ .map(|(h, r)| (h.clone(), r.path.clone()))
+ .collect();
+ let mut first = true;
+ loop {
+ // Anyone else's reload (a device change, a restart of caddy-fallback) drops the
+ // trial: then this is not a verdict on the change.
+ match caddy_link::runs(sock, trial.as_bytes()).await {
+ Ok(true) => {}
+ Ok(false) => {
+ let mut r = reason("apply.reverted.edge_lost", Params::new());
+ r.detail = Some("Caddy no longer runs the trial config".into());
+ return Err(r);
+ }
+ Err(e) => {
+ let mut r = reason("apply.reverted.edge_lost", Params::new());
+ r.detail = Some(e);
+ return Err(r);
+ }
+ }
+ if first {
+ crash::point("watching");
+ first = false;
+ }
+ let mut counts = Vec::new();
+ for h in judged {
+ let Some(rule) = rules.get(h) else { continue };
+ // Does Caddy answer for this host at all? Any status does.
+ match caddy_link::probe(addr, h, "/").await {
+ Probe::Status(_) => {
+ silent.remove(h);
+ }
+ Probe::NoAnswer(e) => {
+ let s = silent.entry(h.clone()).or_insert((0, String::new()));
+ s.0 += 1;
+ s.1 = e;
+ }
+ }
+ if let Some((n, e)) = silent.get(h)
+ && *n >= 3
+ {
+ let mut r = reason(
+ "apply.reverted.no_answer",
+ messages::params([
+ ("hostname", h.clone()),
+ ("verb", plan.verb.into()),
+ ("seconds", self.cfg.watch_secs.to_string()),
+ ]),
+ );
+ r.hostname = Some(h.clone());
+ r.detail = Some(format!("Caddy does not answer for {h}: {e}"));
+ return Err(r);
+ }
+ for (address, p) in Self::probe_host(h, rule).await {
+ seq += 1;
+ seen.entry((h.clone(), address)).or_default().insert(
+ seq,
+ Check {
+ seq,
+ at: now(),
+ ok: p.ok,
+ source: if rule.has_check {
+ "health_check".into()
+ } else {
+ "watch".into()
+ },
+ kind: p.kind.map(str::to_owned),
+ status: p.status,
+ latency_ms: p.latency_ms,
+ },
+ );
+ }
+ let mut passed = 0u32;
+ let mut failed = 0u32;
+ let mut all_failing = !rule.upstreams.is_empty();
+ for ((host, _), m) in &seen {
+ if host != h {
+ continue;
+ }
+ passed += m.values().filter(|c| c.ok).count() as u32;
+ failed += m.values().filter(|c| !c.ok).count() as u32;
+ if m.values().rev().take_while(|c| !c.ok).count() < 3 {
+ all_failing = false;
+ }
+ }
+ counts.push(WatchHost {
+ hostname: h.clone(),
+ passed,
+ failed,
+ total: passed + failed,
+ });
+ if all_failing {
+ return Err(self.revert_reason(h, plan, &seen, &paths));
+ }
+ }
+ self.update(id, |r| {
+ if let Some(w) = &mut r.watch {
+ w.hosts = counts;
+ }
+ });
+ if now() >= ends {
+ break;
+ }
+ tokio::time::sleep(Duration::from_secs(self.cfg.watch_every_secs)).await;
+ }
+ // At the end, as with edge: every judged host needs an upstream whose last probe passed.
+ for h in judged {
+ let last_ok = seen
+ .iter()
+ .filter(|((host, _), _)| host == h)
+ .any(|(_, m)| m.values().next_back().is_some_and(|c| c.ok));
+ if !last_ok {
+ return Err(self.revert_reason(h, plan, &seen, &paths));
+ }
+ }
+ Ok(())
+ }
+}
diff --git a/crates/control/src/hostspec.rs b/crates/control/src/hostspec.rs
index 538a72c..2b7e8ec 100644
--- a/crates/control/src/hostspec.rs
+++ b/crates/control/src/hostspec.rs
@@ -26,6 +26,9 @@ pub struct HostSpec {
pub websockets: bool,
#[serde(default)]
pub share_links: bool,
+ /// Visitors need a Domi device certificate (mTLS).
+ #[serde(default, skip_serializing_if = "std::ops::Not::not")]
+ pub device_certs: bool,
/// `off` or `truncated`.
#[serde(default = "off")]
pub access_log: String,
@@ -115,6 +118,11 @@ impl HostSpec {
to.share_links.to_string(),
);
push("access_log", self.access_log.clone(), to.access_log.clone());
+ push(
+ "device_certs",
+ self.device_certs.to_string(),
+ to.device_certs.to_string(),
+ );
let hc =
|h: &Option| h.as_ref().map(|h| (h.path.clone(), h.interval_secs));
let (a, b) = (hc(&self.health_check), hc(&to.health_check));
@@ -157,6 +165,7 @@ mod tests {
auth: "none".into(),
websockets: false,
share_links: true,
+ device_certs: true,
access_log: "truncated".into(),
health_check: Some(HealthCheckSpec {
path: "/health".into(),
diff --git a/crates/control/src/lib.rs b/crates/control/src/lib.rs
index 683a167..65d3279 100644
--- a/crates/control/src/lib.rs
+++ b/crates/control/src/lib.rs
@@ -7,6 +7,8 @@
//! edge keeps serving the last good config.
pub mod api;
+pub mod caddy_guard;
+pub mod caddy_link;
pub mod config;
pub mod crash;
pub mod edgelink;
@@ -14,9 +16,12 @@ pub mod engine;
pub mod hostspec;
pub mod logger;
pub mod messages;
+pub mod pki;
+pub mod pki_ctl;
pub mod records;
pub mod repo;
pub mod shares;
+pub mod switch;
pub mod tokens;
pub mod util;
@@ -36,6 +41,7 @@ pub async fn serve(
tokio::spawn(ctl.clone().worker());
tokio::spawn(ctl.clone().health_poller());
tokio::spawn(ctl.clone().pusher());
+ tokio::spawn(ctl.clone().pki_poller());
let app = api::router(api::AppState::new(ctl.clone()));
if !listen.ip().is_loopback() {
return Err("ianitor-control only listens on loopback".into());
diff --git a/crates/control/src/main.rs b/crates/control/src/main.rs
index 063e2b3..a5fc768 100644
--- a/crates/control/src/main.rs
+++ b/crates/control/src/main.rs
@@ -9,6 +9,11 @@
//! ianitor-control token list (--config | --state-dir )
//! ianitor-control token revoke (--config | --state-dir )
//! ianitor-control openapi print the OpenAPI document
+//! ianitor-control pki approve|deny (--config | --state-dir ) approve a device request
+//! ianitor-control pki install (--config ) install a signed intermediate
+//! ianitor-control pki status (--config ) open requests
+//! ianitor-control ca init --out [--passphrase-file ] the offline root (never on the server)
+//! ianitor-control ca sign --root --csr --out [--yes] sign an intermediate offline
//! ianitor-control check --config check the config and exit
//! ```
//! The log level comes from `$IANITOR_LOG`. As `GIT_ASKPASS` (with `$IANITOR_ASKPASS=1`),
@@ -25,7 +30,8 @@ fn usage() -> ExitCode {
eprintln!(
"usage: ianitor-control --config | --dev [--edge-bin ] | \
token create --name [--expires-days | --never] (--config | --state-dir ) | \
- token list (...) | token revoke (...) | openapi | check --config "
+ token list (...) | token revoke (...) | openapi | check --config | \
+ caddy-revert --config | caddy-guard --config "
);
ExitCode::from(2)
}
@@ -197,6 +203,174 @@ fn token(args: &[String]) -> Result<(), String> {
}
}
+fn arg_after(args: &[String], name: &str) -> Option {
+ let mut it = args.iter();
+ while let Some(a) = it.next() {
+ if a == name {
+ return it.next().cloned();
+ }
+ }
+ None
+}
+
+/// A passphrase from `--passphrase-file`, or asked on the terminal without echo.
+fn passphrase(args: &[String], confirm: bool) -> Result {
+ if let Some(f) = arg_after(args, "--passphrase-file") {
+ let v = std::fs::read_to_string(&f).map_err(|e| format!("cannot read {f}: {e}"))?;
+ let v = v.trim_end_matches(['\r', '\n']).to_owned();
+ if v.chars().count() < 12 {
+ return Err("the passphrase must have at least 12 characters".into());
+ }
+ return Ok(v);
+ }
+ let p = rpassword::prompt_password("Root key passphrase: ").map_err(|e| e.to_string())?;
+ if p.chars().count() < 12 {
+ return Err("the passphrase must have at least 12 characters".into());
+ }
+ if confirm {
+ let again = rpassword::prompt_password("Again: ").map_err(|e| e.to_string())?;
+ if again != p {
+ return Err("the two passphrases differ".into());
+ }
+ }
+ Ok(p)
+}
+
+/// `ca init` and `ca sign`: the offline root (ROADMAP §1.2; docs/pki.md). Never run on the
+/// server.
+fn ca(args: &[String]) -> Result<(), String> {
+ use ianitor_core::pki;
+ let now = ianitor_control::util::now() as i64;
+ match args.first().map(String::as_str) {
+ Some("init") => {
+ let out = PathBuf::from(arg_after(args, "--out").ok_or("ca init --out ")?);
+ let crt = out.join("domi-root.crt");
+ let key = out.join("domi-root.key");
+ if crt.exists() || key.exists() {
+ return Err(format!(
+ "{} already has a root; refusing to replace it",
+ out.display()
+ ));
+ }
+ std::fs::create_dir_all(&out).map_err(|e| e.to_string())?;
+ let pass = passphrase(args, true)?;
+ let (cert, k) = pki::create_root(now).map_err(|e| e.to_string())?;
+ let sealed = pki::encrypt_key(&k, pass.as_bytes()).map_err(|e| e.to_string())?;
+ ianitor_control::util::write_atomic(&key, sealed.as_bytes(), 0o600)
+ .map_err(|e| e.to_string())?;
+ ianitor_control::util::write_atomic(&crt, cert.as_bytes(), 0o644)
+ .map_err(|e| e.to_string())?;
+ let info = pki::inspect(&cert).map_err(|e| e.to_string())?;
+ eprintln!(
+ "Domi root created in {}: {} (valid until {}).\nSHA-256 {}\n\
+ Copy domi-root.crt to the server's configuration (services.ianitor.pki.rootCertificate).\n\
+ Keep domi-root.key and its passphrase offline (Custos, once it can hold it).",
+ out.display(),
+ info.subject_cn,
+ ianitor_core::time::long_date(info.not_after.max(0) as u64),
+ info.sha256_hex
+ );
+ Ok(())
+ }
+ Some("sign") => {
+ let root = PathBuf::from(
+ arg_after(args, "--root")
+ .ok_or("ca sign --root --csr --out ")?,
+ );
+ let csr_path = arg_after(args, "--csr").ok_or("--csr is required")?;
+ let out = PathBuf::from(arg_after(args, "--out").ok_or("--out is required")?);
+ let csr = std::fs::read_to_string(&csr_path)
+ .map_err(|e| format!("cannot read {csr_path}: {e}"))?;
+ let code = pki::match_code(&pki::csr_der(&csr).map_err(|e| e.to_string())?);
+ eprintln!("This request's code is {code}. It must be the code Ianitor shows.");
+ if !args.iter().any(|a| a == "--yes") {
+ let typed = rpassword::prompt_password("Type the code to sign (no echo): ")
+ .map_err(|e| e.to_string())?;
+ if ianitor_control::pki::normalise_code(&typed)
+ != ianitor_control::pki::normalise_code(&code)
+ {
+ return Err("the code does not match; nothing was signed".into());
+ }
+ }
+ let cert =
+ std::fs::read_to_string(root.join("domi-root.crt")).map_err(|e| e.to_string())?;
+ let sealed =
+ std::fs::read_to_string(root.join("domi-root.key")).map_err(|e| e.to_string())?;
+ let pass = passphrase(args, false)?;
+ let key = pki::decrypt_key(&sealed, pass.as_bytes()).map_err(|e| e.to_string())?;
+ let signed =
+ pki::sign_intermediate(&cert, &key, &csr, now).map_err(|e| e.to_string())?;
+ ianitor_control::util::write_atomic(&out, signed.as_bytes(), 0o644)
+ .map_err(|e| e.to_string())?;
+ let info = pki::inspect(&signed).map_err(|e| e.to_string())?;
+ eprintln!(
+ "Signed {} until {}. Install it on the server: ianitor-control pki install {}",
+ info.subject_cn,
+ ianitor_core::time::long_date(info.not_after.max(0) as u64),
+ out.display()
+ );
+ Ok(())
+ }
+ _ => Err("ca init --out | ca sign --root --csr --out ".into()),
+ }
+}
+
+/// `pki approve|deny|install|status` on the server, as the user control runs as.
+fn pki_cli(args: &[String]) -> Result<(), String> {
+ let dir = state_dir(args)?;
+ same_owner(&dir)?;
+ let now = ianitor_control::util::now();
+ match args.first().map(String::as_str) {
+ Some(verb @ ("approve" | "deny")) => {
+ // The code may be given as one word or three (47 19 83).
+ let code: String = args
+ .iter()
+ .skip(1)
+ .take_while(|a| !a.starts_with("--"))
+ .cloned()
+ .collect::>()
+ .join("");
+ let r = ianitor_control::pki::cli_approve(&dir, &code, verb == "deny", now)?;
+ let name = r.name.clone().unwrap_or_default();
+ eprintln!("Handed to control; waiting for it ...");
+ let state = ianitor_control::pki::cli_wait(&dir, &r.id, now)
+ .map_err(|e| format!("not done for \"{name}\" ({}): {e}", r.id))?;
+ eprintln!(
+ "{} the request for \"{name}\" ({}).",
+ if state == "approved" { "Approved" } else { "Turned down" },
+ r.id
+ );
+ Ok(())
+ }
+ Some("install") => {
+ let f = args.get(1).filter(|a| !a.starts_with("--")).ok_or("pki install ")?;
+ let pem = std::fs::read_to_string(f).map_err(|e| format!("cannot read {f}: {e}"))?;
+ let r = ianitor_control::pki::cli_install(&dir, &pem, now)?;
+ eprintln!("Handed to renewal {}; waiting for control to install it ...", r.id);
+ ianitor_control::pki::cli_wait(&dir, &r.id, now)
+ .map_err(|e| format!("not installed: {e}"))?;
+ eprintln!("Installed. Server certificates are reissued from it now.");
+ Ok(())
+ }
+ Some("status") => {
+ let rs: Vec =
+ ianitor_control::util::read_json(&ianitor_control::pki::requests_path(&dir))?.unwrap_or_default();
+ for r in rs.iter().filter(|r| r.state == "waiting" && r.expires_at > now) {
+ println!(
+ "{} {} {} code {} until {}",
+ r.id,
+ r.kind,
+ r.name.clone().unwrap_or_default(),
+ r.match_code,
+ ianitor_control::util::rfc3339(r.expires_at)
+ );
+ }
+ Ok(())
+ }
+ _ => Err("pki approve | pki deny | pki install | pki status (--config | --state-dir )".into()),
+ }
+}
+
fn main() -> ExitCode {
if std::env::var("IANITOR_ASKPASS").as_deref() == Ok("1") {
return askpass();
@@ -215,11 +389,34 @@ fn main() -> ExitCode {
};
let result = match args.first().map(String::as_str) {
Some("token") => token(&args[1..]),
+ Some("pki") => pki_cli(&args[1..]),
+ Some("ca") => ca(&args[1..]),
Some("openapi") => {
println!("{}", ianitor_control::api::openapi_json());
Ok(())
}
Some("check") => state_dir(&args[1..]).map(|_| eprintln!("config is valid")),
+ // Caddy trial deadline (ianitor_control::caddy_guard): after control stops, and the guard.
+ Some(verb @ ("caddy-revert" | "caddy-guard")) => match args
+ .iter()
+ .position(|a| a == "--config")
+ .and_then(|i| args.get(i + 1))
+ {
+ Some(p) => match Config::load(&PathBuf::from(p)) {
+ Ok(cfg) if verb == "caddy-guard" => {
+ rt.block_on(ianitor_control::caddy_guard::run(cfg))
+ }
+ Ok(cfg) => rt
+ .block_on(ianitor_control::caddy_guard::revert_after_stop(&cfg))
+ .map(|done| {
+ if done {
+ eprintln!("Caddy is back on the last good config.");
+ }
+ }),
+ Err(e) => Err(e.to_string()),
+ },
+ None => return usage(),
+ },
Some("--dev") => rt.block_on(dev::run(&args[1..])),
Some("--config") => match args.get(1) {
Some(p) => match Config::load(&PathBuf::from(p)) {
diff --git a/crates/control/src/messages.rs b/crates/control/src/messages.rs
index 945f222..fe01126 100644
--- a/crates/control/src/messages.rs
+++ b/crates/control/src/messages.rs
@@ -228,6 +228,131 @@ fn template(code: &str) -> &'static str {
"health.unavailable" => {
"Ianitor cannot read health from {engine} right now. Traffic is not affected."
}
+ // 3.6 PKI
+ "pki.waiting" => {
+ "Open Custos on your phone. Approve only if it shows the same code: {code}."
+ }
+ "pki.waiting.manual" => {
+ "Approve it on the server: run ianitor-control pki approve {code}. Approve only if the code matches."
+ }
+ "pki.renew.manual" => {
+ "Sign this request on the offline computer and check that its fingerprint matches (Sign by hand shows both), then install the certificate."
+ }
+ "pki.denied" => "The request was turned down. Nothing was issued.",
+ "pki.expired" => "Nobody approved it in time, so the request closed. Nothing was issued.",
+ "pki.custos_unreachable" => "Custos is not answering, so the request could not be sent.",
+ "pki.device_name_taken" => {
+ "A device with this name already has a certificate or an open request. Use another name, or revoke the old one first."
+ }
+ "pki.device_name" => "Give the device a name of 1 to 64 characters.",
+ "pki.device_kind" => "Choose phone, computer or app.",
+ "pki.issued" => "{name} has a certificate.",
+ "pki.bundle_used" => {
+ "This download was already used or has expired. Make a new one from the device's row."
+ }
+ "pki.renew_due" => "The Domi intermediate certificate expires in {days} days, on {date}.",
+ "pki.renew_urgent" => {
+ "The Domi intermediate certificate expires in {days} days. After that, Domi certificates stop working."
+ }
+ "pki.intermediate_expired" => {
+ "The Domi intermediate certificate has expired. Hosts with a Domi certificate are not trusted until it is renewed."
+ }
+ "pki.renewed" => "Renewed. The Domi intermediate certificate is now valid until {date}.",
+ "pki.not_configured" => {
+ "The Domi certificate authority is not set up on this server. See docs/pki.md."
+ }
+ "pki.no_password" => {
+ "The password for the Domi certificate keys is missing from the server's credentials, so nothing can be issued."
+ }
+ "pki.wrong_password" => {
+ "The password for the Domi certificate keys does not open them. Check the pki-password credential."
+ }
+ "pki.no_intermediate" => {
+ "There is no Domi intermediate certificate yet, so Domi certificates cannot be issued. Set it up first in Certificates."
+ }
+ "pki.not_our_root" => {
+ "This certificate was not signed by the Domi root this server trusts."
+ }
+ "pki.wrong_key" => {
+ "This certificate was made for another request. Sign the request shown here, then try again."
+ }
+ "pki.bad_certificate" => {
+ "This is not a Domi intermediate certificate Ianitor can use. It must be a CA with path length 0 that is valid now."
+ }
+ "pki.request_not_found" => "There is no such request.",
+ "pki.request_closed" => "This request is closed. Start a new one.",
+ "pki.wrong_code" => "That code does not match the request.",
+ "pki.too_many_requests" => "Too many requests are open. Finish or cancel some first.",
+ "pki.device_not_found" => "There is no such device.",
+ "pki.device_not_valid" => {
+ "This device's certificate is revoked or expired, so it cannot be installed. Issue a new one."
+ }
+ "pki.revoked" => {
+ "Revoked. {name} can no longer reach hosts that need a device certificate."
+ }
+ // UI sign-in
+ "ui.no_proof" => {
+ "This request carries a sign-in header but did not come through Ianitor's proxy, so it was refused."
+ }
+ "ui.no_user" => "The sign-in did not say who you are. Sign in again.",
+ // engine switch
+ "engine.unmanaged" => {
+ "This server does not let Ianitor switch engines (no engine settings in control.toml)."
+ }
+ "engine.same" => "{engine} is already serving.",
+ "engine.switching" => "A switch is already running. Wait for it to finish.",
+ "engine.busy" => "A change is being applied. Switch when it has finished.",
+ "engine.switched" => "{engine} is serving now.",
+ "engine.switch_failed" => {
+ "{engine} did not start, so Ianitor went back to {previous}. Traffic is served as before."
+ }
+ "host.header.proof" => {
+ "Only a host behind sign-in can send the ui-proof secret. Choose Sign in first, or remove the rule."
+ }
+ "host.header.proof_host" => {
+ "Only the web UI's admin host can send the ui-proof secret, and {hostname} is not it ([ui] hostname in control.toml)."
+ }
+ "pki.manual.not_ca" => {
+ "This certificate cannot sign other certificates. Sign it again with the signing settings file (.ext)."
+ }
+ "pki.manual.eku" => {
+ "This certificate is limited to some uses, so it could not issue both host and device certificates. Sign it again with the signing settings file (.ext)."
+ }
+ "pki.manual.dates" => {
+ "This certificate is not valid yet, has already expired, or lasts longer than the Domi root. Check the offline computer's clock and use -days 365."
+ }
+ "pki.devices_unwritten" => {
+ "The device list could not be saved or handed to the proxy, so the change is not in force yet. Ianitor keeps trying; try again in a moment."
+ }
+ "engine.not_ready" => {
+ "Caddy is not ready: its settings could not be built from the current routes."
+ }
+ // The eight codes the UI hand-off gave sentences for (handoff §12.2, decision Q12).
+ "repo.duplicate_file" => {
+ "Two files in the routes repository describe {hostname}. Remove one, then Ianitor picks it up."
+ }
+ "file.syntax" => {
+ "{file} in the routes repository has a typing mistake. Changes are paused until it is fixed."
+ }
+ "file.too_large" => {
+ "{file} in the routes repository is too large to read. Changes are paused until it is fixed."
+ }
+ "site.field.unknown" => "ianitor.toml has a setting Ianitor does not know: \"{field}\".",
+ "site.forward_auth" => {
+ "The sign-in settings in ianitor.toml cannot be used. Show details to see why."
+ }
+ "site.forward_auth.header" => {
+ "ianitor.toml asks sign-in to pass on \"{name}\", which cannot be a header name."
+ }
+ "site.secret.name" => {
+ "\"{name}\" cannot be a secret name in ianitor.toml. Use letters, digits, dashes and underscores."
+ }
+ "site.acme" => {
+ "The Let's Encrypt settings in ianitor.toml cannot be used. Show details to see why."
+ }
+ "share.engine_caddy" => {
+ "Share links are paused while Caddy serves. They work again after switching back."
+ }
"internal" => "Something went wrong inside Ianitor control. Show details for more.",
_ => "Something went wrong.",
}
diff --git a/crates/control/src/pki.rs b/crates/control/src/pki.rs
new file mode 100644
index 0000000..1586e3d
--- /dev/null
+++ b/crates/control/src/pki.rs
@@ -0,0 +1,1255 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at https://mozilla.org/MPL/2.0/.
+
+//! The Domi CA on the server (ROADMAP §1.2, §3): the intermediate, the server certificates
+//! of `tls = "domi"` hosts, device certificates and their install files, and the requests
+//! that need an approval.
+//!
+//! Files, under `/pki/` (mode 0700):
+//!
+//! ```text
+//! intermediate.crt the current intermediate (public)
+//! intermediate.key its key, encrypted (IANITOR ENCRYPTED PRIVATE KEY, password from
+//! the `pki-password` credential); never in plain text on disk
+//! previous.crt the one before, while it is still valid (device CA bundle)
+//! pending-.key the new key of an open renewal, encrypted the same way
+//! requests.json approval requests (devices, renewals)
+//! devices.json issued device certificates
+//! devices/