接入小壹专用知识库钥匙

This commit is contained in:
WuYongJie 2026-11-30 01:35:59 +08:00
parent eff36efe1b
commit f4c76a697c
7 changed files with 254 additions and 16 deletions

View File

@ -40,8 +40,8 @@ async function matches(file, item) {
async function httpError(response) {
const body = await response.json().catch(() => ({}));
const messages = {
401: '请重新录入系统凭据「企业知识库/小壹」',
403: '请重新录入系统凭据「企业知识库/小壹」',
401: '请在小壹设置的企业知识库中重新录入小壹钥匙',
403: '请在小壹设置的企业知识库中重新录入小壹钥匙',
410: '此小壹知识版本已撤回。已完整校验的本地工程可继续使用原版本',
};
const message = body.code === 'not_published' ? '此模板还没有发布小壹版本'
@ -81,7 +81,7 @@ export async function acquireXiaoyiRelease(options) {
try {
return await options.fetch(route, {method:'GET', headers, signal});
} catch (error) {
if (error.category === 'credential') throw Error('请录入系统凭据「企业知识库/小壹」', {cause:error});
if (error.category === 'credential') throw Error('请在小壹设置的企业知识库中录入小壹钥匙', {cause:error});
throw error;
}
}

View File

@ -252,7 +252,7 @@ pub(super) fn service(node: &Path, script: &Path, binary: &Path, profile: &Path)
registry.service = None;
}
let mut command = Command::new(node);
command.env_remove("EKB_XIAOYI_READ_KEY");
super::knowledge_http::configure_daemon(&mut command)?;
command.arg(script).arg("--daemon").stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::null()).env_remove("NODE_OPTIONS").env_remove("NODE_PATH");
command.env("PHOTOCRAFT_KNOWLEDGE_HOST", binary);
if let Some(path) = super::knowledge_http::config_path().filter(|_| std::env::var_os("PHOTOCRAFT_KNOWLEDGE_ORIGIN_FILE").is_none()) {

View File

@ -1033,6 +1033,7 @@ impl Backend {
result["knowledgeOrigin"] = json!(intranet);
}
result["knowledgeKeySaved"] = json!(knowledge_http::credential().is_ok());
result["xiaoyiKeySaved"] = json!(knowledge_http::xiaoyi_key_saved());
result["accountEpoch"] = json!(self.access.epoch);
result["origin"] = json!(self.origin);
result["libraryStatus"] = json!(library_status);
@ -1569,6 +1570,7 @@ impl Backend {
"project-sync" => self.sync_project(input),
"project-state" => self.project_state(input),
"configure-knowledge" => knowledge_http::configure(input),
"configure-xiaoyi-knowledge" => Ok(knowledge_http::configure_xiaoyi(input)),
"select-model" => {
if self.auth["account"]["id"].is_null() || input["accountId"] != self.auth["account"]["id"]
|| input["origin"].as_str() != Some(self.origin.as_str())

View File

@ -3,10 +3,20 @@ use super::{R, Value, json};
use base64::{Engine, engine::general_purpose::STANDARD};
use memchr::memmem::Finder;
use reqwest::blocking::{Client, RequestBuilder};
use std::{io::Read, sync::LazyLock, time::Duration};
use std::{
ffi::{OsStr, OsString},
io::{BufReader, Read, Write},
net::{Ipv4Addr, SocketAddrV4, TcpListener, TcpStream},
process::Command,
sync::{Arc, LazyLock, OnceLock},
time::Duration,
};
const CREDENTIAL_NAME: &str = "knowledge:enterprise-knowledge-base";
const XIAOYI_CREDENTIAL_NAME: &str = "企业知识库/小壹";
const XIAOYI_OVERRIDE: &str = "EKB_XIAOYI_READ_KEY";
const XIAOYI_BRIDGE: &str = "PHOTOCRAFT_XIAOYI_OVERRIDE_PORT";
const XIAOYI_CURRENT: &str = "/api/xiaoyi/v1/templates/SFY-CHAIR-001/current";
const ORIGINS: &str = include_str!("../../../../detail-agent-pi/src/enterprise-knowledge-origins.json");
const INVALID: &str = "企业知识库请求边界无效";
const CREDENTIAL: &str = "企业知识库用户凭据未配置或不可读取";
@ -76,6 +86,48 @@ pub(super) fn configure(input: &Value) -> R<Value> {
Ok(json!({"origin":endpoints[0]}))
}
pub(super) fn configure_xiaoyi(input: &Value) -> Value {
let endpoints = match origins() {
Ok(endpoints) => endpoints,
Err(_) => return json!({"status":null,"saved":false,"error":INVALID}),
};
configure_xiaoyi_key(input, &endpoints, || super::vault(XIAOYI_CREDENTIAL_NAME))
}
fn configure_xiaoyi_key(
input: &Value,
origins: &[String],
vault: impl FnOnce() -> R<keyring::Entry>,
) -> Value {
let Ok(key) = normalize_key(input["key"].as_str().unwrap_or_default()) else {
return json!({"status":null,"saved":false,"error":CREDENTIAL});
};
let Ok(client) = MCP_CLIENT.as_ref() else {
return json!({"status":null,"saved":false,"error":NETWORK});
};
let response = origins.iter().find_map(|origin| {
client.get(format!("{origin}{XIAOYI_CURRENT}")).bearer_auth(&key).send().ok()
});
let Some(response) = response else {
return json!({"status":null,"saved":false,"error":NETWORK});
};
let status = response.status().as_u16();
if status != 200 {
return json!({"status":status,"saved":false,"error":format!("小壹钥匙校验失败(HTTP {status})")});
}
if !response.json::<Value>().is_ok_and(|body| {
body["version"].as_str().is_some_and(|version| !version.trim().is_empty())
}) {
return json!({"status":status,"saved":false,"error":RESPONSE});
}
let saved = vault().and_then(|entry| entry.set_password(&key).map_err(|_| CREDENTIAL.into())).is_ok();
json!({"status":status,"saved":saved,"error":if saved { None } else { Some(CREDENTIAL) }})
}
pub(super) fn xiaoyi_key_saved() -> bool {
xiaoyi_credential().is_ok()
}
#[cfg(windows)]
pub(super) fn credential() -> R<String> {
let key = super::vault(CREDENTIAL_NAME).map_err(|_| CREDENTIAL)?
@ -112,7 +164,10 @@ enum Route {
impl Route {
fn parse(input: &Value) -> R<Self> {
let origins = origins()?;
Self::parse_with_origins(input, &origins()?)
}
fn parse_with_origins(input: &Value, origins: &[String]) -> R<Self> {
let origin = input["origin"].as_str().ok_or(INVALID)?;
if !origins.iter().any(|allowed| allowed == origin) {
return Err(INVALID.into());
@ -167,7 +222,18 @@ impl Route {
}
pub(super) fn exchange(input: &Value, mut emit: impl FnMut(Value) -> R<()>) -> R<()> {
if let Err(error) = exchange_inner(input, credential, &mut emit) {
let result = (|| {
let route = Route::parse(input)?;
if route == Route::Xiaoyi && let Some(port) = std::env::var_os(XIAOYI_BRIDGE) {
return relay_override(port.to_str().ok_or(INVALID)?.parse().map_err(|_| INVALID)?, input, &mut emit);
}
exchange_route(route, input, credential, xiaoyi_credential, &mut emit)
})();
emit_error(result, &mut emit)
}
fn emit_error(result: R<()>, emit: &mut impl FnMut(Value) -> R<()>) -> R<()> {
if let Err(error) = result {
let (category, message) = match error.as_str() {
NETWORK => ("network", NETWORK),
CREDENTIAL => ("credential", CREDENTIAL),
@ -193,8 +259,13 @@ fn client(timeout_seconds: u64) -> reqwest::Result<Client> {
.build()
}
fn exchange_inner(input: &Value, credential: impl FnOnce() -> R<String>, emit: &mut impl FnMut(Value) -> R<()>) -> R<()> {
let route = Route::parse(input)?;
fn exchange_route(
route: Route,
input: &Value,
credential: impl FnOnce() -> R<String>,
xiaoyi_key: impl FnOnce() -> R<String>,
emit: &mut impl FnMut(Value) -> R<()>,
) -> R<()> {
let url = format!("{}{}", input["origin"].as_str().ok_or(INVALID)?, input["path"].as_str().ok_or(INVALID)?);
let client = match route {
Route::Health => &HEALTH_CLIENT,
@ -204,21 +275,88 @@ fn exchange_inner(input: &Value, credential: impl FnOnce() -> R<String>, emit: &
let request = route.request(client, url, input)?;
let key = match route {
Route::Health => None,
Route::Xiaoyi => Some(xiaoyi_credential()?),
Route::Xiaoyi => Some(xiaoyi_key()?),
_ => Some(credential()?),
};
send(request, key.as_deref(), emit)
}
fn xiaoyi_credential() -> R<String> {
if let Ok(key) = std::env::var("EKB_XIAOYI_READ_KEY") {
return normalize_key(&key);
}
let key = super::vault(XIAOYI_CREDENTIAL_NAME).map_err(|_| CREDENTIAL)?
.get_password().map_err(|_| CREDENTIAL)?;
normalize_key(&key)
}
// Only the desktop host holds the override. The Node daemon and its RPC
// workers inherit a loopback port used to relay the existing response frames.
pub(super) fn configure_daemon(command: &mut Command) -> R<()> {
static PORT: OnceLock<R<u16>> = OnceLock::new();
let port = if let Some(key) = std::env::var_os(XIAOYI_OVERRIDE) {
let port = PORT.get_or_init(|| start_override_bridge(key)).as_ref().map_err(Clone::clone)?;
Some(*port)
} else {
None
};
set_daemon_bridge(command, port);
Ok(())
}
fn set_daemon_bridge(command: &mut Command, port: Option<u16>) {
command.env_remove(XIAOYI_OVERRIDE).env_remove(XIAOYI_BRIDGE);
if let Some(port) = port {
command.env(XIAOYI_BRIDGE, port.to_string());
}
}
fn start_override_bridge(key: OsString) -> R<u16> {
let listener = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).map_err(|_| NETWORK)?;
let port = listener.local_addr().map_err(|_| NETWORK)?.port();
let key = Arc::new(key);
std::thread::spawn(move || {
for stream in listener.incoming().map_while(Result::ok) {
let key = Arc::clone(&key);
std::thread::spawn(move || {
let _ = serve_override(stream, &key, origins);
});
}
});
Ok(port)
}
fn serve_override(mut stream: TcpStream, key: &OsStr, allowed_origins: impl FnOnce() -> R<[String; 2]>) -> R<()> {
stream.set_read_timeout(Some(Duration::from_secs(5))).map_err(|_| NETWORK)?;
let result = (|| {
let Some(Ok(line)) = super::pi::bounded_line(&mut BufReader::new(&stream))? else {
return Err(INVALID.into());
};
let input: Value = serde_json::from_slice(&line).map_err(|_| INVALID)?;
let route = Route::parse_with_origins(&input, &allowed_origins()?)?;
if route != Route::Xiaoyi {
return Err(INVALID.into());
}
exchange_route(route, &input, || Err(INVALID.into()),
|| normalize_key(key.to_str().ok_or(CREDENTIAL)?), &mut |frame| {
writeln!(stream, "{frame}").map_err(|_| NETWORK.into())
})
})();
emit_error(result, &mut |frame| writeln!(stream, "{frame}").map_err(|_| NETWORK.into()))
}
fn relay_override(port: u16, input: &Value, emit: &mut impl FnMut(Value) -> R<()>) -> R<()> {
let mut stream = TcpStream::connect(SocketAddrV4::new(Ipv4Addr::LOCALHOST, port)).map_err(|_| NETWORK)?;
writeln!(stream, "{input}").map_err(|_| NETWORK)?;
let mut reader = BufReader::new(stream);
while let Some(Ok(line)) = super::pi::bounded_line(&mut reader)? {
let frame: Value = serde_json::from_slice(&line).map_err(|_| RESPONSE)?;
let terminal = matches!(frame["type"].as_str(), Some("result" | "error"));
emit(frame)?;
if terminal {
return Ok(());
}
}
Err(NETWORK.into())
}
fn send(request: RequestBuilder, key: Option<&str>, emit: &mut impl FnMut(Value) -> R<()>) -> R<()> {
let request = if let Some(key) = key { request.bearer_auth(key) } else { request };
let mut response = request.send().map_err(|_| NETWORK)?;
@ -267,6 +405,69 @@ mod tests {
use std::io::{BufRead, BufReader, Cursor, Write};
use std::net::TcpListener;
fn current_fixture(status: u16, body: &'static str, key: &'static str) -> (String, std::thread::JoinHandle<()>) {
let listener = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).unwrap();
let origin = format!("http://{}", listener.local_addr().unwrap());
let server = std::thread::spawn(move || {
let (mut stream, _) = listener.accept().unwrap();
stream.set_read_timeout(Some(Duration::from_secs(5))).unwrap();
let mut lines = BufReader::new(&mut stream).lines();
assert!(lines.next().unwrap().unwrap() == format!("GET {XIAOYI_CURRENT} HTTP/1.1"));
assert!(lines.map(Result::unwrap).take_while(|line| !line.is_empty())
.any(|line| line == format!("authorization: Bearer {key}")));
write!(stream, "HTTP/1.1 {status} Fixture\r\nContent-Length: {}\r\n\r\n{body}", body.len()).unwrap();
});
(origin, server)
}
#[test]
fn jiansun_xiaoyi_override_reaches_current_and_stays_out_of_node_environment() {
const KEY: &str = "synthetic-xiaoyi-override";
let (origin, upstream) = current_fixture(200, r#"{"version":"v1"}"#, KEY);
let listener = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).unwrap();
let port = listener.local_addr().unwrap().port();
let allowed = origin.clone();
let host = std::thread::spawn(move || {
let (stream, _) = listener.accept().unwrap();
serve_override(stream, OsStr::new(KEY), || Ok([allowed, String::new()])).unwrap();
});
let mut node = Command::new("node");
node.env(XIAOYI_OVERRIDE, KEY).arg("-e").arg(
"process.exit(Number('EKB_XIAOYI_READ_KEY' in process.env || !process.env.PHOTOCRAFT_XIAOYI_OVERRIDE_PORT))",
);
set_daemon_bridge(&mut node, Some(port));
assert!(node.status().unwrap().success());
let input = json!({"origin":origin,"path":XIAOYI_CURRENT,"httpMethod":"GET","headers":{}});
let mut frames = Vec::new();
relay_override(port, &input, &mut |frame| {
assert!(!frame.to_string().contains(KEY));
frames.push(frame);
Ok(())
}).unwrap();
assert_eq!(frames[0]["status"], 200);
assert_eq!(frames.last().unwrap()["type"], "result");
host.join().unwrap();
upstream.join().unwrap();
}
#[test]
fn jiansun_xiaoyi_configuration_saves_verified_key_only() {
const KEY: &str = "synthetic-xiaoyi-config";
for (status, body, saved) in [(200, r#"{"version":"v1"}"#, true), (403, "", false), (200, "{}", false)] {
let (origin, server) = current_fixture(status, body, KEY);
let entry = keyring::Entry::new_with_credential(Box::new(keyring::mock::MockCredential::default()));
let result = configure_xiaoyi_key(&json!({"key":KEY}), &[origin], || {
assert!(saved, "未通过校验时不得打开凭据条目");
Ok(entry)
});
assert_eq!(result["saved"], saved);
assert_eq!(result["status"], status);
assert!(!result.to_string().contains(KEY));
server.join().unwrap();
}
}
#[test]
fn jiansun_knowledge_invalid_key_errors_omit_input() {
let error = normalize_key("synthetic\ninvalid-key").unwrap_err();
@ -306,12 +507,12 @@ mod tests {
(origins[0], "GET", "//api/agent/files/a/download"),
] {
let input = json!({"origin":origin,"path":path,"httpMethod":method,"headers":{}});
let result = exchange_inner(&input, || panic!("白名单拒绝后读取了凭据"), &mut |_| Ok(()));
let result = Route::parse(&input);
assert_eq!(result.unwrap_err(), INVALID);
}
let input = json!({"origin":origins[0],"path":"/mcp","httpMethod":"POST","body":"{}",
"headers":{"authorization":"caller-supplied"}});
let result = exchange_inner(&input, || panic!("拒绝调用方鉴权头后读取了凭据"), &mut |_| Ok(()));
let result = exchange_route(Route::Mcp, &input, || panic!("拒绝调用方鉴权头后读取了凭据"), || unreachable!(), &mut |_| Ok(()));
assert_eq!(result.unwrap_err(), INVALID);
}

View File

@ -237,7 +237,7 @@ pub(super) fn run() -> R<()> {
// Read each line without ever allocating more than the request limit. Oversized
// lines are drained through their newline, so the next request stays aligned.
fn bounded_line(reader: &mut impl std::io::BufRead) -> R<Option<Result<Vec<u8>, ()>>> {
pub(super) fn bounded_line(reader: &mut impl std::io::BufRead) -> R<Option<Result<Vec<u8>, ()>>> {
let mut line = Vec::new();
let mut oversized = false;
let mut seen = false;

View File

@ -1001,6 +1001,9 @@ pub struct Workspace {
account_error: String,
api_key: String,
knowledge_key: String,
xiaoyi_key: String,
xiaoyi_key_saved: bool,
xiaoyi_key_error: String,
knowledge_origin: String,
knowledge_key_saved: bool,
config: bool,
@ -1538,6 +1541,9 @@ impl Workspace {
account_error: String::new(),
api_key: String::new(),
knowledge_key: String::new(),
xiaoyi_key: String::new(),
xiaoyi_key_saved: false,
xiaoyi_key_error: String::new(),
knowledge_origin: String::new(),
knowledge_key_saved: false,
config: false,
@ -2682,6 +2688,7 @@ impl Workspace {
self.knowledge_origin = origin.to_owned();
}
self.knowledge_key_saved = v["knowledgeKeySaved"] == true;
self.xiaoyi_key_saved = v["xiaoyiKeySaved"] == true;
self.connection_received(&v);
self.error = v["message"].as_str().unwrap_or("").into();
if self.error == self.library_message { self.error.clear(); }
@ -3175,6 +3182,10 @@ impl Workspace {
"project-cover" => self.cover_failed(&v),
"project-delete" => self.project_deleted(app, &v),
"select-model" => self.receive_model_preference(&v),
"configure-xiaoyi-knowledge" => {
self.xiaoyi_key_saved |= v["saved"] == true;
self.xiaoyi_key_error = v["error"].as_str().unwrap_or_default().to_owned();
}
"configure-knowledge" => {
self.knowledge_origin = v["origin"].as_str().unwrap_or_default().to_owned();
self.knowledge_key_saved = true;

View File

@ -3574,6 +3574,7 @@ impl Workspace {
if !open {
self.api_key.clear();
self.knowledge_key.clear();
self.xiaoyi_key.clear();
}
if !visual.render {
return;
@ -3704,6 +3705,27 @@ impl Workspace {
} else if self.knowledge_key_saved {
ui.label("企业知识库 Key 已保存");
}
ui.add_enabled_ui(self.busy.is_none(), |ui| {
let id = ui.make_persistent_id("xiaoyi-knowledge-key");
super::stitch_ui::halo_field(ui, id.with("field"), None, self.reduce_motion, |ui| ui.add(
super::stitch_ui::text_input(&mut self.xiaoyi_key, "输入小壹知识库钥匙", false)
.id(id).password(true).desired_width(f32::INFINITY).frame(Frame::NONE),
)).on_hover_text("只保存在本机系统凭据库");
if super::stitch_ui::action_button(ui, "校验并保存小壹钥匙", super::stitch_ui::ButtonRole::Quiet,
!self.xiaoyi_key.trim().is_empty()).clicked()
{
self.xiaoyi_key_error.clear();
let key = std::mem::take(&mut self.xiaoyi_key);
self.send("configure-xiaoyi-knowledge", json!({"key":key}));
}
});
if self.busy.as_deref() == Some("configure-xiaoyi-knowledge") {
ui.label("正在校验小壹钥匙…");
} else if !self.xiaoyi_key_error.is_empty() {
ui.label(&self.xiaoyi_key_error);
} else if self.xiaoyi_key_saved {
ui.label("小壹钥匙已保存");
}
super::stitch_ui::divider(ui);
if let Some(id) = notification_id(&self.origin, &self.account, &self.project_context, self.owner_doc) {
@ -7124,6 +7146,7 @@ mod tests {
w.model_settings = true;
w.key_settings = true;
w.api_key = "temporary-secret".into();
w.xiaoyi_key = "synthetic-xiaoyi-draft".into();
w.reduce_motion = false;
}
let frame = |time: f64, app: &mut PhotocraftApp| {
@ -7141,6 +7164,7 @@ mod tests {
}
let exiting = frame(0.41, &mut app);
assert!(app.jiansun.as_ref().unwrap().api_key.is_empty(), "closing must clear the secret before visual exit");
assert!(app.jiansun.as_ref().unwrap().xiaoyi_key.is_empty());
assert!(exiting.shapes.iter().any(|shape| has_label(&shape.shape, "小壹设置")), "the closing surface remains visible during exit");
let _ = frame(0.7, &mut app);
let closed = frame(1.2, &mut app);