feat(models): persist explicitly saved credentials with user-scoped DPAPI

This commit is contained in:
Agent Workbench Dev
2026-10-31 09:30:38 +08:00
parent 249f191ebc
commit 72a496adfa
27 changed files with 857 additions and 21 deletions
+10 -2
View File
@@ -14,6 +14,14 @@ Node24构建通过;[49项相关回归](desktop-host-a-accepted.tap)全部通
Electron固定45.2.0的真实二进制为249810432字节,SHA256010ea51bfb528c8143513439aa93fb40754403daa2023f9decd4517da71706ab;安装脚本显式完成,真实窗口尚未运行。开发工具Inno7.1.1安装命令被自动审批策略阻止、无执行;已核对可直接解包的innosetup-compiler6.3.1依赖,D再开发与验收。正式health仍1.14/PID23172,没有升级或重启。
## B–F
## B:本机加密连接(通过)
本机加密连接正在推进;Electron窗口与IPC、安装/可回退更新、桌面三工程和独立发行尚未实施,按[执行方案](PLAN-1.15.md)验收。
实际CurrentUser DPAPI保存块放在SQLite独立metadata,与连接登记共同提交;原公开registry/导出不写明文Key。显式新Key或本次确认导入可保存,关闭自动加载、删除本机保存、清除内存与本机保存分开。连接/配置修订、当前用户和数据目录参与绑定。加载失败显示损坏/用户/目录/来源状态,原保存块不重写。
[21专项与兼容](desktop-credentials-b-tests.tap)全部通过:实际DPAPI正确/错误entropy及损坏,重开加载与修订、批量导入第二密钥加密失败/事务提交失败回退原行/路由/内存引用,停用/删除/清除及明文扫描。[7组实际浏览器与重启](desktop-credentials-b-actual.json)全部通过,原PID28724/新PID49924;已保存两连接恢复、临时连接丢弃,原公共连接/密文和除runtimeOwner的6表原行保持;恢复后3次自有HTTP请求实际认证成功。日志/SQLite页/WAL/配置/导出不含自有明文测试Key;没有使用正式Key或真实推理。
Python依赖缺失的原失败未启动宿主,随后独立桌面虚拟环境固定Playwright1.64.1。真实UI首轮发现select可访问标签不完整,原失败报告/日志保留;补aria-label。首个已通过布局仍拥挤,保留prelayout原截图/报告,采用既有蓝白控制台的表单网格和当前标签可见性,再实际1440/390复验与人工截图审查通过。不同Windows账号未登录验收;已实际验证错误entropy/损坏并验证不同SID拒绝,不将其写为跨账号实测。
## C–F
Electron窗口与IPC正在实施,真实窗口尚未验收;安装/可回退更新、桌面三工程和独立发行按[执行方案](PLAN-1.15.md)继续。
+6
View File
@@ -11,3 +11,9 @@
49相关回归及9组真实主机通过。除签名挑战,核对实际PID创建、用户SID、加载的不可变输入和数据目录;注册失败不发布半成品内存,锁和启动意图防止不明进程被重复创建。模型队列/HTTP和原生driver加入完整关闭。中文工作区及重复DACL设置的原失败证明需要真实Windows验证;所有失败保留,改为UTF-8 base64输入和仅修改Access权限后复验。原历史导出保持原结构,验收从独立SQLite读取完整原tool行。
本切片仅交付主机基础;Electron窗口关闭/重开需C/E真实证明。下一B把密文和注册写入同一SQLite事务,避免两份磁盘文件之间的部分提交;只加密用户新输入/明确确认导入的Key,不自动持久化原内存连接。不同用户/损坏/配置修订失配应分别显示不可加载。
## B回顾
21专项/兼容和7组实际浏览器、独立宿主重启及HTTP验证通过。DPAPI密文同SQLite事务提交,保存失败回退连接、路由、旧内存引用和全部原行;仅处理用户新填或当前确认导入。已保存连接的原修订跨进程保持,临时连接清除;关闭、删除和清除语义分别验证。SID/目录/源修订异常不自动重写原块。跨Windows账号登录尚未进行,证据不从SID测试外推。
浏览器通过不等于视觉完成:首个窄屏截图仍使用挤在一行的默认控件,原结果保留,补既有控制台表单网格和选中导航自动可见后重新验收。下一C继续同一React客户端,原文件入口只在所属项目定位,不执行文件;Task审查核对当前项目/会话/Task。Electron窗口关闭后自行退出,独立Node继续执行;明确退出宿主才等待所属工具结束。单实例、主frame/固定IPC、导航与权限拒绝均需实际Electron验证。
+95
View File
@@ -0,0 +1,95 @@
{
"success": true,
"root": "D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\desktop-credentials-4083fa57-495c-4f03-a634-38b3af7ac525",
"url": "http://127.0.0.1:62117",
"stage": "plaintext leak scan over actual database, WAL, exports and host logs",
"originalHost": {
"url": "http://127.0.0.1:62117",
"identity": {
"schema": 1,
"protocol": "agent-workbench-host-v1",
"app": "agent-workbench",
"version": "1.14.0",
"instanceId": "ad80c3c8-5484-443d-b142-1d763e49350f",
"pid": 28724,
"createdAt": "2026-10-31T01:21:14.095Z",
"userSid": "S-1-5-21-3906741337-925321518-3767092861-1001",
"ownerId": "41b7bfe9-e7f5-4051-a5bc-e371575da94a",
"executable": {
"path": "D:\\Ai-project\\REA逆向\\tools\\node-v24.22.1-win-x64\\node.exe",
"bytes": 93915464,
"sha256": "d702daa815eabbff763c7d3808e235cf031cf2ca70211b56847bc72f51e240e5"
},
"appRoot": "D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\desktop-credentials-4083fa57-495c-4f03-a634-38b3af7ac525\\app",
"runtimeRoot": "D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\desktop-credentials-4083fa57-495c-4f03-a634-38b3af7ac525\\app",
"runtimeIdentity": "e53c216c4180c7b2960028f2e9cb1763fc5510efe0ea088e5370450e76a621d8",
"dataRoot": "D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\desktop-credentials-4083fa57-495c-4f03-a634-38b3af7ac525\\data",
"port": 62117
},
"reused": false,
"logs": {
"stdoutPath": "D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\desktop-credentials-4083fa57-495c-4f03-a634-38b3af7ac525\\data\\logs\\desktop-host-78659811-d287-4dd2-bee4-655a36c0c328-stdout.log",
"stderrPath": "D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\desktop-credentials-4083fa57-495c-4f03-a634-38b3af7ac525\\data\\logs\\desktop-host-78659811-d287-4dd2-bee4-655a36c0c328-stderr.log"
}
},
"freshHost": {
"url": "http://127.0.0.1:62117",
"identity": {
"schema": 1,
"protocol": "agent-workbench-host-v1",
"app": "agent-workbench",
"version": "1.14.0",
"instanceId": "ae5ee3e1-584d-4969-bbe3-7483382035cb",
"pid": 49924,
"createdAt": "2026-10-31T01:21:23.749Z",
"userSid": "S-1-5-21-3906741337-925321518-3767092861-1001",
"ownerId": "5d0fb73d-77b2-450a-9a07-b089a3e6a4c6",
"executable": {
"path": "D:\\Ai-project\\REA逆向\\tools\\node-v24.22.1-win-x64\\node.exe",
"bytes": 93915464,
"sha256": "d702daa815eabbff763c7d3808e235cf031cf2ca70211b56847bc72f51e240e5"
},
"appRoot": "D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\desktop-credentials-4083fa57-495c-4f03-a634-38b3af7ac525\\app",
"runtimeRoot": "D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\desktop-credentials-4083fa57-495c-4f03-a634-38b3af7ac525\\app",
"runtimeIdentity": "e53c216c4180c7b2960028f2e9cb1763fc5510efe0ea088e5370450e76a621d8",
"dataRoot": "D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\desktop-credentials-4083fa57-495c-4f03-a634-38b3af7ac525\\data",
"port": 62117
},
"reused": false,
"logs": {
"stdoutPath": "D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\desktop-credentials-4083fa57-495c-4f03-a634-38b3af7ac525\\data\\logs\\desktop-host-747ea62f-e2db-46e7-a878-d48d3533ab64-stdout.log",
"stderrPath": "D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\desktop-credentials-4083fa57-495c-4f03-a634-38b3af7ac525\\data\\logs\\desktop-host-747ea62f-e2db-46e7-a878-d48d3533ab64-stderr.log"
}
},
"groups": [
"real connection form and explicit encrypted save",
"real legacy credential save without exposing an existing key",
"real desktop and 390px saved-state controls and layout",
"actual host exit and fresh process restores encrypted revisions",
"fresh host actually uses both DPAPI-restored keys with owned HTTP responses",
"disable, delete and forget through real controls",
"plaintext leak scan over actual database, WAL, exports and host logs"
],
"requests": [
{
"path": "/v1/chat/completions",
"authorizedOwnedKey": true
},
{
"path": "/v1/chat/completions",
"authorizedOwnedKey": true
},
{
"path": "/v1/chat/completions",
"authorizedOwnedKey": true
}
],
"images": [
"D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\desktop-credentials-4083fa57-495c-4f03-a634-38b3af7ac525\\credentials-new-connection.png",
"D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\desktop-credentials-4083fa57-495c-4f03-a634-38b3af7ac525\\credentials-1440.png",
"D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\desktop-credentials-4083fa57-495c-4f03-a634-38b3af7ac525\\credentials-390.png"
],
"pageErrors": [],
"detail": null,
"scope": "Owned CurrentUser DPAPI and local HTTP fixture; no external model request or existing credential is used."
}
+7
View File
@@ -0,0 +1,7 @@
PASS real connection form and explicit encrypted save
PASS real legacy credential save without exposing an existing key
PASS real desktop and 390px saved-state controls and layout
PASS actual host exit and fresh process restores encrypted revisions
PASS fresh host actually uses both DPAPI-restored keys with owned HTTP responses
PASS disable, delete and forget through real controls
PASS plaintext leak scan over actual database, WAL, exports and host logs
+37
View File
@@ -0,0 +1,37 @@
{
"success": true,
"root": "D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\desktop-credentials-4cfcf5da-eaaf-472e-b6c0-99266b1e9a3c",
"url": "http://127.0.0.1:62578",
"stage": "plaintext leak scan over actual database, WAL, exports and host logs",
"groups": [
"real connection form and explicit encrypted save",
"real legacy credential save without exposing an existing key",
"real desktop and 390px saved-state controls and layout",
"actual host exit and fresh process restores encrypted revisions",
"fresh host actually uses both DPAPI-restored keys with owned HTTP responses",
"disable, delete and forget through real controls",
"plaintext leak scan over actual database, WAL, exports and host logs"
],
"requests": [
{
"path": "/v1/chat/completions",
"authorizedOwnedKey": true
},
{
"path": "/v1/chat/completions",
"authorizedOwnedKey": true
},
{
"path": "/v1/chat/completions",
"authorizedOwnedKey": true
}
],
"images": [
"D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\desktop-credentials-4cfcf5da-eaaf-472e-b6c0-99266b1e9a3c\\credentials-new-connection.png",
"D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\desktop-credentials-4cfcf5da-eaaf-472e-b6c0-99266b1e9a3c\\credentials-1440.png",
"D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\desktop-credentials-4cfcf5da-eaaf-472e-b6c0-99266b1e9a3c\\credentials-390.png"
],
"pageErrors": [],
"detail": null,
"scope": "Owned CurrentUser DPAPI and local HTTP fixture; no external model request or existing credential is used."
}
+7
View File
@@ -0,0 +1,7 @@
PASS real connection form and explicit encrypted save
PASS real legacy credential save without exposing an existing key
PASS real desktop and 390px saved-state controls and layout
PASS actual host exit and fresh process restores encrypted revisions
PASS fresh host actually uses both DPAPI-restored keys with owned HTTP responses
PASS disable, delete and forget through real controls
PASS plaintext leak scan over actual database, WAL, exports and host logs
+136
View File
@@ -0,0 +1,136 @@
TAP version 13
# Subtest: actual Windows CurrentUser DPAPI roundtrips owned UTF-8 and rejects damaged bytes and wrong entropy
ok 1 - actual Windows CurrentUser DPAPI roundtrips owned UTF-8 and rejects damaged bytes and wrong entropy
---
duration_ms: 1703.112
type: 'test'
...
# Subtest: only explicitly supplied keys persist; new provider restores original revisions and public views contain no key
ok 2 - only explicitly supplied keys persist; new provider restores original revisions and public views contain no key
---
duration_ms: 2823.1817
type: 'test'
...
# Subtest: registry and cipher commit failure restores original routing, keys, block and every database row
ok 3 - registry and cipher commit failure restores original routing, keys, block and every database row
---
duration_ms: 1872.4547
type: 'test'
...
# Subtest: a two-key import with a protection failure rolls back all registry and cipher entries and retains its preview
ok 4 - a two-key import with a protection failure rolls back all registry and cipher entries and retains its preview
---
duration_ms: 1892.0773
type: 'test'
...
# Subtest: connection revision changes retain the original saved block and report a source mismatch on restart
ok 5 - connection revision changes retain the original saved block and report a source mismatch on restart
---
duration_ms: 2825.6882
type: 'test'
...
# Subtest: disable skips real restart loading, explicit enable restores, delete preserves memory and forget removes both
ok 6 - disable skips real restart loading, explicit enable restores, delete preserves memory and forget removes both
---
duration_ms: 2609.0633
type: 'test'
...
# Subtest: corrupt saved block and another SID do not load; failures are visible without returning ciphertext or plaintext
ok 7 - corrupt saved block and another SID do not load; failures are visible without returning ciphertext or plaintext
---
duration_ms: 2682.8404
type: 'test'
...
# Subtest: legacy persistence requires a new explicit key and binds config and credential revisions; stale requests cannot save
ok 8 - legacy persistence requires a new explicit key and binds config and credential revisions; stale requests cannot save
---
duration_ms: 2361.2135
type: 'test'
...
# Subtest: owned plaintext keys never reach SQLite pages, WAL, config or public execution exports
ok 9 - owned plaintext keys never reach SQLite pages, WAL, config or public execution exports
---
duration_ms: 1256.7214
type: 'test'
...
# Subtest: model registry keeps original credentials/endpoint intact, rejects stale edits, and forgets only volatile keys on restart
ok 10 - model registry keeps original credentials/endpoint intact, rejects stale edits, and forgets only volatile keys on restart
---
duration_ms: 914.4979
type: 'test'
...
# Subtest: config import previews exact revisions, keeps secrets volatile, syncs only when enabled and preserves manual edits on conflicts
ok 11 - config import previews exact revisions, keeps secrets volatile, syncs only when enabled and preserves manual edits on conflicts
---
duration_ms: 753.8609
type: 'test'
...
# Subtest: real HTTP pool fails over 429 to another model and never repeats completed tools; attempts seal actual request bytes and Run identity
ok 12 - real HTTP pool fails over 429 to another model and never repeats completed tools; attempts seal actual request bytes and Run identity
---
duration_ms: 2729.1166
type: 'test'
...
# Subtest: pool rotation and weights select members on new Runs; disabled and missing credentials are excluded without requests
ok 13 - pool rotation and weights select members on new Runs; disabled and missing credentials are excluded without requests
---
duration_ms: 3857.7792
type: 'test'
...
# Subtest: 401 blocks the credential revision; updating the key restores availability without leaking error echoes
ok 14 - 401 blocks the credential revision; updating the key restores availability without leaking error echoes
---
duration_ms: 2080.9134
type: 'test'
...
# Subtest: queued request cancellation and in-flight disable release only owned leases and do not dispatch another HTTP request
ok 15 - queued request cancellation and in-flight disable release only owned leases and do not dispatch another HTTP request
---
duration_ms: 958.8689
type: 'test'
...
# Subtest: compiled model-center HTTP API persists public profiles, blocks forged origins, and local operations never invoke a model
ok 16 - compiled model-center HTTP API persists public profiles, blocks forged origins, and local operations never invoke a model
---
duration_ms: 2084.6897
type: 'test'
...
# Subtest: model registry disk failures restore routing, pool profiles and credential references without partial updates
ok 17 - model registry disk failures restore routing, pool profiles and credential references without partial updates
---
duration_ms: 957.6324
type: 'test'
...
# Subtest: model selection and saved configuration commit together and failures preserve the original mode and endpoint
ok 18 - model selection and saved configuration commit together and failures preserve the original mode and endpoint
---
duration_ms: 711.9416
type: 'test'
...
# Subtest: configuration imports roll back the entire batch and retain one usable preview after validation or commit failure
ok 19 - configuration imports roll back the entire batch and retain one usable preview after validation or commit failure
---
duration_ms: 726.4839
type: 'test'
...
# Subtest: hot upgrade refreshes retained model and importer methods while preserving credential and routing objects
ok 20 - hot upgrade refreshes retained model and importer methods while preserving credential and routing objects
---
duration_ms: 751.8999
type: 'test'
...
# Subtest: hot upgrade refuses active probes and restores retained model methods if installation fails
ok 21 - hot upgrade refuses active probes and restores retained model methods if installation fails
---
duration_ms: 728.8236
type: 'test'
...
1..21
# tests 21
# suites 0
# pass 21
# fail 0
# cancelled 0
# skipped 0
# todo 0
# duration_ms 20118.8961
@@ -0,0 +1,14 @@
{
"success": false,
"root": "D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\desktop-credentials-91af1820-7dfa-4ffd-aa0a-6c002014c8c5",
"url": "http://127.0.0.1:60078",
"stage": "real legacy credential save without exposing an existing key",
"groups": [
"real connection form and explicit encrypted save"
],
"requests": [],
"images": [],
"pageErrors": [],
"detail": "Locator.select_option: Timeout 30000ms exceeded.\nCall log:\n - waiting for get_by_role(\"dialog\", name=\"模型中心\", exact=True).get_by_role(\"form\", name=\"保存加密凭据\", exact=True).get_by_label(\"选择保存连接\", exact=True)\n",
"scope": "Owned CurrentUser DPAPI and local HTTP fixture; no external model request or existing credential is used."
}
@@ -0,0 +1,20 @@
PASS real connection form and explicit encrypted save
Traceback (most recent call last):
File "D:\Ai-project\REA逆向\Agent-Workbench\scripts\verify-desktop-credentials.py", line 127, in <module>
form.get_by_label('选择保存连接', exact=True).select_option('legacy-default')
File "D:\Ai-project\REA逆向\Agent-Workbench\.qa\desktop-python\lib\site-packages\playwright\sync_api\_generated.py", line 13173, in select_option
self._sync(
File "D:\Ai-project\REA逆向\Agent-Workbench\.qa\desktop-python\lib\site-packages\playwright\_impl\_sync_base.py", line 111, in _sync
return task.result()
File "D:\Ai-project\REA逆向\Agent-Workbench\.qa\desktop-python\lib\site-packages\playwright\_impl\_locator.py", line 652, in select_option
return await self._frame.select_option(
File "D:\Ai-project\REA逆向\Agent-Workbench\.qa\desktop-python\lib\site-packages\playwright\_impl\_frame.py", line 819, in select_option
return await self._channel.send("selectOption", self._timeout, params)
File "D:\Ai-project\REA逆向\Agent-Workbench\.qa\desktop-python\lib\site-packages\playwright\_impl\_connection.py", line 78, in send
return await self._connection.wrap_api_call(
File "D:\Ai-project\REA逆向\Agent-Workbench\.qa\desktop-python\lib\site-packages\playwright\_impl\_connection.py", line 636, in wrap_api_call
raise rewrite_error(error, f"{parsed_st['apiName']}: {error}") from None
playwright._impl._errors.TimeoutError: Locator.select_option: Timeout 30000ms exceeded.
Call log:
- waiting for get_by_role("dialog", name="模型中心", exact=True).get_by_role("form", name="保存加密凭据", exact=True).get_by_label("选择保存连接", exact=True)
Binary file not shown.

After

Width:  |  Height:  |  Size: 136 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 139 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 56 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 59 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 136 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 137 KiB

+3
View File
@@ -623,3 +623,6 @@ Claude Code 报告已验证工具输入校验、权限决定、队列并发屏
# 2026-10-31 1.15 A/B衔接
A的49专项和9组实际隔离宿主通过,正式1.14/PID23172保持。PowerShell默认stdin编码在中文路径失效,重新写完整安全描述符误需SeSecurityPrivilege;分别采用UTF-8 base64路径和Access-only DACL。已完成工具的完整原行从只读SQLite核对,保留旧公开导出。B决定以Windows用户级DPAPI加密块存在同一SQLite事务metadata中,配置/密文/内存失败一起回退;显式新Key/确认导入才持久化,原Key不抽取。
# 2026-10-31 B收口与C边界
B实际DPAPI/21专项/7浏览器-重启组通过,未用正式Key。密文与registry同库事务,配置变化保留失效原块;新UI原可访问select错误和prelayout拥挤截图保留,表单网格/活动标签可见后复验。C采用Electron45.2隔离主窗口及6个固定IPC,不导出ipcRenderer/Node;打开目录与文件定位绑定登记项目/当前Task及SHA,窗口退出不结束Node,显式宿主退出保留核验。原窗口内核不复制第二套代理。
+3
View File
@@ -649,3 +649,6 @@
已接续未提交的A初稿;尚未部署。修正初始化发布时机、全路径祖先/链接及多路径检查、Windows秘密目录当前用户ACL、保留宿主热更新身份、请求与模型队列取消,以及剩余原生driver关闭。Start/Stop入口改为挑战签名与实际PID创建/SID/安装/数据目录验证。下一步独立构建与真实隔离进程验证。
工具层初次读取不存在的父AGENTS/根Start脚本和猜测测试文件、Windows rg通配参数失败均无产品副作用;已使用仓库实际AGENTS及scripts路径,限定rg目录。一次补丁因重复文件操作被拒绝,未生效;拆成有效修改后完成。初次总输出超限未视为已读,已重新按函数小段核对。
# 2026-10-31 B交付前回顾
A提交249f191。B构建及21专项/兼容、7组浏览器/DPAPI恢复/HTTP/全数据目录明文扫描通过,实际28724→49924,新恢复两Key共3次夹具响应。完整公开配置和除runtimeOwner的6表原行保持。原Python缺依赖、首轮无select可访问标签和首个prelayout记录保留,采用独立Playwright1.64.1与既有蓝白网格复验。当前正式仍1.14/PID23172,未启动真实推理;C的主进程/桥/预加载初稿尚未编译或接入,不计交付。
+206
View File
@@ -0,0 +1,206 @@
"""Owned Windows DPAPI restart and real browser acceptance; no user credentials."""
import argparse
import hashlib
import http.server
import json
import os
from pathlib import Path
import re
import shutil
import socket
import sqlite3
import subprocess
import threading
import time
import urllib.request
import uuid
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--node', required=True)
args = parser.parse_args()
from playwright.sync_api import sync_playwright, expect
workspace = Path.cwd()
root = workspace / '.qa' / ('desktop-credentials-' + str(uuid.uuid4()))
app_root, data_root = root / 'app', root / 'data'
app_root.mkdir(parents=True)
for name in ['dist-client', 'dist-server']:
shutil.copytree(workspace / name, app_root / name)
shutil.copy2(workspace / 'package.json', app_root / 'package.json')
with socket.socket() as probe:
probe.bind(('127.0.0.1', 0))
port = probe.getsockname()[1]
url = 'http://127.0.0.1:' + str(port)
node = str(Path(args.node).resolve())
allowed = re.compile(r'^(path|pathext|systemroot|systemdrive|windir|comspec|temp|tmp|userprofile|homedrive|homepath|home|appdata|localappdata|programfiles(?:\(x86\))?|commonprogramfiles(?:\(x86\))?|lang|lc_all)$', re.I)
environment = {key: value for key, value in os.environ.items() if allowed.match(key)}
environment['PATH'] = str(Path(node).parent) + os.pathsep + environment.get('PATH', environment.get('Path', ''))
for key in list(environment):
if key.lower() == 'path' and key != 'PATH':
del environment[key]
keys = ['OWNED_UI_DPAPI_' + uuid.uuid4().hex, 'OWNED_UI_LEGACY_' + uuid.uuid4().hex, 'OWNED_UI_VOLATILE_' + uuid.uuid4().hex]
requests = []
class ModelFixture(http.server.BaseHTTPRequestHandler):
def respond(self):
if self.command == 'POST':
self.rfile.read(int(self.headers.get('Content-Length', 0)))
valid = self.headers.get('Authorization') in ['Bearer ' + key for key in keys]
requests.append({'path': self.path, 'authorizedOwnedKey': valid})
result = {'data': [{'id': 'owned-fixture'}]} if self.path.endswith('/models') else {'choices': [{'message': {'role': 'assistant', 'content': 'Owned response OK'}, 'finish_reason': 'stop'}], 'usage': {'prompt_tokens': 5, 'completion_tokens': 4, 'total_tokens': 9}}
encoded = json.dumps(result if valid else {'error': {'message': 'Owned fixture credential rejected'}}).encode()
self.send_response(200 if valid else 401)
self.send_header('Content-Type', 'application/json')
self.send_header('Content-Length', str(len(encoded)))
self.end_headers()
self.wfile.write(encoded)
do_GET = respond
do_POST = respond
def log_message(self, *unused):
pass
fixture = http.server.ThreadingHTTPServer(('127.0.0.1', 0), ModelFixture)
threading.Thread(target=fixture.serve_forever, daemon=True).start()
endpoint = 'http://127.0.0.1:' + str(fixture.server_port) + '/v1'
marks, errors, images = [], [], []
started, token, stage = False, None, 'host start'
def host(command):
child = subprocess.run([node, str(app_root / 'dist-server' / 'host-launcher.mjs'), command, '--app-root', str(app_root), '--data-root', str(data_root), '--node', node, '--port', str(port)], cwd=str(app_root), env=environment, capture_output=True, encoding='utf-8', timeout=75, creationflags=subprocess.CREATE_NO_WINDOW)
if child.returncode:
raise RuntimeError('Owned host operation failed: ' + child.stderr)
return json.loads(child.stdout)
def api(route, payload=None):
req = urllib.request.Request(url + '/api' + route, data=None if payload is None else json.dumps(payload).encode(), headers={'Content-Type': 'application/json', 'X-Workbench-Token': token or '', 'Connection': 'close'})
with urllib.request.urlopen(req, timeout=30) as response:
return json.load(response)
def mark(name):
marks.append(name)
print('PASS ' + name, flush=True)
def snapshot_rows():
with sqlite3.connect((data_root / 'workbench.sqlite').as_uri() + '?mode=ro', uri=True) as db:
result = {table: db.execute('SELECT * FROM ' + table + ' ORDER BY rowid').fetchall() for table in ['metadata', 'projects', 'sessions', 'records', 'events', 'outbox']}
result['metadata'] = [row for row in result['metadata'] if row[0] != 'runtimeOwner']
return result
def save(success, detail=None):
result = {'success': success, 'root': str(root), 'url': url, 'stage': stage, 'originalHost': globals().get('original'), 'freshHost': globals().get('fresh'), 'groups': marks, 'requests': requests, 'images': images, 'pageErrors': errors, 'detail': detail, 'scope': 'Owned CurrentUser DPAPI and local HTTP fixture; no external model request or existing credential is used.'}
(root / 'result.json').write_text(json.dumps(result, ensure_ascii=False, indent=2), encoding='utf-8')
(workspace / '.qa' / 'desktop-credentials-latest.json').write_text(json.dumps(result, ensure_ascii=False, indent=2), encoding='utf-8')
try:
original = host('start'); started = True
token = api('/bootstrap')['token']
api('/config', {'mode': 'demo', 'baseUrl': endpoint, 'model': 'owned-legacy'})
with sync_playwright() as pw:
browser = pw.chromium.launch(channel='msedge', headless=True)
page = browser.new_page(viewport={'width': 1440, 'height': 1000})
page.on('pageerror', lambda error: errors.append(str(error)))
page.goto(url)
page.wait_for_load_state('networkidle')
assert page.get_by_role('button', name='打开模型中心', exact=True).count() == 1
page.get_by_role('button', name='打开模型中心', exact=True).click()
dialog = page.get_by_role('dialog', name='模型中心', exact=True)
expect(dialog).to_be_visible()
stage = 'real connection form and explicit encrypted save'
dialog.get_by_role('button', name='添加连接', exact=True).click()
editor = dialog.get_by_role('form', name='编辑模型连接', exact=True)
editor.get_by_label('连接名称', exact=True).fill('Owned Saved Primary')
editor.get_by_label('接口根地址', exact=True).fill(endpoint)
editor.get_by_label('实际模型名称', exact=True).fill('owned-primary')
editor.get_by_label('本机加密保存本次填写的 API Key', exact=True).check()
expect(editor.get_by_role('button', name='保存模型连接', exact=True)).to_be_disabled()
editor.get_by_label('临时 API Key', exact=True).fill(keys[0])
editor.get_by_role('button', name='保存模型连接', exact=True).click()
expect(dialog.locator('.mc-connection').filter(has_text='Owned Saved Primary')).to_contain_text('可从本机加密保存加载')
assert keys[0] not in page.content()
mark(stage)
initial_image = root / 'credentials-new-connection.png'
page.screenshot(path=str(initial_image), full_page=True)
images.append(str(initial_image))
center = api('/model-center')
saved = next(value for value in center['connections'] if value['name'] == 'Owned Saved Primary')
volatile = api('/model-center/connections', {'name': 'Owned Volatile', 'model': 'owned-volatile', 'baseUrl': endpoint, 'apiKey': keys[2]})
stage = 'real legacy credential save without exposing an existing key'
dialog.get_by_role('button', name='凭据保存', exact=True).click()
form = dialog.get_by_role('form', name='保存加密凭据', exact=True)
expect(form).to_be_visible()
form.get_by_label('选择保存连接', exact=True).select_option('legacy-default')
form.get_by_label('重新填写 API Key', exact=True).fill(keys[1])
form.get_by_role('button', name='加密保存凭据', exact=True).click()
expect(form.get_by_label('重新填写 API Key', exact=True)).to_have_value('')
expect(dialog.locator('.mc-connection').filter(has_text='原模型连接')).to_contain_text('本机加密保存')
mark(stage)
for width in [1440, 390]:
page.set_viewport_size({'width': width, 'height': 1000})
expect(dialog.get_by_role('heading', name='本机加密凭据', exact=True)).to_be_visible()
assert page.evaluate('document.documentElement.scrollWidth <= innerWidth + 1')
image = root / ('credentials-' + str(width) + '.png')
page.screenshot(path=str(image), full_page=True)
images.append(str(image))
mark('real desktop and 390px saved-state controls and layout')
browser.close()
stage = 'actual host exit and fresh process restores encrypted revisions'
api('/model-center/probe', {'id': saved['id']})
before_rows = snapshot_rows()
before_credentials = api('/model-center/credentials')
stopped = host('stop'); started = False
assert stopped['processExited']
fresh = host('start'); started = True
assert fresh['identity']['instanceId'] != original['identity']['instanceId']
token = api('/bootstrap')['token']
restored = api('/model-center')
current = next(value for value in restored['connections'] if value['id'] == saved['id'])
assert current['hasKey'] and current['credentialRevision'] == saved['credentialRevision']
assert next(value for value in restored['connections'] if value['id'] == volatile['id'])['hasKey'] is False
assert next(value for value in restored['connections'] if value['id'] == 'legacy-default')['hasKey']
assert snapshot_rows() == before_rows
assert api('/model-center/credentials')['connections'] == before_credentials['connections']
mark(stage)
api('/model-center/probe', {'id': saved['id']})
api('/model-center/probe', {'id': 'legacy-default'})
assert len(requests) == 3 and all(value['authorizedOwnedKey'] for value in requests)
mark('fresh host actually uses both DPAPI-restored keys with owned HTTP responses')
stage = 'disable, delete and forget through real controls'
with sync_playwright() as pw:
browser = pw.chromium.launch(channel='msedge', headless=True)
page = browser.new_page(viewport={'width': 1280, 'height': 900})
page.goto(url); page.wait_for_load_state('networkidle')
page.get_by_role('button', name='打开模型中心', exact=True).click()
dialog = page.get_by_role('dialog', name='模型中心', exact=True)
dialog.get_by_role('button', name='凭据保存', exact=True).click()
card = dialog.locator('.mc-connection').filter(has_text='Owned Saved Primary')
card.get_by_role('button', name='关闭自动加载', exact=True).click()
expect(card).to_contain_text('关闭自动加载')
card.get_by_role('button', name='启用自动加载', exact=True).click()
expect(card.get_by_role('button', name='关闭自动加载', exact=True)).to_be_visible()
card.get_by_role('button', name='删除本机保存', exact=True).click()
expect(card).to_contain_text('仅本次内存')
assert next(value for value in api('/model-center')['connections'] if value['id'] == saved['id'])['hasKey']
card.get_by_role('button', name='清除该连接凭据', exact=True).click()
deadline = time.time() + 10
while next(value for value in api('/model-center')['connections'] if value['id'] == saved['id'])['hasKey']:
if time.time() > deadline:
raise AssertionError('Credential clearing did not settle')
time.sleep(0.1)
browser.close()
mark(stage)
stage = 'plaintext leak scan over actual database, WAL, exports and host logs'
needles = [needle for key in keys for needle in [key.encode(), key.encode('utf-16le')]]
for file in data_root.rglob('*'):
if file.is_file():
data = file.read_bytes()
assert not any(needle in data for needle in needles), str(file)
assert not any(key in json.dumps(api('/model-center')) for key in keys)
mark(stage)
assert not errors
save(True)
except Exception as error:
save(False, str(error))
raise
finally:
fixture.shutdown(); fixture.server_close()
if started:
host('stop')
+57 -12
View File
@@ -1,16 +1,19 @@
import { useEffect, useRef, useState } from 'react';
import { Activity, Check, CircleHelp, Layers3, Plus, Power, RefreshCw, Route, Server, Settings2 } from 'lucide-react';
import { Activity, Check, CircleHelp, KeyRound, Layers3, Plus, Power, RefreshCw, Route, Server, Settings2 } from 'lucide-react';
import { api } from './api';
import type { Config } from './types';
import './ModelCenter.css';
type Connection = { id: string; name: string; brand: string; protocol: string; baseUrl: string; model: string; enabled: boolean; revision: number; hasKey: boolean;
requiresKey: boolean; contextLimit: number; maxOutputTokens: number; concurrency: number; status: string; activeRequests: number; health: { state: string; reason?: string; cooldownUntil?: number } };
requiresKey: boolean; contextLimit: number; maxOutputTokens: number; concurrency: number; status: string; activeRequests: number; savedCredential?: { status: string }; health: { state: string; reason?: string; cooldownUntil?: number } };
type Pool = { id?: string; name: string; members: { connectionId: string; weight: number }[]; strategy: string; sticky: boolean; maxAttempts: number; revision?: number; queueTimeoutMs: number };
type Attempt = { id: string; connectionId: string; poolId: string | null; model: string; status: string; startedAt: string; ordinal: number; usageStatus: string; reason?: string; taskId?: string; runId: string; requestArtifactId?: string; usage?: { prompt_tokens?: number; completion_tokens?: number } };
type ImportRecord = { id: string; source: string; path: string; enabled: boolean; lastCheckedAt?: string; lastSyncedAt?: string; lastError?: string; lastResult?: { imported?: number; conflicts?: string[] } };
type Center = { revision: number; selected: { type: string; id: string }; connections: Connection[]; pools: Pool[]; imports: ImportRecord[]; attempts: Attempt[]; waiting: number };
type Operations = { checkedAt: string; version: string; scope: string; activeTasks: number; queue: number; checks: { id: string; title: string; status: string; detail: string }[] };
type SavedCredential = { id: string; name: string; revision: number; status: string; enabled?: boolean; savedAt?: string; message: string };
type CredentialView = { supported: boolean; unavailable: boolean; connections: SavedCredential[]; scope: string };
const savedStates: Record<string, string> = { not_saved: '仅本次内存', saved: '本机加密保存', disabled: '关闭自动加载', source_changed: '配置已变化', decrypt_failed: '无法解密', user_mismatch: '用户不匹配', directory_mismatch: '目录不匹配', unavailable: '保存登记不可用' };
const states: Record<string, string> = { configured: '已配置', needs_key: '待填凭据', disabled: '已停用', needs_attention: '需要处理', cooling: '冷却中', completed: '收到响应', failed: '失败', running: '请求中', unknown: '结果待核对', interrupted: '已中断', passed: '通过', attention: '待配置' };
const initial = { name: '', brand: '自定义', model: '', baseUrl: 'https://api.openai.com/v1', requiresKey: true, enabled: true, contextLimit: 16000, maxOutputTokens: 2048, concurrency: 1 };
const emptyPool: Pool = { name: '', members: [], strategy: 'round-robin', sticky: true, maxAttempts: 3, queueTimeoutMs: 15000 };
@@ -19,6 +22,8 @@ export function ModelCenter({ onConfig, onLegacy, busy }: { onConfig: (value: Co
const [tab, setTab] = useState('connections');
const [draft, setDraft] = useState<typeof initial & { id?: string; revision?: number }>(initial);
const [editing, setEditing] = useState(false), [key, setKey] = useState('');
const [persistKey, setPersistKey] = useState(false), [persistImports, setPersistImports] = useState(false);
const [credentialView, setCredentialView] = useState<CredentialView | null>(null), [credentialKey, setCredentialKey] = useState(''), [credentialTarget, setCredentialTarget] = useState('');
const [pool, setPool] = useState<Pool>(emptyPool), [poolEditing, setPoolEditing] = useState(false);
const [working, setWorking] = useState(false), [notice, setNotice] = useState('');
const [operations, setOperations] = useState<Operations | null>(null), [autoInspect, setAutoInspect] = useState(false);
@@ -26,40 +31,51 @@ export function ModelCenter({ onConfig, onLegacy, busy }: { onConfig: (value: Co
const [preview, setPreview] = useState<{ id: string; entries: { id: string; name: string; model: string; baseUrl: string; hasKey: boolean }[]; notices: string[] } | null>(null);
const [discovery, setDiscovery] = useState<{ source: string; path: string; available: boolean; supported: boolean; detail?: string }[]>([]);
const alive = useRef(true), generation = useRef(0);
const tabsRef = useRef<HTMLElement>(null);
async function refresh() { const marker = ++generation.current; const result = await api<Center>('/model-center'); if (alive.current && marker === generation.current) setView(result); }
async function act(action: () => Promise<void>) {
setWorking(true); setNotice('');
try { await action(); if (alive.current) await refresh(); }
try { await action(); if (alive.current) { await refresh(); if (credentialView) await refreshCredentials(); } }
catch (cause) { if (alive.current) setNotice(cause instanceof Error ? cause.message : '操作未完成,请刷新核对。'); }
finally { if (alive.current) setWorking(false); }
}
async function inspect() { const value = await api<Operations>('/operations'); if (alive.current) setOperations(value); }
async function refreshCredentials() { const value = await api<CredentialView>('/model-center/credentials'); if (alive.current) setCredentialView(value); }
useEffect(() => { alive.current = true; void refresh().catch(error => { if (alive.current) setNotice(error.message); }); return () => { alive.current = false; generation.current++; }; }, []);
useEffect(() => { if (!autoInspect || tab !== 'operations') return; const timer = window.setInterval(() => { void inspect().catch(error => { if (alive.current) setNotice(error.message); }); }, 30000); return () => window.clearInterval(timer); }, [autoInspect, tab]);
useEffect(() => { setCredentialKey(''); if (tab === 'credentials') void refreshCredentials().catch(error => { if (alive.current) setNotice(error.message); }); }, [tab]);
useEffect(() => {
const ensureVisible = () => { const nav = tabsRef.current, button = nav?.querySelector<HTMLButtonElement>('button[aria-current]'); if (!nav || !button) return;
const area = nav.getBoundingClientRect(), target = button.getBoundingClientRect(), start = target.left - area.left;
if (start < 0) nav.scrollLeft += start - 12; else if (start + target.width > nav.clientWidth) nav.scrollLeft += start + target.width - nav.clientWidth + 12;
};
const frame = requestAnimationFrame(ensureVisible); window.addEventListener('resize', ensureVisible);
return () => { cancelAnimationFrame(frame); window.removeEventListener('resize', ensureVisible); };
}, [tab]);
const selected = view?.selected;
const selectionName = selected?.type === 'pool' ? view?.pools.find(value => value.id === selected.id)?.name : view?.connections.find(value => value.id === selected?.id)?.name;
const locked = working || busy;
return <section className="model-center" aria-label="模型控制台" aria-busy={working}>
<div className="mc-overview"><div><span className="mc-eyebrow">MODEL CONTROL</span><h2>连接有序,执行有据。</h2><p>统一管理模型服务、调度和每次真实请求。</p></div><div className="mc-current"><Route size={18} /><span>当前路由<strong>{selectionName || '原模型连接'}</strong></span><span className="mc-count">{view?.waiting ?? 0} 等待</span></div></div>
<nav className="mc-tabs" aria-label="模型中心分类">{[['connections', '模型连接', Server], ['pools', '模型池', Layers3], ['attempts', '请求账本', Route], ['imports', '配置导入', Settings2], ['operations', '运行巡检', Activity]].map(([id, title, Icon]) => {
<nav ref={tabsRef} className="mc-tabs" aria-label="模型中心分类">{[['connections', '模型连接', Server], ['pools', '模型池', Layers3], ['attempts', '请求账本', Route], ['imports', '配置导入', Settings2], ['credentials', '凭据保存', KeyRound], ['operations', '运行巡检', Activity]].map(([id, title, Icon]) => {
const Symbol = Icon as typeof Server; return <button key={id as string} type="button" aria-current={tab === id ? 'page' : undefined} onClick={() => { setTab(id as string); setNotice(''); }}><Symbol size={16} />{title as string}</button>;
})}<button className="mc-refresh" type="button" disabled={working} onClick={() => void act(refresh)} aria-label="刷新模型中心"><RefreshCw size={16} /></button></nav>
{notice && <div className="mc-notice" role="status">{notice}</div>}
{busy && <p className="mc-notice">有任务正在执行;连接可停用,其他配置请在任务结束后修改。</p>}
{!view ? <p className="mc-empty">正在读取实际连接状态…</p> : <div className="mc-content">
{tab === 'connections' && <>
<div className="mc-section-title"><div><h3>模型连接</h3><p>凭据仅在本次宿主内存中使用。已配置与调用通过分别显示。</p></div><button className="button primary" disabled={locked} onClick={() => { setDraft(initial); setKey(''); setEditing(true); }}><Plus size={16} />添加连接</button></div>
<div className="mc-section-title"><div><h3>模型连接</h3><p>默认仅在本次宿主内存中使用;可在凭据保存中选择本机加密。已配置与调用通过分别显示。</p></div><button className="button primary" disabled={locked} onClick={() => { setDraft(initial); setKey(''); setPersistKey(false); setEditing(true); }}><Plus size={16} />添加连接</button></div>
<div className="mc-connections">{view.connections.map(value => <article className={'mc-connection ' + (!value.enabled ? 'mc-disabled' : '')} key={value.id}>
<div className="mc-card-heading"><span className="mc-service-icon"><Server size={20} /></span><div><h4>{value.name}</h4><span>{value.brand} · Chat Completions</span></div><span className={'mc-state mc-state-' + value.status}>{states[value.status]}</span></div>
<dl><dt>模型</dt><dd>{value.model || '尚未填写'}</dd><dt>接口</dt><dd>{value.baseUrl}</dd><dt>临时凭据</dt><dd>{value.hasKey ? '已设置,重启需重新填写' : value.requiresKey ? '尚未填写' : '此服务可不填'}</dd><dt>请求 / 容量</dt><dd>{value.activeRequests} 在途 · 并发 {value.concurrency} · 上下文 {value.contextLimit.toLocaleString()}</dd></dl>
<dl><dt>模型</dt><dd>{value.model || '尚未填写'}</dd><dt>接口</dt><dd>{value.baseUrl}</dd><dt>凭据</dt><dd>{value.hasKey ? value.savedCredential?.status === 'saved' ? '已设置,可从本机加密保存加载' : '已设置,重启需重新填写' : value.requiresKey ? '尚未填写' : '此服务可不填'}</dd><dt>请求 / 容量</dt><dd>{value.activeRequests} 在途 · 并发 {value.concurrency} · 上下文 {value.contextLimit.toLocaleString()}</dd></dl>
<div className="mc-capabilities"><span>工具:协议声明</span><span>视觉 / 语音:待验证</span></div>
{value.health.reason && <p className="mc-card-warning">{value.health.reason}{!!value.health.cooldownUntil && value.health.cooldownUntil > Date.now() && ' · 冷却至 ' + new Date(value.health.cooldownUntil).toLocaleTimeString()}</p>}
<footer><button className="button secondary" disabled={locked || !value.enabled} onClick={() => void act(async () => { const result = await api<{ config: Config }>('/model-center/select', { type: value.id === 'legacy-default' ? 'legacy' : 'connection', id: value.id }); if (alive.current) onConfig(result.config); })}>{selected?.id === value.id ? <Check size={14} /> : <Route size={14} />}{selected?.id === value.id ? '当前使用' : '用于新任务'}</button>
<button className="button secondary" disabled={locked} onClick={() => { if (value.id === 'legacy-default') { onLegacy(); return; } setDraft(value); setKey(''); setEditing(true); }}>编辑</button>
<button className="button secondary" disabled={locked} onClick={() => { if (value.id === 'legacy-default') { onLegacy(); return; } setDraft(value); setKey(''); setPersistKey(false); setEditing(true); }}>编辑</button>
{value.id !== 'legacy-default' && <button className="mc-icon-action" aria-label={(value.enabled ? '停用' : '启用') + value.name} disabled={working} onClick={() => void act(async () => { await api('/model-center/toggle', { id: value.id, enabled: !value.enabled }); })}><Power size={15} />{value.enabled ? '停用' : '启用'}</button>}
<button className="mc-probe" disabled={locked || !value.enabled} onClick={() => void act(async () => { await api('/model-center/probe', { id: value.id }); if (alive.current) setNotice('该连接已收到实际响应;请求与用量已记入账本。'); })}>验证响应(调用模型)</button></footer>
</article>)}</div>
{editing && <form className="mc-editor" aria-label="编辑模型连接" onSubmit={event => { event.preventDefault(); void act(async () => { await api('/model-center/connections', { ...draft, ...(key ? { apiKey: key } : {}) }); if (alive.current) { setKey(''); setEditing(false); setNotice('连接已保存。'); } }); }}>
{editing && <form className="mc-editor" aria-label="编辑模型连接" onSubmit={event => { event.preventDefault(); void act(async () => { await api('/model-center/connections', { ...draft, ...(key ? { apiKey: key } : {}), ...(persistKey ? { persistKey: true } : {}) }); if (alive.current) { setKey(''); setEditing(false); setNotice(persistKey ? '连接与本机加密凭据已一起保存。' : '连接已保存。'); } }); }}>
<h3>{draft.id ? '编辑模型连接' : '添加模型连接'}</h3><div className="mc-form-grid">
<label>连接名称<input required value={draft.name} onChange={event => setDraft({ ...draft, name: event.target.value })} /></label>
<label>服务品牌<select value={draft.brand} onChange={event => setDraft({ ...draft, brand: event.target.value })}>{['自定义', 'OpenAI', 'Claude 兼容代理', 'DeepSeek', 'Ollama', 'vLLM', '兼容服务'].map(brand => <option key={brand}>{brand}</option>)}</select></label>
@@ -70,11 +86,40 @@ export function ModelCenter({ onConfig, onLegacy, busy }: { onConfig: (value: Co
<label>输出上限<input type="number" min="256" max="16000" value={draft.maxOutputTokens} onChange={event => setDraft({ ...draft, maxOutputTokens: Number(event.target.value) })} /></label>
<label>并发请求上限<input type="number" min="1" max="8" value={draft.concurrency} onChange={event => setDraft({ ...draft, concurrency: Number(event.target.value) })} /></label>
<label className="mc-checkbox"><input type="checkbox" checked={draft.requiresKey} onChange={event => setDraft({ ...draft, requiresKey: event.target.checked })} />服务需要 API Key</label></div>
<p className="mc-help"><CircleHelp size={14} />选择品牌仅用于分类;接口需要提供兼容的 Chat Completions 协议。</p>
<div className="mc-actions"><button className="button secondary" type="button" onClick={() => { setEditing(false); setKey(''); }}>取消</button><button className="button primary" disabled={locked} type="submit">保存模型连接</button></div>
<label className="mc-checkbox"><input type="checkbox" checked={persistKey} onChange={event => setPersistKey(event.target.checked)} />本机加密保存本次填写的 API Key</label>
<p className="mc-help"><CircleHelp size={14} />加密保存需要新填凭据;配置变化后需重新保存。选择品牌仅用于分类,接口需提供 Chat Completions 协议。</p>
<div className="mc-actions"><button className="button secondary" type="button" onClick={() => { setEditing(false); setKey(''); }}>取消</button><button className="button primary" disabled={locked || persistKey && !key.trim()} type="submit">保存模型连接</button></div>
</form>}
</>}
{tab === 'pools' && <><div className="mc-section-title"><div><h3>模型池</h3><p>按能力、临时凭据、健康和并发选择成员,切换保留已完成操作。</p></div><button className="button primary" disabled={locked} onClick={() => { setPool(emptyPool); setPoolEditing(true); }}><Plus size={16} />新建模型池</button></div>
{tab === 'credentials' && <section aria-label="本机加密凭据">
<div className="mc-section-title"><div><h3>本机加密凭据</h3><p>使用当前Windows用户加密。保存后的 Key 不会回显或包含在导出中。</p></div></div>
{!credentialView ? <p className="mc-empty">正在核对本机保存状态…</p> : <>
<p className="mc-help">只保存这次填写或确认导入的凭据。临时连接在宿主退出后需要重新填写。</p>
{credentialView.unavailable && <p className="mc-card-warning">原保存登记格式不可用;原数据保留,请核对后修复。</p>}
<form className="mc-editor" aria-label="保存加密凭据" onSubmit={event => { event.preventDefault(); void act(async () => {
const target = view.connections.find(value => value.id === (credentialTarget || view.connections[0]?.id));
if (!target) return;
const result = await api<{ config: Config }>('/model-center/credentials', { id: target.id, revision: target.revision, action: 'save', apiKey: credentialKey });
if (alive.current) { setCredentialKey(''); setNotice('本机加密凭据已保存;宿主重启后按原连接身份加载。'); onConfig(result.config); }
}); }}>
<div className="mc-form-grid"><label>选择保存连接<select aria-label="选择保存连接" value={credentialTarget || view.connections[0]?.id || ''} onChange={event => { setCredentialTarget(event.target.value); setCredentialKey(''); }}>{view.connections.map(value => <option key={value.id} value={value.id}>{value.name} · {value.model || '未填写模型'}</option>)}</select></label>
<label>重新填写 API Key<input type="password" autoComplete="off" value={credentialKey} onChange={event => setCredentialKey(event.target.value)} /></label></div>
<p className="mc-help">只保存这次新填的凭据。不同用户、目录或连接配置无法加载原保存块。</p>
<div className="mc-actions"><button type="submit" className="button primary" disabled={locked || !credentialView.supported || credentialView.unavailable || !credentialKey.trim()}>加密保存凭据</button></div>
</form>
<div className="mc-connections">{credentialView.connections.map(value => <article className="mc-connection" key={value.id}>
<div className="mc-card-heading"><KeyRound size={20} /><div><h4>{value.name}</h4><span>{savedStates[value.status] || value.status}</span></div></div>
<p className="mc-help">{value.message}</p>{value.savedAt && <p className="mc-help">保存于 {new Date(value.savedAt).toLocaleString()}</p>}
<div className="mc-actions">{value.status !== 'not_saved' && <>
<button className="button secondary" disabled={locked} onClick={() => void act(async () => { await api('/model-center/credentials', { id: value.id, revision: value.revision, action: value.enabled ? 'disable' : 'enable' }); })}>{value.enabled ? '关闭自动加载' : '启用自动加载'}</button>
<button className="button secondary" disabled={locked} onClick={() => void act(async () => { await api('/model-center/credentials', { id: value.id, revision: value.revision, action: 'delete' }); })}>删除本机保存</button>
</>}
<button className="button secondary" disabled={locked} onClick={() => void act(async () => { const result = await api<{ config: Config }>('/model-center/credentials', { id: value.id, revision: value.revision, action: 'forget' }); if (alive.current) onConfig(result.config); })}>清除该连接凭据</button>
</div>
</article>)}</div><p className="mc-help">删除本机保存保留本次内存连接;清除该连接凭据会同时移除本机保存与内存凭据。</p>
</>}
</section>}
{tab === 'pools' && <><div className="mc-section-title"><div><h3>模型池</h3><p>按能力、凭据、健康和并发选择成员,切换保留已完成操作。</p></div><button className="button primary" disabled={locked} onClick={() => { setPool(emptyPool); setPoolEditing(true); }}><Plus size={16} />新建模型池</button></div>
{!view.pools.length && <p className="mc-empty">添加多个连接后建立模型池,设置轮询与故障切换规则。</p>}
{view.pools.map(value => <article className="mc-pool" key={value.id}><Layers3 size={23} /><div><h4>{value.name}</h4><p>{value.strategy === 'weighted' ? '权重轮询' : '顺序轮询'} · {value.members.length} 个成员 · {value.maxAttempts} 次尝试上限 · {value.sticky ? '运行内保持连接' : '每次请求重新选择'}</p><div className="mc-members">{value.members.map(member => <span key={member.connectionId}>{view.connections.find(connection => connection.id === member.connectionId)?.name} ×{member.weight}</span>)}</div></div><div className="mc-actions"><button className="button secondary" disabled={locked} onClick={() => { setPool(value); setPoolEditing(true); }}>编辑</button><button className="button primary" disabled={locked} onClick={() => void act(async () => { const result = await api<{ config: Config }>('/model-center/select', { type: 'pool', id: value.id }); if (alive.current) onConfig(result.config); })}>{selected?.id === value.id ? '当前模型池' : '使用此模型池'}</button></div></article>)}
{poolEditing && <form className="mc-editor" aria-label="编辑模型池" onSubmit={event => { event.preventDefault(); void act(async () => { await api('/model-center/pools', pool); if (alive.current) setPoolEditing(false); }); }}><h3>模型池规则</h3><div className="mc-form-grid"><label>模型池名称<input required value={pool.name} onChange={event => setPool({ ...pool, name: event.target.value })} /></label><label>调度策略<select value={pool.strategy} onChange={event => setPool({ ...pool, strategy: event.target.value })}><option value="round-robin">顺序轮询</option><option value="weighted">权重轮询</option></select></label><label>单请求尝试上限<input type="number" min="1" max="8" value={pool.maxAttempts} onChange={event => setPool({ ...pool, maxAttempts: Number(event.target.value) })} /></label><label>排队上限(秒)<input type="number" min="1" max="60" value={pool.queueTimeoutMs / 1000} onChange={event => setPool({ ...pool, queueTimeoutMs: Number(event.target.value) * 1000 })} /></label></div><label className="mc-checkbox"><input type="checkbox" checked={pool.sticky} onChange={event => setPool({ ...pool, sticky: event.target.checked })} />同一运行优先保持连接;明确失败后才切换</label>
@@ -86,7 +131,7 @@ export function ModelCenter({ onConfig, onLegacy, busy }: { onConfig: (value: Co
{view.imports.length > 0 && <><h4>已登记来源</h4>{view.imports.map(value => <article className="mc-import-source" key={value.id}><strong>{value.source}</strong><code>{value.path}</code><span>{value.enabled ? '每分钟检查' : '自动同步已关闭'}</span>{value.lastCheckedAt && <p>最近检查 {new Date(value.lastCheckedAt).toLocaleString()}</p>}{value.lastError && <p className="mc-card-warning">{value.lastError}</p>}{!!value.lastResult?.conflicts?.length && <p className="mc-card-warning">有 {value.lastResult.conflicts.length} 项与手动修改冲突,已保留工作台中的修改。</p>}<button className="button secondary" disabled={locked} onClick={() => void act(async () => { await api('/model-center/import-toggle', { id: value.id, enabled: !value.enabled }); })}>{value.enabled ? '关闭自动同步' : '启用自动同步'}</button></article>)}<button className="button secondary" disabled={locked || !view.imports.some(value => value.enabled)} onClick={() => void act(async () => { const result = await api<{ results: { imported?: string[]; conflicts?: string[]; error?: string }[] }>('/model-center/import-sync', {}); const imported = result.results.reduce((sum, value) => sum + (value.imported?.length ?? 0), 0); const conflicts = result.results.reduce((sum, value) => sum + (value.conflicts?.length ?? 0), 0); if (alive.current) setNotice(`已检查启用来源:更新 ${imported} 项,冲突 ${conflicts} 项。`); })}>立即同步已启用来源</button></>}
{discovery.map(value => <article className="mc-import-source" key={value.source}><strong>{value.source}</strong><code>{value.path || '当前版本尚无可发现的配置路径'}</code><span>{value.available ? value.supported ? '可预览' : '当前不支持' : '未发现'}</span>{value.detail && <p>{value.detail}</p>}<button className="button secondary" disabled={!value.available || !value.supported || locked} onClick={() => { setImportSource(value.source); setImportPath(value.path); }}>选择来源</button></article>)}
<div className="mc-editor"><div className="mc-form-grid"><label>配置格式<select value={importSource} onChange={event => setImportSource(event.target.value)}><option value="ccswitch">CCSwitch SQLite</option><option value="workbench-json">工作台连接 JSON</option></select></label><label>本地文件路径<input value={importPath} onChange={event => { setImportPath(event.target.value); setPreview(null); }} /></label></div><button className="button secondary" disabled={locked || !importPath} onClick={() => void act(async () => { const value = await api<typeof preview>('/model-center/import-preview', { source: importSource, path: importPath }); if (alive.current) setPreview(value); })}>预览可导入连接</button></div>
{preview && <div className="mc-editor"><h3>本次预览</h3>{preview.entries.map(value => <p key={value.id}>{value.name} · {value.model} · {value.baseUrl} · {value.hasKey ? '含临时凭据' : '无凭据'}</p>)}{preview.notices.map((value, index) => <p className="mc-help" key={index}>{value}</p>)}<button className="button primary" disabled={locked || !preview.entries.length} onClick={() => void act(async () => { await api('/model-center/import-apply', { previewId: preview.id }); if (alive.current) { setPreview(null); setNotice('已导入可支持的连接。临时凭据只在本次宿主内存中。'); } })}>导入这些连接</button></div>}
{preview && <div className="mc-editor"><h3>本次预览</h3>{preview.entries.map(value => <p key={value.id}>{value.name} · {value.model} · {value.baseUrl} · {value.hasKey ? '含临时凭据' : '无凭据'}</p>)}{preview.notices.map((value, index) => <p className="mc-help" key={index}>{value}</p>)}<label className="mc-checkbox"><input type="checkbox" checked={persistImports} onChange={event => setPersistImports(event.target.checked)} />本机加密保存本次确认导入的凭据</label><button className="button primary" disabled={locked || !preview.entries.length} onClick={() => void act(async () => { await api('/model-center/import-apply', { previewId: preview.id, persistCredentials: persistImports }); if (alive.current) { setPreview(null); setNotice(persistImports ? '连接与本次确认导入的加密凭据已共同保存。' : '已导入可支持的连接。临时凭据只在本次宿主内存中。'); } })}>导入这些连接</button></div>}
</>}
{tab === 'operations' && <><div className="mc-section-title"><div><h3>运行巡检</h3><p>核对真实宿主、数据与近期工件,不发送模型请求。</p></div><button className="button primary" disabled={working} onClick={() => void act(inspect)}><Activity size={15} />开始本地巡检</button></div><label className="mc-checkbox"><input type="checkbox" checked={autoInspect} onChange={event => setAutoInspect(event.target.checked)} />在此页面每30秒检查,离开即停止</label>{operations ? <><p className="mc-help">{new Date(operations.checkedAt).toLocaleString()} · v{operations.version} · {operations.activeTasks} 活动任务 · {operations.queue} 排队</p><div className="mc-checks">{operations.checks.map(value => <article key={value.id}><span className={'mc-state mc-state-' + value.status}>{states[value.status] || value.status}</span><div><h4>{value.title}</h4><p>{value.detail}</p></div></article>)}</div><p className="mc-help">{operations.scope}</p></> : <p className="mc-empty">执行一次本地检查,查看实际结果与检查范围。</p>}</>}
</div>}
+28
View File
@@ -0,0 +1,28 @@
import path from 'node:path';
import { execFileSync } from 'node:child_process';
import { projectEnvironment } from '../process-environment.mjs';
export const credentialError = (message, code = 'CREDENTIAL_UNAVAILABLE', status = 409) => Object.assign(new Error(message), { code, status });
// The command and environment contain no credential. Both directions travel
// over private pipes as ASCII frames; raw child output is never logged.
function transform(action, bytes, entropy) {
if (process.platform !== 'win32') throw credentialError('本机加密凭据仅支持Windows用户级DPAPI。', 'CREDENTIAL_PLATFORM_UNSUPPORTED');
if (!Buffer.isBuffer(bytes) || bytes.length > 128000 || !Buffer.isBuffer(entropy) || entropy.length !== 32) throw credentialError('加密凭据输入无效。');
const script = "$ErrorActionPreference='Stop';$ProgressPreference='SilentlyContinue';Add-Type -AssemblyName System.Security;"
+ '$awbInput=[Console]::In.ReadToEnd()|ConvertFrom-Json;'
+ '$awbBytes=[Convert]::FromBase64String($awbInput.bytes);$awbEntropy=[Convert]::FromBase64String($awbInput.entropy);'
+ 'try{$awbOutput=[Security.Cryptography.ProtectedData]::' + action + '($awbBytes,$awbEntropy,[Security.Cryptography.DataProtectionScope]::CurrentUser);'
+ '[Console]::Out.Write([Convert]::ToBase64String($awbOutput))}'
+ 'finally{[Array]::Clear($awbBytes,0,$awbBytes.Length);[Array]::Clear($awbEntropy,0,$awbEntropy.Length);if($awbOutput){[Array]::Clear($awbOutput,0,$awbOutput.Length)}}';
try {
const output = execFileSync(path.join(process.env.SystemRoot || 'C:\\Windows', 'System32/WindowsPowerShell/v1.0/powershell.exe'),
['-NoProfile', '-NonInteractive', '-EncodedCommand', Buffer.from(script, 'utf16le').toString('base64')],
{ input: JSON.stringify({ bytes: bytes.toString('base64'), entropy: entropy.toString('base64') }), encoding: 'utf8',
windowsHide: true, stdio: ['pipe', 'pipe', 'pipe'], timeout: 15000, maxBuffer: 256000, env: projectEnvironment() }).trim();
if (!/^[A-Za-z0-9+/]+={0,2}$/.test(output) || output.length > 200000) throw new Error('Invalid response');
return Buffer.from(output, 'base64');
} catch { throw credentialError('本机加密凭据无法处理,请核对Windows用户、数据目录或保存块。'); }
}
export const protectCredential = (bytes, entropy) => transform('Protect', bytes, entropy);
export const unprotectCredential = (bytes, entropy) => transform('Unprotect', bytes, entropy);
+2 -1
View File
@@ -67,7 +67,7 @@ export class ConfigImporter {
this.previews.set(id, { source, path: path.resolve(filename), created: Date.now(), ...contents });
return { id, entries: contents.entries.map(({ apiKey, sourceId, origin, ...value }, index) => ({ ...value, id: String(index), hasKey: !!apiKey })), notices: contents.notices, expiresInMs: 300000 };
}
apply(id, autoSync) {
apply(id, autoSync, persistCredentials = false) {
const preview = this.previews.get(id);
if (!preview || Date.now() - preview.created > 300000) throw new Error('导入预览已过期,请重新预览。');
const current = this.read(preview.source, preview.path);
@@ -79,6 +79,7 @@ export class ConfigImporter {
const previous = this.hub.state.connections.find(value => value.importOrigin === item.origin);
if (previous && previous.importRevision !== previous.revision) { conflicts.push(previous.name); continue; }
const value = this.hub.upsert({ ...(previous ?? {}), ...item, id: previous?.id, revision: previous?.revision, enabled: previous ? previous.enabled : true,
persistKey: persistCredentials === true && !!item.apiKey,
...(item.apiKey ? { apiKey: item.apiKey } : { apiKey: '' }) });
const stored = this.hub.connection(value.id); stored.source = preview.source; stored.importOrigin = item.origin; stored.importRevision = stored.revision;
imported.push(value.id);
+78
View File
@@ -0,0 +1,78 @@
import fs from 'node:fs';
import { createHash } from 'node:crypto';
import { canonicalHost } from '../../shared/contracts/desktop-host.mjs';
import { observeWindowsProcess } from '../desktop/process-identity.mjs';
import { assertLocalTree } from '../desktop/file-state.mjs';
import { protectCredential, unprotectCredential, credentialError } from '../desktop/windows-dpapi.mjs';
const metadata = 'modelCredentials';
const sha = value => createHash('sha256').update(value).digest('hex');
const empty = () => ({ schema: 1, revision: 0, entries: {} });
export class CredentialVault {
constructor(store, provider, { protect = protectCredential, unprotect = unprotectCredential } = {}) {
this.store = store; this.provider = provider; this.protect = protect; this.unprotect = unprotect; this.issues = new Map();
assertLocalTree(store.directory); this.dataIdentity = sha(fs.realpathSync.native(store.directory).toLowerCase());
this.userSid = process.platform === 'win32' ? observeWindowsProcess(process.pid).userSid : null;
this.reload();
}
reload() {
const state = this.store.storage.meta(metadata, empty());
this.blocked = !state || state.schema !== 1 || !Number.isSafeInteger(state.revision) || !state.entries || typeof state.entries !== 'object' || Array.isArray(state.entries) || Object.keys(state.entries).length > 101;
this.state = this.blocked ? empty() : state;
}
binding(connection) {
return sha(JSON.stringify(canonicalHost({ app: 'agent-workbench', scope: 'Windows.CurrentUser', userSid: this.userSid,
dataIdentity: this.dataIdentity, connectionId: connection.id, connectionRevision: connection.revision,
protocol: connection.protocol, baseUrl: connection.baseUrl, model: connection.model, requiresKey: connection.requiresKey })));
}
status(connection) {
if (this.blocked) return { status: 'unavailable', storage: 'windows-user-dpapi', message: '本机保存登记格式损坏或来自新版本,未覆盖原记录。' };
const value = this.state.entries[connection.id];
if (!value) return { status: 'not_saved', storage: 'memory', message: '当前凭据只在宿主内存中。' };
const issue = value.userSid !== this.userSid ? 'user_mismatch' : value.dataIdentity !== this.dataIdentity ? 'directory_mismatch'
: value.connectionRevision !== connection.revision || value.bindingSha256 !== this.binding(connection) ? 'source_changed'
: this.issues.get(connection.id);
return { storage: 'windows-user-dpapi', status: issue ?? (value.enabled ? 'saved' : 'disabled'), enabled: value.enabled === true,
connectionRevision: value.connectionRevision, credentialRevision: value.credentialRevision, savedAt: value.savedAt,
message: issue ? '原保存块无法用于当前连接;重新填写后保存,或删除原保存。' : value.enabled ? '当前Windows用户可在宿主重启后加载。' : '已关闭自动加载;本次内存连接保留。' };
}
view(hub) { return { supported: process.platform === 'win32', storage: 'windows-user-dpapi', revision: this.state.revision, unavailable: this.blocked,
connections: hub.connections().map(connection => ({ id: connection.id, name: connection.name, revision: connection.revision, ...this.status(connection) })),
scope: '仅处理用户明确新填或确认导入的凭据;不会提取原内存连接。密文与连接登记在同一SQLite事务提交。' }; }
prepare(connection, explicitKey, credentialRevision) {
if (this.blocked) throw credentialError('原保存登记无法核对;请保留原数据并修复登记后保存。');
if (typeof explicitKey !== 'string' || !explicitKey.trim() || explicitKey.length > 16000) throw credentialError('加密保存需要重新填写API Key。', 'CREDENTIAL_INPUT_REQUIRED', 400);
const bindingSha256 = this.binding(connection), plain = Buffer.from(JSON.stringify({ schema: 1, bindingSha256, credentialRevision, key: explicitKey.trim() }), 'utf8');
let protectedBytes;
try { protectedBytes = this.protect(plain, Buffer.from(bindingSha256, 'hex')); }
finally { plain.fill(0); }
try { return { schema: 1, connectionId: connection.id, connectionRevision: connection.revision, credentialRevision,
userSid: this.userSid, dataIdentity: this.dataIdentity, bindingSha256, enabled: true, savedAt: new Date().toISOString(), ciphertext: protectedBytes.toString('base64') }; }
finally { protectedBytes.fill(0); }
}
stage(id, record) {
if (this.blocked) throw credentialError('本机保存登记无法核对。');
this.state = structuredClone(this.state); this.state.revision++;
if (record) this.state.entries[id] = record; else delete this.state.entries[id];
this.store.storage.setMeta(metadata, this.state); this.issues.delete(id);
}
restore(hub) {
for (const connection of hub.connections()) {
const record = this.state.entries[connection.id]; if (!record || this.status(connection).status !== 'saved') continue;
// Never overwrite or persist credentials already resident in this host.
if (connection.id === 'legacy-default' ? this.provider.hasKey() : this.provider.credentials.has(connection.id)) continue;
let plain;
try {
if (record.schema !== 1 || record.connectionId !== connection.id || !Number.isSafeInteger(record.credentialRevision) || record.credentialRevision < 1
|| typeof record.ciphertext !== 'string' || record.ciphertext.length > 200000 || !/^[A-Za-z0-9+/]+={0,2}$/.test(record.ciphertext)) throw new Error('Invalid saved block');
plain = this.unprotect(Buffer.from(record.ciphertext, 'base64'), Buffer.from(record.bindingSha256, 'hex'));
const payload = JSON.parse(plain.toString('utf8'));
if (payload.schema !== 1 || payload.bindingSha256 !== this.binding(connection) || payload.credentialRevision !== record.credentialRevision
|| typeof payload.key !== 'string' || !payload.key || payload.key.length > 16000) throw new Error('Invalid decrypted binding');
if (connection.id === 'legacy-default') { this.provider.setKey(payload.key); this.provider.legacyCredentialRevision = record.credentialRevision; }
else this.provider.credentials.set(connection.id, { key: payload.key, revision: record.credentialRevision });
} catch { this.issues.set(connection.id, 'decrypt_failed'); }
finally { plain?.fill(0); }
}
}
}
+40 -2
View File
@@ -1,6 +1,7 @@
import { randomUUID, createHash } from 'node:crypto';
import { setTimeout as delay } from 'node:timers/promises';
import { ModelRequestError } from '../../server/diagnostics.mjs';
import { CredentialVault } from './credential-vault.mjs';
const legacyId = 'legacy-default';
const stamp = () => new Date().toISOString();
@@ -25,6 +26,7 @@ export class ModelHub {
for (const attempt of this.attempts) if (attempt.status === 'running') { attempt.status = 'unknown'; attempt.finishedAt = stamp(); attempt.reason = '宿主重启,请求结果与用量待核对。'; recovered = true; }
if (recovered) this.saveAttempts();
provider.credentials ??= new Map();
if (store.storage.meta('modelCredentials', null)) this.vault().restore(this);
}
save(config = null) {
this.state.revision++;
@@ -46,6 +48,8 @@ export class ModelHub {
editRegistry(action) {
if (this.editingRegistry) return action();
const before = structuredClone(this.state), credentials = new Map(this.provider.credentials);
const originalKey = this.provider.apiKey, legacyRevision = this.provider.legacyCredentialRevision;
const vaultIssues = this.credentialVault ? new Map(this.credentialVault.issues) : null;
this.editingRegistry = true;
try {
return this.store.storage.transaction(() => {
@@ -57,6 +61,9 @@ export class ModelHub {
this.state = before;
this.provider.credentials.clear();
for (const [id, value] of credentials) this.provider.credentials.set(id, value);
this.provider.apiKey = originalKey; this.provider.legacyCredentialRevision = legacyRevision;
this.credentialVault?.reload();
if (vaultIssues) this.credentialVault.issues = vaultIssues;
throw cause;
} finally { this.editingRegistry = false; }
}
@@ -66,21 +73,48 @@ export class ModelHub {
model: this.store.config.model, enabled: true, requiresKey: false, revision: this.store.config.configRevision ?? 1,
contextLimit: this.store.config.contextLimit, maxOutputTokens: this.store.config.maxOutputTokens, concurrency: 1, source: 'legacy' }, ...this.state.connections];
}
credential(connection) { return connection.id === legacyId ? { key: this.provider.apiKey, revision: 1 } : this.provider.credentials.get(connection.id); }
credential(connection) { return connection.id === legacyId ? { key: this.provider.apiKey, revision: this.provider.legacyCredentialRevision ?? 1 } : this.provider.credentials.get(connection.id); }
vault() { return this.credentialVault ??= new CredentialVault(this.store, this.provider); }
manageCredential(input) {
const connection = this.connection(input.id);
if (input.revision !== connection.revision) throw error('模型连接已修改,请刷新凭据保存页面。', 409);
return this.editRegistry(() => {
const vault = this.vault(), previous = vault.state.entries[connection.id];
if (input.action === 'save') {
const revision = (this.credential(connection)?.revision ?? 0) + 1, record = vault.prepare(connection, input.apiKey, revision);
if (connection.id === legacyId) { this.provider.setKey(input.apiKey); this.provider.legacyCredentialRevision = revision; }
else this.provider.credentials.set(connection.id, { key: input.apiKey.trim(), revision });
vault.stage(connection.id, record);
} else if (input.action === 'delete' || input.action === 'forget') {
vault.stage(connection.id, null);
if (input.action === 'forget') {
if (connection.id === legacyId) { this.provider.setKey(''); this.provider.legacyCredentialRevision = (this.provider.legacyCredentialRevision ?? 1) + 1; }
else this.provider.credentials.set(connection.id, { key: '', revision: (this.credential(connection)?.revision ?? 0) + 1 });
}
} else if (input.action === 'disable' || input.action === 'enable') {
if (!previous) throw error('该连接没有本机保存块。');
vault.stage(connection.id, { ...previous, enabled: input.action === 'enable' });
if (input.action === 'enable') vault.restore(this);
} else throw error('凭据保存操作无效。');
this.save(); return { credential: vault.status(connection), center: this.view(), config: { ...this.store.config, hasKey: this.provider.hasKey() } };
});
}
identity(connection) { return connection.id + ':' + connection.revision + ':' + (this.credential(connection)?.revision ?? 0); }
status(connection) {
const credential = this.credential(connection), health = this.health.get(this.identity(connection));
const ready = connection.enabled && (!connection.requiresKey || !!credential?.key);
return { ...connection, hasKey: !!credential?.key, credentialRevision: credential?.revision ?? 0, credentialStorage: 'memory',
...(this.credentialVault ? { savedCredential: this.credentialVault.status(connection) } : {}),
status: !connection.enabled ? 'disabled' : !ready ? 'needs_key' : health?.blocked ? 'needs_attention' : health?.cooldownUntil > Date.now() ? 'cooling' : 'configured',
activeRequests: this.leases.get(connection.id) ?? 0, health: health ?? { state: 'unverified' },
capabilities: { tools: 'protocol_declared', vision: 'unknown', audio: 'unknown' } };
}
view() { return { revision: this.state.revision, selected: this.state.selected, connections: this.connections().map(value => this.status(value)), pools: this.state.pools,
imports: Object.entries(this.state.imports).map(([id, value]) => ({ id, ...value })), attempts: this.attempts.slice(-100).reverse(), waiting: this.waiting,
storage: { credentials: 'memory', restart: '临时凭据在宿主退出后需要重新填写。', attemptsRetained: 1000 } }; }
storage: { credentials: this.credentialVault ? 'memory-or-windows-user-dpapi' : 'memory', restart: '临时凭据在宿主退出后需要重新填写;已明确本机加密保存的连接按用户与原配置加载。', attemptsRetained: 1000 } }; }
connection(id) { const value = this.connections().find(item => item.id === id); if (!value) throw error('模型连接不存在。', 404); return value; }
upsert(input) {
if (!this.editingRegistry) return this.editRegistry(() => this.upsert(input));
if (input.id === legacyId) throw error('原连接请通过模型连接设置修改。');
const previous = input.id ? this.connection(input.id) : null;
if (this.state.connections.length >= 100 && !previous) throw error('最多保存100个模型连接。');
@@ -100,6 +134,10 @@ export class ModelHub {
this.state.connections = [...this.state.connections.filter(item => item.id !== connection.id), connection];
this.save();
if (Object.hasOwn(input, 'apiKey')) this.provider.credentials.set(connection.id, { key: input.apiKey.trim(), revision: (this.provider.credentials.get(connection.id)?.revision ?? 0) + 1 });
if (input.persistKey === true) {
const vault = this.vault(), record = vault.prepare(connection, input.apiKey, this.credential(connection)?.revision ?? 1);
vault.stage(connection.id, record);
}
return this.status(connection);
}
toggle(id, enabled) {
+3 -1
View File
@@ -138,16 +138,18 @@ return async (request, response) => {
const hub = provider.modelHub(store);
const importer = () => hub.importer ??= new ConfigImporter(hub);
if (method === 'GET' && route === '/api/model-center') return json(response, hub.view());
if (method === 'GET' && route === '/api/model-center/credentials') return json(response, hub.vault().view(hub));
if (method === 'GET' && route === '/api/model-center/imports') return json(response, importer().discover());
if (method === 'POST') {
const input = await body(request);
if (route === '/api/model-center/toggle') return json(response, hub.toggle(input.id, input.enabled));
if (runtime.hasActivity()) throw Object.assign(new Error('请先停止正在运行的任务,再修改或测试模型配置。'), { status: 409 });
if (route === '/api/model-center/credentials') return json(response, hub.manageCredential(input));
if (route === '/api/model-center/connections') return json(response, hub.upsert(input), 201);
if (route === '/api/model-center/pools') return json(response, hub.pool(input), 201);
if (route === '/api/model-center/select') return json(response, { center: hub.select(input), config: { ...store.config, hasKey: provider.hasKey() } });
if (route === '/api/model-center/import-preview') return json(response, importer().preview(input.source, String(input.path ?? '')));
if (route === '/api/model-center/import-apply') return json(response, importer().apply(input.previewId, input.autoSync));
if (route === '/api/model-center/import-apply') return json(response, importer().apply(input.previewId, input.autoSync, input.persistCredentials));
if (route === '/api/model-center/import-toggle') return json(response, importer().toggle(input.id, input.enabled));
if (route === '/api/model-center/import-sync') return json(response, { results: importer().sync(), center: hub.view() });
if (route === '/api/model-center/probe') {
+5 -1
View File
@@ -9,6 +9,7 @@ import { ConfigImporter } from '../core/models/config-import.mjs';
import { createRequestHandler, createSessionPublisher } from './app.mjs';
import { APP_VERSION } from './diagnostics.mjs';
import { hostAuthority } from '../core/desktop/host-authority.mjs';
import { CredentialVault } from '../core/models/credential-vault.mjs';
// Keep the existing objects and their in-memory connection. No credential is
// extracted, transferred, returned, or persisted by this operation.
@@ -25,7 +26,8 @@ export function installUpgrade(context, { appDirectory, updateServiceInfo = true
const oldAuthorityPrototype = oldAuthority ? Object.getPrototypeOf(oldAuthority) : null;
const oldPrototypes = [Object.getPrototypeOf(store), Object.getPrototypeOf(provider), Object.getPrototypeOf(runtime)];
const oldModelPrototypes = { hub: provider.hub ? Object.getPrototypeOf(provider.hub) : null,
importer: provider.hub?.importer ? Object.getPrototypeOf(provider.hub.importer) : null };
importer: provider.hub?.importer ? Object.getPrototypeOf(provider.hub.importer) : null,
vault: provider.hub?.credentialVault ? Object.getPrototypeOf(provider.hub.credentialVault) : null };
const oldStoreProperties = { ...store };
const oldRuntimeProperties = { appDirectory: runtime.appDirectory, workers: runtime.workers, controlledEngines: runtime.controlledEngines, checks: runtime.checks, deliveries: runtime.deliveries, codeIndex: runtime.codeIndex, changeSets: runtime.changeSets, contextPlans: runtime.contextPlans, workspaces: runtime.workspaces, research: runtime.research, engines: runtime.engines, browser: runtime.browser, taskPlans: runtime.taskPlans, projectMemories: runtime.projectMemories, taskCheckpoints: runtime.taskCheckpoints, skills: runtime.skills, mcp: runtime.mcp };
const oldUpdates = store.listeners('update');
@@ -40,6 +42,7 @@ export function installUpgrade(context, { appDirectory, updateServiceInfo = true
if (provider.hub) {
Object.setPrototypeOf(provider.hub, ModelHub.prototype);
if (provider.hub.importer) Object.setPrototypeOf(provider.hub.importer, ConfigImporter.prototype);
if (provider.hub.credentialVault) Object.setPrototypeOf(provider.hub.credentialVault, CredentialVault.prototype);
}
runtime.appDirectory = root; runtime.workers = null; runtime.controlledEngines = null; runtime.checks = null; runtime.deliveries = null; runtime.codeIndex = null; runtime.changeSets = null; runtime.contextPlans = null; runtime.workspaces = null; runtime.research = null; runtime.engines = null; runtime.browser = null; runtime.taskPlans = null; runtime.projectMemories = null; runtime.taskCheckpoints = null; runtime.skills = null; runtime.mcp = null;
store.ensureStorage();
@@ -75,6 +78,7 @@ export function installUpgrade(context, { appDirectory, updateServiceInfo = true
Object.setPrototypeOf(store, oldPrototypes[0]); Object.setPrototypeOf(provider, oldPrototypes[1]); Object.setPrototypeOf(runtime, oldPrototypes[2]);
if (oldModelPrototypes.hub) Object.setPrototypeOf(provider.hub, oldModelPrototypes.hub);
if (oldModelPrototypes.importer) Object.setPrototypeOf(provider.hub.importer, oldModelPrototypes.importer);
if (oldModelPrototypes.vault) Object.setPrototypeOf(provider.hub.credentialVault, oldModelPrototypes.vault);
store.removeAllListeners('update'); for (const observer of oldUpdates) store.on('update', observer);
server.removeAllListeners('request'); for (const previous of oldHandlers) server.on('request', previous);
throw error;
+2 -2
View File
@@ -5,8 +5,8 @@
用户授权下一阶段全量开发并及时回顾。接续e634a25和正式1.14.0,在feat/desktop-host-1.15按PLAN-1.15的A–F六切片推进;正式服务使用原进程与Provider,开发和验证使用独立数据/端口与自有凭据。每切片回顾、专项验收和本地提交,最终独立源码/桌面安装/便携/保留状态升级全部通过后交付。
1. [complete] A:Windows实际SID/创建/程序/安装/数据目录与签名挑战,注册/并发锁/启动意图;49/49相关专项和9组真实隔离主机通过。原中文ACL编码/重复权限失败及验收字段失败保留,修正后新证据独立保存。关闭真实窗口留待C/E,A不宣称桌面交付;正式PID23172/1.14保持。
2. [in_progress] B:用户显式选择的Windows用户级加密凭据,保存/删除/关闭、损坏/来源修订失效与多连接事务回退;实际重启加载及无明文泄漏验证。
3. [pending] C:Electron隔离窗口和窄范围preload、项目选择及原文件/任务审查入口;实际窗口/刷新/关闭重开、导航/IPC/越界拒绝与390px兼容。
2. [complete] B:CurrentUser DPAPI密文与registry同一SQLite事务,显式新填/确认导入、保存/关闭/删除/清除及失败回退;21/21专项兼容、7组实际浏览器/重启/HTTP/明文扫描通过。实际PID28724→49924、原配置/密文/6表原行保持,2条恢复Key实际3次夹具响应通过。不同Windows账号未实际切换,仅SID拒绝/错误entropy/损坏实际验证;原UI无标签/环境依赖失败及布局截图保留。
3. [in_progress] C:Electron隔离窗口和窄范围preload、项目选择及原文件/任务审查入口;实际窗口/刷新/关闭重开、导航/IPC/越界拒绝与390px兼容。
4. [pending] D:固定依赖/清单、Windows安装与独立新目录更新、活动阻挡和失败回退;实际安装/更新/卸载演练及持久数据核对。
5. [pending] E:实际桌面Node/React/Python工程、原失败修复/审批/父审查/检查/Git与窗口/宿主生命周期及unknown不重放。
6. [pending] F:冻结代码/基准、完整回归/全部界面、独立源码/桌面安装/便携与保留状态升级,封存原日志/截图/失败、回顾和下一阶段计划。
+98
View File
@@ -0,0 +1,98 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import path from 'node:path';
import { randomBytes } from 'node:crypto';
import { fixture } from './helpers.mjs';
import { Store } from '../src/server/store.mjs';
import { Provider } from '../src/server/provider.mjs';
import { ConfigImporter } from '../src/core/models/config-import.mjs';
import { protectCredential, unprotectCredential } from '../src/core/desktop/windows-dpapi.mjs';
const create = f => { const provider = new Provider(); provider.setKey(''); return { provider, hub: provider.modelHub(f.store) }; };
const add = (hub, name, extra = {}) => hub.upsert({ name, model: name, baseUrl: 'http://127.0.0.1:12001/v1', apiKey: 'owned-vault-' + name, ...extra });
const reopen = f => { f.store.close(); const store = new Store(f.data); f.onCleanup(() => store.close()); const provider = new Provider(); provider.setKey(''); return { store, provider, hub: provider.modelHub(store) }; };
test('actual Windows CurrentUser DPAPI roundtrips owned UTF-8 and rejects damaged bytes and wrong entropy', () => {
const plain = Buffer.from('自有测试凭据 owned-key-only', 'utf8'), entropy = randomBytes(32), encrypted = protectCredential(plain, entropy);
assert.notDeepEqual(encrypted, plain); assert.deepEqual(unprotectCredential(encrypted, entropy), plain);
assert.throws(() => unprotectCredential(encrypted, randomBytes(32)), /无法处理/);
encrypted[encrypted.length - 1] ^= 255; assert.throws(() => unprotectCredential(encrypted, entropy), /无法处理/);
});
test('only explicitly supplied keys persist; new provider restores original revisions and public views contain no key', t => {
const f = fixture(t), { provider, hub } = create(f); provider.setKey('owned-unsaved-legacy');
const volatile = add(hub, 'volatile'), saved = add(hub, 'saved', { persistKey: true });
const ledger = f.store.storage.meta('modelCredentials'); assert.deepEqual(Object.keys(ledger.entries), [saved.id]);
assert.equal(hub.credential(saved).revision, ledger.entries[saved.id].credentialRevision);
assert.equal(JSON.stringify(ledger).includes('owned-vault-'), false); assert.equal(JSON.stringify(hub.vault().view(hub)).includes('owned-vault-'), false);
assert.equal(provider.apiKey, 'owned-unsaved-legacy');
const fresh = reopen(f); assert.equal(fresh.provider.hasKey(), false);
assert.equal(fresh.hub.status(fresh.hub.connection(volatile.id)).hasKey, false);
assert.equal(fresh.hub.credential(fresh.hub.connection(saved.id)).key, 'owned-vault-saved');
assert.equal(fresh.hub.credential(fresh.hub.connection(saved.id)).revision, hub.credential(saved).revision);
assert.equal(fresh.hub.vault().status(saved).status, 'saved');
});
test('registry and cipher commit failure restores original routing, keys, block and every database row', t => {
const f = fixture(t), { provider, hub } = create(f), saved = add(hub, 'before', { persistKey: true });
const originalState = structuredClone(hub.state), keyReference = provider.credentials.get(saved.id), block = f.store.storage.meta('modelCredentials');
const snapshot = () => ['metadata', 'projects', 'sessions', 'records', 'events', 'outbox'].map(table => f.store.storage.database.prepare('SELECT * FROM ' + table + ' ORDER BY rowid').all());
const originalRows = snapshot();
f.store.storage.faultInjector = point => { if (point === 'before_commit') throw new Error('owned vault commit failure'); };
assert.throws(() => hub.upsert({ ...saved, model: 'after', apiKey: 'owned-after-key', persistKey: true }), /owned vault commit failure/);
assert.deepEqual(hub.state, originalState); assert.equal(provider.credentials.get(saved.id), keyReference);
assert.deepEqual(hub.vault().state, block); assert.deepEqual(snapshot(), originalRows);
f.store.storage.faultInjector = null;
});
test('a two-key import with a protection failure rolls back all registry and cipher entries and retains its preview', t => {
const f = fixture(t), { hub } = create(f), vault = hub.vault(), importer = new ConfigImporter(hub), filename = path.join(f.root, 'owned-import.json');
fs.writeFileSync(filename, JSON.stringify({ schema: 1, connections: ['one', 'two'].map(name => ({ name, model: name, baseUrl: 'http://127.0.0.1:12002/v1', apiKey: 'owned-import-' + name })) }));
const preview = importer.preview('workbench-json', filename), state = structuredClone(hub.state); let calls = 0;
vault.protect = (bytes, entropy) => { if (++calls === 2) throw new Error('owned second protect failure'); return protectCredential(bytes, entropy); };
assert.throws(() => importer.apply(preview.id, false, true), /owned second protect failure/);
assert.deepEqual(hub.state, state); assert.deepEqual(vault.state.entries, {}); assert.equal(hub.provider.credentials.size, 0); assert.equal(importer.previews.has(preview.id), true);
vault.protect = protectCredential; const accepted = importer.apply(preview.id, false, true);
assert.equal(accepted.imported.length, 2); assert.equal(Object.keys(vault.state.entries).length, 2);
});
test('connection revision changes retain the original saved block and report a source mismatch on restart', t => {
const f = fixture(t), { hub } = create(f), original = add(hub, 'original', { persistKey: true }), block = structuredClone(hub.vault().state.entries[original.id]);
const changed = hub.upsert({ ...original, model: 'changed' }); assert.equal(hub.vault().status(changed).status, 'source_changed');
assert.deepEqual(hub.vault().state.entries[original.id], block);
const fresh = reopen(f); assert.equal(fresh.hub.status(fresh.hub.connection(original.id)).hasKey, false); assert.equal(fresh.hub.vault().status(fresh.hub.connection(original.id)).status, 'source_changed');
});
test('disable skips real restart loading, explicit enable restores, delete preserves memory and forget removes both', t => {
const f = fixture(t), { hub } = create(f), saved = add(hub, 'toggle', { persistKey: true });
hub.manageCredential({ id: saved.id, revision: saved.revision, action: 'disable' }); assert.equal(hub.status(saved).hasKey, true);
const fresh = reopen(f), connection = fresh.hub.connection(saved.id); assert.equal(fresh.hub.status(connection).hasKey, false); assert.equal(fresh.hub.vault().status(connection).status, 'disabled');
fresh.hub.manageCredential({ id: saved.id, revision: saved.revision, action: 'enable' }); assert.equal(fresh.hub.status(connection).hasKey, true);
fresh.hub.manageCredential({ id: saved.id, revision: saved.revision, action: 'delete' }); assert.equal(fresh.hub.status(connection).hasKey, true); assert.equal(fresh.hub.vault().status(connection).status, 'not_saved');
fresh.hub.manageCredential({ id: saved.id, revision: saved.revision, action: 'forget' }); assert.equal(fresh.hub.status(connection).hasKey, false);
});
test('corrupt saved block and another SID do not load; failures are visible without returning ciphertext or plaintext', t => {
const f = fixture(t), { hub } = create(f), saved = add(hub, 'corrupt', { persistKey: true });
const state = f.store.storage.meta('modelCredentials'); state.entries[saved.id].ciphertext = 'AAAA'; f.store.storage.transaction(() => f.store.storage.setMeta('modelCredentials', state));
const fresh = reopen(f), connection = fresh.hub.connection(saved.id); assert.equal(fresh.hub.status(connection).hasKey, false); assert.equal(fresh.hub.vault().status(connection).status, 'decrypt_failed');
const publicView = fresh.hub.vault().view(fresh.hub); assert.equal(JSON.stringify(publicView).includes('AAAA'), false); assert.equal(JSON.stringify(publicView).includes('owned-vault-corrupt'), false);
fresh.hub.vault().state.entries[saved.id].userSid = 'S-1-5-21-1-2-3-1000'; assert.equal(fresh.hub.vault().status(connection).status, 'user_mismatch');
});
test('legacy persistence requires a new explicit key and binds config and credential revisions; stale requests cannot save', t => {
const f = fixture(t), { provider, hub } = create(f), legacy = hub.connection('legacy-default'); provider.setKey('owned-original-memory');
assert.throws(() => hub.manageCredential({ id: legacy.id, revision: legacy.revision, action: 'save' }), /重新填写/); assert.equal(provider.apiKey, 'owned-original-memory');
assert.throws(() => hub.manageCredential({ id: legacy.id, revision: legacy.revision - 1, action: 'save', apiKey: 'owned-explicit' }), /刷新/);
hub.manageCredential({ id: legacy.id, revision: legacy.revision, action: 'save', apiKey: 'owned-explicit' });
const fresh = reopen(f); assert.equal(fresh.provider.apiKey, 'owned-explicit'); assert.equal(fresh.provider.legacyCredentialRevision, 2);
fresh.store.saveConfig({ model: 'new-model' }); assert.equal(fresh.hub.vault().status(fresh.hub.connection(legacy.id)).status, 'source_changed');
});
test('owned plaintext keys never reach SQLite pages, WAL, config or public execution exports', t => {
const f = fixture(t), { hub } = create(f), key = 'OWNED_VAULT_PLAINTEXT_SENTINEL_42fdbedc67b9420f'; add(hub, 'leak-check', { apiKey: key, persistKey: true });
const needles = [Buffer.from(key), Buffer.from(key, 'utf16le'), Buffer.from(Buffer.from(key).toString('base64'))];
for (const file of fs.readdirSync(f.data)) if (fs.statSync(path.join(f.data, file)).isFile()) { const bytes = fs.readFileSync(path.join(f.data, file)); for (const needle of needles) assert.equal(bytes.includes(needle), false, file); }
assert.equal(JSON.stringify(f.store.publicSession(f.session)).includes(key), false); assert.equal(JSON.stringify(hub.view()).includes(key), false);
});