@sparkelf/dsh-dataops-managed 0.3.38 → 0.3.40

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/lib/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import { mkdir, readFile, rename, rm, stat, writeFile } from "node:fs/promises";
1
+ import { chmod, mkdir, readFile, rename, rm, stat, writeFile } from "node:fs/promises";
2
2
  import { fileURLToPath } from "node:url";
3
3
  import { credentialRef } from "@deepseek-ai/dsh-credentials";
4
4
  import * as McpClient from "@sparkelf/dsh-plugin-mcp-credentials";
@@ -901,7 +901,10 @@ const AI_TOOL_ACCESS = {
901
901
  capability: "resource.manage",
902
902
  adminOnly: true,
903
903
  defaultEnabled: true
904
- }
904
+ },
905
+ admin_workspace_restart: { superAdminOnly: true },
906
+ admin_workspace_tunnel_open: { superAdminOnly: true },
907
+ admin_workspace_tunnel_revoke: { superAdminOnly: true }
905
908
  };
906
909
  /** Every managed tool name, in the order the manager considers them. */
907
910
  const AI_TOOL_NAMES = Object.keys(AI_TOOL_ACCESS);
@@ -2734,6 +2737,177 @@ function buildAiManagementTools(ctx, reviewApi, readScope, collectHub) {
2734
2737
  ];
2735
2738
  }
2736
2739
  //#endregion
