dsh-workbench-host 0.6.5 → 0.8.0

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.
@@ -0,0 +1,84 @@
1
+ /** meta 键前缀:一个 action 一行,值只允许 "1"(开)/ "0"(关)。 */
2
+ export const AGENT_ACCESS_KEY_PREFIX = "config.wb-shell.actionAgent.";
3
+ /**
4
+ * 永久锁死的 action:无论 meta 怎么写都不允许 agent 调用。
5
+ * 开关自身必须在里面,否则「先解锁开关、再解锁一切」就绕过了整套限制。
6
+ */
7
+ export const AGENT_LOCKED_ACTIONS = new Set(["actions.setAgentAccess"]);
8
+ export function agentAccessKey(action) {
9
+ return AGENT_ACCESS_KEY_PREFIX + action;
10
+ }
11
+ const ON_VALUES = new Set(["1", "true", "on", "yes"]);
12
+ const OFF_VALUES = new Set(["0", "false", "off", "no"]);
13
+ /**
14
+ * 读本机覆盖。返回 failed=true 表示「读不到/值无效」,调用方必须按关闭处理(fail closed):
15
+ * 数据库故障时宁可 agent 调不到,也不能把用户关掉的 action 静默放行。
16
+ * db 为空只出现在纯 schema 测试里,此时按「没有覆盖」回默认值。
17
+ */
18
+ function readOverride(db, action) {
19
+ if (!db)
20
+ return { value: null, failed: false };
21
+ try {
22
+ const row = db.prepare("SELECT v FROM meta WHERE k = ?").get(agentAccessKey(action));
23
+ const raw = row && row.v !== undefined && row.v !== null ? String(row.v).trim().toLowerCase() : "";
24
+ if (raw === "")
25
+ return { value: null, failed: false };
26
+ if (ON_VALUES.has(raw))
27
+ return { value: true, failed: false };
28
+ if (OFF_VALUES.has(raw))
29
+ return { value: false, failed: false };
30
+ return { value: null, failed: true };
31
+ }
32
+ catch {
33
+ return { value: null, failed: true };
34
+ }
35
+ }
36
+ function writeMeta(db, key, value) {
37
+ if (value === null) {
38
+ db.prepare("DELETE FROM meta WHERE k = ?").run(key);
39
+ return;
40
+ }
41
+ db.prepare("INSERT INTO meta(k, v) VALUES(?, ?) ON CONFLICT(k) DO UPDATE SET v = excluded.v").run(key, value);
42
+ }
43
+ export function createAgentAccess(db) {
44
+ /**
45
+ * 硬锁:安全约束,agent 永远不可调用、界面也不能打开。
46
+ * 两个来源:宿主内置的永久锁定清单,或 action 自己声明 agentLocked:true。
47
+ */
48
+ function locked(action, def) {
49
+ return AGENT_LOCKED_ACTIONS.has(action) || Boolean(def && def.agentLocked === true);
50
+ }
51
+ /** action 定义的默认值:没声明 agentEnabled 就是允许 agent 调用;硬锁恒为关闭。 */
52
+ function declaredValue(action, def) {
53
+ if (locked(action, def))
54
+ return false;
55
+ return !def || def.agentEnabled !== false;
56
+ }
57
+ /** 本机覆盖;没写过返回 null,读失败/值无效返回 failed(调用方按关闭处理)。 */
58
+ function override(action) {
59
+ return readOverride(db, action);
60
+ }
61
+ /** 生效值:硬锁恒为 false;读不到覆盖时 fail closed;最后才是声明默认值。 */
62
+ function effective(action, def) {
63
+ if (locked(action, def))
64
+ return false;
65
+ const own = override(action);
66
+ if (own.failed)
67
+ return false;
68
+ return own.value === null ? declaredValue(action, def) : own.value;
69
+ }
70
+ /** 改开关:硬锁直接拒绝;与声明默认值相同时删掉覆盖行(不留脏 meta),否则写 "1"/"0"。 */
71
+ function set(action, def, agentEnabled) {
72
+ if (locked(action, def)) {
73
+ throw new Error("该 action 的 agent 调用被永久禁止(安全约束),界面也不能解锁:" + action);
74
+ }
75
+ const base = declaredValue(action, def);
76
+ if (agentEnabled === base) {
77
+ writeMeta(db, agentAccessKey(action), null);
78
+ return { agentEnabled: base, source: "declared" };
79
+ }
80
+ writeMeta(db, agentAccessKey(action), agentEnabled ? "1" : "0");
81
+ return { agentEnabled, source: "meta" };
82
+ }
83
+ return { locked, declaredValue, override, effective, set };
84
+ }
@@ -0,0 +1,64 @@
1
+ /**
2
+ * 四个由 invokeAction 最前面特殊分发的内置 action(注册表里没有它们的 execute,
3
+ * 也不能放进 META_ACTIONS,否则会被 META 通用分发吃掉)。
4
+ * 仍然要出现在 actions.list({ domain: "wb-shell" }) 里:界面要看得见、能配置它们的 agent 开关。
5
+ */
6
+ export const BUILTIN_ACTIONS = new Map([
7
+ [
8
+ "capabilities.list",
9
+ {
10
+ description: "列出每个业务插件记录什么、任务归属与首选 action;可按 domain 过滤。",
11
+ input: {
12
+ type: "object",
13
+ properties: { domain: { type: "string", description: "只看某个业务域 id,如 wb-addon-tasks" } },
14
+ },
15
+ execute: () => {
16
+ throw new Error("内置 action 由宿主特殊分发");
17
+ },
18
+ },
19
+ ],
20
+ [
21
+ "capabilities.get",
22
+ {
23
+ description: "查看单个业务插件的完整能力清单(记录内容、warnings、首选 action 与 action 列表)。",
24
+ input: {
25
+ type: "object",
26
+ properties: { domain: { type: "string", description: "业务域 id,如 wb-addon-tasks" } },
27
+ required: ["domain"],
28
+ },
29
+ execute: () => {
30
+ throw new Error("内置 action 由宿主特殊分发");
31
+ },
32
+ },
33
+ ],
34
+ [
35
+ "actions.list",
36
+ {
37
+ description: "列出已安装业务域的 action、参数与必填项;domain 过滤、detail=true 给全量 schema。",
38
+ input: {
39
+ type: "object",
40
+ properties: {
41
+ domain: { type: "string", description: "按域过滤(也可传 wb-shell 只看宿主 action)" },
42
+ detail: { type: "boolean", description: "true 时返回每个 action 的完整 input schema" },
43
+ },
44
+ },
45
+ execute: () => {
46
+ throw new Error("内置 action 由宿主特殊分发");
47
+ },
48
+ },
49
+ ],
50
+ [
51
+ "actions.help",
52
+ {
53
+ description: "查看单个 action 的完整 JSON Schema、参数说明与示例。",
54
+ input: {
55
+ type: "object",
56
+ properties: { action: { type: "string", description: "action 名,如 tasks.create" } },
57
+ required: ["action"],
58
+ },
59
+ execute: () => {
60
+ throw new Error("内置 action 由宿主特殊分发");
61
+ },
62
+ },
63
+ ],
64
+ ]);
@@ -1,5 +1,5 @@
1
1
  import { renderTaskTarget } from "./task-targets.js";
