feat: 連接器可以用帳號登入(MCP 的 OAuth:PKCE、自己註冊、resource),在大腦上、Token 加密存

- 照 MCP 2025-06-18:401 指的 resource metadata(RFC 9728)→ 登入伺服器的 metadata(RFC 8414/OpenID)→ 自己註冊(RFC 7591)→ PKCE S256 加 resource(RFC 8707)→ 換 token。
- 瀏覽器回到大腦的 127.0.0.1 臨時連接埠;瀏覽器在別台電腦時,把登入後那頁的網址貼回聊天(manage_connectors login 加 callback)。登入完連接器馬上重新連線。
- 設定 › 整合 › 連接器 的「登入/重新登入」(大腦本機);manage_connectors 多 login、logout(logout 先問)。
- Token 存 connectors/oauth.json,用設定金鑰同一把鑰匙加密、0600,不放連接器清單(會同步到螢幕和手機);快到期或 401 用 refresh token 換新再試一次。
- 登不進去照實說:不讓 App 註冊、不支援 PKCE、登入伺服器的錯誤、10 分鐘逾時、網址用過。

已驗證:cargo test 606 通過(假的 OAuth+MCP 伺服器:檢查 PKCE、resource、scope;瀏覽器回來、貼網址兩種都換到 token;快到期自動換新;網址只能用一次;登入前連接器說要登入、登入後連上拿到工具)、clippy -D warnings 乾淨。
未驗證:真的 Notion/GitHub 等 OAuth 連接器;設定畫面的「登入」鍵打開瀏覽器。

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
王性驊 2026-11-17 13:08:45 +08:00
parent f19b49f953
commit 05085189fc
7 changed files with 742 additions and 11 deletions

View File

@ -2345,7 +2345,11 @@ computer_use_screenshot、click、mouse_move、mouse_button(按住/放開)
- 只列用網址連的(Streamable HTTP);要在大腦上跑套件的(npm/PyPI)不列,伺服器上的大腦不一定有 Node.js 或 uv。舊式 SSE 的標「還不支援」;下架的不列。
- 電腦上按「加入」會把「新增連接器」表單填好、捲過去:名稱(重複就加「2」)、網址、標頭(例如「Authorization: Bearer {smithery_api_key}」)。還有「{…}」時標頭不遮起來、下面說要換成什麼(金鑰的說明、網址變數可以填的值),換好之前「新增」按不下去。
- 手機:設定 › 整合 ›「從公用市集加入」,打關鍵字,大腦去搜(手機頁面只能連自己的伺服器);點一個,要金鑰的問金鑰、網址有變數的問變數,再請大腦加上。只有擁有者能用。
- 要登入帳號(OAuth)的連接器 AnyBot 還不支援:連線時伺服器回 401(或要求登入的 403)、又沒填金鑰,狀態會說「這個連接器要先登入帳號(OAuth),AnyBot 還不支援」;有填金鑰的話說金鑰不對或過期了。
- 要登入帳號(OAuth)的連接器:連線時伺服器回 401(或要求登入的 403)、又沒填金鑰,狀態會說「這個連接器要先登入帳號(OAuth):在聊天裡請 Bot 幫你登入,或在 設定 › 整合 › 連接器 按「登入」」;有填金鑰的話說金鑰不對或過期了。
- **登入(MCP 的 OAuth,2025-06-18 版)**:AnyBot 先問連接器自己(401 的 WWW-Authenticate 指的 resource metadata,RFC 9728;沒有就找它的 /.well-known/oauth-protected-resource),再問它指的登入伺服器(RFC 8414 的 /.well-known/oauth-authorization-server,或 OpenID 的;都沒有就用 /authorize、/token、/register),自己註冊成一個 App(RFC 7591,名字 AnyBot),用 PKCE(S256)和 resource(RFC 8707,連接器的網址)帶你到登入頁。登入完瀏覽器回到大腦上的 http://127.0.0.1:臨時連接埠/callback,AnyBot 拿 code 換 token,連接器馬上重新連線(「已登入連接器「…」,正在連線。」)。
- 從哪裡登入:設定 › 整合 › 連接器,遠端連接器那一列的「登入」(登入過的是「重新登入」),在大腦本機的瀏覽器打開;或在聊天請 Bot:「幫我登入 Notion」→ Bot 用 manage_connectors 的 login 拿到登入網址,用 open_for_person 開在你正在用的電腦上。瀏覽器不在大腦那台(大腦在伺服器上)時,登入後那一頁會打不開:把那頁的網址整個複製貼給 Bot,它用 login 加 callback 交給大腦完成。螢幕電腦和手機上沒有「登入」鍵,請 Bot 做。
- Token 存在大腦的資料夾 connectors/oauth.json,用跟設定裡金鑰同一把鑰匙(鑰匙圈裡的)加密,檔案只有你能讀;不在連接器清單裡,所以不會同步到螢幕或手機。存取 token 快到期(剩 1 分鐘)或連接器回 401 時,用 refresh token 換新的再試一次;換不了就說「登入過期了:重新登入」。「logout」(會先問)刪掉 token。
- 登不進去時照實說:登入伺服器不讓 App 自己註冊(要先在它那邊建 OAuth App,AnyBot 還不支援填 client_id)、不支援 PKCE(S256)、登入伺服器回錯誤、10 分鐘沒有登入(取消)、登入網址用過一次或過期。
- mcpservers.org 這類網站是給人看的頁面,有瀏覽器檢查、沒有給程式讀的清單,所以用官方 Registry。
- 驗證過的:搜「notion」拿到 6 個;實際連上 AWS Knowledge(不用金鑰,5 個工具);Notion 官方(OAuth)顯示上面那句話。測試是 `cargo test -- --ignored registry_search_live`。
- github 要你的 Token,沒有測。

View File

