diff --git a/.gitignore b/.gitignore index cdf4408..b389e3f 100644 --- a/.gitignore +++ b/.gitignore @@ -11,6 +11,7 @@ bridgehook-extension-*.zip # Tauri apps/desktop/src-tauri/target/ +/target/ # Environment .env diff --git a/Cargo.lock b/Cargo.lock new file mode 100644 index 0000000..caa0453 --- /dev/null +++ b/Cargo.lock @@ -0,0 +1,1946 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 3 + +[[package]] +name = "android_system_properties" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae221649c9976a6f6c56ae1facf410f3ddb33cc661c4b7b61020a912d4237fbc" +dependencies = [ + "libc", +] + +[[package]] +name = "anstream" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "824a212faf96e9acacdbd09febd34438f8f711fb84e09a8916013cd7815ca28d" +dependencies = [ + "anstyle", + "anstyle-parse", + "anstyle-query", + "anstyle-wincon", + "colorchoice", + "is_terminal_polyfill", + "utf8parse", +] + +[[package]] +name = "anstyle" +version = "1.0.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000" + +[[package]] +name = "anstyle-parse" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52ce7f38b242319f7cabaa6813055467063ecdc9d355bbb4ce0c68908cd8130e" +dependencies = [ + "utf8parse", +] + +[[package]] +name = "anstyle-query" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "anstyle-wincon" +version = "3.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d" +dependencies = [ + "anstyle", + "once_cell_polyfill", + "windows-sys 0.61.2", +] + +[[package]] +name = "anyhow" +version = "1.0.104" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" + +[[package]] +name = "atomic-waker" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" + +[[package]] +name = "autocfg" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" + +[[package]] +name = "base16ct" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4c7f02d4ea65f2c1853089ffd8d2787bdbc63de2f0d29dedbcf8ccdfa0ccd4cf" + +[[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 = "base64ct" +version = "1.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06" + +[[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 = "bridgehook" +version = "0.1.0" +dependencies = [ + "anyhow", + "bridgehook-core", + "chrono", + "clap", + "serde", + "serde_json", + "tokio", +] + +[[package]] +name = "bridgehook-core" +version = "0.1.0" +dependencies = [ + "anyhow", + "dirs", + "futures-util", + "hex", + "p256", + "rand_core 0.6.4", + "reqwest", + "serde", + "serde_json", + "sha2", + "thiserror", + "tokio", + "url", +] + +[[package]] +name = "bumpalo" +version = "3.20.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649" + +[[package]] +name = "bytes" +version = "1.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" + +[[package]] +name = "cc" +version = "1.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6651c9ed80effdc7db0ff72512157f901af5e3549e341e24b1dd4887d836d838" +dependencies = [ + "find-msvc-tools", + "shlex", +] + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "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 0.10.1", +] + +[[package]] +name = "chrono" +version = "0.4.45" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1aa79e62e7697b8e29b513a68abacf485adcd1fe8284a4316c5ae868e6633327" +dependencies = [ + "iana-time-zone", + "num-traits", + "windows-link", +] + +[[package]] +name = "clap" +version = "4.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aa8876b300ab35ba921adea3dfd70157a46249b33f95c9084ae5709785478946" +dependencies = [ + "clap_builder", + "clap_derive", +] + +[[package]] +name = "clap_builder" +version = "4.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec0797fb7aeb1406c84efac526901f7ec3ead2124f946b494e72879d4b54704d" +dependencies = [ + "anstream", + "anstyle", + "clap_lex", + "strsim", +] + +[[package]] +name = "clap_derive" +version = "4.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9c751b79415d4e559e3d1fcf128e09e720eb673a06d26cf6f392d37d75b66e0" +dependencies = [ + "heck", + "proc-macro2", + "quote", + "syn 3.0.8", +] + +[[package]] +name = "clap_lex" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c133bc6a41be0d194c306b5506d15e6feeea7b1d6604bd3f8310dfb2ca96486" + +[[package]] +name = "colorchoice" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570" + +[[package]] +name = "const-oid" +version = "0.9.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2459377285ad874054d797f3ccebf984978aa39129f6eafde5cdc8315b612f8" + +[[package]] +name = "core-foundation-sys" +version = "0.8.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" + +[[package]] +name = "cpufeatures" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" +dependencies = [ + "libc", +] + +[[package]] +name = "cpufeatures" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566" +dependencies = [ + "libc", +] + +[[package]] +name = "crypto-bigint" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0dc92fb57ca44df6db8059111ab3af99a63d5d0f8375d9972e319a379c6bab76" +dependencies = [ + "generic-array", + "rand_core 0.6.4", + "subtle", + "zeroize", +] + +[[package]] +name = "crypto-common" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1bfb12502f3fc46cca1bb51ac28df9d618d813cdc3d2f25b9fe775a34af26bb3" +dependencies = [ + "generic-array", + "typenum", +] + +[[package]] +name = "der" +version = "0.7.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7c1832837b905bbfb5101e07cc24c8deddf52f93225eee6ead5f4d63d53ddcb" +dependencies = [ + "const-oid", + "pem-rfc7468", + "zeroize", +] + +[[package]] +name = "digest" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" +dependencies = [ + "block-buffer", + "const-oid", + "crypto-common", + "subtle", +] + +[[package]] +name = "dirs" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3e8aa94d75141228480295a7d0e7feb620b1a5ad9f12bc40be62411e38cce4e" +dependencies = [ + "dirs-sys", +] + +[[package]] +name = "dirs-sys" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e01a3366d27ee9890022452ee61b2b63a67e6f13f58900b651ff5665f0bb1fab" +dependencies = [ + "libc", + "option-ext", + "redox_users", + "windows-sys 0.61.2", +] + +[[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.8", +] + +[[package]] +name = "ecdsa" +version = "0.16.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee27f32b5c5292967d2d4a9d7f1e0b0aed2c15daded5a60300e4abb9d8020bca" +dependencies = [ + "der", + "digest", + "elliptic-curve", + "rfc6979", + "signature", + "spki", +] + +[[package]] +name = "elliptic-curve" +version = "0.13.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b5e6043086bf7973472e0c7dff2142ea0b680d30e18d9cc40f267efbf222bd47" +dependencies = [ + "base16ct", + "crypto-bigint", + "digest", + "ff", + "generic-array", + "group", + "pem-rfc7468", + "pkcs8", + "rand_core 0.6.4", + "sec1", + "subtle", + "zeroize", +] + +[[package]] +name = "errno" +version = "0.3.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "ff" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c0b50bfb653653f9ca9095b427bed08ab8d75a137839d9ad64eb11810d5b6393" +dependencies = [ + "rand_core 0.6.4", + "subtle", +] + +[[package]] +name = "find-msvc-tools" +version = "0.1.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aedcfb3409746eddb02b9e19ebda1c3394f759a152e48ee875a0844d1b955484" + +[[package]] +name = "form_urlencoded" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf" +dependencies = [ + "percent-encoding", +] + +[[package]] +name = "futures-channel" +version = "0.3.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-io" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53c0fa8157de1303bfffdaa1cc2a673bfffb60102f76b0ef4441659124373fed" + +[[package]] +name = "futures-macro" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9fb9654ba8355388abeb8dcb4fc62f511300867002afc858860463bdd9fe0c44" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.8", +] + +[[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-io", + "futures-macro", + "futures-sink", + "futures-task", + "memchr", + "pin-project-lite", + "slab", +] + +[[package]] +name = "generic-array" +version = "0.14.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4bb6743198531e02858aeaea5398fcc883e71851fcbcb5a2f773e2fb6cb1edf2" +dependencies = [ + "typenum", + "version_check", + "zeroize", +] + +[[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 0.10.1", + "wasm-bindgen", +] + +[[package]] +name = "group" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0f9ef7462f7c099f518d754361858f86d8a07af53ba9af0fe635bbccb151a63" +dependencies = [ + "ff", + "rand_core 0.6.4", + "subtle", +] + +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + +[[package]] +name = "hex" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" + +[[package]] +name = "hmac" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e" +dependencies = [ + "digest", +] + +[[package]] +name = "http" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0" +dependencies = [ + "bytes", + "itoa", +] + +[[package]] +name = "http-body" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca2a8f2913ee65f60facd6a5905613afaa448497a0230cc41ce022d93290bc2c" +dependencies = [ + "bytes", + "http", +] + +[[package]] +name = "http-body-util" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23169fe34a5fbcdd3f3862e78fb9b6fccd5f02a6dc6f732547005d45631ce71c" +dependencies = [ + "bytes", + "futures-core", + "http", + "http-body", + "pin-project-lite", +] + +[[package]] +name = "httparse" +version = "1.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" + +[[package]] +name = "hyper" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2c3e324da4c95177d6291d4c8730197c0d1822f8a9766814a4a44fa5ab797c9c" +dependencies = [ + "atomic-waker", + "bytes", + "futures-core", + "http", + "http-body", + "httparse", + "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", + "hyper", + "hyper-util", + "rustls", + "tokio", + "tokio-rustls", + "tower-service", + "webpki-roots", +] + +[[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", + "http-body", + "httparse", + "hyper", + "ipnet", + "libc", + "percent-encoding", + "pin-project-lite", + "socket2", + "tokio", + "tower-service", + "tracing", +] + +[[package]] +name = "iana-time-zone" +version = "0.1.65" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e31bc9ad994ba00e440a8aa5c9ef0ec67d5cb5e5cb0cc7f8b744a35b389cc470" +dependencies = [ + "android_system_properties", + "core-foundation-sys", + "iana-time-zone-haiku", + "js-sys", + "log", + "wasm-bindgen", + "windows-core", +] + +[[package]] +name = "iana-time-zone-haiku" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f" +dependencies = [ + "cc", +] + +[[package]] +name = "icu_collections" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fa68d21081c4a05d5a901a1c62add574c77048b6a1c67be3b50ce0b60d4ca513" +dependencies = [ + "displaydoc", + "potential_utf", + "utf8_iter", + "yoke", + "zerofrom", + "zerovec", +] + +[[package]] +name = "icu_locale_core" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d56e28588da92eee5c3201a6eff33fabdd49b62269c8938d4ff050ce4d900deb" +dependencies = [ + "displaydoc", + "litemap", + "tinystr", + "writeable", + "zerovec", +] + +[[package]] +name = "icu_normalizer" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "12f9cf5f235641ed274641dd81c3f28d870e276763d0797aeeab72317b1c646f" +dependencies = [ + "icu_collections", + "icu_normalizer_data", + "icu_properties", + "icu_provider", + "smallvec", + "zerovec", +] + +[[package]] +name = "icu_normalizer_data" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1563da1ed3e0b3bf3d74c9b85917ac9c56464d2f57242270c09c9e752f8021a0" + +[[package]] +name = "icu_properties" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e7ca276ad3145661a65914e6daf131ca5120cd3dcee8f8f3214b8875184a148" +dependencies = [ + "displaydoc", + "icu_collections", + "icu_locale_core", + "icu_properties_data", + "icu_provider", + "zerotrie", + "zerovec", +] + +[[package]] +name = "icu_properties_data" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e590f038c1464a96894fd6d10127e90a8be4509f56ff7ecef851b15cee0b7caa" + +[[package]] +name = "icu_provider" +version = "2.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d27bbb9d3abbefac45d55f647c9de1d44aafcd1186eb91879afef17c396c3e73" +dependencies = [ + "displaydoc", + "icu_locale_core", + "writeable", + "yoke", + "zerofrom", + "zerotrie", + "zerovec", +] + +[[package]] +name = "idna" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de" +dependencies = [ + "idna_adapter", + "smallvec", + "utf8_iter", +] + +[[package]] +name = "idna_adapter" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714" +dependencies = [ + "icu_normalizer", + "icu_properties", +] + +[[package]] +name = "ipnet" +version = "2.12.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "791930b43c0d5973160d90a8f3894509f2b273430f5c5c73b668636d0287c5c0" + +[[package]] +name = "is_terminal_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695" + +[[package]] +name = "itoa" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" + +[[package]] +name = "js-sys" +version = "0.3.106" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7883d941dae510fb2d978fc3fe018c71c9e2892fd38854de3e8b92c2e5ad9cc5" +dependencies = [ + "cfg-if", + "futures-util", + "wasm-bindgen", +] + +[[package]] +name = "libc" +version = "0.2.190" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce5d3ddc6d3fa000eb1536d85e147bfe31aacaba692ed6a876f95cb7c855be78" + +[[package]] +name = "libredox" +version = "0.1.25" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "61ff90caf6077a803a240f62fdbe88645a890bbca49ef8174c3cb0404362171d" +dependencies = [ + "libc", +] + +[[package]] +name = "litemap" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae" + +[[package]] +name = "log" +version = "0.4.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6" + +[[package]] +name = "lru-slab" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4050469837a6ff301cd14c1f8f24f88549e6d548f24f64e2148eb0f72cebc51f" + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "mio" +version = "1.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1788edb87fdc09c7e26304471e2f5be8cdefb1b6930d6e3985fc02ff53bf86ee" +dependencies = [ + "libc", + "wasi", + "windows-sys 0.61.2", +] + +[[package]] +name = "num-traits" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" +dependencies = [ + "autocfg", +] + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "once_cell_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" + +[[package]] +name = "option-ext" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "04744f49eae99ab78e0d5c0b603ab218f515ea8cfe5a456d7629ad883a3b6e7d" + +[[package]] +name = "p256" +version = "0.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c9863ad85fa8f4460f9c48cb909d38a0d689dba1f6f6988a5e3e0d31071bcd4b" +dependencies = [ + "ecdsa", + "elliptic-curve", + "primeorder", + "sha2", +] + +[[package]] +name = "pem-rfc7468" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "88b39c9bfcfc231068454382784bb460aae594343fb030d46e9f50a645418412" +dependencies = [ + "base64ct", +] + +[[package]] +name = "percent-encoding" +version = "2.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" + +[[package]] +name = "pin-project-lite" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" + +[[package]] +name = "pkcs8" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f950b2377845cebe5cf8b5165cb3cc1a5e0fa5cfa3e1f7f55707d8fd82e0a7b7" +dependencies = [ + "der", + "spki", +] + +[[package]] +name = "potential_utf" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d83eb9bc6d8e5cf568e7a1101d60ee05e81ed50ea106026f3d18deeb046d7661" +dependencies = [ + "zerovec", +] + +[[package]] +name = "primeorder" +version = "0.13.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "353e1ca18966c16d9deb1c69278edbc5f194139612772bd9537af60ac231e1e6" +dependencies = [ + "elliptic-curve", +] + +[[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 = [ + "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.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65c9fb96cbc91e3478eaae79a69fcd3f1ae4ad052e471fe6732fff548984b4af" +dependencies = [ + "chacha20", + "getrandom 0.4.3", + "rand_core 0.10.1", +] + +[[package]] +name = "rand_core" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" +dependencies = [ + "getrandom 0.2.17", +] + +[[package]] +name = "rand_core" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69" + +[[package]] +name = "rand_pcg" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "caa0f4137e1c0a72f4c651489402276c8e8e1cf081f3b0ba156d2cbeef09e86a" +dependencies = [ + "rand_core 0.10.1", +] + +[[package]] +name = "redox_users" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "60dc65c0ff1a7ae1294b0c67b9f14baf70b644404010370171787bfac1038fc0" +dependencies = [ + "libredox", + "thiserror", +] + +[[package]] +name = "reqwest" +version = "0.12.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eddd3ca559203180a307f12d114c268abf583f59b03cb906fd0b3ff8646c1147" +dependencies = [ + "base64 0.22.1", + "bytes", + "futures-core", + "futures-util", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-rustls", + "hyper-util", + "js-sys", + "log", + "percent-encoding", + "pin-project-lite", + "quinn", + "rustls", + "rustls-pki-types", + "serde", + "serde_json", + "serde_urlencoded", + "sync_wrapper", + "tokio", + "tokio-rustls", + "tokio-util", + "tower", + "tower-http", + "tower-service", + "url", + "wasm-bindgen", + "wasm-bindgen-futures", + "wasm-streams", + "web-sys", + "webpki-roots", +] + +[[package]] +name = "rfc6979" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dd2a808d456c4a54e300a23e9f5a67e122c3024119acbfd73e3bf664491cb2" +dependencies = [ + "hmac", + "subtle", +] + +[[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 = "rustls" +version = "0.23.45" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d41d731c7d2f962d1ccc364cec258de3c0e93b38c2fb3ba97ac74513048d634" +dependencies = [ + "once_cell", + "ring", + "rustls-pki-types", + "rustls-webpki", + "subtle", + "zeroize", +] + +[[package]] +name = "rustls-pki-types" +version = "1.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f4925028c7eb5d1fcdaf196971378ed9d2c1c4efc7dc5d011256f76c99c0a96" +dependencies = [ + "web-time", + "zeroize", +] + +[[package]] +name = "rustls-webpki" +version = "0.103.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f3c3cf1d8b1e7d4927e2d154c3fcb02979afb9939629c62cd9048d4f07b60ac2" +dependencies = [ + "ring", + "rustls-pki-types", + "untrusted", +] + +[[package]] +name = "rustversion" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" + +[[package]] +name = "ryu" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" + +[[package]] +name = "sec1" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3e97a565f76233a6003f9f5c54be1d9c5bdfa3eccfb189469f11ec4901c47dc" +dependencies = [ + "base16ct", + "der", + "generic-array", + "pkcs8", + "subtle", + "zeroize", +] + +[[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.8", +] + +[[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 = "signature" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77549399552de45a898a580c1b41d445bf730df867cc44e6c0233bbc4b8329de" +dependencies = [ + "digest", + "rand_core 0.6.4", +] + +[[package]] +name = "slab" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" + +[[package]] +name = "smallvec" +version = "1.16.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5b3dc8af474f516a851ff4bd12db780f948b9250ad37211e4eec0bccea54e01b" + +[[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 = "spki" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d91ed6c858b01f942cd56b37a94b3e0a1798290327d1236e4d9cf4eaca44d29d" +dependencies = [ + "base64ct", + "der", +] + +[[package]] +name = "stable_deref_trait" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" + +[[package]] +name = "strsim" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" + +[[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.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "01016da373cd8f7ef12624f796309f5c31ba8d646dd08856c02cd741d823c622" +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.8", +] + +[[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.8", +] + +[[package]] +name = "tinystr" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1e27c91459209c2986af3dcf603a5a74a4368754ce37414f59acc971167f643" +dependencies = [ + "displaydoc", + "zerovec", +] + +[[package]] +name = "tinyvec" +version = "1.13.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee" + +[[package]] +name = "tokio" +version = "1.53.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e95f91fcc7a621e8b030f6aa23c71fe9838ae2fb4d8118b75602a328f5144044" +dependencies = [ + "bytes", + "libc", + "mio", + "pin-project-lite", + "signal-hook-registry", + "socket2", + "tokio-macros", + "windows-sys 0.61.2", +] + +[[package]] +name = "tokio-macros" +version = "2.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78773a2a397f451582ce068015985c33193cf6dea8b74d2a639fe457b2f07b0e" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.8", +] + +[[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", + "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", + "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 = [ + "pin-project-lite", + "tracing-core", +] + +[[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.26" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d245f478577f809a851594d02313b640fb437e0bb33866753cff937863096954" + +[[package]] +name = "untrusted" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" + +[[package]] +name = "url" +version = "2.5.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed" +dependencies = [ + "form_urlencoded", + "idna", + "percent-encoding", + "serde", +] + +[[package]] +name = "utf8_iter" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be" + +[[package]] +name = "utf8parse" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" + +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + +[[package]] +name = "want" +version = "0.3.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.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9bb54f33acc68fd454578d9820b0bde1a1a3d17aa17bb7b6595806d02886d409" +dependencies = [ + "cfg-if", + "once_cell", + "rustversion", + "wasm-bindgen-macro", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-futures" +version = "0.4.79" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3cbab34de2d982e9b48e18d216d04c4a6f641066ff19ffb699980f591ee3610e" +dependencies = [ + "js-sys", + "tokio", + "wasm-bindgen", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2e29d0c35b16e224a7eeb5cd2d25e3e1968fbd65604117b44d3b789d00ee8535" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6f501a8bc3719dba86ef8ae4728879c08001bea749eb1333ac5b91e040e2a6b7" +dependencies = [ + "bumpalo", + "proc-macro2", + "quote", + "syn 3.0.8", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23f0c9c52aa7cd7d77769a4cfe2a9adb1b331f489a41d912ce14513d5ab995c6" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "wasm-streams" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "15053d8d85c7eccdbefef60f06769760a563c7f0a9d6902a13d35c7800b0ad65" +dependencies = [ + "futures-util", + "js-sys", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", +] + +[[package]] +name = "web-sys" +version = "0.3.106" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "88261b9deccee56594c11a3460c462c41f58d148598fe70ad77070126a68aba4" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "web-time" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a6580f308b1fad9207618087a65c04e7a10bc77e02c8e84e9b00dd4b12fa0bb" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "webpki-roots" +version = "1.0.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7dcd9d09a39985f5344844e66b0c530a33843579125f23e21e9f0f220850f22a" +dependencies = [ + "rustls-pki-types", +] + +[[package]] +name = "windows-core" +version = "0.62.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb" +dependencies = [ + "windows-implement", + "windows-interface", + "windows-link", + "windows-result", + "windows-strings", +] + +[[package]] +name = "windows-implement" +version = "0.60.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "windows-interface" +version = "0.59.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-result" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-strings" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-sys" +version = "0.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.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "709fe23a0424b6a435d82152b1bd3fdfb0833487d5fa90d05d42762a9891fef5" +dependencies = [ + "stable_deref_trait", + "yoke-derive", + "zerofrom", +] + +[[package]] +name = "yoke-derive" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec8ebde2db3681e8c9980cc27822030e68752690ddfa9473e739aeb4dbde6d71" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.8", + "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.8", + "synstructure", +] + +[[package]] +name = "zeroize" +version = "1.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e13084392c5e4bc371903e2935a5eaeed24905a7511356b883835e18a78f6879" + +[[package]] +name = "zerotrie" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ea269c3bd32f0a32c321907a2ae912ba6f4649bb0fc764a15627e99a7095a3f" +dependencies = [ + "displaydoc", + "yoke", + "zerofrom", +] + +[[package]] +name = "zerovec" +version = "0.11.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb0464e17806c1d976d5cba29399c7f08e516e279e2ba493f63123b5fca67dd8" +dependencies = [ + "yoke", + "zerofrom", + "zerovec-derive", +] + +[[package]] +name = "zerovec-derive" +version = "0.11.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "34df6fc39dbd26ddc9c10e6a2984476e13acce22e64e4487636ef494369225da" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.8", +] + +[[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..2c4f57b --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,36 @@ +# Rust workspace: the BridgeHook CLI and its protocol core (HAL-2386). +# The desktop app (apps/desktop/src-tauri) keeps its own lockfile for now and +# moves onto bridgehook-core in a later milestone. +[workspace] +resolver = "2" +members = ["crates/bridgehook-core", "cli"] +exclude = ["apps/desktop/src-tauri"] + +[workspace.package] +version = "0.1.0" +edition = "2021" +license = "MIT" +repository = "https://github.com/hallelx2/bridgehook" +rust-version = "1.82" + +[workspace.dependencies] +bridgehook-core = { path = "crates/bridgehook-core" } +anyhow = "1" +thiserror = "2" +clap = { version = "4", features = ["derive", "env"] } +dirs = "6" +futures-util = "0.3" +hex = "0.4" +p256 = { version = "0.13", features = ["ecdsa", "pkcs8"] } +rand_core = { version = "0.6", features = ["getrandom"] } +reqwest = { version = "0.12", default-features = false, features = ["json", "rustls-tls", "stream"] } +serde = { version = "1", features = ["derive"] } +serde_json = "1" +sha2 = "0.10" +tokio = { version = "1", features = ["macros", "rt-multi-thread", "time", "signal", "sync"] } +url = "2" + +[profile.release] +lto = true +codegen-units = 1 +strip = true diff --git a/cli/Cargo.toml b/cli/Cargo.toml new file mode 100644 index 0000000..5791034 --- /dev/null +++ b/cli/Cargo.toml @@ -0,0 +1,21 @@ +[package] +name = "bridgehook" +description = "Forward webhooks from a stable public URL to localhost, in order, even while you are offline" +version.workspace = true +edition.workspace = true +license.workspace = true +repository.workspace = true +rust-version.workspace = true + +[[bin]] +name = "bridgehook" +path = "src/main.rs" + +[dependencies] +bridgehook-core.workspace = true +anyhow.workspace = true +chrono = { version = "0.4", default-features = false, features = ["clock"] } +clap.workspace = true +serde.workspace = true +serde_json.workspace = true +tokio.workspace = true diff --git a/cli/README.md b/cli/README.md new file mode 100644 index 0000000..dcab0a3 --- /dev/null +++ b/cli/README.md @@ -0,0 +1,38 @@ +# bridgehook CLI + +A stable public webhook URL that forwards to a local port. Webhooks sent while nothing is forwarding wait on the relay, and the next `bridgehook forward` delivers them in order. + +```sh +bridgehook login # pair this machine (approve the code in the browser) +bridgehook forward 3000 # prints https://.bridgehook.dev, forwards to localhost:3000 +bridgehook forward http://api:8080 --path /stripe # any URL; accept only /stripe/* +bridgehook whoami +bridgehook logout # revokes this machine's token on the relay +``` + +Running `forward` again for the same target reuses its channel, so the URL you registered with Stripe or GitHub stays the same. `--path` (repeatable) limits which paths the URL accepts and is applied to a reused channel too; `--any-path` lifts the limit; with neither, the channel keeps what it had. + +If your account already has a channel on that port made by another client (the extension, another machine), taking it over keeps its URL but moves its key here, so that client stops forwarding it. On a terminal the CLI asks first; in a script it refuses unless you pass `--adopt`. `--new` makes a separate URL instead. + +Logging in again (or with `--force`) revokes the token it replaces, so re-pairing never leaves an orphan device using up a slot. + +| Flag / variable | | +|---|---| +| `--json` | one JSON object per line (`ready`, `delivered`, `skipped`, `target_down`, `target_up`, …) for scripts and agents | +| `--relay`, `BRIDGEHOOK_RELAY` | another relay (self-hosted); defaults to the one you signed in to | +| `BRIDGEHOOK_TOKEN` | a device token, instead of the saved one (CI, containers) | +| `--config-dir`, `BRIDGEHOOK_CONFIG_DIR` | where the token, channel keys and channel list live (default `~/.config/bridgehook`, `%APPDATA%\bridgehook`) | + +Ctrl-C finishes the webhook in hand and stops; a second Ctrl-C quits at once. + +## How delivery works + +The protocol lives in `crates/bridgehook-core`, a port of the extension's `QueueDrainer`: the queue is read oldest first, each webhook is claimed before it is forwarded (so the extension and the CLI never both deliver it), a server that is down holds the queue without using up retries, and a webhook that fails three times while the server is up is recorded and skipped. The live stream (`/api/me/stream`) only wakes the drain, so a live webhook never overtakes a queued one. Requests are signed with the channel's P-256 key. + +## Checks + +```sh +pnpm test:cli # unit tests + clippy +pnpm e2e:cli:local # the binary against a throwaway local relay (wrangler dev) +pnpm e2e:cli # the binary against production, with the QA account from .env +``` diff --git a/cli/e2e/cli.e2e.mjs b/cli/e2e/cli.e2e.mjs new file mode 100644 index 0000000..687fa39 --- /dev/null +++ b/cli/e2e/cli.e2e.mjs @@ -0,0 +1,556 @@ +/** + * The CLI end to end, driving the real binary against a real relay. + * + * node cli/e2e/cli.e2e.mjs # production, with the QA account + * node cli/e2e/cli.e2e.mjs --local # a throwaway local relay (wrangler dev) + * + * Checks, in order: + * 1. `bridgehook login` pairs: the script approves the printed code with an + * account session, as a person would in the dashboard; + * 2. `whoami` reports that account; + * 3. `forward` prints a webhook URL; with nothing forwarding, 20 webhooks + * sent to it wait on the relay and all arrive at localhost, in order, + * once `forward` runs again; + * 4. once the stream reports connected, live webhooks arrive within 2 s + * (the stream wakes the drain); + * 5. with the local server down, webhooks wait and then arrive in order + * when it is back; + * 6. a channel another client made on a port: refused to a script without + * `--adopt`; `--adopt --path` keeps its URL and applies the paths; + * 7. Ctrl-C stops within 3 s; `login --force` revokes the token it + * replaces; `logout` revokes the token on the relay. + * + * Production needs the QA account in the repo's gitignored .env + * (BRIDGEHOOK_TEST_EMAIL, BRIDGEHOOK_TEST_PASSWORD) or the environment. Setup + * and teardown revoke the account's devices and delete its channels. Builds + * the binary with cargo unless BRIDGEHOOK_BIN is set. Never prints a token + * or a password. + */ +import { execFileSync, spawn } from "node:child_process"; +import { createECDH } from "node:crypto"; +import { existsSync, mkdtempSync, readFileSync, rmSync } from "node:fs"; +import http from "node:http"; +import { tmpdir } from "node:os"; +import { dirname, join } from "node:path"; +import { createInterface } from "node:readline"; +import { fileURLToPath } from "node:url"; + +const HERE = dirname(fileURLToPath(import.meta.url)); +const ROOT = join(HERE, "..", ".."); +const LOCAL = process.argv.includes("--local"); +const PORT = 3457; +const OFFLINE_COUNT = 20; +const LIVE_LIMIT_MS = 2000; + +const cleanup = []; +let failed = false; +const step = (s) => console.log(`• ${s}`); +function check(cond, message) { + if (!cond) throw new Error(`check failed: ${message}`); +} + +// ── the binary ─────────────────────────────────────────────────────────── +let BIN = process.env.BRIDGEHOOK_BIN; +if (!BIN) { + execFileSync("cargo", ["build", "-p", "bridgehook"], { cwd: ROOT, stdio: "inherit" }); + BIN = join( + ROOT, + "target", + "debug", + process.platform === "win32" ? "bridgehook.exe" : "bridgehook", + ); +} + +// ── the relay and an account session ───────────────────────────────────── +let RELAY = "https://relay.bridgehook.dev"; +let email; +let password; + +function freePort() { + return new Promise((resolve) => { + const s = http.createServer().listen(0, "127.0.0.1", () => { + const { port } = s.address(); + s.close(() => resolve(port)); + }); + }); +} + +let localPersist; +async function startLocalRelay() { + const port = await freePort(); + const persist = mkdtempSync(join(tmpdir(), "bh-cli-e2e-d1-")); + localPersist = persist; + cleanup.push(() => rmSync(persist, { recursive: true, force: true })); + const relayDir = join(ROOT, "relay"); + execFileSync( + "npx", + ["wrangler", "d1", "migrations", "apply", "bridgehook", "--local", "--persist-to", persist], + { + cwd: relayDir, + stdio: "ignore", + env: { ...process.env, CI: "1" }, + }, + ); + const secret = [...crypto.getRandomValues(new Uint8Array(32))] + .map((b) => b.toString(16).padStart(2, "0")) + .join(""); + const base = `http://localhost:${port}`; + const wrangler = spawn( + "npx", + [ + "wrangler", + "dev", + "--port", + String(port), + "--persist-to", + persist, + // wrangler dev rewrites the request host and Origin to the route's + // host; pin them to localhost (it drops the port from Origin). + "--local-upstream", + `localhost:${port}`, + "--var", + `BETTER_AUTH_SECRET:${secret}`, + "--var", + `BETTER_AUTH_URL:${base}`, + "--var", + `WEB_URL:${base}`, + "--var", + "AUTH_TRUSTED_ORIGINS:http://localhost", + ], + { cwd: relayDir, stdio: "ignore", detached: true, env: { ...process.env, CI: "1" } }, + ); + cleanup.push(() => { + try { + process.kill(-wrangler.pid, "SIGTERM"); + } catch {} + }); + for (let i = 0; i < 120; i++) { + try { + if ((await fetch(`${base}/health`)).status < 500) return base; + } catch {} + await sleep(500); + } + throw new Error("local relay did not start"); +} + +/** Fetch with the account's session cookie. */ +let cookie = ""; +async function api(path, init = {}) { + const res = await fetch(`${RELAY}${path}`, { + ...init, + headers: { + "content-type": "application/json", + // A browser on the dashboard sends its origin; locally the + // dashboard origin (WEB_URL) is the relay itself. + ...(LOCAL ? { origin: RELAY } : {}), + ...(cookie ? { cookie } : {}), + ...(init.headers ?? {}), + }, + }); + const set = res.headers.getSetCookie?.() ?? []; + if (set.length) cookie = set.map((c) => c.split(";")[0]).join("; "); + return res; +} + +async function signIn() { + if (LOCAL) { + email = `cli-e2e-${Date.now()}@example.com`; + password = `pw-${crypto.randomUUID()}`; + const up = await api("/auth/sign-up/email", { + method: "POST", + body: JSON.stringify({ email, password, name: "CLI e2e" }), + }); + check(up.ok, `local sign-up answered ${up.status}: ${(await up.text()).slice(0, 200)}`); + // The free plan caps a day at 10 webhooks; the production QA account + // is on Pro, so match it. + execFileSync( + "npx", + [ + "wrangler", + "d1", + "execute", + "bridgehook", + "--local", + "--persist-to", + localPersist, + "--command", + `UPDATE user SET plan = 'pro' WHERE email = '${email}'`, + ], + { cwd: join(ROOT, "relay"), stdio: "ignore", env: { ...process.env, CI: "1" } }, + ); + return; + } + const env = { ...process.env }; + const envFile = join(ROOT, ".env"); + if (existsSync(envFile)) { + for (const line of readFileSync(envFile, "utf8").split("\n")) { + const m = line.match(/^(BRIDGEHOOK_TEST_(?:EMAIL|PASSWORD))=(.*)$/); + if (m && !env[m[1]]) env[m[1]] = m[2].trim().replace(/^(["'])(.*)\1$/, "$2"); + } + } + email = env.BRIDGEHOOK_TEST_EMAIL; + password = env.BRIDGEHOOK_TEST_PASSWORD; + check( + email && password, + "QA credentials missing: set BRIDGEHOOK_TEST_EMAIL and BRIDGEHOOK_TEST_PASSWORD", + ); + const res = await api("/auth/sign-in/email", { + method: "POST", + body: JSON.stringify({ email, password }), + }); + check(res.ok, `QA sign-in answered ${res.status}`); +} + +async function resetAccount(label) { + const { devices = [] } = await (await api("/api/me/devices")).json(); + const active = devices.filter((d) => !d.revokedAt); + for (const d of active) await api(`/api/me/devices/${d.id}`, { method: "DELETE" }); + const { channels = [] } = await (await api("/api/me/channels")).json(); + for (const ch of channels) await api(`/api/me/channels/${ch.id}`, { method: "DELETE" }); + step(`${label}: revoked ${active.length} device(s), deleted ${channels.length} channel(s)`); +} + +// ── the CLI as a child process, its --json lines as events ──────────────── +const CONFIG = mkdtempSync(join(tmpdir(), "bh-cli-e2e-config-")); +cleanup.push(() => rmSync(CONFIG, { recursive: true, force: true })); + +function cli(args) { + const env = { + ...process.env, + BRIDGEHOOK_CONFIG_DIR: CONFIG, + BRIDGEHOOK_RELAY: RELAY, + NO_COLOR: "1", + }; + env.BRIDGEHOOK_TOKEN = ""; + const child = spawn(BIN, ["--json", ...args], { env, stdio: ["ignore", "pipe", "pipe"] }); + const events = []; + const waiters = []; + let stderr = ""; + child.stderr.on("data", (d) => { + stderr += d; + }); + createInterface({ input: child.stdout }).on("line", (line) => { + let e; + try { + e = JSON.parse(line); + } catch { + return; + } + e.at = Date.now(); + events.push(e); + for (const w of [...waiters]) if (w.match(e)) w.resolve(e); + }); + const exited = new Promise((resolve) => child.on("exit", (code) => resolve(code))); + return { + child, + events, + exited, + stderr: () => stderr, + waitFor(match, ms = 30_000, what = "event") { + const seen = events.find(match); + if (seen) return Promise.resolve(seen); + return new Promise((resolve, reject) => { + const w = { + match, + resolve: (e) => { + clearTimeout(t); + resolve(e); + }, + }; + const t = setTimeout(() => { + waiters.splice(waiters.indexOf(w), 1); + reject( + new Error( + `timed out waiting for ${what}; events: ${JSON.stringify(events.map((e) => e.event))}; stderr: ${stderr.slice(-500)}`, + ), + ); + }, ms); + waiters.push(w); + }); + }, + }; +} + +async function run(args) { + const p = cli(args); + const code = await p.exited; + return { code, events: p.events, stderr: p.stderr() }; +} + +// ── a local server that records what reaches it ────────────────────────── +const received = []; +let server = null; +function startServer() { + return new Promise((resolve) => { + server = http.createServer((req, res) => { + let body = ""; + req.on("data", (d) => { + body += d; + }); + req.on("end", () => { + if (req.method !== "HEAD") { + received.push({ + at: Date.now(), + method: req.method, + url: req.url, + body, + header: req.headers["x-e2e"], + }); + } + res.writeHead(200, { "content-type": "application/json" }); + res.end(JSON.stringify({ ok: true })); + }); + }); + server.listen(PORT, "127.0.0.1", resolve); + }); +} +function stopServer() { + return new Promise((resolve) => { + if (!server) return resolve(); + server.closeAllConnections?.(); + server.close(() => resolve()); + server = null; + }); +} +cleanup.push(stopServer); + +async function waitReceived(n, ms) { + const until = Date.now() + ms; + while (received.length < n && Date.now() < until) await sleep(100); + check(received.length >= n, `expected ${n} webhooks at localhost, got ${received.length}`); +} + +function sleep(ms) { + return new Promise((r) => setTimeout(r, ms)); +} + +/** The webhook URL the CLI printed. */ +let sendBase; +async function sendWebhook(tag) { + const res = await fetch(`${sendBase}/e2e?tag=${tag}`, { + method: "POST", + headers: { "content-type": "application/json", "x-e2e": tag }, + body: JSON.stringify({ tag }), + }); + check(res.status < 300, `webhook ${tag} answered ${res.status}`); +} + +// ── the run ────────────────────────────────────────────────────────────── +try { + if (LOCAL) { + RELAY = await startLocalRelay(); + step(`local relay up at ${RELAY}`); + } + await signIn(); + step(`signed in to ${RELAY} (${LOCAL ? "throwaway account" : "QA account"})`); + await resetAccount("setup"); + + // 1. login: approve the code the CLI prints. + const login = cli(["login", "--no-browser"]); + const pairing = await login.waitFor((e) => e.event === "pairing", 30_000, "a pairing code"); + check(/^DV-[A-Z0-9]{4}-[A-Z0-9]{4}$/.test(pairing.code), "pairing code format"); + const approve = await api("/auth/device/approve", { + method: "POST", + body: JSON.stringify({ code: pairing.code }), + }); + check(approve.ok, `approve answered ${approve.status}`); + const signedIn = await login.waitFor((e) => e.event === "signed_in", 60_000, "signed_in"); + check((await login.exited) === 0, "login exits 0"); + check(signedIn.email === email, "login reports the approving account"); + step(`login: paired as device ${signedIn.deviceId}`); + + // 2. whoami + const who = await run(["whoami"]); + check(who.code === 0 && who.events[0]?.email === email, `whoami: ${who.stderr}`); + step(`whoami: ${who.events[0].plan} plan`); + + // 3. offline queue: get the URL with nothing listening, stop, send 20. + const first = cli(["forward", String(PORT)]); + const ready = await first.waitFor((e) => e.event === "ready", 30_000, "ready"); + check(ready.channel === "created", `first forward creates a channel (got ${ready.channel})`); + sendBase = ready.webhookUrl; + first.child.kill("SIGINT"); + check((await first.exited) === 0, "forward stops cleanly on Ctrl-C"); + step(`forward: ${ready.webhookUrl}`); + + for (let i = 0; i < OFFLINE_COUNT; i++) + await sendWebhook(`offline-${String(i).padStart(2, "0")}`); + step(`sent ${OFFLINE_COUNT} webhooks while nothing was forwarding`); + + await startServer(); + const fwd = cli(["forward", String(PORT)]); + const again = await fwd.waitFor((e) => e.event === "ready", 30_000, "ready"); + check( + again.channelId === ready.channelId && again.channel === "reused", + "the second run reuses the same channel and URL", + ); + await waitReceived(OFFLINE_COUNT, 90_000); + const tags = received.map((r) => r.header); + const expected = Array.from( + { length: OFFLINE_COUNT }, + (_, i) => `offline-${String(i).padStart(2, "0")}`, + ); + check(JSON.stringify(tags) === JSON.stringify(expected), `in order: ${tags.join(",")}`); + check( + received.every((r) => r.method === "POST" && r.url.startsWith("/e2e?tag=offline-")), + "method, path and query reach localhost", + ); + check(JSON.parse(received[0].body).tag === "offline-00", "body reaches localhost"); + await fwd.waitFor( + (e) => + e.event === "delivered" && + e.id && + fwd.events.filter((x) => x.event === "delivered").length >= OFFLINE_COUNT, + 30_000, + "delivered reports", + ); + step(`all ${OFFLINE_COUNT} delivered in order`); + + // 4. live delivery latency. Wait for the stream: polling alone (every 2 s) + // can land under 2 s by luck, so only a connected stream proves the wake-up. + await fwd.waitFor( + (e) => e.event === "stream" && e.connected === true, + 30_000, + "stream connected", + ); + const liveLatencies = []; + for (let i = 0; i < 3; i++) { + const before = received.length; + const sent = Date.now(); + await sendWebhook(`live-${i}`); + await waitReceived(before + 1, 15_000); + liveLatencies.push(received[before].at - sent); + } + const best = Math.min(...liveLatencies); + check( + Math.max(...liveLatencies) < LIVE_LIMIT_MS, + `live delivery under ${LIVE_LIMIT_MS} ms: ${liveLatencies.join(", ")} ms`, + ); + step(`live delivery: ${liveLatencies.join(", ")} ms (best ${best})`); + + // 5. target down: webhooks wait, then arrive in order. + await stopServer(); + const downFrom = received.length; + await sendWebhook("down-0"); + await fwd.waitFor((e) => e.event === "target_down", 30_000, "target_down"); + await sendWebhook("down-1"); + await sleep(2000); + check(received.length === downFrom, "nothing delivered while the server is down"); + await startServer(); + await fwd.waitFor((e) => e.event === "target_up", 60_000, "target_up"); + await waitReceived(downFrom + 2, 30_000); + check( + received[downFrom].header === "down-0" && received[downFrom + 1].header === "down-1", + "held webhooks arrive in order", + ); + step("server down: held, then delivered in order once back"); + + // 6. taking over a channel another client made on a port: a script is + // refused without --adopt; --adopt --path takes it (same URL) and applies + // the paths. + const takeoverPort = PORT + 1; + const ecdh = createECDH("prime256v1"); + ecdh.generateKeys(); + const made = await api("/api/channels", { + method: "POST", + body: JSON.stringify({ + publicKey: ecdh.getPublicKey("hex"), + port: takeoverPort, + allowedPaths: [], + }), + }); + check(made.ok, `dashboard-style channel answered ${made.status}`); + const other = await made.json(); + const refused = await run(["forward", String(takeoverPort)]); + check( + refused.code === 1 && + refused.events.some((e) => e.event === "error" && /--adopt/.test(e.message)), + "a script is refused a takeover without --adopt", + ); + const hits = []; + const second = http.createServer((req, res) => { + hits.push(req.url); + res.writeHead(200).end("ok"); + }); + await new Promise((r) => second.listen(takeoverPort, "127.0.0.1", r)); + cleanup.push(() => new Promise((r) => second.close(() => r()))); + const adopt = cli(["forward", String(takeoverPort), "--adopt", "--path", "/only"]); + const adopted = await adopt.waitFor((e) => e.event === "ready", 30_000, "ready (adopt)"); + check( + adopted.channel === "adopted" && adopted.channelId === other.channelId, + "--adopt keeps the same channel", + ); + check(adopted.webhookUrl === other.webhookUrl, "--adopt keeps the same URL"); + const { channels: listedAfter = [] } = await (await api("/api/me/channels")).json(); + const paths = listedAfter.find((c) => c.id === other.channelId)?.allowedPaths; + check( + JSON.stringify(paths) === '["/only"]', + `--path is applied to an adopted channel (got ${JSON.stringify(paths)})`, + ); + const blocked = await fetch(`${other.webhookUrl}/elsewhere`, { method: "POST", body: "{}" }); + check(blocked.status === 403, `a path outside --path is refused (got ${blocked.status})`); + const allowed = await fetch(`${other.webhookUrl}/only/x`, { method: "POST", body: "{}" }); + check(allowed.status < 300, `a path inside --path is accepted (got ${allowed.status})`); + await adopt.waitFor((e) => e.event === "delivered", 15_000, "delivery on the adopted channel"); + check(hits.includes("/only/x"), "the adopted channel delivers to localhost"); + adopt.child.kill("SIGINT"); + check((await adopt.exited) === 0, "adopted forward stops cleanly"); + step("takeover: refused without --adopt; --adopt keeps the URL and applies --path"); + + // 7. Ctrl-C stops promptly, then a second login revokes the token it + // replaces, and logout revokes the token on the relay. + const ctrlC = Date.now(); + fwd.child.kill("SIGINT"); + check((await fwd.exited) === 0, "forward stops cleanly"); + check(Date.now() - ctrlC < 3000, `Ctrl-C stops within 3 s (took ${Date.now() - ctrlC} ms)`); + check( + fwd.events.some((e) => e.event === "stopped"), + "forward reports stopped", + ); + + const firstToken = JSON.parse(readFileSync(join(CONFIG, "token.json"), "utf8")).token; + const relogin = cli(["login", "--no-browser", "--force"]); + const code2 = ( + await relogin.waitFor((e) => e.event === "pairing", 30_000, "a second pairing code") + ).code; + const approve2 = await api("/auth/device/approve", { + method: "POST", + body: JSON.stringify({ code: code2 }), + }); + check(approve2.ok, `second approve answered ${approve2.status}`); + check((await relogin.exited) === 0, "login --force exits 0"); + const replaced = await fetch(`${RELAY}/api/me`, { + headers: { authorization: `Bearer ${firstToken}` }, + }); + check( + replaced.status === 401, + `login --force revokes the token it replaces (got ${replaced.status})`, + ); + const { devices: devs = [] } = await (await api("/api/me/devices")).json(); + check(devs.filter((d) => !d.revokedAt).length === 1, "one active device after re-pairing"); + step("login --force: the replaced token is revoked, no orphan device"); + + const token = JSON.parse(readFileSync(join(CONFIG, "token.json"), "utf8")).token; + const out = await run(["logout"]); + check(out.code === 0 && out.events[0]?.revoked === true, `logout revokes: ${out.stderr}`); + check(!existsSync(join(CONFIG, "token.json")), "logout removes the local token"); + const after = await fetch(`${RELAY}/api/me`, { headers: { authorization: `Bearer ${token}` } }); + check(after.status === 401, `the old token is refused after logout (got ${after.status})`); + step("logout: token revoked on the relay and removed locally"); + + await resetAccount("teardown"); + console.log("\nPASS"); +} catch (err) { + failed = true; + console.error(`\nFAIL: ${err.message}`); + try { + await resetAccount("teardown"); + } catch {} +} finally { + for (const f of cleanup.reverse()) { + try { + await f(); + } catch {} + } + process.exit(failed ? 1 : 0); +} diff --git a/cli/src/forward.rs b/cli/src/forward.rs new file mode 100644 index 0000000..75a5ce2 --- /dev/null +++ b/cli/src/forward.rs @@ -0,0 +1,583 @@ +//! `bridgehook forward `: keep one channel per target, print its +//! public URL, and deliver its queue to the target in order. +//! +//! The live stream only wakes the drain; the drain always reads the queue +//! oldest first, so a live webhook never overtakes one that waited while +//! this machine was offline. Without the stream (signed out, or the stream +//! is down) the queue is polled. + +use crate::output::{clock, Out}; +use crate::Session; +use anyhow::{bail, Result}; +use bridgehook_core::config::{self, ChannelMap}; +use bridgehook_core::drain::{DrainDeps, DrainEvent, Drainer, PassResult}; +use bridgehook_core::forward::{event_path, ForwardOutcome, Target}; +use bridgehook_core::keys::ChannelKey; +use bridgehook_core::relay::{ + ChannelInfo, ForwardResult, PendingPage, QueuedEvent, RelayClient, RelayError, +}; +use bridgehook_core::stream; +use serde_json::json; +use std::collections::BTreeSet; +use std::io::{BufRead, IsTerminal, Write}; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::Arc; +use std::time::Duration; +use tokio::sync::Notify; + +const POLL_WITHOUT_STREAM: Duration = Duration::from_secs(2); +const POLL_WITH_STREAM: Duration = Duration::from_secs(30); +const BLOCKED_WAIT: Duration = Duration::from_secs(10); +const QUOTA_WAIT: Duration = Duration::from_secs(60); +const RETRY_MIN: Duration = Duration::from_secs(2); +/// Relay trouble backs off further than a local server that is down, which +/// should be picked up within seconds of coming back. +const RETRY_MAX_RELAY: Duration = Duration::from_secs(15); +const RETRY_MAX_TARGET: Duration = Duration::from_secs(5); + +#[derive(clap::Args)] +pub struct ForwardArgs { + /// Local port (3000) or URL (http://api:8080/base). + target: String, + /// Only accept webhooks under this path (repeatable). Applied to a reused + /// channel too; without it, a reused channel keeps its paths. + #[arg(long = "path", value_name = "PATH", conflicts_with = "any_path")] + paths: Vec, + /// Accept webhooks on any path (clears a previous --path). + #[arg(long)] + any_path: bool, + /// Make a new channel (and a new URL) instead of reusing this target's. + #[arg(long, conflicts_with = "adopt")] + new: bool, + /// Take over your account's channel on this port without asking, even if + /// another device (the extension, another machine) forwards it now. + #[arg(long)] + adopt: bool, +} + +/// The channel this run forwards for. +struct Channel { + id: String, + key: ChannelKey, + webhook_url: String, + allowed_paths: Option>, + how: &'static str, +} + +pub async fn run(session: &Session, out: Out, args: ForwardArgs) -> Result { + let target = Target::parse(&args.target)?; + for p in &args.paths { + if !p.starts_with('/') { + bail!("--path must start with / (got `{p}`)"); + } + } + let relay = session.client()?; + let channel = resolve_channel(session, &relay, &target, &args, out).await?; + apply_paths(session, &relay, &channel, &args, out).await?; + let executor = config::executor_id(&session.paths)?; + + out.emit( + json!({ + "event": "ready", + "channelId": channel.id, + "webhookUrl": channel.webhook_url, + "target": target.display(), + "channel": channel.how, + }), + || { + format!( + "\n {} {}\n {} {}\n\n{}", + out.dim("Webhook URL"), + out.bold(&channel.webhook_url), + out.dim("Forwarding "), + target.display(), + out.dim("Webhooks sent while this is not running wait on the relay and arrive in order next time. Ctrl-C to stop.\n"), + ) + }, + ); + + let deps = ChannelDeps { + relay: relay.clone(), + key: channel.key, + channel_id: channel.id.clone(), + executor, + device_id: session.device_id().map(str::to_string), + target: target.clone(), + }; + + // Ctrl-C: finish the webhook in hand, then stop. A second Ctrl-C quits. + let stop = Arc::new(AtomicBool::new(false)); + let stopped = Arc::new(Notify::new()); + { + let (stop, stopped) = (stop.clone(), stopped.clone()); + tokio::spawn(async move { + if tokio::signal::ctrl_c().await.is_ok() { + stop.store(true, Ordering::SeqCst); + stopped.notify_one(); + if !out.json { + eprintln!("\nStopping after the current webhook; Ctrl-C again to quit now."); + } + if tokio::signal::ctrl_c().await.is_ok() { + std::process::exit(130); + } + } + }); + } + + // The live stream needs a signed-in token; signed out, the queue is polled. + let wake = Arc::new(Notify::new()); + let connected = Arc::new(AtomicBool::new(false)); + if session.token.is_some() { + tokio::spawn(report_stream_state(out, connected.clone(), stop.clone())); + let (relay, connected, stop, wake) = + (relay.clone(), connected.clone(), stop.clone(), wake.clone()); + let ours = channel.id.clone(); + tokio::spawn(async move { + stream::run(relay, connected, stop, move |frame| { + if frame.kind == "webhook" && frame.channel_id.as_deref() == Some(ours.as_str()) { + wake.notify_one(); + } + }) + .await; + }); + } + + let mut drainer = Drainer::new(); + let mut notify = |e: DrainEvent| report_event(out, &e); + let mut retry = RETRY_MIN; + loop { + if stop.load(Ordering::SeqCst) { + break; + } + let wait = match drainer.pass(&deps, &mut notify).await { + Ok(PassResult::Idle) => { + retry = RETRY_MIN; + if connected.load(Ordering::Relaxed) { + POLL_WITH_STREAM + } else { + POLL_WITHOUT_STREAM + } + } + Ok(PassResult::Blocked) => { + retry = RETRY_MIN; + BLOCKED_WAIT + } + Ok(PassResult::Retry) => next_retry( + &mut retry, + if drainer.target_down() { RETRY_MAX_TARGET } else { RETRY_MAX_RELAY }, + ), + Err(e) => match e.downcast_ref::() { + Some(RelayError::Unauthorized) => bail!( + "the relay no longer accepts this machine's key for {}: another client (the extension or another CLI) took the channel. Run `bridgehook forward {} --adopt` to take it back.", + channel.webhook_url, + args.target + ), + Some(RelayError::ChannelGone) => bail!( + "channel {} was deleted or expired. Run `bridgehook forward {}` again for a new URL.", + channel.id, + args.target + ), + Some(RelayError::Quota { message }) => { + out.emit(json!({ "event": "quota", "message": message }), || { + format!("{} {message}", out.yellow("quota:")) + }); + QUOTA_WAIT + } + _ => { + let w = next_retry(&mut retry, RETRY_MAX_RELAY); + out.emit( + json!({ "event": "relay_error", "message": format!("{e:#}"), "retryInMs": w.as_millis() as u64 }), + || format!("{} {e:#} (retrying in {}s)", out.yellow("relay:"), w.as_secs()), + ); + w + } + }, + }; + if stop.load(Ordering::SeqCst) { + break; + } + // Wait for the timer or Ctrl-C, or for the stream to report a + // webhook (useless while the local server is down). + if drainer.target_down() { + tokio::select! { + _ = stopped.notified() => {} + _ = tokio::time::sleep(wait) => {} + } + } else { + tokio::select! { + _ = stopped.notified() => {} + _ = wake.notified() => {} + _ = tokio::time::sleep(wait) => {} + } + } + } + out.emit(json!({ "event": "stopped" }), || "Stopped.".into()); + Ok(0) +} + +fn next_retry(retry: &mut Duration, max: Duration) -> Duration { + let w = (*retry).min(max); + *retry = (*retry * 2).min(max); + w +} + +/// Reports when the live stream connects or drops (polling takes over). +async fn report_stream_state(out: Out, connected: Arc, stop: Arc) { + let mut last = false; + while !stop.load(Ordering::Relaxed) { + let now = connected.load(Ordering::Relaxed); + if now != last { + last = now; + out.emit(json!({ "event": "stream", "connected": now }), || { + if now { + format!("{} {} live", out.dim(&clock()), out.green("●")) + } else { + format!( + "{} {} live updates lost; checking every {} s until they are back", + out.dim(&clock()), + out.yellow("○"), + POLL_WITHOUT_STREAM.as_secs() + ) + } + }); + } + tokio::time::sleep(Duration::from_millis(200)).await; + } +} + +fn report_event(out: Out, e: &DrainEvent) { + match e { + DrainEvent::Delivered { event, result } => { + let path = event_path(event); + out.emit( + json!({ + "event": "delivered", + "id": event.id, + "method": event.method, + "path": path, + "status": result.status, + "latencyMs": result.latency_ms, + }), + || { + let status = result.status.to_string(); + let status = if result.status < 400 { + out.green(&status) + } else { + out.red(&status) + }; + format!( + "{} {} {:<6} {} {} {}", + out.dim(&clock()), + out.green("→"), + event.method, + path, + status, + out.dim(&format!("{} ms", result.latency_ms)) + ) + }, + ); + } + DrainEvent::Skipped { event, message } => { + let path = event_path(event); + out.emit( + json!({ "event": "skipped", "id": event.id, "method": event.method, "path": path, "message": message }), + || format!("{} {} {:<6} {} {}", out.dim(&clock()), out.red("✗"), event.method, path, message), + ); + } + DrainEvent::TargetDown(message) => { + out.emit( + json!({ "event": "target_down", "message": message }), + || { + format!( + "{} {} {message} Webhooks wait until it is back.", + out.dim(&clock()), + out.yellow("!") + ) + }, + ); + } + DrainEvent::TargetUp => { + out.emit(json!({ "event": "target_up" }), || { + format!( + "{} {} Local server is back; delivering.", + out.dim(&clock()), + out.green("✓") + ) + }); + } + } +} + +/// The paths a channel should accept after this run, when the flags change +/// them: `--path` sets them, `--any-path` clears them, neither keeps them. +fn wanted_paths(args: &ForwardArgs) -> Option> { + if args.any_path { + Some(Vec::new()) + } else if !args.paths.is_empty() { + Some(args.paths.clone()) + } else { + None + } +} + +/// Brings a reused or adopted channel's allowed paths in line with the flags. +async fn apply_paths( + session: &Session, + relay: &RelayClient, + channel: &Channel, + args: &ForwardArgs, + out: Out, +) -> Result<()> { + let Some(wanted) = wanted_paths(args) else { + return Ok(()); + }; + if channel.how == "created" { + return Ok(()); + } + let same = |have: &[String]| { + have.iter().collect::>() == wanted.iter().collect::>() + }; + if channel.allowed_paths.as_deref().is_some_and(same) { + return Ok(()); + } + if session.token.is_none() { + bail!( + "changing which paths a channel accepts needs you signed in (`bridgehook login`), or use --new for a channel made with these paths" + ); + } + relay.set_allowed_paths(&channel.id, &wanted).await?; + out.note(&format!( + "{} this URL now accepts {}.", + out.dim("paths:"), + if wanted.is_empty() { + "any path".to_string() + } else { + wanted.join(", ") + } + )); + Ok(()) +} + +/// Reuse this target's channel when this machine has its key; else adopt the +/// account's channel on the same port (moving its key here, after asking); +/// else create one. +async fn resolve_channel( + session: &Session, + relay: &RelayClient, + target: &Target, + args: &ForwardArgs, + out: Out, +) -> Result { + let mut map = ChannelMap::load(&session.paths)?; + let target_key = target.display(); + let signed_in = session.token.is_some(); + let listed = if signed_in && !args.new { + Some(relay.list_channels().await?) + } else { + None + }; + + if !args.new { + if let Some(id) = map.get(&session.relay_url, &target_key).map(str::to_string) { + if let Some(key) = ChannelKey::load(&session.paths, &id)? { + let found = match &listed { + Some(list) => list + .iter() + .find(|c| c.id == id) + .map(|c| (c.webhook_url.clone(), Some(c.allowed_paths.clone()))), + None => relay.channel_webhook_url(&id).await?.map(|u| (u, None)), + }; + if let Some((webhook_url, allowed_paths)) = found { + return Ok(Channel { + id, + key, + webhook_url, + allowed_paths, + how: "reused", + }); + } + out.note(&format!( + "{} channel {id} is gone; making a new one.", + out.yellow("note:") + )); + } + } + + if let Some(list) = &listed { + let port = target.port(); + if let Some(existing) = list.iter().find(|c| c.port == port) { + let key = match ChannelKey::load(&session.paths, &existing.id)? { + Some(k) => k, + None => { + confirm_takeover(session, existing, args, out)?; + let key = ChannelKey::generate(); + relay + .rotate_key(&existing.id, &key.public_key_hex()) + .await?; + key.save(&session.paths, &existing.id)?; + key + } + }; + map.set(&session.relay_url, &target_key, &existing.id); + map.save(&session.paths)?; + return Ok(Channel { + id: existing.id.clone(), + key, + webhook_url: existing.webhook_url.clone(), + allowed_paths: Some(existing.allowed_paths.clone()), + how: "adopted", + }); + } + } + } + + let key = ChannelKey::generate(); + let paths = wanted_paths(args).unwrap_or_default(); + let created = match relay + .create_channel(&key.public_key_hex(), target.port(), &paths) + .await + { + Ok(c) => c, + Err(RelayError::Unauthorized) => { + bail!( + "{} needs you signed in. Run `bridgehook login` first.", + session.relay_url + ) + } + Err(e) => return Err(e.into()), + }; + key.save(&session.paths, &created.channel_id)?; + map.set(&session.relay_url, &target_key, &created.channel_id); + map.save(&session.paths)?; + Ok(Channel { + id: created.channel_id, + key, + webhook_url: created.webhook_url, + allowed_paths: Some(paths), + how: "created", + }) +} + +/// Taking over a channel moves its key here, so whatever forwards it now +/// (usually the extension) stops. Ask first, unless this device made it or +/// `--adopt` says so; a script without `--adopt` gets an error, not a guess. +fn confirm_takeover( + session: &Session, + existing: &ChannelInfo, + args: &ForwardArgs, + out: Out, +) -> Result<()> { + let ours = existing + .device + .as_ref() + .is_some_and(|d| Some(d.id.as_str()) == session.device_id()); + if args.adopt || ours { + return Ok(()); + } + let owner = existing + .device + .as_ref() + .and_then(|d| d.label.clone().or_else(|| d.kind.clone())) + .unwrap_or_else(|| "another client".into()); + let what = format!( + "Your account already has {} on port {}, made by {owner}. Taking it over keeps that URL, and {owner} stops forwarding it.", + existing.webhook_url, existing.port + ); + let interactive = + !out.json && std::io::stdin().is_terminal() && std::io::stderr().is_terminal(); + if !interactive { + bail!("{what} Pass --adopt to take it over, or --new for a separate URL."); + } + eprint!("{what}\nTake it over? [Y/n] (n makes a separate URL with --new) "); + let _ = std::io::stderr().flush(); + let mut answer = String::new(); + std::io::stdin().lock().read_line(&mut answer)?; + match answer.trim().to_ascii_lowercase().as_str() { + "" | "y" | "yes" => Ok(()), + _ => bail!( + "not taken over. Run `bridgehook forward {} --new` for a separate URL.", + args.target + ), + } +} + +/// The drain's view of one channel on the relay and the local target. +struct ChannelDeps { + relay: RelayClient, + key: ChannelKey, + channel_id: String, + executor: String, + device_id: Option, + target: Target, +} + +impl DrainDeps for ChannelDeps { + async fn fetch_pending(&self, after: Option) -> Result { + Ok(self + .relay + .fetch_pending(&self.channel_id, &self.key, after.as_deref()) + .await?) + } + + async fn claim(&self, event_id: &str) -> Result { + Ok(self + .relay + .claim(&self.channel_id, &self.key, event_id, &self.executor) + .await?) + } + + async fn probe(&self) -> Result<(), String> { + self.target.probe().await + } + + async fn forward(&self, event: &QueuedEvent) -> ForwardOutcome { + self.target.forward(event).await + } + + async fn report(&self, event: &QueuedEvent, result: &ForwardResult) -> Result<()> { + Ok(self + .relay + .report( + &self.channel_id, + &self.key, + &event.id, + result, + self.device_id.as_deref(), + ) + .await?) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn args(paths: &[&str], any: bool) -> ForwardArgs { + ForwardArgs { + target: "3000".into(), + paths: paths.iter().map(|s| s.to_string()).collect(), + any_path: any, + new: false, + adopt: false, + } + } + + #[test] + fn path_flags_set_clear_or_keep() { + assert_eq!( + wanted_paths(&args(&["/a", "/b"], false)), + Some(vec!["/a".into(), "/b".into()]) + ); + assert_eq!(wanted_paths(&args(&[], true)), Some(vec![])); + assert_eq!(wanted_paths(&args(&[], false)), None); + } + + #[test] + fn retry_backoff_caps_per_cause() { + let mut r = RETRY_MIN; + let waits: Vec = (0..5) + .map(|_| next_retry(&mut r, RETRY_MAX_TARGET).as_secs()) + .collect(); + assert_eq!(waits, vec![2, 4, 5, 5, 5]); + } +} diff --git a/cli/src/main.rs b/cli/src/main.rs new file mode 100644 index 0000000..550b670 --- /dev/null +++ b/cli/src/main.rs @@ -0,0 +1,326 @@ +//! `bridgehook`: a stable public webhook URL that forwards to localhost. +//! +//! Webhooks that arrive while nothing is forwarding wait on the relay and +//! are delivered in order when `bridgehook forward` runs again. + +mod forward; +mod output; + +use anyhow::{Context, Result}; +use bridgehook_core::auth; +use bridgehook_core::config::{self, Paths, StoredToken}; +use bridgehook_core::relay::{RelayClient, RelayError}; +use bridgehook_core::DEFAULT_RELAY_URL; +use clap::{Parser, Subcommand}; +use output::Out; +use serde_json::json; +use std::path::PathBuf; + +#[derive(Parser)] +#[command(name = "bridgehook", version, about, propagate_version = true)] +struct Cli { + /// Relay to use (defaults to the relay you signed in to, else the hosted one). + #[arg(long, env = "BRIDGEHOOK_RELAY", global = true)] + relay: Option, + + /// Print one JSON object per line instead of readable text. + #[arg(long, global = true)] + json: bool, + + /// Where the token, keys and channel list are kept. + #[arg( + long, + env = "BRIDGEHOOK_CONFIG_DIR", + global = true, + hide_env_values = true + )] + config_dir: Option, + + #[command(subcommand)] + command: Command, +} + +#[derive(Subcommand)] +enum Command { + /// Pair this machine with your BridgeHook account. + Login { + /// Pair again even if this machine is already signed in. + #[arg(long)] + force: bool, + /// Print the approval link instead of opening a browser. + #[arg(long)] + no_browser: bool, + }, + /// Revoke this machine's token and forget it. + Logout, + /// Show the account this machine is signed in to. + Whoami, + /// Forward webhooks to a local port or URL (e.g. 3000, http://api:8080). + Forward(forward::ForwardArgs), +} + +#[tokio::main] +async fn main() { + let cli = Cli::parse(); + let out = Out::new(cli.json); + let code = match run(cli, out).await { + Ok(code) => code, + Err(e) => { + out.error(&format!("{e:#}")); + 1 + } + }; + std::process::exit(code); +} + +/// The relay, token and paths every command works from. +pub struct Session { + pub paths: Paths, + pub relay_url: String, + pub stored: Option, + /// The token in use: `BRIDGEHOOK_TOKEN`, else the stored one for this relay. + pub token: Option, +} + +impl Session { + fn open(cli: &Cli, out: Out) -> Result { + let paths = match &cli.config_dir { + Some(dir) => Paths::at(dir), + None => Paths::discover()?, + }; + let stored = config::load_token(&paths)?; + let relay_url = cli + .relay + .clone() + .or_else(|| stored.as_ref().map(|t| t.relay.clone())) + .unwrap_or_else(|| DEFAULT_RELAY_URL.to_string()) + .trim_end_matches('/') + .to_string(); + let env_token = std::env::var("BRIDGEHOOK_TOKEN") + .ok() + .filter(|t| !t.trim().is_empty()); + let stored_token = match &stored { + Some(t) if t.relay == relay_url => Some(t.token.clone()), + Some(t) => { + out.note(&format!( + "{} signed in to {}, not {relay_url}; continuing signed out", + out.yellow("note:"), + t.relay + )); + None + } + None => None, + }; + Ok(Self { + paths, + relay_url, + token: env_token.or(stored_token), + stored, + }) + } + + pub fn client(&self) -> Result { + RelayClient::new(&self.relay_url, self.token.clone()) + } + + /// The stored device id, when the token in use is the stored one. + pub fn device_id(&self) -> Option<&str> { + match (&self.stored, &self.token) { + (Some(s), Some(t)) if &s.token == t && s.relay == self.relay_url => Some(&s.device_id), + _ => None, + } + } +} + +async fn run(cli: Cli, out: Out) -> Result { + let session = Session::open(&cli, out)?; + match cli.command { + Command::Login { force, no_browser } => login(&session, out, force, no_browser).await, + Command::Logout => logout(&session, out).await, + Command::Whoami => whoami(&session, out).await, + Command::Forward(args) => forward::run(&session, out, args).await, + } +} + +async fn login(session: &Session, out: Out, force: bool, no_browser: bool) -> Result { + if !force { + if let (Some(stored), Some(_)) = (&session.stored, &session.token) { + if stored.relay == session.relay_url { + match session.client()?.me().await { + Ok(me) => { + out.emit( + json!({ "event": "signed_in", "email": me.user.email, "relay": session.relay_url, "deviceId": stored.device_id }), + || format!("Already signed in as {} ({}). Use --force to pair again.", out.bold(&me.user.email), session.relay_url), + ); + return Ok(0); + } + Err(RelayError::Unauthorized) => { + out.note("The saved token was revoked; pairing again."); + } + Err(e) => return Err(e.into()), + } + } + } + } + + let relay = RelayClient::new(&session.relay_url, None)?; + let minted = auth::pair(&relay, &auth::label_hint(), |start| { + let opened = !no_browser && !out.json && open_browser(&start.verification_url); + out.emit( + json!({ "event": "pairing", "code": start.device_code, "url": start.verification_url, "expiresIn": start.expires_in }), + || { + let how = if opened { "Approve in the browser window that just opened, or open" } else { "Open" }; + format!( + "{how}:\n\n {}\n\nand check the code matches: {}\n\n{}", + out.bold(&start.verification_url), + out.bold(&start.device_code), + out.dim("Waiting for approval…") + ) + }, + ); + }) + .await?; + + let token = StoredToken { + token: minted.token, + device_id: minted.device_id.clone(), + user_id: minted.user_id, + label: minted.label.clone(), + relay: session.relay_url.clone(), + }; + config::save_token(&session.paths, &token)?; + // The token this one replaces (re-pairing, or another relay) would + // otherwise live on as an orphan device holding a slot: revoke it, now + // that the new pairing is safely stored. + if let Some(previous) = session.stored.as_ref().filter(|p| p.token != token.token) { + let old = RelayClient::new(&previous.relay, Some(previous.token.clone()))?; + match old.revoke_device(&previous.device_id).await { + Ok(()) | Err(RelayError::Unauthorized) => {} + Err(e) => out.note(&format!( + "{} could not revoke the previous token on {} ({e}); revoke it from that dashboard's Devices page.", + out.yellow("warning:"), + previous.relay + )), + } + } + let email = RelayClient::new(&session.relay_url, Some(token.token.clone()))? + .me() + .await + .map(|m| m.user.email) + .ok(); + out.emit( + json!({ "event": "signed_in", "email": email, "relay": session.relay_url, "deviceId": minted.device_id, "label": minted.label }), + || match &email { + Some(e) => format!("{} Signed in as {} on this machine ({}).", out.green("✓"), out.bold(e), minted.label), + None => format!("{} Signed in ({}).", out.green("✓"), minted.label), + }, + ); + Ok(0) +} + +async fn logout(session: &Session, out: Out) -> Result { + let Some(stored) = &session.stored else { + out.emit(json!({ "event": "signed_out", "revoked": false }), || { + "Not signed in.".into() + }); + return Ok(0); + }; + let relay = RelayClient::new(&stored.relay, Some(stored.token.clone()))?; + let revoked = match relay.revoke_device(&stored.device_id).await { + Ok(()) => true, + // Already revoked (from the dashboard, say): nothing left to end. + Err(RelayError::Unauthorized) => true, + Err(e) => { + out.note(&format!( + "{} could not revoke the token on {} ({e}); it is removed from this machine. Revoke it from the dashboard's Devices page.", + out.yellow("warning:"), + stored.relay + )); + false + } + }; + config::remove_token(&session.paths).context("removing the saved token")?; + out.emit( + json!({ "event": "signed_out", "revoked": revoked, "relay": stored.relay }), + || format!("{} Signed out of {}.", out.green("✓"), stored.relay), + ); + Ok(if revoked { 0 } else { 1 }) +} + +async fn whoami(session: &Session, out: Out) -> Result { + if session.token.is_none() { + out.emit( + json!({ "event": "whoami", "signedIn": false, "relay": session.relay_url }), + || { + format!( + "Not signed in to {}. Run `bridgehook login`.", + session.relay_url + ) + }, + ); + return Ok(1); + } + let me = session.client()?.me().await?; + let label = session + .stored + .as_ref() + .filter(|_| session.device_id().is_some()) + .map(|s| s.label.clone()); + out.emit( + json!({ + "event": "whoami", + "signedIn": true, + "email": me.user.email, + "plan": me.plan, + "eventsToday": me.events_today, + "eventsPerDay": me.events_per_day, + "relay": session.relay_url, + "deviceId": session.device_id(), + "device": label, + }), + || { + let cap = me + .events_per_day + .map(|n| n.to_string()) + .unwrap_or_else(|| "unlimited".into()); + let mut s = format!( + "{}\n plan {}\n today {} of {cap} webhooks\n relay {}", + out.bold(&me.user.email), + me.plan, + me.events_today, + session.relay_url + ); + if let Some(l) = &label { + s.push_str(&format!("\n device {l}")); + } + s + }, + ); + Ok(0) +} + +/// Best effort: opens the approval page in the default browser. +fn open_browser(url: &str) -> bool { + use std::process::{Command, Stdio}; + let mut cmd = if cfg!(target_os = "macos") { + let mut c = Command::new("open"); + c.arg(url); + c + } else if cfg!(target_os = "windows") { + let mut c = Command::new("rundll32"); + c.args(["url.dll,FileProtocolHandler", url]); + c + } else { + if std::env::var_os("DISPLAY").is_none() && std::env::var_os("WAYLAND_DISPLAY").is_none() { + return false; + } + let mut c = Command::new("xdg-open"); + c.arg(url); + c + }; + cmd.stdin(Stdio::null()) + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .spawn() + .is_ok() +} diff --git a/cli/src/output.rs b/cli/src/output.rs new file mode 100644 index 0000000..7f6e66a --- /dev/null +++ b/cli/src/output.rs @@ -0,0 +1,76 @@ +//! What the CLI prints: readable lines on a terminal, one JSON object per +//! line with `--json` (for scripts and agents). Colour only on a terminal, +//! and never when `NO_COLOR` is set. + +use serde_json::{json, Value}; +use std::io::{IsTerminal, Write}; + +#[derive(Clone, Copy)] +pub struct Out { + pub json: bool, + color: bool, +} + +impl Out { + pub fn new(json: bool) -> Self { + let color = + !json && std::io::stdout().is_terminal() && std::env::var_os("NO_COLOR").is_none(); + Self { json, color } + } + + fn paint(&self, code: &str, s: &str) -> String { + if self.color { + format!("\x1b[{code}m{s}\x1b[0m") + } else { + s.to_string() + } + } + + pub fn green(&self, s: &str) -> String { + self.paint("32", s) + } + pub fn red(&self, s: &str) -> String { + self.paint("31", s) + } + pub fn yellow(&self, s: &str) -> String { + self.paint("33", s) + } + pub fn dim(&self, s: &str) -> String { + self.paint("2", s) + } + pub fn bold(&self, s: &str) -> String { + self.paint("1", s) + } + + /// A JSON line in `--json` mode, otherwise the human line. + pub fn emit(&self, value: Value, human: impl FnOnce() -> String) { + let mut stdout = std::io::stdout().lock(); + if self.json { + let _ = writeln!(stdout, "{value}"); + } else { + let _ = writeln!(stdout, "{}", human()); + } + let _ = stdout.flush(); + } + + /// Notes for people (progress, hints). Go to stderr so `--json` stdout + /// stays machine-readable. + pub fn note(&self, s: &str) { + if !self.json { + eprintln!("{s}"); + } + } + + pub fn error(&self, message: &str) { + if self.json { + println!("{}", json!({ "event": "error", "message": message })); + } else { + eprintln!("{} {message}", self.red("error:")); + } + } +} + +/// Local wall-clock time, HH:MM:SS. +pub fn clock() -> String { + chrono::Local::now().format("%H:%M:%S").to_string() +} diff --git a/crates/bridgehook-core/Cargo.toml b/crates/bridgehook-core/Cargo.toml new file mode 100644 index 0000000..9fdcc23 --- /dev/null +++ b/crates/bridgehook-core/Cargo.toml @@ -0,0 +1,26 @@ +[package] +name = "bridgehook-core" +description = "BridgeHook protocol client: device pairing, signed relay API, ordered delivery" +version.workspace = true +edition.workspace = true +license.workspace = true +repository.workspace = true +rust-version.workspace = true + +[dependencies] +anyhow.workspace = true +thiserror.workspace = true +dirs.workspace = true +futures-util.workspace = true +hex.workspace = true +p256.workspace = true +rand_core.workspace = true +reqwest.workspace = true +serde.workspace = true +serde_json.workspace = true +sha2.workspace = true +tokio.workspace = true +url.workspace = true + +[dev-dependencies] +tokio = { workspace = true, features = ["test-util"] } diff --git a/crates/bridgehook-core/src/auth.rs b/crates/bridgehook-core/src/auth.rs new file mode 100644 index 0000000..c528391 --- /dev/null +++ b/crates/bridgehook-core/src/auth.rs @@ -0,0 +1,189 @@ +//! Device pairing for `bridgehook login`: the relay issues a code, the user +//! approves it in the dashboard (on any device, a phone included), and this +//! install polls until it receives a device token. +//! +//! Polling follows the extension (`apps/extension/pairing.js`): 202 waits +//! the interval, 429 waits `Retry-After`, 5xx and network errors back off +//! (the relay keeps an approved code when minting fails), 410 and other 4xx +//! stop. + +use crate::relay::{DeviceMinted, DeviceStart, ExchangePoll, RelayClient}; +use std::future::Future; +use std::time::Duration; +use tokio::time::Instant; + +const MAX_WAIT: Duration = Duration::from_secs(60); + +#[derive(Debug, thiserror::Error, PartialEq)] +pub enum PairError { + #[error("the pairing code expired or was already used; run `bridgehook login` again")] + Expired, + #[error("pairing timed out; run `bridgehook login` again")] + TimedOut, + #[error("pairing failed ({0}): {1}")] + Failed(u16, String), +} + +/// Polls `exchange` until the code is approved, refused or expired. +pub async fn poll_until_paired( + mut exchange: F, + interval: Duration, + deadline: Instant, +) -> Result +where + F: FnMut() -> Fut, + Fut: Future, +{ + let mut wait = interval; + let mut failures: u32 = 0; + loop { + let now = Instant::now(); + if now >= deadline { + return Err(PairError::TimedOut); + } + tokio::time::sleep(wait.min(deadline - now)).await; + if Instant::now() >= deadline { + return Err(PairError::TimedOut); + } + wait = interval; + match exchange().await { + ExchangePoll::Minted(m) => return Ok(m), + ExchangePoll::Pending => failures = 0, + ExchangePoll::Expired => return Err(PairError::Expired), + ExchangePoll::RetryAfter(d) => wait = d.min(MAX_WAIT), + ExchangePoll::Transient(_) => { + failures += 1; + wait = (interval * 2u32.saturating_pow(failures)).min(MAX_WAIT); + } + ExchangePoll::Failed(status, message) => { + return Err(PairError::Failed(status, message)) + } + } + } +} + +/// Starts pairing, hands the code to `show` (to print it), then waits for +/// approval. +pub async fn pair( + relay: &RelayClient, + label_hint: &str, + show: impl FnOnce(&DeviceStart), +) -> anyhow::Result { + let start = relay.device_start("cli", label_hint).await?; + show(&start); + let interval = Duration::from_secs(start.poll_interval.clamp(2, 30)); + let deadline = Instant::now() + Duration::from_secs(start.expires_in.max(60)); + let code = start.device_code.clone(); + Ok(poll_until_paired(|| relay.device_exchange(&code), interval, deadline).await?) +} + +/// "bridgehook CLI on ", the label shown when approving. +pub fn label_hint() -> String { + let host = std::env::var("HOSTNAME") + .ok() + .filter(|h| !h.is_empty()) + .or_else(|| { + std::fs::read_to_string("/etc/hostname") + .ok() + .map(|h| h.trim().to_string()) + }) + .or_else(|| std::env::var("COMPUTERNAME").ok()) + .filter(|h| !h.is_empty()) + .unwrap_or_else(|| "this machine".into()); + format!("bridgehook CLI on {host}") +} + +#[cfg(test)] +mod tests { + use super::*; + use std::collections::VecDeque; + use std::sync::Mutex; + + fn minted() -> DeviceMinted { + DeviceMinted { + token: "dvc_x".into(), + device_id: "dev_x".into(), + user_id: "usr_x".into(), + label: "cli".into(), + } + } + + async fn run( + script: Vec, + deadline_secs: u64, + ) -> (Result, Duration) { + let script = Mutex::new(VecDeque::from(script)); + let started = Instant::now(); + let r = poll_until_paired( + || { + let next = script + .lock() + .unwrap() + .pop_front() + .unwrap_or(ExchangePoll::Pending); + async move { next } + }, + Duration::from_secs(5), + Instant::now() + Duration::from_secs(deadline_secs), + ) + .await; + (r, started.elapsed()) + } + + #[tokio::test(start_paused = true)] + async fn waits_through_pending_then_returns_the_device() { + let (r, took) = run( + vec![ + ExchangePoll::Pending, + ExchangePoll::Pending, + ExchangePoll::Minted(minted()), + ], + 900, + ) + .await; + assert_eq!(r.unwrap().token, "dvc_x"); + assert_eq!(took, Duration::from_secs(15)); + } + + #[tokio::test(start_paused = true)] + async fn honours_retry_after_and_backs_off_on_server_errors() { + let (r, took) = run( + vec![ + ExchangePoll::RetryAfter(Duration::from_secs(30)), + ExchangePoll::Transient("503".into()), + ExchangePoll::Transient("503".into()), + ExchangePoll::Minted(minted()), + ], + 900, + ) + .await; + assert!(r.is_ok()); + // 5 (first wait) + 30 (Retry-After) + 10 + 20 (backoff) = 65 + assert_eq!(took, Duration::from_secs(65)); + } + + #[tokio::test(start_paused = true)] + async fn stops_on_expired_or_other_client_errors() { + assert_eq!( + run(vec![ExchangePoll::Expired], 900).await.0.unwrap_err(), + PairError::Expired + ); + assert_eq!( + run( + vec![ExchangePoll::Failed(402, "Device quota reached".into())], + 900 + ) + .await + .0 + .unwrap_err(), + PairError::Failed(402, "Device quota reached".into()) + ); + } + + #[tokio::test(start_paused = true)] + async fn times_out_at_the_deadline() { + let (r, took) = run(vec![], 12).await; + assert_eq!(r.unwrap_err(), PairError::TimedOut); + assert!(took <= Duration::from_secs(12)); + } +} diff --git a/crates/bridgehook-core/src/config.rs b/crates/bridgehook-core/src/config.rs new file mode 100644 index 0000000..c5361ae --- /dev/null +++ b/crates/bridgehook-core/src/config.rs @@ -0,0 +1,264 @@ +//! On-disk state: `~/.config/bridgehook/` (XDG; `%APPDATA%\bridgehook` on +//! Windows), or `$BRIDGEHOOK_CONFIG_DIR`. +//! +//! ```text +//! token.json device token from `bridgehook login` (0600) +//! executor-id this install's claim owner id +//! channels.json forward target → channel id, per relay +//! keys/.pk8 the channel's P-256 private key, PKCS#8 DER (0600) +//! ``` +//! +//! Secrets are written to a temporary file with mode 0600 and renamed into +//! place, so a crash never leaves a half-written or world-readable file. + +use anyhow::{Context, Result}; +use serde::{Deserialize, Serialize}; +use std::collections::BTreeMap; +use std::fs; +use std::io::Write; +use std::path::{Path, PathBuf}; + +#[derive(Debug, Clone)] +pub struct Paths { + pub dir: PathBuf, +} + +impl Paths { + /// `$BRIDGEHOOK_CONFIG_DIR`, else the platform config dir + `bridgehook`. + pub fn discover() -> Result { + if let Some(dir) = std::env::var_os("BRIDGEHOOK_CONFIG_DIR") { + return Ok(Self { + dir: PathBuf::from(dir), + }); + } + let base = dirs::config_dir().context("no config directory on this system")?; + Ok(Self { + dir: base.join("bridgehook"), + }) + } + + pub fn at(dir: impl Into) -> Self { + Self { dir: dir.into() } + } + + pub fn token_file(&self) -> PathBuf { + self.dir.join("token.json") + } + pub fn executor_file(&self) -> PathBuf { + self.dir.join("executor-id") + } + pub fn channels_file(&self) -> PathBuf { + self.dir.join("channels.json") + } + pub fn key_file(&self, channel_id: &str) -> PathBuf { + self.dir.join("keys").join(format!("{channel_id}.pk8")) + } +} + +/// Writes `bytes` to `path` readable by the owner only, atomically. +pub fn write_private(path: &Path, bytes: &[u8]) -> Result<()> { + let parent = path.parent().context("path has no parent")?; + create_private_dir(parent)?; + let tmp = path.with_extension(format!("tmp-{}", std::process::id())); + { + let mut opts = fs::OpenOptions::new(); + opts.write(true).create(true).truncate(true); + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt; + opts.mode(0o600); + } + let mut f = opts + .open(&tmp) + .with_context(|| format!("writing {}", tmp.display()))?; + f.write_all(bytes)?; + f.sync_all()?; + } + fs::rename(&tmp, path).with_context(|| format!("saving {}", path.display()))?; + Ok(()) +} + +/// Creates `dir` (and missing parents) as 0700. A directory that already +/// exists keeps its mode: `--config-dir $HOME` must not lock down $HOME. +/// The files inside are 0600 either way. +fn create_private_dir(dir: &Path) -> Result<()> { + if dir.is_dir() { + return Ok(()); + } + #[cfg(unix)] + { + use std::os::unix::fs::DirBuilderExt; + fs::DirBuilder::new() + .recursive(true) + .mode(0o700) + .create(dir) + .with_context(|| format!("creating {}", dir.display()))?; + } + #[cfg(not(unix))] + fs::create_dir_all(dir).with_context(|| format!("creating {}", dir.display()))?; + Ok(()) +} + +/// The device token `bridgehook login` stores. +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct StoredToken { + pub token: String, + pub device_id: String, + pub user_id: String, + #[serde(default)] + pub label: String, + /// The relay the token belongs to. + pub relay: String, +} + +pub fn load_token(paths: &Paths) -> Result> { + let path = paths.token_file(); + match fs::read(&path) { + Ok(bytes) => Ok(Some( + serde_json::from_slice(&bytes) + .with_context(|| format!("reading {}", path.display()))?, + )), + Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None), + Err(e) => Err(e).with_context(|| format!("reading {}", path.display())), + } +} + +pub fn save_token(paths: &Paths, token: &StoredToken) -> Result<()> { + write_private(&paths.token_file(), &serde_json::to_vec_pretty(token)?) +} + +pub fn remove_token(paths: &Paths) -> Result { + match fs::remove_file(paths.token_file()) { + Ok(()) => Ok(true), + Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(false), + Err(e) => Err(e.into()), + } +} + +/// This install's id, used as the claim owner so exactly one executor +/// forwards each webhook. Created on first use. +pub fn executor_id(paths: &Paths) -> Result { + let path = paths.executor_file(); + if let Ok(existing) = fs::read_to_string(&path) { + let id = existing.trim().to_string(); + if !id.is_empty() { + return Ok(id); + } + } + let mut raw = [0u8; 16]; + rand_core::RngCore::fill_bytes(&mut rand_core::OsRng, &mut raw); + let id = format!("cli_{}", hex::encode(raw)); + write_private(&path, id.as_bytes())?; + Ok(id) +} + +/// Forward targets this install created or adopted, keyed by relay then +/// target ("3000", "http://api:8080"). +#[derive(Debug, Default, Serialize, Deserialize)] +pub struct ChannelMap(pub BTreeMap>); + +impl ChannelMap { + pub fn load(paths: &Paths) -> Result { + match fs::read(paths.channels_file()) { + Ok(bytes) => Ok(serde_json::from_slice(&bytes)?), + Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(Self::default()), + Err(e) => Err(e.into()), + } + } + pub fn save(&self, paths: &Paths) -> Result<()> { + write_private(&paths.channels_file(), &serde_json::to_vec_pretty(self)?) + } + pub fn get(&self, relay: &str, target: &str) -> Option<&str> { + self.0.get(relay)?.get(target).map(String::as_str) + } + pub fn set(&mut self, relay: &str, target: &str, channel_id: &str) { + self.0 + .entry(relay.to_string()) + .or_default() + .insert(target.to_string(), channel_id.to_string()); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn temp_dir() -> PathBuf { + let mut raw = [0u8; 8]; + rand_core::RngCore::fill_bytes(&mut rand_core::OsRng, &mut raw); + std::env::temp_dir().join(format!("bh-config-test-{}", hex::encode(raw))) + } + + #[test] + fn token_round_trips_and_is_private() { + let paths = Paths::at(temp_dir()); + assert_eq!(load_token(&paths).unwrap(), None); + let token = StoredToken { + token: "dvc_abc".into(), + device_id: "dev_1".into(), + user_id: "usr_1".into(), + label: "cli".into(), + relay: "https://relay.example".into(), + }; + save_token(&paths, &token).unwrap(); + assert_eq!(load_token(&paths).unwrap(), Some(token)); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + let mode = fs::metadata(paths.token_file()) + .unwrap() + .permissions() + .mode(); + assert_eq!(mode & 0o777, 0o600); + let dir_mode = fs::metadata(&paths.dir).unwrap().permissions().mode(); + assert_eq!(dir_mode & 0o777, 0o700); + } + assert!(remove_token(&paths).unwrap()); + assert!(!remove_token(&paths).unwrap()); + } + + #[cfg(unix)] + #[test] + fn an_existing_config_dir_keeps_its_mode() { + use std::os::unix::fs::PermissionsExt; + let dir = temp_dir(); + fs::create_dir_all(&dir).unwrap(); + fs::set_permissions(&dir, fs::Permissions::from_mode(0o755)).unwrap(); + let paths = Paths::at(&dir); + executor_id(&paths).unwrap(); + let mode = fs::metadata(&dir).unwrap().permissions().mode(); + assert_eq!( + mode & 0o777, + 0o755, + "a directory the user gave must not be chmodded" + ); + let file_mode = fs::metadata(paths.executor_file()) + .unwrap() + .permissions() + .mode(); + assert_eq!(file_mode & 0o777, 0o600); + } + + #[test] + fn executor_id_is_stable() { + let paths = Paths::at(temp_dir()); + let a = executor_id(&paths).unwrap(); + let b = executor_id(&paths).unwrap(); + assert_eq!(a, b); + assert!(a.starts_with("cli_") && a.len() == 36); + } + + #[test] + fn channel_map_is_per_relay() { + let paths = Paths::at(temp_dir()); + let mut map = ChannelMap::load(&paths).unwrap(); + map.set("https://a", "3000", "ch1"); + map.set("https://b", "3000", "ch2"); + map.save(&paths).unwrap(); + let back = ChannelMap::load(&paths).unwrap(); + assert_eq!(back.get("https://a", "3000"), Some("ch1")); + assert_eq!(back.get("https://b", "3000"), Some("ch2")); + assert_eq!(back.get("https://a", "4000"), None); + } +} diff --git a/crates/bridgehook-core/src/drain.rs b/crates/bridgehook-core/src/drain.rs new file mode 100644 index 0000000..1e3c999 --- /dev/null +++ b/crates/bridgehook-core/src/drain.rs @@ -0,0 +1,568 @@ +//! Ordered delivery of a channel's queue: a port of `QueueDrainer` +//! (`apps/web/src/lib/drain.ts`), which the extension and the dashboard tab +//! run, so every executor delivers the same way: +//! +//! - drain the queue (`?pending=1`) oldest first, page by page, so webhooks +//! that arrived while nothing ran go out in order; +//! - claim each event before forwarding and refresh the claim while the +//! target works, so exactly one executor forwards it; a claim held +//! elsewhere stops the pass there (order beats throughput); +//! - target down: stop at that event and retry later, never counting it +//! against the event; probe before claiming while it is down; +//! - target up but this event keeps failing: after [`MAX_ATTEMPTS`] record +//! status 0 and move on, so one payload cannot block the queue; a timeout +//! is recorded at once (the handler may still be running); +//! - an answer that reached us is reported until the relay takes it, never +//! by calling the target again. + +use crate::forward::ForwardOutcome; +use crate::relay::{ForwardResult, PendingPage, QueuedEvent}; +use std::collections::{BTreeMap, HashMap, HashSet}; +use std::future::Future; +use std::time::Duration; + +pub const MAX_ATTEMPTS: u32 = 3; +pub const CLAIM_HEARTBEAT: Duration = Duration::from_secs(20); +pub const REPORT_ATTEMPTS: u32 = 3; + +/// What the drainer needs from the relay and the target. Implemented by the +/// CLI over [`crate::relay::RelayClient`] and [`crate::forward::Target`], and +/// by fakes in tests. +pub trait DrainDeps: Send + Sync { + fn fetch_pending( + &self, + after: Option, + ) -> impl Future> + Send; + fn claim(&self, event_id: &str) -> impl Future> + Send; + fn probe(&self) -> impl Future> + Send; + fn forward(&self, event: &QueuedEvent) -> impl Future + Send; + fn report( + &self, + event: &QueuedEvent, + result: &ForwardResult, + ) -> impl Future> + Send; + fn sleep(&self, d: Duration) -> impl Future + Send { + tokio::time::sleep(d) + } +} + +/// How a pass ended. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum PassResult { + /// Nothing left for this executor. + Idle, + /// Stopped on a target or relay problem; try again soon. + Retry, + /// Another executor holds the oldest event; look again once its claim + /// could be stale. + Blocked, +} + +/// Something worth telling the user about. +#[derive(Debug, Clone, PartialEq)] +pub enum DrainEvent { + Delivered { + event: QueuedEvent, + result: ForwardResult, + }, + Skipped { + event: QueuedEvent, + message: String, + }, + TargetDown(String), + TargetUp, +} + +#[derive(Debug, Clone)] +struct Unreported { + result: ForwardResult, + skipped: Option, +} + +enum Step { + Next, + Retry, + Blocked, +} + +#[derive(Default)] +pub struct Drainer { + handled: HashSet, + attempts: HashMap, + unreported: HashMap, + target_down: bool, +} + +impl Drainer { + pub fn new() -> Self { + Self::default() + } + + pub fn target_down(&self) -> bool { + self.target_down + } + + /// One pass over the queue. `notify` receives user-facing events. + pub async fn pass( + &mut self, + deps: &D, + notify: &mut (dyn FnMut(DrainEvent) + Send), + ) -> anyhow::Result { + let mut after: Option = None; + let mut open = 0usize; + loop { + let page = deps.fetch_pending(after.clone()).await?; + for evt in page.events { + if !self.handled.contains(&evt.id) { + open += 1; + } + match self.step(deps, evt, notify).await? { + Step::Next => {} + Step::Retry => return Ok(PassResult::Retry), + Step::Blocked => return Ok(PassResult::Blocked), + } + } + match page.next_cursor { + Some(c) => after = Some(c), + None => break, + } + } + // Nothing was waiting: whatever the target's last state, no webhook + // is held up by it. + if open == 0 { + self.set_target_up(notify); + } + Ok(PassResult::Idle) + } + + async fn step( + &mut self, + deps: &D, + evt: QueuedEvent, + notify: &mut (dyn FnMut(DrainEvent) + Send), + ) -> anyhow::Result { + if self.handled.contains(&evt.id) { + return Ok(Step::Next); + } + + // Answered earlier but the relay never took the report: send that + // answer again, never the webhook. + if let Some(owed) = self.unreported.get(&evt.id).cloned() { + return Ok(if self.settle(deps, &evt, owed, notify).await { + Step::Next + } else { + Step::Retry + }); + } + + if self.target_down || self.attempts.contains_key(&evt.id) { + if let Err(message) = deps.probe().await { + self.set_target_down(message, notify); + return Ok(Step::Retry); + } + } + + // Another executor holds it: stop so nothing newer overtakes it. + if !deps.claim(&evt.id).await? { + return Ok(Step::Blocked); + } + + // Forward while keeping the claim fresh. + let mut lost = false; + let outcome = { + let fwd = deps.forward(&evt); + tokio::pin!(fwd); + let mut beat = tokio::time::interval_at( + tokio::time::Instant::now() + CLAIM_HEARTBEAT, + CLAIM_HEARTBEAT, + ); + loop { + tokio::select! { + o = &mut fwd => break o, + _ = beat.tick() => { + if let Ok(false) = deps.claim(&evt.id).await { + lost = true; + } + } + } + } + }; + + if lost { + // The claim went stale and another executor took the event; its + // answer is the one the relay keeps. + self.handled.insert(evt.id.clone()); + self.attempts.remove(&evt.id); + return Ok(Step::Next); + } + + let step = match outcome { + ForwardOutcome::Response(result) => { + self.attempts.remove(&evt.id); + self.set_target_up(notify); + let ok = self + .settle( + deps, + &evt, + Unreported { + result, + skipped: None, + }, + notify, + ) + .await; + if ok { + Step::Next + } else { + Step::Retry + } + } + ForwardOutcome::Down(message) => { + self.set_target_down(message, notify); + Step::Retry + } + ForwardOutcome::Timeout { + message, + latency_ms, + } => { + self.attempts.remove(&evt.id); + let ok = self + .settle(deps, &evt, terminal(message, latency_ms), notify) + .await; + if ok { + Step::Next + } else { + Step::Retry + } + } + ForwardOutcome::Failed { + message, + latency_ms, + } => { + let tries = self.attempts.get(&evt.id).copied().unwrap_or(0) + 1; + if tries < MAX_ATTEMPTS { + self.attempts.insert(evt.id.clone(), tries); + Step::Retry + } else { + self.attempts.remove(&evt.id); + let message = format!( + "Forwarding failed {MAX_ATTEMPTS} times while your local server was up. Last error: {message}" + ); + let ok = self + .settle(deps, &evt, terminal(message, latency_ms), notify) + .await; + if ok { + Step::Next + } else { + Step::Retry + } + } + } + }; + Ok(step) + } + + /// Report an answer; on success the event is done, otherwise it is owed. + async fn settle( + &mut self, + deps: &D, + evt: &QueuedEvent, + answer: Unreported, + notify: &mut (dyn FnMut(DrainEvent) + Send), + ) -> bool { + for i in 0..REPORT_ATTEMPTS { + if deps.report(evt, &answer.result).await.is_ok() { + self.unreported.remove(&evt.id); + self.handled.insert(evt.id.clone()); + match answer.skipped { + Some(message) => notify(DrainEvent::Skipped { + event: evt.clone(), + message, + }), + None => notify(DrainEvent::Delivered { + event: evt.clone(), + result: answer.result, + }), + } + return true; + } + if i < REPORT_ATTEMPTS - 1 { + deps.sleep(Duration::from_millis(500 * 3u64.pow(i))).await; + } + } + self.unreported.insert(evt.id.clone(), answer); + false + } + + fn set_target_down(&mut self, message: String, notify: &mut (dyn FnMut(DrainEvent) + Send)) { + if !self.target_down { + self.target_down = true; + notify(DrainEvent::TargetDown(message)); + } + } + + fn set_target_up(&mut self, notify: &mut (dyn FnMut(DrainEvent) + Send)) { + if self.target_down { + self.target_down = false; + notify(DrainEvent::TargetUp); + } + } +} + +fn terminal(message: String, latency_ms: u64) -> Unreported { + Unreported { + result: ForwardResult { + status: 0, + headers: BTreeMap::new(), + body: format!("BridgeHook: {message}"), + latency_ms, + }, + skipped: Some(message), + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::sync::Mutex; + + fn ev(id: &str) -> QueuedEvent { + QueuedEvent { + id: id.into(), + method: "POST".into(), + path: "/webhook".into(), + request_headers: None, + request_body: Some(format!("{{\"id\":\"{id}\"}}")), + channel_id: Some("ch".into()), + } + } + + fn ok(status: u16) -> ForwardOutcome { + ForwardOutcome::Response(ForwardResult { + status, + headers: BTreeMap::new(), + body: "ok".into(), + latency_ms: 3, + }) + } + + /// A scripted relay and target. The queue holds events not yet reported. + #[derive(Default)] + struct Fake { + queue: Mutex>, + page_size: usize, + outcomes: Mutex>>, + claims_refused: Mutex>, + claim_refresh_fails: Mutex, + report_failures: Mutex, + probe_down: Mutex, + forwarded: Mutex>, + reported: Mutex>, + /// Delay the forward of one event (id, duration). + forward_delay: Mutex>, + } + + impl Fake { + fn with(ids: &[&str]) -> Self { + Self { + queue: Mutex::new(ids.iter().map(|i| ev(i)).collect()), + page_size: 100, + ..Default::default() + } + } + fn script(&self, id: &str, outcomes: Vec) { + self.outcomes.lock().unwrap().insert(id.into(), outcomes); + } + } + + impl DrainDeps for Fake { + async fn fetch_pending(&self, after: Option) -> anyhow::Result { + // Keyset paging like the relay's (receivedAt, id) cursor: events + // settled mid-pass leave the queue without shifting later pages. + // Test ids sort in queue order. + let q: Vec = self + .queue + .lock() + .unwrap() + .iter() + .filter(|e| after.as_ref().is_none_or(|a| e.id.as_str() > a.as_str())) + .cloned() + .collect(); + let page: Vec = q.iter().take(self.page_size).cloned().collect(); + let next = if q.len() > page.len() { + page.last().map(|e| e.id.clone()) + } else { + None + }; + Ok(PendingPage { + events: page, + next_cursor: next, + }) + } + async fn claim(&self, event_id: &str) -> anyhow::Result { + if self + .forwarded + .lock() + .unwrap() + .contains(&event_id.to_string()) + && *self.claim_refresh_fails.lock().unwrap() + { + return Ok(false); + } + Ok(!self.claims_refused.lock().unwrap().contains(event_id)) + } + async fn probe(&self) -> Result<(), String> { + if *self.probe_down.lock().unwrap() { + Err("down".into()) + } else { + Ok(()) + } + } + async fn forward(&self, event: &QueuedEvent) -> ForwardOutcome { + self.forwarded.lock().unwrap().push(event.id.clone()); + let delay = self.forward_delay.lock().unwrap().clone(); + if let Some((id, d)) = delay { + if id == event.id { + tokio::time::sleep(d).await; + } + } + let mut o = self.outcomes.lock().unwrap(); + match o.get_mut(&event.id) { + Some(list) if !list.is_empty() => list.remove(0), + _ => ok(200), + } + } + async fn report(&self, event: &QueuedEvent, result: &ForwardResult) -> anyhow::Result<()> { + { + let mut f = self.report_failures.lock().unwrap(); + if *f > 0 { + *f -= 1; + anyhow::bail!("relay down"); + } + } + self.reported + .lock() + .unwrap() + .push((event.id.clone(), result.status)); + self.queue.lock().unwrap().retain(|e| e.id != event.id); + Ok(()) + } + async fn sleep(&self, _d: Duration) {} + } + + async fn run(d: &mut Drainer, fake: &Fake) -> (PassResult, Vec) { + let mut seen = Vec::new(); + let r = d.pass(fake, &mut |e| seen.push(e)).await.unwrap(); + (r, seen) + } + + #[tokio::test] + async fn delivers_the_queue_in_order_across_pages() { + let mut fake = Fake::with(&["a", "b", "c", "d", "e"]); + fake.page_size = 2; + let mut d = Drainer::new(); + let (r, _) = run(&mut d, &fake).await; + assert_eq!(r, PassResult::Idle); + assert_eq!( + *fake.forwarded.lock().unwrap(), + vec!["a", "b", "c", "d", "e"] + ); + assert_eq!(fake.reported.lock().unwrap().len(), 5); + } + + #[tokio::test] + async fn target_down_stops_without_counting_and_resumes_in_order() { + let fake = Fake::with(&["a", "b"]); + fake.script("a", vec![ForwardOutcome::Down("refused".into())]); + let mut d = Drainer::new(); + let (r, seen) = run(&mut d, &fake).await; + assert_eq!(r, PassResult::Retry); + assert_eq!(seen, vec![DrainEvent::TargetDown("refused".into())]); + assert_eq!(*fake.forwarded.lock().unwrap(), vec!["a"]); + // Still down: the probe stops the pass before claiming anything. + *fake.probe_down.lock().unwrap() = true; + assert_eq!(run(&mut d, &fake).await.0, PassResult::Retry); + assert_eq!(fake.forwarded.lock().unwrap().len(), 1); + // Back up: both go out, oldest first. + *fake.probe_down.lock().unwrap() = false; + let (r, seen) = run(&mut d, &fake).await; + assert_eq!(r, PassResult::Idle); + assert_eq!(*fake.forwarded.lock().unwrap(), vec!["a", "a", "b"]); + assert!(seen.contains(&DrainEvent::TargetUp)); + } + + #[tokio::test] + async fn a_failing_event_is_recorded_after_three_tries_and_the_queue_moves_on() { + let fake = Fake::with(&["bad", "next"]); + let fail = || ForwardOutcome::Failed { + message: "reset".into(), + latency_ms: 1, + }; + fake.script("bad", vec![fail(), fail(), fail()]); + let mut d = Drainer::new(); + assert_eq!(run(&mut d, &fake).await.0, PassResult::Retry); + assert_eq!(run(&mut d, &fake).await.0, PassResult::Retry); + let (r, seen) = run(&mut d, &fake).await; + assert_eq!(r, PassResult::Idle); + assert_eq!( + *fake.reported.lock().unwrap(), + vec![("bad".to_string(), 0), ("next".to_string(), 200)] + ); + assert!( + matches!(&seen[0], DrainEvent::Skipped { message, .. } if message.contains("failed 3 times")) + ); + } + + #[tokio::test] + async fn a_timeout_is_recorded_once_and_never_sent_again() { + let fake = Fake::with(&["slow", "next"]); + fake.script( + "slow", + vec![ForwardOutcome::Timeout { + message: "300 s".into(), + latency_ms: 300_000, + }], + ); + let mut d = Drainer::new(); + assert_eq!(run(&mut d, &fake).await.0, PassResult::Idle); + assert_eq!(*fake.forwarded.lock().unwrap(), vec!["slow", "next"]); + assert_eq!(fake.reported.lock().unwrap()[0], ("slow".to_string(), 0)); + } + + #[tokio::test] + async fn a_claim_held_elsewhere_blocks_newer_events() { + let fake = Fake::with(&["held", "newer"]); + fake.claims_refused.lock().unwrap().insert("held".into()); + let mut d = Drainer::new(); + assert_eq!(run(&mut d, &fake).await.0, PassResult::Blocked); + assert!(fake.forwarded.lock().unwrap().is_empty()); + } + + #[tokio::test] + async fn an_unstored_answer_is_reported_again_without_forwarding_again() { + let fake = Fake::with(&["a"]); + *fake.report_failures.lock().unwrap() = REPORT_ATTEMPTS; + let mut d = Drainer::new(); + assert_eq!(run(&mut d, &fake).await.0, PassResult::Retry); + assert_eq!(fake.forwarded.lock().unwrap().len(), 1); + let (r, seen) = run(&mut d, &fake).await; + assert_eq!(r, PassResult::Idle); + assert_eq!(fake.forwarded.lock().unwrap().len(), 1); + assert!(matches!(&seen[0], DrainEvent::Delivered { .. })); + } + + #[tokio::test(start_paused = true)] + async fn a_claim_lost_during_a_long_forward_hands_the_event_over() { + let fake = Fake::with(&["long", "next"]); + *fake.forward_delay.lock().unwrap() = Some(("long".into(), Duration::from_secs(45))); + *fake.claim_refresh_fails.lock().unwrap() = true; + let mut d = Drainer::new(); + let (r, _) = run(&mut d, &fake).await; + assert_eq!(r, PassResult::Idle); + // "long" was handed over (not reported by us); "next" was delivered. + assert_eq!( + *fake.reported.lock().unwrap(), + vec![("next".to_string(), 200)] + ); + } +} diff --git a/crates/bridgehook-core/src/forward.rs b/crates/bridgehook-core/src/forward.rs new file mode 100644 index 0000000..c4730c1 --- /dev/null +++ b/crates/bridgehook-core/src/forward.rs @@ -0,0 +1,272 @@ +//! Sending one queued webhook to the local target and reading its answer. +//! +//! The target is `http://localhost:` or any URL (`http://api:3000` in +//! a container). The relay's own headers (Cloudflare, forwarding, hop-by-hop) +//! are dropped; everything the sender set is passed through. + +use crate::relay::{ForwardResult, QueuedEvent}; +use reqwest::{Client, Method}; +use std::collections::BTreeMap; +use std::time::{Duration, Instant}; +use url::Url; + +/// How long a local handler may take before the webhook is recorded as +/// timed out (it is not sent again: the handler may still be running). +pub const FORWARD_TIMEOUT: Duration = Duration::from_secs(5 * 60); + +/// What happened when the CLI tried the local target. +#[derive(Debug, Clone, PartialEq)] +pub enum ForwardOutcome { + Response(ForwardResult), + /// Nothing listening: wait and retry, never counted against the event. + Down(String), + /// Reached the target but the request failed (reset, bad response). + Failed { + message: String, + latency_ms: u64, + }, + /// The handler did not answer within [`FORWARD_TIMEOUT`]. + Timeout { + message: String, + latency_ms: u64, + }, +} + +const SKIP_HEADERS: &[&str] = &[ + "host", + "cf-ray", + "cf-connecting-ip", + "cf-ipcountry", + "cf-visitor", + "x-real-ip", + "x-forwarded-proto", + "x-forwarded-for", + "connection", + "accept-encoding", + "transfer-encoding", + "content-length", +]; + +#[derive(Clone, Debug)] +pub struct Target { + base: Url, + http: Client, +} + +impl Target { + /// `3000` → `http://localhost:3000`; a URL is used as given. + pub fn parse(spec: &str) -> anyhow::Result { + let base = if let Ok(port) = spec.parse::() { + Url::parse(&format!("http://localhost:{port}"))? + } else { + let url = Url::parse(spec).map_err(|_| { + anyhow::anyhow!( + "`{spec}` is neither a port nor a URL (e.g. 3000 or http://api:3000)" + ) + })?; + anyhow::ensure!( + matches!(url.scheme(), "http" | "https"), + "target must be http or https: {spec}" + ); + url + }; + let http = Client::builder() + .connect_timeout(Duration::from_secs(5)) + .redirect(reqwest::redirect::Policy::none()) + .build()?; + Ok(Self { base, http }) + } + + /// The port the relay records for this target's channel. + pub fn port(&self) -> u16 { + self.base.port_or_known_default().unwrap_or(80) + } + + pub fn display(&self) -> String { + self.base.as_str().trim_end_matches('/').to_string() + } + + /// The URL a webhook for `event_path` is sent to. + pub fn url_for(&self, event_path: &str) -> String { + let base = self.base.as_str().trim_end_matches('/'); + let path = if event_path.is_empty() { + "/" + } else { + event_path + }; + if path.starts_with('/') { + format!("{base}{path}") + } else { + format!("{base}/{path}") + } + } + + /// Is anything listening? Any HTTP answer counts; a refused or failed + /// connection does not. + pub async fn probe(&self) -> Result<(), String> { + match self + .http + .head(self.base.as_str()) + .timeout(Duration::from_secs(5)) + .send() + .await + { + Ok(_) => Ok(()), + Err(e) if e.is_connect() || e.is_timeout() => Err(self.down_message()), + Err(_) => Ok(()), + } + } + + fn down_message(&self) -> String { + format!("Connection refused: is {} running?", self.display()) + } + + pub async fn forward(&self, event: &QueuedEvent) -> ForwardOutcome { + let start = Instant::now(); + let path = event_path(event); + let method = Method::from_bytes(event.method.as_bytes()).unwrap_or(Method::POST); + let mut req = self + .http + .request(method, self.url_for(&path)) + .timeout(FORWARD_TIMEOUT); + for (k, v) in request_headers(event) { + req = req.header(k, v); + } + if let Some(body) = &event.request_body { + req = req.body(body.clone()); + } + let elapsed = || start.elapsed().as_millis() as u64; + match req.send().await { + Ok(res) => { + let status = res.status().as_u16(); + let mut headers = BTreeMap::new(); + for (k, v) in res.headers() { + if let Ok(v) = v.to_str() { + headers.insert(k.as_str().to_string(), v.to_string()); + } + } + match res.text().await { + Ok(body) => ForwardOutcome::Response(ForwardResult { + status, + headers, + body, + latency_ms: elapsed(), + }), + Err(e) if e.is_timeout() => ForwardOutcome::Timeout { + message: self.timeout_message(), + latency_ms: elapsed(), + }, + Err(e) => ForwardOutcome::Failed { + message: e.to_string(), + latency_ms: elapsed(), + }, + } + } + Err(e) if e.is_connect() => ForwardOutcome::Down(self.down_message()), + Err(e) if e.is_timeout() => ForwardOutcome::Timeout { + message: self.timeout_message(), + latency_ms: elapsed(), + }, + Err(e) => ForwardOutcome::Failed { + message: e.to_string(), + latency_ms: elapsed(), + }, + } + } + + fn timeout_message(&self) -> String { + format!( + "{} did not respond within {} seconds", + self.display(), + FORWARD_TIMEOUT.as_secs() + ) + } +} + +/// The path the target receives. Rows written before the relay stored the +/// forward path still carry `/hook/`; strip exactly that. +pub fn event_path(event: &QueuedEvent) -> String { + let raw = event.path.as_str(); + if let Some(ch) = &event.channel_id { + let legacy = format!("/hook/{ch}"); + if raw == legacy { + return "/".into(); + } + if let Some(rest) = raw.strip_prefix(&format!("{legacy}/")) { + return format!("/{rest}"); + } + } + if raw.is_empty() { + "/".into() + } else { + raw.to_string() + } +} + +/// The sender's headers, minus the relay's and hop-by-hop ones. +pub fn request_headers(event: &QueuedEvent) -> Vec<(String, String)> { + let parsed: BTreeMap = event + .request_headers + .as_deref() + .and_then(|h| serde_json::from_str(h).ok()) + .unwrap_or_default(); + parsed + .into_iter() + .filter(|(k, _)| !SKIP_HEADERS.contains(&k.to_ascii_lowercase().as_str())) + .filter_map(|(k, v)| v.as_str().map(|s| (k, s.to_string()))) + .collect() +} + +#[cfg(test)] +mod tests { + use super::*; + + fn ev(path: &str, channel: Option<&str>) -> QueuedEvent { + QueuedEvent { + id: "e1".into(), + method: "POST".into(), + path: path.into(), + request_headers: Some( + r#"{"content-type":"application/json","stripe-signature":"t=1,v1=abc","cf-connecting-ip":"1.2.3.4","host":"x.bridgehook.dev","content-length":"2"}"#.into(), + ), + request_body: Some("{}".into()), + channel_id: channel.map(str::to_string), + } + } + + #[test] + fn targets_from_port_or_url() { + let t = Target::parse("3000").unwrap(); + assert_eq!(t.url_for("/webhook"), "http://localhost:3000/webhook"); + assert_eq!(t.port(), 3000); + let u = Target::parse("http://api:8080/v1").unwrap(); + assert_eq!(u.url_for("/stripe"), "http://api:8080/v1/stripe"); + assert_eq!(u.port(), 8080); + assert!(Target::parse("ftp://x").is_err()); + assert!(Target::parse("not a target").is_err()); + } + + #[test] + fn strips_only_the_legacy_channel_prefix() { + assert_eq!(event_path(&ev("/hook/abc/stripe", Some("abc"))), "/stripe"); + assert_eq!(event_path(&ev("/hook/abc", Some("abc"))), "/"); + assert_eq!( + event_path(&ev("/hook/other/x", Some("abc"))), + "/hook/other/x" + ); + assert_eq!(event_path(&ev("", None)), "/"); + } + + #[test] + fn drops_relay_and_hop_headers() { + let mut h = request_headers(&ev("/x", None)); + h.sort(); + assert_eq!( + h, + vec![ + ("content-type".to_string(), "application/json".to_string()), + ("stripe-signature".to_string(), "t=1,v1=abc".to_string()), + ] + ); + } +} diff --git a/crates/bridgehook-core/src/keys.rs b/crates/bridgehook-core/src/keys.rs new file mode 100644 index 0000000..44e923f --- /dev/null +++ b/crates/bridgehook-core/src/keys.rs @@ -0,0 +1,150 @@ +//! Per-channel ECDSA P-256 keys and request signing. +//! +//! The relay verifies signed executor requests (claim, response, the pending +//! queue, signed DELETE) with WebCrypto ECDSA P-256 / SHA-256 over: +//! +//! ```text +//! METHOD \n PATHNAME \n TIMESTAMP_MS \n hex(sha256(body)) +//! ``` +//! +//! sent as `X-BH-Timestamp` and `X-BH-Signature` (hex of the 64-byte r‖s +//! signature). The public key is the uncompressed SEC1 point, hex (130 +//! chars), the same encoding as the extension and the desktop app. + +use crate::config::{write_private, Paths}; +use anyhow::{Context, Result}; +use p256::ecdsa::{signature::Signer, Signature, SigningKey, VerifyingKey}; +use p256::pkcs8::{DecodePrivateKey, EncodePrivateKey}; +use p256::SecretKey; +use sha2::{Digest, Sha256}; +use std::time::{SystemTime, UNIX_EPOCH}; + +#[derive(Clone)] +pub struct ChannelKey { + signing: SigningKey, +} + +impl ChannelKey { + pub fn generate() -> Self { + Self { + signing: SigningKey::random(&mut rand_core::OsRng), + } + } + + pub fn from_pkcs8(der: &[u8]) -> Result { + let secret = SecretKey::from_pkcs8_der(der).context("reading channel key")?; + Ok(Self { + signing: SigningKey::from(&secret), + }) + } + + pub fn to_pkcs8(&self) -> Result> { + let secret = SecretKey::from(self.signing.as_nonzero_scalar()); + Ok(secret + .to_pkcs8_der() + .context("encoding channel key")? + .as_bytes() + .to_vec()) + } + + /// Uncompressed SEC1 public key, hex (130 chars), as the relay expects. + pub fn public_key_hex(&self) -> String { + let verifying = VerifyingKey::from(&self.signing); + hex::encode(verifying.to_encoded_point(false).as_bytes()) + } + + /// Signature headers for one request: `(X-BH-Timestamp, X-BH-Signature)`. + pub fn sign_request(&self, method: &str, pathname: &str, body: &str) -> (String, String) { + self.sign_request_at(method, pathname, body, now_ms()) + } + + pub fn sign_request_at( + &self, + method: &str, + pathname: &str, + body: &str, + timestamp_ms: u128, + ) -> (String, String) { + let canon = canonical(method, pathname, timestamp_ms, body); + let signature: Signature = self.signing.sign(canon.as_bytes()); + (timestamp_ms.to_string(), hex::encode(signature.to_bytes())) + } + + pub fn save(&self, paths: &Paths, channel_id: &str) -> Result<()> { + write_private(&paths.key_file(channel_id), &self.to_pkcs8()?) + } + + pub fn load(paths: &Paths, channel_id: &str) -> Result> { + match std::fs::read(paths.key_file(channel_id)) { + Ok(der) => Ok(Some(Self::from_pkcs8(&der)?)), + Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None), + Err(e) => Err(e.into()), + } + } +} + +pub fn canonical(method: &str, pathname: &str, timestamp_ms: u128, body: &str) -> String { + let body_hash = hex::encode(Sha256::digest(body.as_bytes())); + format!( + "{}\n{}\n{}\n{}", + method.to_uppercase(), + pathname, + timestamp_ms, + body_hash + ) +} + +fn now_ms() -> u128 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .map(|d| d.as_millis()) + .unwrap_or(0) +} + +#[cfg(test)] +mod tests { + use super::*; + use p256::ecdsa::signature::Verifier; + use p256::EncodedPoint; + + #[test] + fn public_key_is_uncompressed_sec1_hex() { + let key = ChannelKey::generate(); + let hex_key = key.public_key_hex(); + assert_eq!(hex_key.len(), 130); + assert!(hex_key.starts_with("04")); + } + + #[test] + fn canonical_matches_the_relay_format() { + // sha256("") = e3b0c442…b855, the body hash the relay computes for GET. + assert_eq!( + canonical("get", "/api/channels/abc/events", 1700000000000, ""), + "GET\n/api/channels/abc/events\n1700000000000\ne3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" + ); + } + + #[test] + fn signature_verifies_against_the_published_key() { + let key = ChannelKey::generate(); + let (ts, sig_hex) = + key.sign_request_at("POST", "/hook/abc/claim", r#"{"eventId":"e1"}"#, 42); + assert_eq!(ts, "42"); + let sig = Signature::from_slice(&hex::decode(&sig_hex).unwrap()).unwrap(); + assert_eq!(sig_hex.len(), 128); + let point = EncodedPoint::from_bytes(hex::decode(key.public_key_hex()).unwrap()).unwrap(); + let verifying = VerifyingKey::from_encoded_point(&point).unwrap(); + let canon = canonical("POST", "/hook/abc/claim", 42, r#"{"eventId":"e1"}"#); + assert!(verifying.verify(canon.as_bytes(), &sig).is_ok()); + // A different body does not verify. + let other = canonical("POST", "/hook/abc/claim", 42, r#"{"eventId":"e2"}"#); + assert!(verifying.verify(other.as_bytes(), &sig).is_err()); + } + + #[test] + fn pkcs8_round_trip_keeps_the_key() { + let key = ChannelKey::generate(); + let back = ChannelKey::from_pkcs8(&key.to_pkcs8().unwrap()).unwrap(); + assert_eq!(key.public_key_hex(), back.public_key_hex()); + } +} diff --git a/crates/bridgehook-core/src/lib.rs b/crates/bridgehook-core/src/lib.rs new file mode 100644 index 0000000..8efabe1 --- /dev/null +++ b/crates/bridgehook-core/src/lib.rs @@ -0,0 +1,22 @@ +//! BridgeHook protocol client, shared by the CLI (and later the desktop app). +//! +//! - [`config`]: where tokens, channel keys and the executor id live. +//! - [`keys`]: per-channel ECDSA P-256 keys and request signing. +//! - [`relay`]: the typed, signed relay API. +//! - [`auth`]: device-code pairing (`bridgehook login`). +//! - [`drain`]: ordered delivery of a channel's queue to a local target. +//! - [`forward`]: sending one webhook to the local target. +//! - [`stream`]: the `/api/me/stream` wake-up signal. +//! +//! No terminal or UI code lives here. + +pub mod auth; +pub mod config; +pub mod drain; +pub mod forward; +pub mod keys; +pub mod relay; +pub mod stream; + +/// The hosted relay. Self-hosters pass their own with `--relay`. +pub const DEFAULT_RELAY_URL: &str = "https://relay.bridgehook.dev"; diff --git a/crates/bridgehook-core/src/relay.rs b/crates/bridgehook-core/src/relay.rs new file mode 100644 index 0000000..381bd5c --- /dev/null +++ b/crates/bridgehook-core/src/relay.rs @@ -0,0 +1,566 @@ +//! The relay API, typed. Account calls use the device token +//! (`Authorization: Bearer dvc_…`); executor calls on a channel are signed +//! with the channel's key ([`ChannelKey`]). + +use crate::keys::ChannelKey; +use anyhow::Result; +use reqwest::{Client, Method, RequestBuilder, Response, StatusCode}; +use serde::{Deserialize, Serialize}; +use std::collections::BTreeMap; +use std::time::Duration; + +/// A relay answer that was not a success, with its status and message. +#[derive(Debug, thiserror::Error)] +pub enum RelayError { + #[error("{message}")] + Quota { message: String }, + #[error("not signed in to this relay (HTTP 401); run `bridgehook login`")] + Unauthorized, + /// The channel was deleted or expired (404 "Channel not found", 410). + #[error("the channel was deleted or has expired")] + ChannelGone, + #[error("relay answered {status}: {message}")] + Status { status: u16, message: String }, + #[error("could not reach the relay: {0}")] + Network(#[from] reqwest::Error), +} + +#[derive(Debug, Clone, Deserialize)] +pub struct Me { + pub user: MeUser, + pub plan: String, + #[serde(rename = "eventsPerDay")] + pub events_per_day: Option, + #[serde(rename = "eventsToday", default)] + pub events_today: u64, +} + +#[derive(Debug, Clone, Deserialize)] +pub struct MeUser { + pub id: String, + pub email: String, +} + +#[derive(Debug, Clone, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ChannelInfo { + pub id: String, + pub port: u16, + pub webhook_url: String, + #[serde(default)] + pub allowed_paths: Vec, + /// The device that created the channel, if any. + #[serde(default)] + pub device: Option, +} + +#[derive(Debug, Clone, Deserialize)] +pub struct ChannelDevice { + pub id: String, + #[serde(default)] + pub label: Option, + #[serde(default)] + pub kind: Option, +} + +#[derive(Debug, Clone, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct CreatedChannel { + pub channel_id: String, + pub port: u16, + pub webhook_url: String, +} + +/// One webhook waiting in a channel's delivery queue. +#[derive(Debug, Clone, Deserialize, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct QueuedEvent { + pub id: String, + #[serde(default = "default_method")] + pub method: String, + #[serde(default)] + pub path: String, + /// JSON object of the request headers, as stored by the relay. + #[serde(default)] + pub request_headers: Option, + #[serde(default)] + pub request_body: Option, + #[serde(default)] + pub channel_id: Option, +} + +fn default_method() -> String { + "POST".into() +} + +#[derive(Debug, Clone, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct PendingPage { + #[serde(default)] + pub events: Vec, + #[serde(default)] + pub next_cursor: Option, +} + +/// The local server's answer, as reported back to the relay. +#[derive(Debug, Clone, Serialize, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct ForwardResult { + pub status: u16, + pub headers: BTreeMap, + pub body: String, + pub latency_ms: u64, +} + +#[derive(Debug, Clone, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct DeviceStart { + pub device_code: String, + pub verification_url: String, + #[serde(default = "default_poll")] + pub poll_interval: u64, + #[serde(default = "default_expires")] + pub expires_in: u64, +} +fn default_poll() -> u64 { + 5 +} +fn default_expires() -> u64 { + 900 +} + +#[derive(Debug, Clone, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct DeviceMinted { + pub token: String, + pub device_id: String, + pub user_id: String, + #[serde(default)] + pub label: String, +} + +/// What one exchange poll answered. +#[derive(Debug)] +pub enum ExchangePoll { + Minted(DeviceMinted), + Pending, + Expired, + /// 429: wait this long, then poll again. + RetryAfter(Duration), + /// 5xx or a network error: back off and poll again. + Transient(String), + /// Any other 4xx: stop with the relay's message. + Failed(u16, String), +} + +pub const MAX_STORED_BODY_BYTES: usize = 1_048_576; +const MAX_STORED_HEADER_BYTES: usize = 16 * 1024; + +#[derive(Clone)] +pub struct RelayClient { + base: String, + http: Client, + token: Option, +} + +impl RelayClient { + pub fn new(base: &str, token: Option) -> Result { + let http = Client::builder() + .user_agent(concat!("bridgehook-cli/", env!("CARGO_PKG_VERSION"))) + .connect_timeout(Duration::from_secs(15)) + .build()?; + Ok(Self { + base: base.trim_end_matches('/').to_string(), + http, + token, + }) + } + + pub fn base(&self) -> &str { + &self.base + } + + pub fn token(&self) -> Option<&str> { + self.token.as_deref() + } + + pub fn http(&self) -> &Client { + &self.http + } + + fn authed(&self, method: Method, path: &str) -> RequestBuilder { + let mut req = self.http.request(method, format!("{}{}", self.base, path)); + if let Some(t) = &self.token { + req = req.bearer_auth(t); + } + req.timeout(Duration::from_secs(30)) + } + + fn signed( + &self, + key: &ChannelKey, + method: Method, + path_and_query: &str, + body: Option, + ) -> RequestBuilder { + let pathname = path_and_query.split('?').next().unwrap_or(path_and_query); + let body_str = body.clone().unwrap_or_default(); + let (ts, sig) = key.sign_request(method.as_str(), pathname, &body_str); + let mut req = self + .http + .request(method, format!("{}{}", self.base, path_and_query)) + .header("X-BH-Timestamp", ts) + .header("X-BH-Signature", sig) + .timeout(Duration::from_secs(30)); + if let Some(b) = body { + req = req.header("Content-Type", "application/json").body(b); + } + req + } + + pub async fn me(&self) -> Result { + json_or_error(self.authed(Method::GET, "/api/me").send().await?).await + } + + pub async fn list_channels(&self) -> Result, RelayError> { + #[derive(Deserialize)] + struct List { + channels: Vec, + } + let list: List = + json_or_error(self.authed(Method::GET, "/api/me/channels").send().await?).await?; + Ok(list.channels) + } + + pub async fn create_channel( + &self, + public_key: &str, + port: u16, + allowed_paths: &[String], + ) -> Result { + let body = serde_json::json!({ "publicKey": public_key, "port": port, "allowedPaths": allowed_paths }); + json_or_error( + self.authed(Method::POST, "/api/channels") + .json(&body) + .send() + .await?, + ) + .await + } + + /// Puts a new public key on a channel this account owns (adopting a + /// channel whose private key this machine does not have). + pub async fn rotate_key(&self, channel_id: &str, public_key: &str) -> Result<(), RelayError> { + let body = serde_json::json!({ "publicKey": public_key }); + let res = self + .authed( + Method::POST, + &format!("/api/me/channels/{channel_id}/rotate-key"), + ) + .json(&body) + .send() + .await?; + ok_or_error(res).await + } + + /// Restricts which paths the channel accepts (`[]` accepts any). A device + /// token may change this field only. + pub async fn set_allowed_paths( + &self, + channel_id: &str, + allowed_paths: &[String], + ) -> Result<(), RelayError> { + let body = serde_json::json!({ "allowedPaths": allowed_paths }); + let res = self + .authed(Method::PATCH, &format!("/api/me/channels/{channel_id}")) + .json(&body) + .send() + .await?; + ok_or_error(res).await + } + + /// The public URL of a channel, from the channel's own endpoint (answers + /// without sign-in, so it works on a self-hosted relay too). `None` when + /// the channel is gone or expired. + pub async fn channel_webhook_url( + &self, + channel_id: &str, + ) -> Result, RelayError> { + #[derive(Deserialize)] + #[serde(rename_all = "camelCase")] + struct Info { + webhook_url: String, + } + let res = self + .http + .get(format!("{}/hook/{channel_id}", self.base)) + .header("Accept", "application/json") + .timeout(Duration::from_secs(30)) + .send() + .await?; + match res.status().as_u16() { + 404 | 410 => Ok(None), + _ => Ok(Some(json_or_error::(res).await?.webhook_url)), + } + } + + /// Revokes a device. With a device token, only that device's own id is + /// accepted, which is how `bridgehook logout` ends its token. + pub async fn revoke_device(&self, device_id: &str) -> Result<(), RelayError> { + ok_or_error( + self.authed(Method::DELETE, &format!("/api/me/devices/{device_id}")) + .send() + .await?, + ) + .await + } + + pub async fn device_start( + &self, + kind: &str, + label_hint: &str, + ) -> Result { + let body = serde_json::json!({ "kind": kind, "labelHint": label_hint }); + let res = self + .http + .post(format!("{}/auth/device/start", self.base)) + .json(&body) + .timeout(Duration::from_secs(30)) + .send() + .await?; + json_or_error(res).await + } + + pub async fn device_exchange(&self, code: &str) -> ExchangePoll { + let res = self + .http + .post(format!("{}/auth/device/exchange", self.base)) + .json(&serde_json::json!({ "code": code })) + .timeout(Duration::from_secs(30)) + .send() + .await; + let res = match res { + Ok(r) => r, + Err(e) => return ExchangePoll::Transient(e.to_string()), + }; + let status = res.status(); + match status.as_u16() { + 200 => match res.json::().await { + Ok(m) => ExchangePoll::Minted(m), + Err(e) => ExchangePoll::Failed(200, format!("unexpected answer: {e}")), + }, + 202 => ExchangePoll::Pending, + 410 => ExchangePoll::Expired, + 429 => { + let secs = res + .headers() + .get("retry-after") + .and_then(|v| v.to_str().ok()) + .and_then(|v| v.parse::().ok()) + .unwrap_or(60); + ExchangePoll::RetryAfter(Duration::from_secs(secs.clamp(1, 60))) + } + s if s >= 500 => ExchangePoll::Transient(format!("relay answered {s}")), + s => ExchangePoll::Failed(s, error_text(res).await), + } + } + + pub async fn fetch_pending( + &self, + channel_id: &str, + key: &ChannelKey, + after: Option<&str>, + ) -> Result { + let mut path = format!("/api/channels/{channel_id}/events?pending=1&limit=100"); + if let Some(a) = after { + path.push_str("&after="); + path.push_str(&url::form_urlencoded::byte_serialize(a.as_bytes()).collect::()); + } + json_or_error(self.signed(key, Method::GET, &path, None).send().await?).await + } + + /// True when this executor holds the claim (new, or one it already held). + pub async fn claim( + &self, + channel_id: &str, + key: &ChannelKey, + event_id: &str, + client_id: &str, + ) -> Result { + let body = serde_json::json!({ "eventId": event_id, "clientId": client_id }).to_string(); + let res = self + .signed( + key, + Method::POST, + &format!("/hook/{channel_id}/claim"), + Some(body), + ) + .send() + .await?; + match res.status() { + s if s.is_success() => Ok(true), + StatusCode::CONFLICT => { + let v: serde_json::Value = res.json().await.unwrap_or_default(); + Ok(v.get("claimerId").and_then(|c| c.as_str()) == Some(client_id)) + } + // 404 is the channel or the event gone: an error, so the pass + // stops and the next read of the queue no longer has it. + _ => Err(status_error(res).await), + } + } + + /// Stores the local server's answer. Retries once with a trimmed answer + /// when the relay refuses the size, so the event is not delivered again. + pub async fn report( + &self, + channel_id: &str, + key: &ChannelKey, + event_id: &str, + result: &ForwardResult, + device_id: Option<&str>, + ) -> Result<(), RelayError> { + let post = |r: &ForwardResult| { + let mut body = serde_json::json!({ + "eventId": event_id, + "status": r.status, + "headers": r.headers, + "body": r.body, + "latencyMs": r.latency_ms, + }); + if let Some(d) = device_id { + body["deviceId"] = d.into(); + } + self.signed( + key, + Method::POST, + &format!("/hook/{channel_id}/response"), + Some(body.to_string()), + ) + .send() + }; + let mut res = post(result).await?; + if matches!(res.status().as_u16(), 413 | 431) { + res = post(&fit_response(result)).await?; + } + ok_or_error(res).await + } +} + +/// Trims an answer to what the relay stores (1 MiB body, 16 KiB headers). +pub fn fit_response(r: &ForwardResult) -> ForwardResult { + let mut out = r.clone(); + let bytes = r.body.as_bytes(); + if bytes.len() > MAX_STORED_BODY_BYTES - 2048 { + let note = format!( + "\n\n[BridgeHook: response body truncated from {} bytes]", + bytes.len() + ); + let mut cut = MAX_STORED_BODY_BYTES - 2048 - note.len(); + while cut > 0 && !r.body.is_char_boundary(cut) { + cut -= 1; + } + out.body = format!("{}{}", &r.body[..cut], note); + } + let mut size = 0; + out.headers = BTreeMap::new(); + for (k, v) in &r.headers { + size += k.len() + v.len() + 4; + if size > MAX_STORED_HEADER_BYTES { + break; + } + out.headers.insert(k.clone(), v.clone()); + } + out +} + +async fn error_text(res: Response) -> String { + let text = res.text().await.unwrap_or_default(); + serde_json::from_str::(&text) + .ok() + .and_then(|v| v.get("error").and_then(|e| e.as_str()).map(str::to_string)) + .unwrap_or(text) +} + +async fn status_error(res: Response) -> RelayError { + let status = res.status().as_u16(); + if status == 401 { + return RelayError::Unauthorized; + } + let text = res.text().await.unwrap_or_default(); + let parsed = serde_json::from_str::(&text).ok(); + let message = parsed + .as_ref() + .and_then(|v| v.get("error").and_then(|e| e.as_str()).map(str::to_string)) + .unwrap_or(text); + if status == 410 || (status == 404 && message == "Channel not found") { + return RelayError::ChannelGone; + } + if status == 402 + && parsed + .as_ref() + .and_then(|v| v.get("code")) + .and_then(|c| c.as_str()) + == Some("quota") + { + return RelayError::Quota { message }; + } + RelayError::Status { status, message } +} + +async fn json_or_error Deserialize<'de>>(res: Response) -> Result { + if !res.status().is_success() { + return Err(status_error(res).await); + } + Ok(res.json::().await?) +} + +async fn ok_or_error(res: Response) -> Result<(), RelayError> { + if !res.status().is_success() { + return Err(status_error(res).await); + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn fit_response_trims_body_on_a_char_boundary_and_caps_headers() { + let big = "é".repeat(MAX_STORED_BODY_BYTES); // 2 bytes each + let mut headers = BTreeMap::new(); + for i in 0..2000 { + headers.insert(format!("x-header-{i:04}"), "v".repeat(20)); + } + let r = ForwardResult { + status: 200, + headers, + body: big, + latency_ms: 5, + }; + let fitted = fit_response(&r); + assert!(fitted.body.len() <= MAX_STORED_BODY_BYTES); + assert!(fitted.body.ends_with("truncated from 2097152 bytes]")); + let header_bytes: usize = fitted + .headers + .iter() + .map(|(k, v)| k.len() + v.len() + 4) + .sum(); + assert!(header_bytes <= MAX_STORED_HEADER_BYTES); + assert!(!fitted.headers.is_empty()); + } + + #[test] + fn queued_event_parses_relay_rows() { + let page: PendingPage = serde_json::from_str( + r#"{"events":[{"id":"e1","channelId":"c1","method":"POST","path":"/webhook","requestHeaders":"{\"x\":\"1\"}","requestBody":"{}","receivedAt":1}],"nextCursor":"abc"}"#, + ) + .unwrap(); + assert_eq!(page.events[0].id, "e1"); + assert_eq!( + page.events[0].request_headers.as_deref(), + Some("{\"x\":\"1\"}") + ); + assert_eq!(page.next_cursor.as_deref(), Some("abc")); + } +} diff --git a/crates/bridgehook-core/src/stream.rs b/crates/bridgehook-core/src/stream.rs new file mode 100644 index 0000000..5d43ac0 --- /dev/null +++ b/crates/bridgehook-core/src/stream.rs @@ -0,0 +1,118 @@ +//! The account's live event stream (`GET /api/me/stream`, Server-Sent +//! Events). It is only a wake-up signal: a `webhook` frame for a channel +//! wakes that channel's drain, which then reads the queue in order, so a +//! live webhook never overtakes older queued ones. Polling stays as the +//! catch-up when the stream is down. + +use crate::relay::RelayClient; +use futures_util::StreamExt; +use serde::Deserialize; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::Arc; +use std::time::Duration; + +/// Longest gap between bytes before the stream counts as dead (the relay's +/// heartbeat is every 20 s). +pub const READ_TIMEOUT: Duration = Duration::from_secs(45); + +#[derive(Debug, Clone, Deserialize, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct Frame { + #[serde(rename = "type")] + pub kind: String, + #[serde(default)] + pub channel_id: Option, + #[serde(default)] + pub id: Option, +} + +/// Splits SSE text into the JSON payloads of its `data:` lines, one per +/// event. Returns the payloads and the unconsumed remainder. +pub fn parse_sse(buffer: &str) -> (Vec, String) { + let normalized = buffer.replace("\r\n", "\n"); + let mut out = Vec::new(); + let mut rest = normalized.as_str(); + while let Some(end) = rest.find("\n\n") { + let block = &rest[..end]; + rest = &rest[end + 2..]; + let data: Vec<&str> = block + .lines() + .filter_map(|l| l.strip_prefix("data:")) + .map(|l| l.strip_prefix(' ').unwrap_or(l)) + .collect(); + if !data.is_empty() { + out.push(data.join("\n")); + } + } + (out, rest.to_string()) +} + +/// Runs the stream until `stop` is set, reconnecting with backoff (1 s up to +/// 30 s). `connected` reflects whether frames are flowing right now. +pub async fn run( + relay: RelayClient, + connected: Arc, + stop: Arc, + mut on_frame: impl FnMut(Frame) + Send, +) { + let mut backoff = Duration::from_secs(1); + while !stop.load(Ordering::Relaxed) { + let mut req = relay + .http() + .get(format!("{}/api/me/stream", relay.base())) + .header("Accept", "text/event-stream"); + if let Some(t) = relay.token() { + req = req.bearer_auth(t); + } + match req.send().await { + Ok(res) if res.status().is_success() => { + backoff = Duration::from_secs(1); + let mut body = res.bytes_stream(); + let mut buffer = String::new(); + // The relay sends a heartbeat every 20 s; silence past + // READ_TIMEOUT means a dead connection (sleep, NAT expiry), + // so reconnect rather than trust it. + while let Ok(Some(chunk)) = tokio::time::timeout(READ_TIMEOUT, body.next()).await { + if stop.load(Ordering::Relaxed) { + break; + } + let Ok(bytes) = chunk else { break }; + buffer.push_str(&String::from_utf8_lossy(&bytes)); + let (payloads, rest) = parse_sse(&buffer); + buffer = rest; + for p in payloads { + if let Ok(frame) = serde_json::from_str::(&p) { + if frame.kind == "connected" { + connected.store(true, Ordering::Relaxed); + } + on_frame(frame); + } + } + } + } + _ => {} + } + connected.store(false, Ordering::Relaxed); + if stop.load(Ordering::Relaxed) { + break; + } + tokio::time::sleep(backoff).await; + backoff = (backoff * 2).min(Duration::from_secs(30)); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn parses_complete_events_and_keeps_the_partial_one() { + let input = ": heartbeat\n\ndata: {\"type\":\"connected\"}\n\ndata: {\"type\":\"webhook\",\"id\":\"e1\",\"channelId\":\"c1\"}\r\n\r\ndata: {\"type\":\"web"; + let (payloads, rest) = parse_sse(input); + assert_eq!(payloads.len(), 2); + let f: Frame = serde_json::from_str(&payloads[1]).unwrap(); + assert_eq!(f.kind, "webhook"); + assert_eq!(f.channel_id.as_deref(), Some("c1")); + assert_eq!(rest, "data: {\"type\":\"web"); + } +} diff --git a/package.json b/package.json index 2eb4c08..7c9ef52 100644 --- a/package.json +++ b/package.json @@ -7,6 +7,9 @@ "dev:relay": "pnpm --filter @bridgehook/relay dev", "build:web": "pnpm --filter @bridgehook/web build", "build:desktop": "pnpm --filter @bridgehook/desktop tauri build", + "test:cli": "cargo test --workspace && cargo clippy --workspace --all-targets -- -D warnings", + "e2e:cli": "node cli/e2e/cli.e2e.mjs", + "e2e:cli:local": "node cli/e2e/cli.e2e.mjs --local", "deploy:relay": "pnpm --filter @bridgehook/relay deploy", "deploy:web": "pnpm --filter @bridgehook/web deploy", "typecheck": "pnpm -r typecheck", diff --git a/relay/src/routes/me-devices.test.ts b/relay/src/routes/me-devices.test.ts new file mode 100644 index 0000000..1281895 --- /dev/null +++ b/relay/src/routes/me-devices.test.ts @@ -0,0 +1,203 @@ +/** + * Device revocation against a real D1 (Miniflare). A browser session may + * revoke any device on its account; a device token may revoke only itself, + * which is what `bridgehook logout` relies on. + */ +import { readFileSync, readdirSync } from "node:fs"; +import { join } from "node:path"; +import * as schema from "@bridgehook/shared/db/schema"; +import { drizzle } from "drizzle-orm/d1"; +import { Miniflare } from "miniflare"; +import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest"; +import type { Auth } from "../auth.js"; +import type { DB } from "../db.js"; +import { buildMeDevicesRoutes } from "./me-devices.js"; +import { buildMeRoutes } from "./me.js"; + +let mf: Miniflare; +let d1: D1Database; +let db: DB; + +const MIGRATIONS = join(__dirname, "../../migrations"); + +beforeAll(async () => { + mf = new Miniflare({ + modules: true, + script: "export default { fetch() { return new Response('') } }", + d1Databases: ["DB"], + }); + d1 = (await mf.getD1Database("DB")) as unknown as D1Database; + for (const file of readdirSync(MIGRATIONS) + .filter((f) => f.endsWith(".sql")) + .sort()) { + const sql = readFileSync(join(MIGRATIONS, file), "utf8"); + for (const stmt of sql.split("--> statement-breakpoint")) { + if (stmt.trim()) await d1.prepare(stmt).run(); + } + } + db = drizzle(d1, { schema }) as unknown as DB; +}, 30_000); + +afterAll(async () => { + await mf?.dispose(); +}); + +async function sha256Hex(input: string): Promise { + const buf = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(input)); + return [...new Uint8Array(buf)].map((b) => b.toString(16).padStart(2, "0")).join(""); +} + +const TOKENS = { + aliceCli: `dvc_${"a".repeat(32)}`, + aliceExt: `dvc_${"b".repeat(32)}`, + bobCli: `dvc_${"c".repeat(32)}`, +}; +const IDS = { + aliceCli: `dev_${"a".repeat(20)}`, + aliceExt: `dev_${"b".repeat(20)}`, + bobCli: `dev_${"c".repeat(20)}`, +}; + +beforeEach(async () => { + await d1.prepare("DELETE FROM devices").run(); + await d1.prepare("DELETE FROM user").run(); + for (const id of ["u_alice", "u_bob"]) { + await d1 + .prepare("INSERT INTO user (id, name, email, plan) VALUES (?, ?, ?, 'free')") + .bind(id, id, `${id}@example.com`) + .run(); + } + const rows: [keyof typeof IDS, string, string][] = [ + ["aliceCli", "u_alice", "cli"], + ["aliceExt", "u_alice", "extension"], + ["bobCli", "u_bob", "cli"], + ]; + for (const [k, user, kind] of rows) { + await d1 + .prepare( + "INSERT INTO devices (id, user_id, kind, label, token_hash, created_at) VALUES (?, ?, ?, ?, ?, ?)", + ) + .bind(IDS[k], user, kind, k, await sha256Hex(TOKENS[k]), Date.now()) + .run(); + } +}); + +function fakeAuth(): Auth { + return { + api: { + getSession: async ({ headers }: { headers: Headers }) => { + const id = headers.get("x-test-user"); + return id ? { user: { id, email: `${id}@example.com` } } : null; + }, + }, + } as unknown as Auth; +} + +const app = () => buildMeDevicesRoutes(() => ({ auth: fakeAuth(), db })); + +const del = (id: string, headers: Record) => + app().request(`/${id}`, { method: "DELETE", headers }); + +async function revoked(id: string): Promise { + const row = await d1 + .prepare("SELECT revoked_at FROM devices WHERE id = ?") + .bind(id) + .first<{ revoked_at: number | null }>(); + return row?.revoked_at != null; +} + +describe("DELETE /api/me/devices/:id", () => { + it("lets a device token revoke its own device, after which the token stops working", async () => { + const res = await del(IDS.aliceCli, { authorization: `Bearer ${TOKENS.aliceCli}` }); + expect(res.status).toBe(200); + expect(await revoked(IDS.aliceCli)).toBe(true); + + const again = await del(IDS.aliceCli, { authorization: `Bearer ${TOKENS.aliceCli}` }); + expect(again.status).toBe(401); + }); + + it("refuses a device token revoking another device, even on the same account", async () => { + const res = await del(IDS.aliceExt, { authorization: `Bearer ${TOKENS.aliceCli}` }); + expect(res.status).toBe(403); + expect(await revoked(IDS.aliceExt)).toBe(false); + + const other = await del(IDS.bobCli, { authorization: `Bearer ${TOKENS.aliceCli}` }); + expect(other.status).toBe(403); + expect(await revoked(IDS.bobCli)).toBe(false); + }); + + it("still lets a session revoke any of its own devices but not another user's", async () => { + expect((await del(IDS.aliceExt, { "x-test-user": "u_alice" })).status).toBe(200); + expect(await revoked(IDS.aliceExt)).toBe(true); + expect((await del(IDS.bobCli, { "x-test-user": "u_alice" })).status).toBe(404); + expect(await revoked(IDS.bobCli)).toBe(false); + }); + + it("answers 401 with no credentials", async () => { + expect((await del(IDS.aliceCli, {})).status).toBe(401); + }); +}); + +describe("PATCH /api/me/channels/:id with a device token", () => { + const meApp = () => + buildMeRoutes(() => ({ + auth: fakeAuth(), + db, + notifier: { + getChannelDO: () => ({ fetch: async () => new Response("") }), + notifyUser: () => {}, + }, + tunnelDomain: null, + })); + const patch = (id: string, body: unknown, headers: Record) => + meApp().request(`/channels/${id}`, { + method: "PATCH", + headers: { "content-type": "application/json", ...headers }, + body: JSON.stringify(body), + }); + const row = (id: string) => + d1 + .prepare("SELECT allowed_paths, label FROM channels WHERE id = ?") + .bind(id) + .first<{ allowed_paths: string; label: string | null }>(); + const bearer = { authorization: `Bearer ${TOKENS.aliceCli}` }; + + beforeEach(async () => { + await d1.prepare("DELETE FROM channels").run(); + for (const [id, user] of [ + ["chalice", "u_alice"], + ["chbob", "u_bob"], + ]) { + await d1 + .prepare( + "INSERT INTO channels (id, public_key, port, user_id, created_at) VALUES (?, ?, 3000, ?, ?)", + ) + .bind(id, "04".padEnd(130, "a"), user, Date.now()) + .run(); + } + }); + + it("sets allowedPaths on the token owner's channel", async () => { + const res = await patch("chalice", { allowedPaths: ["/stripe"] }, bearer); + expect(res.status).toBe(200); + expect((await row("chalice"))?.allowed_paths).toBe('["/stripe"]'); + }); + + it("refuses any other field, and another user's channel", async () => { + expect((await patch("chalice", { label: "x" }, bearer)).status).toBe(403); + expect((await row("chalice"))?.label).toBeNull(); + expect( + (await patch("chalice", { allowedPaths: ["/a"], responseMode: "sync" }, bearer)).status, + ).toBe(403); + expect((await row("chalice"))?.allowed_paths).toBe("[]"); + expect((await patch("chbob", { allowedPaths: ["/x"] }, bearer)).status).toBe(404); + expect((await row("chbob"))?.allowed_paths).toBe("[]"); + }); + + it("still lets a session change the label", async () => { + expect((await patch("chalice", { label: "api" }, { "x-test-user": "u_alice" })).status).toBe( + 200, + ); + expect((await row("chalice"))?.label).toBe("api"); + }); +}); diff --git a/relay/src/routes/me-devices.ts b/relay/src/routes/me-devices.ts index ab3143d..2cdd244 100644 --- a/relay/src/routes/me-devices.ts +++ b/relay/src/routes/me-devices.ts @@ -10,7 +10,7 @@ import { Hono } from "hono"; import { checkDevicePair, loadUserAccess } from "../access.js"; import { type Auth, getSessionUser } from "../auth.js"; import type { DB } from "../db.js"; -import { newDeviceId, newDeviceToken } from "../identity.js"; +import { newDeviceId, newDeviceToken, resolveCaller } from "../identity.js"; export interface MeDevicesEnv { auth: Auth; @@ -125,13 +125,20 @@ export function buildMeDevicesRoutes(getDeps: (c: { env: unknown }) => MeDevices const deps = getDeps(c); if (!deps) return c.json({ error: "Auth not configured" }, 404); - const sessionUser = await getSessionUser(deps.auth, c.req.raw); - if (!sessionUser) return c.json({ error: "Not signed in" }, 401); + // A browser session may revoke any device on the account. A device + // token (CLI, extension, agent) may revoke only itself, so + // `bridgehook logout` ends the token on the relay, not just locally. + const caller = await resolveCaller(deps.auth, deps.db, c.req.raw, { allowAgentTokens: true }); + if (!caller) return c.json({ error: "Not signed in" }, 401); const deviceId = c.req.param("deviceId"); + if (caller.via === "device-token" && caller.deviceId !== deviceId) { + return c.json({ error: "A device token can revoke only its own device" }, 403); + } if (!/^dev_[a-z0-9]{20}$/.test(deviceId)) { return c.json({ error: "Device not found" }, 404); } + const sessionUser = { id: caller.userId }; const body = await c.req.json().catch(() => null); const label = (body as { label?: unknown } | null)?.label; @@ -161,13 +168,20 @@ export function buildMeDevicesRoutes(getDeps: (c: { env: unknown }) => MeDevices const deps = getDeps(c); if (!deps) return c.json({ error: "Auth not configured" }, 404); - const sessionUser = await getSessionUser(deps.auth, c.req.raw); - if (!sessionUser) return c.json({ error: "Not signed in" }, 401); + // A browser session may revoke any device on the account. A device + // token (CLI, extension, agent) may revoke only itself, so + // `bridgehook logout` ends the token on the relay, not just locally. + const caller = await resolveCaller(deps.auth, deps.db, c.req.raw, { allowAgentTokens: true }); + if (!caller) return c.json({ error: "Not signed in" }, 401); const deviceId = c.req.param("deviceId"); + if (caller.via === "device-token" && caller.deviceId !== deviceId) { + return c.json({ error: "A device token can revoke only its own device" }, 403); + } if (!/^dev_[a-z0-9]{20}$/.test(deviceId)) { return c.json({ error: "Device not found" }, 404); } + const sessionUser = { id: caller.userId }; const [updated] = await deps.db .update(devices) diff --git a/relay/src/routes/me.ts b/relay/src/routes/me.ts index f02f2b6..b406981 100644 --- a/relay/src/routes/me.ts +++ b/relay/src/routes/me.ts @@ -59,8 +59,9 @@ export interface MeEnv { * session at all, and it reads identity, plan, usage and its channels here. * Key rotation also accepts device tokens, so an extension or CLI can adopt a * channel created elsewhere (dashboard, MCP agent); agent tokens are refused - * by resolveCaller. Other mutations (channel edits, replays, deletes) stay - * session-only. + * by resolveCaller. A device token may also set a channel's allowedPaths + * (`bridgehook forward --path`). Other mutations (labels, response mode, + * replays, deletes) stay session-only. */ async function resolveReader(deps: MeEnv, request: Request): Promise<{ id: string } | null> { const caller = await resolveCaller(deps.auth, deps.db, request); @@ -206,8 +207,12 @@ export function buildMeRoutes(getDeps: (c: { env: unknown }) => MeEnv | null) { const deps = getDeps(c); if (!deps) return c.json({ error: "Auth not configured" }, 404); - const sessionUser = await getSessionUser(deps.auth, c.req.raw); - if (!sessionUser) return c.json({ error: "Not signed in" }, 401); + // A device token may set allowedPaths only (`bridgehook forward + // --path`): it can already rotate the channel's key, which is more. + // Label and response mode stay with the dashboard session. + const caller = await resolveCaller(deps.auth, deps.db, c.req.raw); + if (!caller) return c.json({ error: "Not signed in" }, 401); + const sessionUser = { id: caller.userId }; const channelId = c.req.param("channelId"); if (!/^[a-z0-9]{1,24}$/.test(channelId)) { @@ -221,6 +226,14 @@ export function buildMeRoutes(getDeps: (c: { env: unknown }) => MeEnv | null) { responseMode?: unknown; syncTimeoutMs?: unknown; }; + if ( + caller.via === "device-token" && + (patch.label !== undefined || + patch.responseMode !== undefined || + patch.syncTimeoutMs !== undefined) + ) { + return c.json({ error: "A device token can change allowedPaths only" }, 403); + } const update: { label?: string | null;