diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..e9e93a1 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,25 @@ +name: ci +on: + push: + branches: [main] + pull_request: + +permissions: + contents: read + +env: + CARGO_TERM_COLOR: always + +jobs: + test: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - run: rustup toolchain install stable --profile minimal --component clippy,rustfmt && rustup default stable + - run: cargo fmt --check + - run: cargo clippy --all-features --all-targets -- -D warnings + - run: cargo test --all-features + - name: Without the HTTP client + run: cargo test --no-default-features + - name: Package contents + run: cargo package --list diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml new file mode 100644 index 0000000..5f33377 --- /dev/null +++ b/.github/workflows/publish.yml @@ -0,0 +1,30 @@ +# Publishes to crates.io when a GitHub Release is published. The release tag +# must be v, e.g. v0.1.0. Needs the +# CARGO_REGISTRY_TOKEN secret. +name: publish +on: + release: + types: [published] + +permissions: + contents: read + +concurrency: + group: publish-${{ github.ref }} + +jobs: + crates-io: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - run: rustup toolchain install stable --profile minimal && rustup default stable + - name: Tag matches Cargo.toml version + run: | + version="$(cargo metadata --no-deps --format-version 1 | python3 -c 'import json,sys; print(json.load(sys.stdin)["packages"][0]["version"])')" + if [ "v$version" != "$GITHUB_REF_NAME" ]; then + echo "release tag $GITHUB_REF_NAME does not match Cargo.toml version $version"; exit 1 + fi + - run: cargo test --all-features + - run: cargo publish + env: + CARGO_REGISTRY_TOKEN: ${{ secrets.CARGO_REGISTRY_TOKEN }} diff --git a/.github/workflows/release-notify.yml b/.github/workflows/release-notify.yml new file mode 100644 index 0000000..175ac3e --- /dev/null +++ b/.github/workflows/release-notify.yml @@ -0,0 +1,15 @@ +# Posts each published release of this repo to Slack, using the shared +# workflow in hibira-io/.github. Needs the org secret SLACK_WEBHOOK_URL; +# without it the job is a no-op. +name: release-notify + +on: + release: + types: [published] + +permissions: {} + +jobs: + slack: + uses: hibira-io/.github/.github/workflows/release-slack.yml@main + secrets: inherit diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..c17da7f --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +/target +Cargo.lock.bak diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..944fce7 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,5 @@ +# Changelog + +## 0.1.0 + +- First release: realtime trigger, channel auth, user sign-in and webhooks; waiting room passes with Axum and Actix Web middleware; Chat API; Approvals with callback verification; Live Chat verified visitors. diff --git a/Cargo.lock b/Cargo.lock new file mode 100644 index 0000000..9f6c1d1 --- /dev/null +++ b/Cargo.lock @@ -0,0 +1,2202 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 3 + +[[package]] +name = "actix-codec" +version = "0.5.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4c13df95297bcf9014dc89162b0cc69431e192e34e3b419612fc124cfcd45dbf" +dependencies = [ + "bitflags", + "bytes", + "futures-core", + "futures-sink", + "memchr", + "pin-project-lite", + "tokio", + "tokio-util", + "tracing", +] + +[[package]] +name = "actix-http" +version = "3.22.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ef789744a2e6e678dd2dee90b2aecc084022709378f28d9d0eee6d7d299e36b8" +dependencies = [ + "actix-codec", + "actix-service", + "actix-utils", + "bitflags", + "bytes", + "bytestring", + "derive_more", + "encoding_rs", + "foldhash", + "futures-core", + "http 0.2.12", + "httparse", + "httpdate", + "itoa", + "language-tags", + "mime", + "percent-encoding", + "pin-project-lite", + "smallvec", + "tokio", + "tokio-util", + "tracing", +] + +[[package]] +name = "actix-macros" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "367f814ad4afbac74f07df5001214da65f65e185c90ef56c4dd8df23f8695b9b" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "actix-router" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "125f4331c1f10734a96c038bc7503dff22d8ccd5f82b214e6696728561ef1149" +dependencies = [ + "bytestring", + "cfg-if", + "http 0.2.12", + "regex-lite", + "serde", + "tracing", +] + +[[package]] +name = "actix-rt" +version = "2.16.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "07c6d0b470c2b069868a1dc26ad646516e7d19dbf6f9563997c4a563faff6674" +dependencies = [ + "actix-macros", + "futures-core", + "tokio", +] + +[[package]] +name = "actix-server" +version = "2.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5e296908c4d6f3a191e6b9873dbdfec8023350a89129d2b470f61d17233931ee" +dependencies = [ + "actix-rt", + "actix-service", + "futures-core", + "futures-util", + "mio", + "socket2", + "tokio", + "tracing", +] + +[[package]] +name = "actix-service" +version = "2.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e46f36bf0e5af44bdc4bdb36fbbd421aa98c79a9bce724e1edeb3894e10dc7f" +dependencies = [ + "futures-core", + "pin-project-lite", +] + +[[package]] +name = "actix-utils" +version = "3.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0128396dd7313f697ad05b21b1a7be7d4cbb81888704f55996e4a27db196bb4d" +dependencies = [ + "local-waker", + "pin-project-lite", +] + +[[package]] +name = "actix-web" +version = "4.20.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "618475ea8d22e5ad6e8aefaf9f56253b6ad856a7522716bea0b48bbb772341ff" +dependencies = [ + "actix-codec", + "actix-http", + "actix-macros", + "actix-router", + "actix-rt", + "actix-server", + "actix-service", + "actix-utils", + "actix-web-codegen", + "bytes", + "bytestring", + "cfg-if", + "cookie 0.16.2", + "derive_more", + "encoding_rs", + "foldhash", + "futures-core", + "futures-util", + "impl-more", + "itoa", + "language-tags", + "log", + "mime", + "once_cell", + "pin-project-lite", + "regex-lite", + "serde", + "serde_json", + "serde_urlencoded", + "smallvec", + "socket2", + "time", + "tokio", + "tracing", + "url", +] + +[[package]] +name = "actix-web-codegen" +version = "4.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4357272ed7e7ed928f2e6bbb4e422257d0bd4e36f80477faa2f794984b16e386" +dependencies = [ + "actix-router", + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "atomic-waker" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" + +[[package]] +name = "aws-lc-rs" +version = "1.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "048006790404103c488e6c5616b3e7e702a71292aadda08e8f7698a9e0d2eb53" +dependencies = [ + "aws-lc-sys", + "zeroize", +] + +[[package]] +name = "aws-lc-sys" +version = "0.47.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8bfbe32ac36b3c428696ce315464181bc4029d689fd58e3f2a4e58c252242f52" +dependencies = [ + "cc", + "cmake", + "dunce", + "fs_extra", + "pkg-config", +] + +[[package]] +name = "axum" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "31b698c5f9a010f6573133b09e0de5408834d0c82f8d7475a89fc1867a71cd90" +dependencies = [ + "axum-core", + "bytes", + "futures-util", + "http 1.5.0", + "http-body", + "http-body-util", + "hyper", + "hyper-util", + "itoa", + "matchit", + "memchr", + "mime", + "percent-encoding", + "pin-project-lite", + "serde_core", + "sync_wrapper", + "tokio", + "tower", + "tower-layer", + "tower-service", +] + +[[package]] +name = "axum-core" +version = "0.5.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08c78f31d7b1291f7ee735c1c6780ccde7785daae9a9206026862dab7d8792d1" +dependencies = [ + "bytes", + "futures-core", + "http 1.5.0", + "http-body", + "http-body-util", + "mime", + "pin-project-lite", + "sync_wrapper", + "tower-layer", + "tower-service", +] + +[[package]] +name = "base64" +version = "0.22.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" + +[[package]] +name = "base64" +version = "0.23.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5" + +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" + +[[package]] +name = "block-buffer" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" +dependencies = [ + "generic-array", +] + +[[package]] +name = "bumpalo" +version = "3.20.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "87a0cf66fd1eb2fb7b822cb78370d82303750809bc6ba855f3f58e517d3238db" + +[[package]] +name = "bytes" +version = "1.12.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "776dfebd015e2d8732c684a2c71003674ccb49457b539b9e82151ba38e96dd7c" + +[[package]] +name = "bytestring" +version = "1.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "07acef387a61fe24ed2ee3924f1fe89ac9f4b862dfd72b110109133158d7f9f8" +dependencies = [ + "bytes", +] + +[[package]] +name = "cc" +version = "1.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "02f0e023adb368345ce0ca6cdfc0f24a06554468d0e8503e14a0841de79bfa69" +dependencies = [ + "find-msvc-tools", + "jobserver", + "libc", + "shlex", +] + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "cfg_aliases" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527" + +[[package]] +name = "chacha20" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06" +dependencies = [ + "cfg-if", + "cpufeatures 0.3.1", + "rand_core", +] + +[[package]] +name = "cmake" +version = "0.1.58" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c0f78a02292a74a88ac736019ab962ece0bc380e3f977bf72e376c5d78ff0678" +dependencies = [ + "cc", +] + +[[package]] +name = "combine" +version = "4.6.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4356eba6976435498d05a311ee9fc486da3bc81c200d3f0d7dd9703b41913f92" +dependencies = [ + "bytes", + "memchr", +] + +[[package]] +name = "convert_case" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "633458d4ef8c78b72454de2d54fd6ab2e60f9e02be22f3c6104cdc8a4e0fceb9" +dependencies = [ + "unicode-segmentation", +] + +[[package]] +name = "cookie" +version = "0.16.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e859cd57d0710d9e06c381b550c06e76992472a8c6d527aecd2fc673dcc231fb" +dependencies = [ + "percent-encoding", + "time", + "version_check", +] + +[[package]] +name = "cookie" +version = "0.18.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d55f2d6c30eeec7d5c6f98bd4395d4abb1895629eab97ee6522d340623615f8a" +dependencies = [ + "time", + "version_check", +] + +[[package]] +name = "core-foundation" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b2a6cd9ae233e7f62ba4e9353e81a88df7fc8a5987b8d445b4d90c879bd156f6" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "core-foundation-sys" +version = "0.8.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" + +[[package]] +name = "core_detect" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f8f80099a98041a3d1622845c271458a2d73e688351bf3cb999266764b81d48" + +[[package]] +name = "cpufeatures" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" +dependencies = [ + "libc", +] + +[[package]] +name = "cpufeatures" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566" +dependencies = [ + "libc", +] + +[[package]] +name = "crypto-common" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" +dependencies = [ + "generic-array", + "typenum", +] + +[[package]] +name = "deranged" +version = "0.5.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e9de72ce2ad1f90dc62fa25f0f430ef85eb4b0d8fa0be4f30373bc40a21d28e" + +[[package]] +name = "derive_more" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d751e9e49156b02b44f9c1815bcb94b984cdcc4396ecc32521c739452808b134" +dependencies = [ + "derive_more-impl", +] + +[[package]] +name = "derive_more-impl" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "799a97264921d8623a957f6c3b9011f3b5492f557bbb7a5a19b7fa6d06ba8dcb" +dependencies = [ + "convert_case", + "proc-macro2", + "quote", + "rustc_version", + "syn 2.0.119", + "unicode-xid", +] + +[[package]] +name = "digest" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" +dependencies = [ + "block-buffer", + "crypto-common", + "subtle", +] + +[[package]] +name = "displaydoc" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "dunce" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92773504d58c093f6de2459af4af33faa518c13451eb8f2b5698ed3d36e7c813" + +[[package]] +name = "encoding_rs" +version = "0.8.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "89253175e704ab869b04f9db224d38630e0211a53841a79181deae0889e169f5" +dependencies = [ + "cfg-if", + "core_detect", + "multiversion_no_op", + "rustversion", + "scopeguard", + "simdutf8", +] + +[[package]] +name = "errno" +version = "0.3.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e35d6e78f4cebb90e51d543db8fe41528851d6deeef6ef21ebd4bfdc1e784776" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "find-msvc-tools" +version = "0.1.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48" + +[[package]] +name = "fnv" +version = "1.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" + +[[package]] +name = "foldhash" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" + +[[package]] +name = "form_urlencoded" +version = "1.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "afa489199eaffb1211795df1c6236ce1ad0d41a6fa45250add73e3b02420f06e" +dependencies = [ + "percent-encoding", +] + +[[package]] +name = "fs_extra" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "42703706b716c37f96a77aea830392ad231f44c9e9a67872fa5548707e11b11c" + +[[package]] +name = "futures-channel" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1f9e3d69d39e4862ffed03ed071a76f9a13ba1d9109d355b0f0aa6b15e393c4" +dependencies = [ + "futures-core", +] + +[[package]] +name = "futures-core" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" + +[[package]] +name = "futures-sink" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1944426bf7d03f1d14f708785e4b33efd750b36d48a157b836b3efc15ede8e1d" + +[[package]] +name = "futures-task" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd" + +[[package]] +name = "futures-util" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" +dependencies = [ + "futures-core", + "futures-task", + "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.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" +dependencies = [ + "cfg-if", + "js-sys", + "libc", + "r-efi", + "rand_core", + "wasm-bindgen", +] + +[[package]] +name = "hex" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" + +[[package]] +name = "hibira" +version = "0.1.0" +dependencies = [ + "actix-rt", + "actix-web", + "axum", + "base64 0.22.1", + "cookie 0.18.3", + "hex", + "hmac", + "http 1.5.0", + "md-5", + "percent-encoding", + "reqwest", + "serde", + "serde_json", + "sha2", + "thiserror", + "tokio", + "tower", + "url", +] + +[[package]] +name = "hmac" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e" +dependencies = [ + "digest", +] + +[[package]] +name = "http" +version = "0.2.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "601cbb57e577e2f5ef5be8e7b83f0f63994f25aa94d673e54a92d5c516d101f1" +dependencies = [ + "bytes", + "fnv", + "itoa", +] + +[[package]] +name = "http" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0" +dependencies = [ + "bytes", + "itoa", +] + +[[package]] +name = "http-body" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca2a8f2913ee65f60facd6a5905613afaa448497a0230cc41ce022d93290bc2c" +dependencies = [ + "bytes", + "http 1.5.0", +] + +[[package]] +name = "http-body-util" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23169fe34a5fbcdd3f3862e78fb9b6fccd5f02a6dc6f732547005d45631ce71c" +dependencies = [ + "bytes", + "futures-core", + "http 1.5.0", + "http-body", + "pin-project-lite", +] + +[[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.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "229c6ff5584df4c6becbfe00567128bac768c8cd32ebc8a8366bd81ed072e8f3" +dependencies = [ + "atomic-waker", + "bytes", + "futures-core", + "http 1.5.0", + "http-body", + "httparse", + "httpdate", + "itoa", + "pin-project-lite", + "smallvec", + "tokio", + "want", +] + +[[package]] +name = "hyper-rustls" +version = "0.27.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dfa8e654703247911e29c23fbeaa261834bd9bb74efba2f9acddc37bfb127f53" +dependencies = [ + "http 1.5.0", + "hyper", + "hyper-util", + "rustls", + "tokio", + "tokio-rustls", + "tower-service", +] + +[[package]] +name = "hyper-util" +version = "0.1.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ddc03d96684f9226b8a787cdb71488417b53ab5ea8fdb1dac946cb9431cc8bff" +dependencies = [ + "base64 0.23.1", + "bytes", + "futures-channel", + "futures-util", + "http 1.5.0", + "http-body", + "httparse", + "hyper", + "ipnet", + "libc", + "percent-encoding", + "pin-project-lite", + "socket2", + "tokio", + "tower-service", + "tracing", +] + +[[package]] +name = "icu_collections" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe090a42a0d3140fed8c63263ed1fecc02422cb2f4bfe55cd8de2de1b8e105dd" +dependencies = [ + "displaydoc", + "potential_utf", + "utf8_iter", + "yoke", + "zerofrom", + "zerovec", +] + +[[package]] +name = "icu_locale_core" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "25d29b57c17c6528d0dc4c2141cfa2d08200465acb537a3909c8b9b8a4a984c0" +dependencies = [ + "displaydoc", + "litemap", + "tinystr", + "writeable", + "zerovec", +] + +[[package]] +name = "icu_normalizer" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "404a3b8c486f205c87fe7f23ab6894d84a4ad76d6e4671ae1981ba7def87c599" +dependencies = [ + "icu_collections", + "icu_normalizer_data", + "icu_properties", + "icu_provider", + "smallvec", + "zerovec", +] + +[[package]] +name = "icu_normalizer_data" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20f0088bfb7441f7a37fa0c9e20cb1e9cba1cac6b9ce8cd2a6dc44294f8e8cbc" + +[[package]] +name = "icu_properties" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ea83d991c56158f7cf898bf86436c1dfe7c07ee82fe88951f2695c9f37a379f" +dependencies = [ + "displaydoc", + "icu_collections", + "icu_locale_core", + "icu_properties_data", + "icu_provider", + "zerotrie", + "zerovec", +] + +[[package]] +name = "icu_properties_data" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b98f29af82d02b163fe50161388350e743bb3107cc8e8c2f7314cb505faddfcf" + +[[package]] +name = "icu_provider" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "413099315636c588ee8f011190b329b971a09a8fae9d157e01dcae8379468514" +dependencies = [ + "displaydoc", + "icu_locale_core", + "writeable", + "yoke", + "zerofrom", + "zerotrie", + "zerovec", +] + +[[package]] +name = "idna" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de" +dependencies = [ + "idna_adapter", + "smallvec", + "utf8_iter", +] + +[[package]] +name = "idna_adapter" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714" +dependencies = [ + "icu_normalizer", + "icu_properties", +] + +[[package]] +name = "impl-more" +version = "0.3.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2d3a73c82a0b0747dba739b380c046a140b5ae747234bf701df3460282da7193" + +[[package]] +name = "ipnet" +version = "2.12.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "791930b43c0d5973160d90a8f3894509f2b273430f5c5c73b668636d0287c5c0" + +[[package]] +name = "itoa" +version = "1.0.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4" + +[[package]] +name = "jni" +version = "0.22.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5efd9a482cf3a427f00d6b35f14332adc7902ce91efb778580e180ff90fa3498" +dependencies = [ + "cfg-if", + "combine", + "jni-macros", + "jni-sys", + "log", + "simd_cesu8", + "thiserror", + "walkdir", + "windows-link", +] + +[[package]] +name = "jni-macros" +version = "0.22.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a00109accc170f0bdb141fed3e393c565b6f5e072365c3bd58f5b062591560a3" +dependencies = [ + "proc-macro2", + "quote", + "rustc_version", + "simd_cesu8", + "syn 2.0.119", +] + +[[package]] +name = "jni-sys" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6377a88cb3910bee9b0fa88d4f42e1d2da8e79915598f65fb0c7ee14c878af2" +dependencies = [ + "jni-sys-macros", +] + +[[package]] +name = "jni-sys-macros" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38c0b942f458fe50cdac086d2f946512305e5631e720728f2a61aabcd47a6264" +dependencies = [ + "quote", + "syn 2.0.119", +] + +[[package]] +name = "jobserver" +version = "0.1.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c00acbd29eabad4a2392fa0e921c874934dbbf4194312ad20f04a0ed67a3cb3" +dependencies = [ + "getrandom 0.4.3", + "libc", +] + +[[package]] +name = "js-sys" +version = "0.3.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8dc09d2154098bbf4ef54eab6b117a3c24cbbffe94046b16ee6d6d4510584d3a" +dependencies = [ + "cfg-if", + "futures-util", + "wasm-bindgen", +] + +[[package]] +name = "language-tags" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d4345964bb142484797b161f473a503a434de77149dd8c7427788c6e13379388" + +[[package]] +name = "libc" +version = "0.2.191" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" + +[[package]] +name = "litemap" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae" + +[[package]] +name = "local-waker" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "88bab6b3971cb9cda8a370672a73e59a442b87552f005fb60ec07b67fa658f13" + +[[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.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" + +[[package]] +name = "lru-slab" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4050469837a6ff301cd14c1f8f24f88549e6d548f24f64e2148eb0f72cebc51f" + +[[package]] +name = "matchit" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47e1ffaa40ddd1f3ed91f717a33c8c0ee23fff369e3aa8772b9605cc1d22f4c3" + +[[package]] +name = "md-5" +version = "0.10.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d89e7ee0cfbedfc4da3340218492196241d89eefb6dab27de5df917a6d2e78cf" +dependencies = [ + "cfg-if", + "digest", +] + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "mime" +version = "0.3.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d5848f5a9e8117cf94f2f90faac24a87ff81600ff8628c1e3deaab572e76bfa1" + +[[package]] +name = "mio" +version = "1.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20521a903f02b0a573cd6840e9d0a5a0cc043d361fe924092cd70f8556cc9c4a" +dependencies = [ + "libc", + "log", + "wasi", + "windows-sys 0.61.2", +] + +[[package]] +name = "multiversion_no_op" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "743fb55ba31b18fb1ecef6bdc9aa2743314978ac084044301a7eee33fb99a20d" + +[[package]] +name = "num-conv" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441" + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "openssl-probe" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e036b411754132fd6b74e94b74e9a13c5cf606fa93d1885c35860d3060820b1" + +[[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", + "smallvec", + "windows-link", +] + +[[package]] +name = "percent-encoding" +version = "2.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" + +[[package]] +name = "pin-project-lite" +version = "0.2.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c938015719552d665fd0553b90d96cd7ff58e83e4c061ca99e6bb78865a72752" + +[[package]] +name = "pkg-config" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548" + +[[package]] +name = "potential_utf" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d83eb9bc6d8e5cf568e7a1101d60ee05e81ed50ea106026f3d18deeb046d7661" +dependencies = [ + "zerovec", +] + +[[package]] +name = "powerfmt" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a6394b9e965e73d0a289ee54f589087e2c676aedf60885baf52c76b771e4958" + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quinn" +version = "0.11.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4051e23e9185c255a7e33ef59cdbca87a22d359052eecd22fc6b901fb37d9d11" +dependencies = [ + "bytes", + "cfg_aliases", + "pin-project-lite", + "quinn-proto", + "quinn-udp", + "rustc-hash", + "rustls", + "socket2", + "thiserror", + "tokio", + "tracing", + "web-time", +] + +[[package]] +name = "quinn-proto" +version = "0.11.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e750cca55fe4f0439a15d0bb529da9651e79993e8e72c61a899a36d462befbe" +dependencies = [ + "aws-lc-rs", + "bytes", + "getrandom 0.4.3", + "lru-slab", + "rand", + "rand_pcg", + "ring", + "rustc-hash", + "rustls", + "rustls-pki-types", + "slab", + "thiserror", + "tinyvec", + "tracing", + "web-time", +] + +[[package]] +name = "quinn-udp" +version = "0.5.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af66907df18639dcf4db56ca65490cabc4b27a97dbadd96f2926cca73298f016" +dependencies = [ + "cfg_aliases", + "libc", + "once_cell", + "socket2", + "tracing", + "windows-sys 0.61.2", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "r-efi" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" + +[[package]] +name = "rand" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f6fa277c67e6ea590466f04c3fe82cb509f0864fe470643e5570de9514a9b11" +dependencies = [ + "chacha20", + "getrandom 0.4.3", + "rand_core", +] + +[[package]] +name = "rand_core" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69" + +[[package]] +name = "rand_pcg" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eb95882a1e14462c69aea9984bb261293ccfe6022ef8de0eda18bd5afb0052df" +dependencies = [ + "rand_core", +] + +[[package]] +name = "redox_syscall" +version = "0.5.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d" +dependencies = [ + "bitflags", +] + +[[package]] +name = "regex-lite" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cab834c73d247e67f4fae452806d17d3c7501756d98c8808d7c9c7aa7d18f973" + +[[package]] +name = "reqwest" +version = "0.13.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "16a1cfa75cc186dd73d5818e510e042e40927bccc9c236b061cea97e1eb08029" +dependencies = [ + "base64 0.23.1", + "bytes", + "futures-core", + "http 1.5.0", + "http-body", + "http-body-util", + "hyper", + "hyper-rustls", + "hyper-util", + "js-sys", + "log", + "percent-encoding", + "pin-project-lite", + "quinn", + "rustls", + "rustls-pki-types", + "rustls-platform-verifier", + "serde", + "serde_json", + "sync_wrapper", + "tokio", + "tokio-rustls", + "tower", + "tower-http", + "tower-service", + "url", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", +] + +[[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 = "rustc-hash" +version = "2.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d" + +[[package]] +name = "rustc_version" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92" +dependencies = [ + "semver", +] + +[[package]] +name = "rustls" +version = "0.23.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf" +dependencies = [ + "aws-lc-rs", + "once_cell", + "rustls-pki-types", + "rustls-webpki", + "subtle", + "zeroize", +] + +[[package]] +name = "rustls-native-certs" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a073f5dc7469f984c52ad2752b63b0807745133b6de880b7b64c1ac4c48aec4" +dependencies = [ + "openssl-probe", + "rustls-pki-types", + "schannel", + "security-framework", +] + +[[package]] +name = "rustls-pki-types" +version = "1.16.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "102f35f7de7b06d8c61f1cff6592f5253e0dea431c74867aad5dfd70f44663fb" +dependencies = [ + "web-time", + "zeroize", +] + +[[package]] +name = "rustls-platform-verifier" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1167586491e2b18b8bfbb293e8180ec17c201c4f076d7cb3070ca964e7598f98" +dependencies = [ + "core-foundation", + "core-foundation-sys", + "jni", + "log", + "once_cell", + "rustls", + "rustls-native-certs", + "rustls-platform-verifier-android", + "rustls-webpki", + "security-framework", + "security-framework-sys", + "webpki-root-certs", + "windows-sys 0.61.2", +] + +[[package]] +name = "rustls-platform-verifier-android" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eec689c0bc40ff2458a5977b6619cb718087084a18e02a131c599b62d05e1a5f" + +[[package]] +name = "rustls-webpki" +version = "0.103.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3a0760a887c14823fca5a1c970b01d47c328c696c0c64829d1df50e8f853fd5" +dependencies = [ + "aws-lc-rs", + "ring", + "rustls-pki-types", + "untrusted", +] + +[[package]] +name = "rustversion" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" + +[[package]] +name = "ryu" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" + +[[package]] +name = "same-file" +version = "1.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502" +dependencies = [ + "winapi-util", +] + +[[package]] +name = "schannel" +version = "0.1.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9cb23c424d8ee841bb4d813677ca237e2a610067d594fec130f87d6093495ab5" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "scopeguard" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" + +[[package]] +name = "security-framework" +version = "3.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b7f4bc775c73d9a02cde8bf7b2ec4c9d12743edf609006c7facc23998404cd1d" +dependencies = [ + "bitflags", + "core-foundation", + "core-foundation-sys", + "libc", + "security-framework-sys", +] + +[[package]] +name = "security-framework-sys" +version = "2.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2691df843ecc5d231c0b14ece2acc3efb62c0a398c7e1d875f3983ce020e3" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[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.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "serde_json" +version = "1.0.154" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[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 = "sha2" +version = "0.10.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" +dependencies = [ + "cfg-if", + "cpufeatures 0.2.17", + "digest", +] + +[[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 = "simd_cesu8" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "11031e251abf8611c80f460e19dbdeb54a66db918e49c65a7065b46ac7aec520" +dependencies = [ + "rustc_version", + "simdutf8", +] + +[[package]] +name = "simdutf8" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e" + +[[package]] +name = "slab" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" + +[[package]] +name = "smallvec" +version = "1.16.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3244542535d5de959d90ec55d1b5ff0fd2bb7b1310223907d5f11932847f7b59" + +[[package]] +name = "socket2" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "stable_deref_trait" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" + +[[package]] +name = "subtle" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" + +[[package]] +name = "syn" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "3.0.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79" +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.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "901704edd0dfe137f1987838ee4f259e4e063c31371bdb423f7ae38ec6f77f02" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "thiserror" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e" +dependencies = [ + "thiserror-impl", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "time" +version = "0.3.55" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cdb87b95ec50ddfa440816d227a17b2ccbdda963a316a727fda0fc4334f7d134" +dependencies = [ + "deranged", + "num-conv", + "powerfmt", + "serde_core", + "time-core", + "time-macros", +] + +[[package]] +name = "time-core" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e1c906769ad99c88eaa54e728060edef082f8e358ff32030cb7c7d315e81109" + +[[package]] +name = "time-macros" +version = "0.2.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e689342a48d2ea927c87ea50cabf8594854bf940e9310208848d680d668ed85" +dependencies = [ + "num-conv", + "time-core", +] + +[[package]] +name = "tinystr" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "abc840c238154d58f9e86b2792261edfde565a17696e1cda1a449de27979801a" +dependencies = [ + "displaydoc", + "zerovec", +] + +[[package]] +name = "tinyvec" +version = "1.13.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee" + +[[package]] +name = "tokio" +version = "1.54.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b52fd3255258d26fac7264ab5a76b53c13367136dc011d3d6ad4f8ed070396a3" +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.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78773a2a397f451582ce068015985c33193cf6dea8b74d2a639fe457b2f07b0e" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "tokio-rustls" +version = "0.26.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c9cc2678c2cdd569ef8215e2afd7954ada2ae20b4fdd2c5fe6139a3b02d105db" +dependencies = [ + "rustls", + "tokio", +] + +[[package]] +name = "tokio-util" +version = "0.7.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e464cf451ba96ebfc6f9b6542f17ee8b8956e33f1e40d9690624e59d7a7f8a4b" +dependencies = [ + "bytes", + "futures-core", + "futures-sink", + "libc", + "pin-project-lite", + "tokio", +] + +[[package]] +name = "tower" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebe5ef63511595f1344e2d5cfa636d973292adc0eec1f0ad45fae9f0851ab1d4" +dependencies = [ + "futures-core", + "futures-util", + "pin-project-lite", + "sync_wrapper", + "tokio", + "tower-layer", + "tower-service", +] + +[[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 1.5.0", + "http-body", + "pin-project-lite", + "tower", + "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.119", +] + +[[package]] +name = "tracing-core" +version = "0.1.36" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" +dependencies = [ + "once_cell", +] + +[[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 = "unicode-ident" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" + +[[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 = "untrusted" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" + +[[package]] +name = "url" +version = "2.5.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f00cd2407bb42c0ef17be88d4cf020f5cceffd121665bac9b8b9493a369b3b1a" +dependencies = [ + "form_urlencoded", + "idna", + "percent-encoding", + "serde", +] + +[[package]] +name = "utf8_iter" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af3bd9d3e571c26fcce9d033b87ea5ab061b8d2ffe9b7a5675d810d68f03edf0" +dependencies = [ + "utf_types", +] + +[[package]] +name = "utf_types" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a3b425286980a367278453f3b6d28cdcb134b574e5a35824a6ff5eebad50bb6" + +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + +[[package]] +name = "walkdir" +version = "2.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b42e295b7452c4604982280d8586001fcad9b8b201cac67bca9771e7a7475403" +dependencies = [ + "same-file", + "winapi-util", +] + +[[package]] +name = "want" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec4cdd0dd910afe868b7ef477227d8d538b46b3075031afee8a9f2acb0a2ed0b" +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 = "wasm-bindgen" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a0181c14ddd6c7b8b0b0132a5f1ea2f32be0d893cd3ea97b6e3b28886b8a3d1c" +dependencies = [ + "cfg-if", + "rustversion", + "wasm-bindgen-macro", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-futures" +version = "0.4.80" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5e14e0327cb5368ad60ccb22d04a9827a693c95a926d8d125e9fa39e0baec501" +dependencies = [ + "js-sys", + "tokio", + "wasm-bindgen", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e931a02a39abdbf66966fc35902b5ed58344750a70885bed4ebb3d8eaf28ed9" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ca4b54280e455bd831e33a6b8e734baf432fe63fbc35c42ac14ce67a043a53a" +dependencies = [ + "bumpalo", + "proc-macro2", + "quote", + "syn 3.0.10", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b1f9c3798725016c6ee5f2f57869ec0831e8bbc0ab0310a86e787e97f41389e" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "web-sys" +version = "0.3.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d7d179596ff5ec0f6de4db64d54011bde6289cc49603d3a6e4ce3f329207ab88" +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-root-certs" +version = "1.0.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "293198dcebfb821155b5092ab94b5a82ff180eddd7241df3bd6e66a4ffd1a585" +dependencies = [ + "rustls-pki-types", +] + +[[package]] +name = "winapi-util" +version = "0.1.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-sys" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" +dependencies = [ + "windows-targets", +] + +[[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.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" +dependencies = [ + "windows_aarch64_gnullvm", + "windows_aarch64_msvc", + "windows_i686_gnu", + "windows_i686_gnullvm", + "windows_i686_msvc", + "windows_x86_64_gnu", + "windows_x86_64_gnullvm", + "windows_x86_64_msvc", +] + +[[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.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" + +[[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.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" + +[[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.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" + +[[package]] +name = "writeable" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc" + +[[package]] +name = "yoke" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "417ef3fcf6c300b7dbd25c85531a746931c02ad536f3cf4786ed1e88223340b3" +dependencies = [ + "stable_deref_trait", + "yoke-derive", + "zerofrom", +] + +[[package]] +name = "yoke-derive" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec8ebde2db3681e8c9980cc27822030e68752690ddfa9473e739aeb4dbde6d71" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", + "synstructure", +] + +[[package]] +name = "zerofrom" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272" +dependencies = [ + "zerofrom-derive", +] + +[[package]] +name = "zerofrom-derive" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f75b4683f6c7f45248d4d64056a24298c6281e0993356d7d1b4a1a962ef10d4a" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", + "synstructure", +] + +[[package]] +name = "zeroize" +version = "1.9.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85ccff8a4805aba1eaa4cd4afcd49f7557dd2cf5fd79ffc37f8959466effc5aa" + +[[package]] +name = "zerotrie" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ea269c3bd32f0a32c321907a2ae912ba6f4649bb0fc764a15627e99a7095a3f" +dependencies = [ + "displaydoc", + "yoke", + "zerofrom", +] + +[[package]] +name = "zerovec" +version = "0.11.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f58a2799cfe9a1670c7ea8edbd52ef8edb93cb37a7f83bf31ba9e35d9dae6a40" +dependencies = [ + "yoke", + "zerofrom", + "zerovec-derive", +] + +[[package]] +name = "zerovec-derive" +version = "0.11.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3743ddbf47738d929cd1ae2e199d40d0162979dfe31aef8ae646d2bf00bf97a" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..e8d6570 --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,50 @@ +[package] +name = "hibira" +version = "0.1.0" +edition = "2021" +description = "Hibira server SDK: Pusher-protocol realtime (trigger, channel auth, webhooks), waiting rooms with Axum and Actix middleware, Chat API, Approvals and Live Chat verified visitors" +license = "MIT" +repository = "https://github.com/hibira-io/rust" +homepage = "https://hibira.io" +documentation = "https://docs.rs/hibira" +readme = "README.md" +keywords = ["hibira", "pusher", "websocket", "realtime", "waiting-room"] +categories = ["web-programming", "api-bindings", "web-programming::websocket"] +exclude = [".github"] + +[features] +default = ["client"] +## The HTTP client: trigger events, Chat API, Approvals. +client = ["dep:reqwest"] +## Waiting room middleware for Axum. +axum = ["dep:axum"] +## Waiting room middleware for Actix Web. +actix = ["dep:actix-web"] + +[dependencies] +base64 = "0.22" +hex = "0.4" +hmac = "0.12" +md-5 = "0.10" +sha2 = "0.10" +serde = { version = "1", features = ["derive"] } +serde_json = "1" +thiserror = "2" +percent-encoding = "2" +url = "2" +http = "1" +cookie = "0.18" +reqwest = { version = "0.13", default-features = false, features = ["json", "rustls"], optional = true } +axum = { version = "0.8", default-features = false, optional = true } +actix-web = { version = "4.9", default-features = false, features = ["cookies"], optional = true } + +[dev-dependencies] +tokio = { version = "1", features = ["macros", "rt-multi-thread", "net", "io-util"] } +tower = { version = "0.5", features = ["util"] } +axum = { version = "0.8", default-features = false, features = ["tokio", "http1"] } +actix-web = { version = "4.9", default-features = false, features = ["macros", "cookies"] } +actix-rt = "2" + +[package.metadata.docs.rs] +all-features = true +rustdoc-args = ["--cfg", "docsrs"] diff --git a/README.md b/README.md new file mode 100644 index 0000000..165acaf --- /dev/null +++ b/README.md @@ -0,0 +1,153 @@ +# hibira + +The [Hibira](https://hibira.io) server SDK for Rust. + +- **Realtime** (Pusher protocol): trigger events, authorize private and presence channels, answer pusher-js `signin()`, verify webhooks. +- **Waiting rooms**: verify the signed passes visitors bring back from the hosted queue, with middleware for **Axum** and **Actix Web**. +- **Chat API**: conversations with stored history, read receipts and offline push. +- **Approvals**: ask a person for a decision from your app, an agent or a job, and read the answer. +- **Live Chat**: verified visitors for the Hibira Live Chat widget. + +## Using an AI coding assistant? + +Add the [Hibira MCP server](https://hibira.io/guides) to Claude Code, Cursor +or Codex and ask it to "add Hibira to this Axum app": `setup_project` creates +the app and env values, and `get_integration_guide` hands the assistant these +steps. + +## Install + +```toml +[dependencies] +hibira = { version = "0.1", features = ["axum"] } # or "actix" +``` + +Features: `client` (default: the HTTP client, using reqwest with rustls), +`axum`, `actix`. Without `client`, the crate has no network code: signing, +channel auth, webhooks, waiting room passes and Live Chat hashes only. + +Set the app's credentials from the Hibira console: + +```sh +HIBIRA_APP_ID=123 +HIBIRA_KEY=... +HIBIRA_SECRET=... # server only +HIBIRA_HOST=ws.hibira.io # as shown on the app page +``` + +## Realtime + +```rust,ignore +let config = hibira::Config::from_env()?; +let hibira = hibira::Client::new(config.clone()); +hibira.trigger(&["orders"], "order.shipped", &serde_json::json!({ "id": 1042 })).await?; + +// POST /pusher/auth: socket_id and channel_name from the form body +let auth = config.authorize_channel(&socket_id, &channel_name, None)?; +// presence: Some(r#"{"user_id":"7","user_info":{"name":"Ann"}}"#) + +// webhooks: the raw body and the X-Pusher-Key / X-Pusher-Signature headers +if let Some(hook) = config.verify_webhook(key_header, signature_header, &body) { + for event in hook.events { /* channel_occupied, member_added, ... */ } +} +``` + +## Waiting rooms + +Create a room in the Hibira console (or with the MCP `set_waiting_room` +tool), then put the guard in front of the pages it protects. Visitors without +a pass go to the hosted waiting page; the pass they bring back is stored in an +HttpOnly cookie, and the handler receives it. + +**Axum** + +```rust,ignore +use std::sync::Arc; +use axum::{middleware, routing::get, Extension, Router}; +use hibira::{waiting_room::axum_guard, Pass}; + +let guard = Arc::new(config.waiting_room("presale")); +let app = Router::new() + .route("/drop", get(|Extension(pass): Extension| async move { format!("You are number {}", pass.number) })) + .layer(middleware::from_fn_with_state(guard, axum_guard)); +``` + +**Actix Web** + +```rust,ignore +use actix_web::{middleware::from_fn, web, App, HttpResponse}; +use hibira::{waiting_room::actix_guard, Pass}; + +App::new() + .app_data(web::Data::new(config.waiting_room("presale"))) + .wrap(from_fn(actix_guard)) + .route("/drop", web::get().to(|pass: web::ReqData| async move { HttpResponse::Ok().body(format!("number {}", pass.number)) })); +``` + +For any other framework, `Guard::decide(method, uri, headers, https)` returns +`Allow(pass)`, `Redirect { location, set_cookie, .. }` or `Deny`, and +`waiting_room::verify(pass, &options)` checks a pass anywhere. Record +`pass.ticket_id` to allow one checkout per queue number. For rooms with one +place per signed-in customer, set `guard.user` to return +`waiting_room::sign_user(secret, room, user_id, ttl, None)`. + +## Chat API + +```rust,ignore +use hibira::{ConversationFields, SendMessageOptions}; + +let chat = hibira.chat(); +chat.put_conversation("order-1042", &ConversationFields { + name: Some("Order #1042".into()), + members: Some(vec!["buyer-7".into(), "seller-3".into()]), + ..Default::default() +}).await?; +chat.send_message("order-1042", "seller-3", "Shipped today!", &SendMessageOptions::default()).await?; +let page = chat.list_messages("order-1042", Some(0), Some(50), None).await?; +chat.mark_read("order-1042", "buyer-7", 12).await?; +``` + +`get_conversation`, `delete_conversation`, `add_members`, `remove_member`, +`system_message`, `user_conversations` and `request` (any other route) cover +the rest. See the [reference](https://hibira.io/chat-api/reference). + +## Approvals + +```rust,ignore +use hibira::approvals::NewApproval; + +let mut ask = NewApproval::new("Refund order #1042 for $89?"); +ask.options = Some(vec!["Refund".into(), "Decline".into()]); // the first option approves +let approval = hibira.approvals().request(&ask).await?; +// share approval.url with whoever decides, then +let approval = hibira.approvals().wait(&approval.approval_id, std::time::Duration::from_secs(600)).await?; +if approval.is_approved() { refund().await?; } +``` + +With `callback_url` set, Hibira POSTs `approval.decided` or +`approval.expired`, signed with the app secret: check it with +`hibira::approvals::verify_callback(secret, signature_header, &body, None)`. + +## Live Chat + +```rust,ignore +use hibira::livechat::{identity, script_tag, ScriptOptions}; + +let who = identity(&identity_secret, &user.id, Some(&user.name), Some(&user.email)); +let tag = script_tag(&ScriptOptions { workspace: "ws_...", identity: who.as_ref(), ..Default::default() }); +``` + +The identity secret is in Live Chat › Settings › Widget › Verified visitors. +For a single-page app, return `identity(...)` as JSON and call +`HibiraLiveChat.identify(it)` in the browser. + +## 中文摘要 + +`hibira` 是 [Hibira](https://hibira.io) 的 Rust 伺服器端 SDK: + +- **即時(Pusher 協定)**:發送事件、私有與 presence 頻道授權、pusher-js `signin()`、驗證 webhook。 +- **等候室**:驗證訪客從託管排隊頁帶回的簽名 pass,提供 Axum 與 Actix Web middleware;其他框架可用 `Guard::decide()`。 +- **Chat API**:建立對話、發訊息、讀取歷史、標記已讀。 +- **Approvals**:發出需要人決定的請求並等待結果,`verify_callback()` 驗證 callback 簽名。 +- **Live Chat**:`identity()`、`script_tag()` 讓登入使用者以驗證過的身分聊天。 +- 安裝:`hibira = { version = "0.1", features = ["axum"] }`,設定 `HIBIRA_APP_ID` / `HIBIRA_KEY` / `HIBIRA_SECRET`。關閉 `client` feature 時沒有任何網路程式碼。 diff --git a/src/approvals.rs b/src/approvals.rs new file mode 100644 index 0000000..00e9ca5 --- /dev/null +++ b/src/approvals.rs @@ -0,0 +1,234 @@ +//! Hibira Approvals (): ask a person for a +//! decision from your app, an agent or a job, and read the answer. + +use serde::{Deserialize, Serialize}; + +use crate::signing::hmac_sha256_verify; + +/// An approval request and its status. +#[derive(Debug, Clone, Deserialize, Serialize)] +pub struct Approval { + pub approval_id: String, + #[serde(default)] + pub title: String, + /// `pending`, `approved`, `rejected` or `expired`. + pub status: String, + /// The answer page to share with whoever decides. + #[serde(default)] + pub url: String, + #[serde(default)] + pub options: Vec, + #[serde(default)] + pub decision: Option, + #[serde(default)] + pub awaiting_reply: bool, + /// Every other field. + #[serde(flatten)] + pub extra: serde_json::Map, +} + +impl Approval { + pub fn is_pending(&self) -> bool { + self.status == "pending" + } + pub fn is_approved(&self) -> bool { + self.status == "approved" + } +} + +/// A new approval. Only `title` is required. +#[derive(Debug, Clone, Default, Serialize)] +pub struct NewApproval { + pub title: String, + #[serde(skip_serializing_if = "Option::is_none")] + pub details: Option, + /// 2 to 4 choices; the first approves. + #[serde(skip_serializing_if = "Option::is_none")] + pub options: Option>, + /// 1 to 10080 (default 60). + #[serde(skip_serializing_if = "Option::is_none")] + pub expires_in_minutes: Option, + /// A private channel that gets an `approval` event on request and decision. + #[serde(skip_serializing_if = "Option::is_none")] + pub channel: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub push_interests: Option>, + #[serde(skip_serializing_if = "Option::is_none")] + pub push_users: Option>, + /// Who is asking, such as the agent's name. + #[serde(skip_serializing_if = "Option::is_none")] + pub agent: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub approvers: Option>, + #[serde(skip_serializing_if = "Option::is_none")] + pub quorum: Option, + /// Receives a signed POST when decided; check it with [`verify_callback`]. + #[serde(skip_serializing_if = "Option::is_none")] + pub callback_url: Option, +} + +impl NewApproval { + pub fn new(title: impl Into) -> Self { + Self { + title: title.into(), + ..Self::default() + } + } +} + +/// A callback delivery: `approval.decided` or `approval.expired`. +#[derive(Debug, Clone, Deserialize)] +pub struct Event { + pub id: String, + #[serde(rename = "type")] + pub kind: String, + #[serde(default)] + pub created_at: String, + #[serde(default)] + pub workspace_id: Option, + pub data: EventData, +} + +#[derive(Debug, Clone, Deserialize)] +pub struct EventData { + pub approval: Approval, +} + +/// How old (seconds) a callback's timestamp may be. +pub const CALLBACK_TOLERANCE: i64 = 300; + +/// Checks a callback_url delivery (signed with the app secret) or an Approvals +/// workspace webhook (with that endpoint's secret) and returns its event. +/// `header` is the `Hibira-Signature` header, `t=,v1=`; `body` the +/// raw body; `now` Unix seconds (`None` for now). +pub fn verify_callback(secret: &str, header: &str, body: &[u8], now: Option) -> Option { + if secret.is_empty() { + return None; + } + let mut ts = None; + let mut sigs = Vec::new(); + for part in header.split(',') { + if let Some((k, v)) = part.trim().split_once('=') { + match k { + "t" => ts = Some(v), + "v1" => sigs.push(v), + _ => {} + } + } + } + let ts = ts?; + let t: i64 = ts.parse().ok()?; + let now = now.unwrap_or_else(|| { + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|d| d.as_secs() as i64) + .unwrap_or(0) + }); + if (now - t).abs() > CALLBACK_TOLERANCE || sigs.is_empty() { + return None; + } + let mut message = format!("{ts}.").into_bytes(); + message.extend_from_slice(body); + let ok = sigs.iter().any(|s| { + hex::decode(s).is_ok_and(|sig| hmac_sha256_verify(secret.as_bytes(), &message, &sig)) + }); + if !ok { + return None; + } + serde_json::from_slice(body).ok() +} + +#[cfg(feature = "client")] +pub use client::Approvals; + +#[cfg(feature = "client")] +mod client { + use std::time::{Duration, Instant}; + + use serde_json::json; + + use super::{Approval, NewApproval}; + use crate::client::{seg, Client}; + use crate::Error; + + const MAX_WAIT: u64 = 25; + + /// Approvals through the app's credentials, from [`Client::approvals`]. + #[derive(Debug, Clone, Copy)] + pub struct Approvals<'a> { + pub(crate) client: &'a Client, + } + + impl Approvals<'_> { + /// Creates an approval; share its `url` with whoever decides. + pub async fn request(&self, approval: &NewApproval) -> Result { + if approval.title.trim().is_empty() { + return Err(Error::Invalid("title is required".into())); + } + let body = serde_json::to_value(approval).map_err(|e| Error::Invalid(e.to_string()))?; + self.client + .request("POST", "/approvals", &[], Some(&body)) + .await + } + + /// An approval's status. `wait_secs` (up to 25) holds the request until it is answered. + pub async fn get(&self, approval_id: &str, wait_secs: u64) -> Result { + let wait = wait_secs.min(MAX_WAIT); + let query = if wait > 0 { + vec![("wait", wait.to_string())] + } else { + vec![] + }; + self.client + .request_with_timeout( + "GET", + &format!("/approvals/{}", seg(approval_id)?), + &query, + None, + Some(Duration::from_secs(wait + 15)), + ) + .await + } + + /// Answers an approver's question; `details`, when given, replaces the request's details. + pub async fn reply( + &self, + approval_id: &str, + message: &str, + details: Option<&str>, + ) -> Result { + if message.trim().is_empty() { + return Err(Error::Invalid("message is required".into())); + } + let mut body = json!({ "message": message }); + if let Some(d) = details { + body["details"] = d.into(); + } + self.client + .request( + "POST", + &format!("/approvals/{}/replies", seg(approval_id)?), + &[], + Some(&body), + ) + .await + } + + /// Polls until the approval is no longer pending, or `timeout` passes. + pub async fn wait(&self, approval_id: &str, timeout: Duration) -> Result { + let deadline = Instant::now() + timeout; + loop { + let left = deadline.saturating_duration_since(Instant::now()).as_secs(); + let approval = self.get(approval_id, left.min(MAX_WAIT)).await?; + if !approval.is_pending() || left <= MAX_WAIT { + return Ok(approval); + } + } + } + + /// [`super::verify_callback`] with the app secret. + pub fn verify_callback(&self, header: &str, body: &[u8]) -> Option { + super::verify_callback(&self.client.config().secret, header, body, None) + } + } +} diff --git a/src/chat.rs b/src/chat.rs new file mode 100644 index 0000000..e268017 --- /dev/null +++ b/src/chat.rs @@ -0,0 +1,216 @@ +use serde::Serialize; +use serde_json::{json, Map, Value}; + +use crate::client::{seg, Client}; +use crate::Error; + +/// The Chat API (): conversations with stored +/// history, read receipts and offline push. Clients receive `chat.*` events on +/// `#server-to-user-` after pusher-js `signin()`. +#[derive(Debug, Clone, Copy)] +pub struct Chat<'a> { + pub(crate) client: &'a Client, +} + +/// Fields of [`Chat::put_conversation`]. +#[derive(Debug, Clone, Default, Serialize)] +pub struct ConversationFields { + #[serde(skip_serializing_if = "Option::is_none")] + pub name: Option, + /// User IDs; `None` keeps the current members. + #[serde(skip_serializing_if = "Option::is_none")] + pub members: Option>, + #[serde(skip_serializing_if = "Option::is_none")] + pub metadata: Option, + /// `{ user_id: role }` + #[serde(skip_serializing_if = "Option::is_none")] + pub roles: Option>, + /// Up to 10 private or presence channels that also receive the events. + #[serde(skip_serializing_if = "Option::is_none")] + pub watchers: Option>, +} + +/// Options of [`Chat::send_message`]. +#[derive(Debug, Clone, Default, Serialize)] +pub struct SendMessageOptions { + #[serde(skip_serializing_if = "Option::is_none")] + pub name: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub metadata: Option, + /// `offline` (default), `always` or `never`. + #[serde(skip_serializing_if = "Option::is_none")] + pub push: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub push_title: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub push_url: Option, + /// Up to 5 roles that may see the message. + #[serde(skip_serializing_if = "Option::is_none")] + pub visible_to: Option>, + #[serde(skip_serializing_if = "Option::is_none")] + pub idempotency_key: Option, +} + +fn object(v: &T) -> Value { + serde_json::to_value(v).unwrap_or_else(|_| json!({})) +} + +impl Chat<'_> { + /// Any Chat API call, signed. `path` is relative to /apps/APP_ID/chat, + /// such as `/conversations/c1/typing`. + pub async fn request( + &self, + method: &str, + path: &str, + query: &[(&str, String)], + body: Option, + ) -> Result { + let method = method.to_uppercase(); + let path = if path.starts_with('/') { + path.to_string() + } else { + format!("/{path}") + }; + let body = body.or_else(|| matches!(method.as_str(), "POST" | "PUT").then(|| json!({}))); + self.client + .request(&method, &format!("/chat{path}"), query, body.as_ref()) + .await + } + + /// Creates or replaces a conversation. + pub async fn put_conversation( + &self, + id: &str, + fields: &ConversationFields, + ) -> Result { + self.request( + "PUT", + &format!("/conversations/{}", seg(id)?), + &[], + Some(object(fields)), + ) + .await + } + + pub async fn get_conversation(&self, id: &str) -> Result { + self.request("GET", &format!("/conversations/{}", seg(id)?), &[], None) + .await + } + + /// Deletes a conversation with its members, messages and files. + pub async fn delete_conversation(&self, id: &str) -> Result { + self.request("DELETE", &format!("/conversations/{}", seg(id)?), &[], None) + .await + } + + pub async fn add_members(&self, id: &str, user_ids: &[&str]) -> Result { + self.request( + "POST", + &format!("/conversations/{}/members", seg(id)?), + &[], + Some(json!({ "user_ids": user_ids })), + ) + .await + } + + pub async fn remove_member(&self, id: &str, user_id: &str) -> Result { + self.request( + "DELETE", + &format!("/conversations/{}/members/{}", seg(id)?, seg(user_id)?), + &[], + None, + ) + .await + } + + /// Posts a message as a member. + pub async fn send_message( + &self, + id: &str, + user_id: &str, + text: &str, + options: &SendMessageOptions, + ) -> Result { + let mut body = object(options); + body["user_id"] = user_id.into(); + body["text"] = text.into(); + self.request( + "POST", + &format!("/conversations/{}/messages", seg(id)?), + &[], + Some(body), + ) + .await + } + + /// Messages oldest first: after a seq (with limit), or the last n. + pub async fn list_messages( + &self, + id: &str, + after: Option, + limit: Option, + last: Option, + ) -> Result { + let mut q = Vec::new(); + if let Some(v) = after { + q.push(("after", v.to_string())); + } + if let Some(v) = limit { + q.push(("limit", v.to_string())); + } + if let Some(v) = last { + q.push(("last", v.to_string())); + } + self.request( + "GET", + &format!("/conversations/{}/messages", seg(id)?), + &q, + None, + ) + .await + } + + pub async fn mark_read(&self, id: &str, user_id: &str, seq: u64) -> Result { + self.request( + "POST", + &format!("/conversations/{}/read", seg(id)?), + &[], + Some(json!({ "user_id": user_id, "seq": seq })), + ) + .await + } + + /// A message with no sender, such as "Alice joined". + pub async fn system_message(&self, id: &str, text: &str) -> Result { + self.request( + "POST", + &format!("/conversations/{}/system", seg(id)?), + &[], + Some(json!({ "text": text })), + ) + .await + } + + /// A user's conversations, latest activity first, each with its unread count. + pub async fn user_conversations( + &self, + user_id: &str, + limit: Option, + before: Option<&str>, + ) -> Result { + let mut q = Vec::new(); + if let Some(v) = limit { + q.push(("limit", v.to_string())); + } + if let Some(v) = before { + q.push(("before", v.to_string())); + } + self.request( + "GET", + &format!("/users/{}/conversations", seg(user_id)?), + &q, + None, + ) + .await + } +} diff --git a/src/client.rs b/src/client.rs new file mode 100644 index 0000000..3103805 --- /dev/null +++ b/src/client.rs @@ -0,0 +1,202 @@ +use std::time::{Duration, SystemTime, UNIX_EPOCH}; + +use serde::de::DeserializeOwned; +use serde::Serialize; +use serde_json::Value; + +use crate::approvals::Approvals; +use crate::chat::Chat; +use crate::{signing, Config, Error}; + +/// The Hibira HTTP API client: trigger events, the Chat API and Approvals. +/// +/// ```no_run +/// # async fn run() -> Result<(), hibira::Error> { +/// let hibira = hibira::Client::new(hibira::Config::from_env()?); +/// hibira.trigger(&["orders"], "order.shipped", &serde_json::json!({ "id": 1042 })).await?; +/// # Ok(()) } +/// ``` +#[derive(Debug, Clone)] +pub struct Client { + config: Config, + http: reqwest::Client, +} + +impl Client { + pub fn new(config: Config) -> Self { + Self::with_http_client( + config, + reqwest::Client::builder() + .timeout(Duration::from_secs(40)) + .build() + .unwrap_or_default(), + ) + } + + /// Uses your own reqwest client (proxies, timeouts). + pub fn with_http_client(config: Config, http: reqwest::Client) -> Self { + Self { config, http } + } + + pub fn config(&self) -> &Config { + &self.config + } + + /// The Chat API. + pub fn chat(&self) -> Chat<'_> { + Chat { client: self } + } + + /// Hibira Approvals. + pub fn approvals(&self) -> Approvals<'_> { + Approvals { client: self } + } + + /// Publishes an event to up to 100 channels. `data` is serialized to JSON. + pub async fn trigger( + &self, + channels: &[&str], + event: &str, + data: &T, + ) -> Result { + self.trigger_excluding(channels, event, data, None).await + } + + /// Like [`Client::trigger`], leaving out the sender's own connection. + pub async fn trigger_excluding( + &self, + channels: &[&str], + event: &str, + data: &T, + socket_id: Option<&str>, + ) -> Result { + if channels.is_empty() || channels.len() > 100 { + return Err(Error::Invalid("trigger takes 1 to 100 channels".into())); + } + let data = serde_json::to_string(data).map_err(|e| Error::Invalid(e.to_string()))?; + let mut body = serde_json::json!({ "name": event, "channels": channels, "data": data }); + if let Some(id) = socket_id { + body["socket_id"] = id.into(); + } + self.request("POST", "/events", &[], Some(&body)).await + } + + /// Any signed API call: `resource` is relative to /apps/APP_ID, such as + /// `/channels`. Answers the JSON, or `{}` for an empty body. + pub async fn request( + &self, + method: &str, + resource: &str, + query: &[(&str, String)], + body: Option<&Value>, + ) -> Result { + self.request_with_timeout(method, resource, query, body, None) + .await + } + + pub(crate) async fn request_with_timeout( + &self, + method: &str, + resource: &str, + query: &[(&str, String)], + body: Option<&Value>, + timeout: Option, + ) -> Result { + let c = &self.config; + let missing: Vec<&str> = [ + ("HIBIRA_APP_ID", &c.app_id), + ("HIBIRA_KEY", &c.key), + ("HIBIRA_SECRET", &c.secret), + ] + .into_iter() + .filter(|(_, v)| v.is_empty()) + .map(|(k, _)| k) + .collect(); + if !missing.is_empty() { + return Err(Error::Config(format!("set {}", missing.join(", ")))); + } + if !resource.starts_with('/') { + return Err(Error::Invalid("resource must start with \"/\"".into())); + } + let method = method.to_uppercase(); + let path = format!("/apps/{}{}", c.app_id, resource); + let json = body.map(|b| serde_json::to_vec(b).expect("a Value serializes")); + let decoded = percent_encoding::percent_decode_str(&path) + .decode_utf8_lossy() + .into_owned(); + let ts = SystemTime::now() + .duration_since(UNIX_EPOCH) + .map(|d| d.as_secs()) + .unwrap_or(0); + let qs = signing::signed_query( + &method, + &decoded, + query, + json.as_deref(), + &c.key, + &c.secret, + ts, + ); + let scheme = if c.use_tls { "https" } else { "http" }; + let port = c.port.map(|p| format!(":{p}")).unwrap_or_default(); + let url = format!("{scheme}://{}{port}{path}?{qs}", c.host); + let verb = reqwest::Method::from_bytes(method.as_bytes()) + .map_err(|e| Error::Invalid(e.to_string()))?; + let mut req = self.http.request(verb, url).header( + "user-agent", + concat!("hibira-rust/", env!("CARGO_PKG_VERSION")), + ); + if let Some(t) = timeout { + req = req.timeout(t); + } + if let Some(json) = json { + req = req.header("content-type", "application/json").body(json); + } + let res = req.send().await?; + let status = res.status(); + let text = res.text().await?; + if !status.is_success() { + let message = serde_json::from_str::(&text) + .ok() + .and_then(|v| v.get("error").and_then(Value::as_str).map(str::to_string)) + .unwrap_or_else(|| { + if text.trim().is_empty() { + status.canonical_reason().unwrap_or("").to_string() + } else { + text.trim().to_string() + } + }); + return Err(Error::Api { + status: status.as_u16(), + message, + body: text, + }); + } + let text = if text.trim().is_empty() { "{}" } else { &text }; + serde_json::from_str(text).map_err(|e| Error::Api { + status: status.as_u16(), + message: format!("invalid JSON: {e}"), + body: text.to_string(), + }) + } +} + +/// Encodes one path segment and refuses an empty ID. +pub(crate) fn seg(id: &str) -> Result { + if id.is_empty() { + return Err(Error::Invalid("an ID is required".into())); + } + Ok(percent_encoding::utf8_percent_encode(id, UNRESERVED).to_string()) +} + +/// What encodeURIComponent escapes. +const UNRESERVED: &percent_encoding::AsciiSet = &percent_encoding::NON_ALPHANUMERIC + .remove(b'-') + .remove(b'_') + .remove(b'.') + .remove(b'!') + .remove(b'~') + .remove(b'*') + .remove(b'\'') + .remove(b'(') + .remove(b')'); diff --git a/src/lib.rs b/src/lib.rs new file mode 100644 index 0000000..b7bce83 --- /dev/null +++ b/src/lib.rs @@ -0,0 +1,166 @@ +#![cfg_attr(docsrs, feature(doc_cfg))] +#![doc = include_str!("../README.md")] +#![forbid(unsafe_code)] + +pub mod approvals; +pub mod livechat; +pub mod realtime; +pub mod signing; +pub mod waiting_room; + +#[cfg(feature = "client")] +mod chat; +#[cfg(feature = "client")] +mod client; + +#[cfg(feature = "client")] +#[cfg_attr(docsrs, doc(cfg(feature = "client")))] +pub use chat::{Chat, ConversationFields, SendMessageOptions}; +#[cfg(feature = "client")] +#[cfg_attr(docsrs, doc(cfg(feature = "client")))] +pub use client::Client; +pub use waiting_room::{Guard, Pass}; + +/// App credentials and the API host. +#[derive(Clone)] +pub struct Config { + pub app_id: String, + pub key: String, + /// Never send it to a browser. + pub secret: String, + /// As shown on the app page; defaults to `ws.hibira.io`. + pub host: String, + pub port: Option, + pub use_tls: bool, + /// Live Chat › Settings › Widget › Verified visitors secret. + pub livechat_identity_secret: Option, +} + +impl std::fmt::Debug for Config { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("Config") + .field("app_id", &self.app_id) + .field("key", &self.key) + .field("host", &self.host) + .field("port", &self.port) + .field("use_tls", &self.use_tls) + .finish_non_exhaustive() + } +} + +impl Config { + /// Credentials for an app on the default host. + pub fn new( + app_id: impl Into, + key: impl Into, + secret: impl Into, + ) -> Self { + Self { + app_id: app_id.into(), + key: key.into(), + secret: secret.into(), + host: "ws.hibira.io".into(), + port: None, + use_tls: true, + livechat_identity_secret: None, + } + } + + /// Reads HIBIRA_APP_ID, HIBIRA_KEY, HIBIRA_SECRET, HIBIRA_HOST, + /// HIBIRA_PORT, HIBIRA_USE_TLS and HIBIRA_LIVECHAT_IDENTITY_SECRET. + pub fn from_env() -> Result { + let var = |k: &str| std::env::var(k).ok().filter(|v| !v.is_empty()); + let missing: Vec<&str> = ["HIBIRA_APP_ID", "HIBIRA_KEY", "HIBIRA_SECRET"] + .into_iter() + .filter(|k| var(k).is_none()) + .collect(); + if !missing.is_empty() { + return Err(Error::Config(format!("set {}", missing.join(", ")))); + } + let mut c = Self::new( + var("HIBIRA_APP_ID").unwrap_or_default(), + var("HIBIRA_KEY").unwrap_or_default(), + var("HIBIRA_SECRET").unwrap_or_default(), + ); + if let Some(h) = var("HIBIRA_HOST") { + c.host = h; + } + c.port = var("HIBIRA_PORT").and_then(|p| p.parse().ok()); + c.use_tls = var("HIBIRA_USE_TLS").is_none_or(|v| v != "false"); + c.livechat_identity_secret = var("HIBIRA_LIVECHAT_IDENTITY_SECRET"); + Ok(c) + } + + /// The auth for a private or presence channel; see [`realtime::authorize_channel`]. + pub fn authorize_channel( + &self, + socket_id: &str, + channel: &str, + channel_data: Option<&str>, + ) -> Result { + realtime::authorize_channel(&self.key, &self.secret, socket_id, channel, channel_data) + } + + /// The pusher-js `signin()` response; see [`realtime::authenticate_user`]. + pub fn authenticate_user( + &self, + socket_id: &str, + user_data: &str, + ) -> Result { + realtime::authenticate_user(&self.key, &self.secret, socket_id, user_data) + } + + /// Checks and parses a webhook; see [`realtime::verify_webhook`]. + pub fn verify_webhook( + &self, + header_key: Option<&str>, + header_signature: Option<&str>, + body: &[u8], + ) -> Option { + realtime::verify_webhook(&self.key, &self.secret, header_key, header_signature, body) + } + + /// A Live Chat verified-visitor identity, with the configured identity secret. + pub fn livechat_identity( + &self, + user_id: &str, + name: Option<&str>, + email: Option<&str>, + ) -> Option { + livechat::identity( + self.livechat_identity_secret.as_deref()?, + user_id, + name, + email, + ) + } + + /// A waiting room [`Guard`] for `room`, with this app's key and secret. + pub fn waiting_room(&self, room: impl Into) -> Guard { + let mut g = Guard::new(self.key.clone(), self.secret.clone(), room); + g.app_id = Some(self.app_id.clone()); + g + } +} + +/// Errors from this crate. +#[derive(Debug, thiserror::Error)] +pub enum Error { + /// Missing credentials. + #[error("Hibira is not configured: {0}")] + Config(String), + /// A bad argument. + #[error("{0}")] + Invalid(String), + /// The API answered with an error status. + #[error("Hibira API {status}: {message}")] + Api { + status: u16, + message: String, + body: String, + }, + /// The request did not complete. + #[cfg(feature = "client")] + #[error(transparent)] + Http(#[from] reqwest::Error), +} diff --git a/src/livechat.rs b/src/livechat.rs new file mode 100644 index 0000000..06d622c --- /dev/null +++ b/src/livechat.rs @@ -0,0 +1,98 @@ +//! Hibira Live Chat verified visitors. + +use serde::Serialize; + +use crate::signing::hmac_sha256_hex; + +/// The Live Chat widget script. +pub const SCRIPT_URL: &str = "https://chat.hibira.io/w/v1.js"; + +/// hex(HMAC-SHA256(identity secret, user ID)): the widget's `data-user-hash`. +pub fn user_hash(identity_secret: &str, user_id: &str) -> String { + hmac_sha256_hex(identity_secret.as_bytes(), user_id.as_bytes()) +} + +/// Verified-visitor fields for a single-page app: pass them to +/// `HibiraLiveChat.identify()`. +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct Identity { + pub id: String, + pub hash: String, + #[serde(skip_serializing_if = "Option::is_none")] + pub name: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub email: Option, +} + +/// The identity for a user, or `None` without a secret or an ID. +pub fn identity( + identity_secret: &str, + user_id: &str, + name: Option<&str>, + email: Option<&str>, +) -> Option { + if identity_secret.is_empty() || user_id.is_empty() { + return None; + } + Some(Identity { + id: user_id.to_string(), + hash: user_hash(identity_secret, user_id), + name: name.filter(|s| !s.is_empty()).map(str::to_string), + email: email.filter(|s| !s.is_empty()).map(str::to_string), + }) +} + +/// Options for [`script_tag`]. +#[derive(Debug, Clone, Default)] +pub struct ScriptOptions<'a> { + pub workspace: &'a str, + pub identity: Option<&'a Identity>, + pub color: Option<&'a str>, + pub lang: Option<&'a str>, + /// `false` hides the launcher button. + pub hide_launcher: bool, + pub nonce: Option<&'a str>, +} + +/// The widget's `") +} + +fn escape(v: &str) -> String { + v.replace('&', "&") + .replace('"', """) + .replace('<', "<") + .replace('>', ">") +} diff --git a/src/realtime.rs b/src/realtime.rs new file mode 100644 index 0000000..59ab848 --- /dev/null +++ b/src/realtime.rs @@ -0,0 +1,107 @@ +//! Channel authorization, user sign-in and webhook verification. These need +//! no network; [`crate::Client::trigger`] publishes events. + +use serde::Deserialize; + +use crate::signing::{hmac_sha256_hex, hmac_sha256_verify}; + +/// The auth for a private or presence channel subscription: the JSON body to +/// return from your auth endpoint. `channel_data` is the presence member +/// (`{"user_id":"1","user_info":{...}}`) for presence channels. +pub fn authorize_channel( + key: &str, + secret: &str, + socket_id: &str, + channel: &str, + channel_data: Option<&str>, +) -> Result { + check_socket_id(socket_id)?; + let mut message = format!("{socket_id}:{channel}"); + if let Some(data) = channel_data { + message.push(':'); + message.push_str(data); + } + let auth = format!( + "{key}:{}", + hmac_sha256_hex(secret.as_bytes(), message.as_bytes()) + ); + Ok(match channel_data { + Some(data) => serde_json::json!({ "auth": auth, "channel_data": data }), + None => serde_json::json!({ "auth": auth }), + }) +} + +/// The response to pusher-js `signin()`: `user_data` is the user's JSON, with +/// at least an `id`. +pub fn authenticate_user( + key: &str, + secret: &str, + socket_id: &str, + user_data: &str, +) -> Result { + check_socket_id(socket_id)?; + let sig = hmac_sha256_hex( + secret.as_bytes(), + format!("{socket_id}::user::{user_data}").as_bytes(), + ); + Ok(serde_json::json!({ "auth": format!("{key}:{sig}"), "user_data": user_data })) +} + +fn check_socket_id(socket_id: &str) -> Result<(), crate::Error> { + let ok = socket_id.split_once('.').is_some_and(|(a, b)| { + !a.is_empty() + && !b.is_empty() + && a.bytes().all(|c| c.is_ascii_digit()) + && b.bytes().all(|c| c.is_ascii_digit()) + }); + if ok { + Ok(()) + } else { + Err(crate::Error::Invalid(format!( + "invalid socket_id {socket_id:?}" + ))) + } +} + +/// A verified webhook delivery. +#[derive(Debug, Clone, Deserialize)] +pub struct Webhook { + pub time_ms: i64, + pub events: Vec, +} + +/// One webhook event, such as `channel_occupied` or `member_added`. +#[derive(Debug, Clone, Deserialize)] +pub struct WebhookEvent { + pub name: String, + #[serde(default)] + pub channel: Option, + #[serde(default)] + pub event: Option, + #[serde(default)] + pub data: Option, + #[serde(default)] + pub socket_id: Option, + #[serde(default)] + pub user_id: Option, +} + +/// Checks a webhook's `X-Pusher-Key` and `X-Pusher-Signature` +/// (hex HMAC-SHA256 of the raw body) and parses it. Returns `None` when +/// anything is wrong. +pub fn verify_webhook( + key: &str, + secret: &str, + header_key: Option<&str>, + header_signature: Option<&str>, + body: &[u8], +) -> Option { + if header_key? != key { + return None; + } + let sig = hex::decode(header_signature?).ok()?; + if !hmac_sha256_verify(secret.as_bytes(), body, &sig) { + return None; + } + serde_json::from_slice(body).ok() +} diff --git a/src/signing.rs b/src/signing.rs new file mode 100644 index 0000000..8aa4be3 --- /dev/null +++ b/src/signing.rs @@ -0,0 +1,68 @@ +//! Signing for the Channels-protocol HTTP API (auth_version 1.0). + +use hmac::{Hmac, Mac}; +use md5::{Digest, Md5}; +use sha2::Sha256; + +type HmacSha256 = Hmac; + +/// hex(HMAC-SHA256(secret, message)). +pub fn hmac_sha256_hex(secret: &[u8], message: &[u8]) -> String { + hex::encode(hmac_sha256(secret, message)) +} + +pub(crate) fn hmac_sha256(secret: &[u8], message: &[u8]) -> [u8; 32] { + let mut mac = HmacSha256::new_from_slice(secret).expect("HMAC takes any key length"); + mac.update(message); + mac.finalize().into_bytes().into() +} + +/// Constant-time check of an HMAC-SHA256 over `message`. +pub(crate) fn hmac_sha256_verify(secret: &[u8], message: &[u8], signature: &[u8]) -> bool { + let mut mac = HmacSha256::new_from_slice(secret).expect("HMAC takes any key length"); + mac.update(message); + mac.verify_slice(signature).is_ok() +} + +/// The signed query string of a Channels-protocol HTTP API request: the +/// caller's query plus auth_key, auth_timestamp, auth_version, body_md5 (when +/// there is a body) and auth_signature, where auth_signature is +/// hex(HMAC-SHA256(secret, "METHOD\npath\nsorted k=v&...")). +/// +/// `path` is the decoded request path, such as `/apps/123/events`. +pub fn signed_query( + method: &str, + path: &str, + query: &[(&str, String)], + body: Option<&[u8]>, + key: &str, + secret: &str, + timestamp: u64, +) -> String { + let mut params: Vec<(String, String)> = query + .iter() + .map(|(k, v)| (k.to_string(), v.clone())) + .collect(); + params.push(("auth_key".into(), key.into())); + params.push(("auth_timestamp".into(), timestamp.to_string())); + params.push(("auth_version".into(), "1.0".into())); + if let Some(body) = body { + params.push(("body_md5".into(), hex::encode(Md5::digest(body)))); + } + params.sort(); + let sorted = params + .iter() + .map(|(k, v)| format!("{k}={v}")) + .collect::>() + .join("&"); + let signature = hmac_sha256_hex( + secret.as_bytes(), + format!("{}\n{}\n{}", method.to_uppercase(), path, sorted).as_bytes(), + ); + let mut out = url::form_urlencoded::Serializer::new(String::new()); + for (k, v) in ¶ms { + out.append_pair(k, v); + } + out.append_pair("auth_signature", &signature); + out.finish() +} diff --git a/src/waiting_room.rs b/src/waiting_room.rs new file mode 100644 index 0000000..58b09bd --- /dev/null +++ b/src/waiting_room.rs @@ -0,0 +1,465 @@ +//! Hibira waiting rooms: check the signed passes visitors bring back from the +//! hosted queue, and protect pages with a [`Guard`]. +//! +//! A visitor without a valid pass is redirected to the hosted waiting page (a +//! request other than GET or HEAD gets a 403). The `?hibira_pass=...` a +//! visitor brings back is checked, stored in the HttpOnly cookie +//! `hibira_wr_` and removed from the URL. This matches +//! `@hibira-io/waiting-room/server`, the Go module and the framework packages. + +use std::time::{SystemTime, UNIX_EPOCH}; + +use base64::engine::general_purpose::URL_SAFE_NO_PAD; +use base64::Engine; +use http::{header, HeaderMap, Method, Uri}; +use percent_encoding::{utf8_percent_encode, AsciiSet, NON_ALPHANUMERIC}; +use serde::{Deserialize, Serialize}; + +use crate::signing::{hmac_sha256, hmac_sha256_verify}; + +/// Serves the hosted waiting page. +pub const DEFAULT_HOST: &str = "https://ws.hibira.io"; +const PASS_PURPOSE: &str = "hibira-waitroom-pass."; +const USER_PURPOSE: &str = "hibira-waitroom-user."; +const PARAM: &str = "hibira_pass"; +const MAX_PASS_LEN: usize = 1024; + +/// Characters Go's url.PathEscape leaves alone. +const PATH_SEGMENT: &AsciiSet = &NON_ALPHANUMERIC + .remove(b'-') + .remove(b'.') + .remove(b'_') + .remove(b'~') + .remove(b'$') + .remove(b'&') + .remove(b'+') + .remove(b',') + .remove(b':') + .remove(b'=') + .remove(b'@'); + +/// A verified waiting room pass. +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct Pass { + pub app_id: String, + pub room: String, + /// The visitor's queue number. + pub number: i64, + /// The queue ticket's ID: record it to allow one checkout per number. + pub ticket_id: String, + /// The signed user ID, in rooms with one place per signed-in customer. + pub user_id: Option, + pub issued_at: i64, + pub expires_at: i64, +} + +#[derive(Deserialize)] +struct Claims { + v: i64, + #[serde(default)] + app: String, + #[serde(default)] + room: String, + #[serde(default)] + n: i64, + #[serde(default)] + tid: String, + #[serde(default)] + sub: Option, + #[serde(default)] + iat: i64, + exp: Option, +} + +/// Which passes [`verify`] accepts. +#[derive(Debug, Clone, Default)] +pub struct VerifyOptions<'a> { + /// The app secret; give the old and the new one during a rotation. + pub secrets: &'a [String], + /// When set, must match the pass. + pub room: Option<&'a str>, + /// When set, must match the pass. + pub app_id: Option<&'a str>, + /// Unix seconds; defaults to now. + pub now: Option, +} + +fn unix_now() -> i64 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .map(|d| d.as_secs() as i64) + .unwrap_or(0) +} + +/// Checks a pass. Returns `None` when it is missing, forged, expired, or for +/// another room or app. +pub fn verify(pass: &str, o: &VerifyOptions<'_>) -> Option { + if o.secrets.is_empty() || pass.is_empty() || pass.len() > MAX_PASS_LEN { + return None; + } + let (payload, sig) = pass.split_once('.')?; + if payload.is_empty() { + return None; + } + let sig = URL_SAFE_NO_PAD.decode(sig).ok()?; + if sig.len() != 32 { + return None; + } + let message = format!("{PASS_PURPOSE}{payload}"); + if !o + .secrets + .iter() + .filter(|s| !s.is_empty()) + .any(|s| hmac_sha256_verify(s.as_bytes(), message.as_bytes(), &sig)) + { + return None; + } + let raw = URL_SAFE_NO_PAD.decode(payload).ok()?; + let c: Claims = serde_json::from_slice(&raw).ok()?; + let exp = c.exp?; + if c.v != 1 || o.now.unwrap_or_else(unix_now) >= exp { + return None; + } + if o.room.is_some_and(|r| !r.is_empty() && r != c.room) + || o.app_id.is_some_and(|a| !a.is_empty() && a != c.app) + { + return None; + } + Some(Pass { + app_id: c.app, + room: c.room, + number: c.n, + ticket_id: c.tid, + user_id: c.sub, + issued_at: c.iat, + expires_at: exp, + }) +} + +/// Signs a user token for rooms with one place per signed-in customer: the +/// same user ID gets the same place in every browser. `user_id` is 1 to 128 +/// characters without "."; `ttl_secs` is capped at 7 days (0 means 1 hour). +pub fn sign_user( + secret: &str, + room: &str, + user_id: &str, + ttl_secs: u64, + now: Option, +) -> Result { + if user_id.is_empty() || user_id.len() > 128 || user_id.contains('.') { + return Err(crate::Error::Invalid( + r#"user_id must be 1 to 128 characters without ".""#.into(), + )); + } + let ttl = if ttl_secs == 0 { + 3600 + } else { + ttl_secs.min(7 * 24 * 3600) + } as i64; + let exp = now.unwrap_or_else(unix_now) + ttl; + let sig = hmac_sha256( + secret.as_bytes(), + format!("{USER_PURPOSE}{room}.{user_id}.{exp}").as_bytes(), + ); + Ok(format!("{user_id}.{exp}.{}", hex::encode(sig))) +} + +/// The hosted waiting page for a room. +#[derive(Debug, Clone, Default)] +pub struct UrlOptions<'a> { + pub app_key: &'a str, + pub room: &'a str, + pub return_url: Option<&'a str>, + /// Defaults to [`DEFAULT_HOST`]. + pub host: Option<&'a str>, + /// en, zh-TW, zh-CN, ja, ko, th, vi, it or fr. + pub lang: Option<&'a str>, + /// A token from [`sign_user`]. + pub user: Option<&'a str>, +} + +/// The hosted waiting page address for a room. +pub fn waiting_room_url(o: &UrlOptions<'_>) -> String { + let host = o + .host + .filter(|h| !h.is_empty()) + .unwrap_or(DEFAULT_HOST) + .trim_end_matches('/'); + let mut url = format!( + "{host}/wait/{}/{}", + utf8_percent_encode(o.app_key, PATH_SEGMENT), + utf8_percent_encode(o.room, PATH_SEGMENT) + ); + let mut q = url::form_urlencoded::Serializer::new(String::new()); + let mut any = false; + for (k, v) in [("lang", o.lang), ("return", o.return_url), ("user", o.user)] { + if let Some(v) = v.filter(|v| !v.is_empty()) { + q.append_pair(k, v); + any = true; + } + } + if any { + url.push('?'); + url.push_str(&q.finish()); + } + url +} + +/// Protects pages with one waiting room. +#[derive(Clone, Default)] +pub struct Guard { + pub app_key: String, + /// The app secret; give the old and the new one during a rotation. + pub secrets: Vec, + pub room: String, + /// When set, must match the pass. + pub app_id: Option, + /// Defaults to [`DEFAULT_HOST`]. + pub host: Option, + pub lang: Option, + /// Defaults to `hibira_wr_`. + pub cookie_name: Option, + /// Returns a [`sign_user`] token for the request's signed-in customer. + #[allow(clippy::type_complexity)] + pub user: Option Option + Send + Sync>>, + /// Unix seconds; defaults to now (for tests). + pub now: Option, +} + +impl std::fmt::Debug for Guard { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("Guard") + .field("app_key", &self.app_key) + .field("room", &self.room) + .finish_non_exhaustive() + } +} + +/// What to do with a request. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Decision { + /// Serve the page. + Allow(Pass), + /// Answer 302 to `location` with `Cache-Control: no-store`, setting `set_cookie` when given. + Redirect { + location: String, + set_cookie: Option, + pass: Option, + }, + /// Answer 403 with [`DENY_BODY`]: a request other than GET or HEAD without a pass. + Deny, +} + +/// The JSON body of a [`Decision::Deny`] response. +pub const DENY_BODY: &str = r#"{"error":"waiting_room","message":"join the waiting room first"}"#; + +impl Guard { + /// A guard for `room`, with the app key and secret. + pub fn new( + app_key: impl Into, + secret: impl Into, + room: impl Into, + ) -> Self { + Self { + app_key: app_key.into(), + secrets: vec![secret.into()], + room: room.into(), + ..Self::default() + } + } + + /// The pass cookie's name. + pub fn cookie_name(&self) -> String { + self.cookie_name + .clone() + .unwrap_or_else(|| format!("hibira_wr_{}", self.room)) + } + + /// Works out what to do with a request. `https` is whether the request + /// came over TLS; `X-Forwarded-Proto: https` also counts. + pub fn decide(&self, method: &Method, uri: &Uri, headers: &HeaderMap, https: bool) -> Decision { + let now = self.now.unwrap_or_else(unix_now); + let vo = VerifyOptions { + secrets: &self.secrets, + room: Some(&self.room), + app_id: self.app_id.as_deref(), + now: Some(now), + }; + let forwarded = headers + .get("x-forwarded-proto") + .and_then(|v| v.to_str().ok()) + .is_some_and(|v| v.eq_ignore_ascii_case("https")); + let scheme = if https || forwarded { "https" } else { "http" }; + let host = headers + .get(header::HOST) + .and_then(|v| v.to_str().ok()) + .map(str::to_string) + .or_else(|| uri.authority().map(|a| a.to_string())) + .unwrap_or_else(|| "localhost".into()); + let path = uri.path(); + let mut from_queue = None; + let mut kept = url::form_urlencoded::Serializer::new(String::new()); + let mut kept_any = false; + for (k, v) in url::form_urlencoded::parse(uri.query().unwrap_or("").as_bytes()) { + if k == PARAM { + if from_queue.is_none() { + from_queue = Some(v.into_owned()); + } + } else { + kept.append_pair(&k, &v); + kept_any = true; + } + } + let kept = kept.finish(); + let here = if kept_any { + format!("{scheme}://{host}{path}?{kept}") + } else { + format!("{scheme}://{host}{path}") + }; + + if let Some(token) = from_queue.filter(|t| !t.is_empty()) { + if let Some(pass) = verify(&token, &vo) { + let max_age = (pass.expires_at - now).max(1); + let secure = if scheme == "https" { "; Secure" } else { "" }; + let cookie = format!( + "{}={token}; Path=/; Max-Age={max_age}; HttpOnly; SameSite=Lax{secure}", + self.cookie_name() + ); + return Decision::Redirect { + location: here, + set_cookie: Some(cookie), + pass: Some(pass), + }; + } + } + let name = self.cookie_name(); + for value in headers + .get_all(header::COOKIE) + .iter() + .filter_map(|v| v.to_str().ok()) + { + for c in cookie::Cookie::split_parse(value).flatten() { + if c.name() == name { + if let Some(pass) = verify(c.value(), &vo) { + return Decision::Allow(pass); + } + } + } + } + if method != Method::GET && method != Method::HEAD { + return Decision::Deny; + } + let user = self.user.as_ref().and_then(|f| f(headers)); + Decision::Redirect { + location: waiting_room_url(&UrlOptions { + app_key: &self.app_key, + room: &self.room, + return_url: Some(&here), + host: self.host.as_deref(), + lang: self.lang.as_deref(), + user: user.as_deref(), + }), + set_cookie: None, + pass: None, + } + } +} + +/// Axum middleware: `axum::middleware::from_fn_with_state(Arc::new(guard), hibira::waiting_room::axum_guard)`. +/// The handler gets the pass with `Extension`. +#[cfg(feature = "axum")] +#[cfg_attr(docsrs, doc(cfg(feature = "axum")))] +pub async fn axum_guard( + axum::extract::State(guard): axum::extract::State>, + mut request: axum::extract::Request, + next: axum::middleware::Next, +) -> axum::response::Response { + use axum::response::IntoResponse; + let https = request.uri().scheme_str() == Some("https"); + match guard.decide(request.method(), request.uri(), request.headers(), https) { + Decision::Allow(pass) => { + request.extensions_mut().insert(pass); + next.run(request).await + } + Decision::Deny => ( + http::StatusCode::FORBIDDEN, + [ + (header::CACHE_CONTROL, "no-store"), + (header::CONTENT_TYPE, "application/json"), + ], + DENY_BODY, + ) + .into_response(), + Decision::Redirect { + location, + set_cookie, + .. + } => { + let mut res = ( + http::StatusCode::FOUND, + [(header::CACHE_CONTROL, "no-store")], + ) + .into_response(); + if let Ok(v) = http::HeaderValue::from_str(&location) { + res.headers_mut().insert(header::LOCATION, v); + } + if let Some(c) = set_cookie.and_then(|c| http::HeaderValue::from_str(&c).ok()) { + res.headers_mut().insert(header::SET_COOKIE, c); + } + res + } + } +} + +/// Actix Web middleware, for `actix_web::middleware::from_fn(hibira::waiting_room::actix_guard)` +/// with the guard registered as `app_data(web::Data::new(guard))`. The handler +/// gets the pass with `web::ReqData`. +#[cfg(feature = "actix")] +#[cfg_attr(docsrs, doc(cfg(feature = "actix")))] +pub async fn actix_guard( + request: actix_web::dev::ServiceRequest, + next: actix_web::middleware::Next, +) -> Result>, actix_web::Error> { + use actix_web::HttpMessage; + let Some(guard) = request.app_data::>().cloned() else { + return Err(actix_web::error::ErrorInternalServerError( + "hibira waiting room: register the Guard with app_data(web::Data::new(guard))", + )); + }; + let https = request.connection_info().scheme() == "https"; + let method = Method::from_bytes(request.method().as_str().as_bytes()).unwrap_or(Method::GET); + let uri: Uri = request.uri().to_string().parse().unwrap_or_default(); + let mut headers = HeaderMap::new(); + for (k, v) in request.headers() { + if let (Ok(k), Ok(v)) = ( + http::HeaderName::from_bytes(k.as_str().as_bytes()), + http::HeaderValue::from_bytes(v.as_bytes()), + ) { + headers.append(k, v); + } + } + let response = match guard.decide(&method, &uri, &headers, https) { + Decision::Allow(pass) => { + request.extensions_mut().insert(pass); + return Ok(next.call(request).await?.map_into_left_body()); + } + Decision::Deny => actix_web::HttpResponse::Forbidden() + .insert_header(("cache-control", "no-store")) + .content_type("application/json") + .body(DENY_BODY), + Decision::Redirect { + location, + set_cookie, + .. + } => { + let mut res = actix_web::HttpResponse::Found(); + res.insert_header(("cache-control", "no-store")) + .insert_header(("location", location)); + if let Some(c) = set_cookie { + res.insert_header(("set-cookie", c)); + } + res.finish() + } + }; + Ok(request.into_response(response).map_into_right_body()) +} diff --git a/tests/client.rs b/tests/client.rs new file mode 100644 index 0000000..62cf8a2 --- /dev/null +++ b/tests/client.rs @@ -0,0 +1,271 @@ +#![cfg(feature = "client")] + +use std::sync::{Arc, Mutex}; + +use axum::body::Bytes; +use axum::extract::{Request, State}; +use axum::http::StatusCode; +use axum::response::IntoResponse; +use hibira::approvals::NewApproval; +use hibira::signing::hmac_sha256_hex; +use hibira::{Client, Config, ConversationFields, SendMessageOptions}; +use md5::{Digest, Md5}; + +#[derive(Debug, Clone)] +struct Seen { + method: String, + path: String, + query: Vec<(String, String)>, + body: String, +} + +type Log = Arc, Vec<(u16, String)>)>>; + +async fn record(State(log): State, req: Request) -> impl IntoResponse { + let method = req.method().to_string(); + let path = req.uri().path().to_string(); + let query = url::form_urlencoded::parse(req.uri().query().unwrap_or("").as_bytes()) + .into_owned() + .collect(); + let body: Bytes = axum::body::to_bytes(req.into_body(), 1 << 20) + .await + .unwrap(); + let mut g = log.lock().unwrap(); + g.0.push(Seen { + method, + path, + query, + body: String::from_utf8(body.to_vec()).unwrap(), + }); + let (status, body) = if g.1.is_empty() { + (200, "{}".to_string()) + } else { + g.1.remove(0) + }; + (StatusCode::from_u16(status).unwrap(), body) +} + +async fn fake(responses: Vec<(u16, &str)>) -> (Client, Log) { + let log: Log = Arc::new(Mutex::new(( + vec![], + responses + .into_iter() + .map(|(s, b)| (s, b.to_string())) + .collect(), + ))); + let app = axum::Router::new().fallback(record).with_state(log.clone()); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let port = listener.local_addr().unwrap().port(); + tokio::spawn(async move { axum::serve(listener, app).await.unwrap() }); + let mut c = Config::new("1", "app-key", "app-secret"); + c.host = "127.0.0.1".into(); + c.port = Some(port); + c.use_tls = false; + (Client::new(c), log) +} + +fn assert_signed(s: &Seen) { + let mut q: Vec<(String, String)> = s + .query + .iter() + .filter(|(k, _)| k != "auth_signature") + .cloned() + .collect(); + q.sort(); + let sig = &s + .query + .iter() + .find(|(k, _)| k == "auth_signature") + .unwrap() + .1; + let sorted = q + .iter() + .map(|(k, v)| format!("{k}={v}")) + .collect::>() + .join("&"); + let path = percent_encoding::percent_decode_str(&s.path).decode_utf8_lossy(); + assert_eq!( + sig, + &hmac_sha256_hex( + b"app-secret", + format!("{}\n{}\n{}", s.method, path, sorted).as_bytes() + ) + ); + let md5 = q + .iter() + .find(|(k, _)| k == "body_md5") + .map(|(_, v)| v.clone()); + if s.body.is_empty() { + assert_eq!(md5, None); + } else { + assert_eq!(md5.unwrap(), hex::encode(Md5::digest(s.body.as_bytes()))); + } +} + +fn user_query(s: &Seen) -> Vec<(String, String)> { + s.query + .iter() + .filter(|(k, _)| !k.starts_with("auth_") && k != "body_md5") + .cloned() + .collect() +} + +fn json(s: &Seen) -> serde_json::Value { + serde_json::from_str(&s.body).unwrap() +} + +#[tokio::test] +async fn trigger_posts_a_signed_event() { + let (hibira, log) = fake(vec![]).await; + hibira + .trigger( + &["orders"], + "order.shipped", + &serde_json::json!({ "id": 1042 }), + ) + .await + .unwrap(); + let s = log.lock().unwrap().0[0].clone(); + assert_eq!( + (s.method.as_str(), s.path.as_str()), + ("POST", "/apps/1/events") + ); + assert_eq!( + json(&s), + serde_json::json!({ "name": "order.shipped", "channels": ["orders"], "data": "{\"id\":1042}" }) + ); + assert_signed(&s); + assert!(hibira.trigger(&[], "x", &1).await.is_err()); +} + +#[tokio::test] +async fn chat_routes() { + let (hibira, log) = fake(vec![]).await; + let chat = hibira.chat(); + chat.put_conversation( + "order 1", + &ConversationFields { + name: Some("Order 1".into()), + members: Some(vec!["u1".into(), "u2".into()]), + ..Default::default() + }, + ) + .await + .unwrap(); + chat.get_conversation("order 1").await.unwrap(); + chat.delete_conversation("order 1").await.unwrap(); + chat.add_members("c1", &["u3"]).await.unwrap(); + chat.remove_member("c1", "u/3").await.unwrap(); + chat.send_message( + "c1", + "u1", + "Hi", + &SendMessageOptions { + push: Some("offline".into()), + ..Default::default() + }, + ) + .await + .unwrap(); + chat.list_messages("c1", Some(5), Some(20), None) + .await + .unwrap(); + chat.mark_read("c1", "u1", 7).await.unwrap(); + chat.system_message("c1", "Alice joined").await.unwrap(); + chat.user_conversations("u1", Some(10), Some("c9")) + .await + .unwrap(); + chat.request("post", "conversations/c1/typing", &[], None) + .await + .unwrap(); + let s = log.lock().unwrap().0.clone(); + assert_eq!( + (s[0].method.as_str(), s[0].path.as_str()), + ("PUT", "/apps/1/chat/conversations/order%201") + ); + assert_eq!( + json(&s[0]), + serde_json::json!({ "name": "Order 1", "members": ["u1", "u2"] }) + ); + assert_eq!((s[1].method.as_str(), s[1].body.as_str()), ("GET", "")); + assert_eq!(s[2].method, "DELETE"); + assert_eq!(json(&s[3]), serde_json::json!({ "user_ids": ["u3"] })); + assert_eq!(s[4].path, "/apps/1/chat/conversations/c1/members/u%2F3"); + assert_eq!( + json(&s[5]), + serde_json::json!({ "user_id": "u1", "text": "Hi", "push": "offline" }) + ); + assert_eq!( + user_query(&s[6]), + vec![("after".into(), "5".into()), ("limit".into(), "20".into())] + ); + assert_eq!( + json(&s[7]), + serde_json::json!({ "user_id": "u1", "seq": 7 }) + ); + assert_eq!(json(&s[8]), serde_json::json!({ "text": "Alice joined" })); + assert_eq!(s[9].path, "/apps/1/chat/users/u1/conversations"); + assert_eq!( + (s[10].path.as_str(), s[10].body.as_str()), + ("/apps/1/chat/conversations/c1/typing", "{}") + ); + s.iter().for_each(assert_signed); +} + +#[tokio::test] +async fn approvals_and_errors() { + let pending = r#"{"approval_id":"apr_1","title":"Refund?","status":"pending","url":"https://approvals.hibira.io/a/apr_1"}"#; + let approved = r#"{"approval_id":"apr_1","title":"Refund?","status":"approved","url":"u"}"#; + let (hibira, log) = fake(vec![ + (201, pending), + (200, pending), + (200, approved), + (201, pending), + (402, r#"{"error":"Approvals is not on this plan"}"#), + ]) + .await; + let mut a = NewApproval::new("Refund?"); + a.options = Some(vec!["Refund".into(), "Decline".into()]); + a.expires_in_minutes = Some(120); + let out = hibira.approvals().request(&a).await.unwrap(); + assert_eq!(out.url, "https://approvals.hibira.io/a/apr_1"); + let done = hibira + .approvals() + .wait("apr_1", std::time::Duration::from_secs(600)) + .await + .unwrap(); + assert!(done.is_approved()); + hibira + .approvals() + .reply("apr_1", "Staging only.", None) + .await + .unwrap(); + let err = hibira.approvals().get("apr_1", 0).await.unwrap_err(); + assert!( + matches!(err, hibira::Error::Api { status: 402, ref message, .. } if message.contains("not on this plan")), + "{err}" + ); + let s = log.lock().unwrap().0.clone(); + assert_eq!( + json(&s[0]), + serde_json::json!({ "title": "Refund?", "options": ["Refund", "Decline"], "expires_in_minutes": 120 }) + ); + assert_eq!(user_query(&s[1]), vec![("wait".into(), "25".into())]); + assert_eq!(s[3].path, "/apps/1/approvals/apr_1/replies"); + assert!(user_query(&s[4]).is_empty()); + s.iter().for_each(assert_signed); + assert!(hibira + .approvals() + .request(&NewApproval::new(" ")) + .await + .is_err()); +} + +#[tokio::test] +async fn missing_credentials_name_the_variables() { + let hibira = Client::new(Config::new("", "", "")); + let err = hibira.approvals().get("apr_1", 0).await.unwrap_err(); + assert!(err + .to_string() + .contains("HIBIRA_APP_ID, HIBIRA_KEY, HIBIRA_SECRET")); +} diff --git a/tests/middleware.rs b/tests/middleware.rs new file mode 100644 index 0000000..1c9dfee --- /dev/null +++ b/tests/middleware.rs @@ -0,0 +1,169 @@ +#![cfg(all(feature = "axum", feature = "actix"))] + +use std::sync::Arc; + +use hibira::waiting_room::{actix_guard, axum_guard}; +use hibira::{Guard, Pass}; + +const SECRET: &str = "wr-secret-0123456789"; +const PASS: &str = "eyJ2IjoxLCJhcHAiOiJ3ci1hcHAiLCJyb29tIjoicHJlc2FsZSIsIm4iOjQyLCJ0aWQiOiJkNzlmZTc4OWEzOGI4NjMxYjUiLCJpYXQiOjE4MDAwMDAwMDAsImV4cCI6MTgwMDAwMTgwMH0.q7Uc_O6XKwNA_LVLQITlgv_YtDi9dIwiRzUUUSsGa08"; + +fn guard() -> Guard { + let mut g = Guard::new("key", SECRET, "presale"); + g.now = Some(1800000100); + g +} + +mod axum_tests { + use super::*; + use axum::body::Body; + use axum::http::Request; + use axum::routing::get; + use axum::Extension; + use tower::ServiceExt; + + fn app() -> axum::Router { + axum::Router::new() + .route( + "/drop", + get(|Extension(p): Extension| async move { format!("number {}", p.number) }) + .post(|| async { "posted" }), + ) + .layer(axum::middleware::from_fn_with_state( + Arc::new(guard()), + axum_guard, + )) + } + + #[tokio::test] + async fn redirects_denies_and_allows() { + let res = app() + .oneshot( + Request::get("/drop") + .header("host", "shop.test") + .body(Body::empty()) + .unwrap(), + ) + .await + .unwrap(); + assert_eq!(res.status(), 302); + assert_eq!( + res.headers()["location"], + "https://ws.hibira.io/wait/key/presale?return=http%3A%2F%2Fshop.test%2Fdrop" + ); + assert_eq!(res.headers()["cache-control"], "no-store"); + + let res = app() + .oneshot( + Request::post("/drop") + .header("host", "shop.test") + .body(Body::empty()) + .unwrap(), + ) + .await + .unwrap(); + assert_eq!(res.status(), 403); + + let res = app() + .oneshot( + Request::get(format!("/drop?hibira_pass={PASS}")) + .header("host", "shop.test") + .header("x-forwarded-proto", "https") + .body(Body::empty()) + .unwrap(), + ) + .await + .unwrap(); + assert_eq!(res.status(), 302); + assert_eq!(res.headers()["location"], "https://shop.test/drop"); + assert!(res.headers()["set-cookie"] + .to_str() + .unwrap() + .starts_with("hibira_wr_presale=")); + + let res = app() + .oneshot( + Request::get("/drop") + .header("host", "shop.test") + .header("cookie", format!("hibira_wr_presale={PASS}")) + .body(Body::empty()) + .unwrap(), + ) + .await + .unwrap(); + assert_eq!(res.status(), 200); + let body = axum::body::to_bytes(res.into_body(), 1024).await.unwrap(); + assert_eq!(&body[..], b"number 42"); + } +} + +mod actix_tests { + use super::*; + use actix_web::{middleware::from_fn, test, web, App, HttpResponse}; + + #[actix_web::test] + async fn redirects_denies_and_allows() { + let app = test::init_service( + App::new() + .app_data(web::Data::new(guard())) + .wrap(from_fn(actix_guard)) + .route( + "/drop", + web::get().to(|p: web::ReqData| async move { + HttpResponse::Ok().body(format!("number {}", p.number)) + }), + ) + .route( + "/drop", + web::post().to(|| async { HttpResponse::Ok().finish() }), + ), + ) + .await; + + let res = test::call_service( + &app, + test::TestRequest::get() + .uri("/drop") + .insert_header(("host", "shop.test")) + .to_request(), + ) + .await; + assert_eq!(res.status(), 302); + assert_eq!( + res.headers().get("location").unwrap(), + "https://ws.hibira.io/wait/key/presale?return=http%3A%2F%2Fshop.test%2Fdrop" + ); + + let res = + test::call_service(&app, test::TestRequest::post().uri("/drop").to_request()).await; + assert_eq!(res.status(), 403); + + let res = test::call_service( + &app, + test::TestRequest::get() + .uri(&format!("/drop?a=1&hibira_pass={PASS}")) + .insert_header(("host", "shop.test")) + .to_request(), + ) + .await; + assert_eq!(res.status(), 302); + assert_eq!( + res.headers().get("location").unwrap(), + "http://shop.test/drop?a=1" + ); + assert!(res + .headers() + .get("set-cookie") + .unwrap() + .to_str() + .unwrap() + .contains("HttpOnly")); + + let req = test::TestRequest::get() + .uri("/drop") + .insert_header(("cookie", format!("hibira_wr_presale={PASS}"))) + .to_request(); + let body = test::call_and_read_body(&app, req).await; + assert_eq!(&body[..], b"number 42"); + } +} diff --git a/tests/realtime.rs b/tests/realtime.rs new file mode 100644 index 0000000..e42e587 --- /dev/null +++ b/tests/realtime.rs @@ -0,0 +1,123 @@ +use hibira::livechat::{identity, script_tag, user_hash, ScriptOptions}; +use hibira::signing::{hmac_sha256_hex, signed_query}; +use hibira::{approvals, Config}; + +fn config() -> Config { + Config::new("1", "278d425bdf160c739803", "7ad3773142a6692b25b8") +} + +#[test] +fn channel_auth_matches_the_pusher_docs() { + // https://pusher.com/docs/channels/library_auth_reference/auth-signatures/ + let auth = config() + .authorize_channel("1234.1234", "private-foobar", None) + .unwrap(); + assert_eq!( + auth["auth"], + "278d425bdf160c739803:58df8b0c36d6982b82c3ecf6b4662e34fe8c25bba48f5369f135bf843651c3a4" + ); + let data = r#"{"user_id":10,"user_info":{"name":"Mr. Channels"}}"#; + let auth = config() + .authorize_channel("1234.1234", "presence-foobar", Some(data)) + .unwrap(); + assert_eq!( + auth["auth"], + "278d425bdf160c739803:31935e7d86dba64c2a90aed31fdc61869f9b22ba9d8863bba239c03ca481bc80" + ); + assert_eq!(auth["channel_data"], data); + assert!(config() + .authorize_channel("nope", "private-x", None) + .is_err()); +} + +#[test] +fn user_signin() { + let out = config() + .authenticate_user("1234.1234", r#"{"id":"7"}"#) + .unwrap(); + let sig = hmac_sha256_hex(b"7ad3773142a6692b25b8", br#"1234.1234::user::{"id":"7"}"#); + assert_eq!(out["auth"], format!("278d425bdf160c739803:{sig}")); +} + +#[test] +fn webhooks() { + let body = br#"{"time_ms":1,"events":[{"name":"channel_occupied","channel":"orders"}]}"#; + let sig = hmac_sha256_hex(b"7ad3773142a6692b25b8", body); + let c = config(); + let hook = c + .verify_webhook(Some("278d425bdf160c739803"), Some(&sig), body) + .unwrap(); + assert_eq!(hook.events[0].channel.as_deref(), Some("orders")); + assert!(c.verify_webhook(Some("other"), Some(&sig), body).is_none()); + assert!(c + .verify_webhook(Some("278d425bdf160c739803"), Some("00"), body) + .is_none()); + assert!(c.verify_webhook(None, Some(&sig), body).is_none()); +} + +#[test] +fn signed_query_is_sorted_and_signed() { + let qs = signed_query( + "POST", + "/apps/3/events", + &[], + Some(br#"{"name":"foo","channels":["project-3"],"data":"{\"some\":\"data\"}"}"#), + "278d425bdf160c739803", + "7ad3773142a6692b25b8", + 1353088179, + ); + // The worked example in the Pusher HTTP API reference. + assert_eq!( + qs, + "auth_key=278d425bdf160c739803&auth_timestamp=1353088179&auth_version=1.0&body_md5=ec365a775a4cd0599faeb73354201b6f&auth_signature=da454824c97ba181a32ccc17a72625ba02771f50b50e1e7430e47a1f3f457e6c" + ); +} + +#[test] +fn live_chat() { + let h = hmac_sha256_hex(b"idsecret", b"42"); + assert_eq!(user_hash("idsecret", "42"), h); + let who = identity("idsecret", "42", Some("A \"B\" "), Some("")).unwrap(); + assert_eq!(who.email, None); + assert!(identity("", "42", None, None).is_none()); + let tag = script_tag(&ScriptOptions { + workspace: "ws_1", + identity: Some(&who), + hide_launcher: true, + nonce: Some("n1"), + ..Default::default() + }); + assert_eq!( + tag, + format!( + r#""# + ) + ); + assert_eq!(script_tag(&ScriptOptions::default()), ""); + let mut c = config(); + c.livechat_identity_secret = Some("idsecret".into()); + assert_eq!(c.livechat_identity("42", None, None).unwrap().hash, h); +} + +#[test] +fn approval_callbacks() { + let body = br#"{"id":"evt_1","type":"approval.decided","created_at":"2026-11-26T00:00:00Z","data":{"approval":{"approval_id":"apr_1","status":"approved"}}}"#; + let t = 1800000000i64; + let mut msg = format!("{t}.").into_bytes(); + msg.extend_from_slice(body); + let sig = hmac_sha256_hex(b"whsec", &msg); + let header = format!("t={t},v1={sig}"); + let e = approvals::verify_callback("whsec", &header, body, Some(t + 1)).unwrap(); + assert_eq!( + (e.kind.as_str(), e.data.approval.is_approved()), + ("approval.decided", true) + ); + assert!( + approvals::verify_callback("whsec", &format!("t={t},v1=00,v1={sig}"), body, Some(t)) + .is_some() + ); + assert!(approvals::verify_callback("other", &header, body, Some(t)).is_none()); + assert!(approvals::verify_callback("whsec", &header, b"{}", Some(t)).is_none()); + assert!(approvals::verify_callback("whsec", &header, body, Some(t + 301)).is_none()); + assert!(approvals::verify_callback("", &header, body, Some(t)).is_none()); +} diff --git a/tests/waiting_room.rs b/tests/waiting_room.rs new file mode 100644 index 0000000..fa01943 --- /dev/null +++ b/tests/waiting_room.rs @@ -0,0 +1,235 @@ +use hibira::signing::hmac_sha256_hex; +use hibira::waiting_room::{ + sign_user, verify, waiting_room_url, Decision, Guard, UrlOptions, VerifyOptions, +}; +use http::{HeaderMap, HeaderValue, Method, Uri}; + +// The shared test vector: signed by the Hibira server at 1800000000, ttl 30 minutes. +const SECRET: &str = "wr-secret-0123456789"; +const PASS: &str = "eyJ2IjoxLCJhcHAiOiJ3ci1hcHAiLCJyb29tIjoicHJlc2FsZSIsIm4iOjQyLCJ0aWQiOiJkNzlmZTc4OWEzOGI4NjMxYjUiLCJpYXQiOjE4MDAwMDAwMDAsImV4cCI6MTgwMDAwMTgwMH0.q7Uc_O6XKwNA_LVLQITlgv_YtDi9dIwiRzUUUSsGa08"; +const TICKET: &str = "eyJ2IjoxLCJhcHAiOiJ3ci1hcHAiLCJyb29tIjoicHJlc2FsZSIsIm4iOjQyLCJ0aWQiOiJkNzlmZTc4OWEzOGI4NjMxYjUiLCJpYXQiOjE4MDAwMDAwMDAsImV4cCI6MTgwMDA4NjQwMH0.l-KNMOVwV_xJJCQaQ-JXQKsrj-XlEdsTxG7X4Kp_2ck"; +const NOW: i64 = 1800000100; + +fn secrets() -> Vec { + vec![SECRET.to_string()] +} + +#[test] +fn verifies_the_shared_vector() { + let s = secrets(); + let p = verify( + PASS, + &VerifyOptions { + secrets: &s, + room: Some("presale"), + app_id: Some("wr-app"), + now: Some(NOW), + }, + ) + .expect("valid pass"); + assert_eq!( + ( + p.app_id.as_str(), + p.room.as_str(), + p.number, + p.ticket_id.as_str() + ), + ("wr-app", "presale", 42, "d79fe789a38b8631b5") + ); + assert_eq!( + (p.issued_at, p.expires_at, p.user_id), + (1800000000, 1800001800, None) + ); + let rotated = vec!["old".to_string(), SECRET.to_string()]; + assert!(verify( + PASS, + &VerifyOptions { + secrets: &rotated, + now: Some(NOW), + ..Default::default() + } + ) + .is_some()); +} + +#[test] +#[allow(clippy::type_complexity)] +fn rejects_bad_passes() { + let s = secrets(); + let wrong = vec!["wrong".to_string()]; + let o = |room: Option<&'static str>, app: Option<&'static str>, now: i64| (room, app, now); + let cases: Vec<(&str, &str, Vec, (Option<&str>, Option<&str>, i64))> = vec![ + ("wrong secret", PASS, wrong, o(None, None, NOW)), + ("other room", PASS, s.clone(), o(Some("other"), None, NOW)), + ("other app", PASS, s.clone(), o(None, Some("other"), NOW)), + ("expired", PASS, s.clone(), o(None, None, 1800001800)), + ("ticket", TICKET, s.clone(), o(None, None, NOW)), + ("empty", "", s.clone(), o(None, None, NOW)), + ("no secret", PASS, vec![], o(None, None, NOW)), + ("garbage", "a.b.c", s.clone(), o(None, None, NOW)), + ]; + let tampered = format!("{}AAA", &PASS[..PASS.len() - 3]); + let long = "a".repeat(1025); + for (name, pass, secrets, (room, app, now)) in + cases.iter().map(|c| (c.0, c.1, &c.2, c.3)).chain([ + ("tampered", tampered.as_str(), &s, (None, None, NOW)), + ("too long", long.as_str(), &s, (None, None, NOW)), + ]) + { + let got = verify( + pass, + &VerifyOptions { + secrets, + room, + app_id: app, + now: Some(now), + }, + ); + assert!(got.is_none(), "{name}: {got:?}"); + } +} + +#[test] +fn signs_user_tokens() { + let tok = sign_user(SECRET, "presale", "cust_42", 600, Some(1800000000)).unwrap(); + let want = format!( + "cust_42.1800000600.{}", + hmac_sha256_hex( + SECRET.as_bytes(), + b"hibira-waitroom-user.presale.cust_42.1800000600" + ) + ); + assert_eq!(tok, want); + assert!(sign_user(SECRET, "presale", "a.b", 0, None).is_err()); + assert!( + sign_user(SECRET, "presale", "u", 30 * 24 * 3600, Some(1800000000)) + .unwrap() + .starts_with("u.1800604800.") + ); +} + +#[test] +fn builds_the_waiting_page_url() { + let got = waiting_room_url(&UrlOptions { + app_key: "key", + room: "presale", + return_url: Some("https://shop.test/drop?a=1"), + lang: Some("ja"), + ..Default::default() + }); + assert_eq!(got, "https://ws.hibira.io/wait/key/presale?lang=ja&return=https%3A%2F%2Fshop.test%2Fdrop%3Fa%3D1"); +} + +fn guard() -> Guard { + let mut g = Guard::new("key", SECRET, "presale"); + g.now = Some(NOW); + g +} + +fn headers(pairs: &[(&'static str, &str)]) -> HeaderMap { + let mut h = HeaderMap::new(); + for (k, v) in pairs { + h.append(*k, HeaderValue::from_str(v).unwrap()); + } + h +} + +#[test] +fn guard_redirects_and_denies_without_a_pass() { + let g = guard(); + let d = g.decide( + &Method::GET, + &Uri::from_static("/drop"), + &headers(&[("host", "shop.test")]), + true, + ); + assert_eq!( + d, + Decision::Redirect { + location: "https://ws.hibira.io/wait/key/presale?return=https%3A%2F%2Fshop.test%2Fdrop" + .into(), + set_cookie: None, + pass: None + } + ); + assert_eq!( + g.decide( + &Method::POST, + &Uri::from_static("/drop"), + &headers(&[("host", "shop.test")]), + true + ), + Decision::Deny + ); +} + +#[test] +fn guard_stores_a_pass_from_the_queue() { + let g = guard(); + let uri: Uri = format!("/drop?item=7&hibira_pass={PASS}").parse().unwrap(); + match g.decide( + &Method::GET, + &uri, + &headers(&[("host", "example.com"), ("x-forwarded-proto", "https")]), + false, + ) { + Decision::Redirect { + location, + set_cookie, + pass, + } => { + assert_eq!(location, "https://example.com/drop?item=7"); + assert_eq!(set_cookie.unwrap(), format!("hibira_wr_presale={PASS}; Path=/; Max-Age=1700; HttpOnly; SameSite=Lax; Secure")); + assert_eq!(pass.unwrap().number, 42); + } + other => panic!("{other:?}"), + } + match g.decide( + &Method::GET, + &Uri::from_static("/drop?hibira_pass=forged"), + &headers(&[("host", "example.com")]), + false, + ) { + Decision::Redirect { + location, + set_cookie: None, + .. + } => assert!(location.starts_with("https://ws.hibira.io/wait/key/presale")), + other => panic!("{other:?}"), + } +} + +#[test] +fn guard_allows_a_cookie() { + let g = guard(); + let cookie = format!("a=b; hibira_wr_presale={PASS}"); + match g.decide( + &Method::POST, + &Uri::from_static("/drop"), + &headers(&[("host", "shop.test"), ("cookie", &cookie)]), + true, + ) { + Decision::Allow(p) => assert_eq!(p.ticket_id, "d79fe789a38b8631b5"), + other => panic!("{other:?}"), + } +} + +#[test] +fn guard_passes_a_signed_user() { + let mut g = guard(); + g.user = Some(std::sync::Arc::new(|_h: &HeaderMap| { + Some("cust_1.1800000600.ab".to_string()) + })); + match g.decide( + &Method::GET, + &Uri::from_static("/drop"), + &headers(&[("host", "shop.test")]), + true, + ) { + Decision::Redirect { location, .. } => assert!( + location.ends_with("&user=cust_1.1800000600.ab"), + "{location}" + ), + other => panic!("{other:?}"), + } +}