snapshot of https://github.com/tauri-apps/plugins-workspace.git (v2, 2026-09-23; blobs > 131072B omitted)
Some checks failed
integration tests / run-integration-tests (windows-latest) (push) Has been cancelled
Test Rust / test (push) Has been cancelled
test plugins e2e (mobile) / ios (push) Has been cancelled
test plugins e2e / test (map[name:Windows os:windows-latest]) (push) Has been cancelled
test plugins e2e / test (map[name:macOS os:macos-latest]) (push) Has been cancelled
integration tests / run-integration-tests (macos-latest) (push) Has been cancelled
version or publish / version-or-publish (push) Failing after 0s
integration tests / run-integration-tests (ubuntu-22.04) (push) Failing after 0s
Lint JavaScript / eslint (push) Failing after 0s
Sync / sync-to-mirrors (push) Failing after 0s
test plugins e2e (mobile) / android (push) Failing after 0s
test plugins e2e / test (map[name:Linux os:ubuntu-latest]) (push) Failing after 0s
Test Rust / changes (push) Failing after 0s
Lint Rust / changes (push) Failing after 0s
Lint Rust / clippy (push) Has been skipped
Audit Rust / audit-rust (push) Failing after 1s
Audit JavaScript / audit-js (push) Failing after 1s

This commit is contained in:
upstream-mirror
2026-09-23 17:17:10 +05:00
commit 9ad64ec987
1469 changed files with 115067 additions and 0 deletions

352
plugins/http/CHANGELOG.md Normal file
View File