2740
+ //#region src/admin-workspace-tools.ts
2741
+ /**
2742
+ * 超管代维工作区(`admin-workspace-*`)。
2743
+ *
2744
+ * 只注册给超级管理员(`AI_TOOL_ACCESS` 里都是 `superAdminOnly`),每次调用还会再校验一次
2745
+ * scope —— 工具注册只是可见性,真正的闸门在服务端和这里的二次判定。
2746
+ *
2747
+ * **私钥红线**:`tunnel_open` 拿到的私钥**不返回正文**,而是写进工作区里的 0600 一次性文件,
2748
+ * 工具只返回文件路径与 `ssh -i` 命令。私钥因此不会进对话、日志或审计;`revoke` 与到期清理
2749
+ * 负责删文件与目录。
2750
+ */
2751
+ /** 工作区根目录(容器内是挂载卷;本机调试可用环境变量覆盖)。 */
2752
+ const workspaceRoot = () => process.env.DATAOPS_WORKSPACE_ROOT?.trim() || "/workspace";
2753
+ /** 隧道私钥目录:`<workspace>/.dataops/admin-tunnels/<workspaceId>/`。 */
2754
+ const tunnelDirectory = (workspaceId) => join(workspaceRoot(), ".dataops", "admin-tunnels", workspaceId);
2755
+ /** 私钥文件路径。 */
2756
+ const tunnelKeyPath = (workspaceId) => join(tunnelDirectory(workspaceId), "id_ed25519");
2757
+ /** 从 workspace 列表响应里找目标用户的 workspace id。 */
2758
+ const findWorkspaceId = (body, userId) => {
2759
+ const rows = Array.isArray(body) ? body : typeof body === "object" && body !== null && Array.isArray(body.workspaces) ? body.workspaces : [];
2760
+ for (const row of rows) {
2761
+ if (typeof row !== "object" || row === null) continue;
2762
+ const entry = row;
2763
+ if (entry.userId === userId || entry.ownerUserId === userId) {
2764
+ if (typeof entry.id === "string" && entry.id !== "") return entry.id;
2765
+ }
2766
+ }
2767
+ return null;
2768
+ };
2769
+ /** 统一处理 DataOps 响应:401/403/409 给可读错误,其它非 2xx 带状态码抛出。 */
2770
+ const call = async (reviewApi, path, init = {}) => {
2771
+ const result = await reviewApi.request(path, init);
2772
+ const detail = result.body;
2773
+ const reason = typeof detail?.error === "string" ? detail.error : typeof detail?.message === "string" ? detail.message : "";
2774
+ if (result.status === 401) throw new Error("Unauthorized (401): DataOps 会话已过期,请重新登录");
2775
+ if (result.status === 403) throw new Error("Forbidden (403): " + (reason || "只有超级管理员可以代维工作区"));
2776
+ if (result.status === 404) throw new Error("Not Found (404): " + (reason || path + " 不存在(目标工作区或路由缺失)"));
2777
+ if (result.status < 200 || result.status >= 300) throw new Error("DataOps " + path + " failed: HTTP " + result.status.toString() + (reason ? ": " + reason : ""));
2778
+ return result.body;
2779
+ };
2780
+ /**
2781
+ * 构造三个超管代维工具。
2782
+ *
2783
+ * @param reviewApi - 同源桥(携带工作区 JWT)。
2784
+ * @param readScope - 当前 scope 的实时读取器;调用时再判一次超管。
2785
+ */
2786
+ function buildAdminWorkspaceTools(reviewApi, readScope) {
2787
+ const assertSuperAdmin = (tool) => {
2788
+ const scope = readScope();
2789
+ if (scope === void 0 || !isSuperAdmin(scope)) throw new Error("Forbidden (403): " + tool + " 仅超级管理员可用");
2790
+ };
2791
+ /** 解析目标用户的 workspace id:优先新列表接口,退回旧的 userId 重启接口。 */
2792
+ const resolveWorkspaceId = async (userId) => {
2793
+ try {
2794
+ const body = await call(reviewApi, "/api/ai/workspaces");
2795
+ return findWorkspaceId(body, userId);
2796
+ } catch (error) {
2797
+ if (error instanceof Error && /\(404\)/.test(error.message)) return null;
2798
+ throw error;
2799
+ }
2800
+ };
2801
+ return [
2802
+ {
2803
+ name: "admin_workspace_restart",
2804
+ definition: defineTool({
2805
+ name: "admin_workspace_restart",
2806
+ description: "Restart one managed DSH workspace by owner userId. Super administrators only; audited by DataOps. Use after the tunnel-based repair, or when the user reports the workspace is stuck.",
2807
+ parameters: { user_id: {
2808
+ type: "string",
2809
+ required: true,
2810
+ description: "Owner userId of the target workspace (never guess it from a display name)."
2811
+ } },
2812
+ output: {
2813
+ schema: OPEN_OBJECT_SCHEMA,
2814
+ render: renderJson
2815
+ },
2816
+ execute: async (args) => {
2817
+ assertSuperAdmin("admin_workspace_restart");
2818
+ const userId = String(args.user_id);
2819
+ const workspaceId = await resolveWorkspaceId(userId);
2820
+ return {
2821
+ userId,
2822
+ workspaceId,
2823
+ result: (workspaceId === null ? await call(reviewApi, "/api/ai/workspace/restart?userId=" + encodeURIComponent(userId), { method: "POST" }) : await call(reviewApi, "/api/ai/workspaces/" + encodeURIComponent(workspaceId) + "/restart", { method: "POST" })) ?? {}
2824
+ };
2825
+ }
2826
+ })
2827
+ },
2828
+ {
2829
+ name: "admin_workspace_tunnel_open",
2830
+ definition: defineTool({
2831
+ name: "admin_workspace_tunnel_open",
2832
+ description: "Open a temporary SSH tunnel into one user's workspace (24h, server-side expiry). Super administrators only; audited. The private key is NOT returned in the conversation: it is written once to a 0600 file under .dataops/admin-tunnels/<workspaceId>/, and this tool returns that path plus the ssh -i command. Revoke when done.",
2833
+ parameters: { user_id: {
2834
+ type: "string",
2835
+ required: true,
2836
+ description: "Owner userId of the target workspace."
2837
+ } },
2838
+ output: {
2839
+ schema: OPEN_OBJECT_SCHEMA,
2840
+ render: renderJson
2841
+ },
2842
+ execute: async (args) => {
2843
+ assertSuperAdmin("admin_workspace_tunnel_open");
2844
+ const userId = String(args.user_id);
2845
+ const workspaceId = await resolveWorkspaceId(userId);
2846
+ if (workspaceId === null) throw new Error("目标用户没有可代维的工作区(workspaces 列表里找不到 userId=" + userId + ")");
2847
+ const tunnel = await call(reviewApi, "/api/ai/workspaces/" + encodeURIComponent(workspaceId) + "/tunnel", { method: "POST" }) ?? {};
2848
+ const privateKey = typeof tunnel.privateKey === "string" ? tunnel.privateKey : "";
2849
+ if (privateKey === "") throw new Error("开通隧道的响应里没有 privateKey,无法建立一次性凭据");
2850
+ const directory = tunnelDirectory(workspaceId);
2851
+ await mkdir(directory, {
2852
+ recursive: true,
2853
+ mode: 448
2854
+ });
2855
+ await chmod(directory, 448);
2856
+ const keyPath = tunnelKeyPath(workspaceId);
2857
+ await writeFile(keyPath, privateKey, { mode: 384 });
2858
+ await chmod(keyPath, 384);
2859
+ const host = typeof tunnel.targetHost === "string" ? tunnel.targetHost : "127.0.0.1";
2860
+ const port = typeof tunnel.port === "number" ? tunnel.port : 22;
2861
+ return {
2862
+ userId,
2863
+ workspaceId,
2864
+ keyPath,
2865
+ sshCommand: "ssh -i " + keyPath + " -p " + String(port) + " root@" + host,
2866
+ targetHost: host,
2867
+ port,
2868
+ expiresAt: typeof tunnel.expiresAt === "string" ? tunnel.expiresAt : null,
2869
+ note: "私钥只写在上面这个 0600 文件里,不要把它贴进对话;用完调用 admin_workspace_tunnel_revoke 删除。"
2870
+ };
2871
+ }
2872
+ })
2873
+ },
2874
+ {
2875
+ name: "admin_workspace_tunnel_revoke",
2876
+ definition: defineTool({
2877
+ name: "admin_workspace_tunnel_revoke",
2878
+ description: "Revoke the temporary SSH tunnel of one user's workspace and delete the local one-time key file. Super administrators only; audited.",
2879
+ parameters: { user_id: {
2880
+ type: "string",
2881
+ required: true,
2882
+ description: "Owner userId of the target workspace."
2883
+ } },
2884
+ output: {
2885
+ schema: OPEN_OBJECT_SCHEMA,
2886
+ render: renderJson
2887
+ },
2888
+ execute: async (args) => {
2889
+ assertSuperAdmin("admin_workspace_tunnel_revoke");
2890
+ const userId = String(args.user_id);
2891
+ const workspaceId = await resolveWorkspaceId(userId);
2892
+ if (workspaceId === null) throw new Error("目标用户没有可代维的工作区(workspaces 列表里找不到 userId=" + userId + ")");
2893
+ const body = await call(reviewApi, "/api/ai/workspaces/" + encodeURIComponent(workspaceId) + "/tunnel", { method: "DELETE" });
2894
+ await rm(tunnelKeyPath(workspaceId), { force: true });
2895
+ await rm(tunnelDirectory(workspaceId), {
2896
+ recursive: true,
2897
+ force: true
2898
+ });
2899
+ return {
2900
+ userId,
2901
+ workspaceId,
2902
+ revoked: true,
2903
+ result: body ?? {}
2904
+ };
2905
+ }
2906
+ })
2907
+ }
2908
+ ];
2909
+ }
2910
+ //#endregion
2737
2911
  //#region src/tool-manager.ts
