AnyBot/src/chatgpt.rs

1286 lines
62 KiB
Rust
Raw Normal View History

feat: ChatGPT 方案——用 ChatGPT 帳號登入,Bot 用你 ChatGPT 方案的額度,不用 API 金鑰 - 新供應商「ChatGPT 方案」(src/chatgpt.rs):照 OpenAI 給開源 App 的 Sign in with ChatGPT。 第一次登入註冊 AnyBot(dynamic_agent_client → oaiapp_…)並重用;PKCE、state、nonce; ID token 驗 RS256 簽章、iss、aud、exp、nonce;沒同意使用方案算登入但不能用(再登入會要求同意)。 - 要求走 Responses API(api.openai.com/v1/responses,store:false、stream:true、instructions), token 只送 OpenAI 自己的網址;收到 response.completed 才算完成;額度用完停下來給管理用量連結, 不重試、不改用 API 金鑰。token 快到期或 401 時更新(一次一個,refresh token 會輪替)。 - 設定 › 模型 › ChatGPT 方案:使用 ChatGPT 繼續、登出、換帳號、打開登入頁、管理用量; 連到伺服器大腦的螢幕電腦和手機也能登入(登入頁開在自己這台,打不開的那頁網址貼回給大腦)。 - Bot 工具 chatgpt_login(status、login、logout、switch_account;登出和換帳號先問)。 - 修連接器登入:封存的 token 前綴寫錯("sealed:" 實際是 "enc:v1:"),重開 App 後 token 沒解開就被當成憑證送出,登入等於每次重開都失效。 已驗證: cargo test 全綠(chatgpt::、providers::、appctl::、remote::、mcp_oauth::、featuremap::、layout_audit::); 授權網址的參數送到 auth.openai.com 沒被拒(302 到登入頁)。 未驗證: 實際用 ChatGPT 帳號登入、同意、Responses 串流與工具呼叫(要真的 ChatGPT 付費帳號和瀏覽器); 螢幕電腦貼回網址、手機登入(要實機);Windows 的「打開登入頁」。 動到審批路徑(appctl::needs_approval 的 chatgpt_login):需要實機測試+人類簽名。 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 09:23:10 +00:00
//! ChatGPT 方案: bots run on the person's ChatGPT plan (the usage Plus, Pro, Business… come with,
//! the same Codex uses) instead of an API key — OpenAI's Sign in with ChatGPT for open-source and
//! locally hosted apps (developers.openai.com/siwc/token-sharing-open-source).
//!
//! Signing in: the browser goes to auth.openai.com. The first time, AnyBot registers itself there
//! (`client_id=dynamic_agent_client`) and is given its own client id (`oaiapp_…`), kept and used
//! from then on, with this computer's own opaque host id. The browser comes back to
//! `http://127.0.0.1:<port>/auth/callback` on the brain; when the browser is on another computer
//! (a brain on a server) that page can't load, and the person copies its address into the chat
//! (`chatgpt_login` with `callback`): the code is swapped here, where the PKCE verifier is.
//! The ID token is checked (RS256 against OpenAI's published keys, issuer, audience, nonce,
//! expiry) and the grant must include `chatgpt.tokens.use.direct` — without it the person is
//! signed in but the plan can't be used.
//!
//! Requests go to the public Responses API with the access token (providers::stream_responses).
//! An access token lasts an hour; it is renewed with the refresh token, which rotates, so one
//! renewal at a time. A usage limit stops the request: it never moves to API-key billing.
//!
//! Kept in `<資料夾>/providers/chatgpt.json`, the tokens sealed like the settings' secrets; never in
//! the settings, which screens and the phone get.
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};
/// The bot tool that signs in, out, and says how it stands.
pub const TOOL: &str = "chatgpt_login";
pub const ISSUER: &str = "https://auth.openai.com";
/// Where requests on the plan go: only here (the token is never sent to another address).
pub const API_BASE: &str = "https://api.openai.com/v1";
/// The setting the person manages the plan's usage with.
pub const USAGE_URL: &str = "https://chatgpt.com/settings/usage";
/// The scope that lets an app use the plan (signing in alone doesn't).
pub const PLAN_SCOPE: &str = "chatgpt.tokens.use.direct";
const SCOPES: &str = "openid profile email offline_access resource.invoke chatgpt.tokens.use.direct";
const FIRST_CLIENT: &str = "dynamic_agent_client";
const PREFERRED_PORT: u16 = 1455;
const LOGIN_WAIT: Duration = Duration::from_secs(10 * 60);
const HTTP_SECS: u64 = 20;
/// Renew this long before the access token ends.
const RENEW_EARLY_MS: i64 = 5 * 60_000;
pub const NEED_LOGIN: &str = "還沒有登入 ChatGPT。請到「設定 › 模型 › ChatGPT 方案」按「使用 ChatGPT 繼續」,或在聊天裡請 Bot 幫你登入。";
pub const NO_PLAN: &str = "已登入 ChatGPT,但沒有同意讓 AnyBot 使用你的 ChatGPT 方案。要用的話再登入一次並同意;或改用 OpenAI 的 API 金鑰。";
const EXPIRED: &str = "ChatGPT 的登入失效了(登出、在 ChatGPT 設定裡中斷連線,或太久沒用)。請重新登入:設定 › 模型 › ChatGPT 方案,或在聊天裡請 Bot 幫你登入。";
/// The one ChatGPT account this AnyBot uses.
#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq)]
pub struct Account {
/// The client id OpenAI issued to this AnyBot for this account (oaiapp_…): kept after
/// signing out and reused, so signing in again doesn't register again.
#[serde(default)]
pub client_id: String,
/// This computer's stable, opaque id for OpenAI (urn:uuid:…): made once, never replaced.
#[serde(default)]
pub host_id: String,
#[serde(default)]
pub access: String,
#[serde(default)]
pub refresh: String,
#[serde(default)]
pub id_token: String,
/// When the access token ends (ms; 0: not said).
#[serde(default)]
pub expires_at: i64,
#[serde(default)]
pub scopes: Vec<String>,
/// Who signed in (from the checked ID token): `sub` is the identity, the email for showing.
#[serde(default)]
pub sub: String,
#[serde(default)]
pub email: String,
/// The first sign-in with the plan was welcomed (that note shows once).
#[serde(default)]
pub welcomed: bool,
}
impl Account {
pub fn signed_in(&self) -> bool {
!self.access.is_empty() && !self.access.starts_with(crate::vault_store::SEALED)
}
pub fn plan_ok(&self) -> bool {
self.scopes.iter().any(|s| s == PLAN_SCOPE)
}
fn near_end(&self) -> bool {
self.expires_at > 0 && self.expires_at - RENEW_EARLY_MS < crate::model::now_ms()
}
/// Signed out: the tokens go, the registration (client id, who) and the host id stay.
fn without_tokens(&self) -> Account {
Account { client_id: self.client_id.clone(), host_id: self.host_id.clone(), sub: self.sub.clone(), email: self.email.clone(), welcomed: self.welcomed, ..Default::default() }
}
}
// ---------- where things are (tests point them elsewhere) ----------
#[cfg(test)]
thread_local! {
static TEST_AUTH: std::cell::RefCell<Option<String>> = const { std::cell::RefCell::new(None) };
static TEST_FILE: std::cell::RefCell<Option<std::path::PathBuf>> = const { std::cell::RefCell::new(None) };
static TEST_API: std::cell::RefCell<Option<String>> = const { std::cell::RefCell::new(None) };
}
fn auth_base() -> String {
#[cfg(test)]
if let Some(b) = TEST_AUTH.with(|t| t.borrow().clone()) {
return b;
}
ISSUER.to_string()
}
/// Where requests on the plan go (a test's own server in tests).
pub fn api_base() -> String {
#[cfg(test)]
if let Some(b) = TEST_API.with(|t| t.borrow().clone()) {
return b;
}
API_BASE.to_string()
}
fn file() -> std::path::PathBuf {
#[cfg(test)]
if let Some(p) = TEST_FILE.with(|t| t.borrow().clone()) {
return p;
}
crate::model::State::path().parent().map(|d| d.join("providers").join("chatgpt.json")).unwrap_or_else(|| std::path::PathBuf::from("chatgpt.json"))
}
// ---------- the account on disk ----------
fn store() -> &'static Mutex<()> {
static S: OnceLock<Mutex<()>> = OnceLock::new();
S.get_or_init(|| Mutex::new(()))
}
const SEALED_FIELDS: [&str; 3] = ["access", "refresh", "id_token"];
fn read() -> Account {
let mut v: Value = serde_json::from_str(&std::fs::read_to_string(file()).unwrap_or_default()).unwrap_or(json!({}));
for k in SEALED_FIELDS {
if let Some(s) = v[k].as_str().filter(|s| s.starts_with(crate::vault_store::SEALED)).map(String::from) {
// (One that can't be opened now — the keychain is locked — stays sealed and isn't used.)
if let Some(plain) = crate::vault_store::open_text(&s) {
v[k] = json!(plain);
}
}
}
serde_json::from_value(v).unwrap_or_default()
}
fn write(a: &Account) -> Result<(), String> {
let mut v = serde_json::to_value(a).map_err(|e| e.to_string())?;
for k in SEALED_FIELDS {
if let Some(sealed) = v[k].as_str().and_then(crate::vault_store::seal_text) {
v[k] = json!(sealed);
}
}
let p = file();
if let Some(d) = p.parent() {
std::fs::create_dir_all(d).map_err(|e| e.to_string())?;
}
// Written whole and then moved into place, readable by this user only from the start.
let tmp = p.with_extension("json.tmp");
let _ = std::fs::remove_file(&tmp);
let mut o = std::fs::OpenOptions::new();
o.write(true).create_new(true);
#[cfg(unix)]
std::os::unix::fs::OpenOptionsExt::mode(&mut o, 0o600);
o.open(&tmp).and_then(|mut f| f.write_all(serde_json::to_string_pretty(&v).unwrap_or_default().as_bytes())).map_err(|e| e.to_string())?;
std::fs::rename(&tmp, &p).map_err(|e| e.to_string())
}
/// The account as last read or written (the settings ask every frame): by file, and only once
/// every token in it could be opened (a locked keychain is tried again next time).
fn cache() -> &'static Mutex<Option<(std::path::PathBuf, Account)>> {
static C: OnceLock<Mutex<Option<(std::path::PathBuf, Account)>>> = OnceLock::new();
C.get_or_init(Default::default)
}
fn remember(a: &Account) {
let opened = [&a.access, &a.refresh, &a.id_token].iter().all(|t| !t.starts_with(crate::vault_store::SEALED));
*cache().lock().unwrap_or_else(|e| e.into_inner()) = opened.then(|| (file(), a.clone()));
}
/// The account as kept (tokens opened).
pub fn account() -> Account {
let _g = store().lock().unwrap_or_else(|e| e.into_inner());
if let Some((p, a)) = cache().lock().unwrap_or_else(|e| e.into_inner()).as_ref() {
if *p == file() {
return a.clone();
}
}
let a = read();
remember(&a);
a
}
/// Change the account and keep it, in one go.
fn update(f: impl FnOnce(&mut Account)) -> Result<Account, String> {
let _g = store().lock().unwrap_or_else(|e| e.into_inner());
let mut a = read();
f(&mut a);
write(&a)?;
remember(&a);
Ok(a)
}
/// What the settings show under the sign-in buttons (set by the sign-in started there).
fn note_cell() -> &'static Mutex<String> {
static N: OnceLock<Mutex<String>> = OnceLock::new();
N.get_or_init(Default::default)
}
pub fn note() -> String {
note_cell().lock().unwrap_or_else(|e| e.into_inner()).clone()
}
pub fn set_note(s: impl Into<String>) {
*note_cell().lock().unwrap_or_else(|e| e.into_inner()) = s.into();
}
/// The sign-in page of the sign-in waiting now (a link in the settings, for when the browser
/// didn't open, or on Windows, whose `start` cuts an address at its first &).
pub fn login_url() -> Option<String> {
let p = pending().lock().unwrap_or_else(|e| e.into_inner());
p.values().next().filter(|x| x.started.elapsed() < LOGIN_WAIT).map(|x| x.url.clone())
}
/// This computer's host id, made once (an opaque random UUID: nothing about the person).
fn host_id() -> Result<String, String> {
let a = account();
if !a.host_id.is_empty() {
return Ok(a.host_id);
}
let h = crate::httpd::random_hex(16);
let b = h.as_bytes();
let s = |r: std::ops::Range<usize>| std::str::from_utf8(&b[r]).unwrap_or("0").to_string();
// Version 4, variant 10xx.
let variant = ["8", "9", "a", "b"][usize::from_str_radix(&s(16..17), 16).unwrap_or(0) % 4];
let id = format!("urn:uuid:{}-{}-4{}-{}{}-{}", s(0..8), s(8..12), s(13..16), variant, s(17..20), s(20..32));
let id2 = id.clone();
update(move |a| {
if a.host_id.is_empty() {
a.host_id = id2;
}
})
.map(|a| a.host_id)
.or(Ok(id))
}
/// The access token as kept, without asking anyone (whether the provider is ready to use):
/// empty when not signed in or the plan wasn't allowed.
pub fn stored_token() -> String {
let a = account();
if a.signed_in() && a.plan_ok() { a.access } else { String::new() }
}
/// Why there is no token to send (without asking anyone): not signed in, or the plan not allowed.
pub fn why_not_ready() -> &'static str {
let a = account();
if a.signed_in() && !a.plan_ok() { NO_PLAN } else { NEED_LOGIN }
}
// ---------- the protocol ----------
fn enc(s: &str) -> String {
crate::mcp_oauth::enc(s)
}
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()
}
fn query_pairs(q: &str) -> HashMap<String, String> {
q.split('&').filter_map(|kv| kv.split_once('=')).map(|(k, v)| (dec(k), dec(v))).collect()
}
/// A form POST: (status, the JSON answer). Err only when nothing came back.
fn post_form(url: &str, form: &[(&str, String)]) -> Result<(u16, 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!("連不上 OpenAI 的登入伺服器:{e}"))?;
let status = resp.status().as_u16();
let text = resp.body_mut().read_to_string().unwrap_or_default();
Ok((status, serde_json::from_str(&text).unwrap_or(json!({"error": text.chars().take(200).collect::<String>()}))))
}
/// An OAuth error's code, flat (`{"error":"invalid_grant"}`) or nested (`{"error":{"code":…}}`).
fn err_code(v: &Value) -> &str {
v["error"].as_str().or(v["error"]["code"].as_str()).or(v["code"].as_str()).unwrap_or("")
}
fn oauth_error(v: &Value) -> String {
let code = err_code(v);
let said = v["error_description"].as_str().or(v["error"]["message"].as_str()).unwrap_or(code);
if said.is_empty() { "(沒有說原因)".into() } else { said.to_string() }
}
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())
}
/// A sign-in waiting for the person.
#[derive(Clone)]
struct Pending {
/// The sign-in page (shown again as a link in the settings).
url: String,
verifier: String,
nonce: String,
redirect: String,
/// The client id the browser was sent with (FIRST_CLIENT: a new registration).
client_id: 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)
}
/// Sign-ins that finished since last asked: Ok(who) or why not.
fn finished() -> &'static Mutex<Vec<Result<String, String>>> {
static F: OnceLock<Mutex<Vec<Result<String, String>>>> = OnceLock::new();
F.get_or_init(Default::default)
}
pub fn take_finished() -> Vec<Result<String, String>> {
std::mem::take(&mut *finished().lock().unwrap_or_else(|e| e.into_inner()))
}
/// The address that sends the browser to sign in (and, the first time, register AnyBot).
fn authorize_url(a: &Account, host: &str, redirect: &str, state: &str, nonce: &str, verifier: &str) -> (String, String) {
let first = a.client_id.is_empty();
let client = if first { FIRST_CLIENT.to_string() } else { a.client_id.clone() };
let mut url = format!("{}/api/accounts/authorize?client_id={}", auth_base(), enc(&client));
if first {
url.push_str("&agent_name_hint=AnyBot");
} else if !a.email.is_empty() {
url.push_str(&format!("&login_hint={}", enc(&a.email)));
}
// Signed in without the plan: asked again for it (OpenAI shows the consent once more).
if a.signed_in() && !a.plan_ok() {
url.push_str("&prompt=consent");
}
url.push_str(&format!(
"&ext_agent_host_id={}&response_type=code&redirect_uri={}&scope={}&resource={}&state={}&nonce={}&code_challenge={}&code_challenge_method=S256",
enc(host),
enc(redirect),
enc(SCOPES),
enc(API_BASE),
enc(state),
enc(nonce),
enc(&challenge(verifier))
));
(url, client)
}
/// Start signing in: the address to open in the person's browser. A listener on this computer
/// waits for the browser to come back (10 minutes); the address it comes back to can also be
/// handed over with [`finish_from_url`].
pub fn start() -> Result<String, String> {
let host = host_id()?;
// OpenAI's usual port first; any other free one if it's taken (only the port may change).
let listener = std::net::TcpListener::bind(("127.0.0.1", PREFERRED_PORT))
.or_else(|_| 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}/auth/callback");
let (verifier, state, nonce) = (crate::httpd::random_hex(32), crate::httpd::random_hex(16), crate::httpd::random_hex(16));
let (url, client_id) = authorize_url(&account(), &host, &redirect, &state, &nonce, &verifier);
{
// One sign-in at a time: a newer one replaces the one before (its listener stops).
let mut p = pending().lock().unwrap_or_else(|e| e.into_inner());
p.clear();
p.insert(state.clone(), Pending { url: url.clone(), verifier, nonce, redirect, client_id, 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, or a newer sign-in started)
}
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("/auth/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(who) => format!("已用 ChatGPT({who})登入,可以關掉這頁,回到 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('&', "&amp;").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 pending().lock().unwrap_or_else(|e| e.into_inner()).remove(state).is_some() {
finished().lock().unwrap_or_else(|e| e.into_inner()).push(Err("等了 10 分鐘都沒有登入,取消了".into()));
}
}
/// The address the browser came back to, pasted in the chat: finish that sign-in.
pub fn finish_from_url(callback: &str) -> Result<String, String> {
let callback = callback.trim();
let query = callback.split_once('?').map(|x| x.1).ok_or("這個網址裡沒有登入的結果(要有 ?code=…&state=…)")?;
finish_query(query.split('#').next().unwrap_or(query))
}
/// Check the callback, swap the code for tokens, check the ID token and keep it all: who signed in.
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 = finish_pending(&p, &q);
set_note(String::new());
finished().lock().unwrap_or_else(|e| e.into_inner()).push(r.clone());
r
}
fn finish_pending(p: &Pending, q: &HashMap<String, String>) -> Result<String, String> {
if p.started.elapsed() > LOGIN_WAIT {
return Err("這次登入等太久過期了:重新登入一次".into());
}
if let Some(e) = q.get("error") {
if e == "access_denied" {
return Err("你在 ChatGPT 的頁面上沒有同意,所以沒有登入。".into());
}
return Err(format!("OpenAI 說:{}", q.get("error_description").unwrap_or(e)));
}
let code = q.get("code").filter(|c| !c.is_empty()).ok_or("網址裡沒有 code")?;
let given = q.get("client_id").map(|s| s.trim().to_string()).filter(|s| !s.is_empty());
let client_id = if p.client_id == FIRST_CLIENT {
// A new registration must come back with the client id OpenAI issued.
given.filter(|g| g != FIRST_CLIENT).ok_or("OpenAI 沒有給這個 AnyBot 用戶端編號,註冊沒有完成:重新登入一次")?
} else {
if given.as_ref().is_some_and(|g| *g != p.client_id) {
return Err("登入結果裡的用戶端編號跟這個 AnyBot 註冊的不一樣,沒有採用。重新登入一次".into());
}
p.client_id.clone()
};
let (status, v) = post_form(
&format!("{}/api/accounts/oauth/token", auth_base()),
&[
("grant_type", "authorization_code".into()),
("client_id", client_id.clone()),
("code", code.clone()),
("code_verifier", p.verifier.clone()),
("redirect_uri", p.redirect.clone()),
("resource", API_BASE.into()),
],
)?;
if !(200..300).contains(&status) || v["access_token"].as_str().unwrap_or("").is_empty() {
let again = if err_code(&v) == "invalid_grant" { "(這個登入碼不能用了)" } else { "" };
return Err(format!("OpenAI 沒有給登入憑證{again}:{}。重新登入一次", oauth_error(&v)));
}
let id_token = v["id_token"].as_str().unwrap_or("");
if id_token.is_empty() {
return Err("OpenAI 沒有給身分憑證(ID token),沒有採用這次登入".into());
}
let jwks = fetch_jwks()?;
let who = verify_id_token(id_token, &jwks, &client_id, &p.nonce, crate::model::now_ms() / 1000)?;
// (What was granted, as OpenAI's token answer says: not the address, which may be pasted.)
let scopes: Vec<String> = v["scope"].as_str().unwrap_or("").split_whitespace().map(String::from).collect();
let before = account();
// The same registration signs in the same person: another account is not put in its place.
if !before.sub.is_empty() && before.client_id == client_id && before.sub != who.sub {
return Err(format!("登入的是另一個 ChatGPT 帳號({}),這個 AnyBot 用的是 {}。要換帳號,請先「換帳號」再登入。", who.email, before.email));
}
let now = crate::model::now_ms();
update(|a| {
a.client_id = client_id.clone();
a.access = v["access_token"].as_str().unwrap_or("").to_string();
a.refresh = v["refresh_token"].as_str().unwrap_or("").to_string();
a.id_token = id_token.to_string();
a.expires_at = v["expires_in"].as_i64().map(|s| now + s * 1000).unwrap_or(0);
a.scopes = scopes.clone();
a.sub = who.sub.clone();
a.email = who.email.clone();
})?;
if !scopes.iter().any(|s| s == PLAN_SCOPE) {
return Err(NO_PLAN.into());
}
Ok(if who.email.is_empty() { "你的帳號".into() } else { who.email })
}
// ---------- the ID token ----------
#[derive(Debug, PartialEq)]
pub struct Who {
pub sub: String,
pub email: String,
}
fn b64url(s: &str) -> Result<Vec<u8>, String> {
use base64::Engine;
base64::engine::general_purpose::URL_SAFE_NO_PAD.decode(s.trim_end_matches('=')).map_err(|_| "身分憑證的格式不對".to_string())
}
fn fetch_jwks() -> Result<Value, String> {
let mut resp = crate::net::agent(HTTP_SECS).get(&format!("{}/.well-known/jwks.json", auth_base())).call().map_err(|e| format!("拿不到 OpenAI 的簽章金鑰:{e}"))?;
if !(200..300).contains(&resp.status().as_u16()) {
return Err(format!("拿不到 OpenAI 的簽章金鑰(HTTP {})", resp.status().as_u16()));
}
serde_json::from_str(&resp.body_mut().read_to_string().unwrap_or_default()).map_err(|_| "OpenAI 的簽章金鑰不是 JSON".into())
}
/// Check an ID token: signed (RS256) by one of `jwks`' keys, from OpenAI, for this client, for
/// this sign-in (nonce), not ended. Who it is.
pub fn verify_id_token(token: &str, jwks: &Value, client_id: &str, nonce: &str, now_secs: i64) -> Result<Who, String> {
let parts: Vec<&str> = token.split('.').collect();
if parts.len() != 3 {
return Err("身分憑證的格式不對".into());
}
let header: Value = serde_json::from_slice(&b64url(parts[0])?).map_err(|_| "身分憑證的格式不對")?;
if header["alg"] != "RS256" {
return Err(format!("身分憑證的簽章方式不是 RS256({}),沒有採用", header["alg"]));
}
let kid = header["kid"].as_str();
let keys: Vec<&Value> = jwks["keys"].as_array().into_iter().flatten().filter(|k| k["kty"] == "RSA" && (kid.is_none() || k["kid"].as_str() == kid)).collect();
if keys.is_empty() {
return Err("找不到簽這個身分憑證的金鑰,沒有採用".into());
}
let signed = format!("{}.{}", parts[0], parts[1]);
let sig = b64url(parts[2])?;
let ok = keys.iter().any(|k| {
let (Some(n), Some(e)) = (k["n"].as_str().and_then(|n| b64url(n).ok()), k["e"].as_str().and_then(|e| b64url(e).ok())) else { return false };
ring::signature::RsaPublicKeyComponents { n: &n, e: &e }.verify(&ring::signature::RSA_PKCS1_2048_8192_SHA256, signed.as_bytes(), &sig).is_ok()
});
if !ok {
return Err("身分憑證的簽章對不上,沒有採用".into());
}
let c: Value = serde_json::from_slice(&b64url(parts[1])?).map_err(|_| "身分憑證的格式不對")?;
if c["iss"].as_str().map(|s| s.trim_end_matches('/')) != Some(ISSUER) {
return Err("身分憑證不是 OpenAI 發的,沒有採用".into());
}
let aud_ok = match &c["aud"] {
Value::String(s) => s == client_id,
Value::Array(a) => a.iter().any(|x| x == client_id),
_ => false,
};
if !aud_ok {
return Err("身分憑證不是給這個 AnyBot 的,沒有採用".into());
}
// (A minute of clock difference allowed.)
if c["exp"].as_i64().is_none_or(|e| e + 60 < now_secs) {
return Err("身分憑證已經過期,重新登入一次".into());
}
if c["nonce"].as_str() != Some(nonce) {
return Err("身分憑證不是這次登入的,沒有採用".into());
}
let sub = c["sub"].as_str().unwrap_or("").to_string();
if sub.is_empty() {
return Err("身分憑證裡沒有帳號,沒有採用".into());
}
Ok(Who { sub, email: c["email"].as_str().unwrap_or("").to_string() })
}
// ---------- tokens for requests ----------
/// Why there is no token: the words, and whether trying again later may help (a network
/// hiccup) or the person has to do something (sign in again).
#[derive(Debug, Clone, PartialEq)]
pub struct NoToken {
pub msg: String,
pub retry: bool,
}
impl NoToken {
fn needs_person(msg: &str) -> NoToken {
NoToken { msg: msg.into(), retry: false }
}
}
fn renewing() -> &'static Mutex<()> {
static R: OnceLock<Mutex<()>> = OnceLock::new();
R.get_or_init(|| Mutex::new(()))
}
/// The access token to send, renewed first when it is about to end.
pub fn fresh_token() -> Result<String, NoToken> {
let a = account();
if !a.signed_in() {
return Err(NoToken::needs_person(NEED_LOGIN));
}
if !a.plan_ok() {
return Err(NoToken::needs_person(NO_PLAN));
}
if !a.near_end() {
return Ok(a.access);
}
match renew_after(&a.access) {
Ok(t) => Ok(t),
// (Renewed early, and it didn't work this time: the token in hand still has minutes left.)
Err(e) if e.retry && a.expires_at > crate::model::now_ms() + 30_000 && account().access == a.access => Ok(a.access),
Err(e) => Err(e),
}
feat: ChatGPT 方案——用 ChatGPT 帳號登入,Bot 用你 ChatGPT 方案的額度,不用 API 金鑰 - 新供應商「ChatGPT 方案」(src/chatgpt.rs):照 OpenAI 給開源 App 的 Sign in with ChatGPT。 第一次登入註冊 AnyBot(dynamic_agent_client → oaiapp_…)並重用;PKCE、state、nonce; ID token 驗 RS256 簽章、iss、aud、exp、nonce;沒同意使用方案算登入但不能用(再登入會要求同意)。 - 要求走 Responses API(api.openai.com/v1/responses,store:false、stream:true、instructions), token 只送 OpenAI 自己的網址;收到 response.completed 才算完成;額度用完停下來給管理用量連結, 不重試、不改用 API 金鑰。token 快到期或 401 時更新(一次一個,refresh token 會輪替)。 - 設定 › 模型 › ChatGPT 方案:使用 ChatGPT 繼續、登出、換帳號、打開登入頁、管理用量; 連到伺服器大腦的螢幕電腦和手機也能登入(登入頁開在自己這台,打不開的那頁網址貼回給大腦)。 - Bot 工具 chatgpt_login(status、login、logout、switch_account;登出和換帳號先問)。 - 修連接器登入:封存的 token 前綴寫錯("sealed:" 實際是 "enc:v1:"),重開 App 後 token 沒解開就被當成憑證送出,登入等於每次重開都失效。 已驗證: cargo test 全綠(chatgpt::、providers::、appctl::、remote::、mcp_oauth::、featuremap::、layout_audit::); 授權網址的參數送到 auth.openai.com 沒被拒(302 到登入頁)。 未驗證: 實際用 ChatGPT 帳號登入、同意、Responses 串流與工具呼叫(要真的 ChatGPT 付費帳號和瀏覽器); 螢幕電腦貼回網址、手機登入(要實機);Windows 的「打開登入頁」。 動到審批路徑(appctl::needs_approval 的 chatgpt_login):需要實機測試+人類簽名。 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 09:23:10 +00:00
}
/// A new access token, because `stale` ended or was refused. One renewal at a time (the refresh
/// token rotates: two at once would spend it twice); one that another already did is used.
pub fn renew_after(stale: &str) -> Result<String, NoToken> {
let _g = renewing().lock().unwrap_or_else(|e| e.into_inner());
let a = account();
if !a.signed_in() || a.refresh.is_empty() {
return Err(NoToken::needs_person(NEED_LOGIN));
}
if a.access != stale && !a.near_end() {
return Ok(a.access);
}
let (status, v) = post_form(
&format!("{}/api/accounts/oauth/token", auth_base()),
&[("grant_type", "refresh_token".into()), ("client_id", a.client_id.clone()), ("refresh_token", a.refresh.clone()), ("resource", API_BASE.into())],
)
.map_err(|msg| NoToken { msg, retry: true })?;
let access = v["access_token"].as_str().unwrap_or("").to_string();
if (200..300).contains(&status) && !access.is_empty() {
let now = crate::model::now_ms();
let mut moved = false;
let fresh = update(|x| {
// (Signed out, or signed in anew, while this was on its way: that stands.)
if x.refresh != a.refresh || x.client_id != a.client_id {
moved = true;
return;
}
x.access = access.clone();
// (It rotates: the new one replaces the old, together with the access token.)
if let Some(r) = v["refresh_token"].as_str().filter(|r| !r.is_empty()) {
x.refresh = r.to_string();
}
x.expires_at = v["expires_in"].as_i64().map(|s| now + s * 1000).unwrap_or(0);
if let Some(s) = v["scope"].as_str() {
x.scopes = s.split_whitespace().map(String::from).collect();
}
if let Some(t) = v["id_token"].as_str().filter(|t| !t.is_empty()) {
x.id_token = t.to_string();
}
})
.map_err(|msg| NoToken { msg, retry: true })?;
if moved {
return if fresh.signed_in() && fresh.plan_ok() { Ok(fresh.access) } else { Err(NoToken::needs_person(NEED_LOGIN)) };
}
if !fresh.plan_ok() {
return Err(NoToken::needs_person(NO_PLAN));
}
return Ok(access);
}
let code = err_code(&v);
const SPENT: [&str; 6] = ["invalid_grant", "invalid_refresh_token", "token_expired", "refresh_token_expired", "refresh_token_invalidated", "refresh_token_reused"];
if SPENT.contains(&code) {
// The refresh token can't be used any more: those tokens go; signing in again reuses the registration.
let _ = update(|x| {
if x.refresh == a.refresh {
*x = x.without_tokens();
}
});
return Err(NoToken::needs_person(EXPIRED));
}
if code == "invalid_client" {
return Err(NoToken::needs_person("OpenAI 不認得這個 AnyBot 的註冊了。請在「設定 › 模型 › ChatGPT 方案」按「換帳號」,再登入一次。"));
}
// A hiccup (a 5xx, the network): the tokens stay; try again later.
Err(NoToken { msg: format!("沒辦法更新 ChatGPT 的登入(HTTP {status}):{}", oauth_error(&v)), retry: status >= 500 || status == 429 })
}
/// Sign out: AnyBot's access is revoked at OpenAI and the tokens go (the registration stays, so
/// signing in again doesn't register again). `forget`: the registration goes too (換帳號).
pub fn logout(forget: bool) -> Result<String, String> {
// (After a renewal on its way, so it doesn't sign back in.)
let _g = renewing().lock().unwrap_or_else(|e| e.into_inner());
let a = account();
let mut said = String::new();
if a.refresh.starts_with(crate::vault_store::SEALED) {
said = "(這台電腦現在打不開存著的憑證,沒辦法到 OpenAI 撤銷:請到 ChatGPT 設定裡中斷 AnyBot 的連線)".into();
} else if !a.refresh.is_empty() {
// (Revoked twice at most over a network hiccup, a moment apart; signed out here either way.)
feat: ChatGPT 方案——用 ChatGPT 帳號登入,Bot 用你 ChatGPT 方案的額度,不用 API 金鑰 - 新供應商「ChatGPT 方案」(src/chatgpt.rs):照 OpenAI 給開源 App 的 Sign in with ChatGPT。 第一次登入註冊 AnyBot(dynamic_agent_client → oaiapp_…)並重用;PKCE、state、nonce; ID token 驗 RS256 簽章、iss、aud、exp、nonce;沒同意使用方案算登入但不能用(再登入會要求同意)。 - 要求走 Responses API(api.openai.com/v1/responses,store:false、stream:true、instructions), token 只送 OpenAI 自己的網址;收到 response.completed 才算完成;額度用完停下來給管理用量連結, 不重試、不改用 API 金鑰。token 快到期或 401 時更新(一次一個,refresh token 會輪替)。 - 設定 › 模型 › ChatGPT 方案:使用 ChatGPT 繼續、登出、換帳號、打開登入頁、管理用量; 連到伺服器大腦的螢幕電腦和手機也能登入(登入頁開在自己這台,打不開的那頁網址貼回給大腦)。 - Bot 工具 chatgpt_login(status、login、logout、switch_account;登出和換帳號先問)。 - 修連接器登入:封存的 token 前綴寫錯("sealed:" 實際是 "enc:v1:"),重開 App 後 token 沒解開就被當成憑證送出,登入等於每次重開都失效。 已驗證: cargo test 全綠(chatgpt::、providers::、appctl::、remote::、mcp_oauth::、featuremap::、layout_audit::); 授權網址的參數送到 auth.openai.com 沒被拒(302 到登入頁)。 未驗證: 實際用 ChatGPT 帳號登入、同意、Responses 串流與工具呼叫(要真的 ChatGPT 付費帳號和瀏覽器); 螢幕電腦貼回網址、手機登入(要實機);Windows 的「打開登入頁」。 動到審批路徑(appctl::needs_approval 的 chatgpt_login):需要實機測試+人類簽名。 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 09:23:10 +00:00
let mut revoked = false;
for i in 0..2 {
if i > 0 {
std::thread::sleep(Duration::from_secs(1));
}
feat: ChatGPT 方案——用 ChatGPT 帳號登入,Bot 用你 ChatGPT 方案的額度,不用 API 金鑰 - 新供應商「ChatGPT 方案」(src/chatgpt.rs):照 OpenAI 給開源 App 的 Sign in with ChatGPT。 第一次登入註冊 AnyBot(dynamic_agent_client → oaiapp_…)並重用;PKCE、state、nonce; ID token 驗 RS256 簽章、iss、aud、exp、nonce;沒同意使用方案算登入但不能用(再登入會要求同意)。 - 要求走 Responses API(api.openai.com/v1/responses,store:false、stream:true、instructions), token 只送 OpenAI 自己的網址;收到 response.completed 才算完成;額度用完停下來給管理用量連結, 不重試、不改用 API 金鑰。token 快到期或 401 時更新(一次一個,refresh token 會輪替)。 - 設定 › 模型 › ChatGPT 方案:使用 ChatGPT 繼續、登出、換帳號、打開登入頁、管理用量; 連到伺服器大腦的螢幕電腦和手機也能登入(登入頁開在自己這台,打不開的那頁網址貼回給大腦)。 - Bot 工具 chatgpt_login(status、login、logout、switch_account;登出和換帳號先問)。 - 修連接器登入:封存的 token 前綴寫錯("sealed:" 實際是 "enc:v1:"),重開 App 後 token 沒解開就被當成憑證送出,登入等於每次重開都失效。 已驗證: cargo test 全綠(chatgpt::、providers::、appctl::、remote::、mcp_oauth::、featuremap::、layout_audit::); 授權網址的參數送到 auth.openai.com 沒被拒(302 到登入頁)。 未驗證: 實際用 ChatGPT 帳號登入、同意、Responses 串流與工具呼叫(要真的 ChatGPT 付費帳號和瀏覽器); 螢幕電腦貼回網址、手機登入(要實機);Windows 的「打開登入頁」。 動到審批路徑(appctl::needs_approval 的 chatgpt_login):需要實機測試+人類簽名。 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 09:23:10 +00:00
match post_form(&format!("{}/api/accounts/oauth/revoke", auth_base()), &[("token", a.refresh.clone()), ("token_type_hint", "refresh_token".into()), ("client_id", a.client_id.clone())]) {
Ok((s, _)) if (200..300).contains(&s) => {
revoked = true;
break;
}
Ok((s, _)) if s < 500 => break,
_ => {}
}
}
if !revoked {
said = "(OpenAI 那邊沒有確認撤銷;可以到 ChatGPT 設定裡中斷 AnyBot 的連線)".into();
}
}
update(|x| {
*x = if forget { Account { host_id: x.host_id.clone(), ..Default::default() } } else { x.without_tokens() };
})?;
Ok(format!("已登出 ChatGPT{}。{said}", if forget { ",也忘了這個帳號的註冊(下次登入可以換帳號)" } else { "" }))
}
/// The first sign-in with the plan: the welcome, once (None after).
pub fn welcome_once() -> Option<String> {
let a = account();
if a.welcomed || !a.signed_in() || !a.plan_ok() {
return None;
}
let _ = update(|x| x.welcomed = true);
Some(format!("你正在使用你的 ChatGPT 方案:Bot 選「ChatGPT 方案」時,它的 AI 要求會用你 ChatGPT 方案的額度(不是 API 金鑰,不另外計費)。用量可以在 ChatGPT 設定管理:{USAGE_URL}"))
}
/// How it stands, in words (the tool, the settings).
pub fn status_text() -> String {
let a = account();
match (a.signed_in(), a.plan_ok()) {
(true, true) => format!("已用 ChatGPT 登入({}),Bot 可以用你的 ChatGPT 方案。管理用量:{USAGE_URL}", if a.email.is_empty() { "帳號" } else { &a.email }),
(true, false) => NO_PLAN.into(),
_ if !a.email.is_empty() => format!("目前沒有登入(上次是 {})。", a.email),
_ => "還沒有用 ChatGPT 登入。".into(),
}
}
// ---------- a screen or the phone of this brain ----------
/// A screen of this brain (設定 › 模型 on a computer connected to it) or the owner's phone asks:
/// the tool's actions, done here where the account is, and how it stands after. `login` without
/// a callback gives the sign-in page as `url` (the browser on their side opens it; the page it
/// comes back to won't load there, and they paste its address back: `login` with `callback`).
pub fn for_screen(v: &Value) -> Value {
let action = v["action"].as_str().unwrap_or("status");
let callback = v["callback"].as_str().map(str::trim).filter(|c| !c.is_empty());
let (text, ok, url) = match (action, callback) {
("login", None) => match start() {
Ok(u) => (String::new(), true, Some(u)),
Err(e) => (e, false, None),
},
_ => {
let (t, ok) = run_tool(&json!({"action": action, "callback": callback}).to_string());
(t, ok, None)
}
};
let mut v = view();
v["ok"] = json!(ok);
v["text"] = json!(text);
v["url"] = json!(url);
v
}
/// How the account stands, for a screen or the phone (never a token).
pub fn view() -> Value {
feat: ChatGPT 方案——用 ChatGPT 帳號登入,Bot 用你 ChatGPT 方案的額度,不用 API 金鑰 - 新供應商「ChatGPT 方案」(src/chatgpt.rs):照 OpenAI 給開源 App 的 Sign in with ChatGPT。 第一次登入註冊 AnyBot(dynamic_agent_client → oaiapp_…)並重用;PKCE、state、nonce; ID token 驗 RS256 簽章、iss、aud、exp、nonce;沒同意使用方案算登入但不能用(再登入會要求同意)。 - 要求走 Responses API(api.openai.com/v1/responses,store:false、stream:true、instructions), token 只送 OpenAI 自己的網址;收到 response.completed 才算完成;額度用完停下來給管理用量連結, 不重試、不改用 API 金鑰。token 快到期或 401 時更新(一次一個,refresh token 會輪替)。 - 設定 › 模型 › ChatGPT 方案:使用 ChatGPT 繼續、登出、換帳號、打開登入頁、管理用量; 連到伺服器大腦的螢幕電腦和手機也能登入(登入頁開在自己這台,打不開的那頁網址貼回給大腦)。 - Bot 工具 chatgpt_login(status、login、logout、switch_account;登出和換帳號先問)。 - 修連接器登入:封存的 token 前綴寫錯("sealed:" 實際是 "enc:v1:"),重開 App 後 token 沒解開就被當成憑證送出,登入等於每次重開都失效。 已驗證: cargo test 全綠(chatgpt::、providers::、appctl::、remote::、mcp_oauth::、featuremap::、layout_audit::); 授權網址的參數送到 auth.openai.com 沒被拒(302 到登入頁)。 未驗證: 實際用 ChatGPT 帳號登入、同意、Responses 串流與工具呼叫(要真的 ChatGPT 付費帳號和瀏覽器); 螢幕電腦貼回網址、手機登入(要實機);Windows 的「打開登入頁」。 動到審批路徑(appctl::needs_approval 的 chatgpt_login):需要實機測試+人類簽名。 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 09:23:10 +00:00
let a = account();
json!({"signed_in": a.signed_in(), "plan_ok": a.plan_ok(), "email": a.email, "registered": !a.client_id.is_empty(), "status": status_text(), "limited": limited()})
}
/// 已達用量上限: the plan said its usage is used up. Requests nobody is watching (a routine, a
/// channel's message, a check) aren't sent on the plan until one goes through again; a turn
/// the person is watching still tries (they chose to ask).
static LIMITED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
pub fn limited() -> bool {
LIMITED.load(std::sync::atomic::Ordering::Relaxed)
}
pub fn set_limited(on: bool) {
LIMITED.store(on, std::sync::atomic::Ordering::Relaxed);
}
/// Only OpenAI's own sign-in page is opened from what a brain sends (a screen opens it in a browser).
pub fn is_sign_in_page(url: &str) -> bool {
url.starts_with("https://auth.openai.com/")
feat: ChatGPT 方案——用 ChatGPT 帳號登入,Bot 用你 ChatGPT 方案的額度,不用 API 金鑰 - 新供應商「ChatGPT 方案」(src/chatgpt.rs):照 OpenAI 給開源 App 的 Sign in with ChatGPT。 第一次登入註冊 AnyBot(dynamic_agent_client → oaiapp_…)並重用;PKCE、state、nonce; ID token 驗 RS256 簽章、iss、aud、exp、nonce;沒同意使用方案算登入但不能用(再登入會要求同意)。 - 要求走 Responses API(api.openai.com/v1/responses,store:false、stream:true、instructions), token 只送 OpenAI 自己的網址;收到 response.completed 才算完成;額度用完停下來給管理用量連結, 不重試、不改用 API 金鑰。token 快到期或 401 時更新(一次一個,refresh token 會輪替)。 - 設定 › 模型 › ChatGPT 方案:使用 ChatGPT 繼續、登出、換帳號、打開登入頁、管理用量; 連到伺服器大腦的螢幕電腦和手機也能登入(登入頁開在自己這台,打不開的那頁網址貼回給大腦)。 - Bot 工具 chatgpt_login(status、login、logout、switch_account;登出和換帳號先問)。 - 修連接器登入:封存的 token 前綴寫錯("sealed:" 實際是 "enc:v1:"),重開 App 後 token 沒解開就被當成憑證送出,登入等於每次重開都失效。 已驗證: cargo test 全綠(chatgpt::、providers::、appctl::、remote::、mcp_oauth::、featuremap::、layout_audit::); 授權網址的參數送到 auth.openai.com 沒被拒(302 到登入頁)。 未驗證: 實際用 ChatGPT 帳號登入、同意、Responses 串流與工具呼叫(要真的 ChatGPT 付費帳號和瀏覽器); 螢幕電腦貼回網址、手機登入(要實機);Windows 的「打開登入頁」。 動到審批路徑(appctl::needs_approval 的 chatgpt_login):需要實機測試+人類簽名。 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 09:23:10 +00:00
}
/// On a screen: how the brain's account stands, as it last said (None: not asked yet).
fn brain_cell() -> &'static Mutex<Option<(Instant, Value)>> {
static B: OnceLock<Mutex<Option<(Instant, Value)>>> = OnceLock::new();
B.get_or_init(Default::default)
}
pub fn brain_view() -> Option<Value> {
brain_cell().lock().unwrap_or_else(|e| e.into_inner()).as_ref().map(|(_, v)| v.clone())
}
/// (The sign-in page the brain gave stays until the account is usable: a later "how it stands"
/// answer doesn't carry it.)
pub fn set_brain_view(mut v: Value) {
let mut c = brain_cell().lock().unwrap_or_else(|e| e.into_inner());
let usable = v["signed_in"] == true && v["plan_ok"] == true;
if v["url"].is_null() && !usable {
if let Some((_, old)) = c.as_ref() {
v["url"] = old["url"].clone();
}
}
*c = Some((Instant::now(), v));
}
/// The brain's view is old enough to ask again (or was never asked).
pub fn brain_view_stale(secs: u64) -> bool {
brain_cell().lock().unwrap_or_else(|e| e.into_inner()).as_ref().is_none_or(|(t, _)| t.elapsed().as_secs() >= secs)
}
/// The plan can be used: signed in here, or (on a screen) on the brain, with the plan allowed.
pub fn usable() -> bool {
!stored_token().is_empty() || brain_view().is_some_and(|v| v["signed_in"] == true && v["plan_ok"] == true)
}
// ---------- the bot's tool ----------
pub fn spec() -> Value {
json!({"name": TOOL, "description": "The ChatGPT plan provider (「ChatGPT 方案」): bots run on the person's ChatGPT plan (Plus, Pro, Business…) instead of an OpenAI API key. action=status: signed in or not, as whom. action=login: an address for the person to sign in with (open it with open_for_person or give it to them); it finishes by itself within 10 minutes. If the page it comes back to can't load (their browser is on another computer), ask them to copy that page's whole address and call again with callback=that address. action=logout: sign out (AnyBot's access is revoked). action=switch_account: sign out and forget this account's registration, to sign in with another ChatGPT account. A bot uses the plan once its provider is ChatGPT 方案 (update_my_profile provider=chatgpt).",
"parameters": {"type": "object", "properties": {
"action": {"type": "string", "enum": ["status", "login", "logout", "switch_account"]},
"callback": {"type": "string", "description": "login only: the whole address the browser came back to (http://127.0.0.1:…/auth/callback?code=…)."}
}, "required": ["action"]}})
}
/// Run the tool (over the network: off the window's thread). (text, ok)
pub fn run_tool(args: &str) -> (String, bool) {
let v: Value = serde_json::from_str(args).unwrap_or(json!({}));
let r = match v["action"].as_str().unwrap_or("") {
"status" => Ok(status_text()),
"login" => match v["callback"].as_str().map(str::trim).filter(|c| !c.is_empty()) {
Some(cb) => finish_from_url(cb).map(|who| {
let welcome = welcome_once().map(|w| format!("\n請轉告使用者:{w}")).unwrap_or_default();
format!("已用 ChatGPT({who})登入。Bot 的供應商選「ChatGPT 方案」就會用你的方案。{welcome}")
}),
None => start().map(|u| {
format!("請使用者打開這個網址,用 ChatGPT 帳號登入並同意讓 AnyBot 使用方案(用 open_for_person 開在他正在用的電腦上,或把網址給他):\n{u}\n登入好了 AnyBot 會自己接上(最多等 10 分鐘)。如果登入後那一頁打不開(他的瀏覽器在別台電腦),請他把那一頁的網址整個複製給你,再用 {TOOL}(action=login、callback=那個網址)。")
}),
},
"logout" => logout(false),
"switch_account" => logout(true),
other => Err(format!("{TOOL} 的 action 要是 status、login、logout 或 switch_account(收到「{other}」)。")),
};
match r {
Ok(t) => (t, true),
Err(e) => (e, false),
}
}
/// What the call does, in a line (the step, the approval card).
fix: 十一個小錯——瀏覽器設定檔換得了、支線改不了設定、直接連線的拒絕照實說、手機的標籤和設定頁照實寫 1. 瀏覽器設定檔只能列出:browser 的 action 就是 profiles,裡面的 list/add/use 傳不到 browser_profiles,帶 name 也只列出。現在帶 name 就換到那個設定檔、還沒有就先新增 (profiles_tool 自己判斷,工具定義不變);步驟寫「切換到「…」」。 2. 支線改得了設定:支線的 update_bot 按允許後把主 Bot 改名。update_bot、update_settings、 update_my_profile、teach_skill,和新增/修改/移除連接器或 hook,在支線一律馬上回 「支線改不了設定:回到主線再請它改。」,不跳卡片;ChatGPT 登入登出照樣跳卡。 3. 直接連線的拒絕說「區網連線(沒有加密)」:直接連線是 https,擋的原因是只憑手機密碼。 改成「這會放寬 Bot 能做的事:同一個網路直接連的裝置只能收緊、不能放寬…」;能力、可以 用的電腦只有勾回才擋(勾掉以前也被擋)。 4. 本機網址的卡寫「(在 上)」:Bot 的電腦都開不了瀏覽器時,寫「(在 執行 AnyBot 的這台 電腦 上)」。 5. 手機把監看叫醒的訊息標「例行任務」:照電腦版的標籤表(目標、例行任務、觸發、訊息管道、 來自其他 Bot),加上「監看」;測試確認手機和電腦用同一張表。 6. 步驟名字:replay_skill 寫「重播技能 「記一筆」」(以前「工具 工作資料夾」);例行任務的 送出證據寫「傳訊息給其他 Bot 給 同事:早安」(以前「message_bot 工作資料夾」);只有 檔案步驟會寫資料夾。 7. 執行步驟用的模型的卡寫「自動 → 不分開」(以前「(空) → 「off」」)。 8. ChatGPT 的卡照要做的事寫標題:「…想要登出 ChatGPT 方案」「…想要換 ChatGPT 帳號」 (以前「想要ChatGPT 方案登入」),手機和電腦都是。 9. 正常關掉 AnyBot 時,沒做完的支線寫「AnyBot 關掉了,這條支線停了」(以前「被停止了」, 像使用者按了停止);還在等主線的也一起照實寫。 10. 手機的設定頁只讀一次:狀態版本一變就重讀開著的設定頁,其他頁下次打開重讀(/always-approve 填了預設規則,權限頁不用重新整理)。 11. 沒有 Docker 時手機的電腦頁寫「已是 v14」「這台 Docker 主機沒有 gVisor」:問不到的事送 null,頁面寫「沒有 Docker,現在沒有這台電腦」,不說有沒有 gVisor。 功能地圖:browser、branch、profile、autonomy、models、market、phone、files、replay、 routines、box 的子功能、Bot 那一行、步驟和看到的結果照新行為改;拿掉只在描述錯誤的陷阱 (autonomy 的設定頁不更新、box 的已是 v14)。FEATURES.md 同步。verify-approval-routing: approval_json、approval_body 只改了標題的字,模型的假設不變,rehash coverage.tsv(這個 commit 是新的同步 commit)。 找到但沒修:browser 的 tabs 也一樣,裡面的 switch/new/close 傳不到 browser_tabs(工具 說明本身就叫模型用 action 帶),要改工具定義才修得好。 已驗證: env -u 金鑰… DOCKER_HOST=unix:///nonexistent cargo test(676 過、46 ignored)、 cargo clippy --bin anybot --all-targets -D warnings、sh deploy/ci/lint-sh.sh、 verify-approval-routing run.sh --replay(10 個重走都過);新測試先在拿掉修正的程式上跑過、 11 個都失敗;verify-anybot 照地圖跑 box、browser、models、files、replay、routines、branch、 autonomy、profile、phone、market 的步驟,全部通過(證據在 target/verify-anybot/)。 未驗證: --ignored 的實機瀏覽器測試(botbrowser 的 reads_a_real_page、a_persons_firefox_profile、 a_finished_job_quits_its_firefox、a_finished_job_quits_its_chrome,browser 的 lines_go_in_whole_and_numbers_stay_put、a_send_is_seen_with_the_post_it_answers_and_its_own_address) 會開真的瀏覽器,要人在實機跑、簽名;本機網址的卡按「允許」(會開真的瀏覽器);電腦版視窗 上的卡片標題和支線卡(要開視窗);帳號連線的手機(要帳號伺服器)。 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Uirha5sXAsDLzxz6UZJgoC
2026-11-18 09:44:16 +00:00
/// What a call does, as the title of its card: 「…想要登出 ChatGPT 方案」 (the tool's own name,
/// 「ChatGPT 方案登入」, made a logout's card read 「…想要ChatGPT 方案登入」).
pub fn ask_label(args: &str) -> &'static str {
let v: Value = serde_json::from_str(args).unwrap_or(json!({}));
match v["action"].as_str().unwrap_or("") {
"login" => "登入 ChatGPT 方案",
"logout" => "登出 ChatGPT 方案",
"switch_account" => "換 ChatGPT 帳號",
_ => "查看 ChatGPT 方案",
}
}
feat: ChatGPT 方案——用 ChatGPT 帳號登入,Bot 用你 ChatGPT 方案的額度,不用 API 金鑰 - 新供應商「ChatGPT 方案」(src/chatgpt.rs):照 OpenAI 給開源 App 的 Sign in with ChatGPT。 第一次登入註冊 AnyBot(dynamic_agent_client → oaiapp_…)並重用;PKCE、state、nonce; ID token 驗 RS256 簽章、iss、aud、exp、nonce;沒同意使用方案算登入但不能用(再登入會要求同意)。 - 要求走 Responses API(api.openai.com/v1/responses,store:false、stream:true、instructions), token 只送 OpenAI 自己的網址;收到 response.completed 才算完成;額度用完停下來給管理用量連結, 不重試、不改用 API 金鑰。token 快到期或 401 時更新(一次一個,refresh token 會輪替)。 - 設定 › 模型 › ChatGPT 方案:使用 ChatGPT 繼續、登出、換帳號、打開登入頁、管理用量; 連到伺服器大腦的螢幕電腦和手機也能登入(登入頁開在自己這台,打不開的那頁網址貼回給大腦)。 - Bot 工具 chatgpt_login(status、login、logout、switch_account;登出和換帳號先問)。 - 修連接器登入:封存的 token 前綴寫錯("sealed:" 實際是 "enc:v1:"),重開 App 後 token 沒解開就被當成憑證送出,登入等於每次重開都失效。 已驗證: cargo test 全綠(chatgpt::、providers::、appctl::、remote::、mcp_oauth::、featuremap::、layout_audit::); 授權網址的參數送到 auth.openai.com 沒被拒(302 到登入頁)。 未驗證: 實際用 ChatGPT 帳號登入、同意、Responses 串流與工具呼叫(要真的 ChatGPT 付費帳號和瀏覽器); 螢幕電腦貼回網址、手機登入(要實機);Windows 的「打開登入頁」。 動到審批路徑(appctl::needs_approval 的 chatgpt_login):需要實機測試+人類簽名。 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 09:23:10 +00:00
pub fn describe(args: &str) -> String {
let v: Value = serde_json::from_str(args).unwrap_or(json!({}));
match v["action"].as_str().unwrap_or("") {
"login" if v["callback"].as_str().is_some_and(|c| !c.trim().is_empty()) => "完成登入".into(),
"login" => "登入".into(),
"logout" => "登出".into(),
"switch_account" => "換帳號".into(),
_ => "查看狀態".into(),
}
}
#[cfg(test)]
pub mod tests {
use super::*;
use std::io::Read;
/// A test RSA key (2048-bit, PKCS#8 DER, base64) — made for these tests only.
const TEST_KEY: &str = include_str!("chatgpt_test_key.b64");
pub fn key() -> ring::signature::RsaKeyPair {
use base64::Engine;
let der = base64::engine::general_purpose::STANDARD.decode(TEST_KEY.split_whitespace().collect::<String>()).unwrap();
ring::signature::RsaKeyPair::from_pkcs8(&der).unwrap()
}
pub fn jwks() -> Value {
use base64::Engine;
use ring::signature::KeyPair;
let k = key();
// The public key is DER: SEQUENCE { INTEGER n, INTEGER e }.
let der = k.public_key().as_ref().to_vec();
let mut at = 0;
let mut item = |want: u8| -> Vec<u8> {
assert_eq!(der[at], want);
at += 1;
let mut len = der[at] as usize;
at += 1;
if len & 0x80 != 0 {
let n = len & 0x7f;
len = der[at..at + n].iter().fold(0, |a, b| a * 256 + *b as usize);
at += n;
}
let v = if want == 0x30 { vec![] } else { der[at..at + len].to_vec() };
if want != 0x30 {
at += len;
}
v
};
item(0x30);
let (n, e) = (item(0x02), item(0x02));
let trim = |v: Vec<u8>| v.into_iter().skip_while(|b| *b == 0).collect::<Vec<u8>>();
let b = |x: &[u8]| base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(x);
json!({"keys": [{"kty": "RSA", "kid": "k1", "alg": "RS256", "n": b(&trim(n)), "e": b(&trim(e))}]})
}
pub fn id_token(claims: &Value) -> String {
use base64::Engine;
let b = |x: &[u8]| base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(x);
let signed = format!("{}.{}", b(json!({"alg": "RS256", "kid": "k1", "typ": "JWT"}).to_string().as_bytes()), b(claims.to_string().as_bytes()));
let k = key();
let mut sig = vec![0u8; k.public().modulus_len()];
k.sign(&ring::signature::RSA_PKCS1_SHA256, &ring::rand::SystemRandom::new(), signed.as_bytes(), &mut sig).unwrap();
format!("{signed}.{}", b(&sig))
}
fn claims(aud: &str, nonce: &str, exp: i64) -> Value {
json!({"iss": ISSUER, "aud": aud, "sub": "user-1", "email": "a@example.com", "nonce": nonce, "exp": exp, "iat": exp - 3600})
}
#[test]
fn an_id_token_is_taken_only_when_everything_checks_out() {
let now = 1_900_000_000;
let ok = id_token(&claims("oaiapp_1", "n1", now + 600));
assert_eq!(verify_id_token(&ok, &jwks(), "oaiapp_1", "n1", now).unwrap(), Who { sub: "user-1".into(), email: "a@example.com".into() });
// Another client, another sign-in, ended, not OpenAI's.
assert!(verify_id_token(&ok, &jwks(), "oaiapp_2", "n1", now).unwrap_err().contains("不是給這個"));
assert!(verify_id_token(&ok, &jwks(), "oaiapp_1", "n2", now).unwrap_err().contains("不是這次登入"));
assert!(verify_id_token(&ok, &jwks(), "oaiapp_1", "n1", now + 3600).unwrap_err().contains("過期"));
let mut other = claims("oaiapp_1", "n1", now + 600);
other["iss"] = json!("https://evil.example");
assert!(verify_id_token(&id_token(&other), &jwks(), "oaiapp_1", "n1", now).unwrap_err().contains("不是 OpenAI"));
// A token changed after signing: the signature no longer matches.
let parts: Vec<&str> = ok.split('.').collect();
use base64::Engine;
let forged = base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(claims("oaiapp_1", "n1", now + 99_999).to_string());
assert!(verify_id_token(&format!("{}.{forged}.{}", parts[0], parts[2]), &jwks(), "oaiapp_1", "n1", now).unwrap_err().contains("簽章"));
// Not signed at all.
let none = format!("{}.{}.", base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(r#"{"alg":"none"}"#), parts[1]);
assert!(verify_id_token(&none, &jwks(), "oaiapp_1", "n1", now).is_err());
}
#[test]
fn the_first_sign_in_registers_and_later_ones_reuse_the_client_id() {
let (first, c) = authorize_url(&Account::default(), "urn:uuid:h", "http://127.0.0.1:1455/auth/callback", "s", "n", "v");
assert_eq!(c, FIRST_CLIENT);
assert!(first.starts_with("https://auth.openai.com/api/accounts/authorize?client_id=dynamic_agent_client&agent_name_hint=AnyBot&"), "{first}");
for part in ["ext_agent_host_id=urn%3Auuid%3Ah", "redirect_uri=http%3A%2F%2F127.0.0.1%3A1455%2Fauth%2Fcallback", "scope=openid%20profile%20email%20offline_access%20resource.invoke%20chatgpt.tokens.use.direct", "resource=https%3A%2F%2Fapi.openai.com%2Fv1", "code_challenge_method=S256", "nonce=n", "state=s"] {
assert!(first.contains(part), "{part} missing: {first}");
}
let known = Account { client_id: "oaiapp_9".into(), email: "a@example.com".into(), ..Default::default() };
let (again, c) = authorize_url(&known, "urn:uuid:h", "http://127.0.0.1:5000/auth/callback", "s", "n", "v");
assert_eq!(c, "oaiapp_9");
assert!(again.contains("client_id=oaiapp_9") && !again.contains("agent_name_hint") && again.contains("login_hint=a%40example.com"), "{again}");
}
#[test]
fn a_host_id_is_an_opaque_uuid_made_once() {
let dir = std::env::temp_dir().join(format!("anybot-chatgpt-host-{}", crate::httpd::random_hex(6)));
TEST_FILE.with(|t| *t.borrow_mut() = Some(dir.join("chatgpt.json")));
let h = host_id().unwrap();
assert!(h.starts_with("urn:uuid:") && h.len() == "urn:uuid:".len() + 36 && h.chars().nth(23) == Some('4'), "{h}");
assert_eq!(host_id().unwrap(), h);
// Signing out, even forgetting the registration, keeps it.
let _ = logout(true);
assert_eq!(account().host_id, h);
TEST_FILE.with(|t| *t.borrow_mut() = None);
let _ = std::fs::remove_dir_all(dir);
}
/// OpenAI's sign-in server, as far as AnyBot uses it: the token endpoint (codes, refresh
/// tokens), the keys, revocation.
pub struct FakeAuth {
pub url: String,
pub seen: std::sync::Arc<Mutex<Vec<String>>>,
}
impl FakeAuth {
/// `client`: the id it issues; `nonce`: what the ID token carries; `scope`: what it grants.
pub fn start(client: &str, nonce_of: std::sync::Arc<Mutex<String>>, scope: &str) -> FakeAuth {
let l = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
let url = format!("http://127.0.0.1:{}", l.local_addr().unwrap().port());
let seen: std::sync::Arc<Mutex<Vec<String>>> = Default::default();
let (client, scope, s2) = (client.to_string(), scope.to_string(), seen.clone());
let refreshes = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
std::thread::spawn(move || {
for s in l.incoming().flatten() {
let mut s = s;
let mut r = BufReader::new(s.try_clone().unwrap());
let mut line = String::new();
r.read_line(&mut line).unwrap();
let mut len = 0;
loop {
let mut h = String::new();
r.read_line(&mut h).unwrap();
if h.trim().is_empty() {
break;
}
if let Some(v) = h.to_lowercase().strip_prefix("content-length:") {
len = v.trim().parse().unwrap_or(0);
}
}
let mut body = vec![0; len];
r.read_exact(&mut body).unwrap();
let body = String::from_utf8_lossy(&body).to_string();
let path = line.split_whitespace().nth(1).unwrap_or("").to_string();
s2.lock().unwrap().push(format!("{path} {body}"));
let q = query_pairs(&body);
let answer = match path.as_str() {
"/.well-known/jwks.json" => jwks(),
"/api/accounts/oauth/revoke" => json!({}),
_ if q.get("grant_type").map(String::as_str) == Some("refresh_token") => {
let n = refreshes.fetch_add(1, std::sync::atomic::Ordering::SeqCst) + 1;
if let Some(spent) = q.get("refresh_token").filter(|r| r.starts_with("spent")) {
// (Flat, or nested as {"error":{"code":…}}.)
let b = if spent == "spent-nested" { json!({"error": {"code": "refresh_token_expired", "message": "expired"}}) } else { json!({"error": "refresh_token_reused"}) }.to_string();
let _ = s.write_all(format!("HTTP/1.1 400 Bad Request\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{b}", b.len()).as_bytes());
continue;
}
json!({"access_token": format!("access-{n}"), "refresh_token": format!("refresh-{n}"), "expires_in": 3600, "scope": scope})
}
_ => {
let now = crate::model::now_ms() / 1000;
let nonce = nonce_of.lock().unwrap().clone();
json!({"access_token": "access-0", "refresh_token": "refresh-0", "expires_in": 3600, "token_type": "Bearer", "scope": scope, "id_token": id_token(&json!({"iss": ISSUER, "aud": client, "sub": "user-1", "email": "a@example.com", "nonce": nonce, "exp": now + 600}))})
}
};
let b = answer.to_string();
let _ = s.write_all(format!("HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{b}", b.len()).as_bytes());
}
});
FakeAuth { url, seen }
}
}
/// Point this thread's sign-in at `auth` and its account file at a folder of its own.
pub fn use_test_place(auth: &str) -> std::path::PathBuf {
let dir = std::env::temp_dir().join(format!("anybot-chatgpt-{}", crate::httpd::random_hex(6)));
TEST_FILE.with(|t| *t.borrow_mut() = Some(dir.join("chatgpt.json")));
TEST_AUTH.with(|t| *t.borrow_mut() = Some(auth.to_string()));
dir
}
pub fn use_test_api(url: Option<String>) {
TEST_API.with(|t| *t.borrow_mut() = url);
}
pub fn leave_test_place(dir: std::path::PathBuf) {
TEST_FILE.with(|t| *t.borrow_mut() = None);
TEST_AUTH.with(|t| *t.borrow_mut() = None);
let _ = std::fs::remove_dir_all(dir);
}
/// Save a signed-in account (for the provider's tests).
pub fn sign_in_for_test(access: &str, expires_in_ms: i64) {
update(|a| {
a.client_id = "oaiapp_1".into();
a.access = access.into();
a.refresh = "refresh-x".into();
a.expires_at = crate::model::now_ms() + expires_in_ms;
a.scopes = vec![PLAN_SCOPE.into()];
a.email = "a@example.com".into();
a.sub = "user-1".into();
})
.unwrap();
}
/// Sign-ins are one at a time for the whole program: the tests that start one take turns.
fn one_at_a_time() -> std::sync::MutexGuard<'static, ()> {
static T: Mutex<()> = Mutex::new(());
T.lock().unwrap_or_else(|e| e.into_inner())
}
/// Start a sign-in without a browser: the state and nonce it is waiting on.
fn begin() -> (String, String) {
let url = start().unwrap();
let q = query_pairs(url.split_once('?').unwrap().1);
(q["state"].clone(), q["nonce"].clone())
}
#[test]
fn signing_in_registers_checks_the_id_token_and_keeps_the_tokens() {
let nonce = std::sync::Arc::new(Mutex::new(String::new()));
let fake = FakeAuth::start("oaiapp_new", nonce.clone(), "chatgpt.tokens.use.direct email offline_access openid profile resource.invoke");
let _turn = one_at_a_time();
let dir = use_test_place(&fake.url);
let (state, n) = begin();
*nonce.lock().unwrap() = n;
// A new registration that comes back without the issued client id isn't finished.
assert!(finish_from_url(&format!("http://127.0.0.1:1455/auth/callback?code=c1&state={state}")).unwrap_err().contains("註冊沒有完成"));
let (state, n) = begin();
*nonce.lock().unwrap() = n;
let who = finish_from_url(&format!("http://127.0.0.1:1455/auth/callback?code=c1&scope=openid&state={state}&client_id=oaiapp_new")).unwrap();
assert_eq!(who, "a@example.com");
let a = account();
assert_eq!((a.client_id.as_str(), a.access.as_str(), a.refresh.as_str(), a.sub.as_str()), ("oaiapp_new", "access-0", "refresh-0", "user-1"));
assert!(a.plan_ok() && a.host_id.starts_with("urn:uuid:"));
let exchange = fake.seen.lock().unwrap().iter().find(|s| s.contains("authorization_code")).cloned().unwrap();
assert!(exchange.contains("client_id=oaiapp_new") && exchange.contains("code_verifier=") && exchange.contains("resource=https%3A%2F%2Fapi.openai.com%2Fv1"), "{exchange}");
assert_eq!(stored_token(), "access-0");
// The welcome shows once.
assert!(welcome_once().unwrap().contains(USAGE_URL));
assert!(welcome_once().is_none());
// A used state is gone; a callback for another client id is refused.
assert!(finish_from_url(&format!("http://127.0.0.1:1455/auth/callback?code=c1&state={state}&client_id=oaiapp_new")).is_err());
let (state, n) = begin();
*nonce.lock().unwrap() = n;
assert!(finish_from_url(&format!("http://127.0.0.1:1455/auth/callback?code=c2&state={state}&client_id=oaiapp_other")).unwrap_err().contains("不一樣"));
// The registration's own placeholder is never taken as the issued id.
logout(true).unwrap();
let (state, n) = begin();
*nonce.lock().unwrap() = n;
assert!(finish_from_url(&format!("http://127.0.0.1:1455/auth/callback?code=c3&state={state}&client_id=dynamic_agent_client")).unwrap_err().contains("註冊沒有完成"));
let (state, n) = begin();
*nonce.lock().unwrap() = n;
finish_from_url(&format!("http://127.0.0.1:1455/auth/callback?code=c4&state={state}&client_id=oaiapp_new")).unwrap();
// A screen of this brain: how it stands, and a sign-in page for its browser.
let v = for_screen(&json!({"action": "status"}));
assert_eq!((v["signed_in"].clone(), v["plan_ok"].clone(), v["email"].clone()), (json!(true), json!(true), json!("a@example.com")));
// Declining on OpenAI's page.
let (state, _) = begin();
assert!(finish_from_url(&format!("http://127.0.0.1:1455/auth/callback?error=access_denied&state={state}")).unwrap_err().contains("沒有同意"));
let v = for_screen(&json!({"action": "login"}));
assert!(v["url"].as_str().unwrap().contains("/api/accounts/authorize?"), "{v}");
pending().lock().unwrap().clear();
// Signing out revokes and keeps the registration; switching accounts forgets it.
logout(false).unwrap();
assert!(fake.seen.lock().unwrap().iter().any(|s| s.starts_with("/api/accounts/oauth/revoke") && s.contains("token=refresh-0")));
let a = account();
assert!(!a.signed_in() && a.client_id == "oaiapp_new" && stored_token().is_empty());
logout(true).unwrap();
assert!(account().client_id.is_empty());
leave_test_place(dir);
}
#[test]
fn without_the_plan_scope_it_is_signed_in_but_not_usable() {
let nonce = std::sync::Arc::new(Mutex::new(String::new()));
let fake = FakeAuth::start("oaiapp_new", nonce.clone(), "email offline_access openid profile");
let _turn = one_at_a_time();
let dir = use_test_place(&fake.url);
let (state, n) = begin();
*nonce.lock().unwrap() = n;
let e = finish_from_url(&format!("http://127.0.0.1:1455/auth/callback?code=c1&state={state}&client_id=oaiapp_new")).unwrap_err();
assert_eq!(e, NO_PLAN);
assert!(account().signed_in() && stored_token().is_empty());
assert_eq!(fresh_token().unwrap_err(), NoToken { msg: NO_PLAN.into(), retry: false });
leave_test_place(dir);
}
#[test]
fn a_token_near_its_end_is_renewed_and_a_spent_refresh_token_signs_out() {
let fake = FakeAuth::start("oaiapp_1", Default::default(), PLAN_SCOPE);
let dir = use_test_place(&fake.url);
sign_in_for_test("old", 60_000);
assert_eq!(fresh_token().unwrap(), "access-1");
let a = account();
assert_eq!((a.access.as_str(), a.refresh.as_str()), ("access-1", "refresh-1"));
// Another step that still holds the old one gets the one already renewed.
assert_eq!(renew_after("old").unwrap(), "access-1");
assert_eq!(fake.seen.lock().unwrap().iter().filter(|s| s.contains("grant_type=refresh_token")).count(), 1);
// Plenty of time left: not renewed.
sign_in_for_test("fine", 3_600_000);
assert_eq!(fresh_token().unwrap(), "fine");
// Renewed early but the sign-in server can't be reached: the token in hand (minutes left) is used.
sign_in_for_test("still-good", 120_000);
TEST_AUTH.with(|t| *t.borrow_mut() = Some("http://127.0.0.1:1".into()));
assert_eq!(fresh_token().unwrap(), "still-good");
// …but not once it is about to end.
sign_in_for_test("ending", 10_000);
assert!(fresh_token().unwrap_err().retry);
TEST_AUTH.with(|t| *t.borrow_mut() = Some(fake.url.clone()));
feat: ChatGPT 方案——用 ChatGPT 帳號登入,Bot 用你 ChatGPT 方案的額度,不用 API 金鑰 - 新供應商「ChatGPT 方案」(src/chatgpt.rs):照 OpenAI 給開源 App 的 Sign in with ChatGPT。 第一次登入註冊 AnyBot(dynamic_agent_client → oaiapp_…)並重用;PKCE、state、nonce; ID token 驗 RS256 簽章、iss、aud、exp、nonce;沒同意使用方案算登入但不能用(再登入會要求同意)。 - 要求走 Responses API(api.openai.com/v1/responses,store:false、stream:true、instructions), token 只送 OpenAI 自己的網址;收到 response.completed 才算完成;額度用完停下來給管理用量連結, 不重試、不改用 API 金鑰。token 快到期或 401 時更新(一次一個,refresh token 會輪替)。 - 設定 › 模型 › ChatGPT 方案:使用 ChatGPT 繼續、登出、換帳號、打開登入頁、管理用量; 連到伺服器大腦的螢幕電腦和手機也能登入(登入頁開在自己這台,打不開的那頁網址貼回給大腦)。 - Bot 工具 chatgpt_login(status、login、logout、switch_account;登出和換帳號先問)。 - 修連接器登入:封存的 token 前綴寫錯("sealed:" 實際是 "enc:v1:"),重開 App 後 token 沒解開就被當成憑證送出,登入等於每次重開都失效。 已驗證: cargo test 全綠(chatgpt::、providers::、appctl::、remote::、mcp_oauth::、featuremap::、layout_audit::); 授權網址的參數送到 auth.openai.com 沒被拒(302 到登入頁)。 未驗證: 實際用 ChatGPT 帳號登入、同意、Responses 串流與工具呼叫(要真的 ChatGPT 付費帳號和瀏覽器); 螢幕電腦貼回網址、手機登入(要實機);Windows 的「打開登入頁」。 動到審批路徑(appctl::needs_approval 的 chatgpt_login):需要實機測試+人類簽名。 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 09:23:10 +00:00
// A refresh token OpenAI won't take: signed out, the registration kept.
update(|a| a.refresh = "spent".into()).unwrap();
let e = renew_after("fine").unwrap_err();
assert!(!e.retry && e.msg.contains("重新登入"), "{e:?}");
assert!(!account().signed_in() && account().client_id == "oaiapp_1");
// The same when OpenAI nests the code.
sign_in_for_test("fine", 3_600_000);
update(|a| a.refresh = "spent-nested".into()).unwrap();
assert!(renew_after("fine").unwrap_err().msg.contains("重新登入"));
assert!(!account().signed_in());
leave_test_place(dir);
}
#[test]
fn tokens_that_could_not_be_opened_are_not_used_as_tokens() {
let dir = use_test_place("http://127.0.0.1:1");
let p = file();
std::fs::create_dir_all(p.parent().unwrap()).unwrap();
// Sealed with a key this computer can't open now (a locked keychain): not a sign-in.
let sealed = format!("{}00ff", crate::vault_store::SEALED);
std::fs::write(&p, json!({"client_id": "oaiapp_1", "access": sealed, "refresh": sealed, "scopes": [PLAN_SCOPE], "expires_at": crate::model::now_ms() + 3_600_000}).to_string()).unwrap();
assert!(!account().signed_in());
assert!(stored_token().is_empty());
assert_eq!(fresh_token().unwrap_err().msg, NEED_LOGIN);
// Written by AnyBot: this user's only.
update(|a| a.email = "a@example.com".into()).unwrap();
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
assert_eq!(std::fs::metadata(&p).unwrap().permissions().mode() & 0o777, 0o600);
}
leave_test_place(dir);
}
#[test]
fn only_openais_sign_in_page_is_opened() {
assert!(is_sign_in_page("https://auth.openai.com/api/accounts/authorize?client_id=x"));
for bad in ["http://auth.openai.com/x", "https://auth.openai.com.evil.example/x", "file:///etc/passwd", "https://evil.example/?https://auth.openai.com/"] {
assert!(!is_sign_in_page(bad), "{bad}");
}
// What a screen or the phone gets: how it stands, never a token.
let dir = use_test_place("http://127.0.0.1:1");
sign_in_for_test("secret-token", 3_600_000);
let v = view().to_string();
assert!(v.contains("\"signed_in\":true") && !v.contains("secret-token") && !v.contains("refresh-x"), "{v}");
leave_test_place(dir);
}
feat: ChatGPT 方案——用 ChatGPT 帳號登入,Bot 用你 ChatGPT 方案的額度,不用 API 金鑰 - 新供應商「ChatGPT 方案」(src/chatgpt.rs):照 OpenAI 給開源 App 的 Sign in with ChatGPT。 第一次登入註冊 AnyBot(dynamic_agent_client → oaiapp_…)並重用;PKCE、state、nonce; ID token 驗 RS256 簽章、iss、aud、exp、nonce;沒同意使用方案算登入但不能用(再登入會要求同意)。 - 要求走 Responses API(api.openai.com/v1/responses,store:false、stream:true、instructions), token 只送 OpenAI 自己的網址;收到 response.completed 才算完成;額度用完停下來給管理用量連結, 不重試、不改用 API 金鑰。token 快到期或 401 時更新(一次一個,refresh token 會輪替)。 - 設定 › 模型 › ChatGPT 方案:使用 ChatGPT 繼續、登出、換帳號、打開登入頁、管理用量; 連到伺服器大腦的螢幕電腦和手機也能登入(登入頁開在自己這台,打不開的那頁網址貼回給大腦)。 - Bot 工具 chatgpt_login(status、login、logout、switch_account;登出和換帳號先問)。 - 修連接器登入:封存的 token 前綴寫錯("sealed:" 實際是 "enc:v1:"),重開 App 後 token 沒解開就被當成憑證送出,登入等於每次重開都失效。 已驗證: cargo test 全綠(chatgpt::、providers::、appctl::、remote::、mcp_oauth::、featuremap::、layout_audit::); 授權網址的參數送到 auth.openai.com 沒被拒(302 到登入頁)。 未驗證: 實際用 ChatGPT 帳號登入、同意、Responses 串流與工具呼叫(要真的 ChatGPT 付費帳號和瀏覽器); 螢幕電腦貼回網址、手機登入(要實機);Windows 的「打開登入頁」。 動到審批路徑(appctl::needs_approval 的 chatgpt_login):需要實機測試+人類簽名。 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 09:23:10 +00:00
#[test]
fn signed_in_without_the_plan_asks_for_consent_again() {
let declined = Account { client_id: "oaiapp_9".into(), access: "a".into(), scopes: vec!["openid".into()], ..Default::default() };
let (url, _) = authorize_url(&declined, "urn:uuid:h", "http://127.0.0.1:1455/auth/callback", "s", "n", "v");
assert!(url.contains("&prompt=consent"), "{url}");
let fine = Account { scopes: vec![PLAN_SCOPE.into()], ..declined };
assert!(!authorize_url(&fine, "urn:uuid:h", "http://127.0.0.1:1455/auth/callback", "s", "n", "v").0.contains("prompt="));
}
#[test]
fn the_tool_says_what_to_do() {
let _turn = one_at_a_time();
let dir = use_test_place("http://127.0.0.1:1");
assert!(run_tool(r#"{"action":"status"}"#).0.contains("還沒有用 ChatGPT 登入"));
let (text, ok) = run_tool(r#"{"action":"login"}"#);
assert!(ok && text.contains("/api/accounts/authorize?") && text.contains("callback"), "{text}");
assert!(!run_tool(r#"{"action":"nope"}"#).1);
assert_eq!(describe(r#"{"action":"login","callback":"http://x"}"#), "完成登入");
pending().lock().unwrap().clear();
leave_test_place(dir);
}
}