2
- export function createCapabilities({ domains, SHELL_VERSION, actionEntry, taskTargets }) {
2
+ export function createCapabilities({ domains, SHELL_VERSION, actionEntry, taskTargets, agentVisible }) {
3
3
  function findDomain(raw) {
4
4
  const key = String(raw ?? "").trim();
5
5
  if (!key)
@@ -123,7 +123,7 @@ export function createCapabilities({ domains, SHELL_VERSION, actionEntry, taskTa
123
123
  };
124
124
  }
125
125
  /** capabilities.list:聚合各插件“记录什么、首选哪个 action”,给 agent 做统一发现。 */
126
- async function capabilityListMeta(args) {
126
+ async function capabilityListMeta(args, origin = "ui") {
127
127
  const kind = args.kind === undefined || args.kind === null ? "" : String(args.kind).trim();
128
128
  const out = [];
129
129
  for (const rec of domains.values()) {
@@ -138,7 +138,9 @@ export function createCapabilities({ domains, SHELL_VERSION, actionEntry, taskTa
138
138
  error: rec.error,
139
139
  summary: cap.summary,
140
140
  source: cap.source,
141
- actionCount: rec.actions.size,
141
+ actionCount: origin === "agent"
142
+ ? [...rec.actions].filter(([action, def]) => agentVisible(action, def)).length
143
+ : rec.actions.size,
142
144
  requires: cap.requires ?? [],
143
145
  missingRequires: cap.missingRequires ?? [],
144
146
  records: cap.records.map((r) => ({
@@ -177,7 +179,7 @@ export function createCapabilities({ domains, SHELL_VERSION, actionEntry, taskTa
177
179
  return lines.join("\n");
178
180
  }
179
181
  /** capabilities.get:单个业务域的完整能力清单 + action 摘要(字段细节仍走 actions.help)。 */
180
- async function capabilityGetMeta(args) {
182
+ async function capabilityGetMeta(args, origin = "ui") {
181
183
  const name = String(args.domain ?? args.id ?? "").trim();
182
184
  if (!name)
183
185
  throw new Error("缺少 domain;先用 capabilities.list 查看可用业务域");
@@ -206,7 +208,10 @@ export function createCapabilities({ domains, SHELL_VERSION, actionEntry, taskTa
206
208
  missingRequires: cap.missingRequires ?? [],
207
209
  },
208
210
  source: cap.source,
209
- actions: [...rec.actions].map(([action, def]) => actionEntry(action, rec.def.id, def)),
211
+ // capabilities.get 也是 agent 的发现入口:被本机关闭的 action 不列给它(ui 仍看全量)。
212
+ actions: [...rec.actions]
213
+ .filter(([action, def]) => origin !== "agent" || agentVisible(action, def))
214
+ .map(([action, def]) => actionEntry(action, rec.def.id, def)),
210
215
  warnings: cap.warnings,
211
216
  };
212
217
  }
package/lib/index.js CHANGED
@@ -16,13 +16,14 @@ import { SyncClock, } from "./sync/sync.js";
16
16
  import { AuditLog } from "./infra/audit.js";
17
17
  import { createActions } from "./actions/actions.js";
18
18
  import { installNetwork } from "./infra/network.js";
19
+ import { createSearch } from "./infra/search.js";
19
20
  export const name = "dsh-workbench";
20
21
  export const inject = ["webServer", "tools", "connection"];
21
22
  /** 本地库与云端配置路径(05 文档约定目录)。 */
22
23
  const WB_HOME = process.env.WB_HOME ?? join(homedir(), ".dsh", "workbench");
23
24
  const CLOUD_DEFAULT = process.env.WB_CLOUD_URL ?? "http://127.0.0.1:8791";
24
25
  /** 宿主 API 版本:业务插件用它做兼容判断。 */
25
- export const SHELL_VERSION = "0.6.5";
26
+ export const SHELL_VERSION = "0.8.0";
26
27
  const DOMAIN_ID_RE = /^[a-z][a-z0-9_-]{2,63}$/;
27
28
  const ACTION_RE = /^[a-z][a-z0-9_-]*(?:\.[a-z][a-z0-9_-]*)+$/i;
28
29
  function loadCreds() {
@@ -97,6 +98,7 @@ export function apply(ctx) {
97
98
  const subscribers = new Set();
98
99
  const domains = new Map();
99
100
  const clock = new SyncClock();
101
+ const eventListeners = new Map();
100
102
  const emit = (event, data) => {
101
103
  for (const s of subscribers) {
102
104
  try {
@@ -106,8 +108,36 @@ export function apply(ctx) {
106
108
  /* 单个订阅者断开不影响其他订阅者 */
107
109
  }
108
110
  }
111
+ for (const key of [event, "*"]) {
112
+ const set = eventListeners.get(key);
113
+ if (!set)
114
+ continue;
115
+ for (const listener of set) {
116
+ try {
117
+ listener(data);
118
+ }
119
+ catch {
120
+ /* 单个插件监听器出错不影响其它监听器 */
121
+ }
122
+ }
123
+ }
109
124
  };
110
125
  const log = (...args) => console.warn("[dsh-workbench]", ...args);
126
+ // ── 跨域搜索:插件注册 provider,宿主只聚合,不读业务表 ──
127
+ const searchProviders = new Map();
128
+ function registerSearchProvider(provider) {
129
+ const id = String(provider?.domainId || "");
130
+ if (!id || typeof provider.search !== "function") {
131
+ log("registerSearchProvider 参数不合法", provider);
132
+ return () => { };
133
+ }
134
+ searchProviders.set(id, provider);
135
+ return () => {
136
+ if (searchProviders.get(id) === provider)
137
+ searchProviders.delete(id);
138
+ };
139
+ }
140
+ const search = createSearch(searchProviders, (...args) => log(...args));
111
141
  // 审计日志:本机行为账本;表初始化与过期清理失败都不应影响宿主启动。
112
142
  const audit = new AuditLog(state.db, () => clock.now());
113
143
  try {
@@ -137,6 +167,16 @@ export function apply(ctx) {
137
167
  },
138
168
  };
139
169
  }
170
+ const { invoke, actionNames, installTool, schemaSnapshot } = createActions({
171
+ domains,
172
+ SHELL_VERSION,
173
+ publicInfo,
174
+ audit,
175
+ clock,
176
+ emit,
177
+ db: state.db,
178
+ search,
179
+ });
140
180
  function registerAction(rec, action, def) {
141
181
  if (!ACTION_RE.test(action)) {
142
182
  throw new Error("非法 action 名(应形如 tasks.list):" + action);
@@ -152,7 +192,7 @@ export function apply(ctx) {
152
192
  log("业务域已注册,忽略重复注册", def.id);
153
193
  return () => { };
154
194
  }
155
- const rec = { def, actions: new Map(), error: null, dispose: null };
195
+ const rec = { def, actions: new Map(), hooks: new Map(), error: null, dispose: null };
156
196
  domains.set(def.id, rec);
157
197
  const setupApi = {
158
198
  addon: { id: def.id, version: def.version, dir: "" },
@@ -162,6 +202,26 @@ export function apply(ctx) {
162
202
  hasAddon: (id) => domains.has(id),
163
203
  action: (name, actionDef) => registerAction(rec, name, actionDef),
164
204
  tool: (name, actionDef) => registerAction(rec, name, actionDef),
205
+ call: (action, args) => invoke(action, args ?? {}, "plugin"),
206
+ on: (event, listener) => {
207
+ const key = String(event || "*");
208
+ let set = eventListeners.get(key);
209
+ if (!set) {
210
+ set = new Set();
211
+ eventListeners.set(key, set);
212
+ }
213
+ set.add(listener);
214
+ return () => {
215
+ set.delete(listener);
216
+ };
217
+ },
218
+ registerHook: (name, handler) => {
219
+ if (!/^[a-z][a-z0-9_-]{1,40}$/.test(String(name || ""))) {
220
+ throw new Error("非法 hook 名(小写字母开头,允许数字/_/-):" + name);
221
+ }
222
+ rec.hooks.set(String(name), handler);
223
+ },
224
+ registerSearchProvider,
165
225
  emit: (event, data) => emit("domain-event", { domainId: def.id, event, data: data ?? null }),
166
226
  now: () => clock.now(),
167
227
  markSyncDirty: (table) => {
@@ -214,14 +274,27 @@ export function apply(ctx) {
214
274
  function backupDomains() {
215
275
  return [...domains.values()].map((rec) => ({ def: rec.def, enabled: rec.error === null, error: rec.error }));
216
276
  }
217
- const { invoke, actionNames, installTool, schemaSnapshot } = createActions({ domains, SHELL_VERSION, publicInfo, audit, clock, emit, db: state.db });
218
277
  const host = {
219
278
  db: state.db,
220
279
  shellVersion: SHELL_VERSION,
221
280
  registerDomain,
222
281
  hasDomain: (id) => domains.has(id),
223
282
  listDomains,
224
- invoke,
283
+ call: (action, args) => invoke(action, args ?? {}, "plugin"),
284
+ invoke: (action, args, _origin) => invoke(action, args ?? {}, "plugin"),
285
+ on: (event, listener) => {
286
+ const key = String(event || "*");
287
+ let set = eventListeners.get(key);
288
+ if (!set) {
289
+ set = new Set();
290
+ eventListeners.set(key, set);
291
+ }
292
+ set.add(listener);
293
+ return () => {
294
+ set.delete(listener);
295
+ };
296
+ },
297
+ registerSearchProvider,
225
298
  actionNames,
226
299
  emit,
227
300
  log,
@@ -228,8 +228,8 @@ export class AuditLog {
228
228
  const action = String(input.action || "").trim();
229
229
  if (!action)
230
230
  return null;
231
- // 自举元 action 与审计自身不记
232
- if (action.startsWith("audit.") || action.startsWith("actions.") || action.startsWith("capabilities.")) {
231
+ // 自举元 action 与审计自身不记;显式 force 的安全事件(如改权限开关、被策略拦截)例外。
232
+ if (!input.force && (action.startsWith("audit.") || action.startsWith("actions.") || action.startsWith("capabilities."))) {
233
233
  return null;
234
234
  }
235
235
  if (!input.force && isReadAction(action) && !this.recordsReads())
@@ -82,18 +82,39 @@ function validateManifest(value) {
82
82
  modules,
83
83
  };
84
84
  }
85
- /** 导出选中的业务模块;任一模块失败则整体失败,避免产出缺数据的备份。 */
85
+ /**
86
+ * 导出选中的业务模块;任一模块失败则整体失败,避免产出缺数据的备份。
87
+ *
88
+ * moduleIds 为空(含 `all`)=全量导出:跳过没有 exportData 的域,并在 manifest.skipped 注明;
89
+ * 显式列表=调用方指定:未知模块或不可导出模块都拒绝,不静默丢数据。
90
+ */
86
91
  export async function createBackup(opts) {
87
- const wanted = opts.moduleIds && opts.moduleIds.length ? new Set(opts.moduleIds) : null;
88
- const selected = opts.domains.filter((d) => d.enabled && (!wanted || wanted.has(d.def.id)));
89
- if (!selected.length)
90
- throw new BackupError("没有可导出的模块");
92
+ const asked = (opts.moduleIds ?? []).filter((id) => id && id !== "all");
93
+ const wanted = asked.length ? new Set(asked) : null;
94
+ const known = new Map(opts.domains.map((d) => [d.def.id, d]));
91
95
  if (wanted) {
92
- const known = new Set(opts.domains.map((d) => d.def.id));
93
96
  for (const id of wanted)
94
97
  if (!known.has(id))
95
98
  throw new BackupError("模块未安装:" + id);
99
+ for (const id of wanted) {
100
+ const rec = known.get(id);
101
+ if (!rec.def.exportData)
102
+ throw new BackupError("模块未实现数据导出:" + rec.def.title, "not_exportable");
103
+ }
104
+ }
105
+ const selected = opts.domains.filter((d) => d.enabled && (!wanted || wanted.has(d.def.id)));
106
+ if (!selected.length) {
107
+ throw new BackupError(wanted ? "选中的模块都未启用,无法导出:" + asked.join(", ") : "没有可导出的模块");
96
108
  }
109
+ const skipped = wanted
110
+ ? []
111
+ : opts.domains
112
+ .filter((d) => d.enabled && typeof d.def.exportData !== "function")
113
+ .map((d) => ({ id: d.def.id, title: d.def.title, reason: "no-export" }));
114
+ // 全量导出只遍历能导出的域;显式列表在上面的校验里已保证都能导出。
115
+ const exportable = wanted ? selected : selected.filter((d) => typeof d.def.exportData === "function");
116
+ if (!exportable.length)
117
+ throw new BackupError("没有可导出的模块");
97
118
  const exportedAt = new Date().toISOString();
98
119
  const shellVersion = opts.shellVersion;
99
120
  const manifestBase = {
@@ -104,10 +125,8 @@ export async function createBackup(opts) {
104
125
  };
105
126
  const modules = [];
106
127
  const files = [];
107
- for (const rec of selected) {
128
+ for (const rec of exportable) {
108
129
  const def = rec.def;
109
- if (!def.exportData)
110
- throw new BackupError("模块未实现数据导出:" + def.title, "export");
111
130
  let data;
112
131
  try {
113
132
  data = await def.exportData({ shellVersion, formatVersion: BACKUP_FORMAT_VERSION, exportedAt });
@@ -130,7 +149,7 @@ export async function createBackup(opts) {
130
149
  sha256: sha256(buf),
131
150
  });
132
151
  }
133
- const manifest = { ...manifestBase, modules };
152
+ const manifest = skipped.length ? { ...manifestBase, modules, skipped } : { ...manifestBase, modules };
134
153
  files.unshift({ name: "manifest.json", data: Buffer.from(JSON.stringify(manifest, null, 2), "utf8") });
135
154
  const now = new Date();
136
155
  return { filename: "dsh-workbench-backup-" + stamp(now) + ".zip", buffer: zipCreate(files), manifest };
@@ -135,6 +135,74 @@ export function installNetwork({ ctx, state, saveCreds, clock, domains, emit, su
135
135
  syncBusy = false;
136
136
  }
137
137
  }
138
+ // ── HTTP:/workbench/hooks/*(外部入口,不经过 DSH connection 门)──
139
+ // 鉴权由业务插件负责(token/HMAC/IP);宿主只保证默认只监听本机回环。
140
+ ctx.effect?.(() => ctx.webServer?.register({
141
+ kind: "prefix",
142
+ path: "/workbench/hooks",
143
+ handler: async (req, res) => {
144
+ const send = (code, obj, headers = {}) => {
145
+ res.writeHead(code, { "content-type": "application/json", ...headers });
146
+ res.end(JSON.stringify(obj));
147
+ };
148
+ try {
149
+ const url = new URL(req.url ?? "", "http://local");
150
+ const p = url.pathname.replace(/^\/workbench\/hooks/, "");
151
+ const m = req.method ?? "GET";
152
+ if (m !== "POST" && m !== "GET")
153
+ return send(405, { ok: false, error: "method not allowed" });
154
+ const hookM = /^\/([^/]+)\/([^/]+)$/.exec(p);
155
+ if (!hookM)
156
+ return send(404, { ok: false, error: "no hook route " + p });
157
+ const domainId = decodeURIComponent(hookM[1]);
158
+ const hookName = decodeURIComponent(hookM[2]);
159
+ // 允许 /hooks/connector/inbound 这样的短域名;内部 id 仍是 wb-addon-connector。
160
+ const rec = domains.get(domainId) ?? domains.get("wb-addon-" + domainId);
161
+ const handler = rec?.hooks?.get(hookName);
162
+ if (!handler)
163
+ return send(404, { ok: false, error: "no hook " + domainId + "/" + hookName });
164
+ const remote = String(req.socket?.remoteAddress ?? "");
165
+ const loopback = remote === "127.0.0.1" || remote === "::1" || remote === "::ffff:127.0.0.1";
166
+ if (!loopback)
167
+ return send(403, { ok: false, error: "hook is local-only (use a reverse proxy)" });
168
+ const chunks = [];
169
+ let total = 0;
170
+ for await (const c of req) {
171
+ const buf = c;
172
+ total += buf.length;
173
+ if (total > 1024 * 1024)
174
+ return send(413, { ok: false, error: "body too large" });
175
+ chunks.push(buf);
176
+ }
177
+ const body = Buffer.concat(chunks.map((c) => Buffer.from(c)));
178
+ const out = await handler({
179
+ method: m,
180
+ path: p,
181
+ query: Object.fromEntries(url.searchParams),
182
+ headers: req.headers,
183
+ remoteAddress: remote,
184
+ body,
185
+ });
186
+ const status = Number(out?.status ?? 200);
187
+ const headers = out?.headers ?? {};
188
+ const payload = out?.body ?? { ok: true };
189
+ if (Buffer.isBuffer(payload) || payload instanceof Uint8Array) {
190
+ res.writeHead(status, { "content-type": "application/octet-stream", ...headers });
191
+ res.end(Buffer.from(payload));
192
+ return;
193
+ }
194
+ if (typeof payload === "string") {
195
+ res.writeHead(status, { "content-type": "text/plain; charset=utf-8", ...headers });
196
+ res.end(payload);
197
+ return;
198
+ }
199
+ send(status, payload, headers);
200
+ }
201
+ catch (e) {
202
+ return send(500, { ok: false, error: String((e && e.message) || e) });
203
+ }
204
+ },
205
+ }, "workbench-hooks"), "workbench-hooks");
138
206
  // ── HTTP:/workbench/api/*(同域 cookie 之外的连接门由 host connection.requestRejection 兜底)──
139
207
  ctx.effect?.(() => ctx.webServer?.register({
140
208
  kind: "prefix",
@@ -245,9 +313,9 @@ export function installNetwork({ ctx, state, saveCreds, clock, domains, emit, su
245
313
  }
246
314
  }
247
315
  if (p === "/backup/export" && m === "GET") {
316
+ const raw = url.searchParams.get("modules");
317
+ const ids = raw && raw !== "all" ? raw.split(",").map((x) => x.trim()).filter(Boolean) : null;
248
318
  try {
249
- const raw = url.searchParams.get("modules");
250
- const ids = raw && raw !== "all" ? raw.split(",").map((x) => x.trim()).filter(Boolean) : null;
251
319
  const backup = await createBackup({ domains: backupDomains(), shellVersion: SHELL_VERSION, moduleIds: ids });
252
320
  res.writeHead(200, {
253
321
  "content-type": "application/zip",
@@ -259,7 +327,12 @@ export function installNetwork({ ctx, state, saveCreds, clock, domains, emit, su
259
327
  return;
260
328
  }
261
329
  catch (e) {
262
- return send(500, { ok: false, error: String((e && e.message) || e) });
330
+ const err = e;
331
+ const code = err && err.name === "BackupError" && err.code ? String(err.code) : "export";
332
+ // 调用方可纠正的问题给 4xx(带 machine-readable code),导出执行期异常才算 500。
333
+ const status = code === "incompatible" ? 422 : code === "export" ? 500 : 400;
334
+ log("备份导出失败", code, ids && ids.length ? ids.join(",") : "all");
335
+ return send(status, { ok: false, code, error: String((e && e.message) || e) });
263
336
  }
264
337
  }
265
338
  if (p === "/backup/import" && m === "POST") {
@@ -0,0 +1,83 @@
1
+ const TIMEOUT_MS = 500;
2
+ const MAX_QUERY = 100;
3
+ function normalize(q) {
4
+ return String(q ?? "").trim().slice(0, MAX_QUERY);
5
+ }
6
+ function scoreHit(hit, q) {
7
+ const needle = q.toLowerCase();
8
+ const title = String(hit.title || "").toLowerCase();
9
+ let score = 0;
10
+ if (title === needle)
11
+ score = 100;
12
+ else if (title.startsWith(needle))
13
+ score = 80;
14
+ else if (title.includes(needle))
15
+ score = 60;
16
+ if (String(hit.snippet || "").toLowerCase().includes(needle))
17
+ score += 20;
18
+ if (hit.url)
19
+ score += 1;
20
+ return score;
21
+ }
22
+ export function createSearch(providers, log = () => { }) {
23
+ function list() {
24
+ return [...providers.values()].map((p) => ({
25
+ domainId: p.domainId,
26
+ search: typeof p.search === "function",
27
+ })).filter((p) => p.search);
28
+ }
29
+ async function query(input) {
30
+ const started = Date.now();
31
+ const args = input && typeof input === "object" ? input : {};
32
+ const q = normalize(String(args.q ?? ""));
33
+ const limit = Math.max(1, Math.min(50, Number(args.limit) || 20));
34
+ const wanted = Array.isArray(args.domains)
35
+ ? args.domains.map(String).filter(Boolean)
36
+ : [];
37
+ if (!q)
38
+ return { q, items: [], domains: list().map((p) => p.domainId), partial: false, failed: [], tookMs: 0 };
39
+ const active = [...providers.values()].filter((p) => typeof p.search === "function" && (wanted.length === 0 || wanted.includes(p.domainId)));
40
+ const failed = [];
41
+ const batches = await Promise.all(active.map(async (provider) => {
42
+ let timer = null;
43
+ const timeout = new Promise((resolve) => {
44
+ timer = setTimeout(() => {
45
+ failed.push(provider.domainId);
46
+ resolve([]);
47
+ }, TIMEOUT_MS);
48
+ if (typeof timer.unref === "function")
49
+ timer.unref();
50
+ });
51
+ try {
52
+ const hits = await Promise.race([
53
+ Promise.resolve(provider.search(q, { limit })).then((x) => (Array.isArray(x) ? x : [])),
54
+ timeout,
55
+ ]);
56
+ return hits.map((hit) => ({ ...hit, domainId: provider.domainId }));
57
+ }
58
+ catch (error) {
59
+ failed.push(provider.domainId);
60
+ log("search provider failed", provider.domainId, error?.message);
61
+ return [];
62
+ }
63
+ finally {
64
+ if (timer)
65
+ clearTimeout(timer);
66
+ }
67
+ }));
68
+ const items = batches
69
+ .flat()
70
+ .filter((hit) => hit && hit.id && hit.title)
71
+ .map((hit) => ({ ...hit, score: scoreHit(hit, q) }))
72
+ .sort((a, b) => b.score - a.score || Number(b.at || 0) - Number(a.at || 0) || String(a.title).localeCompare(String(b.title)));
73
+ return {
74
+ q,
75
+ items: items.slice(0, limit * Math.max(1, active.length)).slice(0, 100),
76
+ domains: list().map((p) => p.domainId),
77
+ partial: failed.length > 0,
78
+ failed,
79
+ tookMs: Date.now() - started,
80
+ };
81
+ }
82
+ return { query, list };
83
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-workbench-host",
3
- "version": "0.6.5",
3
+ "version": "0.8.0",
4
4
  "type": "module",
5
5
  "main": "lib/index.js",
6
6
  "engines": {