Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 13 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -96,16 +96,22 @@ outbound proxy and priced with a custom price sheet.
### Security

- **Outbound redaction** replaces keys, private keys and connection strings
before a request leaves for an untrusted upstream, and restores them in the
response.
before a request leaves, and restores them in the response.
- **Tool-call inspection** cuts off the response stream when an upstream returns
a tool call carrying a command that would grant code execution.
- **Config scan** checks client configuration files (skills, hooks, MCP servers)
for hidden characters, injected instructions and dangerous commands.

Each runs in Off, Observe or Enforce mode, and all three start in Observe. The
Findings page collects the scan results and compares each upstream's last 24
hours with the 30 days before.
Both apply to every upstream and run in Off, Observe or Enforce mode, starting
in Observe. The Security page lists every rule: built-in rules can be turned off
one at a time, custom rules are regular expressions, and any rule can be tried
on a sample first. Everything the two protections catch is kept in a log.

### MCP

The MCP page shows the MCP servers each client has configured side by side, and
copies a server to another client or removes it, showing the change before
anything is written. It also lists skills and hooks, and scans client
configuration files for hidden characters, injected instructions and dangerous
commands.

<picture>
<source media="(prefers-color-scheme: dark)" srcset="docs/screenshots/findings-en-dark.png">
Expand Down
16 changes: 10 additions & 6 deletions README.zh-CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -84,15 +84,19 @@ Anthropic Messages、OpenAI Chat Completions、OpenAI Responses 与 Gemini 之

### 安全

- **出站脱敏**:请求发往不受信任的上游之前,替换其中的密钥、私钥与连接串,并在
响应中还原。
- **出站脱敏**:请求发出之前,替换其中的密钥、私钥与连接串,并在响应中还原。
- **工具调用审查**:上游返回的工具调用中出现可直接获得执行权限的命令时,在流中
切断。
- **配置面扫描**:检查客户端配置文件(skill、hook、MCP server)中的隐藏字符、
注入内容与危险命令。

三项防护各有「关闭 / 观察 / 拦截」三档,出厂均为「观察」。「发现」页汇总扫描结果,
并对比各上游最近 24 小时与此前 30 天的行为。
两项防护对所有上游生效,各有「关闭 / 观察 / 拦截」三档,出厂均为「观察」。安全页
列出全部规则:内置规则可以逐条停用,也可以用正则表达式添加自定义规则,任何规则
都可以先拿一段文本试过。两项防护命中的内容都记入日志。

### MCP

MCP 页并排列出各客户端配置的 MCP server,可以把一个 server 复制到其他客户端,或
从某个客户端移除,写入前先显示改动。同一页列出 skill 与 hook,并扫描客户端配置
文件中的隐藏字符、注入内容与危险命令。

<picture>
<source media="(prefers-color-scheme: dark)" srcset="docs/screenshots/findings-dark.png">
Expand Down
8 changes: 4 additions & 4 deletions src-tauri/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion src-tauri/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ tauri-plugin-deep-link = "2"
# 编出来的东西不一样;而更要紧的是,打进 `.app` 的那个 twcore 二进制
# 必须和这里编译进去的协议镜像来自同一个 core 版本 —— 打包脚本正是从
# 这个 tag 去取二进制的(见 scripts/fetch-core.sh)。
tw-api = { git = "https://github.com/ThinkWatchProject/ThinkWatch-Core.git", tag = "v0.17.2" }
tw-api = { git = "https://github.com/ThinkWatchProject/ThinkWatch-Core.git", tag = "v0.18.0" }

anyhow = "1"
libc = "0.2"
Expand Down
105 changes: 97 additions & 8 deletions src-tauri/src/control.rs
Original file line number Diff line number Diff line change
Expand Up @@ -324,11 +324,6 @@ impl ControlClient {
.await
}

/// 出站密钥检测攒下的证据。
pub async fn leaks(&self) -> Result<Vec<tw_api::LeakGroup>> {
Ok(serde_json::from_slice(&self.get("/leaks").await?)?)
}

