From 146e3178493333ef1dd5fef1904ad9ad448811d9 Mon Sep 17 00:00:00 2001 From: eternal-flame-AD Date: Tue, 12 Nov 2024 22:22:48 -0600 Subject: [PATCH] init Signed-off-by: eternal-flame-AD --- .gitignore | 5 + .gitmodules | 3 + .vscode/settings.json | 6 + Cargo.lock | 3286 ++++++++++++++++++++++++++ Cargo.toml | 66 + LICENSE | 73 + README.md | 38 + build.rs | 556 +++++ rust-toolchain | 1 + src/deliver/mod.rs | 1 + src/fetch/mod.rs | 597 +++++ src/lib.rs | 755 ++++++ src/main.rs | 33 + src/post_process/image_processing.rs | 156 ++ src/post_process/mod.rs | 469 ++++ src/post_process/sniff.rs | 221 ++ src/sandbox.rs | 103 + src/stream.rs | 72 + submodules/file | 1 + wrangler.toml | 6 + 20 files changed, 6448 insertions(+) create mode 100644 .gitignore create mode 100644 .gitmodules create mode 100644 .vscode/settings.json create mode 100644 Cargo.lock create mode 100644 Cargo.toml create mode 100644 LICENSE create mode 100644 README.md create mode 100644 build.rs create mode 100644 rust-toolchain create mode 100644 src/deliver/mod.rs create mode 100644 src/fetch/mod.rs create mode 100644 src/lib.rs create mode 100644 src/main.rs create mode 100644 src/post_process/image_processing.rs create mode 100644 src/post_process/mod.rs create mode 100644 src/post_process/sniff.rs create mode 100644 src/sandbox.rs create mode 100644 src/stream.rs create mode 160000 submodules/file create mode 100644 wrangler.toml diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..aeab13e --- /dev/null +++ b/.gitignore @@ -0,0 +1,5 @@ +target +node_modules +.wrangler +/bundled +/build diff --git a/.gitmodules b/.gitmodules new file mode 100644 index 0000000..a6b518d --- /dev/null +++ b/.gitmodules @@ -0,0 +1,3 @@ +[submodule "submodules/file"] + path = submodules/file + url = https://github.com/file/file diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 0000000..a14aea1 --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,6 @@ +{ + "rust-analyzer.cargo.features": [ + //"cf-worker" + "env-local" + ], +} \ No newline at end of file diff --git a/Cargo.lock b/Cargo.lock new file mode 100644 index 0000000..e1ca8b4 --- /dev/null +++ b/Cargo.lock @@ -0,0 +1,3286 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "addr2line" +version = "0.24.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dfbe277e56a376000877090da837660b4427aad530e3028d44e0bffe4f89a1c1" +dependencies = [ + "gimli", +] + +[[package]] +name = "adler2" +version = "2.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "512761e0bb2578dd7380c6baaa0f4ce03e84f95e960231d1dec8bf4d7d6e2627" + +[[package]] +name = "ahash" +version = "0.8.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e89da841a80418a9b391ebaea17f5c112ffaaa96f621d2c285b5174da76b9011" +dependencies = [ + "cfg-if", + "once_cell", + "version_check", + "zerocopy", +] + +[[package]] +name = "aho-corasick" +version = "1.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e60d3430d3a69478ad0993f19238d2df97c507009a52b3c10addcd7f6bcb916" +dependencies = [ + "memchr", +] + +[[package]] +name = "aligned-vec" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4aa90d7ce82d4be67b64039a3d588d38dbcc6736577de4a847025ce5b0c468d1" + +[[package]] +name = "alloc-no-stdlib" +version = "2.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc7bb162ec39d46ab1ca8c77bf72e890535becd1751bb45f64c597edb4c8c6b3" + +[[package]] +name = "alloc-stdlib" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94fb8275041c72129eb51b7d0322c29b8387a0386127718b096429201a5d6ece" +dependencies = [ + "alloc-no-stdlib", +] + +[[package]] +name = "allocator-api2" +version = "0.2.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "45862d1c77f2228b9e10bc609d5bc203d86ebc9b87ad8d5d5167a6c9abf739d9" + +[[package]] +name = "anstream" +version = "0.6.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8acc5369981196006228e28809f761875c0327210a891e941f4c683b3a99529b" +dependencies = [ + "anstyle", + "anstyle-parse", + "anstyle-query", + "anstyle-wincon", + "colorchoice", + "is_terminal_polyfill", + "utf8parse", +] + +[[package]] +name = "anstyle" +version = "1.0.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "55cc3b69f167a1ef2e161439aa98aed94e6028e5f9a59be9a6ffb47aef1651f9" + +[[package]] +name = "anstyle-parse" +version = "0.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b2d16507662817a6a20a9ea92df6652ee4f94f914589377d69f3b21bc5798a9" +dependencies = [ + "utf8parse", +] + +[[package]] +name = "anstyle-query" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "79947af37f4177cfead1110013d678905c37501914fba0efea834c3fe9a8d60c" +dependencies = [ + "windows-sys 0.59.0", +] + +[[package]] +name = "anstyle-wincon" +version = "3.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2109dbce0e72be3ec00bed26e6a7479ca384ad226efdd66db8fa2e3a38c83125" +dependencies = [ + "anstyle", + "windows-sys 0.59.0", +] + +[[package]] +name = "anyhow" +version = "1.0.93" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4c95c10ba0b00a02636238b814946408b1322d5ac4760326e6fb8ec956d85775" + +[[package]] +name = "arbitrary" +version = "1.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dde20b3d026af13f561bdd0f15edf01fc734f0dafcedbaf42bba506a9517f223" + +[[package]] +name = "arg_enum_proc_macro" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ae92a5119aa49cdbcf6b9f893fe4e1d98b04ccbf82ee0584ad948a44a734dea" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "arrayref" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "76a2e8124351fda1ef8aaaa3bbd7ebbcb486bbcd4225aca0aa0d84bb2db8fecb" + +[[package]] +name = "arrayvec" +version = "0.7.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7c02d123df017efcdfbd739ef81735b36c5ba83ec3c59c80a9d7ecc718f92e50" + +[[package]] +name = "async-compression" +version = "0.4.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0cb8f1d480b0ea3783ab015936d2a55c87e219676f0c0b7dec61494043f21857" +dependencies = [ + "brotli", + "flate2", + "futures-core", + "memchr", + "pin-project-lite", + "tokio", + "zstd", + "zstd-safe", +] + +[[package]] +name = "async-trait" +version = "0.1.83" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "721cae7de5c34fbb2acd27e21e6d2cf7b886dce0c27388d46c4e6c47ea4318dd" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[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.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ace50bade8e6234aa140d9a2f552bbee1db4d353f69b8217bc503490fc1a9f26" + +[[package]] +name = "av1-grain" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6678909d8c5d46a42abcf571271e15fdbc0a225e3646cf23762cd415046c78bf" +dependencies = [ + "anyhow", + "arrayvec", + "log", + "nom", + "num-rational", + "v_frame", +] + +[[package]] +name = "avif-serialize" +version = "0.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e335041290c43101ca215eed6f43ec437eb5a42125573f600fc3fa42b9bddd62" +dependencies = [ + "arrayvec", +] + +[[package]] +name = "axum" +version = "0.7.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "504e3947307ac8326a5437504c517c4b56716c9d98fac0028c2acc7ca47d70ae" +dependencies = [ + "async-trait", + "axum-core", + "bytes", + "futures-util", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-util", + "itoa", + "matchit", + "memchr", + "mime", + "percent-encoding", + "pin-project-lite", + "rustversion", + "serde", + "serde_json", + "serde_path_to_error", + "serde_urlencoded", + "sync_wrapper 1.0.1", + "tokio", + "tower", + "tower-layer", + "tower-service", +] + +[[package]] +name = "axum-core" +version = "0.4.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09f2bd6146b97ae3359fa0cc6d6b376d9539582c7b4220f041a33ec24c226199" +dependencies = [ + "async-trait", + "bytes", + "futures-util", + "http", + "http-body", + "http-body-util", + "mime", + "pin-project-lite", + "rustversion", + "sync_wrapper 1.0.1", + "tower-layer", + "tower-service", +] + +[[package]] +name = "backtrace" +version = "0.3.74" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8d82cb332cdfaed17ae235a638438ac4d4839913cc2af585c3c6746e8f8bee1a" +dependencies = [ + "addr2line", + "cfg-if", + "libc", + "miniz_oxide", + "object", + "rustc-demangle", + "windows-targets", +] + +[[package]] +name = "base64" +version = "0.22.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" + +[[package]] +name = "bitflags" +version = "1.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" + +[[package]] +name = "bitflags" +version = "2.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b048fb63fd8b5923fc5aa7b340d8e156aec7ec02f0c78fa8a6ddc2613f6f71de" + +[[package]] +name = "bitstream-io" +version = "2.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6099cdc01846bc367c4e7dd630dc5966dccf36b652fae7a74e17b640411a91b2" + +[[package]] +name = "brotli" +version = "7.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc97b8f16f944bba54f0433f07e30be199b6dc2bd25937444bbad560bcea29bd" +dependencies = [ + "alloc-no-stdlib", + "alloc-stdlib", + "brotli-decompressor", +] + +[[package]] +name = "brotli-decompressor" +version = "4.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a45bd2e4095a8b518033b128020dd4a55aab1c0a381ba4404a472630f4bc362" +dependencies = [ + "alloc-no-stdlib", + "alloc-stdlib", +] + +[[package]] +name = "built" +version = "0.7.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c360505aed52b7ec96a3636c3f039d99103c37d1d9b4f7a8c743d3ea9ffcd03b" + +[[package]] +name = "bumpalo" +version = "3.16.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "79296716171880943b8470b5f8d03aa55eb2e645a4874bdbb28adb49162e012c" + +[[package]] +name = "bytemuck" +version = "1.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8334215b81e418a0a7bdb8ef0849474f40bb10c8b71f1c4ed315cff49f32494d" + +[[package]] +name = "byteorder" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" + +[[package]] +name = "byteorder-lite" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f1fe948ff07f4bd06c30984e69f5b4899c516a3ef74f34df92a2df2ab535495" + +[[package]] +name = "bytes" +version = "1.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ac0150caa2ae65ca5bd83f25c7de183dea78d4d366469f148435e2acfbad0da" + +[[package]] +name = "cc" +version = "1.1.37" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "40545c26d092346d8a8dab71ee48e7685a7a9cba76e634790c215b41a4a7b4cf" +dependencies = [ + "jobserver", + "libc", + "shlex", +] + +[[package]] +name = "cfg-expr" +version = "0.15.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d067ad48b8650848b989a59a86c6c36a995d02d2bf778d45c3c5d57bc2718f02" +dependencies = [ + "smallvec", + "target-lexicon", +] + +[[package]] +name = "cfg-if" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" + +[[package]] +name = "chrono" +version = "0.4.38" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a21f936df1771bf62b77f047b726c4625ff2e8aa607c01ec06e5a05bd8463401" +dependencies = [ + "js-sys", + "num-traits", + "wasm-bindgen", +] + +[[package]] +name = "chumsky" +version = "0.9.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8eebd66744a15ded14960ab4ccdbfb51ad3b81f51f3f04a80adac98c985396c9" +dependencies = [ + "hashbrown 0.14.5", + "stacker", +] + +[[package]] +name = "clap" +version = "4.5.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b97f376d85a664d5837dbae44bf546e6477a679ff6610010f17276f686d867e8" +dependencies = [ + "clap_builder", + "clap_derive", +] + +[[package]] +name = "clap_builder" +version = "4.5.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "19bc80abd44e4bed93ca373a0704ccbd1b710dc5749406201bb018272808dc54" +dependencies = [ + "anstream", + "anstyle", + "clap_lex", + "strsim", +] + +[[package]] +name = "clap_derive" +version = "4.5.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ac6a0c7b1a9e9a5186361f67dfa1b88213572f427fb9ab038efb2bd8c582dab" +dependencies = [ + "heck", + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "clap_lex" +version = "0.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1462739cb27611015575c0c11df5df7601141071f07518d56fcc1be504cbec97" + +[[package]] +name = "color_quant" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d7b894f5411737b7867f4827955924d7c254fc9f4d91a6aad6b097804b1018b" + +[[package]] +name = "colorchoice" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5b63caa9aa9397e2d9480a9b13673856c78d8ac123288526c37d7839f2a86990" + +[[package]] +name = "console_error_panic_hook" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a06aeb73f470f66dcdbf7223caeebb85984942f22f1adb2a088cf9668146bbbc" +dependencies = [ + "cfg-if", + "wasm-bindgen", +] + +[[package]] +name = "core-foundation" +version = "0.9.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "91e195e091a93c46f7102ec7818a2aa394e1e1771c3ab4825963fa03e45afb8f" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "core-foundation-sys" +version = "0.8.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" + +[[package]] +name = "core_maths" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3b02505ccb8c50b0aa21ace0fc08c3e53adebd4e58caa18a36152803c7709a3" +dependencies = [ + "libm", +] + +[[package]] +name = "crc32fast" +version = "1.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a97769d94ddab943e4510d138150169a2758b5ef3eb191a9ee688de3e23ef7b3" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "crossbeam-deque" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "613f8cc01fe9cf1a3eb3d7f488fd2fa8388403e97039e2f73692932e291a770d" +dependencies = [ + "crossbeam-epoch", + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-epoch" +version = "0.9.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5b82ac4a3c2ca9c3460964f020e1402edd5753411d7737aa39c3714ad1b5420e" +dependencies = [ + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-utils" +version = "0.8.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "22ec99545bb0ed0ea7bb9b8e1e9122ea386ff8a48c0922e43f36d45ab09e0e80" + +[[package]] +name = "dashmap" +version = "6.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5041cc499144891f3790297212f32a74fb938e5136a14943f338ef9e0ae276cf" +dependencies = [ + "cfg-if", + "crossbeam-utils", + "hashbrown 0.14.5", + "lock_api", + "once_cell", + "parking_lot_core", +] + +[[package]] +name = "data-url" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c297a1c74b71ae29df00c3e22dd9534821d60eb9af5a0192823fa2acea70c2a" + +[[package]] +name = "displaydoc" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "97369cbbc041bc366949bc74d34658d6cda5621039731c6310521892a3a20ae0" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "either" +version = "1.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "60b1af1c220855b6ceac025d3f6ecdd2b7c4894bfe9cd9bda4fbb4bc7c0d4cf0" + +[[package]] +name = "encoding_rs" +version = "0.8.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "75030f3c4f45dafd7586dd6780965a8c7e8e285a5ecb86713e63a79c5b2766f3" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "env_filter" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4f2c92ceda6ceec50f43169f9ee8424fe2db276791afde7b2cd8bc084cb376ab" +dependencies = [ + "log", + "regex", +] + +[[package]] +name = "env_logger" +version = "0.11.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e13fa619b91fb2381732789fc5de83b45675e882f66623b7d8cb4f643017018d" +dependencies = [ + "anstream", + "anstyle", + "env_filter", + "humantime", + "log", +] + +[[package]] +name = "equivalent" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5443807d6dff69373d433ab9ef5378ad8df50ca6298caf15de6e52e24aaf54d5" + +[[package]] +name = "errno" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "534c5cf6194dfab3db3242765c03bbe257cf92f22b38f6bc0c58d59108a820ba" +dependencies = [ + "libc", + "windows-sys 0.52.0", +] + +[[package]] +name = "fastrand" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "486f806e73c5707928240ddc295403b1b93c96a02038563881c4a2fd84b81ac4" + +[[package]] +name = "fdeflate" +version = "0.3.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "07c6f4c64c1d33a3111c4466f7365ebdcc37c5bd1ea0d62aae2e3d722aacbedb" +dependencies = [ + "simd-adler32", +] + +[[package]] +name = "flate2" +version = "1.0.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a1b589b4dc103969ad3cf85c950899926ec64300a1a46d76c03a6072957036f0" +dependencies = [ + "crc32fast", + "miniz_oxide", +] + +[[package]] +name = "float-cmp" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "98de4bbd547a563b716d8dfa9aad1cb19bfab00f4fa09a6a4ed21dbcf44ce9c4" + +[[package]] +name = "fnv" +version = "1.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" + +[[package]] +name = "fontdb" +version = "0.22.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a3a6f9af55fb97ad673fb7a69533eb2f967648a06fa21f8c9bb2cd6d33975716" +dependencies = [ + "log", + "slotmap", + "tinyvec", + "ttf-parser", +] + +[[package]] +name = "foreign-types" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f6f339eb8adc052cd2ca78910fda869aefa38d22d5cb648e6485e4d3fc06f3b1" +dependencies = [ + "foreign-types-shared", +] + +[[package]] +name = "foreign-types-shared" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00b0228411908ca8685dba7fc2cdd70ec9990a6e753e89b6ac91a84c40fbaf4b" + +[[package]] +name = "form_urlencoded" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e13624c2627564efccf4934284bdd98cbaa14e79b0b5a141218e507b3a823456" +dependencies = [ + "percent-encoding", +] + +[[package]] +name = "futures" +version = "0.3.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65bc07b1a8bc7c85c5f2e110c476c7389b4554ba72af57d8445ea63a576b0876" +dependencies = [ + "futures-channel", + "futures-core", + "futures-executor", + "futures-io", + "futures-sink", + "futures-task", + "futures-util", +] + +[[package]] +name = "futures-channel" +version = "0.3.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2dff15bf788c671c1934e366d07e30c1814a8ef514e1af724a602e8a2fbe1b10" +dependencies = [ + "futures-core", + "futures-sink", +] + +[[package]] +name = "futures-core" +version = "0.3.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "05f29059c0c2090612e8d742178b0580d2dc940c837851ad723096f87af6663e" + +[[package]] +name = "futures-executor" +version = "0.3.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e28d1d997f585e54aebc3f97d39e72338912123a67330d723fdbb564d646c9f" +dependencies = [ + "futures-core", + "futures-task", + "futures-util", +] + +[[package]] +name = "futures-io" +version = "0.3.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e5c1b78ca4aae1ac06c48a526a655760685149f0d465d21f37abfe57ce075c6" + +[[package]] +name = "futures-macro" +version = "0.3.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "162ee34ebcb7c64a8abebc059ce0fee27c2262618d7b60ed8faf72fef13c3650" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "futures-sink" +version = "0.3.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e575fab7d1e0dcb8d0c7bcf9a63ee213816ab51902e6d244a95819acacf1d4f7" + +[[package]] +name = "futures-task" +version = "0.3.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f90f7dce0722e95104fcb095585910c0977252f286e354b5e3bd38902cd99988" + +[[package]] +name = "futures-timer" +version = "3.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f288b0a4f20f9a56b5d1da57e2227c661b7b16168e2f72365f57b63326e29b24" + +[[package]] +name = "futures-util" +version = "0.3.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9fa08315bb612088cc391249efdc3bc77536f16c91f6cf495e6fbe85b20a4a81" +dependencies = [ + "futures-channel", + "futures-core", + "futures-io", + "futures-macro", + "futures-sink", + "futures-task", + "memchr", + "pin-project-lite", + "pin-utils", + "slab", +] + +[[package]] +name = "getrandom" +version = "0.2.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c4567c8db10ae91089c99af84c68c38da3ec2f087c3f82960bcdbf3656b6f4d7" +dependencies = [ + "cfg-if", + "libc", + "wasi", +] + +[[package]] +name = "gif" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3fb2d69b19215e18bb912fa30f7ce15846e301408695e44e0ef719f1da9e19f2" +dependencies = [ + "color_quant", + "weezl", +] + +[[package]] +name = "gimli" +version = "0.31.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "07e28edb80900c19c28f1072f2e8aeca7fa06b23cd4169cefe1af5aa3260783f" + +[[package]] +name = "governor" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0746aa765db78b521451ef74221663b57ba595bf83f75d0ce23cc09447c8139f" +dependencies = [ + "cfg-if", + "dashmap", + "futures-sink", + "futures-timer", + "futures-util", + "no-std-compat", + "nonzero_ext", + "parking_lot", + "portable-atomic", + "quanta", + "rand", + "smallvec", + "spinning_top", +] + +[[package]] +name = "h2" +version = "0.4.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "524e8ac6999421f49a846c2d4411f337e53497d8ec55d67753beffa43c5d9205" +dependencies = [ + "atomic-waker", + "bytes", + "fnv", + "futures-core", + "futures-sink", + "http", + "indexmap", + "slab", + "tokio", + "tokio-util", + "tracing", +] + +[[package]] +name = "hashbrown" +version = "0.14.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1" +dependencies = [ + "ahash", + "allocator-api2", +] + +[[package]] +name = "hashbrown" +version = "0.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a9bfc1af68b1726ea47d3d5109de126281def866b33970e10fbab11b5dafab3" + +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + +[[package]] +name = "hermit-abi" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d231dfb89cfffdbc30e7fc41579ed6066ad03abda9e567ccafae602b97ec5024" + +[[package]] +name = "http" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "21b9ddb458710bc376481b842f5da65cdf31522de232c1ca8146abce2a358258" +dependencies = [ + "bytes", + "fnv", + "itoa", +] + +[[package]] +name = "http-body" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1efedce1fb8e6913f23e0c92de8e62cd5b772a67e7b3946df930a62566c93184" +dependencies = [ + "bytes", + "http", +] + +[[package]] +name = "http-body-util" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "793429d76616a256bcb62c2a2ec2bed781c8307e797e2598c50010f2bee2544f" +dependencies = [ + "bytes", + "futures-util", + "http", + "http-body", + "pin-project-lite", +] + +[[package]] +name = "httparse" +version = "1.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7d71d3574edd2771538b901e6549113b4006ece66150fb69c0fb6d9a2adae946" + +[[package]] +name = "httpdate" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9" + +[[package]] +name = "humantime" +version = "2.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a3a5bfb195931eeb336b2a7b4d761daec841b97f947d34394601737a7bba5e4" + +[[package]] +name = "hyper" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbbff0a806a4728c99295b254c8838933b5b082d75e3cb70c8dab21fdfbcfa9a" +dependencies = [ + "bytes", + "futures-channel", + "futures-util", + "h2", + "http", + "http-body", + "httparse", + "httpdate", + "itoa", + "pin-project-lite", + "smallvec", + "tokio", + "want", +] + +[[package]] +name = "hyper-rustls" +version = "0.27.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08afdbb5c31130e3034af566421053ab03787c640246a446327f550d11bcb333" +dependencies = [ + "futures-util", + "http", + "hyper", + "hyper-util", + "rustls", + "rustls-pki-types", + "tokio", + "tokio-rustls", + "tower-service", +] + +[[package]] +name = "hyper-tls" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "70206fc6890eaca9fde8a0bf71caa2ddfc9fe045ac9e5c70df101a7dbde866e0" +dependencies = [ + "bytes", + "http-body-util", + "hyper", + "hyper-util", + "native-tls", + "tokio", + "tokio-native-tls", + "tower-service", +] + +[[package]] +name = "hyper-util" +version = "0.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df2dcfbe0677734ab2f3ffa7fa7bfd4706bfdc1ef393f2ee30184aed67e631b4" +dependencies = [ + "bytes", + "futures-channel", + "futures-util", + "http", + "http-body", + "hyper", + "pin-project-lite", + "socket2", + "tokio", + "tower-service", + "tracing", +] + +[[package]] +name = "icu_collections" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db2fa452206ebee18c4b5c2274dbf1de17008e874b4dc4f0aea9d01ca79e4526" +dependencies = [ + "displaydoc", + "yoke", + "zerofrom", + "zerovec", +] + +[[package]] +name = "icu_locid" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13acbb8371917fc971be86fc8057c41a64b521c184808a698c02acc242dbf637" +dependencies = [ + "displaydoc", + "litemap", + "tinystr", + "writeable", + "zerovec", +] + +[[package]] +name = "icu_locid_transform" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "01d11ac35de8e40fdeda00d9e1e9d92525f3f9d887cdd7aa81d727596788b54e" +dependencies = [ + "displaydoc", + "icu_locid", + "icu_locid_transform_data", + "icu_provider", + "tinystr", + "zerovec", +] + +[[package]] +name = "icu_locid_transform_data" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fdc8ff3388f852bede6b579ad4e978ab004f139284d7b28715f773507b946f6e" + +[[package]] +name = "icu_normalizer" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "19ce3e0da2ec68599d193c93d088142efd7f9c5d6fc9b803774855747dc6a84f" +dependencies = [ + "displaydoc", + "icu_collections", + "icu_normalizer_data", + "icu_properties", + "icu_provider", + "smallvec", + "utf16_iter", + "utf8_iter", + "write16", + "zerovec", +] + +[[package]] +name = "icu_normalizer_data" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8cafbf7aa791e9b22bec55a167906f9e1215fd475cd22adfcf660e03e989516" + +[[package]] +name = "icu_properties" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93d6020766cfc6302c15dbbc9c8778c37e62c14427cb7f6e601d849e092aeef5" +dependencies = [ + "displaydoc", + "icu_collections", + "icu_locid_transform", + "icu_properties_data", + "icu_provider", + "tinystr", + "zerovec", +] + +[[package]] +name = "icu_properties_data" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67a8effbc3dd3e4ba1afa8ad918d5684b8868b3b26500753effea8d2eed19569" + +[[package]] +name = "icu_provider" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ed421c8a8ef78d3e2dbc98a973be2f3770cb42b606e3ab18d6237c4dfde68d9" +dependencies = [ + "displaydoc", + "icu_locid", + "icu_provider_macros", + "stable_deref_trait", + "tinystr", + "writeable", + "yoke", + "zerofrom", + "zerovec", +] + +[[package]] +name = "icu_provider_macros" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ec89e9337638ecdc08744df490b221a7399bf8d164eb52a665454e60e075ad6" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "idna" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "686f825264d630750a544639377bae737628043f20d38bbc029e8f29ea968a7e" +dependencies = [ + "idna_adapter", + "smallvec", + "utf8_iter", +] + +[[package]] +name = "idna_adapter" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "daca1df1c957320b2cf139ac61e7bd64fed304c5040df000a745aa1de3b4ef71" +dependencies = [ + "icu_normalizer", + "icu_properties", +] + +[[package]] +name = "image" +version = "0.25.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd6f44aed642f18953a158afeb30206f4d50da59fbc66ecb53c66488de73563b" +dependencies = [ + "bytemuck", + "byteorder-lite", + "color_quant", + "gif", + "image-webp 0.2.0", + "num-traits", + "png", + "ravif", + "rayon", + "rgb", + "zune-core", + "zune-jpeg", +] + +[[package]] +name = "image-webp" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f79afb8cbee2ef20f59ccd477a218c12a93943d075b492015ecb1bb81f8ee904" +dependencies = [ + "byteorder-lite", + "quick-error", +] + +[[package]] +name = "image-webp" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e031e8e3d94711a9ccb5d6ea357439ef3dcbed361798bd4071dc4d9793fbe22f" +dependencies = [ + "byteorder-lite", + "quick-error", +] + +[[package]] +name = "imagesize" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "edcd27d72f2f071c64249075f42e205ff93c9a4c5f6c6da53e79ed9f9832c285" + +[[package]] +name = "imgref" +version = "1.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d0263a3d970d5c054ed9312c0057b4f3bde9c0b33836d3637361d4a9e6e7a408" + +[[package]] +name = "indexmap" +version = "2.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "707907fe3c25f5424cce2cb7e1cbcafee6bdbe735ca90ef77c29e84591e5b9da" +dependencies = [ + "equivalent", + "hashbrown 0.15.1", +] + +[[package]] +name = "interpolate_name" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c34819042dc3d3971c46c2190835914dfbe0c3c13f61449b2997f4e9722dfa60" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "ipnet" +version = "2.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ddc24109865250148c2e0f3d25d4f0f479571723792d3802153c60922a4fb708" + +[[package]] +name = "is_terminal_polyfill" +version = "1.70.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7943c866cc5cd64cbc25b2e01621d07fa8eb2a1a23160ee81ce38704e97b8ecf" + +[[package]] +name = "itertools" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba291022dbbd398a455acf126c1e341954079855bc60dfdda641363bd6922569" +dependencies = [ + "either", +] + +[[package]] +name = "itoa" +version = "1.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "49f1f14873335454500d59611f1cf4a4b0f786f9ac11f4312a78e4cf2566695b" + +[[package]] +name = "jobserver" +version = "0.1.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "48d1dbcbbeb6a7fec7e059840aa538bd62aaccf972c7346c4d9d2059312853d0" +dependencies = [ + "libc", +] + +[[package]] +name = "js-sys" +version = "0.3.72" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6a88f1bda2bd75b0452a14784937d796722fdebfe50df998aeb3f0b7603019a9" +dependencies = [ + "wasm-bindgen", +] + +[[package]] +name = "kurbo" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "89234b2cc610a7dd927ebde6b41dd1a5d4214cffaef4cf1fb2195d592f92518f" +dependencies = [ + "arrayvec", + "smallvec", +] + +[[package]] +name = "libc" +version = "0.2.162" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "18d287de67fe55fd7e1581fe933d965a5a9477b38e949cfa9f8574ef01506398" + +[[package]] +name = "libfuzzer-sys" +version = "0.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b9569d2f74e257076d8c6bfa73fb505b46b851e51ddaecc825944aa3bed17fa" +dependencies = [ + "arbitrary", + "cc", +] + +[[package]] +name = "libm" +version = "0.2.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8355be11b20d696c8f18f6cc018c4e372165b1fa8126cef092399c9951984ffa" + +[[package]] +name = "linux-raw-sys" +version = "0.4.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78b3ae25bc7c8c38cec158d1f2757ee79e9b3740fbc7ccf0e59e4b08d793fa89" + +[[package]] +name = "litemap" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "643cb0b8d4fcc284004d5fd0d67ccf61dfffadb7f75e1e71bc420f4688a3a704" + +[[package]] +name = "lock_api" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "07af8b9cdd281b7915f413fa73f29ebd5d55d0d3f0155584dade1ff18cea1b17" +dependencies = [ + "autocfg", + "scopeguard", +] + +[[package]] +name = "log" +version = "0.4.22" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7a70ba024b9dc04c27ea2f0c0548feb474ec5c54bba33a7f72f873a39d07b24" + +[[package]] +name = "loop9" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0fae87c125b03c1d2c0150c90365d7d6bcc53fb73a9acaef207d2d065860f062" +dependencies = [ + "imgref", +] + +[[package]] +name = "matchit" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e7465ac9959cc2b1404e8e2367b43684a6d13790fe23056cc8c6c5a6b7bcb94" + +[[package]] +name = "maybe-rayon" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ea1f30cedd69f0a2954655f7188c6a834246d2bcf1e315e2ac40c4b24dc9519" +dependencies = [ + "cfg-if", + "rayon", +] + +[[package]] +name = "memchr" +version = "2.7.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78ca9ab1a0babb1e7d5695e3530886289c18cf2f87ec19a575a0abdce112e3a3" + +[[package]] +name = "mime" +version = "0.3.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a" + +[[package]] +name = "minimal-lexical" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a" + +[[package]] +name = "miniz_oxide" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e2d80299ef12ff69b16a84bb182e3b9df68b5a91574d3d4fa6e41b65deec4df1" +dependencies = [ + "adler2", + "simd-adler32", +] + +[[package]] +name = "mio" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "80e04d1dcff3aae0704555fe5fee3bcfaf3d1fdf8a7e521d5b9d2b42acb52cec" +dependencies = [ + "hermit-abi", + "libc", + "wasi", + "windows-sys 0.52.0", +] + +[[package]] +name = "native-tls" +version = "0.2.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a8614eb2c83d59d1c8cc974dd3f920198647674a0a035e1af1fa58707e317466" +dependencies = [ + "libc", + "log", + "openssl", + "openssl-probe", + "openssl-sys", + "schannel", + "security-framework", + "security-framework-sys", + "tempfile", +] + +[[package]] +name = "new_debug_unreachable" +version = "1.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "650eef8c711430f1a879fdd01d4745a7deea475becfb90269c06775983bbf086" + +[[package]] +name = "no-std-compat" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b93853da6d84c2e3c7d730d6473e8817692dd89be387eb01b94d7f108ecb5b8c" + +[[package]] +name = "nom" +version = "7.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d273983c5a657a70a3e8f2a01329822f3b8c8172b73826411a55751e404a0a4a" +dependencies = [ + "memchr", + "minimal-lexical", +] + +[[package]] +name = "nonzero_ext" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38bf9645c8b145698bb0b18a4637dcacbc421ea49bef2317e4fd8065a387cf21" + +[[package]] +name = "noop_proc_macro" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0676bb32a98c1a483ce53e500a81ad9c3d5b3f7c920c28c24e9cb0980d0b5bc8" + +[[package]] +name = "num-bigint" +version = "0.4.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a5e44f723f1133c9deac646763579fdb3ac745e418f2a7af9cd0c431da1f20b9" +dependencies = [ + "num-integer", + "num-traits", +] + +[[package]] +name = "num-derive" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed3955f1a9c7c0c15e092f9c887db08b1fc683305fdf6eb6684f22555355e202" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "num-integer" +version = "0.1.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7969661fd2958a5cb096e56c8e1ad0444ac2bbcd0061bd28660485a44879858f" +dependencies = [ + "num-traits", +] + +[[package]] +name = "num-rational" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f83d14da390562dca69fc84082e73e548e1ad308d24accdedd2720017cb37824" +dependencies = [ + "num-bigint", + "num-integer", + "num-traits", +] + +[[package]] +name = "num-traits" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" +dependencies = [ + "autocfg", +] + +[[package]] +name = "object" +version = "0.36.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aedf0a2d09c573ed1d8d85b30c119153926a2b36dce0ab28322c09a117a4683e" +dependencies = [ + "memchr", +] + +[[package]] +name = "once_cell" +version = "1.20.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1261fe7e33c73b354eab43b1273a57c8f967d0391e80353e51f764ac02cf6775" + +[[package]] +name = "openssl" +version = "0.10.68" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6174bc48f102d208783c2c84bf931bb75927a617866870de8a4ea85597f871f5" +dependencies = [ + "bitflags 2.6.0", + "cfg-if", + "foreign-types", + "libc", + "once_cell", + "openssl-macros", + "openssl-sys", +] + +[[package]] +name = "openssl-macros" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a948666b637a0f465e8564c73e89d4dde00d72d4d473cc972f390fc3dcee7d9c" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "openssl-probe" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff011a302c396a5197692431fc1948019154afc178baf7d8e37367442a4601cf" + +[[package]] +name = "openssl-sys" +version = "0.9.104" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "45abf306cbf99debc8195b66b7346498d7b10c210de50418b5ccd7ceba08c741" +dependencies = [ + "cc", + "libc", + "pkg-config", + "vcpkg", +] + +[[package]] +name = "parking_lot" +version = "0.12.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1bf18183cf54e8d6059647fc3063646a1801cf30896933ec2311622cc4b9a27" +dependencies = [ + "lock_api", + "parking_lot_core", +] + +[[package]] +name = "parking_lot_core" +version = "0.9.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e401f977ab385c9e4e3ab30627d6f26d00e2c73eef317493c4ec6d468726cf8" +dependencies = [ + "cfg-if", + "libc", + "redox_syscall", + "smallvec", + "windows-targets", +] + +[[package]] +name = "paste" +version = "1.0.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "57c0d7b74b563b49d38dae00a0c37d4d6de9b432382b2892f0574ddcae73fd0a" + +[[package]] +name = "percent-encoding" +version = "2.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3148f5046208a5d56bcfc03053e3ca6334e51da8dfb19b6cdc8b306fae3283e" + +[[package]] +name = "pico-args" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5be167a7af36ee22fe3115051bc51f6e6c7054c9348e28deb4f49bd6f705a315" + +[[package]] +name = "pin-project" +version = "1.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "be57f64e946e500c8ee36ef6331845d40a93055567ec57e8fae13efd33759b95" +dependencies = [ + "pin-project-internal", +] + +[[package]] +name = "pin-project-internal" +version = "1.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c0f5fad0874fc7abcd4d750e76917eaebbecaa2c20bde22e1dbeeba8beb758c" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "pin-project-lite" +version = "0.2.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "915a1e146535de9163f3987b8944ed8cf49a18bb0056bcebcdcece385cece4ff" + +[[package]] +name = "pin-utils" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184" + +[[package]] +name = "pkg-config" +version = "0.3.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "953ec861398dccce10c670dfeaf3ec4911ca479e9c02154b3a215178c5f566f2" + +[[package]] +name = "png" +version = "0.17.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52f9d46a34a05a6a57566bc2bfae066ef07585a6e3fa30fbbdff5936380623f0" +dependencies = [ + "bitflags 1.3.2", + "crc32fast", + "fdeflate", + "flate2", + "miniz_oxide", +] + +[[package]] +name = "portable-atomic" +version = "1.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc9c68a3f6da06753e9335d63e27f6b9754dd1920d941135b7ea8224f141adb2" + +[[package]] +name = "ppv-lite86" +version = "0.2.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77957b295656769bb8ad2b6a6b09d897d94f05c41b069aede1fcdaa675eaea04" +dependencies = [ + "zerocopy", +] + +[[package]] +name = "proc-macro2" +version = "1.0.89" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f139b0662de085916d1fb67d2b4169d1addddda1919e696f3252b740b629986e" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "profiling" +version = "1.0.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "afbdc74edc00b6f6a218ca6a5364d6226a259d4b8ea1af4a0ea063f27e179f4d" +dependencies = [ + "profiling-procmacros", +] + +[[package]] +name = "profiling-procmacros" +version = "1.0.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a65f2e60fbf1063868558d69c6beacf412dc755f9fc020f514b7955fc914fe30" +dependencies = [ + "quote", + "syn", +] + +[[package]] +name = "psm" +version = "0.1.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aa37f80ca58604976033fae9515a8a2989fc13797d953f7c04fb8fa36a11f205" +dependencies = [ + "cc", +] + +[[package]] +name = "quanta" +version = "0.12.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e5167a477619228a0b284fac2674e3c388cba90631d7b7de620e6f1fcd08da5" +dependencies = [ + "crossbeam-utils", + "libc", + "once_cell", + "raw-cpuid", + "wasi", + "web-sys", + "winapi", +] + +[[package]] +name = "quick-error" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a993555f31e5a609f617c12db6250dedcac1b0a85076912c436e6fc9b2c8e6a3" + +[[package]] +name = "quote" +version = "1.0.37" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b5b9d34b8991d19d98081b46eacdd8eb58c6f2b201139f7c5f643cc155a633af" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "rand" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "34af8d1a0e25924bc5b7c43c079c942339d8f0a8b57c39049bef581b46327404" +dependencies = [ + "libc", + "rand_chacha", + "rand_core", +] + +[[package]] +name = "rand_chacha" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88" +dependencies = [ + "ppv-lite86", + "rand_core", +] + +[[package]] +name = "rand_core" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" +dependencies = [ + "getrandom", +] + +[[package]] +name = "rav1e" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd87ce80a7665b1cce111f8a16c1f3929f6547ce91ade6addf4ec86a8dda5ce9" +dependencies = [ + "arbitrary", + "arg_enum_proc_macro", + "arrayvec", + "av1-grain", + "bitstream-io", + "built", + "cfg-if", + "interpolate_name", + "itertools", + "libc", + "libfuzzer-sys", + "log", + "maybe-rayon", + "new_debug_unreachable", + "noop_proc_macro", + "num-derive", + "num-traits", + "once_cell", + "paste", + "profiling", + "rand", + "rand_chacha", + "simd_helpers", + "system-deps", + "thiserror 1.0.69", + "v_frame", + "wasm-bindgen", +] + +[[package]] +name = "ravif" +version = "0.11.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2413fd96bd0ea5cdeeb37eaf446a22e6ed7b981d792828721e74ded1980a45c6" +dependencies = [ + "avif-serialize", + "imgref", + "loop9", + "quick-error", + "rav1e", + "rayon", + "rgb", +] + +[[package]] +name = "raw-cpuid" +version = "11.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ab240315c661615f2ee9f0f2cd32d5a7343a84d5ebcccb99d46e6637565e7b0" +dependencies = [ + "bitflags 2.6.0", +] + +[[package]] +name = "rayon" +version = "1.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b418a60154510ca1a002a752ca9714984e21e4241e804d32555251faf8b78ffa" +dependencies = [ + "either", + "rayon-core", +] + +[[package]] +name = "rayon-core" +version = "1.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1465873a3dfdaa8ae7cb14b4383657caab0b3e8a0aa9ae8e04b044854c8dfce2" +dependencies = [ + "crossbeam-deque", + "crossbeam-utils", +] + +[[package]] +name = "redox_syscall" +version = "0.5.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b6dfecf2c74bce2466cabf93f6664d6998a69eb21e39f4207930065b27b771f" +dependencies = [ + "bitflags 2.6.0", +] + +[[package]] +name = "regex" +version = "1.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b544ef1b4eac5dc2db33ea63606ae9ffcfac26c1416a2806ae0bf5f56b201191" +dependencies = [ + "aho-corasick", + "memchr", + "regex-automata", + "regex-syntax", +] + +[[package]] +name = "regex-automata" +version = "0.4.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "809e8dc61f6de73b46c85f4c96486310fe304c434cfa43669d7b40f711150908" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax", +] + +[[package]] +name = "regex-syntax" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b15c43186be67a4fd63bee50d0303afffcef381492ebe2c5d87f324e1b8815c" + +[[package]] +name = "reqwest" +version = "0.12.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a77c62af46e79de0a562e1a9849205ffcb7fc1238876e9bd743357570e04046f" +dependencies = [ + "async-compression", + "base64", + "bytes", + "encoding_rs", + "futures-core", + "futures-util", + "h2", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-rustls", + "hyper-tls", + "hyper-util", + "ipnet", + "js-sys", + "log", + "mime", + "native-tls", + "once_cell", + "percent-encoding", + "pin-project-lite", + "rustls-pemfile", + "serde", + "serde_json", + "serde_urlencoded", + "sync_wrapper 1.0.1", + "system-configuration", + "tokio", + "tokio-native-tls", + "tokio-util", + "tower-service", + "url", + "wasm-bindgen", + "wasm-bindgen-futures", + "wasm-streams", + "web-sys", + "windows-registry", +] + +[[package]] +name = "resvg" +version = "0.44.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a325d5e8d1cebddd070b13f44cec8071594ab67d1012797c121f27a669b7958" +dependencies = [ + "gif", + "image-webp 0.1.3", + "log", + "pico-args", + "rgb", + "svgtypes", + "tiny-skia", + "usvg", +] + +[[package]] +name = "rgb" +version = "0.8.50" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "57397d16646700483b67d2dd6511d79318f9d057fdbd21a4066aeac8b41d310a" +dependencies = [ + "bytemuck", +] + +[[package]] +name = "ring" +version = "0.17.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c17fa4cb658e3583423e915b9f3acc01cceaee1860e33d59ebae66adc3a2dc0d" +dependencies = [ + "cc", + "cfg-if", + "getrandom", + "libc", + "spin", + "untrusted", + "windows-sys 0.52.0", +] + +[[package]] +name = "roxmltree" +version = "0.20.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c20b6793b5c2fa6553b250154b78d6d0db37e72700ae35fad9387a46f487c97" + +[[package]] +name = "rustc-demangle" +version = "0.1.24" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "719b953e2095829ee67db738b3bfa9fa368c94900df327b3f07fe6e794d2fe1f" + +[[package]] +name = "rustix" +version = "0.38.40" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "99e4ea3e1cdc4b559b8e5650f9c8e5998e3e5c1343b4eaf034565f32318d63c0" +dependencies = [ + "bitflags 2.6.0", + "errno", + "libc", + "linux-raw-sys", + "windows-sys 0.52.0", +] + +[[package]] +name = "rustls" +version = "0.23.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eee87ff5d9b36712a58574e12e9f0ea80f915a5b0ac518d322b24a465617925e" +dependencies = [ + "once_cell", + "rustls-pki-types", + "rustls-webpki", + "subtle", + "zeroize", +] + +[[package]] +name = "rustls-pemfile" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dce314e5fee3f39953d46bb63bb8a46d40c2f8fb7cc5a3b6cab2bde9721d6e50" +dependencies = [ + "rustls-pki-types", +] + +[[package]] +name = "rustls-pki-types" +version = "1.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "16f1201b3c9a7ee8039bcadc17b7e605e2945b27eee7631788c1bd2b0643674b" + +[[package]] +name = "rustls-webpki" +version = "0.102.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "64ca1bc8749bd4cf37b5ce386cc146580777b4e8572c7b97baf22c83f444bee9" +dependencies = [ + "ring", + "rustls-pki-types", + "untrusted", +] + +[[package]] +name = "rustversion" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e819f2bc632f285be6d7cd36e25940d45b2391dd6d9b939e79de557f7014248" + +[[package]] +name = "rustybuzz" +version = "0.18.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c85d1ccd519e61834798eb52c4e886e8c2d7d698dd3d6ce0b1b47eb8557f1181" +dependencies = [ + "bitflags 2.6.0", + "bytemuck", + "core_maths", + "log", + "smallvec", + "ttf-parser", + "unicode-bidi-mirroring", + "unicode-ccc", + "unicode-properties", + "unicode-script", +] + +[[package]] +name = "ryu" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f3cb5ba0dc43242ce17de99c180e96db90b235b8a9fdc9543c96d2209116bd9f" + +[[package]] +name = "schannel" +version = "0.1.26" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "01227be5826fa0690321a2ba6c5cd57a19cf3f6a09e76973b58e61de6ab9d1c1" +dependencies = [ + "windows-sys 0.59.0", +] + +[[package]] +name = "scopeguard" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" + +[[package]] +name = "security-framework" +version = "2.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "897b2245f0b511c87893af39b033e5ca9cce68824c4d7e7630b5a1d339658d02" +dependencies = [ + "bitflags 2.6.0", + "core-foundation", + "core-foundation-sys", + "libc", + "security-framework-sys", +] + +[[package]] +name = "security-framework-sys" +version = "2.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fa39c7303dc58b5543c94d22c1766b0d31f2ee58306363ea622b10bbc075eaa2" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "serde" +version = "1.0.214" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f55c3193aca71c12ad7890f1785d2b73e1b9f63a0bbc353c08ef26fe03fc56b5" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde-wasm-bindgen" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f3b143e2833c57ab9ad3ea280d21fd34e285a42837aeb0ee301f4f41890fa00e" +dependencies = [ + "js-sys", + "serde", + "wasm-bindgen", +] + +[[package]] +name = "serde-wasm-bindgen" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8302e169f0eddcc139c70f139d19d6467353af16f9fce27e8c30158036a1e16b" +dependencies = [ + "js-sys", + "serde", + "wasm-bindgen", +] + +[[package]] +name = "serde_derive" +version = "1.0.214" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "de523f781f095e28fa605cdce0f8307e451cc0fd14e2eb4cd2e98a355b147766" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "serde_json" +version = "1.0.132" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d726bfaff4b320266d395898905d0eba0345aae23b54aee3a737e260fd46db03" +dependencies = [ + "itoa", + "memchr", + "ryu", + "serde", +] + +[[package]] +name = "serde_path_to_error" +version = "0.1.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af99884400da37c88f5e9146b7f1fd0fbcae8f6eec4e9da38b67d05486f814a6" +dependencies = [ + "itoa", + "serde", +] + +[[package]] +name = "serde_spanned" +version = "0.6.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "87607cb1398ed59d48732e575a4c28a7a8ebf2454b964fe3f224f2afc07909e1" +dependencies = [ + "serde", +] + +[[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 = "shlex" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64" + +[[package]] +name = "simd-adler32" +version = "0.3.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d66dc143e6b11c1eddc06d5c423cfc97062865baf299914ab64caa38182078fe" + +[[package]] +name = "simd_helpers" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "95890f873bec569a0362c235787f3aca6e1e887302ba4840839bcc6459c42da6" +dependencies = [ + "quote", +] + +[[package]] +name = "simplecss" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a11be7c62927d9427e9f40f3444d5499d868648e2edbc4e2116de69e7ec0e89d" +dependencies = [ + "log", +] + +[[package]] +name = "siphasher" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "56199f7ddabf13fe5074ce809e7d3f42b42ae711800501b5b16ea82ad029c39d" + +[[package]] +name = "slab" +version = "0.4.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f92a496fb766b417c996b9c5e57daf2f7ad3b0bebe1ccfca4856390e3d3bb67" +dependencies = [ + "autocfg", +] + +[[package]] +name = "slotmap" +version = "1.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dbff4acf519f630b3a3ddcfaea6c06b42174d9a44bc70c620e9ed1649d58b82a" +dependencies = [ + "version_check", +] + +[[package]] +name = "smallvec" +version = "1.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c5e1a9a646d36c3599cd173a41282daf47c44583ad367b8e6837255952e5c67" + +[[package]] +name = "socket2" +version = "0.5.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce305eb0b4296696835b71df73eb912e0f1ffd2556a501fcede6e0c50349191c" +dependencies = [ + "libc", + "windows-sys 0.52.0", +] + +[[package]] +name = "spin" +version = "0.9.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6980e8d7511241f8acf4aebddbb1ff938df5eebe98691418c4468d0b72a96a67" + +[[package]] +name = "spinning_top" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d96d2d1d716fb500937168cc09353ffdc7a012be8475ac7308e1bdf0e3923300" +dependencies = [ + "lock_api", +] + +[[package]] +name = "stable_deref_trait" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a8f112729512f8e442d81f95a8a7ddf2b7c6b8a1a6f509a95864142b30cab2d3" + +[[package]] +name = "stacker" +version = "0.1.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "799c883d55abdb5e98af1a7b3f23b9b6de8ecada0ecac058672d7635eb48ca7b" +dependencies = [ + "cc", + "cfg-if", + "libc", + "psm", + "windows-sys 0.59.0", +] + +[[package]] +name = "strict-num" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6637bab7722d379c8b41ba849228d680cc12d0a45ba1fa2b48f2a30577a06731" +dependencies = [ + "float-cmp", +] + +[[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 = "svgtypes" +version = "0.15.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "794de53cc48eaabeed0ab6a3404a65f40b3e38c067e4435883a65d2aa4ca000e" +dependencies = [ + "kurbo", + "siphasher", +] + +[[package]] +name = "syn" +version = "2.0.87" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "25aa4ce346d03a6dcd68dd8b4010bcb74e54e62c90c573f394c46eae99aba32d" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "sync_wrapper" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2047c6ded9c721764247e62cd3b03c09ffc529b2ba5b10ec482ae507a4a70160" + +[[package]] +name = "sync_wrapper" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7065abeca94b6a8a577f9bd45aa0867a2238b74e8eb67cf10d492bc39351394" +dependencies = [ + "futures-core", +] + +[[package]] +name = "synstructure" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c8af7666ab7b6390ab78131fb5b0fce11d6b7a6951602017c35fa82800708971" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "system-configuration" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c879d448e9d986b661742763247d3693ed13609438cf3d006f51f5368a5ba6b" +dependencies = [ + "bitflags 2.6.0", + "core-foundation", + "system-configuration-sys", +] + +[[package]] +name = "system-configuration-sys" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e1d1b10ced5ca923a1fcb8d03e96b8d3268065d724548c0211415ff6ac6bac4" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "system-deps" +version = "6.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a3e535eb8dded36d55ec13eddacd30dec501792ff23a0b1682c38601b8cf2349" +dependencies = [ + "cfg-expr", + "heck", + "pkg-config", + "toml", + "version-compare", +] + +[[package]] +name = "target-lexicon" +version = "0.12.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "61c41af27dd6d1e27b1b16b489db798443478cef1f06a660c96db617ba5de3b1" + +[[package]] +name = "tempfile" +version = "3.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "28cce251fcbc87fac86a866eeb0d6c2d536fc16d06f184bb61aeae11aa4cee0c" +dependencies = [ + "cfg-if", + "fastrand", + "once_cell", + "rustix", + "windows-sys 0.59.0", +] + +[[package]] +name = "thiserror" +version = "1.0.69" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52" +dependencies = [ + "thiserror-impl 1.0.69", +] + +[[package]] +name = "thiserror" +version = "2.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c006c85c7651b3cf2ada4584faa36773bd07bac24acfb39f3c431b36d7e667aa" +dependencies = [ + "thiserror-impl 2.0.3", +] + +[[package]] +name = "thiserror-impl" +version = "1.0.69" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f077553d607adc1caf65430528a576c757a71ed73944b66ebb58ef2bbd243568" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "tiny-skia" +version = "0.11.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "83d13394d44dae3207b52a326c0c85a8bf87f1541f23b0d143811088497b09ab" +dependencies = [ + "arrayref", + "arrayvec", + "bytemuck", + "cfg-if", + "log", + "png", + "tiny-skia-path", +] + +[[package]] +name = "tiny-skia-path" +version = "0.11.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9c9e7fc0c2e86a30b117d0462aa261b72b7a99b7ebd7deb3a14ceda95c5bdc93" +dependencies = [ + "arrayref", + "bytemuck", + "strict-num", +] + +[[package]] +name = "tinystr" +version = "0.7.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9117f5d4db391c1cf6927e7bea3db74b9a1c1add8f7eda9ffd5364f40f57b82f" +dependencies = [ + "displaydoc", + "zerovec", +] + +[[package]] +name = "tinyvec" +version = "1.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "445e881f4f6d382d5f27c034e25eb92edd7c784ceab92a0937db7f2e9471b938" +dependencies = [ + "tinyvec_macros", +] + +[[package]] +name = "tinyvec_macros" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20" + +[[package]] +name = "tokio" +version = "1.41.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "22cfb5bee7a6a52939ca9224d6ac897bb669134078daa8735560897f69de4d33" +dependencies = [ + "backtrace", + "bytes", + "libc", + "mio", + "pin-project-lite", + "socket2", + "tokio-macros", + "windows-sys 0.52.0", +] + +[[package]] +name = "tokio-macros" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "693d596312e88961bc67d7f1f97af8a70227d9f90c31bba5806eec004978d752" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "tokio-native-tls" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbae76ab933c85776efabc971569dd6119c580d8f5d448769dec1764bf796ef2" +dependencies = [ + "native-tls", + "tokio", +] + +[[package]] +name = "tokio-rustls" +version = "0.26.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c7bc40d0e5a97695bb96e27995cd3a08538541b0a846f65bba7a359f36700d4" +dependencies = [ + "rustls", + "rustls-pki-types", + "tokio", +] + +[[package]] +name = "tokio-util" +version = "0.7.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "61e7c3654c13bcd040d4a03abee2c75b1d14a37b423cf5a813ceae1cc903ec6a" +dependencies = [ + "bytes", + "futures-core", + "futures-sink", + "pin-project-lite", + "tokio", +] + +[[package]] +name = "toml" +version = "0.8.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a1ed1f98e3fdc28d6d910e6737ae6ab1a93bf1985935a1193e68f93eeb68d24e" +dependencies = [ + "serde", + "serde_spanned", + "toml_datetime", + "toml_edit", +] + +[[package]] +name = "toml_datetime" +version = "0.6.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0dd7358ecb8fc2f8d014bf86f6f638ce72ba252a2c3a2572f2a795f1d23efb41" +dependencies = [ + "serde", +] + +[[package]] +name = "toml_edit" +version = "0.22.22" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ae48d6208a266e853d946088ed816055e556cc6028c5e8e2b84d9fa5dd7c7f5" +dependencies = [ + "indexmap", + "serde", + "serde_spanned", + "toml_datetime", + "winnow", +] + +[[package]] +name = "tower" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2873938d487c3cfb9aed7546dc9f2711d867c9f90c46b889989a2cb84eba6b4f" +dependencies = [ + "futures-core", + "futures-util", + "pin-project-lite", + "sync_wrapper 0.1.2", + "tokio", + "tower-layer", + "tower-service", +] + +[[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.40" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3523ab5a71916ccf420eebdf5521fcef02141234bbc0b8a49f2fdc4544364ef" +dependencies = [ + "pin-project-lite", + "tracing-core", +] + +[[package]] +name = "tracing-core" +version = "0.1.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c06d3da6113f116aaee68e4d601191614c9053067f9ab7f6edbcb161237daa54" +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 = "ttf-parser" +version = "0.24.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5be21190ff5d38e8b4a2d3b6a3ae57f612cc39c96e83cedeaf7abc338a8bac4a" +dependencies = [ + "core_maths", +] + +[[package]] +name = "unicode-bidi" +version = "0.3.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5ab17db44d7388991a428b2ee655ce0c212e862eff1768a455c58f9aad6e7893" + +[[package]] +name = "unicode-bidi-mirroring" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "64af057ad7466495ca113126be61838d8af947f41d93a949980b2389a118082f" + +[[package]] +name = "unicode-ccc" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "260bc6647b3893a9a90668360803a15f96b85a5257b1c3a0c3daf6ae2496de42" + +[[package]] +name = "unicode-ident" +version = "1.0.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e91b56cd4cadaeb79bbf1a5645f6b4f8dc5bde8834ad5894a8db35fda9efa1fe" + +[[package]] +name = "unicode-properties" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e70f2a8b45122e719eb623c01822704c4e0907e7e426a05927e1a1cfff5b75d0" + +[[package]] +name = "unicode-script" +version = "0.5.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9fb421b350c9aff471779e262955939f565ec18b86c15364e6bdf0d662ca7c1f" + +[[package]] +name = "unicode-vo" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1d386ff53b415b7fe27b50bb44679e2cc4660272694b7b6f3326d8480823a94" + +[[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.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8d157f1b96d14500ffdc1f10ba712e780825526c03d9a49b4d0324b0d9113ada" +dependencies = [ + "form_urlencoded", + "idna", + "percent-encoding", +] + +[[package]] +name = "usvg" +version = "0.44.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7447e703d7223b067607655e625e0dbca80822880248937da65966194c4864e6" +dependencies = [ + "base64", + "data-url", + "flate2", + "fontdb", + "imagesize", + "kurbo", + "log", + "pico-args", + "roxmltree", + "rustybuzz", + "simplecss", + "siphasher", + "strict-num", + "svgtypes", + "tiny-skia-path", + "unicode-bidi", + "unicode-script", + "unicode-vo", + "xmlwriter", +] + +[[package]] +name = "utf16_iter" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c8232dd3cdaed5356e0f716d285e4b40b932ac434100fe9b7e0e8e935b9e6246" + +[[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 = "v_frame" +version = "0.3.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6f32aaa24bacd11e488aa9ba66369c7cd514885742c9fe08cfe85884db3e92b" +dependencies = [ + "aligned-vec", + "num-traits", + "wasm-bindgen", +] + +[[package]] +name = "vcpkg" +version = "0.2.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426" + +[[package]] +name = "version-compare" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "852e951cb7832cb45cb1169900d19760cfa39b82bc0ea9c0e5a14ae88411c98b" + +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + +[[package]] +name = "want" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bfa7760aed19e106de2c7c0b581b509f2f25d3dacaf737cb82ac61bc6d760b0e" +dependencies = [ + "try-lock", +] + +[[package]] +name = "wasi" +version = "0.11.0+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423" + +[[package]] +name = "wasm-bindgen" +version = "0.2.95" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "128d1e363af62632b8eb57219c8fd7877144af57558fb2ef0368d0087bddeb2e" +dependencies = [ + "cfg-if", + "once_cell", + "wasm-bindgen-macro", +] + +[[package]] +name = "wasm-bindgen-backend" +version = "0.2.95" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb6dd4d3ca0ddffd1dd1c9c04f94b868c37ff5fac97c30b97cff2d74fce3a358" +dependencies = [ + "bumpalo", + "log", + "once_cell", + "proc-macro2", + "quote", + "syn", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-futures" +version = "0.4.45" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc7ec4f8827a71586374db3e87abdb5a2bb3a15afed140221307c3ec06b1f63b" +dependencies = [ + "cfg-if", + "js-sys", + "wasm-bindgen", + "web-sys", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.95" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e79384be7f8f5a9dd5d7167216f022090cf1f9ec128e6e6a482a2cb5c5422c56" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.95" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "26c6ab57572f7a24a4985830b120de1594465e5d500f24afe89e16b4e833ef68" +dependencies = [ + "proc-macro2", + "quote", + "syn", + "wasm-bindgen-backend", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.95" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65fc09f10666a9f147042251e0dda9c18f166ff7de300607007e96bdebc1068d" + +[[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.72" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f6488b90108c040df0fe62fa815cbdee25124641df01814dd7282749234c6112" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "weezl" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53a85b86a771b1c87058196170769dd264f66c0782acf1ae6cc51bfd64b39082" + +[[package]] +name = "winapi" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" +dependencies = [ + "winapi-i686-pc-windows-gnu", + "winapi-x86_64-pc-windows-gnu", +] + +[[package]] +name = "winapi-i686-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" + +[[package]] +name = "winapi-x86_64-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" + +[[package]] +name = "windows-registry" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e400001bb720a623c1c69032f8e3e4cf09984deec740f007dd2b03ec864804b0" +dependencies = [ + "windows-result", + "windows-strings", + "windows-targets", +] + +[[package]] +name = "windows-result" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d1043d8214f791817bab27572aaa8af63732e11bf84aa21a45a78d6c317ae0e" +dependencies = [ + "windows-targets", +] + +[[package]] +name = "windows-strings" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4cd9b125c486025df0eabcb585e62173c6c9eddcec5d117d3b6e8c30e2ee4d10" +dependencies = [ + "windows-result", + "windows-targets", +] + +[[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.59.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b" +dependencies = [ + "windows-targets", +] + +[[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 = "winnow" +version = "0.6.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "36c1fec1a2bb5866f07c25f68c26e565c4c200aebb96d7e55710c19d3e8ac49b" +dependencies = [ + "memchr", +] + +[[package]] +name = "worker" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d8aca53ec63e508176a89a573c972266f0f98bcc48bd866def7be0d939ef9268" +dependencies = [ + "async-trait", + "axum", + "bytes", + "chrono", + "futures-channel", + "futures-util", + "http", + "http-body", + "js-sys", + "matchit", + "pin-project", + "serde", + "serde-wasm-bindgen 0.6.5", + "serde_json", + "serde_urlencoded", + "tokio", + "url", + "wasm-bindgen", + "wasm-bindgen-futures", + "wasm-streams", + "web-sys", + "worker-kv", + "worker-macros", + "worker-sys", +] + +[[package]] +name = "worker-kv" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f06d4d1416a9f8346ee9123b0d9a11b3cfa38e6cfb5a139698017d1597c4d41" +dependencies = [ + "js-sys", + "serde", + "serde-wasm-bindgen 0.5.0", + "serde_json", + "thiserror 1.0.69", + "wasm-bindgen", + "wasm-bindgen-futures", +] + +[[package]] +name = "worker-macros" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1118a0ceb59ddde7fdbaff6c47b6fa6ee47848975ea38b4ae9bb4080f96541cd" +dependencies = [ + "async-trait", + "proc-macro2", + "quote", + "syn", + "wasm-bindgen", + "wasm-bindgen-futures", + "wasm-bindgen-macro-support", + "worker-sys", +] + +[[package]] +name = "worker-sys" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d5643a2ba07df61aa50e37212ffcb0944417db7d3960d4331f36aeb2fa5e2fd7" +dependencies = [ + "cfg-if", + "js-sys", + "wasm-bindgen", + "web-sys", +] + +[[package]] +name = "write16" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d1890f4022759daae28ed4fe62859b1236caebfc61ede2f63ed4e695f3f6d936" + +[[package]] +name = "writeable" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e9df38ee2d2c3c5948ea468a8406ff0db0b29ae1ffde1bcf20ef305bcc95c51" + +[[package]] +name = "xmlwriter" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec7a2a501ed189703dba8b08142f057e887dfc4b2cc4db2d343ac6376ba3e0b9" + +[[package]] +name = "yoke" +version = "0.7.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c5b1314b079b0930c31e3af543d8ee1757b1951ae1e1565ec704403a7240ca5" +dependencies = [ + "serde", + "stable_deref_trait", + "yoke-derive", + "zerofrom", +] + +[[package]] +name = "yoke-derive" +version = "0.7.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "28cc31741b18cb6f1d5ff12f5b7523e3d6eb0852bbbad19d73905511d9849b95" +dependencies = [ + "proc-macro2", + "quote", + "syn", + "synstructure", +] + +[[package]] +name = "yumechi-no-kuni-proxy-worker" +version = "0.1.0" +dependencies = [ + "axum", + "chumsky", + "clap", + "console_error_panic_hook", + "env_logger", + "futures", + "governor", + "image", + "log", + "quote", + "rand_core", + "reqwest", + "resvg", + "serde", + "serde_json", + "siphasher", + "thiserror 2.0.3", + "tokio", + "toml", + "tower-service", + "worker", + "worker-macros", +] + +[[package]] +name = "zerocopy" +version = "0.7.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1b9b4fd18abc82b8136838da5d50bae7bdea537c574d8dc1a34ed098d6c166f0" +dependencies = [ + "byteorder", + "zerocopy-derive", +] + +[[package]] +name = "zerocopy-derive" +version = "0.7.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fa4f8080344d4671fb4e831a13ad1e68092748387dfc4f55e356242fae12ce3e" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "zerofrom" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "91ec111ce797d0e0784a1116d0ddcdbea84322cd79e5d5ad173daeba4f93ab55" +dependencies = [ + "zerofrom-derive", +] + +[[package]] +name = "zerofrom-derive" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ea7b4a3637ea8669cedf0f1fd5c286a17f3de97b8dd5a70a6c167a1730e63a5" +dependencies = [ + "proc-macro2", + "quote", + "syn", + "synstructure", +] + +[[package]] +name = "zeroize" +version = "1.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ced3678a2879b30306d323f4542626697a464a97c0a07c9aebf7ebca65cd4dde" + +[[package]] +name = "zerovec" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aa2b893d79df23bfb12d5461018d408ea19dfafe76c2c7ef6d4eba614f8ff079" +dependencies = [ + "yoke", + "zerofrom", + "zerovec-derive", +] + +[[package]] +name = "zerovec-derive" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6eafa6dfb17584ea3e2bd6e76e0cc15ad7af12b09abdd1ca55961bed9b1063c6" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "zstd" +version = "0.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fcf2b778a664581e31e389454a7072dab1647606d44f7feea22cd5abb9c9f3f9" +dependencies = [ + "zstd-safe", +] + +[[package]] +name = "zstd-safe" +version = "7.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "54a3ab4db68cea366acc5c897c7b4d4d1b8994a9cd6e6f841f8964566a419059" +dependencies = [ + "zstd-sys", +] + +[[package]] +name = "zstd-sys" +version = "2.0.13+zstd.1.5.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38ff0f21cfee8f97d94cef41359e0c89aa6113028ab0291aa8ca0038995a95aa" +dependencies = [ + "cc", + "pkg-config", +] + +[[package]] +name = "zune-core" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f423a2c17029964870cfaabb1f13dfab7d092a62a29a89264f4d36990ca414a" + +[[package]] +name = "zune-jpeg" +version = "0.4.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "16099418600b4d8f028622f73ff6e3deaabdff330fb9a2a131dea781ee8b0768" +dependencies = [ + "zune-core", +] diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..c96e70c --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,66 @@ +[package] +name = "yumechi-no-kuni-proxy-worker" +version = "0.1.0" +edition = "2021" +authors = [ "eternal-flame-AD " ] + +[package.metadata.release] +release = false + +[lib] +crate-type = ["cdylib", "rlib"] +build = "build.rs" + +[profile.release] +lto = true +strip = true +opt-level = "z" +codegen-units = 1 + +[profile.release-local] +inherits = "release" +opt-level = 3 +strip = false + +[features] +default = [] +env-local = ["axum/tokio", "axum/http1", "axum/http2", "reqwest", "tokio", "env_logger", "governor", "clap", "toml", "image/rayon"] +cf-worker = ["dep:worker", "dep:worker-macros", "dep:console_error_panic_hook"] +apparmor = ["dep:rand_core", "dep:siphasher"] +reqwest = ["dep:reqwest"] +svg-text = ["resvg/text"] +tokio = ["dep:tokio"] +env_logger = ["dep:env_logger"] +governor = ["dep:governor"] + +[dependencies] +worker = { version="0.4.2", features=['http', 'axum'], optional = true } +worker-macros = { version="0.4.2", features=['http'], optional = true } +axum = { version = "0.7", default-features = false, features = ["query", "json"] } +tower-service = "0.3.2" +console_error_panic_hook = { version = "0.1.1", optional = true } +serde = { version = "1.0.214", features = ["derive"] } +futures = "0.3.31" +image = { version = "0.25.5", default-features = false, features = ["avif", "bmp", "gif", "ico", "jpeg", "png", "webp"] } +reqwest = { version = "0.12.9", features = ["brotli", "gzip", "stream", "zstd"], optional = true } +rand_core = { version = "0.6.4", features = ["getrandom"], optional = true } +siphasher = { version = "1.0.1", optional = true } +tokio = { version = "1.41.1", features = ["rt", "rt-multi-thread", "macros"], optional = true } +clap = { version = "4.5.20", features = ["derive"], optional = true } +toml = { version = "0.8", optional = true } +log = "0.4.22" +env_logger = { version = "0.11.5", optional = true } +governor = { version = "0.7.0", features = ["dashmap"], optional = true } +resvg = { version = "0.44.0", default-features = false, features = ["gif", "image-webp"] } +thiserror = "2.0.3" + +[build-dependencies] +chumsky = "0.9.3" +quote = "1.0.37" +serde = { version = "1.0.214", features = ["derive"] } +serde_json = "1.0.132" + +[[bin]] +name = "yumechi-no-kuni-proxy-worker" +path = "src/main.rs" +required-features = ["env-local"] diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..66ae5c5 --- /dev/null +++ b/LICENSE @@ -0,0 +1,73 @@ +Apache License +Version 2.0, January 2004 +http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + +"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. + +"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. + +"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. + +"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. + +"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. + +"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. + +"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). + +"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. + +"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." + +"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: + + (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. + + You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + +To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. + +Copyright 2024 Yumechi + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/README.md b/README.md new file mode 100644 index 0000000..2f95abc --- /dev/null +++ b/README.md @@ -0,0 +1,38 @@ +# Yumechi-no-kuni-proxy-worker + +This is a misskey proxy worker for ゆめちのくに (Yumechi-no-kuni) instance. Runs natively on both local and Cloudflare Workers environments! + + +Work in progress! Currently to do: + +- [X] Content-Type sniffing +- [X] SVG rendering + - [ ] Font rendering (likely will not run on Cloudflare Workers Free plan) +- [X] Preset image resizing +- [X] Opportunistic Redirection on large video files +- [X] RFC9110 compliant proxy loop detection with defensive programming against known vulnerable proxies +- [X] HTTPs only mode and X-Forwarded-Proto reflection +- [X] Cache-Control header +- [X] Rate-limiting on local deployment (untested) + + +## Demo + +### Avatar resizing + +Preview at: + +[https://yumechi-no-kuni-proxy-worker.eternal-flame-ad.workers.dev/proxy/avatar.webp?url=https://media.misskeyusercontent.com/io/274cc4f7-4674-4db1-9439-9fac08a66aa1.png](https://yumechi-no-kuni-proxy-worker.eternal-flame-ad.workers.dev/proxy/avatar.webp?url=https://media.misskeyusercontent.com/io/274cc4f7-4674-4db1-9439-9fac08a66aa1.png) + +Image: + +![Syuilo Avatar resived.png](https://yumechi-no-kuni-proxy-worker.eternal-flame-ad.workers.dev/proxy/avatar.webp?url=https://media.misskeyusercontent.com/io/274cc4f7-4674-4db1-9439-9fac08a66aa1.png) + + +### SVG rendering + +(font rendering disabled due to size restrictions) + +[https://yumechi-no-kuni-proxy-worker.eternal-flame-ad.workers.dev/proxy/static.webp?url=https://upload.wikimedia.org/wikipedia/commons/a/ad/AES-AddRoundKey.svg](https://yumechi-no-kuni-proxy-worker.eternal-flame-ad.workers.dev/proxy/static.webp?url=https://upload.wikimedia.org/wikipedia/commons/a/ad/AES-AddRoundKey.svg) + +![AES-AddRoundKey.svg](https://yumechi-no-kuni-proxy-worker.eternal-flame-ad.workers.dev/proxy/static.webp?url=https://upload.wikimedia.org/wikipedia/commons/a/ad/AES-AddRoundKey.svg) \ No newline at end of file diff --git a/build.rs b/build.rs new file mode 100644 index 0000000..acd560e --- /dev/null +++ b/build.rs @@ -0,0 +1,556 @@ +use std::{env, ops::Range, vec}; + +use chumsky::prelude::*; +use quote::ToTokens; +use text::whitespace; + +const FILES_TO_PARSE: &[&str] = &[ + "jpeg", + "images", + "sgml", + "riff", + "animation", + "audio", + "matroska", + "vorbis", + "audio", + "msdos", + "webassembly", + "elf", + "mach", +]; + +const BLACKLISTED: &[&str] = &["fuji-", "canon-", "corel-", "dicom", "garmin"]; + +// remove extension entries not in this list from safe entries +const SAFE_EXTENSIONS: &[&str] = &[ + ".png", ".gif", ".jpeg", ".webp", ".avif", ".apng", ".bmp", ".tiff", ".x-icon", ".opus", + ".ogg", ".mp4", ".m4v", ".3gpp", ".mpeg", ".webm", ".aac", ".flac", ".wav", +]; + +const SAFE_WHITELISTED: &[&str] = &[ + "png", "gif", "jpeg", "webp", "avif", "apng", "bmp", "tiff", "x-icon", "opus", "ogg", "mp4", + "m4v", "3gpp", "mpeg", "webm", "aac", "flac", "wav", "svg", "rss", +]; + +// we want to have signatures for these to be able to detect them +const UNSAFE_WHITELISTED: &[&str] = &[ + ".exe", + ".wasm", + "elf", + "mach", + "javascript", + "bios", + "firmware", + "driver", + "mpegurl", +]; + +fn static_signatures() -> Vec { + vec![ + MIMEAssociation { + mime: "application/x-elf-executable".to_string().into(), + ext: vec![".pie".to_string(), ".elf".to_string(), ".so".to_string()], + safe: false, + signatures: vec![FlattenedFileSignature { + test: vec![0x7f, b'E', b'L', b'F'], + mask: vec![0xff, 0xff, 0xff, 0xff], + }], + }, + MIMEAssociation { + mime: "application/x-mach-binary".to_string().into(), + ext: vec![".dylib".to_string(), ".bundle".to_string()], + safe: false, + signatures: vec![FlattenedFileSignature { + test: vec![0xfe, 0xed, 0xfa, 0xce], + mask: vec![0xff, 0xff, 0xff, 0xff], + }], + }, + MIMEAssociation { + mime: "application/vnd.microsoft.portable-executable" + .to_string() + .into(), + ext: vec![".exe".to_string(), ".dll".to_string(), ".sys".to_string()], + safe: false, + signatures: vec![FlattenedFileSignature { + test: b"PE\0\0".to_vec(), + mask: vec![0xff, 0xff, 0xff, 0xff], + }], + }, + ] +} + +#[derive(Debug, Clone)] +pub enum MagicFileLine { + Nop, + Unknown, + Magic { + indent: u8, + offset: u64, + ty: MagicType, + }, + AssignAttr { + attr: String, + value: String, + }, +} + +#[derive(Debug, Clone)] +pub enum MagicType { + Unknown(String), + Belong { + test: Vec, + mask: Option>, + }, + String { + test: Vec, + }, +} + +pub fn parse_string_repr() -> impl Parser, Error = Simple> { + just('\\') + .ignore_then(choice(( + just('\\').to(b'\\'), + just('n').to(b'\n'), + just('r').to(b'\r'), + just('t').to(b'\t'), + just('x').ignore_then( + one_of("0123456789abcdefABCDEF") + .repeated() + .exactly(2) + .map(|s| u8::from_str_radix(&s.iter().collect::(), 16).unwrap()), + ), + ))) + .or(none_of("\\").map(|c| c as u8)) + .repeated() + .at_least(1) + .map(|s| s.to_vec()) + .then_ignore(end()) +} + +pub fn parse_hex_repr() -> impl Parser, Error = Simple> { + just("0x") + .ignore_then( + one_of("0123456789abcdef") + .repeated() + .exactly(2) + .map(|s| u8::from_str_radix(&s.iter().collect::(), 16).unwrap()) + .repeated() + .at_least(1), + ) + .map(|s| s.to_vec()) + .then_ignore(end()) +} + +pub fn parse_magic_line() -> impl Parser> { + choice(( + just('#') + .then_ignore(any().repeated()) + .to(MagicFileLine::Nop), + just('>') + .repeated() + .map(|i| i.len() as u8) + .then( + one_of("0123456789") + .repeated() + .at_least(1) + .try_map(|s, span| { + s.iter() + .collect::() + .parse::() + .map_err(|_| Simple::custom(span, "Failed to parse number")) + }) + .or(just("0x").ignore_then( + one_of("0123456789abcdefABCDEF") + .repeated() + .at_least(1) + .try_map(|s, span| { + u64::from_str_radix(&s.iter().collect::(), 16) + .map_err(|_| Simple::custom(span, "Failed to parse number")) + }), + )), + ) + .then_ignore(whitespace().at_least(1)) + .then( + none_of(" \t\n") + .repeated() + .at_least(1) + .map(String::from_iter), + ) + .then_ignore(whitespace().at_least(1)) + .then( + none_of(" \t\n") + .repeated() + .at_least(1) + .map(String::from_iter), + ) + .try_map(|(((indent, offset), ty), rep), span: Range| { + Ok(MagicFileLine::Magic { + indent, + offset, + ty: match ty.as_str() { + "string" => MagicType::String { + test: parse_string_repr().parse(rep).map_err(|_| { + Simple::custom(span, "Failed to parse string pattern") + })?, + }, + "belong" => MagicType::Belong { + test: parse_hex_repr() + .parse(rep) + .map_err(|_| Simple::custom(span, "Failed to parse hex pattern"))?, + mask: None, + }, + s if s.starts_with("belong&") => { + let mask = &s["belong&".len()..]; + let span_clone = span.clone(); + MagicType::Belong { + test: parse_hex_repr().parse(rep).map_err(|_| { + Simple::custom(span, "Failed to parse hex pattern") + })?, + mask: Some(parse_hex_repr().parse(mask).map_err(|_| { + Simple::custom(span_clone, "Failed to parse hex pattern") + })?), + } + } + _ => MagicType::Unknown(ty), + }, + }) + }) + .then_ignore(any().repeated()), + just("!:") + .ignore_then( + one_of("abcdefghijklmnopqrstuvwxyz") + .repeated() + .at_least(1) + .map(|s| s.iter().collect()), + ) + .then_ignore(whitespace().at_least(1)) + .then(any().repeated().map(String::from_iter)) + .map(|(attr, value)| MagicFileLine::AssignAttr { attr, value }), + )) + .then_ignore(whitespace()) + .then_ignore(end()) +} + +#[derive(Debug, Clone, PartialEq, serde::Serialize)] +pub struct FileSignature { + pub offset: u64, + pub test: Vec, + pub mask: Option>, +} + +#[derive(Debug, Clone, PartialEq, serde::Serialize)] +pub struct FlattenedFileSignature { + pub test: Vec, + pub mask: Vec, +} + +impl FlattenedFileSignature { + fn codegen(&self) -> impl ToTokens { + let data = self + .test + .iter() + .copied() + .zip(self.mask.iter().copied()) + .map(|(t, m)| { + quote::quote! { + (#t, #m) + } + }); + quote::quote! { + FlattenedFileSignature(&[#(#data),*]) + } + } +} + +impl From for FlattenedFileSignature { + fn from(sig: FileSignature) -> Self { + let len = sig.test.len(); + FlattenedFileSignature { + test: std::iter::repeat(0) + .take(sig.offset as usize) + .chain(sig.test) + .collect(), + mask: sig.mask.unwrap_or_else(|| { + std::iter::repeat(0) + .take(sig.offset as usize) + .chain(std::iter::repeat(!0).take(len)) + .collect() + }), + } + } +} + +impl std::ops::BitAnd for FlattenedFileSignature { + type Output = FlattenedFileSignature; + + fn bitand(mut self, mut rhs: FlattenedFileSignature) -> Self::Output { + if self.test.len() < rhs.test.len() { + std::mem::swap(&mut self, &mut rhs); + } + let test = self + .test + .iter() + .zip( + rhs.test + .iter() + .chain(std::iter::repeat(&0).take(self.test.len() - rhs.test.len())), + ) + .map(|(a, b)| a | b) + .collect(); + let mask = self + .mask + .iter() + .zip( + rhs.mask + .iter() + .chain(std::iter::repeat(&0).take(self.test.len() - rhs.test.len())), + ) + .map(|(a, b)| a | b) + .collect(); + FlattenedFileSignature { test, mask } + } +} + +#[derive(Debug, Clone, PartialEq, serde::Serialize)] +pub struct MIMEAssociation { + pub mime: Option, + pub ext: Vec, + pub safe: bool, + pub signatures: Vec, +} + +impl MIMEAssociation { + fn codegen(&self) -> impl ToTokens { + let mime = self.mime.as_deref().unwrap_or(""); + let ext = self.ext.first().map(|s| s.as_str()).unwrap_or(""); + let safe = self.safe; + let signatures = self.signatures.iter().map(|s| s.codegen()); + quote::quote! { + MIMEAssociation { + mime: #mime, + ext: #ext, + safe: #safe, + signatures: &[#(#signatures),*], + } + } + } + fn build_vec(lines: Vec) -> Vec { + let mut stack = Vec::new(); + + let mut out: Vec = Vec::new(); + + for line in lines { + match line { + MagicFileLine::Magic { ty, offset, indent } => match ty { + MagicType::Belong { test, mask } => { + stack.truncate(indent as usize); + stack.push(FileSignature { offset, test, mask }); + } + MagicType::String { test } => { + stack.truncate(indent as usize); + stack.push(FileSignature { + offset, + test, + mask: None, + }); + } + _ => {} + }, + MagicFileLine::AssignAttr { attr, value } => match attr.as_str() { + "mime" if !stack.is_empty() => { + let mime = value; + let flattened = stack.iter().map(|sig| sig.clone().into()).fold( + FlattenedFileSignature { + test: Vec::new(), + mask: Vec::new(), + }, + |a, b| a & b, + ); + if flattened.test.len() > 64 { + eprintln!("Signature too long: {:?}", flattened.test.len()); + continue; + } + if let Some(existing) = out + .iter_mut() + .find(|m| m.mime.as_deref().map(|m| m == mime).unwrap_or(false)) + { + existing.signatures.push(flattened); + } else { + out.push(MIMEAssociation { + mime: Some(mime), + safe: false, + ext: vec![], + signatures: vec![flattened], + }); + } + } + "ext" if !stack.is_empty() => { + let ext = value; + let flattened = stack.iter().map(|sig| sig.clone().into()).fold( + FlattenedFileSignature { + test: Vec::new(), + mask: Vec::new(), + }, + |a, b| a & b, + ); + if flattened.test.len() > 64 { + eprintln!("Signature too long: {:?}", flattened.test.len()); + continue; + } + if let Some(existing) = + out.iter_mut().find(|m| m.signatures.contains(&flattened)) + { + existing + .ext + .extend(ext.split('/').map(|s| format!(".{}", s))) + } else { + out.push(MIMEAssociation { + mime: None, + safe: false, + ext: ext.split('/').map(|s| format!(".{}", s)).collect(), + signatures: vec![flattened], + }); + } + } + _ => {} + }, + _ => {} + } + } + + out.iter_mut().for_each(|m| { + m.ext.sort(); + m.ext.dedup(); + m.signatures.sort_by(|a, b| a.test.cmp(&b.test)); + m.signatures.dedup(); + }); + out.dedup(); + + out + } +} + +const BASE_DIR: &str = "submodules/file/magic/Magdir/"; + +fn main() { + let signatures = static_signatures() + .into_iter() + .chain(FILES_TO_PARSE.iter().flat_map(|file| { + println!("cargo:rerun-if-changed={}", file); + eprintln!("Using file: {}", file); + let path = format!("{}{}", BASE_DIR, file); + let content = std::fs::read(&path) + .map(|v| String::from_utf8_lossy(&v).to_string()) + .unwrap(); + let lines = content + .lines() + .filter(|line| !line.is_empty()) + .map(|line| { + parse_magic_line().parse(line).unwrap_or_else(|e| { + eprintln!("Failed to parse line: {:?}", line); + eprintln!("Error: {:?}", e); + MagicFileLine::Unknown + }) + }) + .collect::>(); + MIMEAssociation::build_vec(lines) + .into_iter() + .map(|mut m| { + if m.mime + .as_ref() + .map(|m| UNSAFE_WHITELISTED.iter().any(|u| m.contains(u))) + .unwrap_or(false) + { + m.safe = false; + return m; + } + if m.ext + .iter() + .any(|ext| UNSAFE_WHITELISTED.iter().any(|u| ext.contains(u))) + { + m.safe = false; + return m; + } + if m.mime + .as_ref() + .map(|m| SAFE_WHITELISTED.iter().any(|w| m.contains(w))) + .unwrap_or(false) + { + m.safe = true; + } + if m.ext + .iter() + .any(|ext| SAFE_WHITELISTED.iter().any(|w| ext.contains(w))) + { + m.safe = true; + } + + if m.safe { + m.ext + .retain(|ext| SAFE_EXTENSIONS.iter().any(|s| ext.contains(s))); + } + + m + }) + .filter(|m| { + if let Some(incoming) = &m.mime { + let mime = incoming.to_lowercase(); + if BLACKLISTED.iter().any(|b| mime.contains(b)) { + return false; + } + if SAFE_WHITELISTED.iter().any(|w| mime.contains(w)) + || UNSAFE_WHITELISTED.iter().any(|u| mime.contains(u)) + { + return true; + } + } + if m.ext + .iter() + .any(|ext| BLACKLISTED.iter().any(|b| ext.contains(b))) + { + return false; + } + if let Some(incoming) = &m.mime { + let mime = incoming.to_lowercase(); + if SAFE_WHITELISTED.iter().all(|w| mime.contains(w)) + || UNSAFE_WHITELISTED.iter().any(|u| mime.contains(u)) + { + return true; + } + } + if m.ext.iter().any(|ext| { + SAFE_WHITELISTED.iter().any(|w| ext.contains(w)) + || UNSAFE_WHITELISTED.iter().any(|u| ext.contains(u)) + }) { + return true; + } + false + }) + })) + .collect::>(); + + let max_size = signatures + .iter() + .map(|s| s.signatures.iter().map(|s| s.test.len()).max().unwrap()) + .max() + .unwrap(); + + if max_size > 128 { + panic!("Max signature size is too large: {}", max_size); + } + + std::fs::write(env::var("OUT_DIR").unwrap() + "/magic.rs", { + let signatures = signatures.iter().map(|s| s.codegen()); + + quote::quote! { + /// Maximum size of a signature + pub const SNIFF_SIZE: usize = #max_size; + #[allow(clippy::all)] + const MAGICS: &[MIMEAssociation] = &[#(#signatures),*]; + } + .into_token_stream() + .to_string() + }) + .unwrap(); +} diff --git a/rust-toolchain b/rust-toolchain new file mode 100644 index 0000000..ea3769f --- /dev/null +++ b/rust-toolchain @@ -0,0 +1 @@ +1.81 diff --git a/src/deliver/mod.rs b/src/deliver/mod.rs new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/src/deliver/mod.rs @@ -0,0 +1 @@ + diff --git a/src/fetch/mod.rs b/src/fetch/mod.rs new file mode 100644 index 0000000..a8667ca --- /dev/null +++ b/src/fetch/mod.rs @@ -0,0 +1,597 @@ +use crate::{ErrorResponse, FetchConfig, MAX_SIZE}; +use axum::{ + body::Bytes, + extract::FromRequestParts, + http::{request::Parts, HeaderMap}, +}; +use futures::stream::TryStreamExt; +use std::{borrow::Cow, collections::HashSet, convert::Infallible, pin::Pin}; + +/// Default maximum number of redirects to follow +pub const DEFAULT_MAX_REDIRECTS: usize = 6; + +/// Some context about the request for writing response and logging +#[allow(missing_docs)] +pub struct RequestCtx<'a> { + pub url: &'a str, + pub secure: bool, +} + +const fn http_version_to_via(v: axum::http::Version) -> &'static str { + match v { + axum::http::Version::HTTP_09 => "0.9", + axum::http::Version::HTTP_10 => "1.0", + axum::http::Version::HTTP_11 => "1.1", + axum::http::Version::HTTP_2 => "2.0", + axum::http::Version::HTTP_3 => "3.0", + _ => "1.1", + } +} + +/// Trait for HTTP responses +pub trait HTTPResponse { + /// Type of the byte buffer + type Bytes: Into> + AsRef<[u8]> + Into + Send + 'static; + /// Type of body stream + type BodyStream: futures::Stream> + Send + 'static; + + /// Get some context about the request + fn request(&self) -> RequestCtx<'_>; + /// Get the status code + fn status(&self) -> u16; + /// Get a header value + fn header_one<'a>(&'a self, name: &str) -> Result>, ErrorResponse>; + /// Walk through all headers with a callback + fn header_walk bool>(&self, f: F); + /// Collect all headers + fn header_collect(&self, out: &mut HeaderMap) -> Result<(), ErrorResponse>; + /// Get the body stream + fn body(self) -> Self::BodyStream; +} + +/// Information about the incoming request +pub struct IncomingInfo { + version: axum::http::Version, + user_agent: String, + via: String, +} + +impl IncomingInfo { + /// Check if the request is potentially looping + pub fn looping(&self, self_via: &str) -> bool { + if self.user_agent.is_empty() { + return true; + } + + if self.via.contains(self_via) { + return true; + } + + // defense against upstream + if self.user_agent.contains("Misskey/") || + // Purposefully typoed + // https://raw.githubusercontent.com/backrunner/misskey-media-proxy-worker/refs/heads/main/wrangler.toml + self.user_agent.contains("Edg/119.0.2109.1") + { + return true; + } + + let split = self.via.split(", "); + + let mut seen = HashSet::new(); + for part in split { + if !seen.insert(part) { + return true; + } + } + + false + } +} + +#[axum::async_trait] +impl FromRequestParts for IncomingInfo { + type Rejection = Infallible; + async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result { + Ok(Self { + version: parts.version, + user_agent: parts + .headers + .get("user-agent") + .and_then(|v| v.to_str().ok()) + .unwrap_or_default() + .to_string(), + via: parts + .headers + .get_all("via") + .into_iter() + .fold(String::new(), |mut acc, v| { + acc.push_str(v.to_str().unwrap_or_default()); + acc.push_str(", "); + acc + }), + }) + } +} + +/// Trait for upstream clients +pub trait UpstreamClient { + /// Type of the response + type Response: HTTPResponse; + /// Create a new client + fn new(config: &FetchConfig) -> Self; + /// Request the upstream + fn request_upstream( + &self, + info: &IncomingInfo, + url: &str, + polish: bool, + secure: bool, + remaining: usize, + ) -> impl std::future::Future>; +} + +/// Reqwest client +#[cfg(feature = "reqwest")] +pub mod reqwest { + use super::{ + http_version_to_via, Cow, ErrorResponse, HTTPResponse, HeaderMap, Pin, RequestCtx, + TryStreamExt, UpstreamClient, MAX_SIZE, + }; + use ::reqwest::{redirect::Policy, ClientBuilder, Url}; + use axum::body::Bytes; + use reqwest::dns::Resolve; + use std::{sync::Arc, time::Duration}; + + /// A Safe DNS resolver that only resolves to global addresses unless the requester itself is local. + pub struct SafeResolver(); + + // pulled from https://doc.rust-lang.org/src/core/net/ip_addr.rs.html#1650 + const fn is_unicast_local_v6(ip: &std::net::Ipv6Addr) -> bool { + ip.segments()[0] & 0xfe00 == 0xfc00 + } + + const fn is_unicast_link_local_v6(ip: &std::net::Ipv6Addr) -> bool { + ip.segments()[0] & 0xffc0 == 0xfe80 + } + + impl Resolve for SafeResolver { + fn resolve(&self, name: reqwest::dns::Name) -> reqwest::dns::Resolving { + Box::pin(async move { + match tokio::net::lookup_host(format!("{}:80", name.as_str())).await { + Ok(lookup) => Ok(Box::new(lookup.filter(|addr| match addr { + std::net::SocketAddr::V4(a) => { + !a.ip().is_loopback() + && !a.ip().is_private() + && !a.ip().is_link_local() + && !a.ip().is_multicast() + && !a.ip().is_documentation() + && !a.ip().is_unspecified() + } + + std::net::SocketAddr::V6(a) => { + !a.ip().is_loopback() + && !a.ip().is_multicast() + && !a.ip().is_unspecified() + && is_unicast_local_v6(a.ip()) + && !is_unicast_link_local_v6(a.ip()) + && a.ip().to_ipv4_mapped().is_none() + } + })) + as Box + Send>), + Err(e) => { + log::error!("Failed to resolve {}: {}", name.as_str(), e); + Err(e.into()) + } + } + }) + } + } + + /// Reqwest client + pub struct ReqwestClient { + https_only: bool, + via_ident: String, + client: ::reqwest::Client, + } + + /// Response from Reqwest + pub struct ReqwestResponse(::reqwest::Response); + + impl HTTPResponse for ReqwestResponse { + type Bytes = Bytes; + type BodyStream = Pin< + Box> + Send + 'static>, + >; + + fn request(&self) -> RequestCtx<'_> { + RequestCtx { + url: self.0.url().as_str(), + secure: self.0.url().scheme().eq_ignore_ascii_case("https"), + } + } + + fn status(&self) -> u16 { + self.0.status().as_u16() + } + + fn header_one<'a>(&'a self, name: &str) -> Result>, ErrorResponse> { + self.0 + .headers() + .get(name) + .map(|v| v.to_str().map(Cow::Borrowed)) + .transpose() + .map_err(|_| ErrorResponse::upstream_protocol_error()) + } + + fn header_walk bool>(&self, mut f: F) { + for (name, value) in self.0.headers() { + if !f(name.as_str(), value.to_str().unwrap_or_default()) { + break; + } + } + } + + fn header_collect(&self, out: &mut HeaderMap) -> Result<(), ErrorResponse> { + for (name, value) in self.0.headers() { + out.insert(name, value.clone()); + } + Ok(()) + } + + fn body(self) -> Self::BodyStream { + Box::pin(self.0.bytes_stream().map_err(Into::into)) + } + } + + impl UpstreamClient for ReqwestClient { + type Response = ReqwestResponse; + fn new(config: &crate::FetchConfig) -> Self { + Self { + https_only: !config.allow_http, + via_ident: config.via.clone(), + client: ClientBuilder::new() + .https_only(!config.allow_http) + .dns_resolver(Arc::new(SafeResolver())) + .brotli(true) + .zstd(true) + .gzip(true) + .redirect(Policy::none()) + .connect_timeout(Duration::from_secs(5)) + .timeout(Duration::from_secs(15)) + .user_agent(config.user_agent.clone()) + .build() + .expect("Failed to create reqwest client"), + } + } + async fn request_upstream( + &self, + info: &super::IncomingInfo, + url: &str, + polish: bool, + mut secure: bool, + remaining: usize, + ) -> Result { + if remaining == 0 { + return Err(ErrorResponse::too_many_redirects()); + } + + if info.looping(&self.via_ident) { + return Err(ErrorResponse::loop_detected()); + } + + let url_parsed = Url::parse(url).map_err(|_| ErrorResponse::bad_url())?; + secure &= url_parsed.scheme().eq_ignore_ascii_case("https"); + + if self.https_only && !secure { + return Err(ErrorResponse::insecure_request()); + } + + let resp = self + .client + .get(url_parsed) + .header( + "via", + format!( + "{}, {} {}", + info.via, + http_version_to_via(info.version), + self.via_ident + ), + ) + .send() + .await?; + + if resp.status().is_redirection() { + if let Some(location) = resp.headers().get("location").and_then(|l| l.to_str().ok()) + { + return Box::pin(self.request_upstream( + info, + location, + polish, + secure, + remaining - 1, + )) + .await; + } + } + + if !resp.status().is_success() { + return Err(ErrorResponse::unexpected_status( + url, + resp.status().as_u16(), + )); + } + + let content_length = resp.headers().get("content-length"); + if let Some(content_length) = content_length.and_then(|c| c.to_str().ok()) { + if content_length.parse::().unwrap_or(0) > MAX_SIZE { + return Err(ErrorResponse::payload_too_large()); + } + } + + let content_type = resp.headers().get("content-type"); + if let Some(content_type) = content_type.and_then(|c| c.to_str().ok()) { + if !["image/", "video/", "audio/", "application/octet-stream"] + .iter() + .any(|prefix| { + content_type[..prefix.len().min(content_type.len())] + .eq_ignore_ascii_case(prefix) + }) + { + return Err(ErrorResponse::not_media()); + } + } + + Ok(ReqwestResponse(resp)) + } + } +} + +/// Cloudflare Workers client +#[cfg(feature = "cf-worker")] +#[cfg_attr( + not(target_arch = "wasm32"), + deprecated = "You should use reqwest instead when not on Cloudflare Workers" +)] +pub mod cf_worker { + use std::time::Duration; + + use super::{ + http_version_to_via, Cow, ErrorResponse, HTTPResponse, HeaderMap, Pin, RequestCtx, + UpstreamClient, MAX_SIZE, + }; + use axum::http::{HeaderName, HeaderValue}; + use futures::{FutureExt, Stream, TryFutureExt}; + use worker::{ + AbortController, ByteStream, CfProperties, Fetch, Headers, Method, PolishConfig, Request, + RequestInit, RequestRedirect, Url, + }; + + /// Cloudflare Workers client + pub struct CfWorkerClient { + https_only: bool, + user_agent: String, + via_ident: String, + } + + /// Wrapper for the body stream + pub struct CfBodyStreamWrapper { + stream: Option>, + } + + impl Stream for CfBodyStreamWrapper { + type Item = Result, ErrorResponse>; + + fn poll_next( + self: Pin<&mut Self>, + cx: &mut std::task::Context<'_>, + ) -> std::task::Poll> { + let this = self.get_mut(); + match this.stream.as_mut() { + Some(Ok(stream)) => match futures::ready!(std::pin::pin!(stream).poll_next(cx)) { + Some(Ok(chunk)) => std::task::Poll::Ready(Some(Ok(chunk))), + Some(Err(e)) => std::task::Poll::Ready(Some(Err(ErrorResponse::from(e)))), + None => std::task::Poll::Ready(None), + }, + Some(Err(e)) => std::task::Poll::Ready(Some(Err(e.clone()))), + None => std::task::Poll::Ready(None), + } + } + + fn size_hint(&self) -> (usize, Option) { + match self.stream { + Some(Ok(ref stream)) => stream.size_hint(), + _ => (0, None), + } + } + } + + #[allow(unsafe_code, reason = "this is never used concurrently")] + unsafe impl Send for CfBodyStreamWrapper {} + #[allow(unsafe_code, reason = "this is never used concurrently")] + unsafe impl Sync for CfBodyStreamWrapper {} + + /// Response from Cloudflare Workers + pub struct CfWorkerResponse { + resp: worker::Response, + url: Url, + } + + impl HTTPResponse for CfWorkerResponse { + type Bytes = Vec; + type BodyStream = CfBodyStreamWrapper; + + fn request(&self) -> RequestCtx<'_> { + RequestCtx { + url: self.url.as_str(), + secure: self.url.scheme().eq_ignore_ascii_case("https"), + } + } + + fn status(&self) -> u16 { + self.resp.status_code() + } + + fn header_one<'a>(&'a self, name: &str) -> Result>, ErrorResponse> { + self.resp + .headers() + .get(name) + .map(|v| v.map(|v| Cow::Owned(v.to_string()))) + .map_err(|_| ErrorResponse::upstream_protocol_error()) + } + + fn header_walk bool>(&self, mut f: F) { + for (name, value) in self.resp.headers().entries() { + if !f(&name, &value) { + break; + } + } + } + + fn header_collect(&self, out: &mut HeaderMap) -> Result<(), ErrorResponse> { + for name in self.resp.headers().keys() { + out.insert( + HeaderName::from_bytes(name.as_bytes()) + .map_err(|_| ErrorResponse::upstream_protocol_error())?, + self.resp + .headers() + .get(&name) + .map_err(|_| ErrorResponse::upstream_protocol_error())? + .map(HeaderValue::try_from) + .transpose() + .map_err(|_| ErrorResponse::upstream_protocol_error())? + .ok_or(ErrorResponse::upstream_protocol_error())?, + ); + } + Ok(()) + } + + fn body(mut self) -> Self::BodyStream { + let stream = self.resp.stream().map_err(ErrorResponse::from); + CfBodyStreamWrapper { + stream: Some(stream), + } + } + } + + impl UpstreamClient for CfWorkerClient { + type Response = CfWorkerResponse; + + fn new(config: &crate::FetchConfig) -> Self { + Self { + https_only: !config.allow_http, + user_agent: config.user_agent.clone(), + via_ident: config.via.clone(), + } + } + + async fn request_upstream( + &self, + info: &super::IncomingInfo, + url: &str, + polish: bool, + mut secure: bool, + remaining: usize, + ) -> Result { + if remaining == 0 { + return Err(ErrorResponse::too_many_redirects()); + } + + if info.looping(&self.via_ident) { + return Err(ErrorResponse::loop_detected()); + } + + let mut headers = Headers::new(); + + headers.set("user-agent", &self.user_agent)?; + headers.set( + "via", + &format!( + "{}, {} {}", + info.via, + http_version_to_via(info.version), + self.via_ident + ), + )?; + + let mut prop = CfProperties::new(); + if polish { + prop.polish = Some(PolishConfig::Lossless); + } + let mut init = RequestInit::new(); + let init = init + .with_method(Method::Get) + .with_headers(headers) + .with_cf_properties(prop) + .with_redirect(RequestRedirect::Manual); + + let url_parsed = Url::parse(url).map_err(|_| ErrorResponse::bad_url())?; + + if self.https_only && !url_parsed.scheme().eq_ignore_ascii_case("https") { + return Err(ErrorResponse::insecure_request()); + } + + secure &= url_parsed.scheme().eq_ignore_ascii_case("http"); + + let req = Request::new_with_init(url, init)?; + + let abc = AbortController::default(); + let abs = abc.signal(); + let req = Fetch::Request(req); + + let mut resp_fut = std::pin::pin!(req + .send_with_signal(&abs) + .map_err(ErrorResponse::worker_fetch_error)); + + let timeout = std::pin::pin!(worker::Delay::from(Duration::from_secs(5))); + + let resp = futures::select! { + resp = resp_fut => resp?, + _ = timeout.fuse() => return Err(ErrorResponse::upstream_timeout()), + }; + + if resp.status_code() == 301 || resp.status_code() == 302 { + if let Ok(Some(location)) = resp.headers().get("location") { + return Box::pin(self.request_upstream( + info, + &location, + polish, + secure, + remaining - 1, + )) + .await; + } + } + + if resp.status_code() < 200 || resp.status_code() >= 300 { + return Err(ErrorResponse::unexpected_status(url, resp.status_code())); + } + + let content_length = resp.headers().get("content-length").unwrap_or_default(); + if let Some(content_length) = content_length { + if content_length.parse::().unwrap_or(0) > MAX_SIZE { + return Err(ErrorResponse::payload_too_large()); + } + } + + let content_type = resp.headers().get("content-type").unwrap_or_default(); + if let Some(content_type) = content_type { + if !["image/", "video/", "audio/", "application/octet-stream"] + .iter() + .any(|prefix| { + content_type.as_str()[..prefix.len().min(content_type.len())] + .eq_ignore_ascii_case(prefix) + }) + { + return Err(ErrorResponse::not_media()); + } + } + + Ok(CfWorkerResponse { + resp, + url: url_parsed, + }) + } + } +} diff --git a/src/lib.rs b/src/lib.rs new file mode 100644 index 0000000..8239c5c --- /dev/null +++ b/src/lib.rs @@ -0,0 +1,755 @@ +#![doc = include_str!("../README.md")] +#![warn(clippy::all, clippy::pedantic)] +#![warn(unsafe_code)] +#![warn(missing_docs)] +#![allow(clippy::missing_errors_doc, clippy::module_name_repetitions)] + +use std::{ + borrow::Cow, fmt::Display, marker::PhantomData, net::SocketAddr, num::NonZero, sync::Arc, +}; + +#[cfg(feature = "governor")] +use axum::extract::ConnectInfo; +use axum::{ + body::Body, + extract::{Path, Query, State}, + http::{self, HeaderMap, StatusCode}, + response::{IntoResponse, Redirect, Response}, + routing::get, + Json, Router, +}; +use fetch::{HTTPResponse, IncomingInfo, UpstreamClient, DEFAULT_MAX_REDIRECTS}; +#[cfg(feature = "governor")] +use governor::{ + clock::SystemClock, middleware::StateInformationMiddleware, state::keyed::DashMapStateStore, + RateLimiter, +}; +use post_process::MediaResponse; +use sandbox::{NoSandbox, Sandboxing}; + +use serde::Deserialize; +#[cfg(feature = "cf-worker")] +use worker::{event, Context, Env, HttpRequest, Result as WorkerResult}; + +/// Module for delivering the final processed media to the client +pub mod deliver; +/// Module for fetching media from upstream +pub mod fetch; +/// Module for post-processing media +pub mod post_process; +/// Sandbox utilities for processing media +pub mod sandbox; +/// Stream utilities +pub mod stream; + +const MAX_SIZE: usize = 32 << 20; + +#[cfg(all(not(feature = "cf-worker"), not(feature = "reqwest")))] +compile_error!("At least one of the `cf-worker` or `reqwest` features must be enabled. hint: '--features env-local' enables everything related to local runtime"); + +#[cfg(feature = "cf-worker")] +/// The upstream client chosen by the build configuration +pub type Upstream = crate::fetch::cf_worker::CfWorkerClient; + +#[cfg(all(not(feature = "cf-worker"), feature = "reqwest"))] +/// The upstream client chosen by the build configuration +pub type Upstream = crate::fetch::reqwest::ReqwestClient; + +/// Application configuration +#[derive(Debug, Clone, serde::Deserialize)] +pub struct Config { + /// The listen address + pub listen: String, + + /// Send Cache-Control headers + pub enable_cache: bool, + + /// Index page configuration + pub index_redirect: IndexConfig, + + /// Whether to only serve media with a known safe signature + pub strictly_secure: bool, + + /// Fetch configuration + pub fetch: FetchConfig, + + /// Post-processing configuration + pub post_process: PostProcessConfig, + + #[cfg(feature = "governor")] + /// Governor configuration + pub rate_limit: RateLimitConfig, +} + +/// Governor configuration +#[cfg(feature = "governor")] +#[derive(Debug, Clone, serde::Deserialize)] +pub struct RateLimitConfig { + /// The rate limit replenish interval in milliseconds + pub replenish_every: u64, + /// The rate limit burst size + pub burst: NonZero, +} + +impl Default for Config { + fn default() -> Self { + Config { + listen: "127.0.0.1:3000".to_string(), + enable_cache: false, + fetch: FetchConfig { + allow_http: false, + via: concat!(env!("CARGO_PKG_NAME"), "/", env!("CARGO_PKG_VERSION")).to_string(), + user_agent: concat!(env!("CARGO_PKG_NAME"), "/", env!("CARGO_PKG_VERSION")) + .to_string(), + }, + index_redirect: IndexConfig::Message(format!( + "Welcome to {}", + concat!(env!("CARGO_PKG_NAME"), "/", env!("CARGO_PKG_VERSION")), + )), + strictly_secure: true, + post_process: PostProcessConfig { + enable_redirects: false, + normalization: NormalizationPolicy::Opportunistic, + allow_svg_passthrough: false, + }, + #[cfg(feature = "governor")] + rate_limit: RateLimitConfig { + replenish_every: 2000, + burst: NonZero::new(32).unwrap(), + }, + } + } +} +/// Fetch configuration +#[derive(Debug, Clone, serde::Deserialize)] +pub struct FetchConfig { + /// Whether to allow HTTP requests + pub allow_http: bool, + /// The via string to use when fetching media + pub via: String, + /// The user agent to use when fetching media + pub user_agent: String, +} + +/// Post-processing configuration +#[derive(Debug, Clone, serde::Deserialize)] +pub struct PostProcessConfig { + /// Opportunistically redirect to the original URL if the media is not modified + /// + /// Potentially leaks the user's IP address and other metadata + pub enable_redirects: bool, + /// Whether to normalize media files when the request specifically asks for a format + pub normalization: NormalizationPolicy, + /// Whether to allow SVG passthrough + /// + /// This opens up the possibility of SVG-based attacks + pub allow_svg_passthrough: bool, +} + +/// Normalization policy +#[derive(Copy, Debug, Clone, serde::Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum NormalizationPolicy { + /// Only return the requested format and fail if it can't be provided + Enforce, + /// Always make an attempt to return the requested format + Always, + /// Only return the requested format if the conversion does not result in significant changes + /// + /// This is the default + Opportunistic, + /// Ignore the requested format and return the original + Never, +} + +impl Default for NormalizationPolicy { + fn default() -> Self { + Self::Opportunistic + } +} + +#[derive(Debug, Clone, serde::Deserialize)] +#[serde(untagged)] +/// Index page configuration +pub enum IndexConfig { + /// Redirect to a URL + #[allow(missing_docs)] + Redirect { permanent: bool, url: String }, + /// Display a message + Message(String), +} + +#[cfg(any(feature = "cf-worker", feature = "reqwest"))] +/// Application Router +pub fn router(config: Config) -> Router +where + <::Response as HTTPResponse>::BodyStream: Unpin, +{ + use std::time::Duration; + + use axum::middleware; + #[cfg(feature = "governor")] + use governor::{ + clock::SystemClock, middleware::StateInformationMiddleware, Quota, RateLimiter, + }; + + let state = AppState { + #[cfg(feature = "governor")] + limiter: RateLimiter::dashmap_with_clock( + Quota::with_period(Duration::from_millis(config.rate_limit.replenish_every)) + .unwrap() + .allow_burst(config.rate_limit.burst), + SystemClock::default(), + ) + .with_middleware::(), + client: Upstream::new(&config.fetch), + sandbox: NoSandbox, + config, + }; + + let state = Arc::new(state); + + let router = Router::new() + .route("/", get(App::::index)) + .route( + "/proxy", + get(App::::proxy_without_filename) + .head(App::::proxy_without_filename) + .options(App::::proxy_options) + .route_layer(middleware::from_fn_with_state( + state.clone(), + set_cache_control, + )) + .fallback(|| async { ErrorResponse::method_not_allowed() }), + ) + .route( + "/proxy/:filename", + get(App::::proxy_with_filename) + .head(App::::proxy_with_filename) + .options(App::::proxy_options) + .route_layer(middleware::from_fn_with_state( + state.clone(), + set_cache_control, + )) + .fallback(|| async { ErrorResponse::method_not_allowed() }), + ) + .with_state(Arc::clone(&state)); + + #[cfg(feature = "governor")] + return router.route_layer(middleware::from_fn_with_state(state, rate_limit_middleware)); + #[cfg(not(feature = "governor"))] + router +} + +/// Set the Cache-Control header +#[cfg_attr(feature = "cf-worker", worker::send)] +pub async fn set_cache_control( + State(state): State>>, + request: axum::extract::Request, + next: axum::middleware::Next, +) -> Response { + let mut resp = next.run(request).await; + if state.config.enable_cache { + if resp.status() == StatusCode::OK { + let headers = resp.headers_mut(); + headers.insert( + "Cache-Control", + "public, max-age=31536000, immutable".parse().unwrap(), + ); + } else { + let headers = resp.headers_mut(); + headers.insert("Cache-Control", "max-age=300".parse().unwrap()); + } + } else { + let headers = resp.headers_mut(); + headers.insert("Cache-Control", "no-store".parse().unwrap()); + } + resp +} + +/// Middleware for rate limiting +#[cfg(feature = "governor")] +#[cfg_attr(feature = "cf-worker", worker::send)] +pub async fn rate_limit_middleware( + State(state): State>>, + ConnectInfo(addr): ConnectInfo, + request: axum::extract::Request, + next: axum::middleware::Next, +) -> Response { + use std::time::SystemTime; + + match state.limiter.check_key(&addr) { + Ok(ok) => { + let mut resp = next.run(request).await; + + let headers = resp.headers_mut(); + headers.insert( + "X-RateLimit-Limit", + #[allow(clippy::unwrap_used)] + ok.quota().burst_size().to_string().parse().unwrap(), + ); + headers.insert( + "X-RateLimit-Replenish-Interval", + state + .config + .rate_limit + .replenish_every + .to_string() + .parse() + .unwrap(), + ); + headers.insert( + "X-RateLimit-Remaining", + ok.remaining_burst_capacity().to_string().parse().unwrap(), + ); + + resp + } + Err(err) => { + log::warn!("Rate limit exceeded for {}: {}", addr, err); + let mut resp = ErrorResponse::rate_limit_exceeded().into_response(); + + let headers = resp.headers_mut(); + headers.insert( + "X-RateLimit-Limit", + #[allow(clippy::unwrap_used)] + err.quota().burst_size().to_string().parse().unwrap(), + ); + headers.insert( + "X-RateLimit-Replenish-Interval", + state + .config + .rate_limit + .replenish_every + .to_string() + .parse() + .unwrap(), + ); + headers.insert("X-RateLimit-Remaining", "0".parse().unwrap()); + headers.insert( + "Retry-After", + err.wait_time_from(SystemTime::now().into()) + .as_secs() + .to_string() + .parse() + .unwrap(), + ); + + resp + } + } +} + +#[cfg(feature = "cf-worker")] +#[event(fetch)] +async fn fetch( + req: HttpRequest, + _env: Env, + _ctx: Context, +) -> WorkerResult> { + use fetch::cf_worker::CfWorkerClient; + use tower_service::Service; + + #[cfg(all(feature = "cf-worker", target_arch = "wasm32"))] + console_error_panic_hook::set_once(); + Ok(router::(Default::default()) + .call(req) + .await?) +} + +/// Query parameters for the proxy endpoint +#[derive(Debug, Clone, serde::Deserialize)] +#[allow(missing_docs)] +pub struct ProxyQuery { + pub url: String, + #[serde(flatten)] + pub image_options: ImageOptions, +} + +fn deserialize_query_bool<'de, D>(deserializer: D) -> Result, D::Error> +where + D: serde::Deserializer<'de>, +{ + Option::::deserialize(deserializer)?.map_or(Ok(None), |s| match s.as_str() { + "true" | "True" | "TRUE" | "1" | "Y" | "yes" | "Yes" | "YES" => Ok(Some(true)), + "false" | "False" | "FALSE" | "0" | "N" | "no" | "No" | "NO" => Ok(Some(false)), + _ => Err(serde::de::Error::custom("expected 'true' or 'false'")), + }) +} + +/// Query options for the proxy endpoint +#[derive(Debug, Clone, serde::Deserialize)] +pub struct ImageOptions { + /// If set to true, always proxy the image instead of redirecting + #[serde(default, deserialize_with = "deserialize_query_bool")] + pub origin: Option, + /// See upstream specification + #[serde(default, deserialize_with = "deserialize_query_bool")] + pub avatar: Option, + /// See upstream specification + #[serde(default, deserialize_with = "deserialize_query_bool")] + pub static_: Option, + /// See upstream specification + #[serde(default, deserialize_with = "deserialize_query_bool")] + pub preview: Option, + /// See upstream specification + #[serde(default, deserialize_with = "deserialize_query_bool")] + pub badge: Option, + /// See upstream specification + #[serde(default, deserialize_with = "deserialize_query_bool")] + pub emoji: Option, + /// Set the preferred format, see [`NormalizationPolicy`] for more information + pub format: Option, +} + +impl ImageOptions { + /// Whether post-processing is requested + pub fn requested_postprocess(&self) -> bool { + self.format.is_some() + || self.avatar.is_some() + || self.static_.is_some() + || self.preview.is_some() + || self.badge.is_some() + || self.emoji.is_some() + } + /// Apply preferred format and image type from filename + pub fn apply_filename(&mut self, filename: &str) { + let mut split = filename.split('.'); + let stem = split.next().unwrap_or_default(); + let ext = split.last().unwrap_or_default(); + match ext { + "png" => self.format = Some("png".to_string()), + "jpg" | "jpeg" => self.format = Some("jpeg".to_string()), + "webp" => self.format = Some("webp".to_string()), + "tiff" => self.format = Some("tiff".to_string()), + "gif" => self.format = Some("gif".to_string()), + "bmp" => self.format = Some("bmp".to_string()), + _ => {} + } + match stem { + "avatar" => self.avatar = Some(true), + "static" => self.static_ = Some(true), + "preview" => self.preview = Some(true), + "badge" => self.badge = Some(true), + "emoji" => self.emoji = Some(true), + _ => {} + } + } +} + +#[allow( + clippy::trivially_copy_pass_by_ref, + reason = "Serde requires references" +)] +fn serialize_status(status: &StatusCode, serializer: S) -> Result +where + S: serde::Serializer, +{ + serializer.serialize_u16(status.as_u16()) +} + +#[derive(Debug, Clone, serde::Serialize)] +/// Error response +#[allow(missing_docs)] +pub struct ErrorResponse { + #[serde(serialize_with = "serialize_status")] + pub status: StatusCode, + pub message: Cow<'static, str>, +} + +impl Display for ErrorResponse { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "{}: {}", self.status, self.message) + } +} + +impl std::error::Error for ErrorResponse {} + +impl ErrorResponse { + /// Method not allowed + pub const fn method_not_allowed() -> Self { + Self { + status: StatusCode::METHOD_NOT_ALLOWED, + message: Cow::Borrowed("Method not allowed"), + } + } + /// Upstream request timed out + #[must_use] + pub const fn upstream_timeout() -> Self { + Self { + status: StatusCode::GATEWAY_TIMEOUT, + message: Cow::Borrowed("Upstream request timed out"), + } + } + /// Unexpected status code + #[must_use] + pub fn unexpected_status(url: &str, status: u16) -> Self { + Self { + status: StatusCode::BAD_GATEWAY, + message: format!("Unexpected status code when accessing {}: {}", url, status).into(), + } + } + /// Insecure request + #[must_use] + pub const fn insecure_request() -> Self { + Self { + status: StatusCode::FORBIDDEN, + message: Cow::Borrowed("HTTP requests are disabled"), + } + } + /// Rate limit exceeded + #[must_use] + pub const fn rate_limit_exceeded() -> Self { + Self { + status: StatusCode::TOO_MANY_REQUESTS, + message: Cow::Borrowed("Rate limit exceeded"), + } + } + /// Bad URL + #[must_use] + pub const fn bad_url() -> Self { + Self { + status: StatusCode::BAD_REQUEST, + message: Cow::Borrowed("Bad URL"), + } + } + /// Upstream sent invalid HTTP response + #[must_use] + pub fn upstream_protocol_error() -> Self { + Self { + status: StatusCode::BAD_GATEWAY, + message: Cow::Borrowed("Upstream protocol error"), + } + } + /// Too many redirects + #[must_use] + pub const fn too_many_redirects() -> Self { + Self { + status: StatusCode::TOO_MANY_REQUESTS, + message: Cow::Borrowed("Too many redirects"), + } + } + /// Cloudflare worker reported an error + #[cfg(feature = "cf-worker")] + #[must_use] + #[allow(clippy::needless_pass_by_value)] + pub fn worker_fetch_error(e: worker::Error) -> Self { + Self { + status: StatusCode::BAD_GATEWAY, + message: Cow::Owned(e.to_string()), + } + } + /// Requested media is too large + #[must_use] + pub const fn loop_detected() -> Self { + Self { + status: StatusCode::LOOP_DETECTED, + message: Cow::Borrowed( + "Loop detected, please make sure your User-Agent and Via headers are not being stripped", + ), + } + } + /// Received more data than allowed in one receive + #[must_use] + pub const fn mtu_buffer_overflow() -> Self { + Self { + status: StatusCode::PAYLOAD_TOO_LARGE, + message: Cow::Borrowed("MTU buffer overflow"), + } + } + /// Requested media is too large + #[must_use] + pub const fn payload_too_large() -> Self { + Self { + status: StatusCode::PAYLOAD_TOO_LARGE, + message: Cow::Borrowed("Payload too large"), + } + } + /// Post-processing failed + #[must_use] + pub const fn postprocess_failed(msg: Cow<'static, str>) -> Self { + Self { + status: StatusCode::INTERNAL_SERVER_ERROR, + message: msg, + } + } + /// Requested media is unsafe + #[must_use] + pub const fn unsafe_media() -> Self { + Self { + status: StatusCode::FORBIDDEN, + message: Cow::Borrowed("Unsafe media type"), + } + } + /// Requested media can not be processed + #[must_use] + pub const fn unsupported_media() -> Self { + Self { + status: StatusCode::UNSUPPORTED_MEDIA_TYPE, + message: Cow::Borrowed("Unsupported media type"), + } + } + /// Requested media is not a media file + #[must_use] + pub const fn not_media() -> Self { + Self { + status: StatusCode::BAD_REQUEST, + message: Cow::Borrowed("Not a media file"), + } + } +} + +#[cfg(feature = "cf-worker")] +impl From for ErrorResponse { + fn from(e: worker::Error) -> Self { + Self { + status: StatusCode::INTERNAL_SERVER_ERROR, + message: Cow::Owned(e.to_string()), + } + } +} + +#[cfg(feature = "reqwest")] +impl From for ErrorResponse { + fn from(e: reqwest::Error) -> Self { + Self { + status: StatusCode::BAD_GATEWAY, + message: Cow::Owned(e.to_string()), + } + } +} + +impl IntoResponse for ErrorResponse { + fn into_response(self) -> axum::response::Response { + (self.status, Json(self)).into_response() + } +} + +/// Application state +#[allow(unused)] +pub struct AppState { + #[cfg(feature = "governor")] + limiter: RateLimiter< + SocketAddr, + DashMapStateStore, + SystemClock, + StateInformationMiddleware, + >, + config: Config, + client: C, + sandbox: S, +} + +/// App routes +pub struct App { + _marker: PhantomData<(C, S)>, +} + +#[cfg(any(feature = "cf-worker", feature = "reqwest"))] +#[allow(clippy::unused_async)] +impl App { + /// Root endpoint + #[cfg_attr(feature = "cf-worker", worker::send)] + pub async fn index(State(state): State>>) -> Response { + match &state.clone().config.index_redirect { + IndexConfig::Redirect { permanent, ref url } => { + if *permanent { + Redirect::permanent(url).into_response() + } else { + Redirect::temporary(url).into_response() + } + } + IndexConfig::Message(msg) => (StatusCode::OK, msg.to_string()).into_response(), + } + } + + #[cfg_attr(feature = "cf-worker", worker::send)] + async fn proxy_impl<'a>( + method: http::Method, + filename: Option<&str>, + State(state): State>>, + Query(query): Query, + info: IncomingInfo, + ) -> Result + where + <::Response as HTTPResponse>::BodyStream: Unpin, + { + let mut options = query.image_options; + if let Some(filename) = filename { + options.apply_filename(&filename); + } + match method { + http::Method::GET => {} + http::Method::HEAD => { + let mut resp = Response::new(Body::empty()); + resp.headers_mut().insert( + "Content-Type", + match options.format.as_deref() { + Some("png") => "image/png", + Some("jpeg") | Some("jpg") => "image/jpeg", + Some("webp") => "image/webp", + _ => "image/webp", + } + .parse() + .unwrap(), + ); + return Ok(resp); + } + _ => { + return Err(ErrorResponse::method_not_allowed()); + } + } + + let resp = state + .client + .request_upstream(&info, &query.url, false, true, DEFAULT_MAX_REDIRECTS) + .await?; + + let media = + MediaResponse::from_upstream_response(resp, &state.config.post_process, options) + .await?; + + Ok(media.into_response()) + } + + /// Proxy endpoint without filename + #[cfg_attr(feature = "cf-worker", worker::send)] + pub async fn proxy_without_filename( + method: http::Method, + Query(query): Query, + State(state): State>>, + info: IncomingInfo, + ) -> Result + where + <::Response as HTTPResponse>::BodyStream: Unpin, + { + Self::proxy_impl(method, None, State(state), Query(query), info).await + } + + /// Proxy OPTIONS endpoint + #[cfg_attr(feature = "cf-worker", worker::send)] + pub async fn proxy_options() -> HeaderMap { + let mut hm = HeaderMap::new(); + hm.insert( + "Access-Control-Allow-Methods", + "GET, OPTIONS".parse().unwrap(), + ); + + hm + } + + /// Proxy endpoint with filename + #[cfg_attr(feature = "cf-worker", worker::send)] + pub async fn proxy_with_filename( + method: http::Method, + Path(filename): Path, + State(state): State>>, + Query(query): Query, + info: IncomingInfo, + ) -> Result + where + <::Response as HTTPResponse>::BodyStream: Unpin, + { + Self::proxy_impl(method, Some(&filename), State(state), Query(query), info).await + } +} diff --git a/src/main.rs b/src/main.rs new file mode 100644 index 0000000..4367df8 --- /dev/null +++ b/src/main.rs @@ -0,0 +1,33 @@ +use std::net::SocketAddr; + +use clap::Parser; +use yumechi_no_kuni_proxy_worker::{router, sandbox::NoSandbox, Config, Upstream}; + +#[derive(Parser)] +struct Cli { + #[clap(short, long)] + config: String, +} + +#[tokio::main] +async fn main() { + env_logger::init(); + + let cli = Cli::parse(); + let config_bytes = tokio::fs::read_to_string(&cli.config) + .await + .expect("Failed to read config file"); + let config: Config = toml::from_str(&config_bytes).expect("Failed to parse config file"); + + let listen = config.listen.clone(); + + let router = router::(config); + + let ms = router.into_make_service_with_connect_info::(); + + let listener = tokio::net::TcpListener::bind(listen) + .await + .expect("Failed to bind listener"); + + axum::serve(listener, ms).await.expect("Failed to serve"); +} diff --git a/src/post_process/image_processing.rs b/src/post_process/image_processing.rs new file mode 100644 index 0000000..e46a600 --- /dev/null +++ b/src/post_process/image_processing.rs @@ -0,0 +1,156 @@ +use std::io::Cursor; + +use image::{ + codecs::{png::PngDecoder, webp::WebPDecoder}, + AnimationDecoder, DynamicImage, GenericImageView, ImageResult, +}; + +use crate::ImageOptions; + +pub const fn clamp_width(input: (u32, u32), max_width: u32) -> (u32, u32) { + if input.0 > max_width { + (max_width, input.1 * max_width / input.0) + } else { + input + } +} + +pub const fn clamp_height(input: (u32, u32), max_height: u32) -> (u32, u32) { + if input.1 > max_height { + (input.0 * max_height / input.1, max_height) + } else { + input + } +} + +pub const fn clamp_dimensions(input: (u32, u32), max_width: u32, max_height: u32) -> (u32, u32) { + clamp_height(clamp_width(input, max_width), max_height) +} + +// All constants are following https://github.com/misskey-dev/media-proxy/blob/master/SPECIFICATION.md + +pub fn postprocess_webp_image( + data: &[u8], + opt: &ImageOptions, +) -> ImageResult> { + let dec = WebPDecoder::new(Cursor::new(data))?; + + if !dec.has_animation() { + return Ok(Some(postprocess_static_image(data, &opt)?)); + } + + if opt.static_ == Some(true) { + let first_frame = match dec.into_frames().next() { + Some(Ok(frame)) => frame, + _ => return Ok(None), + }; + return Ok(Some(process_static_image_impl( + first_frame.into_buffer().into(), + opt, + ))); + } + + Ok(None) +} + +pub fn postprocess_png_image(data: &[u8], opt: &ImageOptions) -> ImageResult> { + let dec = PngDecoder::new(Cursor::new(data))?; + + if dec.is_apng()? { + return Ok(Some(postprocess_static_image(data, &opt)?)); + } + + if opt.static_ == Some(true) { + let first_frame = match dec.apng()?.into_frames().next() { + Some(Ok(frame)) => frame, + _ => return Ok(None), + }; + return Ok(Some(process_static_image_impl( + first_frame.into_buffer().into(), + opt, + ))); + } + + Ok(None) +} + +#[derive(Debug, thiserror::Error)] +pub enum SvgPostprocessError { + #[error("Image error: {0}")] + Image(#[from] image::ImageError), + #[error("SVG error: {0}")] + Svg(#[from] resvg::usvg::Error), +} + +pub fn postprocess_svg_image( + data: &[u8], + opt: &ImageOptions, +) -> Result { + use resvg::{ + tiny_skia::Pixmap, + usvg::{self, Transform}, + }; + + let svg = usvg::Tree::from_data( + data, + &usvg::Options { + default_size: usvg::Size::from_wh(256., 256.).unwrap(), + ..Default::default() + }, + )?; + + let size = svg.size(); + let clamped = clamp_dimensions((size.width() as u32, size.height() as u32), 800, 800); + + let transform = Transform::from_scale( + clamped.0 as f32 / size.width() as f32, + clamped.1 as f32 / size.height() as f32, + ); + + let mut pm = Pixmap::new(clamped.0 as _, clamped.1 as _).unwrap(); + + resvg::render(&svg, transform, &mut pm.as_mut()); + + let image = + image::RgbaImage::from_vec(pm.width() as _, pm.height() as _, pm.data().to_vec()).unwrap(); + + Ok(process_static_image_impl( + DynamicImage::ImageRgba8(image), + &opt, + )) +} + +pub fn postprocess_static_image(data: &[u8], opt: &ImageOptions) -> ImageResult { + Ok(process_static_image_impl( + image::load_from_memory(data)?, + &opt, + )) +} + +fn process_static_image_impl(mut image: DynamicImage, opt: &ImageOptions) -> DynamicImage { + let mut out_dim = image.dimensions(); + + if opt.badge == Some(true) { + return image.resize_exact(96, 96, image::imageops::FilterType::Nearest); + } + + if opt.emoji == Some(true) { + out_dim = clamp_height(out_dim, 128); + } else if opt.avatar == Some(true) { + out_dim = clamp_height(out_dim, 320); + } + + if opt.preview == Some(true) { + out_dim = clamp_dimensions(out_dim, 200, 200); + } + + if opt.static_ == Some(true) { + out_dim = clamp_dimensions(out_dim, 498, 422); + } + + if out_dim != image.dimensions() { + image = image.resize_exact(out_dim.0, out_dim.1, image::imageops::FilterType::Lanczos3); + } + + image +} diff --git a/src/post_process/mod.rs b/src/post_process/mod.rs new file mode 100644 index 0000000..92d3770 --- /dev/null +++ b/src/post_process/mod.rs @@ -0,0 +1,469 @@ +use std::{ + io::{BufWriter, Cursor, Write}, + pin::Pin, +}; + +use axum::{ + body::{Body, Bytes}, + http::HeaderValue, + response::{IntoResponse, Redirect}, +}; +use futures::StreamExt; +use image::{ + codecs::gif::{GifEncoder, Repeat}, + Frames, ImageFormat, +}; +use sniff::SniffingStream; + +use crate::{fetch::HTTPResponse, ErrorResponse, ImageOptions, PostProcessConfig}; + +const SLURP_LIMIT: usize = 32 << 20; +const MTU_BUFFER_SIZE: usize = 8192; + +/// Module for sniffing media types and filtering out unsafe media +pub mod sniff; + +/// Module for processing images +pub mod image_processing; + +/// The kind of data passed to the client +pub enum MediaResponse<'a, R: HTTPResponse + 'a> +where + ::BodyStream: Unpin, +{ + /// Send a redirect + Redirect(String), + /// A buffer of data + #[allow(missing_docs)] + Buffer { + data: Vec, + content_type: Option, + }, + /// A static image + ProcessedStaticImage(StaticImage), + /// An animated image + ProcessedAnimatedImage(AnimatedImage<'a>), + /// Pipe the response through (video, audio, etc.)0 + PassThru(PassThru), +} + +impl<'a, R: HTTPResponse + 'a> MediaResponse<'a, R> +where + ::BodyStream: Unpin, +{ + /// Create a new media response from a redirect + pub async fn from_upstream_response( + response: R, + config: &PostProcessConfig, + options: ImageOptions, + ) -> Result { + let content_length = response + .header_one("content-length") + .ok() + .flatten() + .and_then(|cl| cl.parse::().ok()); + + let claimed_ct = response.header_one("content-type").ok().flatten(); + + // svg need special handling so we deal with it first + let is_svg = claimed_ct + .as_deref() + .map(|ct| ct.starts_with("image/svg")) + .unwrap_or(false); + + // first if the media type is not something we can handle + if !is_svg + && (!options.requested_postprocess() + || claimed_ct + .map(|ct| ct.starts_with("video/") || ct.starts_with("audio/")) + .unwrap_or(false)) + { + if config.enable_redirects + && options.origin != Some(true) + && content_length.map_or(false, |cl| cl > 1 << 20) + { + return Ok(MediaResponse::Redirect(response.request().url.to_string())); + } else { + return Ok(MediaResponse::probe_then_through(response).await?); + } + } + + let is_https = response.request().secure; + + let mut sniffer = Box::pin(SniffingStream::new(response)); + + let mut header = Cursor::new([0; MTU_BUFFER_SIZE]); + + let mut overflow = false; + while futures::future::poll_fn(|cx| { + sniffer.as_mut().poll_sniff(cx, |buf| { + if header.write_all(buf).is_err() { + overflow = true; + } + }) + }) + .await + .is_some() + {} + + if overflow { + return Err(ErrorResponse::mtu_buffer_overflow()); + } + + let result = sniffer.result_ref().cloned(); + + let mut remaining_body = Pin::into_inner(sniffer).into_remaining_body(); + + match result { + _ if is_svg => { + let header_len = header.position(); + let header = header.into_inner(); + let mut buf = Vec::with_capacity(header_len as usize); + + buf.extend_from_slice(&header[..header_len as usize]); + + while let Some(Ok(bytes)) = remaining_body.next().await { + if buf.len() + bytes.as_ref().len() > 1 << 20 { + return Err(ErrorResponse::payload_too_large()); + } + buf.extend_from_slice(bytes.as_ref()); + } + + let img = image_processing::postprocess_svg_image(&buf, &options) + .map_err(|e| ErrorResponse::postprocess_failed(e.to_string().into()))?; + + Ok(MediaResponse::ProcessedStaticImage(StaticImage { + data: img, + format: ImageFormat::WebP, + is_https, + })) + } + Some(rs) => { + if rs.maybe_unsafe { + return Err(ErrorResponse::unsafe_media()); + } + + match rs.sniffed_mime { + Some(mime) => { + if mime.starts_with("image/") { + // slurp it up + + let header_len = header.position(); + let header = header.into_inner(); + let mut buf = if let Some(cl) = content_length { + let mut ret = Vec::with_capacity(cl); + ret.extend_from_slice(&header[..header_len as usize]); + ret + } else { + header[..header_len as usize].to_vec() + }; + while let Some(Ok(bytes)) = remaining_body.next().await { + if buf.len() + bytes.as_ref().len() > SLURP_LIMIT { + return Err(ErrorResponse::payload_too_large()); + } + buf.extend_from_slice(bytes.as_ref()); + } + + let output_static_format = if options + .format + .as_deref() + .map_or(false, |f| f.eq_ignore_ascii_case("png")) + { + ImageFormat::Png + } else if options + .format + .as_deref() + .map_or(false, |f| f.eq_ignore_ascii_case("jpeg")) + { + ImageFormat::Jpeg + } else { + ImageFormat::WebP + }; + + if options.format.is_none() { + if mime.starts_with("image/png") || mime.starts_with("image/apng") { + let result = + image_processing::postprocess_png_image(&buf, &options) + .map_err(|e| { + ErrorResponse::postprocess_failed( + e.to_string().into(), + ) + })?; + + return match result { + Some(img) => { + Ok(MediaResponse::ProcessedStaticImage(StaticImage { + data: img, + format: output_static_format, + is_https, + })) + } + None => Ok(MediaResponse::Buffer { + data: buf, + content_type: Some("image/png".into()), + }), + }; + } + if mime.starts_with("image/webp") { + let result = + image_processing::postprocess_webp_image(&buf, &options) + .map_err(|e| { + ErrorResponse::postprocess_failed( + e.to_string().into(), + ) + })?; + + return match result { + Some(img) => { + Ok(MediaResponse::ProcessedStaticImage(StaticImage { + data: img, + format: output_static_format, + is_https, + })) + } + None => Ok(MediaResponse::Buffer { + data: buf, + content_type: Some("image/webp".into()), + }), + }; + } + } + + let result = image_processing::postprocess_static_image(&buf, &options) + .map_err(|e| { + ErrorResponse::postprocess_failed(e.to_string().into()) + })?; + + Ok(MediaResponse::ProcessedStaticImage(StaticImage { + data: result, + format: output_static_format, + is_https, + })) + } else { + Ok(MediaResponse::PassThru(PassThru { + header_len: header.position() as _, + header: header.into_inner(), + remaining_body, + content_type: Some(mime.to_string()), + is_https, + })) + } + } + None => Ok(MediaResponse::PassThru(PassThru { + header_len: header.position() as _, + header: header.into_inner(), + remaining_body, + content_type: None, + is_https, + })), + } + } + None => Err(ErrorResponse::unsupported_media()), + } + } +} + +impl<'a, R: HTTPResponse + 'a> IntoResponse for MediaResponse<'a, R> +where + ::BodyStream: Unpin, +{ + fn into_response(self) -> axum::response::Response { + match self { + MediaResponse::Buffer { data, content_type } => { + let mut resp = axum::http::Response::new(Body::from(data)); + if let Some(ct) = content_type { + resp.headers_mut() + .insert("content-type", HeaderValue::from_str(&ct).unwrap()); + } + resp.into_response() + } + MediaResponse::Redirect(ret) => Redirect::permanent(&ret).into_response(), + MediaResponse::ProcessedStaticImage(img) => img.into_response(), + MediaResponse::ProcessedAnimatedImage(img) => img.into_response(), + MediaResponse::PassThru(pt) => pt.into_response(), + } + } +} + +impl<'a, R: HTTPResponse + 'a> MediaResponse<'a, R> +where + ::BodyStream: Unpin, +{ + /// Probe the response for media type and then pass through + /// + /// Mainly used for the /proxy/?url= endpoint + pub async fn probe_then_through(response: R) -> Result { + let content_type = response + .header_one("content-type") + .ok() + .flatten() + .map(|ct| ct.to_string()); + let is_https = response.request().secure; + + let mut sniffed = Box::pin(sniff::SniffingStream::new(response)); + + let mut header = Cursor::new([0; MTU_BUFFER_SIZE]); + + let mut overflow = false; + + while futures::future::poll_fn(|cx| { + sniffed.as_mut().poll_sniff(cx, |buf| { + if header.write_all(buf).is_err() { + overflow = true; + } + }) + }) + .await + .is_some() + {} + + if overflow { + return Err(ErrorResponse::mtu_buffer_overflow()); + } + + let result = sniffed.result_ref().cloned(); + let body = Pin::into_inner(sniffed).into_remaining_body(); + + match result { + Some(rs) => { + if rs.maybe_unsafe { + return Err(ErrorResponse::unsafe_media()); + } + + Ok(MediaResponse::PassThru(PassThru { + header_len: header + .position() + .try_into() + .map_err(|_| ErrorResponse::payload_too_large())?, + header: header.into_inner(), + remaining_body: body, + content_type, + is_https, + })) + } + None => Err(ErrorResponse::unsupported_media()), + } + } +} + +/// Pass through the response +pub struct PassThru { + header: [u8; MTU_BUFFER_SIZE], + header_len: usize, + content_type: Option, + is_https: bool, + + remaining_body: ::BodyStream, +} + +impl IntoResponse for PassThru { + fn into_response(self) -> axum::response::Response { + if self + .content_type + .as_deref() + .map_or(false, |ct| ct.starts_with("image/svg")) + { + // reject svg pass through + return ErrorResponse::unsupported_media().into_response(); + } + + let content_type = HeaderValue::from_str( + self.content_type + .as_deref() + .unwrap_or("application/octet-stream"), + ); + let proto = if self.is_https { + HeaderValue::from_static("https") + } else { + HeaderValue::from_static("http") + }; + let header = Bytes::from(self.header[..self.header_len].to_vec()); + let header_stream = futures::stream::once(async { Ok(header) }); + let mut resp = axum::http::Response::new(Body::from_stream(header_stream.chain( + self.remaining_body.map(|res| match res { + Ok(bytes) => Ok(bytes.into()), + Err(e) => Err(e.message), + }), + ))); + resp.headers_mut().insert("x-forwarded-proto", proto); + if let Ok(ct) = content_type { + resp.headers_mut().insert("content-type", ct); + } + resp.into_response() + } +} + +/// Processed static image +pub struct StaticImage { + data: image::DynamicImage, + format: ImageFormat, + + is_https: bool, +} + +impl IntoResponse for StaticImage { + fn into_response(self) -> axum::response::Response { + let mut buf = BufWriter::new(Cursor::new(Vec::new())); + self.data.write_to(&mut buf, self.format).unwrap(); + let mut resp = + axum::http::Response::new(Body::from(buf.into_inner().unwrap().into_inner())); + + let mime = match self.format { + ImageFormat::Png => "image/png", + ImageFormat::Jpeg => "image/jpeg", + ImageFormat::Gif => "image/gif", + ImageFormat::WebP => "image/webp", + ImageFormat::Tiff => "image/tiff", + ImageFormat::Bmp => "image/bmp", + ImageFormat::Avif => "image/avif", + ImageFormat::OpenExr => "image/openexr", + ImageFormat::Ico => "image/vnd.microsoft.icon", + _ => "application/octet-stream", + }; + + resp.headers_mut().insert( + "x-forwarded-proto", + HeaderValue::from_static(if self.is_https { "https" } else { "http" }), + ); + + resp.headers_mut() + .insert("content-type", HeaderValue::from_static(mime)); + + resp.into_response() + } +} + +/// Processed animated image +pub struct AnimatedImage<'a> { + frames: Frames<'a>, + + is_https: bool, +} + +impl<'a> IntoResponse for AnimatedImage<'a> { + fn into_response(self) -> axum::response::Response { + let mut buf = BufWriter::new(Cursor::new(Vec::new())); + let mut gif = GifEncoder::new(&mut buf); + gif.set_repeat(Repeat::Infinite).unwrap(); + + if let Err(e) = gif.try_encode_frames(self.frames) { + return ErrorResponse::postprocess_failed(format!("gif encoding failed: {e}").into()) + .into_response(); + } + + drop(gif); + + let mut resp = + axum::http::Response::new(Body::from(buf.into_inner().unwrap().into_inner())); + + resp.headers_mut().insert( + "x-forwarded-proto", + HeaderValue::from_static(if self.is_https { "https" } else { "http" }), + ); + + resp.headers_mut() + .insert("content-type", HeaderValue::from_static("image/gif")); + + resp.into_response() + } +} diff --git a/src/post_process/sniff.rs b/src/post_process/sniff.rs new file mode 100644 index 0000000..0aef5f2 --- /dev/null +++ b/src/post_process/sniff.rs @@ -0,0 +1,221 @@ +use std::{ + io::{Cursor, Write}, + pin::Pin, + task::Poll, +}; + +use futures::{Stream, StreamExt}; + +use crate::{fetch::HTTPResponse, ErrorResponse}; + +// MIME sniffing data +include!(concat!(env!("OUT_DIR"), "/magic.rs")); + +/// An association between a MIME type and a file extension +#[derive(Clone)] +pub struct MIMEAssociation { + /// The MIME type + pub mime: &'static str, + /// The file extension + pub ext: &'static str, + /// Whether the file is safe to display + pub safe: bool, + /// The file signatures + signatures: &'static [FlattenedFileSignature], +} + +#[derive(Debug, Clone, PartialEq, serde::Serialize)] +struct FlattenedFileSignature(&'static [(u8, u8)]); + +impl FlattenedFileSignature { + #[inline] + fn matches(&self, test: &[u8]) -> bool { + if self.0.len() > test.len() { + return false; + } + self.0 + .iter() + .zip(test.iter()) + .all(|((sig, mask), byte)| sig & mask == *byte & mask) + } +} + +/// A stream that sniffs the MIME type of the data it receives +pub struct SniffingStream { + body: ::BodyStream, + sniff_buffer: Cursor<[u8; SNIFF_SIZE]>, + sniffed: Option, +} + +/// The result of MIME sniffing +#[derive(Debug, Clone, PartialEq, serde::Serialize)] +pub struct SniffResult { + /// The MIME type that was sniffed + pub sniffed_mime: Option<&'static str>, + /// Whether the file may be unsafe + pub maybe_unsafe: bool, +} + +impl SniffingStream { + /// Create a new `SniffingStream` from a response + pub fn new(response: R) -> Self { + Self { + body: response.body(), + sniff_buffer: Cursor::new([0; SNIFF_SIZE]), + sniffed: None, + } + } + /// Create a new `SniffingStream` from a body stream + pub fn new_from_body_stream(response: ::BodyStream) -> Self { + Self { + body: response, + sniff_buffer: Cursor::new([0; SNIFF_SIZE]), + sniffed: None, + } + } + /// Get the result of MIME sniffing + pub fn result_ref(&self) -> Option<&SniffResult> { + self.sniffed.as_ref() + } + /// Get the result of MIME sniffing + pub fn result(self) -> Option { + self.sniffed + } + /// Get the remaining body stream + pub fn into_remaining_body(self) -> ::BodyStream { + self.body + } + /// Poll the stream for MIME sniffing, writing any data consumed to a buffer + pub fn poll_sniff<'a>( + mut self: Pin<&'a mut Self>, + cx: &mut std::task::Context<'_>, + mut notify: impl FnMut(&[u8]), + ) -> Poll>> + where + ::BodyStream: Unpin, + { + #[allow(clippy::cast_possible_truncation)] + let remaining_sniff_buffer = SNIFF_SIZE - self.sniff_buffer.position() as usize; + + if remaining_sniff_buffer > 0 { + match self.body.poll_next_unpin(cx) { + Poll::Ready(None) => { + return Poll::Ready(None); + } + Poll::Ready(Some(Err(e))) => { + return Poll::Ready(Some(Err(e))); + } + Poll::Pending => { + return Poll::Pending; + } + Poll::Ready(Some(Ok(bytes))) => { + notify(bytes.as_ref()); + self.sniff_buffer.write_all(bytes.as_ref()).ok(); + + if self.sniff_buffer.position() == SNIFF_SIZE as u64 { + let cands = MAGICS.iter().filter(|assoc| { + assoc + .signatures + .iter() + .any(|sig| sig.matches(self.sniff_buffer.get_ref())) + }); + let mut all_safe = true; + let mut best_match = None; + + for cand in cands { + match best_match { + None => best_match = Some(cand), + Some(assoc) if assoc.signatures.len() < cand.signatures.len() => { + best_match = Some(cand); + } + _ => {} + } + if !cand.safe { + all_safe = false; + break; + } + } + + self.sniffed = Some(SniffResult { + sniffed_mime: best_match.map(|assoc| assoc.mime), + maybe_unsafe: !all_safe, + }); + self.sniff_buffer.set_position(0); + + return Poll::Ready(None); + } + + return Poll::Ready(Some(Ok(bytes.as_ref().len()))); + } + } + } + + Poll::Ready(None) + } +} + +impl Stream for SniffingStream +where + ::BodyStream: Unpin, +{ + type Item = Result<::Bytes, ErrorResponse>; + + fn poll_next( + mut self: Pin<&mut Self>, + cx: &mut std::task::Context<'_>, + ) -> Poll> { + #[allow(clippy::cast_possible_truncation)] + let remaining_sniff_buffer = SNIFF_SIZE - self.sniff_buffer.position() as usize; + if self.sniffed.is_none() && remaining_sniff_buffer > 0 { + match self.body.poll_next_unpin(cx) { + Poll::Ready(None) => { + return Poll::Ready(None); + } + Poll::Ready(Some(Err(e))) => { + return Poll::Ready(Some(Err(e))); + } + Poll::Pending => { + return Poll::Pending; + } + Poll::Ready(Some(Ok(bytes))) => { + #[allow(clippy::unused_io_amount)] + self.sniff_buffer.write(bytes.as_ref()).ok(); + + if self.sniff_buffer.position() == SNIFF_SIZE as u64 { + let cands = MAGICS.iter().filter(|assoc| { + assoc + .signatures + .iter() + .any(|sig| sig.matches(self.sniff_buffer.get_ref())) + }); + let mut all_safe = true; + let mut best_match = None; + + for cand in cands { + if best_match + .map_or(0, |assoc: &MIMEAssociation| assoc.signatures.len()) + < cand.signatures.len() + { + best_match = Some(cand); + } + if !cand.safe { + all_safe = false; + break; + } + } + + self.sniffed = Some(SniffResult { + sniffed_mime: best_match.map(|assoc| assoc.mime), + maybe_unsafe: !all_safe, + }); + self.sniff_buffer.set_position(0); + } + + return Poll::Ready(Some(Ok(bytes))); + } + } + } + + self.body.poll_next_unpin(cx) + } +} diff --git a/src/sandbox.rs b/src/sandbox.rs new file mode 100644 index 0000000..da9e79d --- /dev/null +++ b/src/sandbox.rs @@ -0,0 +1,103 @@ +/// A trait for setting up a thread sandboxing environment +pub trait Sandboxing { + /// The type of the guard that is returned by the setup function + type Guard; + + /// Set up the sandboxing environment + fn setup(&self, key: &[u8]) -> Self::Guard; +} + +/// A sandboxing environment that does nothing +#[derive(Default, Clone, Copy)] +pub struct NoSandbox; + +impl Sandboxing for NoSandbox { + type Guard = (); + + fn setup(&self, _key: &[u8]) -> Self::Guard {} +} + +/// A sandboxing environment that uses `AppArmor` hats +#[cfg(feature = "apparmor")] +pub mod apparmor { + use std::{ + ffi::{c_int, c_ulong, CString}, + hash::Hasher, + }; + + use rand_core::RngCore; + use siphasher::sip::SipHasher; + + use super::Sandboxing; + + #[link(name = "apparmor")] + extern "C" { + fn aa_change_hat(profile: *const i8, token: c_ulong) -> c_int; + } + + /// An `AppArmor` hat environment + pub struct AppArmorHat { + profile: CString, + hasher: SipHasher, + } + + impl AppArmorHat { + /// Create a new `AppArmor` hat environment + /// + /// # Panics + /// Panics if the profile name is invalid C string + #[must_use] + pub fn new(profile: &str) -> Self { + let cstr = std::ffi::CString::new(profile).expect("Invalid profile name"); + let mut buf = [0; 16]; + rand_core::OsRng.fill_bytes(&mut buf); + Self { + profile: cstr, + hasher: SipHasher::new_with_key(&buf), + } + } + } + + /// A 'challange' to the less secure task to prove it can still function + /// The key here is hide the token reasonably well against ROP attacks + pub struct AppArmorHandle { + hasher: SipHasher, + hash_1x: Box, + } + + impl Drop for AppArmorHandle { + #[allow(clippy::inline_always, reason = "Intentional")] + #[inline(always)] + fn drop(&mut self) { + self.hasher.write_u64(*self.hash_1x); + let hash_2x = self.hasher.finish(); + #[allow(unsafe_code)] + let ret = unsafe { aa_change_hat(std::ptr::null(), hash_2x as c_ulong) }; + + // This should never happen as aa_change_hat in return mode will kill on any failed call + // This should never happen as aa_change_hat in return mode will kill on any failed call + assert!(ret == 0, "AppArmor hat return failed: {ret}"); + } + } + + impl Sandboxing for AppArmorHat { + type Guard = AppArmorHandle; + fn setup(&self, key: &[u8]) -> Self::Guard { + let mut hash = self.hasher; + hash.write(key); + let hash_1x = hash.finish(); + let mut hash_2 = self.hasher; + hash_2.write_u64(hash_1x); + let hash_2x = hash_2.finish(); + + #[allow(unsafe_code)] + let ret = unsafe { aa_change_hat(self.profile.as_ptr(), hash_2x as c_ulong) }; + assert!(ret == 0, "AppArmor hat change failed: {ret}"); + + AppArmorHandle { + hasher: hash, + hash_1x: Box::new(hash_1x), + } + } + } +} diff --git a/src/stream.rs b/src/stream.rs new file mode 100644 index 0000000..e82c106 --- /dev/null +++ b/src/stream.rs @@ -0,0 +1,72 @@ +use std::{ + pin::Pin, + sync::atomic::{AtomicUsize, Ordering}, + task::Poll, +}; + +type Bytes = Vec; + +use futures::{Stream, StreamExt}; + +/// A stream that limits the amount of data it can receive +pub struct LimitedStream +where + T: Stream> + 'static, +{ + ended: bool, + stream: Pin>, + limit: AtomicUsize, +} + +impl LimitedStream +where + T: Stream> + 'static, +{ + /// Create a new `LimitedStream` with a given stream and limit + pub fn new(stream: T, limit: usize) -> Self { + Self { + ended: false, + stream: Box::pin(stream), + limit: AtomicUsize::new(limit), + } + } +} + +impl Stream for LimitedStream +where + T: Stream> + 'static, +{ + type Item = Result>; + + fn poll_next( + mut self: Pin<&mut Self>, + cx: &mut std::task::Context<'_>, + ) -> Poll> { + match self.limit.load(Ordering::SeqCst) { + 0 => { + if self.ended { + Poll::Ready(None) + } else { + self.ended = true; + Poll::Ready(Some(Err(None))) + } + } + remaining_len => { + let p = self.stream.poll_next_unpin(cx); + match p { + Poll::Ready(Some(Ok(mut data))) => { + if data.len() > remaining_len { + self.limit.store(0, Ordering::SeqCst); + data.truncate(remaining_len); + Poll::Ready(Some(Ok(data))) + } else { + self.limit.fetch_sub(data.len(), Ordering::SeqCst); + Poll::Ready(Some(Ok(data))) + } + } + _ => p.map_err(|e| Some(e)), + } + } + } + } +} diff --git a/submodules/file b/submodules/file new file mode 160000 index 0000000..87ed2d4 --- /dev/null +++ b/submodules/file @@ -0,0 +1 @@ +Subproject commit 87ed2d47d61450bd1ee3f25d568c26116810437c diff --git a/wrangler.toml b/wrangler.toml new file mode 100644 index 0000000..9e9b855 --- /dev/null +++ b/wrangler.toml @@ -0,0 +1,6 @@ +name = "yumechi-no-kuni-proxy-worker" +main = "build/worker/shim.mjs" +compatibility_date = "2024-11-11" + +[build] +command = "cargo install -q worker-build && worker-build --release --features cf-worker" \ No newline at end of file