2738
2912
  /**
2739
2913
  * Reconcile the managed tools with the current DataOps scope.
@@ -2759,7 +2933,7 @@ var AiToolManager = class {
2759
2933
  this.ctx = ctx;
2760
2934
  this.reviewApi = reviewApi;
2761
2935
  this.collectHub = collectHub;
2762
- this.definitions = new Map(buildAiManagementTools(ctx, reviewApi, () => this.scope, this.collectHub).map((tool) => [tool.name, tool.definition]));
2936
+ this.definitions = new Map([...buildAiManagementTools(ctx, reviewApi, () => this.scope, this.collectHub), ...buildAdminWorkspaceTools(reviewApi, () => this.scope)].map((tool) => [tool.name, tool.definition]));
2763
2937
  this.unsubscribeExpiry = onAuthStateChange((state) => {
2764
2938
  if (state === "expired") this.clear();
2765
2939
  });
@@ -0,0 +1,10 @@
1
+ import type { ReviewApi } from './review-api.ts';
2
+ import { type DataOpsScope } from './tool-scope.ts';
3
+ import type { AiManagedTool } from './tools.ts';
4
+ /**
5
+ * 构造三个超管代维工具。
6
+ *
7
+ * @param reviewApi - 同源桥(携带工作区 JWT)。
8
+ * @param readScope - 当前 scope 的实时读取器;调用时再判一次超管。
9
+ */
10
+ export declare function buildAdminWorkspaceTools(reviewApi: ReviewApi, readScope: () => DataOpsScope | undefined): AiManagedTool[];
@@ -165,6 +165,15 @@ export declare const AI_TOOL_ACCESS: {
165
165
  readonly adminOnly: true;
166
166
  readonly defaultEnabled: true;
167
167
  };