@ -5,6 +5,7 @@
## 子功能
- 本機伺服器:填指令(例如 `npx -y @modelcontextprotocol/server-filesystem ~/Documents`),可加環境變數。遠端伺服器:填網址(Streamable HTTP,回 JSON 或 SSE 都可以),可加標頭(例如 Authorization)。
- 登入帳號(OAuth):遠端連接器回「要先登入」時,設定裡那一列按「登入」(只在大腦本機),或在聊天請 Bot 登入:瀏覽器打開登入頁,登入完自動接上;瀏覽器在別台電腦、登入後那頁打不開時,把那頁網址貼回聊天。Token 存在大腦、加密,不會同步到螢幕或手機;快到期自動換新,401 時換一次再試。
- 帳號、密碼:給要用帳號密碼登入的伺服器。在指令、環境變數、網址或標頭寫「{username}」「{password}」,就填在那裡;都沒寫時,本機伺服器收到環境變數 `MCP_USERNAME`、`MCP_PASSWORD`,遠端伺服器收到 Basic 驗證。
- 「給 Bot 的使用說明」:寫進 Bot 的系統指示(例如「查詢客戶資料時先用 search_customers」)。
- 「已加入」是一張清單,每個連接器一列:名稱、色點和狀態(「已連上,N 個工具」「連線中…」「未連線」「已關閉」或紅字錯誤原因)、「設定」和開關。按「設定」在那一列下面展開它的欄位(名稱、指令或網址、環境變數、標頭、帳號和密碼並排、給 Bot 的使用說明——每個欄位名稱都在輸入框上面),最下面左邊「移除」、右邊「重新連線」;再按「收起」收回。下面列「可以用的工具」。「新增連接器」表單也是同樣的欄位(名稱在上、框在下)。
@ -27,7 +28,7 @@
## 怎麼操作
- Bot:工具少時直接呼叫那個 `mcp__…` 工具。工具多時先 `find_connector_tool`:`query` 用功能的字找(英文比較準),或只給 `server` 列出那個連接器全部工具的名字;結果有完整名稱、說明和參數,再用 `use_connector_tool`(`tool` 是完整名稱,`arguments` 是參數)。名字給錯會叫你先找。
- Bot(管理):`manage_connectors`:`action` 是 list、add(name,加 command 或 url,env、headers、username、password、instructions)、update(只給要改的;換了指令或網址沒給新密碼,舊密碼清掉)、remove、reconnect。加之前先在自己的電腦跑一次指令確認能動;秘密放 env、headers 或 password,不要寫進 instructions。
- Bot(管理):`manage_connectors`:`action` 是 list、add(name,加 command 或 url,env、headers、username、password、instructions)、update(只給要改的;換了指令或網址沒給新密碼,舊密碼清掉)、remove、reconnect、login(要登入的遠端連接器:回一個登入網址,用 `open_for_person` 開給使用者;登入後那頁打不開時,他把網址貼給你,再 login 加 callback)、logout(會先問)。加之前先在自己的電腦跑一次指令確認能動;秘密放 env、headers 或 password,不要寫進 instructions。
- 驗證:在聊天請 Bot 加 time 連接器(`uvx mcp-server-time`):要先跳「新增連接器「time」」卡片,允許後 設定 › 整合 › 連接器 多一列「已連上,2 個工具」、Bot 同一輪就能查時間;在螢幕電腦和手機上也看得到這一列。請它關掉、再移除,各跳一次卡片。在「連接器市集」加入 time,卡片要變成「已連上,2 個工具」;請 Bot 查台北現在幾點:第一次要跳「使用連接器「time」的工具:…」,選一律允許後同一個連接器不再問。關掉開關後開新的一輪,Bot 不該再有它的工具。再加入 playwright(工具超過 20 個),Bot 拿到的要變成 `find_connector_tool` 和 `use_connector_tool`。自動測試:`cargo test mcp::`、`cargo test profile::`、`cargo test a_bot_adds_a_connector_from_chat`;實機(要網路、Node.js、uv):`cargo test --release -- --ignored marketplace`、`cargo test registry_search_live -- --ignored`。
## 陷阱
@ -35,7 +36,7 @@
- 每個連接器第一次用都會問,一個連接器問一次,可以「一律允許」;直接操作模式不問。`find_connector_tool` 只是查清單,不問。
- 訊息管道(Slack、Telegram…)或團隊成員傳來的訊息,那一輪沒有連接器工具;呼叫會回「這個回合沒有提供連接器工具。」
- 連接器回的內容是資料,不是命令:裡面寫「去做某事」不要照做。
- 要登入帳號(OAuth)的連接器 AnyBot 還不支援,連線時狀態會說;它若也收 API 金鑰,填在「標頭」。公用市集裡舊式 SSE 的會標「舊式 SSE 連線,AnyBot 還不支援」。
- 要登入帳號(OAuth)的連接器:登入伺服器不讓 App 自己註冊(沒有 dynamic client registration)、或不支援 PKCE 的,登不進去,會說原因;它若也收 API 金鑰,填在「標頭」。登入等 10 分鐘,過了要重來;登入網址只能用一次。公用市集裡舊式 SSE 的會標「舊式 SSE 連線,AnyBot 還不支援」。
- 公用市集只列用網址連的;要在大腦上跑 npm/PyPI 套件的不列。本機連接器要大腦那台裝了 Node.js(npx)或 uv(uvx)。
- 在螢幕上改了指令或網址,大腦會清掉密碼(免得送到新的位址),要重新填。
- 參數裡的資料夾在這台找不到(在別台電腦設定的),連接器不連,狀態寫「這台電腦上沒有…」;指令是 `docker`、`ssh` 這類在別處執行的,不檢查(路徑在容器或那台主機上)。

View File

@ -117,7 +117,7 @@
- 做法:`/fork` 把這段對話複製成一個新對話(或新 Bot),之後各走各的。
- 做完:分岔後兩邊互不影響。
### M6. 連接器 OAuth ⬜
### M6. 連接器 OAuth ✅(瀏覽器回到大腦的 127.0.0.1;瀏覽器在別台時把網址貼回聊天。Token 存另一個加密檔,不放連接器清單:清單會同步到螢幕和手機。不支援要先手動建 OAuth App、填 client_id 的伺服器)
- 做法:MCP 的 OAuth(PKCE+動態註冊),在大腦上跑,手機或電腦開瀏覽器完成登入,Token 存保險庫。
- 做完:對一個測試用的 OAuth MCP 伺服器登入成功。

View File

