commit 7e9bd0b55d54ab2519d945e9a72719ed25261402 Author: Matthew L McPeak Date: Fri Jun 19 06:02:08 2026 -0400 Inital Commit diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..63dc40d --- /dev/null +++ b/.env.example @@ -0,0 +1,13 @@ +DATABASE_URL=postgres://mercury:mercury@db:5432/mercury +JWT_SECRET=change_me_in_production +JWT_EXPIRY_SECS=3600 +CACHE_MAX_CAPACITY=10000 +CACHE_IDLE_TIMEOUT_SECS=300 +CACHE_SWEEP_INTERVAL_SECS=60 +# Comma-separated allowed CORS origins, or * for permissive. Empty = no CORS headers. +CORS_ORIGINS= + +# CDN (MinIO object storage) — credentials and bucket are pre-configured internally. +# When registering CDN objects in the admin UI, use this URL prefix: +# docker-compose: http://cdn:9000/mercury/ +# standalone: http://localhost:9000/mercury/ diff --git a/.forgejo/workflows/ci.yml b/.forgejo/workflows/ci.yml new file mode 100644 index 0000000..59e96c3 --- /dev/null +++ b/.forgejo/workflows/ci.yml @@ -0,0 +1,96 @@ +name: ci + +on: + push: + tags: + - "v*" + pull_request: + +jobs: + test: + runs-on: self-hosted + container: git.mcpeakdev.com/mcpeakdev/rust-ci:latest + steps: + - name: Checkout + uses: actions/checkout@v4 + + - name: Cache cargo registry + uses: actions/cache@v4 + with: + path: | + ~/.cargo/registry + ~/.cargo/git + target + key: ${{ runner.os }}-cargo-${{ hashFiles('Cargo.lock') }} + restore-keys: | + ${{ runner.os }}-cargo- + + - name: Check formatting + run: cargo fmt --check + + - name: Clippy + run: cargo clippy -- -D warnings + + - name: Run tests + run: cargo test + + build-ui: + runs-on: self-hosted + container: git.mcpeakdev.com/mcpeakdev/bun-ci:latest + steps: + - name: Checkout + uses: actions/checkout@v4 + + - name: Install dependencies + run: | + printf '@nychthemeron:registry=https://git.mcpeakdev.com/api/packages/McPeakDev/npm/\n//git.mcpeakdev.com/api/packages/McPeakDev/npm/:_authToken=%s\n' "$BUN_AUTH_TOKEN" > .npmrc + bun install --frozen-lockfile + rm .npmrc + working-directory: ui + env: + BUN_AUTH_TOKEN: ${{ secrets.BUN_AUTH_TOKEN }} + + - name: Audit dependencies + run: bun audit || true + working-directory: ui + + - name: Type check + run: bun run build + working-directory: ui + + publish: + needs: [test, build-ui] + if: startsWith(github.ref, 'refs/tags/v') + runs-on: self-hosted + container: git.mcpeakdev.com/mcpeakdev/docker-pub:latest + steps: + - name: Checkout + uses: actions/checkout@v4 + + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@v3 + + - name: Log in to registry + uses: docker/login-action@v3 + with: + registry: git.mcpeakdev.com + username: ${{ github.actor }} + password: ${{ secrets.BUN_AUTH_TOKEN }} + + - name: Extract image tag + id: meta + run: echo "tag=${GITHUB_REF_NAME#v}" >> "$GITHUB_OUTPUT" + + - name: Build and push + uses: docker/build-push-action@v6 + with: + context: . + file: Dockerfile + push: true + tags: | + git.mcpeakdev.com/mcpeakdev/mercury:${{ steps.meta.outputs.tag }} + git.mcpeakdev.com/mcpeakdev/mercury:latest + cache-from: type=registry,ref=git.mcpeakdev.com/mcpeakdev/mercury:latest + cache-to: type=inline + secrets: | + bun_auth_token=${{ secrets.BUN_AUTH_TOKEN }} diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..6674425 --- /dev/null +++ b/.gitignore @@ -0,0 +1,22 @@ +# ---> Rust +# Generated by Cargo +# will have compiled files and executables +debug/ +target/ + + +# These are backup files generated by rustfmt +**/*.rs.bk + +# MSVC Windows builds of rustc generate these, which store debugging information +*.pdb + +# RustRover +# JetBrains specific template is maintained in a separate JetBrains.gitignore that can +# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore +# and can be added to the global gitignore or merged into this file. For a more nuclear +# option (not recommended) you can uncomment the following to ignore the entire idea folder. +#.idea/ + +# Git worktrees +.worktrees/ diff --git a/Cargo.lock b/Cargo.lock new file mode 100644 index 0000000..131827e --- /dev/null +++ b/Cargo.lock @@ -0,0 +1,3306 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "ahash" +version = "0.8.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a15f179cd60c4584b8a8c596927aadc462e27f2ca70c04e0071964a73ba7a75" +dependencies = [ + "cfg-if", + "getrandom 0.3.4", + "once_cell", + "version_check", + "zerocopy", +] + +[[package]] +name = "aho-corasick" +version = "1.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ddd31a130427c27518df266943a5308ed92d4b226cc639f5a8f1002816174301" +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.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "819e7219dbd41043ac279b19830f2efc897156490d7fd6ea916720117ee66311" +dependencies = [ + "libc", +] + +[[package]] +name = "anyhow" +version = "1.0.102" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f202df86484c868dbad7eaa557ef785d5c66295e41b460ef922eca0723b842c" + +[[package]] +name = "async-trait" +version = "0.1.89" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9035ad2d096bed7955a320ee7e2230574d28fd3c3a0f186cbea1ff3c7eed5dbb" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.118", +] + +[[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.7.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "edca88bc138befd0323b20752846e6587272d3b03b0343c8ea28a6f819e6e71f" +dependencies = [ + "async-trait", + "axum-core", + "axum-macros", + "bytes", + "futures-util", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-util", + "itoa", + "matchit", + "memchr", + "mime", + "multer", + "percent-encoding", + "pin-project-lite", + "rustversion", + "serde", + "serde_json", + "serde_path_to_error", + "serde_urlencoded", + "sync_wrapper", + "tokio", + "tower 0.5.3", + "tower-layer", + "tower-service", + "tracing", +] + +[[package]] +name = "axum-core" +version = "0.4.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09f2bd6146b97ae3359fa0cc6d6b376d9539582c7b4220f041a33ec24c226199" +dependencies = [ + "async-trait", + "bytes", + "futures-util", + "http", + "http-body", + "http-body-util", + "mime", + "pin-project-lite", + "rustversion", + "sync_wrapper", + "tower-layer", + "tower-service", + "tracing", +] + +[[package]] +name = "axum-macros" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "57d123550fa8d071b7255cb0cc04dc302baa6c8c4a79f55701552684d8399bce" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.118", +] + +[[package]] +name = "base64" +version = "0.21.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9d297deb1925b89f2ccc13d7635fa0714f12c87adce1c75356b39ca9b7178567" + +[[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 = "bcrypt" +version = "0.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e65938ed058ef47d92cf8b346cc76ef48984572ade631927e9937b5ffc7662c7" +dependencies = [ + "base64 0.22.1", + "blowfish", + "getrandom 0.2.17", + "subtle", + "zeroize", +] + +[[package]] +name = "bitflags" +version = "2.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b4388bee8683e3d04af747c73422af53102d2bd24d9eadb6cbc100baef4b43f8" +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 = "blowfish" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e412e2cd0f2b2d93e02543ceae7917b3c70331573df19ee046bcbc35e45e87d7" +dependencies = [ + "byteorder", + "cipher", +] + +[[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.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e748733b7cbc798e1434b6ac524f0c1ff2ab456fe201501e6497c8417a4fc33" + +[[package]] +name = "cc" +version = "1.2.64" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dad887fd958be91b5098c0248def011f4523ab786cd411be668777e55063501f" +dependencies = [ + "find-msvc-tools", + "shlex", +] + +[[package]] +name = "cfg-if" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" + +[[package]] +name = "cfg_aliases" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "613afe47fcd5fac7ccf1db93babcb082c5994d996f20b8b159f2ad1658eb5724" + +[[package]] +name = "chrono" +version = "0.4.45" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1aa79e62e7697b8e29b513a68abacf485adcd1fe8284a4316c5ae868e6633327" +dependencies = [ + "iana-time-zone", + "js-sys", + "num-traits", + "serde", + "wasm-bindgen", + "windows-link", +] + +[[package]] +name = "cipher" +version = "0.4.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad" +dependencies = [ + "crypto-common", + "inout", +] + +[[package]] +name = "const-oid" +version = "0.9.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2459377285ad874054d797f3ccebf984978aa39129f6eafde5cdc8315b612f8" + +[[package]] +name = "core-foundation-sys" +version = "0.8.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" + +[[package]] +name = "cpufeatures" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" +dependencies = [ + "libc", +] + +[[package]] +name = "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.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0f58bbc28f91df819d0aa2a2c00cd19754769c2fad90579b3592b1c9ba7a3115" +dependencies = [ + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-utils" +version = "0.8.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d0a5c400df2834b80a4c3327b3aad3a4c4cd4de0629063962b03235697506a28" + +[[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 = "dashmap" +version = "5.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "978747c1d849a7d2ee5e8adc0159961c48fb7e5db2f06af6723b80123bb53856" +dependencies = [ + "cfg-if", + "hashbrown 0.14.5", + "lock_api", + "once_cell", + "parking_lot_core", +] + +[[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.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ac70aa55017e108007fbaf5aa0f54b021c98f92ff8af59d42eda9da96e3dd4f" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.118", +] + +[[package]] +name = "dotenvy" +version = "0.15.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1aaf95b3e5c8f23aa320147307562d361db0ae0d51242340f558153b4eb2439b" + +[[package]] +name = "either" +version = "1.16.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "91622ff5e7162018101f2fea40d6ebf4a78bbe5a49736a2020649edf9693679e" +dependencies = [ + "serde", +] + +[[package]] +name = "encoding_rs" +version = "0.8.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "75030f3c4f45dafd7586dd6780965a8c7e8e285a5ecb86713e63a79c5b2766f3" +dependencies = [ + "cfg-if", +] + +[[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 = "2.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0206175f82b8d6bf6652ff7d71a1e27fd2e4efde587fd368662814d6ec1d9ce0" + +[[package]] +name = "fastrand" +version = "2.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f1f227452a390804cdb637b74a86990f2a7d7ba4b7d5693aac9b4dd6defd8d6" + +[[package]] +name = "find-msvc-tools" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5baebc0774151f905a1a2cc41989300b1e6fbb29aff0ceffa1064fdd3088d582" + +[[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-channel" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "07bbe89c50d7a535e539b8c17bc0b49bdb77747034daa8087407d655f3f7cc1d" +dependencies = [ + "futures-core", + "futures-sink", +] + +[[package]] +name = "futures-core" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e3450815272ef58cec6d564423f6e755e25379b217b0bc688e295ba24df6b1d" + +[[package]] +name = "futures-executor" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "baf29c38818342a3b26b5b923639e7b1f4a61fc5e76102d4b1981c6dc7a7579d" +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.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cecba35d7ad927e23624b22ad55235f2239cfa44fd10428eecbeba6d6a717718" + +[[package]] +name = "futures-macro" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e835b70203e41293343137df5c0664546da5745f82ec9b84d40be8336958447b" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.118", +] + +[[package]] +name = "futures-sink" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c39754e157331b013978ec91992bde1ac089843443c49cbc7f46150b0fad0893" + +[[package]] +name = "futures-task" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "037711b3d59c33004d3856fbdc83b99d4ff37a24768fa1be9ce3538a1cde4393" + +[[package]] +name = "futures-util" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "389ca41296e6190b48053de0321d02a77f32f8a5d2461dd38762c0593805c6d6" +dependencies = [ + "futures-core", + "futures-io", + "futures-macro", + "futures-sink", + "futures-task", + "memchr", + "pin-project-lite", + "slab", +] + +[[package]] +name = "generic-array" +version = "0.14.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" +dependencies = [ + "typenum", + "version_check", +] + +[[package]] +name = "getrandom" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" +dependencies = [ + "cfg-if", + "js-sys", + "libc", + "wasi", + "wasm-bindgen", +] + +[[package]] +name = "getrandom" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd" +dependencies = [ + "cfg-if", + "js-sys", + "libc", + "r-efi 5.3.0", + "wasip2", + "wasm-bindgen", +] + +[[package]] +name = "getrandom" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0de51e6874e94e7bf76d726fc5d13ba782deca734ff60d5bb2fb2607c7406555" +dependencies = [ + "cfg-if", + "libc", + "r-efi 6.0.0", + "wasip2", + "wasip3", +] + +[[package]] +name = "glob" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0cc23270f6e1808e30a928bdc84dea0b9b4136a8bc82338574f23baf47bbd280" + +[[package]] +name = "hashbrown" +version = "0.14.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1" +dependencies = [ + "ahash", + "allocator-api2", +] + +[[package]] +name = "hashbrown" +version = "0.15.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1" +dependencies = [ + "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.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e8094feaf31ff591f651a2664fb9cfd92bba7a60ce3197265e9482ebe753c8f7" +dependencies = [ + "hashbrown 0.14.5", +] + +[[package]] +name = "heck" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "95505c38b4572b2d910cecb0281560f54b440a19336cbbcb27bf6ce6adc6f5a8" +dependencies = [ + "unicode-segmentation", +] + +[[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.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6970f50e31d6fc17d3fa27329444bfa74e196cf62e95052a3f6fee181dba6425" +dependencies = [ + "bytes", + "itoa", +] + +[[package]] +name = "http-body" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1efedce1fb8e6913f23e0c92de8e62cd5b772a67e7b3946df930a62566c93184" +dependencies = [ + "bytes", + "http", +] + +[[package]] +name = "http-body-util" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b021d93e26becf5dc7e1b75b1bed1fd93124b374ceb73f43d4d4eafec896a64a" +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 = "hyper" +version = "1.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "55281c53a1894c864990125767da440a4e630446785086f52523b20033b74498" +dependencies = [ + "atomic-waker", + "bytes", + "futures-channel", + "futures-core", + "http", + "http-body", + "httparse", + "httpdate", + "itoa", + "pin-project-lite", + "smallvec", + "tokio", + "want", +] + +[[package]] +name = "hyper-rustls" +version = "0.27.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33ca68d021ef39cf6463ab54c1d0f5daf03377b70561305bb89a8f83aab66e0f" +dependencies = [ + "http", + "hyper", + "hyper-util", + "rustls 0.23.40", + "tokio", + "tokio-rustls", + "tower-service", + "webpki-roots 1.0.8", +] + +[[package]] +name = "hyper-util" +version = "0.1.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "96547c2556ec9d12fb1578c4eaf448b04993e7fb79cbaad930a656880a6bdfa0" +dependencies = [ + "base64 0.22.1", + "bytes", + "futures-channel", + "futures-util", + "http", + "http-body", + "hyper", + "ipnet", + "libc", + "percent-encoding", + "pin-project-lite", + "socket2", + "tokio", + "tower-service", + "tracing", +] + +[[package]] +name = "iana-time-zone" +version = "0.1.65" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e31bc9ad994ba00e440a8aa5c9ef0ec67d5cb5e5cb0cc7f8b744a35b389cc470" +dependencies = [ + "android_system_properties", + "core-foundation-sys", + "iana-time-zone-haiku", + "js-sys", + "log", + "wasm-bindgen", + "windows-core", +] + +[[package]] +name = "iana-time-zone-haiku" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f" +dependencies = [ + "cc", +] + +[[package]] +name = "icu_collections" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2984d1cd16c883d7935b9e07e44071dca8d917fd52ecc02c04d5fa0b5a3f191c" +dependencies = [ + "displaydoc", + "potential_utf", + "utf8_iter", + "yoke", + "zerofrom", + "zerovec", +] + +[[package]] +name = "icu_locale_core" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92219b62b3e2b4d88ac5119f8904c10f8f61bf7e95b640d25ba3075e6cac2c29" +dependencies = [ + "displaydoc", + "litemap", + "tinystr", + "writeable", + "zerovec", +] + +[[package]] +name = "icu_normalizer" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c56e5ee99d6e3d33bd91c5d85458b6005a22140021cc324cea84dd0e72cff3b4" +dependencies = [ + "icu_collections", + "icu_normalizer_data", + "icu_properties", + "icu_provider", + "smallvec", + "zerovec", +] + +[[package]] +name = "icu_normalizer_data" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da3be0ae77ea334f4da67c12f149704f19f81d1adf7c51cf482943e84a2bad38" + +[[package]] +name = "icu_properties" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bee3b67d0ea5c2cca5003417989af8996f8604e34fb9ddf96208a033901e70de" +dependencies = [ + "icu_collections", + "icu_locale_core", + "icu_properties_data", + "icu_provider", + "zerotrie", + "zerovec", +] + +[[package]] +name = "icu_properties_data" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e2bbb201e0c04f7b4b3e14382af113e17ba4f63e2c9d2ee626b720cbce54a14" + +[[package]] +name = "icu_provider" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "139c4cf31c8b5f33d7e199446eff9c1e02decfc2f0eec2c8d71f65befa45b421" +dependencies = [ + "displaydoc", + "icu_locale_core", + "writeable", + "yoke", + "zerofrom", + "zerotrie", + "zerovec", +] + +[[package]] +name = "id-arena" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954" + +[[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.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d466e9454f08e4a911e14806c24e16fba1b4c121d1ea474396f396069cf949d9" +dependencies = [ + "equivalent", + "hashbrown 0.17.1", + "serde", + "serde_core", +] + +[[package]] +name = "inout" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "879f10e63c20629ecabbb64a8010319738c66a5cd0c29b02d63d272b03751d01" +dependencies = [ + "generic-array", +] + +[[package]] +name = "ipnet" +version = "2.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d98f6fed1fde3f8c21bc40a1abb88dd75e67924f9cffc3ef95607bad8017f8e2" + +[[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.102" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "03d04c30968dffe80775bd4d7fb676131cd04a1fb46d2686dbffbaec2d9dfd31" +dependencies = [ + "cfg-if", + "futures-util", + "wasm-bindgen", +] + +[[package]] +name = "jsonwebtoken" +version = "9.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a87cc7a48537badeae96744432de36f4be2b4a34a05a5ef32e9dd8a1c169dde" +dependencies = [ + "base64 0.22.1", + "js-sys", + "pem", + "ring", + "serde", + "serde_json", + "simple_asn1", +] + +[[package]] +name = "lazy_static" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe" +dependencies = [ + "spin", +] + +[[package]] +name = "leb128fmt" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09edd9e8b54e49e587e4f6295a7d29c3ea94d469cb40ab8ca70b288248a81db2" + +[[package]] +name = "libc" +version = "0.2.186" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "68ab91017fe16c622486840e4c83c9a37afeff978bd239b5293d61ece587de66" + +[[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.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f02ab6bace2054fb888a3c16f990117b579d14a3088e472d63c6011fa185c9d3" +dependencies = [ + "bitflags", + "libc", + "plain", + "redox_syscall 0.8.1", +] + +[[package]] +name = "libsqlite3-sys" +version = "0.27.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf4e226dcd58b4be396f7bd3c20da8fdee2911400705297ba7d2d7cc2c30f716" +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.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92daf443525c4cce67b150400bc2316076100ce0b3686209eb8cf3c31612e6f0" + +[[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.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "953f07c43838f8e6f9758cab68bf5bed85465e7587ebe0b823f1bcd81978ad3a" + +[[package]] +name = "lru-slab" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "112b39cec0b298b6c1999fee3e31427f74f676e4cb9879ed1a121b43661a4154" + +[[package]] +name = "matchers" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d1525a2a28c7f4fa0fc98bb91ae755d1e2d1505079e05539e35bc876b5d65ae9" +dependencies = [ + "regex-automata", +] + +[[package]] +name = "matchit" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e7465ac9959cc2b1404e8e2367b43684a6d13790fe23056cc8c6c5a6b7bcb94" + +[[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.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "88904434abc2901f197fe8cc55f0445e7ded921dba5911dad2e2b39b48e663c4" + +[[package]] +name = "mercury" +version = "0.1.0" +dependencies = [ + "anyhow", + "axum", + "bcrypt", + "chrono", + "dashmap", + "dotenvy", + "glob", + "http-body-util", + "jsonwebtoken", + "reqwest", + "serde", + "serde_json", + "sha2", + "sqlx", + "tokio", + "tower 0.4.13", + "tower-http 0.5.2", + "tracing", + "tracing-subscriber", + "uuid", +] + +[[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.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "02bd0af71c67b473010cbbc60715ee815645a4dc942899111f494b4b737d6fda" +dependencies = [ + "libc", + "wasi", + "windows-sys 0.61.2", +] + +[[package]] +name = "multer" +version = "3.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "83e87776546dc87511aa5ee218730c92b666d7264ab6ed41f9d215af9cd5224b" +dependencies = [ + "bytes", + "encoding_rs", + "futures-util", + "http", + "httparse", + "memchr", + "mime", + "spin", + "version_check", +] + +[[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" +version = "0.4.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a5e44f723f1133c9deac646763579fdb3ac745e418f2a7af9cd0c431da1f20b9" +dependencies = [ + "num-integer", + "num-traits", +] + +[[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 0.8.6", + "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.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7969661fd2958a5cb096e56c8e1ad0444ac2bbcd0061bd28660485a44879858f" +dependencies = [ + "num-traits", +] + +[[package]] +name = "num-iter" +version = "0.1.45" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1429034a0490724d0075ebb2bc9e875d6503c3cf69e235a8941aa757d83ef5bf" +dependencies = [ + "autocfg", + "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_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 = "paste" +version = "1.0.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "57c0d7b74b563b49d38dae00a0c37d4d6de9b432382b2892f0574ddcae73fd0a" + +[[package]] +name = "pem" +version = "3.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d30c53c26bc5b31a98cd02d20f25a7c8567146caf63ed593a9d87b2775291be" +dependencies = [ + "base64 0.22.1", + "serde_core", +] + +[[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" +version = "1.1.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2466b2336ed02bcdca6b294417127b90ec92038d1d5c4fbeac971a922e0e0924" +dependencies = [ + "pin-project-internal", +] + +[[package]] +name = "pin-project-internal" +version = "1.1.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c96395f0a926bc13b1c17622aaddda1ecb55d49c8f1bf9777e4d877800a43f8b" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.118", +] + +[[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.33" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "19f132c84eca552bf34cab8ec81f1c1dcc229b811638f9d283dceabe58c5569e" + +[[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.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0103b1cef7ec0cf76490e969665504990193874ea05c85ff9bab8b911d0a0564" +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 = "prettyplease" +version = "0.2.37" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "479ca8adacdd7ce8f1fb39ce9ecccbfe93a3f1344b3d0d97f20bc0196208f62b" +dependencies = [ + "proc-macro2", + "syn 2.0.118", +] + +[[package]] +name = "proc-macro2" +version = "1.0.106" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quinn" +version = "0.11.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9e20a958963c291dc322d98411f541009df2ced7b5a4f2bd52337638cfccf20" +dependencies = [ + "bytes", + "cfg_aliases", + "pin-project-lite", + "quinn-proto", + "quinn-udp", + "rustc-hash", + "rustls 0.23.40", + "socket2", + "thiserror 2.0.18", + "tokio", + "tracing", + "web-time", +] + +[[package]] +name = "quinn-proto" +version = "0.11.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "434b42fec591c96ef50e21e886936e66d3cc3f737104fdb9b737c40ffb94c098" +dependencies = [ + "bytes", + "getrandom 0.3.4", + "lru-slab", + "rand 0.9.4", + "ring", + "rustc-hash", + "rustls 0.23.40", + "rustls-pki-types", + "slab", + "thiserror 2.0.18", + "tinyvec", + "tracing", + "web-time", +] + +[[package]] +name = "quinn-udp" +version = "0.5.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "addec6a0dcad8a8d96a771f815f0eaf55f9d1805756410b39f5fa81332574cbd" +dependencies = [ + "cfg_aliases", + "libc", + "once_cell", + "socket2", + "tracing", + "windows-sys 0.52.0", +] + +[[package]] +name = "quote" +version = "1.0.45" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41f2619966050689382d2b44f664f4bc593e129785a36d6ee376ddf37259b924" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "r-efi" +version = "5.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f" + +[[package]] +name = "r-efi" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" + +[[package]] +name = "rand" +version = "0.8.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5ca0ecfa931c29007047d1bc58e623ab12e5590e8c7cc53200d5202b69266d8a" +dependencies = [ + "libc", + "rand_chacha 0.3.1", + "rand_core 0.6.4", +] + +[[package]] +name = "rand" +version = "0.9.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "44c5af06bb1b7d3216d91932aed5265164bf384dc89cd6ba05cf59a35f5f76ea" +dependencies = [ + "rand_chacha 0.9.0", + "rand_core 0.9.5", +] + +[[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 0.6.4", +] + +[[package]] +name = "rand_chacha" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb" +dependencies = [ + "ppv-lite86", + "rand_core 0.9.5", +] + +[[package]] +name = "rand_core" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" +dependencies = [ + "getrandom 0.2.17", +] + +[[package]] +name = "rand_core" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c" +dependencies = [ + "getrandom 0.3.4", +] + +[[package]] +name = "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.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5b44b894f2a6e36457d665d1e08c3866add6ed5e70050c1b4ba8a8ddedb02ce7" +dependencies = [ + "bitflags", +] + +[[package]] +name = "regex-automata" +version = "0.4.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e1dd4122fc1595e8162618945476892eefca7b88c52820e74af6262213cae8f" +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 = "reqwest" +version = "0.12.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eddd3ca559203180a307f12d114c268abf583f59b03cb906fd0b3ff8646c1147" +dependencies = [ + "base64 0.22.1", + "bytes", + "futures-core", + "futures-util", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-rustls", + "hyper-util", + "js-sys", + "log", + "percent-encoding", + "pin-project-lite", + "quinn", + "rustls 0.23.40", + "rustls-pki-types", + "serde", + "serde_json", + "serde_urlencoded", + "sync_wrapper", + "tokio", + "tokio-rustls", + "tokio-util", + "tower 0.5.3", + "tower-http 0.6.11", + "tower-service", + "url", + "wasm-bindgen", + "wasm-bindgen-futures", + "wasm-streams", + "web-sys", + "webpki-roots 1.0.8", +] + +[[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 0.6.4", + "signature", + "spki", + "subtle", + "zeroize", +] + +[[package]] +name = "rustc-hash" +version = "2.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94300abf3f1ae2e2b8ffb7b58043de3d399c73fa6f4b73826402a5c457614dbe" + +[[package]] +name = "rustix" +version = "1.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6fe4565b9518b83ef4f91bb47ce29620ca828bd32cb7e408f0062e9930ba190" +dependencies = [ + "bitflags", + "errno", + "libc", + "linux-raw-sys", + "windows-sys 0.61.2", +] + +[[package]] +name = "rustls" +version = "0.21.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f56a14d1f48b391359b22f731fd4bd7e43c97f3c50eee276f3aa09c94784d3e" +dependencies = [ + "ring", + "rustls-webpki 0.101.7", + "sct", +] + +[[package]] +name = "rustls" +version = "0.23.40" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ef86cd5876211988985292b91c96a8f2d298df24e75989a43a3c73f2d4d8168b" +dependencies = [ + "once_cell", + "ring", + "rustls-pki-types", + "rustls-webpki 0.103.13", + "subtle", + "zeroize", +] + +[[package]] +name = "rustls-pemfile" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c74cae0a4cf6ccbbf5f359f08efdf8ee7e1dc532573bf0db71968cb56b1448c" +dependencies = [ + "base64 0.21.7", +] + +[[package]] +name = "rustls-pki-types" +version = "1.14.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "30a7197ae7eb376e574fe940d068c30fe0462554a3ddbe4eca7838e049c937a9" +dependencies = [ + "web-time", + "zeroize", +] + +[[package]] +name = "rustls-webpki" +version = "0.101.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b6275d1ee7a1cd780b64aca7726599a1dbc893b1e64144529e55c3c2f745765" +dependencies = [ + "ring", + "untrusted", +] + +[[package]] +name = "rustls-webpki" +version = "0.103.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "61c429a8649f110dddef65e2a5ad240f747e85f7758a6bccc7e5777bd33f756e" +dependencies = [ + "ring", + "rustls-pki-types", + "untrusted", +] + +[[package]] +name = "rustversion" +version = "1.0.22" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b39cdef0fa800fc44525c84ccb54a029961a8215f9619753635a9c0d2538d46d" + +[[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 = "sct" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da046153aa2352493d6cb7da4b6e5c0c057d8a1d0a9aa8560baffdd945acd414" +dependencies = [ + "ring", + "untrusted", +] + +[[package]] +name = "semver" +version = "1.0.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" + +[[package]] +name = "serde" +version = "1.0.228" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a8e94ea7f378bd32cbbd37198a4a91436180c5bb472411e48b5ec2e2124ae9e" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.228" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41d385c7d4ca58e59fc732af25c3983b67ac852c1a25000afe1175de458b67ad" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.228" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.118", +] + +[[package]] +name = "serde_json" +version = "1.0.150" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e8014e44b4736ed0538adeecded0fce2a272f22dc9578a7eb6b2d9993c74cfb9" +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.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3bf829a2d51ab4a5ddf1352d8470c140cadc8301b2ae1789db023f01cedd6ba" +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 0.6.4", +] + +[[package]] +name = "simple_asn1" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d585997b0ac10be3c5ee635f1bab02d512760d14b7c468801ac8a01d9ae5f1d" +dependencies = [ + "num-bigint", + "num-traits", + "thiserror 2.0.18", + "time", +] + +[[package]] +name = "slab" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" + +[[package]] +name = "smallvec" +version = "1.15.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ed6a63f02c8539c91a8685a86f4099661ba3da017932f6ebbea6de3f0fa7c90" + +[[package]] +name = "socket2" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52d1cfed4120b4d927bf7c0f86d2087a4a7d6027c906d9f9d525a80573b9be51" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "spin" +version = "0.9.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6980e8d7511241f8acf4aebddbb1ff938df5eebe98691418c4468d0b72a96a67" +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 = "sqlformat" +version = "0.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7bba3a93db0cc4f7bdece8bb09e77e2e785c20bfebf79eb8340ed80708048790" +dependencies = [ + "nom", + "unicode_categories", +] + +[[package]] +name = "sqlx" +version = "0.7.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c9a2ccff1a000a5a59cd33da541d9f2fdcd9e6e8229cc200565942bff36d0aaa" +dependencies = [ + "sqlx-core", + "sqlx-macros", + "sqlx-mysql", + "sqlx-postgres", + "sqlx-sqlite", +] + +[[package]] +name = "sqlx-core" +version = "0.7.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24ba59a9342a3d9bab6c56c118be528b27c9b60e490080e9711a04dccac83ef6" +dependencies = [ + "ahash", + "atoi", + "byteorder", + "bytes", + "chrono", + "crc", + "crossbeam-queue", + "either", + "event-listener", + "futures-channel", + "futures-core", + "futures-intrusive", + "futures-io", + "futures-util", + "hashlink", + "hex", + "indexmap", + "log", + "memchr", + "once_cell", + "paste", + "percent-encoding", + "rustls 0.21.12", + "rustls-pemfile", + "serde", + "serde_json", + "sha2", + "smallvec", + "sqlformat", + "thiserror 1.0.69", + "tokio", + "tokio-stream", + "tracing", + "url", + "uuid", + "webpki-roots 0.25.4", +] + +[[package]] +name = "sqlx-macros" +version = "0.7.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ea40e2345eb2faa9e1e5e326db8c34711317d2b5e08d0d5741619048a803127" +dependencies = [ + "proc-macro2", + "quote", + "sqlx-core", + "sqlx-macros-core", + "syn 1.0.109", +] + +[[package]] +name = "sqlx-macros-core" +version = "0.7.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5833ef53aaa16d860e92123292f1f6a3d53c34ba8b1969f152ef1a7bb803f3c8" +dependencies = [ + "dotenvy", + "either", + "heck 0.4.1", + "hex", + "once_cell", + "proc-macro2", + "quote", + "serde", + "serde_json", + "sha2", + "sqlx-core", + "sqlx-mysql", + "sqlx-postgres", + "sqlx-sqlite", + "syn 1.0.109", + "tempfile", + "tokio", + "url", +] + +[[package]] +name = "sqlx-mysql" +version = "0.7.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ed31390216d20e538e447a7a9b959e06ed9fc51c37b514b46eb758016ecd418" +dependencies = [ + "atoi", + "base64 0.21.7", + "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 0.8.6", + "rsa", + "serde", + "sha1", + "sha2", + "smallvec", + "sqlx-core", + "stringprep", + "thiserror 1.0.69", + "tracing", + "uuid", + "whoami", +] + +[[package]] +name = "sqlx-postgres" +version = "0.7.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7c824eb80b894f926f89a0b9da0c7f435d27cdd35b8c655b114e58223918577e" +dependencies = [ + "atoi", + "base64 0.21.7", + "bitflags", + "byteorder", + "chrono", + "crc", + "dotenvy", + "etcetera", + "futures-channel", + "futures-core", + "futures-io", + "futures-util", + "hex", + "hkdf", + "hmac", + "home", + "itoa", + "log", + "md-5", + "memchr", + "once_cell", + "rand 0.8.6", + "serde", + "serde_json", + "sha2", + "smallvec", + "sqlx-core", + "stringprep", + "thiserror 1.0.69", + "tracing", + "uuid", + "whoami", +] + +[[package]] +name = "sqlx-sqlite" +version = "0.7.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b244ef0a8414da0bed4bb1910426e890b19e5e9bccc27ada6b797d05c55ae0aa" +dependencies = [ + "atoi", + "chrono", + "flume", + "futures-channel", + "futures-core", + "futures-executor", + "futures-intrusive", + "futures-util", + "libsqlite3-sys", + "log", + "percent-encoding", + "serde", + "sqlx-core", + "tracing", + "url", + "urlencoding", + "uuid", +] + +[[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 = "subtle" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" + +[[package]] +name = "syn" +version = "1.0.109" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b64191b275b66ffe2469e8af2c1cfe3bafa67b529ead792a6d0160888b4237" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "2.0.118" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1b9ae57f904213ebb649ce6895b8a66c66f0203b9319718f69a5612a065b1422" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "sync_wrapper" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263" +dependencies = [ + "futures-core", +] + +[[package]] +name = "synstructure" +version = "0.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "728a70f3dbaf5bab7f0c4b1ac8d7ae5ea60a4b5549c8a5914361c99147a709d2" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.118", +] + +[[package]] +name = "tempfile" +version = "3.27.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" +dependencies = [ + "fastrand", + "getrandom 0.4.2", + "once_cell", + "rustix", + "windows-sys 0.61.2", +] + +[[package]] +name = "thiserror" +version = "1.0.69" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52" +dependencies = [ + "thiserror-impl 1.0.69", +] + +[[package]] +name = "thiserror" +version = "2.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4288b5bcbc7920c07a1149a35cf9590a2aa808e0bc1eafaade0b80947865fbc4" +dependencies = [ + "thiserror-impl 2.0.18", +] + +[[package]] +name = "thiserror-impl" +version = "1.0.69" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.118", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebc4ee7f67670e9b64d05fa4253e753e016c6c95ff35b89b7941d6b856dec1d5" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.118", +] + +[[package]] +name = "thread_local" +version = "1.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f60246a4944f24f6e018aa17cdeffb7818b76356965d03b07d6a9886e8962185" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "time" +version = "0.3.49" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "711a53c2d47bbd818258c498c8dbfe186a2526c631495cfe7e078567f86b8469" +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.29" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "71c652a3727a9cbb9a02f707f530b618ce00d0ccd762009c8c23bd191df3c17d" +dependencies = [ + "num-conv", + "time-core", +] + +[[package]] +name = "tinystr" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c8323304221c2a851516f22236c5722a72eaa19749016521d6dff0824447d96d" +dependencies = [ + "displaydoc", + "zerovec", +] + +[[package]] +name = "tinyvec" +version = "1.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3e61e67053d25a4e82c844e8424039d9745781b3fc4f32b8d55ed50f5f667ef3" +dependencies = [ + "tinyvec_macros", +] + +[[package]] +name = "tinyvec_macros" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20" + +[[package]] +name = "tokio" +version = "1.52.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8fc7f01b389ac15039e4dc9531aa973a135d7a4135281b12d7c1bc79fd57fffe" +dependencies = [ + "bytes", + "libc", + "mio", + "parking_lot", + "pin-project-lite", + "signal-hook-registry", + "socket2", + "tokio-macros", + "windows-sys 0.61.2", +] + +[[package]] +name = "tokio-macros" +version = "2.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "385a6cb71ab9ab790c5fe8d67f1645e6c450a7ce006a33de03daa956cf70a496" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.118", +] + +[[package]] +name = "tokio-rustls" +version = "0.26.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1729aa945f29d91ba541258c8df89027d5792d85a8841fb65e8bf0f4ede4ef61" +dependencies = [ + "rustls 0.23.40", + "tokio", +] + +[[package]] +name = "tokio-stream" +version = "0.1.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32da49809aab5c3bc678af03902d4ccddea2a87d028d86392a4b1560c6906c70" +dependencies = [ + "futures-core", + "pin-project-lite", + "tokio", +] + +[[package]] +name = "tokio-util" +version = "0.7.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ae9cec805b01e8fc3fd2fe289f89149a9b66dd16786abd8b19cfa7b48cb0098" +dependencies = [ + "bytes", + "futures-core", + "futures-sink", + "pin-project-lite", + "tokio", +] + +[[package]] +name = "tower" +version = "0.4.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8fa9be0de6cf49e536ce1851f987bd21a43b771b09473c3549a6c853db37c1c" +dependencies = [ + "futures-core", + "futures-util", + "pin-project", + "pin-project-lite", + "tower-layer", + "tower-service", + "tracing", +] + +[[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.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e9cd434a998747dd2c4276bc96ee2e0c7a2eadf3cae88e52be55a05fa9053f5" +dependencies = [ + "bitflags", + "bytes", + "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-http" +version = "0.6.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4cfcf7e2740e6fc6d4d688b4ef00650406bb94adf4731e43c096c3a19fe40840" +dependencies = [ + "bitflags", + "bytes", + "futures-util", + "http", + "http-body", + "pin-project-lite", + "tower 0.5.3", + "tower-layer", + "tower-service", + "url", +] + +[[package]] +name = "tower-layer" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "121c2a6cda46980bb0fcd1647ffaf6cd3fc79a013de288782836f6df9c48780e" + +[[package]] +name = "tower-service" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3" + +[[package]] +name = "tracing" +version = "0.1.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" +dependencies = [ + "log", + "pin-project-lite", + "tracing-attributes", + "tracing-core", +] + +[[package]] +name = "tracing-attributes" +version = "0.1.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.118", +] + +[[package]] +name = "tracing-core" +version = "0.1.36" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" +dependencies = [ + "once_cell", + "valuable", +] + +[[package]] +name = "tracing-log" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee855f1f400bd0e5c02d150ae5de3840039a3f54b025156404e34c23c03f47c3" +dependencies = [ + "log", + "once_cell", + "tracing-core", +] + +[[package]] +name = "tracing-subscriber" +version = "0.3.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb7f578e5945fb242538965c2d0b04418d38ec25c79d160cd279bf0731c8d319" +dependencies = [ + "matchers", + "nu-ansi-term", + "once_cell", + "regex-automata", + "sharded-slab", + "smallvec", + "thread_local", + "tracing", + "tracing-core", + "tracing-log", +] + +[[package]] +name = "try-lock" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" + +[[package]] +name = "typenum" +version = "1.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" + +[[package]] +name = "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.24" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75" + +[[package]] +name = "unicode-normalization" +version = "0.1.25" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5fd4f6878c9cb28d874b009da9e8d183b5abc80117c40bbd187a1fde336be6e8" +dependencies = [ + "tinyvec", +] + +[[package]] +name = "unicode-properties" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7df058c713841ad818f1dc5d3fd88063241cc61f49f5fbea4b951e8cf5a8d71d" + +[[package]] +name = "unicode-segmentation" +version = "1.13.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6f5d3c3b1bf09027a88a6bc961fc00497d651009560b5463668dc81b0fa87a8" + +[[package]] +name = "unicode-xid" +version = "0.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853" + +[[package]] +name = "unicode_categories" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "39ec24b3121d976906ece63c9daad25b85969647682eee313cb5779fdd69e14e" + +[[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 = "urlencoding" +version = "2.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "daf8dba3b7eb870caf1ddeed7bc9d2a049f3cfdfae7cb521b087cc33ae4c49da" + +[[package]] +name = "utf8_iter" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be" + +[[package]] +name = "uuid" +version = "1.23.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "144d6b123cef80b301b8f72a9e2ca4370ddec21950d0a103dd22c437006d2db7" +dependencies = [ + "getrandom 0.4.2", + "js-sys", + "serde_core", + "wasm-bindgen", +] + +[[package]] +name = "valuable" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba73ea9cf16a25df0c8caa16c51acb937d5712a8429db78a3ee29d5dcacd3a65" + +[[package]] +name = "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 = "want" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bfa7760aed19e106de2c7c0b581b509f2f25d3dacaf737cb82ac61bc6d760b0e" +dependencies = [ + "try-lock", +] + +[[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + +[[package]] +name = "wasip2" +version = "1.0.4+wasi-0.2.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b67efb37e106e55ce722a510d6b5f9c17f083e5fc79afc2badeb12cc313d9487" +dependencies = [ + "wit-bindgen 0.57.1", +] + +[[package]] +name = "wasip3" +version = "0.4.0+wasi-0.3.0-rc-2026-01-06" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5428f8bf88ea5ddc08faddef2ac4a67e390b88186c703ce6dbd955e1c145aca5" +dependencies = [ + "wit-bindgen 0.51.0", +] + +[[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.125" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ddb3f79143bced6de84270411622a2699cee572fc0875aeaf1e7867cf9fca1a" +dependencies = [ + "cfg-if", + "once_cell", + "rustversion", + "wasm-bindgen-macro", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-futures" +version = "0.4.75" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "503b14d284f2c8dac03b819967e155ea753f573586193b2b2c95990cb5d69280" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.125" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e21a184b13fb19e157296e2c46056aec9092264fab83e4ba59e68c61b323c3d" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.125" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fecefd9c35bd935a20fc3fc344b5f29138961e4f47fb03297d88f2587afb5ebd" +dependencies = [ + "bumpalo", + "proc-macro2", + "quote", + "syn 2.0.118", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.125" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23939e44bb9a5d7576fa2b563dc2e136628f1224e88a8deed09e04858b77871f" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "wasm-encoder" +version = "0.244.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "990065f2fe63003fe337b932cfb5e3b80e0b4d0f5ff650e6985b1048f62c8319" +dependencies = [ + "leb128fmt", + "wasmparser", +] + +[[package]] +name = "wasm-metadata" +version = "0.244.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb0e353e6a2fbdc176932bbaab493762eb1255a7900fe0fea1a2f96c296cc909" +dependencies = [ + "anyhow", + "indexmap", + "wasm-encoder", + "wasmparser", +] + +[[package]] +name = "wasm-streams" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "15053d8d85c7eccdbefef60f06769760a563c7f0a9d6902a13d35c7800b0ad65" +dependencies = [ + "futures-util", + "js-sys", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", +] + +[[package]] +name = "wasmparser" +version = "0.244.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47b807c72e1bac69382b3a6fb3dbe8ea4c0ed87ff5629b8685ae6b9a611028fe" +dependencies = [ + "bitflags", + "hashbrown 0.15.5", + "indexmap", + "semver", +] + +[[package]] +name = "web-sys" +version = "0.3.102" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6430a72df5eb332242960fe84b3002a241163998241eb596d4f739b9757061d" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "web-time" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a6580f308b1fad9207618087a65c04e7a10bc77e02c8e84e9b00dd4b12fa0bb" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "webpki-roots" +version = "0.25.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5f20c57d8d7db6d3b86154206ae5d8fba62dd39573114de97c2cb0578251f8e1" + +[[package]] +name = "webpki-roots" +version = "1.0.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bf85cb06032201fa7c6f829d7db5a7e5aa45bcc0655327713065f6f0576731bf" +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.118", +] + +[[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.118", +] + +[[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 = "wit-bindgen" +version = "0.51.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d7249219f66ced02969388cf2bb044a09756a083d0fab1e566056b04d9fbcaa5" +dependencies = [ + "wit-bindgen-rust-macro", +] + +[[package]] +name = "wit-bindgen" +version = "0.57.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e" + +[[package]] +name = "wit-bindgen-core" +version = "0.51.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ea61de684c3ea68cb082b7a88508a8b27fcc8b797d738bfc99a82facf1d752dc" +dependencies = [ + "anyhow", + "heck 0.5.0", + "wit-parser", +] + +[[package]] +name = "wit-bindgen-rust" +version = "0.51.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b7c566e0f4b284dd6561c786d9cb0142da491f46a9fbed79ea69cdad5db17f21" +dependencies = [ + "anyhow", + "heck 0.5.0", + "indexmap", + "prettyplease", + "syn 2.0.118", + "wasm-metadata", + "wit-bindgen-core", + "wit-component", +] + +[[package]] +name = "wit-bindgen-rust-macro" +version = "0.51.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c0f9bfd77e6a48eccf51359e3ae77140a7f50b1e2ebfe62422d8afdaffab17a" +dependencies = [ + "anyhow", + "prettyplease", + "proc-macro2", + "quote", + "syn 2.0.118", + "wit-bindgen-core", + "wit-bindgen-rust", +] + +[[package]] +name = "wit-component" +version = "0.244.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9d66ea20e9553b30172b5e831994e35fbde2d165325bec84fc43dbf6f4eb9cb2" +dependencies = [ + "anyhow", + "bitflags", + "indexmap", + "log", + "serde", + "serde_derive", + "serde_json", + "wasm-encoder", + "wasm-metadata", + "wasmparser", + "wit-parser", +] + +[[package]] +name = "wit-parser" +version = "0.244.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ecc8ac4bc1dc3381b7f59c34f00b67e18f910c2c0f50015669dde7def656a736" +dependencies = [ + "anyhow", + "id-arena", + "indexmap", + "log", + "semver", + "serde", + "serde_derive", + "serde_json", + "unicode-xid", + "wasmparser", +] + +[[package]] +name = "writeable" +version = "0.6.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ffae5123b2d3fc086436f8834ae3ab053a283cfac8fe0a0b8eaae044768a4c4" + +[[package]] +name = "yoke" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "709fe23a0424b6a435d82152b1bd3fdfb0833487d5fa90d05d42762a9891fef5" +dependencies = [ + "stable_deref_trait", + "yoke-derive", + "zerofrom", +] + +[[package]] +name = "yoke-derive" +version = "0.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "de844c262c8848816172cef550288e7dc6c7b7814b4ee56b3e1553f275f1858e" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.118", + "synstructure", +] + +[[package]] +name = "zerocopy" +version = "0.8.52" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce1022995ff5ff5d841ad7d994facc23098cd40152f2c1d11cd607c6f530653f" +dependencies = [ + "zerocopy-derive", +] + +[[package]] +name = "zerocopy-derive" +version = "0.8.52" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ae7f38b72ec2a254e2b87ef277cf2cd4fb97cbebf944faa6f33354da0867930" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.118", +] + +[[package]] +name = "zerofrom" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272" +dependencies = [ + "zerofrom-derive", +] + +[[package]] +name = "zerofrom-derive" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "11532158c46691caf0f2593ea8358fed6bbf68a0315e80aae9bd41fbade684a1" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.118", + "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.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0f9152d31db0792fa83f70fb2f83148effb5c1f5b8c7686c3459e361d9bc20bf" +dependencies = [ + "displaydoc", + "yoke", + "zerofrom", +] + +[[package]] +name = "zerovec" +version = "0.11.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "90f911cbc359ab6af17377d242225f4d75119aec87ea711a880987b18cd7b239" +dependencies = [ + "yoke", + "zerofrom", + "zerovec-derive", +] + +[[package]] +name = "zerovec-derive" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "625dc425cab0dca6dc3c3319506e6593dcb08a9f387ea3b284dbd52a92c40555" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.118", +] + +[[package]] +name = "zmij" +version = "1.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8848ee67ecc8aedbaf3e4122217aff892639231befc6a1b58d29fff4c2cabaa" diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..d6bed48 --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,33 @@ +[package] +name = "mercury" +version = "0.1.0" +edition = "2021" + +[[bin]] +name = "mercury" +path = "src/main.rs" + +[dependencies] +axum = { version = "0.7", features = ["macros", "multipart"] } +tokio = { version = "1", features = ["full"] } +sqlx = { version = "0.7", features = ["runtime-tokio-rustls", "postgres", "uuid", "chrono", "migrate"] } +serde = { version = "1", features = ["derive"] } +serde_json = "1" +jsonwebtoken = "9" +bcrypt = "0.15" +dashmap = "5" +glob = "0.3" +tower-http = { version = "0.5", features = ["fs", "cors"] } +reqwest = { version = "0.12", default-features = false, features = ["rustls-tls", "json", "stream"] } +tower = { version = "0.4", features = ["util"] } +uuid = { version = "1", features = ["v4", "serde"] } +chrono = { version = "0.4", features = ["serde"] } +dotenvy = "0.15" +anyhow = "1" +tracing = "0.1" +tracing-subscriber = { version = "0.3", features = ["env-filter"] } +sha2 = "0.10" + +[dev-dependencies] +tower = { version = "0.4", features = ["util"] } +http-body-util = "0.1" diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..a84c57e --- /dev/null +++ b/Dockerfile @@ -0,0 +1,48 @@ +# Stage 1: Build Vue UI +FROM oven/bun:1-alpine AS ui-builder +WORKDIR /ui +COPY ui/ . +RUN --mount=type=secret,id=bun_auth_token \ + printf '//git.mcpeakdev.com/api/packages/McPeakDev/npm/:_authToken=%s\n@nychthemeron:registry=https://git.mcpeakdev.com/api/packages/McPeakDev/npm/\n' \ + "$(cat /run/secrets/bun_auth_token)" > .npmrc && \ + bun install --frozen-lockfile +RUN bun run build + +# Stage 2: Build Rust API +FROM rust:1.96-slim AS api-builder +RUN apt-get update && apt-get install -y pkg-config libssl-dev && rm -rf /var/lib/apt/lists/* +WORKDIR /app +COPY Cargo.toml Cargo.lock ./ +COPY src/ src/ +RUN cargo build --release + +# Stage 3: Download MinIO and mc binaries +FROM alpine:3 AS minio-download +ARG TARGETARCH=amd64 +RUN wget -q "https://dl.min.io/server/minio/release/linux-${TARGETARCH}/minio" -O /minio && \ + chmod +x /minio && \ + wget -q "https://dl.min.io/client/mc/release/linux-${TARGETARCH}/mc" -O /mc && \ + chmod +x /mc + +# Stage 4: Final image +FROM postgres:16 +RUN apt-get update && apt-get install -y --no-install-recommends ca-certificates libssl3 && rm -rf /var/lib/apt/lists/* + +ENV PGDATA=/var/lib/postgresql/data +ENV DATABASE_URL=postgres://mercury:mercury@127.0.0.1/mercury +ENV MINIO_ROOT_USER=mercury +ENV MINIO_ROOT_PASSWORD=mercurycdn +ENV MINIO_VOLUMES=/var/lib/minio/data +ENV CDN_ENDPOINT=http://localhost:9000 +ENV CDN_BUCKET=mercury + +WORKDIR /app +COPY --from=api-builder /app/target/release/mercury . +COPY --from=ui-builder /ui/dist ./ui/dist +COPY --from=minio-download /minio /usr/local/bin/minio +COPY --from=minio-download /mc /usr/local/bin/mc +COPY entrypoint.sh /entrypoint.sh +RUN chmod +x /entrypoint.sh + +EXPOSE 3000 +ENTRYPOINT ["/entrypoint.sh"] diff --git a/README.md b/README.md new file mode 100644 index 0000000..2781a6a --- /dev/null +++ b/README.md @@ -0,0 +1,174 @@ +# Mercury + +A high-performance, monolithic Rust API with a dynamic CRUD engine, query registry cache, JWT bitmask permissions, and a Vue 3 admin frontend. + +![Login](pics/Mercury-Login.png) +![Permissions](pics/Mercury.png) + +## Quick Start + +```bash +cp .env.example .env # set JWT_SECRET +docker compose up --build +``` + +API: http://localhost:3000/api +Admin UI: http://localhost:3000 +Default credentials: `admin` / `admin` + +--- + +## API Contract + +### Authentication + +``` +POST /auth/login +Body: { "username": "...", "password": "..." } +Returns: { "token": "" } +``` + +All admin routes require `Authorization: Bearer `. + +--- + +### CRUD — Dynamic Table Access + +Requests are mapped to the named PostgreSQL table. The SQL is generated, cached, and executed automatically. + +``` +GET /api/{table} List all rows (supports ?col=val filters) +GET /api/{table}/{id} Get row by id +POST /api/{table} Insert row (JSON body) +PUT /api/{table}/{id} Update row by id (JSON body) +DELETE /api/{table}/{id} Delete row by id +``` + +**Notes:** +- `users` and `permissions` tables are blacklisted from public CRUD — use the admin suite. +- Filters are ANDed together: `GET /api/orders?status=open&priority=high` + +--- + +### Admin — Query Registry + +Requires JWT with `ADMIN_QUERY` permission (bit 8). + +``` +GET /admin/queries List all registered queries +POST /admin/queries Register a raw SQL template +GET /admin/queries/{identifier} Get query by slug +PUT /admin/queries/{identifier} Update SQL template or description +DELETE /admin/queries/{identifier} Remove query (evicts from cache) +GET /admin/queries/{identifier}/execute Execute query with ?param=val bindings +``` + +SQL templates use `:param_name` placeholders: +```sql +SELECT * FROM orders WHERE user_id = :user_id AND status = :status +``` + +--- + +### Admin — Cache + +Requires JWT with `ADMIN_CACHE` permission (bit 16). + +``` +GET /admin/cache/stats Cache size, hit count, miss count +DELETE /admin/cache Flush entire cache +``` + +--- + +### Admin — Users + +Requires JWT with `SUPER_ADMIN` permission (bit 32). + +``` +GET /admin/users List users +POST /admin/users Create user +GET /admin/users/{id} Get user +PUT /admin/users/{id} Update user +DELETE /admin/users/{id} Delete user +POST /admin/users/{id}/permissions/grant/{bit} OR bit into permissions mask +DELETE /admin/users/{id}/permissions/revoke/{bit} AND NOT bit from permissions mask +``` + +--- + +### Admin — Permissions + +Requires JWT with `SUPER_ADMIN` permission (bit 32). + +``` +GET /admin/permissions List permission definitions +POST /admin/permissions Create custom permission (auto-assigns next bit) +PUT /admin/permissions/{id} Update name/description +DELETE /admin/permissions/{id} Remove permission +``` + +--- + +### Admin — Route Blacklist + +Requires JWT with `SUPER_ADMIN` permission (bit 32). Changes take effect immediately in memory. + +``` +GET /admin/blacklist List all entries +POST /admin/blacklist Add glob pattern +PUT /admin/blacklist/{id} Update entry (set active: false to disable) +DELETE /admin/blacklist/{id} Remove entry +``` + +Pattern syntax: `*` matches one path segment, `**` matches many. +Example: `/api/sensitive/**` blocks all methods under that path. + +--- + +## Permission Bitmask + +| Name | Bit | Value | +|-------------|-----|-------| +| READ | 0 | 1 | +| WRITE | 1 | 2 | +| DELETE | 2 | 4 | +| ADMIN_QUERY | 3 | 8 | +| ADMIN_CACHE | 4 | 16 | +| SUPER_ADMIN | 5 | 32 | + +Custom permissions are added via the admin suite and assigned the next available power-of-2 bit. Masks support up to 128 bits (u128). + +--- + +## Configuration + +| Variable | Default | Description | +|---|---|---| +| `DATABASE_URL` | required | PostgreSQL connection string | +| `JWT_SECRET` | required | HMAC-HS256 signing secret | +| `JWT_EXPIRY_SECS` | 3600 | Token lifetime in seconds | +| `CACHE_MAX_CAPACITY` | 10000 | Max query templates in memory | +| `CACHE_IDLE_TIMEOUT_SECS` | 300 | Evict after N seconds idle | +| `CACHE_SWEEP_INTERVAL_SECS` | 60 | Sweep interval for eviction task | + +--- + +## Development + +```bash +# API only (requires local Postgres) +cargo run + +# UI dev server (proxies to local API) +cd ui && npm install && npm run dev + +# Full stack +docker compose up --build +``` + +## Stack + +- **API:** Rust, Axum, SQLx, PostgreSQL, DashMap, jsonwebtoken, bcrypt +- **Frontend:** Vue 3, Vite, @nychthemeron/library (dark mode default) +- **Infra:** Docker multi-stage build, docker compose diff --git a/dev.sh b/dev.sh new file mode 100755 index 0000000..b959777 --- /dev/null +++ b/dev.sh @@ -0,0 +1,15 @@ +#!/usr/bin/env bash +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" + +cd $SCRIPT_DIR/ui/ && bun i + +cd "$SCRIPT_DIR" + +cleanup() { + docker compose down +} +trap cleanup INT TERM + +docker compose up --build diff --git a/docker-compose.dev.yml b/docker-compose.dev.yml new file mode 100644 index 0000000..96aa935 --- /dev/null +++ b/docker-compose.dev.yml @@ -0,0 +1,4 @@ +# Reserved for future dev overrides. +# Port mapping omitted — dev.sh connects to the container's internal IP directly +# to avoid Docker Desktop WSL2 port-forwarding limitations. +services: {} diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 0000000..392bed6 --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,69 @@ +services: + db: + image: postgres:16-alpine + environment: + POSTGRES_USER: mercury + POSTGRES_PASSWORD: mercury + POSTGRES_DB: mercury + volumes: + - postgres_data:/var/lib/postgresql/data + healthcheck: + test: ["CMD-SHELL", "pg_isready -U mercury"] + interval: 5s + timeout: 5s + retries: 5 + + cdn: + image: minio/minio + command: server /data --console-address ":9001" + environment: + MINIO_ROOT_USER: mercury + MINIO_ROOT_PASSWORD: mercurycdn + volumes: + - cdn_data:/data + healthcheck: + test: ["CMD", "mc", "ready", "local"] + interval: 5s + timeout: 5s + retries: 10 + + cdn-init: + image: minio/mc + depends_on: + cdn: + condition: service_healthy + entrypoint: > + /bin/sh -c " + mc alias set local http://cdn:9000 mercury mercurycdn && + mc mb --ignore-existing local/mercury && + mc anonymous set public local/mercury && + echo 'CDN bucket ready' + " + restart: on-failure + + api: + build: . + ports: + - "3000:3000" + environment: + DATABASE_URL: postgres://mercury:mercury@db:5432/mercury + JWT_SECRET: ${JWT_SECRET:-change_me_in_production} + JWT_EXPIRY_SECS: ${JWT_EXPIRY_SECS:-3600} + CACHE_MAX_CAPACITY: ${CACHE_MAX_CAPACITY:-10000} + CACHE_IDLE_TIMEOUT_SECS: ${CACHE_IDLE_TIMEOUT_SECS:-300} + CACHE_SWEEP_INTERVAL_SECS: ${CACHE_SWEEP_INTERVAL_SECS:-60} + CDN_ENDPOINT: http://cdn:9000 + CDN_BUCKET: mercury + MERCURY_ADMIN_USER: test + MERCURY_ADMIN_PASSWORD: test + depends_on: + db: + condition: service_healthy + cdn: + condition: service_healthy + mem_limit: 512m + mem_reservation: 256m + +volumes: + postgres_data: + cdn_data: diff --git a/docs/superpowers/plans/2026-06-16-mercury-implementation.md b/docs/superpowers/plans/2026-06-16-mercury-implementation.md new file mode 100644 index 0000000..98a116f --- /dev/null +++ b/docs/superpowers/plans/2026-06-16-mercury-implementation.md @@ -0,0 +1,3438 @@ +# Mercury Implementation Plan + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** Build Mercury — a monolithic Rust API with dynamic CRUD, a JWT bitmask permission system, a query registry cache, an admin suite, and a Vue 3 frontend — runnable via a single `docker compose up`. + +**Architecture:** Axum handles HTTP routing behind two middleware layers: a glob-based blacklist check and a JWT permission-bit validator. The CRUD engine auto-generates parameterized SQL from route + HTTP method, caches templates in a DashMap with TTI eviction, and persists named queries in PostgreSQL. Vue 3 is built by Vite and served as static files by `tower-http::ServeDir`. + +**Tech Stack:** Rust 1.75+, Axum 0.7, SQLx 0.7, PostgreSQL 16, DashMap 5, glob 0.3, jsonwebtoken 9, bcrypt 0.15, Vue 3, Vite, @nychthemeron/library, tower-http 0.5, Docker multi-stage build. + +--- + +## File Map + +``` +Mercury/ + Cargo.toml + .env.example + Dockerfile + docker-compose.yml + README.md + src/ + main.rs startup: config, pool, caches, router, static files + config.rs Config struct from env vars + state.rs AppState, QueryCache, BlacklistCache types + auth/ + mod.rs JWT Claims, encode/decode helpers + middleware.rs RequirePermission extractor + cache/ + mod.rs pub use re-exports + query_cache.rs DashMap + sweep task + hit/miss counters + blacklist_cache.rs Arc>> + reload fn + db/ + mod.rs pub use re-exports + pool.rs PgPool init + run migrations + migrations/ + 001_initial.sql schema, seed permissions, seed blacklist + models/ + mod.rs pub use re-exports + user.rs User, CreateUser, UpdateUser + permission.rs Permission, CreatePermission, UpdatePermission + query.rs StoredQuery, CreateQuery, UpdateQuery + blacklist.rs BlacklistEntry, CreateBlacklistEntry, UpdateBlacklistEntry + routes/ + mod.rs pub use re-exports + auth.rs POST /auth/login + crud.rs generic /api/{table} + query builder + row→JSON + admin/ + mod.rs admin Router assembly + queries.rs query registry CRUD + cache.rs cache stats + flush + users.rs user management + grant/revoke + permissions.rs permission definitions CRUD + blacklist.rs blacklist CRUD + trigger reload + ui/ + .npmrc + package.json + vite.config.ts + src/ + main.ts + App.vue + router/index.ts + stores/auth.ts + views/ + Login.vue + admin/ + Layout.vue + Queries.vue + Users.vue + Permissions.vue + Blacklist.vue + Cache.vue + tests/ + integration/ + auth_test.rs + crud_test.rs + admin_test.rs +``` + +--- + +## Task 1: Cargo.toml + project skeleton + +**Files:** +- Create: `Cargo.toml` +- Create: `src/main.rs` (stub) + +- [ ] **Step 1: Write Cargo.toml** + +```toml +[package] +name = "mercury" +version = "0.1.0" +edition = "2021" + +[[bin]] +name = "mercury" +path = "src/main.rs" + +[dependencies] +axum = { version = "0.7", features = ["macros"] } +tokio = { version = "1", features = ["full"] } +sqlx = { version = "0.7", features = ["runtime-tokio-rustls", "postgres", "uuid", "chrono", "migrate"] } +serde = { version = "1", features = ["derive"] } +serde_json = "1" +jsonwebtoken = "9" +bcrypt = "0.15" +dashmap = "5" +glob = "0.3" +tower-http = { version = "0.5", features = ["fs", "cors"] } +tower = { version = "0.4", features = ["util"] } +uuid = { version = "1", features = ["v4", "serde"] } +chrono = { version = "0.4", features = ["serde"] } +dotenvy = "0.15" +anyhow = "1" +tracing = "0.1" +tracing-subscriber = { version = "0.3", features = ["env-filter"] } + +[dev-dependencies] +tower = { version = "0.4", features = ["util"] } +http-body-util = "0.1" +``` + +- [ ] **Step 2: Write src/main.rs stub** + +```rust +#[tokio::main] +async fn main() { + println!("Mercury starting..."); +} +``` + +- [ ] **Step 3: Verify it compiles** + +```bash +cargo build +``` +Expected: `Compiling mercury v0.1.0` then `Finished`. + +- [ ] **Step 4: Commit** + +```bash +git add Cargo.toml src/main.rs +git commit -m "chore: init Mercury project scaffold" +``` + +--- + +## Task 2: Config + +**Files:** +- Create: `src/config.rs` +- Create: `.env.example` + +- [ ] **Step 1: Write failing test** + +In `src/config.rs`: + +```rust +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_config_defaults() { + std::env::set_var("DATABASE_URL", "postgres://test"); + std::env::set_var("JWT_SECRET", "secret"); + let cfg = Config::from_env().unwrap(); + assert_eq!(cfg.jwt_expiry_secs, 3600); + assert_eq!(cfg.cache_max_capacity, 10_000); + assert_eq!(cfg.cache_idle_timeout_secs, 300); + assert_eq!(cfg.cache_sweep_interval_secs, 60); + } +} +``` + +- [ ] **Step 2: Run test — expect compile failure** + +```bash +cargo test config +``` +Expected: `error[E0433]: failed to resolve: use of undeclared crate or module` + +- [ ] **Step 3: Implement Config** + +```rust +use anyhow::Result; + +#[derive(Clone, Debug)] +pub struct Config { + pub database_url: String, + pub jwt_secret: String, + pub jwt_expiry_secs: u64, + pub cache_max_capacity: usize, + pub cache_idle_timeout_secs: u64, + pub cache_sweep_interval_secs: u64, +} + +impl Config { + pub fn from_env() -> Result { + Ok(Self { + database_url: std::env::var("DATABASE_URL")?, + jwt_secret: std::env::var("JWT_SECRET")?, + jwt_expiry_secs: std::env::var("JWT_EXPIRY_SECS") + .unwrap_or_else(|_| "3600".into()) + .parse()?, + cache_max_capacity: std::env::var("CACHE_MAX_CAPACITY") + .unwrap_or_else(|_| "10000".into()) + .parse()?, + cache_idle_timeout_secs: std::env::var("CACHE_IDLE_TIMEOUT_SECS") + .unwrap_or_else(|_| "300".into()) + .parse()?, + cache_sweep_interval_secs: std::env::var("CACHE_SWEEP_INTERVAL_SECS") + .unwrap_or_else(|_| "60".into()) + .parse()?, + }) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_config_defaults() { + std::env::set_var("DATABASE_URL", "postgres://test"); + std::env::set_var("JWT_SECRET", "secret"); + let cfg = Config::from_env().unwrap(); + assert_eq!(cfg.jwt_expiry_secs, 3600); + assert_eq!(cfg.cache_max_capacity, 10_000); + assert_eq!(cfg.cache_idle_timeout_secs, 300); + assert_eq!(cfg.cache_sweep_interval_secs, 60); + } +} +``` + +- [ ] **Step 4: Add to main.rs and run test** + +Add `mod config;` to `src/main.rs`. Then: + +```bash +cargo test config +``` +Expected: `test config::tests::test_config_defaults ... ok` + +- [ ] **Step 5: Write .env.example** + +```env +DATABASE_URL=postgres://mercury:mercury@db:5432/mercury +JWT_SECRET=change_me_in_production +JWT_EXPIRY_SECS=3600 +CACHE_MAX_CAPACITY=10000 +CACHE_IDLE_TIMEOUT_SECS=300 +CACHE_SWEEP_INTERVAL_SECS=60 +``` + +- [ ] **Step 6: Commit** + +```bash +git add src/config.rs src/main.rs .env.example +git commit -m "feat: add Config struct loaded from env vars" +``` + +--- + +## Task 3: Models + +**Files:** +- Create: `src/models/mod.rs` +- Create: `src/models/user.rs` +- Create: `src/models/permission.rs` +- Create: `src/models/query.rs` +- Create: `src/models/blacklist.rs` + +- [ ] **Step 1: Write src/models/user.rs** + +```rust +use chrono::{DateTime, Utc}; +use serde::{Deserialize, Serialize}; + +#[derive(Debug, Clone, Serialize, Deserialize, sqlx::FromRow)] +pub struct User { + pub id: i32, + pub username: String, + #[serde(skip_serializing)] + pub password_hash: String, + pub permissions_mask: String, + pub created_at: DateTime, +} + +#[derive(Debug, Deserialize)] +pub struct CreateUser { + pub username: String, + pub password: String, + pub permissions_mask: Option, +} + +#[derive(Debug, Deserialize)] +pub struct UpdateUser { + pub username: Option, + pub password: Option, + pub permissions_mask: Option, +} + +#[derive(Debug, Deserialize)] +pub struct LoginRequest { + pub username: String, + pub password: String, +} +``` + +- [ ] **Step 2: Write src/models/permission.rs** + +```rust +use serde::{Deserialize, Serialize}; + +#[derive(Debug, Clone, Serialize, Deserialize, sqlx::FromRow)] +pub struct Permission { + pub id: i32, + pub name: String, + pub bit_value: String, + pub description: Option, +} + +#[derive(Debug, Deserialize)] +pub struct CreatePermission { + pub name: String, + pub description: Option, +} + +#[derive(Debug, Deserialize)] +pub struct UpdatePermission { + pub name: Option, + pub description: Option, +} +``` + +- [ ] **Step 3: Write src/models/query.rs** + +```rust +use chrono::{DateTime, Utc}; +use serde::{Deserialize, Serialize}; +use uuid::Uuid; + +#[derive(Debug, Clone, Serialize, Deserialize, sqlx::FromRow)] +pub struct StoredQuery { + pub id: Uuid, + pub identifier: String, + pub sql_template: String, + pub description: Option, + pub created_at: DateTime, + pub updated_at: DateTime, +} + +#[derive(Debug, Deserialize)] +pub struct CreateQuery { + pub identifier: String, + pub sql_template: String, + pub description: Option, +} + +#[derive(Debug, Deserialize)] +pub struct UpdateQuery { + pub sql_template: Option, + pub description: Option, +} +``` + +- [ ] **Step 4: Write src/models/blacklist.rs** + +```rust +use chrono::{DateTime, Utc}; +use serde::{Deserialize, Serialize}; + +#[derive(Debug, Clone, Serialize, Deserialize, sqlx::FromRow)] +pub struct BlacklistEntry { + pub id: i32, + pub pattern: String, + pub method: Option, + pub reason: Option, + pub active: bool, + pub created_at: DateTime, +} + +#[derive(Debug, Deserialize)] +pub struct CreateBlacklistEntry { + pub pattern: String, + pub method: Option, + pub reason: Option, +} + +#[derive(Debug, Deserialize)] +pub struct UpdateBlacklistEntry { + pub pattern: Option, + pub method: Option, + pub reason: Option, + pub active: Option, +} +``` + +- [ ] **Step 5: Write src/models/mod.rs** + +```rust +pub mod blacklist; +pub mod permission; +pub mod query; +pub mod user; +``` + +- [ ] **Step 6: Add mod to main.rs and compile** + +Add `mod models;` to `src/main.rs`. + +```bash +cargo build +``` +Expected: `Finished` with no errors. + +- [ ] **Step 7: Commit** + +```bash +git add src/models/ +git commit -m "feat: add domain models for user, permission, query, blacklist" +``` + +--- + +## Task 4: Database pool + migration + +**Files:** +- Create: `src/db/mod.rs` +- Create: `src/db/pool.rs` +- Create: `src/db/migrations/001_initial.sql` + +- [ ] **Step 1: Write src/db/migrations/001_initial.sql** + +```sql +CREATE EXTENSION IF NOT EXISTS pgcrypto; + +CREATE TABLE users ( + id SERIAL PRIMARY KEY, + username VARCHAR(255) UNIQUE NOT NULL, + password_hash TEXT NOT NULL, + permissions_mask TEXT NOT NULL DEFAULT '0', + created_at TIMESTAMPTZ NOT NULL DEFAULT now() +); + +CREATE TABLE permissions ( + id SERIAL PRIMARY KEY, + name VARCHAR(255) UNIQUE NOT NULL, + bit_value TEXT UNIQUE NOT NULL, + description TEXT +); + +CREATE TABLE queries ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + identifier VARCHAR(255) UNIQUE NOT NULL, + sql_template TEXT NOT NULL, + description TEXT, + created_at TIMESTAMPTZ NOT NULL DEFAULT now(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT now() +); + +CREATE TABLE blacklist ( + id SERIAL PRIMARY KEY, + pattern VARCHAR(500) NOT NULL, + method VARCHAR(10), + reason TEXT, + active BOOLEAN NOT NULL DEFAULT true, + created_at TIMESTAMPTZ NOT NULL DEFAULT now() +); + +-- Seed permissions +INSERT INTO permissions (name, bit_value, description) VALUES + ('READ', '1', 'Can read via CRUD endpoints'), + ('WRITE', '2', 'Can insert/update via CRUD'), + ('DELETE', '4', 'Can delete via CRUD'), + ('ADMIN_QUERY', '8', 'Can manage query registry'), + ('ADMIN_CACHE', '16', 'Can manage cache'), + ('SUPER_ADMIN', '32', 'Full access'); + +-- Seed blacklist (users and permissions tables are admin-only) +INSERT INTO blacklist (pattern, method, reason, active) VALUES + ('/api/users/**', NULL, 'admin-only table', true), + ('/api/permissions/**', NULL, 'admin-only table', true); +``` + +- [ ] **Step 2: Write src/db/pool.rs** + +```rust +use anyhow::Result; +use sqlx::{postgres::PgPoolOptions, PgPool}; + +pub async fn create_pool(database_url: &str) -> Result { + let pool = PgPoolOptions::new() + .max_connections(10) + .connect(database_url) + .await?; + sqlx::migrate!("src/db/migrations").run(&pool).await?; + Ok(pool) +} +``` + +- [ ] **Step 3: Write src/db/mod.rs** + +```rust +pub mod pool; +pub use pool::create_pool; +``` + +- [ ] **Step 4: Add mod to main.rs and compile** + +Add `mod db;` to `src/main.rs`. + +```bash +cargo build +``` +Expected: `Finished` with no errors. + +- [ ] **Step 5: Commit** + +```bash +git add src/db/ +git commit -m "feat: add database pool and initial migration" +``` + +--- + +## Task 5: AppState + +**Files:** +- Create: `src/state.rs` + +- [ ] **Step 1: Write src/state.rs** + +```rust +use std::sync::{ + atomic::{AtomicU64, Ordering}, + Arc, +}; +use std::time::{SystemTime, UNIX_EPOCH}; + +use dashmap::DashMap; +use glob::Pattern; +use sqlx::PgPool; +use tokio::sync::RwLock; + +use crate::config::Config; +use crate::models::blacklist::BlacklistEntry; + +pub fn unix_now() -> u64 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap() + .as_secs() +} + +#[derive(Clone)] +pub struct AppState { + pub pool: PgPool, + pub query_cache: QueryCache, + pub blacklist_cache: BlacklistCache, + pub config: Arc, +} + +#[derive(Clone)] +pub struct QueryCache { + pub map: Arc>, + pub hits: Arc, + pub misses: Arc, +} + +#[derive(Clone, Debug)] +pub struct CacheEntry { + pub sql: String, + pub param_order: Vec, + pub last_accessed_secs: Arc, +} + +impl CacheEntry { + pub fn new(sql: String, param_order: Vec) -> Self { + Self { + sql, + param_order, + last_accessed_secs: Arc::new(AtomicU64::new(unix_now())), + } + } + + pub fn touch(&self) { + self.last_accessed_secs.store(unix_now(), Ordering::Relaxed); + } + + pub fn last_accessed(&self) -> u64 { + self.last_accessed_secs.load(Ordering::Relaxed) + } +} + +impl QueryCache { + pub fn new() -> Self { + Self { + map: Arc::new(DashMap::new()), + hits: Arc::new(AtomicU64::new(0)), + misses: Arc::new(AtomicU64::new(0)), + } + } + + pub fn get(&self, key: &str) -> Option { + if let Some(entry) = self.map.get(key) { + entry.touch(); + self.hits.fetch_add(1, Ordering::Relaxed); + Some(entry.clone()) + } else { + self.misses.fetch_add(1, Ordering::Relaxed); + None + } + } + + pub fn insert(&self, key: String, entry: CacheEntry, max_capacity: usize) { + if self.map.len() >= max_capacity { + let oldest_key = self + .map + .iter() + .min_by_key(|e| e.last_accessed()) + .map(|e| e.key().clone()); + if let Some(k) = oldest_key { + self.map.remove(&k); + } + } + self.map.insert(key, entry); + } + + pub fn remove(&self, key: &str) { + self.map.remove(key); + } + + pub fn hits(&self) -> u64 { + self.hits.load(Ordering::Relaxed) + } + + pub fn misses(&self) -> u64 { + self.misses.load(Ordering::Relaxed) + } + + pub fn len(&self) -> usize { + self.map.len() + } + + pub fn flush(&self) { + self.map.clear(); + } +} + +#[derive(Clone)] +pub struct BlacklistCache { + pub inner: Arc>>, +} + +#[derive(Clone)] +pub struct CompiledEntry { + pub entry: BlacklistEntry, + pub pattern: Pattern, +} + +impl BlacklistCache { + pub fn new() -> Self { + Self { + inner: Arc::new(RwLock::new(Vec::new())), + } + } + + pub async fn load(&self, entries: Vec) { + let compiled: Vec = entries + .into_iter() + .filter_map(|e| { + Pattern::new(&e.pattern) + .ok() + .map(|pattern| CompiledEntry { entry: e, pattern }) + }) + .collect(); + let mut guard = self.inner.write().await; + *guard = compiled; + } + + pub async fn is_blocked(&self, method: &str, path: &str) -> bool { + let guard = self.inner.read().await; + guard.iter().any(|compiled| { + if !compiled.entry.active { + return false; + } + let method_matches = compiled + .entry + .method + .as_deref() + .map(|m| m.eq_ignore_ascii_case(method)) + .unwrap_or(true); + method_matches && compiled.pattern.matches(path) + }) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_cache_insert_and_get() { + let cache = QueryCache::new(); + let entry = CacheEntry::new("SELECT 1".into(), vec![]); + cache.insert("key1".into(), entry, 100); + let got = cache.get("key1"); + assert!(got.is_some()); + assert_eq!(got.unwrap().sql, "SELECT 1"); + assert_eq!(cache.hits(), 1); + assert_eq!(cache.misses(), 0); + } + + #[test] + fn test_cache_miss() { + let cache = QueryCache::new(); + let got = cache.get("missing"); + assert!(got.is_none()); + assert_eq!(cache.misses(), 1); + } + + #[test] + fn test_cache_capacity_evicts_oldest() { + let cache = QueryCache::new(); + let e1 = CacheEntry::new("SELECT 1".into(), vec![]); + // force e1 to be older + e1.last_accessed_secs.store(1, Ordering::Relaxed); + cache.map.insert("old".into(), e1); + let e2 = CacheEntry::new("SELECT 2".into(), vec![]); + cache.insert("new".into(), e2, 1); // capacity=1, should evict "old" + assert!(cache.map.get("old").is_none()); + assert!(cache.map.get("new").is_some()); + } + + #[tokio::test] + async fn test_blacklist_blocks_pattern() { + use chrono::Utc; + let cache = BlacklistCache::new(); + let entry = BlacklistEntry { + id: 1, + pattern: "/api/users/**".into(), + method: None, + reason: None, + active: true, + created_at: Utc::now(), + }; + cache.load(vec![entry]).await; + assert!(cache.is_blocked("GET", "/api/users/42").await); + assert!(!cache.is_blocked("GET", "/api/orders/1").await); + } + + #[tokio::test] + async fn test_blacklist_method_specific() { + use chrono::Utc; + let cache = BlacklistCache::new(); + let entry = BlacklistEntry { + id: 2, + pattern: "/api/secrets".into(), + method: Some("GET".into()), + reason: None, + active: true, + created_at: Utc::now(), + }; + cache.load(vec![entry]).await; + assert!(cache.is_blocked("GET", "/api/secrets").await); + assert!(!cache.is_blocked("POST", "/api/secrets").await); + } +} +``` + +- [ ] **Step 2: Add mod to main.rs** + +Add `mod state;` to `src/main.rs`. + +- [ ] **Step 3: Run tests** + +```bash +cargo test state +``` +Expected: 4 tests pass. + +- [ ] **Step 4: Commit** + +```bash +git add src/state.rs src/main.rs +git commit -m "feat: add AppState with QueryCache and BlacklistCache" +``` + +--- + +## Task 6: Cache sweep background task + +**Files:** +- Create: `src/cache/mod.rs` +- Create: `src/cache/sweep.rs` + +- [ ] **Step 1: Write src/cache/sweep.rs** + +```rust +use std::time::Duration; +use crate::state::QueryCache; + +pub fn spawn_sweep_task(cache: QueryCache, idle_timeout_secs: u64, sweep_interval_secs: u64) { + tokio::spawn(async move { + let interval = Duration::from_secs(sweep_interval_secs); + loop { + tokio::time::sleep(interval).await; + let now = crate::state::unix_now(); + cache.map.retain(|_, entry| { + now.saturating_sub(entry.last_accessed()) < idle_timeout_secs + }); + } + }); +} +``` + +- [ ] **Step 2: Write src/cache/mod.rs** + +```rust +pub mod sweep; +pub use sweep::spawn_sweep_task; +``` + +- [ ] **Step 3: Add mod to main.rs and compile** + +Add `mod cache;` to `src/main.rs`. + +```bash +cargo build +``` +Expected: `Finished` with no errors. + +- [ ] **Step 4: Commit** + +```bash +git add src/cache/ +git commit -m "feat: add cache sweep background task for TTI eviction" +``` + +--- + +## Task 7: JWT auth module + +**Files:** +- Create: `src/auth/mod.rs` + +- [ ] **Step 1: Write failing tests** + +```rust +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_encode_decode_roundtrip() { + let secret = "test_secret"; + let token = encode_jwt("alice", 63u128, secret, 3600).unwrap(); + let claims = decode_jwt(&token, secret).unwrap(); + assert_eq!(claims.sub, "alice"); + assert_eq!(claims.permissions_mask(), 63u128); + } + + #[test] + fn test_expired_token_rejected() { + let secret = "test_secret"; + let token = encode_jwt("alice", 1u128, secret, 0).unwrap(); + // exp=0 means already expired + let result = decode_jwt(&token, secret); + assert!(result.is_err()); + } +} +``` + +- [ ] **Step 2: Run test — expect compile failure** + +```bash +cargo test auth +``` + +- [ ] **Step 3: Implement src/auth/mod.rs** + +```rust +pub mod middleware; + +use anyhow::Result; +use chrono::Utc; +use jsonwebtoken::{decode, encode, DecodingKey, EncodingKey, Header, Validation}; +use serde::{Deserialize, Serialize}; + +pub mod permissions { + pub const READ: u128 = 1; + pub const WRITE: u128 = 2; + pub const DELETE: u128 = 4; + pub const ADMIN_QUERY: u128 = 8; + pub const ADMIN_CACHE: u128 = 16; + pub const SUPER_ADMIN: u128 = 32; +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct Claims { + pub sub: String, + pub permissions: String, // u128 stored as decimal string + pub exp: usize, +} + +impl Claims { + pub fn permissions_mask(&self) -> u128 { + self.permissions.parse().unwrap_or(0) + } + + pub fn has_permission(&self, bit: u128) -> bool { + self.permissions_mask() & bit != 0 + } +} + +pub fn encode_jwt(username: &str, mask: u128, secret: &str, expiry_secs: u64) -> Result { + let exp = (Utc::now().timestamp() as u64 + expiry_secs) as usize; + let claims = Claims { + sub: username.to_string(), + permissions: mask.to_string(), + exp, + }; + let token = encode( + &Header::default(), + &claims, + &EncodingKey::from_secret(secret.as_bytes()), + )?; + Ok(token) +} + +pub fn decode_jwt(token: &str, secret: &str) -> Result { + let data = decode::( + token, + &DecodingKey::from_secret(secret.as_bytes()), + &Validation::default(), + )?; + Ok(data.claims) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_encode_decode_roundtrip() { + let secret = "test_secret"; + let token = encode_jwt("alice", 63u128, secret, 3600).unwrap(); + let claims = decode_jwt(&token, secret).unwrap(); + assert_eq!(claims.sub, "alice"); + assert_eq!(claims.permissions_mask(), 63u128); + } + + #[test] + fn test_has_permission() { + let claims = Claims { + sub: "bob".into(), + permissions: "9".into(), // READ (1) + ADMIN_QUERY (8) + exp: 9999999999, + }; + assert!(claims.has_permission(permissions::READ)); + assert!(claims.has_permission(permissions::ADMIN_QUERY)); + assert!(!claims.has_permission(permissions::SUPER_ADMIN)); + } +} +``` + +- [ ] **Step 4: Create stub for middleware (needed for mod declaration)** + +Create `src/auth/middleware.rs` as an empty stub: + +```rust +// filled in Task 8 +``` + +- [ ] **Step 5: Add mod to main.rs and run tests** + +Add `mod auth;` to `src/main.rs`. + +```bash +cargo test auth::tests +``` +Expected: 2 tests pass (`test_encode_decode_roundtrip`, `test_has_permission`). + +- [ ] **Step 6: Commit** + +```bash +git add src/auth/ +git commit -m "feat: add JWT encode/decode with u128 bitmask permissions" +``` + +--- + +## Task 8: Auth middleware + blacklist middleware + +**Files:** +- Modify: `src/auth/middleware.rs` + +- [ ] **Step 1: Write src/auth/middleware.rs** + +```rust +use axum::{ + extract::{Request, State}, + http::StatusCode, + middleware::Next, + response::Response, +}; + +use crate::{auth::decode_jwt, state::AppState}; + +pub async fn blacklist_layer( + State(state): State, + req: Request, + next: Next, +) -> Result { + let method = req.method().as_str().to_uppercase(); + let path = req.uri().path().to_string(); + if state.blacklist_cache.is_blocked(&method, &path).await { + return Err(StatusCode::FORBIDDEN); + } + Ok(next.run(req).await) +} + +pub fn extract_bearer(req: &Request) -> Option { + req.headers() + .get("authorization") + .and_then(|v| v.to_str().ok()) + .and_then(|v| v.strip_prefix("Bearer ")) + .map(|s| s.to_string()) +} + +pub async fn require_auth( + State(state): State, + mut req: Request, + next: Next, +) -> Result { + let token = extract_bearer(&req).ok_or(StatusCode::UNAUTHORIZED)?; + let claims = decode_jwt(&token, &state.config.jwt_secret) + .map_err(|_| StatusCode::UNAUTHORIZED)?; + req.extensions_mut().insert(claims); + Ok(next.run(req).await) +} + +pub async fn require_super_admin( + State(state): State, + mut req: Request, + next: Next, +) -> Result { + let token = extract_bearer(&req).ok_or(StatusCode::UNAUTHORIZED)?; + let claims = decode_jwt(&token, &state.config.jwt_secret) + .map_err(|_| StatusCode::UNAUTHORIZED)?; + if !claims.has_permission(crate::auth::permissions::SUPER_ADMIN) { + return Err(StatusCode::FORBIDDEN); + } + req.extensions_mut().insert(claims); + Ok(next.run(req).await) +} + +pub async fn require_admin_query( + State(state): State, + mut req: Request, + next: Next, +) -> Result { + let token = extract_bearer(&req).ok_or(StatusCode::UNAUTHORIZED)?; + let claims = decode_jwt(&token, &state.config.jwt_secret) + .map_err(|_| StatusCode::UNAUTHORIZED)?; + if !claims.has_permission(crate::auth::permissions::ADMIN_QUERY) { + return Err(StatusCode::FORBIDDEN); + } + req.extensions_mut().insert(claims); + Ok(next.run(req).await) +} + +pub async fn require_admin_cache( + State(state): State, + mut req: Request, + next: Next, +) -> Result { + let token = extract_bearer(&req).ok_or(StatusCode::UNAUTHORIZED)?; + let claims = decode_jwt(&token, &state.config.jwt_secret) + .map_err(|_| StatusCode::UNAUTHORIZED)?; + if !claims.has_permission(crate::auth::permissions::ADMIN_CACHE) { + return Err(StatusCode::FORBIDDEN); + } + req.extensions_mut().insert(claims); + Ok(next.run(req).await) +} +``` + +- [ ] **Step 2: Compile** + +```bash +cargo build +``` +Expected: `Finished` with no errors. + +- [ ] **Step 3: Commit** + +```bash +git add src/auth/middleware.rs +git commit -m "feat: add blacklist and JWT permission middlewares" +``` + +--- + +## Task 9: Auth login route + +**Files:** +- Create: `src/routes/mod.rs` +- Create: `src/routes/auth.rs` + +- [ ] **Step 1: Write src/routes/auth.rs** + +```rust +use axum::{extract::State, http::StatusCode, Json}; +use serde_json::{json, Value}; + +use crate::{ + auth::encode_jwt, + models::user::LoginRequest, + state::AppState, +}; + +pub async fn login( + State(state): State, + Json(body): Json, +) -> Result, StatusCode> { + let user = sqlx::query_as!( + crate::models::user::User, + "SELECT id, username, password_hash, permissions_mask, created_at FROM users WHERE username = $1", + body.username + ) + .fetch_optional(&state.pool) + .await + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)? + .ok_or(StatusCode::UNAUTHORIZED)?; + + let valid = bcrypt::verify(&body.password, &user.password_hash) + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; + + if !valid { + return Err(StatusCode::UNAUTHORIZED); + } + + let mask: u128 = user.permissions_mask.parse().unwrap_or(0); + let token = encode_jwt(&user.username, mask, &state.config.jwt_secret, state.config.jwt_expiry_secs) + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; + + Ok(Json(json!({ "token": token }))) +} +``` + +- [ ] **Step 2: Write src/routes/mod.rs** + +```rust +pub mod admin; +pub mod auth; +pub mod crud; +``` + +- [ ] **Step 3: Create stub files to satisfy mod declarations** + +Create `src/routes/crud.rs`: +```rust +// filled in Task 10 +``` + +Create `src/routes/admin/mod.rs`: +```rust +// filled in Task 15 +``` + +- [ ] **Step 4: Add mod to main.rs and compile** + +Add `mod routes;` to `src/main.rs`. + +```bash +cargo build +``` +Expected: `Finished`. + +- [ ] **Step 5: Commit** + +```bash +git add src/routes/ +git commit -m "feat: add /auth/login route with bcrypt verification" +``` + +--- + +## Task 10: CRUD route + query builder + +**Files:** +- Modify: `src/routes/crud.rs` + +- [ ] **Step 1: Write failing test** + +In `src/routes/crud.rs`: + +```rust +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_build_select_all() { + let (sql, params, key) = build_query("GET", "orders", None, &[], &[]).unwrap(); + assert_eq!(sql, "SELECT * FROM orders"); + assert!(params.is_empty()); + assert_eq!(key, "GET:orders:"); + } + + #[test] + fn test_build_select_by_id() { + let (sql, params, key) = build_query("GET", "orders", Some("42"), &[], &[]).unwrap(); + assert_eq!(sql, "SELECT * FROM orders WHERE id = $1"); + assert_eq!(params, vec!["42".to_string()]); + assert_eq!(key, "GET:orders:by_id"); + } + + #[test] + fn test_build_insert() { + let cols = vec![("email".into(), "a@b.com".into()), ("name".into(), "Alice".into())]; + let (sql, params, key) = build_query("POST", "users", None, &cols, &[]).unwrap(); + assert_eq!(sql, "INSERT INTO users (email, name) VALUES ($1, $2) RETURNING *"); + assert_eq!(params, vec!["a@b.com", "Alice"]); + assert_eq!(key, "POST:users:email,name"); + } + + #[test] + fn test_build_update() { + let cols = vec![("name".into(), "Bob".into())]; + let (sql, params, key) = build_query("PUT", "users", Some("7"), &cols, &[]).unwrap(); + assert_eq!(sql, "UPDATE users SET name = $1 WHERE id = $2 RETURNING *"); + assert_eq!(params, vec!["Bob", "7"]); + assert_eq!(key, "PUT:users:name:by_id"); + } + + #[test] + fn test_build_delete() { + let (sql, params, key) = build_query("DELETE", "users", Some("3"), &[], &[]).unwrap(); + assert_eq!(sql, "DELETE FROM users WHERE id = $1"); + assert_eq!(params, vec!["3"]); + assert_eq!(key, "DELETE:users:by_id"); + } + + #[test] + fn test_build_select_with_filters() { + let filters = vec![("status".into(), "active".into()), ("role".into(), "admin".into())]; + let (sql, params, key) = build_query("GET", "users", None, &[], &filters).unwrap(); + assert_eq!(sql, "SELECT * FROM users WHERE role = $1 AND status = $2"); + assert_eq!(params, vec!["admin", "active"]); + assert_eq!(key, "GET:users:role,status"); + } + + #[test] + fn test_rejects_invalid_table_name() { + let result = build_query("GET", "users; DROP TABLE users--", None, &[], &[]); + assert!(result.is_err()); + } +} +``` + +- [ ] **Step 2: Run test — expect compile failure** + +```bash +cargo test crud +``` + +- [ ] **Step 3: Implement src/routes/crud.rs** + +```rust +use anyhow::{anyhow, Result}; +use axum::{ + extract::{Path, Query, State}, + http::{Method, StatusCode}, + Json, +}; +use serde_json::Value; +use sqlx::postgres::PgRow; +use sqlx::Row; +use std::collections::HashMap; + +use crate::state::{AppState, CacheEntry}; + +fn validate_identifier(name: &str) -> Result<()> { + if name.chars().all(|c| c.is_alphanumeric() || c == '_') { + Ok(()) + } else { + Err(anyhow!("invalid identifier: {}", name)) + } +} + +/// Returns (sql, ordered_param_values, cache_key) +/// body_cols: sorted (col, val) pairs from request body +/// filter_cols: sorted (col, val) pairs from query params +pub fn build_query( + method: &str, + table: &str, + id: Option<&str>, + body_cols: &[(String, String)], + filter_cols: &[(String, String)], +) -> Result<(String, Vec, String)> { + validate_identifier(table)?; + for (col, _) in body_cols.iter().chain(filter_cols.iter()) { + validate_identifier(col)?; + } + + let mut sorted_body = body_cols.to_vec(); + sorted_body.sort_by(|a, b| a.0.cmp(&b.0)); + let mut sorted_filters = filter_cols.to_vec(); + sorted_filters.sort_by(|a, b| a.0.cmp(&b.0)); + + match method.to_uppercase().as_str() { + "GET" => { + if let Some(id_val) = id { + let sql = format!("SELECT * FROM {} WHERE id = $1", table); + let key = format!("GET:{}:by_id", table); + Ok((sql, vec![id_val.to_string()], key)) + } else if sorted_filters.is_empty() { + let sql = format!("SELECT * FROM {}", table); + let key = format!("GET:{}:", table); + Ok((sql, vec![], key)) + } else { + let col_names: Vec = sorted_filters.iter().map(|(c, _)| c.clone()).collect(); + let where_clause: Vec = col_names + .iter() + .enumerate() + .map(|(i, c)| format!("{} = ${}", c, i + 1)) + .collect(); + let sql = format!("SELECT * FROM {} WHERE {}", table, where_clause.join(" AND ")); + let params: Vec = sorted_filters.iter().map(|(_, v)| v.clone()).collect(); + let key = format!("GET:{}:{}", table, col_names.join(",")); + Ok((sql, params, key)) + } + } + "POST" => { + if sorted_body.is_empty() { + return Err(anyhow!("POST requires a body with at least one field")); + } + let cols: Vec = sorted_body.iter().map(|(c, _)| c.clone()).collect(); + let placeholders: Vec = (1..=cols.len()).map(|i| format!("${}", i)).collect(); + let sql = format!( + "INSERT INTO {} ({}) VALUES ({}) RETURNING *", + table, + cols.join(", "), + placeholders.join(", ") + ); + let params: Vec = sorted_body.iter().map(|(_, v)| v.clone()).collect(); + let key = format!("POST:{}:{}", table, cols.join(",")); + Ok((sql, params, key)) + } + "PUT" => { + let id_val = id.ok_or_else(|| anyhow!("PUT requires an id"))?; + if sorted_body.is_empty() { + return Err(anyhow!("PUT requires a body with at least one field")); + } + let cols: Vec = sorted_body.iter().map(|(c, _)| c.clone()).collect(); + let set_clause: Vec = cols + .iter() + .enumerate() + .map(|(i, c)| format!("{} = ${}", c, i + 1)) + .collect(); + let id_placeholder = cols.len() + 1; + let sql = format!( + "UPDATE {} SET {} WHERE id = ${} RETURNING *", + table, + set_clause.join(", "), + id_placeholder + ); + let mut params: Vec = sorted_body.iter().map(|(_, v)| v.clone()).collect(); + params.push(id_val.to_string()); + let key = format!("PUT:{}:{}:by_id", table, cols.join(",")); + Ok((sql, params, key)) + } + "DELETE" => { + let id_val = id.ok_or_else(|| anyhow!("DELETE requires an id"))?; + let sql = format!("DELETE FROM {} WHERE id = $1", table); + let key = format!("DELETE:{}:by_id", table); + Ok((sql, vec![id_val.to_string()], key)) + } + m => Err(anyhow!("unsupported method: {}", m)), + } +} + +pub fn pg_row_to_json(row: PgRow) -> Value { + let columns = row.columns(); + let mut map = serde_json::Map::new(); + for col in columns { + let name = col.name().to_string(); + let type_name = col.type_info().name(); + let val = match type_name { + "INT2" | "INT4" | "INT8" | "SERIAL" => row + .try_get::(col.ordinal()) + .map(|v| Value::Number(v.into())) + .unwrap_or(Value::Null), + "FLOAT4" | "FLOAT8" => row + .try_get::(col.ordinal()) + .ok() + .and_then(|v| serde_json::Number::from_f64(v)) + .map(Value::Number) + .unwrap_or(Value::Null), + "BOOL" => row + .try_get::(col.ordinal()) + .map(Value::Bool) + .unwrap_or(Value::Null), + "UUID" => row + .try_get::(col.ordinal()) + .map(|v| Value::String(v.to_string())) + .unwrap_or(Value::Null), + "TIMESTAMPTZ" | "TIMESTAMP" => row + .try_get::, _>(col.ordinal()) + .map(|v| Value::String(v.to_rfc3339())) + .unwrap_or(Value::Null), + _ => row + .try_get::(col.ordinal()) + .map(Value::String) + .unwrap_or(Value::Null), + }; + map.insert(name, val); + } + Value::Object(map) +} + +pub async fn handle_crud( + State(state): State, + method: Method, + Path(params): Path>, + Query(query_params): Query>, + body: Option>>, +) -> Result, StatusCode> { + let table = params.get("table").ok_or(StatusCode::BAD_REQUEST)?; + let id = params.get("id").map(|s| s.as_str()); + let method_str = method.as_str(); + + let body_cols: Vec<(String, String)> = body + .map(|Json(b)| { + b.into_iter() + .filter_map(|(k, v)| match v { + Value::String(s) => Some((k, s)), + Value::Number(n) => Some((k, n.to_string())), + Value::Bool(b) => Some((k, b.to_string())), + _ => None, + }) + .collect() + }) + .unwrap_or_default(); + + let filter_cols: Vec<(String, String)> = query_params.into_iter().collect(); + + let (sql, params_vals, cache_key) = + build_query(method_str, table, id, &body_cols, &filter_cols) + .map_err(|_| StatusCode::BAD_REQUEST)?; + + let cached = state.query_cache.get(&cache_key); + let _entry = if cached.is_none() { + let entry = CacheEntry::new(sql.clone(), vec![]); + state + .query_cache + .insert(cache_key, entry.clone(), state.config.cache_max_capacity); + entry + } else { + cached.unwrap() + }; + + let mut q = sqlx::query(&sql); + for val in ¶ms_vals { + q = q.bind(val.as_str()); + } + + match method_str.to_uppercase().as_str() { + "GET" => { + let rows = q + .fetch_all(&state.pool) + .await + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; + let json_rows: Vec = rows.into_iter().map(pg_row_to_json).collect(); + Ok(Json(Value::Array(json_rows))) + } + "POST" | "PUT" => { + let row = q + .fetch_one(&state.pool) + .await + .map_err(|e| { + if e.to_string().contains("no rows") { + StatusCode::NOT_FOUND + } else { + StatusCode::INTERNAL_SERVER_ERROR + } + })?; + Ok(Json(pg_row_to_json(row))) + } + "DELETE" => { + q.execute(&state.pool) + .await + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; + Ok(Json(serde_json::json!({ "deleted": true }))) + } + _ => Err(StatusCode::METHOD_NOT_ALLOWED), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_build_select_all() { + let (sql, params, key) = build_query("GET", "orders", None, &[], &[]).unwrap(); + assert_eq!(sql, "SELECT * FROM orders"); + assert!(params.is_empty()); + assert_eq!(key, "GET:orders:"); + } + + #[test] + fn test_build_select_by_id() { + let (sql, params, key) = build_query("GET", "orders", Some("42"), &[], &[]).unwrap(); + assert_eq!(sql, "SELECT * FROM orders WHERE id = $1"); + assert_eq!(params, vec!["42".to_string()]); + assert_eq!(key, "GET:orders:by_id"); + } + + #[test] + fn test_build_insert() { + let cols = vec![("email".into(), "a@b.com".into()), ("name".into(), "Alice".into())]; + let (sql, params, key) = build_query("POST", "users", None, &cols, &[]).unwrap(); + assert_eq!(sql, "INSERT INTO users (email, name) VALUES ($1, $2) RETURNING *"); + assert_eq!(params, vec!["a@b.com", "Alice"]); + assert_eq!(key, "POST:users:email,name"); + } + + #[test] + fn test_build_update() { + let cols = vec![("name".into(), "Bob".into())]; + let (sql, params, key) = build_query("PUT", "users", Some("7"), &cols, &[]).unwrap(); + assert_eq!(sql, "UPDATE users SET name = $1 WHERE id = $2 RETURNING *"); + assert_eq!(params, vec!["Bob", "7"]); + assert_eq!(key, "PUT:users:name:by_id"); + } + + #[test] + fn test_build_delete() { + let (sql, params, key) = build_query("DELETE", "users", Some("3"), &[], &[]).unwrap(); + assert_eq!(sql, "DELETE FROM users WHERE id = $1"); + assert_eq!(params, vec!["3"]); + assert_eq!(key, "DELETE:users:by_id"); + } + + #[test] + fn test_build_select_with_filters() { + let filters = vec![("status".into(), "active".into()), ("role".into(), "admin".into())]; + let (sql, params, key) = build_query("GET", "users", None, &[], &filters).unwrap(); + assert_eq!(sql, "SELECT * FROM users WHERE role = $1 AND status = $2"); + assert_eq!(params, vec!["admin", "active"]); + assert_eq!(key, "GET:users:role,status"); + } + + #[test] + fn test_rejects_invalid_table_name() { + let result = build_query("GET", "users; DROP TABLE users--", None, &[], &[]); + assert!(result.is_err()); + } +} +``` + +- [ ] **Step 4: Run tests** + +```bash +cargo test crud::tests +``` +Expected: 7 tests pass. + +- [ ] **Step 5: Commit** + +```bash +git add src/routes/crud.rs +git commit -m "feat: add dynamic CRUD query builder with cache integration" +``` + +--- + +## Task 11: Admin routes — queries + +**Files:** +- Create: `src/routes/admin/queries.rs` + +- [ ] **Step 1: Write src/routes/admin/queries.rs** + +```rust +use axum::{ + extract::{Extension, Path, Query, State}, + http::StatusCode, + Json, +}; +use serde_json::{json, Value}; +use std::collections::HashMap; + +use crate::{ + auth::Claims, + models::query::{CreateQuery, StoredQuery, UpdateQuery}, + state::AppState, +}; + +pub async fn list_queries( + State(state): State, + Extension(_claims): Extension, +) -> Result>, StatusCode> { + let queries = sqlx::query_as!( + StoredQuery, + "SELECT id, identifier, sql_template, description, created_at, updated_at FROM queries ORDER BY created_at DESC" + ) + .fetch_all(&state.pool) + .await + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; + Ok(Json(queries)) +} + +pub async fn get_query( + State(state): State, + Extension(_claims): Extension, + Path(identifier): Path, +) -> Result, StatusCode> { + let q = sqlx::query_as!( + StoredQuery, + "SELECT id, identifier, sql_template, description, created_at, updated_at FROM queries WHERE identifier = $1", + identifier + ) + .fetch_optional(&state.pool) + .await + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)? + .ok_or(StatusCode::NOT_FOUND)?; + Ok(Json(q)) +} + +pub async fn create_query( + State(state): State, + Extension(_claims): Extension, + Json(body): Json, +) -> Result, StatusCode> { + let q = sqlx::query_as!( + StoredQuery, + "INSERT INTO queries (identifier, sql_template, description) VALUES ($1, $2, $3) RETURNING id, identifier, sql_template, description, created_at, updated_at", + body.identifier, + body.sql_template, + body.description + ) + .fetch_one(&state.pool) + .await + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; + Ok(Json(q)) +} + +pub async fn update_query( + State(state): State, + Extension(_claims): Extension, + Path(identifier): Path, + Json(body): Json, +) -> Result, StatusCode> { + let existing = sqlx::query_as!( + StoredQuery, + "SELECT id, identifier, sql_template, description, created_at, updated_at FROM queries WHERE identifier = $1", + identifier + ) + .fetch_optional(&state.pool) + .await + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)? + .ok_or(StatusCode::NOT_FOUND)?; + + let new_sql = body.sql_template.as_deref().unwrap_or(&existing.sql_template); + let new_desc = body.description.as_deref().or(existing.description.as_deref()); + + let q = sqlx::query_as!( + StoredQuery, + "UPDATE queries SET sql_template = $1, description = $2, updated_at = now() WHERE identifier = $3 RETURNING id, identifier, sql_template, description, created_at, updated_at", + new_sql, + new_desc, + identifier + ) + .fetch_one(&state.pool) + .await + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; + + state.query_cache.remove(&identifier); + Ok(Json(q)) +} + +pub async fn delete_query( + State(state): State, + Extension(_claims): Extension, + Path(identifier): Path, +) -> Result, StatusCode> { + sqlx::query!("DELETE FROM queries WHERE identifier = $1", identifier) + .execute(&state.pool) + .await + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; + state.query_cache.remove(&identifier); + Ok(Json(json!({ "deleted": true }))) +} + +pub async fn execute_query( + State(state): State, + Extension(_claims): Extension, + Path(identifier): Path, + Query(params): Query>, +) -> Result, StatusCode> { + let stored = sqlx::query_as!( + StoredQuery, + "SELECT id, identifier, sql_template, description, created_at, updated_at FROM queries WHERE identifier = $1", + identifier + ) + .fetch_optional(&state.pool) + .await + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)? + .ok_or(StatusCode::NOT_FOUND)?; + + let mut sql = stored.sql_template.clone(); + let mut bound_vals: Vec = Vec::new(); + let mut idx = 1usize; + let mut sorted_params: Vec<(String, String)> = params.into_iter().collect(); + sorted_params.sort_by(|a, b| a.0.cmp(&b.0)); + for (name, val) in &sorted_params { + let placeholder = format!(":{}", name); + if sql.contains(&placeholder) { + sql = sql.replace(&placeholder, &format!("${}", idx)); + bound_vals.push(val.clone()); + idx += 1; + } + } + + let mut q = sqlx::query(&sql); + for val in &bound_vals { + q = q.bind(val.as_str()); + } + + let rows = q + .fetch_all(&state.pool) + .await + .map_err(|e| { + tracing::error!("query execution error: {}", e); + StatusCode::INTERNAL_SERVER_ERROR + })?; + + let json_rows: Vec = rows + .into_iter() + .map(crate::routes::crud::pg_row_to_json) + .collect(); + + Ok(Json(Value::Array(json_rows))) +} +``` + +- [ ] **Step 2: Compile** + +```bash +cargo build +``` +Expected: `Finished`. + +- [ ] **Step 3: Commit** + +```bash +git add src/routes/admin/queries.rs +git commit -m "feat: add admin query registry CRUD routes" +``` + +--- + +## Task 12: Admin routes — cache, users, permissions, blacklist + +**Files:** +- Create: `src/routes/admin/cache.rs` +- Create: `src/routes/admin/users.rs` +- Create: `src/routes/admin/permissions.rs` +- Create: `src/routes/admin/blacklist.rs` +- Modify: `src/routes/admin/mod.rs` + +- [ ] **Step 1: Write src/routes/admin/cache.rs** + +```rust +use axum::{extract::State, http::StatusCode, Json}; +use serde_json::{json, Value}; + +use crate::{auth::Claims, state::AppState}; +use axum::extract::Extension; + +pub async fn cache_stats( + State(state): State, + Extension(_claims): Extension, +) -> Json { + Json(json!({ + "size": state.query_cache.len(), + "hits": state.query_cache.hits(), + "misses": state.query_cache.misses(), + })) +} + +pub async fn flush_cache( + State(state): State, + Extension(_claims): Extension, +) -> Result, StatusCode> { + state.query_cache.flush(); + Ok(Json(json!({ "flushed": true }))) +} +``` + +- [ ] **Step 2: Write src/routes/admin/users.rs** + +```rust +use axum::{ + extract::{Extension, Path, State}, + http::StatusCode, + Json, +}; +use serde_json::{json, Value}; + +use crate::{ + auth::{encode_jwt, Claims}, + models::user::{CreateUser, UpdateUser, User}, + state::AppState, +}; + +pub async fn list_users( + State(state): State, + Extension(_claims): Extension, +) -> Result>, StatusCode> { + let users = sqlx::query_as!( + User, + "SELECT id, username, password_hash, permissions_mask, created_at FROM users ORDER BY id" + ) + .fetch_all(&state.pool) + .await + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; + Ok(Json(users)) +} + +pub async fn get_user( + State(state): State, + Extension(_claims): Extension, + Path(id): Path, +) -> Result, StatusCode> { + let user = sqlx::query_as!( + User, + "SELECT id, username, password_hash, permissions_mask, created_at FROM users WHERE id = $1", + id + ) + .fetch_optional(&state.pool) + .await + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)? + .ok_or(StatusCode::NOT_FOUND)?; + Ok(Json(user)) +} + +pub async fn create_user( + State(state): State, + Extension(_claims): Extension, + Json(body): Json, +) -> Result, StatusCode> { + let hash = bcrypt::hash(&body.password, bcrypt::DEFAULT_COST) + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; + let mask = body.permissions_mask.unwrap_or_else(|| "0".into()); + let user = sqlx::query_as!( + User, + "INSERT INTO users (username, password_hash, permissions_mask) VALUES ($1, $2, $3) RETURNING id, username, password_hash, permissions_mask, created_at", + body.username, + hash, + mask + ) + .fetch_one(&state.pool) + .await + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; + Ok(Json(user)) +} + +pub async fn update_user( + State(state): State, + Extension(_claims): Extension, + Path(id): Path, + Json(body): Json, +) -> Result, StatusCode> { + let existing = sqlx::query_as!( + User, + "SELECT id, username, password_hash, permissions_mask, created_at FROM users WHERE id = $1", + id + ) + .fetch_optional(&state.pool) + .await + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)? + .ok_or(StatusCode::NOT_FOUND)?; + + let new_username = body.username.as_deref().unwrap_or(&existing.username); + let new_hash = if let Some(pw) = &body.password { + bcrypt::hash(pw, bcrypt::DEFAULT_COST).map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)? + } else { + existing.password_hash.clone() + }; + let new_mask = body.permissions_mask.as_deref().unwrap_or(&existing.permissions_mask); + + let user = sqlx::query_as!( + User, + "UPDATE users SET username = $1, password_hash = $2, permissions_mask = $3 WHERE id = $4 RETURNING id, username, password_hash, permissions_mask, created_at", + new_username, + new_hash, + new_mask, + id + ) + .fetch_one(&state.pool) + .await + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; + Ok(Json(user)) +} + +pub async fn delete_user( + State(state): State, + Extension(_claims): Extension, + Path(id): Path, +) -> Result, StatusCode> { + sqlx::query!("DELETE FROM users WHERE id = $1", id) + .execute(&state.pool) + .await + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; + Ok(Json(json!({ "deleted": true }))) +} + +pub async fn grant_permission( + State(state): State, + Extension(_claims): Extension, + Path((id, bit_value)): Path<(i32, String)>, +) -> Result, StatusCode> { + let user = sqlx::query_as!( + User, + "SELECT id, username, password_hash, permissions_mask, created_at FROM users WHERE id = $1", + id + ) + .fetch_optional(&state.pool) + .await + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)? + .ok_or(StatusCode::NOT_FOUND)?; + + let current: u128 = user.permissions_mask.parse().unwrap_or(0); + let bit: u128 = bit_value.parse().map_err(|_| StatusCode::BAD_REQUEST)?; + let new_mask = (current | bit).to_string(); + + let updated = sqlx::query_as!( + User, + "UPDATE users SET permissions_mask = $1 WHERE id = $2 RETURNING id, username, password_hash, permissions_mask, created_at", + new_mask, + id + ) + .fetch_one(&state.pool) + .await + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; + Ok(Json(updated)) +} + +pub async fn revoke_permission( + State(state): State, + Extension(_claims): Extension, + Path((id, bit_value)): Path<(i32, String)>, +) -> Result, StatusCode> { + let user = sqlx::query_as!( + User, + "SELECT id, username, password_hash, permissions_mask, created_at FROM users WHERE id = $1", + id + ) + .fetch_optional(&state.pool) + .await + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)? + .ok_or(StatusCode::NOT_FOUND)?; + + let current: u128 = user.permissions_mask.parse().unwrap_or(0); + let bit: u128 = bit_value.parse().map_err(|_| StatusCode::BAD_REQUEST)?; + let new_mask = (current & !bit).to_string(); + + let updated = sqlx::query_as!( + User, + "UPDATE users SET permissions_mask = $1 WHERE id = $2 RETURNING id, username, password_hash, permissions_mask, created_at", + new_mask, + id + ) + .fetch_one(&state.pool) + .await + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; + Ok(Json(updated)) +} +``` + +- [ ] **Step 3: Write src/routes/admin/permissions.rs** + +```rust +use axum::{ + extract::{Extension, Path, State}, + http::StatusCode, + Json, +}; +use serde_json::{json, Value}; + +use crate::{ + auth::Claims, + models::permission::{CreatePermission, Permission, UpdatePermission}, + state::AppState, +}; + +pub async fn list_permissions( + State(state): State, + Extension(_claims): Extension, +) -> Result>, StatusCode> { + let perms = sqlx::query_as!( + Permission, + "SELECT id, name, bit_value, description FROM permissions ORDER BY id" + ) + .fetch_all(&state.pool) + .await + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; + Ok(Json(perms)) +} + +pub async fn create_permission( + State(state): State, + Extension(_claims): Extension, + Json(body): Json, +) -> Result, StatusCode> { + let existing: Vec = sqlx::query_scalar!("SELECT bit_value FROM permissions") + .fetch_all(&state.pool) + .await + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)? + .into_iter() + .flatten() + .collect(); + + let next_bit = (0u128..) + .map(|i| 1u128 << i) + .find(|bit| !existing.contains(&bit.to_string())) + .ok_or(StatusCode::INSUFFICIENT_STORAGE)?; + + let perm = sqlx::query_as!( + Permission, + "INSERT INTO permissions (name, bit_value, description) VALUES ($1, $2, $3) RETURNING id, name, bit_value, description", + body.name, + next_bit.to_string(), + body.description + ) + .fetch_one(&state.pool) + .await + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; + Ok(Json(perm)) +} + +pub async fn update_permission( + State(state): State, + Extension(_claims): Extension, + Path(id): Path, + Json(body): Json, +) -> Result, StatusCode> { + let existing = sqlx::query_as!( + Permission, + "SELECT id, name, bit_value, description FROM permissions WHERE id = $1", + id + ) + .fetch_optional(&state.pool) + .await + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)? + .ok_or(StatusCode::NOT_FOUND)?; + + let new_name = body.name.as_deref().unwrap_or(&existing.name); + let new_desc = body.description.as_deref().or(existing.description.as_deref()); + + let perm = sqlx::query_as!( + Permission, + "UPDATE permissions SET name = $1, description = $2 WHERE id = $3 RETURNING id, name, bit_value, description", + new_name, + new_desc, + id + ) + .fetch_one(&state.pool) + .await + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; + Ok(Json(perm)) +} + +pub async fn delete_permission( + State(state): State, + Extension(_claims): Extension, + Path(id): Path, +) -> Result, StatusCode> { + sqlx::query!("DELETE FROM permissions WHERE id = $1", id) + .execute(&state.pool) + .await + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; + Ok(Json(json!({ "deleted": true }))) +} +``` + +- [ ] **Step 4: Write src/routes/admin/blacklist.rs** + +```rust +use axum::{ + extract::{Extension, Path, State}, + http::StatusCode, + Json, +}; +use serde_json::{json, Value}; + +use crate::{ + auth::Claims, + models::blacklist::{BlacklistEntry, CreateBlacklistEntry, UpdateBlacklistEntry}, + state::AppState, +}; + +async fn reload_blacklist(state: &AppState) -> Result<(), StatusCode> { + let entries = sqlx::query_as!( + BlacklistEntry, + "SELECT id, pattern, method, reason, active, created_at FROM blacklist ORDER BY id" + ) + .fetch_all(&state.pool) + .await + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; + state.blacklist_cache.load(entries).await; + Ok(()) +} + +pub async fn list_blacklist( + State(state): State, + Extension(_claims): Extension, +) -> Result>, StatusCode> { + let entries = sqlx::query_as!( + BlacklistEntry, + "SELECT id, pattern, method, reason, active, created_at FROM blacklist ORDER BY id" + ) + .fetch_all(&state.pool) + .await + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; + Ok(Json(entries)) +} + +pub async fn create_blacklist_entry( + State(state): State, + Extension(_claims): Extension, + Json(body): Json, +) -> Result, StatusCode> { + let entry = sqlx::query_as!( + BlacklistEntry, + "INSERT INTO blacklist (pattern, method, reason) VALUES ($1, $2, $3) RETURNING id, pattern, method, reason, active, created_at", + body.pattern, + body.method, + body.reason + ) + .fetch_one(&state.pool) + .await + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; + reload_blacklist(&state).await?; + Ok(Json(entry)) +} + +pub async fn update_blacklist_entry( + State(state): State, + Extension(_claims): Extension, + Path(id): Path, + Json(body): Json, +) -> Result, StatusCode> { + let existing = sqlx::query_as!( + BlacklistEntry, + "SELECT id, pattern, method, reason, active, created_at FROM blacklist WHERE id = $1", + id + ) + .fetch_optional(&state.pool) + .await + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)? + .ok_or(StatusCode::NOT_FOUND)?; + + let new_pattern = body.pattern.as_deref().unwrap_or(&existing.pattern); + let new_method = body.method.as_deref().or(existing.method.as_deref()); + let new_reason = body.reason.as_deref().or(existing.reason.as_deref()); + let new_active = body.active.unwrap_or(existing.active); + + let entry = sqlx::query_as!( + BlacklistEntry, + "UPDATE blacklist SET pattern = $1, method = $2, reason = $3, active = $4 WHERE id = $5 RETURNING id, pattern, method, reason, active, created_at", + new_pattern, + new_method, + new_reason, + new_active, + id + ) + .fetch_one(&state.pool) + .await + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; + reload_blacklist(&state).await?; + Ok(Json(entry)) +} + +pub async fn delete_blacklist_entry( + State(state): State, + Extension(_claims): Extension, + Path(id): Path, +) -> Result, StatusCode> { + sqlx::query!("DELETE FROM blacklist WHERE id = $1", id) + .execute(&state.pool) + .await + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; + reload_blacklist(&state).await?; + Ok(Json(json!({ "deleted": true }))) +} +``` + +- [ ] **Step 5: Write src/routes/admin/mod.rs** + +```rust +pub mod blacklist; +pub mod cache; +pub mod permissions; +pub mod queries; +pub mod users; + +use axum::{ + middleware, + routing::{delete, get, post, put}, + Router, +}; + +use crate::{ + auth::middleware::{require_admin_cache, require_admin_query, require_super_admin}, + state::AppState, +}; + +pub fn admin_router(state: AppState) -> Router { + let query_routes = Router::new() + .route("/", get(queries::list_queries).post(queries::create_query)) + .route( + "/:identifier", + get(queries::get_query) + .put(queries::update_query) + .delete(queries::delete_query), + ) + .route("/:identifier/execute", get(queries::execute_query)) + .route_layer(middleware::from_fn_with_state( + state.clone(), + require_admin_query, + )); + + let cache_routes = Router::new() + .route("/stats", get(cache::cache_stats)) + .route("/", delete(cache::flush_cache)) + .route_layer(middleware::from_fn_with_state( + state.clone(), + require_admin_cache, + )); + + let super_routes = Router::new() + .route("/users", get(users::list_users).post(users::create_user)) + .route( + "/users/:id", + get(users::get_user) + .put(users::update_user) + .delete(users::delete_user), + ) + .route( + "/users/:id/permissions/grant/:bit_value", + post(users::grant_permission), + ) + .route( + "/users/:id/permissions/revoke/:bit_value", + delete(users::revoke_permission), + ) + .route( + "/permissions", + get(permissions::list_permissions).post(permissions::create_permission), + ) + .route( + "/permissions/:id", + put(permissions::update_permission).delete(permissions::delete_permission), + ) + .route( + "/blacklist", + get(blacklist::list_blacklist).post(blacklist::create_blacklist_entry), + ) + .route( + "/blacklist/:id", + put(blacklist::update_blacklist_entry).delete(blacklist::delete_blacklist_entry), + ) + .route_layer(middleware::from_fn_with_state( + state.clone(), + require_super_admin, + )); + + Router::new() + .nest("/queries", query_routes) + .nest("/cache", cache_routes) + .merge(super_routes) +} +``` + +- [ ] **Step 6: Compile** + +```bash +cargo build +``` +Expected: `Finished`. + +- [ ] **Step 7: Commit** + +```bash +git add src/routes/admin/ +git commit -m "feat: add admin routes for cache, users, permissions, and blacklist" +``` + +--- + +## Task 13: main.rs — full wiring + +**Files:** +- Modify: `src/main.rs` + +- [ ] **Step 1: Write full src/main.rs** + +```rust +mod auth; +mod cache; +mod config; +mod db; +mod models; +mod routes; +mod state; + +use std::sync::Arc; + +use axum::{middleware, routing::{delete, get, post, put}, Router}; +use tower_http::{cors::CorsLayer, services::ServeDir}; +use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt}; + +use crate::{ + auth::middleware::blacklist_layer, + cache::spawn_sweep_task, + config::Config, + db::create_pool, + models::blacklist::BlacklistEntry, + routes::{ + admin::admin_router, + auth::login, + crud::handle_crud, + }, + state::{AppState, BlacklistCache, QueryCache}, +}; + +#[tokio::main] +async fn main() -> anyhow::Result<()> { + dotenvy::dotenv().ok(); + + tracing_subscriber::registry() + .with(tracing_subscriber::EnvFilter::try_from_default_env() + .unwrap_or_else(|_| "mercury=info".into())) + .with(tracing_subscriber::fmt::layer()) + .init(); + + let config = Arc::new(Config::from_env()?); + let pool = create_pool(&config.database_url).await?; + + // Seed admin user if not present + let count: i64 = sqlx::query_scalar!("SELECT COUNT(*) FROM users WHERE username = 'admin'") + .fetch_one(&pool) + .await? + .unwrap_or(0); + if count == 0 { + let hash = bcrypt::hash("admin", bcrypt::DEFAULT_COST)?; + sqlx::query!( + "INSERT INTO users (username, password_hash, permissions_mask) VALUES ('admin', $1, '63')", + hash + ) + .execute(&pool) + .await?; + tracing::info!("seeded admin user"); + } + + let query_cache = QueryCache::new(); + let blacklist_cache = BlacklistCache::new(); + + // Load blacklist from DB into memory + let entries = sqlx::query_as!( + BlacklistEntry, + "SELECT id, pattern, method, reason, active, created_at FROM blacklist ORDER BY id" + ) + .fetch_all(&pool) + .await?; + blacklist_cache.load(entries).await; + + // Start cache sweep + spawn_sweep_task( + query_cache.clone(), + config.cache_idle_timeout_secs, + config.cache_sweep_interval_secs, + ); + + let state = AppState { + pool, + query_cache, + blacklist_cache, + config: config.clone(), + }; + + let crud_routes = Router::new() + .route("/api/:table", get(handle_crud).post(handle_crud)) + .route("/api/:table/:id", get(handle_crud).put(handle_crud).delete(handle_crud)) + .route_layer(middleware::from_fn_with_state(state.clone(), blacklist_layer)); + + let app = Router::new() + .route("/auth/login", post(login)) + .merge(crud_routes) + .nest("/admin", admin_router(state.clone())) + .nest_service("/", ServeDir::new("ui/dist")) + .layer(CorsLayer::permissive()) + .with_state(state); + + let addr = std::net::SocketAddr::from(([0, 0, 0, 0], 3000)); + tracing::info!("listening on {}", addr); + let listener = tokio::net::TcpListener::bind(addr).await?; + axum::serve(listener, app).await?; + Ok(()) +} +``` + +- [ ] **Step 2: Compile** + +```bash +cargo build +``` +Expected: `Finished`. + +- [ ] **Step 3: Commit** + +```bash +git add src/main.rs +git commit -m "feat: wire full Axum router with middleware, CRUD, admin, and static file serving" +``` + +--- + +## Task 14: Docker setup + +**Files:** +- Create: `Dockerfile` +- Create: `docker-compose.yml` + +- [ ] **Step 1: Write Dockerfile** + +```dockerfile +# Stage 1: Build Vue UI +FROM node:20-alpine AS ui-builder +WORKDIR /ui +COPY ui/.npmrc . +COPY ui/package*.json . +RUN npm install +COPY ui/ . +RUN npm run build + +# Stage 2: Build Rust API +FROM rust:1.75-slim AS api-builder +RUN apt-get update && apt-get install -y pkg-config libssl-dev && rm -rf /var/lib/apt/lists/* +WORKDIR /app +COPY Cargo.toml Cargo.lock ./ +COPY src/ src/ +RUN cargo build --release + +# Stage 3: Final image +FROM debian:bookworm-slim +RUN apt-get update && apt-get install -y ca-certificates libssl3 && rm -rf /var/lib/apt/lists/* +WORKDIR /app +COPY --from=api-builder /app/target/release/mercury . +COPY --from=ui-builder /ui/dist ./ui/dist +EXPOSE 3000 +CMD ["./mercury"] +``` + +- [ ] **Step 2: Write docker-compose.yml** + +```yaml +services: + db: + image: postgres:16-alpine + environment: + POSTGRES_USER: mercury + POSTGRES_PASSWORD: mercury + POSTGRES_DB: mercury + volumes: + - postgres_data:/var/lib/postgresql/data + healthcheck: + test: ["CMD-SHELL", "pg_isready -U mercury"] + interval: 5s + timeout: 5s + retries: 5 + + api: + build: . + ports: + - "3000:3000" + environment: + DATABASE_URL: postgres://mercury:mercury@db:5432/mercury + JWT_SECRET: ${JWT_SECRET:-change_me_in_production} + JWT_EXPIRY_SECS: ${JWT_EXPIRY_SECS:-3600} + CACHE_MAX_CAPACITY: ${CACHE_MAX_CAPACITY:-10000} + CACHE_IDLE_TIMEOUT_SECS: ${CACHE_IDLE_TIMEOUT_SECS:-300} + CACHE_SWEEP_INTERVAL_SECS: ${CACHE_SWEEP_INTERVAL_SECS:-60} + depends_on: + db: + condition: service_healthy + mem_limit: 512m + mem_reservation: 256m + +volumes: + postgres_data: +``` + +- [ ] **Step 3: Commit** + +```bash +git add Dockerfile docker-compose.yml +git commit -m "feat: add multi-stage Dockerfile and docker-compose" +``` + +--- + +## Task 15: Vue UI scaffold + +**Files:** +- Create: `ui/.npmrc` +- Create: `ui/package.json` +- Create: `ui/vite.config.ts` +- Create: `ui/src/main.ts` +- Create: `ui/src/App.vue` +- Create: `ui/src/router/index.ts` +- Create: `ui/src/stores/auth.ts` + +- [ ] **Step 1: Write ui/.npmrc** + +``` +@nychthemeron:registry=https://git.mcpeakdev.com/api/packages/McPeakDev/npm/ +``` + +- [ ] **Step 2: Write ui/package.json** + +```json +{ + "name": "mercury-ui", + "private": true, + "version": "0.1.0", + "type": "module", + "scripts": { + "dev": "vite", + "build": "vue-tsc && vite build", + "preview": "vite preview" + }, + "dependencies": { + "@nychthemeron/library": "latest", + "pinia": "^2.1.0", + "vue": "^3.4.0", + "vue-router": "^4.3.0" + }, + "devDependencies": { + "@vitejs/plugin-vue": "^5.0.0", + "typescript": "^5.3.0", + "vite": "^5.0.0", + "vue-tsc": "^2.0.0" + } +} +``` + +- [ ] **Step 3: Write ui/vite.config.ts** + +```typescript +import { defineConfig } from 'vite' +import vue from '@vitejs/plugin-vue' + +export default defineConfig({ + plugins: [vue()], + server: { + proxy: { + '/api': 'http://localhost:3000', + '/auth': 'http://localhost:3000', + '/admin': 'http://localhost:3000', + }, + }, + build: { + outDir: 'dist', + }, +}) +``` + +- [ ] **Step 4: Write ui/src/stores/auth.ts** + +```typescript +import { defineStore } from 'pinia' +import { ref, computed } from 'vue' + +interface Claims { + sub: string + permissions: string + exp: number +} + +function parseJwt(token: string): Claims | null { + try { + const payload = token.split('.')[1] + return JSON.parse(atob(payload)) as Claims + } catch { + return null + } +} + +export const useAuthStore = defineStore('auth', () => { + const token = ref(localStorage.getItem('mercury_token')) + const claims = computed(() => + token.value ? parseJwt(token.value) : null + ) + const isAuthenticated = computed(() => { + if (!claims.value) return false + return claims.value.exp * 1000 > Date.now() + }) + const username = computed(() => claims.value?.sub ?? '') + + function hasPermission(bit: bigint): boolean { + if (!claims.value) return false + const mask = BigInt(claims.value.permissions) + return (mask & bit) !== 0n + } + + const isSuperAdmin = computed(() => hasPermission(32n)) + + async function login(username: string, password: string): Promise { + const res = await fetch('/auth/login', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ username, password }), + }) + if (!res.ok) throw new Error('Invalid credentials') + const data = await res.json() + token.value = data.token + localStorage.setItem('mercury_token', data.token) + } + + function logout() { + token.value = null + localStorage.removeItem('mercury_token') + } + + function authHeaders(): Record { + return token.value ? { Authorization: `Bearer ${token.value}` } : {} + } + + return { token, claims, isAuthenticated, username, isSuperAdmin, hasPermission, login, logout, authHeaders } +}) +``` + +- [ ] **Step 5: Write ui/src/router/index.ts** + +```typescript +import { createRouter, createWebHistory } from 'vue-router' +import { useAuthStore } from '../stores/auth' + +const router = createRouter({ + history: createWebHistory(), + routes: [ + { path: '/login', component: () => import('../views/Login.vue') }, + { + path: '/admin', + component: () => import('../views/admin/Layout.vue'), + children: [ + { path: 'queries', component: () => import('../views/admin/Queries.vue') }, + { path: 'users', component: () => import('../views/admin/Users.vue') }, + { path: 'permissions', component: () => import('../views/admin/Permissions.vue') }, + { path: 'blacklist', component: () => import('../views/admin/Blacklist.vue') }, + { path: 'cache', component: () => import('../views/admin/Cache.vue') }, + ], + meta: { requiresAuth: true }, + }, + { path: '/', redirect: '/admin/queries' }, + ], +}) + +router.beforeEach((to) => { + const auth = useAuthStore() + if (to.meta.requiresAuth && !auth.isAuthenticated) { + return '/login' + } + if (to.path === '/login' && auth.isAuthenticated) { + return '/admin/queries' + } +}) + +export default router +``` + +- [ ] **Step 6: Write ui/src/main.ts** + +```typescript +import { createApp } from 'vue' +import { createPinia } from 'pinia' +import NychthemeronLibrary from '@nychthemeron/library' +import App from './App.vue' +import router from './router' + +const app = createApp(App) +app.use(createPinia()) +app.use(router) +app.use(NychthemeronLibrary, { theme: 'dark' }) +app.mount('#app') +``` + +- [ ] **Step 7: Write ui/src/App.vue** + +```vue + +``` + +- [ ] **Step 8: Create ui/src/views/Login.vue** + +```vue + + + + + +``` + +- [ ] **Step 9: Commit** + +```bash +git add ui/ +git commit -m "feat: scaffold Vue 3 UI with auth store, router, and login view" +``` + +--- + +## Task 16: Admin views + +**Files:** +- Create: `ui/src/views/admin/Layout.vue` +- Create: `ui/src/views/admin/Queries.vue` +- Create: `ui/src/views/admin/Users.vue` +- Create: `ui/src/views/admin/Permissions.vue` +- Create: `ui/src/views/admin/Blacklist.vue` +- Create: `ui/src/views/admin/Cache.vue` + +- [ ] **Step 1: Write ui/src/views/admin/Layout.vue** + +```vue + + + + + +``` + +- [ ] **Step 2: Write ui/src/views/admin/Queries.vue** + +```vue + + + +``` + +- [ ] **Step 3: Write ui/src/views/admin/Users.vue** + +```vue + + + +``` + +- [ ] **Step 4: Write ui/src/views/admin/Permissions.vue** + +```vue + + + +``` + +- [ ] **Step 5: Write ui/src/views/admin/Blacklist.vue** + +```vue + + + +``` + +- [ ] **Step 6: Write ui/src/views/admin/Cache.vue** + +```vue + + + + + +``` + +- [ ] **Step 7: Commit** + +```bash +git add ui/src/views/ +git commit -m "feat: add admin views for queries, users, permissions, blacklist, cache" +``` + +--- + +## Task 17: README update + +**Files:** +- Modify: `README.md` + +- [ ] **Step 1: Write README.md** + +```markdown +# Mercury + +A high-performance, monolithic Rust API with a dynamic CRUD engine, query registry cache, JWT bitmask permissions, and a Vue 3 admin frontend. + +## Quick Start + +```bash +cp .env.example .env # set JWT_SECRET +docker compose up --build +``` + +API: http://localhost:3000/api +Admin UI: http://localhost:3000 +Default credentials: `admin` / `admin` + +--- + +## API Contract + +### Authentication + +``` +POST /auth/login +Body: { "username": "...", "password": "..." } +Returns: { "token": "" } +``` + +All admin routes require `Authorization: Bearer `. + +--- + +### CRUD — Dynamic Table Access + +Requests are mapped to the named PostgreSQL table. The SQL is generated, cached, and executed automatically. + +``` +GET /api/{table} List all rows (supports ?col=val filters) +GET /api/{table}/{id} Get row by id +POST /api/{table} Insert row (JSON body) +PUT /api/{table}/{id} Update row by id (JSON body) +DELETE /api/{table}/{id} Delete row by id +``` + +**Notes:** +- `users` and `permissions` tables are blacklisted from public CRUD — use the admin suite. +- Filters are ANDed together: `GET /api/orders?status=open&priority=high` + +--- + +### Admin — Query Registry + +Requires JWT with `ADMIN_QUERY` permission (bit 8). + +``` +GET /admin/queries List all registered queries +POST /admin/queries Register a raw SQL template +GET /admin/queries/{identifier} Get query by slug +PUT /admin/queries/{identifier} Update SQL template or description +DELETE /admin/queries/{identifier} Remove query (evicts from cache) +GET /admin/queries/{identifier}/execute Execute query with ?param=val bindings +``` + +SQL templates use `:param_name` placeholders: +```sql +SELECT * FROM orders WHERE user_id = :user_id AND status = :status +``` + +--- + +### Admin — Cache + +Requires JWT with `ADMIN_CACHE` permission (bit 16). + +``` +GET /admin/cache/stats Cache size, hit count, miss count +DELETE /admin/cache Flush entire cache +``` + +--- + +### Admin — Users + +Requires JWT with `SUPER_ADMIN` permission (bit 32). + +``` +GET /admin/users List users +POST /admin/users Create user +GET /admin/users/{id} Get user +PUT /admin/users/{id} Update user +DELETE /admin/users/{id} Delete user +POST /admin/users/{id}/permissions/grant/{bit} OR bit into permissions mask +DELETE /admin/users/{id}/permissions/revoke/{bit} AND NOT bit from permissions mask +``` + +--- + +### Admin — Permissions + +Requires JWT with `SUPER_ADMIN` permission (bit 32). + +``` +GET /admin/permissions List permission definitions +POST /admin/permissions Create custom permission (auto-assigns next bit) +PUT /admin/permissions/{id} Update name/description +DELETE /admin/permissions/{id} Remove permission +``` + +--- + +### Admin — Route Blacklist + +Requires JWT with `SUPER_ADMIN` permission (bit 32). Changes take effect immediately in memory. + +``` +GET /admin/blacklist List all entries +POST /admin/blacklist Add glob pattern +PUT /admin/blacklist/{id} Update entry (set active: false to disable) +DELETE /admin/blacklist/{id} Remove entry +``` + +Pattern syntax: `*` matches one path segment, `**` matches many. +Example: `/api/sensitive/**` blocks all methods under that path. + +--- + +## Permission Bitmask + +| Name | Bit | Value | +|-------------|-----|-------| +| READ | 0 | 1 | +| WRITE | 1 | 2 | +| DELETE | 2 | 4 | +| ADMIN_QUERY | 3 | 8 | +| ADMIN_CACHE | 4 | 16 | +| SUPER_ADMIN | 5 | 32 | + +Custom permissions are added via the admin suite and assigned the next available power-of-2 bit. Masks support up to 128 bits (u128). + +--- + +## Configuration + +| Variable | Default | Description | +|---|---|---| +| `DATABASE_URL` | required | PostgreSQL connection string | +| `JWT_SECRET` | required | HMAC-HS256 signing secret | +| `JWT_EXPIRY_SECS` | 3600 | Token lifetime in seconds | +| `CACHE_MAX_CAPACITY` | 10000 | Max query templates in memory | +| `CACHE_IDLE_TIMEOUT_SECS` | 300 | Evict after N seconds idle | +| `CACHE_SWEEP_INTERVAL_SECS` | 60 | Sweep interval for eviction task | + +--- + +## Development + +```bash +# API only (requires local Postgres) +cargo run + +# UI dev server (proxies to local API) +cd ui && npm install && npm run dev + +# Full stack +docker compose up --build +``` + +## Stack + +- **API:** Rust, Axum, SQLx, PostgreSQL, DashMap, jsonwebtoken, bcrypt +- **Frontend:** Vue 3, Vite, @nychthemeron/library (dark mode default) +- **Infra:** Docker multi-stage build, docker compose +``` + +- [ ] **Step 2: Commit** + +```bash +git add README.md +git commit -m "docs: update README with full API contract and configuration" +``` + +--- + +## Self-Review Checklist + +### Spec Coverage + +| Spec requirement | Task | +|---|---| +| Axum + SQLx + PostgreSQL | Task 1, 4 | +| Config from env vars | Task 2 | +| DashMap TTI cache with sweep | Task 5, 6 | +| Blacklist in-memory with glob | Task 5 | +| JWT with u128 bitmask | Task 7 | +| Auth + blacklist middleware | Task 8 | +| CRUD query builder | Task 10 | +| /auth/login | Task 9 | +| Admin query registry CRUD | Task 11 | +| Admin cache stats + flush | Task 12 | +| Admin user management | Task 12 | +| Admin permission definitions | Task 12 | +| Admin blacklist CRUD + reload | Task 12 | +| Router assembly + main.rs | Task 13 | +| Dockerfile multi-stage | Task 14 | +| docker-compose with mem_limit | Task 14 | +| Admin seeded in migration | Task 4 (schema) + Task 13 (seed on startup) | +| Vue 3 + @nychthemeron/library | Task 15 | +| Dark mode default | Task 15 (main.ts) | +| Login view | Task 15 | +| Admin views (5 pages) | Task 16 | +| README with API contract | Task 17 | +| `users`/`permissions` blacklisted | Task 4 (migration seed) | +| Blacklist reloads on write | Task 12 (blacklist.rs) | +| Permission grant/revoke endpoints | Task 12 (users.rs) | +| Custom permissions auto-assign bit | Task 12 (permissions.rs) | + +All spec requirements covered. No gaps found. diff --git a/docs/superpowers/plans/2026-06-17-security-fixes.md b/docs/superpowers/plans/2026-06-17-security-fixes.md new file mode 100644 index 0000000..0c7736d --- /dev/null +++ b/docs/superpowers/plans/2026-06-17-security-fixes.md @@ -0,0 +1,1072 @@ +# Security Fixes Implementation Plan + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** Fix all Critical, Important, and Minor security/robustness issues identified in the June 2026 code review. + +**Architecture:** Fixes are applied in dependency order — shared utilities first, then middleware, then handlers, then startup. No new crates required except `rpassword` is intentionally avoided (plain stdin for first-user prompt is acceptable). + +**Tech Stack:** Rust, Axum 0.7, SQLx 0.7, jsonwebtoken 9, bcrypt 0.15, DashMap 5, tower-http 0.5 + +--- + +## File Map + +| File | Changes | +|------|---------| +| `src/state.rs` | Fix `unix_now()` panic | +| `src/routes/mod.rs` | Add shared `is_valid_identifier()` | +| `src/routes/admin/tables.rs` | Use shared validator, add `PROTECTED_TABLES` denylist | +| `src/routes/admin/queries.rs` | Sort params longest-first before substitution | +| `src/routes/crud.rs` | Fix cache key, drop NULL_SENTINEL, enforce R/W/D bits, use shared validator | +| `src/auth/middleware.rs` | Stash Claims in extensions in `blacklist_layer`; add `authenticate()` helper | +| `src/config.rs` | Add `cors_origins: Vec` field | +| `src/main.rs` | First-user interactive prompt, body size limit, configured CORS | + +--- + +## Task 1: Fix `unix_now()` panic on sub-epoch clock + +**Files:** +- Modify: `src/state.rs:16-19` + +- [ ] **Step 1: Apply the fix** + +Change `src/state.rs`: +```rust +pub fn unix_now() -> u64 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap_or_default() + .as_secs() +} +``` + +- [ ] **Step 2: Run tests** + +```bash +cargo test +``` +Expected: all tests pass. + +- [ ] **Step 3: Commit** + +```bash +git add src/state.rs +git commit -m "fix: don't panic in unix_now() when clock is before epoch" +``` + +--- + +## Task 2: Fix stored query prefix-substitution bug + +**Files:** +- Modify: `src/routes/admin/queries.rs:29-30` + +**The bug:** When sorted alphabetically, `:user` is replaced before `:username`, turning `:username` into `$1name` — invalid SQL. + +- [ ] **Step 1: Write a failing test** + +Add to `src/routes/admin/queries.rs` (at the bottom, inside a `#[cfg(test)]` block — create the block if it doesn't exist): + +```rust +#[cfg(test)] +mod tests { + #[test] + fn test_prefix_param_substitution_order() { + // Simulate the substitution logic with a prefix-conflicting pair. + let template = "SELECT * FROM t WHERE user_id = :user_id AND username = :username"; + let mut params: Vec<(String, String)> = vec![ + ("user_id".into(), "42".into()), + ("username".into(), "alice".into()), + ]; + // Sort longest-first (the fix) + params.sort_by(|a, b| b.0.len().cmp(&a.0.len())); + let mut sql = template.to_string(); + for (i, (name, _)) in params.iter().enumerate() { + sql = sql.replace(&format!(":{}", name), &format!("${}", i + 1)); + } + assert!(sql.contains("$1") && sql.contains("$2"), "sql: {}", sql); + assert!(!sql.contains(":username"), "placeholder not replaced: {}", sql); + assert!(!sql.contains(":user_id"), "placeholder not replaced: {}", sql); + // username (len 8) should be $1, user_id (len 7) should be $2 + assert_eq!(sql, "SELECT * FROM t WHERE user_id = $2 AND username = $1"); + } +} +``` + +- [ ] **Step 2: Run test to confirm it fails before the fix** + +```bash +cargo test test_prefix_param_substitution_order +``` +Expected: FAIL (currently sorts alphabetically, not by length). + +- [ ] **Step 3: Apply the fix in `execute_query`** + +In `src/routes/admin/queries.rs`, change line 30 from: +```rust +sorted_params.sort_by(|a, b| a.0.cmp(&b.0)); +``` +to: +```rust +sorted_params.sort_by(|a, b| b.0.len().cmp(&a.0.len()).then(a.0.cmp(&b.0))); +``` + +- [ ] **Step 4: Run test to confirm it passes** + +```bash +cargo test test_prefix_param_substitution_order +``` +Expected: PASS. + +- [ ] **Step 5: Commit** + +```bash +git add src/routes/admin/queries.rs +git commit -m "fix: sort stored query params longest-first to prevent prefix substitution corruption" +``` + +--- + +## Task 3: Fix cache key collision between by-id lookup and column filter + +**Files:** +- Modify: `src/routes/crud.rs:48` + +**The bug:** `GET /api/users/by_id` and `GET /api/users?by_id=foo` both produce key `"GET:users:by_id"`. Tilde (`~`) is not a valid identifier character so `"~id"` can never collide with a column name. + +- [ ] **Step 1: Update the existing test to expect the new key** + +In `src/routes/crud.rs` tests, change `test_build_select_by_id`: +```rust +#[test] +fn test_build_select_by_id() { + let (sql, params, key) = build_query("GET", "orders", Some("42"), &[], &[]).unwrap(); + assert_eq!(sql, "SELECT * FROM orders WHERE id = $1"); + assert_eq!(params, vec![Value::String("42".into())]); + assert_eq!(key, "GET:orders:~id"); +} +``` + +> Note: `params` type changes to `Vec` in Task 6. For now, keep as `Vec` and update `"by_id"` → `"~id"` only. +> +> If doing this task before Task 6, the test assertion for params stays `vec!["42".to_string()]`. Just change the key assertion to `"GET:orders:~id"`. + +- [ ] **Step 2: Apply the fix** + +In `src/routes/crud.rs:48`, change: +```rust +let key = format!("GET:{}:by_id", table); +``` +to: +```rust +let key = format!("GET:{}:~id", table); +``` + +- [ ] **Step 3: Run tests** + +```bash +cargo test +``` +Expected: all tests pass. + +- [ ] **Step 4: Commit** + +```bash +git add src/routes/crud.rs +git commit -m "fix: change by-id cache key to ~id to prevent column name collision" +``` + +--- + +## Task 4: Extract shared `is_valid_identifier` to eliminate duplication + +**Files:** +- Modify: `src/routes/mod.rs` +- Modify: `src/routes/crud.rs:16-22` +- Modify: `src/routes/admin/tables.rs:17-23` + +- [ ] **Step 1: Add the shared function to `src/routes/mod.rs`** + +Replace the current content of `src/routes/mod.rs`: +```rust +pub mod admin; +pub mod auth; +pub mod crud; + +/// Returns true if `name` is a safe SQL identifier (non-empty, alphanumeric + underscore only). +pub fn is_valid_identifier(name: &str) -> bool { + !name.is_empty() && name.chars().all(|c| c.is_alphanumeric() || c == '_') +} +``` + +- [ ] **Step 2: Update `src/routes/crud.rs` to use the shared function** + +Remove the local `validate_identifier` (lines 16-22): +```rust +// DELETE this function entirely: +fn validate_identifier(name: &str) -> Result<()> { + if name.chars().all(|c| c.is_alphanumeric() || c == '_') { + Ok(()) + } else { + Err(anyhow!("invalid identifier: {}", name)) + } +} +``` + +Replace the two call sites in `build_query`: +```rust +// Line 34 — was: validate_identifier(table)?; +if !crate::routes::is_valid_identifier(table) { + return Err(anyhow!("invalid identifier: {}", table)); +} +// Line 35-37 — was: for (col, _) in ... { validate_identifier(col)?; } +for (col, _) in body_cols.iter().chain(filter_cols.iter()) { + if !crate::routes::is_valid_identifier(col) { + return Err(anyhow!("invalid identifier: {}", col)); + } +} +``` + +- [ ] **Step 3: Update `src/routes/admin/tables.rs` to use the shared function** + +Remove the local `validate_identifier` (lines 17-23): +```rust +// DELETE this function entirely: +fn validate_identifier(name: &str) -> Result<(), StatusCode> { + if !name.is_empty() && name.chars().all(|c| c.is_alphanumeric() || c == '_') { + Ok(()) + } else { + Err(StatusCode::BAD_REQUEST) + } +} +``` + +Replace all three call sites: +```rust +// In get_table_preview, create_table, drop_table — replace validate_identifier(&name)? with: +if !crate::routes::is_valid_identifier(&name) { + return Err(StatusCode::BAD_REQUEST); +} +// In create_table column loop — replace validate_identifier(&col.name)? with: +if !crate::routes::is_valid_identifier(&col.name) { + return Err(StatusCode::BAD_REQUEST); +} +``` + +- [ ] **Step 4: Run tests** + +```bash +cargo test +``` +Expected: all tests pass. + +- [ ] **Step 5: Commit** + +```bash +git add src/routes/mod.rs src/routes/crud.rs src/routes/admin/tables.rs +git commit -m "refactor: extract shared is_valid_identifier to eliminate duplication" +``` + +--- + +## Task 5: Add protected-table denylist to DDL operations + +**Files:** +- Modify: `src/routes/admin/tables.rs` + +- [ ] **Step 1: Write failing tests** + +Add to `src/routes/admin/tables.rs` at the bottom: + +```rust +#[cfg(test)] +mod tests { + use super::PROTECTED_TABLES; + + #[test] + fn test_protected_tables_list() { + assert!(PROTECTED_TABLES.contains(&"users")); + assert!(PROTECTED_TABLES.contains(&"blacklist")); + assert!(PROTECTED_TABLES.contains(&"api_keys")); + assert!(PROTECTED_TABLES.contains(&"queries")); + assert!(PROTECTED_TABLES.contains(&"permissions")); + } + + #[test] + fn test_is_protected() { + assert!(is_protected("users")); + assert!(is_protected("USERS")); // case-insensitive + assert!(!is_protected("orders")); + } +} +``` + +- [ ] **Step 2: Run test to confirm it fails** + +```bash +cargo test test_protected_tables_list test_is_protected +``` +Expected: FAIL — `PROTECTED_TABLES` and `is_protected` not defined yet. + +- [ ] **Step 3: Add the denylist and helper** + +At the top of `src/routes/admin/tables.rs`, after the `use` imports, add: + +```rust +const PROTECTED_TABLES: &[&str] = &["users", "blacklist", "api_keys", "queries", "permissions"]; + +fn is_protected(name: &str) -> bool { + let lower = name.to_lowercase(); + PROTECTED_TABLES.iter().any(|&t| t == lower) +} +``` + +- [ ] **Step 4: Guard `drop_table`** + +In `drop_table`, after `validate_identifier(&name)?;`, add: +```rust +if is_protected(&name) { + return Err(StatusCode::FORBIDDEN); +} +``` + +- [ ] **Step 5: Guard `create_table`** + +In `create_table`, after `validate_identifier(&body.name)?;`, add: +```rust +if is_protected(&body.name) { + return Err(StatusCode::FORBIDDEN); +} +``` + +- [ ] **Step 6: Run tests** + +```bash +cargo test +``` +Expected: all tests pass. + +- [ ] **Step 7: Commit** + +```bash +git add src/routes/admin/tables.rs +git commit -m "fix: block DDL operations on protected system tables" +``` + +--- + +## Task 6: Eliminate NULL_SENTINEL — thread `serde_json::Value` through `build_query` + +**Files:** +- Modify: `src/routes/crud.rs` (signature of `build_query`, binding loop, password hashing) + +**The bug:** `"\x00NULL"` is an in-band sentinel — a real string field containing those bytes would be silently written as SQL NULL. + +- [ ] **Step 1: Update `build_query` signature and return type** + +Change the function signature and all `Vec` params returns to `Vec`. Full new function (replace lines 27-114): + +```rust +/// Returns (sql, ordered_param_values, cache_key) +pub fn build_query( + method: &str, + table: &str, + id: Option<&str>, + body_cols: &[(String, Value)], + filter_cols: &[(String, String)], +) -> Result<(String, Vec, String)> { + if !crate::routes::is_valid_identifier(table) { + return Err(anyhow!("invalid identifier: {}", table)); + } + for (col, _) in body_cols.iter() { + if !crate::routes::is_valid_identifier(col) { + return Err(anyhow!("invalid identifier: {}", col)); + } + } + for (col, _) in filter_cols.iter() { + if !crate::routes::is_valid_identifier(col) { + return Err(anyhow!("invalid identifier: {}", col)); + } + } + + let mut sorted_body = body_cols.to_vec(); + sorted_body.sort_by(|a, b| a.0.cmp(&b.0)); + let mut sorted_filters = filter_cols.to_vec(); + sorted_filters.sort_by(|a, b| a.0.cmp(&b.0)); + + match method.to_uppercase().as_str() { + "GET" => { + if let Some(id_val) = id { + let sql = format!("SELECT * FROM {} WHERE id = $1", table); + let key = format!("GET:{}:~id", table); + Ok((sql, vec![Value::String(id_val.to_string())], key)) + } else if sorted_filters.is_empty() { + let sql = format!("SELECT * FROM {}", table); + let key = format!("GET:{}:", table); + Ok((sql, vec![], key)) + } else { + let col_names: Vec = sorted_filters.iter().map(|(c, _)| c.clone()).collect(); + let where_clause: Vec = col_names + .iter() + .enumerate() + .map(|(i, c)| format!("{} = ${}", c, i + 1)) + .collect(); + let sql = format!("SELECT * FROM {} WHERE {}", table, where_clause.join(" AND ")); + let params: Vec = sorted_filters.iter().map(|(_, v)| Value::String(v.clone())).collect(); + let key = format!("GET:{}:{}", table, col_names.join(",")); + Ok((sql, params, key)) + } + } + "POST" => { + if sorted_body.is_empty() { + return Err(anyhow!("POST requires a body with at least one field")); + } + let cols: Vec = sorted_body.iter().map(|(c, _)| c.clone()).collect(); + let placeholders: Vec = (1..=cols.len()).map(|i| format!("${}", i)).collect(); + let sql = format!( + "INSERT INTO {} ({}) VALUES ({}) RETURNING *", + table, + cols.join(", "), + placeholders.join(", ") + ); + let params: Vec = sorted_body.iter().map(|(_, v)| v.clone()).collect(); + let key = format!("POST:{}:{}", table, cols.join(",")); + Ok((sql, params, key)) + } + "PUT" => { + let id_val = id.ok_or_else(|| anyhow!("PUT requires an id"))?; + if sorted_body.is_empty() { + return Err(anyhow!("PUT requires a body with at least one field")); + } + let cols: Vec = sorted_body.iter().map(|(c, _)| c.clone()).collect(); + let set_clause: Vec = cols + .iter() + .enumerate() + .map(|(i, c)| format!("{} = ${}", c, i + 1)) + .collect(); + let id_placeholder = cols.len() + 1; + let sql = format!( + "UPDATE {} SET {} WHERE id = ${} RETURNING *", + table, + set_clause.join(", "), + id_placeholder + ); + let mut params: Vec = sorted_body.iter().map(|(_, v)| v.clone()).collect(); + params.push(Value::String(id_val.to_string())); + let key = format!("PUT:{}:{}:by_id", table, cols.join(",")); + Ok((sql, params, key)) + } + "DELETE" => { + let id_val = id.ok_or_else(|| anyhow!("DELETE requires an id"))?; + let sql = format!("DELETE FROM {} WHERE id = $1", table); + let key = format!("DELETE:{}:by_id", table); + Ok((sql, vec![Value::String(id_val.to_string())], key)) + } + m => Err(anyhow!("unsupported method: {}", m)), + } +} +``` + +- [ ] **Step 2: Update `handle_crud` — simplify body collection and remove sentinel** + +Replace the body collection block (lines 206-234) in `handle_crud`: + +```rust +// Body params: collect as typed Values directly +let mut body_cols: Vec<(String, Value)> = body + .map(|Json(b)| b.into_iter().collect()) + .unwrap_or_default(); + +// Hash the password field for the users table before building the query. +if table == "users" && matches!(method_str.to_uppercase().as_str(), "POST" | "PUT") { + if let Some(pos) = body_cols.iter().position(|(k, _)| k == "password") { + let (_, val) = body_cols.remove(pos); + if let Value::String(plaintext) = val { + let hash = bcrypt::hash(&plaintext, bcrypt::DEFAULT_COST) + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; + body_cols.push(("password_hash".to_string(), Value::String(hash))); + } + } +} +``` + +- [ ] **Step 3: Update the binding loop in `handle_crud`** + +Replace the binding loop (after `let mut q = sqlx::query(&sql);`): + +```rust +let mut q = sqlx::query(&sql); +for val in ¶ms_vals { + match val { + Value::Null => q = q.bind(Option::::None), + Value::Bool(b) => q = q.bind(*b), + Value::Number(n) => { + if let Some(i) = n.as_i64() { + q = q.bind(i); + } else if let Some(f) = n.as_f64() { + q = q.bind(f); + } else { + q = q.bind(n.to_string()); + } + } + Value::String(s) => q = q.bind(s.as_str()), + other => q = q.bind(other.to_string()), + } +} +``` + +- [ ] **Step 4: Update unit tests for `build_query` to use `Value`** + +In the `#[cfg(test)]` block at the bottom of `src/routes/crud.rs`, update all `build_query` calls (the signature now takes `&[(String, Value)]` for body_cols and returns `Vec`). + +Update `test_build_insert`: +```rust +#[test] +fn test_build_insert() { + let cols = vec![ + ("email".into(), Value::String("a@b.com".into())), + ("name".into(), Value::String("Alice".into())), + ]; + let (sql, params, key) = build_query("POST", "users", None, &cols, &[]).unwrap(); + assert_eq!(sql, "INSERT INTO users (email, name) VALUES ($1, $2) RETURNING *"); + assert_eq!(params, vec![Value::String("a@b.com".into()), Value::String("Alice".into())]); + assert_eq!(key, "POST:users:email,name"); +} +``` + +Update `test_build_update`: +```rust +#[test] +fn test_build_update() { + let cols = vec![("name".into(), Value::String("Bob".into()))]; + let (sql, params, key) = build_query("PUT", "users", Some("7"), &cols, &[]).unwrap(); + assert_eq!(sql, "UPDATE users SET name = $1 WHERE id = $2 RETURNING *"); + assert_eq!(params, vec![Value::String("Bob".into()), Value::String("7".into())]); + assert_eq!(key, "PUT:users:name:by_id"); +} +``` + +Update `test_build_select_by_id` (already changed key in Task 3): +```rust +#[test] +fn test_build_select_by_id() { + let (sql, params, key) = build_query("GET", "orders", Some("42"), &[], &[]).unwrap(); + assert_eq!(sql, "SELECT * FROM orders WHERE id = $1"); + assert_eq!(params, vec![Value::String("42".into())]); + assert_eq!(key, "GET:orders:~id"); +} +``` + +Update `test_build_delete`: +```rust +#[test] +fn test_build_delete() { + let (sql, params, key) = build_query("DELETE", "users", Some("3"), &[], &[]).unwrap(); + assert_eq!(sql, "DELETE FROM users WHERE id = $1"); + assert_eq!(params, vec![Value::String("3".into())]); + assert_eq!(key, "DELETE:users:by_id"); +} +``` + +Update `test_build_select_all` (no body/filter params, just check it compiles): +```rust +#[test] +fn test_build_select_all() { + let (sql, params, key) = build_query("GET", "orders", None, &[], &[]).unwrap(); + assert_eq!(sql, "SELECT * FROM orders"); + assert!(params.is_empty()); + assert_eq!(key, "GET:orders:"); +} +``` + +Update `test_build_select_with_filters`: +```rust +#[test] +fn test_build_select_with_filters() { + let filters = vec![("status".into(), "active".into()), ("role".into(), "admin".into())]; + let (sql, params, key) = build_query("GET", "users", None, &[], &filters).unwrap(); + assert_eq!(sql, "SELECT * FROM users WHERE role = $1 AND status = $2"); + assert_eq!(params, vec![Value::String("admin".into()), Value::String("active".into())]); + assert_eq!(key, "GET:users:role,status"); +} +``` + +`test_rejects_invalid_table_name` needs no change. + +- [ ] **Step 5: Run tests** + +```bash +cargo test +``` +Expected: all tests pass. + +- [ ] **Step 6: Commit** + +```bash +git add src/routes/crud.rs +git commit -m "fix: eliminate NULL_SENTINEL by threading serde_json::Value through build_query" +``` + +--- + +## Task 7: Stash Claims in `blacklist_layer` to eliminate double DB hit + +**Files:** +- Modify: `src/auth/middleware.rs` + +**The fix:** Add an `authenticate()` helper. `blacklist_layer` stashes resolved `Claims` in request extensions. All `require_*` functions check extensions first, skipping the DB call if already authenticated. + +- [ ] **Step 1: Rewrite `src/auth/middleware.rs`** + +Replace the entire file: + +```rust +use axum::{ + extract::{Request, State}, + http::StatusCode, + middleware::Next, + response::Response, +}; + +use crate::{auth::{decode_jwt, resolve_api_key, Claims}, state::AppState}; + +/// Resolves a Bearer token to Claims, trying JWT then API key. +/// On success, inserts Claims into request extensions so downstream middleware +/// can reuse them without hitting the database again. +async fn authenticate( + token: &str, + state: &AppState, + req: &mut Request, +) -> Option { + if let Some(existing) = req.extensions().get::().cloned() { + return Some(existing); + } + let claims = if let Ok(c) = decode_jwt(token, &state.config.jwt_secret) { + c + } else { + resolve_api_key(token, &state.pool).await? + }; + req.extensions_mut().insert(claims.clone()); + Some(claims) +} + +pub async fn blacklist_layer( + State(state): State, + mut req: Request, + next: Next, +) -> Result { + let method = req.method().as_str().to_uppercase(); + let path = req.uri().path().to_string(); + let caller_mask = if let Some(token) = extract_bearer(&req) { + authenticate(&token, &state, &mut req) + .await + .map(|c| c.permissions_mask()) + .unwrap_or(0) + } else { + 0 + }; + if state.blacklist_cache.is_blocked(&method, &path, caller_mask).await { + return Err(StatusCode::FORBIDDEN); + } + Ok(next.run(req).await) +} + +pub fn extract_bearer(req: &Request) -> Option { + req.headers() + .get("authorization") + .and_then(|v| v.to_str().ok()) + .and_then(|v| v.strip_prefix("Bearer ")) + .map(|s| s.to_string()) +} + +pub async fn require_auth( + State(state): State, + mut req: Request, + next: Next, +) -> Result { + let token = extract_bearer(&req).ok_or(StatusCode::UNAUTHORIZED)?; + authenticate(&token, &state, &mut req).await.ok_or(StatusCode::UNAUTHORIZED)?; + Ok(next.run(req).await) +} + +pub async fn require_super_admin( + State(state): State, + mut req: Request, + next: Next, +) -> Result { + let token = extract_bearer(&req).ok_or(StatusCode::UNAUTHORIZED)?; + let claims = authenticate(&token, &state, &mut req).await.ok_or(StatusCode::UNAUTHORIZED)?; + if !claims.has_permission(crate::auth::permissions::SUPER_ADMIN) { + return Err(StatusCode::FORBIDDEN); + } + Ok(next.run(req).await) +} + +pub async fn require_admin_query( + State(state): State, + mut req: Request, + next: Next, +) -> Result { + let token = extract_bearer(&req).ok_or(StatusCode::UNAUTHORIZED)?; + let claims = authenticate(&token, &state, &mut req).await.ok_or(StatusCode::UNAUTHORIZED)?; + if !claims.has_permission(crate::auth::permissions::ADMIN_QUERY) { + return Err(StatusCode::FORBIDDEN); + } + Ok(next.run(req).await) +} + +pub async fn require_admin_cache( + State(state): State, + mut req: Request, + next: Next, +) -> Result { + let token = extract_bearer(&req).ok_or(StatusCode::UNAUTHORIZED)?; + let claims = authenticate(&token, &state, &mut req).await.ok_or(StatusCode::UNAUTHORIZED)?; + if !claims.has_permission(crate::auth::permissions::ADMIN_CACHE) { + return Err(StatusCode::FORBIDDEN); + } + Ok(next.run(req).await) +} +``` + +- [ ] **Step 2: Run tests** + +```bash +cargo test +``` +Expected: all tests pass. + +- [ ] **Step 3: Commit** + +```bash +git add src/auth/middleware.rs +git commit -m "fix: stash Claims in request extensions to eliminate double DB hit per API key request" +``` + +--- + +## Task 8: Enforce READ/WRITE/DELETE permission bits in CRUD handler + +**Files:** +- Modify: `src/routes/crud.rs` + +- [ ] **Step 1: Add `Extension(claims)` to `handle_crud` and check permissions** + +Change the `handle_crud` signature to extract `Claims`: + +```rust +pub async fn handle_crud( + State(state): State, + method: Method, + Extension(claims): Extension, + Path(params): Path>, + Query(query_params): Query>, + body: Option>>, +) -> Result, StatusCode> { +``` + +Then add permission check immediately after extracting `method_str`: + +```rust +let method_str = method.as_str(); + +// Enforce permission bits before doing any work. +let required_bit = match method_str.to_uppercase().as_str() { + "GET" => crate::auth::permissions::READ, + "POST" | "PUT" => crate::auth::permissions::WRITE, + "DELETE" => crate::auth::permissions::DELETE, + _ => return Err(StatusCode::METHOD_NOT_ALLOWED), +}; +if !claims.has_permission(required_bit) { + return Err(StatusCode::FORBIDDEN); +} +``` + +- [ ] **Step 2: Run tests** + +```bash +cargo test +``` +Expected: all tests pass. (`build_query` unit tests don't call `handle_crud`, so they're unaffected.) + +- [ ] **Step 3: Commit** + +```bash +git add src/routes/crud.rs +git commit -m "fix: enforce READ/WRITE/DELETE permission bits in CRUD handler" +``` + +--- + +## Task 9: Add configurable CORS and body size limit + +**Files:** +- Modify: `src/config.rs` +- Modify: `src/main.rs` + +- [ ] **Step 1: Add `cors_origins` to `Config`** + +In `src/config.rs`, add the field and parsing: + +```rust +use anyhow::Result; + +#[derive(Clone, Debug)] +pub struct Config { + pub database_url: String, + pub jwt_secret: String, + pub jwt_expiry_secs: u64, + pub cache_max_capacity: usize, + pub cache_idle_timeout_secs: u64, + pub cache_sweep_interval_secs: u64, + /// Comma-separated list of allowed CORS origins, or "*" for permissive. + /// If empty, no CORS headers are added. + pub cors_origins: Vec, +} + +impl Config { + pub fn from_env() -> Result { + Ok(Self { + database_url: std::env::var("DATABASE_URL")?, + jwt_secret: std::env::var("JWT_SECRET")?, + jwt_expiry_secs: std::env::var("JWT_EXPIRY_SECS") + .unwrap_or_else(|_| "3600".into()) + .parse()?, + cache_max_capacity: std::env::var("CACHE_MAX_CAPACITY") + .unwrap_or_else(|_| "10000".into()) + .parse()?, + cache_idle_timeout_secs: std::env::var("CACHE_IDLE_TIMEOUT_SECS") + .unwrap_or_else(|_| "300".into()) + .parse()?, + cache_sweep_interval_secs: std::env::var("CACHE_SWEEP_INTERVAL_SECS") + .unwrap_or_else(|_| "60".into()) + .parse()?, + cors_origins: std::env::var("CORS_ORIGINS") + .unwrap_or_default() + .split(',') + .map(|s| s.trim().to_string()) + .filter(|s| !s.is_empty()) + .collect(), + }) + } +} +``` + +- [ ] **Step 2: Update `.env.example`** + +Add `CORS_ORIGINS=` (empty, no CORS by default) to `.env.example`. + +- [ ] **Step 3: Update `src/main.rs` imports and app builder** + +Add imports at the top of `src/main.rs`: +```rust +use axum::extract::DefaultBodyLimit; +use axum::http::{header, HeaderValue, Method}; +use tower_http::cors::{Any, CorsLayer}; +``` + +Replace `CorsLayer::permissive()` in the app builder with a configured layer. The CRUD routes also get a body size limit. Replace the `crud_routes` and `app` blocks: + +```rust +let crud_routes = Router::new() + .route("/api/:table", get(handle_crud).post(handle_crud)) + .route("/api/:table/", get(handle_crud).post(handle_crud)) + .route("/api/:table/:id", get(handle_crud).put(handle_crud).delete(handle_crud)) + .route("/api/:table/:id/", get(handle_crud).put(handle_crud).delete(handle_crud)) + .layer(DefaultBodyLimit::max(1 * 1024 * 1024)) // 1 MB + .route_layer(middleware::from_fn_with_state(state.clone(), require_auth)) + .route_layer(middleware::from_fn_with_state(state.clone(), blacklist_layer)); + +let cors_layer = build_cors(&config.cors_origins); + +let app = Router::new() + .route("/auth/login", post(login)) + .merge(crud_routes) + .nest("/api/admin", admin_router(state.clone())) + .nest_service("/", ServeDir::new("ui/dist").fallback(ServeFile::new("ui/dist/index.html"))) + .layer(cors_layer) + .with_state(state); +``` + +Add the `build_cors` helper function (before `main`): + +```rust +fn build_cors(origins: &[String]) -> CorsLayer { + if origins.is_empty() { + return CorsLayer::new(); + } + if origins.iter().any(|o| o == "*") { + return CorsLayer::permissive(); + } + let parsed: Vec = origins + .iter() + .filter_map(|o| o.parse().ok()) + .collect(); + CorsLayer::new() + .allow_origin(parsed) + .allow_methods([Method::GET, Method::POST, Method::PUT, Method::DELETE, Method::OPTIONS]) + .allow_headers([header::CONTENT_TYPE, header::AUTHORIZATION]) +} +``` + +- [ ] **Step 4: Run tests** + +```bash +cargo test +``` +Expected: all tests pass. + +- [ ] **Step 5: Commit** + +```bash +git add src/config.rs src/main.rs .env.example +git commit -m "fix: replace permissive CORS with configured origins; add 1MB body size limit" +``` + +--- + +## Task 10: First-user interactive setup (replace hardcoded admin/admin) + +**Files:** +- Modify: `src/main.rs` + +**Behavior:** On startup, if no users exist in the database, the server prompts on stdin for a username and password, creates that user with full permissions (mask=63), then starts serving. Routes are locked down by auth from the first request — there is no magic credential. + +- [ ] **Step 1: Add `use std::io::Write;` import to `src/main.rs`** + +In `src/main.rs` imports, add: +```rust +use std::io::{self, Write}; +``` + +- [ ] **Step 2: Replace the admin seed block** + +Remove lines 42-56 in `src/main.rs` (the current admin seed): +```rust +// DELETE all of this: +let count: i64 = sqlx::query_scalar::<_, Option>("SELECT COUNT(*) FROM users WHERE username = 'admin'") + .fetch_one(&pool) + .await? + .unwrap_or(0); +if count == 0 { + let hash = bcrypt::hash("admin", bcrypt::DEFAULT_COST)?; + sqlx::query( + "INSERT INTO users (username, password_hash, permissions_mask) VALUES ('admin', $1, '63')" + ) + .bind(hash) + .execute(&pool) + .await?; + tracing::info!("seeded admin user"); +} +``` + +Replace with: +```rust +// If no users exist, prompt to create the first admin. +let user_count: i64 = sqlx::query_scalar::<_, Option>("SELECT COUNT(*) FROM users") + .fetch_one(&pool) + .await? + .unwrap_or(0); +if user_count == 0 { + println!("\nNo users found. Create the first admin account."); + print!("Username: "); + io::stdout().flush()?; + let mut username = String::new(); + io::stdin().read_line(&mut username)?; + let username = username.trim().to_string(); + if username.is_empty() { + anyhow::bail!("username cannot be empty"); + } + + print!("Password: "); + io::stdout().flush()?; + let mut password = String::new(); + io::stdin().read_line(&mut password)?; + let password = password.trim().to_string(); + if password.is_empty() { + anyhow::bail!("password cannot be empty"); + } + + let hash = bcrypt::hash(&password, bcrypt::DEFAULT_COST)?; + sqlx::query( + "INSERT INTO users (username, password_hash, permissions_mask) VALUES ($1, $2, '63')", + ) + .bind(&username) + .bind(hash) + .execute(&pool) + .await?; + tracing::info!("created first admin user: {}", username); + println!("Admin user '{}' created. Starting server...\n", username); +} +``` + +- [ ] **Step 3: Run tests** + +```bash +cargo test +``` +Expected: all tests pass (this is startup logic, not unit-testable without a DB). + +- [ ] **Step 4: Commit** + +```bash +git add src/main.rs +git commit -m "fix: replace hardcoded admin/admin seed with interactive first-user setup on empty DB" +``` + +--- + +## Task 11: Remove spurious `mut` on `body_cols_typed` + +> **Note:** After Task 6, `body_cols_typed` no longer exists — this was eliminated when the body collection was simplified. Verify the `mut` warning is gone. + +- [ ] **Step 1: Confirm no `mut` warning** + +```bash +cargo build 2>&1 | grep "unused_mut\|body_cols_typed" +``` +Expected: no output (variable was removed in Task 6). + +If the warning still appears for another variable, find and remove the `mut`: +```bash +cargo build 2>&1 | grep "warning.*mut" +``` +Fix any remaining spurious `mut` annotations. + +- [ ] **Step 2: Commit if any change was needed** + +```bash +git add src/routes/crud.rs +git commit -m "fix: remove spurious mut annotations" +``` + +--- + +## Self-Review + +**Spec coverage check:** +- C1 (CRUD permissions) → Task 8 ✓ +- C2 (admin/admin seed) → Task 10 ✓ +- C3 (protected tables) → Task 5 ✓ +- C4 (prefix substitution) → Task 2 ✓ +- I1 (cache key collision) → Task 3 ✓ +- I2 (double DB hit) → Task 7 ✓ +- I3 (NULL_SENTINEL) → Task 6 ✓ +- I4 (unix_now panic) → Task 1 ✓ +- M1 (duplicate validator) → Task 4 ✓ +- M3 (permissive CORS) → Task 9 ✓ +- M5 (body size limit) → Task 9 ✓ +- M6 (spurious mut) → Task 11 ✓ + +**Dependency order:** +- Task 4 (shared validator) must run before Task 5 (it uses `is_valid_identifier`) +- Task 6 (Value params) must run before Task 8 (handle_crud signature stabilizes) +- Task 7 (stash Claims) must run before Task 8 (handle_crud reads claims from extensions) +- All other tasks are independent + +**Type consistency check:** +- `build_query` returns `Vec` after Task 6; all callers updated in the same task ✓ +- `is_valid_identifier` returns `bool` (added Task 4); callers in Tasks 4 and 5 check `!is_valid_identifier(...)` ✓ +- `authenticate()` returns `Option` (Task 7); all require_* callers use `.ok_or(UNAUTHORIZED)?` ✓ diff --git a/docs/superpowers/plans/2026-06-18-cors-cdn-implementation.md b/docs/superpowers/plans/2026-06-18-cors-cdn-implementation.md new file mode 100644 index 0000000..f42c1a7 --- /dev/null +++ b/docs/superpowers/plans/2026-06-18-cors-cdn-implementation.md @@ -0,0 +1,1638 @@ +# Dynamic CORS + CDN Proxy Implementation Plan + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** Add runtime-editable CORS origins backed by PostgreSQL (managed via CRUD API, protected by super_admin bypass mask) and a CDN proxy that maps keys to local container URLs with a DB registry; add loading spinners to all admin views. + +**Architecture:** CORS uses a custom async Axum middleware (`cors_layer`) that reads from an `Arc>` in-memory cache, populated from the `cors_origins` table and reloaded after every mutation via the CRUD hook. The CDN adds dedicated routes at `/api/cdn` and `/api/cdn/:key` that read from `cdn_objects` and proxy to internal URLs via `reqwest`; write operations are blocked for non-super-admins by blacklist migration. Both features get Vue admin views. + +**Tech Stack:** Rust/axum 0.7, sqlx 0.7, tokio, reqwest 0.12, Vue 3/TypeScript + +## Global Constraints + +- All DB access uses `sqlx::query_as` / `sqlx::query` (not `sqlx::query!` macro — no compile-time DB required). +- Blacklist super-admin bypass bit is `'32'` (string, matches existing migrations). +- All new Rust modules follow existing `pub mod` declaration in their parent `mod.rs`. +- Vue components import auth store via `import { useAuthStore } from '../../stores/auth'`. +- No new npm dependencies — existing NychButton, NychDialog, NychInputText, NychSelect are available globally. +- `cargo test` must pass after every Rust task. + +--- + +## File Map + +| File | Action | +|---|---| +| `docker-compose.yml` | Modify — add `cdn` (MinIO), `cdn-init`, `cdn_data` volume; `api` depends on `cdn` | +| `Dockerfile` | Modify — add `minio-download` stage; copy `minio` + `mc` binaries to final image | +| `entrypoint.sh` | Modify — start MinIO in background, wait for health, create bucket before Postgres | +| `.env.example` | Modify — add `CDN_ACCESS_KEY`, `CDN_SECRET_KEY`, `CDN_BUCKET` | +| `src/db/migrations/007_cors_origins.sql` | Create | +| `src/db/migrations/008_cdn_objects.sql` | Create | +| `src/state.rs` | Modify — add `CorsCache`, `CorsState`, `http_client`; update `AppState` | +| `src/models/cdn.rs` | Create | +| `src/models/mod.rs` | Modify — add `pub mod cdn` | +| `src/auth/middleware.rs` | Modify — add `cors_layer` | +| `src/routes/cdn.rs` | Create | +| `src/routes/mod.rs` | Modify — add `pub mod cdn` | +| `src/routes/crud.rs` | Modify — add `reload_cors`, hook | +| `src/routes/admin/tables.rs` | Modify — add `cors_origins`, `cdn_objects` to `PROTECTED_TABLES` | +| `src/main.rs` | Modify — remove `build_cors`, wire `cors_cache`, `http_client`, `cors_layer`, CDN routes | +| `Cargo.toml` | Modify — add `reqwest`, remove `cors` feature from `tower-http` | +| `ui/src/assets/main.css` | Modify — add spinner keyframe + classes | +| `ui/src/views/admin/Blacklist.vue` | Modify — add loading state | +| `ui/src/views/admin/ApiKeys.vue` | Modify — add loading state | +| `ui/src/views/admin/Cache.vue` | Modify — add loading state | +| `ui/src/views/admin/Queries.vue` | Modify — add loading state | +| `ui/src/views/admin/Tables.vue` | Modify — add loading state | +| `ui/src/views/admin/Users.vue` | Modify — add loading state | +| `ui/src/views/admin/Permissions.vue` | Modify — add loading state | +| `ui/src/views/admin/Cors.vue` | Create | +| `ui/src/views/admin/Cdn.vue` | Create | +| `ui/src/router/index.ts` | Modify — add `/admin/cors` and `/admin/cdn` routes | +| `ui/src/views/admin/Layout.vue` | Modify — add CORS and CDN nav items | + +--- + +### Task 0: Infrastructure — Docker Compose + Dockerfile + Entrypoint + +> **Already done** — these files were updated during planning. Mark complete and move to Task 1. + +**Files (already modified):** +- `docker-compose.yml` — `cdn` (MinIO) + `cdn-init` services; `cdn_data` volume; `api` `depends_on` cdn healthy +- `Dockerfile` — `minio-download` stage (`alpine:3`, downloads `minio` + `mc` via `TARGETARCH`); copies binaries to final image; exposes 9000/9001 +- `entrypoint.sh` — starts MinIO in background, loops `mc alias set` until ready, creates `$CDN_BUCKET` with anonymous download policy, then starts Postgres + Mercury +- `.env.example` — documents `CDN_ACCESS_KEY`, `CDN_SECRET_KEY`, `CDN_BUCKET`, and the URL prefix pattern + +**CDN URL pattern (important for admin users registering objects):** +- docker-compose stack: `http://cdn:9000/mercury/` +- standalone image: `http://localhost:9000/mercury/` + +The bucket is created with anonymous read (`mc anonymous set download`), so the Mercury proxy makes unauthenticated GET requests — no credentials needed in the API. + +- [ ] **Mark complete — files already written.** + +--- + +### Task 1: DB Migrations + +**Files:** +- Create: `src/db/migrations/007_cors_origins.sql` +- Create: `src/db/migrations/008_cdn_objects.sql` + +**Interfaces:** +- Produces: `cors_origins(id, origin, created_at)` and `cdn_objects(id, key, url, content_type, description, created_at)` tables; blacklist seeds for both. + +- [ ] **Step 1: Write 007_cors_origins.sql** + +```sql +CREATE TABLE cors_origins ( + id SERIAL PRIMARY KEY, + origin TEXT NOT NULL UNIQUE, + created_at TIMESTAMPTZ NOT NULL DEFAULT now() +); + +-- Restrict CRUD mutations to super-admins (bit 32). Mirrors blacklist/queries pattern. +INSERT INTO blacklist (pattern, method, reason, active, bypass_mask) VALUES + ('/api/cors_origins', NULL, 'admin-only table', true, '32'), + ('/api/cors_origins/**', NULL, 'admin-only table', true, '32'); +``` + +- [ ] **Step 2: Write 008_cdn_objects.sql** + +```sql +CREATE TABLE cdn_objects ( + id SERIAL PRIMARY KEY, + key TEXT NOT NULL UNIQUE, + url TEXT NOT NULL, + content_type TEXT, + description TEXT, + created_at TIMESTAMPTZ NOT NULL DEFAULT now() +); + +-- Block mutations to /api/cdn for non-super-admins. GET is unblocked (no entry). +INSERT INTO blacklist (pattern, method, reason, active, bypass_mask) VALUES + ('/api/cdn', 'POST,PUT,PATCH,DELETE', 'CDN write operations are super-admin only', true, '32'), + ('/api/cdn/**', 'POST,PUT,PATCH,DELETE', 'CDN write operations are super-admin only', true, '32'); +``` + +- [ ] **Step 3: Verify migrations compile** + +```bash +cd /home/mcpeakml/code/rust/Mercury && cargo build 2>&1 | tail -3 +``` +Expected: `Finished dev` (sqlx migrate! scans the directory; new files are included automatically). + +--- + +### Task 2: CorsCache + AppState + +**Files:** +- Modify: `src/state.rs` +- Modify: `Cargo.toml` + +**Interfaces:** +- Produces: + - `CorsCache::new() -> CorsCache` + - `CorsCache::load(origins: Vec) -> ()` (async) + - `AppState.cors_cache: CorsCache` + - `AppState.http_client: reqwest::Client` + +- [ ] **Step 1: Add reqwest to Cargo.toml** + +Replace the tower-http line and add reqwest: + +```toml +tower-http = { version = "0.5", features = ["fs"] } +reqwest = { version = "0.12", default-features = false, features = ["rustls-tls", "json"] } +``` + +- [ ] **Step 2: Write the failing tests** + +Add to the `#[cfg(test)]` block at the bottom of `src/state.rs`: + +```rust +#[tokio::test] +async fn test_cors_cache_wildcard() { + let cache = CorsCache::new(); + cache.load(vec!["*".to_string()]).await; + let guard = cache.inner.read().await; + assert!(guard.wildcard); + assert!(guard.origins.is_empty()); +} + +#[tokio::test] +async fn test_cors_cache_specific_origin() { + let cache = CorsCache::new(); + cache.load(vec!["https://example.com".to_string()]).await; + let guard = cache.inner.read().await; + assert!(!guard.wildcard); + assert_eq!(guard.origins.len(), 1); + assert_eq!(guard.origins[0], "https://example.com"); +} + +#[tokio::test] +async fn test_cors_cache_empty() { + let cache = CorsCache::new(); + cache.load(vec![]).await; + let guard = cache.inner.read().await; + assert!(!guard.wildcard); + assert!(guard.origins.is_empty()); +} + +#[tokio::test] +async fn test_cors_cache_load_replaces() { + let cache = CorsCache::new(); + cache.load(vec!["https://a.com".to_string()]).await; + cache.load(vec!["https://b.com".to_string()]).await; + let guard = cache.inner.read().await; + assert_eq!(guard.origins.len(), 1); + assert_eq!(guard.origins[0], "https://b.com"); +} +``` + +- [ ] **Step 3: Run tests to verify they fail** + +```bash +cd /home/mcpeakml/code/rust/Mercury && cargo test cors_cache 2>&1 | tail -5 +``` +Expected: compile error — `CorsCache` not defined yet. + +- [ ] **Step 4: Add CorsCache + CorsState structs and update AppState** + +In `src/state.rs`, add these imports at the top: + +```rust +use axum::http::HeaderValue; +``` + +Add after the `BlacklistCache` impl block: + +```rust +#[derive(Clone)] +pub struct CorsCache { + pub inner: Arc>, +} + +#[derive(Clone, Default)] +pub struct CorsState { + pub wildcard: bool, + pub origins: Vec, +} + +impl CorsCache { + pub fn new() -> Self { + Self { + inner: Arc::new(RwLock::new(CorsState::default())), + } + } + + pub async fn load(&self, origins: Vec) { + let wildcard = origins.iter().any(|o| o == "*"); + let parsed: Vec = origins + .iter() + .filter(|o| *o != "*") + .filter_map(|o| o.parse().ok()) + .collect(); + let mut guard = self.inner.write().await; + *guard = CorsState { wildcard, origins: parsed }; + } +} +``` + +Update `AppState`: + +```rust +#[derive(Clone)] +pub struct AppState { + pub pool: PgPool, + pub query_cache: QueryCache, + pub blacklist_cache: BlacklistCache, + pub cors_cache: CorsCache, + pub http_client: reqwest::Client, + pub config: Arc, +} +``` + +- [ ] **Step 5: Run tests to verify they pass** + +```bash +cd /home/mcpeakml/code/rust/Mercury && cargo test cors_cache 2>&1 | tail -5 +``` +Expected: `test result: ok. 4 passed` + +--- + +### Task 3: CdnObject Model + +**Files:** +- Create: `src/models/cdn.rs` +- Modify: `src/models/mod.rs` + +**Interfaces:** +- Produces: `CdnObject`, `CreateCdnObject`, `UpdateCdnObject` — used by `routes/cdn.rs` + +- [ ] **Step 1: Create src/models/cdn.rs** + +```rust +use chrono::{DateTime, Utc}; +use serde::{Deserialize, Serialize}; + +#[derive(Debug, Clone, Serialize, Deserialize, sqlx::FromRow)] +pub struct CdnObject { + pub id: i32, + pub key: String, + pub url: String, + pub content_type: Option, + pub description: Option, + pub created_at: DateTime, +} + +#[derive(Debug, Deserialize)] +pub struct CreateCdnObject { + pub key: String, + pub url: String, + pub content_type: Option, + pub description: Option, +} + +#[derive(Debug, Deserialize)] +pub struct UpdateCdnObject { + pub key: Option, + pub url: Option, + pub content_type: Option, + pub description: Option, +} +``` + +- [ ] **Step 2: Add to src/models/mod.rs** + +```rust +pub mod api_key; +pub mod blacklist; +pub mod cdn; +pub mod permission; +pub mod query; +pub mod user; +``` + +- [ ] **Step 3: Verify compilation** + +```bash +cd /home/mcpeakml/code/rust/Mercury && cargo build 2>&1 | tail -3 +``` +Expected: `Finished dev` + +--- + +### Task 4: cors_layer Middleware + +**Files:** +- Modify: `src/auth/middleware.rs` + +**Interfaces:** +- Consumes: `AppState.cors_cache: CorsCache` +- Produces: `cors_layer(State, Request, Next) -> Response` — applied globally in `main.rs` + +- [ ] **Step 1: Update imports in src/auth/middleware.rs** + +Replace the existing imports block with: + +```rust +use axum::{ + extract::{Request, State}, + http::{header, HeaderMap, HeaderValue, Method, StatusCode}, + middleware::Next, + response::{IntoResponse, Response}, +}; + +use crate::{ + auth::{decode_jwt, resolve_api_key, Claims}, + state::AppState, +}; +``` + +- [ ] **Step 2: Add cors_layer function** + +Add after the `require_admin_cache` function: + +```rust +pub async fn cors_layer( + State(state): State, + req: Request, + next: Next, +) -> Response { + let is_preflight = req.method() == Method::OPTIONS; + let origin_header = req.headers().get(header::ORIGIN).cloned(); + + enum CorsDecision { + None, + Wildcard, + Specific(HeaderValue), + } + + let decision = { + let guard = state.cors_cache.inner.read().await; + if guard.wildcard { + CorsDecision::Wildcard + } else if let Some(origin) = origin_header.as_ref() { + if guard.origins.contains(origin) { + CorsDecision::Specific(origin.clone()) + } else { + CorsDecision::None + } + } else { + CorsDecision::None + } + }; + + let (cors_origin, vary) = match &decision { + CorsDecision::None => (None, false), + CorsDecision::Wildcard => (Some(HeaderValue::from_static("*")), false), + CorsDecision::Specific(v) => (Some(v.clone()), true), + }; + + if is_preflight { + let mut headers = HeaderMap::new(); + if let Some(origin) = cors_origin { + headers.insert(header::ACCESS_CONTROL_ALLOW_ORIGIN, origin); + headers.insert( + header::ACCESS_CONTROL_ALLOW_METHODS, + HeaderValue::from_static("GET, POST, PUT, DELETE, OPTIONS"), + ); + headers.insert( + header::ACCESS_CONTROL_ALLOW_HEADERS, + HeaderValue::from_static("content-type, authorization"), + ); + if vary { + headers.insert(header::VARY, HeaderValue::from_static("Origin")); + } + } + return (StatusCode::NO_CONTENT, headers).into_response(); + } + + let mut response = next.run(req).await; + if let Some(origin) = cors_origin { + response + .headers_mut() + .insert(header::ACCESS_CONTROL_ALLOW_ORIGIN, origin); + if vary { + response + .headers_mut() + .append(header::VARY, HeaderValue::from_static("Origin")); + } + } + response +} +``` + +- [ ] **Step 3: Verify compilation** + +```bash +cd /home/mcpeakml/code/rust/Mercury && cargo build 2>&1 | tail -3 +``` +Expected: `Finished dev` + +--- + +### Task 5: CDN Route Handlers + +**Files:** +- Create: `src/routes/cdn.rs` +- Modify: `src/routes/mod.rs` + +**Interfaces:** +- Consumes: `AppState.pool`, `AppState.http_client`, `CdnObject`, `CreateCdnObject`, `UpdateCdnObject` +- Produces: `cdn_list`, `cdn_proxy`, `cdn_create`, `cdn_update`, `cdn_delete` — registered in `main.rs` + +- [ ] **Step 1: Create src/routes/cdn.rs** + +```rust +use axum::{ + extract::{Path, State}, + http::{header, StatusCode}, + response::IntoResponse, + Json, +}; +use serde_json::Value; +use sqlx::Row; + +use crate::{ + models::cdn::{CdnObject, CreateCdnObject, UpdateCdnObject}, + state::AppState, +}; + +pub async fn cdn_list( + State(state): State, +) -> Result>, StatusCode> { + let objects = sqlx::query_as::<_, CdnObject>( + "SELECT id, key, url, content_type, description, created_at \ + FROM cdn_objects ORDER BY id", + ) + .fetch_all(&state.pool) + .await + .map_err(|e| { + tracing::error!("cdn_list: {}", e); + StatusCode::INTERNAL_SERVER_ERROR + })?; + Ok(Json(objects)) +} + +pub async fn cdn_proxy( + State(state): State, + Path(key): Path, +) -> Result { + let row = sqlx::query( + "SELECT url, content_type FROM cdn_objects WHERE key = $1", + ) + .bind(&key) + .fetch_optional(&state.pool) + .await + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)? + .ok_or(StatusCode::NOT_FOUND)?; + + let url: String = row.try_get("url").map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; + let content_type: Option = row.try_get::, _>("content_type").ok().flatten(); + + let upstream = state + .http_client + .get(&url) + .send() + .await + .map_err(|e| { + tracing::error!("cdn_proxy upstream error for key={}: {}", key, e); + StatusCode::BAD_GATEWAY + })?; + + let status = + StatusCode::from_u16(upstream.status().as_u16()).unwrap_or(StatusCode::BAD_GATEWAY); + + let bytes = upstream + .bytes() + .await + .map_err(|_| StatusCode::BAD_GATEWAY)?; + + let ct = content_type.unwrap_or_else(|| "application/octet-stream".to_string()); + + Ok((status, [(header::CONTENT_TYPE, ct)], bytes)) +} + +pub async fn cdn_create( + State(state): State, + Json(body): Json, +) -> Result, StatusCode> { + let obj = sqlx::query_as::<_, CdnObject>( + "INSERT INTO cdn_objects (key, url, content_type, description) \ + VALUES ($1, $2, $3, $4) \ + RETURNING id, key, url, content_type, description, created_at", + ) + .bind(&body.key) + .bind(&body.url) + .bind(&body.content_type) + .bind(&body.description) + .fetch_one(&state.pool) + .await + .map_err(|e| { + tracing::error!("cdn_create: {}", e); + StatusCode::INTERNAL_SERVER_ERROR + })?; + Ok(Json(obj)) +} + +pub async fn cdn_update( + State(state): State, + Path(key): Path, + Json(body): Json, +) -> Result, StatusCode> { + let obj = sqlx::query_as::<_, CdnObject>( + "UPDATE cdn_objects \ + SET key = COALESCE($2, key), \ + url = COALESCE($3, url), \ + content_type = COALESCE($4, content_type), \ + description = COALESCE($5, description) \ + WHERE key = $1 \ + RETURNING id, key, url, content_type, description, created_at", + ) + .bind(&key) + .bind(&body.key) + .bind(&body.url) + .bind(&body.content_type) + .bind(&body.description) + .fetch_optional(&state.pool) + .await + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)? + .ok_or(StatusCode::NOT_FOUND)?; + Ok(Json(obj)) +} + +pub async fn cdn_delete( + State(state): State, + Path(key): Path, +) -> Result, StatusCode> { + let rows = sqlx::query("DELETE FROM cdn_objects WHERE key = $1") + .bind(&key) + .execute(&state.pool) + .await + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)? + .rows_affected(); + if rows == 0 { + return Err(StatusCode::NOT_FOUND); + } + Ok(Json(serde_json::json!({ "deleted": true }))) +} +``` + +- [ ] **Step 2: Add pub mod cdn to src/routes/mod.rs** + +```rust +pub mod admin; +pub mod auth; +pub mod cdn; +pub mod crud; + +pub fn is_valid_identifier(name: &str) -> bool { + !name.is_empty() && name.chars().all(|c| c.is_alphanumeric() || c == '_') +} +``` + +- [ ] **Step 3: Verify compilation** + +```bash +cd /home/mcpeakml/code/rust/Mercury && cargo build 2>&1 | tail -3 +``` +Expected: `Finished dev` + +--- + +### Task 6: reload_cors Hook + Protected Tables + +**Files:** +- Modify: `src/routes/crud.rs` +- Modify: `src/routes/admin/tables.rs` + +**Interfaces:** +- Consumes: `AppState.cors_cache: CorsCache` +- Produces: `reload_cors` called after every non-GET mutation to `cors_origins` table + +- [ ] **Step 1: Add reload_cors to src/routes/crud.rs** + +Add after the existing `reload_blacklist` function (around line 193): + +```rust +async fn reload_cors(state: &AppState) -> Result<(), StatusCode> { + let origins: Vec = sqlx::query_scalar::<_, String>( + "SELECT origin FROM cors_origins ORDER BY id", + ) + .fetch_all(&state.pool) + .await + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; + state.cors_cache.load(origins).await; + Ok(()) +} +``` + +- [ ] **Step 2: Add cors_origins hook in handle_crud** + +Find the block starting at line 335 (the blacklist reload hook) and update it to: + +```rust + // Reload in-memory caches after mutations to their backing tables. + if table == "blacklist" && method_str != "GET" { + reload_blacklist(&state).await?; + } + if table == "cors_origins" && method_str != "GET" { + reload_cors(&state).await?; + } +``` + +- [ ] **Step 3: Add cors_origins + cdn_objects to PROTECTED_TABLES in src/routes/admin/tables.rs** + +Find line 27: +```rust +const PROTECTED_TABLES: &[&str] = &["users", "blacklist", "api_keys", "queries", "permissions"]; +``` +Replace with: +```rust +const PROTECTED_TABLES: &[&str] = &[ + "users", "blacklist", "api_keys", "queries", "permissions", + "cors_origins", "cdn_objects", +]; +``` + +- [ ] **Step 4: Run tests** + +```bash +cd /home/mcpeakml/code/rust/Mercury && cargo test 2>&1 | tail -5 +``` +Expected: all tests pass. + +--- + +### Task 7: main.rs Wiring + +**Files:** +- Modify: `src/main.rs` + +**Interfaces:** +- Consumes: `CorsCache`, `cors_layer`, `cdn_list`, `cdn_proxy`, `cdn_create`, `cdn_update`, `cdn_delete` +- Produces: running server with dynamic CORS + CDN proxy routes + +- [ ] **Step 1: Update imports in src/main.rs** + +Replace the current imports block with: + +```rust +mod auth; +mod cache; +mod config; +mod db; +mod models; +mod routes; +mod state; + +use std::io::{self, Write}; +use std::sync::Arc; + +use axum::{ + extract::DefaultBodyLimit, + middleware, + routing::{delete, get, post, put}, + Router, +}; +use tower_http::services::{ServeDir, ServeFile}; +use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt}; + +use crate::{ + auth::middleware::{blacklist_layer, cors_layer, require_auth}, + cache::spawn_sweep_task, + config::Config, + db::create_pool, + models::blacklist::BlacklistEntry, + routes::{ + admin::admin_router, + auth::login, + cdn::{cdn_create, cdn_delete, cdn_list, cdn_proxy, cdn_update}, + crud::handle_crud, + }, + state::{AppState, BlacklistCache, CorsCache, QueryCache}, +}; +``` + +- [ ] **Step 2: Remove build_cors function** + +Delete the entire `fn build_cors(origins: &[String]) -> CorsLayer` function (lines 35–53 in the original file). + +- [ ] **Step 3: Add cors_origins seeding + cors_cache + http_client after the blacklist load block** + +Find the existing blacklist load block (around line 127) and add after `blacklist_cache.load(entries).await;`: + +```rust + // Load CORS origins; seed from CORS_ORIGINS env var if table is empty. + let cors_count: i64 = sqlx::query_scalar::<_, Option>("SELECT COUNT(*) FROM cors_origins") + .fetch_one(&pool) + .await? + .unwrap_or(0); + if cors_count == 0 && !config.cors_origins.is_empty() { + for origin in &config.cors_origins { + sqlx::query( + "INSERT INTO cors_origins (origin) VALUES ($1) ON CONFLICT DO NOTHING", + ) + .bind(origin) + .execute(&pool) + .await?; + } + tracing::info!( + "seeded {} CORS origin(s) from CORS_ORIGINS env var", + config.cors_origins.len() + ); + } + let cors_origins: Vec = + sqlx::query_scalar::<_, String>("SELECT origin FROM cors_origins ORDER BY id") + .fetch_all(&pool) + .await?; + let cors_cache = CorsCache::new(); + cors_cache.load(cors_origins).await; + + let http_client = reqwest::Client::new(); +``` + +- [ ] **Step 4: Update AppState construction** + +Find `let state = AppState { ... }` and update to: + +```rust + let state = AppState { + pool, + query_cache, + blacklist_cache, + cors_cache, + http_client, + config: config.clone(), + }; +``` + +- [ ] **Step 5: Update router construction** + +Replace the entire `let crud_routes = ...`, `let cors_layer = ...`, and `let app = ...` block with: + +```rust + let crud_routes = Router::new() + .route("/api/:table", get(handle_crud).post(handle_crud)) + .route("/api/:table/", get(handle_crud).post(handle_crud)) + .route( + "/api/:table/:id", + get(handle_crud).put(handle_crud).delete(handle_crud), + ) + .route( + "/api/:table/:id/", + get(handle_crud).put(handle_crud).delete(handle_crud), + ) + .layer(DefaultBodyLimit::max(1024 * 1024)) + .route_layer(middleware::from_fn_with_state(state.clone(), require_auth)) + .route_layer(middleware::from_fn_with_state(state.clone(), blacklist_layer)); + + // CDN routes: GET is public; POST/PUT/DELETE are blacklisted for non-super-admins. + let cdn_routes = Router::new() + .route("/api/cdn", get(cdn_list).post(cdn_create)) + .route("/api/cdn/:key", get(cdn_proxy).put(cdn_update).delete(cdn_delete)) + .route_layer(middleware::from_fn_with_state(state.clone(), blacklist_layer)); + + let app = Router::new() + .route("/auth/login", post(login)) + .merge(cdn_routes) + .merge(crud_routes) + .nest("/api/admin", admin_router(state.clone())) + .nest_service( + "/", + ServeDir::new("ui/dist").fallback(ServeFile::new("ui/dist/index.html")), + ) + .layer(middleware::from_fn_with_state(state.clone(), cors_layer)) + .with_state(state); +``` + +Note: `cdn_routes` is merged before `crud_routes` so `/api/cdn` literal paths take precedence over the `/api/:table` parameterised CRUD routes. + +- [ ] **Step 6: Run full test suite** + +```bash +cd /home/mcpeakml/code/rust/Mercury && cargo test 2>&1 | tail -5 +``` +Expected: all tests pass. + +--- + +### Task 8: Spinner CSS + +**Files:** +- Modify: `ui/src/assets/main.css` + +**Interfaces:** +- Produces: `.loading-overlay` and `.loading-spinner` classes available globally to all Vue views + +- [ ] **Step 1: Append spinner styles to ui/src/assets/main.css** + +Add at the end of the file: + +```css +/* ── Loading spinner ─────────────────────────────────────── */ +@keyframes mercury-spin { + to { transform: rotate(360deg); } +} + +.loading-spinner { + width: 1.25rem; + height: 1.25rem; + border: 2px solid var(--border); + border-top-color: var(--primary); + border-radius: 50%; + animation: mercury-spin 0.7s linear infinite; + flex-shrink: 0; +} + +.loading-overlay { + display: flex; + align-items: center; + justify-content: center; + gap: 0.6rem; + padding: 3rem 2rem; + color: var(--text-muted); + font-size: 0.85rem; + font-family: var(--font-sans); +} +``` + +--- + +### Task 9: Loading State — Existing Admin Views + +**Files:** +- Modify: `ui/src/views/admin/Blacklist.vue` +- Modify: `ui/src/views/admin/ApiKeys.vue` +- Modify: `ui/src/views/admin/Cache.vue` +- Modify: `ui/src/views/admin/Queries.vue` +- Modify: `ui/src/views/admin/Tables.vue` +- Modify: `ui/src/views/admin/Users.vue` +- Modify: `ui/src/views/admin/Permissions.vue` + +**Interfaces:** +- Consumes: `.loading-overlay` + `.loading-spinner` from `main.css` + +--- + +#### 9a — Blacklist.vue + +- [ ] **Step 1: Add loading ref to script** + +In the ` + + +``` + +--- + +### Task 11: Cdn.vue + +**Files:** +- Create: `ui/src/views/admin/Cdn.vue` + +**Interfaces:** +- Consumes: `GET /api/cdn`, `POST /api/cdn`, `PUT /api/cdn/:key`, `DELETE /api/cdn/:key` + +- [ ] **Step 1: Create ui/src/views/admin/Cdn.vue** + +```vue + + + + + +``` + +--- + +### Task 12: Router + Nav Updates + +**Files:** +- Modify: `ui/src/router/index.ts` +- Modify: `ui/src/views/admin/Layout.vue` + +**Interfaces:** +- Produces: `/admin/cors` and `/admin/cdn` routed and visible in sidebar + +- [ ] **Step 1: Add routes to ui/src/router/index.ts** + +Replace the children array: +```ts +children: [ + { path: 'queries', component: () => import('../views/admin/Queries.vue') }, + { path: 'tables', component: () => import('../views/admin/Tables.vue') }, + { path: 'users', component: () => import('../views/admin/Users.vue') }, + { path: 'permissions', component: () => import('../views/admin/Permissions.vue') }, + { path: 'blacklist', component: () => import('../views/admin/Blacklist.vue') }, + { path: 'api-keys', component: () => import('../views/admin/ApiKeys.vue') }, + { path: 'cache', component: () => import('../views/admin/Cache.vue') }, + { path: 'cors', component: () => import('../views/admin/Cors.vue') }, + { path: 'cdn', component: () => import('../views/admin/Cdn.vue') }, +], +``` + +- [ ] **Step 2: Add nav items to Layout.vue** + +Replace the `navItems` array: +```ts +const navItems = [ + { to: "/admin/queries", label: "Queries", icon: "⌗" }, + { to: "/admin/tables", label: "Tables", icon: "▦" }, + { to: "/admin/users", label: "Users", icon: "◉" }, + { to: "/admin/permissions", label: "Permissions", icon: "⬡" }, + { to: "/admin/blacklist", label: "Blacklist", icon: "⊘" }, + { to: "/admin/api-keys", label: "API Keys", icon: "⚿" }, + { to: "/admin/cache", label: "Cache", icon: "◈" }, + { to: "/admin/cors", label: "CORS", icon: "✦" }, + { to: "/admin/cdn", label: "CDN Objects", icon: "▣" }, +]; +``` + +- [ ] **Step 3: Build the frontend** + +```bash +cd /home/mcpeakml/code/rust/Mercury/ui && bun run build 2>&1 | tail -5 +``` +Expected: `dist/` rebuilt successfully with no errors. + +--- + +## Self-Review + +**Spec coverage check:** +- ✅ CORS origins stored in DB (`cors_origins` table) — Task 1 +- ✅ CORS in-memory cache (`CorsCache`) — Task 2 +- ✅ Custom async `cors_layer` middleware (replaces static `CorsLayer`) — Task 4 +- ✅ CORS reload after CRUD mutation — Task 6 +- ✅ CORS_ORIGINS env var seeds DB on first startup — Task 7 +- ✅ CDN DB table (`cdn_objects`) — Task 1 +- ✅ CDN proxy handler (`cdn_proxy`) — Task 5 +- ✅ CDN CRUD handlers — Task 5 +- ✅ CDN blacklist for mutations (POST/PUT/DELETE), GET unblocked — Task 1 + Task 7 +- ✅ `cors_origins` + `cdn_objects` in PROTECTED_TABLES (drop-safe) — Task 6 +- ✅ Spinner CSS — Task 8 +- ✅ Loading state across 7 existing views — Task 9 +- ✅ Cors.vue admin view — Task 10 +- ✅ Cdn.vue admin view — Task 11 +- ✅ Router + nav for both views — Task 12 + +**Type consistency check:** +- `CorsCache` defined in Task 2, consumed in Task 4 (middleware) and Task 6 (reload_cors) and Task 7 (AppState init) — consistent. +- `CdnObject`, `CreateCdnObject`, `UpdateCdnObject` defined in Task 3, consumed in Task 5 — consistent. +- `cdn_list`, `cdn_proxy`, `cdn_create`, `cdn_update`, `cdn_delete` defined in Task 5, imported in Task 7 — consistent. +- `cors_layer` defined in Task 4, imported in Task 7 — consistent. +- `AppState.http_client: reqwest::Client` added in Task 2, used in Task 5 (`state.http_client`) — consistent. +- Vue views use `GET /api/cdn` (not `/api/cdn_objects`) for list — matches CDN route defined in Task 7. +- Vue Cors.vue uses `GET /api/cors_origins` — matches CRUD route (blacklist allows super_admin GET via bypass_mask) — consistent. diff --git a/docs/superpowers/specs/2026-06-16-mercury-design.md b/docs/superpowers/specs/2026-06-16-mercury-design.md new file mode 100644 index 0000000..b5a1549 --- /dev/null +++ b/docs/superpowers/specs/2026-06-16-mercury-design.md @@ -0,0 +1,323 @@ +# Mercury — Design Spec +**Date:** 2026-06-16 + +## Overview + +Mercury is a monolithic, high-performance universal CRUD API written in Rust. It accepts HTTP requests, maps them to PostgreSQL tables, generates and caches SQL dynamically, and exposes an admin suite (with a Vue 3 frontend) for managing queries, users, permissions, and route security. A JWT-based bitmask permission system gates all admin operations. + +--- + +## Architecture + +``` +HTTP Request + ↓ + Blacklist Middleware (in-memory glob match) + ↓ + Auth Middleware (JWT decode + permission bit check, admin routes only) + ↓ + Axum Router + ↓ + Query Cache (DashMap) + ↓ cache miss + Query Registry (PostgreSQL: queries table) + ↓ query not yet registered + Query Builder (auto-generates SQL from route + HTTP method) + ↓ + PostgreSQL (sqlx PgPool) +``` + +**Stack:** +- `axum` — async HTTP framework (tokio-native) +- `sqlx` — async PostgreSQL driver, raw query support, compile-time checked migrations +- `DashMap` — concurrent hashmap for the query cache +- `glob` — compiled pattern matching for the route blacklist +- `jsonwebtoken` — JWT encode/decode +- Vue 3 + Vite + `@nychthemeron/library` — frontend, served as static files by Rust +- `tower-http::ServeDir` — serves `ui/dist/` at `/` + +--- + +## Endpoints + +### Public + +``` +POST /auth/login → returns JWT +``` + +### CRUD (no auth, blacklist-checked) + +``` +GET /api/{table} → SELECT * FROM {table} [?col=val filters] +GET /api/{table}/{id} → SELECT * FROM {table} WHERE id = {id} +POST /api/{table} → INSERT INTO {table} +PUT /api/{table}/{id} → UPDATE {table} WHERE id = {id} +DELETE /api/{table}/{id} → DELETE FROM {table} WHERE id = {id} +``` + +`users` and `permissions` are blacklisted by default — only accessible via the admin suite. + +### Admin — Query Registry (JWT + `ADMIN_QUERY` bit) + +``` +GET /admin/queries → list all registered queries +POST /admin/queries → register raw SQL template +GET /admin/queries/{identifier} → get query by slug identifier +PUT /admin/queries/{identifier} → update SQL template or metadata +DELETE /admin/queries/{identifier} → remove from registry + evict from cache +GET /admin/queries/{identifier}/execute → execute query with ?param=val bindings +``` + +`{identifier}` is the human-readable slug (e.g. `get-user-orders`), not the internal UUID. The UUID is used internally only. + +### Admin — Cache (JWT + `ADMIN_CACHE` bit) + +``` +GET /admin/cache/stats → current size, hit count, miss count +DELETE /admin/cache → flush entire cache +``` + +### Admin — Users (JWT + `SUPER_ADMIN` bit) + +``` +GET /admin/users → list users +POST /admin/users → create user +GET /admin/users/{id} → get user +PUT /admin/users/{id} → update user +DELETE /admin/users/{id} → delete user +POST /admin/users/{id}/permissions/grant/{bit_value} → OR bit into mask +DELETE /admin/users/{id}/permissions/revoke/{bit_value} → AND NOT bit from mask +``` + +### Admin — Permissions (JWT + `SUPER_ADMIN` bit) + +``` +GET /admin/permissions → list all permission definitions +POST /admin/permissions → create custom permission (auto-assigns next available bit_value) +PUT /admin/permissions/{id} → update name/description +DELETE /admin/permissions/{id} → remove permission definition +``` + +### Admin — Blacklist (JWT + `SUPER_ADMIN` bit) + +``` +GET /admin/blacklist → list all entries +POST /admin/blacklist → add route pattern +PUT /admin/blacklist/{id} → update entry +DELETE /admin/blacklist/{id} → remove entry +``` + +Any write to the blacklist immediately reloads the in-memory blacklist from the DB. + +### Frontend (served by Rust) + +``` +GET / → serves ui/dist/index.html (SPA entry) +GET /assets/* → static assets +``` + +--- + +## Database Schema + +### `users` +| column | type | notes | +|---|---|---| +| id | SERIAL PRIMARY KEY | | +| username | VARCHAR UNIQUE NOT NULL | | +| password_hash | TEXT NOT NULL | bcrypt | +| permissions_mask | NUMERIC NOT NULL DEFAULT 0 | u128 bitmask | +| created_at | TIMESTAMPTZ NOT NULL DEFAULT now() | | + +### `permissions` +| column | type | notes | +|---|---|---| +| id | SERIAL PRIMARY KEY | | +| name | VARCHAR UNIQUE NOT NULL | e.g. `READ` | +| bit_value | NUMERIC UNIQUE NOT NULL | power of 2, up to 2^127 | +| description | TEXT | | + +### `queries` +| column | type | notes | +|---|---|---| +| id | UUID PRIMARY KEY DEFAULT gen_random_uuid() | | +| identifier | VARCHAR UNIQUE NOT NULL | human-readable slug | +| sql_template | TEXT NOT NULL | raw SQL with :param placeholders | +| description | TEXT | | +| created_at | TIMESTAMPTZ NOT NULL DEFAULT now() | | +| updated_at | TIMESTAMPTZ NOT NULL DEFAULT now() | | + +### `blacklist` +| column | type | notes | +|---|---|---| +| id | SERIAL PRIMARY KEY | | +| pattern | VARCHAR NOT NULL | glob-style, e.g. `/api/users/**` | +| method | VARCHAR | NULL = all methods | +| reason | TEXT | | +| active | BOOLEAN NOT NULL DEFAULT true | | +| created_at | TIMESTAMPTZ NOT NULL DEFAULT now() | | + +### Seed Data (migration) +Default permission definitions: + +| name | bit_value | +|---|---| +| READ | 1 | +| WRITE | 2 | +| DELETE | 4 | +| ADMIN_QUERY | 8 | +| ADMIN_CACHE | 16 | +| SUPER_ADMIN | 32 | + +Default user: `admin` / `admin`, `permissions_mask = 63` (all bits set). + +Default blacklist entries: `/api/users/**` and `/api/permissions/**` (method: NULL). + +--- + +## Query Cache + +**Structure:** `DashMap` + +- Key: deterministic string derived from `{METHOD}:{table}:{params}` for auto-generated queries, or query `identifier` for named queries +- Value: the compiled query + timestamp of last access +- Hit/miss counters: two `AtomicU64` values on the shared state struct + +**Eviction:** a tokio background task runs every `CACHE_SWEEP_INTERVAL_SECS`. It iterates the map and removes entries where `last_accessed.elapsed() > CACHE_IDLE_TIMEOUT_SECS`. + +**Capacity:** before inserting a new entry, if `cache.len() >= CACHE_MAX_CAPACITY`, the entry with the oldest `last_accessed` is evicted first. + +**Cache invalidation:** deleting or updating a query via the admin suite immediately removes it from the DashMap. + +--- + +## Blacklist Cache + +**Structure:** `Arc>>` + +- Loaded from DB at startup +- Reloaded (write lock, full rebuild from DB) on any admin write to the `blacklist` table +- Checked in middleware on every request before routing: if any active entry matches `(method, path)`, return `403 Forbidden` + +--- + +## Permission System + +Permissions are u128 bitmasks. The JWT claims embed the user's current `permissions_mask`. Middleware extracts the JWT and performs a bitwise AND check — no DB lookup per request. + +``` +READ = 1 +WRITE = 2 +DELETE = 4 +ADMIN_QUERY = 8 +ADMIN_CACHE = 16 +SUPER_ADMIN = 32 +``` + +Custom permissions auto-assign the next unused power-of-2 bit_value. Up to 128 distinct permission bits supported. + +`permissions_mask` stored as PostgreSQL `NUMERIC` (arbitrary precision), converted to/from `u128` in the Rust data layer. + +--- + +## JWT + +- Algorithm: HS256 +- Claims: `sub` (username), `permissions` (u128 as string), `exp` +- Secret: `JWT_SECRET` env var +- Passed as `Authorization: Bearer ` header +- Token expiry: configurable via `JWT_EXPIRY_SECS` + +--- + +## Configuration (env vars) + +```env +DATABASE_URL=postgres://mercury:mercury@db:5432/mercury +JWT_SECRET=changeme +JWT_EXPIRY_SECS=3600 +CACHE_MAX_CAPACITY=10000 +CACHE_IDLE_TIMEOUT_SECS=300 +CACHE_SWEEP_INTERVAL_SECS=60 +``` + +--- + +## Project Structure + +``` +Mercury/ + src/ + main.rs -- startup: config, DB pool, cache init, router mount + config.rs -- Config struct loaded from env + auth/ + mod.rs -- JWT encode/decode, Claims struct + middleware.rs -- axum middleware: validate JWT, check permission bit + cache/ + query_cache.rs -- DashMap cache + sweep task + hit/miss counters + blacklist_cache.rs -- Arc> + glob::Pattern, reload fn + db/ + pool.rs -- sqlx PgPool init + migrations/ -- .sql files, run via sqlx::migrate!() + 001_initial.sql -- all tables + seed data + routes/ + crud.rs -- generic /api/{table} handler + query builder + auth.rs -- /auth/login + admin/ + queries.rs + cache.rs + users.rs + permissions.rs + blacklist.rs + models/ + query.rs + user.rs + permission.rs + blacklist.rs + ui/ + .npmrc -- @nychthemeron:registry=https://git.mcpeakdev.com/api/packages/McPeakDev/npm/ + package.json + vite.config.ts + src/ + main.ts -- dark mode default, router, pinia init + App.vue + router/index.ts -- route guards: redirect /login if no JWT + stores/auth.ts -- JWT storage, permissions bitmask helpers + views/ + Login.vue + admin/ + Queries.vue + Users.vue + Permissions.vue + Blacklist.vue + Cache.vue + Cargo.toml + docker-compose.yml + Dockerfile -- multi-stage: Node build UI, Rust build API + .env.example +``` + +--- + +## Docker + +**Multi-stage Dockerfile:** +1. Stage 1 (node): install `@nychthemeron/library`, run `vite build` → `ui/dist/` +2. Stage 2 (rust): compile API, copy `ui/dist/` into final image +3. Final image runs the Rust binary; `tower-http::ServeDir` serves `ui/dist/` at `/` + +**docker-compose.yml:** +- `db` service: `postgres:16-alpine`, persistent volume, health check +- `api` service: built from Dockerfile, depends on `db`, `mem_limit` set, env vars from `.env` +- Migrations run at API startup via `sqlx::migrate!()` + +--- + +## Frontend Contract + +- Dark mode is the default; set via `@nychthemeron/library` theme config in `main.ts` +- Login page at `/login` calls `POST /auth/login`, stores JWT in `localStorage` +- All admin views require `SUPER_ADMIN` bit in JWT; route guard redirects to `/login` if absent +- Permission bitmask helpers in `stores/auth.ts`: `hasPermission(bit: number): boolean` +- Admin views wire directly to their respective admin endpoints diff --git a/docs/superpowers/specs/2026-06-18-cors-dynamic-design.md b/docs/superpowers/specs/2026-06-18-cors-dynamic-design.md new file mode 100644 index 0000000..d679712 --- /dev/null +++ b/docs/superpowers/specs/2026-06-18-cors-dynamic-design.md @@ -0,0 +1,199 @@ +# Mercury — Dynamic CORS Design Spec +**Date:** 2026-06-18 + +## Overview + +Replace the static startup-time `CorsLayer` with a DB-backed, in-memory CORS cache that can be edited at runtime through the standard CRUD API, mirroring the existing route blacklist pattern. Add a Vue admin view for managing origins and add loading state indicators across all admin views. + +--- + +## Motivation + +CORS origins are currently loaded from the `CORS_ORIGINS` environment variable at server startup and baked into a static `tower_http::CorsLayer`. Changing origins requires a server restart. This feature makes CORS origins a first-class runtime configuration: stored in PostgreSQL, held in an in-memory cache, and editable by super-admins through the standard CRUD API without downtime. + +--- + +## Data Layer + +### Migration `007_cors_origins.sql` + +Create a `cors_origins` table: + +```sql +CREATE TABLE cors_origins ( + id SERIAL PRIMARY KEY, + origin TEXT NOT NULL UNIQUE, + created_at TIMESTAMPTZ NOT NULL DEFAULT now() +); +``` + +Seed blacklist entries to restrict CRUD access to super-admins only (SUPER_ADMIN bit = 32), matching the existing pattern for `blacklist`, `queries`, `users`, and `permissions`: + +```sql +INSERT INTO blacklist (pattern, method, reason, active, bypass_mask) VALUES + ('/api/cors_origins', NULL, 'admin-only table', true, '32'), + ('/api/cors_origins/**', NULL, 'admin-only table', true, '32'); +``` + +### Startup Seeding + +On server startup, if the `cors_origins` table is empty and the `CORS_ORIGINS` environment variable is set, seed the table from the env var (splitting on `,`, trimming whitespace). This provides a smooth migration path from the env-var approach. Once the DB has entries, `CORS_ORIGINS` is ignored. + +--- + +## In-Memory Cache + +### `CorsCache` in `state.rs` + +```rust +pub struct CorsCache { + pub inner: Arc>, +} + +pub struct CorsState { + pub wildcard: bool, + pub origins: Vec, +} +``` + +`CorsCache::load(origins: Vec)`: +- Sets `wildcard = true` if any origin is `"*"` +- Parses each string into a `HeaderValue`, skipping malformed entries +- Acquires a write lock and replaces the inner state + +`AppState` gains a `cors_cache: CorsCache` field alongside `blacklist_cache`. + +--- + +## Middleware + +### `cors_layer` in `auth/middleware.rs` + +An async Axum middleware (`from_fn_with_state`) that runs on every request. Behavior: + +| Cache state | Request type | Action | +|---|---|---| +| Empty (no origins, no wildcard) | Any | Pass through — no CORS headers added | +| Wildcard (`*`) | Non-OPTIONS | Add `Access-Control-Allow-Origin: *` to response | +| Wildcard (`*`) | OPTIONS preflight | Return `204` with `Access-Control-Allow-Origin: *`, `Access-Control-Allow-Methods`, `Access-Control-Allow-Headers` | +| Specific origins | Non-OPTIONS, Origin matches | Echo origin back as `Access-Control-Allow-Origin`, add `Vary: Origin` | +| Specific origins | Non-OPTIONS, Origin no match | Pass through — no CORS headers | +| Specific origins | OPTIONS preflight, Origin matches | Return `204` with echoed origin, `Vary: Origin`, `Access-Control-Allow-Methods`, `Access-Control-Allow-Headers` | +| Specific origins | OPTIONS preflight, Origin no match | Return `204` with no CORS headers | + +Allowed methods: `GET, POST, PUT, DELETE, OPTIONS`. +Allowed headers: `Content-Type, Authorization`. + +The middleware is applied globally via `.layer(middleware::from_fn_with_state(state.clone(), cors_layer))` in `main.rs`, replacing the removed `build_cors()` call and static `CorsLayer`. + +### `reload_cors` in `routes/crud.rs` + +Called after any non-GET mutation to the `cors_origins` table, exactly mirroring `reload_blacklist`: + +```rust +async fn reload_cors(state: &AppState) -> Result<(), StatusCode> { + // SELECT origin FROM cors_origins ORDER BY id + // state.cors_cache.load(origins).await +} +``` + +The existing `handle_crud` hook block gains a `cors_origins` branch alongside the `blacklist` branch. + +--- + +## Admin Interface + +### `Cors.vue` + +New Vue view at `ui/src/views/admin/Cors.vue`: + +- **Header:** "CORS Origins" with subtitle "Allowed cross-origin request sources — matched against the request Origin header" +- **Table card:** lists all origins with `id`, `origin` (monospace), `created_at`, and a `Delete` button per row +- **Create dialog:** single `Origin` text input with placeholder `https://app.example.com` or `*`, and an `Add Origin` submit button +- **Empty state:** icon + "No origins configured — cross-origin requests will be rejected" label + hint +- **API calls:** `GET /api/cors_origins` (list), `POST /api/cors_origins` (create), `DELETE /api/cors_origins/:id` (remove) + +### Router & Navigation + +- Route added to `ui/src/router/index.ts`: `{ path: 'cors', component: () => import('../views/admin/Cors.vue') }` +- Nav item added to `Layout.vue` `navItems`: `{ to: '/admin/cors', label: 'CORS', icon: '✦' }` + +--- + +## Loading State (All Admin Views) + +A consistent loading indicator is added to every admin view (`Queries.vue`, `Tables.vue`, `Users.vue`, `Permissions.vue`, `Blacklist.vue`, `ApiKeys.vue`, `Cache.vue`, and the new `Cors.vue`). + +### Pattern + +Each view gains a `loading` ref: + +```ts +const loading = ref(false) + +async function load() { + loading.value = true + try { + // existing fetch logic + } finally { + loading.value = false + } +} +``` + +Mutating operations (`submitCreate`, `submitEdit`, `deleteEntry`, etc.) also set `loading = true` for their duration. + +### Shared CSS Spinner + +A `.spinner` keyframe animation added once to `main.css`: + +```css +@keyframes spin { to { transform: rotate(360deg); } } + +.loading-spinner { + width: 1.25rem; + height: 1.25rem; + border: 2px solid var(--border); + border-top-color: var(--primary); + border-radius: 50%; + animation: spin 0.7s linear infinite; +} + +.loading-overlay { + display: flex; + align-items: center; + justify-content: center; + gap: 0.6rem; + padding: 3rem 2rem; + color: var(--text-muted); + font-size: 0.85rem; + font-family: var(--font-sans); +} +``` + +Each view shows a `
Loading…
` in place of the table/content when `loading` is true. + +--- + +## Files Changed + +| File | Change | +|---|---| +| `src/db/migrations/007_cors_origins.sql` | New migration | +| `src/state.rs` | Add `CorsCache`, `CorsState`; add `cors_cache` to `AppState` | +| `src/auth/middleware.rs` | Add `cors_layer` middleware | +| `src/routes/crud.rs` | Add `reload_cors`, hook into `handle_crud` | +| `src/main.rs` | Remove `build_cors`, remove static `CorsLayer`, seed `cors_origins` from env on startup, apply `cors_layer` | +| `ui/src/views/admin/Cors.vue` | New view | +| `ui/src/router/index.ts` | Add `/admin/cors` route | +| `ui/src/views/admin/Layout.vue` | Add CORS nav item | +| `ui/src/assets/main.css` | Add spinner CSS | +| `ui/src/views/admin/*.vue` (all 7 existing) | Add `loading` ref and spinner display | + +--- + +## Out of Scope + +- Credentials support (`Access-Control-Allow-Credentials`) — not currently used +- Per-origin method/header overrides — uniform allow-list for all origins +- Max-age preflight caching header — can be added later diff --git a/entrypoint.sh b/entrypoint.sh new file mode 100644 index 0000000..939bdd7 --- /dev/null +++ b/entrypoint.sh @@ -0,0 +1,37 @@ +#!/bin/sh +set -e + +PGDATA="${PGDATA:-/var/lib/postgresql/data}" +PGLOG="/var/log/postgresql/postgresql.log" +MINIO_DATA="${MINIO_VOLUMES:-/var/lib/minio/data}" +CDN_BUCKET="${CDN_BUCKET:-mercury}" + +mkdir -p "$PGDATA" /var/log/postgresql "$MINIO_DATA" +chown postgres:postgres "$PGDATA" /var/log/postgresql + +# Start MinIO in background +minio server "$MINIO_DATA" --console-address ":9001" > /var/log/minio.log 2>&1 & + +# Wait for MinIO to accept connections +echo "Waiting for MinIO..." +until mc alias set local http://localhost:9000 "$MINIO_ROOT_USER" "$MINIO_ROOT_PASSWORD" > /dev/null 2>&1; do + sleep 1 +done + +# Create default bucket with anonymous read+write (MinIO is internal; no ports exposed) +mc mb --ignore-existing "local/${CDN_BUCKET}" > /dev/null 2>&1 +mc anonymous set public "local/${CDN_BUCKET}" > /dev/null 2>&1 +echo "MinIO ready — bucket: ${CDN_BUCKET} (http://localhost:9000/${CDN_BUCKET})" + +# Initialise PostgreSQL on first start +if [ ! -f "$PGDATA/PG_VERSION" ]; then + su -s /bin/sh postgres -c "initdb -D $PGDATA" + su -s /bin/sh postgres -c "pg_ctl start -D $PGDATA -w -l $PGLOG" + su -s /bin/sh postgres -c "psql postgres -c \"CREATE USER mercury WITH PASSWORD 'mercury';\"" + su -s /bin/sh postgres -c "psql postgres -c \"CREATE DATABASE mercury OWNER mercury;\"" + su -s /bin/sh postgres -c "pg_ctl stop -D $PGDATA -w" +fi + +su -s /bin/sh postgres -c "pg_ctl start -D $PGDATA -w -l $PGLOG" + +exec /app/mercury diff --git a/pics/Mercury-Login.png b/pics/Mercury-Login.png new file mode 100644 index 0000000..7cbda99 Binary files /dev/null and b/pics/Mercury-Login.png differ diff --git a/pics/Mercury.png b/pics/Mercury.png new file mode 100644 index 0000000..4d04cf8 Binary files /dev/null and b/pics/Mercury.png differ diff --git a/src/auth/middleware.rs b/src/auth/middleware.rs new file mode 100644 index 0000000..36154cf --- /dev/null +++ b/src/auth/middleware.rs @@ -0,0 +1,181 @@ +use axum::{ + extract::{Request, State}, + http::{header, HeaderMap, HeaderValue, Method, StatusCode}, + middleware::Next, + response::{IntoResponse, Response}, +}; + +use crate::{ + auth::{decode_jwt, resolve_api_key, Claims}, + state::AppState, +}; + +/// Resolves a Bearer token to Claims, trying JWT then API key. +/// Inserts Claims into request extensions on success so downstream +/// middleware can reuse them without an additional DB round-trip. +async fn authenticate(token: &str, state: &AppState, req: &mut Request) -> Option { + if let Some(existing) = req.extensions().get::().cloned() { + return Some(existing); + } + let claims = if let Ok(c) = decode_jwt(token, &state.config.jwt_secret) { + c + } else { + resolve_api_key(token, &state.pool).await? + }; + req.extensions_mut().insert(claims.clone()); + Some(claims) +} + +pub async fn blacklist_layer( + State(state): State, + mut req: Request, + next: Next, +) -> Result { + let method = req.method().as_str().to_uppercase(); + let path = req.uri().path().to_string(); + let caller_mask = if let Some(token) = extract_bearer(&req) { + authenticate(&token, &state, &mut req) + .await + .map(|c| c.permissions_mask()) + .unwrap_or(0) + } else { + 0 + }; + if state + .blacklist_cache + .is_blocked(&method, &path, caller_mask) + .await + { + return Err(StatusCode::FORBIDDEN); + } + Ok(next.run(req).await) +} + +pub fn extract_bearer(req: &Request) -> Option { + req.headers() + .get("authorization") + .and_then(|v| v.to_str().ok()) + .and_then(|v| v.strip_prefix("Bearer ")) + .map(|s| s.to_string()) +} + +pub async fn require_auth( + State(state): State, + mut req: Request, + next: Next, +) -> Result { + let token = extract_bearer(&req).ok_or(StatusCode::UNAUTHORIZED)?; + authenticate(&token, &state, &mut req) + .await + .ok_or(StatusCode::UNAUTHORIZED)?; + Ok(next.run(req).await) +} + +pub async fn require_super_admin( + State(state): State, + mut req: Request, + next: Next, +) -> Result { + let token = extract_bearer(&req).ok_or(StatusCode::UNAUTHORIZED)?; + let claims = authenticate(&token, &state, &mut req) + .await + .ok_or(StatusCode::UNAUTHORIZED)?; + if !claims.has_permission(crate::auth::permissions::SUPER_ADMIN) { + return Err(StatusCode::FORBIDDEN); + } + Ok(next.run(req).await) +} + +pub async fn require_admin_query( + State(state): State, + mut req: Request, + next: Next, +) -> Result { + let token = extract_bearer(&req).ok_or(StatusCode::UNAUTHORIZED)?; + let claims = authenticate(&token, &state, &mut req) + .await + .ok_or(StatusCode::UNAUTHORIZED)?; + if !claims.has_permission(crate::auth::permissions::ADMIN_QUERY) { + return Err(StatusCode::FORBIDDEN); + } + Ok(next.run(req).await) +} + +pub async fn require_admin_cache( + State(state): State, + mut req: Request, + next: Next, +) -> Result { + let token = extract_bearer(&req).ok_or(StatusCode::UNAUTHORIZED)?; + let claims = authenticate(&token, &state, &mut req) + .await + .ok_or(StatusCode::UNAUTHORIZED)?; + if !claims.has_permission(crate::auth::permissions::ADMIN_CACHE) { + return Err(StatusCode::FORBIDDEN); + } + Ok(next.run(req).await) +} + +pub async fn cors_layer(State(state): State, req: Request, next: Next) -> Response { + let is_preflight = req.method() == Method::OPTIONS; + let origin_header = req.headers().get(header::ORIGIN).cloned(); + + enum CorsDecision { + None, + Wildcard, + Specific(HeaderValue), + } + + let decision = { + let guard = state.cors_cache.inner.read().await; + if guard.wildcard { + CorsDecision::Wildcard + } else if let Some(origin) = origin_header.as_ref() { + if guard.origins.contains(origin) { + CorsDecision::Specific(origin.clone()) + } else { + CorsDecision::None + } + } else { + CorsDecision::None + } + }; + + let (cors_origin, vary) = match &decision { + CorsDecision::None => (None, false), + CorsDecision::Wildcard => (Some(HeaderValue::from_static("*")), false), + CorsDecision::Specific(v) => (Some(v.clone()), true), + }; + + if is_preflight { + let mut headers = HeaderMap::new(); + if let Some(origin) = cors_origin { + headers.insert(header::ACCESS_CONTROL_ALLOW_ORIGIN, origin); + headers.insert( + header::ACCESS_CONTROL_ALLOW_METHODS, + HeaderValue::from_static("GET, POST, PUT, DELETE, OPTIONS"), + ); + headers.insert( + header::ACCESS_CONTROL_ALLOW_HEADERS, + HeaderValue::from_static("content-type, authorization"), + ); + if vary { + headers.insert(header::VARY, HeaderValue::from_static("Origin")); + } + } + return (StatusCode::NO_CONTENT, headers).into_response(); + } + + let mut response = next.run(req).await; + if let Some(origin) = cors_origin { + response + .headers_mut() + .insert(header::ACCESS_CONTROL_ALLOW_ORIGIN, origin); + if vary { + response + .headers_mut() + .append(header::VARY, HeaderValue::from_static("Origin")); + } + } + response +} diff --git a/src/auth/mod.rs b/src/auth/mod.rs new file mode 100644 index 0000000..fb6a7df --- /dev/null +++ b/src/auth/mod.rs @@ -0,0 +1,123 @@ +pub mod middleware; + +use anyhow::Result; +use chrono::Utc; +use jsonwebtoken::{decode, encode, DecodingKey, EncodingKey, Header, Validation}; +use serde::{Deserialize, Serialize}; +use sha2::{Digest, Sha256}; +use uuid::Uuid; + +#[allow(dead_code)] +pub mod permissions { + pub const READ: u128 = 1; + pub const WRITE: u128 = 2; + pub const DELETE: u128 = 4; + pub const ADMIN_QUERY: u128 = 8; + pub const ADMIN_CACHE: u128 = 16; + pub const SUPER_ADMIN: u128 = 32; +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct Claims { + pub sub: String, + pub permissions: String, // u128 stored as decimal string + pub exp: usize, +} + +impl Claims { + pub fn permissions_mask(&self) -> u128 { + self.permissions.parse().unwrap_or(0) + } + + pub fn has_permission(&self, bit: u128) -> bool { + self.permissions_mask() & bit != 0 + } +} + +pub fn encode_jwt(username: &str, mask: u128, secret: &str, expiry_secs: u64) -> Result { + let exp = (Utc::now().timestamp() as u64 + expiry_secs) as usize; + let claims = Claims { + sub: username.to_string(), + permissions: mask.to_string(), + exp, + }; + let token = encode( + &Header::default(), + &claims, + &EncodingKey::from_secret(secret.as_bytes()), + )?; + Ok(token) +} + +/// Generates a new API key: `mrc_<32 random hex chars>`. +/// Returns `(plain_key, key_prefix, key_hash)`. +pub fn generate_api_key() -> (String, String, String) { + let raw = format!("{}{}", Uuid::new_v4().simple(), Uuid::new_v4().simple()); + let key = format!("mrc_{}", raw); + let prefix = raw[..8].to_string(); + let hash = hash_api_key(&key); + (key, prefix, hash) +} + +pub fn hash_api_key(key: &str) -> String { + format!("{:x}", Sha256::digest(key.as_bytes())) +} + +/// Resolves an API key token against the database. +/// Updates `last_used_at` on success. +pub async fn resolve_api_key(token: &str, pool: &sqlx::PgPool) -> Option { + if !token.starts_with("mrc_") { + return None; + } + let hash = hash_api_key(token); + let row: (String, String) = sqlx::query_as( + "UPDATE api_keys SET last_used_at = now() + WHERE key_hash = $1 AND (expires_at IS NULL OR expires_at > now()) + RETURNING name, permissions_mask", + ) + .bind(&hash) + .fetch_optional(pool) + .await + .ok()??; + + Some(Claims { + sub: row.0, + permissions: row.1, + exp: usize::MAX, + }) +} + +pub fn decode_jwt(token: &str, secret: &str) -> Result { + let data = decode::( + token, + &DecodingKey::from_secret(secret.as_bytes()), + &Validation::default(), + )?; + Ok(data.claims) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_encode_decode_roundtrip() { + let secret = "test_secret"; + let token = encode_jwt("alice", 63u128, secret, 3600).unwrap(); + let claims = decode_jwt(&token, secret).unwrap(); + assert_eq!(claims.sub, "alice"); + assert_eq!(claims.permissions_mask(), 63u128); + } + + #[test] + fn test_has_permission() { + let claims = Claims { + sub: "bob".into(), + permissions: "9".into(), // READ (1) + ADMIN_QUERY (8) + exp: 9999999999, + }; + assert!(claims.has_permission(permissions::READ)); + assert!(claims.has_permission(permissions::ADMIN_QUERY)); + assert!(!claims.has_permission(permissions::SUPER_ADMIN)); + } +} diff --git a/src/cache/mod.rs b/src/cache/mod.rs new file mode 100644 index 0000000..a1ca063 --- /dev/null +++ b/src/cache/mod.rs @@ -0,0 +1,2 @@ +pub mod sweep; +pub use sweep::spawn_sweep_task; diff --git a/src/cache/sweep.rs b/src/cache/sweep.rs new file mode 100644 index 0000000..bee1933 --- /dev/null +++ b/src/cache/sweep.rs @@ -0,0 +1,15 @@ +use crate::state::QueryCache; +use std::time::Duration; + +pub fn spawn_sweep_task(cache: QueryCache, idle_timeout_secs: u64, sweep_interval_secs: u64) { + tokio::spawn(async move { + let interval = Duration::from_secs(sweep_interval_secs); + loop { + tokio::time::sleep(interval).await; + let now = crate::state::unix_now(); + cache + .map + .retain(|_, entry| now.saturating_sub(entry.last_accessed()) < idle_timeout_secs); + } + }); +} diff --git a/src/config.rs b/src/config.rs new file mode 100644 index 0000000..aee1b76 --- /dev/null +++ b/src/config.rs @@ -0,0 +1,64 @@ +use anyhow::Result; + +#[derive(Clone, Debug)] +pub struct Config { + pub database_url: String, + pub jwt_secret: String, + pub jwt_expiry_secs: u64, + pub cache_max_capacity: usize, + pub cache_idle_timeout_secs: u64, + pub cache_sweep_interval_secs: u64, + /// Comma-separated allowed CORS origins, or "*" for permissive. Empty = no CORS headers. + pub cors_origins: Vec, + /// Base URL of the MinIO/S3 endpoint (no trailing slash). + pub cdn_endpoint: String, + /// Bucket name used for CDN object storage. + pub cdn_bucket: String, +} + +impl Config { + pub fn from_env() -> Result { + Ok(Self { + database_url: std::env::var("DATABASE_URL")?, + jwt_secret: std::env::var("JWT_SECRET")?, + jwt_expiry_secs: std::env::var("JWT_EXPIRY_SECS") + .unwrap_or_else(|_| "3600".into()) + .parse()?, + cache_max_capacity: std::env::var("CACHE_MAX_CAPACITY") + .unwrap_or_else(|_| "10000".into()) + .parse()?, + cache_idle_timeout_secs: std::env::var("CACHE_IDLE_TIMEOUT_SECS") + .unwrap_or_else(|_| "300".into()) + .parse()?, + cache_sweep_interval_secs: std::env::var("CACHE_SWEEP_INTERVAL_SECS") + .unwrap_or_else(|_| "60".into()) + .parse()?, + cors_origins: std::env::var("CORS_ORIGINS") + .unwrap_or_default() + .split(',') + .map(|s| s.trim().to_string()) + .filter(|s| !s.is_empty()) + .collect(), + cdn_endpoint: std::env::var("CDN_ENDPOINT") + .unwrap_or_else(|_| "http://localhost:9000".into()), + cdn_bucket: std::env::var("CDN_BUCKET").unwrap_or_else(|_| "mercury".into()), + }) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_config_defaults() { + std::env::set_var("DATABASE_URL", "postgres://test"); + std::env::set_var("JWT_SECRET", "secret"); + let cfg = Config::from_env().unwrap(); + assert_eq!(cfg.jwt_expiry_secs, 3600); + assert_eq!(cfg.cache_max_capacity, 10_000); + assert_eq!(cfg.cache_idle_timeout_secs, 300); + assert_eq!(cfg.cache_sweep_interval_secs, 60); + assert!(cfg.cors_origins.is_empty()); + } +} diff --git a/src/db/migrations/001_initial.sql b/src/db/migrations/001_initial.sql new file mode 100644 index 0000000..e2b3711 --- /dev/null +++ b/src/db/migrations/001_initial.sql @@ -0,0 +1,48 @@ +CREATE EXTENSION IF NOT EXISTS pgcrypto; + +CREATE TABLE users ( + id SERIAL PRIMARY KEY, + username VARCHAR(255) UNIQUE NOT NULL, + password_hash TEXT NOT NULL, + permissions_mask TEXT NOT NULL DEFAULT '0', + created_at TIMESTAMPTZ NOT NULL DEFAULT now() +); + +CREATE TABLE permissions ( + id SERIAL PRIMARY KEY, + name VARCHAR(255) UNIQUE NOT NULL, + bit_value TEXT UNIQUE NOT NULL, + description TEXT +); + +CREATE TABLE queries ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + identifier VARCHAR(255) UNIQUE NOT NULL, + sql_template TEXT NOT NULL, + description TEXT, + created_at TIMESTAMPTZ NOT NULL DEFAULT now(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT now() +); + +CREATE TABLE blacklist ( + id SERIAL PRIMARY KEY, + pattern VARCHAR(500) NOT NULL, + method VARCHAR(10), + reason TEXT, + active BOOLEAN NOT NULL DEFAULT true, + created_at TIMESTAMPTZ NOT NULL DEFAULT now() +); + +-- Seed permissions +INSERT INTO permissions (name, bit_value, description) VALUES + ('READ', '1', 'Can read via CRUD endpoints'), + ('WRITE', '2', 'Can insert/update via CRUD'), + ('DELETE', '4', 'Can delete via CRUD'), + ('ADMIN_QUERY', '8', 'Can manage query registry'), + ('ADMIN_CACHE', '16', 'Can manage cache'), + ('SUPER_ADMIN', '32', 'Full access'); + +-- Seed blacklist (users and permissions tables are admin-only) +INSERT INTO blacklist (pattern, method, reason, active) VALUES + ('/api/users/**', NULL, 'admin-only table', true), + ('/api/permissions/**', NULL, 'admin-only table', true); diff --git a/src/db/migrations/002_blacklist_system_tables.sql b/src/db/migrations/002_blacklist_system_tables.sql new file mode 100644 index 0000000..8823f83 --- /dev/null +++ b/src/db/migrations/002_blacklist_system_tables.sql @@ -0,0 +1,9 @@ +-- Block PostgreSQL system catalog tables from the public CRUD API. +-- The pg_ prefix covers pg_tables, pg_class, pg_user, pg_shadow, pg_authid, etc. +-- information_schema columns contain dots so they're already rejected by the +-- identifier validator, but we block them here for defense in depth. +INSERT INTO blacklist (pattern, method, reason, active) VALUES + ('/api/pg_*', NULL, 'postgresql system catalog', true), + ('/api/pg_*/**', NULL, 'postgresql system catalog', true), + ('/api/information_schema', NULL, 'postgresql information schema', true), + ('/api/information_schema/**', NULL, 'postgresql information schema', true); diff --git a/src/db/migrations/003_blacklist_bypass_permission.sql b/src/db/migrations/003_blacklist_bypass_permission.sql new file mode 100644 index 0000000..2efe878 --- /dev/null +++ b/src/db/migrations/003_blacklist_bypass_permission.sql @@ -0,0 +1,32 @@ +-- Allow blacklist entries to be bypassed by callers who hold a specific permission bit. +-- bypass_mask NULL means the rule blocks everyone unconditionally. +ALTER TABLE blacklist ADD COLUMN bypass_mask TEXT; + +-- Existing user/permission rules: SUPER_ADMIN (bit 32) can bypass them so the +-- admin UI can reach these tables via the generic /api/:table CRUD endpoint. +UPDATE blacklist +SET bypass_mask = '32' +WHERE pattern IN ('/api/users/**', '/api/permissions/**'); + +-- Add rules for queries and blacklist tables, which also need admin-only CRUD access. +INSERT INTO blacklist (pattern, method, reason, active, bypass_mask) VALUES + ('/api/users', NULL, 'admin-only table', true, '32'), + ('/api/permissions', NULL, 'admin-only table', true, '32'), + ('/api/queries', NULL, 'admin-only table', true, '32'), + ('/api/queries/**', NULL, 'admin-only table', true, '32'), + ('/api/blacklist', NULL, 'admin-only table', true, '32'), + ('/api/blacklist/**', NULL, 'admin-only table', true, '32'); + +-- Automatically update updated_at on queries mutations so the generic CRUD +-- endpoint doesn't need to know about that column. +CREATE OR REPLACE FUNCTION update_updated_at() +RETURNS TRIGGER AS $$ +BEGIN + NEW.updated_at = NOW(); + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER queries_updated_at + BEFORE UPDATE ON queries + FOR EACH ROW EXECUTE FUNCTION update_updated_at(); diff --git a/src/db/migrations/004_blacklist_method_text.sql b/src/db/migrations/004_blacklist_method_text.sql new file mode 100644 index 0000000..b9582b5 --- /dev/null +++ b/src/db/migrations/004_blacklist_method_text.sql @@ -0,0 +1,2 @@ +-- Widen method column to support comma-separated multi-method values e.g. "GET,POST" +ALTER TABLE blacklist ALTER COLUMN method TYPE TEXT; diff --git a/src/db/migrations/005_api_keys.sql b/src/db/migrations/005_api_keys.sql new file mode 100644 index 0000000..75ef167 --- /dev/null +++ b/src/db/migrations/005_api_keys.sql @@ -0,0 +1,12 @@ +CREATE TABLE api_keys ( + id SERIAL PRIMARY KEY, + name VARCHAR(255) NOT NULL, + key_prefix VARCHAR(16) NOT NULL, + key_hash TEXT NOT NULL UNIQUE, + permissions_mask TEXT NOT NULL DEFAULT '0', + created_at TIMESTAMPTZ NOT NULL DEFAULT now(), + expires_at TIMESTAMPTZ, + last_used_at TIMESTAMPTZ +); + +CREATE INDEX idx_api_keys_hash ON api_keys(key_hash); diff --git a/src/db/migrations/006_seed_api_keys_blacklist.sql b/src/db/migrations/006_seed_api_keys_blacklist.sql new file mode 100644 index 0000000..1ddf16c --- /dev/null +++ b/src/db/migrations/006_seed_api_keys_blacklist.sql @@ -0,0 +1,5 @@ +-- Prevent raw CRUD access to the api_keys table (would expose key_hash). +-- The proper endpoints live at /api/admin/api-keys and are guarded by require_super_admin. +INSERT INTO blacklist (pattern, method, reason, active) VALUES + ('/api/api_keys', NULL, 'api key hashes must not be exposed via generic CRUD', true), + ('/api/api_keys/**', NULL, 'api key hashes must not be exposed via generic CRUD', true); diff --git a/src/db/migrations/007_cors_origins.sql b/src/db/migrations/007_cors_origins.sql new file mode 100644 index 0000000..cc4150e --- /dev/null +++ b/src/db/migrations/007_cors_origins.sql @@ -0,0 +1,10 @@ +CREATE TABLE cors_origins ( + id SERIAL PRIMARY KEY, + origin TEXT NOT NULL UNIQUE, + created_at TIMESTAMPTZ NOT NULL DEFAULT now() +); + +-- Restrict mutations to super-admins (bit 32); GET remains open for all admins. +INSERT INTO blacklist (pattern, method, reason, active, bypass_mask) VALUES + ('/api/cors_origins', 'POST,PUT,PATCH,DELETE', 'admin-only table', true, '32'), + ('/api/cors_origins/**', 'POST,PUT,PATCH,DELETE', 'admin-only table', true, '32'); diff --git a/src/db/migrations/008_cdn_objects.sql b/src/db/migrations/008_cdn_objects.sql new file mode 100644 index 0000000..208dcef --- /dev/null +++ b/src/db/migrations/008_cdn_objects.sql @@ -0,0 +1,13 @@ +CREATE TABLE cdn_objects ( + id SERIAL PRIMARY KEY, + key TEXT NOT NULL UNIQUE, + url TEXT NOT NULL, + content_type TEXT, + description TEXT, + created_at TIMESTAMPTZ NOT NULL DEFAULT now() +); + +-- Block mutations to /api/cdn for non-super-admins. GET is unblocked (no entry). +INSERT INTO blacklist (pattern, method, reason, active, bypass_mask) VALUES + ('/api/cdn', 'POST,PUT,PATCH,DELETE', 'CDN write operations are super-admin only', true, '32'), + ('/api/cdn/**', 'POST,PUT,PATCH,DELETE', 'CDN write operations are super-admin only', true, '32'); diff --git a/src/db/migrations/009_cdn_drop_url.sql b/src/db/migrations/009_cdn_drop_url.sql new file mode 100644 index 0000000..b7bb87d --- /dev/null +++ b/src/db/migrations/009_cdn_drop_url.sql @@ -0,0 +1,2 @@ +-- Remove url column: the proxy constructs the URL from cdn_endpoint + cdn_bucket + key. +ALTER TABLE cdn_objects DROP COLUMN IF EXISTS url; diff --git a/src/db/mod.rs b/src/db/mod.rs new file mode 100644 index 0000000..620c68e --- /dev/null +++ b/src/db/mod.rs @@ -0,0 +1,2 @@ +pub mod pool; +pub use pool::create_pool; diff --git a/src/db/pool.rs b/src/db/pool.rs new file mode 100644 index 0000000..d2c4790 --- /dev/null +++ b/src/db/pool.rs @@ -0,0 +1,11 @@ +use anyhow::Result; +use sqlx::{postgres::PgPoolOptions, PgPool}; + +pub async fn create_pool(database_url: &str) -> Result { + let pool = PgPoolOptions::new() + .max_connections(10) + .connect(database_url) + .await?; + sqlx::migrate!("src/db/migrations").run(&pool).await?; + Ok(pool) +} diff --git a/src/main.rs b/src/main.rs new file mode 100644 index 0000000..9166837 --- /dev/null +++ b/src/main.rs @@ -0,0 +1,207 @@ +mod auth; +mod cache; +mod config; +mod db; +mod models; +mod routes; +mod state; + +use std::io::{self, Write}; +use std::sync::Arc; + +use axum::{ + extract::DefaultBodyLimit, + middleware, + routing::{get, post}, + Router, +}; +use tower_http::services::{ServeDir, ServeFile}; +use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt}; + +use crate::{ + auth::middleware::{blacklist_layer, cors_layer, require_auth}, + cache::spawn_sweep_task, + config::Config, + db::create_pool, + models::blacklist::BlacklistEntry, + routes::{ + admin::admin_router, + auth::login, + cdn::{cdn_create, cdn_delete, cdn_list, cdn_proxy, cdn_update, cdn_upload}, + crud::handle_crud, + }, + state::{AppState, BlacklistCache, CorsCache, QueryCache}, +}; + +#[tokio::main] +async fn main() -> anyhow::Result<()> { + dotenvy::dotenv().ok(); + + tracing_subscriber::registry() + .with( + tracing_subscriber::EnvFilter::try_from_default_env() + .unwrap_or_else(|_| "mercury=info".into()), + ) + .with(tracing_subscriber::fmt::layer()) + .init(); + + let config = Arc::new(Config::from_env()?); + let pool = create_pool(&config.database_url).await?; + + // If no users exist, prompt to create the first admin interactively. + let user_count: i64 = sqlx::query_scalar::<_, Option>("SELECT COUNT(*) FROM users") + .fetch_one(&pool) + .await? + .unwrap_or(0); + if user_count == 0 { + let (username, password) = match ( + std::env::var("MERCURY_ADMIN_USER") + .ok() + .filter(|s| !s.is_empty()), + std::env::var("MERCURY_ADMIN_PASSWORD") + .ok() + .filter(|s| !s.is_empty()), + ) { + (Some(u), Some(p)) => { + tracing::info!("creating first admin user from environment variables"); + (u, p) + } + _ => { + println!("\nNo users found. Create the first admin account."); + print!("Username: "); + io::stdout().flush()?; + let mut username = String::new(); + io::stdin().read_line(&mut username)?; + let username = username.trim().to_string(); + if username.is_empty() { + anyhow::bail!("username cannot be empty"); + } + + print!("Password: "); + io::stdout().flush()?; + let mut password = String::new(); + io::stdin().read_line(&mut password)?; + let password = password.trim().to_string(); + if password.is_empty() { + anyhow::bail!("password cannot be empty"); + } + (username, password) + } + }; + + let hash = bcrypt::hash(&password, bcrypt::DEFAULT_COST)?; + sqlx::query( + "INSERT INTO users (username, password_hash, permissions_mask) VALUES ($1, $2, '63')", + ) + .bind(&username) + .bind(hash) + .execute(&pool) + .await?; + tracing::info!("created first admin user: {}", username); + println!("Admin user '{}' created. Starting server...\n", username); + } + + let query_cache = QueryCache::new(); + let blacklist_cache = BlacklistCache::new(); + + // Load blacklist from DB into memory + let entries = sqlx::query_as::<_, BlacklistEntry>( + "SELECT id, pattern, method, reason, active, bypass_mask, created_at FROM blacklist ORDER BY id" + ) + .fetch_all(&pool) + .await?; + blacklist_cache.load(entries).await; + + // Load CORS origins; seed from CORS_ORIGINS env var if table is empty. + let cors_count: i64 = sqlx::query_scalar::<_, Option>("SELECT COUNT(*) FROM cors_origins") + .fetch_one(&pool) + .await? + .unwrap_or(0); + if cors_count == 0 && !config.cors_origins.is_empty() { + for origin in &config.cors_origins { + sqlx::query("INSERT INTO cors_origins (origin) VALUES ($1) ON CONFLICT DO NOTHING") + .bind(origin) + .execute(&pool) + .await?; + } + tracing::info!( + "seeded {} CORS origin(s) from CORS_ORIGINS env var", + config.cors_origins.len() + ); + } + let cors_origins: Vec = + sqlx::query_scalar::<_, String>("SELECT origin FROM cors_origins ORDER BY id") + .fetch_all(&pool) + .await?; + let cors_cache = CorsCache::new(); + cors_cache.load(cors_origins).await; + + let http_client = reqwest::Client::new(); + let cdn_base_url = format!("{}/{}", config.cdn_endpoint, config.cdn_bucket); + + // Start cache sweep + spawn_sweep_task( + query_cache.clone(), + config.cache_idle_timeout_secs, + config.cache_sweep_interval_secs, + ); + + let state = AppState { + pool, + query_cache, + blacklist_cache, + cors_cache, + http_client, + cdn_base_url, + config: config.clone(), + }; + + let crud_routes = Router::new() + .route("/api/:table", get(handle_crud).post(handle_crud)) + .route("/api/:table/", get(handle_crud).post(handle_crud)) + .route( + "/api/:table/:id", + get(handle_crud).put(handle_crud).delete(handle_crud), + ) + .route( + "/api/:table/:id/", + get(handle_crud).put(handle_crud).delete(handle_crud), + ) + .layer(DefaultBodyLimit::max(1024 * 1024)) + .route_layer(middleware::from_fn_with_state(state.clone(), require_auth)) + .route_layer(middleware::from_fn_with_state( + state.clone(), + blacklist_layer, + )); + + // CDN routes: GET is public; POST/PUT/DELETE are blacklisted for non-super-admins. + let cdn_routes = Router::new() + .route("/api/cdn", get(cdn_list).post(cdn_create)) + .route("/api/cdn/upload", post(cdn_upload)) + .route( + "/api/cdn/:key", + get(cdn_proxy).put(cdn_update).delete(cdn_delete), + ) + .route_layer(middleware::from_fn_with_state( + state.clone(), + blacklist_layer, + )); + + let app = Router::new() + .route("/auth/login", post(login)) + .merge(cdn_routes) + .merge(crud_routes) + .nest("/api/admin", admin_router(state.clone())) + .nest_service( + "/", + ServeDir::new("ui/dist").fallback(ServeFile::new("ui/dist/index.html")), + ) + .layer(middleware::from_fn_with_state(state.clone(), cors_layer)) + .with_state(state); + + let addr = std::net::SocketAddr::from(([0, 0, 0, 0], 3000)); + tracing::info!("listening on {}", addr); + let listener = tokio::net::TcpListener::bind(addr).await?; + axum::serve(listener, app).await?; + Ok(()) +} diff --git a/src/models/api_key.rs b/src/models/api_key.rs new file mode 100644 index 0000000..7437c6b --- /dev/null +++ b/src/models/api_key.rs @@ -0,0 +1,27 @@ +use chrono::{DateTime, Utc}; +use serde::{Deserialize, Serialize}; + +#[derive(Debug, Clone, Serialize, Deserialize, sqlx::FromRow)] +pub struct ApiKey { + pub id: i32, + pub name: String, + pub key_prefix: String, + pub permissions_mask: String, + pub created_at: DateTime, + pub expires_at: Option>, + pub last_used_at: Option>, +} + +#[derive(Debug, Deserialize)] +pub struct CreateApiKey { + pub name: String, + pub permissions_mask: Option, + pub expires_at: Option>, +} + +#[derive(Debug, Deserialize)] +pub struct UpdateApiKey { + pub name: Option, + pub permissions_mask: Option, + pub expires_at: Option>, +} diff --git a/src/models/blacklist.rs b/src/models/blacklist.rs new file mode 100644 index 0000000..7ed6b2b --- /dev/null +++ b/src/models/blacklist.rs @@ -0,0 +1,30 @@ +use chrono::{DateTime, Utc}; +use serde::{Deserialize, Serialize}; + +#[derive(Debug, Clone, Serialize, Deserialize, sqlx::FromRow)] +pub struct BlacklistEntry { + pub id: i32, + pub pattern: String, + pub method: Option, + pub reason: Option, + pub active: bool, + pub bypass_mask: Option, + pub created_at: DateTime, +} + +#[allow(dead_code)] +#[derive(Debug, Deserialize)] +pub struct CreateBlacklistEntry { + pub pattern: String, + pub method: Option, + pub reason: Option, +} + +#[allow(dead_code)] +#[derive(Debug, Deserialize)] +pub struct UpdateBlacklistEntry { + pub pattern: Option, + pub method: Option, + pub reason: Option, + pub active: Option, +} diff --git a/src/models/cdn.rs b/src/models/cdn.rs new file mode 100644 index 0000000..38413a7 --- /dev/null +++ b/src/models/cdn.rs @@ -0,0 +1,25 @@ +use chrono::{DateTime, Utc}; +use serde::{Deserialize, Serialize}; + +#[derive(Debug, Clone, Serialize, Deserialize, sqlx::FromRow)] +pub struct CdnObject { + pub id: i32, + pub key: String, + pub content_type: Option, + pub description: Option, + pub created_at: DateTime, +} + +#[derive(Debug, Deserialize)] +pub struct CreateCdnObject { + pub key: String, + pub content_type: Option, + pub description: Option, +} + +#[derive(Debug, Deserialize)] +pub struct UpdateCdnObject { + pub key: Option, + pub content_type: Option, + pub description: Option, +} diff --git a/src/models/mod.rs b/src/models/mod.rs new file mode 100644 index 0000000..6bd2f74 --- /dev/null +++ b/src/models/mod.rs @@ -0,0 +1,6 @@ +pub mod api_key; +pub mod blacklist; +pub mod cdn; +pub mod permission; +pub mod query; +pub mod user; diff --git a/src/models/permission.rs b/src/models/permission.rs new file mode 100644 index 0000000..cf702fc --- /dev/null +++ b/src/models/permission.rs @@ -0,0 +1,24 @@ +use serde::{Deserialize, Serialize}; + +#[allow(dead_code)] +#[derive(Debug, Clone, Serialize, Deserialize, sqlx::FromRow)] +pub struct Permission { + pub id: i32, + pub name: String, + pub bit_value: String, + pub description: Option, +} + +#[allow(dead_code)] +#[derive(Debug, Deserialize)] +pub struct CreatePermission { + pub name: String, + pub description: Option, +} + +#[allow(dead_code)] +#[derive(Debug, Deserialize)] +pub struct UpdatePermission { + pub name: Option, + pub description: Option, +} diff --git a/src/models/query.rs b/src/models/query.rs new file mode 100644 index 0000000..b0b8082 --- /dev/null +++ b/src/models/query.rs @@ -0,0 +1,28 @@ +use chrono::{DateTime, Utc}; +use serde::{Deserialize, Serialize}; +use uuid::Uuid; + +#[derive(Debug, Clone, Serialize, Deserialize, sqlx::FromRow)] +pub struct StoredQuery { + pub id: Uuid, + pub identifier: String, + pub sql_template: String, + pub description: Option, + pub created_at: DateTime, + pub updated_at: DateTime, +} + +#[allow(dead_code)] +#[derive(Debug, Deserialize)] +pub struct CreateQuery { + pub identifier: String, + pub sql_template: String, + pub description: Option, +} + +#[allow(dead_code)] +#[derive(Debug, Deserialize)] +pub struct UpdateQuery { + pub sql_template: Option, + pub description: Option, +} diff --git a/src/models/user.rs b/src/models/user.rs new file mode 100644 index 0000000..ec9ff38 --- /dev/null +++ b/src/models/user.rs @@ -0,0 +1,34 @@ +use chrono::{DateTime, Utc}; +use serde::{Deserialize, Serialize}; + +#[derive(Debug, Clone, Serialize, Deserialize, sqlx::FromRow)] +pub struct User { + pub id: i32, + pub username: String, + #[serde(skip_serializing)] + pub password_hash: String, + pub permissions_mask: String, + pub created_at: DateTime, +} + +#[allow(dead_code)] +#[derive(Debug, Deserialize)] +pub struct CreateUser { + pub username: String, + pub password: String, + pub permissions_mask: Option, +} + +#[allow(dead_code)] +#[derive(Debug, Deserialize)] +pub struct UpdateUser { + pub username: Option, + pub password: Option, + pub permissions_mask: Option, +} + +#[derive(Debug, Deserialize)] +pub struct LoginRequest { + pub username: String, + pub password: String, +} diff --git a/src/routes/admin/api_keys.rs b/src/routes/admin/api_keys.rs new file mode 100644 index 0000000..58ab6da --- /dev/null +++ b/src/routes/admin/api_keys.rs @@ -0,0 +1,103 @@ +use axum::{ + extract::{Path, State}, + http::StatusCode, + Json, +}; +use serde_json::{json, Value}; + +use crate::{ + auth::generate_api_key, + models::api_key::{ApiKey, CreateApiKey, UpdateApiKey}, + state::AppState, +}; + +pub async fn list_api_keys(State(state): State) -> Result>, StatusCode> { + let keys = sqlx::query_as::<_, ApiKey>( + "SELECT id, name, key_prefix, permissions_mask, created_at, expires_at, last_used_at + FROM api_keys ORDER BY created_at DESC", + ) + .fetch_all(&state.pool) + .await + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; + Ok(Json(keys)) +} + +pub async fn create_api_key( + State(state): State, + Json(body): Json, +) -> Result, StatusCode> { + let (plain_key, key_prefix, key_hash) = generate_api_key(); + let mask = body.permissions_mask.unwrap_or_else(|| "0".into()); + + sqlx::query( + "INSERT INTO api_keys (name, key_prefix, key_hash, permissions_mask, expires_at) + VALUES ($1, $2, $3, $4, $5)", + ) + .bind(&body.name) + .bind(&key_prefix) + .bind(&key_hash) + .bind(&mask) + .bind(body.expires_at) + .execute(&state.pool) + .await + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; + + Ok(Json(json!({ + "key": plain_key, + "prefix": key_prefix, + "name": body.name, + "permissions_mask": mask, + "note": "Store this key securely — it will not be shown again." + }))) +} + +pub async fn update_api_key( + State(state): State, + Path(id): Path, + Json(body): Json, +) -> Result, StatusCode> { + if body.name.is_none() && body.permissions_mask.is_none() && body.expires_at.is_none() { + return Err(StatusCode::BAD_REQUEST); + } + + let key = sqlx::query_as::<_, ApiKey>( + "UPDATE api_keys + SET name = COALESCE($1, name), + permissions_mask = COALESCE($2, permissions_mask), + expires_at = CASE WHEN $3::boolean THEN $4 ELSE expires_at END + WHERE id = $5 + RETURNING id, name, key_prefix, permissions_mask, created_at, expires_at, last_used_at", + ) + .bind(body.name.as_deref()) + .bind(body.permissions_mask.as_deref()) + .bind(body.expires_at.is_some()) + .bind(body.expires_at) + .bind(id) + .fetch_optional(&state.pool) + .await + .map_err(|e| { + tracing::error!("update api_key {}: {}", id, e); + StatusCode::INTERNAL_SERVER_ERROR + })? + .ok_or(StatusCode::NOT_FOUND)?; + + Ok(Json(key)) +} + +pub async fn revoke_api_key( + State(state): State, + Path(id): Path, +) -> Result { + let rows = sqlx::query("DELETE FROM api_keys WHERE id = $1") + .bind(id) + .execute(&state.pool) + .await + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)? + .rows_affected(); + + if rows == 0 { + Err(StatusCode::NOT_FOUND) + } else { + Ok(StatusCode::NO_CONTENT) + } +} diff --git a/src/routes/admin/cache.rs b/src/routes/admin/cache.rs new file mode 100644 index 0000000..b159eae --- /dev/null +++ b/src/routes/admin/cache.rs @@ -0,0 +1,24 @@ +use axum::extract::Extension; +use axum::{extract::State, http::StatusCode, Json}; +use serde_json::{json, Value}; + +use crate::{auth::Claims, state::AppState}; + +pub async fn cache_stats( + State(state): State, + Extension(_claims): Extension, +) -> Json { + Json(json!({ + "size": state.query_cache.len(), + "hits": state.query_cache.hits(), + "misses": state.query_cache.misses(), + })) +} + +pub async fn flush_cache( + State(state): State, + Extension(_claims): Extension, +) -> Result, StatusCode> { + state.query_cache.flush(); + Ok(Json(json!({ "flushed": true }))) +} diff --git a/src/routes/admin/mod.rs b/src/routes/admin/mod.rs new file mode 100644 index 0000000..ad78995 --- /dev/null +++ b/src/routes/admin/mod.rs @@ -0,0 +1,62 @@ +pub mod api_keys; +pub mod cache; +pub mod queries; +pub mod tables; + +use axum::{ + middleware, + routing::{delete, get, put}, + Router, +}; + +use crate::{ + auth::middleware::{require_admin_cache, require_admin_query, require_super_admin}, + state::AppState, +}; + +pub fn admin_router(state: AppState) -> Router { + let query_routes = Router::new() + .route("/:identifier/execute", get(queries::execute_query)) + .route_layer(middleware::from_fn_with_state( + state.clone(), + require_admin_query, + )); + + // Registered with explicit paths (not nested) to avoid Axum double-nest + // ambiguity with route("/", handler) which can silently 404. + let cache_routes = Router::new() + .route("/cache/stats", get(cache::cache_stats)) + .route("/cache", delete(cache::flush_cache)) + .route("/cache/", delete(cache::flush_cache)) + .route_layer(middleware::from_fn_with_state( + state.clone(), + require_admin_cache, + )); + + let super_routes = Router::new() + .route( + "/tables", + get(tables::list_tables).post(tables::create_table), + ) + .route( + "/tables/:name", + get(tables::get_table_preview).delete(tables::drop_table), + ) + .route( + "/api-keys", + get(api_keys::list_api_keys).post(api_keys::create_api_key), + ) + .route( + "/api-keys/:id", + put(api_keys::update_api_key).delete(api_keys::revoke_api_key), + ) + .route_layer(middleware::from_fn_with_state( + state.clone(), + require_super_admin, + )); + + Router::new() + .nest("/queries", query_routes) + .merge(cache_routes) + .merge(super_routes) +} diff --git a/src/routes/admin/queries.rs b/src/routes/admin/queries.rs new file mode 100644 index 0000000..ce4dd15 --- /dev/null +++ b/src/routes/admin/queries.rs @@ -0,0 +1,85 @@ +use axum::{ + extract::{Extension, Path, Query, State}, + http::StatusCode, + Json, +}; +use serde_json::Value; +use std::collections::HashMap; + +use crate::{auth::Claims, models::query::StoredQuery, state::AppState}; + +pub async fn execute_query( + State(state): State, + Extension(_claims): Extension, + Path(identifier): Path, + Query(params): Query>, +) -> Result, StatusCode> { + let stored = sqlx::query_as::<_, StoredQuery>( + "SELECT id, identifier, sql_template, description, created_at, updated_at FROM queries WHERE identifier = $1" + ) + .bind(&identifier) + .fetch_optional(&state.pool) + .await + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)? + .ok_or(StatusCode::NOT_FOUND)?; + + let mut sql = stored.sql_template.clone(); + let mut bound_vals: Vec = Vec::new(); + let mut idx = 1usize; + let mut sorted_params: Vec<(String, String)> = params.into_iter().collect(); + sorted_params.sort_by(|a, b| b.0.len().cmp(&a.0.len()).then(a.0.cmp(&b.0))); + for (name, val) in &sorted_params { + let placeholder = format!(":{}", name); + if sql.contains(&placeholder) { + sql = sql.replace(&placeholder, &format!("${}", idx)); + bound_vals.push(val.clone()); + idx += 1; + } + } + + let mut q = sqlx::query(&sql); + for val in &bound_vals { + q = q.bind(val.as_str()); + } + + let rows = q.fetch_all(&state.pool).await.map_err(|e| { + tracing::error!("query execution error: {}", e); + StatusCode::INTERNAL_SERVER_ERROR + })?; + + let json_rows: Vec = rows + .into_iter() + .map(crate::routes::crud::pg_row_to_json) + .collect(); + + Ok(Json(Value::Array(json_rows))) +} + +#[cfg(test)] +mod tests { + #[test] + fn test_prefix_param_substitution_order() { + let template = "SELECT * FROM t WHERE user_id = :user_id AND username = :username"; + let mut params: Vec<(String, String)> = vec![ + ("user_id".into(), "42".into()), + ("username".into(), "alice".into()), + ]; + params.sort_by(|a, b| b.0.len().cmp(&a.0.len()).then(a.0.cmp(&b.0))); + let mut sql = template.to_string(); + for (i, (name, _)) in params.iter().enumerate() { + sql = sql.replace(&format!(":{}", name), &format!("${}", i + 1)); + } + assert!( + !sql.contains(":username"), + "placeholder not replaced: {}", + sql + ); + assert!( + !sql.contains(":user_id"), + "placeholder not replaced: {}", + sql + ); + // username (len 8) comes first → $1; user_id (len 7) → $2 + assert_eq!(sql, "SELECT * FROM t WHERE user_id = $2 AND username = $1"); + } +} diff --git a/src/routes/admin/tables.rs b/src/routes/admin/tables.rs new file mode 100644 index 0000000..695d2a8 --- /dev/null +++ b/src/routes/admin/tables.rs @@ -0,0 +1,250 @@ +use axum::{ + extract::{Extension, Path, State}, + http::StatusCode, + Json, +}; +use serde::{Deserialize, Serialize}; +use serde_json::Value; +use sqlx::Row; + +use crate::{auth::Claims, routes::crud::pg_row_to_json, state::AppState}; + +const ALLOWED_TYPES: &[&str] = &[ + "TEXT", + "INTEGER", + "BIGINT", + "SMALLINT", + "BOOLEAN", + "NUMERIC", + "FLOAT4", + "FLOAT8", + "UUID", + "TIMESTAMPTZ", + "DATE", + "JSONB", +]; + +const PROTECTED_TABLES: &[&str] = &[ + "users", + "blacklist", + "api_keys", + "queries", + "permissions", + "cors_origins", + "cdn_objects", +]; + +fn is_protected(name: &str) -> bool { + let lower = name.to_lowercase(); + PROTECTED_TABLES.iter().any(|&t| t == lower) +} + +#[derive(Debug, Deserialize)] +pub struct ColumnDef { + pub name: String, + pub col_type: String, + pub nullable: Option, +} + +#[derive(Debug, Deserialize)] +pub struct CreateTableRequest { + pub name: String, + pub columns: Vec, +} + +#[derive(Debug, Serialize)] +pub struct TableInfo { + pub table_name: String, + pub column_count: i64, +} + +#[derive(Debug, Serialize)] +pub struct ColumnInfo { + pub column_name: String, + pub data_type: String, + pub is_nullable: String, +} + +#[derive(Debug, Serialize)] +pub struct TablePreview { + pub table_name: String, + pub row_count: i64, + pub columns: Vec, + pub sample_rows: Vec, +} + +pub async fn list_tables( + State(state): State, + Extension(_claims): Extension, +) -> Result>, StatusCode> { + let rows = sqlx::query( + r#" + SELECT t.table_name, + COUNT(c.column_name)::bigint AS column_count + FROM information_schema.tables t + LEFT JOIN information_schema.columns c + ON c.table_schema = t.table_schema AND c.table_name = t.table_name + WHERE t.table_schema = 'public' AND t.table_type = 'BASE TABLE' + GROUP BY t.table_name + ORDER BY t.table_name + "#, + ) + .fetch_all(&state.pool) + .await + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; + + let tables = rows + .into_iter() + .map(|r| TableInfo { + table_name: r.try_get::("table_name").unwrap_or_default(), + column_count: r.try_get::("column_count").unwrap_or(0), + }) + .collect(); + + Ok(Json(tables)) +} + +pub async fn get_table_preview( + State(state): State, + Extension(_claims): Extension, + Path(name): Path, +) -> Result, StatusCode> { + if !crate::routes::is_valid_identifier(&name) { + return Err(StatusCode::BAD_REQUEST); + } + + let col_rows = sqlx::query( + "SELECT column_name, data_type, is_nullable \ + FROM information_schema.columns \ + WHERE table_schema = 'public' AND table_name = $1 \ + ORDER BY ordinal_position", + ) + .bind(&name) + .fetch_all(&state.pool) + .await + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; + + if col_rows.is_empty() { + return Err(StatusCode::NOT_FOUND); + } + + let columns: Vec = col_rows + .into_iter() + .map(|r| ColumnInfo { + column_name: r.try_get::("column_name").unwrap_or_default(), + data_type: r.try_get::("data_type").unwrap_or_default(), + is_nullable: r.try_get::("is_nullable").unwrap_or_default(), + }) + .collect(); + + let count_sql = format!("SELECT COUNT(*)::bigint FROM {}", name); + let row_count: i64 = sqlx::query(&count_sql) + .fetch_one(&state.pool) + .await + .map(|r| r.try_get::(0).unwrap_or(0)) + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; + + let sample_sql = format!("SELECT * FROM {} LIMIT 10", name); + let sample_rows: Vec = sqlx::query(&sample_sql) + .fetch_all(&state.pool) + .await + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)? + .into_iter() + .map(pg_row_to_json) + .collect(); + + Ok(Json(TablePreview { + table_name: name, + row_count, + columns, + sample_rows, + })) +} + +pub async fn create_table( + State(state): State, + Extension(_claims): Extension, + Json(body): Json, +) -> Result, StatusCode> { + if !crate::routes::is_valid_identifier(&body.name) { + return Err(StatusCode::BAD_REQUEST); + } + if is_protected(&body.name) { + return Err(StatusCode::FORBIDDEN); + } + + if body.columns.is_empty() { + return Err(StatusCode::BAD_REQUEST); + } + + let mut col_defs = vec!["id SERIAL PRIMARY KEY".to_string()]; + + for col in &body.columns { + if !crate::routes::is_valid_identifier(&col.name) { + return Err(StatusCode::BAD_REQUEST); + } + + let upper_type = col.col_type.to_uppercase(); + if !ALLOWED_TYPES.contains(&upper_type.as_str()) { + return Err(StatusCode::UNPROCESSABLE_ENTITY); + } + + let nullable = col.nullable.unwrap_or(true); + let null_clause = if nullable { "" } else { " NOT NULL" }; + col_defs.push(format!("{} {}{}", col.name, upper_type, null_clause)); + } + + let sql = format!("CREATE TABLE {} ({})", body.name, col_defs.join(", ")); + + sqlx::query(&sql).execute(&state.pool).await.map_err(|e| { + tracing::error!("create table error: {}", e); + StatusCode::INTERNAL_SERVER_ERROR + })?; + + Ok(Json(TableInfo { + table_name: body.name, + column_count: body.columns.len() as i64 + 1, + })) +} + +pub async fn drop_table( + State(state): State, + Extension(_claims): Extension, + Path(name): Path, +) -> Result, StatusCode> { + if !crate::routes::is_valid_identifier(&name) { + return Err(StatusCode::BAD_REQUEST); + } + if is_protected(&name) { + return Err(StatusCode::FORBIDDEN); + } + + let sql = format!("DROP TABLE IF EXISTS {}", name); + sqlx::query(&sql).execute(&state.pool).await.map_err(|e| { + tracing::error!("drop table error: {}", e); + StatusCode::INTERNAL_SERVER_ERROR + })?; + + Ok(Json(serde_json::json!({ "dropped": true }))) +} + +#[cfg(test)] +mod tests { + use super::{is_protected, PROTECTED_TABLES}; + + #[test] + fn test_protected_tables_list() { + assert!(PROTECTED_TABLES.contains(&"users")); + assert!(PROTECTED_TABLES.contains(&"blacklist")); + assert!(PROTECTED_TABLES.contains(&"api_keys")); + assert!(PROTECTED_TABLES.contains(&"queries")); + assert!(PROTECTED_TABLES.contains(&"permissions")); + } + + #[test] + fn test_is_protected() { + assert!(is_protected("users")); + assert!(is_protected("USERS")); + assert!(!is_protected("orders")); + } +} diff --git a/src/routes/auth.rs b/src/routes/auth.rs new file mode 100644 index 0000000..e4cdf40 --- /dev/null +++ b/src/routes/auth.rs @@ -0,0 +1,36 @@ +use axum::{extract::State, http::StatusCode, Json}; +use serde_json::{json, Value}; + +use crate::{auth::encode_jwt, models::user::LoginRequest, state::AppState}; + +pub async fn login( + State(state): State, + Json(body): Json, +) -> Result, StatusCode> { + let user = sqlx::query_as::<_, crate::models::user::User>( + "SELECT id, username, password_hash, permissions_mask, created_at FROM users WHERE username = $1", + ) + .bind(&body.username) + .fetch_optional(&state.pool) + .await + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)? + .ok_or(StatusCode::UNAUTHORIZED)?; + + let valid = bcrypt::verify(&body.password, &user.password_hash) + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; + + if !valid { + return Err(StatusCode::UNAUTHORIZED); + } + + let mask: u128 = user.permissions_mask.parse().unwrap_or(0); + let token = encode_jwt( + &user.username, + mask, + &state.config.jwt_secret, + state.config.jwt_expiry_secs, + ) + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; + + Ok(Json(json!({ "token": token }))) +} diff --git a/src/routes/cdn.rs b/src/routes/cdn.rs new file mode 100644 index 0000000..c274a75 --- /dev/null +++ b/src/routes/cdn.rs @@ -0,0 +1,249 @@ +use axum::{ + extract::{Multipart, Path, State}, + http::{header, StatusCode}, + response::IntoResponse, + Json, +}; +use serde_json::Value; +use sqlx::Row; + +use crate::{ + models::cdn::{CdnObject, CreateCdnObject, UpdateCdnObject}, + state::AppState, +}; + +pub async fn cdn_list(State(state): State) -> Result>, StatusCode> { + let objects = sqlx::query_as::<_, CdnObject>( + "SELECT id, key, content_type, description, created_at \ + FROM cdn_objects ORDER BY id", + ) + .fetch_all(&state.pool) + .await + .map_err(|e| { + tracing::error!("cdn_list: {}", e); + StatusCode::INTERNAL_SERVER_ERROR + })?; + Ok(Json(objects)) +} + +pub async fn cdn_proxy( + State(state): State, + Path(key): Path, +) -> Result { + let row = sqlx::query("SELECT content_type FROM cdn_objects WHERE key = $1") + .bind(&key) + .fetch_optional(&state.pool) + .await + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)? + .ok_or(StatusCode::NOT_FOUND)?; + + let content_type: Option = row + .try_get::, _>("content_type") + .ok() + .flatten(); + let url = format!("{}/{}", state.cdn_base_url, key); + + let upstream = state.http_client.get(&url).send().await.map_err(|e| { + tracing::error!("cdn_proxy upstream error for key={}: {}", key, e); + StatusCode::BAD_GATEWAY + })?; + + let status = + StatusCode::from_u16(upstream.status().as_u16()).unwrap_or(StatusCode::BAD_GATEWAY); + + let bytes = upstream + .bytes() + .await + .map_err(|_| StatusCode::BAD_GATEWAY)?; + + let ct = content_type.unwrap_or_else(|| "application/octet-stream".to_string()); + + Ok((status, [(header::CONTENT_TYPE, ct)], bytes)) +} + +pub async fn cdn_create( + State(state): State, + Json(body): Json, +) -> Result, StatusCode> { + let obj = sqlx::query_as::<_, CdnObject>( + "INSERT INTO cdn_objects (key, content_type, description) \ + VALUES ($1, $2, $3) \ + RETURNING id, key, content_type, description, created_at", + ) + .bind(&body.key) + .bind(&body.content_type) + .bind(&body.description) + .fetch_one(&state.pool) + .await + .map_err(|e| { + tracing::error!("cdn_create: {}", e); + if let sqlx::Error::Database(db_err) = &e { + if db_err.code().as_deref() == Some("23505") { + return StatusCode::CONFLICT; + } + } + StatusCode::INTERNAL_SERVER_ERROR + })?; + Ok(Json(obj)) +} + +pub async fn cdn_update( + State(state): State, + Path(key): Path, + Json(body): Json, +) -> Result, StatusCode> { + let obj = sqlx::query_as::<_, CdnObject>( + "UPDATE cdn_objects \ + SET key = COALESCE($2, key), \ + content_type = COALESCE($3, content_type), \ + description = COALESCE($4, description) \ + WHERE key = $1 \ + RETURNING id, key, content_type, description, created_at", + ) + .bind(&key) + .bind(&body.key) + .bind(&body.content_type) + .bind(&body.description) + .fetch_optional(&state.pool) + .await + .map_err(|e| { + tracing::error!("cdn_update: {}", e); + if let sqlx::Error::Database(db_err) = &e { + if db_err.code().as_deref() == Some("23505") { + return StatusCode::CONFLICT; + } + } + StatusCode::INTERNAL_SERVER_ERROR + })? + .ok_or(StatusCode::NOT_FOUND)?; + Ok(Json(obj)) +} + +pub async fn cdn_delete( + State(state): State, + Path(key): Path, +) -> Result, StatusCode> { + let rows = sqlx::query("DELETE FROM cdn_objects WHERE key = $1") + .bind(&key) + .execute(&state.pool) + .await + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)? + .rows_affected(); + if rows == 0 { + return Err(StatusCode::NOT_FOUND); + } + + let url = format!("{}/{}", state.cdn_base_url, key); + let res = state + .http_client + .delete(&url) + .send() + .await + .map_err(|e| { + tracing::error!("cdn_delete: MinIO DELETE failed for key={}: {}", key, e); + StatusCode::BAD_GATEWAY + })?; + if !res.status().is_success() { + tracing::error!( + "cdn_delete: MinIO returned {} for key={}", + res.status(), + key + ); + return Err(StatusCode::BAD_GATEWAY); + } + + Ok(Json(serde_json::json!({ "deleted": true }))) +} + +/// Receive a multipart upload, PUT the file to MinIO, then register it in cdn_objects. +/// Fields: `file` (required), `key` (optional — defaults to filename), `content_type` +/// (optional — defaults to detected), `description` (optional). +pub async fn cdn_upload( + State(state): State, + mut multipart: Multipart, +) -> Result, StatusCode> { + let mut file_bytes: Option = None; + let mut filename: Option = None; + let mut key_override: Option = None; + let mut content_type_override: Option = None; + let mut description: Option = None; + + while let Some(field) = multipart + .next_field() + .await + .map_err(|_| StatusCode::BAD_REQUEST)? + { + let field_name = field.name().unwrap_or("").to_string(); + match field_name.as_str() { + "file" => { + filename = field.file_name().map(|s| s.to_string()); + if content_type_override.is_none() { + content_type_override = field.content_type().map(|s| s.to_string()); + } + file_bytes = Some(field.bytes().await.map_err(|_| StatusCode::BAD_REQUEST)?); + } + "key" => { + let v = field.text().await.map_err(|_| StatusCode::BAD_REQUEST)?; + if !v.is_empty() { + key_override = Some(v); + } + } + "content_type" => { + let v = field.text().await.map_err(|_| StatusCode::BAD_REQUEST)?; + if !v.is_empty() { + content_type_override = Some(v); + } + } + "description" => { + let v = field.text().await.map_err(|_| StatusCode::BAD_REQUEST)?; + if !v.is_empty() { + description = Some(v); + } + } + _ => {} + } + } + + let bytes = file_bytes.ok_or(StatusCode::BAD_REQUEST)?; + let key = key_override.or(filename).ok_or(StatusCode::BAD_REQUEST)?; + let ct = content_type_override.unwrap_or_else(|| "application/octet-stream".to_string()); + + // Upload to MinIO (bucket is anonymous-public, so no auth needed) + let upload_url = format!("{}/{}", state.cdn_base_url, key); + let res = state + .http_client + .put(&upload_url) + .header("Content-Type", &ct) + .body(bytes) + .send() + .await + .map_err(|e| { + tracing::error!("cdn_upload: MinIO PUT failed: {}", e); + StatusCode::BAD_GATEWAY + })?; + + if !res.status().is_success() { + tracing::error!("cdn_upload: MinIO returned {}", res.status()); + return Err(StatusCode::BAD_GATEWAY); + } + + let obj = sqlx::query_as::<_, CdnObject>( + "INSERT INTO cdn_objects (key, content_type, description) \ + VALUES ($1, $2, $3) \ + ON CONFLICT (key) DO UPDATE \ + SET content_type = EXCLUDED.content_type, \ + description = EXCLUDED.description \ + RETURNING id, key, content_type, description, created_at", + ) + .bind(&key) + .bind(&ct) + .bind(&description) + .fetch_one(&state.pool) + .await + .map_err(|e| { + tracing::error!("cdn_upload: DB insert failed: {}", e); + StatusCode::INTERNAL_SERVER_ERROR + })?; + + Ok(Json(obj)) +} diff --git a/src/routes/crud.rs b/src/routes/crud.rs new file mode 100644 index 0000000..c44777f --- /dev/null +++ b/src/routes/crud.rs @@ -0,0 +1,449 @@ +use anyhow::{anyhow, Result}; +use axum::{ + extract::{Extension, Path, Query, State}, + http::{Method, StatusCode}, + Json, +}; +use serde_json::Value; +use sqlx::postgres::PgRow; +use sqlx::Column; +use sqlx::Row; +use sqlx::TypeInfo; +use std::collections::HashMap; + +use crate::{ + auth::Claims, + models::blacklist::BlacklistEntry, + state::{AppState, CacheEntry}, +}; + +/// Returns (sql, ordered_param_values, cache_key). +/// body_cols: (col_name, typed_value) pairs from request body. +/// filter_cols: (col_name, string_value) pairs from query params. +fn coerce_id(id_val: &str) -> Value { + if let Ok(n) = id_val.parse::() { + Value::Number(n.into()) + } else { + Value::String(id_val.to_string()) + } +} + +pub fn build_query( + method: &str, + table: &str, + id: Option<&str>, + body_cols: &[(String, Value)], + filter_cols: &[(String, String)], +) -> Result<(String, Vec, String)> { + if !crate::routes::is_valid_identifier(table) { + return Err(anyhow!("invalid identifier: {}", table)); + } + for (col, _) in body_cols.iter() { + if !crate::routes::is_valid_identifier(col) { + return Err(anyhow!("invalid identifier: {}", col)); + } + } + for (col, _) in filter_cols.iter() { + if !crate::routes::is_valid_identifier(col) { + return Err(anyhow!("invalid identifier: {}", col)); + } + } + + let mut sorted_body = body_cols.to_vec(); + sorted_body.sort_by(|a, b| a.0.cmp(&b.0)); + let mut sorted_filters = filter_cols.to_vec(); + sorted_filters.sort_by(|a, b| a.0.cmp(&b.0)); + + match method.to_uppercase().as_str() { + "GET" => { + if let Some(id_val) = id { + let sql = format!("SELECT * FROM {} WHERE id = $1", table); + let key = format!("GET:{}:~id", table); + Ok((sql, vec![coerce_id(id_val)], key)) + } else if sorted_filters.is_empty() { + let sql = format!("SELECT * FROM {}", table); + let key = format!("GET:{}:", table); + Ok((sql, vec![], key)) + } else { + let col_names: Vec = + sorted_filters.iter().map(|(c, _)| c.clone()).collect(); + let where_clause: Vec = col_names + .iter() + .enumerate() + .map(|(i, c)| format!("{} = ${}", c, i + 1)) + .collect(); + let sql = format!( + "SELECT * FROM {} WHERE {}", + table, + where_clause.join(" AND ") + ); + let params: Vec = sorted_filters + .iter() + .map(|(_, v)| Value::String(v.clone())) + .collect(); + let key = format!("GET:{}:{}", table, col_names.join(",")); + Ok((sql, params, key)) + } + } + "POST" => { + if sorted_body.is_empty() { + return Err(anyhow!("POST requires a body with at least one field")); + } + let cols: Vec = sorted_body.iter().map(|(c, _)| c.clone()).collect(); + let placeholders: Vec = (1..=cols.len()).map(|i| format!("${}", i)).collect(); + let sql = format!( + "INSERT INTO {} ({}) VALUES ({}) RETURNING *", + table, + cols.join(", "), + placeholders.join(", ") + ); + let params: Vec = sorted_body.iter().map(|(_, v)| v.clone()).collect(); + let key = format!("POST:{}:{}", table, cols.join(",")); + Ok((sql, params, key)) + } + "PUT" => { + let id_val = id.ok_or_else(|| anyhow!("PUT requires an id"))?; + if sorted_body.is_empty() { + return Err(anyhow!("PUT requires a body with at least one field")); + } + let cols: Vec = sorted_body.iter().map(|(c, _)| c.clone()).collect(); + let set_clause: Vec = cols + .iter() + .enumerate() + .map(|(i, c)| format!("{} = ${}", c, i + 1)) + .collect(); + let id_placeholder = cols.len() + 1; + let sql = format!( + "UPDATE {} SET {} WHERE id = ${} RETURNING *", + table, + set_clause.join(", "), + id_placeholder + ); + let mut params: Vec = sorted_body.iter().map(|(_, v)| v.clone()).collect(); + params.push(coerce_id(id_val)); + let key = format!("PUT:{}:{}:by_id", table, cols.join(",")); + Ok((sql, params, key)) + } + "DELETE" => { + let id_val = id.ok_or_else(|| anyhow!("DELETE requires an id"))?; + let sql = format!("DELETE FROM {} WHERE id = $1", table); + let key = format!("DELETE:{}:by_id", table); + Ok((sql, vec![coerce_id(id_val)], key)) + } + m => Err(anyhow!("unsupported method: {}", m)), + } +} + +pub fn pg_row_to_json(row: PgRow) -> Value { + let columns = row.columns(); + let mut map = serde_json::Map::new(); + for col in columns { + let name = col.name().to_string(); + let type_name = col.type_info().name(); + let val = match type_name { + "INT2" => row + .try_get::(col.ordinal()) + .map(|v| Value::Number(i64::from(v).into())) + .unwrap_or(Value::Null), + "INT4" | "SERIAL" => row + .try_get::(col.ordinal()) + .map(|v| Value::Number(i64::from(v).into())) + .unwrap_or(Value::Null), + "INT8" => row + .try_get::(col.ordinal()) + .map(|v| Value::Number(v.into())) + .unwrap_or(Value::Null), + "FLOAT4" | "FLOAT8" => row + .try_get::(col.ordinal()) + .ok() + .and_then(serde_json::Number::from_f64) + .map(Value::Number) + .unwrap_or(Value::Null), + "BOOL" => row + .try_get::(col.ordinal()) + .map(Value::Bool) + .unwrap_or(Value::Null), + "UUID" => row + .try_get::(col.ordinal()) + .map(|v| Value::String(v.to_string())) + .unwrap_or(Value::Null), + "TIMESTAMPTZ" | "TIMESTAMP" => row + .try_get::, _>(col.ordinal()) + .map(|v| Value::String(v.to_rfc3339())) + .unwrap_or(Value::Null), + _ => row + .try_get::(col.ordinal()) + .map(Value::String) + .unwrap_or(Value::Null), + }; + map.insert(name, val); + } + Value::Object(map) +} + +async fn reload_blacklist(state: &AppState) -> Result<(), StatusCode> { + let entries = sqlx::query_as::<_, BlacklistEntry>( + "SELECT id, pattern, method, reason, active, bypass_mask, created_at FROM blacklist ORDER BY id", + ) + .fetch_all(&state.pool) + .await + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; + state.blacklist_cache.load(entries).await; + Ok(()) +} + +async fn reload_cors(state: &AppState) -> Result<(), StatusCode> { + let origins: Vec = + sqlx::query_scalar::<_, String>("SELECT origin FROM cors_origins ORDER BY id") + .fetch_all(&state.pool) + .await + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; + state.cors_cache.load(origins).await; + Ok(()) +} + +fn strip_password_hash(v: Value) -> Value { + match v { + Value::Object(mut m) => { + m.remove("password_hash"); + Value::Object(m) + } + Value::Array(arr) => Value::Array( + arr.into_iter() + .map(|item| match item { + Value::Object(mut m) => { + m.remove("password_hash"); + Value::Object(m) + } + other => other, + }) + .collect(), + ), + other => other, + } +} + +pub async fn handle_crud( + State(state): State, + method: Method, + Extension(claims): Extension, + Path(params): Path>, + Query(query_params): Query>, + body: Option>>, +) -> Result, StatusCode> { + let table = params.get("table").ok_or(StatusCode::BAD_REQUEST)?.clone(); + let id = params.get("id").map(|s| s.as_str()); + let method_str = method.as_str(); + + // Enforce permission bits before doing any work. + let required_bit = match method_str.to_uppercase().as_str() { + "GET" => crate::auth::permissions::READ, + "POST" | "PUT" => crate::auth::permissions::WRITE, + "DELETE" => crate::auth::permissions::DELETE, + _ => return Err(StatusCode::METHOD_NOT_ALLOWED), + }; + if !claims.has_permission(required_bit) { + return Err(StatusCode::FORBIDDEN); + } + + // Collect body as typed Values directly — no sentinel needed. + let mut body_cols: Vec<(String, Value)> = body + .map(|Json(b)| b.into_iter().collect()) + .unwrap_or_default(); + + // Hash the password field for the users table before building the query. + if table == "users" && matches!(method_str.to_uppercase().as_str(), "POST" | "PUT") { + if let Some(pos) = body_cols.iter().position(|(k, _)| k == "password") { + let (_, val) = body_cols.remove(pos); + if let Value::String(plaintext) = val { + let hash = bcrypt::hash(&plaintext, bcrypt::DEFAULT_COST) + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; + body_cols.push(("password_hash".to_string(), Value::String(hash))); + } + } + } + + let filter_cols: Vec<(String, String)> = query_params.into_iter().collect(); + + let (sql, params_vals, cache_key) = + build_query(method_str, &table, id, &body_cols, &filter_cols) + .map_err(|_| StatusCode::BAD_REQUEST)?; + + let sql = if let Some(entry) = state.query_cache.get(&cache_key) { + entry.sql.clone() + } else { + let entry = CacheEntry::new(sql.clone()); + state + .query_cache + .insert(cache_key, entry.clone(), state.config.cache_max_capacity); + entry.sql + }; + + let mut q = sqlx::query(&sql); + for val in ¶ms_vals { + match val { + Value::Null => q = q.bind(Option::::None), + Value::Bool(b) => q = q.bind(*b), + Value::Number(n) => { + if let Some(i) = n.as_i64() { + q = q.bind(i); + } else if let Some(f) = n.as_f64() { + q = q.bind(f); + } else { + q = q.bind(n.to_string()); + } + } + Value::String(s) => q = q.bind(s.as_str()), + other => q = q.bind(other.to_string()), + } + } + + let response = match method_str.to_uppercase().as_str() { + "GET" => { + let rows = q.fetch_all(&state.pool).await.map_err(|e| { + tracing::error!("GET {}: {}", table, e); + StatusCode::INTERNAL_SERVER_ERROR + })?; + let mut v = Value::Array(rows.into_iter().map(pg_row_to_json).collect()); + if table == "users" { + v = strip_password_hash(v); + } + v + } + "POST" | "PUT" => { + let row = q.fetch_one(&state.pool).await.map_err(|e| { + if matches!(e, sqlx::Error::RowNotFound) { + StatusCode::NOT_FOUND + } else { + tracing::error!("{} {}: {}", method_str, table, e); + StatusCode::INTERNAL_SERVER_ERROR + } + })?; + let mut v = pg_row_to_json(row); + if table == "users" { + v = strip_password_hash(v); + } + v + } + "DELETE" => { + let rows_affected = q + .execute(&state.pool) + .await + .map_err(|e| { + tracing::error!("DELETE {}: {}", table, e); + StatusCode::INTERNAL_SERVER_ERROR + })? + .rows_affected(); + if rows_affected == 0 { + return Err(StatusCode::NOT_FOUND); + } + serde_json::json!({ "deleted": true }) + } + _ => return Err(StatusCode::METHOD_NOT_ALLOWED), + }; + + // Reload in-memory caches after mutations to their backing tables. + if table == "blacklist" && method_str != "GET" { + reload_blacklist(&state).await?; + } + if table == "cors_origins" && method_str != "GET" { + reload_cors(&state).await?; + } + + Ok(Json(response)) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_build_select_all() { + let (sql, params, key) = build_query("GET", "orders", None, &[], &[]).unwrap(); + assert_eq!(sql, "SELECT * FROM orders"); + assert!(params.is_empty()); + assert_eq!(key, "GET:orders:"); + } + + #[test] + fn test_build_select_by_id() { + let (sql, params, key) = build_query("GET", "orders", Some("42"), &[], &[]).unwrap(); + assert_eq!(sql, "SELECT * FROM orders WHERE id = $1"); + assert_eq!(params, vec![Value::Number(42.into())]); + assert_eq!(key, "GET:orders:~id"); + } + + #[test] + fn test_build_insert() { + let cols = vec![ + ("email".into(), Value::String("a@b.com".into())), + ("name".into(), Value::String("Alice".into())), + ]; + let (sql, params, key) = build_query("POST", "users", None, &cols, &[]).unwrap(); + assert_eq!( + sql, + "INSERT INTO users (email, name) VALUES ($1, $2) RETURNING *" + ); + assert_eq!( + params, + vec![ + Value::String("a@b.com".into()), + Value::String("Alice".into()) + ] + ); + assert_eq!(key, "POST:users:email,name"); + } + + #[test] + fn test_build_update() { + let cols = vec![("name".into(), Value::String("Bob".into()))]; + let (sql, params, key) = build_query("PUT", "users", Some("7"), &cols, &[]).unwrap(); + assert_eq!(sql, "UPDATE users SET name = $1 WHERE id = $2 RETURNING *"); + assert_eq!( + params, + vec![Value::String("Bob".into()), Value::Number(7.into())] + ); + assert_eq!(key, "PUT:users:name:by_id"); + } + + #[test] + fn test_build_delete() { + let (sql, params, key) = build_query("DELETE", "users", Some("3"), &[], &[]).unwrap(); + assert_eq!(sql, "DELETE FROM users WHERE id = $1"); + assert_eq!(params, vec![Value::Number(3.into())]); + assert_eq!(key, "DELETE:users:by_id"); + } + + #[test] + fn test_build_select_with_filters() { + let filters = vec![ + ("status".into(), "active".into()), + ("role".into(), "admin".into()), + ]; + let (sql, params, key) = build_query("GET", "users", None, &[], &filters).unwrap(); + assert_eq!(sql, "SELECT * FROM users WHERE role = $1 AND status = $2"); + assert_eq!( + params, + vec![ + Value::String("admin".into()), + Value::String("active".into()) + ] + ); + assert_eq!(key, "GET:users:role,status"); + } + + #[test] + fn test_build_null_body_value() { + let cols = vec![("note".into(), Value::Null)]; + let (sql, params, key) = build_query("POST", "items", None, &cols, &[]).unwrap(); + assert_eq!(sql, "INSERT INTO items (note) VALUES ($1) RETURNING *"); + assert_eq!(params, vec![Value::Null]); + assert_eq!(key, "POST:items:note"); + } + + #[test] + fn test_rejects_invalid_table_name() { + let result = build_query("GET", "users; DROP TABLE users--", None, &[], &[]); + assert!(result.is_err()); + } +} diff --git a/src/routes/mod.rs b/src/routes/mod.rs new file mode 100644 index 0000000..f9ec927 --- /dev/null +++ b/src/routes/mod.rs @@ -0,0 +1,8 @@ +pub mod admin; +pub mod auth; +pub mod cdn; +pub mod crud; + +pub fn is_valid_identifier(name: &str) -> bool { + !name.is_empty() && name.chars().all(|c| c.is_alphanumeric() || c == '_') +} diff --git a/src/state.rs b/src/state.rs new file mode 100644 index 0000000..484da65 --- /dev/null +++ b/src/state.rs @@ -0,0 +1,330 @@ +use std::sync::{ + atomic::{AtomicU64, Ordering}, + Arc, +}; +use std::time::{SystemTime, UNIX_EPOCH}; + +use axum::http::HeaderValue; +use dashmap::DashMap; +use glob::Pattern; +use sqlx::PgPool; +use tokio::sync::RwLock; + +use crate::config::Config; +use crate::models::blacklist::BlacklistEntry; + +pub fn unix_now() -> u64 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap_or_default() + .as_secs() +} + +#[derive(Clone)] +pub struct AppState { + pub pool: PgPool, + pub query_cache: QueryCache, + pub blacklist_cache: BlacklistCache, + pub cors_cache: CorsCache, + pub http_client: reqwest::Client, + pub cdn_base_url: String, + pub config: Arc, +} + +#[derive(Clone)] +pub struct QueryCache { + pub map: Arc>, + pub hits: Arc, + pub misses: Arc, +} + +#[derive(Clone, Debug)] +pub struct CacheEntry { + pub sql: String, + pub last_accessed_secs: Arc, +} + +impl CacheEntry { + pub fn new(sql: String) -> Self { + Self { + sql, + last_accessed_secs: Arc::new(AtomicU64::new(unix_now())), + } + } + + pub fn touch(&self) { + self.last_accessed_secs.store(unix_now(), Ordering::Relaxed); + } + + pub fn last_accessed(&self) -> u64 { + self.last_accessed_secs.load(Ordering::Relaxed) + } +} + +impl QueryCache { + pub fn new() -> Self { + Self { + map: Arc::new(DashMap::new()), + hits: Arc::new(AtomicU64::new(0)), + misses: Arc::new(AtomicU64::new(0)), + } + } + + pub fn get(&self, key: &str) -> Option { + if let Some(entry) = self.map.get(key) { + entry.touch(); + self.hits.fetch_add(1, Ordering::Relaxed); + Some(entry.clone()) + } else { + self.misses.fetch_add(1, Ordering::Relaxed); + None + } + } + + pub fn insert(&self, key: String, entry: CacheEntry, max_capacity: usize) { + if self.map.len() >= max_capacity { + let oldest_key = self + .map + .iter() + .min_by_key(|e| e.last_accessed()) + .map(|e| e.key().clone()); + if let Some(k) = oldest_key { + self.map.remove(&k); + } + } + self.map.insert(key, entry); + } + + #[allow(dead_code)] + pub fn remove(&self, key: &str) { + self.map.remove(key); + } + + pub fn hits(&self) -> u64 { + self.hits.load(Ordering::Relaxed) + } + + pub fn misses(&self) -> u64 { + self.misses.load(Ordering::Relaxed) + } + + pub fn len(&self) -> usize { + self.map.len() + } + + pub fn flush(&self) { + self.map.clear(); + } +} + +#[derive(Clone)] +pub struct BlacklistCache { + pub inner: Arc>>, +} + +#[derive(Clone)] +pub struct CompiledEntry { + pub entry: BlacklistEntry, + pub pattern: Pattern, + pub bypass_mask: Option, +} + +impl BlacklistCache { + pub fn new() -> Self { + Self { + inner: Arc::new(RwLock::new(Vec::new())), + } + } + + pub async fn load(&self, entries: Vec) { + let compiled: Vec = entries + .into_iter() + .filter_map(|e| { + let bypass_mask = e + .bypass_mask + .as_deref() + .and_then(|s| s.parse::().ok()); + Pattern::new(&e.pattern).ok().map(|pattern| CompiledEntry { + entry: e, + pattern, + bypass_mask, + }) + }) + .collect(); + let mut guard = self.inner.write().await; + *guard = compiled; + } + + /// Returns true if the request should be blocked. + /// `caller_mask` is 0 for unauthenticated requests; bypass only applies + /// when the caller holds the permission bit stored in bypass_mask. + pub async fn is_blocked(&self, method: &str, path: &str, caller_mask: u128) -> bool { + let path = path.trim_end_matches('/'); + let path = if path.is_empty() { "/" } else { path }; + let guard = self.inner.read().await; + guard.iter().any(|compiled| { + if !compiled.entry.active { + return false; + } + let method_matches = compiled + .entry + .method + .as_deref() + .map(|m| { + m.split(',') + .any(|part| part.trim().eq_ignore_ascii_case(method)) + }) + .unwrap_or(true); + if !method_matches || !compiled.pattern.matches(path) { + return false; + } + // If caller holds the bypass permission, they are not blocked. + !matches!(compiled.bypass_mask, Some(mask) if caller_mask & mask != 0) + }) + } +} + +#[derive(Clone)] +pub struct CorsCache { + pub inner: Arc>, +} + +#[derive(Clone, Default)] +pub struct CorsState { + pub wildcard: bool, + pub origins: Vec, +} + +impl CorsCache { + pub fn new() -> Self { + Self { + inner: Arc::new(RwLock::new(CorsState::default())), + } + } + + pub async fn load(&self, origins: Vec) { + let wildcard = origins.iter().any(|o| o == "*"); + let parsed: Vec = origins + .iter() + .filter(|o| *o != "*") + .filter_map(|o| o.parse().ok()) + .collect(); + let mut guard = self.inner.write().await; + *guard = CorsState { + wildcard, + origins: parsed, + }; + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_cache_insert_and_get() { + let cache = QueryCache::new(); + let entry = CacheEntry::new("SELECT 1".into()); + cache.insert("key1".into(), entry, 100); + let got = cache.get("key1"); + assert!(got.is_some()); + assert_eq!(got.unwrap().sql, "SELECT 1"); + assert_eq!(cache.hits(), 1); + assert_eq!(cache.misses(), 0); + } + + #[test] + fn test_cache_miss() { + let cache = QueryCache::new(); + let got = cache.get("missing"); + assert!(got.is_none()); + assert_eq!(cache.misses(), 1); + } + + #[test] + fn test_cache_capacity_evicts_oldest() { + let cache = QueryCache::new(); + let e1 = CacheEntry::new("SELECT 1".into()); + // force e1 to be older + e1.last_accessed_secs.store(1, Ordering::Relaxed); + cache.map.insert("old".into(), e1); + let e2 = CacheEntry::new("SELECT 2".into()); + cache.insert("new".into(), e2, 1); // capacity=1, should evict "old" + assert!(cache.map.get("old").is_none()); + assert!(cache.map.get("new").is_some()); + } + + #[tokio::test] + async fn test_blacklist_blocks_pattern() { + use chrono::Utc; + let cache = BlacklistCache::new(); + let entry = BlacklistEntry { + id: 1, + pattern: "/api/users/**".into(), + method: None, + reason: None, + active: true, + bypass_mask: None, + created_at: Utc::now(), + }; + cache.load(vec![entry]).await; + assert!(cache.is_blocked("GET", "/api/users/42", 0).await); + assert!(!cache.is_blocked("GET", "/api/orders/1", 0).await); + } + + #[tokio::test] + async fn test_blacklist_method_specific() { + use chrono::Utc; + let cache = BlacklistCache::new(); + let entry = BlacklistEntry { + id: 2, + pattern: "/api/secrets".into(), + method: Some("GET".into()), + reason: None, + active: true, + bypass_mask: None, + created_at: Utc::now(), + }; + cache.load(vec![entry]).await; + assert!(cache.is_blocked("GET", "/api/secrets", 0).await); + assert!(!cache.is_blocked("POST", "/api/secrets", 0).await); + } + + #[tokio::test] + async fn test_cors_cache_wildcard() { + let cache = CorsCache::new(); + cache.load(vec!["*".to_string()]).await; + let guard = cache.inner.read().await; + assert!(guard.wildcard); + assert!(guard.origins.is_empty()); + } + + #[tokio::test] + async fn test_cors_cache_specific_origin() { + let cache = CorsCache::new(); + cache.load(vec!["https://example.com".to_string()]).await; + let guard = cache.inner.read().await; + assert!(!guard.wildcard); + assert_eq!(guard.origins.len(), 1); + assert_eq!(guard.origins[0], "https://example.com"); + } + + #[tokio::test] + async fn test_cors_cache_empty() { + let cache = CorsCache::new(); + cache.load(vec![]).await; + let guard = cache.inner.read().await; + assert!(!guard.wildcard); + assert!(guard.origins.is_empty()); + } + + #[tokio::test] + async fn test_cors_cache_load_replaces() { + let cache = CorsCache::new(); + cache.load(vec!["https://a.com".to_string()]).await; + cache.load(vec!["https://b.com".to_string()]).await; + let guard = cache.inner.read().await; + assert_eq!(guard.origins.len(), 1); + assert_eq!(guard.origins[0], "https://b.com"); + } +} diff --git a/ui/.gitignore b/ui/.gitignore new file mode 100644 index 0000000..27420d2 --- /dev/null +++ b/ui/.gitignore @@ -0,0 +1,11 @@ +node_modules/ +dist/ +.npmrc + +# vue-tsc emit artifacts (should never appear in src/ — noEmit is set) +src/**/*.vue.js +src/**/*.vue.js.map +src/**/*.vue.d.ts +src/**/*.vue.d.ts.map +src/**/*.ts.js +src/**/*.ts.js.map diff --git a/ui/bun.lock b/ui/bun.lock new file mode 100644 index 0000000..caff4cc --- /dev/null +++ b/ui/bun.lock @@ -0,0 +1,230 @@ +{ + "lockfileVersion": 1, + "configVersion": 1, + "workspaces": { + "": { + "name": "mercury-ui", + "dependencies": { + "@nychthemeron/library": "latest", + "pinia": "^2.1.0", + "vue": "^3.4.0", + "vue-router": "^4.3.0", + }, + "devDependencies": { + "@vitejs/plugin-vue": "^5.0.0", + "typescript": "^5.3.0", + "vite": "^5.0.0", + "vue-tsc": "^2.0.0", + }, + }, + }, + "packages": { + "@babel/helper-string-parser": ["@babel/helper-string-parser@7.29.7", "", {}, "sha512-Pb5ijPrZ89GDH8223L4UP8i6QApWxs04RbPQJTeWDV0/keR2E36MeKnyr6LYmUUvqRRI+Iv87SuF1W6ErINzYw=="], + + "@babel/helper-validator-identifier": ["@babel/helper-validator-identifier@7.29.7", "", {}, "sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg=="], + + "@babel/parser": ["@babel/parser@7.29.7", "", { "dependencies": { "@babel/types": "^7.29.7" }, "bin": "./bin/babel-parser.js" }, "sha512-hnORnjP/1P/zFEndoeX+n+t1RwWRJiJpM/jO7FW32Kn9r5+sJB2JWOdYo4L6k78j15eCwY3Gm/7364B1EMwtNg=="], + + "@babel/types": ["@babel/types@7.29.7", "", { "dependencies": { "@babel/helper-string-parser": "^7.29.7", "@babel/helper-validator-identifier": "^7.29.7" } }, "sha512-4zBIxpPzowiZpusoFkyGVwakdRJUyuH5PxQ/PrqghfdFWWasvnCdPfQXHrenDai+gyLARulZjZowCOj6fjT4pA=="], + + "@esbuild/aix-ppc64": ["@esbuild/aix-ppc64@0.21.5", "", { "os": "aix", "cpu": "ppc64" }, "sha512-1SDgH6ZSPTlggy1yI6+Dbkiz8xzpHJEVAlF/AM1tHPLsf5STom9rwtjE4hKAF20FfXXNTFqEYXyJNWh1GiZedQ=="], + + "@esbuild/android-arm": ["@esbuild/android-arm@0.21.5", "", { "os": "android", "cpu": "arm" }, "sha512-vCPvzSjpPHEi1siZdlvAlsPxXl7WbOVUBBAowWug4rJHb68Ox8KualB+1ocNvT5fjv6wpkX6o/iEpbDrf68zcg=="], + + "@esbuild/android-arm64": ["@esbuild/android-arm64@0.21.5", "", { "os": "android", "cpu": "arm64" }, "sha512-c0uX9VAUBQ7dTDCjq+wdyGLowMdtR/GoC2U5IYk/7D1H1JYC0qseD7+11iMP2mRLN9RcCMRcjC4YMclCzGwS/A=="], + + "@esbuild/android-x64": ["@esbuild/android-x64@0.21.5", "", { "os": "android", "cpu": "x64" }, "sha512-D7aPRUUNHRBwHxzxRvp856rjUHRFW1SdQATKXH2hqA0kAZb1hKmi02OpYRacl0TxIGz/ZmXWlbZgjwWYaCakTA=="], + + "@esbuild/darwin-arm64": ["@esbuild/darwin-arm64@0.21.5", "", { "os": "darwin", "cpu": "arm64" }, "sha512-DwqXqZyuk5AiWWf3UfLiRDJ5EDd49zg6O9wclZ7kUMv2WRFr4HKjXp/5t8JZ11QbQfUS6/cRCKGwYhtNAY88kQ=="], + + "@esbuild/darwin-x64": ["@esbuild/darwin-x64@0.21.5", "", { "os": "darwin", "cpu": "x64" }, "sha512-se/JjF8NlmKVG4kNIuyWMV/22ZaerB+qaSi5MdrXtd6R08kvs2qCN4C09miupktDitvh8jRFflwGFBQcxZRjbw=="], + + "@esbuild/freebsd-arm64": ["@esbuild/freebsd-arm64@0.21.5", "", { "os": "freebsd", "cpu": "arm64" }, "sha512-5JcRxxRDUJLX8JXp/wcBCy3pENnCgBR9bN6JsY4OmhfUtIHe3ZW0mawA7+RDAcMLrMIZaf03NlQiX9DGyB8h4g=="], + + "@esbuild/freebsd-x64": ["@esbuild/freebsd-x64@0.21.5", "", { "os": "freebsd", "cpu": "x64" }, "sha512-J95kNBj1zkbMXtHVH29bBriQygMXqoVQOQYA+ISs0/2l3T9/kj42ow2mpqerRBxDJnmkUDCaQT/dfNXWX/ZZCQ=="], + + "@esbuild/linux-arm": ["@esbuild/linux-arm@0.21.5", "", { "os": "linux", "cpu": "arm" }, "sha512-bPb5AHZtbeNGjCKVZ9UGqGwo8EUu4cLq68E95A53KlxAPRmUyYv2D6F0uUI65XisGOL1hBP5mTronbgo+0bFcA=="], + + "@esbuild/linux-arm64": ["@esbuild/linux-arm64@0.21.5", "", { "os": "linux", "cpu": "arm64" }, "sha512-ibKvmyYzKsBeX8d8I7MH/TMfWDXBF3db4qM6sy+7re0YXya+K1cem3on9XgdT2EQGMu4hQyZhan7TeQ8XkGp4Q=="], + + "@esbuild/linux-ia32": ["@esbuild/linux-ia32@0.21.5", "", { "os": "linux", "cpu": "ia32" }, "sha512-YvjXDqLRqPDl2dvRODYmmhz4rPeVKYvppfGYKSNGdyZkA01046pLWyRKKI3ax8fbJoK5QbxblURkwK/MWY18Tg=="], + + "@esbuild/linux-loong64": ["@esbuild/linux-loong64@0.21.5", "", { "os": "linux", "cpu": "none" }, "sha512-uHf1BmMG8qEvzdrzAqg2SIG/02+4/DHB6a9Kbya0XDvwDEKCoC8ZRWI5JJvNdUjtciBGFQ5PuBlpEOXQj+JQSg=="], + + "@esbuild/linux-mips64el": ["@esbuild/linux-mips64el@0.21.5", "", { "os": "linux", "cpu": "none" }, "sha512-IajOmO+KJK23bj52dFSNCMsz1QP1DqM6cwLUv3W1QwyxkyIWecfafnI555fvSGqEKwjMXVLokcV5ygHW5b3Jbg=="], + + "@esbuild/linux-ppc64": ["@esbuild/linux-ppc64@0.21.5", "", { "os": "linux", "cpu": "ppc64" }, "sha512-1hHV/Z4OEfMwpLO8rp7CvlhBDnjsC3CttJXIhBi+5Aj5r+MBvy4egg7wCbe//hSsT+RvDAG7s81tAvpL2XAE4w=="], + + "@esbuild/linux-riscv64": ["@esbuild/linux-riscv64@0.21.5", "", { "os": "linux", "cpu": "none" }, "sha512-2HdXDMd9GMgTGrPWnJzP2ALSokE/0O5HhTUvWIbD3YdjME8JwvSCnNGBnTThKGEB91OZhzrJ4qIIxk/SBmyDDA=="], + + "@esbuild/linux-s390x": ["@esbuild/linux-s390x@0.21.5", "", { "os": "linux", "cpu": "s390x" }, "sha512-zus5sxzqBJD3eXxwvjN1yQkRepANgxE9lgOW2qLnmr8ikMTphkjgXu1HR01K4FJg8h1kEEDAqDcZQtbrRnB41A=="], + + "@esbuild/linux-x64": ["@esbuild/linux-x64@0.21.5", "", { "os": "linux", "cpu": "x64" }, "sha512-1rYdTpyv03iycF1+BhzrzQJCdOuAOtaqHTWJZCWvijKD2N5Xu0TtVC8/+1faWqcP9iBCWOmjmhoH94dH82BxPQ=="], + + "@esbuild/netbsd-x64": ["@esbuild/netbsd-x64@0.21.5", "", { "os": "none", "cpu": "x64" }, "sha512-Woi2MXzXjMULccIwMnLciyZH4nCIMpWQAs049KEeMvOcNADVxo0UBIQPfSmxB3CWKedngg7sWZdLvLczpe0tLg=="], + + "@esbuild/openbsd-x64": ["@esbuild/openbsd-x64@0.21.5", "", { "os": "openbsd", "cpu": "x64" }, "sha512-HLNNw99xsvx12lFBUwoT8EVCsSvRNDVxNpjZ7bPn947b8gJPzeHWyNVhFsaerc0n3TsbOINvRP2byTZ5LKezow=="], + + "@esbuild/sunos-x64": ["@esbuild/sunos-x64@0.21.5", "", { "os": "sunos", "cpu": "x64" }, "sha512-6+gjmFpfy0BHU5Tpptkuh8+uw3mnrvgs+dSPQXQOv3ekbordwnzTVEb4qnIvQcYXq6gzkyTnoZ9dZG+D4garKg=="], + + "@esbuild/win32-arm64": ["@esbuild/win32-arm64@0.21.5", "", { "os": "win32", "cpu": "arm64" }, "sha512-Z0gOTd75VvXqyq7nsl93zwahcTROgqvuAcYDUr+vOv8uHhNSKROyU961kgtCD1e95IqPKSQKH7tBTslnS3tA8A=="], + + "@esbuild/win32-ia32": ["@esbuild/win32-ia32@0.21.5", "", { "os": "win32", "cpu": "ia32" }, "sha512-SWXFF1CL2RVNMaVs+BBClwtfZSvDgtL//G/smwAc5oVK/UPu2Gu9tIaRgFmYFFKrmg3SyAjSrElf0TiJ1v8fYA=="], + + "@esbuild/win32-x64": ["@esbuild/win32-x64@0.21.5", "", { "os": "win32", "cpu": "x64" }, "sha512-tQd/1efJuzPC6rCFwEvLtci/xNFcTZknmXs98FYDfGE4wP9ClFV98nyKrzJKVPMhdDnjzLhdUyMX4PsQAPjwIw=="], + + "@jridgewell/sourcemap-codec": ["@jridgewell/sourcemap-codec@1.5.5", "", {}, "sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og=="], + + "@nychthemeron/library": ["@nychthemeron/library@0.0.1", "https://git.mcpeakdev.com/api/packages/McPeakDev/npm/%40nychthemeron%2Flibrary/-/0.0.1/library-0.0.1.tgz", { "peerDependencies": { "primevue": "^4.5.0", "vue": "^3.5.0" } }, "sha512-84pcTnF8Ead8D7TSLhKTS8ACpaOCTS0mylzkWqgGrNs4fnrH9tEJg874nFHegiFy5P1fuKCk4B7Yt/Pjc4NK/Q=="], + + "@primeuix/styled": ["@primeuix/styled@0.7.4", "", { "dependencies": { "@primeuix/utils": "^0.6.1" } }, "sha512-QSO/NpOQg8e9BONWRBx9y8VGMCMYz0J/uKfNJEya/RGEu7ARx0oYW0ugI1N3/KB1AAvyGxzKBzGImbwg0KUiOQ=="], + + "@primeuix/styles": ["@primeuix/styles@2.0.3", "", { "dependencies": { "@primeuix/styled": "^0.7.4" } }, "sha512-2ykAB6BaHzR/6TwF8ShpJTsZrid6cVIEBVlookSdvOdmlWuevGu5vWOScgIwqWwlZcvkFYAGR/SUV3OHCTBMdw=="], + + "@primeuix/utils": ["@primeuix/utils@0.6.4", "", {}, "sha512-pZ5f+vj7wSzRhC7KoEQRU5fvYAe+RP9+m39CTscZ3UywCD1Y2o6Fe1rRgklMPSkzUcty2jzkA0zMYkiJBD1hgg=="], + + "@primevue/core": ["@primevue/core@4.5.5", "", { "dependencies": { "@primeuix/styled": "^0.7.4", "@primeuix/utils": "^0.6.2" }, "peerDependencies": { "vue": "^3.5.0" } }, "sha512-JpkXhq1ddc70JdsC3CC4dM+UbeeWuCW/8DpS9dNBfrOk824TLSlRlMEGFyVKqRMn5WPQvYLiy3xXfLQeNdSqhQ=="], + + "@primevue/icons": ["@primevue/icons@4.5.5", "", { "dependencies": { "@primeuix/utils": "^0.6.2", "@primevue/core": "4.5.5" } }, "sha512-eteOhTdAOXEYE9qW1AOrBBgDxQ2szHJxSkEK1XVdV2TKxGM5FQf03Ovms0VDyZTc16XBIgvwYjXJQS0BPbhPaA=="], + + "@rollup/rollup-android-arm-eabi": ["@rollup/rollup-android-arm-eabi@4.62.0", "", { "os": "android", "cpu": "arm" }, "sha512-IPIQ55ythEHkfEd9jMEi32OQ7SxURsGA43JI22lj01OLZNt2NUbJX8YUHxkVWyQ6daHPNn0truF5nSj3DQp6YQ=="], + + "@rollup/rollup-android-arm64": ["@rollup/rollup-android-arm64@4.62.0", "", { "os": "android", "cpu": "arm64" }, "sha512-M6s9cr10MibETyo8JsOkq+Lo1+lU6hcvb1MApnUql5qte/5hMEgzlN8/ReIKNfRV8rrqX50W1BX9zoUhC192RA=="], + + "@rollup/rollup-darwin-arm64": ["@rollup/rollup-darwin-arm64@4.62.0", "", { "os": "darwin", "cpu": "arm64" }, "sha512-BqCoMoIbn0keKys+dEAdBa70EtOwV1bEsQCUgU9FdiZmmMge/Zk7LlkYGqbrdHR+Frnt0E1FOanly+rlwvvQzw=="], + + "@rollup/rollup-darwin-x64": ["@rollup/rollup-darwin-x64@4.62.0", "", { "os": "darwin", "cpu": "x64" }, "sha512-SIMzST3VFNXDAbeIWDWiFCNM5qncUBDWaEV7NfE7oZbDt2mgfW4MvbKdbYiGOLoM32gbTv608UMd0XktEYSD7w=="], + + "@rollup/rollup-freebsd-arm64": ["@rollup/rollup-freebsd-arm64@4.62.0", "", { "os": "freebsd", "cpu": "arm64" }, "sha512-ezjfSQMP7ArdUsbBwbQIfwAlhE84I2iVnzQNCFSveqV42q+BmKlzVpf7mxv5EchLcoWU4y6/heFzVg1F+hodUQ=="], + + "@rollup/rollup-freebsd-x64": ["@rollup/rollup-freebsd-x64@4.62.0", "", { "os": "freebsd", "cpu": "x64" }, "sha512-9+qTWGW9AZRhnUgwtTwzNwcPlL87ngkeN0LA+q1bADvmY9aNvWaF2TFW8BZgnQPYxpDI7+rMVLivcd4V737TAQ=="], + + "@rollup/rollup-linux-arm-gnueabihf": ["@rollup/rollup-linux-arm-gnueabihf@4.62.0", "", { "os": "linux", "cpu": "arm" }, "sha512-T1dMEQhXA/jkJ/jyMIw9IovK8bSUq7A8kLIlvZTb/6YIVsp2zLavr4F3oyllHWo7eIVJRyE5n3tUjQJEbE1IuQ=="], + + "@rollup/rollup-linux-arm-musleabihf": ["@rollup/rollup-linux-arm-musleabihf@4.62.0", "", { "os": "linux", "cpu": "arm" }, "sha512-2as0LgT7qQpyceQq6VUJYnumUMUrgGQCWIiDIN9DE0/tglsk6o66uCB4f3djRawAltvfCNLyZZrsqbPA6inCsA=="], + + "@rollup/rollup-linux-arm64-gnu": ["@rollup/rollup-linux-arm64-gnu@4.62.0", "", { "os": "linux", "cpu": "arm64" }, "sha512-bVURMg+6eNN9C/yc0aVjooZcwTTtYF4YW3xta5pP0//r3o1V8gXEHXWCndj47w/HhwsFroZrFhR+6uQP5T0n0g=="], + + "@rollup/rollup-linux-arm64-musl": ["@rollup/rollup-linux-arm64-musl@4.62.0", "", { "os": "linux", "cpu": "arm64" }, "sha512-Ful8pM/2yYI83PViWdFdpZhdI8HJ5qsXANe5atypbHDf+KIBBDsZsbyy8hbXnULVvW9NsTh5DHwbcBftyLTfiw=="], + + "@rollup/rollup-linux-loong64-gnu": ["@rollup/rollup-linux-loong64-gnu@4.62.0", "", { "os": "linux", "cpu": "none" }, "sha512-9Gp/DgrkzfUBmNPVTyPTvay+4xEP7M/clXpj3efXBcm6uTIVIgDg4rqUpqKXvLEuFRVuEpSAOkhgNeecvaZ4Cg=="], + + "@rollup/rollup-linux-loong64-musl": ["@rollup/rollup-linux-loong64-musl@4.62.0", "", { "os": "linux", "cpu": "none" }, "sha512-m9tsJz54LUXkSYM8+8PG81B9IKK5r+2T0clMq4QrS16xFosufU7firBDAZEsDheDs7wTlP7h3++S7lMsU955HA=="], + + "@rollup/rollup-linux-ppc64-gnu": ["@rollup/rollup-linux-ppc64-gnu@4.62.0", "", { "os": "linux", "cpu": "ppc64" }, "sha512-3UvJ5PNVU16aJf6M3tFI24pWzAl2/ynfbyRN3ICyQajK1lSkrnVYNnLz3v04J32qKa0FczJc22zeToc0lr2A3w=="], + + "@rollup/rollup-linux-ppc64-musl": ["@rollup/rollup-linux-ppc64-musl@4.62.0", "", { "os": "linux", "cpu": "ppc64" }, "sha512-vRWUAbYLGHBZS6Q8Msb2sfnf1fvJf+47t8l/TwOerM2qArzy+IeNMTHrYLHXh95h8MoatPHI5hhSZNs+mGXKPg=="], + + "@rollup/rollup-linux-riscv64-gnu": ["@rollup/rollup-linux-riscv64-gnu@4.62.0", "", { "os": "linux", "cpu": "none" }, "sha512-c00T5SYENHAt86cfW47URaP3Us5vLC/4QO7GYud1G5VNRffCwwCuBspwqYrriuJB+5m0WFzClCn9wed0FBjKvg=="], + + "@rollup/rollup-linux-riscv64-musl": ["@rollup/rollup-linux-riscv64-musl@4.62.0", "", { "os": "linux", "cpu": "none" }, "sha512-krrCDilhXOwFkSkO3Wm9I/f9H0L92XHHwy2fwxjukxIbh0dem8gZqOW5Y8BsHrpJv5qwlRBV+Wl4ZFyRWhUpwg=="], + + "@rollup/rollup-linux-s390x-gnu": ["@rollup/rollup-linux-s390x-gnu@4.62.0", "", { "os": "linux", "cpu": "s390x" }, "sha512-7pfYFSTc4/rUC/FtAI0Qp6QthDBCIi6/AuP1xYqFk5vanI6KnL5dWKP60OM/05LOsbwTmIcvr6eXC4CJuJ75IA=="], + + "@rollup/rollup-linux-x64-gnu": ["@rollup/rollup-linux-x64-gnu@4.62.0", "", { "os": "linux", "cpu": "x64" }, "sha512-7SDIalKeIpG0Ifogbbdn58HmSotYMlf23K3dCJEmiVd9Fg36Vmni82iPQec27N3wY4Bvbxftkxz6vSx9OcouTg=="], + + "@rollup/rollup-linux-x64-musl": ["@rollup/rollup-linux-x64-musl@4.62.0", "", { "os": "linux", "cpu": "x64" }, "sha512-eRZevouTH2i1HeAVLqJuLnt256krQkGY0TN6WsTmsIhuzbh457HuWDMakKwmi0Cjadux983CoSr8Lim2QhUIFw=="], + + "@rollup/rollup-openbsd-x64": ["@rollup/rollup-openbsd-x64@4.62.0", "", { "os": "openbsd", "cpu": "x64" }, "sha512-3oVS7FLGa4U1qcvao9ylGxrjXZyUQqR8UwxEcnUEyPX53O/C/mKDZegNXTdHCP+h3e6ta/f1EN38Yif1mmZHYg=="], + + "@rollup/rollup-openharmony-arm64": ["@rollup/rollup-openharmony-arm64@4.62.0", "", { "os": "none", "cpu": "arm64" }, "sha512-yTB9TgfWj5wHe5QgktAgXTLLot1gvEjl1NiPPAUiCs4oPrIWFl5V4nC3GrkNdj9LaAU4s94nVrGbGOCqUpyWsg=="], + + "@rollup/rollup-win32-arm64-msvc": ["@rollup/rollup-win32-arm64-msvc@4.62.0", "", { "os": "win32", "cpu": "arm64" }, "sha512-5LOhoaesY3doG1c+ac/2JtgREpKoJr5bUHH8tKY0V8di7+uSV6BwLs2PlR0/yzefGOkR+wE7ZolZphHCsyG5Rw=="], + + "@rollup/rollup-win32-ia32-msvc": ["@rollup/rollup-win32-ia32-msvc@4.62.0", "", { "os": "win32", "cpu": "ia32" }, "sha512-yYkWHhmbhRTWTnWos5HC4GcPQfjlzzCNbM9e/+GXrLuaBXYA3qSDR9f0Vgufd5S8yX81U8jPKp7ZnAjZFMtRnw=="], + + "@rollup/rollup-win32-x64-gnu": ["@rollup/rollup-win32-x64-gnu@4.62.0", "", { "os": "win32", "cpu": "x64" }, "sha512-SoTb6lPg25xZlA2ibwQ++ahCCnH+FP0qmEuafMJ4gznZKOlXioKEAeJLgCrqjM98ACziXM9V1amFjICVL4IFoA=="], + + "@rollup/rollup-win32-x64-msvc": ["@rollup/rollup-win32-x64-msvc@4.62.0", "", { "os": "win32", "cpu": "x64" }, "sha512-5L+T1fMX4RIEBoZzT0+sQ0PhTS36NULFmMXtl1TZo44TMAROIMHbZufSOjVWt/Y622BtxgxtaNOokbTDvfsrZA=="], + + "@types/estree": ["@types/estree@1.0.9", "", {}, "sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg=="], + + "@vitejs/plugin-vue": ["@vitejs/plugin-vue@5.2.4", "", { "peerDependencies": { "vite": "^5.0.0 || ^6.0.0", "vue": "^3.2.25" } }, "sha512-7Yx/SXSOcQq5HiiV3orevHUFn+pmMB4cgbEkDYgnkUWb0WfeQ/wa2yFv6D5ICiCQOVpjA7vYDXrC7AGO8yjDHA=="], + + "@volar/language-core": ["@volar/language-core@2.4.15", "", { "dependencies": { "@volar/source-map": "2.4.15" } }, "sha512-3VHw+QZU0ZG9IuQmzT68IyN4hZNd9GchGPhbD9+pa8CVv7rnoOZwo7T8weIbrRmihqy3ATpdfXFnqRrfPVK6CA=="], + + "@volar/source-map": ["@volar/source-map@2.4.15", "", {}, "sha512-CPbMWlUN6hVZJYGcU/GSoHu4EnCHiLaXI9n8c9la6RaI9W5JHX+NqG+GSQcB0JdC2FIBLdZJwGsfKyBB71VlTg=="], + + "@volar/typescript": ["@volar/typescript@2.4.15", "", { "dependencies": { "@volar/language-core": "2.4.15", "path-browserify": "^1.0.1", "vscode-uri": "^3.0.8" } }, "sha512-2aZ8i0cqPGjXb4BhkMsPYDkkuc2ZQ6yOpqwAuNwUoncELqoy5fRgOQtLR9gB0g902iS0NAkvpIzs27geVyVdPg=="], + + "@vue/compiler-core": ["@vue/compiler-core@3.5.38", "", { "dependencies": { "@babel/parser": "^7.29.7", "@vue/shared": "3.5.38", "entities": "^7.0.1", "estree-walker": "^2.0.2", "source-map-js": "^1.2.1" } }, "sha512-s99aGxWYig9ErHbct27KXEGhrBYlRI6c4MwAgXErOAbX9xiW37/uMa+XUDO69zLz83dng8UUZ70CTOJrLrYrEQ=="], + + "@vue/compiler-dom": ["@vue/compiler-dom@3.5.38", "", { "dependencies": { "@vue/compiler-core": "3.5.38", "@vue/shared": "3.5.38" } }, "sha512-JTqp25l8aFfJYF7/KmsXZjAxJz7T+SjmTJLoXVjHtc2BrSgSiW2n9Aem/cWq1OPe68A8JL06B3eVdhlP0H4TVw=="], + + "@vue/compiler-sfc": ["@vue/compiler-sfc@3.5.38", "", { "dependencies": { "@babel/parser": "^7.29.7", "@vue/compiler-core": "3.5.38", "@vue/compiler-dom": "3.5.38", "@vue/compiler-ssr": "3.5.38", "@vue/shared": "3.5.38", "estree-walker": "^2.0.2", "magic-string": "^0.30.21", "postcss": "^8.5.15", "source-map-js": "^1.2.1" } }, "sha512-DuA2GiZawSEW442iw/9+Fkol8hTgb4Ke5KkhmSry65QA7YuyMbIdy8p0XZRMvNwJdgRz307W8g1CSzdvS4nuNg=="], + + "@vue/compiler-ssr": ["@vue/compiler-ssr@3.5.38", "", { "dependencies": { "@vue/compiler-dom": "3.5.38", "@vue/shared": "3.5.38" } }, "sha512-7s+W5Gc42FGxZMcuwl8H5B29T8BJPMdBT7KHFE+BbAuZ/iTEdTtv7z2XiMjiaUUw4w3ZcCEdHs36RuYJ2VA7bA=="], + + "@vue/compiler-vue2": ["@vue/compiler-vue2@2.7.16", "", { "dependencies": { "de-indent": "^1.0.2", "he": "^1.2.0" } }, "sha512-qYC3Psj9S/mfu9uVi5WvNZIzq+xnXMhOwbTFKKDD7b1lhpnn71jXSFdTQ+WsIEk0ONCd7VV2IMm7ONl6tbQ86A=="], + + "@vue/devtools-api": ["@vue/devtools-api@6.6.4", "", {}, "sha512-sGhTPMuXqZ1rVOk32RylztWkfXTRhuS7vgAKv0zjqk8gbsHkJ7xfFf+jbySxt7tWObEJwyKaHMikV/WGDiQm8g=="], + + "@vue/language-core": ["@vue/language-core@2.2.12", "", { "dependencies": { "@volar/language-core": "2.4.15", "@vue/compiler-dom": "^3.5.0", "@vue/compiler-vue2": "^2.7.16", "@vue/shared": "^3.5.0", "alien-signals": "^1.0.3", "minimatch": "^9.0.3", "muggle-string": "^0.4.1", "path-browserify": "^1.0.1" }, "peerDependencies": { "typescript": "*" }, "optionalPeers": ["typescript"] }, "sha512-IsGljWbKGU1MZpBPN+BvPAdr55YPkj2nB/TBNGNC32Vy2qLG25DYu/NBN2vNtZqdRbTRjaoYrahLrToim2NanA=="], + + "@vue/reactivity": ["@vue/reactivity@3.5.38", "", { "dependencies": { "@vue/shared": "3.5.38" } }, "sha512-pG6LV/NDNRbKizcUjFFLAfjaL8mcv4DmR9avNcUw2gDHBzZneuS2TWCmp633ynzxz9YYKNeEPK2I8Wraqy2HUQ=="], + + "@vue/runtime-core": ["@vue/runtime-core@3.5.38", "", { "dependencies": { "@vue/reactivity": "3.5.38", "@vue/shared": "3.5.38" } }, "sha512-iyW8WVfF1CpCXxncZY5Ei6rSd6oZr5DgEom//fUjRBRl56AXPD+s9ATvukRt77ZFTuYlnVA1bxY+dJB94tWVYw=="], + + "@vue/runtime-dom": ["@vue/runtime-dom@3.5.38", "", { "dependencies": { "@vue/reactivity": "3.5.38", "@vue/runtime-core": "3.5.38", "@vue/shared": "3.5.38", "csstype": "^3.2.3" } }, "sha512-apX2wt9sdfDshS+a2xueFZLVpt0GkRJZSoPmrW/SA4yzXTznhfcMVW59gr7h4YQeY0vJhdJkk2rsIDwgfFgC5A=="], + + "@vue/server-renderer": ["@vue/server-renderer@3.5.38", "", { "dependencies": { "@vue/compiler-ssr": "3.5.38", "@vue/shared": "3.5.38" }, "peerDependencies": { "vue": "3.5.38" } }, "sha512-vue8vbf2QlV4quHqzwmJy6dWfmRhP1J8l4wtZg60CL6VoKqcPY2oe7may3+1d9qfpedjK5PRLFqd5k3Isj9mUw=="], + + "@vue/shared": ["@vue/shared@3.5.38", "", {}, "sha512-FTW0AFZNaK5/mOqvGBwVfUlNLU38TiQn4+DQgIFUnrBBJQ1crMJ82yeGQLV5jyKFsO8yRukpbuP7x+nRbH6aug=="], + + "alien-signals": ["alien-signals@1.0.13", "", {}, "sha512-OGj9yyTnJEttvzhTUWuscOvtqxq5vrhF7vL9oS0xJ2mK0ItPYP1/y+vCFebfxoEyAz0++1AIwJ5CMr+Fk3nDmg=="], + + "balanced-match": ["balanced-match@1.0.2", "", {}, "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw=="], + + "brace-expansion": ["brace-expansion@2.1.1", "", { "dependencies": { "balanced-match": "^1.0.0" } }, "sha512-WR1cURNjuvBLMZBMbqM0UoE+WAfdUcEV1ccD8PVBVOI+Z3ND4+SZbN8RsfT2bMuG1qwz5RFvPukSZm5fF2D5eA=="], + + "csstype": ["csstype@3.2.3", "", {}, "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ=="], + + "de-indent": ["de-indent@1.0.2", "", {}, "sha512-e/1zu3xH5MQryN2zdVaF0OrdNLUbvWxzMbi+iNA6Bky7l1RoP8a2fIbRocyHclXt/arDrrR6lL3TqFD9pMQTsg=="], + + "entities": ["entities@7.0.1", "", {}, "sha512-TWrgLOFUQTH994YUyl1yT4uyavY5nNB5muff+RtWaqNVCAK408b5ZnnbNAUEWLTCpum9w6arT70i1XdQ4UeOPA=="], + + "esbuild": ["esbuild@0.21.5", "", { "optionalDependencies": { "@esbuild/aix-ppc64": "0.21.5", "@esbuild/android-arm": "0.21.5", "@esbuild/android-arm64": "0.21.5", "@esbuild/android-x64": "0.21.5", "@esbuild/darwin-arm64": "0.21.5", "@esbuild/darwin-x64": "0.21.5", "@esbuild/freebsd-arm64": "0.21.5", "@esbuild/freebsd-x64": "0.21.5", "@esbuild/linux-arm": "0.21.5", "@esbuild/linux-arm64": "0.21.5", "@esbuild/linux-ia32": "0.21.5", "@esbuild/linux-loong64": "0.21.5", "@esbuild/linux-mips64el": "0.21.5", "@esbuild/linux-ppc64": "0.21.5", "@esbuild/linux-riscv64": "0.21.5", "@esbuild/linux-s390x": "0.21.5", "@esbuild/linux-x64": "0.21.5", "@esbuild/netbsd-x64": "0.21.5", "@esbuild/openbsd-x64": "0.21.5", "@esbuild/sunos-x64": "0.21.5", "@esbuild/win32-arm64": "0.21.5", "@esbuild/win32-ia32": "0.21.5", "@esbuild/win32-x64": "0.21.5" }, "bin": { "esbuild": "bin/esbuild" } }, "sha512-mg3OPMV4hXywwpoDxu3Qda5xCKQi+vCTZq8S9J/EpkhB2HzKXq4SNFZE3+NK93JYxc8VMSep+lOUSC/RVKaBqw=="], + + "estree-walker": ["estree-walker@2.0.2", "", {}, "sha512-Rfkk/Mp/DL7JVje3u18FxFujQlTNR2q6QfMSMB7AvCBx91NGj/ba3kCfza0f6dVDbw7YlRf/nDrn7pQrCCyQ/w=="], + + "fsevents": ["fsevents@2.3.3", "", { "os": "darwin" }, "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw=="], + + "he": ["he@1.2.0", "", { "bin": { "he": "bin/he" } }, "sha512-F/1DnUGPopORZi0ni+CvrCgHQ5FyEAHRLSApuYWMmrbSwoN2Mn/7k+Gl38gJnR7yyDZk6WLXwiGod1JOWNDKGw=="], + + "magic-string": ["magic-string@0.30.21", "", { "dependencies": { "@jridgewell/sourcemap-codec": "^1.5.5" } }, "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ=="], + + "minimatch": ["minimatch@9.0.9", "", { "dependencies": { "brace-expansion": "^2.0.2" } }, "sha512-OBwBN9AL4dqmETlpS2zasx+vTeWclWzkblfZk7KTA5j3jeOONz/tRCnZomUyvNg83wL5Zv9Ss6HMJXAgL8R2Yg=="], + + "muggle-string": ["muggle-string@0.4.1", "", {}, "sha512-VNTrAak/KhO2i8dqqnqnAHOa3cYBwXEZe9h+D5h/1ZqFSTEFHdM65lR7RoIqq3tBBYavsOXV84NoHXZ0AkPyqQ=="], + + "nanoid": ["nanoid@3.3.12", "", { "bin": { "nanoid": "bin/nanoid.cjs" } }, "sha512-ZB9RH/39qpq5Vu6Y+NmUaFhQR6pp+M2Xt76XBnEwDaGcVAqhlvxrl3B2bKS5D3NH3QR76v3aSrKaF/Kiy7lEtQ=="], + + "path-browserify": ["path-browserify@1.0.1", "", {}, "sha512-b7uo2UCUOYZcnF/3ID0lulOJi/bafxa1xPe7ZPsammBSpjSWQkjNxlt635YGS2MiR9GjvuXCtz2emr3jbsz98g=="], + + "picocolors": ["picocolors@1.1.1", "", {}, "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA=="], + + "pinia": ["pinia@2.3.1", "", { "dependencies": { "@vue/devtools-api": "^6.6.3", "vue-demi": "^0.14.10" }, "peerDependencies": { "typescript": ">=4.4.4", "vue": "^2.7.0 || ^3.5.11" }, "optionalPeers": ["typescript"] }, "sha512-khUlZSwt9xXCaTbbxFYBKDc/bWAGWJjOgvxETwkTN7KRm66EeT1ZdZj6i2ceh9sP2Pzqsbc704r2yngBrxBVug=="], + + "postcss": ["postcss@8.5.15", "", { "dependencies": { "nanoid": "^3.3.12", "picocolors": "^1.1.1", "source-map-js": "^1.2.1" } }, "sha512-FfR8sjd4em2T6fb3I2MwAJU7HWVMr9zba+enmQeeWFfCbm+UOC/0X4DS8XtpUTMwWMGbjKYP7xjfNekzyGmB3A=="], + + "primevue": ["primevue@4.5.5", "", { "dependencies": { "@primeuix/styled": "^0.7.4", "@primeuix/styles": "^2.0.3", "@primeuix/utils": "^0.6.2", "@primevue/core": "4.5.5", "@primevue/icons": "4.5.5" } }, "sha512-Kv5REIewCdP806QaoU+4nBXfmpzOGFKkZ9qH4KsL6MjiAQVc4PUzypt8erl4r3Vzh3nr3aWZIxkxYRRsLGiX2A=="], + + "rollup": ["rollup@4.62.0", "", { "dependencies": { "@types/estree": "1.0.9" }, "optionalDependencies": { "@rollup/rollup-android-arm-eabi": "4.62.0", "@rollup/rollup-android-arm64": "4.62.0", "@rollup/rollup-darwin-arm64": "4.62.0", "@rollup/rollup-darwin-x64": "4.62.0", "@rollup/rollup-freebsd-arm64": "4.62.0", "@rollup/rollup-freebsd-x64": "4.62.0", "@rollup/rollup-linux-arm-gnueabihf": "4.62.0", "@rollup/rollup-linux-arm-musleabihf": "4.62.0", "@rollup/rollup-linux-arm64-gnu": "4.62.0", "@rollup/rollup-linux-arm64-musl": "4.62.0", "@rollup/rollup-linux-loong64-gnu": "4.62.0", "@rollup/rollup-linux-loong64-musl": "4.62.0", "@rollup/rollup-linux-ppc64-gnu": "4.62.0", "@rollup/rollup-linux-ppc64-musl": "4.62.0", "@rollup/rollup-linux-riscv64-gnu": "4.62.0", "@rollup/rollup-linux-riscv64-musl": "4.62.0", "@rollup/rollup-linux-s390x-gnu": "4.62.0", "@rollup/rollup-linux-x64-gnu": "4.62.0", "@rollup/rollup-linux-x64-musl": "4.62.0", "@rollup/rollup-openbsd-x64": "4.62.0", "@rollup/rollup-openharmony-arm64": "4.62.0", "@rollup/rollup-win32-arm64-msvc": "4.62.0", "@rollup/rollup-win32-ia32-msvc": "4.62.0", "@rollup/rollup-win32-x64-gnu": "4.62.0", "@rollup/rollup-win32-x64-msvc": "4.62.0", "fsevents": "~2.3.2" }, "bin": { "rollup": "dist/bin/rollup" } }, "sha512-nc72Wgq62I7rtDV4izT5/aaS0zxy3kttkinf9586ApknY3jZO9NYsmtc24fUckA0X7Q2v+ML4a15pdUlV5V/jA=="], + + "source-map-js": ["source-map-js@1.2.1", "", {}, "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA=="], + + "typescript": ["typescript@5.9.3", "", { "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" } }, "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw=="], + + "vite": ["vite@5.4.21", "", { "dependencies": { "esbuild": "^0.21.3", "postcss": "^8.4.43", "rollup": "^4.20.0" }, "optionalDependencies": { "fsevents": "~2.3.3" }, "peerDependencies": { "@types/node": "^18.0.0 || >=20.0.0", "less": "*", "lightningcss": "^1.21.0", "sass": "*", "sass-embedded": "*", "stylus": "*", "sugarss": "*", "terser": "^5.4.0" }, "optionalPeers": ["@types/node", "less", "lightningcss", "sass", "sass-embedded", "stylus", "sugarss", "terser"], "bin": { "vite": "bin/vite.js" } }, "sha512-o5a9xKjbtuhY6Bi5S3+HvbRERmouabWbyUcpXXUA1u+GNUKoROi9byOJ8M0nHbHYHkYICiMlqxkg1KkYmm25Sw=="], + + "vscode-uri": ["vscode-uri@3.1.0", "", {}, "sha512-/BpdSx+yCQGnCvecbyXdxHDkuk55/G3xwnC0GqY4gmQ3j+A+g8kzzgB4Nk/SINjqn6+waqw3EgbVF2QKExkRxQ=="], + + "vue": ["vue@3.5.38", "", { "dependencies": { "@vue/compiler-dom": "3.5.38", "@vue/compiler-sfc": "3.5.38", "@vue/runtime-dom": "3.5.38", "@vue/server-renderer": "3.5.38", "@vue/shared": "3.5.38" }, "peerDependencies": { "typescript": "*" }, "optionalPeers": ["typescript"] }, "sha512-vAMKHfImQlYSy0C+PBue4s3ERZ2xGKfgZg5GXAsLInq1dyh2H78ILVP5sK0KPFPVW4kv+OGCIvBEondcjpZp7A=="], + + "vue-demi": ["vue-demi@0.14.10", "", { "peerDependencies": { "@vue/composition-api": "^1.0.0-rc.1", "vue": "^3.0.0-0 || ^2.6.0" }, "optionalPeers": ["@vue/composition-api"], "bin": { "vue-demi-fix": "bin/vue-demi-fix.js", "vue-demi-switch": "bin/vue-demi-switch.js" } }, "sha512-nMZBOwuzabUO0nLgIcc6rycZEebF6eeUfaiQx9+WSk8e29IbLvPU9feI6tqW4kTo3hvoYAJkMh8n8D0fuISphg=="], + + "vue-router": ["vue-router@4.6.4", "", { "dependencies": { "@vue/devtools-api": "^6.6.4" }, "peerDependencies": { "vue": "^3.5.0" } }, "sha512-Hz9q5sa33Yhduglwz6g9skT8OBPii+4bFn88w6J+J4MfEo4KRRpmiNG/hHHkdbRFlLBOqxN8y8gf2Fb0MTUgVg=="], + + "vue-tsc": ["vue-tsc@2.2.12", "", { "dependencies": { "@volar/typescript": "2.4.15", "@vue/language-core": "2.2.12" }, "peerDependencies": { "typescript": ">=5.0.0" }, "bin": { "vue-tsc": "./bin/vue-tsc.js" } }, "sha512-P7OP77b2h/Pmk+lZdJ0YWs+5tJ6J2+uOQPo7tlBnY44QqQSPYvS0qVT4wqDJgwrZaLe47etJLLQRFia71GYITw=="], + } +} diff --git a/ui/index.html b/ui/index.html new file mode 100644 index 0000000..e66c144 --- /dev/null +++ b/ui/index.html @@ -0,0 +1,13 @@ + + + + + + Mercury + + + +
+ + + diff --git a/ui/package.json b/ui/package.json new file mode 100644 index 0000000..4e2e8ae --- /dev/null +++ b/ui/package.json @@ -0,0 +1,23 @@ +{ + "name": "mercury-ui", + "private": true, + "version": "0.1.0", + "type": "module", + "scripts": { + "dev": "vite", + "build": "vue-tsc --noEmit && vite build", + "preview": "vite preview" + }, + "dependencies": { + "@nychthemeron/library": "latest", + "pinia": "^2.1.0", + "vue": "^3.4.0", + "vue-router": "^4.3.0" + }, + "devDependencies": { + "@vitejs/plugin-vue": "^5.0.0", + "typescript": "^5.3.0", + "vite": "^5.0.0", + "vue-tsc": "^2.0.0" + } +} diff --git a/ui/public/favicon.svg b/ui/public/favicon.svg new file mode 100644 index 0000000..12fae39 --- /dev/null +++ b/ui/public/favicon.svg @@ -0,0 +1,13 @@ + + + + + + + + + + + + + diff --git a/ui/src/App.vue b/ui/src/App.vue new file mode 100644 index 0000000..7c2aa3f --- /dev/null +++ b/ui/src/App.vue @@ -0,0 +1,3 @@ + diff --git a/ui/src/assets/main.css b/ui/src/assets/main.css new file mode 100644 index 0000000..65ef861 --- /dev/null +++ b/ui/src/assets/main.css @@ -0,0 +1,278 @@ +*, +*::before, +*::after { + box-sizing: border-box; + -webkit-font-smoothing: antialiased; + -moz-osx-font-smoothing: grayscale; + text-rendering: optimizeLegibility; +} + +body { + margin: 0; + font-family: var(--font-serif); + background-color: var(--surface-0); + color: var(--text-body); + min-height: 100vh; +} + +h1, +h2, +h3 { + font-family: var(--font-serif); + font-weight: 600; /* Cinzel's actual heaviest weight — avoids synthetic bold */ + font-optical-sizing: auto; + color: var(--text-high); + margin: 0; + letter-spacing: 0.06em; +} + +a { + color: var(--primary); + text-decoration: none; +} +a:hover { + text-decoration: underline; +} + +code { + font-family: var(--font-mono); + font-size: 0.85em; + color: var(--text-label); + background: var(--surface-2); + padding: 0.1em 0.4em; + border-radius: 3px; + border: 1px solid var(--border-lo); +} + +/* ── Page header ────────────────────────────────────────── */ +.page-header { + display: flex; + justify-content: space-between; + align-items: flex-end; + margin-bottom: 1.75rem; +} + +.page-title { + display: flex; + flex-direction: column; + gap: 0.25rem; +} + +.page-title h2 { + font-size: 1.6rem; + line-height: 1; +} + +.page-title .subtitle { + font-family: var(--font-sans); + font-size: 0.8rem; + color: var(--text-muted); + letter-spacing: 0.02em; +} + +/* ── Table card ─────────────────────────────────────────── */ +.table-card { + background-color: var(--surface-1); + border: 1px solid var(--border); + border-radius: 12px; + box-shadow: + 0 4px 24px rgba(0, 0, 0, 0.07), + 0 1px 4px rgba(0, 0, 0, 0.05); + overflow: hidden; +} + +/* Scroll wrapper sits inside the card so the header stays pinned */ +.table-scroll { + overflow-x: auto; +} + +.table-card-header { + display: flex; + align-items: center; + justify-content: space-between; + padding: 0.875rem 1.25rem; + border-bottom: 1px solid var(--border); + background: var(--surface-2); +} + +.table-card-header .count { + font-size: 0.78rem; + color: var(--text-muted); + font-family: var(--font-mono); +} + +.data-table { + width: 100%; + min-width: max-content; + border-collapse: collapse; + font-family: var(--font-serif); + font-size: 0.875rem; +} + +.data-table th { + padding: 0.65rem 1.25rem; + text-align: left; + background-color: var(--surface-2); + border-bottom: 1px solid var(--border); + font-weight: 700; + font-size: 0.7rem; + color: var(--text-muted); + letter-spacing: 0.1em; + text-transform: uppercase; +} + +.data-table td { + padding: 0.8rem 1.25rem; + text-align: left; + border-bottom: 1px solid var(--border-lo); + color: var(--text-body); + vertical-align: middle; +} + +.data-table tbody tr:last-child td { + border-bottom: none; +} + +.data-table tbody tr { + transition: background-color 0.12s ease; +} + +.data-table tbody tr:hover td { + background: color-mix(in srgb, var(--primary) 4%, var(--surface-1)); +} + +.actions-cell { + display: flex; + gap: 0.4rem; +} + +/* ── Empty state ────────────────────────────────────────── */ +.empty-state { + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; + gap: 0.5rem; + padding: 4rem 2rem; + color: var(--text-dim); +} + +.empty-state .empty-icon { + font-size: 2.5rem; + opacity: 0.35; + line-height: 1; +} + +.empty-state .empty-label { + font-family: var(--font-serif); + font-size: 1rem; + letter-spacing: 0.04em; + color: var(--text-muted); +} + +.empty-state .empty-hint { + font-size: 0.8rem; + color: var(--text-dim); +} + +/* ── Dialog form ────────────────────────────────────────── */ +.dialog-form { + display: flex; + flex-direction: column; + gap: 1.1rem; + padding-top: 0.25rem; +} + +.field { + display: flex; + flex-direction: column; + gap: 0.4rem; +} + +.field label { + font-size: 0.72rem; + font-weight: 700; + letter-spacing: 0.09em; + text-transform: uppercase; + color: var(--text-muted); +} + +.field .hint { + margin: 0; + font-size: 0.78rem; + color: var(--text-dim); +} + +.optional { + font-weight: 400; + font-size: 0.72rem; + color: var(--text-dim); + letter-spacing: 0; + text-transform: none; +} + +/* ── Gold divider ───────────────────────────────────────── */ +.gold-rule { + display: flex; + align-items: center; + gap: 0.6rem; + color: var(--primary); + font-size: 0.6rem; + letter-spacing: 0.2em; + opacity: 0.6; +} +.gold-rule::before, +.gold-rule::after { + content: ""; + flex: 1; + height: 1px; + background: linear-gradient( + 90deg, + transparent, + var(--primary), + transparent + ); +} +.nych-dialog { + min-width: 500px; +} + +[class^="nych-button"] { + box-shadow: unset !important; + justify-content: center !important; +} + +[class^="nych-button"]:hover { + box-shadow: 0 0 5px var(--text-high); +} + +.nych-loading-icon .wreath { + transform-box: fill-box; + transform-origin: center; +} + +/* ── Loading spinner ─────────────────────────────────────── */ +@keyframes mercury-spin { + to { transform: rotate(360deg); } +} + +.loading-spinner { + width: 1.25rem; + height: 1.25rem; + border: 2px solid var(--border); + border-top-color: var(--primary); + border-radius: 50%; + animation: mercury-spin 0.7s linear infinite; + flex-shrink: 0; +} + +.loading-overlay { + display: flex; + align-items: center; + justify-content: center; + gap: 0.6rem; + padding: 3rem 2rem; + color: var(--text-muted); + font-size: 0.85rem; + font-family: var(--font-sans); +} diff --git a/ui/src/env.d.ts b/ui/src/env.d.ts new file mode 100644 index 0000000..6ac34fb --- /dev/null +++ b/ui/src/env.d.ts @@ -0,0 +1,7 @@ +/// + +declare module '*.vue' { + import type { DefineComponent } from 'vue' + const component: DefineComponent + export default component +} diff --git a/ui/src/main.ts b/ui/src/main.ts new file mode 100644 index 0000000..92a3949 --- /dev/null +++ b/ui/src/main.ts @@ -0,0 +1,16 @@ +import { createApp } from "vue"; +import '@nychthemeron/library/theme' +import './assets/main.css' +import './stores/theme' +import { createPinia } from "pinia"; +import PrimeVue from "@primevue/core/config"; +import { createNychthemeron } from "@nychthemeron/library"; +import App from "./App.vue"; +import router from "./router"; + +const app = createApp(App); +app.use(createPinia()); +app.use(router); +app.use(PrimeVue, { unstyled: true }); +app.use(createNychthemeron()); +app.mount("#app"); diff --git a/ui/src/router/index.ts b/ui/src/router/index.ts new file mode 100644 index 0000000..f942970 --- /dev/null +++ b/ui/src/router/index.ts @@ -0,0 +1,38 @@ +import { createRouter, createWebHistory } from 'vue-router' +import { useAuthStore } from '../stores/auth' + +const router = createRouter({ + history: createWebHistory(), + routes: [ + { path: '/login', component: () => import('../views/Login.vue') }, + { + path: '/admin', + component: () => import('../views/admin/Layout.vue'), + children: [ + { path: 'queries', component: () => import('../views/admin/Queries.vue') }, + { path: 'tables', component: () => import('../views/admin/Tables.vue') }, + { path: 'users', component: () => import('../views/admin/Users.vue') }, + { path: 'permissions', component: () => import('../views/admin/Permissions.vue') }, + { path: 'blacklist', component: () => import('../views/admin/Blacklist.vue') }, + { path: 'api-keys', component: () => import('../views/admin/ApiKeys.vue') }, + { path: 'cache', component: () => import('../views/admin/Cache.vue') }, + { path: 'cors', component: () => import('../views/admin/Cors.vue') }, + { path: 'cdn', component: () => import('../views/admin/Cdn.vue') }, + ], + meta: { requiresAuth: true }, + }, + { path: '/', redirect: '/admin/queries' }, + ], +}) + +router.beforeEach((to) => { + const auth = useAuthStore() + if (to.meta.requiresAuth && !auth.isAuthenticated) { + return '/login' + } + if (to.path === '/login' && auth.isAuthenticated) { + return '/admin/queries' + } +}) + +export default router diff --git a/ui/src/stores/auth.ts b/ui/src/stores/auth.ts new file mode 100644 index 0000000..4fe8b5f --- /dev/null +++ b/ui/src/stores/auth.ts @@ -0,0 +1,70 @@ +import { defineStore } from "pinia"; +import { ref, computed } from "vue"; + +interface Claims { + sub: string; + permissions: string; + exp: number; +} + +function parseJwt(token: string): Claims | null { + try { + const payload = token.split(".")[1]; + return payload ? (JSON.parse(atob(payload)) as Claims) : null; + } catch { + return null; + } +} + +export const useAuthStore = defineStore("auth", () => { + const token = ref(localStorage.getItem("mercury_token")); + const claims = computed(() => + token.value ? parseJwt(token.value) : null, + ); + const isAuthenticated = computed(() => { + if (!claims.value) return false; + return claims.value.exp * 1000 > Date.now(); + }); + const username = computed(() => claims.value?.sub ?? ""); + + function hasPermission(bit: bigint): boolean { + if (!claims.value) return false; + const mask = BigInt(claims.value.permissions); + return (mask & bit) !== 0n; + } + + const isSuperAdmin = computed(() => hasPermission(32n)); + + async function login(username: string, password: string): Promise { + const res = await fetch("/auth/login", { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ username, password }), + }); + if (!res.ok) throw new Error("Invalid credentials"); + const data = await res.json(); + token.value = data.token; + localStorage.setItem("mercury_token", data.token); + } + + function logout() { + token.value = null; + localStorage.removeItem("mercury_token"); + } + + function authHeaders(): Record { + return token.value ? { Authorization: `Bearer ${token.value}` } : {}; + } + + return { + token, + claims, + isAuthenticated, + username, + isSuperAdmin, + hasPermission, + login, + logout, + authHeaders, + }; +}); diff --git a/ui/src/stores/theme.ts b/ui/src/stores/theme.ts new file mode 100644 index 0000000..9cebd64 --- /dev/null +++ b/ui/src/stores/theme.ts @@ -0,0 +1,24 @@ +import { ref } from 'vue' + +export type Theme = 'apollo' | 'hades' + +const stored = localStorage.getItem('mercury-theme') as Theme | null +const theme = ref(stored ?? 'apollo') + +function applyTheme(t: Theme) { + theme.value = t + document.documentElement.setAttribute('data-theme', t) + localStorage.setItem('mercury-theme', t) +} + +applyTheme(theme.value) + +export function useTheme() { + return { + theme, + isDark: () => theme.value === 'hades', + toggle() { + applyTheme(theme.value === 'apollo' ? 'hades' : 'apollo') + }, + } +} diff --git a/ui/src/views/Login.vue b/ui/src/views/Login.vue new file mode 100644 index 0000000..c6b097b --- /dev/null +++ b/ui/src/views/Login.vue @@ -0,0 +1,173 @@ + + + + + diff --git a/ui/src/views/admin/ApiKeys.vue b/ui/src/views/admin/ApiKeys.vue new file mode 100644 index 0000000..b6027b3 --- /dev/null +++ b/ui/src/views/admin/ApiKeys.vue @@ -0,0 +1,255 @@ + + + + + diff --git a/ui/src/views/admin/Blacklist.vue b/ui/src/views/admin/Blacklist.vue new file mode 100644 index 0000000..debcdd2 --- /dev/null +++ b/ui/src/views/admin/Blacklist.vue @@ -0,0 +1,242 @@ + + + + + diff --git a/ui/src/views/admin/Cache.vue b/ui/src/views/admin/Cache.vue new file mode 100644 index 0000000..eb536a7 --- /dev/null +++ b/ui/src/views/admin/Cache.vue @@ -0,0 +1,160 @@ + + + + + diff --git a/ui/src/views/admin/Cdn.vue b/ui/src/views/admin/Cdn.vue new file mode 100644 index 0000000..162014d --- /dev/null +++ b/ui/src/views/admin/Cdn.vue @@ -0,0 +1,203 @@ + + + + + diff --git a/ui/src/views/admin/Cors.vue b/ui/src/views/admin/Cors.vue new file mode 100644 index 0000000..8f5f1ef --- /dev/null +++ b/ui/src/views/admin/Cors.vue @@ -0,0 +1,118 @@ + + + + + diff --git a/ui/src/views/admin/Layout.vue b/ui/src/views/admin/Layout.vue new file mode 100644 index 0000000..37837fb --- /dev/null +++ b/ui/src/views/admin/Layout.vue @@ -0,0 +1,267 @@ + + + + + diff --git a/ui/src/views/admin/MethodSelect.vue b/ui/src/views/admin/MethodSelect.vue new file mode 100644 index 0000000..128dab8 --- /dev/null +++ b/ui/src/views/admin/MethodSelect.vue @@ -0,0 +1,122 @@ + + + + + diff --git a/ui/src/views/admin/Permissions.vue b/ui/src/views/admin/Permissions.vue new file mode 100644 index 0000000..2d72d01 --- /dev/null +++ b/ui/src/views/admin/Permissions.vue @@ -0,0 +1,157 @@ + + + + + diff --git a/ui/src/views/admin/Queries.vue b/ui/src/views/admin/Queries.vue new file mode 100644 index 0000000..354b8a5 --- /dev/null +++ b/ui/src/views/admin/Queries.vue @@ -0,0 +1,147 @@ + + + + + diff --git a/ui/src/views/admin/Tables.vue b/ui/src/views/admin/Tables.vue new file mode 100644 index 0000000..122ba46 --- /dev/null +++ b/ui/src/views/admin/Tables.vue @@ -0,0 +1,575 @@ + + + + + diff --git a/ui/src/views/admin/Users.vue b/ui/src/views/admin/Users.vue new file mode 100644 index 0000000..8ba0ee2 --- /dev/null +++ b/ui/src/views/admin/Users.vue @@ -0,0 +1,208 @@ + + + + + diff --git a/ui/tsconfig.json b/ui/tsconfig.json new file mode 100644 index 0000000..d5763ca --- /dev/null +++ b/ui/tsconfig.json @@ -0,0 +1,16 @@ +{ + "compilerOptions": { + "target": "ES2020", + "module": "ESNext", + "moduleResolution": "bundler", + "lib": ["ES2020", "DOM", "DOM.Iterable"], + "jsx": "preserve", + "noEmit": true, + "strict": true, + "skipLibCheck": true, + "isolatedModules": true, + "useDefineForClassFields": true + }, + "include": ["src/**/*.ts", "src/**/*.d.ts", "src/**/*.tsx", "src/**/*.vue"], + "exclude": ["node_modules", "dist"] +} diff --git a/ui/vite.config.d.ts b/ui/vite.config.d.ts new file mode 100644 index 0000000..fd582a2 --- /dev/null +++ b/ui/vite.config.d.ts @@ -0,0 +1,3 @@ +declare const _default: any; +export default _default; +//# sourceMappingURL=vite.config.d.ts.map \ No newline at end of file diff --git a/ui/vite.config.ts b/ui/vite.config.ts new file mode 100644 index 0000000..07eb712 --- /dev/null +++ b/ui/vite.config.ts @@ -0,0 +1,28 @@ +import { defineConfig } from "vite"; +import vue from "@vitejs/plugin-vue"; + +export default defineConfig({ + plugins: [vue()], + server: { + proxy: { + "/api": "http://localhost:3000", + "/auth": "http://localhost:3000", + "/admin": "http://localhost:3000", + }, + }, + build: { + outDir: "dist", + rollupOptions: { + output: { + manualChunks: { + vue: ["vue", "vue-router", "pinia"], + primevue: ["@primevue/core"], + nychthemeron: ["@nychthemeron/library"], + }, + entryFileNames: "js/[name]-[hash].js", + chunkFileNames: "js/[name]-[hash].js", + assetFileNames: "assets/[name]-[hash][extname]", + }, + }, + }, +});