168
+ readonly admin_workspace_restart: {
169
+ readonly superAdminOnly: true;
170
+ };
171
+ readonly admin_workspace_tunnel_open: {
172
+ readonly superAdminOnly: true;
173
+ };
174
+ readonly admin_workspace_tunnel_revoke: {
175
+ readonly superAdminOnly: true;
176
+ };
168
177
  };
169
178
  /** Every managed tool name, in the order the manager considers them. */
170
179
  export declare const AI_TOOL_NAMES: AiToolName[];
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sparkelf/dsh-dataops-managed",
3
- "version": "0.3.38",
3
+ "version": "0.3.40",
4
4
  "description": "DataOps JWT intake and credential-backed MCP tools for managed DeepSeek Harness workspaces.",
5
5
  "type": "module",
6
6
  "main": "./lib/index.js",
@@ -19,13 +19,16 @@ description: 超管代维另一个用户的 DSH 工作区时使用。包含临
19
19
 
20
20
  两个工具:
21
21
 
22
- - `admin_workspace_tunnel_open(userId)` → 返回一次性连接信息(`privateKey` / `targetHost` / `port` / `expiresAt`)。**私钥只出现这一次**,不落库、不进日志。
22
+ - `admin_workspace_tunnel_open(userId)` → 私钥**不返回正文**:工具把它写成工作区内的 0600 一次性文件
23
+ (`/workspace/.dataops/admin-tunnels/<workspaceId>/id_ed25519`,目录 0700),只返回 `keyPath`、
24
+ `sshCommand`、`targetHost`、`port`、`expiresAt`。
23
25
  - `admin_workspace_tunnel_revoke(userId)` → 立即撤销(删除对应的 `authorized_keys` 标记行并结束转发)。
24
26
 
25
27
  规则:
26
28
 
27
29
  1. 开通前先在门户里确认目标工作区 id 和 owner,**不要凭用户名猜 userId**;
28
- 2. 私钥只在当轮使用,用完即 `revoke`;不要把私钥写进文件、贴进聊天、存进工作区;
30
+ 2. 私钥只存在于上面那个 0600 文件里(工具不会把正文给你);不要 `cat` 它、不要贴进聊天、
31
+ 不要复制到别处;用完即 `revoke`,`revoke` 会同时删掉文件与目录;
29
32
  3. 隧道默认 **24 小时**到期,服务端每 5 分钟清理过期标记;到期后连接立即失效,**不要依赖自己记时间**;
30
33
  4. 同一目标不要并行开多条;用完就撤销,撤销后要复验「再连失败」再结束。
31
34