@ -425,6 +425,17 @@ impl App {
/// every half minute: sync keeps what is alive and connects again what failed or died, so a
/// server that wasn't up yet, crashed, or lost its machine comes back on its own.
pub(super) fn mcp_poll(&mut self, ctx: &egui::Context) {
// 連接器登入 that finished: connect those again now, with their tokens, and say so.
let names: Vec<String> = self.state.mcp_servers.iter().map(|s| s.name.clone()).collect();
for (name, r) in crate::mcp_oauth::take_finished(|n| names.iter().any(|x| x == n)) {
match r {
Ok(()) => {
self.mcp_reconnect(&name);
self.notice = Some(format!("已登入連接器「{name}」,正在連線。"));
}
Err(e) => self.notice = Some(format!("連接器「{name}」沒有登入成功:{e}")),
}
}
if self.ch.mcp_busy.load(Ordering::SeqCst) {
return;
}
@ -455,6 +466,22 @@ impl App {
return;
}
};
// 連接器登入: over the network, on a thread; the connection follows when it is done (mcp_poll).
if let crate::mcp::Change::Login { name, url, callback } = change {
std::thread::spawn(move || {
let r = match callback {
Some(cb) => crate::mcp_oauth::finish_from_url(&cb).map(|n| format!("已登入「{n}」,正在連線:稍後用 action=list 看它連上了沒有。")),
None => crate::mcp_oauth::start(&name, &url).map(|u| {
format!("請使用者打開這個網址登入「{name}」(用 open_for_person 開在他正在用的電腦上,或把網址給他):\n{u}\n登入好了 AnyBot 會自己接上(最多等 10 分鐘),不用再做什麼。如果登入後那一頁打不開(他的瀏覽器在別台電腦),請他把那一頁的網址整個複製給你,再用 manage_connectors(action=login、name=「{name}」、callback=那個網址)。")
}),
};
let _ = call.reply.send(match r {
Ok(t) => (t, true),
Err(e) => (format!("沒辦法登入「{name}」:{e}"), false),
});
});
return;
}
if change == crate::mcp::Change::List {
let text = crate::mcp::list_text(&self.state.mcp_servers, &crate::mcp::status(), &self.ch.mcp_errors.lock().unwrap(), self.ch.mcp_busy.load(Ordering::SeqCst));
let _ = call.reply.send((text, true));
@ -541,6 +568,7 @@ impl App {
let at = if self.mir.on { "在大腦上:" } else { "" };
let mut remove = None;
let mut reconnect = None;
let mut login: Option<(String, String)> = None;
// The servers as one list (a row each: name, its state, 設定, the switch); the one being
// set up unfolds its fields under its row — every name above its box, all boxes alike.
let open_now = self.ch.mcp_open;
@ -636,6 +664,13 @@ impl App {
if s.enabled && ui.add(secondary_button("重新連線")).on_hover_text(t("再連一次,看連不連得上")).clicked() {
reconnect = Some(s.name.clone());
}
// 連接器登入: a remote connector, on the brain itself (a screen: ask a bot).
if s.enabled && !s.url.trim().is_empty() && !self.mir.on {
let word = if crate::mcp_oauth::tokens(&s.name).is_some() { "重新登入" } else { "登入" };
if ui.add(secondary_button(word)).on_hover_text(t("用帳號登入這個連接器(OAuth),在瀏覽器打開登入頁")).clicked() {
login = Some((s.name.clone(), s.url.clone()));
}
}
});
});
ui.add_space(crate::theme::sp::S3);
@ -649,6 +684,15 @@ impl App {
if let Some(i) = remove {
self.state.mcp_servers.remove(i);
}
if let Some((name, url)) = login {
let note = self.ch.note.clone();
std::thread::spawn(move || match crate::mcp_oauth::start(&name, &url) {
Ok(u) => {
let _ = crate::computer::spawn_reaped(&mut crate::preview::system_open(&u));
}
Err(e) => *note.lock().unwrap() = format!("沒辦法登入「{name}」:{e}"),
});
}
if let Some(name) = reconnect {
if self.mir.on {
self.mirror_mcp_reconnect(&name);

View File

@ -42,6 +42,7 @@ mod lock;
mod macapps;
mod marks;
mod mcp;
mod mcp_oauth;
mod memory;
mod memstore;
mod mention;

View File

@ -131,6 +131,9 @@ struct Live {
/// The server no longer knows this session (HTTP 404 on a session, as the spec says it
/// answers): the link has to be made again.
expired: bool,
/// 連接器登入 (mcp_oauth.rs): the connector whose OAuth token this link sends, renewed once
/// when the server says it is no longer good (401).
oauth: Option<String>,
}
impl Live {
@ -236,12 +239,17 @@ pub fn http_refusal(status: u16, asks_login: bool, has_key: bool, body: &str) ->
return if has_key {
format!("金鑰不對或過期了(HTTP {status}):檢查「標頭」裡的金鑰")
} else {
"這個連接器要先登入帳號(OAuth),AnyBot 還不支援;它若也收 API 金鑰,填在「標頭」(例如 Authorization: Bearer …)".into()
"這個連接器要先登入帳號(OAuth):在聊天裡請 Bot 幫你登入(manage_connectors 的 login),或在 設定 › 整合 › 連接器 按「登入」;它若也收 API 金鑰,也可以填在「標頭」(例如 Authorization: Bearer …)".into()
};
}
format!("MCP 伺服器回 HTTP {status}:{}", body.chars().take(200).collect::<String>())
}
/// A request's params, to send it again.
fn params_again(msg: &Value) -> Value {
msg["params"].clone()
}
/// Answers from Streamable HTTP: plain JSON, or SSE with `data:` lines.
pub fn parse_http_answer(body: &str, id: u64) -> Result<Value, String> {
let candidates: Vec<Value> = if body.trim_start().starts_with('{') || body.trim_start().starts_with('[') {
@ -298,6 +306,16 @@ impl Live {
if st == 404 && session.is_some() {
self.expired = true;
}
// 連接器登入: the token ran out — a new one with the refresh token, and once more.
if st == 401 {
if let Some(name) = self.oauth.take() {
if let Ok(t) = crate::mcp_oauth::renew(&name) {
headers.insert("Authorization".into(), format!("Bearer {t}"));
return self.request_until(method, params_again(&msg), cancel);
}
return Err(format!("「{name}」的登入過期了:重新登入(在聊天裡請 Bot 用 manage_connectors 的 login,或 設定 › 整合 › 連接器 按「登入」)。"));
}
}
if !(200..300).contains(&st) {
return Err(http_refusal(st, asks_login, !headers.is_empty(), &body));
}
@ -362,12 +380,21 @@ fn connect(config: &Server) -> Result<Conn, String> {
// (The table keeps the server as it is written: a change of 帳號 or 密碼 is a change.)
let s = &config.resolved();
let mut errlog: Option<ErrLog> = None;
let mut oauth: Option<String> = None;
let link = if !s.url.trim().is_empty() {
let u = s.url.trim();
if crate::web::is_forbidden_browser_url(u) {
return Err("安全規則禁止將 MCP 連接器指向雲端中繼資料或 Docker 內部管理端點。".into());
}
Link::Http { url: u.to_string(), headers: s.headers.clone(), session: None }
let mut headers = s.headers.clone();
// 連接器登入: logged in with OAuth (and no key of its own given): its token.
if !headers.keys().any(|k| k.eq_ignore_ascii_case("authorization")) {
if let Some(t) = crate::mcp_oauth::bearer(&s.name) {
headers.insert("Authorization".into(), format!("Bearer {t}"));
oauth = Some(s.name.clone());
}
}
Link::Http { url: u.to_string(), headers, session: None }
} else {
if s.command.trim().is_empty() {
return Err("請給指令或網址".into());
@ -441,7 +468,7 @@ fn connect(config: &Server) -> Result<Conn, String> {
});
Link::Stdio { child, stdin, rx }
};
let mut live = Live { link, next_id: 1, expired: false };
let mut live = Live { link, next_id: 1, expired: false, oauth };
match handshake(&mut live, &s.name) {
Ok(tools) => {
// Streamable HTTP pushes only on an open GET stream; keep one per connection.
@ -922,7 +949,7 @@ pub fn registry_form(e: &Value, servers: &[Server]) -> (String, String, String,
}
hint.push(line);
}
hint.push("按「新增」就會連線;要登入帳號(OAuth)的連接器 AnyBot 還不支援,連線時會說。".into());
hint.push("按「新增」就會連線;要登入帳號(OAuth)的連接器連線時會說,按它的「登入」或請 Bot 幫你登入。".into());
(name, url, header, hint.join(" "))
}
@ -961,7 +988,8 @@ pub fn manage_spec() -> Value {
json!({"name": MANAGE_TOOL,
"description": "List, add, change (including turning on or off), reconnect or remove the person's connectors (MCP servers) — what 設定 › 整合 › 連接器 does. They run on the brain (this AnyBot) and every bot with the 連接器 ability gets their tools; a connector added now can be used from your next step. Adding, changing and removing show the person a card first (a command runs on the brain). A local server is a command (`npx -y …`, `uvx …`; the brain needs Node.js or uv); a remote one is a URL (Streamable HTTP). Secrets go in env, headers or password, never in instructions. Try a command once on your computer before adding it. After adding, the answer says whether it connected (a first start may download packages for a minute; check again with action=list).",
"parameters": {"type": "object", "properties": {
"action": {"type": "string", "enum": ["list", "add", "update", "remove", "reconnect"]},
"action": {"type": "string", "enum": ["list", "add", "update", "remove", "reconnect", "login", "logout"], "description": "login: a remote connector that signs people in (OAuth) — gives the address the person opens to log in (open it for them with open_for_person, or give it to them); once they have, it connects by itself. When that page couldn't load (the browser on another computer), they paste its address to you: login again with callback = that address."},
"callback": {"type": "string", "description": "login: the address the browser came back to after logging in (http://127.0.0.1:…/callback?code=…)."},
"name": {"type": "string", "description": "The connector's name (short, e.g. gitlab). Needed for everything but list."},
"command": {"type": "string", "description": "A local server's command line, e.g. `npx -y @zereight/mcp-gitlab`. Not with url."},
"url": {"type": "string", "description": "A remote server's address (http:// or https://). Not with command."},
@ -984,6 +1012,10 @@ pub enum Change {
Update { before: Server, after: Server },
Remove(Server),
Reconnect(String),
/// 連接器登入 (mcp_oauth.rs): start (the address for the person), or finish with the address
/// the browser came back to.
Login { name: String, url: String, callback: Option<String> },
Logout(String),
}
/// `{"K": "v"}`, or 「K=v K2=v2」 as the form takes it.
@ -1092,7 +1124,15 @@ pub fn parse_change(args: &str, servers: &[Server]) -> Result<Change, String> {
}
"remove" => Ok(Change::Remove(existing()?)),
"reconnect" => Ok(Change::Reconnect(existing()?.name)),
other => Err(format!("action「{other}」看不懂:用 list、add、update、remove 或 reconnect。")),
"login" => {
let s = existing()?;
if s.url.trim().is_empty() {
return Err(format!("「{}」是在這台跑的程式(不是網址),沒有帳號登入:它的金鑰填在 env。", s.name));
}
Ok(Change::Login { name: s.name, url: s.url, callback: text("callback").map(|c| c.trim().to_string()).filter(|c| !c.is_empty()) })
}
"logout" => Ok(Change::Logout(existing()?.name)),
other => Err(format!("action「{other}」看不懂:用 list、add、update、remove、reconnect、login 或 logout。")),
}
}
@ -1139,7 +1179,8 @@ fn server_lines(s: &Server) -> Vec<String> {
/// What the person is asked before the change (None: nothing to ask — a list or a reconnect).
pub fn change_question(c: &Change) -> Option<String> {
match c {
Change::List | Change::Reconnect(_) => None,
Change::List | Change::Reconnect(_) | Change::Login { .. } => None,
Change::Logout(n) => Some(format!("登出連接器「{n}」:它的登入刪掉,要再登入才能用它的工具。")),
Change::Add(s) => Some(format!("新增連接器「{}」(加在大腦的 設定 › 整合 › 連接器):\n- {}", s.name, server_lines(s).join("\n- "))),
Change::Update { before, after } => {
let (b, a) = (server_lines(before), server_lines(after));
@ -1179,6 +1220,12 @@ pub fn apply_change(c: &Change, servers: &mut Vec<Server>) -> String {
format!("已移除連接器「{}」。", s.name)
}
Change::Reconnect(n) => format!("正在重新連線「{n}」。"),
// (A login is done by the window, on a thread: it goes over the network.)
Change::Login { .. } => String::new(),
Change::Logout(n) => match crate::mcp_oauth::logout(n) {
Ok(()) => format!("已登出「{n}」。"),
Err(e) => format!("登出「{n}」時出錯:{e}"),
},
}
}

634
src/mcp_oauth.rs Normal file
View File

@ -0,0 +1,634 @@
//! 連接器登入 (M6): a remote connector that signs people in with OAuth — MCP's authorization
//! (2025-06-18): the server's 401 names its Protected Resource Metadata (RFC 9728), which names
//! the authorization server; its metadata (RFC 8414, or OpenID's) gives the endpoints; AnyBot
//! registers itself there (Dynamic Client Registration, RFC 7591), sends the person to log in
//! with PKCE (S256) and the resource indicator (RFC 8707), and swaps the code for tokens.
//!
//! It runs on the brain. The login page opens in the person's browser; it comes back to a
//! listener on this computer (`http://127.0.0.1:port/callback`). When the browser is on another
//! computer (a brain on a server), that page can't load: the person copies its address back into
//! the chat, and the bot hands it over (manage_connectors login with `callback`).
//!
//! The tokens are kept in `<資料夾>/connectors/oauth.json`, sealed with the same key as the
//! settings' secrets (the keychain's); never in the connector list, which screens and the phone
//! get. An access token near its end is renewed with the refresh token.
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
use std::collections::HashMap;
use std::io::{BufRead, BufReader, Write};
use std::sync::{Mutex, OnceLock};
use std::time::{Duration, Instant};
/// How long a login waits for the person.
const LOGIN_WAIT: Duration = Duration::from_secs(10 * 60);
const HTTP_SECS: u64 = 20;
/// One connector's tokens and where to renew them.
#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq)]
pub struct Tokens {
pub access: String,
#[serde(default)]
pub refresh: String,
/// When the access token ends (ms; 0: not said).
#[serde(default)]
pub expires_at: i64,
pub token_endpoint: String,
pub client_id: String,
#[serde(default)]
pub client_secret: String,
#[serde(default)]
pub resource: String,
}
fn file() -> std::path::PathBuf {
crate::model::State::path().parent().map(|d| d.join("connectors").join("oauth.json")).unwrap_or_else(|| std::path::PathBuf::from("oauth.json"))
}
fn store() -> &'static Mutex<()> {
static S: OnceLock<Mutex<()>> = OnceLock::new();
S.get_or_init(|| Mutex::new(()))
}
fn read_all() -> HashMap<String, Tokens> {
let text = std::fs::read_to_string(file()).unwrap_or_default();
let mut v: Value = serde_json::from_str(&text).unwrap_or(json!({}));
if let Some(o) = v.as_object_mut() {
for t in o.values_mut() {
for k in ["access", "refresh", "client_secret"] {
if let Some(s) = t[k].as_str().filter(|s| s.starts_with("sealed:")).map(String::from) {
t[k] = json!(crate::vault_store::open_text(&s).unwrap_or_default());
}
}
}
}
serde_json::from_value(v).unwrap_or_default()
}
fn write_all(all: &HashMap<String, Tokens>) -> Result<(), String> {
let mut v = serde_json::to_value(all).map_err(|e| e.to_string())?;
if let Some(o) = v.as_object_mut() {
for t in o.values_mut() {
for k in ["access", "refresh", "client_secret"] {
if let Some(sealed) = t[k].as_str().and_then(crate::vault_store::seal_text) {
t[k] = json!(sealed);
}
}
}
}
let p = file();
if let Some(d) = p.parent() {
std::fs::create_dir_all(d).map_err(|e| e.to_string())?;
}
std::fs::write(&p, serde_json::to_string_pretty(&v).unwrap_or_default()).map_err(|e| e.to_string())?;
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
let _ = std::fs::set_permissions(&p, std::fs::Permissions::from_mode(0o600));
}
Ok(())
}
/// This connector's tokens, if it is logged in.
pub fn tokens(server: &str) -> Option<Tokens> {
let _g = store().lock().unwrap_or_else(|e| e.into_inner());
read_all().remove(server).filter(|t| !t.access.is_empty())
}
fn save(server: &str, t: Option<Tokens>) -> Result<(), String> {
let _g = store().lock().unwrap_or_else(|e| e.into_inner());
let mut all = read_all();
match t {
Some(t) => all.insert(server.to_string(), t),
None => all.remove(server),
};
write_all(&all)
}
/// Log a connector out (its tokens go).
pub fn logout(server: &str) -> Result<(), String> {
save(server, None)
}
/// The access token to send, renewed first when it is about to end.
pub fn bearer(server: &str) -> Option<String> {
let t = tokens(server)?;
if t.expires_at > 0 && t.expires_at - 60_000 < crate::model::now_ms() && !t.refresh.is_empty() {
return renew(server).ok().or(Some(t.access));
}
Some(t.access)
}
/// A new access token with the refresh token (after a 401, or near its end).
pub fn renew(server: &str) -> Result<String, String> {
let t = tokens(server).ok_or("沒有登入")?;
if t.refresh.is_empty() {
return Err("登入過期了,要重新登入".into());
}
let mut form = vec![("grant_type", "refresh_token".to_string()), ("refresh_token", t.refresh.clone()), ("client_id", t.client_id.clone())];
if !t.resource.is_empty() {
form.push(("resource", t.resource.clone()));
}
if !t.client_secret.is_empty() {
form.push(("client_secret", t.client_secret.clone()));
}
let v = post_form(&t.token_endpoint, &form)?;
let fresh = tokens_from(&v, &t)?;
save(server, Some(fresh.clone()))?;
Ok(fresh.access)
}
fn tokens_from(v: &Value, base: &Tokens) -> Result<Tokens, String> {
let access = v["access_token"].as_str().unwrap_or("").to_string();
if access.is_empty() {
return Err(format!("登入伺服器沒有給 token:{}", v["error_description"].as_str().or(v["error"].as_str()).unwrap_or("(沒有說原因)")));
}
Ok(Tokens {
access,
refresh: v["refresh_token"].as_str().map(String::from).unwrap_or_else(|| base.refresh.clone()),
expires_at: v["expires_in"].as_i64().map(|s| crate::model::now_ms() + s * 1000).unwrap_or(0),
..base.clone()
})
}
// ---------- the protocol ----------
/// Percent-encoding for a URL's query or a form (everything but the unreserved characters).
pub fn enc(s: &str) -> String {
s.bytes().map(|b| if b.is_ascii_alphanumeric() || b"-._~".contains(&b) { (b as char).to_string() } else { format!("%{b:02X}") }).collect()
}
fn dec(s: &str) -> String {
let b = s.as_bytes();
let mut out = Vec::with_capacity(b.len());
let mut i = 0;
while i < b.len() {
match b[i] {
b'+' => out.push(b' '),
b'%' if i + 2 < b.len() => match std::str::from_utf8(&b[i + 1..i + 3]).ok().and_then(|h| u8::from_str_radix(h, 16).ok()) {
Some(x) => {
out.push(x);
i += 3;
continue;
}
None => out.push(b'%'),
},
c => out.push(c),
}
i += 1;
}
String::from_utf8_lossy(&out).into_owned()
}
/// A query's `key=value` pairs.
fn query_pairs(q: &str) -> HashMap<String, String> {
q.split('&').filter_map(|kv| kv.split_once('=')).map(|(k, v)| (dec(k), dec(v))).collect()
}
fn get_json(url: &str) -> Result<Value, String> {
let mut resp = crate::net::agent(HTTP_SECS).get(url).header("Accept", "application/json").call().map_err(|e| format!("連不上 {url}:{e}"))?;
if !(200..300).contains(&resp.status().as_u16()) {
return Err(format!("{url} 回 HTTP {}", resp.status().as_u16()));
}
let body = resp.body_mut().read_to_string().unwrap_or_default();
serde_json::from_str(&body).map_err(|e| format!("{url} 回的不是 JSON:{e}"))
}
fn post_form(url: &str, form: &[(&str, String)]) -> Result<Value, String> {
let body: String = form.iter().map(|(k, v)| format!("{}={}", enc(k), enc(v))).collect::<Vec<_>>().join("&");
let mut resp = crate::net::agent(HTTP_SECS).post(url).header("Content-Type", "application/x-www-form-urlencoded").header("Accept", "application/json").send(body.as_bytes()).map_err(|e| format!("連不上 {url}:{e}"))?;
let status = resp.status().as_u16();
let text = resp.body_mut().read_to_string().unwrap_or_default();
let v: Value = serde_json::from_str(&text).unwrap_or(json!({"error": text.chars().take(200).collect::<String>()}));
if !(200..300).contains(&status) {
return Err(format!("登入伺服器回 HTTP {status}:{}", v["error_description"].as_str().or(v["error"].as_str()).unwrap_or("")));
}
Ok(v)
}
/// `scheme://host[:port]` of an address.
fn origin(url: &str) -> String {
let (scheme, rest) = url.split_once("://").unwrap_or(("https", url));
format!("{scheme}://{}", rest.split('/').next().unwrap_or(""))
}
/// The path of an address ("" for none or "/").
fn path_of(url: &str) -> String {
let rest = url.split_once("://").map(|x| x.1).unwrap_or(url);
let p = rest.find('/').map(|i| &rest[i..]).unwrap_or("");
let p = p.split(['?', '#']).next().unwrap_or("");
if p == "/" { String::new() } else { p.trim_end_matches('/').to_string() }
}
/// What a 401's WWW-Authenticate names as the resource's metadata.
pub fn resource_metadata(www_authenticate: &str) -> Option<String> {
let i = www_authenticate.find("resource_metadata=")?;
let rest = &www_authenticate[i + "resource_metadata=".len()..];
let v = if let Some(r) = rest.strip_prefix('"') { r.split('"').next()? } else { rest.split([',', ' ']).next()? };
Some(v.to_string()).filter(|s| !s.is_empty())
}
/// Where a login goes.
#[derive(Clone, Debug, PartialEq)]
pub struct Endpoints {
pub authorize: String,
pub token: String,
pub register: String,
pub scopes: Vec<String>,
/// The resource the tokens are for (the connector's address).
pub resource: String,
}
/// Ask the connector who signs people in, and that server where.
pub fn discover(mcp_url: &str) -> Result<Endpoints, String> {
// The 401 names the resource's metadata (RFC 9728); else its well-known places.
let probe = crate::net::agent(HTTP_SECS)
.post(mcp_url)
.header("Content-Type", "application/json")
.header("Accept", "application/json, text/event-stream")
.send(json!({"jsonrpc": "2.0", "id": 0, "method": "initialize", "params": {"protocolVersion": "2025-06-18", "capabilities": {}, "clientInfo": {"name": "AnyBot", "version": "1"}}}).to_string().as_bytes());
let named = probe.ok().and_then(|r| r.headers().get("www-authenticate").and_then(|v| v.to_str().ok()).and_then(resource_metadata));
let (o, p) = (origin(mcp_url), path_of(mcp_url));
let mut tries: Vec<String> = named.into_iter().collect();
if !p.is_empty() {
tries.push(format!("{o}/.well-known/oauth-protected-resource{p}"));
}
tries.push(format!("{o}/.well-known/oauth-protected-resource"));
let prm = tries.iter().find_map(|u| get_json(u).ok());
let issuer = prm.as_ref().and_then(|m| m["authorization_servers"][0].as_str().map(String::from)).unwrap_or_else(|| o.clone());
let resource = prm.as_ref().and_then(|m| m["resource"].as_str().map(String::from)).unwrap_or_else(|| mcp_url.to_string());
// The authorization server's metadata (RFC 8414, then OpenID's), path-aware.
let (io, ip) = (origin(&issuer), path_of(&issuer));
let mut meta_tries = vec![];
if !ip.is_empty() {
meta_tries.push(format!("{io}/.well-known/oauth-authorization-server{ip}"));
meta_tries.push(format!("{io}/.well-known/openid-configuration{ip}"));
meta_tries.push(format!("{io}{ip}/.well-known/openid-configuration"));
} else {
meta_tries.push(format!("{io}/.well-known/oauth-authorization-server"));
meta_tries.push(format!("{io}/.well-known/openid-configuration"));
}
let meta = meta_tries.iter().find_map(|u| get_json(u).ok());
let s = |k: &str, default: &str| meta.as_ref().and_then(|m| m[k].as_str().map(String::from)).unwrap_or_else(|| format!("{io}{default}"));
let scopes: Vec<String> = prm
.as_ref()
.and_then(|m| m["scopes_supported"].as_array().cloned())
.or_else(|| meta.as_ref().and_then(|m| m["scopes_supported"].as_array().cloned()))
.unwrap_or_default()
.iter()
.filter_map(|x| x.as_str().map(String::from))
.collect();
if let Some(methods) = meta.as_ref().and_then(|m| m["code_challenge_methods_supported"].as_array()) {
if !methods.iter().any(|m| m == "S256") {
return Err("這個連接器的登入伺服器不支援 PKCE(S256),AnyBot 不能安全地登入它。".into());
}
}
Ok(Endpoints { authorize: s("authorization_endpoint", "/authorize"), token: s("token_endpoint", "/token"), register: s("registration_endpoint", "/register"), scopes, resource })
}
/// Register AnyBot with the authorization server (RFC 7591): its client id (and secret, if it
/// gives one).
fn register(e: &Endpoints, redirect: &str) -> Result<(String, String), String> {
let mut resp = crate::net::agent(HTTP_SECS)
.post(e.register.as_str())
.header("Content-Type", "application/json")
.send(json!({"client_name": "AnyBot", "redirect_uris": [redirect], "grant_types": ["authorization_code", "refresh_token"], "response_types": ["code"], "token_endpoint_auth_method": "none"}).to_string().as_bytes())
.map_err(|e| format!("連不上登入伺服器:{e}"))?;
let status = resp.status().as_u16();
let v: Value = serde_json::from_str(&resp.body_mut().read_to_string().unwrap_or_default()).unwrap_or(Value::Null);
match v["client_id"].as_str() {
Some(id) if (200..300).contains(&status) => Ok((id.to_string(), v["client_secret"].as_str().unwrap_or("").to_string())),
_ => Err(format!("這個連接器的登入伺服器不讓 App 自己註冊(HTTP {status}):要先在它那邊建一個 OAuth App 才能登入,AnyBot 還不支援填 client_id。")),
}
}
/// A login waiting for the person.
#[derive(Clone)]
struct Pending {
server: String,
verifier: String,
redirect: String,
endpoints: Endpoints,
client_id: String,
client_secret: String,
started: Instant,
}
fn pending() -> &'static Mutex<HashMap<String, Pending>> {
static P: OnceLock<Mutex<HashMap<String, Pending>>> = OnceLock::new();
P.get_or_init(Default::default)
}
/// A finished login: the connector, and whether it worked.
type Finished = (String, Result<(), String>);
/// Logins that finished since last asked.
fn finished() -> &'static Mutex<Vec<Finished>> {
static F: OnceLock<Mutex<Vec<Finished>>> = OnceLock::new();
F.get_or_init(Default::default)
}
/// Logins of the connectors `mine` takes that finished since last time (the window reconnects
/// those and says so; another AnyBot in this process — tests — takes its own).
pub fn take_finished(mine: impl Fn(&str) -> bool) -> Vec<(String, Result<(), String>)> {
let mut all = finished().lock().unwrap_or_else(|e| e.into_inner());
let (taken, left): (Vec<_>, Vec<_>) = std::mem::take(&mut *all).into_iter().partition(|(n, _)| mine(n));
*all = left;
taken
}
fn challenge(verifier: &str) -> String {
use base64::Engine;
base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(ring::digest::digest(&ring::digest::SHA256, verifier.as_bytes()).as_ref())
}
/// Start logging connector `server` (its address `mcp_url`) in: the address to open in the
/// person's browser. A listener on this computer waits for the browser to come back.
pub fn start(server: &str, mcp_url: &str) -> Result<String, String> {
let endpoints = discover(mcp_url)?;
let listener = std::net::TcpListener::bind("127.0.0.1:0").map_err(|e| format!("開不了接登入結果的連接埠:{e}"))?;
let port = listener.local_addr().map_err(|e| e.to_string())?.port();
let redirect = format!("http://127.0.0.1:{port}/callback");
let (client_id, client_secret) = register(&endpoints, &redirect)?;
let verifier = crate::httpd::random_hex(32);
let state = crate::httpd::random_hex(16);
let mut url = format!(
"{}{}response_type=code&client_id={}&redirect_uri={}&code_challenge={}&code_challenge_method=S256&state={}&resource={}",
endpoints.authorize,
if endpoints.authorize.contains('?') { "&" } else { "?" },
enc(&client_id),
enc(&redirect),
enc(&challenge(&verifier)),
enc(&state),
enc(&endpoints.resource)
);
if !endpoints.scopes.is_empty() {
url.push_str(&format!("&scope={}", enc(&endpoints.scopes.join(" "))));
}
{
let mut p = pending().lock().unwrap_or_else(|e| e.into_inner());
p.retain(|_, x| x.started.elapsed() < LOGIN_WAIT && x.server != server);
p.insert(state.clone(), Pending { server: server.to_string(), verifier, redirect, endpoints, client_id, client_secret, started: Instant::now() });
}
std::thread::spawn(move || listen(listener, &state));
Ok(url)
}
/// Wait for the browser to come back (or the time to run out).
fn listen(listener: std::net::TcpListener, state: &str) {
let _ = listener.set_nonblocking(true);
let t0 = Instant::now();
while t0.elapsed() < LOGIN_WAIT {
if !pending().lock().unwrap_or_else(|e| e.into_inner()).contains_key(state) {
return; // (finished another way: the address pasted in the chat)
}
let Ok((mut stream, _)) = listener.accept() else {
std::thread::sleep(Duration::from_millis(100));
continue;
};
let _ = stream.set_nonblocking(false);
let _ = stream.set_read_timeout(Some(Duration::from_secs(5)));
let mut line = String::new();
let _ = BufReader::new(&stream).read_line(&mut line);
let target = line.split_whitespace().nth(1).unwrap_or("");
let Some(query) = target.strip_prefix("/callback?") else {
let _ = stream.write_all(b"HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\nConnection: close\r\n\r\n");
continue;
};
let r = finish_query(query);
let page = match &r {
Ok(name) => format!("已登入「{name}」,可以關掉這頁,回到 AnyBot。"),
Err(e) => format!("沒有登入成功:{e}"),
};
let html = format!("<!doctype html><meta charset=utf-8><title>AnyBot</title><body style=\"font:16px system-ui;padding:40px\">{}</body>", page.replace('<', "&lt;"));
let _ = stream.write_all(format!("HTTP/1.1 200 OK\r\nContent-Type: text/html; charset=utf-8\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{html}", html.len()).as_bytes());
if r.is_ok() || !pending().lock().unwrap_or_else(|e| e.into_inner()).contains_key(state) {
return;
}
}
if let Some(p) = pending().lock().unwrap_or_else(|e| e.into_inner()).remove(state) {
finished().lock().unwrap_or_else(|e| e.into_inner()).push((p.server, Err("等了 10 分鐘都沒有登入,取消了".into())));
}
}
/// The address the browser came back to, pasted in the chat: finish that login.
pub fn finish_from_url(callback: &str) -> Result<String, String> {
let query = callback.split_once('?').map(|x| x.1).ok_or("這個網址裡沒有登入的結果(要有 ?code=…&state=…)")?;
finish_query(query.split('#').next().unwrap_or(query))
}
/// Swap the code for tokens and keep them: the connector's name.
fn finish_query(query: &str) -> Result<String, String> {
let q = query_pairs(query);
let state = q.get("state").cloned().unwrap_or_default();
let p = pending().lock().unwrap_or_else(|e| e.into_inner()).remove(&state).ok_or("這個登入結果對不上任何進行中的登入(過期了,或已經用過):重新登入一次")?;
let r = (|| {
if let Some(e) = q.get("error") {
return Err(format!("登入伺服器說:{}", q.get("error_description").unwrap_or(e)));
}
let code = q.get("code").filter(|c| !c.is_empty()).ok_or("網址裡沒有 code")?;
let mut form = vec![
("grant_type", "authorization_code".to_string()),
("code", code.clone()),
("redirect_uri", p.redirect.clone()),
("client_id", p.client_id.clone()),
("code_verifier", p.verifier.clone()),
("resource", p.endpoints.resource.clone()),
];
if !p.client_secret.is_empty() {
form.push(("client_secret", p.client_secret.clone()));
}
let v = post_form(&p.endpoints.token, &form)?;
let base = Tokens { token_endpoint: p.endpoints.token.clone(), client_id: p.client_id.clone(), client_secret: p.client_secret.clone(), resource: p.endpoints.resource.clone(), ..Default::default() };
save(&p.server, Some(tokens_from(&v, &base)?))
})();
finished().lock().unwrap_or_else(|e| e.into_inner()).push((p.server.clone(), r.clone()));
r.map(|_| p.server)
}
#[cfg(test)]
pub mod tests {
use super::*;
use std::io::Read;
use std::sync::Arc;
/// A connector that only answers with a token, and the server that hands them out — both in
/// one: it checks the PKCE challenge, the redirect, and the resource.
pub struct FakeOAuth {
pub port: u16,
pub url: String,
pub tokens_given: Arc<Mutex<u32>>,
}
fn respond(s: &mut std::net::TcpStream, status: &str, headers: &[(&str, String)], body: &str) {
let mut h = format!("HTTP/1.1 {status}\r\nContent-Length: {}\r\nConnection: close\r\n", body.len());
for (k, v) in headers {
h.push_str(&format!("{k}: {v}\r\n"));
}
let _ = s.write_all(format!("{h}\r\n{body}").as_bytes());
}
impl FakeOAuth {
pub fn start() -> FakeOAuth {
let l = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
let port = l.local_addr().unwrap().port();
let base = format!("http://127.0.0.1:{port}");
let given = Arc::new(Mutex::new(0u32));
let g = given.clone();
let url = format!("{base}/mcp");
std::thread::spawn(move || {
let mut challenge_seen = String::new();
let mut token_n = 0;
for s in l.incoming().flatten() {
let mut s = s;
let mut r = BufReader::new(s.try_clone().unwrap());
let mut first = String::new();
if r.read_line(&mut first).is_err() {
continue;
}
let mut len = 0usize;
let mut auth = String::new();
loop {
let mut h = String::new();
if r.read_line(&mut h).is_err() || h.trim().is_empty() {
break;
}
let lower = h.to_ascii_lowercase();
if let Some(v) = lower.strip_prefix("content-length:") {
len = v.trim().parse().unwrap_or(0);
}
if lower.starts_with("authorization:") {
auth = h.split_once(':').unwrap().1.trim().to_string();
}
}
let mut body = vec![0u8; len];
let _ = r.read_exact(&mut body);
let body = String::from_utf8_lossy(&body).to_string();
let target = first.split_whitespace().nth(1).unwrap_or("").to_string();
let (path, query) = target.split_once('?').unwrap_or((&target, ""));
let json_h = || vec![("Content-Type", "application/json".to_string())];
match path {
"/mcp" if auth.starts_with("Bearer good-") => {
let v: Value = serde_json::from_str(&body).unwrap_or(Value::Null);
let result = match v["method"].as_str().unwrap_or("") {
"initialize" => json!({"protocolVersion": "2025-06-18", "capabilities": {"tools": {}}, "serverInfo": {"name": "fake", "version": "1"}}),
"tools/list" => json!({"tools": [{"name": "whoami", "description": "Who is logged in", "inputSchema": {"type": "object"}}]}),
_ => json!({}),
};
if v["id"].is_null() {
respond(&mut s, "202 Accepted", &[], "");
} else {
respond(&mut s, "200 OK", &json_h(), &json!({"jsonrpc": "2.0", "id": v["id"], "result": result}).to_string());
}
}
"/mcp" => respond(&mut s, "401 Unauthorized", &[("WWW-Authenticate", format!("Bearer resource_metadata=\"{base}/.well-known/oauth-protected-resource/mcp\""))], ""),
"/.well-known/oauth-protected-resource/mcp" => respond(&mut s, "200 OK", &json_h(), &json!({"resource": format!("{base}/mcp"), "authorization_servers": [base], "scopes_supported": ["mcp:tools"]}).to_string()),
"/.well-known/oauth-authorization-server" => respond(&mut s, "200 OK", &json_h(), &json!({"issuer": base, "authorization_endpoint": format!("{base}/authorize"), "token_endpoint": format!("{base}/token"), "registration_endpoint": format!("{base}/register"), "code_challenge_methods_supported": ["S256"]}).to_string()),
"/register" => respond(&mut s, "201 Created", &json_h(), &json!({"client_id": "anybot-client"}).to_string()),
"/authorize" => {
// (The person logs in and allows it: back to AnyBot with a code.)
let q = query_pairs(query);
assert_eq!(q.get("code_challenge_method").map(String::as_str), Some("S256"));
assert_eq!(q.get("resource"), Some(&format!("{base}/mcp")));
assert_eq!(q.get("scope").map(String::as_str), Some("mcp:tools"));
challenge_seen = q["code_challenge"].clone();
let to = format!("{}?code=the-code&state={}", q["redirect_uri"], enc(&q["state"]));
respond(&mut s, "302 Found", &[("Location", to)], "");
}
"/token" => {
let f = query_pairs(&body);
let ok = match f.get("grant_type").map(String::as_str) {
Some("authorization_code") => f.get("code").map(String::as_str) == Some("the-code") && challenge(&f["code_verifier"]) == challenge_seen,
Some("refresh_token") => f.get("refresh_token").map(String::as_str) == Some("r-1"),
_ => false,
};
if ok {
token_n += 1;
*g.lock().unwrap() += 1;
respond(&mut s, "200 OK", &json_h(), &json!({"access_token": format!("good-{token_n}"), "refresh_token": "r-1", "expires_in": 3600, "token_type": "Bearer"}).to_string());
} else {
respond(&mut s, "400 Bad Request", &json_h(), &json!({"error": "invalid_grant"}).to_string());
}
}
_ => respond(&mut s, "404 Not Found", &[], ""),
}
}
});
FakeOAuth { port, url, tokens_given: given }
}
}
#[test]
fn the_words_of_a_login() {
assert_eq!(resource_metadata(r#"Bearer error="invalid_token", resource_metadata="https://a.example/.well-known/oauth-protected-resource""#).as_deref(), Some("https://a.example/.well-known/oauth-protected-resource"));
assert_eq!(resource_metadata("Bearer realm=x"), None);
assert_eq!((origin("https://mcp.notion.com/mcp?x=1"), path_of("https://mcp.notion.com/mcp?x=1")), ("https://mcp.notion.com".into(), "/mcp".into()));
assert_eq!(path_of("https://a.example/"), "");
assert_eq!(enc("a b/c?d=é"), "a%20b%2Fc%3Fd%3D%C3%A9");
assert_eq!(dec("a%20b%2Fc+d%C3%A9%"), "a b/c dé%");
// S256 = base64url(sha256(verifier)), no padding (checked against Python's hashlib).
assert_eq!(challenge("dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWwjXk"), "qBDSUaImE-WxTq4xZVKSKIi4bDy4teecLEwvWS_LsfQ");
}
/// Against a test OAuth server: the login address is right, the browser's way back is caught,
/// the code becomes tokens (PKCE checked by the server), and a token near its end is renewed.
#[test]
fn logging_a_connector_in() {
let fake = FakeOAuth::start();
let name = format!("oauth-test-{}", fake.port);
let url = start(&name, &fake.url).unwrap();
assert!(url.starts_with(&format!("http://127.0.0.1:{}/authorize?response_type=code&client_id=anybot-client", fake.port)), "{url}");
// The person's browser: the login page sends it back to AnyBot's listener.
let mut page = crate::net::agent(10).get(url.as_str()).call().unwrap();
let text = page.body_mut().read_to_string().unwrap();
assert!(text.contains("已登入"), "{text}");
let t = tokens(&name).unwrap();
assert_eq!((t.access.as_str(), t.refresh.as_str(), t.resource.as_str()), ("good-1", "r-1", fake.url.as_str()));
assert!(take_finished(|n| n == name).iter().any(|(_, r)| r.is_ok()));
// Near its end: renewed before it is sent.
let mut all = read_all();
all.get_mut(&name).unwrap().expires_at = crate::model::now_ms() + 1000;
write_all(&all).unwrap();
assert_eq!(bearer(&name).as_deref(), Some("good-2"));
assert_eq!(*fake.tokens_given.lock().unwrap(), 2, "one for the code, one renewal");
// The same address again: that login is used up.
assert!(finish_from_url("http://127.0.0.1:1/callback?code=the-code&state=nope").is_err());
logout(&name).unwrap();
assert!(tokens(&name).is_none());
}
/// The connector itself: before the login it says to log in; after it, it connects with the
/// token and its tools are there.
#[test]
fn a_logged_in_connector_connects() {
// (sync keeps only the servers it is given: one test at a time touches the table.)
let _one = crate::mcp::test_lock();
let fake = FakeOAuth::start();
let name = format!("oauth-conn-{}", fake.port);
let server = crate::mcp::Server { name: name.clone(), url: fake.url.clone(), enabled: true, ..Default::default() };
let errs = crate::mcp::sync(std::slice::from_ref(&server));
assert!(errs.iter().any(|(n, e)| n == &name && e.contains("登入")), "{errs:?}");
let url = start(&name, &fake.url).unwrap();
crate::net::agent(10).get(url.as_str()).call().unwrap();
crate::mcp::forget(&name);
let errs = crate::mcp::sync(std::slice::from_ref(&server));
assert!(errs.iter().all(|(n, _)| n != &name), "{errs:?}");
assert_eq!(crate::mcp::status().get(&name).copied(), Some(1), "its one tool");
crate::mcp::forget(&name);
let _ = logout(&name);
}
/// The browser on another computer: the address it came back to is pasted in the chat.
#[test]
fn a_pasted_address_finishes_the_login() {
let fake = FakeOAuth::start();
let name = format!("oauth-paste-{}", fake.port);
let url = start(&name, &fake.url).unwrap();
let no_follow: ureq::Agent = crate::net::config().max_redirects(0).http_status_as_error(false).build().into();
let resp = no_follow.get(url.as_str()).call().unwrap();
let back = resp.headers().get("location").unwrap().to_str().unwrap().to_string();
assert_eq!(finish_from_url(&back).unwrap(), name);
assert_eq!(tokens(&name).unwrap().access, "good-1");
let _ = logout(&name);
}
}