@philomelcc/dsh-workbench 0.1.16 → 0.1.18
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +6 -0
- package/client.js +547 -2
- package/index.js +129 -7
- package/lib/dpapi.js +92 -0
- package/lib/tool.js +71 -0
- package/lib/tools.js +360 -0
- package/lib/vault.js +342 -0
- package/package.json +5 -1
package/index.js
CHANGED
|
@@ -1,14 +1,19 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Host half of the workbench shell.
|
|
3
3
|
*
|
|
4
|
-
*
|
|
5
|
-
*
|
|
6
|
-
*
|
|
7
|
-
*
|
|
8
|
-
*
|
|
9
|
-
*
|
|
4
|
+
* Two duties:
|
|
5
|
+
* 1. One-click restart: stops the running web host and lets an external
|
|
6
|
+
* supervisor start it again, so the current page simply reconnects. Only
|
|
7
|
+
* offered when such a supervisor is actually present — exiting without one
|
|
8
|
+
* would strand the user with a dead server.
|
|
9
|
+
* 2. Key vault: encrypted local secret storage plus the agent-facing tools
|
|
10
|
+
* (key_search / key_annotate / key_use). Values never leave the host in
|
|
11
|
+
* plaintext; endpoints under /wb/workbench/keys/* are local-only.
|
|
10
12
|
*/
|
|
11
13
|
import { execSync } from 'node:child_process';
|
|
14
|
+
import { createVault } from './lib/vault.js';
|
|
15
|
+
import { registerTools } from './lib/tools.js';
|
|
16
|
+
import { selfTest } from './lib/dpapi.js';
|
|
12
17
|
|
|
13
18
|
/** Supervisor that can start the host again, resolved per platform. */
|
|
14
19
|
function resolveSupervisor() {
|
|
@@ -37,7 +42,41 @@ function startSupervisor(supervisor) {
|
|
|
37
42
|
execSync(`schtasks /run /tn ${JSON.stringify(supervisor.task)}`, { windowsHide: true, stdio: 'ignore' });
|
|
38
43
|
}
|
|
39
44
|
|
|
40
|
-
export const inject = ['webServer'];
|
|
45
|
+
export const inject = ['webServer', 'tools', 'systemPrompt'];
|
|
46
|
+
|
|
47
|
+
const LOOPBACK = /^(::1|127\.0\.0\.1|::ffff:127\.0\.0\.1)$/;
|
|
48
|
+
|
|
49
|
+
function send(res, status, body) {
|
|
50
|
+
res.writeHead(status, {
|
|
51
|
+
'Content-Type': 'application/json; charset=utf-8',
|
|
52
|
+
'Cache-Control': 'no-store',
|
|
53
|
+
});
|
|
54
|
+
res.end(JSON.stringify(body));
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
function ok(res, payload) {
|
|
58
|
+
send(res, 200, { ok: true, at: Date.now(), ...payload });
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function fail(res, error, status = 400) {
|
|
62
|
+
send(res, status, { ok: false, error: error instanceof Error ? error.message : String(error) });
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
async function readJson(req) {
|
|
66
|
+
const chunks = [];
|
|
67
|
+
let size = 0;
|
|
68
|
+
for await (const chunk of req) {
|
|
69
|
+
size += chunk.length;
|
|
70
|
+
if (size > 256 * 1024) throw new Error('请求体过大');
|
|
71
|
+
chunks.push(chunk);
|
|
72
|
+
}
|
|
73
|
+
if (chunks.length === 0) return {};
|
|
74
|
+
try {
|
|
75
|
+
return JSON.parse(Buffer.concat(chunks).toString('utf8'));
|
|
76
|
+
} catch {
|
|
77
|
+
throw new Error('请求体不是合法 JSON');
|
|
78
|
+
}
|
|
79
|
+
}
|
|
41
80
|
|
|
42
81
|
export function apply(ctx) {
|
|
43
82
|
ctx.effect(() => ctx.webServer.register({
|
|
@@ -76,4 +115,87 @@ export function apply(ctx) {
|
|
|
76
115
|
}, 300);
|
|
77
116
|
},
|
|
78
117
|
}), 'workbench: restart route');
|
|
118
|
+
|
|
119
|
+
// ── 密钥库 ────────────────────────────────────────────────────────────
|
|
120
|
+
const vault = createVault();
|
|
121
|
+
|
|
122
|
+
let dpapiState = { ok: false, error: '' };
|
|
123
|
+
try {
|
|
124
|
+
dpapiState = { ok: selfTest(), error: '' };
|
|
125
|
+
if (!dpapiState.ok) dpapiState.error = 'DPAPI 自检未通过';
|
|
126
|
+
} catch (error) {
|
|
127
|
+
dpapiState = { ok: false, error: error instanceof Error ? error.message : String(error) };
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
registerTools(ctx, vault);
|
|
131
|
+
|
|
132
|
+
function route(path, handler) {
|
|
133
|
+
return ctx.effect(
|
|
134
|
+
() =>
|
|
135
|
+
ctx.webServer.register({
|
|
136
|
+
kind: 'exact',
|
|
137
|
+
path,
|
|
138
|
+
handler: async (req, res) => {
|
|
139
|
+
const remote = req.socket && req.socket.remoteAddress ? req.socket.remoteAddress : '';
|
|
140
|
+
if (!LOOPBACK.test(remote)) return fail(res, '只允许本机访问', 403);
|
|
141
|
+
try {
|
|
142
|
+
await handler(req, res);
|
|
143
|
+
} catch (error) {
|
|
144
|
+
fail(res, error);
|
|
145
|
+
}
|
|
146
|
+
},
|
|
147
|
+
}),
|
|
148
|
+
`workbench: ${path}`,
|
|
149
|
+
);
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
route('/wb/workbench/keys/list', async (_req, res) => {
|
|
153
|
+
ok(res, { items: vault.list(), stats: vault.stats(), dpapi: dpapiState });
|
|
154
|
+
});
|
|
155
|
+
|
|
156
|
+
route('/wb/workbench/keys/audit', async (req, res) => {
|
|
157
|
+
const url = new URL(req.url || '/', 'http://127.0.0.1');
|
|
158
|
+
const limit = Number(url.searchParams.get('limit')) || 100;
|
|
159
|
+
ok(res, { records: vault.audit(limit) });
|
|
160
|
+
});
|
|
161
|
+
|
|
162
|
+
route('/wb/workbench/keys/add', async (req, res) => {
|
|
163
|
+
const body = await readJson(req);
|
|
164
|
+
const item = await vault.add({
|
|
165
|
+
name: body.name,
|
|
166
|
+
purpose: body.purpose,
|
|
167
|
+
note: body.note,
|
|
168
|
+
tags: body.tags,
|
|
169
|
+
field: body.field,
|
|
170
|
+
value: body.value,
|
|
171
|
+
});
|
|
172
|
+
vault.appendAudit({ action: 'add', id: item.id, name: item.name, session: 'workbench' });
|
|
173
|
+
ok(res, { item });
|
|
174
|
+
});
|
|
175
|
+
|
|
176
|
+
route('/wb/workbench/keys/replace', async (req, res) => {
|
|
177
|
+
const body = await readJson(req);
|
|
178
|
+
const item = await vault.replace(String(body.id || ''), String(body.value || ''));
|
|
179
|
+
vault.appendAudit({ action: 'replace', id: item.id, name: item.name, session: 'workbench' });
|
|
180
|
+
ok(res, { item });
|
|
181
|
+
});
|
|
182
|
+
|
|
183
|
+
route('/wb/workbench/keys/annotate', async (req, res) => {
|
|
184
|
+
const body = await readJson(req);
|
|
185
|
+
const patch = {};
|
|
186
|
+
for (const key of ['name', 'purpose', 'note', 'field']) {
|
|
187
|
+
if (body[key] !== undefined) patch[key] = String(body[key]);
|
|
188
|
+
}
|
|
189
|
+
if (body.tags !== undefined) patch.tags = body.tags;
|
|
190
|
+
const item = await vault.annotate(String(body.id || ''), patch);
|
|
191
|
+
vault.appendAudit({ action: 'annotate', id: item.id, name: item.name, session: 'workbench' });
|
|
192
|
+
ok(res, { item });
|
|
193
|
+
});
|
|
194
|
+
|
|
195
|
+
route('/wb/workbench/keys/remove', async (req, res) => {
|
|
196
|
+
const body = await readJson(req);
|
|
197
|
+
const item = await vault.remove(String(body.id || ''));
|
|
198
|
+
vault.appendAudit({ action: 'remove', id: item.id, name: item.name, session: 'workbench' });
|
|
199
|
+
ok(res, { item });
|
|
200
|
+
});
|
|
79
201
|
}
|
package/lib/dpapi.js
ADDED
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Windows DPAPI 封装(CryptProtectData / CryptUnprotectData)。
|
|
3
|
+
*
|
|
4
|
+
* 为什么用它:密钥要能落盘但「顺手读文件」读不到明文。DPAPI 用当前 Windows
|
|
5
|
+
* 用户的凭据加密,密文只有同一用户能解——文件本身是密文,光 cat 出来是
|
|
6
|
+
* `01000000d08c9ddf…` 这种 blob。
|
|
7
|
+
*
|
|
8
|
+
* 局限(页面上也写了):同一用户身份下能主动调 API 的进程理论上可以解开,
|
|
9
|
+
* 所以这不是密码学意义上的隔离,只是把「直接读文件」这条路堵死。
|
|
10
|
+
*
|
|
11
|
+
* 走 koffi 做 FFI:实测加密 2ms、解密 <1ms、往返正确。
|
|
12
|
+
*/
|
|
13
|
+
import { createRequire } from 'node:module';
|
|
14
|
+
|
|
15
|
+
const require = createRequire(import.meta.url);
|
|
16
|
+
|
|
17
|
+
/** CRYPTPROTECT_UI_FORBIDDEN:任何情况下都不弹系统框。 */
|
|
18
|
+
const UI_FORBIDDEN = 0x1;
|
|
19
|
+
|
|
20
|
+
let cached = null;
|
|
21
|
+
|
|
22
|
+
function loadApi() {
|
|
23
|
+
if (cached) return cached;
|
|
24
|
+
if (process.platform !== 'win32') {
|
|
25
|
+
throw new Error('密钥库目前只支持 Windows(依赖 Windows DPAPI 加密)');
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
let koffi;
|
|
29
|
+
try {
|
|
30
|
+
koffi = require('koffi');
|
|
31
|
+
} catch (error) {
|
|
32
|
+
throw new Error(`密钥库无法加载 koffi(DPAPI 依赖):${error instanceof Error ? error.message : String(error)}`);
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
const crypt32 = koffi.load('crypt32.dll');
|
|
36
|
+
const kernel32 = koffi.load('kernel32.dll');
|
|
37
|
+
|
|
38
|
+
// struct 是 koffi 的全局注册表;插件热重载时可能已经定义过,重复定义会抛错。
|
|
39
|
+
try {
|
|
40
|
+
koffi.struct('DATA_BLOB', { cbData: 'uint32_t', pbData: 'uint8_t *' });
|
|
41
|
+
} catch {
|
|
42
|
+
/* 已注册,忽略 */
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
const CryptProtectData = crypt32.func(
|
|
46
|
+
'bool __stdcall CryptProtectData(DATA_BLOB *pDataIn, const char16_t *szDataDescr, DATA_BLOB *pOptionalEntropy, void *pvReserved, void *pPromptStruct, uint32_t dwFlags, _Out_ DATA_BLOB *pDataOut)',
|
|
47
|
+
);
|
|
48
|
+
const CryptUnprotectData = crypt32.func(
|
|
49
|
+
'bool __stdcall CryptUnprotectData(DATA_BLOB *pDataIn, _Out_ void **ppszDataDescr, DATA_BLOB *pOptionalEntropy, void *pvReserved, void *pPromptStruct, uint32_t dwFlags, _Out_ DATA_BLOB *pDataOut)',
|
|
50
|
+
);
|
|
51
|
+
const LocalFree = kernel32.func('void * __stdcall LocalFree(void *hMem)');
|
|
52
|
+
|
|
53
|
+
cached = { koffi, CryptProtectData, CryptUnprotectData, LocalFree };
|
|
54
|
+
return cached;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
function takeBlob(api, blob) {
|
|
58
|
+
const raw = api.koffi.decode(blob.pbData, 'uint8_t', blob.cbData);
|
|
59
|
+
api.LocalFree(blob.pbData);
|
|
60
|
+
return Buffer.from(raw);
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** 加密一段 UTF-8 文本,返回 DPAPI 密文(Buffer)。 */
|
|
64
|
+
export function protect(text) {
|
|
65
|
+
const api = loadApi();
|
|
66
|
+
const input = Buffer.from(String(text), 'utf8');
|
|
67
|
+
const inBlob = { cbData: input.length, pbData: input };
|
|
68
|
+
const out = {};
|
|
69
|
+
if (!api.CryptProtectData(inBlob, null, null, null, null, UI_FORBIDDEN, out)) {
|
|
70
|
+
throw new Error('DPAPI 加密失败(CryptProtectData 返回 false)');
|
|
71
|
+
}
|
|
72
|
+
return takeBlob(api, out);
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** 解开 protect() 产出的密文,返回 UTF-8 文本。 */
|
|
76
|
+
export function unprotect(cipher) {
|
|
77
|
+
const api = loadApi();
|
|
78
|
+
const input = Buffer.isBuffer(cipher) ? cipher : Buffer.from(cipher);
|
|
79
|
+
if (input.length === 0) throw new Error('密文为空');
|
|
80
|
+
const inBlob = { cbData: input.length, pbData: input };
|
|
81
|
+
const out = {};
|
|
82
|
+
if (!api.CryptUnprotectData(inBlob, null, null, null, null, UI_FORBIDDEN, out)) {
|
|
83
|
+
throw new Error('DPAPI 解密失败:这段密文不是由当前 Windows 用户加密的');
|
|
84
|
+
}
|
|
85
|
+
return takeBlob(api, out).toString('utf8');
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/** 只用来在启动时自检 DPAPI 是否可用,不碰任何真实密钥。 */
|
|
89
|
+
export function selfTest() {
|
|
90
|
+
const probe = 'dsh-keys-selftest';
|
|
91
|
+
return unprotect(protect(probe)) === probe;
|
|
92
|
+
}
|
package/lib/tool.js
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 极简 defineTool:把参数 DSL 编译成 JSON Schema,并做基本校验。
|
|
3
|
+
*
|
|
4
|
+
* 不 import `@deepseek-ai/dsh-tools` —— 插件以 link 方式安装时模块解析从
|
|
5
|
+
* 工作区物理路径开始,找不到 profile 里的 dsh 包。工具定义本身是普通对象,
|
|
6
|
+
* 只要字段齐全就能注册。
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
/** 把 `{ url: { type:'string', required:true, description } }` 编成 JSON Schema。 */
|
|
10
|
+
export function compileParameters(parameters = {}) {
|
|
11
|
+
const properties = {};
|
|
12
|
+
const required = [];
|
|
13
|
+
for (const [key, spec] of Object.entries(parameters)) {
|
|
14
|
+
const { required: isRequired, ...rest } = spec ?? {};
|
|
15
|
+
properties[key] = { ...rest };
|
|
16
|
+
if (isRequired === true) required.push(key);
|
|
17
|
+
}
|
|
18
|
+
return {
|
|
19
|
+
type: "object",
|
|
20
|
+
properties,
|
|
21
|
+
...(required.length > 0 ? { required } : {}),
|
|
22
|
+
additionalProperties: false,
|
|
23
|
+
};
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
function typeOf(value) {
|
|
27
|
+
if (value === null) return "null";
|
|
28
|
+
if (Array.isArray(value)) return "array";
|
|
29
|
+
if (typeof value === "number") return Number.isInteger(value) ? "integer" : "number";
|
|
30
|
+
return typeof value;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** 校验必填和基本类型;返回错误信息数组(空数组表示通过)。 */
|
|
34
|
+
export function validateArguments(schema, args) {
|
|
35
|
+
const violations = [];
|
|
36
|
+
const value = args && typeof args === "object" ? args : {};
|
|
37
|
+
for (const key of schema.required ?? []) {
|
|
38
|
+
if (value[key] === undefined || value[key] === null) violations.push(`缺少必填参数: ${key}`);
|
|
39
|
+
}
|
|
40
|
+
for (const [key, propSchema] of Object.entries(schema.properties ?? {})) {
|
|
41
|
+
const given = value[key];
|
|
42
|
+
if (given === undefined || given === null) continue;
|
|
43
|
+
const expected = propSchema.type;
|
|
44
|
+
if (!expected) continue;
|
|
45
|
+
const actual = typeOf(given);
|
|
46
|
+
const ok =
|
|
47
|
+
expected === "number" ? actual === "number" || actual === "integer" : actual === expected;
|
|
48
|
+
if (!ok) violations.push(`参数 ${key} 应为 ${expected},收到 ${actual}`);
|
|
49
|
+
}
|
|
50
|
+
return violations;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export function defineTool(options) {
|
|
54
|
+
const schema = compileParameters(options.parameters);
|
|
55
|
+
return {
|
|
56
|
+
name: options.name,
|
|
57
|
+
description: options.description,
|
|
58
|
+
parameters: schema,
|
|
59
|
+
output: options.output,
|
|
60
|
+
...(options.timeoutMs ? { timeoutMs: options.timeoutMs } : {}),
|
|
61
|
+
async execute(args, exec) {
|
|
62
|
+
const violations = validateArguments(schema, args);
|
|
63
|
+
if (violations.length > 0) {
|
|
64
|
+
const error = new Error(`参数不合法: ${violations.join("; ")}`);
|
|
65
|
+
error.code = "invalid_arguments";
|
|
66
|
+
throw error;
|
|
67
|
+
}
|
|
68
|
+
return await options.execute(args ?? {}, exec);
|
|
69
|
+
},
|
|
70
|
+
};
|
|
71
|
+
}
|
package/lib/tools.js
ADDED
|
@@ -0,0 +1,360 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Agent 工具:key_search / key_annotate / key_use。
|
|
3
|
+
*
|
|
4
|
+
* 铁律:任何工具的返回值里都不出现明文密钥。
|
|
5
|
+
* - search / annotate 只碰元数据;
|
|
6
|
+
* - use 在 host 内存里解出值、立刻用于请求,再把响应体里可能回显的密钥替换成 [redacted]。
|
|
7
|
+
*/
|
|
8
|
+
import { defineTool } from "./tool.js";
|
|
9
|
+
|
|
10
|
+
const HTTP_TIMEOUT_MS = 20000;
|
|
11
|
+
const MAX_BODY_BYTES = 64 * 1024;
|
|
12
|
+
|
|
13
|
+
function text(content) {
|
|
14
|
+
return [{ type: "text", text: content }];
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
function sessionTitleOf(ctx, exec) {
|
|
18
|
+
try {
|
|
19
|
+
const service = ctx.get?.("sessionTitle");
|
|
20
|
+
const session = exec?.agent?.session;
|
|
21
|
+
return service && session ? (service.get(session)?.title ?? null) : null;
|
|
22
|
+
} catch {
|
|
23
|
+
return null;
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** 已知格式的凭据前缀,兜底扫一遍响应体。 */
|
|
28
|
+
const CREDENTIAL_PATTERNS = [
|
|
29
|
+
/sk-[A-Za-z0-9_-]{20,}/g,
|
|
30
|
+
/ghp_[A-Za-z0-9]{20,}/g,
|
|
31
|
+
/github_pat_[A-Za-z0-9_]{20,}/g,
|
|
32
|
+
/AKIA[0-9A-Z]{16}/g,
|
|
33
|
+
/xox[bp]-[A-Za-z0-9-]{10,}/g,
|
|
34
|
+
/-----BEGIN [A-Z ]+-----[\s\S]*?-----END [A-Z ]+-----/g,
|
|
35
|
+
];
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* 把文本里出现的已知密钥值 + 常见凭据格式替换成 [redacted]。
|
|
39
|
+
* @returns {{ text: string, count: number }}
|
|
40
|
+
*/
|
|
41
|
+
export function redactText(input, secrets = []) {
|
|
42
|
+
let out = String(input ?? "");
|
|
43
|
+
let count = 0;
|
|
44
|
+
const list = [...new Set(secrets.filter((secret) => typeof secret === "string" && secret.length >= 8))].sort(
|
|
45
|
+
(a, b) => b.length - a.length,
|
|
46
|
+
);
|
|
47
|
+
for (const secret of list) {
|
|
48
|
+
if (!out.includes(secret)) continue;
|
|
49
|
+
out = out.split(secret).join("[redacted]");
|
|
50
|
+
count += 1;
|
|
51
|
+
}
|
|
52
|
+
for (const pattern of CREDENTIAL_PATTERNS) {
|
|
53
|
+
out = out.replace(pattern, () => {
|
|
54
|
+
count += 1;
|
|
55
|
+
return "[redacted]";
|
|
56
|
+
});
|
|
57
|
+
}
|
|
58
|
+
return { text: out, count };
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function headerView(headers) {
|
|
62
|
+
const out = {};
|
|
63
|
+
for (const [key, value] of headers.entries()) {
|
|
64
|
+
const name = key.toLowerCase();
|
|
65
|
+
if (name === "set-cookie" || name === "cookie") continue;
|
|
66
|
+
out[name] = value;
|
|
67
|
+
}
|
|
68
|
+
return out;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
function directionText(method, url) {
|
|
72
|
+
let host = url;
|
|
73
|
+
try {
|
|
74
|
+
host = new URL(url).host;
|
|
75
|
+
} catch {
|
|
76
|
+
/* keep raw */
|
|
77
|
+
}
|
|
78
|
+
return `${method} ${host}`;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
function itemLine(item) {
|
|
82
|
+
const parts = [item.name ? `【${item.name}】` : "", item.purpose ? `用途:${item.purpose}` : ""];
|
|
83
|
+
if (item.field) parts.push(`字段:${item.field}`);
|
|
84
|
+
if (item.note) parts.push(`备注:${item.note}`);
|
|
85
|
+
if (item.tags?.length) parts.push(`标签:${item.tags.join("/")}`);
|
|
86
|
+
parts.push(`id=${item.id}`);
|
|
87
|
+
parts.push(`预览=${item.masked}`);
|
|
88
|
+
if (item.lastUsedAt) parts.push(`上次使用:${item.lastUsedAt}`);
|
|
89
|
+
return parts.filter(Boolean).join(" · ");
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
export function registerTools(ctx, vault) {
|
|
93
|
+
const keySearch = defineTool({
|
|
94
|
+
name: "key_search",
|
|
95
|
+
description: [
|
|
96
|
+
"按用途 / 备注 / 名称 / 标签检索本机密钥库,返回条目清单。",
|
|
97
|
+
"返回值只有元数据与掩码预览,**永远不含明文**,也不要去尝试读取明文。",
|
|
98
|
+
"需要某个服务(如阿里云、GitHub、某个 API)的密钥时,先用它按用途搜一次。",
|
|
99
|
+
"搜不到就请用户在「工作台 · 密钥」页添加,不要自己去翻文件或环境变量。",
|
|
100
|
+
].join(" "),
|
|
101
|
+
parameters: {
|
|
102
|
+
query: {
|
|
103
|
+
type: "string",
|
|
104
|
+
description: "检索词,匹配名称/用途/备注/标签,空格分隔多个词(全部命中)",
|
|
105
|
+
},
|
|
106
|
+
limit: { type: "number", description: "最多返回几条,默认 20" },
|
|
107
|
+
},
|
|
108
|
+
output: {
|
|
109
|
+
schema: {
|
|
110
|
+
type: "object",
|
|
111
|
+
additionalProperties: false,
|
|
112
|
+
properties: {
|
|
113
|
+
total: { type: "number" },
|
|
114
|
+
items: {
|
|
115
|
+
type: "array",
|
|
116
|
+
items: {
|
|
117
|
+
type: "object",
|
|
118
|
+
additionalProperties: false,
|
|
119
|
+
properties: {
|
|
120
|
+
id: { type: "string" },
|
|
121
|
+
name: { type: "string" },
|
|
122
|
+
purpose: { type: "string" },
|
|
123
|
+
note: { type: "string" },
|
|
124
|
+
field: { type: "string" },
|
|
125
|
+
tags: { type: "array", items: { type: "string" } },
|
|
126
|
+
masked: { type: "string" },
|
|
127
|
+
updatedAt: { type: "string" },
|
|
128
|
+
lastUsedAt: { type: "string" },
|
|
129
|
+
},
|
|
130
|
+
required: ["id", "name", "masked"],
|
|
131
|
+
},
|
|
132
|
+
},
|
|
133
|
+
},
|
|
134
|
+
required: ["total", "items"],
|
|
135
|
+
},
|
|
136
|
+
render(_args, value) {
|
|
137
|
+
if (value.total === 0) {
|
|
138
|
+
return text("密钥库里没有匹配的条目。请用户在「工作台 · 密钥」页添加。");
|
|
139
|
+
}
|
|
140
|
+
const lines = value.items.map((item) => itemLine(item));
|
|
141
|
+
const more =
|
|
142
|
+
value.total > value.items.length ? `\n(共 ${value.total} 条,只列出前 ${value.items.length} 条)` : "";
|
|
143
|
+
return text(`密钥库命中 ${value.total} 条:\n` + lines.join("\n") + more + "\n\n用 key_use 按 id 使用;用 key_annotate 改名称/用途/备注。");
|
|
144
|
+
},
|
|
145
|
+
},
|
|
146
|
+
async execute(args) {
|
|
147
|
+
const limit = Math.max(1, Math.min(Number(args.limit) || 20, 50));
|
|
148
|
+
const hits = vault.search(args.query);
|
|
149
|
+
const items = hits.slice(0, limit).map((item) => ({
|
|
150
|
+
id: item.id,
|
|
151
|
+
name: item.name,
|
|
152
|
+
purpose: item.purpose,
|
|
153
|
+
note: item.note,
|
|
154
|
+
field: item.field,
|
|
155
|
+
tags: item.tags,
|
|
156
|
+
masked: item.masked,
|
|
157
|
+
updatedAt: item.updatedAt,
|
|
158
|
+
lastUsedAt: item.lastUsedAt || "",
|
|
159
|
+
}));
|
|
160
|
+
return { total: hits.length, items };
|
|
161
|
+
},
|
|
162
|
+
});
|
|
163
|
+
|
|
164
|
+
const keyAnnotate = defineTool({
|
|
165
|
+
name: "key_annotate",
|
|
166
|
+
description: [
|
|
167
|
+
"给密钥库里的条目改名 / 改用途 / 写备注 / 换标签(只动元数据,不碰值)。",
|
|
168
|
+
"用户说「把那个 xxx 的密钥记成 yyy 用途」时用它。",
|
|
169
|
+
"至少传 id 和一项要改的字段。",
|
|
170
|
+
].join(" "),
|
|
171
|
+
parameters: {
|
|
172
|
+
id: { type: "string", required: true, description: "key_search 返回的条目 id" },
|
|
173
|
+
name: { type: "string", description: "新名称(≤60 字)" },
|
|
174
|
+
purpose: { type: "string", description: "用途,如「阿里云 OSS 上传」(≤60 字)" },
|
|
175
|
+
note: { type: "string", description: "备注,如「生产账号,只读」(≤400 字)" },
|
|
176
|
+
tags: { type: "array", items: { type: "string" }, description: "标签列表(≤8 个)" },
|
|
177
|
+
},
|
|
178
|
+
output: {
|
|
179
|
+
schema: {
|
|
180
|
+
type: "object",
|
|
181
|
+
additionalProperties: false,
|
|
182
|
+
properties: {
|
|
183
|
+
id: { type: "string" },
|
|
184
|
+
name: { type: "string" },
|
|
185
|
+
purpose: { type: "string" },
|
|
186
|
+
note: { type: "string" },
|
|
187
|
+
tags: { type: "array", items: { type: "string" } },
|
|
188
|
+
},
|
|
189
|
+
required: ["id", "name"],
|
|
190
|
+
},
|
|
191
|
+
render(_args, value) {
|
|
192
|
+
return text(
|
|
193
|
+
[
|
|
194
|
+
`已更新密钥条目 ${value.id}`,
|
|
195
|
+
`名称:${value.name}`,
|
|
196
|
+
value.purpose ? `用途:${value.purpose}` : "",
|
|
197
|
+
value.note ? `备注:${value.note}` : "",
|
|
198
|
+
value.tags?.length ? `标签:${value.tags.join("/")}` : "",
|
|
199
|
+
]
|
|
200
|
+
.filter(Boolean)
|
|
201
|
+
.join("\n"),
|
|
202
|
+
);
|
|
203
|
+
},
|
|
204
|
+
},
|
|
205
|
+
async execute(args) {
|
|
206
|
+
const patch = {};
|
|
207
|
+
for (const key of ["name", "purpose", "note"]) {
|
|
208
|
+
if (args[key] !== undefined) patch[key] = String(args[key]);
|
|
209
|
+
}
|
|
210
|
+
if (args.tags !== undefined) patch.tags = args.tags;
|
|
211
|
+
if (Object.keys(patch).length === 0) throw new Error("至少要改一项(name / purpose / note / tags)");
|
|
212
|
+
const item = await vault.annotate(String(args.id), patch);
|
|
213
|
+
vault.appendAudit({ action: "annotate", id: item.id, name: item.name, session: sessionTitleOf(ctx, {}) || "" });
|
|
214
|
+
return { id: item.id, name: item.name, purpose: item.purpose, note: item.note, tags: item.tags };
|
|
215
|
+
},
|
|
216
|
+
});
|
|
217
|
+
|
|
218
|
+
const keyUse = defineTool({
|
|
219
|
+
name: "key_use",
|
|
220
|
+
description: [
|
|
221
|
+
"用密钥库里的某条密钥代替你发一次 HTTP 请求——你给出 URL/方法/额外头/请求体,",
|
|
222
|
+
"host 在内存里解出密钥、拼进请求(默认 Authorization: Bearer),发出去后只把响应交给你。",
|
|
223
|
+
"你**不会**看到密钥本身;响应里若回显了密钥会被替换成 [redacted]。",
|
|
224
|
+
"适用:调第三方 REST API、验证密钥是否有效、上传/下载需要鉴权的内容。",
|
|
225
|
+
"需要跑命令行程序(gh/aws 等)时做不了,请让用户自己执行或改用 API。",
|
|
226
|
+
].join(" "),
|
|
227
|
+
parameters: {
|
|
228
|
+
id: { type: "string", required: true, description: "key_search 返回的条目 id" },
|
|
229
|
+
url: { type: "string", required: true, description: "完整请求 URL(含协议)" },
|
|
230
|
+
method: { type: "string", description: "HTTP 方法,默认 GET" },
|
|
231
|
+
auth: {
|
|
232
|
+
type: "string",
|
|
233
|
+
enum: ["bearer", "header", "query", "basic", "none"],
|
|
234
|
+
description: "密钥放哪:bearer(默认,Authorization: Bearer xxx)/ header(自定义头)/ query(URL 参数)/ basic(用户名:密钥)/ none",
|
|
235
|
+
},
|
|
236
|
+
headerName: { type: "string", description: "auth=header 时的头名,如 X-API-Key" },
|
|
237
|
+
queryParam: { type: "string", description: "auth=query 时的参数名,如 api_key" },
|
|
238
|
+
headers: {
|
|
239
|
+
type: "object",
|
|
240
|
+
description: "额外请求头(键值都是字符串);鉴权头由工具自己拼",
|
|
241
|
+
},
|
|
242
|
+
body: { type: "string", description: "请求体文本" },
|
|
243
|
+
contentType: { type: "string", description: "请求体类型,默认 application/json" },
|
|
244
|
+
},
|
|
245
|
+
output: {
|
|
246
|
+
schema: {
|
|
247
|
+
type: "object",
|
|
248
|
+
additionalProperties: false,
|
|
249
|
+
properties: {
|
|
250
|
+
ok: { type: "boolean" },
|
|
251
|
+
status: { type: "number" },
|
|
252
|
+
request: { type: "string" },
|
|
253
|
+
headers: { type: "object" },
|
|
254
|
+
body: { type: "string" },
|
|
255
|
+
truncated: { type: "boolean" },
|
|
256
|
+
redacted: { type: "number" },
|
|
257
|
+
error: { type: "string" },
|
|
258
|
+
},
|
|
259
|
+
required: ["ok", "status", "request"],
|
|
260
|
+
},
|
|
261
|
+
render(_args, value) {
|
|
262
|
+
if (!value.ok && value.error) {
|
|
263
|
+
return text(`请求失败(${value.request}):${value.error}`);
|
|
264
|
+
}
|
|
265
|
+
const lines = [
|
|
266
|
+
`${value.request} → HTTP ${value.status}`,
|
|
267
|
+
value.truncated ? "响应体已截断(超过 64 KiB)" : "",
|
|
268
|
+
value.redacted ? `响应里有 ${value.redacted} 处密钥回显,已替换成 [redacted]` : "",
|
|
269
|
+
"",
|
|
270
|
+
value.body || "(空响应体)",
|
|
271
|
+
].filter(Boolean);
|
|
272
|
+
return text(lines.join("\n"));
|
|
273
|
+
},
|
|
274
|
+
},
|
|
275
|
+
async execute(args) {
|
|
276
|
+
const id = String(args.id || "");
|
|
277
|
+
const url = String(args.url || "").trim();
|
|
278
|
+
if (!/^https?:\/\//i.test(url)) throw new Error("url 必须是 http(s) 地址");
|
|
279
|
+
const method = String(args.method || "GET").toUpperCase();
|
|
280
|
+
const { item, value: secret } = vault.reveal(id);
|
|
281
|
+
|
|
282
|
+
const headers = {};
|
|
283
|
+
for (const [key, value] of Object.entries(args.headers || {})) {
|
|
284
|
+
if (typeof value === "string") headers[key] = value;
|
|
285
|
+
}
|
|
286
|
+
let target = url;
|
|
287
|
+
const auth = String(args.auth || "bearer");
|
|
288
|
+
if (auth === "bearer") {
|
|
289
|
+
headers.authorization = `Bearer ${secret}`;
|
|
290
|
+
} else if (auth === "header") {
|
|
291
|
+
const name = String(args.headerName || item.field || "X-API-Key");
|
|
292
|
+
headers[name] = secret;
|
|
293
|
+
} else if (auth === "query") {
|
|
294
|
+
const name = String(args.queryParam || item.field || "api_key");
|
|
295
|
+
const parsed = new URL(target);
|
|
296
|
+
parsed.searchParams.set(name, secret);
|
|
297
|
+
target = parsed.toString();
|
|
298
|
+
} else if (auth === "basic") {
|
|
299
|
+
headers.authorization = `Basic ${Buffer.from(`:${secret}`).toString("base64")}`;
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
const init = { method, headers, redirect: "follow", signal: AbortSignal.timeout(HTTP_TIMEOUT_MS) };
|
|
303
|
+
if (args.body !== undefined && method !== "GET" && method !== "HEAD") {
|
|
304
|
+
init.body = String(args.body);
|
|
305
|
+
if (!Object.keys(headers).some((key) => key.toLowerCase() === "content-type")) {
|
|
306
|
+
headers["content-type"] = String(args.contentType || "application/json");
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
let response;
|
|
311
|
+
try {
|
|
312
|
+
response = await fetch(target, init);
|
|
313
|
+
} catch (error) {
|
|
314
|
+
const reason = error instanceof Error ? error.message : String(error);
|
|
315
|
+
vault.appendAudit({ action: "use", id: item.id, name: item.name, mode: "http", ok: false, error: reason });
|
|
316
|
+
return { ok: false, status: 0, request: directionText(method, url), error: reason };
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
const raw = Buffer.from(await response.arrayBuffer());
|
|
320
|
+
const truncated = raw.length > MAX_BODY_BYTES;
|
|
321
|
+
const bodyText = raw.subarray(0, MAX_BODY_BYTES).toString("utf8");
|
|
322
|
+
const { text: safeBody, count } = redactText(bodyText, [secret]);
|
|
323
|
+
const headerMap = headerView(response.headers);
|
|
324
|
+
const { text: safeHeadersText, count: headerCount } = redactText(JSON.stringify(headerMap), [secret]);
|
|
325
|
+
|
|
326
|
+
vault.touch(item.id, "http").catch(() => {});
|
|
327
|
+
|
|
328
|
+
return {
|
|
329
|
+
ok: response.ok,
|
|
330
|
+
status: response.status,
|
|
331
|
+
request: directionText(method, url),
|
|
332
|
+
headers: JSON.parse(safeHeadersText),
|
|
333
|
+
body: safeBody,
|
|
334
|
+
truncated,
|
|
335
|
+
redacted: count + headerCount,
|
|
336
|
+
};
|
|
337
|
+
},
|
|
338
|
+
});
|
|
339
|
+
|
|
340
|
+
ctx.effect(() => ctx.tools.register(keySearch), "keys: tool key_search");
|
|
341
|
+
ctx.effect(() => ctx.tools.register(keyAnnotate), "keys: tool key_annotate");
|
|
342
|
+
ctx.effect(() => ctx.tools.register(keyUse), "keys: tool key_use");
|
|
343
|
+
|
|
344
|
+
ctx.effect(
|
|
345
|
+
() =>
|
|
346
|
+
ctx.systemPrompt.section({
|
|
347
|
+
name: "key-vault",
|
|
348
|
+
order: 1000,
|
|
349
|
+
text: [
|
|
350
|
+
"本机有一个加密密钥库(工作台「密钥」页)。你需要某个服务的密钥时:",
|
|
351
|
+
"1. 先 key_search 按用途/备注检索;",
|
|
352
|
+
"2. 找到了就用 key_use 让 host 代发 HTTP 请求——你拿不到也看不到明文,不要去读 vault.json、.credentials.yaml 或环境变量;",
|
|
353
|
+
"3. 条目名称/用途/备注不合适时,用 key_annotate 整理(只改元数据);",
|
|
354
|
+
"4. 搜不到就请用户在「工作台 · 密钥」页粘贴添加,不要自己猜或复用别的密钥。",
|
|
355
|
+
"密钥库的文件是加密的:直接读只会得到密文,那属于无效尝试。",
|
|
356
|
+
].join("\n"),
|
|
357
|
+
}),
|
|
358
|
+
"keys: prompt section",
|
|
359
|
+
);
|
|
360
|
+
}
|