From 68971e86691890ef2c7d9243bdbe8a8da4e51967 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E6=80=A7=E9=A9=8A?= Date: Wed, 18 Nov 2026 20:06:35 +0800 Subject: [PATCH] =?UTF-8?q?fix:=20=E7=B6=B2=E5=9D=80=E7=85=A7=E7=80=8F?= =?UTF-8?q?=E8=A6=BD=E5=99=A8=E7=9A=84=E8=AE=80=E6=B3=95=E6=AF=94=E5=B0=8D?= =?UTF-8?q?=EF=BC=88web(domain:=E2=80=A6)=E3=80=81=E5=85=A7=E9=83=A8?= =?UTF-8?q?=E7=B6=B2=E5=9D=80=E5=8D=A1=EF=BC=89=EF=BC=9B=E5=AF=A9=E6=A0=B8?= =?UTF-8?q?=E5=93=A1=E5=8F=AA=E8=AE=80=E5=85=A9=E7=AB=AF=E6=99=82=E7=85=A7?= =?UTF-8?q?=E6=A8=A3=E5=95=8F=EF=BC=9B=E4=B8=8A=E5=82=B3=E7=9A=84=E9=96=8B?= =?UTF-8?q?=E9=97=9C=E5=8D=A1=E4=B8=8D=E7=B5=A6=E5=AF=A9=E6=A0=B8=E7=9C=81?= =?UTF-8?q?=E6=8E=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 第三輪審查(6a6d905..4303646)的四個 P1,加上能收的 P2。 P1-1 `web(domain:…)` 比對的不是瀏覽器打開的那個網站:gate.rs 自己切網址,`me@example.com`、 `example.com.`、`example.com\cart`、`browser_tabs` 帶網址開新分頁都對不上(0 張卡)。 P1-2 同一個根:web.rs 的 normalize_url/host_port 用 rsplit('@')、不把 `\` 當 `/`, `http://127.0.0.1\@a.com/`、`http://192.168.1.1\.example.com/` 被當成公開網址,內部網址卡不跳。 修法:web::parse_url 用 WHATWG 的 `url` crate(Cargo.lock 本來就有,改成直接依賴)——`\` 是 `/`、 帳號@ 不是主機、小寫、punycode、結尾的點、各種寫法的 IP;normalize_url、host_port、web::host_of 都用它, gate 的 web(…) 用 host_of 比主機(規則的網域也同樣讀),比對清單加上 browser_tabs 帶網址。 InBotsBrowser 把解析過的網址交給瀏覽器(open、新分頁、web_fetch),檢查的就是打開的;web_fetch 轉址的每一站也照解析過的去要。地圖寫清楚:只比對用網址打開或讀的那一步,點連結、轉址、上一頁不算。 P1-3 審核員只讀長參數的兩端:模型可以把要擋的東西塞在中間,審核員說允許就不跳卡片。修法:參數被截過、 而且這一步真的給模型看了(model_reads,跟 review_action 一樣的判斷)時,審核員的允許、直接操作下的 「都不符合」都改成跳卡片:「參數很長,自動審核只讀了開頭和結尾,所以先問你」(沒有直接操作時照舊可以 一律允許,跟審核失敗一樣)。選這個而不是把上限拉高:上限拉多高,中間都還是可能藏東西。 P1-4 從這台上傳檔案、電腦工具或「在這台電腦上執行」沒開時,那張卡被送進 reviewed(),允許規則就省掉了。 修法:抽成 here_upload_decision——開關沒開的那張卡(工作資料夾內外都是)一律跳、不給審核,別的 yes (樣式卡的允許)也省不掉它;開關開著才照檔案規則和 reviewed()。 P2: - browser.md 的陷阱和自動審核說的對齊(本機網址:一律允許、直接操作、自動審核的允許都可以不問, 「一律詢問」照樣問)。 - 「對不上任何東西」的提醒(gate::rule_warning)擴到 web(…)(沒寫 domain:、用 *、寫了 https:// 或路徑、 不是網站)和 tool(…)(不是哪一步的名字,例如 tool(browser) 要寫 tool(browser_*));featuremap 的 every_tool 搬出測試,提醒用同一份工具清單。 - hook 的「ask」跟瀏覽器的樣式卡放在同一張(run_call 的通用 hook 詢問不再管 InBotsBrowser)。 沒改,記著(略過樣式規則的路):伺服器大腦上的 open_for_person、/goal 評審自己呼叫的 web_fetch、 在使用者自己的瀏覽器 browser_open(OnComputer,不用問的不比對)、別人傳來的訊息那一輪的 web_fetch (沒有自動審核)。vault.rs 的 host_of 也是自己切網址,沒動。沒碰 src/remote.rs、src/botbrowser.rs。 特性表 connector_decisions_are_characterized 多 20 列(38 → 58):審核員說允許、長參數 × 審核員允許/ 都不符合/允許樣式/詢問樣式。tool_specs_are_locked、approval_decisions_are_characterized 沒有 diff。 已驗證: 全部 cargo test 686 通過(不帶金鑰、DOCKER_HOST 指到不存在、ANYBOT_VAULT_KEY_FILE 放暫存、 PATH 前面放假的 security 記下每次呼叫:這次 0 次);把四個修法和 hook 合併各自改回去, addresses_are_read_as_a_browser_reads_them、pattern_rules_decide_before_the_model、an_ask_pattern_stops_the_bots_browser、 connector_decisions_are_characterized、an_upload_with_the_switches_off_always_asks、 a_hook_ask_and_a_rule_make_one_card_for_a_browser_step 都失敗,改回來都過;clippy -D warnings、lint-sh、 verify-approval-routing run.sh --replay(跟基準一樣);verify-anybot:browser 每一步可跑的照 md 原文冷跑全過 (target/verify-anybot/20261118-200336:「在瀏覽器打開 http://127.0.0.1/@a.com/(符合你的「一律詢問」規則: web(domain:127.0.0.1))」,192.168.1.5\.example.com 跳內部網址卡、先給審核員看;全部拒絕、沒有開瀏覽器) 未驗證: 真的瀏覽器打開解析過的網址(scratch 沒有 Docker,這台開會出現真的瀏覽器);直接操作那一半的實機; 電腦設定頁提醒那一行的樣子;--ignored 的瀏覽器實機測試(清單見 4303646) 未簽: 審批路徑、瀏覽器——要人類跑 --ignored 並簽名才能合併,沒有合併、沒有推 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Uirha5sXAsDLzxz6UZJgoC --- Cargo.lock | 1 + Cargo.toml | 2 + FEATURES.md | 4 +- SECURITY.md | 2 +- docs/feature-map/autonomy.md | 4 +- docs/feature-map/browser.md | 8 +-- src/agent.rs | 126 +++++++++++++++++++++++++++++------ src/agent/steps.rs | 117 ++++++++++++++++++++++++-------- src/app.rs | 4 +- src/app/remote_ui.rs | 2 +- src/featuremap.rs | 44 ++++++------ src/gate.rs | 77 ++++++++++++++++++--- src/web.rs | 99 ++++++++++++++++++--------- 13 files changed, 368 insertions(+), 122 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 5d409a4..f7bc525 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -387,6 +387,7 @@ dependencies = [ "unicode-normalization", "unicode-width", "ureq", + "url", "vt100", "wayland-client", "wayland-protocols", diff --git a/Cargo.toml b/Cargo.toml index 7a1c16f..d766feb 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -11,6 +11,8 @@ name = "anybot" path = "src/main.rs" [dependencies] +# WHATWG URL parsing: the host a browser opens is the host the rules check (`\` is `/`, user@ isn't the host, IDNA, IPs in any spelling). +url = "2.5.8" zhconv = { version = "0.4", default-features = false, features = ["mediawiki"] } eframe = "0.37" # 正式圖表:座標軸、网格、hover 十字準線與數值、框選縮放(和 eframe 同步發版) diff --git a/FEATURES.md b/FEATURES.md index 269a165..22a61d1 100644 --- a/FEATURES.md +++ b/FEATURES.md @@ -803,7 +803,7 @@ AnyBot 是一個桌面聊天 App,介面和運作方式照 Grok Bot 重做。 0. **不需要許可的** - App 操作工具(第 26 節),只有「刪除例行任務」會先問。 - 讀公開網頁。 - - AnyBot 自己的瀏覽器——但自動審核開著時,符合樣式的「一律詢問」(`tool(browser_click)`、`web(domain:…)`,`web_fetch` 也算)照樣問、沒有「一律允許」(只比對,不問模型);要問的那幾步(本機或內部網路的網址、上傳檔案)照第 7 步交給自動審核或直接操作,直接操作時「一律詢問」照樣擋(以前瀏覽器完全不經自動審核,直接操作連本機網址都不看規則)。 + - AnyBot 自己的瀏覽器——但自動審核開著時,符合樣式的「一律詢問」(`tool(browser_click)`、`web(domain:…)`,`web_fetch` 也算)照樣問、沒有「一律允許」(只比對,不問模型)。`web(domain:…)` 比對用網址打開或讀的那一步(`open`、帶網址開新分頁、`web_fetch`),網址照瀏覽器的讀法(WHATWG:大小寫、結尾的點、帳號@、反斜線、IDN、各種寫法的 IP),瀏覽器拿到的就是比對過的那個網址;點連結、轉址、上一頁到的網頁不比對。要問的那幾步(本機或內部網路的網址、上傳檔案)照第 7 步交給自動審核或直接操作,直接操作時「一律詢問」照樣擋(以前瀏覽器完全不經自動審核,直接操作連本機網址都不看規則)。從這台上傳檔案而電腦工具或「在這台電腦上執行」沒開時,那張卡(第 3、5 步)不給自動審核省掉。本機或內部網路網址的判斷也改成瀏覽器的讀法:以前 `http://127.0.0.1\@a.com/` 這種寫法會被當成公開網址、不問就開。 1. **決定在哪台電腦做** - 操作螢幕和讀你自己的瀏覽器:一律在「你的電腦」。 - 其他工具:用 Bot 指定的電腦,沒指定就用預設電腦。 @@ -1501,7 +1501,7 @@ computer_use_screenshot、click、mouse_move、mouse_button(按住/放開) - 都沒寫:本機伺服器收到環境變數 `MCP_USERNAME`、`MCP_PASSWORD`(自己設了同名變數的話用自己的);遠端伺服器收到 `Authorization: Basic …`(自己有 Authorization 標頭的話不加)。 - 密碼跟金鑰一樣:螢幕只看得到「已設定」,不會拿到內容;在螢幕上改指令或網址時,大腦會把密碼清掉(不然會被送到新的位址)。 - **螢幕上的開關就是大腦上的開關**:看大腦時,連接器的開關關掉,大腦就停掉那個伺服器、Bot 沒有它的工具;再打開,大腦用它自己留著的金鑰和密碼重新接上。狀態那一行顯示的是大腦上的結果(接不上會說原因)。 -- 權限:每個連接器第一次被用時問「使用連接器「X」的工具:…」,可以一律允許;直接操作模式下不問。自動審核開著時:符合樣式的「一律詢問」(例如 `connector(slack__post_message)`)每次問、沒有「一律允許」——直接操作模式下、連接器一律允許過也一樣(只比對樣式,不問模型)。沒一律允許過的,跟電腦上的步驟一樣交給自動審核(第 15 節):符合「無需詢問直接允許」(例如 `connector(gitlab__get_*)`)的不問、結果寫「(自動審核:符合「…」,直接允許)」;用一般的話寫的「一律詢問」由審核員判斷。一律允許過的連接器不再給審核員看:用一般的話寫的規則,包括直接操作填的三條預設(「用我的帳號發文、留言,或傳訊息給別人」…),擋不住它,要擋就寫成樣式。(以前連接器的步驟完全不經自動審核,直接操作時連「一律詢問」都不看。)用 use_connector_tool 叫的照它真正的工具名稱比對;審核員讀參數的前 3000 字和最後 1000 字(更長的中間省略),卡片只列前 160 字。hook 的「ask」跟規則放在同一張卡。新增 `connector(…)` 規則時對不上任何連接器的工具(寫成顯示的名稱、大小寫不對、中文名稱要寫代碼、超過 64 字被截掉),設定頁和手機會說。 +- 權限:每個連接器第一次被用時問「使用連接器「X」的工具:…」,可以一律允許;直接操作模式下不問。自動審核開著時:符合樣式的「一律詢問」(例如 `connector(slack__post_message)`)每次問、沒有「一律允許」——直接操作模式下、連接器一律允許過也一樣(只比對樣式,不問模型)。沒一律允許過的,跟電腦上的步驟一樣交給自動審核(第 15 節):符合「無需詢問直接允許」(例如 `connector(gitlab__get_*)`)的不問、結果寫「(自動審核:符合「…」,直接允許)」;用一般的話寫的「一律詢問」由審核員判斷。一律允許過的連接器不再給審核員看:用一般的話寫的規則,包括直接操作填的三條預設(「用我的帳號發文、留言,或傳訊息給別人」…),擋不住它,要擋就寫成樣式。(以前連接器的步驟完全不經自動審核,直接操作時連「一律詢問」都不看。)用 use_connector_tool 叫的照它真正的工具名稱比對;審核員讀參數的前 3000 字和最後 1000 字(更長的中間省略),卡片只列前 160 字。hook 的「ask」跟規則放在同一張卡。新增 `connector(…)` 規則時對不上任何連接器的工具(寫成顯示的名稱、大小寫不對、中文名稱要寫代碼、超過 64 字被截掉),設定頁和手機會說;`web(…)` 沒寫成 `web(domain:網站)`、`tool(…)` 不是哪一步的名字(例如 `tool(browser)`)也會說。審核員只讀了長參數的開頭和結尾時,它說允許(或直接操作下說都不符合)也照樣跳卡片:「參數很長,自動審核只讀了開頭和結尾,所以先問你」。 - 工具回傳的文字、圖片都會交給 Bot;一次最多等 120 秒(估計值)。按停止時,本機連接器的呼叫馬上結束(以前要等到它回或 120 秒);用網址連的照樣等。 - 連接器關掉、移除、重新連線或連不上時,連同它帶起來的所有程式一起關(npx/uvx/sh 底下真正的伺服器以前會一直留著)。 - **憑證**:AnyBot 所有的 HTTP 連線(連接器、模型服務、Webhook、語音、下載)都信任同一份憑證:公開的加上這台電腦自己信任的。以前只有連帳號伺服器的那條會看這台電腦信任的,公司自己簽憑證的連接器或模型服務在別處會失敗。`clippy.toml` 擋下在 net.rs 以外自己建 HTTP 用戶端。 diff --git a/SECURITY.md b/SECURITY.md index a0bce90..bc202a2 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -54,7 +54,7 @@ AnyBot 的 privacy 模型一句话:**Bot 跑在你自己的機器上,你的 - gVisor 是加分不是標配:純 Docker 的 box 與主機共享核心。 - 備份安全性以你的帳號密碼強度為上限。 - relay 是自架元件:它被攻破時洩露的是雜湊、session 清單與備份密文,不是明文。 -- 「一律允許」過的連接器、AnyBot 瀏覽器本來不用問的步驟,只再比對**固定樣式**的「一律詢問」(`connector(slack__post_message)`、`tool(browser_click)`、`web(domain:…)` 這種,不問模型):用一般的話寫的規則——包括直接操作填的三條預設(刪除、付款、用我的帳號發文或傳訊息)——擋不住它們。 +- 「一律允許」過的連接器、AnyBot 瀏覽器本來不用問的步驟,只再比對**固定樣式**的「一律詢問」(`connector(slack__post_message)`、`tool(browser_click)`、`web(domain:…)` 這種,不問模型):用一般的話寫的規則——包括直接操作填的三條預設(刪除、付款、用我的帳號發文或傳訊息)——擋不住它們。`web(domain:…)` 只看用網址打開或讀的那一步:點連結、網頁轉址、上一頁到的網頁看不到。 ## 硬化建議 diff --git a/docs/feature-map/autonomy.md b/docs/feature-map/autonomy.md index 0ea0d50..220989e 100644 --- a/docs/feature-map/autonomy.md +++ b/docs/feature-map/autonomy.md @@ -8,7 +8,7 @@ - `autonomy-yolo` 一律放行(/always-approve,也可以打 /yolo):你自己打的指令,一把全開——打開直接操作,之後所有 Bot 要等「允許」的都自動允許,連直接操作還會問的也不問,自動審核也略過。仍然擋:安全規則一律拒絕的;別人傳來的訊息(訊息管道、團隊成員)那一輪照樣等你按;問題卡、「需要處理」和 /plan 的計畫卡照樣等你。打開時已經在等的卡片(你自己的)一起放行。開著時每個聊天的輸入框上方、臉的同一行右邊有一個紅色閃電圖示(不另外佔一行;新對話沒有臉時自己一小行):滑過去看「一律放行 · Bot 做事不再問你」和還會擋什麼,點一下有「關閉一律放行」。「/always-approve off」關掉:要核准的又會問;直接操作是它順手打開的就一起關,本來就開著的留著。「/always-approve status」看現在是不是。管理員鎖了直接操作或「在這台電腦上執行」就打不開。 - `autonomy-still-asks` 直接操作仍會問或擋:安全規則擋的;符合「一律詢問」規則的(連接器的工具、AnyBot 瀏覽器開本機網址和上傳也算;「一律允許」過的只比對樣式);畫面上目標寫著付款、傳送、刪除這類字的點擊;用「郵件」「訊息」寄送(「訊息」開了「無需詢問直接傳送」除外);沙盒外的 AppleScript(選「一律允許」前);打電話、傳簡訊、在 X 發文;用保險庫的卡片。問題卡和「需要處理」也照樣等你。 - `autonomy-review` 自動審核:兩組用一般的話寫的規則「無需詢問直接允許」「一律詢問」,由這個 Bot 的模型判斷,兩邊都符合時「一律詢問」優先。符合允許就直接做;符合詢問就問你,而且沒有「一律允許」;都不符合照常問;審核沒回應就先問你。連接器的工具、AnyBot 瀏覽器要問的步驟(本機網址、上傳)也經過它,「一律允許」過的除外。 -- `autonomy-patterns` 固定樣式的規則:規則也可以寫成 `shell(git *)`(指令;允許要 `a && b` 每一段都符合,詢問只要一段)、`file(~/Projects/**)`(檔案或資料夾,** 任何層、* 一層)、`connector(gitlab__*)`(連接器的工具)、`web(domain:example.com)`(那個網站和它底下的網址)、`tool(browser_click)`(工具的名字)。樣式先判斷、每次一樣、不呼叫模型:要問的步驟、連接器的工具、AnyBot 瀏覽器的步驟和 `web_fetch`(「一律允許」過、本來不用問的也一樣)符合「一律詢問」的樣式一定問(模型說允許也沒用);指令、檔案不用問或「一律允許」過的不比對;符合允許的樣式就允許,但用一般的話寫的「一律詢問」還是會先讓模型看一次;有藏起來的指令($()、反引號)的,樣式不會允許。`connector(…)` 對不上任何連接器的工具時,新增的地方會說。 +- `autonomy-patterns` 固定樣式的規則:規則也可以寫成 `shell(git *)`(指令;允許要 `a && b` 每一段都符合,詢問只要一段)、`file(~/Projects/**)`(檔案或資料夾,** 任何層、* 一層)、`connector(gitlab__*)`(連接器的工具)、`web(domain:example.com)`(用網址打開或讀那個網站和它底下的網址;點連結、轉址到的不算)、`tool(browser_click)`(工具的名字)。樣式先判斷、每次一樣、不呼叫模型:要問的步驟、連接器的工具、AnyBot 瀏覽器的步驟和 `web_fetch`(「一律允許」過、本來不用問的也一樣)符合「一律詢問」的樣式一定問(模型說允許也沒用);指令、檔案不用問或「一律允許」過的不比對;符合允許的樣式就允許,但用一般的話寫的「一律詢問」還是會先讓模型看一次;有藏起來的指令($()、反引號)的,樣式不會允許。樣式對不上任何東西時(`connector(…)` 沒有那個工具、`web(…)` 沒寫成 `web(domain:網站)`、`tool(…)` 不是哪一步的名字,例如要寫 `tool(browser_*)` 不是 `tool(browser)`),新增的地方會說。 - `autonomy-hooks` Hooks:使用者(和管理員)自己的程式,AnyBot 在固定的時間點跑它們,格式跟 Claude Code 一樣(hooks.json)。PreToolUse 可以擋下一步(exit 2 或 deny)、改參數、要先問或省掉一次詢問(但擋不過安全規則,也省不掉付款/傳送/刪除這類每次問);PostToolUse 改 Bot 讀到的結果或加一句;UserPromptSubmit、SessionStart 補資訊給模型或擋下這一輪;Stop 叫它多做(一輪最多 3 次);Notification 跟著通知跑。hook 自己出錯(結束碼不對、逾時、JSON 看不懂)就當它不在,紀錄檔寫原因。 - `autonomy-remote` 從手機打開:直接連線(同一個網路)的手機關得掉,但打不開直接操作、新增不了「無需詢問直接允許」規則和連接器(「這項設定會讓 Bot 不用問就動手,不能從區網連線…打開」);要在電腦上的 AnyBot,或用帳號連線。 @@ -33,7 +33,7 @@ - **手機打不開直接操作**(covers `autonomy-remote`、`autonomy-direct`、`autonomy-review`):重新整理,帳戶選單 › 設定 › 權限,按「直接操作」。指令:`$CTL phone open --listed && $CTL phone click '#b-me' && $CTL phone click '#sheet-in .opt' --text 設定 && $CTL phone click '[data-go="perms"]' && $CTL phone wait-text '刪除檔案或資料夾' && $CTL phone click 'label.sw:has([data-sset="direct_mode"])' && $CTL phone click '#sheet-in .opt' --text 打開 && $CTL phone wait-text '不能從區網連線' && $CTL phone shot autonomy-perms && $CTL wait-api /api/settings '.direct_mode == false'`。看到:「一律詢問(優先)」裡三條預設規則;按開關、確認「打開」後跳出「這項設定會讓 Bot 不用問就動手,不能從區網連線…」,直接操作還是關的。 - **桌面的閃電圖示**(covers `autonomy-yolo`):指令:要開視窗——第一步之後 `$CTL stop && ABV_ALLOW_WINDOW=1 $CTL desktop-shot autonomy-yolo ANYBOT_SHOT_REAL=1 && $CTL serve`。看到:臉的同一行右邊一個紅色閃電圖示。 - **直接操作照樣問、允許的樣式**(covers `autonomy-still-asks`、`autonomy-patterns`):指令:走不到——直接連線的手機打不開直接操作(上面那步)、也加不了「無需詢問直接允許」規則(同樣 403),scratch 也沒有你的電腦的指令和檔案。看到:連接器的樣式(「一律允許」過也問)在 [connectors](connectors.md) 的「一律允許也照樣式問」,瀏覽器的樣式和審核員在 [browser](browser.md) 的「照你的「一律詢問」」;最接近的真路是 `cargo test direct_mode_still_asks_a_connector_step_its_ask_rule_names`(用設定的開關打開直接操作:符合 `connector(…)` 的步驟跳卡片、沒有「一律允許」;一律放行照樣放行)和下面 `agent::` 的幾個(允許的樣式不跳卡片、結果寫「自動審核:符合…」)。 -- 自動測試:`cargo test always`、`cargo test gate::`(`pattern_rules_decide_before_the_model`)、`cargo test agent::`(`a_review_that_fails_asks_instead_of_allowing`、`an_ask_pattern_stops_direct_mode_without_asking_a_model`、`a_connector_ask_rule_stops_direct_mode`、`a_connector_step_in_direct_mode_is_reviewed_by_the_sentence_rules`、`a_connector_allow_rule_lets_it_run_and_an_ask_rule_wins`、`rules_about_other_things_leave_a_connector_alone`、`an_ask_pattern_wins_over_a_connectors_grant`、`connector_decisions_are_characterized`、`an_ask_pattern_stops_the_bots_browser`、`private_pages_and_uploads_go_through_the_persons_rules`)、`cargo test direct_mode_still_asks`、`cargo test hooks::`、`cargo test remote::`(`roles_gate_the_sync_and_hands_apis`)。 +- 自動測試:`cargo test always`、`cargo test gate::`(`pattern_rules_decide_before_the_model`)、`cargo test agent::`(`a_review_that_fails_asks_instead_of_allowing`、`an_ask_pattern_stops_direct_mode_without_asking_a_model`、`a_connector_ask_rule_stops_direct_mode`、`a_connector_step_in_direct_mode_is_reviewed_by_the_sentence_rules`、`a_connector_allow_rule_lets_it_run_and_an_ask_rule_wins`、`rules_about_other_things_leave_a_connector_alone`、`an_ask_pattern_wins_over_a_connectors_grant`、`connector_decisions_are_characterized`、`an_ask_pattern_stops_the_bots_browser`、`private_pages_and_uploads_go_through_the_persons_rules`、`pattern_rules_that_name_nothing_are_said_so`)、`cargo test direct_mode_still_asks`、`cargo test hooks::`、`cargo test remote::`(`roles_gate_the_sync_and_hands_apis`)。 ## 陷阱 diff --git a/docs/feature-map/browser.md b/docs/feature-map/browser.md index 3b3160e..d4c2f32 100644 --- a/docs/feature-map/browser.md +++ b/docs/feature-map/browser.md @@ -30,11 +30,11 @@ Bot 用 AnyBot 自己的瀏覽器上網、登入網站、點按、打字、送 - **公開網頁以外不讀**(covers `browser-fetch`):請 Bot 用 `web_fetch` 讀本機網址。指令:`$CTL phone send '[[call web_fetch {"url":"http://127.0.0.1:9/"}]]' && $CTL phone wait-text 'web_fetch 只讀公開的網頁' --in '#msgs' && $CTL api GET /api/bots/1 --jq '[.messages[].tools[]? | {name, status}]'`。看到:「web_fetch 只讀公開的網頁,「127.0.0.1」是這台電腦或內部網路的位址。要看本機或區網上的服務,用 shell(例如 curl)或 browser_open。」;步驟 failed。 - **中繼資料擋下、本機網址先問**(covers `browser-actions`):`open` 雲端中繼資料,再 `open` 本機網址、按「拒絕」。指令:`$CTL phone send '[[call browser {"action":"open","url":"http://169.254.169.254/latest/meta-data/"}]]' && $CTL phone wait-text '禁止在瀏覽器開啟雲端中繼資料' --in '#msgs' && $CTL phone send '[[call browser {"action":"open","url":"http://127.0.0.1:9/"}]]' && $CTL phone wait-text '在瀏覽器開啟本機或內部網路網址' --in '#ask' && $CTL phone shot browser-private && $CTL api GET '/api/state?since=0' --jq '.approvals[0] | {tool, can_always}' && $CTL phone click '#ask button[data-a="reject"]' && $CTL phone wait-text '使用者拒絕了開啟這個內部網址' --in '#msgs' && $CTL api GET /api/bots/1 --jq '[.messages[].tools[]? | select(.name == "browser_open") | .status]'`。看到:中繼資料沒有卡片就「被安全規則擋下:禁止在瀏覽器開啟雲端中繼資料(169.254.169.254)…」;本機網址跳卡片「在瀏覽器開啟本機或內部網路網址:http://127.0.0.1:9/」(可以一律允許);拒絕後兩步都是 denied。 -- **照你的「一律詢問」**(covers `browser-actions`、`browser-fetch`):打開自動審核,「一律詢問」加 `web(domain:127.0.0.1)` 和一句「打開內部網站前先問我」;`open` 本機網址、`web_fetch` 它,再 `open` 另一個內部網址,都按「拒絕」。指令:`$CTL phone click '[data-back]' && $CTL phone click '#b-me' && $CTL phone click '#sheet-in .opt' --text 設定 && $CTL phone click '[data-go="perms"]' && $CTL phone click 'label.sw:has([data-sset="auto_review"])' && $CTL wait-api /api/settings '.auto_review == true' && $CTL phone click '[data-addrule="ask"]' && $CTL phone type '#ask-in' 'web(domain:127.0.0.1)' && $CTL phone click '#ask-ok' && $CTL phone click '[data-addrule="ask"]' && $CTL phone type '#ask-in' '打開內部網站前先問我' && $CTL phone click '#ask-ok' && $CTL wait-api /api/settings '.ask_rules | length == 2' && $CTL model-reply 你是動作審核員 '{"verdict":"ask","rule":"打開內部網站前先問我"}' && $CTL phone open --listed && $CTL phone click '.row[data-bot="1"]' && $CTL phone send '[[call browser {"action":"open","url":"http://127.0.0.1:9/"}]]' && $CTL phone wait-text '規則:web(domain:127.0.0.1)' --in '#ask' && $CTL phone shot browser-rule && $CTL wait-api '/api/state?since=0' '.approvals[0].can_always == false' && $CTL phone click '#ask button[data-a="reject"]' && $CTL wait-api '/api/state?since=0' '.bots[0].busy == false' && $CTL phone send '[[call web_fetch {"url":"http://127.0.0.1:9/"}]]' && $CTL phone wait-text '規則:web(domain:127.0.0.1)' --in '#ask' && $CTL phone click '#ask button[data-a="reject"]' && $CTL wait-api '/api/state?since=0' '.bots[0].busy == false' && $CTL phone send '[[call browser {"action":"open","url":"http://192.168.1.5/"}]]' && $CTL phone wait-text '規則:打開內部網站前先問我' --in '#ask' && $CTL phone shot browser-review && $CTL phone click '#ask button[data-a="reject"]' && $CTL model-reply --clear && $CTL model 'select(.rule == "你是動作審核員") | .user[0:40]' && $CTL api GET /api/bots/1 --jq '[.messages[].tools[]? | select(.name == "browser_open" or .name == "web_fetch") | .status]'`。看到:本機網址不再是平常那張(可以一律允許)的卡,而是「在瀏覽器打開 http://127.0.0.1:9/(符合你的「一律詢問」規則:web(domain:127.0.0.1))」,只有「允許」「拒絕」;`web_fetch` 也停下來問;192.168.1.5 是平常的內部網址卡,但先給審核員看(「要審核的動作:在瀏覽器開啟本機或內部網路網址:http://192.168.1.5/」),說詢問就寫那條規則;每一步都是 denied,沒有開瀏覽器。 +- **照你的「一律詢問」**(covers `browser-actions`、`browser-fetch`):打開自動審核,「一律詢問」加 `web(domain:127.0.0.1)` 和一句「打開內部網站前先問我」;`open` 本機網址、用反斜線寫的同一個(`http://127.0.0.1\@a.com/`)、`web_fetch` 它,再 `open` 用反斜線寫的另一個內部網址,都按「拒絕」。指令:`$CTL phone click '[data-back]' && $CTL phone click '#b-me' && $CTL phone click '#sheet-in .opt' --text 設定 && $CTL phone click '[data-go="perms"]' && $CTL phone click 'label.sw:has([data-sset="auto_review"])' && $CTL wait-api /api/settings '.auto_review == true' && $CTL phone click '[data-addrule="ask"]' && $CTL phone type '#ask-in' 'web(domain:127.0.0.1)' && $CTL phone click '#ask-ok' && $CTL phone click '[data-addrule="ask"]' && $CTL phone type '#ask-in' '打開內部網站前先問我' && $CTL phone click '#ask-ok' && $CTL wait-api /api/settings '.ask_rules | length == 2' && $CTL model-reply 你是動作審核員 '{"verdict":"ask","rule":"打開內部網站前先問我"}' && $CTL phone open --listed && $CTL phone click '.row[data-bot="1"]' && $CTL phone send '[[call browser {"action":"open","url":"http://127.0.0.1:9/"}]]' && $CTL phone wait-text '規則:web(domain:127.0.0.1)' --in '#ask' && $CTL phone shot browser-rule && $CTL wait-api '/api/state?since=0' '.approvals[0].can_always == false' && $CTL phone click '#ask button[data-a="reject"]' && $CTL wait-api '/api/state?since=0' '.bots[0].busy == false' && $CTL phone send '[[call browser {"action":"open","url":"http://127.0.0.1\\@a.com/"}]]' && $CTL phone wait-text '在瀏覽器打開 http://127.0.0.1/@a.com/(符合你的「一律詢問」規則:web(domain:127.0.0.1))' --in '#ask' && $CTL phone shot browser-backslash && $CTL phone click '#ask button[data-a="reject"]' && $CTL wait-api '/api/state?since=0' '.bots[0].busy == false' && $CTL phone send '[[call web_fetch {"url":"http://127.0.0.1:9/"}]]' && $CTL phone wait-text '規則:web(domain:127.0.0.1)' --in '#ask' && $CTL phone click '#ask button[data-a="reject"]' && $CTL wait-api '/api/state?since=0' '.bots[0].busy == false' && $CTL phone send '[[call browser {"action":"open","url":"http://192.168.1.5\\.example.com/"}]]' && $CTL phone wait-text '在瀏覽器開啟本機或內部網路網址:http://192.168.1.5/.example.com/' --in '#ask' && $CTL phone wait-text '規則:打開內部網站前先問我' --in '#ask' && $CTL phone shot browser-review && $CTL phone click '#ask button[data-a="reject"]' && $CTL model-reply --clear && $CTL model 'select(.rule == "你是動作審核員") | .user[0:40]' && $CTL api GET /api/bots/1 --jq '[.messages[].tools[]? | select(.name == "browser_open" or .name == "web_fetch") | .status]'`。看到:本機網址不再是平常那張(可以一律允許)的卡,而是「在瀏覽器打開 http://127.0.0.1:9/(符合你的「一律詢問」規則:web(domain:127.0.0.1))」,只有「允許」「拒絕」;反斜線寫的照瀏覽器的讀法是 127.0.0.1,卡片寫的就是會打開的「http://127.0.0.1/@a.com/」;`web_fetch` 也停下來問;`192.168.1.5\.example.com` 一樣是內部網址(卡片寫「http://192.168.1.5/.example.com/」),先給審核員看(「要審核的動作:在瀏覽器開啟本機或內部網路網址:…」),說詢問就寫那條規則;每一步都是 denied,沒有開瀏覽器。 - **已送帳本、設定檔**(covers `browser-gate`、`browser-profiles`):請 Bot 查送過什麼、列設定檔。指令:`$CTL phone send '[[call browser {"action":"sent"}]]' && $CTL phone wait-text '帳本裡最近 30 天沒有送出紀錄' --in '#msgs' && $CTL phone send '[[call browser {"action":"profiles"}]]' && $CTL phone click '.step.done .h' --text 瀏覽器設定檔 && $CTL phone wait-text '預設(使用中)' --in '#msgs' && $CTL api GET /api/bots/1 --jq '[.messages[].tools[]? | .result][-2:]'`。看到:「帳本裡最近 30 天沒有送出紀錄(AnyBot 從開始記帳本那天起才有…)」;「AnyBot 瀏覽器的設定檔:預設(使用中)、你的瀏覽器。每個設定檔有自己的登入。…」;兩步都沒開瀏覽器。 - **真的開網頁、打字、送出**(covers `browser-actions`、`browser-refs`、`browser-type`、`browser-wait`、`browser-gate`、`browser-own`、`browser-close`、`browser-profiles`):指令:走不到——Bot 的電腦的瀏覽器要 Docker;改開在這台 Mac 會在使用者的螢幕上開真的瀏覽器。看到:最接近的真路是無頭的實機測試(下面):`click` 輸入框回「游標已在…裡」、`type` 多行整段進去、編號不變;在回覆框送出有【系統】那行和留言網址,同一篇再送被擋,搜尋框按 Enter 不算送出。 - **桌面的設定檔區塊**(covers `browser-profiles`、`browser-close`):指令:要開視窗——`$CTL stop && ABV_ALLOW_WINDOW=1 $CTL desktop-shot browser ANYBOT_SHOT_REAL=1 ANYBOT_SHOT_VIEW=computers`。看到:設定 › 電腦「AnyBot 瀏覽器設定檔」的使用中設定檔、「開啟視窗」、「做完就關掉瀏覽器」、「發布前檢查」。 -- 自動測試:`cargo test browser::`、`cargo test publish::`、`cargo test evidence::`、`cargo test an_ask_pattern_stops_the_bots_browser`、`cargo test private_pages_and_uploads_go_through_the_persons_rules`、`cargo test the_bots_browser_is_not_held_up_by_rules_about_other_things`;實機(無頭 Chrome,或 Brave/Firefox;暫存資料夾、自己的連接埠):`ANYBOT_DATA_DIR=<暫存資料夾> ANYBOT_BROWSER_PORT=9398 ANYBOT_BROWSER_FLAGS=--headless=new cargo test lines_go_in_whole_and_numbers_stay_put -- --ignored`,`a_send_is_seen_with_the_post_it_answers_and_its_own_address` 照同樣跑(Firefox 加 `ANYBOT_BROWSER_ENGINE=firefox ANYBOT_FIREFOX_HEADLESS=1`、`HOME` 也換掉)。 +- 自動測試:`cargo test browser::`、`cargo test publish::`、`cargo test evidence::`、`cargo test an_ask_pattern_stops_the_bots_browser`、`cargo test private_pages_and_uploads_go_through_the_persons_rules`、`cargo test the_bots_browser_is_not_held_up_by_rules_about_other_things`、`cargo test addresses_are_read_as_a_browser_reads_them`、`cargo test an_upload_with_the_switches_off_always_asks`、`cargo test a_hook_ask_and_a_rule_make_one_card_for_a_browser_step`;實機(無頭 Chrome,或 Brave/Firefox;暫存資料夾、自己的連接埠):`ANYBOT_DATA_DIR=<暫存資料夾> ANYBOT_BROWSER_PORT=9398 ANYBOT_BROWSER_FLAGS=--headless=new cargo test lines_go_in_whole_and_numbers_stay_put -- --ignored`,`a_send_is_seen_with_the_post_it_answers_and_its_own_address` 照同樣跑(Firefox 加 `ANYBOT_BROWSER_ENGINE=firefox ANYBOT_FIREFOX_HEADLESS=1`、`HOME` 也換掉)。 ## 陷阱 @@ -46,8 +46,8 @@ Bot 用 AnyBot 自己的瀏覽器上網、登入網站、點按、打字、送 - 下拉選單用 `select`,`option` 填選項上看得到的字(給 `value` 也行,對下拉選單 `type` 也會改成選選項);什麼都沒給會報錯。 - `fill` 是保險庫的填入;指著頁面上一個欄位(有 `ref`/`text`、沒有 kind/id/site)時當成 `type`(有 `option` 時當 `select`),不會跑去保險庫。 - `eval` 只能讀頁面:不能發請求、讀 cookie 或儲存、送出表單、換頁(會被拒絕);直接呼叫網站內部 API 會被當成機器人。 -- 雲端中繼資料位址永遠打不開;本機或內部網路的網址要使用者允許(直接操作模式除外,但符合「一律詢問」規則的照樣問)。 -- 自動審核開著時,「一律詢問」寫成樣式(`tool(browser_click)`、`web(domain:example.com)`)的,AnyBot 瀏覽器的步驟和 `web_fetch` 每次都停下來問,本來不用問、一律允許過的也一樣;用一般的話寫的只看本來就要問的(本機網址、上傳檔案)。 +- 雲端中繼資料位址永遠打不開;本機或內部網路的網址先問使用者(可以一律允許)——直接操作開著、或自動審核的「無需詢問直接允許」符合時不問,符合「一律詢問」的照樣問。網址照瀏覽器的讀法判斷:大小寫、結尾的點、`帳號@`、反斜線、十進位寫的 IP 都看得出是哪台。 +- 自動審核開著時,「一律詢問」的樣式本來不用問、一律允許過的也照樣問:`tool(…)` 比對每一步的名字(`tool(browser_click)`、`tool(browser_*)`);`web(domain:example.com)` 比對用網址打開或讀的那一步(`open`、帶網址開新分頁、`web_fetch`),點連結、網頁自己轉址、上一頁到的網頁不比對。用一般的話寫的只看本來就要問的(本機網址、上傳檔案)。從這台上傳檔案時 Bot 的電腦工具或「在這台電腦上執行」沒開,一律跳卡片,規則省不掉。 - 發布關卡、已送帳本、送出後確認只管 AnyBot 自己的瀏覽器;用螢幕操作送出的,只能從步驟推算。頁面看不出回哪一篇時,只擋 24 小時內同一頁一模一樣的內容。 - 送出後頁面上沒看到(例如從動態牆送出),結果寫「還沒確認」:不要因此再送一次,回原貼文看。 - 網頁要上傳檔案(Threads、IG 加相片、表單附件):用 `upload` 直接放進頁面的檔案欄位。用螢幕去點「加入相片」會跳出 Bot 電腦的檔案視窗(「取消」「Open」在最上面),還要在裡面找檔案、按 Open。 diff --git a/src/agent.rs b/src/agent.rs index 211fbee..dfdfe60 100644 --- a/src/agent.rs +++ b/src/agent.rs @@ -1874,9 +1874,9 @@ fn run_call(t: CallTurn<'_>, asked: ToolCall) -> Flow { browser: Default::default(), }; let tool = steps::tool_for(&s); - // A hook's 「ask」: OnComputer and Connector put it with their own question (one card); every - // other tool asks here (an app action, a file sent out… would have gone ahead). - if !matches!(tool.name(), "OnComputer" | "Connector") { + // A hook's 「ask」: OnComputer, Connector and InBotsBrowser put it with their own question (one + // card); every other tool asks here (an app action, a file sent out… would have gone ahead). + if !matches!(tool.name(), "OnComputer" | "Connector" | "InBotsBrowser") { if let Some(why) = s.hook_word.permission.clone().filter(|(p, _)| p == "ask").map(|(_, w)| w) { let answer = s.ask_person(ApprovalKind::Action, format!("{}(你的 hook 要先問:{})", s.what(), if why.is_empty() { "沒有說原因" } else { why.as_str() }), String::new()); if s.cancel.load(Ordering::Relaxed) { @@ -4794,18 +4794,25 @@ echo 'done送出了' > done.html; (setsid pyt fn an_ask_pattern_stops_the_bots_browser() { for direct in [false, true] { let mine = Review { allow: vec![], ask: vec!["tool(browser_click)".into(), "web(domain:example.com)".into(), "web(domain:127.0.0.1)".into()] }; + let open = |id: &str, url: &str| sse_call(id, "browser", serde_json::json!({"action": "open", "url": url})); let replies = vec![ sse_call("c1", "browser", serde_json::json!({"action": "click", "ref": "3"})), - sse_call("c2", "browser", serde_json::json!({"action": "open", "url": "https://shop.example.com/cart"})), + open("c2", "https://shop.example.com/cart"), sse_call("c3", "web_fetch", serde_json::json!({"url": "http://127.0.0.1:9/"})), + // The host a browser opens, however the address is written (the reviewer's probes). + open("c4", "https://me@example.com/cart"), + open("c5", "https://shop.example.com./cart"), + open("c6", "https://example.com\\cart"), + sse_call("c7", "browser_tabs", serde_json::json!({"action": "new", "url": "https://shop.example.com/cart"})), ]; let (asked, results, seen) = browser_turn(replies, direct, Some(mine), &[], ApprovalAnswer::Reject); - assert_eq!(asked.len(), 3, "direct={direct}: {asked:?} {results:?}"); - for ((reason, grant), rule) in asked.iter().zip(["tool(browser_click)", "web(domain:example.com)", "web(domain:127.0.0.1)"]) { + assert_eq!(asked.len(), 7, "direct={direct}: {asked:?} {results:?}"); + for ((reason, grant), rule) in asked.iter().zip(["tool(browser_click)", "web(domain:example.com)", "web(domain:127.0.0.1)", "web(domain:example.com)", "web(domain:example.com)", "web(domain:example.com)", "web(domain:example.com)"]) { assert!(reason.contains(&format!("符合你的「一律詢問」規則:{rule}")) && grant.is_empty(), "{reason} [{grant}]"); } + assert!(asked[5].0.contains("https://example.com/cart"), "the card shows the address that would open: {}", asked[5].0); assert!(results.iter().all(|r| r.contains("使用者拒絕了這個操作")), "{results:?}"); - assert_eq!(seen.len(), 4, "no model call to review them"); + assert_eq!(seen.len(), 8, "no model call to review them"); } } @@ -4850,6 +4857,69 @@ echo 'done送出了' > done.html; (setsid pyt assert!(asked.is_empty(), "直接操作 with no rules: {asked:?}"); } + /// An upload of a file of this computer while the bot's computer tools or 在這台電腦上執行 are + /// off: the switches' question is a card whatever 自動審核 says (gate steps 3 and 5 before 7) — + /// an allow rule saved it before. With them on, the allow rule lets it go; 直接操作 counts as on. + #[test] + fn an_upload_with_the_switches_off_always_asks() { + let w = std::env::temp_dir().join(format!("anybot-upload-{}", std::process::id())); + std::fs::create_dir_all(&w).unwrap(); + std::fs::write(w.join("a.txt"), "x").unwrap(); + let here = tools::Target { name: crate::model::THIS_COMPUTER_NAME.into(), place: tools::Place::Local { workdir: w.clone() } }; + let allow = Some(Review { allow: vec!["tool(browser_upload)".into()], ask: vec![] }); + let job = |direct: bool| Job { review: allow.clone(), direct: Arc::new(AtomicBool::new(direct)), ..test_job() }; + let args = serde_json::json!({"ref": "4", "path": "a.txt"}).to_string(); + let decide = |job: &Job, switches_on: bool| steps::here_upload_decision(job, &args, &here, "a.txt", &w.join("a.txt"), &[], false, switches_on, &AtomicBool::new(false)); + let (d, switch, note) = decide(&job(false), false); + assert!(matches!(&d, Decision::Ask { grant, .. } if grant.is_empty()) && switch && note.is_empty(), "switches off: {d:?}"); + let (d, switch, note) = decide(&job(false), true); + assert!(d == Decision::Allow && !switch && note.is_empty(), "switches on, a file in the work folder: {d:?}"); + // A file outside the work folder is asked about by the file rules: 自動審核's allow lets it go. + let out = std::env::temp_dir().join(format!("anybot-upload-out-{}.txt", std::process::id())); + std::fs::write(&out, "y").unwrap(); + let path = out.display().to_string(); + let (d, switch, note) = steps::here_upload_decision(&job(false), &args, &here, &path, &out, &[], false, true, &AtomicBool::new(false)); + assert!(d == Decision::Allow && !switch && note.contains("tool(browser_upload)"), "outside, switches on: {d:?} {note}"); + let (d, switch, _) = steps::here_upload_decision(&job(false), &args, &here, &path, &out, &[], false, false, &AtomicBool::new(false)); + assert!(matches!(d, Decision::Ask { .. }) && switch, "outside, switches off: {d:?}"); + let (d, _, _) = decide(&job(true), true); + assert_eq!(d, Decision::Allow, "直接操作"); + let _ = std::fs::remove_file(&out); + let _ = std::fs::remove_dir_all(&w); + } + + /// A hook's 「ask」 about an AnyBot-browser step goes on the same card as a pattern rule's (one + /// card, no 「一律允許」); alone it is a card of its own, as before. + #[cfg(unix)] + #[test] + fn a_hook_ask_and_a_rule_make_one_card_for_a_browser_step() { + use crate::hooks::{Config, Group, Hook, Hooks}; + let mut c = Config::default(); + let hook = Hook { kind: "command".into(), command: r#"echo '{"hookSpecificOutput":{"permissionDecision":"ask","permissionDecisionReason":"瀏覽器先給我看"}}'"#.into(), url: String::new(), headers: Default::default(), timeout: Some(10) }; + c.hooks.insert("PreToolUse".into(), vec![Group { matcher: "browser_.*".into(), hooks: vec![hook] }]); + crate::hooks::test_hooks().lock().unwrap().insert(1, Hooks { admin: Config::default(), mine: c }); + let click = || sse_call("c1", "browser", serde_json::json!({"action": "click", "ref": "3"})); + let mine = Some(Review { allow: vec![], ask: vec!["tool(browser_click)".into()] }); + let (both, _, _) = browser_turn(vec![click()], false, mine, &[], ApprovalAnswer::Reject); + let (alone, _, _) = browser_turn(vec![click()], false, None, &[], ApprovalAnswer::Reject); + crate::hooks::test_hooks().lock().unwrap().remove(&1); + assert!(both.len() == 1 && both[0].0.contains("規則:tool(browser_click)") && both[0].0.contains("你的 hook 要先問:瀏覽器先給我看") && both[0].1.is_empty(), "{both:?}"); + assert!(alone.len() == 1 && alone[0].0.contains("你的 hook 要先問:瀏覽器先給我看") && alone[0].1.is_empty(), "{alone:?}"); + } + + /// Pattern rules nothing is compared with are said so where they are added: a connector's + /// that names no tool, a web(…) not written as web(domain:site), a tool(…) by a name no step runs as. + #[test] + fn pattern_rules_that_name_nothing_are_said_so() { + let w = |r: &str| crate::gate::rule_warning(r, &[]); + for ok in ["web(domain:example.com)", "web(domain:Bücher.example)", "tool(browser_click)", "tool(browser_*)", "tool(web_fetch)", "tool(shell)", "tool(computer_use_click)", "shell(git *)", "file(~/x/**)", "付款前先問我"] { + assert_eq!(w(ok), None, "{ok}"); + } + for (bad, says) in [("tool(browser)", "browser_click"), ("tool(computer)", "computer_use_click"), ("web(example.com)", "web(domain:"), ("web(domain:*.example.com)", "不用 *"), ("web(domain:https://example.com/a)", "整個 example.com"), ("web(domain:not a site)", "看起來不是網站")] { + assert!(w(bad).is_some_and(|t| t.contains(says)), "{bad}: {:?}", w(bad)); + } + } + /// A connector step's decision on fixed rules, as Allow / Allow+note (自動審核 let it, the result /// says so) / Ask[the grant 「一律允許」 would keep] with why (rule=…, failed, hook), and how many /// times the reviewer model was asked — 「一律允許」 for the connector or not × 直接操作 or not × @@ -4863,18 +4933,27 @@ echo 'done送出了' > done.html; (setsid pyt let add = crate::mcp::tool_name("calc-ch", "add"); let says = |text: &str| Fake::start(Format::OpenAi, vec![], Some(Reply::text(text))); let (ask, none, garbled) = (says(r#"{"verdict":"ask","rule":"傳訊息給別人前先問我"}"#), says(r#"{"verdict":"none","rule":""}"#), says("嗯…讓我想想")); + let allow = says(r#"{"verdict":"allow","rule":"計算不用問"}"#); + let short = r#"{"a":1,"b":2}"#.to_string(); + // An argument longer than the reviewer reads, what a rule would name in the middle. + let long = format!(r#"{{"a":"{}","to":"SECRET-IN-THE-MIDDLE","z":"{}"}}"#, "x".repeat(3500), "y".repeat(3500)); let rules = |allow: &[&str], ask: &[&str]| Some(Review { allow: allow.iter().map(|r| r.to_string()).collect(), ask: ask.iter().map(|r| r.to_string()).collect() }); let words = "傳訊息給別人前先問我"; - let sets: Vec<(&str, Option, &Fake)> = vec![ - ("off", None, &none), - ("ask-pattern", rules(&[], &["connector(calc-ch__add)"]), &none), - ("allow-pattern", rules(&["connector(calc-ch__*)"], &[]), &none), - ("both-patterns", rules(&["connector(calc-ch__*)"], &["connector(calc-ch__add)"]), &none), - ("other-connector", rules(&["connector(other__*)"], &["connector(other__*)"]), &none), - ("sentence:ask", rules(&[], &[words]), &ask), - ("sentence:none", rules(&[], &[words]), &none), - ("sentence:garbled", rules(&[], &[words]), &garbled), - ("allow-pattern+sentence:ask", rules(&["connector(calc-ch__*)"], &[words]), &ask), + let sets: Vec<(&str, Option, &Fake, &String)> = vec![ + ("off", None, &none, &short), + ("ask-pattern", rules(&[], &["connector(calc-ch__add)"]), &none, &short), + ("allow-pattern", rules(&["connector(calc-ch__*)"], &[]), &none, &short), + ("both-patterns", rules(&["connector(calc-ch__*)"], &["connector(calc-ch__add)"]), &none, &short), + ("other-connector", rules(&["connector(other__*)"], &["connector(other__*)"]), &none, &short), + ("sentence:ask", rules(&[], &[words]), &ask, &short), + ("sentence:none", rules(&[], &[words]), &none, &short), + ("sentence:garbled", rules(&[], &[words]), &garbled, &short), + ("allow-pattern+sentence:ask", rules(&["connector(calc-ch__*)"], &[words]), &ask, &short), + ("sentence-allow:allow", rules(&["計算不用問"], &[]), &allow, &short), + ("cut sentence-allow:allow", rules(&["計算不用問"], &[]), &allow, &long), + ("cut sentence:none", rules(&[], &[words]), &none, &long), + ("cut allow-pattern", rules(&["connector(calc-ch__*)"], &[]), &none, &long), + ("cut ask-pattern", rules(&[], &["connector(calc-ch__add)"]), &none, &long), ]; let shape = |d: &Decision, note: &str| match d { Decision::Allow if note.is_empty() => "Allow".to_string(), @@ -4889,17 +4968,18 @@ echo 'done送出了' > done.html; (setsid pyt String::new() }; let hook = if reason.contains("你的 hook 要先問") { " +hook" } else { "" }; - format!("Ask[{grant}]{why}{hook}") + let cut = if reason.contains(steps::REVIEW_CUT_NOTE) { " cut" } else { "" }; + format!("Ask[{grant}]{why}{hook}{cut}") } }; let mut got = vec![]; - for (set, review, fake) in &sets { + for (set, review, fake, args) in &sets { for granted in [false, true] { for direct in [false, true] { let job = Job { req: ChatRequest { base_url: fake.base(), model: "m".into(), ..test_job().req }, review: review.clone(), direct: Arc::new(AtomicBool::new(direct)), ..test_job() }; let grants: Vec = if granted { vec!["mcp:calc-ch".into()] } else { vec![] }; let before = fake.requests(); - let (d, note) = steps::connector_decision(&job, &grants, &add, r#"{"a":1,"b":2}"#, None, &AtomicBool::new(false)); + let (d, note) = steps::connector_decision(&job, &grants, &add, args, None, &AtomicBool::new(false)); got.push(format!("{set} granted={granted} direct={direct}: {} model={}", shape(&d, ¬e), fake.requests() - before)); } } @@ -4924,6 +5004,12 @@ echo 'done送出了' > done.html; (setsid pyt ("sentence:none", ["Ask[mcp:calc-ch] model=1", "Allow model=1", "Allow model=0", "Allow model=0"].map(String::from)), ("sentence:garbled", ["Ask[mcp:calc-ch] failed model=1", "Ask[] failed model=1", "Allow model=0", "Allow model=0"].map(String::from)), ("allow-pattern+sentence:ask", [format!("Ask[]{rule_w} model=1"), format!("Ask[]{rule_w} model=1"), "Allow model=0".into(), "Allow model=0".into()]), + ("sentence-allow:allow", ["Allow+note model=1", "Allow model=0", "Allow model=0", "Allow model=0"].map(String::from)), + // The reviewer read only the ends: its yes, or 直接操作's "no rule is about it", asks. + ("cut sentence-allow:allow", ["Ask[mcp:calc-ch] cut model=1", "Allow model=0", "Allow model=0", "Allow model=0"].map(String::from)), + ("cut sentence:none", ["Ask[mcp:calc-ch] model=1", "Ask[] cut model=1", "Allow model=0", "Allow model=0"].map(String::from)), + ("cut allow-pattern", ["Allow+note model=0", "Allow model=0", "Allow model=0", "Allow model=0"].map(String::from)), + ("cut ask-pattern", [0; 4].map(|_| format!("Ask[]{rule_a} model=0"))), ] .into_iter() .flat_map(|(set, four)| [(false, false), (false, true), (true, false), (true, true)].into_iter().zip(four).map(move |((g, d), w)| format!("{set} granted={g} direct={d}: {w}"))) diff --git a/src/agent/steps.rs b/src/agent/steps.rs index efc5cd7..2f0bac0 100644 --- a/src/agent/steps.rs +++ b/src/agent/steps.rs @@ -497,6 +497,35 @@ impl TurnTool for SentLog { } } +/// An upload of a file of this computer to a page in AnyBot's browser: what the person +/// attached for this bot goes; 在這台電腦上執行 locked refuses; with the bot's computer tools or +/// 在這台電腦上執行 off (`switches_on` false, 直接操作 counts as on) the switches' question is +/// asked as it is — gate steps 3 and 5 come before 自動審核 (step 7), so no rule saves it; else +/// the file rules (tools::decide_file_out), then `reviewed` (自動審核, 直接操作). Returns the +/// decision, whether it is the switches' question (no other yes saves it), and the note. +#[allow(clippy::too_many_arguments)] +pub(super) fn here_upload_decision(job: &Job, args: &str, here: &tools::Target, path: &str, named: &std::path::Path, grants: &[String], given: bool, switches_on: bool, cancel: &AtomicBool) -> (Decision, bool, String) { + if given { + return (Decision::Allow, false, String::new()); + } + if job.local_locked { + return (Decision::Deny(format!("「在這台電腦上執行」設成了永不允許(或被管理員關閉),不能上傳「{}」上的檔案。", here.name)), false, String::new()); + } + let outside = |grant: String| Decision::Ask { reason: format!("把工作資料夾以外的檔案上傳到網頁:{}", named.display()), grant }; + match tools::decide_file_out(here, path, grants) { + Decision::Allow if !switches_on => (Decision::Ask { reason: format!("把「{}」上的檔案上傳到網頁:{}", here.name, named.display()), grant: String::new() }, true, String::new()), + Decision::Ask { grant, .. } if !switches_on => (outside(grant), true, String::new()), + d => { + let d = match d { + Decision::Ask { grant, .. } => outside(grant), + d => d, + }; + let (d, _, note) = reviewed(job, "browser_upload", args, d, false, cancel); + (d, false, note) + } + } +} + /// Public web pages need no computer and no permission — and neither does AnyBot's own /// browser (like the reference assistant's own browser). A step naming a computer with no /// browser there is said so, not run elsewhere. @@ -540,11 +569,18 @@ impl TurnTool for InBotsBrowser { // bot goes as it is. The path is made whole here, so the browser takes the // very file that was checked. let mut call_args = call.args.clone(); - // The page this step opens, made whole: the safety rules first. - let opens = (call.name == "browser_open" || (call.name == "browser_tabs" && tools::args_of(&call.args)["action"].as_str() == Some("new"))) - .then(|| tools::args_of(&call.args)["url"].as_str().unwrap_or("").trim().to_string()) - .filter(|u| !u.is_empty()) - .and_then(|u| web::normalize_url(&u).ok()); + // The page this step opens or fetches by its address, as a browser reads it (web::parse_url): + // the browser is handed that very address, and the safety rules, the private-network card + // and the person's rules all check it — what is checked is what opens. + let by_address = call.name == "browser_open" || call.name == "web_fetch" || (call.name == "browser_tabs" && tools::args_of(&call.args)["action"].as_str() == Some("new")); + let url_given = tools::args_of(&call.args)["url"].as_str().unwrap_or("").trim().to_string(); + let canonical = by_address.then(|| web::normalize_url(&url_given).ok()).flatten(); + if let Some(c) = &canonical { + let mut v = tools::args_of(&call.args); + v["url"] = serde_json::Value::String(c.clone()); + call_args = v.to_string(); + } + let opens = canonical.clone().filter(|_| call.name != "web_fetch"); let private = opens.as_deref().is_some_and(|norm| !matches!(place, BrowserAt::Box) && web::is_private_browser_url(norm)); if opens.as_deref().is_some_and(web::is_forbidden_browser_url) { s.finish("被安全規則擋下:禁止在瀏覽器開啟雲端中繼資料(169.254.169.254)或系統內部管理端點。", ToolStatus::Denied, None); @@ -555,13 +591,22 @@ impl TurnTool for InBotsBrowser { return Flow::Next; } // The person's 「一律詢問」 patterns (only compared, no model call) over a browser step that - // needs no permission or was 「一律允許」, as for a connector: one card naming the rule; a yes - // to it is the yes to this step (no second card below). What would be asked anyway goes - // through `reviewed` (自動審核, 直接操作) — never sentences on every click. + // needs no permission or was 「一律允許」, as for a connector — and a hook's 「ask」 on the same + // card: one card naming the rule; a yes to it is the yes to this step (no second card below, + // except the switches' own). What would be asked anyway goes through `reviewed` (自動審核, + // 直接操作) — never sentences on every click. let on_line = if on.is_empty() { String::new() } else { format!("\n(在 {on} 上)") }; + let step_words = format!("{} {}", web::label(&call.name), canonical.clone().unwrap_or_else(|| s.what())); + let hook_ask = s.hook_word.permission.clone().filter(|(p, _)| p == "ask").map(|(_, why)| format!("(你的 hook 要先問:{})", if why.is_empty() { "沒有說原因" } else { why.as_str() })); + let first = match (ask_pattern(job, &call.name, &call_args, &step_words), hook_ask) { + (Some(Decision::Ask { reason, .. }), Some(hook)) => Some(format!("{reason}{hook}")), + (Some(Decision::Ask { reason, .. }), None) => Some(reason), + (_, Some(hook)) => Some(format!("{step_words}{hook}")), + _ => None, + }; let mut said_yes = false; - if let Some(Decision::Ask { reason, grant }) = ask_pattern(job, &call.name, &call.args, &format!("{} {}", web::label(&call.name), s.what())) { - if s.ask_person(ApprovalKind::Action, format!("{reason}{on_line}"), grant) == ApprovalAnswer::Reject { + if let Some(reason) = first { + if s.ask_person(ApprovalKind::Action, format!("{reason}{on_line}"), String::new()) == ApprovalAnswer::Reject { s.finish("使用者拒絕了這個操作。在他傳下一則訊息之前不要再試同樣的操作,也不要換個寫法做同一件事;告訴他你停在哪裡,問他想怎麼做。", ToolStatus::Denied, None); return Flow::Next; } @@ -574,7 +619,7 @@ impl TurnTool for InBotsBrowser { if let (true, false, Some(norm)) = (private, said_yes, opens.as_deref()) { let grant = "browser:private".to_string(); let decision = if s.grants.contains(&grant) { Decision::Allow } else { Decision::Ask { reason: format!("在瀏覽器開啟本機或內部網路網址:{norm}"), grant } }; - let (decision, _, note) = reviewed(job, &call.name, &call.args, decision, false, cancel); + let (decision, _, note) = reviewed(job, &call.name, &call_args, decision, false, cancel); review_note = note; if let Decision::Ask { reason, grant } = decision { match s.ask_person(ApprovalKind::Action, format!("{reason}{on_line}"), grant) { @@ -603,25 +648,14 @@ impl TurnTool for InBotsBrowser { tools::Place::Local { workdir } => tools::resolve(workdir, &path), _ => std::path::PathBuf::from(&path), }; - let direct = job.direct.load(Ordering::Relaxed); - let decision = if crate::attach::is_given(bot_id, &named) { - Decision::Allow - } else if job.local_locked { - Decision::Deny(format!("「在這台電腦上執行」設成了永不允許(或被管理員關閉),不能上傳「{}」上的檔案。", here.name)) - } else { - match tools::decide_file_out(&here, &path, s.grants) { - Decision::Allow if !direct && !(*s.tools_on && *s.local_on) => Decision::Ask { reason: format!("把「{}」上的檔案上傳到網頁:{}", here.name, named.display()), grant: String::new() }, - Decision::Ask { grant, .. } => Decision::Ask { reason: format!("把工作資料夾以外的檔案上傳到網頁:{}", named.display()), grant }, - d => d, - } - }; - // (直接操作 and 自動審核 as for any step: an 「一律詢問」 rule still stops it.) - let (decision, _, note) = reviewed(job, &call.name, &call.args, decision, false, cancel); + let given = crate::attach::is_given(bot_id, &named); + let switches_on = job.direct.load(Ordering::Relaxed) || (*s.tools_on && *s.local_on); + let (decision, switch_asks, note) = here_upload_decision(job, &call_args, &here, &path, &named, s.grants, given, switches_on, cancel); review_note = note; let refused = match decision { Decision::Allow => None, Decision::Deny(r) => Some(format!("被安全規則擋下:{r}")), - Decision::Ask { .. } if said_yes => None, + Decision::Ask { .. } if said_yes && !switch_asks => None, Decision::Ask { reason, grant } => { let (atx, arx) = channel(); send(StreamEvent::ToolStatus(call.id.clone(), ToolStatus::Waiting)); @@ -654,7 +688,7 @@ impl TurnTool for InBotsBrowser { } let grant = format!("upload-device:{on}"); let decision = if s.grants.contains(&grant) { Decision::Allow } else { Decision::Ask { reason: format!("把「{on}」上的檔案上傳到網頁:{path}"), grant } }; - let (decision, _, note) = reviewed(job, &call.name, &call.args, decision, false, cancel); + let (decision, _, note) = reviewed(job, &call.name, &call_args, decision, false, cancel); review_note = note; if let (Decision::Ask { reason, grant }, false) = (decision, said_yes) { let (atx, arx) = channel(); @@ -1554,8 +1588,28 @@ fn ask_pattern(job: &Job, name: &str, args: &str, reason: &str) -> Option bool { + use crate::gate::{is_pattern, patterns, PatternVerdict}; + let Some(rv) = &job.review else { return false }; + let words = |v: &[String]| v.iter().any(|r| !is_pattern(r)); + if job.direct.load(Ordering::Relaxed) { + return matches!(patterns(name, args, &[], &rv.ask), PatternVerdict::NoMatch) && words(&rv.ask); + } + match patterns(name, args, &rv.allow, &rv.ask) { + PatternVerdict::Ask(_) => false, + PatternVerdict::Allow(_) => words(&rv.ask), + PatternVerdict::NoMatch => words(&rv.ask) || words(&rv.allow), + } +} + /// Arguments as the reviewer reads them: whole up to [`REVIEW_ARGS`], else the start and the end -/// with how much was left out between them. +/// with how much was left out between them (and then its yes is not enough: REVIEW_CUT_NOTE). pub(super) fn for_reviewer(args: &str) -> String { let n = args.chars().count(); if n <= REVIEW_ARGS { @@ -1582,8 +1636,13 @@ pub(super) fn connector_decision(job: &Job, grants: &[String], name: &str, args: None if grants.contains(&grant) => (Decision::Allow, String::new()), None => { let read = format!("{what}{}", for_reviewer(args)); - match reviewed(job, name, args, Decision::Ask { reason: read.clone(), grant }, false, cancel) { + // The reviewer read only the two ends of a long argument: its yes (or, in 直接操作, its + // "no rule is about it") doesn't cover the middle, which the model chose to put there. + let cut = args.chars().count() > REVIEW_ARGS && model_reads(job, name, args); + let direct = job.direct.load(Ordering::Relaxed); + match reviewed(job, name, args, Decision::Ask { reason: read.clone(), grant: grant.clone() }, false, cancel) { (Decision::Ask { reason, grant }, _, note) => (Decision::Ask { reason: reason.strip_prefix(&read).map(|rest| format!("{card}{rest}")).unwrap_or(reason), grant }, note), + (Decision::Allow, _, _) if cut => (Decision::Ask { reason: format!("{card}{REVIEW_CUT_NOTE}"), grant: if direct { String::new() } else { grant } }, String::new()), (d, _, note) => (d, note), } } diff --git a/src/app.rs b/src/app.rs index 44ab3c5..d45af7a 100644 --- a/src/app.rs +++ b/src/app.rs @@ -5993,8 +5993,8 @@ impl App { }); }); }); - // A connector(…) rule that names no connector's tool: said where it is. - if let Some(w) = crate::mcp::rule_names_nothing(r, &self.state.mcp_servers) { + // A pattern rule nothing it is compared with answers to: said where it is. + if let Some(w) = crate::gate::rule_warning(r, &self.state.mcp_servers) { hint(ui, w, p); } } diff --git a/src/app/remote_ui.rs b/src/app/remote_ui.rs index 566ed44..1b4afdd 100644 --- a/src/app/remote_ui.rs +++ b/src/app/remote_ui.rs @@ -1552,7 +1552,7 @@ impl App { if text.is_empty() { return fail("規則是空的"); } - let unknown = crate::mcp::rule_names_nothing(&text, &self.state.mcp_servers); + let unknown = crate::gate::rule_warning(&text, &self.state.mcp_servers); if !list.contains(&text) { list.push(text); } diff --git a/src/featuremap.rs b/src/featuremap.rs index 83ee473..79a3255 100644 --- a/src/featuremap.rs +++ b/src/featuremap.rs @@ -128,6 +128,27 @@ pub fn read(topic: &str) -> Result { .ok_or_else(|| format!("沒有「{t}」這一區。可以讀:{}", AREAS.iter().map(|a| a.slug).collect::>().join("、"))) } +/// Every tool a bot can be given, from where the window puts them together (app.rs), as it is +/// offered (the one `browser` and `computer` tools among them). +pub fn every_tool() -> Vec { + let names = |specs: &[Value]| specs.iter().filter_map(|t| t["name"].as_str().map(String::from)).collect::>(); + let one = vec!["x".to_string()]; + let mut all = names(&crate::appctl::specs()); + all.extend(names(&crate::tools::specs_for(&one, "x"))); + all.extend(names(&crate::web::specs_for(&one, "x"))); + all.extend(names(&crate::computer::specs_for(&one, "x", true))); + all.extend(names(&crate::macapps::specs())); + all.extend(names(&crate::phone::specs())); + all.extend(names(&crate::vault::specs_for(&crate::vault::Offer { login: true, card: true, contact: true }))); + all.extend(crate::ask::spec()["name"].as_str().map(String::from)); + all.extend([crate::plan::SUBMIT_TOOL, crate::plan::UPDATE_TOOL, crate::outputs::TOOL].map(String::from)); + all.extend(crate::teach::view_step_spec()["name"].as_str().map(String::from)); + all.extend([crate::mcp::FIND_TOOL, crate::mcp::USE_TOOL, crate::agent::REPLAY_TOOL, crate::tools::HANDOFF_TOOL, "show_card", "react", "send_to_device", "send_file", "open_for_person", "publish_site", TOOL].map(String::from)); + all.sort(); + all.dedup(); + all +} + #[cfg(test)] mod tests { use super::*; @@ -142,33 +163,10 @@ mod tests { bot_view(AREAS.iter().find(|a| a.slug == slug).unwrap().text) } - fn names(specs: &[Value]) -> Vec { - specs.iter().filter_map(|t| t["name"].as_str().map(String::from)).collect() - } - fn actions(specs: &[Value], tool: &str) -> Vec { specs.iter().filter(|t| t["name"] == tool).flat_map(|t| t["parameters"]["properties"]["action"]["enum"].as_array().cloned().unwrap_or_default()).filter_map(|a| a.as_str().map(String::from)).collect() } - /// Every tool a bot can be given, from where the window puts them together (app.rs). - fn every_tool() -> Vec { - let one = vec!["x".to_string()]; - let mut all = names(&crate::appctl::specs()); - all.extend(names(&crate::tools::specs_for(&one, "x"))); - all.extend(names(&crate::web::specs_for(&one, "x"))); - all.extend(names(&crate::computer::specs_for(&one, "x", true))); - all.extend(names(&crate::macapps::specs())); - all.extend(names(&crate::phone::specs())); - all.extend(names(&crate::vault::specs_for(&crate::vault::Offer { login: true, card: true, contact: true }))); - all.push(crate::ask::spec()["name"].as_str().unwrap().to_string()); - all.extend([crate::plan::SUBMIT_TOOL, crate::plan::UPDATE_TOOL, crate::outputs::TOOL].map(String::from)); - all.push(crate::teach::view_step_spec()["name"].as_str().unwrap().to_string()); - all.extend([crate::mcp::FIND_TOOL, crate::mcp::USE_TOOL, crate::agent::REPLAY_TOOL, crate::tools::HANDOFF_TOOL, "show_card", "react", "send_to_device", "send_file", "open_for_person", "publish_site", TOOL].map(String::from)); - all.sort(); - all.dedup(); - all - } - #[test] fn every_tool_a_bot_can_be_given_is_on_the_map() { let map = map_text(); diff --git a/src/gate.rs b/src/gate.rs index e82b3b0..d858bb8 100644 --- a/src/gate.rs +++ b/src/gate.rs @@ -230,10 +230,6 @@ pub fn glob(pat: &str, text: &str, slash_stops: bool) -> bool { go(&p, &t, slash_stops) } -fn host_of(url: &str) -> String { - url.split("://").nth(1).unwrap_or(url).split(['/', ':', '?', '#']).next().unwrap_or("").to_ascii_lowercase() -} - /// Whether `rule` (a pattern) is about this step; `all` for an allow (every part of a command /// must match), any part for an ask. fn pattern_matches(rule: &str, name: &str, args: &serde_json::Value, all: bool) -> bool { @@ -263,16 +259,69 @@ fn pattern_matches(rule: &str, name: &str, args: &serde_json::Value, all: bool) let tool = if name == crate::mcp::USE_TOOL { s("tool") } else { name.to_string() }; tool.strip_prefix("mcp__").is_some_and(|t| glob(inner, t, false)) } - "web" if matches!(name, "web_fetch" | "browser_open") => { - let host = host_of(&s("url")); - let want = inner.strip_prefix("domain:").unwrap_or(inner).trim().to_ascii_lowercase(); - !host.is_empty() && (host == want || host.ends_with(&format!(".{want}"))) + // Every way a step opens or fetches a page by its address (a new tab with one too): the + // host as the browser reads it (web::host_of — `\`, user@, case, a trailing dot, IDNA, + // IPs in any spelling), the rule's domain read the same way. (Pages reached by a click, a + // redirect or 上一頁 aren't opened by address: no rule sees them.) + "web" if matches!(name, "web_fetch" | "browser_open") || (name == "browser_tabs" && s("action") == "new") => { + let want = inner.strip_prefix("domain:").unwrap_or(inner).trim(); + match (crate::web::host_of(&s("url")), crate::web::host_of(want)) { + (Some(host), Some(want)) => host == want || host.ends_with(&format!(".{want}")), + _ => false, + } } "tool" => glob(inner, name, false), _ => false, } } +/// Every name a `tool(…)` pattern is compared with: the tools as steps run (the one `browser` and +/// `computer` tools are opened up into browser_click, computer_use_click…), connectors' too. +fn tool_names() -> Vec { + static FIXED: std::sync::OnceLock> = std::sync::OnceLock::new(); + let mut v = FIXED + .get_or_init(|| { + let mut v = crate::featuremap::every_tool(); + v.extend(crate::browser::NAMES.iter().chain(crate::computer::NAMES.iter()).chain(crate::web::NAMES.iter()).map(|n| n.to_string())); + v.extend(["browser_fill_login", "browser_fill_card", "browser_fill_contact"].map(String::from)); + v.retain(|n| n != crate::browser::TOOL && n != crate::computer::TOOL); + v + }) + .clone(); + v.extend(crate::mcp::tools().iter().map(|t| crate::mcp::tool_name(&t.server, &t.name))); + v +} + +/// What to tell the person adding a rule written as a pattern that nothing it is compared with +/// answers to — said where the rule is added (the settings page, the phone). None: it can match, +/// or it is a sentence for the model, or a shell / file pattern (any command or path may come). +pub fn rule_warning(rule: &str, servers: &[crate::mcp::Server]) -> Option { + let r = rule.trim(); + if !is_pattern(r) { + return None; + } + let (kind, inner) = r.split_once('(').map(|(k, rest)| (k, rest.strip_suffix(')').unwrap_or(rest).trim()))?; + match kind { + "connector" => crate::mcp::rule_names_nothing(r, servers), + "web" => { + let Some(domain) = inner.strip_prefix("domain:").map(str::trim) else { + return Some(format!("「{r}」要寫成 web(domain:網站),例如 web(domain:example.com)。")); + }; + if domain.contains('*') { + Some(format!("「{r}」不用 *:web(domain:example.com) 已經包含它底下的網址(shop.example.com 也算)。")) + } else if crate::web::host_of(domain).is_none() { + Some(format!("「{r}」的「{domain}」看起來不是網站,例如 web(domain:example.com)。")) + } else if domain.contains('/') || domain.contains('@') { + Some(format!("「{r}」只比對網站,會當成整個 {}(不寫 https://、帳號和路徑)。", crate::web::host_of(domain).unwrap_or_default())) + } else { + None + } + } + "tool" => (!tool_names().iter().any(|n| glob(inner, n, false))).then(|| format!("「{r}」對不上任何工具的名字:比對的是每一步真正的名字,例如 browser_click、browser_open、web_fetch、shell、computer_use_click(瀏覽器的全部寫 tool(browser_*))。")), + _ => None, + } +} + /// The pattern rules' word on a step: any ask pattern about it asks (over any allow); else an /// allow pattern that covers it allows; else they say nothing (the sentences go to the model). pub fn patterns(name: &str, args: &str, allow: &[String], ask: &[String]) -> PatternVerdict { @@ -317,6 +366,18 @@ mod pattern_tests { assert_eq!(p(crate::mcp::USE_TOOL, serde_json::json!({"tool": "mcp__gitlab__delete_project"})), PatternVerdict::NoMatch); assert_eq!(p("web_fetch", serde_json::json!({"url": "https://docs.example.com/a"})), PatternVerdict::Allow("web(domain:example.com)".into())); assert_eq!(p("web_fetch", serde_json::json!({"url": "https://example.com.evil.net/"})), PatternVerdict::NoMatch); + // The host as a browser reads it: user@, a trailing dot, case, a backslash, a new tab by address. + for (name, args) in [ + ("web_fetch", serde_json::json!({"url": "https://x@example.com/"})), + ("web_fetch", serde_json::json!({"url": "https://EXAMPLE.com./"})), + ("browser_open", serde_json::json!({"url": "https://shop.example.com\\cart"})), + ("browser_tabs", serde_json::json!({"action": "new", "url": "https://me@shop.example.com./cart"})), + ] { + assert_eq!(p(name, args.clone()), PatternVerdict::Allow("web(domain:example.com)".into()), "{name} {args}"); + } + assert_eq!(p("web_fetch", serde_json::json!({"url": "https://example.com@evil.net/"})), PatternVerdict::NoMatch, "evil.net is the host"); + assert_eq!(p("browser_tabs", serde_json::json!({"action": "select", "index": 1})), PatternVerdict::NoMatch); + assert_eq!(patterns("browser_open", r#"{"url":"https://xn--bcher-kva.example/"}"#, &[], &["web(domain:Bücher.example)".into()]), PatternVerdict::Ask("web(domain:Bücher.example)".into()), "the rule's domain read the same way"); assert_eq!(p("browser_click", serde_json::json!({})), PatternVerdict::Ask("tool(browser_click)".into())); assert!(is_pattern("shell(ls)") && !is_pattern("刪除檔案前先問我") && !is_pattern("shell ls")); } diff --git a/src/web.rs b/src/web.rs index 85688e5..1b4ebfd 100644 --- a/src/web.rs +++ b/src/web.rs @@ -165,26 +165,47 @@ pub fn run(name: &str, args: &str, cancel: &AtomicBool) -> (String, bool) { } } -pub fn normalize_url(u: &str) -> Result { +/// A web address as a browser reads it (WHATWG URL, the `url` crate): `\` is `/`, `user@` is not +/// the host, the host lowercased and in punycode, an IP in any spelling made plain. Everything that +/// checks an address (the private-network card, the rules, web_fetch's own check) reads it this +/// way, and the browser is handed the address as parsed — what is checked is what opens. (Taking +/// the host apart by hand let `http://127.0.0.1\@a.com/` past the private-network card.) +pub fn parse_url(u: &str) -> Result { let u = u.trim(); if u.is_empty() { return Err("請給網址".into()); } - let full = if u.starts_with("http://") || u.starts_with("https://") { u.to_string() } else { format!("https://{u}") }; - // Check the host part after the scheme (a fixed [8..] cut one byte short for http://). - let rest = full.split_once("://").map(|(_, r)| r).unwrap_or(&full); - let authority = rest.split(['/', '?', '#']).next().unwrap_or(""); - let host_only = authority.rsplit('@').next().unwrap_or(authority); - let bare = if let Some(v6) = host_only.strip_prefix('[') { - v6.split_once(']').map(|(a, _)| a).unwrap_or(host_only) - } else { - host_only.split(':').next().unwrap_or(host_only) + let bad = || format!("「{u}」看起來不是網址"); + let has_scheme = ["http://", "https://"].iter().any(|p| u.get(..p.len()).is_some_and(|h| h.eq_ignore_ascii_case(p))); + let full = if has_scheme { u.to_string() } else { format!("https://{u}") }; + if full.contains(char::is_whitespace) { + return Err(bad()); } - .trim_end_matches('.'); - if full.contains(char::is_whitespace) || (!bare.contains('.') && !bare.contains(':') && !bare.eq_ignore_ascii_case("localhost")) { - return Err(format!("「{u}」看起來不是網址")); + let parsed = url::Url::parse(&full).map_err(|_| bad())?; + match parsed.host() { + Some(url::Host::Domain(d)) if d.trim_end_matches('.').contains('.') || d.trim_end_matches('.') == "localhost" => Ok(parsed), + Some(url::Host::Ipv4(_) | url::Host::Ipv6(_)) => Ok(parsed), + _ => Err(bad()), } - Ok(full) +} + +/// [`parse_url`], written out (the form handed to the browser). +pub fn normalize_url(u: &str) -> Result { + parse_url(u).map(|p| p.to_string()) +} + +/// The host a browser would open for this address: lowercased, punycode, no trailing dot, an IP +/// plain (an IPv6 one without brackets). None when it isn't a web address. +pub fn host_of(u: &str) -> Option { + parse_url(u).ok().and_then(|p| host_text(&p)) +} + +fn host_text(p: &url::Url) -> Option { + Some(match p.host()? { + url::Host::Domain(d) => d.trim_end_matches('.').to_ascii_lowercase(), + url::Host::Ipv4(a) => a.to_string(), + url::Host::Ipv6(a) => a.to_string(), + }) } // ---------- web_fetch ---------- @@ -247,22 +268,11 @@ pub fn is_private_browser_url(url: &str) -> bool { public_only(&full).is_err() } -/// The host and port of a web address (the brackets off an IPv6 one). +/// The host and port of a web address as a browser reads it ([`parse_url`]; an IPv6 host without +/// brackets). fn host_port(url: &str) -> Option<(String, u16)> { - let (scheme, rest) = url.split_once("://")?; - let auth = rest.split(['/', '?', '#']).next()?.rsplit('@').next()?; - let default = if scheme.eq_ignore_ascii_case("https") { 443 } else { 80 }; - let (host, port) = match auth.strip_prefix('[') { - Some(v6) => { - let (h, after) = v6.split_once(']')?; - (h, after.strip_prefix(':').map(str::parse).transpose().ok()?.unwrap_or(default)) - } - None => match auth.rsplit_once(':') { - Some((h, p)) => (h, if p.is_empty() { default } else { p.parse().ok()? }), - None => (auth, default), - }, - }; - (!host.is_empty()).then(|| (host.to_string(), port)) + let p = parse_url(url).ok()?; + Some((host_text(&p)?, p.port_or_known_default()?)) } /// web_fetch runs with nothing asked, so it reads the public web only: a page (or a redirect) @@ -344,7 +354,8 @@ pub fn get_public_bytes(url: &str, limit: u64) -> Result<(String, u16, String, V Some(_) if hops >= MAX_REDIRECTS => return Err(format!("{url} 一直轉址,讀不到內容。")), Some(to) => { hops += 1; - url = to; + // (As parsed: the stop that is checked is the one asked for.) + url = normalize_url(&to)?; } None => break resp, } @@ -802,6 +813,34 @@ mod tests { assert!(normalize_url("").is_err()); } + /// Addresses are read the way a browser reads them (WHATWG): a backslash is a slash, `user@` + /// isn't the host, case, a trailing dot, punycode and an IP in any spelling don't change which + /// host it is — so the private-network card and the person's rules see the host that opens, + /// and the browser is handed that same address. (By hand, `http://127.0.0.1\@a.com/` and + /// `http://192.168.1.1\.example.com/` passed as public; `me@example.com` as host `me@example.com`.) + #[test] + fn addresses_are_read_as_a_browser_reads_them() { + for private in ["http://127.0.0.1\\@a.com/", "http://192.168.1.1\\.example.com/", "http://me@127.0.0.1/", "http://localhost./", "http://2130706433/", "http://0x7f.1/", "http://[::1]:8080/", "http://[::ffff:127.0.0.1]/", "HTTP://192.168.1.5/"] { + assert!(is_private_browser_url(private), "{private}"); + } + assert!(is_forbidden_browser_url(&normalize_url("http://169.254.169.254\\@a.com/latest").unwrap())); + assert!(is_forbidden_browser_url(&normalize_url("http://2852039166/").unwrap()), "169.254.169.254 written as one number"); + for (given, host) in [ + ("https://me@example.com/cart", "example.com"), + ("https://shop.EXAMPLE.com./cart", "shop.example.com"), + ("https://example.com\\cart", "example.com"), + ("https://bücher.example/", "xn--bcher-kva.example"), + ("example.com:8443/x", "example.com"), + ("http://[::1]:8080/", "::1"), + ("http://2130706433/", "127.0.0.1"), + ] { + assert_eq!(host_of(given).as_deref(), Some(host), "{given}"); + } + assert_eq!(normalize_url("http://127.0.0.1\\@a.com/").unwrap(), "http://127.0.0.1/@a.com/", "what is checked is what opens"); + assert_eq!(normalize_url("https://me@example.com\\cart").unwrap(), "https://me@example.com/cart"); + assert!(normalize_url("ftp://example.com/").is_err() && normalize_url("javascript:alert(1)").is_err() && normalize_url("intranet").is_err()); + } + #[test] fn front_browser_follows_window_order() { let json = r#"[{"owner":"Window Server","layer":24,"alpha":1,"w":1920,"h":30},