@@ -0,0 +1,352 @@
# Changelog
## [2.7.0]
- [`1198a524`](https://github.com/tauri-apps/plugins-workspace/commit/1198a524b710abf2abeb1d9bd7b252402d26ca6d) **Security:** Added the `scopeRedirects` plugin configuration option, which checks the URL scope on every hop of a redirect chain instead of only on the URL requested by the frontend. Without it, a server on an allowed origin can redirect the request to any other origin - including `localhost` services, internal hosts and cloud metadata endpoints - and the plugin follows it, returning the response to the webview.
```json
{
"plugins": {
"http": {
"scopeRedirects": true
}
}
}
```
It is opt-in because a redirect to a URL that is not allowed by the scope now fails with `url not allowed on the configured scope` instead of being followed, so applications that rely on being redirected outside of their scope must add the redirect target to the scope. **This will become the default in v3.**
Note that `tauri_plugin_http::init()` now returns `TauriPlugin<R, Option<Config>>` instead of `TauriPlugin<R>`.
## [2.6.1]
- [`a21555dd`](https://github.com/tauri-apps/plugins-workspace/commit/a21555ddd2eaadfed23848912fe2802c2ba7579e) ([#3566](https://github.com/tauri-apps/plugins-workspace/pull/3566) by [@followdarko](https://github.com/tauri-apps/plugins-workspace/../../followdarko)) Fix unhandled promise rejections on every `fetch` teardown: the request/body cleanup commands were fired as floating promises, and releasing an already-released resource rejects with `The resource id N is invalid.`. `dropBody` is now idempotent and both cleanup calls handle their own rejection.
## [2.6.0]
- [`f8053e65`](https://github.com/tauri-apps/plugins-workspace/commit/f8053e659e4ccd85c1f52833411ff8417cbc5e69) ([#3527](https://github.com/tauri-apps/plugins-workspace/pull/3527) by [@Legend-Master](https://github.com/tauri-apps/plugins-workspace/../../Legend-Master)) Documented Cargo feature flags in each plugin's crate-level documentation.
- [`19fb3926`](https://github.com/tauri-apps/plugins-workspace/commit/19fb3926fd24d95371bc3a7593256861df406436) ([#3528](https://github.com/tauri-apps/plugins-workspace/pull/3528) by [@Legend-Master](https://github.com/tauri-apps/plugins-workspace/../../Legend-Master)) Added `system-proxy` feature to replace the old `macos-system-configuration` feature flag to match the new reqwest API.
### Dependencies
- Upgraded to `fs-js@2.5.2`
## \[2.5.9]
### Dependencies
- Upgraded to `fs-js@2.5.1`
## \[2.5.8]
- [`29712892`](https://github.com/tauri-apps/plugins-workspace/commit/29712892526cfc2d35c9002e0a56925084ae1b73) ([#3252](https://github.com/tauri-apps/plugins-workspace/pull/3252) by [@NVolcz](https://github.com/tauri-apps/plugins-workspace/../../NVolcz)) Correct Response header initialization to support cloning and ensure Set-Cookie visibility.
### Dependencies
- Upgraded to `fs-js@2.5.0`
## \[2.5.7]
- [`61e9b0ab`](https://github.com/tauri-apps/plugins-workspace/commit/61e9b0ab64c56cc5f7a5cb3b92b386671da6e0a2) ([#3228](https://github.com/tauri-apps/plugins-workspace/pull/3228)) Cleanup resource when the returned `ReadableStream.cancel` is called to avoid memory leaks
## \[2.5.6]
- [`b1dbee2c`](https://github.com/tauri-apps/plugins-workspace/commit/b1dbee2c55c1aa7b64732c4cc9f8cb20520b8666) ([#3210](https://github.com/tauri-apps/plugins-workspace/pull/3210) by [@FabianLars](https://github.com/tauri-apps/plugins-workspace/../../FabianLars)) Fixed an issue that caused the Origin header to always be `null` on macOS, iOS and Linux.
## \[2.5.5]
- [`e8915f17`](https://github.com/tauri-apps/plugins-workspace/commit/e8915f17e418138f0776870353cd6ce7254b0473) ([#2562](https://github.com/tauri-apps/plugins-workspace/pull/2562) by [@amrbashir](https://github.com/tauri-apps/plugins-workspace/../../amrbashir)) Fix aborting a request in the middle of a streaming response.
### Dependencies
- Upgraded to `fs-js@2.4.5`
## \[2.5.4]
- [`93426f85`](https://github.com/tauri-apps/plugins-workspace/commit/93426f85120f49beb9f40222bff45185a32d54a9) Fixed an issue that caused docs.rs builds to fail. No user facing changes.
### Dependencies
- Upgraded to `fs-js@2.4.4`
## \[2.5.3]
### Dependencies
- Upgraded to `fs-js@2.4.3`
## \[2.5.2]
### Dependencies
- Upgraded to `fs-js@2.4.2`
## \[2.5.1]
### Dependencies
- Upgraded to `fs-js@2.4.1`
## \[2.5.0]
- [`f209b2f2`](https://github.com/tauri-apps/plugins-workspace/commit/f209b2f23cb29133c97ad5961fb46ef794dbe063) ([#2804](https://github.com/tauri-apps/plugins-workspace/pull/2804) by [@renovate](https://github.com/tauri-apps/plugins-workspace/../../renovate)) Updated tauri to 2.6
### Dependencies
- Upgraded to `fs-js@2.4.0`
## \[2.4.4]
- [`ff384cba`](https://github.com/tauri-apps/plugins-workspace/commit/ff384cbabe82ae715798a4ee49fd07ffcfbcdb5d) ([#2636](https://github.com/tauri-apps/plugins-workspace/pull/2636) by [@asomethings](https://github.com/tauri-apps/plugins-workspace/../../asomethings)) Properly handle responses with status code 204.
### Dependencies
- Upgraded to `fs-js@2.3.0`
## \[2.4.3]
- [`37c0477a`](https://github.com/tauri-apps/plugins-workspace/commit/37c0477afe926d326573f1827045875ce8bf8187) ([#2561](https://github.com/tauri-apps/plugins-workspace/pull/2561)) Add `zstd` cargo feature flag to enable `reqwest/zstd` flag.
- [`9ebbfb2e`](https://github.com/tauri-apps/plugins-workspace/commit/9ebbfb2e3ccef8e0f277a0c02fe6b399b41feeb6) ([#1978](https://github.com/tauri-apps/plugins-workspace/pull/1978)) Persist cookies to disk and load it on next app start.
### Dependencies
- Upgraded to `fs-js@2.2.1`
## \[2.4.2]
- [`a15eedf3`](https://github.com/tauri-apps/plugins-workspace/commit/a15eedf37854344f7ffbcb0d373d848563817011) ([#2535](https://github.com/tauri-apps/plugins-workspace/pull/2535) by [@amrbashir](https://github.com/tauri-apps/plugins-workspace/../../amrbashir)) Fix `fetch` occasionally throwing an error due to trying to close the underline stream twice.
## \[2.4.1]
- [`d3183aa9`](https://github.com/tauri-apps/plugins-workspace/commit/d3183aa99da7ca67e627394132ddeb3b85ccef06) ([#2522](https://github.com/tauri-apps/plugins-workspace/pull/2522) by [@adrieljss](https://github.com/tauri-apps/plugins-workspace/../../adrieljss)) Fix `fetch` blocking until the whole response is read even if it was a streaming response.
## \[2.4.0]
- [`cb38f54f`](https://github.com/tauri-apps/plugins-workspace/commit/cb38f54f4a4ef30995283cd82166c62da17bac44) ([#2479](https://github.com/tauri-apps/plugins-workspace/pull/2479) by [@adrieljss](https://github.com/tauri-apps/plugins-workspace/../../adrieljss)) Add stream support for HTTP stream responses.
## \[2.3.0]
- [`10513649`](https://github.com/tauri-apps/plugins-workspace/commit/105136494c5a5bf4b1f1cc06cc71815412d17ec8) ([#2204](https://github.com/tauri-apps/plugins-workspace/pull/2204) by [@RickeyWard](https://github.com/tauri-apps/plugins-workspace/../../RickeyWard)) Add `dangerous-settings` feature flag and new JS `danger` option to disable tls hostname/certificate validation.
## \[2.2.0]
- [`3a79266b`](https://github.com/tauri-apps/plugins-workspace/commit/3a79266b8cf96a55b1ae6339d725567d45a44b1d) ([#2173](https://github.com/tauri-apps/plugins-workspace/pull/2173) by [@FabianLars](https://github.com/tauri-apps/plugins-workspace/../../FabianLars)) Bumped all plugins to `v2.2.0`. From now, the versions for the Rust and JavaScript packages of each plugin will be in sync with each other.
### Dependencies
- Upgraded to `fs@2.2.0`
## \[2.0.2]
### Dependencies
- Upgraded to `fs-js@2.0.4`
## \[2.0.4]
- [`a3b553dd`](https://github.com/tauri-apps/plugins-workspace/commit/a3b553ddb403771aa699362c4e69a064b7731da5) ([#2079](https://github.com/tauri-apps/plugins-workspace/pull/2079) by [@amrbashir](https://github.com/tauri-apps/plugins-workspace/../../amrbashir)) Add tracing logs for requestes and responses behind `tracing` feature flag.
### Dependencies
- Upgraded to `fs@2.1.0`
## \[2.0.3]
### Dependencies
- Upgraded to `fs@2.0.3`
## \[2.0.1]
- [`cfd48b3b`](https://github.com/tauri-apps/plugins-workspace/commit/cfd48b3b2ec0fccfc162197518694ed59ceda22c) ([#1941](https://github.com/tauri-apps/plugins-workspace/pull/1941) by [@Nipsuli](https://github.com/tauri-apps/plugins-workspace/../../Nipsuli)) Allow skipping sending `Origin` header in HTTP requests by setting `Origin` header to an empty string when calling `fetch`.
- [`9b2840db`](https://github.com/tauri-apps/plugins-workspace/commit/9b2840db9464cf08db75806270e4441f0af81e5d) ([#1884](https://github.com/tauri-apps/plugins-workspace/pull/1884) by [@amrbashir](https://github.com/tauri-apps/plugins-workspace/../../amrbashir)) Retain headers order.
## \[2.0.1]
- [`a1a82208`](https://github.com/tauri-apps/plugins-workspace/commit/a1a82208ed4ab87f83310be0dc95428aec9ab241) ([#1873](https://github.com/tauri-apps/plugins-workspace/pull/1873) by [@lucasfernog](https://github.com/tauri-apps/plugins-workspace/../../lucasfernog)) Downgrade MSRV to 1.77.2 to support Windows 7.
### Dependencies
- Upgraded to `fs@2.0.1`
## \[2.0.0]
- [`e2c4dfb6`](https://github.com/tauri-apps/plugins-workspace/commit/e2c4dfb6af43e5dd8d9ceba232c315f5febd55c1) Update to tauri v2 stable release.
### Dependencies
- Upgraded to `fs@2.0.0`
## \[2.0.0-rc.6]
### Dependencies
- Upgraded to `fs@2.0.0-rc.6`
## \[2.0.0-rc.5]
### Dependencies
- Upgraded to `fs@2.0.0-rc.5`
## \[2.0.0-rc.4]
### Dependencies
- Upgraded to `fs@2.0.0-rc.4`
## \[2.0.0-rc.3]
### Dependencies
- Upgraded to `fs@2.0.0-rc.3`
## \[2.0.0-rc.2]
### Dependencies
- Upgraded to `fs@2.0.0-rc.2`
## \[2.0.0-rc.2]
- [`e2e97db5`](https://github.com/tauri-apps/plugins-workspace/commit/e2e97db51983267f5be84d4f6f0278d58834d1f5) ([#1701](https://github.com/tauri-apps/plugins-workspace/pull/1701) by [@lucasfernog](https://github.com/tauri-apps/plugins-workspace/../../lucasfernog)) Update to tauri 2.0.0-rc.8
## \[2.0.0-rc.1]
- [`84f8bd5e`](https://github.com/tauri-apps/plugins-workspace/commit/84f8bd5e1ef22e664267380b5bbf756ebc5389c3) ([#1662](https://github.com/tauri-apps/plugins-workspace/pull/1662) by [@twlite](https://github.com/tauri-apps/plugins-workspace/../../twlite)) Fixed an issue with abort signal not aborting the fetch request.
## \[2.0.0-rc.0]
- [`9887d1`](https://github.com/tauri-apps/plugins-workspace/commit/9887d14bd0e971c4c0f5c1188fc4005d3fc2e29e) Update to tauri RC.
### Dependencies
- Upgraded to `fs@2.0.0-rc.0`
## \[2.0.0-beta.9]
- [`99d6ac0f`](https://github.com/tauri-apps/plugins-workspace/commit/99d6ac0f9506a6a4a1aa59c728157190a7441af6) ([#1606](https://github.com/tauri-apps/plugins-workspace/pull/1606) by [@FabianLars](https://github.com/tauri-apps/plugins-workspace/../../FabianLars)) The JS packages now specify the *minimum* `@tauri-apps/api` version instead of a single exact version.
- [`6de87966`](https://github.com/tauri-apps/plugins-workspace/commit/6de87966ecc00ad9d91c25be452f1f46bd2b7e1f) ([#1597](https://github.com/tauri-apps/plugins-workspace/pull/1597) by [@Legend-Master](https://github.com/tauri-apps/plugins-workspace/../../Legend-Master)) Update to tauri beta.25.
## \[2.0.0-beta.8]
- [`ac9a25cc`](https://github.com/tauri-apps/plugins-workspace/commit/ac9a25cc12ee2b325f00212ba74316da3369bde5) ([#1395](https://github.com/tauri-apps/plugins-workspace/pull/1395) by [@amrbashir](https://github.com/tauri-apps/plugins-workspace/../../amrbashir)) Fix cancelling requests using `AbortSignal`.
- [`a6654932`](https://github.com/tauri-apps/plugins-workspace/commit/a66549329c60dea35e3a06a38c357e368c9053a1) ([#1526](https://github.com/tauri-apps/plugins-workspace/pull/1526) by [@amrbashir](https://github.com/tauri-apps/plugins-workspace/../../amrbashir)) Fix missing `Set-Cookie` headers in the response which meant `request.headers.getSetCookie()` always returned empty array.
- [`22a17980`](https://github.com/tauri-apps/plugins-workspace/commit/22a17980ff4f6f8c40adb1b8f4ffc6dae2fe7e30) ([#1537](https://github.com/tauri-apps/plugins-workspace/pull/1537) by [@lucasfernog](https://github.com/tauri-apps/plugins-workspace/../../lucasfernog)) Update to tauri beta.24.
## \[2.0.0-beta.7]
- [`76daee7a`](https://github.com/tauri-apps/plugins-workspace/commit/76daee7aafece34de3092c86e531cf9eb1138989) ([#1512](https://github.com/tauri-apps/plugins-workspace/pull/1512) by [@renovate](https://github.com/tauri-apps/plugins-workspace/../../renovate)) Update to tauri beta.23.
## \[2.0.0-beta.6]
- [`0f739dbc`](https://github.com/tauri-apps/plugins-workspace/commit/0f739dbc483a1f091977cbe575c3862fd39f8cf1) ([#1392](https://github.com/tauri-apps/plugins-workspace/pull/1392) by [@amrbashir](https://github.com/tauri-apps/plugins-workspace/../../amrbashir)) Allow setting `Origin` header when `unsafe-headers` feature flag is active.
## \[2.0.0-beta.5]
- [`9013854f`](https://github.com/tauri-apps/plugins-workspace/commit/9013854f42a49a230b9dbb9d02774765528a923f)([#1382](https://github.com/tauri-apps/plugins-workspace/pull/1382)) Update to tauri beta.22.
## \[2.0.0-beta.4]
- [`9d7ae45b`](https://github.com/tauri-apps/plugins-workspace/commit/9d7ae45b0edf9b22c73e7d7c413a784bb35c3d77)([#1354](https://github.com/tauri-apps/plugins-workspace/pull/1354)) Include headers created by browser if not declared by user, which fixes missing headers like `Content-Type` when using `FormData`.
- [`430bd6f4`](https://github.com/tauri-apps/plugins-workspace/commit/430bd6f4f379bee5d232ae6b098ae131db7f178a)([#1363](https://github.com/tauri-apps/plugins-workspace/pull/1363)) Update to tauri beta.20.
## \[2.0.0-beta.3]
- [`bd1ed590`](https://github.com/tauri-apps/plugins-workspace/commit/bd1ed5903ffcce5500310dac1e59e8c67674ef1e)([#1237](https://github.com/tauri-apps/plugins-workspace/pull/1237)) Update to tauri beta.17.
## \[2.0.0-beta.6]
### Dependencies
- Upgraded to `fs@2.0.0-beta.6`
## \[2.0.0-beta.5]
- [`500ff10`](https://github.com/tauri-apps/plugins-workspace/commit/500ff10fbd89fdfc73caf9d153029dad567b4ff1)([#1166](https://github.com/tauri-apps/plugins-workspace/pull/1166)) **Breaking change:** Removed the `default-tls` feature flag. The `rustls-tls`, `http2`, `macos-system-configuration`, and `charset` feature flags are now enabled by default.
- [`e3d41f4`](https://github.com/tauri-apps/plugins-workspace/commit/e3d41f4011bd3ea3ce281bb38bbe31d3709f8e0f)([#1191](https://github.com/tauri-apps/plugins-workspace/pull/1191)) Internally use the webview scoped resources table instead of the app one, so other webviews can't access other webviews resources.
- [`7e2fcc5`](https://github.com/tauri-apps/plugins-workspace/commit/7e2fcc5e74df7c3c718e40f75bfb0eafc7d69d8d)([#1146](https://github.com/tauri-apps/plugins-workspace/pull/1146)) Update dependencies to align with tauri 2.0.0-beta.14.
- [`e3d41f4`](https://github.com/tauri-apps/plugins-workspace/commit/e3d41f4011bd3ea3ce281bb38bbe31d3709f8e0f)([#1191](https://github.com/tauri-apps/plugins-workspace/pull/1191)) Update for tauri 2.0.0-beta.15.
### Dependencies
- Upgraded to `fs@2.0.0-beta.5`
## \[2.0.0-beta.4]
### Dependencies
- Upgraded to `fs@2.0.0-beta.4`
## \[2.0.0-beta.3]
- [`c873e4d`](https://github.com/tauri-apps/plugins-workspace/commit/c873e4d6c74e759742f7c9a88e35cff10a75122a)([#1059](https://github.com/tauri-apps/plugins-workspace/pull/1059)) Fixes scope not allowing subpaths, query parameters and hash when those values are empty.
- [`a04ea2f`](https://github.com/tauri-apps/plugins-workspace/commit/a04ea2f38294d5a3987578283badc8eec87a7752)([#1071](https://github.com/tauri-apps/plugins-workspace/pull/1071)) The global API script is now only added to the binary when the `withGlobalTauri` config is true.
- [`753c7be`](https://github.com/tauri-apps/plugins-workspace/commit/753c7be0a6a78121d2e88ea0efc3040580c885b4)([#1050](https://github.com/tauri-apps/plugins-workspace/pull/1050)) Add `unsafe-headers` cargo feature flag to allow using [forbidden headers](https://fetch.spec.whatwg.org/#terminology-headers).
### Dependencies
- Upgraded to `fs@2.0.0-beta.3`
## \[2.0.0-beta.2]
- [`ae56b13`](https://github.com/tauri-apps/plugins-workspace/commit/ae56b13a4d49dbf922b8a0fbb0d557bb63c1d72b)([#983](https://github.com/tauri-apps/plugins-workspace/pull/983)) Allow `User-Agent` header to be set.
- [`99bea25`](https://github.com/tauri-apps/plugins-workspace/commit/99bea2559c2c0648c2519c50a18cd124dacef57b)([#1005](https://github.com/tauri-apps/plugins-workspace/pull/1005)) Update to tauri beta.8.
## \[2.0.0-beta.1]
- [`569defb`](https://github.com/tauri-apps/plugins-workspace/commit/569defbe9492e38938554bb7bdc1be9151456d21) Update to tauri beta.4.
## \[2.0.0-beta.0]
- [`d198c01`](https://github.com/tauri-apps/plugins-workspace/commit/d198c014863ee260cb0de88a14b7fc4356ef7474)([#862](https://github.com/tauri-apps/plugins-workspace/pull/862)) Update to tauri beta.
- [`1a34720`](https://github.com/tauri-apps/plugins-workspace/commit/1a347203a54eccc954749d11c4ee81fdd9a0cde7)([#858](https://github.com/tauri-apps/plugins-workspace/pull/858)) Fix http fetch client option init with parameter `connectTimeout`
## \[2.0.0-alpha.9]
### Dependencies
- Upgraded to `fs@2.0.0-alpha.7`
## \[2.0.0-alpha.6]
- [`bfa87da`](https://github.com/tauri-apps/plugins-workspace/commit/bfa87da848f9f1da2abae3354eed632881eddf11)([#824](https://github.com/tauri-apps/plugins-workspace/pull/824)) Add `proxy` field to `fetch` options to configure proxy.
## \[2.0.0-alpha.5]
- [`387c2f9`](https://github.com/tauri-apps/plugins-workspace/commit/387c2f9e0ce4c75c07ffa3fd76391a25b58f5daf)([#802](https://github.com/tauri-apps/plugins-workspace/pull/802)) Update to @tauri-apps/api v2.0.0-alpha.13.
## \[2.0.0-alpha.4]
- [`387c2f9`](https://github.com/tauri-apps/plugins-workspace/commit/387c2f9e0ce4c75c07ffa3fd76391a25b58f5daf)([#802](https://github.com/tauri-apps/plugins-workspace/pull/802)) Update to @tauri-apps/api v2.0.0-alpha.12.
## \[2.0.0-alpha.3]
- [`e438e0a`](https://github.com/tauri-apps/plugins-workspace/commit/e438e0a62d4b430a5159f05f13ecd397dd891a0d)([#676](https://github.com/tauri-apps/plugins-workspace/pull/676)) Update to @tauri-apps/api v2.0.0-alpha.11.
## \[2.0.0-alpha.2]
- [`5c13736`](https://github.com/tauri-apps/plugins-workspace/commit/5c137365c60790e8d4037d449e8237aa3fffdab0)([#673](https://github.com/tauri-apps/plugins-workspace/pull/673)) Update to @tauri-apps/api v2.0.0-alpha.9.
## \[2.0.0-alpha.3]
- [`2cb0fa7`](https://github.com/tauri-apps/plugins-workspace/commit/2cb0fa719b8b1f5ac07dada93520dbbcf637d64c)([#587](https://github.com/tauri-apps/plugins-workspace/pull/587)) Remove `cmd` property which breaks invoke call.
- [`4e2cef9`](https://github.com/tauri-apps/plugins-workspace/commit/4e2cef9b702bbbb9cf4ee17de50791cb21f1b2a4)([#593](https://github.com/tauri-apps/plugins-workspace/pull/593)) Update to alpha.12.
### Dependencies
- Upgraded to `fs@2.0.0-alpha.2`
## \[2.0.0-alpha.2]
- [`aec17a9`](https://github.com/tauri-apps/plugins-workspace/commit/aec17a90fc365774c70c4876b94a899416120e26)([#558](https://github.com/tauri-apps/plugins-workspace/pull/558)) Improve response performance by using the new IPC streaming data.
## \[2.0.0-alpha.1]
- [`7d9df72`](https://github.com/tauri-apps/plugins-workspace/commit/7d9df7297a221a64d9de945ffc2cd8313d3104dc)([#428](https://github.com/tauri-apps/plugins-workspace/pull/428)) Multipart requests are now handled in JavaScript by the `Request` JavaScript class so you just need to use a `FormData` body and not set the content-type header to `multipart/form-data`. `application/x-www-form-urlencoded` requests must be done manually.
- [`7d9df72`](https://github.com/tauri-apps/plugins-workspace/commit/7d9df7297a221a64d9de945ffc2cd8313d3104dc)([#428](https://github.com/tauri-apps/plugins-workspace/pull/428)) The http plugin has been rewritten from scratch and now only exposes a `fetch` function in Javascript and Re-exports `reqwest` crate in Rust. The new `fetch` method tries to be as close and compliant to the `fetch` Web API as possible.
- [`d74fc0a`](https://github.com/tauri-apps/plugins-workspace/commit/d74fc0a097996e90a37be8f57d50b7d1f6ca616f)([#555](https://github.com/tauri-apps/plugins-workspace/pull/555)) Update to alpha.11.
## \[2.0.0-alpha.0]
- [`717ae67`](https://github.com/tauri-apps/plugins-workspace/commit/717ae670978feb4492fac1f295998b93f2b9347f)([#371](https://github.com/tauri-apps/plugins-workspace/pull/371)) First v2 alpha release!

80
plugins/http/Cargo.toml Normal file
View File

@@ -0,0 +1,80 @@
[package]
name = "tauri-plugin-http"
version = "2.7.0"
description = "Access an HTTP client written in Rust."
edition = { workspace = true }
authors = { workspace = true }
license = { workspace = true }
rust-version = { workspace = true }
repository = { workspace = true }
links = "tauri-plugin-http"
exclude = [
"/banner.png",
"/guest-js",
"/package.json",
"/rollup.config.js",
"/tsconfig.json",
]
[package.metadata.platforms.support]
windows = { level = "full", notes = "" }
linux = { level = "full", notes = "" }
macos = { level = "full", notes = "" }
android = { level = "full", notes = "" }
ios = { level = "full", notes = "" }
[build-dependencies]
tauri-plugin = { workspace = true, features = ["build"] }
schemars = { workspace = true }
serde = { workspace = true }
url = { workspace = true }
urlpattern = "0.3"
regex = "1"
[dependencies]
serde = { workspace = true }
serde_json = { workspace = true }
tauri = { workspace = true }
thiserror = { workspace = true }
tokio = { version = "1", features = ["sync", "macros"] }
tauri-plugin-fs = { path = "../fs", version = "2.5.2" }
urlpattern = "0.3"
regex = "1"
http = "1"
# 0.12.16 is when `system-proxy` was added
reqwest = { version = "0.12.16", default-features = false }
url = { workspace = true }
data-url = "0.3"
cookie_store = { version = "0.22", optional = true, features = ["serde"] }
bytes = { version = "1.9", optional = true }
tracing = { workspace = true, optional = true }
[features]
default = ["rustls-tls", "http2", "charset", "system-proxy", "cookies"]
multipart = ["reqwest/multipart"]
json = ["reqwest/json"]
stream = ["reqwest/stream"]
native-tls = ["reqwest/native-tls"]
native-tls-vendored = ["reqwest/native-tls-vendored"]
native-tls-alpn = ["reqwest/native-tls-alpn"]
rustls-tls = ["reqwest/rustls-tls"]
rustls-tls-manual-roots = ["reqwest/rustls-tls-manual-roots"]
rustls-tls-webpki-roots = ["reqwest/rustls-tls-webpki-roots"]
rustls-tls-native-roots = ["reqwest/rustls-tls-native-roots"]
blocking = ["reqwest/blocking"]
cookies = ["reqwest/cookies", "dep:cookie_store", "dep:bytes"]
gzip = ["reqwest/gzip"]
brotli = ["reqwest/brotli"]
deflate = ["reqwest/deflate"]
zstd = ["reqwest/zstd"]
trust-dns = ["reqwest/trust-dns"]
socks = ["reqwest/socks"]
http2 = ["reqwest/http2"]
charset = ["reqwest/charset"]
# Deprecated, switch to system-proxy
macos-system-configuration = ["reqwest/macos-system-configuration"]
system-proxy = ["reqwest/system-proxy"]
unsafe-headers = []
tracing = ["dep:tracing"]
dangerous-settings = []

20
plugins/http/LICENSE.spdx Normal file
View File

@@ -0,0 +1,20 @@
SPDXVersion: SPDX-2.1
DataLicense: CC0-1.0
PackageName: tauri
DataFormat: SPDXRef-1
PackageSupplier: Organization: The Tauri Programme in the Commons Conservancy
PackageHomePage: https://tauri.app
PackageLicenseDeclared: Apache-2.0
PackageLicenseDeclared: MIT
PackageCopyrightText: 2019-2022, The Tauri Programme in the Commons Conservancy
PackageSummary: <text>Tauri is a rust project that enables developers to make secure
and small desktop applications using a web frontend.
</text>
PackageComment: <text>The package includes the following libraries; see
Relationship information.
</text>
Created: 2019-05-20T09:00:00Z
PackageDownloadLocation: git://github.com/tauri-apps/tauri
PackageDownloadLocation: git+https://github.com/tauri-apps/tauri.git
PackageDownloadLocation: git+ssh://github.com/tauri-apps/tauri.git
Creator: Person: Daniel Thompson-Yvetot

View File

@@ -0,0 +1,177 @@
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

21
plugins/http/LICENSE_MIT Normal file
View File

@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2017 - Present Tauri Apps Contributors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

93
plugins/http/README.md Normal file
View File

@@ -0,0 +1,93 @@
![plugin-http](https://github.com/tauri-apps/plugins-workspace/raw/v2/plugins/http/banner.png)
Access the HTTP client written in Rust.
| Platform | Supported |
| -------- | --------- |
| Linux | ✓ |
| Windows | ✓ |
| macOS | ✓ |
| Android | ✓ |
| iOS | ✓ |
## Install
_This plugin requires a Rust version of at least **1.77.2**_
There are three general methods of installation that we can recommend.
1. Use crates.io and npm (easiest, and requires you to trust that our publishing pipeline worked)
2. Pull sources directly from Github using git tags / revision hashes (most secure)
3. Git submodule install this repo in your tauri project and then use file protocol to ingest the source (most secure, but inconvenient to use)
Install the Core plugin by adding the following to your `Cargo.toml` file:
`src-tauri/Cargo.toml`
```toml
[dependencies]
tauri-plugin-http = "2.0.0"
# alternatively with Git:
tauri-plugin-http = { git = "https://github.com/tauri-apps/plugins-workspace", branch = "v2" }
```
You can install the JavaScript Guest bindings using your preferred JavaScript package manager:
```sh
pnpm add @tauri-apps/plugin-http
# or
npm add @tauri-apps/plugin-http
# or
yarn add @tauri-apps/plugin-http
```
## Usage
First you need to register the core plugin with Tauri:
`src-tauri/src/lib.rs`
```rust
fn main() {
tauri::Builder::default()
.plugin(tauri_plugin_http::init())
.run(tauri::generate_context!())
.expect("error while running tauri application");
}
```
Afterwards all the plugin's APIs are available through the JavaScript guest bindings:
```javascript
import { fetch } from '@tauri-apps/plugin-http'
const response = await fetch('http://localhost:3003/users/2', {
method: 'GET',
connectTimeout: 30
})
```
## Contributing
PRs accepted. Please make sure to read the Contributing Guide before making a pull request.
## Partners
<table>
<tbody>
<tr>
<td align="center" valign="middle">
<a href="https://crabnebula.dev" target="_blank">
<img src="https://github.com/tauri-apps/plugins-workspace/raw/v2/.github/sponsors/crabnebula.svg" alt="CrabNebula" width="283">
</a>
</td>
</tr>
</tbody>
</table>
For the complete list of sponsors please visit our [website](https://tauri.app#sponsors) and [Open Collective](https://opencollective.com/tauri).
## License
Code: (c) 2015 - Present - The Tauri Programme within The Commons Conservancy.
MIT or MIT/Apache 2.0 where applicable.

23
plugins/http/SECURITY.md Normal file
View File

@@ -0,0 +1,23 @@
# Security Policy
**Do not report security vulnerabilities through public GitHub issues.**
**Please use the [Private Vulnerability Disclosure](https://docs.github.com/en/code-security/security-advisories/guidance-on-reporting-and-writing-information-about-vulnerabilities/privately-reporting-a-security-vulnerability#privately-reporting-a-security-vulnerability) feature of GitHub.**
Include as much of the following information:
- Type of issue (e.g. improper input parsing, privilege escalation, etc.)
- The location of the affected source code (tag/branch/commit or direct URL)
- Any special configuration required to reproduce the issue
- The distribution affected or used to help us with reproduction of the issue
- Step-by-step instructions to reproduce the issue
- Ideally a reproduction repository
- Impact of the issue, including how an attacker might exploit the issue
We prefer to receive reports in English.
## Contact
Please disclose a vulnerability or security relevant issue here: [https://github.com/tauri-apps/plugins-workspace/security/advisories/new](https://github.com/tauri-apps/plugins-workspace/security/advisories/new).
Alternatively, you can also contact us by email via [security@tauri.app](mailto:security@tauri.app).

1
plugins/http/api-iife.js Normal file
View File

@@ -0,0 +1 @@
if("__TAURI__"in window){var __TAURI_PLUGIN_HTTP__=function(e,t){"use strict";const r="Request cancelled";return e.fetch=async function(e,n){const a=n?.signal;if(a?.aborted)throw new Error(r);const o=n?.maxRedirections,i=n?.connectTimeout,s=n?.proxy,c=n?.danger;n&&(delete n.maxRedirections,delete n.connectTimeout,delete n.proxy,delete n.danger);const d=n?.headers?n.headers instanceof Headers?n.headers:new Headers(n.headers):new Headers,l=new Request(e,n),u=await l.arrayBuffer(),h=0!==u.byteLength?Array.from(new Uint8Array(u)):null;for(const[e,t]of l.headers)d.get(e)||d.set(e,t);const _=(d instanceof Headers?Array.from(d.entries()):Array.isArray(d)?d:Object.entries(d)).map(([e,t])=>[e,"string"==typeof t?t:t.toString()]);if(a?.aborted)throw new Error(r);const w=await t.invoke("plugin:http|fetch",{clientConfig:{method:l.method,url:l.url,headers:_,data:h,maxRedirections:o,connectTimeout:i,proxy:s,danger:c}}),f=()=>t.invoke("plugin:http|fetch_cancel",{rid:w}).catch(()=>{});if(a?.aborted)throw f(),new Error(r);a?.addEventListener("abort",()=>{f()});const{status:y,statusText:p,url:b,headers:g,rid:v}=await t.invoke("plugin:http|fetch_send",{rid:w});let T=!1;const m=()=>T?Promise.resolve():(T=!0,t.invoke("plugin:http|fetch_cancel_body",{rid:v}).catch(()=>{})),R=[101,103,204,205,304].includes(y)?null:new ReadableStream({start:e=>{a?.addEventListener("abort",()=>{e.error(r),m()})},pull:e=>(async e=>{let r;try{r=await t.invoke("plugin:http|fetch_read_body",{rid:v})}catch(t){return e.error(t),void m()}const n=new Uint8Array(r),a=n[n.byteLength-1],o=n.slice(0,n.byteLength-1);1!==a?e.enqueue(o):e.close()})(e),cancel:()=>{m()}}),A=new Response(R,{status:y,statusText:p});Object.defineProperty(A,"url",{value:b,writable:!1}),Object.defineProperty(A,"headers",{value:new Headers(g),writable:!1});const P=A.clone.bind(A);return Object.defineProperty(A,"clone",{value:()=>{const e=P();return Object.defineProperty(e,"url",{value:b,writable:!1}),Object.defineProperty(e,"headers",{value:new Headers(g),writable:!1}),e}}),A},e}({},window.__TAURI__.core);Object.defineProperty(window.__TAURI__,"http",{value:__TAURI_PLUGIN_HTTP__})}

BIN
plugins/http/banner.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 51 KiB

73
plugins/http/build.rs Normal file
View File

@@ -0,0 +1,73 @@
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
#[path = "src/scope.rs"]
#[allow(dead_code)]
mod scope;
const COMMANDS: &[&str] = &[
"fetch",
"fetch_cancel",
"fetch_send",
"fetch_read_body",
"fetch_cancel_body",
];
/// HTTP scope entry.
#[derive(schemars::JsonSchema)]
#[serde(untagged)]
#[allow(unused)]
enum HttpScopeEntry {
/// A URL that can be accessed by the webview when using the HTTP APIs.
/// Wildcards can be used following the URL pattern standard.
///
/// See [the URL Pattern spec](https://urlpattern.spec.whatwg.org/) for more information.
///
/// Examples:
///
/// - "https://*" : allows all HTTPS origin on port 443
///
/// - "https://*:*" : allows all HTTPS origin on any port
///
/// - "https://*.github.com/tauri-apps/tauri": allows any subdomain of "github.com" with the "tauri-apps/api" path
///
/// - "https://myapi.service.com/users/*": allows access to any URLs that begins with "https://myapi.service.com/users/"
Value(String),
Object {
/// A URL that can be accessed by the webview when using the HTTP APIs.
/// Wildcards can be used following the URL pattern standard.
///
/// See [the URL Pattern spec](https://urlpattern.spec.whatwg.org/) for more information.
///
/// Examples:
///
/// - "https://*" : allows all HTTPS origin on port 443
///
/// - "https://*:*" : allows all HTTPS origin on any port
///
/// - "https://*.github.com/tauri-apps/tauri": allows any subdomain of "github.com" with the "tauri-apps/api" path
///
/// - "https://myapi.service.com/users/*": allows access to any URLs that begins with "https://myapi.service.com/users/"
url: String,
},
}
// Ensure `HttpScopeEntry` and `scope::EntryRaw` is kept in sync
fn _f() {
match scope::EntryRaw::Value(String::new()) {
scope::EntryRaw::Value(url) => HttpScopeEntry::Value(url),
scope::EntryRaw::Object { url } => HttpScopeEntry::Object { url },
};
match HttpScopeEntry::Value(String::new()) {
HttpScopeEntry::Value(url) => scope::EntryRaw::Value(url),
HttpScopeEntry::Object { url } => scope::EntryRaw::Object { url },
};
}
fn main() {
tauri_plugin::Builder::new(COMMANDS)
.global_api_script_path("./api-iife.js")
.global_scope_schema(schemars::schema_for!(HttpScopeEntry))
.build();
}

View File

@@ -0,0 +1,347 @@
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
/**
* Make HTTP requests with the Rust backend.
*
* ## Security
*
* This API has a scope configuration that forces you to restrict the URLs that can be accessed using glob patterns.
*
* For instance, this scope configuration only allows making HTTP requests to all subdomains for `tauri.app` except for `https://private.tauri.app`:
* ```json
* {
* "permissions": [
* {
* "identifier": "http:default",
* "allow": [{ "url": "https://*.tauri.app" }],
* "deny": [{ "url": "https://private.tauri.app" }]
* }
* ]
* }
* ```
* Trying to execute any API with a URL not configured on the scope results in a promise rejection due to denied access.
*
* @module
*/
import { invoke } from '@tauri-apps/api/core'
/**
* Configuration of a proxy that a Client should pass requests to.
*
* @since 2.0.0
*/
export interface Proxy {
/**
* Proxy all traffic to the passed URL.
*/
all?: string | ProxyConfig
/**
* Proxy all HTTP traffic to the passed URL.
*/
http?: string | ProxyConfig
/**
* Proxy all HTTPS traffic to the passed URL.
*/
https?: string | ProxyConfig
}
/**
* Detailed configuration of a single proxy server, used when a plain URL string is not enough.
*
* @since 2.0.0
*/
export interface ProxyConfig {
/**
* The URL of the proxy server.
*/
url: string
/**
* Set the `Proxy-Authorization` header using Basic auth.
*/
basicAuth?: {
/**
* The user name sent to the proxy server.
*/
username: string
/**
* The password sent to the proxy server.
*/
password: string
}
/**
* A configuration for filtering out requests that shouldn't be proxied.
* Entries are expected to be comma-separated (whitespace between entries is ignored)
*/
noProxy?: string
}
/**
* Options to configure the Rust client used to make fetch requests
*
* @since 2.0.0
*/
export interface ClientOptions {
/**
* Defines the maximum number of redirects the client should follow.
* If set to 0, no redirects will be followed.
*
* When the `scopeRedirects` plugin configuration is enabled, every redirect must
* also be allowed by the configured scope, otherwise the request fails
* instead of being followed.
*/
maxRedirections?: number
/** Timeout in milliseconds */
connectTimeout?: number
/**
* Configuration of a proxy that a Client should pass requests to.
*/
proxy?: Proxy
/**
* Configuration for dangerous settings on the client such as disabling SSL verification.
*/
danger?: DangerousSettings
}
/**
* Configuration for dangerous settings on the client such as disabling SSL verification.
*
* @since 2.3.0
*/
export interface DangerousSettings {
/**
* Disables SSL verification.
*/
acceptInvalidCerts?: boolean
/**
* Disables hostname verification.
*/
acceptInvalidHostnames?: boolean
}
const ERROR_REQUEST_CANCELLED = 'Request cancelled'
/**
* Fetch a resource from the network. It returns a `Promise` that resolves to the
* `Response` to that `Request`, whether it is successful or not.
*
* The request is performed by the Rust backend instead of the webview, so it is not subject to
* CORS, but the URL must be allowed by the plugin scope.
*
* @example
* ```typescript
* import { fetch } from '@tauri-apps/plugin-http';
* const response = await fetch("http://my.json.host/data.json");
* console.log(response.status); // e.g. 200
* console.log(response.statusText); // e.g. "OK"
* const jsonData = await response.json();
* ```
*
* @param input The resource to fetch, as a URL, a string or a `Request` object.
* @param init The standard `fetch` request options, extended with the Rust client options from
* {@linkcode ClientOptions}: `maxRedirections`, `connectTimeout`, `proxy` and `danger`. The
* `signal` option can be used to abort the request.
* @returns A promise resolving to the `Response` of the request.
*
* @since 2.0.0
*/
export async function fetch(
input: URL | Request | string,
init?: RequestInit & ClientOptions
): Promise<Response> {
// Optimistically check for abort signal and avoid doing any work
const signal = init?.signal
if (signal?.aborted) {
throw new Error(ERROR_REQUEST_CANCELLED)
}
const maxRedirections = init?.maxRedirections
const connectTimeout = init?.connectTimeout
const proxy = init?.proxy
const danger = init?.danger
// Remove these fields before creating the request
if (init) {
delete init.maxRedirections
delete init.connectTimeout
delete init.proxy
delete init.danger
}
const headers = init?.headers
? init.headers instanceof Headers
? init.headers
: new Headers(init.headers)
: new Headers()
const req = new Request(input, init)
const buffer = await req.arrayBuffer()
const data =
buffer.byteLength !== 0 ? Array.from(new Uint8Array(buffer)) : null
// append new headers created by the browser `Request` implementation,
// if not already declared by the caller of this function
for (const [key, value] of req.headers) {
if (!headers.get(key)) {
headers.set(key, value)
}
}
const headersArray =
headers instanceof Headers
? Array.from(headers.entries())
: Array.isArray(headers)
? headers
: Object.entries(headers)
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
const mappedHeaders: Array<[string, string]> = headersArray.map(
([name, val]) => [
name,
// we need to ensure we have all header values as strings
// eslint-disable-next-line
typeof val === 'string' ? val : (val as any).toString()
]
)
// Optimistically check for abort signal and avoid doing any work on the Rust side
if (signal?.aborted) {
throw new Error(ERROR_REQUEST_CANCELLED)
}
const rid = await invoke<number>('plugin:http|fetch', {
clientConfig: {
method: req.method,
url: req.url,
headers: mappedHeaders,
data,
maxRedirections,
connectTimeout,
proxy,
danger
}
})
const abort = () =>
invoke('plugin:http|fetch_cancel', { rid }).catch(() => {})
// Optimistically check for abort signal
// and avoid doing any work after doing intial work on the Rust side
if (signal?.aborted) {
// we don't care about the result of this promise
void abort()
throw new Error(ERROR_REQUEST_CANCELLED)
}
signal?.addEventListener('abort', () => void abort())
interface FetchSendResponse {
status: number
statusText: string
headers: [[string, string]]
url: string
rid: number
}
const {
status,
statusText,
url,
headers: responseHeaders,
rid: responseRid
} = await invoke<FetchSendResponse>('plugin:http|fetch_send', {
rid
})
let bodyDropped = false
const dropBody = () => {
if (bodyDropped) return Promise.resolve()
bodyDropped = true
return invoke('plugin:http|fetch_cancel_body', { rid: responseRid }).catch(
() => {}
)
}
const readChunk = async (
controller: ReadableStreamDefaultController<Uint8Array>
) => {
let data: ArrayBuffer
try {
data = await invoke('plugin:http|fetch_read_body', {
rid: responseRid
})
} catch (e) {
// close the stream if an error occurs
// and drop the body on Rust side
controller.error(e)
void dropBody()
return
}
const dataUint8 = new Uint8Array(data)
const lastByte = dataUint8[dataUint8.byteLength - 1]
const actualData = dataUint8.slice(0, dataUint8.byteLength - 1)
// close when the signal to close (last byte is 1) is sent from the IPC.
if (lastByte === 1) {
controller.close()
return
}
controller.enqueue(actualData)
}
// no body for 101, 103, 204, 205 and 304
// see https://fetch.spec.whatwg.org/#null-body-status
const body = [101, 103, 204, 205, 304].includes(status)
? null
: new ReadableStream<Uint8Array>({
start: (controller) => {
// listen for abort events to cancel reading
signal?.addEventListener('abort', () => {
controller.error(ERROR_REQUEST_CANCELLED)
void dropBody()
})
},
pull: (controller) => readChunk(controller),
cancel: () => {
// Ensure body resources are released on stream cancellation
void dropBody()
}
})
const res = new Response(body, {
status,
statusText
})
// `Response.url` cannot be set via the constructor, so we define it manually
Object.defineProperty(res, 'url', { value: url, writable: false })
// Expose `set-cookie` via `response.headers` (and `getSetCookie()` where
// supported). This is not Fetch-spec compliant for network responses in
// browsers, where `set-cookie` is treated as a forbidden response
// header and is generally not readable from JavaScript.
Object.defineProperty(res, 'headers', {
value: new Headers(responseHeaders),
writable: false
})
// Patch clone() per-instance so cloning preserves the overridden properties
const originalClone = res.clone.bind(res)
Object.defineProperty(res, 'clone', {
value: () => {
const cloned = originalClone()
Object.defineProperty(cloned, 'url', { value: url, writable: false })
Object.defineProperty(cloned, 'headers', {
value: new Headers(responseHeaders),
writable: false
})
return cloned
}
})
return res
}

29
plugins/http/package.json Normal file
View File

@@ -0,0 +1,29 @@
{
"name": "@tauri-apps/plugin-http",
"version": "2.6.1",
"license": "MIT OR Apache-2.0",
"authors": [
"Tauri Programme within The Commons Conservancy"
],
"repository": "https://github.com/tauri-apps/plugins-workspace",
"type": "module",
"types": "./dist-js/index.d.ts",
"main": "./dist-js/index.cjs",
"module": "./dist-js/index.js",
"exports": {
"types": "./dist-js/index.d.ts",
"import": "./dist-js/index.js",
"require": "./dist-js/index.cjs"
},
"scripts": {
"build": "rollup -c"
},
"files": [
"dist-js",
"README.md",
"LICENSE"
],
"dependencies": {
"@tauri-apps/api": "^2.11.0"
}
}

View File

@@ -0,0 +1,13 @@
# Automatically generated - DO NOT EDIT!
"$schema" = "../../schemas/schema.json"
[[permission]]
identifier = "allow-fetch"
description = "Enables the fetch command without any pre-configured scope."
commands.allow = ["fetch"]
[[permission]]
identifier = "deny-fetch"
description = "Denies the fetch command without any pre-configured scope."
commands.deny = ["fetch"]

View File

@@ -0,0 +1,13 @@
# Automatically generated - DO NOT EDIT!
"$schema" = "../../schemas/schema.json"
[[permission]]
identifier = "allow-fetch-cancel"
description = "Enables the fetch_cancel command without any pre-configured scope."
commands.allow = ["fetch_cancel"]
[[permission]]
identifier = "deny-fetch-cancel"
description = "Denies the fetch_cancel command without any pre-configured scope."
commands.deny = ["fetch_cancel"]

View File

@@ -0,0 +1,13 @@
# Automatically generated - DO NOT EDIT!
"$schema" = "../../schemas/schema.json"
[[permission]]
identifier = "allow-fetch-cancel-body"
description = "Enables the fetch_cancel_body command without any pre-configured scope."
commands.allow = ["fetch_cancel_body"]
[[permission]]
identifier = "deny-fetch-cancel-body"
description = "Denies the fetch_cancel_body command without any pre-configured scope."
commands.deny = ["fetch_cancel_body"]

View File

@@ -0,0 +1,13 @@
# Automatically generated - DO NOT EDIT!
"$schema" = "../../schemas/schema.json"
[[permission]]
identifier = "allow-fetch-read-body"
description = "Enables the fetch_read_body command without any pre-configured scope."
commands.allow = ["fetch_read_body"]
[[permission]]
identifier = "deny-fetch-read-body"
description = "Denies the fetch_read_body command without any pre-configured scope."
commands.deny = ["fetch_read_body"]

View File

@@ -0,0 +1,13 @@
# Automatically generated - DO NOT EDIT!
"$schema" = "../../schemas/schema.json"
[[permission]]
identifier = "allow-fetch-send"
description = "Enables the fetch_send command without any pre-configured scope."
commands.allow = ["fetch_send"]
[[permission]]
identifier = "deny-fetch-send"
description = "Denies the fetch_send command without any pre-configured scope."
commands.deny = ["fetch_send"]

View File

@@ -0,0 +1,160 @@
## Default Permission
This permission set configures what kind of
fetch operations are available from the http plugin.
This enables all fetch operations but does not
allow explicitly any origins to be fetched. This needs to
be manually configured before usage.
#### Granted Permissions
All fetch operations are enabled.
#### This default permission set includes the following:
- `allow-fetch`
- `allow-fetch-cancel`
- `allow-fetch-send`
- `allow-fetch-read-body`
- `allow-fetch-cancel-body`
## Permission Table
<table>
<tr>
<th>Identifier</th>
<th>Description</th>
</tr>
<tr>
<td>
`http:allow-fetch`
</td>
<td>
Enables the fetch command without any pre-configured scope.
</td>
</tr>
<tr>
<td>
`http:deny-fetch`
</td>
<td>
Denies the fetch command without any pre-configured scope.
</td>
</tr>
<tr>
<td>
`http:allow-fetch-cancel`
</td>
<td>
Enables the fetch_cancel command without any pre-configured scope.
</td>
</tr>
<tr>
<td>
`http:deny-fetch-cancel`
</td>
<td>
Denies the fetch_cancel command without any pre-configured scope.
</td>
</tr>
<tr>
<td>
`http:allow-fetch-cancel-body`
</td>
<td>
Enables the fetch_cancel_body command without any pre-configured scope.
</td>
</tr>
<tr>
<td>
`http:deny-fetch-cancel-body`
</td>
<td>
Denies the fetch_cancel_body command without any pre-configured scope.
</td>
</tr>
<tr>
<td>
`http:allow-fetch-read-body`
</td>
<td>
Enables the fetch_read_body command without any pre-configured scope.
</td>
</tr>
<tr>
<td>
`http:deny-fetch-read-body`
</td>
<td>
Denies the fetch_read_body command without any pre-configured scope.
</td>
</tr>
<tr>
<td>
`http:allow-fetch-send`
</td>
<td>
Enables the fetch_send command without any pre-configured scope.
</td>
</tr>
<tr>
<td>
`http:deny-fetch-send`
</td>
<td>
Denies the fetch_send command without any pre-configured scope.
</td>
</tr>
</table>

View File

@@ -0,0 +1,23 @@
"$schema" = "schemas/schema.json"
[default]
description = """
This permission set configures what kind of
fetch operations are available from the http plugin.
This enables all fetch operations but does not
allow explicitly any origins to be fetched. This needs to
be manually configured before usage.
#### Granted Permissions
All fetch operations are enabled.
"""
permissions = [
"allow-fetch",
"allow-fetch-cancel",
"allow-fetch-send",
"allow-fetch-read-body",
"allow-fetch-cancel-body",
]

View File

@@ -0,0 +1,366 @@
{
"$schema": "http://json-schema.org/draft-07/schema#",
"title": "PermissionFile",
"description": "Permission file that can define a default permission, a set of permissions or a list of inlined permissions.",
"type": "object",
"properties": {
"default": {
"description": "The default permission set for the plugin",
"anyOf": [
{
"$ref": "#/definitions/DefaultPermission"
},
{
"type": "null"
}
]
},
"set": {
"description": "A list of permissions sets defined",
"type": "array",
"items": {
"$ref": "#/definitions/PermissionSet"
}
},
"permission": {
"description": "A list of inlined permissions",
"default": [],
"type": "array",
"items": {
"$ref": "#/definitions/Permission"
}
}
},
"definitions": {
"DefaultPermission": {
"description": "The default permission set of the plugin.\n\nWorks similarly to a permission with the \"default\" identifier.",
"type": "object",
"required": [
"permissions"
],
"properties": {
"version": {
"description": "The version of the permission.",
"type": [
"integer",
"null"
],
"format": "uint64",
"minimum": 1.0
},
"description": {
"description": "Human-readable description of what the permission does. Tauri convention is to use `<h4>` headings in markdown content for Tauri documentation generation purposes.",
"type": [
"string",
"null"
]
},
"permissions": {
"description": "All permissions this set contains.",
"type": "array",
"items": {
"type": "string"
}
}
}
},
"PermissionSet": {
"description": "A set of direct permissions grouped together under a new name.",
"type": "object",
"required": [
"description",
"identifier",
"permissions"
],
"properties": {
"identifier": {
"description": "A unique identifier for the permission.",
"type": "string"
},
"description": {
"description": "Human-readable description of what the permission does.",
"type": "string"
},
"permissions": {
"description": "All permissions this set contains.",
"type": "array",
"items": {
"$ref": "#/definitions/PermissionKind"
}
}
}
},
"Permission": {
"description": "Descriptions of explicit privileges of commands.\n\nIt can enable commands to be accessible in the frontend of the application.\n\nIf the scope is defined it can be used to fine grain control the access of individual or multiple commands.",
"type": "object",
"required": [
"identifier"
],
"properties": {
"version": {
"description": "The version of the permission.",
"type": [
"integer",
"null"
],
"format": "uint64",
"minimum": 1.0
},
"identifier": {
"description": "A unique identifier for the permission.",
"type": "string"
},
"description": {
"description": "Human-readable description of what the permission does. Tauri internal convention is to use `<h4>` headings in markdown content for Tauri documentation generation purposes.",
"type": [
"string",
"null"
]
},
"commands": {
"description": "Allowed or denied commands when using this permission.",
"default": {
"allow": [],
"deny": []
},
"allOf": [
{
"$ref": "#/definitions/Commands"
}
]
},
"scope": {
"description": "Allowed or denied scoped when using this permission.",
"allOf": [
{
"$ref": "#/definitions/Scopes"
}
]
},
"platforms": {
"description": "Target platforms this permission applies. By default all platforms are affected by this permission.",
"type": [
"array",
"null"
],
"items": {
"$ref": "#/definitions/Target"
}
}
}
},
"Commands": {
"description": "Allowed and denied commands inside a permission.\n\nIf two commands clash inside of `allow` and `deny`, it should be denied by default.",
"type": "object",
"properties": {
"allow": {
"description": "Allowed command.",
"default": [],
"type": "array",
"items": {
"type": "string"
}
},
"deny": {
"description": "Denied command, which takes priority.",
"default": [],
"type": "array",
"items": {
"type": "string"
}
}
}
},
"Scopes": {
"description": "An argument for fine grained behavior control of Tauri commands.\n\nIt can be of any serde serializable type and is used to allow or prevent certain actions inside a Tauri command. The configured scope is passed to the command and will be enforced by the command implementation.\n\n## Example\n\n```json { \"allow\": [{ \"path\": \"$HOME/**\" }], \"deny\": [{ \"path\": \"$HOME/secret.txt\" }] } ```",
"type": "object",
"properties": {
"allow": {
"description": "Data that defines what is allowed by the scope.",
"type": [
"array",
"null"
],
"items": {
"$ref": "#/definitions/Value"
}
},
"deny": {
"description": "Data that defines what is denied by the scope. This should be prioritized by validation logic.",
"type": [
"array",
"null"
],
"items": {
"$ref": "#/definitions/Value"
}
}
}
},
"Value": {
"description": "All supported ACL values.",
"anyOf": [
{
"description": "Represents a null JSON value.",
"type": "null"
},
{
"description": "Represents a [`bool`].",
"type": "boolean"
},
{
"description": "Represents a valid ACL [`Number`].",
"allOf": [
{
"$ref": "#/definitions/Number"
}
]
},
{
"description": "Represents a [`String`].",
"type": "string"
},
{
"description": "Represents a list of other [`Value`]s.",
"type": "array",
"items": {
"$ref": "#/definitions/Value"
}
},
{
"description": "Represents a map of [`String`] keys to [`Value`]s.",
"type": "object",
"additionalProperties": {
"$ref": "#/definitions/Value"
}
}
]
},
"Number": {
"description": "A valid ACL number.",
"anyOf": [
{
"description": "Represents an [`i64`].",
"type": "integer",
"format": "int64"
},
{
"description": "Represents a [`f64`].",
"type": "number",
"format": "double"
}
]
},
"Target": {
"description": "Platform target.",
"oneOf": [
{
"description": "MacOS.",
"type": "string",
"enum": [
"macOS"
]
},
{
"description": "Windows.",
"type": "string",
"enum": [
"windows"
]
},
{
"description": "Linux.",
"type": "string",
"enum": [
"linux"
]
},
{
"description": "Android.",
"type": "string",
"enum": [
"android"
]
},
{
"description": "iOS.",
"type": "string",
"enum": [
"iOS"
]
}
]
},
"PermissionKind": {
"type": "string",
"oneOf": [
{
"description": "Enables the fetch command without any pre-configured scope.",
"type": "string",
"const": "allow-fetch",
"markdownDescription": "Enables the fetch command without any pre-configured scope."
},
{
"description": "Denies the fetch command without any pre-configured scope.",
"type": "string",
"const": "deny-fetch",
"markdownDescription": "Denies the fetch command without any pre-configured scope."
},
{
"description": "Enables the fetch_cancel command without any pre-configured scope.",
"type": "string",
"const": "allow-fetch-cancel",
"markdownDescription": "Enables the fetch_cancel command without any pre-configured scope."
},
{
"description": "Denies the fetch_cancel command without any pre-configured scope.",
"type": "string",
"const": "deny-fetch-cancel",
"markdownDescription": "Denies the fetch_cancel command without any pre-configured scope."
},
{
"description": "Enables the fetch_cancel_body command without any pre-configured scope.",
"type": "string",
"const": "allow-fetch-cancel-body",
"markdownDescription": "Enables the fetch_cancel_body command without any pre-configured scope."
},
{
"description": "Denies the fetch_cancel_body command without any pre-configured scope.",
"type": "string",
"const": "deny-fetch-cancel-body",
"markdownDescription": "Denies the fetch_cancel_body command without any pre-configured scope."
},
{
"description": "Enables the fetch_read_body command without any pre-configured scope.",
"type": "string",
"const": "allow-fetch-read-body",
"markdownDescription": "Enables the fetch_read_body command without any pre-configured scope."
},
{
"description": "Denies the fetch_read_body command without any pre-configured scope.",
"type": "string",
"const": "deny-fetch-read-body",
"markdownDescription": "Denies the fetch_read_body command without any pre-configured scope."
},
{
"description": "Enables the fetch_send command without any pre-configured scope.",
"type": "string",
"const": "allow-fetch-send",
"markdownDescription": "Enables the fetch_send command without any pre-configured scope."
},
{
"description": "Denies the fetch_send command without any pre-configured scope.",
"type": "string",
"const": "deny-fetch-send",
"markdownDescription": "Denies the fetch_send command without any pre-configured scope."
},
{
"description": "This permission set configures what kind of\nfetch operations are available from the http plugin.\n\nThis enables all fetch operations but does not\nallow explicitly any origins to be fetched. This needs to\nbe manually configured before usage.\n\n#### Granted Permissions\n\nAll fetch operations are enabled.\n\n\n#### This default permission set includes:\n\n- `allow-fetch`\n- `allow-fetch-cancel`\n- `allow-fetch-send`\n- `allow-fetch-read-body`\n- `allow-fetch-cancel-body`",
"type": "string",
"const": "default",
"markdownDescription": "This permission set configures what kind of\nfetch operations are available from the http plugin.\n\nThis enables all fetch operations but does not\nallow explicitly any origins to be fetched. This needs to\nbe manually configured before usage.\n\n#### Granted Permissions\n\nAll fetch operations are enabled.\n\n\n#### This default permission set includes:\n\n- `allow-fetch`\n- `allow-fetch-cancel`\n- `allow-fetch-send`\n- `allow-fetch-read-body`\n- `allow-fetch-cancel-body`"
}
]
}
}
}

View File

@@ -0,0 +1,7 @@
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
import { createConfig } from '../../shared/rollup.config.js'
export default createConfig()

View File

@@ -0,0 +1,718 @@
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use std::{future::Future, pin::Pin, str::FromStr, sync::Arc, time::Duration};
use http::{header, HeaderMap, HeaderName, HeaderValue, Method, StatusCode};
use reqwest::{redirect::Policy, NoProxy};
use serde::{Deserialize, Serialize};
use tauri::{
async_runtime::Mutex,
command,
ipc::{CommandScope, GlobalScope},
Manager, ResourceId, ResourceTable, Runtime, State, Webview,
};
use tokio::sync::oneshot::{channel, Receiver, Sender};
use crate::{
scope::{Entry, Scope},
Error, Http, Result,
};
const HTTP_USER_AGENT: &str = concat!(env!("CARGO_PKG_NAME"), "/", env!("CARGO_PKG_VERSION"),);
/// Matches the default [`reqwest`] redirect policy, used when the frontend does not
/// configure `maxRedirections`.
const DEFAULT_MAX_REDIRECTIONS: usize = 10;
struct ReqwestResponse(reqwest::Response);
impl tauri::Resource for ReqwestResponse {}
type CancelableResponseResult = Result<reqwest::Response>;
type CancelableResponseFuture =
Pin<Box<dyn Future<Output = CancelableResponseResult> + Send + Sync>>;
struct FetchRequest {
fut: Mutex<CancelableResponseFuture>,
abort_tx_rid: ResourceId,
abort_rx_rid: ResourceId,
}
impl tauri::Resource for FetchRequest {}
struct AbortSender(Sender<()>);
impl tauri::Resource for AbortRecveiver {}
impl AbortSender {
fn abort(self) {
let _ = self.0.send(());
}
}
struct AbortRecveiver(Receiver<()>);
impl tauri::Resource for AbortSender {}
trait AddRequest {
fn add_request(&mut self, fut: CancelableResponseFuture) -> ResourceId;
}
impl AddRequest for ResourceTable {
fn add_request(&mut self, fut: CancelableResponseFuture) -> ResourceId {
let (tx, rx) = channel::<()>();
let (tx, rx) = (AbortSender(tx), AbortRecveiver(rx));
let req = FetchRequest {
fut: Mutex::new(fut),
abort_tx_rid: self.add(tx),
abort_rx_rid: self.add(rx),
};
self.add(req)
}
}
#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
pub struct FetchResponse {
status: u16,
status_text: String,
headers: Vec<(String, String)>,
url: String,
rid: ResourceId,
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
#[allow(dead_code)] //feature flags shoudln't affect api
pub struct DangerousSettings {
accept_invalid_certs: bool,
accept_invalid_hostnames: bool,
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ClientConfig {
method: String,
url: url::Url,
headers: Vec<(String, String)>,
data: Option<Vec<u8>>,
connect_timeout: Option<u64>,
max_redirections: Option<usize>,
proxy: Option<Proxy>,
danger: Option<DangerousSettings>,
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Proxy {
all: Option<UrlOrConfig>,
http: Option<UrlOrConfig>,
https: Option<UrlOrConfig>,
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
#[serde(untagged)]
pub enum UrlOrConfig {
Url(String),
Config(ProxyConfig),
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ProxyConfig {
url: String,
basic_auth: Option<BasicAuth>,
no_proxy: Option<String>,
}
#[derive(Debug, Deserialize)]
pub struct BasicAuth {
username: String,
password: String,
}
#[inline]
fn proxy_creator(
url_or_config: UrlOrConfig,
proxy_fn: fn(String) -> reqwest::Result<reqwest::Proxy>,
) -> reqwest::Result<reqwest::Proxy> {
match url_or_config {
UrlOrConfig::Url(url) => Ok(proxy_fn(url)?),
UrlOrConfig::Config(ProxyConfig {
url,
basic_auth,
no_proxy,
}) => {
let mut proxy = proxy_fn(url)?;
if let Some(basic_auth) = basic_auth {
proxy = proxy.basic_auth(&basic_auth.username, &basic_auth.password);
}
if let Some(no_proxy) = no_proxy {
proxy = proxy.no_proxy(NoProxy::from_string(&no_proxy));
}
Ok(proxy)
}
}
}
fn attach_proxy(
proxy: Proxy,
mut builder: reqwest::ClientBuilder,
) -> crate::Result<reqwest::ClientBuilder> {
let Proxy { all, http, https } = proxy;
if let Some(all) = all {
let proxy = proxy_creator(all, reqwest::Proxy::all)?;
builder = builder.proxy(proxy);
}
if let Some(http) = http {
let proxy = proxy_creator(http, reqwest::Proxy::http)?;
builder = builder.proxy(proxy);
}
if let Some(https) = https {
let proxy = proxy_creator(https, reqwest::Proxy::https)?;
builder = builder.proxy(proxy);
}
Ok(builder)
}
/// Builds the redirect policy for the request.
///
/// When `scope` is [`Some`], **every** hop is checked against it. Validating only the URL the
/// frontend asked for is not enough: a server on an allowed origin can answer with a redirect to
/// any other origin (an open redirect, or a server the attacker controls), and following it would
/// give the webview access to a URL the scope denies.
///
/// That check is opt-in through the `scopeRedirects` configuration because it breaks applications
/// that rely on being redirected outside of their scope.
// TODO(v3): always check the scope and take it by value instead of `Option`
fn redirect_policy(scope: Option<Scope>, max_redirections: Option<usize>) -> Policy {
if max_redirections == Some(0) {
return Policy::none();
}
let max_redirections = max_redirections.unwrap_or(DEFAULT_MAX_REDIRECTIONS);
let Some(scope) = scope else {
return Policy::limited(max_redirections);
};
Policy::custom(move |attempt| {
// the first URL in `previous` is the initial request, so it must be excluded
if attempt.previous().len() > max_redirections {
attempt.error("too many redirects")
} else if scope.is_allowed(attempt.url()) {
attempt.follow()
} else {
let url = attempt.url().clone();
attempt.error(Error::UrlNotAllowed(url))
}
})
}
/// [`reqwest`] wraps the error returned by the redirect policy, and its `Display` impl does not
/// include the source, so we unwrap our own scope error to keep the reason visible to the frontend.
fn map_request_error(error: reqwest::Error) -> Error {
if error.is_redirect() {
let mut source = std::error::Error::source(&error);
while let Some(err) = source {
if let Some(Error::UrlNotAllowed(url)) = err.downcast_ref::<Error>() {
return Error::UrlNotAllowed(url.clone());
}
source = err.source();
}
}
Error::Network(error)
}
#[command]
pub async fn fetch<R: Runtime>(
webview: Webview<R>,
state: State<'_, Http>,
client_config: ClientConfig,
command_scope: CommandScope<Entry>,
global_scope: GlobalScope<Entry>,
) -> crate::Result<ResourceId> {
let ClientConfig {
method,
url,
headers: headers_raw,
data,
connect_timeout,
max_redirections,
proxy,
danger,
} = client_config;
let scheme = url.scheme();
let method = Method::from_bytes(method.as_bytes())?;
let mut headers = HeaderMap::new();
for (h, v) in headers_raw {
let name = HeaderName::from_str(&h)?;
#[cfg(not(feature = "unsafe-headers"))]
if is_unsafe_header(&name) {
#[cfg(debug_assertions)]
{
eprintln!("[\x1b[33mWARNING\x1b[0m] Skipping {name} header as it is a forbidden header per fetch spec https://fetch.spec.whatwg.org/#terminology-headers");
eprintln!("[\x1b[33mWARNING\x1b[0m] if keeping the header is a desired behavior, you can enable `unsafe-headers` feature flag in your Cargo.toml");
}
continue;
}
headers.append(name, HeaderValue::from_str(&v)?);
}
match scheme {
"http" | "https" => {
let scope = Scope::new(
command_scope
.allows()
.iter()
.chain(global_scope.allows())
.cloned()
.collect(),
command_scope
.denies()
.iter()
.chain(global_scope.denies())
.cloned()
.collect(),
);
if !scope.is_allowed(&url) {
return Err(Error::UrlNotAllowed(url));
}
let mut builder = reqwest::ClientBuilder::new();
if let Some(danger_config) = danger {
#[cfg(not(feature = "dangerous-settings"))]
{
#[cfg(debug_assertions)]
{
eprintln!("[\x1b[33mWARNING\x1b[0m] using dangerous settings requires `dangerous-settings` feature flag in your Cargo.toml");
}
let _ = danger_config;
return Err(Error::DangerousSettings);
}
#[cfg(feature = "dangerous-settings")]
{
builder = builder
.danger_accept_invalid_certs(danger_config.accept_invalid_certs)
.danger_accept_invalid_hostnames(danger_config.accept_invalid_hostnames)
}
}
if let Some(timeout) = connect_timeout {
builder = builder.connect_timeout(Duration::from_millis(timeout));
}
let scope = state.config.scope_redirects.then_some(scope);
builder = builder.redirect(redirect_policy(scope, max_redirections));
if let Some(proxy_config) = proxy {
builder = attach_proxy(proxy_config, builder)?;
}
#[cfg(feature = "cookies")]
{
builder = builder.cookie_provider(state.cookies_jar.clone());
}
let mut request = builder.build()?.request(method.clone(), url);
// POST and PUT requests should always have a 0 length content-length,
// if there is no body. https://fetch.spec.whatwg.org/#http-network-or-cache-fetch
if data.is_none() && matches!(method, Method::POST | Method::PUT) {
headers.append(header::CONTENT_LENGTH, HeaderValue::from_str("0")?);
}
if headers.contains_key(header::RANGE) {
// https://fetch.spec.whatwg.org/#http-network-or-cache-fetch step 18
// If httpRequest's header list contains `Range`, then append (`Accept-Encoding`, `identity`)
headers.append(header::ACCEPT_ENCODING, HeaderValue::from_str("identity")?);
}
if !headers.contains_key(header::USER_AGENT) {
headers.append(header::USER_AGENT, HeaderValue::from_str(HTTP_USER_AGENT)?);
}
// ensure we have an Origin header set
if cfg!(not(feature = "unsafe-headers")) || !headers.contains_key(header::ORIGIN) {
if let Ok(url) = webview.url() {
// The url crate returns OpaqueOrigin for tauri://localhost which serializes to "null"
let origin = if url.scheme() == "tauri" {
"tauri://localhost".to_string()
} else {
url.origin().ascii_serialization()
};
headers.append(header::ORIGIN, HeaderValue::from_str(&origin)?);
}
}
// In case empty origin is passed, remove it. Some services do not like Origin header
// so this way we can remove it in explicit way. The default behaviour is still to set it
if cfg!(feature = "unsafe-headers")
&& headers.get(header::ORIGIN) == Some(&HeaderValue::from_static(""))
{
headers.remove(header::ORIGIN);
};
if let Some(data) = data {
request = request.body(data);
}
request = request.headers(headers);
#[cfg(feature = "tracing")]
tracing::trace!("{:?}", request);
let fut = async move { request.send().await.map_err(map_request_error) };
let mut resources_table = webview.resources_table();
let rid = resources_table.add_request(Box::pin(fut));
Ok(rid)
}
"data" => {
let data_url =
data_url::DataUrl::process(url.as_str()).map_err(|_| Error::DataUrlError)?;
let (body, _) = data_url
.decode_to_vec()
.map_err(|_| Error::DataUrlDecodeError)?;
let response = http::Response::builder()
.status(StatusCode::OK)
.header(header::CONTENT_TYPE, data_url.mime_type().to_string())
.body(reqwest::Body::from(body))?;
#[cfg(feature = "tracing")]
tracing::trace!("{:?}", response);
let fut = async move { Ok(reqwest::Response::from(response)) };
let mut resources_table = webview.resources_table();
let rid = resources_table.add_request(Box::pin(fut));
Ok(rid)
}
_ => Err(Error::SchemeNotSupport(scheme.to_string())),
}
}
#[command]
pub fn fetch_cancel<R: Runtime>(webview: Webview<R>, rid: ResourceId) -> crate::Result<()> {
let mut resources_table = webview.resources_table();
let req = resources_table.get::<FetchRequest>(rid)?;
let abort_tx = resources_table.take::<AbortSender>(req.abort_tx_rid)?;
if let Some(abort_tx) = Arc::into_inner(abort_tx) {
abort_tx.abort();
}
Ok(())
}
#[command]
pub async fn fetch_send<R: Runtime>(
webview: Webview<R>,
rid: ResourceId,
) -> crate::Result<FetchResponse> {
let (req, abort_rx) = {
let mut resources_table = webview.resources_table();
let req = resources_table.get::<FetchRequest>(rid)?;
let abort_rx = resources_table.take::<AbortRecveiver>(req.abort_rx_rid)?;
(req, abort_rx)
};
let Some(abort_rx) = Arc::into_inner(abort_rx) else {
return Err(Error::RequestCanceled);
};
let mut fut = req.fut.lock().await;
let res = tokio::select! {
res = fut.as_mut() => res?,
_ = abort_rx.0 => {
let mut resources_table = webview.resources_table();
resources_table.close(rid)?;
return Err(Error::RequestCanceled);
}
};
#[cfg(feature = "tracing")]
tracing::trace!("{:?}", res);
let status = res.status();
let url = res.url().to_string();
let mut headers = Vec::new();
for (key, val) in res.headers().iter() {
headers.push((
key.as_str().into(),
String::from_utf8(val.as_bytes().to_vec())?,
));
}
let mut resources_table = webview.resources_table();
let rid = resources_table.add(ReqwestResponse(res));
Ok(FetchResponse {
status: status.as_u16(),
status_text: status.canonical_reason().unwrap_or_default().to_string(),
headers,
url,
rid,
})
}
#[command]
pub async fn fetch_read_body<R: Runtime>(
webview: Webview<R>,
rid: ResourceId,
) -> crate::Result<tauri::ipc::Response> {
let res = {
let resources_table = webview.resources_table();
resources_table.get::<ReqwestResponse>(rid)?
};
// SAFETY: we can access the inner value mutably
// because we are the only ones with a reference to it
// and we don't want to use `Arc::into_inner` because we want to keep the value in the table
// for potential future calls to `fetch_cancel_body`
let res_ptr = Arc::as_ptr(&res) as *mut ReqwestResponse;
let res = unsafe { &mut *res_ptr };
let res = &mut res.0;
let Some(chunk) = res.chunk().await? else {
let mut resources_table = webview.resources_table();
resources_table.close(rid)?;
// return a response with a single byte to indicate that the body is empty
return Ok(tauri::ipc::Response::new(vec![1]));
};
let mut chunk = chunk.to_vec();
// append a 0 byte to indicate that the body is not empty
chunk.push(0);
Ok(tauri::ipc::Response::new(chunk))
}
#[command]
pub async fn fetch_cancel_body<R: Runtime>(
webview: Webview<R>,
rid: ResourceId,
) -> crate::Result<()> {
let mut resources_table = webview.resources_table();
resources_table.close(rid)?;
Ok(())
}
// forbidden headers per fetch spec https://fetch.spec.whatwg.org/#terminology-headers
#[cfg(not(feature = "unsafe-headers"))]
fn is_unsafe_header(header: &HeaderName) -> bool {
matches!(
*header,
header::ACCEPT_CHARSET
| header::ACCEPT_ENCODING
| header::ACCESS_CONTROL_REQUEST_HEADERS
| header::ACCESS_CONTROL_REQUEST_METHOD
| header::CONNECTION
| header::CONTENT_LENGTH
| header::COOKIE
| header::DATE
| header::DNT
| header::EXPECT
| header::HOST
| header::ORIGIN
| header::REFERER
| header::SET_COOKIE
| header::TE
| header::TRAILER
| header::TRANSFER_ENCODING
| header::UPGRADE
| header::VIA
) || {
let lower = header.as_str().to_lowercase();
lower.starts_with("proxy-") || lower.starts_with("sec-")
}
}
#[cfg(test)]
mod tests {
use std::{
io::{BufRead, BufReader, Write},
net::TcpListener,
sync::Arc,
};
use super::*;
/// Test server with an open redirect:
///
/// - `/redirect-external` answers a 302 to `http://127.0.0.1:{port}/secret`, which is a
/// different origin as far as the scope is concerned - the tests allow `localhost`;
/// - `/redirect/{n}` answers a 302 to `/redirect/{n-1}` on `localhost`, and `/redirect/0`
/// answers a 302 to `/target`, so the whole chain stays in scope;
/// - anything else answers a 200, so a bypass shows up as a successful response.
fn spawn_server() -> u16 {
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
let port = listener.local_addr().unwrap().port();
std::thread::spawn(move || {
for stream in listener.incoming() {
let mut stream = stream.unwrap();
// the whole request must be consumed, otherwise closing the connection
// with unread data queued resets it before the client reads the response
let mut reader = BufReader::new(stream.try_clone().unwrap());
let mut request_line = String::new();
reader.read_line(&mut request_line).unwrap();
loop {
let mut header = String::new();
reader.read_line(&mut header).unwrap();
if matches!(header.as_str(), "" | "\r\n" | "\n") {
break;
}
}
let path = request_line.split(' ').nth(1).unwrap_or("/");
let location = match path.strip_prefix("/redirect/") {
Some("0") => Some(format!("http://localhost:{port}/target")),
Some(remaining) => Some(format!(
"http://localhost:{port}/redirect/{}",
remaining.parse::<usize>().unwrap() - 1
)),
None if path == "/redirect-external" => {
Some(format!("http://127.0.0.1:{port}/secret"))
}
None => None,
};
let response = match location {
Some(location) => format!(
"HTTP/1.1 302 Found\r\nLocation: {location}\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"
),
None => "HTTP/1.1 200 OK\r\nContent-Length: 6\r\nConnection: close\r\n\r\nsecret"
.to_string(),
};
let _ = stream.write_all(response.as_bytes());
let _ = stream.flush();
}
});
port
}
fn get(
url: &str,
scope: Option<Scope>,
max_redirections: Option<usize>,
) -> Result<reqwest::Response> {
let client = reqwest::ClientBuilder::new()
.redirect(redirect_policy(scope, max_redirections))
.build()
.unwrap();
let request = client.get(url);
tauri::async_runtime::block_on(
async move { request.send().await.map_err(map_request_error) },
)
}
fn localhost_scope(port: u16) -> Option<Scope> {
let entry = Arc::new(format!("http://localhost:{port}/*").parse().unwrap());
Some(Scope::new(vec![entry], Vec::new()))
}
#[test]
fn redirect_outside_of_scope_is_denied() {
let port = spawn_server();
let err = get(
&format!("http://localhost:{port}/redirect-external"),
localhost_scope(port),
None,
)
.unwrap_err();
match err {
Error::UrlNotAllowed(url) => {
assert_eq!(url.as_str(), format!("http://127.0.0.1:{port}/secret"))
}
e => panic!("expected the redirect to be denied by the scope, got {e:?}"),
}
}
#[test]
fn redirect_outside_of_scope_is_followed_when_not_configured() {
let port = spawn_server();
// `scopeRedirects` is disabled, so only the URL requested by the frontend is checked
let response = get(
&format!("http://localhost:{port}/redirect-external"),
None,
None,
)
.unwrap();
assert_eq!(response.status(), StatusCode::OK);
}
#[test]
fn redirect_denied_by_the_scope_is_denied() {
let port = spawn_server();
let allow = Arc::new(format!("http://localhost:{port}/*").parse().unwrap());
let deny = Arc::new(format!("http://localhost:{port}/target").parse().unwrap());
let scope = Some(Scope::new(vec![allow], vec![deny]));
let err = get(&format!("http://localhost:{port}/redirect/0"), scope, None).unwrap_err();
assert!(matches!(err, Error::UrlNotAllowed(_)));
}
#[test]
fn redirect_inside_of_scope_is_followed() {
let port = spawn_server();
let response = get(
&format!("http://localhost:{port}/redirect/2"),
localhost_scope(port),
None,
)
.unwrap();
assert_eq!(response.status(), StatusCode::OK);
assert_eq!(response.url().path(), "/target");
}
#[test]
fn max_redirections_is_enforced() {
let port = spawn_server();
for scope in [localhost_scope(port), None] {
let err = get(
&format!("http://localhost:{port}/redirect/5"),
scope,
Some(2),
)
.unwrap_err();
assert!(matches!(err, Error::Network(e) if e.is_redirect()));
}
}
#[test]
fn zero_max_redirections_does_not_follow() {
let port = spawn_server();
let response = get(
&format!("http://localhost:{port}/redirect/0"),
localhost_scope(port),
Some(0),
)
.unwrap();
assert_eq!(response.status(), StatusCode::FOUND);
}
}

View File

@@ -0,0 +1,47 @@
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use serde::Deserialize;
/// HTTP plugin configuration, defined on the `plugins > http` object of your `tauri.conf.json`.
#[derive(Debug, Clone, Default, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct Config {
/// Whether the scope is checked on every hop of a redirect chain instead of only on the
/// URL requested by the frontend. Defaults to `false`.
///
/// When disabled, a server on an allowed origin can answer with a redirect to any other
/// origin - an open redirect, or a server an attacker controls - and the plugin follows it,
/// handing the webview a response from a URL the scope denies, such as a `localhost`
/// service, an internal host or a cloud metadata endpoint.
///
/// When enabled, a redirect to a URL that is not allowed by the scope fails with
/// [`Error::UrlNotAllowed`](crate::Error::UrlNotAllowed) instead of being followed, so every
/// redirect target must also be part of the scope. This is opt-in because it breaks
/// applications that rely on being redirected outside of their configured scope.
// TODO(v3): enforce the scope on redirects by default and remove this option
#[serde(default)]
pub scope_redirects: bool,
}
#[cfg(test)]
mod tests {
use super::Config;
#[test]
fn deserializes_the_plugin_configuration() {
// the plugin configuration is optional, and the scope check is opt-in
let config: Option<Config> = serde_json::from_value(serde_json::Value::Null).unwrap();
assert!(config.is_none());
let config: Config = serde_json::from_str("{}").unwrap();
assert!(!config.scope_redirects);
let config: Config = serde_json::from_str(r#"{ "scopeRedirects": true }"#).unwrap();
assert!(config.scope_redirects);
// a typo must not silently disable the scope check
assert!(serde_json::from_str::<Config>(r#"{ "scopeRedirect": true }"#).is_err());
}
}

84
plugins/http/src/error.rs Normal file
View File

@@ -0,0 +1,84 @@
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use serde::{Serialize, Serializer};
use url::Url;
/// Errors that can happen while using the HTTP plugin.
///
/// The error is serialized to the frontend as its [`Display`](std::fmt::Display) string.
#[derive(Debug, thiserror::Error)]
pub enum Error {
/// JSON serialization or deserialization error.
#[error(transparent)]
Json(#[from] serde_json::Error),
/// File system error, raised for instance when the cookie store file cannot be created or
/// opened on startup.
#[error(transparent)]
Io(#[from] std::io::Error),
/// Error from the underlying [`reqwest`] client, raised while building the client, sending the
/// request or reading the response body.
#[error(transparent)]
Network(#[from] reqwest::Error),
/// Error from the [`http`] crate, raised while building the response of a `data:` URL.
#[error(transparent)]
Http(#[from] http::Error),
/// A header name given by the frontend is not a valid HTTP header name.
#[error(transparent)]
HttpInvalidHeaderName(#[from] http::header::InvalidHeaderName),
/// A header value is not a valid HTTP header value.
#[error(transparent)]
HttpInvalidHeaderValue(#[from] http::header::InvalidHeaderValue),
/// URL not allowed by the scope.
///
/// Raised for the URL requested by the frontend, and - when the
/// [`scope_redirects`](crate::Config::scope_redirects) configuration is enabled - for any
/// redirect target that is not allowed by the scope.
#[error("url not allowed on the configured scope: {0}")]
UrlNotAllowed(Url),
/// Failed to parse a URL.
#[error(transparent)]
UrlParseError(#[from] url::ParseError),
/// HTTP method error.
#[error(transparent)]
HttpMethod(#[from] http::method::InvalidMethod),
/// The requested URL uses an unsupported scheme. Only `http`, `https` and `data` are handled.
#[error("scheme {0} not supported")]
SchemeNotSupport(String),
/// The request was aborted by the frontend before the response was received.
#[error("Request canceled")]
RequestCanceled,
/// Error from the file system plugin.
#[error(transparent)]
FsError(#[from] tauri_plugin_fs::Error),
/// The `data:` URL could not be processed.
#[error("failed to process data url")]
DataUrlError,
/// The body of the `data:` URL could not be decoded into bytes.
#[error("failed to decode data url into bytes")]
DataUrlDecodeError,
/// Error from the Tauri APIs, raised for instance while resolving a path or while reading the
/// webview resource table.
#[error(transparent)]
Tauri(#[from] tauri::Error),
/// A response header value is not valid UTF-8, so it cannot be forwarded to the frontend.
#[error(transparent)]
Utf8(#[from] std::string::FromUtf8Error),
/// The frontend requested dangerous client settings, but the `dangerous-settings` Cargo
/// feature is not enabled.
#[error("dangerous settings used but are not enabled")]
DangerousSettings,
}
impl Serialize for Error {
fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_str(self.to_string().as_ref())
}
}
/// Alias for a [`Result`](std::result::Result) with the error type [`Error`].
pub type Result<T> = std::result::Result<T, Error>;

160
plugins/http/src/lib.rs Normal file
View File

@@ -0,0 +1,160 @@
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
//! Access the HTTP client written in Rust.
//!
//! ## Cargo features
//!
//! ### Reqwest feature forwards
//!
//! These features forwards [`reqwest`](https://docs.rs/reqwest/0.12.28/reqwest/index.html) features:
//!
//! - **http2** *(enabled by default)*: Enables HTTP/2 support.
//! - **native-tls**: Enables TLS functionality provided by native-tls.
//! - **native-tls-vendored**: Enables the vendored feature of native-tls.
//! - **native-tls-alpn**: Enables the alpn feature of native-tls.
//! - **rustls-tls** *(enabled by default)*: Enables TLS functionality provided by rustls. Equivalent to
//! rustls-tls-webpki-roots.
//! - **rustls-tls-manual-roots**: Enables TLS functionality provided by rustls, without setting any root
//! certificates. Roots have to be specified manually.
//! - **rustls-tls-webpki-roots**: Enables TLS functionality provided by rustls, while using root certificates
//! from the webpki-roots crate.
//! - **rustls-tls-native-roots**: Enables TLS functionality provided by rustls, while using root certificates
//! from the rustls-native-certs crate.
//! - **blocking**: Provides the [blocking](https://docs.rs/reqwest/0.12.28/reqwest/blocking/index.html) client API.
//! - **charset** *(enabled by default)*: Improved support for decoding text.
//! - **cookies** *(enabled by default)*: Provides cookie session support.
//! - **gzip**: Provides response body gzip decompression.
//! - **brotli**: Provides response body brotli decompression.
//! - **zstd**: Provides response body zstd decompression.
//! - **deflate**: Provides response body deflate decompression.
//! - **json**: Provides serialization and deserialization for JSON bodies.
//! - **multipart**: Provides functionality for multipart forms.
//! - **stream**: Adds support for futures::Stream.
//! - **socks**: Provides SOCKS5 proxy support.
//! - **trust-dns**: Enables a trust-dns/Hickory DNS async resolver instead of the default threadpool using
//! getaddrinfo.
//! - **macos-system-configuration** *(deprecated, use `system-proxy` instead)*: Use Windows and macOS system proxy settings automatically.
//! - **system-proxy** *(enabled by default)*: Use Windows and macOS system proxy settings automatically.
//!
//! ### tauri-plugin-http features
//!
//! - **tracing**: Adds request, response, and cookie-store diagnostics through `tracing`.
//! - **unsafe-headers**: Allows webview requests to send any headers.
//! - **dangerous-settings**: Allows dangerous client settings such as accepting invalid certificates or hostnames.
//!
//! ## Configuration
//!
//! See [`Config`] for the options that can be set on the `plugins > http` object of your
//! `tauri.conf.json`:
//!
//! ```json
//! {
//! "plugins": {
//! "http": {
//! "scopeRedirects": true
//! }
//! }
//! }
//! ```
pub use reqwest;
use tauri::{
plugin::{Builder, TauriPlugin},
Manager, Runtime,
};
pub use config::Config;
pub use error::{Error, Result};
mod commands;
mod config;
mod error;
#[cfg(feature = "cookies")]
mod reqwest_cookie_store;
mod scope;
#[cfg(feature = "cookies")]
const COOKIES_FILENAME: &str = ".cookies";
pub(crate) struct Http {
pub(crate) config: Config,
#[cfg(feature = "cookies")]
cookies_jar: std::sync::Arc<crate::reqwest_cookie_store::CookieStoreMutex>,
}
/// Initializes the plugin.
///
/// The plugin reads its [`Config`] from the `plugins > http` object of the `tauri.conf.json` file;
/// when that object is missing, [`Config::default`] is used.
///
/// With the `cookies` Cargo feature (enabled by default), a cookie jar is loaded from a `.cookies`
/// file in the application cache directory on setup and written back to it when the application
/// exits. A jar that cannot be read is replaced by an empty one.
///
/// Register it on the Tauri builder with `.plugin(tauri_plugin_http::init())`.
pub fn init<R: Runtime>() -> TauriPlugin<R, Option<Config>> {
Builder::<R, Option<Config>>::new("http")
.setup(|app, api| {
#[cfg(feature = "cookies")]
let cookies_jar = {
use crate::reqwest_cookie_store::*;
use std::fs::File;
use std::io::BufReader;
let cache_dir = app.path().app_cache_dir()?;
std::fs::create_dir_all(&cache_dir)?;
let path = cache_dir.join(COOKIES_FILENAME);
let file = File::options()
.create(true)
.append(true)
.read(true)
.open(&path)?;
let reader = BufReader::new(file);
CookieStoreMutex::load(path.clone(), reader).unwrap_or_else(|_e| {
#[cfg(feature = "tracing")]
tracing::warn!(
"failed to load cookie store: {_e}, falling back to empty store"
);
CookieStoreMutex::new(path, Default::default())
})
};
let state = Http {
config: api.config().clone().unwrap_or_default(),
#[cfg(feature = "cookies")]
cookies_jar: std::sync::Arc::new(cookies_jar),
};
app.manage(state);
Ok(())
})
.on_event(|app, event| {
#[cfg(feature = "cookies")]
if let tauri::RunEvent::Exit = event {
let state = app.state::<Http>();
match state.cookies_jar.request_save() {
Ok(rx) => {
let _ = rx.recv();
}
Err(_e) => {
#[cfg(feature = "tracing")]
tracing::error!("failed to save cookie jar: {_e}");
}
}
}
})
.invoke_handler(tauri::generate_handler![
commands::fetch,
commands::fetch_cancel,
commands::fetch_send,
commands::fetch_read_body,
commands::fetch_cancel_body,
])
.build()
}

View File

@@ -0,0 +1,133 @@
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
// taken from https://github.com/pfernie/reqwest_cookie_store/blob/2ec4afabcd55e24d3afe3f0626ee6dc97bed938d/src/lib.rs
use std::{
path::PathBuf,
sync::{mpsc::Receiver, Mutex},
};
use cookie_store::{CookieStore, RawCookie, RawCookieParseError};
use reqwest::header::HeaderValue;
fn set_cookies(
cookie_store: &mut CookieStore,
cookie_headers: &mut dyn Iterator<Item = &HeaderValue>,
url: &url::Url,
) {
let cookies = cookie_headers.filter_map(|val| {
std::str::from_utf8(val.as_bytes())
.map_err(RawCookieParseError::from)
.and_then(RawCookie::parse)
.map(|c| c.into_owned())
.ok()
});
cookie_store.store_response_cookies(cookies, url);
}
fn cookies(cookie_store: &CookieStore, url: &url::Url) -> Option<HeaderValue> {
let s = cookie_store
.get_request_values(url)
.map(|(name, value)| format!("{name}={value}"))
.collect::<Vec<_>>()
.join("; ");
if s.is_empty() {
return None;
}
HeaderValue::from_maybe_shared(bytes::Bytes::from(s)).ok()
}
/// A [`cookie_store::CookieStore`] wrapped internally by a [`std::sync::Mutex`], suitable for use in
/// async/concurrent contexts.
#[derive(Debug)]
pub struct CookieStoreMutex {
pub path: PathBuf,
store: Mutex<CookieStore>,
save_task: Mutex<Option<CancellableTask>>,
}
impl CookieStoreMutex {
/// Create a new [`CookieStoreMutex`] from an existing [`cookie_store::CookieStore`].
pub fn new(path: PathBuf, cookie_store: CookieStore) -> CookieStoreMutex {
CookieStoreMutex {
path,
store: Mutex::new(cookie_store),
save_task: Default::default(),
}
}
pub fn load<R: std::io::BufRead>(
path: PathBuf,
reader: R,
) -> cookie_store::Result<CookieStoreMutex> {
cookie_store::serde::load(reader, |c| serde_json::from_str(c))
.map(|store| CookieStoreMutex::new(path, store))
}
fn cookies_to_str(&self) -> Result<String, serde_json::Error> {
let mut cookies = Vec::new();
for cookie in self
.store
.lock()
.expect("poisoned cookie jar mutex")
.iter_unexpired()
{
if cookie.is_persistent() {
cookies.push(cookie.clone());
}
}
serde_json::to_string(&cookies)
}
pub fn request_save(&self) -> cookie_store::Result<Receiver<()>> {
let cookie_str = self.cookies_to_str()?;
let path = self.path.clone();
let (tx, rx) = std::sync::mpsc::channel();
let task = tauri::async_runtime::spawn(async move {
match tokio::fs::write(&path, &cookie_str).await {
Ok(()) => {
let _ = tx.send(());
}
Err(_e) => {
#[cfg(feature = "tracing")]
tracing::error!("failed to save cookie jar: {_e}");
}
}
});
self.save_task
.lock()
.unwrap()
.replace(CancellableTask(task));
Ok(rx)
}
}
impl reqwest::cookie::CookieStore for CookieStoreMutex {
fn set_cookies(&self, cookie_headers: &mut dyn Iterator<Item = &HeaderValue>, url: &url::Url) {
set_cookies(&mut self.store.lock().unwrap(), cookie_headers, url);
// try to persist cookies immediately asynchronously
if let Err(_e) = self.request_save() {
#[cfg(feature = "tracing")]
tracing::error!("failed to save cookie jar: {_e}");
}
}
fn cookies(&self, url: &url::Url) -> Option<HeaderValue> {
let store = self.store.lock().unwrap();
cookies(&store, url)
}
}
#[derive(Debug)]
struct CancellableTask(tauri::async_runtime::JoinHandle<()>);
impl Drop for CancellableTask {
fn drop(&mut self) {
self.0.abort();
}
}

230
plugins/http/src/scope.rs Normal file
View File

@@ -0,0 +1,230 @@
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use std::sync::Arc;
use serde::{Deserialize, Deserializer};
use url::Url;
use urlpattern::{UrlPattern, UrlPatternMatchInput};
#[allow(rustdoc::bare_urls)]
#[derive(Debug)]
pub struct Entry {
pub url: UrlPattern,
}
fn parse_url_pattern(s: &str) -> Result<UrlPattern, urlpattern::quirks::Error> {
let mut init = urlpattern::UrlPatternInit::parse_constructor_string::<regex::Regex>(s, None)?;
if init.search.as_ref().map(|p| p.is_empty()).unwrap_or(true) {
init.search.replace("*".to_string());
}
if init.hash.as_ref().map(|p| p.is_empty()).unwrap_or(true) {
init.hash.replace("*".to_string());
}
if init
.pathname
.as_ref()
.map(|p| p.is_empty() || p == "/")
.unwrap_or(true)
{
init.pathname.replace("*".to_string());
}
UrlPattern::parse(init, Default::default())
}
#[derive(Deserialize)]
#[serde(untagged)]
pub(crate) enum EntryRaw {
Value(String),
Object { url: String },
}
impl<'de> Deserialize<'de> for Entry {
fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
where
D: Deserializer<'de>,
{
EntryRaw::deserialize(deserializer).and_then(|raw| {
let url = match raw {
EntryRaw::Value(url) => url,
EntryRaw::Object { url } => url,
};
Ok(Entry {
url: parse_url_pattern(&url).map_err(|e| {
serde::de::Error::custom(format!("`{url}` is not a valid URL pattern: {e}"))
})?,
})
})
}
}
/// Scope for HTTP access.
#[derive(Debug)]
pub struct Scope {
allowed: Vec<Arc<Entry>>,
denied: Vec<Arc<Entry>>,
}
impl Scope {
/// Creates a new scope from the scope configuration.
pub(crate) fn new(allowed: Vec<Arc<Entry>>, denied: Vec<Arc<Entry>>) -> Self {
Self { allowed, denied }
}
/// Determines if the given URL is allowed on this scope.
pub fn is_allowed(&self, url: &Url) -> bool {
let denied = self.denied.iter().any(|entry| {
entry
.url
.test(UrlPatternMatchInput::Url(url.clone()))
.unwrap_or_default()
});
if denied {
false
} else {
self.allowed.iter().any(|entry| {
entry
.url
.test(UrlPatternMatchInput::Url(url.clone()))
.unwrap_or_default()
})
}
}
}
#[cfg(test)]
impl std::str::FromStr for Entry {
type Err = urlpattern::quirks::Error;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let url = parse_url_pattern(s)?;
Ok(Self { url })
}
}
#[cfg(test)]
mod tests {
use std::sync::Arc;
#[test]
fn denied_takes_precedence() {
let allow = Arc::new("http://localhost:8080/file.png".parse().unwrap());
let deny = Arc::new("http://localhost:8080/*".parse().unwrap());
let scope = super::Scope::new(vec![allow], vec![deny]);
assert!(!scope.is_allowed(&"http://localhost:8080/file.png".parse().unwrap()));
assert!(!scope.is_allowed(&"http://localhost:8080?framework=tauri".parse().unwrap()));
}
#[test]
fn fixed_url() {
// plain URL
let entry = Arc::new("http://localhost:8080".parse().unwrap());
let scope = super::Scope::new(vec![entry], Vec::new());
assert!(scope.is_allowed(&"http://localhost:8080".parse().unwrap()));
assert!(scope.is_allowed(&"http://localhost:8080/".parse().unwrap()));
assert!(scope.is_allowed(&"http://localhost:8080/file".parse().unwrap()));
assert!(scope.is_allowed(&"http://localhost:8080/path/to/asset.png".parse().unwrap()));
assert!(scope.is_allowed(&"http://localhost:8080/path/list?limit=50".parse().unwrap()));
assert!(!scope.is_allowed(&"https://localhost:8080".parse().unwrap()));
assert!(!scope.is_allowed(&"http://localhost:8081".parse().unwrap()));
assert!(!scope.is_allowed(&"http://local:8080".parse().unwrap()));
}
#[test]
fn fixed_path() {
// URL with fixed path
let entry = Arc::new("http://localhost:8080/file.png".parse().unwrap());
let scope = super::Scope::new(vec![entry], Vec::new());
assert!(scope.is_allowed(&"http://localhost:8080/file.png".parse().unwrap()));
assert!(scope.is_allowed(&"http://localhost:8080/file.png?q=1".parse().unwrap()));
assert!(!scope.is_allowed(&"http://localhost:8080".parse().unwrap()));
assert!(!scope.is_allowed(&"http://localhost:8080/file".parse().unwrap()));
assert!(!scope.is_allowed(&"http://localhost:8080/file.png/other.jpg".parse().unwrap()));
}
#[test]
fn pattern_wildcard() {
let entry = Arc::new("http://localhost:8080/*.png".parse().unwrap());
let scope = super::Scope::new(vec![entry], Vec::new());
assert!(scope.is_allowed(&"http://localhost:8080/file.png".parse().unwrap()));
assert!(scope.is_allowed(&"http://localhost:8080/file.png#head".parse().unwrap()));
assert!(scope.is_allowed(&"http://localhost:8080/assets/file.png".parse().unwrap()));
assert!(scope.is_allowed(
&"http://localhost:8080/assets/file.png?width=100&height=200"
.parse()
.unwrap()
));
assert!(!scope.is_allowed(&"http://localhost:8080/file.jpeg".parse().unwrap()));
}
#[test]
fn domain_wildcard() {
let entry = Arc::new("http://*".parse().unwrap());
let scope = super::Scope::new(vec![entry], Vec::new());
assert!(scope.is_allowed(&"http://something.else".parse().unwrap()));
assert!(scope.is_allowed(&"http://something.else#tauri".parse().unwrap()));
assert!(scope.is_allowed(&"http://something.else/path/to/file".parse().unwrap()));
assert!(scope.is_allowed(&"http://something.else?rel=tauri".parse().unwrap()));
assert!(scope.is_allowed(
&"http://something.else/path/to/file.mp4?start=500"
.parse()
.unwrap()
));
assert!(!scope.is_allowed(&"https://something.else".parse().unwrap()));
let entry = Arc::new("http://*/*".parse().unwrap());
let scope = super::Scope::new(vec![entry], Vec::new());
assert!(scope.is_allowed(&"http://something.else".parse().unwrap()));
assert!(scope.is_allowed(&"http://something.else/path/to/file".parse().unwrap()));
}
#[test]
fn scheme_wildcard() {
let entry = Arc::new("*://*".parse().unwrap());
let scope = super::Scope::new(vec![entry], Vec::new());
assert!(scope.is_allowed(&"http://something.else".parse().unwrap()));
assert!(scope.is_allowed(&"http://something.else/path/to/file".parse().unwrap()));
assert!(scope.is_allowed(&"file://path".parse().unwrap()));
assert!(scope.is_allowed(&"file://path/to/file".parse().unwrap()));
assert!(scope.is_allowed(&"https://something.else".parse().unwrap()));
assert!(scope.is_allowed(&"https://something.else?x=1#frag".parse().unwrap()));
let entry = Arc::new("*://*/*".parse().unwrap());
let scope = super::Scope::new(vec![entry], Vec::new());
assert!(scope.is_allowed(&"http://something.else".parse().unwrap()));
assert!(scope.is_allowed(&"http://something.else/path/to/file".parse().unwrap()));
assert!(scope.is_allowed(&"file://path/to/file".parse().unwrap()));
assert!(scope.is_allowed(&"https://something.else".parse().unwrap()));
}
#[test]
fn validate_query() {
let entry = Arc::new("https://tauri.app/path?x=*".parse().unwrap());
let scope = super::Scope::new(vec![entry], Vec::new());
assert!(scope.is_allowed(&"https://tauri.app/path?x=5".parse().unwrap()));
assert!(!scope.is_allowed(&"https://tauri.app/path?y=5".parse().unwrap()));
}
#[test]
fn validate_hash() {
let entry = Arc::new("https://tauri.app/path#frame*".parse().unwrap());
let scope = super::Scope::new(vec![entry], Vec::new());
assert!(scope.is_allowed(&"https://tauri.app/path#frame".parse().unwrap()));
assert!(!scope.is_allowed(&"https://tauri.app/path#work".parse().unwrap()));
}
}

View File

@@ -0,0 +1,7 @@
{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"rootDir": "guest-js"
},
"include": ["guest-js/*.ts"]
}