commit bc4eeef0489490ab2ec3b2101089064f2cafeed9 Author: SW Date: Wed Sep 30 22:02:32 2026 +0200 Initial implementation of IP Subnet Allocator diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..b253fa1 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,12 @@ +/target +**/*.rs.bk +.env +.git +.gitignore +README.md +LICENSE +data/ +exports/ +backups/ +*.db +*.db-* diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..ad91918 --- /dev/null +++ b/.env.example @@ -0,0 +1,17 @@ +# Port na hostiteli, na kterém bude aplikace dostupná +APP_PORT=8080 + +# Logování (debug, info, warn, error) +RUST_LOG=info + +# Bind adresy uvnitř kontejneru +APP_BIND=0.0.0.0:8080 + +# Cesta k SQLite databázi uvnitř kontejneru +DATABASE_URL=sqlite:/app/data/subnet-allocator.db + +# Časové pásmo pro zobrazení času ve webovém UI +APP_TIMEZONE=Europe/Prague + +# Adresář pro exporty uvnitř kontejneru +APP_EXPORTS_DIR=/app/exports diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..038e988 --- /dev/null +++ b/.gitignore @@ -0,0 +1,8 @@ +/target +**/*.rs.bk +data/ +exports/ +backups/ +.env +*.db +*.db-* diff --git a/Cargo.lock b/Cargo.lock new file mode 100644 index 0000000..1ed6089 --- /dev/null +++ b/Cargo.lock @@ -0,0 +1,2644 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "aho-corasick" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba" +dependencies = [ + "memchr", +] + +[[package]] +name = "allocator-api2" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923" + +[[package]] +name = "android_system_properties" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae221649c9976a6f6c56ae1facf410f3ddb33cc661c4b7b61020a912d4237fbc" +dependencies = [ + "libc", +] + +[[package]] +name = "anyhow" +version = "1.0.104" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" + +[[package]] +name = "askama" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b79091df18a97caea757e28cd2d5fda49c6cd4bd01ddffd7ff01ace0c0ad2c28" +dependencies = [ + "askama_derive", + "askama_escape", + "humansize", + "num-traits", + "percent-encoding", +] + +[[package]] +name = "askama_derive" +version = "0.12.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "19fe8d6cb13c4714962c072ea496f3392015f0989b1a2847bb4b2d9effd71d83" +dependencies = [ + "askama_parser", + "basic-toml", + "mime", + "mime_guess", + "proc-macro2", + "quote", + "serde", + "syn 2.0.119", +] + +[[package]] +name = "askama_escape" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "619743e34b5ba4e9703bba34deac3427c72507c7159f5fd030aea8cac0cfe341" + +[[package]] +name = "askama_parser" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "acb1161c6b64d1c3d83108213c2a2533a342ac225aabd0bda218278c2ddb00c0" +dependencies = [ + "nom", +] + +[[package]] +name = "atoi" +version = "2.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f28d99ec8bfea296261ca1af174f24225171fea9664ba9003cbebee704810528" +dependencies = [ + "num-traits", +] + +[[package]] +name = "atomic-waker" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" + +[[package]] +name = "autocfg" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" + +[[package]] +name = "axum" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "31b698c5f9a010f6573133b09e0de5408834d0c82f8d7475a89fc1867a71cd90" +dependencies = [ + "axum-core", + "bytes", + "form_urlencoded", + "futures-util", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-util", + "itoa", + "matchit", + "memchr", + "mime", + "percent-encoding", + "pin-project-lite", + "serde_core", + "serde_json", + "serde_path_to_error", + "serde_urlencoded", + "sync_wrapper", + "tokio", + "tower", + "tower-layer", + "tower-service", + "tracing", +] + +[[package]] +name = "axum-core" +version = "0.5.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08c78f31d7b1291f7ee735c1c6780ccde7785daae9a9206026862dab7d8792d1" +dependencies = [ + "bytes", + "futures-core", + "http", + "http-body", + "http-body-util", + "mime", + "pin-project-lite", + "sync_wrapper", + "tower-layer", + "tower-service", + "tracing", +] + +[[package]] +name = "axum-extra" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9963ff19f40c6102c76756ef0a46004c0d58957d87259fc9208ff8441c12ab96" +dependencies = [ + "axum", + "axum-core", + "bytes", + "cookie", + "futures-util", + "http", + "http-body", + "http-body-util", + "mime", + "pin-project-lite", + "rustversion", + "serde_core", + "tower-layer", + "tower-service", + "tracing", +] + +[[package]] +name = "base64" +version = "0.22.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" + +[[package]] +name = "base64ct" +version = "1.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06" + +[[package]] +name = "basic-toml" +version = "0.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba62675e8242a4c4e806d12f11d136e626e6c8361d6b829310732241652a178a" +dependencies = [ + "serde", +] + +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" +dependencies = [ + "serde_core", +] + +[[package]] +name = "block-buffer" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" +dependencies = [ + "generic-array", +] + +[[package]] +name = "bumpalo" +version = "3.20.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649" + +[[package]] +name = "byteorder" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" + +[[package]] +name = "bytes" +version = "1.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" + +[[package]] +name = "cc" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f360145194ee8e21db5ee7f3fcd4fe52210864c75c985dae33218202c8bbe040" +dependencies = [ + "find-msvc-tools", + "shlex", +] + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "chrono" +version = "0.4.45" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1aa79e62e7697b8e29b513a68abacf485adcd1fe8284a4316c5ae868e6633327" +dependencies = [ + "iana-time-zone", + "js-sys", + "num-traits", + "serde", + "wasm-bindgen", + "windows-link", +] + +[[package]] +name = "const-oid" +version = "0.9.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2459377285ad874054d797f3ccebf984978aa39129f6eafde5cdc8315b612f8" + +[[package]] +name = "cookie" +version = "0.18.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1a373e3602691c3cdea496d2f0ee5935151e6168fe87739483c463db1b2f2f87" +dependencies = [ + "percent-encoding", + "time", + "version_check", +] + +[[package]] +name = "core-foundation-sys" +version = "0.8.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" + +[[package]] +name = "cpufeatures" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" +dependencies = [ + "libc", +] + +[[package]] +name = "crc" +version = "3.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5eb8a2a1cd12ab0d987a5d5e825195d372001a4094a0376319d5a0ad71c1ba0d" +dependencies = [ + "crc-catalog", +] + +[[package]] +name = "crc-catalog" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "217698eaf96b4a3f0bc4f3662aaa55bdf913cd54d7204591faa790070c6d0853" + +[[package]] +name = "crossbeam-queue" +version = "0.3.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "03e8bd762f7479489c70ed6c768ddca99d7296857de437a68dcb2a94365b3fae" +dependencies = [ + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-utils" +version = "0.8.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6" + +[[package]] +name = "crypto-common" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" +dependencies = [ + "generic-array", + "typenum", +] + +[[package]] +name = "csv" +version = "1.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52cd9d68cf7efc6ddfaaee42e7288d3a99d613d4b50f76ce9827ae0c6e14f938" +dependencies = [ + "csv-core", + "itoa", + "ryu", + "serde_core", +] + +[[package]] +name = "csv-core" +version = "0.1.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "704a3c26996a80471189265814dbc2c257598b96b8a7feae2d31ace646bb9782" +dependencies = [ + "memchr", +] + +[[package]] +name = "der" +version = "0.7.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7c1832837b905bbfb5101e07cc24c8deddf52f93225eee6ead5f4d63d53ddcb" +dependencies = [ + "const-oid", + "pem-rfc7468", + "zeroize", +] + +[[package]] +name = "deranged" +version = "0.5.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7cd812cc2bc1d69d4764bd80df88b4317eaef9e773c75226407d9bc0876b211c" + +[[package]] +name = "digest" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" +dependencies = [ + "block-buffer", + "const-oid", + "crypto-common", + "subtle", +] + +[[package]] +name = "displaydoc" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.6", +] + +[[package]] +name = "dotenvy" +version = "0.15.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1aaf95b3e5c8f23aa320147307562d361db0ae0d51242340f558153b4eb2439b" + +[[package]] +name = "either" +version = "1.18.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "252afb9ae5eaa683babdc6a068b3f5726eb19e05070c731f9b2a23a7c3e8ed34" +dependencies = [ + "serde", +] + +[[package]] +name = "equivalent" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f" + +[[package]] +name = "errno" +version = "0.3.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "etcetera" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "136d1b5283a1ab77bd9257427ffd09d8667ced0570b6f938942bc7568ed5b943" +dependencies = [ + "cfg-if", + "home", + "windows-sys 0.48.0", +] + +[[package]] +name = "event-listener" +version = "5.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a23add41df1562121a9393cb065eab5146a1242410f23a644851e90cfd669d2" +dependencies = [ + "parking", + "pin-project-lite", +] + +[[package]] +name = "fastrand" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" + +[[package]] +name = "find-msvc-tools" +version = "0.1.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aedcfb3409746eddb02b9e19ebda1c3394f759a152e48ee875a0844d1b955484" + +[[package]] +name = "flume" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da0e4dd2a88388a1f4ccc7c9ce104604dab68d9f408dc34cd45823d5a9069095" +dependencies = [ + "futures-core", + "futures-sink", + "spin", +] + +[[package]] +name = "foldhash" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2" + +[[package]] +name = "form_urlencoded" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf" +dependencies = [ + "percent-encoding", +] + +[[package]] +name = "futures" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a31d2a3fbaaeb2af2368bbdd904aa8e812d3c04a1ee10d3171f52d556e5d0a3" +dependencies = [ + "futures-channel", + "futures-core", + "futures-executor", + "futures-io", + "futures-sink", + "futures-task", + "futures-util", +] + +[[package]] +name = "futures-channel" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1f9e3d69d39e4862ffed03ed071a76f9a13ba1d9109d355b0f0aa6b15e393c4" +dependencies = [ + "futures-core", + "futures-sink", +] + +[[package]] +name = "futures-core" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" + +[[package]] +name = "futures-executor" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "031b47cf1a3c6cc8bc2fc76cd437f521619387907d469316e7c0bc278f1f5432" +dependencies = [ + "futures-core", + "futures-task", + "futures-util", +] + +[[package]] +name = "futures-intrusive" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d930c203dd0b6ff06e0201a4a2fe9149b43c684fd4420555b26d21b1a02956f" +dependencies = [ + "futures-core", + "lock_api", + "parking_lot", +] + +[[package]] +name = "futures-io" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53c0fa8157de1303bfffdaa1cc2a673bfffb60102f76b0ef4441659124373fed" + +[[package]] +name = "futures-macro" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9fb9654ba8355388abeb8dcb4fc62f511300867002afc858860463bdd9fe0c44" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.6", +] + +[[package]] +name = "futures-sink" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1944426bf7d03f1d14f708785e4b33efd750b36d48a157b836b3efc15ede8e1d" + +[[package]] +name = "futures-task" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd" + +[[package]] +name = "futures-util" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" +dependencies = [ + "futures-channel", + "futures-core", + "futures-io", + "futures-macro", + "futures-sink", + "futures-task", + "memchr", + "pin-project-lite", + "slab", +] + +[[package]] +name = "generic-array" +version = "0.14.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" +dependencies = [ + "typenum", + "version_check", +] + +[[package]] +name = "getrandom" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" +dependencies = [ + "cfg-if", + "libc", + "wasi", +] + +[[package]] +name = "getrandom" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" +dependencies = [ + "cfg-if", + "libc", + "r-efi", +] + +[[package]] +name = "hashbrown" +version = "0.15.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1" +dependencies = [ + "allocator-api2", + "equivalent", + "foldhash", +] + +[[package]] +name = "hashbrown" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" + +[[package]] +name = "hashlink" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7382cf6263419f2d8df38c55d7da83da5c18aef87fc7a7fc1fb1e344edfe14c1" +dependencies = [ + "hashbrown 0.15.5", +] + +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + +[[package]] +name = "hex" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" + +[[package]] +name = "hkdf" +version = "0.12.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7b5f8eb2ad728638ea2c7d47a21db23b7b58a72ed6a38256b8a1849f15fbbdf7" +dependencies = [ + "hmac", +] + +[[package]] +name = "hmac" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e" +dependencies = [ + "digest", +] + +[[package]] +name = "home" +version = "0.5.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc627f471c528ff0c4a49e1d5e60450c8f6461dd6d10ba9dcd3a61d3dff7728d" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "http" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0" +dependencies = [ + "bytes", + "itoa", +] + +[[package]] +name = "http-body" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca2a8f2913ee65f60facd6a5905613afaa448497a0230cc41ce022d93290bc2c" +dependencies = [ + "bytes", + "http", +] + +[[package]] +name = "http-body-util" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23169fe34a5fbcdd3f3862e78fb9b6fccd5f02a6dc6f732547005d45631ce71c" +dependencies = [ + "bytes", + "futures-core", + "http", + "http-body", + "pin-project-lite", +] + +[[package]] +name = "http-range-header" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9171a2ea8a68358193d15dd5d70c1c10a2afc3e7e4c5bc92bc9f025cebd7359c" + +[[package]] +name = "httparse" +version = "1.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" + +[[package]] +name = "httpdate" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9" + +[[package]] +name = "humansize" +version = "2.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6cb51c9a029ddc91b07a787f1d86b53ccfa49b0e86688c946ebe8d3555685dd7" +dependencies = [ + "libm", +] + +[[package]] +name = "hyper" +version = "1.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27b501faa50e7a26c3d3560ca625132f4078a17771f4810baf70475ae48cbe43" +dependencies = [ + "atomic-waker", + "bytes", + "futures-channel", + "futures-core", + "http", + "http-body", + "httparse", + "httpdate", + "itoa", + "pin-project-lite", + "smallvec", + "tokio", +] + +[[package]] +name = "hyper-util" +version = "0.1.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ddc03d96684f9226b8a787cdb71488417b53ab5ea8fdb1dac946cb9431cc8bff" +dependencies = [ + "bytes", + "http", + "http-body", + "hyper", + "pin-project-lite", + "tokio", + "tower-service", +] + +[[package]] +name = "iana-time-zone" +version = "0.1.65" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e31bc9ad994ba00e440a8aa5c9ef0ec67d5cb5e5cb0cc7f8b744a35b389cc470" +dependencies = [ + "android_system_properties", + "core-foundation-sys", + "iana-time-zone-haiku", + "js-sys", + "log", + "wasm-bindgen", + "windows-core", +] + +[[package]] +name = "iana-time-zone-haiku" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f" +dependencies = [ + "cc", +] + +[[package]] +name = "icu_collections" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fa68d21081c4a05d5a901a1c62add574c77048b6a1c67be3b50ce0b60d4ca513" +dependencies = [ + "displaydoc", + "potential_utf", + "utf8_iter", + "yoke", + "zerofrom", + "zerovec", +] + +[[package]] +name = "icu_locale_core" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d56e28588da92eee5c3201a6eff33fabdd49b62269c8938d4ff050ce4d900deb" +dependencies = [ + "displaydoc", + "litemap", + "tinystr", + "writeable", + "zerovec", +] + +[[package]] +name = "icu_normalizer" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "12f9cf5f235641ed274641dd81c3f28d870e276763d0797aeeab72317b1c646f" +dependencies = [ + "icu_collections", + "icu_normalizer_data", + "icu_properties", + "icu_provider", + "smallvec", + "zerovec", +] + +[[package]] +name = "icu_normalizer_data" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1563da1ed3e0b3bf3d74c9b85917ac9c56464d2f57242270c09c9e752f8021a0" + +[[package]] +name = "icu_properties" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e7ca276ad3145661a65914e6daf131ca5120cd3dcee8f8f3214b8875184a148" +dependencies = [ + "displaydoc", + "icu_collections", + "icu_locale_core", + "icu_properties_data", + "icu_provider", + "zerotrie", + "zerovec", +] + +[[package]] +name = "icu_properties_data" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e590f038c1464a96894fd6d10127e90a8be4509f56ff7ecef851b15cee0b7caa" + +[[package]] +name = "icu_provider" +version = "2.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d27bbb9d3abbefac45d55f647c9de1d44aafcd1186eb91879afef17c396c3e73" +dependencies = [ + "displaydoc", + "icu_locale_core", + "writeable", + "yoke", + "zerofrom", + "zerotrie", + "zerovec", +] + +[[package]] +name = "idna" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de" +dependencies = [ + "idna_adapter", + "smallvec", + "utf8_iter", +] + +[[package]] +name = "idna_adapter" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714" +dependencies = [ + "icu_normalizer", + "icu_properties", +] + +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown 0.17.1", +] + +[[package]] +name = "ipnet" +version = "2.12.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "791930b43c0d5973160d90a8f3894509f2b273430f5c5c73b668636d0287c5c0" + +[[package]] +name = "itoa" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" + +[[package]] +name = "js-sys" +version = "0.3.106" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7883d941dae510fb2d978fc3fe018c71c9e2892fd38854de3e8b92c2e5ad9cc5" +dependencies = [ + "cfg-if", + "futures-util", + "wasm-bindgen", +] + +[[package]] +name = "lazy_static" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe" +dependencies = [ + "spin", +] + +[[package]] +name = "libc" +version = "0.2.189" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2" + +[[package]] +name = "libm" +version = "0.2.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981" + +[[package]] +name = "libredox" +version = "0.1.25" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "61ff90caf6077a803a240f62fdbe88645a890bbca49ef8174c3cb0404362171d" +dependencies = [ + "bitflags", + "libc", + "plain", + "redox_syscall 0.9.4", +] + +[[package]] +name = "libsqlite3-sys" +version = "0.30.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2e99fb7a497b1e3339bc746195567ed8d3e24945ecd636e3619d20b9de9e9149" +dependencies = [ + "cc", + "pkg-config", + "vcpkg", +] + +[[package]] +name = "linux-raw-sys" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" + +[[package]] +name = "litemap" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae" + +[[package]] +name = "lock_api" +version = "0.4.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965" +dependencies = [ + "scopeguard", +] + +[[package]] +name = "log" +version = "0.4.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6" + +[[package]] +name = "matchers" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d1525a2a28c7f4fa0fc98bb91ae755d1e2d1505079e05539e35bc876b5d65ae9" +dependencies = [ + "regex-automata", +] + +[[package]] +name = "matchit" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47e1ffaa40ddd1f3ed91f717a33c8c0ee23fff369e3aa8772b9605cc1d22f4c3" + +[[package]] +name = "md-5" +version = "0.10.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d89e7ee0cfbedfc4da3340218492196241d89eefb6dab27de5df917a6d2e78cf" +dependencies = [ + "cfg-if", + "digest", +] + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "mime" +version = "0.3.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a" + +[[package]] +name = "mime_guess" +version = "2.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f7c44f8e672c00fe5308fa235f821cb4198414e1c77935c1ab6948d3fd78550e" +dependencies = [ + "mime", + "unicase", +] + +[[package]] +name = "minimal-lexical" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a" + +[[package]] +name = "mio" +version = "1.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4b18443e9c262bfe8fa82f51666e2642c53393f7e5c27b3e1aeab922cff5b9d8" +dependencies = [ + "libc", + "wasi", + "windows-sys 0.61.2", +] + +[[package]] +name = "nom" +version = "7.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d273983c5a657a70a3e8f2a01329822f3b8c8172b73826411a55751e404a0a4a" +dependencies = [ + "memchr", + "minimal-lexical", +] + +[[package]] +name = "nu-ansi-term" +version = "0.50.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "num-bigint-dig" +version = "0.8.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e661dda6640fad38e827a6d4a310ff4763082116fe217f279885c97f511bb0b7" +dependencies = [ + "lazy_static", + "libm", + "num-integer", + "num-iter", + "num-traits", + "rand", + "smallvec", + "zeroize", +] + +[[package]] +name = "num-conv" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441" + +[[package]] +name = "num-integer" +version = "0.1.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7ce2d95d4b3734dc35aa2f45e1aa22cd416814592a4f9d9205e11affd5b8e10b" +dependencies = [ + "num-traits", +] + +[[package]] +name = "num-iter" +version = "0.1.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c92800bd69a1eac91786bcfe9da64a897eb72911b8dc3095decbd07429e8048b" +dependencies = [ + "num-integer", + "num-traits", +] + +[[package]] +name = "num-traits" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" +dependencies = [ + "autocfg", + "libm", +] + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "parking" +version = "2.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f38d5652c16fde515bb1ecef450ab0f6a219d619a7274976324d5e377f7dceba" + +[[package]] +name = "parking_lot" +version = "0.12.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a" +dependencies = [ + "lock_api", + "parking_lot_core", +] + +[[package]] +name = "parking_lot_core" +version = "0.9.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1" +dependencies = [ + "cfg-if", + "libc", + "redox_syscall 0.5.18", + "smallvec", + "windows-link", +] + +[[package]] +name = "pem-rfc7468" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "88b39c9bfcfc231068454382784bb460aae594343fb030d46e9f50a645418412" +dependencies = [ + "base64ct", +] + +[[package]] +name = "percent-encoding" +version = "2.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" + +[[package]] +name = "pin-project-lite" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" + +[[package]] +name = "pkcs1" +version = "0.7.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c8ffb9f10fa047879315e6625af03c164b16962a5368d724ed16323b68ace47f" +dependencies = [ + "der", + "pkcs8", + "spki", +] + +[[package]] +name = "pkcs8" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f950b2377845cebe5cf8b5165cb3cc1a5e0fa5cfa3e1f7f55707d8fd82e0a7b7" +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 = "plain" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b4596b6d070b27117e987119b4dac604f3c58cfb0b191112e24771b2faeac1a6" + +[[package]] +name = "potential_utf" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d83eb9bc6d8e5cf568e7a1101d60ee05e81ed50ea106026f3d18deeb046d7661" +dependencies = [ + "zerovec", +] + +[[package]] +name = "powerfmt" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "439ee305def115ba05938db6eb1644ff94165c5ab5e9420d1c1bcedbba909391" + +[[package]] +name = "ppv-lite86" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9" +dependencies = [ + "zerocopy", +] + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "r-efi" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" + +[[package]] +name = "rand" +version = "0.8.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e058c7de0b26af77780c769414d6257830bb240f3c38477dbc2c16e5f54d6d4c" +dependencies = [ + "libc", + "rand_chacha", + "rand_core", +] + +[[package]] +name = "rand_chacha" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88" +dependencies = [ + "ppv-lite86", + "rand_core", +] + +[[package]] +name = "rand_core" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" +dependencies = [ + "getrandom 0.2.17", +] + +[[package]] +name = "redox_syscall" +version = "0.5.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d" +dependencies = [ + "bitflags", +] + +[[package]] +name = "redox_syscall" +version = "0.9.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "737970939a87c6fa31e7acad13307bccbb017a073b695b6089a2c484f929e20e" +dependencies = [ + "bitflags", +] + +[[package]] +name = "regex-automata" +version = "0.4.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax", +] + +[[package]] +name = "regex-syntax" +version = "0.8.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" + +[[package]] +name = "ring" +version = "0.17.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7" +dependencies = [ + "cc", + "cfg-if", + "getrandom 0.2.17", + "libc", + "untrusted", + "windows-sys 0.52.0", +] + +[[package]] +name = "rsa" +version = "0.9.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8573f03f5883dcaebdfcf4725caa1ecb9c15b2ef50c43a07b816e06799bb12d" +dependencies = [ + "const-oid", + "digest", + "num-bigint-dig", + "num-integer", + "num-traits", + "pkcs1", + "pkcs8", + "rand_core", + "signature", + "spki", + "subtle", + "zeroize", +] + +[[package]] +name = "rustix" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "891efababe418670775f199f0d233d84843c227a0949a883ce15b37c78d6629d" +dependencies = [ + "bitflags", + "errno", + "libc", + "linux-raw-sys", + "windows-sys 0.61.2", +] + +[[package]] +name = "rustls" +version = "0.23.45" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d41d731c7d2f962d1ccc364cec258de3c0e93b38c2fb3ba97ac74513048d634" +dependencies = [ + "once_cell", + "ring", + "rustls-pki-types", + "rustls-webpki", + "subtle", + "zeroize", +] + +[[package]] +name = "rustls-pki-types" +version = "1.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f4925028c7eb5d1fcdaf196971378ed9d2c1c4efc7dc5d011256f76c99c0a96" +dependencies = [ + "zeroize", +] + +[[package]] +name = "rustls-webpki" +version = "0.103.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f3c3cf1d8b1e7d4927e2d154c3fcb02979afb9939629c62cd9048d4f07b60ac2" +dependencies = [ + "ring", + "rustls-pki-types", + "untrusted", +] + +[[package]] +name = "rustversion" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" + +[[package]] +name = "ryu" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" + +[[package]] +name = "scopeguard" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.6", +] + +[[package]] +name = "serde_json" +version = "1.0.151" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c841b55ecdae098c80dcae9cf767f6f8a0c2cdb3416bbef72181df4d0fe73f14" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "serde_path_to_error" +version = "0.1.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10a9ff822e371bb5403e391ecd83e182e0e77ba7f6fe0160b795797109d1b457" +dependencies = [ + "itoa", + "serde", + "serde_core", +] + +[[package]] +name = "serde_urlencoded" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd" +dependencies = [ + "form_urlencoded", + "itoa", + "ryu", + "serde", +] + +[[package]] +name = "sha1" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a978451301f4db1d02937a4ab3ccce137717b81826e79b7d49ffe3244a13c3b8" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest", +] + +[[package]] +name = "sha2" +version = "0.10.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest", +] + +[[package]] +name = "sharded-slab" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f40ca3c46823713e0d4209592e8d6e826aa57e928f09752619fc696c499637f6" +dependencies = [ + "lazy_static", +] + +[[package]] +name = "shlex" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" + +[[package]] +name = "signal-hook-registry" +version = "1.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b" +dependencies = [ + "errno", + "libc", +] + +[[package]] +name = "signature" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77549399552de45a898a580c1b41d445bf730df867cc44e6c0233bbc4b8329de" +dependencies = [ + "digest", + "rand_core", +] + +[[package]] +name = "slab" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" + +[[package]] +name = "smallvec" +version = "1.16.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9395f0f0eee849a9b707b2f06bb92a6a422090e2123bb2ef8e87a0e61892a8e" +dependencies = [ + "serde", +] + +[[package]] +name = "socket2" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "spin" +version = "0.9.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3763264f6b73151db08c50ff20d7d8a0b8796e021cdea7ceedad07b80155fa0e" +dependencies = [ + "lock_api", +] + +[[package]] +name = "spki" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d91ed6c858b01f942cd56b37a94b3e0a1798290327d1236e4d9cf4eaca44d29d" +dependencies = [ + "base64ct", + "der", +] + +[[package]] +name = "sqlx" +version = "0.8.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fefb893899429669dcdd979aff487bd78f4064e5e7907e4269081e0ef7d97dc" +dependencies = [ + "sqlx-core", + "sqlx-macros", + "sqlx-mysql", + "sqlx-postgres", + "sqlx-sqlite", +] + +[[package]] +name = "sqlx-core" +version = "0.8.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee6798b1838b6a0f69c007c133b8df5866302197e404e8b6ee8ed3e3a5e68dc6" +dependencies = [ + "base64", + "bytes", + "chrono", + "crc", + "crossbeam-queue", + "either", + "event-listener", + "futures-core", + "futures-intrusive", + "futures-io", + "futures-util", + "hashbrown 0.15.5", + "hashlink", + "indexmap", + "log", + "memchr", + "once_cell", + "percent-encoding", + "rustls", + "serde", + "serde_json", + "sha2", + "smallvec", + "thiserror", + "tokio", + "tokio-stream", + "tracing", + "url", + "webpki-roots 0.26.11", +] + +[[package]] +name = "sqlx-macros" +version = "0.8.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2d452988ccaacfbf5e0bdbc348fb91d7c8af5bee192173ac3636b5fb6e6715d" +dependencies = [ + "proc-macro2", + "quote", + "sqlx-core", + "sqlx-macros-core", + "syn 2.0.119", +] + +[[package]] +name = "sqlx-macros-core" +version = "0.8.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "19a9c1841124ac5a61741f96e1d9e2ec77424bf323962dd894bdb93f37d5219b" +dependencies = [ + "dotenvy", + "either", + "heck", + "hex", + "once_cell", + "proc-macro2", + "quote", + "serde", + "serde_json", + "sha2", + "sqlx-core", + "sqlx-mysql", + "sqlx-postgres", + "sqlx-sqlite", + "syn 2.0.119", + "tokio", + "url", +] + +[[package]] +name = "sqlx-mysql" +version = "0.8.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aa003f0038df784eb8fecbbac13affe3da23b45194bd57dba231c8f48199c526" +dependencies = [ + "atoi", + "base64", + "bitflags", + "byteorder", + "bytes", + "chrono", + "crc", + "digest", + "dotenvy", + "either", + "futures-channel", + "futures-core", + "futures-io", + "futures-util", + "generic-array", + "hex", + "hkdf", + "hmac", + "itoa", + "log", + "md-5", + "memchr", + "once_cell", + "percent-encoding", + "rand", + "rsa", + "serde", + "sha1", + "sha2", + "smallvec", + "sqlx-core", + "stringprep", + "thiserror", + "tracing", + "whoami", +] + +[[package]] +name = "sqlx-postgres" +version = "0.8.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db58fcd5a53cf07c184b154801ff91347e4c30d17a3562a635ff028ad5deda46" +dependencies = [ + "atoi", + "base64", + "bitflags", + "byteorder", + "chrono", + "crc", + "dotenvy", + "etcetera", + "futures-channel", + "futures-core", + "futures-util", + "hex", + "hkdf", + "hmac", + "home", + "itoa", + "log", + "md-5", + "memchr", + "once_cell", + "rand", + "serde", + "serde_json", + "sha2", + "smallvec", + "sqlx-core", + "stringprep", + "thiserror", + "tracing", + "whoami", +] + +[[package]] +name = "sqlx-sqlite" +version = "0.8.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2d12fe70b2c1b4401038055f90f151b78208de1f9f89a7dbfd41587a10c3eea" +dependencies = [ + "atoi", + "chrono", + "flume", + "futures-channel", + "futures-core", + "futures-executor", + "futures-intrusive", + "futures-util", + "libsqlite3-sys", + "log", + "percent-encoding", + "serde", + "serde_urlencoded", + "sqlx-core", + "thiserror", + "tracing", + "url", +] + +[[package]] +name = "stable_deref_trait" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" + +[[package]] +name = "stringprep" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7b4df3d392d81bd458a8a621b8bffbd2302a12ffe288a9d931670948749463b1" +dependencies = [ + "unicode-bidi", + "unicode-normalization", + "unicode-properties", +] + +[[package]] +name = "sub-aligator" +version = "0.1.0" +dependencies = [ + "anyhow", + "askama", + "axum", + "axum-extra", + "chrono", + "csv", + "futures", + "ipnet", + "rand", + "serde", + "serde_json", + "sqlx", + "tempfile", + "thiserror", + "tokio", + "tokio-test", + "tower", + "tower-http", + "tracing", + "tracing-subscriber", +] + +[[package]] +name = "subtle" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" + +[[package]] +name = "syn" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "3.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8593e8e72159ed2257d083c7a454a85cbf854f37a0966d8d483aff8c8a3ebcee" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "sync_wrapper" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263" + +[[package]] +name = "synstructure" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "901704edd0dfe137f1987838ee4f259e4e063c31371bdb423f7ae38ec6f77f02" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.6", +] + +[[package]] +name = "tempfile" +version = "3.27.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" +dependencies = [ + "fastrand", + "getrandom 0.4.3", + "once_cell", + "rustix", + "windows-sys 0.61.2", +] + +[[package]] +name = "thiserror" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e" +dependencies = [ + "thiserror-impl", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.6", +] + +[[package]] +name = "thread_local" +version = "1.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ad99c4c6d32803332c548b1af0540b357b3f5fc0be8f6c6bfe8b2e6ae784070" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "time" +version = "0.3.55" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cdb87b95ec50ddfa440816d227a17b2ccbdda963a316a727fda0fc4334f7d134" +dependencies = [ + "deranged", + "num-conv", + "powerfmt", + "serde_core", + "time-core", + "time-macros", +] + +[[package]] +name = "time-core" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e1c906769ad99c88eaa54e728060edef082f8e358ff32030cb7c7d315e81109" + +[[package]] +name = "time-macros" +version = "0.2.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e689342a48d2ea927c87ea50cabf8594854bf940e9310208848d680d668ed85" +dependencies = [ + "num-conv", + "time-core", +] + +[[package]] +name = "tinystr" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1e27c91459209c2986af3dcf603a5a74a4368754ce37414f59acc971167f643" +dependencies = [ + "displaydoc", + "zerovec", +] + +[[package]] +name = "tinyvec" +version = "1.13.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee" + +[[package]] +name = "tokio" +version = "1.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "202caea871b69668250d242070849eb495be178ed697a3e98aebce5bc81a0bed" +dependencies = [ + "bytes", + "libc", + "mio", + "pin-project-lite", + "signal-hook-registry", + "socket2", + "tokio-macros", + "windows-sys 0.61.2", +] + +[[package]] +name = "tokio-macros" +version = "2.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78773a2a397f451582ce068015985c33193cf6dea8b74d2a639fe457b2f07b0e" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.6", +] + +[[package]] +name = "tokio-stream" +version = "0.1.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a3d06f0b082ba57c26b79407372e57cf2a1e28124f78e9479fe80322cf53420b" +dependencies = [ + "futures-core", + "pin-project-lite", + "tokio", +] + +[[package]] +name = "tokio-test" +version = "0.4.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "12bc5db7778a8e08ee255090861e0e7aac55e784300077e7ed293c7be36168b2" +dependencies = [ + "futures-core", + "tokio", + "tokio-stream", +] + +[[package]] +name = "tokio-util" +version = "0.7.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "494815d09bf52b5548659851081238f0ca39ff638363907596da739561c62c52" +dependencies = [ + "bytes", + "futures-core", + "futures-sink", + "pin-project-lite", + "tokio", +] + +[[package]] +name = "tower" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebe5ef63511595f1344e2d5cfa636d973292adc0eec1f0ad45fae9f0851ab1d4" +dependencies = [ + "futures-core", + "futures-util", + "pin-project-lite", + "sync_wrapper", + "tokio", + "tower-layer", + "tower-service", + "tracing", +] + +[[package]] +name = "tower-http" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08a05a66a4fdd61cbbe0a1d755ffe0ca6aba159dd4820936a0ff8a8278245b9c" +dependencies = [ + "bitflags", + "bytes", + "futures-core", + "futures-util", + "http", + "http-body", + "http-body-util", + "http-range-header", + "httpdate", + "mime", + "mime_guess", + "percent-encoding", + "pin-project-lite", + "tokio", + "tokio-util", + "tower-layer", + "tower-service", + "tracing", +] + +[[package]] +name = "tower-layer" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "121c2a6cda46980bb0fcd1647ffaf6cd3fc79a013de288782836f6df9c48780e" + +[[package]] +name = "tower-service" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3" + +[[package]] +name = "tracing" +version = "0.1.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" +dependencies = [ + "log", + "pin-project-lite", + "tracing-attributes", + "tracing-core", +] + +[[package]] +name = "tracing-attributes" +version = "0.1.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "tracing-core" +version = "0.1.36" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" +dependencies = [ + "once_cell", + "valuable", +] + +[[package]] +name = "tracing-log" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee855f1f400bd0e5c02d150ae5de3840039a3f54b025156404e34c23c03f47c3" +dependencies = [ + "log", + "once_cell", + "tracing-core", +] + +[[package]] +name = "tracing-subscriber" +version = "0.3.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb7f578e5945fb242538965c2d0b04418d38ec25c79d160cd279bf0731c8d319" +dependencies = [ + "matchers", + "nu-ansi-term", + "once_cell", + "regex-automata", + "sharded-slab", + "smallvec", + "thread_local", + "tracing", + "tracing-core", + "tracing-log", +] + +[[package]] +name = "typenum" +version = "1.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" + +[[package]] +name = "unicase" +version = "2.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dbc4bc3a9f746d862c45cb89d705aa10f187bb96c76001afab07a0d35ce60142" + +[[package]] +name = "unicode-bidi" +version = "0.3.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c1cb5db39152898a79168971543b1cb5020dff7fe43c8dc468b0885f5e29df5" + +[[package]] +name = "unicode-ident" +version = "1.0.26" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d245f478577f809a851594d02313b640fb437e0bb33866753cff937863096954" + +[[package]] +name = "unicode-normalization" +version = "0.1.25" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5fd4f6878c9cb28d874b009da9e8d183b5abc80117c40bbd187a1fde336be6e8" +dependencies = [ + "tinyvec", +] + +[[package]] +name = "unicode-properties" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7df058c713841ad818f1dc5d3fd88063241cc61f49f5fbea4b951e8cf5a8d71d" + +[[package]] +name = "untrusted" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" + +[[package]] +name = "url" +version = "2.5.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed" +dependencies = [ + "form_urlencoded", + "idna", + "percent-encoding", + "serde", +] + +[[package]] +name = "utf8_iter" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be" + +[[package]] +name = "valuable" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba73ea9cf16a25df0c8caa16c51acb937d5712a8429db78a3ee29d5dcacd3a65" + +[[package]] +name = "vcpkg" +version = "0.2.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426" + +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + +[[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + +[[package]] +name = "wasite" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8dad83b4f25e74f184f64c43b150b91efe7647395b42289f38e50566d82855b" + +[[package]] +name = "wasm-bindgen" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9bb54f33acc68fd454578d9820b0bde1a1a3d17aa17bb7b6595806d02886d409" +dependencies = [ + "cfg-if", + "once_cell", + "rustversion", + "wasm-bindgen-macro", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2e29d0c35b16e224a7eeb5cd2d25e3e1968fbd65604117b44d3b789d00ee8535" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6f501a8bc3719dba86ef8ae4728879c08001bea749eb1333ac5b91e040e2a6b7" +dependencies = [ + "bumpalo", + "proc-macro2", + "quote", + "syn 3.0.6", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23f0c9c52aa7cd7d77769a4cfe2a9adb1b331f489a41d912ce14513d5ab995c6" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "webpki-roots" +version = "0.26.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "521bc38abb08001b01866da9f51eb7c5d647a19260e00054a8c7fd5f9e57f7a9" +dependencies = [ + "webpki-roots 1.0.9", +] + +[[package]] +name = "webpki-roots" +version = "1.0.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7dcd9d09a39985f5344844e66b0c530a33843579125f23e21e9f0f220850f22a" +dependencies = [ + "rustls-pki-types", +] + +[[package]] +name = "whoami" +version = "1.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d4a4db5077702ca3015d3d02d74974948aba2ad9e12ab7df718ee64ccd7e97d" +dependencies = [ + "libredox", + "wasite", +] + +[[package]] +name = "windows-core" +version = "0.62.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb" +dependencies = [ + "windows-implement", + "windows-interface", + "windows-link", + "windows-result", + "windows-strings", +] + +[[package]] +name = "windows-implement" +version = "0.60.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "windows-interface" +version = "0.59.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-result" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-strings" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-sys" +version = "0.48.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "677d2418bec65e3338edb076e806bc1ec15693c5d0104683f2efe857f61056a9" +dependencies = [ + "windows-targets 0.48.5", +] + +[[package]] +name = "windows-sys" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" +dependencies = [ + "windows-targets 0.52.6", +] + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-targets" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a2fa6e2155d7247be68c096456083145c183cbbbc2764150dda45a87197940c" +dependencies = [ + "windows_aarch64_gnullvm 0.48.5", + "windows_aarch64_msvc 0.48.5", + "windows_i686_gnu 0.48.5", + "windows_i686_msvc 0.48.5", + "windows_x86_64_gnu 0.48.5", + "windows_x86_64_gnullvm 0.48.5", + "windows_x86_64_msvc 0.48.5", +] + +[[package]] +name = "windows-targets" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" +dependencies = [ + "windows_aarch64_gnullvm 0.52.6", + "windows_aarch64_msvc 0.52.6", + "windows_i686_gnu 0.52.6", + "windows_i686_gnullvm", + "windows_i686_msvc 0.52.6", + "windows_x86_64_gnu 0.52.6", + "windows_x86_64_gnullvm 0.52.6", + "windows_x86_64_msvc 0.52.6", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b38e32f0abccf9987a4e3079dfb67dcd799fb61361e53e2882c3cbaf0d905d8" + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc35310971f3b2dbbf3f0690a219f40e2d9afcf64f9ab7cc1be722937c26b4bc" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" + +[[package]] +name = "windows_i686_gnu" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a75915e7def60c94dcef72200b9a8e58e5091744960da64ec734a6c6e9b3743e" + +[[package]] +name = "windows_i686_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" + +[[package]] +name = "windows_i686_msvc" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f55c233f70c4b27f66c523580f78f1004e8b5a8b659e05a4eb49d4166cca406" + +[[package]] +name = "windows_i686_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53d40abd2583d23e4718fddf1ebec84dbff8381c07cae67ff7768bbf19c6718e" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b7b52767868a23d5bab768e390dc5f5c55825b6d30b86c844ff2dc7414044cc" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed94fce61571a4006852b7389a063ab983c02eb1bb37b47f8272ce92d06d9538" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" + +[[package]] +name = "writeable" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc" + +[[package]] +name = "yoke" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "709fe23a0424b6a435d82152b1bd3fdfb0833487d5fa90d05d42762a9891fef5" +dependencies = [ + "stable_deref_trait", + "yoke-derive", + "zerofrom", +] + +[[package]] +name = "yoke-derive" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec8ebde2db3681e8c9980cc27822030e68752690ddfa9473e739aeb4dbde6d71" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.6", + "synstructure", +] + +[[package]] +name = "zerocopy" +version = "0.8.59" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6df92bf3d9227be3d53173901ddbffac2babc27ae50f397776ffd6dc33f800cb" +dependencies = [ + "zerocopy-derive", +] + +[[package]] +name = "zerocopy-derive" +version = "0.8.59" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac4f328cf2f05d084e496c3e9c3f33ed0a183656a16e1fcec4d464d8373aec82" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "zerofrom" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272" +dependencies = [ + "zerofrom-derive", +] + +[[package]] +name = "zerofrom-derive" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f75b4683f6c7f45248d4d64056a24298c6281e0993356d7d1b4a1a962ef10d4a" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.6", + "synstructure", +] + +[[package]] +name = "zeroize" +version = "1.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e13c156562582aa81c60cb29407084cdb54c4164760106ab78e6c5b0858cf64e" + +[[package]] +name = "zerotrie" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ea269c3bd32f0a32c321907a2ae912ba6f4649bb0fc764a15627e99a7095a3f" +dependencies = [ + "displaydoc", + "yoke", + "zerofrom", +] + +[[package]] +name = "zerovec" +version = "0.11.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb0464e17806c1d976d5cba29399c7f08e516e279e2ba493f63123b5fca67dd8" +dependencies = [ + "yoke", + "zerofrom", + "zerovec-derive", +] + +[[package]] +name = "zerovec-derive" +version = "0.11.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "34df6fc39dbd26ddc9c10e6a2984476e13acce22e64e4487636ef494369225da" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.6", +] + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..f2bc200 --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,46 @@ +[package] +name = "sub-aligator" +version = "0.1.0" +edition = "2024" +authors = ["janvete"] +description = "Internal IP subnet allocator" +license = "MIT" +repository = "https://git.janvete.com/seth/sub-aligator" +homepage = "https://git.janvete.com/seth/sub-aligator" +keywords = ["network", "ip", "subnet", "allocator", "web"] +categories = ["web-programming"] + +[dependencies] +anyhow = "1" +askama = "0.12.1" +axum = "0.8.3" +chrono = { version = "0.4.41", features = ["serde"] } +csv = "1.3.3" +ipnet = "2.11.0" +rand = "0.8" +serde = { version = "1.0.219", features = ["derive"] } +serde_json = "1.0.140" +sqlx = { version = "0.8.6", features = ["runtime-tokio-rustls", "sqlite", "migrate", "chrono"] } +thiserror = "2.0.12" +tokio = { version = "1.44.2", features = ["rt-multi-thread", "macros", "signal"] } +tower = "0.5.2" +tower-http = { version = "0.7.1", features = ["fs", "set-header", "trace", "catch-panic"] } +axum-extra = { version = "0.10.1", features = ["cookie"] } +tracing = "0.1.41" +tracing-subscriber = { version = "0.3.19", features = ["env-filter"] } + +[dev-dependencies] +futures = "0.3" +tempfile = "3.21.0" +tokio-test = "0.4.4" + +[package.metadata.deb] +maintainer = "janvete " +copyright = "2026, janvete" +extended-description = "Internal IP subnet allocator." +section = "utils" +priority = "optional" +assets = [ + ["target/release/sub-aligator", "usr/bin/sub-aligator", "755"], + ["README.md", "usr/share/doc/sub-aligator/README.md", "644"], +] diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..e943f61 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,42 @@ +# syntax=docker/dockerfile:1 + +FROM rust:1.82-bookworm AS builder + +WORKDIR /app + +COPY Cargo.toml Cargo.lock ./ +COPY src ./src +COPY migrations ./migrations +COPY static ./static +COPY templates ./templates + +RUN cargo build --release + +FROM debian:bookworm-slim + +RUN apt-get update && apt-get install -y --no-install-recommends \ + ca-certificates \ + curl \ + sqlite3 \ + && rm -rf /var/lib/apt/lists/* + +RUN groupadd -r app && useradd -r -g app app + +WORKDIR /app + +RUN mkdir -p /app/data /app/exports /app/backups && \ + chown -R app:app /app + +COPY --from=builder /app/target/release/sub-aligator /usr/local/bin/sub-aligator +COPY --from=builder /app/migrations /app/migrations +COPY --from=builder /app/static /app/static +COPY --from=builder /app/templates /app/templates + +USER app + +EXPOSE 8080 + +HEALTHCHECK --interval=30s --timeout=5s --start-period=5s --retries=3 \ + CMD curl -fsS http://localhost:8080/healthz >/dev/null || exit 1 + +CMD ["/usr/local/bin/sub-aligator"] diff --git a/Formula/sub-aligator.rb b/Formula/sub-aligator.rb new file mode 100644 index 0000000..8263362 --- /dev/null +++ b/Formula/sub-aligator.rb @@ -0,0 +1,17 @@ +class SubAligator < Formula + desc "Internal IP subnet allocator" + homepage "https://git.janvete.com/seth/sub-aligator" + url "https://git.janvete.com/seth/sub-aligator/archive/v0.1.0.tar.gz" + sha256 "44b0c1282a59584d00e8b534fad3570aa8c1f90362012d4fe445039b88f61fe4" + license "MIT" + + depends_on "rust" => :build + + def install + system "cargo", "install", *std_cargo_args + end + + test do + system "#{bin}/sub-aligator", "--version" + end +end diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..2e6aed8 --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 janvete + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/README.md b/README.md new file mode 100644 index 0000000..679781a --- /dev/null +++ b/README.md @@ -0,0 +1,169 @@ +# IP Subnet Allocator + +Jednoduchá interní webová aplikace pro evidenci a automatické přidělování IPv4 subnetů. + +## Účel + +Aplikace slouží výhradně pro interní evidenci a automatické přidělování IPv4 subnetů. Není to obecný IPAM, monitoring, inventář zařízení, správa VLAN ani síťová topologie. + +Je navržena pro provoz pouze uvnitř LAN/VPN. **Aplikace neobsahuje autentizaci** – musí být zařazena za firewall/reverse proxy v důvěryhodné síti. + +## Přehled funkcí + +- Dva přednastavené pooly: + - VLAN / zákaznické subnety: `10.91.0.0/16` + - VPN subnety: `10.200.0.0/16` +- Automatické přidělování subnetů pomocí **first-fit** algoritmu pro prefixy /20 až /30. +- Atomický zápis alokací přes SQLite transakci `BEGIN IMMEDIATE`. +- Webové UI s retro TUI/terminál vzhledem, server-side renderované pomocí Askama. +- Dynamické preview dalšího volného subnetu přes HTMX. +- Historie alokací s filtrem, vyhledáváním a stránkováním. +- Uvolňování subnetů (status `released`) s povinnou poznámkou. +- Auditní log všech operací. +- Exporty do Markdown, CSV a JSON. +- SQLite migrace probíhají automaticky při startu. +- Zálohovací a obnovovací skripty. + +## Architektura + +- **Rust** edition 2024 +- **Axum** + **Tokio** +- **SQLx** s **SQLite** +- **Askama** pro HTML šablony +- **HTMX** z lokálního statického souboru +- Vlastní CSS bez externích frameworků +- CIDR/IP výpočty pomocí `ipnet` + +## Rychlý start + +```bash +cd sub-aligator +cp .env.example .env +docker compose up -d --build +``` + +Otevřete prohlížeč na: + +``` +http://IP_SERVERU:8080 +``` + +Výchozí port lze změnit v `.env` pomocí proměnné `APP_PORT`. + +## Persistentní data + +Docker Compose vytváří lokální adresáře: + +- `./data` – SQLite databáze +- `./exports` – vygenerované exporty (Markdown, CSV, JSON) +- `./backups` – zálohy databáze + +Tyto adresáře jsou bind mountovány do kontejneru, takže data přetrvávají i po odstranění kontejneru. + +## Záloha a obnova + +### Záloha + +```bash +./scripts/backup.sh +``` + +Skript vytvoří konzistentní zálohu databáze pomocí `sqlite3 .backup` s UTC timestampem v názvu souboru. Zálohy se ukládají do `./backups`. + +### Obnova + +```bash +./scripts/restore.sh ./backups/subnet-allocator.db.20240930T120000Z.backup +``` + +**Upozornění:** obnova přepíše aktuální databázi. Před obnovou doporučujeme zastavit kontejner a vytvořit zálohu aktuálního stavu. + +### Automatizace zálohy + +Na hostovi můžete použít systemd timer nebo cron. Příklad cron záznamu: + +```cron +0 2 * * * /cesta/k/sub-aligator/scripts/backup.sh >> /var/log/subnet-allocator-backup.log 2>&1 +``` + +## Exporty + +Po každém úspěšném vytvoření nebo uvolnění subnetu se vygenerují read-only exporty: + +- `/app/exports/allocations.md` +- `/app/exports/allocations.csv` +- `/app/exports/allocations.json` + +Ke stažení jsou dostupné přes endpointy: + +- `GET /exports/allocations.md` +- `GET /exports/allocations.csv` +- `GET /exports/allocations.json` + +Markdown export obsahuje samostatnou sekci pro každý pool s tabulkou aktivních a rezervovaných alokací. CSV a JSON obsahují všechny alokace včetně released. + +## Bezpečnostní omezení + +- Aplikace **nemá autentizaci**. Používejte ji pouze za VPN/LAN/firewallem. +- CSRF tokeny jsou povinné pro POST formuláře. +- Nastaveny bezpečnostní hlavičky: `X-Content-Type-Options`, `X-Frame-Options`, `Referrer-Policy`, `Content-Security-Policy`. +- Aplikace nemá žádný defaultní přístup z Internetu; bind portu se řeší přes Docker Compose. +- `/healthz` vrací pouze `{"status":"ok"}`. + +## Pozdější přidání autentizace přes Caddy + Authentik + +Aplikace je připravena pro autentizaci přes důvěryhodnou reverse proxy. Funkce `get_actor_from_request()` v `src/audit.rs` nyní vrací `local`, ale může být upravena pro čtení hlavičky, například `X-Authentik-Username`. + +Příklad konfigurace Caddy s Authentik: + +```caddy +subnet.example.com { + reverse_proxy /outpost.goauthentik.io/* http://authentik:9000 + forward_auth http://authentik:9000 { + uri /outpost.goauthentik.io/auth/caddy + copy_headers X-Authentik-Username X-Authentik-Groups X-Authentik-Email + } + reverse_proxy subnet-allocator:8080 +} +``` + +Po úpravě `get_actor_from_request()` bude auditní log obsahovat skutečného uživatele. + +## Příklad first-fit alokace + +1. První požadavek `/30` získá `10.91.0.0/30`. +2. Následný požadavek `/24` získá `10.91.1.0/24` (vyhne se obsazenému `/30`). +3. Další požadavek `/30` zaplní mezeru a získá `10.91.0.4/30`. + +Algoritmus vždy respektuje CIDR zarovnání a najde první volný prostor dostatečné velikosti. + +## Endpointy + +- `GET /` – hlavní stránka +- `GET /healthz` – healthcheck +- `GET /partials/pools/{slug}/preview?prefix_length=24` – HTMX preview +- `POST /allocations` – vytvoření alokace +- `GET /allocations` – seznam alokací (součást `/`) +- `GET /allocations/{id}` – detail alokace +- `POST /allocations/{id}/release` – uvolnění alokace +- `GET /exports/allocations.{md,csv,json}` – exporty + +## Troubleshooting + +### Kontejner nenastartuje + +```bash +docker compose logs -f subnet-allocator +``` + +### Databáze je uzamčena + +Pokud dojde k neočekávanému ukončení, může zůstat `-wal` nebo `-shm` soubor. Zastavte kontejner a zkontrolujte `./data`. + +### Exporty se negenerují + +Zkontrolujte práva adresáře `./exports` a proměnnou `APP_EXPORTS_DIR`. + +## Licence + +MIT. Viz soubor `LICENSE`. diff --git a/compose.yaml b/compose.yaml new file mode 100644 index 0000000..aa959fe --- /dev/null +++ b/compose.yaml @@ -0,0 +1,25 @@ +services: + subnet-allocator: + build: + context: . + dockerfile: Dockerfile + container_name: subnet-allocator + ports: + - "${APP_PORT:-8080}:8080" + volumes: + - ./data:/app/data + - ./exports:/app/exports + - ./backups:/app/backups + environment: + - RUST_LOG=info + - APP_BIND=0.0.0.0:8080 + - DATABASE_URL=sqlite:/app/data/subnet-allocator.db + - APP_TIMEZONE=Europe/Prague + - APP_EXPORTS_DIR=/app/exports + restart: unless-stopped + healthcheck: + test: ["CMD", "curl", "-fsS", "http://localhost:8080/healthz"] + interval: 30s + timeout: 5s + start_period: 5s + retries: 3 diff --git a/migrations/20240930000001_create_pools.sql b/migrations/20240930000001_create_pools.sql new file mode 100644 index 0000000..afb806e --- /dev/null +++ b/migrations/20240930000001_create_pools.sql @@ -0,0 +1,13 @@ +CREATE TABLE IF NOT EXISTS pools ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + slug TEXT NOT NULL UNIQUE, + name TEXT NOT NULL, + cidr TEXT NOT NULL UNIQUE, + kind TEXT NOT NULL, + allowed_prefixes_json TEXT NOT NULL, + enabled BOOLEAN NOT NULL DEFAULT true, + created_at TEXT NOT NULL +); + +CREATE INDEX IF NOT EXISTS idx_pools_slug ON pools(slug); +CREATE INDEX IF NOT EXISTS idx_pools_enabled ON pools(enabled); diff --git a/migrations/20240930000002_create_allocations.sql b/migrations/20240930000002_create_allocations.sql new file mode 100644 index 0000000..ccdf54f --- /dev/null +++ b/migrations/20240930000002_create_allocations.sql @@ -0,0 +1,20 @@ +CREATE TABLE IF NOT EXISTS allocations ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + pool_id INTEGER NOT NULL REFERENCES pools(id), + cidr TEXT NOT NULL UNIQUE, + prefix_length INTEGER NOT NULL, + address_count INTEGER NOT NULL, + usable_host_count INTEGER NOT NULL, + note TEXT NOT NULL, + status TEXT NOT NULL CHECK(status IN ('active', 'reserved', 'released')), + created_at TEXT NOT NULL, + created_by TEXT NOT NULL DEFAULT 'local', + released_at TEXT NULL, + released_by TEXT NULL, + release_note TEXT NULL +); + +CREATE INDEX IF NOT EXISTS idx_allocations_pool_id ON allocations(pool_id); +CREATE INDEX IF NOT EXISTS idx_allocations_status ON allocations(status); +CREATE INDEX IF NOT EXISTS idx_allocations_pool_status ON allocations(pool_id, status); +CREATE INDEX IF NOT EXISTS idx_allocations_created_at ON allocations(created_at DESC); diff --git a/migrations/20240930000003_create_audit_events.sql b/migrations/20240930000003_create_audit_events.sql new file mode 100644 index 0000000..99116cf --- /dev/null +++ b/migrations/20240930000003_create_audit_events.sql @@ -0,0 +1,13 @@ +CREATE TABLE IF NOT EXISTS audit_events ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + event_type TEXT NOT NULL, + allocation_id INTEGER NULL REFERENCES allocations(id), + pool_id INTEGER NULL REFERENCES pools(id), + actor TEXT NOT NULL DEFAULT 'local', + details_json TEXT NOT NULL, + created_at TEXT NOT NULL +); + +CREATE INDEX IF NOT EXISTS idx_audit_events_allocation_id ON audit_events(allocation_id); +CREATE INDEX IF NOT EXISTS idx_audit_events_pool_id ON audit_events(pool_id); +CREATE INDEX IF NOT EXISTS idx_audit_events_created_at ON audit_events(created_at DESC); diff --git a/scripts/backup.sh b/scripts/backup.sh new file mode 100755 index 0000000..3401500 --- /dev/null +++ b/scripts/backup.sh @@ -0,0 +1,32 @@ +#!/usr/bin/env bash +set -euo pipefail + +# Skript vytvoří konzistentní SQLite backup přes sqlite3 .backup příkaz. +# Nepoužívejte obyčejný cp pro běžící SQLite databázi. + +DATA_DIR="${DATA_DIR:-./data}" +BACKUP_DIR="${BACKUP_DIR:-./backups}" +DB_NAME="${DB_NAME:-subnet-allocator.db}" + +DB_PATH="${DATA_DIR}/${DB_NAME}" + +if ! command -v sqlite3 >/dev/null 2>&1; then + echo "ERROR: sqlite3 není nainstalováno." >&2 + exit 1 +fi + +if [ ! -f "$DB_PATH" ]; then + echo "ERROR: Databáze neexistuje: $DB_PATH" >&2 + exit 1 +fi + +mkdir -p "$BACKUP_DIR" + +TIMESTAMP=$(date -u +"%Y%m%dT%H%M%SZ") +BACKUP_FILE="${BACKUP_DIR}/${DB_NAME}.${TIMESTAMP}.backup" + +echo "Vytvářím konzistentní backup: $BACKUP_FILE" +sqlite3 "$DB_PATH" ".backup '${BACKUP_FILE}'" + +echo "Backup dokončen: $BACKUP_FILE" +ls -lh "$BACKUP_FILE" diff --git a/scripts/restore.sh b/scripts/restore.sh new file mode 100755 index 0000000..a3564f0 --- /dev/null +++ b/scripts/restore.sh @@ -0,0 +1,41 @@ +#!/usr/bin/env bash +set -euo pipefail + +# Bezpečnostní upozornění: obnova přepíše aktuální databázi. +# Zastavte kontejner před obnovou a nezapomeňte si předem zálohovat aktuální stav. + +DATA_DIR="${DATA_DIR:-./data}" +BACKUP_DIR="${BACKUP_DIR:-./backups}" +DB_NAME="${DB_NAME:-subnet-allocator.db}" + +DB_PATH="${DATA_DIR}/${DB_NAME}" + +if [ $# -lt 1 ]; then + echo "Použití: $0 " >&2 + echo "Dostupné backupy v ${BACKUP_DIR}:" >&2 + ls -1 "$BACKUP_DIR"/*.backup 2>/dev/null || echo " žádné" >&2 + exit 1 +fi + +BACKUP_FILE="$1" + +if [ ! -f "$BACKUP_FILE" ]; then + echo "ERROR: Backup soubor neexistuje: $BACKUP_FILE" >&2 + exit 1 +fi + +if [ -f "$DB_PATH" ]; then + echo "UPOZORNĚNÍ: Aktuální databáze ${DB_PATH} bude přepsána." >&2 + read -r -p "Pokračovat? [y/N] " CONFIRM + if [[ ! "$CONFIRM" =~ ^[Yy]$ ]]; then + echo "Obnova zrušena." >&2 + exit 0 + fi +fi + +mkdir -p "$DATA_DIR" + +echo "Obnovuji databázi z: $BACKUP_FILE" +cp "$BACKUP_FILE" "$DB_PATH" + +echo "Obnova dokončena: $DB_PATH" diff --git a/src/allocator.rs b/src/allocator.rs new file mode 100644 index 0000000..26d97af --- /dev/null +++ b/src/allocator.rs @@ -0,0 +1,264 @@ +use ipnet::Ipv4Net; +use std::net::Ipv4Addr; +use thiserror::Error; + +#[derive(Debug, Error)] +pub enum AllocateError { + #[error("Neplatný parent prefix: {0}")] + InvalidParent(String), + #[error("Požadovaná maska /{0} není v tomto poolu povolena")] + PrefixNotAllowed(i32), + #[error("Subnet /{prefix} se do poolu {parent} nevejde")] + DoesNotFit { prefix: i32, parent: String }, + #[error("Pool je plný, není dostatek volného místa pro /{0}")] + PoolFull(i32), +} + +#[derive(Clone, Debug)] +pub struct SubnetInfo { + pub cidr: String, + pub prefix_length: i32, + pub address_count: i32, + pub usable_host_count: i32, + pub network: String, + pub broadcast: String, + pub first_host: String, + pub last_host: String, +} + +pub fn parse_ipv4_net(cidr: &str) -> Result { + cidr.parse::() + .map_err(|_| AllocateError::InvalidParent(cidr.to_string())) +} + +pub fn allowed_prefixes_default() -> Vec { + vec![20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30] +} + +pub fn host_count(prefix_length: i32) -> i32 { + let hosts = 2u32.pow(32 - prefix_length as u32); + hosts as i32 +} + +pub fn usable_host_count(prefix_length: i32) -> i32 { + match prefix_length { + 32 => 1, + 31 => 2, + _ => { + let total = host_count(prefix_length); + (total - 2).max(0) + } + } +} + +pub fn subnet_info(cidr: &str) -> Result { + let net = parse_ipv4_net(cidr)?; + let prefix = net.prefix_len() as i32; + let total = host_count(prefix); + let usable = usable_host_count(prefix); + + let network = net.network(); + let broadcast = net.broadcast(); + + let (first, last) = if prefix == 32 { + (network, network) + } else if prefix == 31 { + (network, broadcast) + } else { + let first = increment_ip(network, 1); + let last = decrement_ip(broadcast, 1); + (first, last) + }; + + Ok(SubnetInfo { + cidr: cidr.to_string(), + prefix_length: prefix, + address_count: total, + usable_host_count: usable, + network: network.to_string(), + broadcast: broadcast.to_string(), + first_host: first.to_string(), + last_host: last.to_string(), + }) +} + +fn increment_ip(ip: Ipv4Addr, n: u32) -> Ipv4Addr { + let octets = ip.octets(); + let num = u32::from_be_bytes(octets).wrapping_add(n); + Ipv4Addr::from(num) +} + +fn decrement_ip(ip: Ipv4Addr, n: u32) -> Ipv4Addr { + let octets = ip.octets(); + let num = u32::from_be_bytes(octets).wrapping_sub(n); + Ipv4Addr::from(num) +} + +/// First-fit allocation: iterate from the lowest address of the parent prefix, +/// find the first aligned subnet of `prefix_length` that does not overlap any +/// active/reserved allocation. +pub fn find_next_subnet( + parent_cidr: &str, + prefix_length: i32, + allowed_prefixes: &[i32], + existing: &[String], +) -> Result { + if !allowed_prefixes.contains(&prefix_length) { + return Err(AllocateError::PrefixNotAllowed(prefix_length)); + } + + let parent = parse_ipv4_net(parent_cidr)?; + if prefix_length < parent.prefix_len() as i32 { + return Err(AllocateError::DoesNotFit { + prefix: prefix_length, + parent: parent_cidr.to_string(), + }); + } + + let existing_nets: Vec = existing + .iter() + .filter_map(|c| c.parse::().ok()) + .collect(); + + let parent_start = u32::from_be_bytes(parent.network().octets()); + let parent_end = u32::from_be_bytes(parent.broadcast().octets()); + let size = host_count(prefix_length) as u32; + + let mut candidate_start = parent_start; + + while candidate_start.saturating_add(size - 1) <= parent_end { + // Align to prefix boundary. + let mask = !(size - 1); + let aligned = candidate_start & mask; + + if aligned < parent_start { + candidate_start = aligned.wrapping_add(size); + continue; + } + + let candidate_end = aligned + size - 1; + if candidate_end > parent_end { + break; + } + + let candidate_net = Ipv4Net::new(Ipv4Addr::from(aligned), prefix_length as u8) + .map_err(|_| AllocateError::InvalidParent(parent_cidr.to_string()))?; + + let overlaps = existing_nets.iter().any(|e| e.contains(&candidate_net) || candidate_net.contains(e)); + + if !overlaps { + return subnet_info(&candidate_net.to_string()); + } + + candidate_start = candidate_end + 1; + } + + Err(AllocateError::PoolFull(prefix_length)) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn allocate(parent: &str, prefix: i32, existing: &[String]) -> SubnetInfo { + find_next_subnet(parent, prefix, &allowed_prefixes_default(), existing).unwrap() + } + + fn s(cidr: &str) -> String { + cidr.to_string() + } + + #[test] + fn empty_pool_allocates_slash_24() { + let info = allocate("10.91.0.0/16", 24, &[]); + assert_eq!(info.cidr, "10.91.0.0/24"); + } + + #[test] + fn slash_30_then_slash_24() { + let mut existing = vec![]; + let a = allocate("10.91.0.0/16", 30, &existing); + assert_eq!(a.cidr, "10.91.0.0/30"); + existing.push(a.cidr); + + let b = allocate("10.91.0.0/16", 24, &existing); + assert_eq!(b.cidr, "10.91.1.0/24"); + } + + #[test] + fn slash_30_then_slash_30_fills_gap() { + let mut existing = vec![]; + let a = allocate("10.91.0.0/16", 30, &existing); + assert_eq!(a.cidr, "10.91.0.0/30"); + existing.push(a.cidr); + + let b = allocate("10.91.0.0/16", 24, &existing); + assert_eq!(b.cidr, "10.91.1.0/24"); + existing.push(b.cidr); + + let c = allocate("10.91.0.0/16", 30, &existing); + assert_eq!(c.cidr, "10.91.0.4/30"); + } + + #[test] + fn mix_30_29_24_without_overlap() { + let mut existing = vec![]; + let a = allocate("10.91.0.0/16", 30, &existing); + existing.push(a.cidr); + let b = allocate("10.91.0.0/16", 29, &existing); + existing.push(b.cidr); + let c = allocate("10.91.0.0/16", 24, &existing); + existing.push(c.cidr); + + assert!(!existing.is_empty()); + let nets: Vec = existing.iter().filter_map(|x| x.parse().ok()).collect(); + for i in 0..nets.len() { + for j in (i + 1)..nets.len() { + assert!( + !nets[i].contains(&nets[j]) && !nets[j].contains(&nets[i]), + "overlap between {} and {}", + nets[i], + nets[j] + ); + } + } + } + + #[test] + fn cidr_alignment_is_respected() { + let existing = vec![s("10.91.0.128/30")]; + let info = allocate("10.91.0.0/24", 25, &existing); + assert_eq!(info.cidr, "10.91.0.0/25"); + } + + #[test] + fn full_pool_returns_error() { + let existing = vec![s("10.91.0.0/24"), s("10.91.1.0/24")]; + let err = find_next_subnet("10.91.0.0/23", 24, &allowed_prefixes_default(), &existing) + .unwrap_err(); + assert!(matches!(err, AllocateError::PoolFull(24))); + } + + #[test] + fn released_subnet_is_reusable() { + let mut existing = vec![s("10.91.0.0/30")]; + // simulate release by removing it + existing.clear(); + let info = allocate("10.91.0.0/16", 30, &existing); + assert_eq!(info.cidr, "10.91.0.0/30"); + } + + #[test] + fn subnet_outside_parent_is_rejected() { + let err = find_next_subnet("10.91.0.0/23", 20, &allowed_prefixes_default(), &[]) + .unwrap_err(); + assert!(matches!(err, AllocateError::DoesNotFit { .. })); + } + + #[test] + fn prefix_not_allowed_is_rejected() { + let err = find_next_subnet("10.91.0.0/16", 19, &allowed_prefixes_default(), &[]) + .unwrap_err(); + assert!(matches!(err, AllocateError::PrefixNotAllowed(19))); + } +} diff --git a/src/audit.rs b/src/audit.rs new file mode 100644 index 0000000..09fb2a4 --- /dev/null +++ b/src/audit.rs @@ -0,0 +1,32 @@ +use crate::models::now_utc_rfc3339; +use axum::http::HeaderMap; +use serde_json::Value; +use sqlx::SqliteConnection; + +pub fn get_actor_from_request(_headers: &HeaderMap) -> String { + // Placeholder: later read X-Authentik-Username or similar trusted header. + "local".to_string() +} + +pub async fn log_event( + conn: &mut SqliteConnection, + event_type: &str, + allocation_id: Option, + pool_id: Option, + actor: &str, + details: Value, +) -> anyhow::Result<()> { + let json = details.to_string(); + sqlx::query( + "INSERT INTO audit_events (event_type, allocation_id, pool_id, actor, details_json, created_at) VALUES (?, ?, ?, ?, ?, ?)", + ) + .bind(event_type) + .bind(allocation_id) + .bind(pool_id) + .bind(actor) + .bind(json) + .bind(now_utc_rfc3339()) + .execute(&mut *conn) + .await?; + Ok(()) +} diff --git a/src/config.rs b/src/config.rs new file mode 100644 index 0000000..2b0f89d --- /dev/null +++ b/src/config.rs @@ -0,0 +1,21 @@ +use std::env; + +#[derive(Clone, Debug)] +pub struct Config { + pub database_url: String, + pub bind: String, + pub timezone: String, + pub exports_dir: String, +} + +impl Config { + pub fn from_env() -> Self { + Self { + database_url: env::var("DATABASE_URL") + .unwrap_or_else(|_| "sqlite:subnet-allocator.db".to_string()), + bind: env::var("APP_BIND").unwrap_or_else(|_| "0.0.0.0:8080".to_string()), + timezone: env::var("APP_TIMEZONE").unwrap_or_else(|_| "Europe/Prague".to_string()), + exports_dir: env::var("APP_EXPORTS_DIR").unwrap_or_else(|_| "./exports".to_string()), + } + } +} diff --git a/src/csrf.rs b/src/csrf.rs new file mode 100644 index 0000000..37b1441 --- /dev/null +++ b/src/csrf.rs @@ -0,0 +1,34 @@ +use axum_extra::extract::cookie::{Cookie, CookieJar, SameSite}; +use rand::{distributions::Alphanumeric, Rng}; + +const CSRF_COOKIE: &str = "csrf_token"; + +pub fn generate_token() -> String { + rand::thread_rng() + .sample_iter(&Alphanumeric) + .take(32) + .map(char::from) + .collect() +} + +pub fn ensure_csrf_cookie(jar: CookieJar) -> (CookieJar, String) { + if let Some(cookie) = jar.get(CSRF_COOKIE) { + let token = cookie.value().to_string(); + if token.len() >= 32 { + return (jar, token); + } + } + let token = generate_token(); + let cookie = Cookie::build((CSRF_COOKIE, token.clone())) + .http_only(true) + .same_site(SameSite::Strict) + .path("/") + .build(); + (jar.add(cookie), token) +} + +pub fn validate_csrf(jar: &CookieJar, token: &str) -> bool { + jar.get(CSRF_COOKIE) + .map(|c| c.value() == token) + .unwrap_or(false) +} diff --git a/src/db.rs b/src/db.rs new file mode 100644 index 0000000..87765f2 --- /dev/null +++ b/src/db.rs @@ -0,0 +1,82 @@ +use crate::config::Config; +use crate::models::now_utc_rfc3339; +use anyhow::Context; +use sqlx::migrate::{MigrateDatabase, Migrator}; +use sqlx::sqlite::{SqliteConnectOptions, SqliteJournalMode, SqliteSynchronous}; +use sqlx::{Sqlite, SqlitePool}; +use std::path::Path; +use std::str::FromStr; +use tracing::info; + +pub async fn init_db(config: &Config) -> anyhow::Result { + let database_url = &config.database_url; + + if database_url.starts_with("sqlite:") { + let db_path = database_url + .strip_prefix("sqlite:") + .unwrap_or(database_url); + if !Sqlite::database_exists(database_url).await.unwrap_or(false) { + Sqlite::create_database(database_url) + .await + .context("create sqlite database")?; + } + + let options = SqliteConnectOptions::from_str(db_path) + .context("parse sqlite connect options")? + .journal_mode(SqliteJournalMode::Wal) + .synchronous(SqliteSynchronous::Normal) + .create_if_missing(true); + + let pool = SqlitePool::connect_with(options) + .await + .context("connect to sqlite")?; + + Migrator::new(Path::new("./migrations")) + .await + .context("load migrations")? + .run(&pool) + .await + .context("run migrations")?; + + seed_default_pools(&pool).await.context("seed default pools")?; + + info!("Database initialized: {}", database_url); + Ok(pool) + } else { + anyhow::bail!("Unsupported DATABASE_URL: {}", database_url) + } +} + +async fn seed_default_pools(pool: &SqlitePool) -> anyhow::Result<()> { + let allowed = serde_json::to_string(&[20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30])?; + + let now = now_utc_rfc3339(); + + sqlx::query( + "INSERT OR IGNORE INTO pools (slug, name, cidr, kind, allowed_prefixes_json, enabled, created_at) VALUES (?, ?, ?, ?, ?, ?, ?)" + ) + .bind("vlan") + .bind("VLAN / zákaznické subnety") + .bind("10.91.0.0/16") + .bind("VLAN") + .bind(&allowed) + .bind(true) + .bind(&now) + .execute(pool) + .await?; + + sqlx::query( + "INSERT OR IGNORE INTO pools (slug, name, cidr, kind, allowed_prefixes_json, enabled, created_at) VALUES (?, ?, ?, ?, ?, ?, ?)" + ) + .bind("vpn") + .bind("VPN subnety") + .bind("10.200.0.0/16") + .bind("VPN") + .bind(&allowed) + .bind(true) + .bind(&now) + .execute(pool) + .await?; + + Ok(()) +} diff --git a/src/exports.rs b/src/exports.rs new file mode 100644 index 0000000..ab2d592 --- /dev/null +++ b/src/exports.rs @@ -0,0 +1,154 @@ +use crate::models::{Allocation, Pool}; +use anyhow::Context; +use serde_json::json; +use std::fs; +use std::path::Path; +use tracing::{error, info}; + +pub async fn regenerate_exports( + exports_dir: &str, + pools: &[Pool], + allocations: &[Allocation], +) { + let dir = Path::new(exports_dir); + if let Err(e) = fs::create_dir_all(dir) { + error!("Failed to create exports dir: {}", e); + return; + } + + if let Err(e) = generate_markdown(dir, pools, allocations).await { + error!("Markdown export failed: {}", e); + } else { + info!("Markdown export regenerated"); + } + + if let Err(e) = generate_csv(dir, allocations).await { + error!("CSV export failed: {}", e); + } else { + info!("CSV export regenerated"); + } + + if let Err(e) = generate_json(dir, allocations).await { + error!("JSON export failed: {}", e); + } else { + info!("JSON export regenerated"); + } +} + +async fn generate_markdown( + dir: &Path, + pools: &[Pool], + allocations: &[Allocation], +) -> anyhow::Result<()> { + let path = dir.join("allocations.md"); + let mut lines = vec![ + "# IP Subnet Allocator – Export".to_string(), + "".to_string(), + format!("Vygenerováno: {}", chrono::Utc::now().to_rfc3339()), + "".to_string(), + ]; + + for pool in pools { + lines.push(format!("## {} ({})", pool.name, pool.cidr)); + lines.push("".to_string()); + + let pool_allocs: Vec<&Allocation> = allocations + .iter() + .filter(|a| a.pool_id == pool.id && a.status.as_str() != "released") + .collect(); + + if pool_allocs.is_empty() { + lines.push("*Žádné aktivní ani rezervované alokace.*".to_string()); + lines.push("".to_string()); + continue; + } + + lines.push("| Subnet | Stav | Poznámka | Vytvořeno |".to_string()); + lines.push("|--------|------|----------|-----------|".to_string()); + for a in pool_allocs { + lines.push(format!( + "| {} | {} | {} | {} |", + a.cidr, a.status.as_str(), a.note, a.created_at + )); + } + lines.push("".to_string()); + } + + fs::write(&path, lines.join("\n")).context("write allocations.md")?; + Ok(()) +} + +async fn generate_csv(dir: &Path, allocations: &[Allocation]) -> anyhow::Result<()> { + let path = dir.join("allocations.csv"); + let mut wtr = csv::Writer::from_path(&path).context("create csv writer")?; + + wtr.write_record([ + "id", + "pool_id", + "cidr", + "prefix_length", + "address_count", + "usable_host_count", + "note", + "status", + "created_at", + "created_by", + "released_at", + "released_by", + "release_note", + ])?; + + for a in allocations { + wtr.write_record(&[ + a.id.to_string(), + a.pool_id.to_string(), + a.cidr.clone(), + a.prefix_length.to_string(), + a.address_count.to_string(), + a.usable_host_count.to_string(), + a.note.clone(), + a.status.as_str().to_string(), + a.created_at.clone(), + a.created_by.clone(), + a.released_at.clone().unwrap_or_default(), + a.released_by.clone().unwrap_or_default(), + a.release_note.clone().unwrap_or_default(), + ])?; + } + + wtr.flush().context("flush csv")?; + Ok(()) +} + +async fn generate_json(dir: &Path, allocations: &[Allocation]) -> anyhow::Result<()> { + let path = dir.join("allocations.json"); + let data: Vec = allocations + .iter() + .map(|a| { + json!({ + "id": a.id, + "pool_id": a.pool_id, + "cidr": a.cidr, + "prefix_length": a.prefix_length, + "address_count": a.address_count, + "usable_host_count": a.usable_host_count, + "note": a.note, + "status": a.status.as_str(), + "created_at": a.created_at, + "created_by": a.created_by, + "released_at": a.released_at, + "released_by": a.released_by, + "release_note": a.release_note, + }) + }) + .collect(); + + let output = json!({ + "generated_at": chrono::Utc::now().to_rfc3339(), + "allocations": data, + }); + + fs::write(&path, serde_json::to_string_pretty(&output).context("serialize json")?) + .context("write allocations.json")?; + Ok(()) +} diff --git a/src/handlers/allocations.rs b/src/handlers/allocations.rs new file mode 100644 index 0000000..1479775 --- /dev/null +++ b/src/handlers/allocations.rs @@ -0,0 +1,469 @@ +use crate::allocator::{find_next_subnet, subnet_info}; +use crate::audit::{get_actor_from_request, log_event}; +use crate::csrf::{ensure_csrf_cookie, validate_csrf}; +use crate::exports::regenerate_exports; +use crate::models::{ + now_utc_rfc3339, Allocation, AllocationDetail, AllocationStatus, AuditEventDisplay, Pool, +}; +use crate::state::AppState; +use crate::templates::{AllocationDetailTemplate, FlashData, IndexTemplate, PoolTemplate, SuccessMessage}; +use askama::Template; +use axum::extract::{Form, Path, State}; +use axum::http::HeaderMap; +use axum::response::{Html, IntoResponse, Response}; +use axum_extra::extract::cookie::CookieJar; +use serde::Deserialize; +use serde_json::json; +use sqlx::SqlitePool; +use tracing::{error, info, warn}; + +#[derive(Deserialize, Debug)] +pub struct AllocateForm { + pub pool_slug: String, + pub prefix_length: i32, + pub note: String, + pub ticket: Option, + pub csrf_token: String, +} + +#[derive(Deserialize, Debug)] +pub struct ReleaseForm { + pub release_note: String, + pub csrf_token: String, +} + +pub async fn create_allocation( + State(state): State, + jar: CookieJar, + headers: HeaderMap, + Form(form): Form, +) -> Response { + let (jar, csrf_token) = ensure_csrf_cookie(jar); + let actor = get_actor_from_request(&headers); + + if !validate_csrf(&jar, &form.csrf_token) { + return render_index_with_error(&state, &jar, &csrf_token, "Neplatný CSRF token.").await.into_response(); + } + + let note = form.note.trim(); + if note.len() < 3 { + return render_index_with_error(&state, &jar, &csrf_token, "Poznámka musí mít alespoň 3 znaky.").await.into_response(); + } + + let pool = match load_pool_by_slug(&state.pool, &form.pool_slug).await { + Some(p) => p, + None => return render_index_with_error(&state, &jar, &csrf_token, "Pool neexistuje.").await.into_response(), + }; + + let result = allocate_in_tx( + &state.pool, + pool.id, + &pool.cidr, + &pool.allowed_prefixes(), + form.prefix_length, + note, + form.ticket.as_deref().unwrap_or(""), + &actor, + ) + .await; + + match result { + Ok((allocation, info)) => { + let _ = regenerate_after_change(&state).await; + + let success = SuccessMessage { + cidr: allocation.cidr.clone(), + note: allocation.note.clone(), + network: info.network, + broadcast: info.broadcast, + first_host: info.first_host, + last_host: info.last_host, + usable_host_count: info.usable_host_count, + }; + + let actual_cidr_different = allocation.cidr + != find_preview_cidr(&pool.cidr, &pool.allowed_prefixes(), form.prefix_length); + + let mut message = success.clone(); + if actual_cidr_different { + message.note = format!( + "{} (preview se mezitím změnil, přiděleno: {})", + allocation.note, allocation.cidr + ); + } + + info!( + "Allocated {} in pool {} by {}", + allocation.cidr, pool.slug, actor + ); + render_index_with_success(&state, &jar, &csrf_token, message).await.into_response() + } + Err(e) => { + warn!("Allocation failed: {}", e); + render_index_with_error(&state, &jar, &csrf_token, &e.to_string()).await.into_response() + } + } +} + +fn find_preview_cidr(parent: &str, allowed: &[i32], prefix: i32) -> String { + find_next_subnet(parent, prefix, allowed, &[]) + .map(|i| i.cidr) + .unwrap_or_default() +} + +#[allow(clippy::too_many_arguments)] +pub async fn allocate_in_tx( + pool: &SqlitePool, + pool_id: i64, + parent_cidr: &str, + allowed_prefixes: &[i32], + prefix_length: i32, + note: &str, + ticket: &str, + actor: &str, +) -> anyhow::Result<(Allocation, crate::allocator::SubnetInfo)> { + let mut conn = pool.acquire().await?; + + sqlx::query("BEGIN IMMEDIATE") + .execute(&mut *conn) + .await?; + + let active: Vec = sqlx::query_scalar( + "SELECT cidr FROM allocations WHERE pool_id = ? AND status IN ('active', 'reserved')", + ) + .bind(pool_id) + .fetch_all(&mut *conn) + .await?; + + let info = find_next_subnet(parent_cidr, prefix_length, allowed_prefixes, &active)?; + + let note_with_ticket = if ticket.is_empty() { + note.to_string() + } else { + format!("{} [ticket: {}]", note, ticket) + }; + + let id = sqlx::query( + "INSERT INTO allocations (pool_id, cidr, prefix_length, address_count, usable_host_count, note, status, created_at, created_by) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)" + ) + .bind(pool_id) + .bind(&info.cidr) + .bind(info.prefix_length) + .bind(info.address_count) + .bind(info.usable_host_count) + .bind(¬e_with_ticket) + .bind(AllocationStatus::Active.as_str()) + .bind(now_utc_rfc3339()) + .bind(actor) + .execute(&mut *conn) + .await? + .last_insert_rowid(); + + log_event( + &mut conn, + "allocation_created", + Some(id), + Some(pool_id), + actor, + json!({ + "cidr": info.cidr, + "prefix_length": info.prefix_length, + "note": note_with_ticket, + }), + ) + .await + .ok(); + + sqlx::query("COMMIT").execute(&mut *conn).await?; + + let allocation = sqlx::query_as::<_, Allocation>("SELECT * FROM allocations WHERE id = ?") + .bind(id) + .fetch_one(pool) + .await?; + + Ok((allocation, info)) +} + +pub async fn release_allocation( + State(state): State, + jar: CookieJar, + headers: HeaderMap, + Path(id): Path, + Form(form): Form, +) -> Response { + let (jar, csrf_token) = ensure_csrf_cookie(jar); + let actor = get_actor_from_request(&headers); + + if !validate_csrf(&jar, &form.csrf_token) { + return render_detail_with_error(&state, id, &jar, &csrf_token, "Neplatný CSRF token.").await.into_response(); + } + + let release_note = form.release_note.trim(); + if release_note.len() < 3 { + return render_detail_with_error( + &state, + id, + &jar, + &csrf_token, + "Poznámka k uvolnění musí mít alespoň 3 znaky.", + ) + .await.into_response(); + } + + let result = release_in_tx(&state.pool, id, release_note, &actor).await; + + match result { + Ok(_) => { + let _ = regenerate_after_change(&state).await; + info!("Released allocation {} by {}", id, actor); + render_detail_with_error(&state, id, &jar, &csrf_token, "Subnet byl úspěšně uvolněn.").await.into_response() + } + Err(e) => { + warn!("Release failed for allocation {}: {}", id, e); + render_detail_with_error(&state, id, &jar, &csrf_token, &e.to_string()).await.into_response() + } + } +} + +pub async fn release_in_tx( + pool: &SqlitePool, + id: i64, + release_note: &str, + actor: &str, +) -> anyhow::Result<()> { + let mut conn = pool.acquire().await?; + + sqlx::query("BEGIN IMMEDIATE") + .execute(&mut *conn) + .await?; + + let allocation: Allocation = + sqlx::query_as("SELECT * FROM allocations WHERE id = ? AND status IN ('active', 'reserved')") + .bind(id) + .fetch_one(&mut *conn) + .await + .map_err(|_| anyhow::anyhow!("Alokace neexistuje nebo již není aktivní."))?; + + sqlx::query( + "UPDATE allocations SET status = 'released', released_at = ?, released_by = ?, release_note = ? WHERE id = ?", + ) + .bind(now_utc_rfc3339()) + .bind(actor) + .bind(release_note) + .bind(id) + .execute(&mut *conn) + .await?; + + log_event( + &mut conn, + "allocation_released", + Some(id), + Some(allocation.pool_id), + actor, + json!({ + "cidr": allocation.cidr, + "release_note": release_note, + }), + ) + .await + .ok(); + + sqlx::query("COMMIT").execute(&mut *conn).await?; + Ok(()) +} + +async fn regenerate_after_change(state: &AppState) -> anyhow::Result<()> { + let pools: Vec = sqlx::query_as("SELECT * FROM pools WHERE enabled = true") + .fetch_all(&state.pool) + .await?; + let allocations: Vec = + sqlx::query_as("SELECT * FROM allocations ORDER BY created_at DESC") + .fetch_all(&state.pool) + .await?; + regenerate_exports(&state.config.exports_dir, &pools, &allocations).await; + Ok(()) +} + +async fn load_pool_by_slug(pool: &SqlitePool, slug: &str) -> Option { + sqlx::query_as::<_, Pool>("SELECT * FROM pools WHERE slug = ? AND enabled = true") + .bind(slug) + .fetch_optional(pool) + .await + .ok() + .flatten() +} + +async fn render_index_with_error(state: &AppState, _jar: &CookieJar, csrf_token: &str, error: &str) -> Html { + let template = build_index_template(state, csrf_token, FlashData::error(error)).await; + match template.render() { + Ok(html) => Html(html), + Err(e) => { + error!("Template render error: {}", e); + Html("Chyba při vykreslování stránky.".to_string()) + } + } +} + +async fn render_index_with_success(state: &AppState, _jar: &CookieJar, csrf_token: &str, success: SuccessMessage) -> Html { + let template = build_index_template(state, csrf_token, FlashData::from(Some(success))).await; + match template.render() { + Ok(html) => Html(html), + Err(e) => { + error!("Template render error: {}", e); + Html("Chyba při vykreslování stránky.".to_string()) + } + } +} + +pub async fn build_index_template( + state: &AppState, + csrf_token: &str, + flash: FlashData, +) -> IndexTemplate { + IndexTemplate { + pools: load_pool_templates(state).await, + allocations: vec![], + page: 1, + total_pages: 0, + total_count: 0, + query: String::new(), + pool_filter: String::new(), + status_filter: String::new(), + csrf_token: csrf_token.to_string(), + flash, + } +} + +async fn load_pool_templates(state: &AppState) -> Vec { + sqlx::query_as::<_, Pool>("SELECT * FROM pools WHERE enabled = true ORDER BY id") + .fetch_all(&state.pool) + .await + .unwrap_or_default() + .into_iter() + .map(PoolTemplate::from) + .collect() +} + +async fn render_detail_with_error(state: &AppState, id: i64, _jar: &CookieJar, csrf_token: &str, error: &str) -> Html { + let template = build_detail_template(state, id, csrf_token, FlashData::error(error)).await; + match template.render() { + Ok(html) => Html(html), + Err(e) => { + error!("Template render error: {}", e); + Html("Chyba při vykreslování stránky.".to_string()) + } + } +} + +async fn build_detail_template( + state: &AppState, + id: i64, + csrf_token: &str, + flash: FlashData, +) -> AllocationDetailTemplate { + let allocation = sqlx::query_as::<_, Allocation>("SELECT * FROM allocations WHERE id = ?") + .bind(id) + .fetch_optional(&state.pool) + .await + .ok() + .flatten(); + + let allocation = match allocation { + Some(a) => a, + None => { + return AllocationDetailTemplate { + allocation: AllocationDetail { + id: 0, + cidr: "N/A".to_string(), + kind: "N/A".to_string(), + pool_name: "N/A".to_string(), + address_count: 0, + usable_host_count: 0, + note: "Alokace nenalezena.".to_string(), + ticket: "–".to_string(), + status: "released".to_string(), + network: "N/A".to_string(), + broadcast: "N/A".to_string(), + first_host: "N/A".to_string(), + last_host: "N/A".to_string(), + created_at_local: "N/A".to_string(), + created_by: "local".to_string(), + released_at_local: "–".to_string(), + released_by: "–".to_string(), + release_note: "–".to_string(), + }, + audit_events: vec![], + csrf_token: csrf_token.to_string(), + flash, + } + } + }; + + let pool: Pool = sqlx::query_as("SELECT * FROM pools WHERE id = ?") + .bind(allocation.pool_id) + .fetch_one(&state.pool) + .await + .unwrap(); + + let info = subnet_info(&allocation.cidr).unwrap(); + + let detail = AllocationDetail { + id: allocation.id, + cidr: allocation.cidr.clone(), + kind: pool.kind.clone(), + pool_name: pool.name, + address_count: allocation.address_count, + usable_host_count: allocation.usable_host_count, + note: allocation.note.clone(), + ticket: extract_ticket(&allocation.note).unwrap_or_else(|| "–".to_string()), + status: allocation.status.clone(), + network: info.network, + broadcast: info.broadcast, + first_host: info.first_host, + last_host: info.last_host, + created_at_local: crate::models::utc_to_local(&allocation.created_at, &state.config.timezone), + created_by: allocation.created_by.clone(), + released_at_local: allocation + .released_at + .as_ref() + .map(|d| crate::models::utc_to_local(d, &state.config.timezone)) + .unwrap_or_else(|| "–".to_string()), + released_by: allocation.released_by.clone().unwrap_or_else(|| "–".to_string()), + release_note: allocation + .release_note + .clone() + .unwrap_or_else(|| "–".to_string()), + }; + + let audit: Vec = sqlx::query_as( + "SELECT * FROM audit_events WHERE allocation_id = ? ORDER BY created_at DESC", + ) + .bind(id) + .fetch_all(&state.pool) + .await + .unwrap_or_default(); + + let audit_displays: Vec = audit + .into_iter() + .map(|e| AuditEventDisplay { + created_at_local: crate::models::utc_to_local(&e.created_at, &state.config.timezone), + event_type: e.event_type, + actor: e.actor, + details_json: e.details_json, + }) + .collect(); + + AllocationDetailTemplate { + allocation: detail, + audit_events: audit_displays, + csrf_token: csrf_token.to_string(), + flash, + } +} + +fn extract_ticket(note: &str) -> Option { + note.split("[ticket: ") + .nth(1) + .and_then(|s| s.split(']').next()) + .map(|s| s.to_string()) +} diff --git a/src/handlers/exports.rs b/src/handlers/exports.rs new file mode 100644 index 0000000..e1655fc --- /dev/null +++ b/src/handlers/exports.rs @@ -0,0 +1,57 @@ +use crate::state::AppState; +use axum::extract::State; +use axum::http::{HeaderMap, HeaderValue, StatusCode}; +use axum::response::IntoResponse; +use std::path::Path; +use tracing::error; + +pub async fn export_md(State(state): State) -> impl IntoResponse { + serve_export( + state.config.exports_dir.clone(), + "allocations.md", + "text/markdown; charset=utf-8", + ) +} + +pub async fn export_csv(State(state): State) -> impl IntoResponse { + serve_export( + state.config.exports_dir.clone(), + "allocations.csv", + "text/csv; charset=utf-8", + ) +} + +pub async fn export_json(State(state): State) -> impl IntoResponse { + serve_export( + state.config.exports_dir.clone(), + "allocations.json", + "application/json; charset=utf-8", + ) +} + +fn serve_export(dir: String, filename: &'static str, content_type: &'static str) -> impl IntoResponse { + let path = Path::new(&dir).join(filename); + match std::fs::read_to_string(&path) { + Ok(content) => { + let mut headers = HeaderMap::new(); + headers.insert( + axum::http::header::CONTENT_TYPE, + HeaderValue::from_static(content_type), + ); + let disposition = format!("attachment; filename=\"{}\"", filename); + headers.insert( + axum::http::header::CONTENT_DISPOSITION, + HeaderValue::from_str(&disposition).unwrap(), + ); + (StatusCode::OK, headers, content) + } + Err(e) => { + error!("Export read error: {}", e); + ( + StatusCode::NOT_FOUND, + HeaderMap::new(), + "Export nenalezen.".to_string(), + ) + } + } +} diff --git a/src/handlers/mod.rs b/src/handlers/mod.rs new file mode 100644 index 0000000..075b28e --- /dev/null +++ b/src/handlers/mod.rs @@ -0,0 +1,4 @@ +pub mod allocations; +pub mod exports; +pub mod pages; +pub mod partials; diff --git a/src/handlers/pages.rs b/src/handlers/pages.rs new file mode 100644 index 0000000..a8f3404 --- /dev/null +++ b/src/handlers/pages.rs @@ -0,0 +1,263 @@ +use crate::csrf::ensure_csrf_cookie; +use crate::models::{utc_to_local, Allocation, AllocationListItem, AuditEvent, Pool}; +use crate::state::AppState; +use crate::templates::{AllocationDetailTemplate, FlashData, IndexTemplate, PoolTemplate}; +use askama::Template; +use axum::extract::{Query, State}; +use axum::response::{Html, IntoResponse, Response}; +use axum_extra::extract::cookie::CookieJar; +use serde::Deserialize; +use tracing::error; + +const PAGE_SIZE: i64 = 50; + +#[derive(Deserialize, Debug, Default)] +pub struct IndexQuery { + #[serde(default)] + pub page: i64, + #[serde(default)] + pub q: String, + #[serde(default)] + pub pool: String, + #[serde(default)] + pub status: String, +} + +pub async fn index( + State(state): State, + jar: CookieJar, + Query(q): Query, +) -> impl IntoResponse { + let (jar, csrf_token) = ensure_csrf_cookie(jar); + let page = q.page.max(1); + + let pools: Vec = sqlx::query_as::<_, Pool>( + "SELECT * FROM pools WHERE enabled = true ORDER BY id", + ) + .fetch_all(&state.pool) + .await + .unwrap_or_default() + .into_iter() + .map(PoolTemplate::from) + .collect(); + + let (allocations, total_count) = + load_allocations(&state, &q.q, &q.pool, &q.status, page).await; + + let total_pages = (total_count + PAGE_SIZE - 1) / PAGE_SIZE; + + let template = IndexTemplate { + pools, + allocations, + page, + total_pages, + total_count, + query: q.q, + pool_filter: q.pool, + status_filter: q.status, + csrf_token, + flash: FlashData::default(), + }; + + match template.render() { + Ok(html) => (jar, Html(html)).into_response(), + Err(e) => { + error!("Index template render error: {}", e); + (jar, Html("Chyba při vykreslování stránky.".to_string())).into_response() + } + } +} + +pub async fn allocation_detail( + State(state): State, + jar: CookieJar, + axum::extract::Path(id): axum::extract::Path, +) -> Response { + let (jar, csrf_token) = ensure_csrf_cookie(jar); + + let allocation: Option = + sqlx::query_as("SELECT * FROM allocations WHERE id = ?") + .bind(id) + .fetch_optional(&state.pool) + .await + .unwrap_or_default(); + + let allocation = match allocation { + Some(a) => a, + None => { + return (jar, Html("Alokace nenalezena.".to_string())).into_response(); + } + }; + + let pool: Pool = sqlx::query_as("SELECT * FROM pools WHERE id = ?") + .bind(allocation.pool_id) + .fetch_one(&state.pool) + .await + .unwrap(); + + let info = crate::allocator::subnet_info(&allocation.cidr).unwrap(); + + let detail = crate::models::AllocationDetail { + id: allocation.id, + cidr: allocation.cidr.clone(), + kind: pool.kind.clone(), + pool_name: pool.name, + address_count: allocation.address_count, + usable_host_count: allocation.usable_host_count, + note: allocation.note.clone(), + ticket: extract_ticket(&allocation.note).unwrap_or_else(|| "–".to_string()), + status: allocation.status.clone(), + network: info.network, + broadcast: info.broadcast, + first_host: info.first_host, + last_host: info.last_host, + created_at_local: utc_to_local(&allocation.created_at, &state.config.timezone), + created_by: allocation.created_by.clone(), + released_at_local: allocation + .released_at + .as_ref() + .map(|d| utc_to_local(d, &state.config.timezone)) + .unwrap_or_else(|| "–".to_string()), + released_by: allocation.released_by.clone().unwrap_or_else(|| "–".to_string()), + release_note: allocation + .release_note + .clone() + .unwrap_or_else(|| "–".to_string()), + }; + + let audit: Vec = sqlx::query_as( + "SELECT * FROM audit_events WHERE allocation_id = ? ORDER BY created_at DESC", + ) + .bind(id) + .fetch_all(&state.pool) + .await + .unwrap_or_default(); + + let audit_displays: Vec = audit + .into_iter() + .map(|e| crate::models::AuditEventDisplay { + created_at_local: utc_to_local(&e.created_at, &state.config.timezone), + event_type: e.event_type, + actor: e.actor, + details_json: e.details_json, + }) + .collect(); + + let template = AllocationDetailTemplate { + allocation: detail, + audit_events: audit_displays, + csrf_token, + flash: FlashData::default(), + }; + + match template.render() { + Ok(html) => (jar, Html(html)).into_response(), + Err(e) => { + error!("Detail template render error: {}", e); + (jar, Html("Chyba při vykreslování stránky.".to_string())).into_response() + } + } +} + +fn extract_ticket(note: &str) -> Option { + note.split("[ticket: ") + .nth(1) + .and_then(|s| s.split(']').next()) + .map(|s| s.to_string()) +} + +async fn load_allocations( + state: &AppState, + q: &str, + pool_filter: &str, + status_filter: &str, + page: i64, +) -> (Vec, i64) { + let offset = (page - 1) * PAGE_SIZE; + let like = format!("%{}%", q); + + let count: i64 = sqlx::query_scalar( + r#" + SELECT COUNT(*) + FROM allocations a + JOIN pools p ON p.id = a.pool_id + WHERE (a.cidr LIKE ? OR a.note LIKE ?) + AND (? = '' OR p.slug = ?) + AND (? = '' OR a.status = ?) + "#, + ) + .bind(&like) + .bind(&like) + .bind(pool_filter) + .bind(pool_filter) + .bind(status_filter) + .bind(status_filter) + .fetch_one(&state.pool) + .await + .unwrap_or(0); + + let allocations: Vec = sqlx::query_as( + r#" + SELECT a.* + FROM allocations a + JOIN pools p ON p.id = a.pool_id + WHERE (a.cidr LIKE ? OR a.note LIKE ?) + AND (? = '' OR p.slug = ?) + AND (? = '' OR a.status = ?) + ORDER BY a.created_at DESC + LIMIT ? OFFSET ? + "#, + ) + .bind(&like) + .bind(&like) + .bind(pool_filter) + .bind(pool_filter) + .bind(status_filter) + .bind(status_filter) + .bind(PAGE_SIZE) + .bind(offset) + .fetch_all(&state.pool) + .await + .unwrap_or_default(); + + let pool_ids: Vec = allocations.iter().map(|a| a.pool_id).collect(); + let pools: Vec = if pool_ids.is_empty() { + vec![] + } else { + let placeholders = pool_ids.iter().map(|_| "?").collect::>().join(","); + let query = format!("SELECT * FROM pools WHERE id IN ({})", placeholders); + let mut q = sqlx::query_as::<_, Pool>(&query); + for id in &pool_ids { + q = q.bind(id); + } + q.fetch_all(&state.pool).await.unwrap_or_default() + }; + + let pool_map: std::collections::HashMap = pools + .into_iter() + .map(|p| (p.id, p)) + .collect(); + + let items = allocations + .into_iter() + .map(|a| { + let p = pool_map.get(&a.pool_id); + AllocationListItem { + id: a.id, + cidr: a.cidr, + kind: p.as_ref().map(|p| p.kind.clone()).unwrap_or_default(), + pool_name: p.as_ref().map(|p| p.name.clone()).unwrap_or_default(), + address_count: a.address_count, + note: a.note, + status: a.status.clone(), + created_at_local: utc_to_local(&a.created_at, &state.config.timezone), + } + }) + .collect(); + + (items, count) +} + +pub async fn healthz() -> impl IntoResponse { + axum::Json(serde_json::json!({ "status": "ok" })) +} diff --git a/src/handlers/partials.rs b/src/handlers/partials.rs new file mode 100644 index 0000000..c39fa87 --- /dev/null +++ b/src/handlers/partials.rs @@ -0,0 +1,78 @@ +use crate::allocator::{find_next_subnet, usable_host_count}; +use crate::models::Pool; +use crate::state::AppState; +use crate::templates::PoolPreviewTemplate; +use askama::Template; +use axum::extract::{Path, Query, State}; +use axum::response::{Html, IntoResponse}; +use serde::Deserialize; +use tracing::error; + +#[derive(Deserialize, Debug)] +pub struct PreviewQuery { + pub prefix_length: i32, +} + +pub async fn pool_preview( + State(state): State, + Path(slug): Path, + Query(q): Query, +) -> impl IntoResponse { + let pool: Option = sqlx::query_as("SELECT * FROM pools WHERE slug = ? AND enabled = true") + .bind(&slug) + .fetch_optional(&state.pool) + .await + .unwrap_or_default(); + + let pool = match pool { + Some(p) => p, + None => { + let template = PoolPreviewTemplate { + cidr: String::new(), + prefix_length: q.prefix_length, + address_count: 0, + usable_host_count: 0, + has_error: true, + error: "Pool neexistuje.".to_string(), + }; + return Html(template.render().unwrap_or_default()); + } + }; + + let active: Vec = sqlx::query_scalar( + "SELECT cidr FROM allocations WHERE pool_id = ? AND status IN ('active', 'reserved')", + ) + .bind(pool.id) + .fetch_all(&state.pool) + .await + .unwrap_or_default(); + + let allowed = pool.allowed_prefixes(); + + let template = match find_next_subnet(&pool.cidr, q.prefix_length, &allowed, &active) { + Ok(info) => PoolPreviewTemplate { + cidr: info.cidr, + prefix_length: info.prefix_length, + address_count: info.address_count, + usable_host_count: info.usable_host_count, + has_error: false, + error: String::new(), + }, + Err(e) => PoolPreviewTemplate { + cidr: String::new(), + prefix_length: q.prefix_length, + address_count: usable_host_count(q.prefix_length), + usable_host_count: usable_host_count(q.prefix_length), + has_error: true, + error: e.to_string(), + }, + }; + + match template.render() { + Ok(html) => Html(html), + Err(e) => { + error!("Preview template render error: {}", e); + Html("Chyba preview.".to_string()) + } + } +} diff --git a/src/lib.rs b/src/lib.rs new file mode 100644 index 0000000..3c606f6 --- /dev/null +++ b/src/lib.rs @@ -0,0 +1,11 @@ +pub mod allocator; +pub mod audit; +pub mod config; +pub mod csrf; +pub mod db; +pub mod exports; +pub mod handlers; +pub mod models; +pub mod routes; +pub mod state; +pub mod templates; diff --git a/src/main.rs b/src/main.rs new file mode 100644 index 0000000..63efb85 --- /dev/null +++ b/src/main.rs @@ -0,0 +1,74 @@ +use std::net::SocketAddr; +use sub_aligator::config::Config; +use sub_aligator::db::init_db; +use sub_aligator::routes::router; +use sub_aligator::state::AppState; +use tokio::net::TcpListener; +use tower_http::services::ServeDir; +use tower_http::set_header::SetResponseHeaderLayer; +use tracing::info; + +#[tokio::main] +async fn main() -> anyhow::Result<()> { + tracing_subscriber::fmt() + .with_env_filter(tracing_subscriber::EnvFilter::from_default_env()) + .init(); + + let config = Config::from_env(); + let pool = init_db(&config).await?; + let state = AppState::new(config.clone(), pool); + + let app = router() + .layer(SetResponseHeaderLayer::if_not_present( + axum::http::header::X_CONTENT_TYPE_OPTIONS, + axum::http::HeaderValue::from_static("nosniff"), + )) + .layer(SetResponseHeaderLayer::if_not_present( + axum::http::header::X_FRAME_OPTIONS, + axum::http::HeaderValue::from_static("DENY"), + )) + .layer(SetResponseHeaderLayer::if_not_present( + axum::http::header::REFERRER_POLICY, + axum::http::HeaderValue::from_static("strict-origin-when-cross-origin"), + )) + .layer(SetResponseHeaderLayer::if_not_present( + axum::http::header::CONTENT_SECURITY_POLICY, + axum::http::HeaderValue::from_static( + "default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self'; form-action 'self'; frame-ancestors 'none'; base-uri 'self';", + ), + )) + .nest_service("/static", ServeDir::new("static")) + .with_state(state); + + let addr: SocketAddr = config.bind.parse()?; + info!("Listening on http://{}", addr); + + let listener = TcpListener::bind(&addr).await?; + axum::serve(listener, app) + .with_graceful_shutdown(shutdown_signal()) + .await?; + + Ok(()) +} + +async fn shutdown_signal() { + let ctrl_c = async { + tokio::signal::ctrl_c() + .await + .expect("failed to install Ctrl+C handler"); + }; + + let terminate = async { + tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate()) + .expect("failed to install signal handler") + .recv() + .await; + }; + + tokio::select! { + _ = ctrl_c => {}, + _ = terminate => {}, + } + + info!("Shutdown signal received, stopping server"); +} diff --git a/src/models.rs b/src/models.rs new file mode 100644 index 0000000..762eca3 --- /dev/null +++ b/src/models.rs @@ -0,0 +1,140 @@ +use chrono::{DateTime, Local, Utc}; +use serde::Serialize; +use sqlx::FromRow; + +#[derive(Clone, Debug, FromRow)] +pub struct Pool { + pub id: i64, + pub slug: String, + pub name: String, + pub cidr: String, + pub kind: String, + pub allowed_prefixes_json: String, + pub enabled: i64, + pub created_at: String, +} + +impl Pool { + pub fn allowed_prefixes(&self) -> Vec { + serde_json::from_str(&self.allowed_prefixes_json).unwrap_or_default() + } + + pub fn is_enabled(&self) -> bool { + self.enabled != 0 + } +} + +#[derive(Clone, Debug, FromRow)] +pub struct Allocation { + pub id: i64, + pub pool_id: i64, + pub cidr: String, + pub prefix_length: i32, + pub address_count: i32, + pub usable_host_count: i32, + pub note: String, + pub status: String, + pub created_at: String, + pub created_by: String, + pub released_at: Option, + pub released_by: Option, + pub release_note: Option, +} + +impl Allocation { + pub fn status_enum(&self) -> AllocationStatus { + match self.status.as_str() { + "reserved" => AllocationStatus::Reserved, + "released" => AllocationStatus::Released, + _ => AllocationStatus::Active, + } + } +} + +#[derive(Clone, Debug, sqlx::Type)] +#[sqlx(rename_all = "lowercase")] +pub enum AllocationStatus { + Active, + Reserved, + Released, +} + +impl AllocationStatus { + pub fn as_str(&self) -> &'static str { + match self { + AllocationStatus::Active => "active", + AllocationStatus::Reserved => "reserved", + AllocationStatus::Released => "released", + } + } +} + +#[derive(Clone, Debug, FromRow)] +pub struct AuditEvent { + pub id: i64, + pub event_type: String, + pub allocation_id: Option, + pub pool_id: Option, + pub actor: String, + pub details_json: String, + pub created_at: String, +} + +#[derive(Clone, Debug, Serialize)] +pub struct AllocationListItem { + pub id: i64, + pub cidr: String, + pub kind: String, + pub pool_name: String, + pub address_count: i32, + pub note: String, + pub status: String, + pub created_at_local: String, +} + +#[derive(Clone, Debug, Serialize)] +pub struct AllocationDetail { + pub id: i64, + pub cidr: String, + pub kind: String, + pub pool_name: String, + pub address_count: i32, + pub usable_host_count: i32, + pub note: String, + pub ticket: String, + pub status: String, + pub network: String, + pub broadcast: String, + pub first_host: String, + pub last_host: String, + pub created_at_local: String, + pub created_by: String, + pub released_at_local: String, + pub released_by: String, + pub release_note: String, +} + +#[derive(Clone, Debug, Serialize)] +pub struct AuditEventDisplay { + pub created_at_local: String, + pub event_type: String, + pub actor: String, + pub details_json: String, +} + +pub fn utc_to_local(utc_str: &str, _tz: &str) -> String { + match DateTime::parse_from_rfc3339(utc_str) { + Ok(dt) => { + let local = dt.with_timezone(&Local); + local.format("%d.%m.%Y %H:%M:%S").to_string() + } + Err(_) => { + // Fallback: try interpreting as Europe/Prague or just return as-is. + utc_str.to_string() + } + } +} + +pub fn now_utc_rfc3339() -> String { + Utc::now().to_rfc3339() +} diff --git a/src/routes.rs b/src/routes.rs new file mode 100644 index 0000000..e239305 --- /dev/null +++ b/src/routes.rs @@ -0,0 +1,19 @@ +use crate::handlers::{allocations, exports, pages, partials}; +use axum::routing::{get, post}; +use axum::Router; + +pub fn router() -> Router { + Router::new() + .route("/", get(pages::index)) + .route("/healthz", get(pages::healthz)) + .route("/partials/pools/{slug}/preview", get(partials::pool_preview)) + .route("/allocations", post(allocations::create_allocation)) + .route("/allocations/{id}", get(pages::allocation_detail)) + .route( + "/allocations/{id}/release", + post(allocations::release_allocation), + ) + .route("/exports/allocations.md", get(exports::export_md)) + .route("/exports/allocations.csv", get(exports::export_csv)) + .route("/exports/allocations.json", get(exports::export_json)) +} diff --git a/src/state.rs b/src/state.rs new file mode 100644 index 0000000..9f67763 --- /dev/null +++ b/src/state.rs @@ -0,0 +1,14 @@ +use crate::config::Config; +use sqlx::SqlitePool; + +#[derive(Clone)] +pub struct AppState { + pub config: Config, + pub pool: SqlitePool, +} + +impl AppState { + pub fn new(config: Config, pool: SqlitePool) -> Self { + Self { config, pool } + } +} diff --git a/src/templates.rs b/src/templates.rs new file mode 100644 index 0000000..0841760 --- /dev/null +++ b/src/templates.rs @@ -0,0 +1,142 @@ +use crate::models::{AllocationDetail, AllocationListItem, AuditEventDisplay, Pool}; +use askama::Template; + +#[derive(Template)] +#[template(path = "base.html")] +pub struct BaseTemplate { + pub title: String, +} + +#[derive(Template)] +#[template(path = "index.html")] +pub struct IndexTemplate { + pub pools: Vec, + pub allocations: Vec, + pub page: i64, + pub total_pages: i64, + pub total_count: i64, + pub query: String, + pub pool_filter: String, + pub status_filter: String, + pub csrf_token: String, + pub flash: FlashData, +} + +#[derive(Clone, Debug)] +pub struct PoolTemplate { + pub id: i64, + pub slug: String, + pub name: String, + pub cidr: String, + pub kind: String, + pub allowed_prefixes: Vec, + pub allowed_prefixes_json: String, +} + +impl From for PoolTemplate { + fn from(p: Pool) -> Self { + let allowed: Vec = p.allowed_prefixes(); + Self { + id: p.id, + slug: p.slug.clone(), + name: p.name, + cidr: p.cidr, + kind: p.kind, + allowed_prefixes_json: serde_json::to_string(&allowed).unwrap_or_default(), + allowed_prefixes: allowed.into_iter().map(|x| x.to_string()).collect(), + } + } +} + +#[derive(Clone, Debug)] +pub struct SuccessMessage { + pub cidr: String, + pub note: String, + pub network: String, + pub broadcast: String, + pub first_host: String, + pub last_host: String, + pub usable_host_count: i32, +} + +#[derive(Clone, Debug, Default)] +pub struct FlashData { + pub has_success: bool, + pub success_cidr: String, + pub success_note: String, + pub success_network: String, + pub success_broadcast: String, + pub success_first_host: String, + pub success_last_host: String, + pub success_usable_host_count: i32, + pub has_error: bool, + pub error: String, +} + +impl From> for FlashData { + fn from(success: Option) -> Self { + match success { + Some(s) => FlashData { + has_success: true, + success_cidr: s.cidr, + success_note: s.note, + success_network: s.network, + success_broadcast: s.broadcast, + success_first_host: s.first_host, + success_last_host: s.last_host, + success_usable_host_count: s.usable_host_count, + has_error: false, + error: String::new(), + }, + None => FlashData::default(), + } + } +} + +impl FlashData { + pub fn error(message: impl Into) -> Self { + FlashData { + has_error: true, + error: message.into(), + ..Default::default() + } + } +} + +#[derive(Template)] +#[template(path = "partials/pool_preview.html")] +pub struct PoolPreviewTemplate { + pub cidr: String, + pub prefix_length: i32, + pub address_count: i32, + pub usable_host_count: i32, + pub has_error: bool, + pub error: String, +} + +#[derive(Template)] +#[template(path = "fragments/flash.html")] +pub struct FlashTemplate { + pub flash: FlashData, +} + +#[derive(Template)] +#[template(path = "fragments/allocations_table.html")] +pub struct AllocationsTableTemplate { + pub allocations: Vec, + pub page: i64, + pub total_pages: i64, + pub total_count: i64, + pub query: String, + pub pool_filter: String, + pub status_filter: String, +} + +#[derive(Template)] +#[template(path = "allocation_detail.html")] +pub struct AllocationDetailTemplate { + pub allocation: AllocationDetail, + pub audit_events: Vec, + pub csrf_token: String, + pub flash: FlashData, +} diff --git a/static/htmx.min.js b/static/htmx.min.js new file mode 100644 index 0000000..59937d7 --- /dev/null +++ b/static/htmx.min.js @@ -0,0 +1 @@ +var htmx=function(){"use strict";const Q={onLoad:null,process:null,on:null,off:null,trigger:null,ajax:null,find:null,findAll:null,closest:null,values:function(e,t){const n=cn(e,t||"post");return n.values},remove:null,addClass:null,removeClass:null,toggleClass:null,takeClass:null,swap:null,defineExtension:null,removeExtension:null,logAll:null,logNone:null,logger:null,config:{historyEnabled:true,historyCacheSize:10,refreshOnHistoryMiss:false,defaultSwapStyle:"innerHTML",defaultSwapDelay:0,defaultSettleDelay:20,includeIndicatorStyles:true,indicatorClass:"htmx-indicator",requestClass:"htmx-request",addedClass:"htmx-added",settlingClass:"htmx-settling",swappingClass:"htmx-swapping",allowEval:true,allowScriptTags:true,inlineScriptNonce:"",inlineStyleNonce:"",attributesToSettle:["class","style","width","height"],withCredentials:false,timeout:0,wsReconnectDelay:"full-jitter",wsBinaryType:"blob",disableSelector:"[hx-disable], [data-hx-disable]",scrollBehavior:"instant",defaultFocusScroll:false,getCacheBusterParam:false,globalViewTransitions:false,methodsThatUseUrlParams:["get","delete"],selfRequestsOnly:true,ignoreTitle:false,scrollIntoViewOnBoost:true,triggerSpecsCache:null,disableInheritance:false,responseHandling:[{code:"204",swap:false},{code:"[23]..",swap:true},{code:"[45]..",swap:false,error:true}],allowNestedOobSwaps:true},parseInterval:null,_:null,version:"2.0.4"};Q.onLoad=j;Q.process=kt;Q.on=ye;Q.off=be;Q.trigger=he;Q.ajax=Rn;Q.find=u;Q.findAll=x;Q.closest=g;Q.remove=z;Q.addClass=K;Q.removeClass=G;Q.toggleClass=W;Q.takeClass=Z;Q.swap=$e;Q.defineExtension=Fn;Q.removeExtension=Bn;Q.logAll=V;Q.logNone=_;Q.parseInterval=d;Q._=e;const n={addTriggerHandler:St,bodyContains:le,canAccessLocalStorage:B,findThisElement:Se,filterValues:hn,swap:$e,hasAttribute:s,getAttributeValue:te,getClosestAttributeValue:re,getClosestMatch:o,getExpressionVars:En,getHeaders:fn,getInputValues:cn,getInternalData:ie,getSwapSpecification:gn,getTriggerSpecs:st,getTarget:Ee,makeFragment:P,mergeObjects:ce,makeSettleInfo:xn,oobSwap:He,querySelectorExt:ae,settleImmediately:Kt,shouldCancel:ht,triggerEvent:he,triggerErrorEvent:fe,withExtensions:Ft};const r=["get","post","put","delete","patch"];const H=r.map(function(e){return"[hx-"+e+"], [data-hx-"+e+"]"}).join(", ");function d(e){if(e==undefined){return undefined}let t=NaN;if(e.slice(-2)=="ms"){t=parseFloat(e.slice(0,-2))}else if(e.slice(-1)=="s"){t=parseFloat(e.slice(0,-1))*1e3}else if(e.slice(-1)=="m"){t=parseFloat(e.slice(0,-1))*1e3*60}else{t=parseFloat(e)}return isNaN(t)?undefined:t}function ee(e,t){return e instanceof Element&&e.getAttribute(t)}function s(e,t){return!!e.hasAttribute&&(e.hasAttribute(t)||e.hasAttribute("data-"+t))}function te(e,t){return ee(e,t)||ee(e,"data-"+t)}function c(e){const t=e.parentElement;if(!t&&e.parentNode instanceof ShadowRoot)return e.parentNode;return t}function ne(){return document}function m(e,t){return e.getRootNode?e.getRootNode({composed:t}):ne()}function o(e,t){while(e&&!t(e)){e=c(e)}return e||null}function i(e,t,n){const r=te(t,n);const o=te(t,"hx-disinherit");var i=te(t,"hx-inherit");if(e!==t){if(Q.config.disableInheritance){if(i&&(i==="*"||i.split(" ").indexOf(n)>=0)){return r}else{return null}}if(o&&(o==="*"||o.split(" ").indexOf(n)>=0)){return"unset"}}return r}function re(t,n){let r=null;o(t,function(e){return!!(r=i(t,ue(e),n))});if(r!=="unset"){return r}}function h(e,t){const n=e instanceof Element&&(e.matches||e.matchesSelector||e.msMatchesSelector||e.mozMatchesSelector||e.webkitMatchesSelector||e.oMatchesSelector);return!!n&&n.call(e,t)}function T(e){const t=/<([a-z][^\/\0>\x20\t\r\n\f]*)/i;const n=t.exec(e);if(n){return n[1].toLowerCase()}else{return""}}function q(e){const t=new DOMParser;return t.parseFromString(e,"text/html")}function L(e,t){while(t.childNodes.length>0){e.append(t.childNodes[0])}}function A(e){const t=ne().createElement("script");se(e.attributes,function(e){t.setAttribute(e.name,e.value)});t.textContent=e.textContent;t.async=false;if(Q.config.inlineScriptNonce){t.nonce=Q.config.inlineScriptNonce}return t}function N(e){return e.matches("script")&&(e.type==="text/javascript"||e.type==="module"||e.type==="")}function I(e){Array.from(e.querySelectorAll("script")).forEach(e=>{if(N(e)){const t=A(e);const n=e.parentNode;try{n.insertBefore(t,e)}catch(e){O(e)}finally{e.remove()}}})}function P(e){const t=e.replace(/]*)?>[\s\S]*?<\/head>/i,"");const n=T(t);let r;if(n==="html"){r=new DocumentFragment;const i=q(e);L(r,i.body);r.title=i.title}else if(n==="body"){r=new DocumentFragment;const i=q(t);L(r,i.body);r.title=i.title}else{const i=q('");r=i.querySelector("template").content;r.title=i.title;var o=r.querySelector("title");if(o&&o.parentNode===r){o.remove();r.title=o.innerText}}if(r){if(Q.config.allowScriptTags){I(r)}else{r.querySelectorAll("script").forEach(e=>e.remove())}}return r}function oe(e){if(e){e()}}function t(e,t){return Object.prototype.toString.call(e)==="[object "+t+"]"}function k(e){return typeof e==="function"}function D(e){return t(e,"Object")}function ie(e){const t="htmx-internal-data";let n=e[t];if(!n){n=e[t]={}}return n}function M(t){const n=[];if(t){for(let e=0;e=0}function le(e){return e.getRootNode({composed:true})===document}function F(e){return e.trim().split(/\s+/)}function ce(e,t){for(const n in t){if(t.hasOwnProperty(n)){e[n]=t[n]}}return e}function S(e){try{return JSON.parse(e)}catch(e){O(e);return null}}function B(){const e="htmx:localStorageTest";try{localStorage.setItem(e,e);localStorage.removeItem(e);return true}catch(e){return false}}function U(t){try{const e=new URL(t);if(e){t=e.pathname+e.search}if(!/^\/$/.test(t)){t=t.replace(/\/+$/,"")}return t}catch(e){return t}}function e(e){return vn(ne().body,function(){return eval(e)})}function j(t){const e=Q.on("htmx:load",function(e){t(e.detail.elt)});return e}function V(){Q.logger=function(e,t,n){if(console){console.log(t,e,n)}}}function _(){Q.logger=null}function u(e,t){if(typeof e!=="string"){return e.querySelector(t)}else{return u(ne(),e)}}function x(e,t){if(typeof e!=="string"){return e.querySelectorAll(t)}else{return x(ne(),e)}}function E(){return window}function z(e,t){e=y(e);if(t){E().setTimeout(function(){z(e);e=null},t)}else{c(e).removeChild(e)}}function ue(e){return e instanceof Element?e:null}function $(e){return e instanceof HTMLElement?e:null}function J(e){return typeof e==="string"?e:null}function f(e){return e instanceof Element||e instanceof Document||e instanceof DocumentFragment?e:null}function K(e,t,n){e=ue(y(e));if(!e){return}if(n){E().setTimeout(function(){K(e,t);e=null},n)}else{e.classList&&e.classList.add(t)}}function G(e,t,n){let r=ue(y(e));if(!r){return}if(n){E().setTimeout(function(){G(r,t);r=null},n)}else{if(r.classList){r.classList.remove(t);if(r.classList.length===0){r.removeAttribute("class")}}}}function W(e,t){e=y(e);e.classList.toggle(t)}function Z(e,t){e=y(e);se(e.parentElement.children,function(e){G(e,t)});K(ue(e),t)}function g(e,t){e=ue(y(e));if(e&&e.closest){return e.closest(t)}else{do{if(e==null||h(e,t)){return e}}while(e=e&&ue(c(e)));return null}}function l(e,t){return e.substring(0,t.length)===t}function Y(e,t){return e.substring(e.length-t.length)===t}function ge(e){const t=e.trim();if(l(t,"<")&&Y(t,"/>")){return t.substring(1,t.length-2)}else{return t}}function p(t,r,n){if(r.indexOf("global ")===0){return p(t,r.slice(7),true)}t=y(t);const o=[];{let t=0;let n=0;for(let e=0;e"){t--}}if(n0){const r=ge(o.shift());let e;if(r.indexOf("closest ")===0){e=g(ue(t),ge(r.substr(8)))}else if(r.indexOf("find ")===0){e=u(f(t),ge(r.substr(5)))}else if(r==="next"||r==="nextElementSibling"){e=ue(t).nextElementSibling}else if(r.indexOf("next ")===0){e=pe(t,ge(r.substr(5)),!!n)}else if(r==="previous"||r==="previousElementSibling"){e=ue(t).previousElementSibling}else if(r.indexOf("previous ")===0){e=me(t,ge(r.substr(9)),!!n)}else if(r==="document"){e=document}else if(r==="window"){e=window}else if(r==="body"){e=document.body}else if(r==="root"){e=m(t,!!n)}else if(r==="host"){e=t.getRootNode().host}else{s.push(r)}if(e){i.push(e)}}if(s.length>0){const e=s.join(",");const c=f(m(t,!!n));i.push(...M(c.querySelectorAll(e)))}return i}var pe=function(t,e,n){const r=f(m(t,n)).querySelectorAll(e);for(let e=0;e=0;e--){const o=r[e];if(o.compareDocumentPosition(t)===Node.DOCUMENT_POSITION_FOLLOWING){return o}}};function ae(e,t){if(typeof e!=="string"){return p(e,t)[0]}else{return p(ne().body,e)[0]}}function y(e,t){if(typeof e==="string"){return u(f(t)||document,e)}else{return e}}function xe(e,t,n,r){if(k(t)){return{target:ne().body,event:J(e),listener:t,options:n}}else{return{target:y(e),event:J(t),listener:n,options:r}}}function ye(t,n,r,o){Vn(function(){const e=xe(t,n,r,o);e.target.addEventListener(e.event,e.listener,e.options)});const e=k(n);return e?n:r}function be(t,n,r){Vn(function(){const e=xe(t,n,r);e.target.removeEventListener(e.event,e.listener)});return k(n)?n:r}const ve=ne().createElement("output");function we(e,t){const n=re(e,t);if(n){if(n==="this"){return[Se(e,t)]}else{const r=p(e,n);if(r.length===0){O('The selector "'+n+'" on '+t+" returned no matches!");return[ve]}else{return r}}}}function Se(e,t){return ue(o(e,function(e){return te(ue(e),t)!=null}))}function Ee(e){const t=re(e,"hx-target");if(t){if(t==="this"){return Se(e,"hx-target")}else{return ae(e,t)}}else{const n=ie(e);if(n.boosted){return ne().body}else{return e}}}function Ce(t){const n=Q.config.attributesToSettle;for(let e=0;e0){s=e.substring(0,e.indexOf(":"));n=e.substring(e.indexOf(":")+1)}else{s=e}o.removeAttribute("hx-swap-oob");o.removeAttribute("data-hx-swap-oob");const r=p(t,n,false);if(r){se(r,function(e){let t;const n=o.cloneNode(true);t=ne().createDocumentFragment();t.appendChild(n);if(!Re(s,e)){t=f(n)}const r={shouldSwap:true,target:e,fragment:t};if(!he(e,"htmx:oobBeforeSwap",r))return;e=r.target;if(r.shouldSwap){qe(t);_e(s,e,e,t,i);Te()}se(i.elts,function(e){he(e,"htmx:oobAfterSwap",r)})});o.parentNode.removeChild(o)}else{o.parentNode.removeChild(o);fe(ne().body,"htmx:oobErrorNoTarget",{content:o})}return e}function Te(){const e=u("#--htmx-preserve-pantry--");if(e){for(const t of[...e.children]){const n=u("#"+t.id);n.parentNode.moveBefore(t,n);n.remove()}e.remove()}}function qe(e){se(x(e,"[hx-preserve], [data-hx-preserve]"),function(e){const t=te(e,"id");const n=ne().getElementById(t);if(n!=null){if(e.moveBefore){let e=u("#--htmx-preserve-pantry--");if(e==null){ne().body.insertAdjacentHTML("afterend","
");e=u("#--htmx-preserve-pantry--")}e.moveBefore(n,null)}else{e.parentNode.replaceChild(n,e)}}})}function Le(l,e,c){se(e.querySelectorAll("[id]"),function(t){const n=ee(t,"id");if(n&&n.length>0){const r=n.replace("'","\\'");const o=t.tagName.replace(":","\\:");const e=f(l);const i=e&&e.querySelector(o+"[id='"+r+"']");if(i&&i!==e){const s=t.cloneNode();Oe(t,i);c.tasks.push(function(){Oe(t,s)})}}})}function Ae(e){return function(){G(e,Q.config.addedClass);kt(ue(e));Ne(f(e));he(e,"htmx:load")}}function Ne(e){const t="[autofocus]";const n=$(h(e,t)?e:e.querySelector(t));if(n!=null){n.focus()}}function a(e,t,n,r){Le(e,n,r);while(n.childNodes.length>0){const o=n.firstChild;K(ue(o),Q.config.addedClass);e.insertBefore(o,t);if(o.nodeType!==Node.TEXT_NODE&&o.nodeType!==Node.COMMENT_NODE){r.tasks.push(Ae(o))}}}function Ie(e,t){let n=0;while(n0}function $e(e,t,r,o){if(!o){o={}}e=y(e);const i=o.contextElement?m(o.contextElement,false):ne();const n=document.activeElement;let s={};try{s={elt:n,start:n?n.selectionStart:null,end:n?n.selectionEnd:null}}catch(e){}const l=xn(e);if(r.swapStyle==="textContent"){e.textContent=t}else{let n=P(t);l.title=n.title;if(o.selectOOB){const u=o.selectOOB.split(",");for(let t=0;t0){E().setTimeout(c,r.settleDelay)}else{c()}}function Je(e,t,n){const r=e.getResponseHeader(t);if(r.indexOf("{")===0){const o=S(r);for(const i in o){if(o.hasOwnProperty(i)){let e=o[i];if(D(e)){n=e.target!==undefined?e.target:n}else{e={value:e}}he(n,i,e)}}}else{const s=r.split(",");for(let e=0;e0){const s=o[0];if(s==="]"){e--;if(e===0){if(n===null){t=t+"true"}o.shift();t+=")})";try{const l=vn(r,function(){return Function(t)()},function(){return true});l.source=t;return l}catch(e){fe(ne().body,"htmx:syntax:error",{error:e,source:t});return null}}}else if(s==="["){e++}if(tt(s,n,i)){t+="(("+i+"."+s+") ? ("+i+"."+s+") : (window."+s+"))"}else{t=t+s}n=o.shift()}}}function C(e,t){let n="";while(e.length>0&&!t.test(e[0])){n+=e.shift()}return n}function rt(e){let t;if(e.length>0&&Ye.test(e[0])){e.shift();t=C(e,Qe).trim();e.shift()}else{t=C(e,v)}return t}const ot="input, textarea, select";function it(e,t,n){const r=[];const o=et(t);do{C(o,w);const l=o.length;const c=C(o,/[,\[\s]/);if(c!==""){if(c==="every"){const u={trigger:"every"};C(o,w);u.pollInterval=d(C(o,/[,\[\s]/));C(o,w);var i=nt(e,o,"event");if(i){u.eventFilter=i}r.push(u)}else{const a={trigger:c};var i=nt(e,o,"event");if(i){a.eventFilter=i}C(o,w);while(o.length>0&&o[0]!==","){const f=o.shift();if(f==="changed"){a.changed=true}else if(f==="once"){a.once=true}else if(f==="consume"){a.consume=true}else if(f==="delay"&&o[0]===":"){o.shift();a.delay=d(C(o,v))}else if(f==="from"&&o[0]===":"){o.shift();if(Ye.test(o[0])){var s=rt(o)}else{var s=C(o,v);if(s==="closest"||s==="find"||s==="next"||s==="previous"){o.shift();const h=rt(o);if(h.length>0){s+=" "+h}}}a.from=s}else if(f==="target"&&o[0]===":"){o.shift();a.target=rt(o)}else if(f==="throttle"&&o[0]===":"){o.shift();a.throttle=d(C(o,v))}else if(f==="queue"&&o[0]===":"){o.shift();a.queue=C(o,v)}else if(f==="root"&&o[0]===":"){o.shift();a[f]=rt(o)}else if(f==="threshold"&&o[0]===":"){o.shift();a[f]=C(o,v)}else{fe(e,"htmx:syntax:error",{token:o.shift()})}C(o,w)}r.push(a)}}if(o.length===l){fe(e,"htmx:syntax:error",{token:o.shift()})}C(o,w)}while(o[0]===","&&o.shift());if(n){n[t]=r}return r}function st(e){const t=te(e,"hx-trigger");let n=[];if(t){const r=Q.config.triggerSpecsCache;n=r&&r[t]||it(e,t,r)}if(n.length>0){return n}else if(h(e,"form")){return[{trigger:"submit"}]}else if(h(e,'input[type="button"], input[type="submit"]')){return[{trigger:"click"}]}else if(h(e,ot)){return[{trigger:"change"}]}else{return[{trigger:"click"}]}}function lt(e){ie(e).cancelled=true}function ct(e,t,n){const r=ie(e);r.timeout=E().setTimeout(function(){if(le(e)&&r.cancelled!==true){if(!gt(n,e,Mt("hx:poll:trigger",{triggerSpec:n,target:e}))){t(e)}ct(e,t,n)}},n.pollInterval)}function ut(e){return location.hostname===e.hostname&&ee(e,"href")&&ee(e,"href").indexOf("#")!==0}function at(e){return g(e,Q.config.disableSelector)}function ft(t,n,e){if(t instanceof HTMLAnchorElement&&ut(t)&&(t.target===""||t.target==="_self")||t.tagName==="FORM"&&String(ee(t,"method")).toLowerCase()!=="dialog"){n.boosted=true;let r,o;if(t.tagName==="A"){r="get";o=ee(t,"href")}else{const i=ee(t,"method");r=i?i.toLowerCase():"get";o=ee(t,"action");if(o==null||o===""){o=ne().location.href}if(r==="get"&&o.includes("?")){o=o.replace(/\?[^#]+/,"")}}e.forEach(function(e){pt(t,function(e,t){const n=ue(e);if(at(n)){b(n);return}de(r,o,n,t)},n,e,true)})}}function ht(e,t){const n=ue(t);if(!n){return false}if(e.type==="submit"||e.type==="click"){if(n.tagName==="FORM"){return true}if(h(n,'input[type="submit"], button')&&(h(n,"[form]")||g(n,"form")!==null)){return true}if(n instanceof HTMLAnchorElement&&n.href&&(n.getAttribute("href")==="#"||n.getAttribute("href").indexOf("#")!==0)){return true}}return false}function dt(e,t){return ie(e).boosted&&e instanceof HTMLAnchorElement&&t.type==="click"&&(t.ctrlKey||t.metaKey)}function gt(e,t,n){const r=e.eventFilter;if(r){try{return r.call(t,n)!==true}catch(e){const o=r.source;fe(ne().body,"htmx:eventFilter:error",{error:e,source:o});return true}}return false}function pt(l,c,e,u,a){const f=ie(l);let t;if(u.from){t=p(l,u.from)}else{t=[l]}if(u.changed){if(!("lastValue"in f)){f.lastValue=new WeakMap}t.forEach(function(e){if(!f.lastValue.has(u)){f.lastValue.set(u,new WeakMap)}f.lastValue.get(u).set(e,e.value)})}se(t,function(i){const s=function(e){if(!le(l)){i.removeEventListener(u.trigger,s);return}if(dt(l,e)){return}if(a||ht(e,l)){e.preventDefault()}if(gt(u,l,e)){return}const t=ie(e);t.triggerSpec=u;if(t.handledFor==null){t.handledFor=[]}if(t.handledFor.indexOf(l)<0){t.handledFor.push(l);if(u.consume){e.stopPropagation()}if(u.target&&e.target){if(!h(ue(e.target),u.target)){return}}if(u.once){if(f.triggeredOnce){return}else{f.triggeredOnce=true}}if(u.changed){const n=event.target;const r=n.value;const o=f.lastValue.get(u);if(o.has(n)&&o.get(n)===r){return}o.set(n,r)}if(f.delayed){clearTimeout(f.delayed)}if(f.throttle){return}if(u.throttle>0){if(!f.throttle){he(l,"htmx:trigger");c(l,e);f.throttle=E().setTimeout(function(){f.throttle=null},u.throttle)}}else if(u.delay>0){f.delayed=E().setTimeout(function(){he(l,"htmx:trigger");c(l,e)},u.delay)}else{he(l,"htmx:trigger");c(l,e)}}};if(e.listenerInfos==null){e.listenerInfos=[]}e.listenerInfos.push({trigger:u.trigger,listener:s,on:i});i.addEventListener(u.trigger,s)})}let mt=false;let xt=null;function yt(){if(!xt){xt=function(){mt=true};window.addEventListener("scroll",xt);window.addEventListener("resize",xt);setInterval(function(){if(mt){mt=false;se(ne().querySelectorAll("[hx-trigger*='revealed'],[data-hx-trigger*='revealed']"),function(e){bt(e)})}},200)}}function bt(e){if(!s(e,"data-hx-revealed")&&X(e)){e.setAttribute("data-hx-revealed","true");const t=ie(e);if(t.initHash){he(e,"revealed")}else{e.addEventListener("htmx:afterProcessNode",function(){he(e,"revealed")},{once:true})}}}function vt(e,t,n,r){const o=function(){if(!n.loaded){n.loaded=true;he(e,"htmx:trigger");t(e)}};if(r>0){E().setTimeout(o,r)}else{o()}}function wt(t,n,e){let i=false;se(r,function(r){if(s(t,"hx-"+r)){const o=te(t,"hx-"+r);i=true;n.path=o;n.verb=r;e.forEach(function(e){St(t,e,n,function(e,t){const n=ue(e);if(g(n,Q.config.disableSelector)){b(n);return}de(r,o,n,t)})})}});return i}function St(r,e,t,n){if(e.trigger==="revealed"){yt();pt(r,n,t,e);bt(ue(r))}else if(e.trigger==="intersect"){const o={};if(e.root){o.root=ae(r,e.root)}if(e.threshold){o.threshold=parseFloat(e.threshold)}const i=new IntersectionObserver(function(t){for(let e=0;e0){t.polling=true;ct(ue(r),n,e)}else{pt(r,n,t,e)}}function Et(e){const t=ue(e);if(!t){return false}const n=t.attributes;for(let e=0;e", "+e).join(""));return o}else{return[]}}function Tt(e){const t=g(ue(e.target),"button, input[type='submit']");const n=Lt(e);if(n){n.lastButtonClicked=t}}function qt(e){const t=Lt(e);if(t){t.lastButtonClicked=null}}function Lt(e){const t=g(ue(e.target),"button, input[type='submit']");if(!t){return}const n=y("#"+ee(t,"form"),t.getRootNode())||g(t,"form");if(!n){return}return ie(n)}function At(e){e.addEventListener("click",Tt);e.addEventListener("focusin",Tt);e.addEventListener("focusout",qt)}function Nt(t,e,n){const r=ie(t);if(!Array.isArray(r.onHandlers)){r.onHandlers=[]}let o;const i=function(e){vn(t,function(){if(at(t)){return}if(!o){o=new Function("event",n)}o.call(t,e)})};t.addEventListener(e,i);r.onHandlers.push({event:e,listener:i})}function It(t){ke(t);for(let e=0;eQ.config.historyCacheSize){i.shift()}while(i.length>0){try{localStorage.setItem("htmx-history-cache",JSON.stringify(i));break}catch(e){fe(ne().body,"htmx:historyCacheError",{cause:e,cache:i});i.shift()}}}function Vt(t){if(!B()){return null}t=U(t);const n=S(localStorage.getItem("htmx-history-cache"))||[];for(let e=0;e=200&&this.status<400){he(ne().body,"htmx:historyCacheMissLoad",i);const e=P(this.response);const t=e.querySelector("[hx-history-elt],[data-hx-history-elt]")||e;const n=Ut();const r=xn(n);kn(e.title);qe(e);Ve(n,t,r);Te();Kt(r.tasks);Bt=o;he(ne().body,"htmx:historyRestore",{path:o,cacheMiss:true,serverResponse:this.response})}else{fe(ne().body,"htmx:historyCacheMissLoadError",i)}};e.send()}function Wt(e){zt();e=e||location.pathname+location.search;const t=Vt(e);if(t){const n=P(t.content);const r=Ut();const o=xn(r);kn(t.title);qe(n);Ve(r,n,o);Te();Kt(o.tasks);E().setTimeout(function(){window.scrollTo(0,t.scroll)},0);Bt=e;he(ne().body,"htmx:historyRestore",{path:e,item:t})}else{if(Q.config.refreshOnHistoryMiss){window.location.reload(true)}else{Gt(e)}}}function Zt(e){let t=we(e,"hx-indicator");if(t==null){t=[e]}se(t,function(e){const t=ie(e);t.requestCount=(t.requestCount||0)+1;e.classList.add.call(e.classList,Q.config.requestClass)});return t}function Yt(e){let t=we(e,"hx-disabled-elt");if(t==null){t=[]}se(t,function(e){const t=ie(e);t.requestCount=(t.requestCount||0)+1;e.setAttribute("disabled","");e.setAttribute("data-disabled-by-htmx","")});return t}function Qt(e,t){se(e.concat(t),function(e){const t=ie(e);t.requestCount=(t.requestCount||1)-1});se(e,function(e){const t=ie(e);if(t.requestCount===0){e.classList.remove.call(e.classList,Q.config.requestClass)}});se(t,function(e){const t=ie(e);if(t.requestCount===0){e.removeAttribute("disabled");e.removeAttribute("data-disabled-by-htmx")}})}function en(t,n){for(let e=0;en.indexOf(e)<0)}else{e=e.filter(e=>e!==n)}r.delete(t);se(e,e=>r.append(t,e))}}function on(t,n,r,o,i){if(o==null||en(t,o)){return}else{t.push(o)}if(tn(o)){const s=ee(o,"name");let e=o.value;if(o instanceof HTMLSelectElement&&o.multiple){e=M(o.querySelectorAll("option:checked")).map(function(e){return e.value})}if(o instanceof HTMLInputElement&&o.files){e=M(o.files)}nn(s,e,n);if(i){sn(o,r)}}if(o instanceof HTMLFormElement){se(o.elements,function(e){if(t.indexOf(e)>=0){rn(e.name,e.value,n)}else{t.push(e)}if(i){sn(e,r)}});new FormData(o).forEach(function(e,t){if(e instanceof File&&e.name===""){return}nn(t,e,n)})}}function sn(e,t){const n=e;if(n.willValidate){he(n,"htmx:validation:validate");if(!n.checkValidity()){t.push({elt:n,message:n.validationMessage,validity:n.validity});he(n,"htmx:validation:failed",{message:n.validationMessage,validity:n.validity})}}}function ln(n,e){for(const t of e.keys()){n.delete(t)}e.forEach(function(e,t){n.append(t,e)});return n}function cn(e,t){const n=[];const r=new FormData;const o=new FormData;const i=[];const s=ie(e);if(s.lastButtonClicked&&!le(s.lastButtonClicked)){s.lastButtonClicked=null}let l=e instanceof HTMLFormElement&&e.noValidate!==true||te(e,"hx-validate")==="true";if(s.lastButtonClicked){l=l&&s.lastButtonClicked.formNoValidate!==true}if(t!=="get"){on(n,o,i,g(e,"form"),l)}on(n,r,i,e,l);if(s.lastButtonClicked||e.tagName==="BUTTON"||e.tagName==="INPUT"&&ee(e,"type")==="submit"){const u=s.lastButtonClicked||e;const a=ee(u,"name");nn(a,u.value,o)}const c=we(e,"hx-include");se(c,function(e){on(n,r,i,ue(e),l);if(!h(e,"form")){se(f(e).querySelectorAll(ot),function(e){on(n,r,i,e,l)})}});ln(r,o);return{errors:i,formData:r,values:An(r)}}function un(e,t,n){if(e!==""){e+="&"}if(String(n)==="[object Object]"){n=JSON.stringify(n)}const r=encodeURIComponent(n);e+=encodeURIComponent(t)+"="+r;return e}function an(e){e=qn(e);let n="";e.forEach(function(e,t){n=un(n,t,e)});return n}function fn(e,t,n){const r={"HX-Request":"true","HX-Trigger":ee(e,"id"),"HX-Trigger-Name":ee(e,"name"),"HX-Target":te(t,"id"),"HX-Current-URL":ne().location.href};bn(e,"hx-headers",false,r);if(n!==undefined){r["HX-Prompt"]=n}if(ie(e).boosted){r["HX-Boosted"]="true"}return r}function hn(n,e){const t=re(e,"hx-params");if(t){if(t==="none"){return new FormData}else if(t==="*"){return n}else if(t.indexOf("not ")===0){se(t.slice(4).split(","),function(e){e=e.trim();n.delete(e)});return n}else{const r=new FormData;se(t.split(","),function(t){t=t.trim();if(n.has(t)){n.getAll(t).forEach(function(e){r.append(t,e)})}});return r}}else{return n}}function dn(e){return!!ee(e,"href")&&ee(e,"href").indexOf("#")>=0}function gn(e,t){const n=t||re(e,"hx-swap");const r={swapStyle:ie(e).boosted?"innerHTML":Q.config.defaultSwapStyle,swapDelay:Q.config.defaultSwapDelay,settleDelay:Q.config.defaultSettleDelay};if(Q.config.scrollIntoViewOnBoost&&ie(e).boosted&&!dn(e)){r.show="top"}if(n){const s=F(n);if(s.length>0){for(let e=0;e0?o.join(":"):null;r.scroll=u;r.scrollTarget=i}else if(l.indexOf("show:")===0){const a=l.slice(5);var o=a.split(":");const f=o.pop();var i=o.length>0?o.join(":"):null;r.show=f;r.showTarget=i}else if(l.indexOf("focus-scroll:")===0){const h=l.slice("focus-scroll:".length);r.focusScroll=h=="true"}else if(e==0){r.swapStyle=l}else{O("Unknown modifier in hx-swap: "+l)}}}}return r}function pn(e){return re(e,"hx-encoding")==="multipart/form-data"||h(e,"form")&&ee(e,"enctype")==="multipart/form-data"}function mn(t,n,r){let o=null;Ft(n,function(e){if(o==null){o=e.encodeParameters(t,r,n)}});if(o!=null){return o}else{if(pn(n)){return ln(new FormData,qn(r))}else{return an(r)}}}function xn(e){return{tasks:[],elts:[e]}}function yn(e,t){const n=e[0];const r=e[e.length-1];if(t.scroll){var o=null;if(t.scrollTarget){o=ue(ae(n,t.scrollTarget))}if(t.scroll==="top"&&(n||o)){o=o||n;o.scrollTop=0}if(t.scroll==="bottom"&&(r||o)){o=o||r;o.scrollTop=o.scrollHeight}}if(t.show){var o=null;if(t.showTarget){let e=t.showTarget;if(t.showTarget==="window"){e="body"}o=ue(ae(n,e))}if(t.show==="top"&&(n||o)){o=o||n;o.scrollIntoView({block:"start",behavior:Q.config.scrollBehavior})}if(t.show==="bottom"&&(r||o)){o=o||r;o.scrollIntoView({block:"end",behavior:Q.config.scrollBehavior})}}}function bn(r,e,o,i){if(i==null){i={}}if(r==null){return i}const s=te(r,e);if(s){let e=s.trim();let t=o;if(e==="unset"){return null}if(e.indexOf("javascript:")===0){e=e.slice(11);t=true}else if(e.indexOf("js:")===0){e=e.slice(3);t=true}if(e.indexOf("{")!==0){e="{"+e+"}"}let n;if(t){n=vn(r,function(){return Function("return ("+e+")")()},{})}else{n=S(e)}for(const l in n){if(n.hasOwnProperty(l)){if(i[l]==null){i[l]=n[l]}}}}return bn(ue(c(r)),e,o,i)}function vn(e,t,n){if(Q.config.allowEval){return t()}else{fe(e,"htmx:evalDisallowedError");return n}}function wn(e,t){return bn(e,"hx-vars",true,t)}function Sn(e,t){return bn(e,"hx-vals",false,t)}function En(e){return ce(wn(e),Sn(e))}function Cn(t,n,r){if(r!==null){try{t.setRequestHeader(n,r)}catch(e){t.setRequestHeader(n,encodeURIComponent(r));t.setRequestHeader(n+"-URI-AutoEncoded","true")}}}function On(t){if(t.responseURL&&typeof URL!=="undefined"){try{const e=new URL(t.responseURL);return e.pathname+e.search}catch(e){fe(ne().body,"htmx:badResponseUrl",{url:t.responseURL})}}}function R(e,t){return t.test(e.getAllResponseHeaders())}function Rn(t,n,r){t=t.toLowerCase();if(r){if(r instanceof Element||typeof r==="string"){return de(t,n,null,null,{targetOverride:y(r)||ve,returnPromise:true})}else{let e=y(r.target);if(r.target&&!e||r.source&&!e&&!y(r.source)){e=ve}return de(t,n,y(r.source),r.event,{handler:r.handler,headers:r.headers,values:r.values,targetOverride:e,swapOverride:r.swap,select:r.select,returnPromise:true})}}else{return de(t,n,null,null,{returnPromise:true})}}function Hn(e){const t=[];while(e){t.push(e);e=e.parentElement}return t}function Tn(e,t,n){let r;let o;if(typeof URL==="function"){o=new URL(t,document.location.href);const i=document.location.origin;r=i===o.origin}else{o=t;r=l(t,document.location.origin)}if(Q.config.selfRequestsOnly){if(!r){return false}}return he(e,"htmx:validateUrl",ce({url:o,sameHost:r},n))}function qn(e){if(e instanceof FormData)return e;const t=new FormData;for(const n in e){if(e.hasOwnProperty(n)){if(e[n]&&typeof e[n].forEach==="function"){e[n].forEach(function(e){t.append(n,e)})}else if(typeof e[n]==="object"&&!(e[n]instanceof Blob)){t.append(n,JSON.stringify(e[n]))}else{t.append(n,e[n])}}}return t}function Ln(r,o,e){return new Proxy(e,{get:function(t,e){if(typeof e==="number")return t[e];if(e==="length")return t.length;if(e==="push"){return function(e){t.push(e);r.append(o,e)}}if(typeof t[e]==="function"){return function(){t[e].apply(t,arguments);r.delete(o);t.forEach(function(e){r.append(o,e)})}}if(t[e]&&t[e].length===1){return t[e][0]}else{return t[e]}},set:function(e,t,n){e[t]=n;r.delete(o);e.forEach(function(e){r.append(o,e)});return true}})}function An(o){return new Proxy(o,{get:function(e,t){if(typeof t==="symbol"){const r=Reflect.get(e,t);if(typeof r==="function"){return function(){return r.apply(o,arguments)}}else{return r}}if(t==="toJSON"){return()=>Object.fromEntries(o)}if(t in e){if(typeof e[t]==="function"){return function(){return o[t].apply(o,arguments)}}else{return e[t]}}const n=o.getAll(t);if(n.length===0){return undefined}else if(n.length===1){return n[0]}else{return Ln(e,t,n)}},set:function(t,n,e){if(typeof n!=="string"){return false}t.delete(n);if(e&&typeof e.forEach==="function"){e.forEach(function(e){t.append(n,e)})}else if(typeof e==="object"&&!(e instanceof Blob)){t.append(n,JSON.stringify(e))}else{t.append(n,e)}return true},deleteProperty:function(e,t){if(typeof t==="string"){e.delete(t)}return true},ownKeys:function(e){return Reflect.ownKeys(Object.fromEntries(e))},getOwnPropertyDescriptor:function(e,t){return Reflect.getOwnPropertyDescriptor(Object.fromEntries(e),t)}})}function de(t,n,r,o,i,D){let s=null;let l=null;i=i!=null?i:{};if(i.returnPromise&&typeof Promise!=="undefined"){var e=new Promise(function(e,t){s=e;l=t})}if(r==null){r=ne().body}const M=i.handler||Dn;const X=i.select||null;if(!le(r)){oe(s);return e}const c=i.targetOverride||ue(Ee(r));if(c==null||c==ve){fe(r,"htmx:targetError",{target:te(r,"hx-target")});oe(l);return e}let u=ie(r);const a=u.lastButtonClicked;if(a){const L=ee(a,"formaction");if(L!=null){n=L}const A=ee(a,"formmethod");if(A!=null){if(A.toLowerCase()!=="dialog"){t=A}}}const f=re(r,"hx-confirm");if(D===undefined){const K=function(e){return de(t,n,r,o,i,!!e)};const G={target:c,elt:r,path:n,verb:t,triggeringEvent:o,etc:i,issueRequest:K,question:f};if(he(r,"htmx:confirm",G)===false){oe(s);return e}}let h=r;let d=re(r,"hx-sync");let g=null;let F=false;if(d){const N=d.split(":");const I=N[0].trim();if(I==="this"){h=Se(r,"hx-sync")}else{h=ue(ae(r,I))}d=(N[1]||"drop").trim();u=ie(h);if(d==="drop"&&u.xhr&&u.abortable!==true){oe(s);return e}else if(d==="abort"){if(u.xhr){oe(s);return e}else{F=true}}else if(d==="replace"){he(h,"htmx:abort")}else if(d.indexOf("queue")===0){const W=d.split(" ");g=(W[1]||"last").trim()}}if(u.xhr){if(u.abortable){he(h,"htmx:abort")}else{if(g==null){if(o){const P=ie(o);if(P&&P.triggerSpec&&P.triggerSpec.queue){g=P.triggerSpec.queue}}if(g==null){g="last"}}if(u.queuedRequests==null){u.queuedRequests=[]}if(g==="first"&&u.queuedRequests.length===0){u.queuedRequests.push(function(){de(t,n,r,o,i)})}else if(g==="all"){u.queuedRequests.push(function(){de(t,n,r,o,i)})}else if(g==="last"){u.queuedRequests=[];u.queuedRequests.push(function(){de(t,n,r,o,i)})}oe(s);return e}}const p=new XMLHttpRequest;u.xhr=p;u.abortable=F;const m=function(){u.xhr=null;u.abortable=false;if(u.queuedRequests!=null&&u.queuedRequests.length>0){const e=u.queuedRequests.shift();e()}};const B=re(r,"hx-prompt");if(B){var x=prompt(B);if(x===null||!he(r,"htmx:prompt",{prompt:x,target:c})){oe(s);m();return e}}if(f&&!D){if(!confirm(f)){oe(s);m();return e}}let y=fn(r,c,x);if(t!=="get"&&!pn(r)){y["Content-Type"]="application/x-www-form-urlencoded"}if(i.headers){y=ce(y,i.headers)}const U=cn(r,t);let b=U.errors;const j=U.formData;if(i.values){ln(j,qn(i.values))}const V=qn(En(r));const v=ln(j,V);let w=hn(v,r);if(Q.config.getCacheBusterParam&&t==="get"){w.set("org.htmx.cache-buster",ee(c,"id")||"true")}if(n==null||n===""){n=ne().location.href}const S=bn(r,"hx-request");const _=ie(r).boosted;let E=Q.config.methodsThatUseUrlParams.indexOf(t)>=0;const C={boosted:_,useUrlParams:E,formData:w,parameters:An(w),unfilteredFormData:v,unfilteredParameters:An(v),headers:y,target:c,verb:t,errors:b,withCredentials:i.credentials||S.credentials||Q.config.withCredentials,timeout:i.timeout||S.timeout||Q.config.timeout,path:n,triggeringEvent:o};if(!he(r,"htmx:configRequest",C)){oe(s);m();return e}n=C.path;t=C.verb;y=C.headers;w=qn(C.parameters);b=C.errors;E=C.useUrlParams;if(b&&b.length>0){he(r,"htmx:validation:halted",C);oe(s);m();return e}const z=n.split("#");const $=z[0];const O=z[1];let R=n;if(E){R=$;const Z=!w.keys().next().done;if(Z){if(R.indexOf("?")<0){R+="?"}else{R+="&"}R+=an(w);if(O){R+="#"+O}}}if(!Tn(r,R,C)){fe(r,"htmx:invalidPath",C);oe(l);return e}p.open(t.toUpperCase(),R,true);p.overrideMimeType("text/html");p.withCredentials=C.withCredentials;p.timeout=C.timeout;if(S.noHeaders){}else{for(const k in y){if(y.hasOwnProperty(k)){const Y=y[k];Cn(p,k,Y)}}}const H={xhr:p,target:c,requestConfig:C,etc:i,boosted:_,select:X,pathInfo:{requestPath:n,finalRequestPath:R,responsePath:null,anchor:O}};p.onload=function(){try{const t=Hn(r);H.pathInfo.responsePath=On(p);M(r,H);if(H.keepIndicators!==true){Qt(T,q)}he(r,"htmx:afterRequest",H);he(r,"htmx:afterOnLoad",H);if(!le(r)){let e=null;while(t.length>0&&e==null){const n=t.shift();if(le(n)){e=n}}if(e){he(e,"htmx:afterRequest",H);he(e,"htmx:afterOnLoad",H)}}oe(s);m()}catch(e){fe(r,"htmx:onLoadError",ce({error:e},H));throw e}};p.onerror=function(){Qt(T,q);fe(r,"htmx:afterRequest",H);fe(r,"htmx:sendError",H);oe(l);m()};p.onabort=function(){Qt(T,q);fe(r,"htmx:afterRequest",H);fe(r,"htmx:sendAbort",H);oe(l);m()};p.ontimeout=function(){Qt(T,q);fe(r,"htmx:afterRequest",H);fe(r,"htmx:timeout",H);oe(l);m()};if(!he(r,"htmx:beforeRequest",H)){oe(s);m();return e}var T=Zt(r);var q=Yt(r);se(["loadstart","loadend","progress","abort"],function(t){se([p,p.upload],function(e){e.addEventListener(t,function(e){he(r,"htmx:xhr:"+t,{lengthComputable:e.lengthComputable,loaded:e.loaded,total:e.total})})})});he(r,"htmx:beforeSend",H);const J=E?null:mn(p,r,w);p.send(J);return e}function Nn(e,t){const n=t.xhr;let r=null;let o=null;if(R(n,/HX-Push:/i)){r=n.getResponseHeader("HX-Push");o="push"}else if(R(n,/HX-Push-Url:/i)){r=n.getResponseHeader("HX-Push-Url");o="push"}else if(R(n,/HX-Replace-Url:/i)){r=n.getResponseHeader("HX-Replace-Url");o="replace"}if(r){if(r==="false"){return{}}else{return{type:o,path:r}}}const i=t.pathInfo.finalRequestPath;const s=t.pathInfo.responsePath;const l=re(e,"hx-push-url");const c=re(e,"hx-replace-url");const u=ie(e).boosted;let a=null;let f=null;if(l){a="push";f=l}else if(c){a="replace";f=c}else if(u){a="push";f=s||i}if(f){if(f==="false"){return{}}if(f==="true"){f=s||i}if(t.pathInfo.anchor&&f.indexOf("#")===-1){f=f+"#"+t.pathInfo.anchor}return{type:a,path:f}}else{return{}}}function In(e,t){var n=new RegExp(e.code);return n.test(t.toString(10))}function Pn(e){for(var t=0;t0){E().setTimeout(e,x.swapDelay)}else{e()}}if(f){fe(o,"htmx:responseError",ce({error:"Response Status Error Code "+s.status+" from "+i.pathInfo.requestPath},i))}}const Mn={};function Xn(){return{init:function(e){return null},getSelectors:function(){return null},onEvent:function(e,t){return true},transformResponse:function(e,t,n){return e},isInlineSwap:function(e){return false},handleSwap:function(e,t,n,r){return false},encodeParameters:function(e,t,n){return null}}}function Fn(e,t){if(t.init){t.init(n)}Mn[e]=ce(Xn(),t)}function Bn(e){delete Mn[e]}function Un(e,n,r){if(n==undefined){n=[]}if(e==undefined){return n}if(r==undefined){r=[]}const t=te(e,"hx-ext");if(t){se(t.split(","),function(e){e=e.replace(/ /g,"");if(e.slice(0,7)=="ignore:"){r.push(e.slice(7));return}if(r.indexOf(e)<0){const t=Mn[e];if(t&&n.indexOf(t)<0){n.push(t)}}})}return Un(ue(c(e)),n,r)}var jn=false;ne().addEventListener("DOMContentLoaded",function(){jn=true});function Vn(e){if(jn||ne().readyState==="complete"){e()}else{ne().addEventListener("DOMContentLoaded",e)}}function _n(){if(Q.config.includeIndicatorStyles!==false){const e=Q.config.inlineStyleNonce?` nonce="${Q.config.inlineStyleNonce}"`:"";ne().head.insertAdjacentHTML("beforeend"," ."+Q.config.indicatorClass+"{opacity:0} ."+Q.config.requestClass+" ."+Q.config.indicatorClass+"{opacity:1; transition: opacity 200ms ease-in;} ."+Q.config.requestClass+"."+Q.config.indicatorClass+"{opacity:1; transition: opacity 200ms ease-in;} ")}}function zn(){const e=ne().querySelector('meta[name="htmx-config"]');if(e){return S(e.content)}else{return null}}function $n(){const e=zn();if(e){Q.config=ce(Q.config,e)}}Vn(function(){$n();_n();let e=ne().body;kt(e);const t=ne().querySelectorAll("[hx-trigger='restored'],[data-hx-trigger='restored']");e.addEventListener("htmx:abort",function(e){const t=e.target;const n=ie(t);if(n&&n.xhr){n.xhr.abort()}});const n=window.onpopstate?window.onpopstate.bind(window):null;window.onpopstate=function(e){if(e.state&&e.state.htmx){Wt();se(t,function(e){he(e,"htmx:restored",{document:ne(),triggerEvent:he})})}else{if(n){n(e)}}};E().setTimeout(function(){he(e,"htmx:load",{});e=null},0)});return Q}(); \ No newline at end of file diff --git a/static/style.css b/static/style.css new file mode 100644 index 0000000..ac4072f --- /dev/null +++ b/static/style.css @@ -0,0 +1,370 @@ +:root { + --bg: #f4f1ea; + --fg: #1a1a1a; + --muted: #5c5c5c; + --border: #3a3a3a; + --accent: #2b2b2b; + --accent-fg: #f4f1ea; + --success-bg: #e8f5e9; + --success-fg: #1b5e20; + --error-bg: #ffebee; + --error-fg: #b71c1c; + --warning-bg: #fff8e1; + --warning-fg: #7c4a00; + --card-bg: #faf8f3; + --hover: #ebe7de; + --active: #d4edda; + --reserved: #fff3cd; + --released: #e2e3e5; + --link: #0044cc; +} + +* { + box-sizing: border-box; +} + +html { + font-size: 16px; +} + +body { + margin: 0; + padding: 1rem; + font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", monospace; + background: var(--bg); + color: var(--fg); + line-height: 1.5; + min-height: 100vh; +} + +a { + color: var(--link); + text-decoration: underline; +} + +a:hover { + background: var(--hover); +} + +.container { + max-width: 1200px; + margin: 0 auto; +} + +header { + text-align: center; + margin-bottom: 1.5rem; + border: 2px solid var(--border); + padding: 1rem; + background: var(--card-bg); +} + +header h1 { + margin: 0; + font-size: 1.75rem; + letter-spacing: 0.05em; + text-transform: uppercase; +} + +header p { + margin: 0.5rem 0 0; + color: var(--muted); +} + +.box { + border: 2px solid var(--border); + background: var(--card-bg); + padding: 1rem; + margin-bottom: 1rem; +} + +.box-title { + margin: -1rem -1rem 1rem; + padding: 0.5rem 1rem; + background: var(--accent); + color: var(--accent-fg); + font-weight: bold; + border-bottom: 2px solid var(--border); +} + +.grid { + display: grid; + grid-template-columns: repeat(auto-fit, minmax(320px, 1fr)); + gap: 1rem; +} + +label { + display: block; + margin-bottom: 0.25rem; + font-weight: bold; +} + +select, +input[type="text"], +input[type="number"], +textarea { + width: 100%; + padding: 0.5rem; + border: 2px solid var(--border); + background: var(--bg); + color: var(--fg); + font-family: inherit; + font-size: 1rem; +} + +select:focus, +input:focus, +textarea:focus { + outline: 2px solid var(--accent); + outline-offset: 2px; +} + +.btn { + display: inline-block; + padding: 0.5rem 1rem; + border: 2px solid var(--border); + background: var(--accent); + color: var(--accent-fg); + font-family: inherit; + font-size: 1rem; + cursor: pointer; + text-decoration: none; +} + +.btn:hover { + background: var(--fg); +} + +.btn-secondary { + background: var(--bg); + color: var(--fg); +} + +.btn-secondary:hover { + background: var(--hover); +} + +.btn-danger { + background: var(--error-bg); + color: var(--error-fg); +} + +.btn-danger:hover { + background: var(--error-fg); + color: var(--error-bg); +} + +.preview-box { + border: 2px solid var(--border); + padding: 0.75rem; + background: var(--bg); + margin-top: 1rem; +} + +.preview-box .label { + color: var(--muted); +} + +.preview-box .value { + font-weight: bold; +} + +.message { + border: 2px solid var(--border); + padding: 1rem; + margin-bottom: 1rem; +} + +.message.success { + background: var(--success-bg); + color: var(--success-fg); +} + +.message.error { + background: var(--error-bg); + color: var(--error-fg); +} + +.filters { + display: flex; + flex-wrap: wrap; + gap: 0.5rem; + align-items: end; + margin-bottom: 1rem; +} + +.filters > div { + flex: 1 1 180px; +} + +table { + width: 100%; + border-collapse: collapse; + border: 2px solid var(--border); +} + +th, +td { + border: 1px solid var(--border); + padding: 0.5rem; + text-align: left; + vertical-align: top; +} + +th { + background: var(--accent); + color: var(--accent-fg); +} + +tr:nth-child(even) { + background: var(--bg); +} + +tr:hover { + background: var(--hover); +} + +.status { + display: inline-block; + padding: 0.125rem 0.5rem; + border: 1px solid var(--border); + font-weight: bold; + text-transform: uppercase; + font-size: 0.875rem; +} + +.status.active { + background: var(--active); + color: #155724; +} + +.status.reserved { + background: var(--reserved); + color: #856404; +} + +.status.released { + background: var(--released); + color: #383d41; +} + +.pagination { + display: flex; + justify-content: space-between; + align-items: center; + margin-top: 1rem; + flex-wrap: wrap; + gap: 0.5rem; +} + +.modal-overlay { + position: fixed; + inset: 0; + background: rgba(0, 0, 0, 0.5); + display: flex; + align-items: center; + justify-content: center; + padding: 1rem; + z-index: 1000; +} + +.modal { + background: var(--bg); + border: 2px solid var(--border); + max-width: 600px; + width: 100%; + max-height: 90vh; + overflow-y: auto; +} + +.modal .modal-title { + background: var(--accent); + color: var(--accent-fg); + padding: 0.75rem 1rem; + margin: 0; + border-bottom: 2px solid var(--border); +} + +.modal .modal-body { + padding: 1rem; +} + +.modal .modal-actions { + display: flex; + justify-content: flex-end; + gap: 0.5rem; + padding: 0 1rem 1rem; +} + +.detail-grid { + display: grid; + grid-template-columns: repeat(auto-fit, minmax(240px, 1fr)); + gap: 1rem; + margin-bottom: 1rem; +} + +.detail-item { + border: 1px solid var(--border); + padding: 0.5rem; + background: var(--bg); +} + +.detail-item .label { + color: var(--muted); + font-size: 0.875rem; +} + +.detail-item .value { + font-weight: bold; + word-break: break-all; +} + +.small { + font-size: 0.875rem; + color: var(--muted); +} + +@media (max-width: 640px) { + body { + padding: 0.5rem; + } + + .grid { + grid-template-columns: 1fr; + } + + table, + thead, + tbody, + th, + td, + tr { + display: block; + } + + thead { + display: none; + } + + tr { + margin-bottom: 1rem; + border: 2px solid var(--border); + } + + td { + border: none; + border-bottom: 1px solid var(--border); + position: relative; + padding-left: 45%; + } + + td::before { + content: attr(data-label); + position: absolute; + left: 0.5rem; + top: 0.5rem; + width: 40%; + font-weight: bold; + color: var(--muted); + } +} diff --git a/templates/allocation_detail.html b/templates/allocation_detail.html new file mode 100644 index 0000000..9663c56 --- /dev/null +++ b/templates/allocation_detail.html @@ -0,0 +1,126 @@ +{% extends "base.html" %} + +{% block title %}Detail {{ allocation.cidr }} | IP Subnet Allocator{% endblock %} + +{% block content %} +
+ {% include "fragments/flash.html" %} +
+ +
+
Detail alokace {{ allocation.cidr }}
+ +
+
+
Subnet
+
{{ allocation.cidr }}
+
+
+
Pool
+
{{ allocation.pool_name }}
+
+
+
Typ
+
{{ allocation.kind }}
+
+
+
Stav
+
{{ allocation.status }}
+
+
+
Celkem adres
+
{{ allocation.address_count }}
+
+
+
Použitelných hostů
+
{{ allocation.usable_host_count }}
+
+
+
Network address
+
{{ allocation.network }}
+
+
+
Broadcast address
+
{{ allocation.broadcast }}
+
+
+
První host
+
{{ allocation.first_host }}
+
+
+
Poslední host
+
{{ allocation.last_host }}
+
+
+
Poznámka
+
{{ allocation.note }}
+
+
+
Ticket / reference
+
{{ allocation.ticket }}
+
+
+
Vytvořeno
+
{{ allocation.created_at_local }} ({{ allocation.created_by }})
+
+ {% if allocation.released_at_local != "–" %} +
+
Uvolněno
+
{{ allocation.released_at_local }} ({{ allocation.released_by }})
+
+
+
Poznámka k uvolnění
+
{{ allocation.release_note }}
+
+ {% endif %} +
+ + {% if allocation.status == "active" || allocation.status == "reserved" %} + + {% endif %} + + Zpět +
+ +{% if audit_events.len() > 0 %} +
+
Auditní historie
+ + + + + + + + + + + {% for e in audit_events %} + + + + + + + {% endfor %} + +
ČasUdálostAktorDetaily
{{ e.created_at_local }}{{ e.event_type }}{{ e.actor }}
{{ e.details_json }}
+
+{% endif %} + + +{% endblock %} diff --git a/templates/base.html b/templates/base.html new file mode 100644 index 0000000..0ebbcc0 --- /dev/null +++ b/templates/base.html @@ -0,0 +1,29 @@ + + + + + + + {% block title %}IP Subnet Allocator{% endblock %} + + + {% block head %}{% endblock %} + + +
+
+

IP Subnet Allocator

+

Interní evidence a přidělování IPv4 subnetů

+
+ {% block content %}{% endblock %} + +
+ + diff --git a/templates/fragments/allocations_table.html b/templates/fragments/allocations_table.html new file mode 100644 index 0000000..e292408 --- /dev/null +++ b/templates/fragments/allocations_table.html @@ -0,0 +1,48 @@ + + + + + + + + + + + + + + + {% for a in allocations %} + + + + + + + + + + + {% else %} + + + + {% endfor %} + +
SubnetTypPoolPočet adresPoznámkaStavVytvořenoAkce
{{ a.cidr }}{{ a.kind }}{{ a.pool_name }}{{ a.address_count }}{{ a.note }}{{ a.status }}{{ a.created_at_local }}Detail
Žádné alokace.
+ +{% if total_pages > 1 %} + +{% endif %} diff --git a/templates/fragments/flash.html b/templates/fragments/flash.html new file mode 100644 index 0000000..254c257 --- /dev/null +++ b/templates/fragments/flash.html @@ -0,0 +1,19 @@ +{% if flash.has_success %} +
+

Přiděleno: {{ flash.success_cidr }}

+

{{ flash.success_note }}

+

+ Network: {{ flash.success_network }} | + Broadcast: {{ flash.success_broadcast }} | + První host: {{ flash.success_first_host }} | + Poslední host: {{ flash.success_last_host }} | + Použitelných hostů: {{ flash.success_usable_host_count }} +

+
+{% endif %} + +{% if flash.has_error %} +
+

{{ flash.error }}

+
+{% endif %} diff --git a/templates/index.html b/templates/index.html new file mode 100644 index 0000000..1af9bfb --- /dev/null +++ b/templates/index.html @@ -0,0 +1,172 @@ +{% extends "base.html" %} + +{% block content %} +
+ {% include "fragments/flash.html" %} +
+ +
+ {% for pool in pools %} +
+
{{ pool.name }}
+

Parent prefix: {{ pool.cidr }}

+

Typ: {{ pool.kind }}

+ +
+ + + +
+
+ + +
+ {% endfor %} +
+ +
+
Přidělené subnety
+ +
+
+ + +
+
+ + +
+
+ + +
+
+ + Reset +
+
+ +
+ {% include "fragments/allocations_table.html" %} +
+
+ + + + +{% endblock %} diff --git a/templates/partials/pool_preview.html b/templates/partials/pool_preview.html new file mode 100644 index 0000000..45246f7 --- /dev/null +++ b/templates/partials/pool_preview.html @@ -0,0 +1,26 @@ +
+ {% if has_error %} +

{{ error }}

+

Další volný subnet: –

+ {% else %} +

+ Další volný subnet: + {{ cidr }} +

+

+ Celkem adres: + {{ address_count }} +

+

+ Použitelných hostů: + {{ usable_host_count }} +

+ {% if prefix_length >= 31 %} +

+ Pro /31 a /32 se network/broadcast adresy dle RFC 3021 mohou shodovat s host adresami. +

+ {% else %} +

+ {% endif %} + {% endif %} +
diff --git a/tests/concurrency.rs b/tests/concurrency.rs new file mode 100644 index 0000000..8dadc4c --- /dev/null +++ b/tests/concurrency.rs @@ -0,0 +1,72 @@ +use sqlx::migrate::{MigrateDatabase, Migrator}; +use sqlx::{sqlite::SqlitePoolOptions, Sqlite, SqlitePool}; +use std::collections::HashSet; +use std::path::Path; + +async fn setup_db() -> SqlitePool { + let url = "sqlite::memory:"; + Sqlite::create_database(url).await.ok(); + let pool = SqlitePoolOptions::new() + .max_connections(20) + .connect(url) + .await + .unwrap(); + Migrator::new(Path::new("./migrations")) + .await + .unwrap() + .run(&pool) + .await + .unwrap(); + + sqlx::query( + "INSERT INTO pools (slug, name, cidr, kind, allowed_prefixes_json, enabled, created_at) VALUES (?, ?, ?, ?, ?, ?, ?)" + ) + .bind("vlan") + .bind("VLAN / zákaznické subnety") + .bind("10.91.0.0/16") + .bind("VLAN") + .bind("[20,21,22,23,24,25,26,27,28,29,30]") + .bind(1) + .bind(chrono::Utc::now().to_rfc3339()) + .execute(&pool) + .await + .unwrap(); + + pool +} + +#[tokio::test] +async fn concurrent_allocations_do_not_overlap() { + let pool = setup_db().await; + let mut handles = vec![]; + + for i in 0..5 { + let p = pool.clone(); + handles.push(tokio::spawn(async move { + sub_aligator::handlers::allocations::allocate_in_tx( + &p, + 1, + "10.91.0.0/16", + &[24], + 24, + &format!("test allocation {}", i), + "", + "local", + ) + .await + })); + } + + let results: Vec<_> = futures::future::join_all(handles).await; + let mut cidrs = HashSet::new(); + for r in results { + let Ok(Ok((allocation, _))) = r else { panic!("task failed") }; + assert!( + cidrs.insert(allocation.cidr.clone()), + "duplicate CIDR allocated: {}", + allocation.cidr + ); + } + + assert_eq!(cidrs.len(), 5); +}