/// 一条请求的全部细节,含 body。
pub async fn request_detail(&self, id: i64) -> Result<tw_api::RequestDetail> {
Ok(serde_json::from_slice(
Expand Down Expand Up @@ -393,9 +388,103 @@ impl ControlClient {
.await
}

/// 每个上游最近是不是变了(防线三)。
pub async fn baseline(&self) -> Result<tw_api::BaselineResponse> {
Ok(serde_json::from_slice(&self.get("/baseline").await?)?)
// ---------------------------------------------------------------- 安全

/// 两项防护的档位和全部规则。
pub async fn security(&self) -> Result<tw_api::SecurityDetail> {
Ok(serde_json::from_slice(&self.get("/security").await?)?)
}

/// 安全日志的一页,按时间倒序。
pub async fn security_events(
&self,
guard: Option<&str>,
within: Option<(i64, i64)>,
before: Option<i64>,
limit: usize,
) -> Result<tw_api::SecurityEventsPage> {
let mut path = format!("/security/events?limit={limit}{}", window_q(within));
if let Some(g) = guard {
path.push_str(&format!("&guard={}", urlencode(g)));
}
if let Some(b) = before {
path.push_str(&format!("&before={b}"));
}
Ok(serde_json::from_slice(&self.get(&path).await?)?)
}

pub async fn set_security_mode(
&self,
guard: &str,
req: &tw_api::ModeSave,
) -> Result<tw_api::ConfigWritten> {
self.send_json(
hyper::Method::PUT,
&format!("/security/{}/mode", segment(guard)),
req,
)
.await
}

/// 启用或停用一条内置规则。
pub async fn toggle_security_rule(
&self,
guard: &str,
id: &str,
req: &tw_api::RuleToggle,
) -> Result<tw_api::ConfigWritten> {
self.send_json(
hyper::Method::PUT,
&format!("/security/{}/builtin/{}", segment(guard), segment(id)),
req,
)
.await
}

pub async fn create_security_rule(
&self,
guard: &str,
req: &tw_api::CustomRuleSave,
) -> Result<tw_api::ConfigWritten> {
self.post_json(&format!("/security/{}/custom", segment(guard)), req)
.await
}

pub async fn update_security_rule(
&self,
guard: &str,
name: &str,
req: &tw_api::CustomRuleSave,
) -> Result<tw_api::ConfigWritten> {
self.send_json(
hyper::Method::PUT,
&format!("/security/{}/custom/{}", segment(guard), segment(name)),
req,
)
.await
}

pub async fn delete_security_rule(
&self,
guard: &str,
name: &str,
base_version: Option<&str>,
) -> Result<tw_api::ConfigWritten> {
let path = with_base(
format!("/security/{}/custom/{}", segment(guard), segment(name)),
base_version,
);
self.send_json(hyper::Method::DELETE, &path, &()).await
}

/// 拿一段文本试一试规则。**不发出任何请求**
pub async fn test_security(
&self,
guard: &str,
req: &tw_api::SecurityTestRequest,
) -> Result<tw_api::SecurityTestResult> {
self.post_json(&format!("/security/{}/test", segment(guard)), req)
.await
}

/// 会话列表。
Expand Down
18 changes: 9 additions & 9 deletions src-tauri/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ pub mod menubar;
pub mod notices;
pub mod prefs;
pub mod routing;
pub mod security;
pub mod supervisor;
pub mod theme;
pub mod update;
Expand Down Expand Up @@ -299,7 +300,6 @@ async fn dashboard(
latency_by_provider: c.latency_by_provider(None).await.unwrap_or_default(),
history: c.history(200, None).await.unwrap_or_default(),
storage: c.storage().await.ok(),
leaks: c.leaks().await.unwrap_or_default(),
// 趋势和分组。**拿不到就是空的,不该让整页失败** —— 旧 core
// 没有这两个端点,而这一页别的部分照样有用(同一条:
// 观测层的缺失不该扩散)。
Expand All @@ -325,8 +325,6 @@ pub struct Dashboard {
history: Vec<tw_api::HistoryRow>,
/// 拿不到就是没有 —— 存储层不在的时候网关照常跑
storage: Option<tw_api::StorageStatus>,
/// 出站密钥检测攒下的证据(观察态)
leaks: Vec<tw_api::LeakGroup>,
/// 按界面给的格宽分格。**稀疏的** —— 空桶由界面补
buckets: Vec<tw_api::CostBucket>,
/// 同样的格子,再按模型分层。趋势图靠它把「什么时候花的」和
Expand Down Expand Up @@ -595,11 +593,6 @@ async fn replay_run(
.map_err(|e| format!("{e:#}"))
}

#[tauri::command]
async fn baseline(state: tauri::State<'_, AppState>) -> Result<tw_api::BaselineResponse, String> {
state.control.baseline().await.map_err(|e| format!("{e:#}"))
}

#[tauri::command]
async fn sessions(
state: tauri::State<'_, AppState>,
Expand Down Expand Up @@ -1542,7 +1535,14 @@ pub fn run() {
mcp_targets,
mcp_plan,
mcp_apply,
baseline,
security::security_detail,
security::security_events,
security::set_security_mode,
security::toggle_security_rule,
security::create_security_rule,
security::update_security_rule,
security::delete_security_rule,
security::test_security,
replay_quote,
replay_run,
save_diagnostics,
Expand Down
59 changes: 43 additions & 16 deletions src-tauri/src/notices/rules.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,13 +40,16 @@ fn l1_step(s: &tw_api::L1Stage) -> String {
/// 界面上的落点。和 `App.tsx` 里的页面标识是同一套词
const UPSTREAMS: &str = "upstreams";
const SECURITY: &str = "security";
const MCP: &str = "mcp";
const CONFIG: &str = "config";

/// 一个键默认落在哪一页(那一条已经不在列表里时用)。按键的种类,也就是冒号前那段
pub fn default_view(key: &str) -> &'static str {
match key.split(':').next().unwrap_or(key) {
"upstream" | "quota" | "credential" | "auth" | "writeback" | "proxy" => UPSTREAMS,
"toolwall" | "scan" => SECURITY,
"toolwall" => SECURITY,
// 客户端配置里的可疑内容在 MCP 页:服务器、技能、钩子和扫描发现都在那儿
"scan" => MCP,
// 网关、配置文件,以及认不出来的:设置页至少能看到网关在不在跑
_ => CONFIG,
}
Expand Down Expand Up @@ -297,15 +300,16 @@ pub fn from_event(ev: &Event) -> Vec<Signal> {
.now(),
]
}
// 客户端此刻正在弹批准提示,**这一条要立刻说**
// 客户端此刻正在弹批准提示,**这一条要立刻说**。只说处置为「切断」的
// 那些规则:「仅记录」的那一类本来就是用户说了不必打断的
Event::ToolCallFlagged {
provider,
tool,
why,
high,
rule,
action,
blocked,
..
} if *high => {
} if action == "cut" => {
let title = if *blocked {
tr!(
format!("已拦截 {provider} 返回的 {tool} 调用"),
Expand All @@ -317,26 +321,27 @@ pub fn from_event(ev: &Event) -> Vec<Signal> {
format!("Suspicious {tool} Call from “{provider}”")
)
};
let tail = if *blocked {
let name = tool_rule_name(rule);
let body = if *blocked {
tr!(
"此上游标记为不受信任,响应流已切断。",
"This upstream is marked untrusted; the response stream was cut off."
format!("命中规则「{name}」,响应已切断。"),
format!("It matched the rule “{name}”, so the response was cut off.")
)
} else {
tr!(
"建议在客户端拒绝此调用。",
"Rejecting this call in the client is recommended."
format!("命中规则「{name}」。建议在客户端拒绝此调用。"),
format!("It matched the rule “{name}”. Rejecting this call in the client is recommended.")
)
};
// **正文不带调用内容**:系统通知在锁屏上也看得见
vec![
Signal::raised(format!("toolwall:{provider}"), Level::Warning, title)
.body(tr!(format!("{why}。{tail}"), format!("{why}. {tail}")))
.body(body)
.view(SECURITY)
.now(),
]
}
// 英文写页面现在的名字「Findings」:点开这一条落到的就是那一页
// 英文写页面现在的名字「MCP」:点开这一条落到的就是那一页
Event::ScanAlert { alerts, .. } if !alerts.is_empty() => vec![
Signal::raised(
"scan",
Expand All @@ -347,19 +352,41 @@ pub fn from_event(ev: &Event) -> Vec<Signal> {
),
)
.body(tr!(
format!("新增 {} 项,详见安全页。", alerts.len()),
format!("新增 {} 项,详见 MCP 页。", alerts.len()),
match alerts.len() {
1 => "1 new item. Details are on the Findings page.".to_string(),
n => format!("{n} new items. Details are on the Findings page."),
1 => "1 new item. Details are on the MCP page.".to_string(),
n => format!("{n} new items. Details are on the MCP page."),
}
))
.view(SECURITY)
.view(MCP)
.now(),
],
_ => Vec::new(),
}
}

/// 工具调用规则的名字,和安全页上的一样。**只有内置的这些**:自定义规则的
/// id 就是用户起的名字,原样用;core 以后加的规则这里还不认识,也原样用 id。
fn tool_rule_name(rule: &str) -> String {
let (zh, en) = match rule {
"curl-pipe-sh" => ("下载即执行", "Download and run"),
"base64-decode-exec" => ("解码后执行", "Decode and run"),
"exfil-env" => ("外发环境变量", "Send out environment variables"),
"exfil-credentials" => ("外发凭据文件", "Send out a credential file"),
"exfil-credentials-reversed" => (
"外发凭据文件(动词在前)",
"Send out a credential file (verb first)",
),
"ssh-key-read" => ("读取私钥或云凭据", "Read a private key or cloud credential"),
"write-startup-item" => ("写入启动项", "Write a startup item"),
"crontab-install" => ("安装定时任务", "Install a scheduled job"),
"rm-rf-root" => ("删除主目录或根目录", "Delete home or root"),
"chmod-777" => ("开放全部写权限", "World-writable permissions"),
other => return other.to_string(),
};
tr!(zh, en).to_string()
}

/// 网关本身的状态。**这是唯一的 critical** —— 它一停,所有客户端都在瞎
pub fn from_core_state(state: &crate::supervisor::CoreState) -> Vec<Signal> {
use crate::supervisor::CoreState;
Expand Down
Loading
Loading