huaweicloud-devkit 2.0.0-next.4 → 2.0.0-next.6

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.
Files changed (72) hide show
  1. package/README.md +1 -1
  2. package/integrations/opencode/commands/huaweicloud-doctor.md +1 -1
  3. package/integrations/opencode/hooks/safety-gate.js +235 -0
  4. package/package.json +1 -1
  5. package/plugins/huaweicloud-core/.claude-plugin/plugin.json +3 -16
  6. package/plugins/huaweicloud-core/.codex-plugin/plugin.json +3 -16
  7. package/plugins/huaweicloud-core/.cursor-plugin/plugin.json +3 -16
  8. package/plugins/huaweicloud-core/.hermes-plugin/plugin.json +3 -16
  9. package/plugins/huaweicloud-core/.workbuddy-plugin/plugin.json +3 -16
  10. package/plugins/huaweicloud-core/dist/agents/opencode-config.js +29 -4
  11. package/plugins/huaweicloud-core/dist/agents/opencode.js +55 -14
  12. package/plugins/huaweicloud-core/dist/approval-gate.js +23 -5
  13. package/plugins/huaweicloud-core/dist/doctor-payload.js +29 -0
  14. package/plugins/huaweicloud-core/dist/explain-error.js +9 -1
  15. package/plugins/huaweicloud-core/dist/hcloud-plan.js +6 -1
  16. package/plugins/huaweicloud-core/dist/lib/hdkit/hdkitservice-api.js +18 -9
  17. package/plugins/huaweicloud-core/dist/lib/opencode-permission-seam.js +51 -20
  18. package/plugins/huaweicloud-core/dist/mcp-server.js +520 -290
  19. package/plugins/huaweicloud-core/dist/mcp-server.js.map +4 -4
  20. package/plugins/huaweicloud-core/dist/packs/auth/tools.js +5 -1
  21. package/plugins/huaweicloud-core/dist/packs/registry.js +1 -0
  22. package/plugins/huaweicloud-core/dist/packs/sandbox/expose-task.js +71 -0
  23. package/plugins/huaweicloud-core/dist/packs/sandbox/handlers-account.js +25 -1
  24. package/plugins/huaweicloud-core/dist/packs/sandbox/handlers-tunnel.js +28 -3
  25. package/plugins/huaweicloud-core/dist/packs/sandbox/schemas.js +14 -0
  26. package/plugins/huaweicloud-core/dist/packs/sandbox/tools.js +11 -3
  27. package/plugins/huaweicloud-core/dist/payload-placement.js +8 -0
  28. package/plugins/huaweicloud-core/dist/risk-rule-engine.js +20 -4
  29. package/plugins/huaweicloud-core/dist/safety/classify-hcloud.js +6 -6
  30. package/plugins/huaweicloud-core/dist/safety/classify-text.js +10 -0
  31. package/plugins/huaweicloud-core/dist/safety/policy.js +12 -0
  32. package/plugins/huaweicloud-core/dist/safety/protected-payload.js +93 -0
  33. package/plugins/huaweicloud-core/dist/safety/redact.js +21 -3
  34. package/plugins/huaweicloud-core/dist/safety/risk-merge.js +24 -4
  35. package/plugins/huaweicloud-core/dist/safety-integrity.js +122 -0
  36. package/plugins/huaweicloud-core/dist/sandbox/devbridge-cleanup.js +1 -1
  37. package/plugins/huaweicloud-core/dist/setup-cli.js +8 -1
  38. package/plugins/huaweicloud-core/dist/tool-definitions.js +4 -0
  39. package/plugins/huaweicloud-core/hooks/huaweicloud-safety.mjs +44 -1
  40. package/plugins/huaweicloud-core/hooks/huaweicloud-safety.py +75 -2
  41. package/plugins/huaweicloud-core/openclaw.plugin.json +2 -2
  42. package/plugins/huaweicloud-core/safety/policy.json +5 -0
  43. package/plugins/huaweicloud-core/safety/rules/cloud-risk-rules.json +1 -1
  44. package/plugins/huaweicloud-core/skills/huawei-sandbox/SKILL.md +42 -39
  45. package/plugins/huaweicloud-core/skills/huaweicloud-safety/references/approvals.md +1 -1
  46. package/plugins/huaweicloud-core/src/agents/opencode-config.ts +33 -3
  47. package/plugins/huaweicloud-core/src/agents/opencode.ts +66 -15
  48. package/plugins/huaweicloud-core/src/approval-gate.ts +29 -4
  49. package/plugins/huaweicloud-core/src/doctor-payload.ts +40 -2
  50. package/plugins/huaweicloud-core/src/explain-error.ts +9 -1
  51. package/plugins/huaweicloud-core/src/hcloud-plan.ts +6 -1
  52. package/plugins/huaweicloud-core/src/lib/hdkit/hdkitservice-api.ts +32 -1
  53. package/plugins/huaweicloud-core/src/lib/opencode-permission-seam.ts +60 -19
  54. package/plugins/huaweicloud-core/src/packs/auth/tools.ts +7 -1
  55. package/plugins/huaweicloud-core/src/packs/registry.ts +1 -0
  56. package/plugins/huaweicloud-core/src/packs/sandbox/expose-task.ts +105 -0
  57. package/plugins/huaweicloud-core/src/packs/sandbox/handlers-account.ts +28 -1
  58. package/plugins/huaweicloud-core/src/packs/sandbox/handlers-tunnel.ts +41 -15
  59. package/plugins/huaweicloud-core/src/packs/sandbox/schemas.ts +20 -0
  60. package/plugins/huaweicloud-core/src/packs/sandbox/tools.ts +12 -2
  61. package/plugins/huaweicloud-core/src/payload-placement.ts +8 -0
  62. package/plugins/huaweicloud-core/src/risk-rule-engine.ts +20 -7
  63. package/plugins/huaweicloud-core/src/safety/classify-hcloud.ts +28 -16
  64. package/plugins/huaweicloud-core/src/safety/classify-text.ts +10 -0
  65. package/plugins/huaweicloud-core/src/safety/policy.ts +13 -0
  66. package/plugins/huaweicloud-core/src/safety/protected-payload.ts +97 -0
  67. package/plugins/huaweicloud-core/src/safety/redact.ts +24 -6
  68. package/plugins/huaweicloud-core/src/safety/risk-merge.ts +26 -5
  69. package/plugins/huaweicloud-core/src/safety-integrity.ts +132 -0
  70. package/plugins/huaweicloud-core/src/sandbox/devbridge-cleanup.ts +7 -5
  71. package/plugins/huaweicloud-core/src/setup-cli.ts +8 -0
  72. package/plugins/huaweicloud-core/src/tool-definitions.ts +4 -0
@@ -127,6 +127,10 @@ async function handleAuthSwitch(args = {}, opts = {}) {
127
127
  refreshUserHashAfterAuthChange();
128
128
  return persisted;
129
129
  }
130
+ // F-APV-1: the confirm-token rejection spells its way out (exported for the
131
+ // test that pins the envelope). Confirm tokens share the approval tokens'
132
+ // process-scoped lifetime: a restart drops every pending confirm.
133
+ export const AUTH_CONFIRM_TOKEN_NOT_FOUND_NEXT_STEP = 'This confirmation token was never minted in this process — mistyped, or dropped by a server restart (confirm tokens are process-scoped and never persisted). Re-run the huaweicloud_auth_switch action that returned needs_confirmation to mint a fresh token, then call huaweicloud_auth_confirm with it.';
130
134
  async function handleAuthConfirm(args = {}, _opts = {}) {
131
135
  // D4-24 precise JSON contract (#745): a missing or already-consumed confirm
132
136
  // token returns a structured result instead of throwing a generic Error
@@ -142,7 +146,7 @@ async function handleAuthConfirm(args = {}, _opts = {}) {
142
146
  if (token && consumedConfirms.has(token)) {
143
147
  return { status: 'ok', outcome: 'already_processed' };
144
148
  }
145
- return { status: 'rejected', code: 'CONFIRM_TOKEN_NOT_FOUND' };
149
+ return { status: 'rejected', code: 'CONFIRM_TOKEN_NOT_FOUND', nextStep: AUTH_CONFIRM_TOKEN_NOT_FOUND_NEXT_STEP };
146
150
  }
147
151
  if (args.decision === 's1') {
148
152
  pendingConfirms.delete(token);
@@ -69,6 +69,7 @@ export const PACK_OF = {
69
69
  huaweicloud_sandbox_deploy_nginx: 'sandbox',
70
70
  huaweicloud_sandbox_deploy_check: 'sandbox',
71
71
  huaweicloud_sandbox_expose_tunnel: 'sandbox',
72
+ huaweicloud_sandbox_expose_poll: 'sandbox',
72
73
  huaweicloud_sandbox_renew_tunnel: 'sandbox',
73
74
  huaweicloud_sandbox_keepalive_watchdog: 'sandbox',
74
75
  huaweicloud_sandbox_check_user: 'sandbox',
@@ -0,0 +1,71 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ // The async expose-task registry (AX N-SB.1). An expose chain can outlive
3
+ // the host's MCP request timeout (auth gate + selective cleanups + up to
4
+ // four ~63s expose execs + the persistence re-verify + keepalive enrollment)
5
+ // while the server completes it — the synchronous tool then loses the
6
+ // publicUrl. An async start returns immediately and the poll tool delivers
7
+ // the finished result in-band.
8
+ //
9
+ // The registry is process-scoped (the stdio MCP server owns one). A restart
10
+ // loses the receipt while the tunnel may already live; the unknown hint
11
+ // therefore teaches recovery (re-expose / deploy_check) and never fabricates
12
+ // a URL. Entries are swept after the TTL so a long session cannot grow the
13
+ // map unbounded.
14
+ export const EXPOSE_TASK_ID_PATTERN = /^exp-[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
15
+ const EXPOSE_TASK_TTL_MS = 30 * 60_000;
16
+ const tasks = new Map();
17
+ function sweep(now) {
18
+ for (const [taskId, task] of tasks) {
19
+ if (now - task.startedAt > EXPOSE_TASK_TTL_MS)
20
+ tasks.delete(taskId);
21
+ }
22
+ }
23
+ export function startExposeTask(workspaceId, port, run) {
24
+ const now = Date.now();
25
+ sweep(now);
26
+ const taskId = `exp-${randomUUID()}`;
27
+ const snapshot = { startedAt: now, workspaceId, port };
28
+ tasks.set(taskId, { ...snapshot, state: 'running' });
29
+ // The chain runs detached from the tool call: the client may time out or
30
+ // cancel the start request, but the server-side work (and the tunnel it
31
+ // creates) must continue. Both settle paths are recorded, so the promise
32
+ // is never an unhandled rejection.
33
+ void run().then((result) => {
34
+ tasks.set(taskId, { ...snapshot, state: 'done', result });
35
+ }, (error) => {
36
+ tasks.set(taskId, {
37
+ ...snapshot,
38
+ state: 'failed',
39
+ error: error instanceof Error ? error.message : String(error),
40
+ });
41
+ });
42
+ return { taskId, startedAt: now };
43
+ }
44
+ export function pollExposeTask(taskId) {
45
+ const now = Date.now();
46
+ sweep(now);
47
+ const task = tasks.get(taskId);
48
+ if (!task) {
49
+ return {
50
+ state: 'unknown',
51
+ hint: 'No task with this id is known to this MCP server process (it never started here, the session restarted, or the ' +
52
+ '30-minute receipt expired). The tunnel may already exist: run huaweicloud_sandbox_deploy_check to read it, or ' +
53
+ 're-run huaweicloud_sandbox_expose_tunnel (same port) — do not assume success without a URL.',
54
+ };
55
+ }
56
+ if (task.state === 'running') {
57
+ return {
58
+ state: 'running',
59
+ elapsedMs: now - task.startedAt,
60
+ hint: 'The expose chain is running in the background (auth, cleanup, host start, health check, keepalive). Call again.',
61
+ };
62
+ }
63
+ if (task.state === 'done') {
64
+ return { state: 'done', result: task.result };
65
+ }
66
+ return { state: 'failed', error: task.error };
67
+ }
68
+ // Test seam: isolate a process-global registry between cases.
69
+ export function _resetExposeTasksForTests() {
70
+ tasks.clear();
71
+ }
@@ -50,7 +50,12 @@ export async function handleConnect(args = {}, _opts = {}) {
50
50
  }
51
51
  let connectResult;
52
52
  try {
53
- connectResult = await hdkitConnectWithRetry(connectArgs);
53
+ // AX N-SB.2: the MCP tool answers inside the host's request budget — a
54
+ // transient gateway timeout returns a pending receipt instead of sleeping
55
+ // through the 30s/45s table (the next call re-attempts and reuses any
56
+ // instance the server already created). Short backoffs (tests/operators)
57
+ // keep the inline ladder.
58
+ connectResult = await hdkitConnectWithRetry(connectArgs, { maxInlineDelayMs: 1000 });
54
59
  }
55
60
  catch (error) {
56
61
  // 业务预期失败(429 三码 / 烧核 / 凭证失效)转结构化返回,remediation 才能穿透 MCP 边界;
@@ -128,6 +133,25 @@ export async function handleConnect(args = {}, _opts = {}) {
128
133
  }
129
134
  throw error;
130
135
  }
136
+ if (connectResult?.pending === true) {
137
+ const retryAfterMs = typeof connectResult.retryAfterMs === 'number' && Number.isFinite(connectResult.retryAfterMs)
138
+ ? connectResult.retryAfterMs
139
+ : 30000;
140
+ const retryAfter = `${Math.max(1, Math.ceil(retryAfterMs / 1000))}s`;
141
+ return {
142
+ ok: false,
143
+ pending: true,
144
+ retryAfter,
145
+ retryAfterMs,
146
+ ...(typeof connectResult.code === 'string' ? { code: connectResult.code } : {}),
147
+ message: typeof connectResult.message === 'string' && connectResult.message
148
+ ? connectResult.message
149
+ : 'the hdkitservice gateway timed out during orchestration.',
150
+ hint: `The sandbox instance may already exist on the server. Re-call huaweicloud_sandbox_connect with the SAME ` +
151
+ `parameters after ~${retryAfter} — a created instance is reused. Do not start a second sandbox and do not ` +
152
+ `debug this as a credential failure.`,
153
+ };
154
+ }
131
155
  const rawDevStageId = connectResult?.dev_stage_id || connectResult?.devStageId;
132
156
  const devStageId = typeof rawDevStageId === 'string' ? rawDevStageId : undefined;
133
157
  let announceConnect = true;
@@ -1,6 +1,8 @@
1
1
  import { exposeTunnel, renewTunnel, installKeepaliveWatchdog, validateTunnelId, } from "../../sandbox/devbridge-tunnel.js";
2
2
  import { getCurrentWorkspaceId } from "../../sandbox/session-manager.js";
3
+ import { validateTunnelPort } from "../../sandbox/devbridge-validation.js";
3
4
  import { poolContextFor } from "../../lib/hdkit/sandbox-pool.js";
5
+ import { startExposeTask, pollExposeTask } from "./expose-task.js";
4
6
  import { buildKeyringInjectScript, ensureDevbridgeKey, listKeysForQuotaHint, recreateDevbridgeKey, } from "../../sandbox/devbridge-key.js";
5
7
  import { SANDBOX_TIMEOUT_MS } from "./schemas.js";
6
8
  // Tunnel handlers (expose/renew/keepalive-watchdog) for the sandbox pack,
@@ -18,8 +20,8 @@ export async function handleExposeTunnel(args = {}, _opts = {}) {
18
20
  const sandboxUser9 = args.username || 'root';
19
21
  const sandboxTimeout9 = args.timeout_ms || SANDBOX_TIMEOUT_MS.expose_tunnel;
20
22
  const exposePoolContext = poolContextFor(sandboxWsId9);
21
- return await exposeTunnel(sandboxWsId9, {
22
- port: args.port,
23
+ const exposeArgs = {
24
+ port: validateTunnelPort(args.port),
23
25
  expiryHours: typeof args.expiry_hours === 'number' ? args.expiry_hours : undefined,
24
26
  keepalive: typeof args.keepalive === 'boolean' ? args.keepalive : undefined,
25
27
  cleanupMode: args.cleanup_mode,
@@ -27,7 +29,30 @@ export async function handleExposeTunnel(args = {}, _opts = {}) {
27
29
  poolType: exposePoolContext?.poolMode || 'ephemeral',
28
30
  poolContext: exposePoolContext,
29
31
  keyUpgrade: { ensureDevbridgeKey, recreateDevbridgeKey, buildKeyringInjectScript, listKeysForQuotaHint },
30
- }, sandboxUser9, sandboxTimeout9);
32
+ };
33
+ // AX N-SB.1: the chain can outlive the host's request timeout while the
34
+ // server completes it — async starts it detached and the poll tool delivers
35
+ // the URL in-band. The fast parameter checks above stay synchronous, so a
36
+ // bad port is an immediate error, not a deferred task failure.
37
+ if (args.mode === 'async') {
38
+ const { taskId } = startExposeTask(sandboxWsId9, exposeArgs.port, () => exposeTunnel(sandboxWsId9, exposeArgs, sandboxUser9, sandboxTimeout9));
39
+ return {
40
+ started: true,
41
+ mode: 'async',
42
+ taskId,
43
+ hint: 'The expose chain is running in the background. Poll huaweicloud_sandbox_expose_poll with this taskId until ' +
44
+ 'state is done — the publicUrl and urlLifetimeHint are delivered there (the task receipt lives 30 minutes in ' +
45
+ 'this MCP server process).',
46
+ };
47
+ }
48
+ return await exposeTunnel(sandboxWsId9, exposeArgs, sandboxUser9, sandboxTimeout9);
49
+ }
50
+ export async function handleExposePoll(args = {}, _opts = {}) {
51
+ const taskId = args.task_id;
52
+ if (typeof taskId !== 'string' || taskId === '') {
53
+ throw new Error('task_id is required — pass the taskId returned by huaweicloud_sandbox_expose_tunnel mode:"async".');
54
+ }
55
+ return pollExposeTask(taskId);
31
56
  }
32
57
  export async function handleRenewTunnel(args = {}, _opts = {}) {
33
58
  if (!args.tunnel_id) {
@@ -1,6 +1,7 @@
1
1
  import { z } from 'zod';
2
2
  import { HWEXEC_POLL_HEADROOM_MS, HWEXEC_TAIL_BYTES_DEFAULT, HWEXEC_TAIL_BYTES_MAX, HWEXEC_TASK_ID_PATTERN, HWEXEC_WAIT_MS_MAX, } from "../../sandbox/hwexec-task.js";
3
3
  import { numericArg, looseObject, gitConfig, workspaceId, username, vendorConfirmed, approvalTokenArg, approvedByUserArg, } from "../../lib/tool-schema-parts.js";
4
+ import { EXPOSE_TASK_ID_PATTERN } from "./expose-task.js";
4
5
  // The sandbox pack's zod schema family, extracted from tools.ts in the
5
6
  // within-pack split for the jscpd complex-file bar. tools.ts stays the stable
6
7
  // face: it imports every schema here for the SANDBOX_TOOLS /
@@ -169,6 +170,13 @@ export const exposeTunnelSchema = z.looseObject({
169
170
  .enum(['stale', 'all', 'none'])
170
171
  .optional()
171
172
  .describe("Tunnel cleanup before exposing. stale (default): delete same-port tunnels + orphan records/hosts; preserve other ports, other sessions and keepalive-protected tunnels — except a tunnel bound to THIS port, which is always replaced. all: wipe every tunnel/host (manual full reset only — a shared sandbox loses every session's tunnels). none: no cleanup (a stale same-port host can then conflict)."),
173
+ mode: z
174
+ .enum(['sync', 'async'])
175
+ .optional()
176
+ .describe('sync (default): run the whole expose chain and return its result. async: start the chain in the background and return ' +
177
+ '{started:true, taskId, hint} immediately — use it on MCP hosts whose per-request timeout is shorter than the expose ' +
178
+ 'chain (auth + selective cleanup + up to four ~63s expose attempts + re-verify + keepalive enrollment), then poll ' +
179
+ 'huaweicloud_sandbox_expose_poll with taskId. The task receipt lives in this MCP server process (30 min).'),
172
180
  workspace_id: workspaceId,
173
181
  username,
174
182
  timeout_ms: numericArg
@@ -177,6 +185,12 @@ export const exposeTunnelSchema = z.looseObject({
177
185
  approvalToken: approvalTokenArg,
178
186
  approvedByUser: approvedByUserArg,
179
187
  });
188
+ export const exposePollSchema = z.looseObject({
189
+ task_id: z
190
+ .string()
191
+ .regex(EXPOSE_TASK_ID_PATTERN, 'task_id must be the exp-<uuid> from huaweicloud_sandbox_expose_tunnel mode:"async".')
192
+ .describe('The taskId returned by huaweicloud_sandbox_expose_tunnel with mode:"async".'),
193
+ });
180
194
  export const renewTunnelSchema = z.looseObject({
181
195
  tunnel_id: z
182
196
  .string()
@@ -1,9 +1,9 @@
1
- import { execWithSessionSchema, execOneShotSchema, execPollSchema, closeSessionSchema, uploadFileSchema, uploadProjectSchema, deployNginxSchema, deployCheckSchema, checkUserSchema, exposeTunnelSchema, renewTunnelSchema, keepaliveWatchdogSchema, signAgreementSchema, connectSchema, credentialsSchema, shutdownSchema, } from "./schemas.js";
1
+ import { execWithSessionSchema, execOneShotSchema, execPollSchema, closeSessionSchema, uploadFileSchema, uploadProjectSchema, deployNginxSchema, deployCheckSchema, checkUserSchema, exposeTunnelSchema, exposePollSchema, renewTunnelSchema, keepaliveWatchdogSchema, signAgreementSchema, connectSchema, credentialsSchema, shutdownSchema, } from "./schemas.js";
2
2
  import { handleExecWithSession, handleExecOneShot, handleCloseSession } from "./handlers-session.js";
3
3
  import { handleHwexecPoll } from "./handlers-hwexec.js";
4
4
  import { handleUploadFile, handleUploadProject } from "./handlers-upload.js";
5
5
  import { handleDeployNginx, handleDeployCheck } from "./handlers-deploy.js";
6
- import { handleExposeTunnel, handleRenewTunnel, handleKeepaliveWatchdog } from "./handlers-tunnel.js";
6
+ import { handleExposeTunnel, handleExposePoll, handleRenewTunnel, handleKeepaliveWatchdog } from "./handlers-tunnel.js";
7
7
  import { handleCheckUser, handleSignAgreement, handleConnect, handleShutdown } from "./handlers-account.js";
8
8
  import { handleCredentials } from "./handlers-credentials.js";
9
9
  // The sandbox pack's stable face (split from the former 879-line monolith
@@ -78,6 +78,12 @@ export const SANDBOX_TOOLS = [
78
78
  schema: exposeTunnelSchema,
79
79
  handler: handleExposeTunnel,
80
80
  },
81
+ {
82
+ name: 'huaweicloud_sandbox_expose_poll',
83
+ description: 'Poll an async expose task started by huaweicloud_sandbox_expose_tunnel with mode: "async". Returns state: running (the chain is still working — call again), done (result carries the full expose envelope: ok, publicUrl, port, tunnelId, expiresAt, urlLifetimeHint, keepalive, warnings), failed (an unexpected throw escaped the chain, with error), or unknown (no receipt in this MCP server process — it never started here, the session restarted, or the 30-minute receipt expired; the tunnel may already exist, so check huaweicloud_sandbox_deploy_check or re-expose — never assume success without a URL). The urlLifetimeHint MUST be relayed with the URL: the tunnel expiry is not the sandbox lifetime.',
84
+ schema: exposePollSchema,
85
+ handler: handleExposePoll,
86
+ },
81
87
  {
82
88
  name: 'huaweicloud_sandbox_renew_tunnel',
83
89
  description: "Renew a DevBridge tunnel's lifetime (devbridge update <id> -e <hours>) — a ROLLING window: expiration = now + hours regardless of remaining time, so renewing before expiry keeps the SAME public URL alive indefinitely (the URL is bound to the tunnel ID and never changes). Default 720h = the 30-day maximum. Returns ok, tunnelId, expiresAt (absolute ISO timestamp read back via show -v — a management-plane loss (10002 tunnel not found) is NOT misread as success), renewedForHours. Use the tunnelId from huaweicloud_sandbox_expose_tunnel or extract it from the URL. The keepalive watchdog renews automatically; this tool is the manual/one-off path.",
@@ -104,7 +110,7 @@ export const SANDBOX_TOOLS = [
104
110
  },
105
111
  {
106
112
  name: 'huaweicloud_sandbox_connect',
107
- description: 'Connect to a sandbox via hdkitservice. One instance per user per pool — reuses the same-pool sandbox if available, otherwise creates a new one. Quota: 1 instance per pool type (a user may hold 1 ephemeral AND 1 persistent simultaneously; same-type requests reuse the existing instance). On quota exhaustion the API returns HTTP 429 with one of three codes: HDKIT_QUOTA_EXCEEDED (retry useless — release or reuse the existing instance; Retry-After 60), HDKIT_TEMPLATE_QUOTA_EXCEEDED (the running instances of this account for this sandbox type are at the limit — shut down or release an instance of the same type and retry; no Retry-After), or HDKIT_CAPACITY_INSUFFICIENT (pool capacity; retry later / off-peak; Retry-After 60). Gateway 502/504 timeouts during orchestration are retried automatically (30s/45s backoff) — the server may already have created the instance, so a retry reuses it. An outdated plugin version is rejected by the 409 HDKIT_VERSION_TOO_OLD version gate, surfaced by the sandbox tools (connect/check_user/sign_agreement/credentials) as ok:false and by the voucher trio as claimed:false, always carrying code, message, and remediation naming the upgrade act (npx --yes huaweicloud-devkit@latest update --target <agent>, restart the agent session, or huaweicloud_upgrade), with clientVersion and minVersion present when the service sends them. Returns session_id, dev_stage_id, connection_id, connection_address, expiresAt (STS credential expiry), pool_type/resolved template_id echo, server-configured lifecycle numbers (pool_idle_shutdown_minutes / pool_idle_delete_minutes / pool_reclaim_minutes) and started (true when a reused instance was woken from shutdown). Lifecycle hints are announced only on the first connect of a session or when started=true. Ephemeral pool (default): idle auto-shutdown after 30min, auto-delete after 1h — do not keep important data there. Persistent pool: data disk retained (EVS 32G), idle shutdown after 1h, idle reclaim capped at 7 days. Numbers are configured by hdkitservice; the text follows the server echo and falls back to these defaults. Vendor-gated (vendorConfirmed): call only when the vendor is established — see the vendorConfirmed parameter description; when unknown, ask which cloud the user means first.',
113
+ description: 'Connect to a sandbox via hdkitservice. One instance per user per pool — reuses the same-pool sandbox if available, otherwise creates a new one. Quota: 1 instance per pool type (a user may hold 1 ephemeral AND 1 persistent simultaneously; same-type requests reuse the existing instance). On quota exhaustion the API returns HTTP 429 with one of three codes: HDKIT_QUOTA_EXCEEDED (retry useless — release or reuse the existing instance; Retry-After 60), HDKIT_TEMPLATE_QUOTA_EXCEEDED (the running instances of this account for this sandbox type are at the limit — shut down or release an instance of the same type and retry; no Retry-After), or HDKIT_CAPACITY_INSUFFICIENT (pool capacity; retry later / off-peak; Retry-After 60). Gateway 502/504 timeouts during orchestration return a pending receipt (ok:false, pending:true, retryAfter, hint) instead of holding the call through the backoff — the server may already have created the instance; re-call this tool with the SAME parameters after retryAfter and a created instance is reused. An outdated plugin version is rejected by the 409 HDKIT_VERSION_TOO_OLD version gate, surfaced by the sandbox tools (connect/check_user/sign_agreement/credentials) as ok:false and by the voucher trio as claimed:false, always carrying code, message, and remediation naming the upgrade act (npx --yes huaweicloud-devkit@latest update --target <agent>, restart the agent session, or huaweicloud_upgrade), with clientVersion and minVersion present when the service sends them. Returns session_id, dev_stage_id, connection_id, connection_address, expiresAt (STS credential expiry), pool_type/resolved template_id echo, server-configured lifecycle numbers (pool_idle_shutdown_minutes / pool_idle_delete_minutes / pool_reclaim_minutes) and started (true when a reused instance was woken from shutdown). Lifecycle hints are announced only on the first connect of a session or when started=true. Ephemeral pool (default): idle auto-shutdown after 30min, auto-delete after 1h — do not keep important data there. Persistent pool: data disk retained (EVS 32G), idle shutdown after 1h, idle reclaim capped at 7 days. Numbers are configured by hdkitservice; the text follows the server echo and falls back to these defaults. Vendor-gated (vendorConfirmed): call only when the vendor is established — see the vendorConfirmed parameter description; when unknown, ask which cloud the user means first.',
108
114
  schema: connectSchema,
109
115
  handler: handleConnect,
110
116
  },
@@ -134,6 +140,7 @@ export const SANDBOX_TOOL_SCHEMAS = {
134
140
  huaweicloud_sandbox_deploy_nginx: deployNginxSchema,
135
141
  huaweicloud_sandbox_deploy_check: deployCheckSchema,
136
142
  huaweicloud_sandbox_expose_tunnel: exposeTunnelSchema,
143
+ huaweicloud_sandbox_expose_poll: exposePollSchema,
137
144
  huaweicloud_sandbox_renew_tunnel: renewTunnelSchema,
138
145
  huaweicloud_sandbox_keepalive_watchdog: keepaliveWatchdogSchema,
139
146
  huaweicloud_sandbox_check_user: checkUserSchema,
@@ -155,6 +162,7 @@ export const SANDBOX_TOOL_HANDLERS = {
155
162
  huaweicloud_sandbox_deploy_nginx: handleDeployNginx,
156
163
  huaweicloud_sandbox_deploy_check: handleDeployCheck,
157
164
  huaweicloud_sandbox_expose_tunnel: handleExposeTunnel,
165
+ huaweicloud_sandbox_expose_poll: handleExposePoll,
158
166
  huaweicloud_sandbox_renew_tunnel: handleRenewTunnel,
159
167
  huaweicloud_sandbox_keepalive_watchdog: handleKeepaliveWatchdog,
160
168
  huaweicloud_sandbox_check_user: handleCheckUser,
@@ -2,6 +2,7 @@ import { existsSync, mkdirSync, rmSync, writeFileSync } from 'node:fs';
2
2
  import { join } from 'node:path';
3
3
  import { copyDir, copyFileVerified, pruneStale } from "./payload-files.js";
4
4
  import { PLUGIN_ROOT } from "./payload-utils.js";
5
+ import { writeIntegrityReceipt } from "./safety-integrity.js";
5
6
  // The server-payload placement (the install-payload.ts internals split):
6
7
  // the one shared seam every per-agent install/update call site ships the
7
8
  // payload through — the agent rules file, the MCP server (dist/), the
@@ -65,6 +66,13 @@ export function copyServerPayload(pluginDest, opts = {}) {
65
66
  }
66
67
  copyDir(join(PLUGIN_ROOT, 'safety'), join(pluginDest, 'safety'));
67
68
  console.log(` Safety Policy -> ${join(pluginDest, 'safety')}`);
69
+ // The integrity receipt (the integrity unit's layer 3): a hash manifest
70
+ // of the classifier files that just landed, written at the one shared
71
+ // placement seam so every install/update path records it and doctor can
72
+ // detect drift later. Covers whatever shipped — a skipDist payload
73
+ // records its safety/ files only.
74
+ writeIntegrityReceipt(pluginDest);
75
+ console.log(` Integrity receipt -> ${join(pluginDest, '.safety-integrity.json')}`);
68
76
  const skillsSrc = join(PLUGIN_ROOT, 'skills');
69
77
  // A missing source tree must abort, not silently skip: copyDir's
70
78
  // existsSync guard would no-op the copy while this function still prints
@@ -3,6 +3,7 @@ import { dirname, join } from 'node:path';
3
3
  import { fileURLToPath } from 'node:url';
4
4
  import { asText } from "./lib/as-text.js";
5
5
  import { asRecord } from "./lib/as-record.js";
6
+ import { redactEvidenceText } from "./safety/redact.js";
6
7
  const __dirname = dirname(fileURLToPath(import.meta.url));
7
8
  const defaultRulesPath = join(__dirname, '..', 'safety', 'rules', 'cloud-risk-rules.json');
8
9
  const SEVERITY_RANK = {
@@ -58,9 +59,7 @@ export function loadRiskRules(options = {}) {
58
59
  return toCatalog(JSON.parse(readFileSync(path, 'utf8')));
59
60
  }
60
61
  function redactEvidence(text) {
61
- return String(text)
62
- .replace(/((?:access[_-]?key(?:[_-]?(?:id|secret))?|secret[_-]?key|secret[_-]?string|secret[_-]?binary|secret(?!:\/)|security[_-]?token|x[_-]?auth[_-]?token|token|authorization|password|passwd|admin[_-]?pass|credential)\\*["']?\s*[:=]\s*[\\"'\\]*\s*)("[^"]*"|'[^']*'|[^\s,;]+)/gi, '$1<redacted>')
63
- .replace(/\b(AK|SK)\\*["']?\s*[:=]\s*("[^"]*"|'[^']*'|[^\s,;]+)/gi, '$1=<redacted>');
62
+ return redactEvidenceText(text);
64
63
  }
65
64
  function normalizeText(value) {
66
65
  if (typeof value === 'string')
@@ -84,10 +83,27 @@ function evaluationContext(stage, input) {
84
83
  }
85
84
  return { text: normalizeText(input) };
86
85
  }
86
+ // Shell-transcribed commands and nested JSON artifacts arrive with escaped
87
+ // quotes (`\"Action\":` / `{\"privileged\":true}`) — the spelling a shell or
88
+ // an embedded JSON string actually produces. The catalog's JSON-shaped rules
89
+ // were authored against the unescaped spelling, so a backslash between the
90
+ // key and the quote made deny-severity rules (IAM administrator grants, OBS
91
+ // anonymous writes, privileged containers) silently miss. Matching therefore
92
+ // tests the raw value AND a quote-unescaped shadow; evidence/display keep the
93
+ // raw text. Only quote-adjacent backslashes are folded, so Windows paths are
94
+ // untouched.
95
+ function normalizeRuleText(text) {
96
+ return text.replace(/\\+(["'])/g, '$1');
97
+ }
87
98
  function conditionMatches(condition, context) {
88
99
  const field = condition.field || 'text';
89
100
  const value = Object.hasOwn(context, field) ? context[field] : context.text;
90
- return new RegExp(condition.regex, 'ims').test(String(value || ''));
101
+ const raw = String(value || '');
102
+ const regex = new RegExp(condition.regex, 'ims');
103
+ if (regex.test(raw))
104
+ return true;
105
+ const normalized = normalizeRuleText(raw);
106
+ return normalized !== raw && regex.test(normalized);
91
107
  }
92
108
  function ruleMatches(rule, context) {
93
109
  const match = rule.match || {};
@@ -101,18 +101,18 @@ export function classifyHcloudArgs(args, options = {}) {
101
101
  const isExecution = executionOps.test(operation) && !readOnly;
102
102
  const isWrite = !readOnly && hasWritePrefix(operation, policy);
103
103
  if (isExecution && !options.allowWrites) {
104
- return {
104
+ return applyCommandRiskRules({
105
105
  decision: 'deny',
106
106
  risk: 'execution',
107
107
  reason: 'Huawei Cloud execution/trigger operation blocked until approved.',
108
- };
108
+ }, normalizedArgs, options);
109
109
  }
110
110
  if (isWrite && !options.allowWrites) {
111
- return {
111
+ return applyCommandRiskRules({
112
112
  decision: 'deny',
113
113
  risk: 'write',
114
114
  reason: 'Huawei Cloud write operation blocked until the agent presents a plan and receives explicit user approval.',
115
- };
115
+ }, normalizedArgs, options);
116
116
  }
117
117
  const obsutilWrites = OBSUTIL_WRITES;
118
118
  const obsutilReads = ['ls', 'stat', 'cat', 'help', 'version'];
@@ -123,11 +123,11 @@ export function classifyHcloudArgs(args, options = {}) {
123
123
  const isObsWrite = isObs && obsutilWrites.has(operation.toLowerCase());
124
124
  const isObsRead = isObs && obsutilReads.includes(operation.toLowerCase());
125
125
  if (isObsWrite && !options.allowWrites) {
126
- return {
126
+ return applyCommandRiskRules({
127
127
  decision: 'deny',
128
128
  risk: 'write',
129
129
  reason: 'OBS write operation blocked until the agent presents a plan and receives explicit user approval.',
130
- };
130
+ }, normalizedArgs, options);
131
131
  }
132
132
  if (isObsRead) {
133
133
  return applyCommandRiskRules({
@@ -3,6 +3,7 @@ import { classifyHcloudArgs } from "./classify-hcloud.js";
3
3
  import { credentialFileCandidates } from "./credential-path.js";
4
4
  import { DEFAULT_POLICY } from "./default-policy.js";
5
5
  import { matchesAny } from "./policy.js";
6
+ import { protectedPayloadWriteDenied } from "./protected-payload.js";
6
7
  import { applyRawCommandRiskRules } from "./risk-merge.js";
7
8
  import { unwrapSecretExecWrapper } from "./secret-exec.js";
8
9
  import { unwrapSkillQualityCli } from "./skill-quality-cli.js";
@@ -805,6 +806,15 @@ export function classifyTextCommand(command, options = {}) {
805
806
  reason: 'Reading Huawei Cloud credential or profile files is blocked. Use redacted profile inspection tools instead.',
806
807
  };
807
808
  }
809
+ // The payload path-write gate (the integrity unit's layer 1): the same
810
+ // candidate doctrine as the credential gate, but WRITE-shaped — a
811
+ // redirection/tee/copy-family/dd/sed -i/patch command targeting a
812
+ // protectedPayloadPathMarkers path denies (the bash-face disarm vector
813
+ // the edit seam closed for edit tools; protected-payload.ts owns the
814
+ // shape spec, mirrored by the py twin after its CONFIG_FILE_RE gate).
815
+ const payloadWrite = protectedPayloadWriteDenied(text, policy);
816
+ if (payloadWrite !== null)
817
+ return payloadWrite;
808
818
  // The vault CLI's own reveal surface: `secret get` prints a stored secret
809
819
  // to stdout, which is the agent context when run through the Bash tool.
810
820
  // `secret exec` (values reach only the child env) stays allowed. Matched
@@ -31,9 +31,21 @@ export function loadPolicy(path) {
31
31
  if (raw.writeOperationPrefixes !== undefined && writeOperationPrefixes.length === 0) {
32
32
  throw new TypeError('safety policy field "writeOperationPrefixes" must not be empty');
33
33
  }
34
+ const protectedPayloadPathMarkers = toStringArray(raw.protectedPayloadPathMarkers, 'protectedPayloadPathMarkers');
35
+ // Same emptied-list doctrine as writeOperationPrefixes: a present-but-empty
36
+ // marker list silently disarms the payload path-write gate, so it fails
37
+ // LOUD at load. The py twin has no load-time throw (its load_policy catches
38
+ // everything) and normalizes the degraded shape to an unset gate — the
39
+ // recorded py fail-open posture for a hand-corrupted policy file, the same
40
+ // divergence class the write vocabulary carries (the .mjs face is the
41
+ // fail-closed one).
42
+ if (raw.protectedPayloadPathMarkers !== undefined && protectedPayloadPathMarkers.length === 0) {
43
+ throw new TypeError('safety policy field "protectedPayloadPathMarkers" must not be empty');
44
+ }
34
45
  return {
35
46
  secretKeyNamePatterns: toStringArray(raw.secretKeyNamePatterns, 'secretKeyNamePatterns'),
36
47
  credentialFilePatterns: toStringArray(raw.credentialFilePatterns, 'credentialFilePatterns'),
48
+ protectedPayloadPathMarkers,
37
49
  blockedConfigureSubcommands: toStringArray(raw.blockedConfigureSubcommands, 'blockedConfigureSubcommands'),
38
50
  blockedSecretOperations: toStringArray(raw.blockedSecretOperations, 'blockedSecretOperations'),
39
51
  blockedSecretCliPatterns: toStringArray(raw.blockedSecretCliPatterns, 'blockedSecretCliPatterns'),
@@ -0,0 +1,93 @@
1
+ import { credentialFileCandidates } from "./credential-path.js";
2
+ // The payload path-write gate (the integrity unit's layer 1): a
3
+ // write-shaped shell command that targets the DEPLOYED devkit payload —
4
+ // the classifier files the in-process gates import — denies. The residual
5
+ // it closes: PR #22's seam killed the edit-tool vector on the deployed
6
+ // classifier, but the bash face could still `echo '<permissive>' >
7
+ // …/dist/safety-policy.js` and the adapter's lazy, retryable import loaded
8
+ // the agent's file, disarming every in-process gate mid-session (the TLA
9
+ // counterexample path). READ-shaped references stay allowed: skills reads,
10
+ // skill-tracker, doctor, and plain `cat`/`ls`/`grep` over the payload tree
11
+ // are legitimate agent surface.
12
+ //
13
+ // Write-shape spec (mirrored by the py twin's evaluate gate — keep the two
14
+ // byte-identical in verdicts):
15
+ // candidates: raw text, quote-stripped shadow, path-normalized both (the
16
+ // credentialFileCandidates doctrine — a quote pair inside the path or a
17
+ // redundant `//`/`./` segment must not hide the marker);
18
+ // chunks: each candidate splits on [;&|\n\r] — a crude split, deliberately:
19
+ // it can only over-SPLIT (a separator inside quotes is part of a FILE
20
+ // NAME, and a real payload path never carries one), never join, so a
21
+ // detection can only be lost on non-payload targets;
22
+ // shapes, per chunk (MARKER = the policy alternation):
23
+ // 1. redirect />>?[^;&|]*MARKER/ — target-side marker
24
+ // 2. tee anchor + tee … MARKER — tee's operands are targets
25
+ // 3. cp|mv|rsync|install anchor + … final word carries MARKER (dest)
26
+ // 4. dd anchor + … of=… MARKER — of= is the output
27
+ // 5. sed anchor + … -i … MARKER — in-place edit target
28
+ // 6. patch anchor + … MARKER — operand is the target
29
+ // anchor: chunk start, optional env assignments, then optional
30
+ // sudo/env/nice/nohup/command/xargs heads — command position for the
31
+ // write verbs, so `grep tee <marker-file>` (a read) never trips.
32
+ // Whitespace classes are [ \t] (bash IFS without newline — chunks carry no
33
+ // newlines), keeping JS/py classes identical.
34
+ //
35
+ // Honest ceiling (documented, not closed): quote/variable indirection
36
+ // building the marker path, `cp -t`-style flag targets, timeout-wrapped
37
+ // write verbs, and verbs outside the shape table (truncate/ln/…) are
38
+ // residuals of a text gate; rm/rename of payload files break the gate
39
+ // fail-closed at import time rather than disarm it. Against arbitrary
40
+ // user-permission bash NO purely local mechanism fully closes this — the
41
+ // layer-2 load-time canary and the layer-3 doctor drift check raise the
42
+ // escape cost to forging multiple artifacts.
43
+ // The shape fragments are shared verbatim with the py twin. Every \s in
44
+ // them is [ \t]; MARKER substitutes the policy alternation.
45
+ function shapeRegexes(markers) {
46
+ if (markers.length === 0)
47
+ return [];
48
+ const markerAlt = `(?:${markers.join('|')})`;
49
+ const anchor = String.raw `^[ \t]*(?:[A-Za-z_][A-Za-z0-9_]*=\S*[ \t]+)*(?:(?:sudo|env|nice|nohup|command|xargs)[ \t]+)*`;
50
+ return [
51
+ // 1. Redirection: the marker sits in the redirect's target region.
52
+ // Direction is inherent — `cat <marker> > /tmp/out` keeps its marker
53
+ // BEFORE the operator and never matches.
54
+ new RegExp(String.raw `>>?[^;&|]*` + markerAlt, 'i'),
55
+ // 2. tee: every operand is a write target.
56
+ new RegExp(anchor + String.raw `tee\b[^;&|]*` + markerAlt, 'i'),
57
+ // 3. The copy family: the destination is the LAST operand, so the
58
+ // marker must ride the final word — `cp <marker> /tmp/` (a copy-out)
59
+ // stays allowed.
60
+ new RegExp(anchor + String.raw `(?:cp|mv|rsync|install)\b[^;&|]*[ \t]\S*` + markerAlt + String.raw `\S*[ \t]*$`, 'i'),
61
+ // 4. dd: the of= operand is the output.
62
+ new RegExp(anchor + String.raw `dd\b[^;&|]*\bof[ \t]*=[ \t]*[^;&|]*` + markerAlt, 'i'),
63
+ // 5. sed: a whitespace-preceded -i flag (in-place) anywhere before the
64
+ // marker; a read-only sed over the payload stays allowed.
65
+ new RegExp(anchor + String.raw `sed\b[^;&|]*[ \t]-i\b[^;&|]*` + markerAlt, 'i'),
66
+ // 6. patch: the operand is the file being patched.
67
+ new RegExp(anchor + String.raw `patch\b[^;&|]*` + markerAlt, 'i'),
68
+ ];
69
+ }
70
+ export function protectedPayloadWriteDenied(text, policy) {
71
+ if (policy.protectedPayloadPathMarkers.length === 0)
72
+ return null;
73
+ const shapes = shapeRegexes(policy.protectedPayloadPathMarkers);
74
+ // The candidates a path-bearing gate tests (the credential gate's set):
75
+ // quoting and path redundancy must not hide the marker.
76
+ for (const candidate of credentialFileCandidates(text)) {
77
+ for (const chunk of candidate.split(/[;&|\n\r]/)) {
78
+ for (const shape of shapes) {
79
+ if (shape.test(chunk)) {
80
+ return {
81
+ decision: 'deny',
82
+ // risk 'invalid': exempt from NO roster exemption class (the
83
+ // .mjs/py hooks skip write/execution/destructive for exempt
84
+ // shapes — a payload-write deny must never be skippable).
85
+ risk: 'invalid',
86
+ reason: "Writing to the deployed Huawei Cloud DevKit plugin payload is blocked: this command targets the installed safety policy files, and modifying them would disarm the gates that classify agent commands. Reinstall or update via npx huaweicloud-devkit install from your own terminal; see the huaweicloud-safety skill's approvals reference for the integrity model.",
87
+ };
88
+ }
89
+ }
90
+ }
91
+ }
92
+ return null;
93
+ }
@@ -4,11 +4,18 @@ function isSecretKeyName(key, policy = DEFAULT_POLICY) {
4
4
  const normalized = String(key)
5
5
  .toLowerCase()
6
6
  .replace(/[^a-z0-9]/g, '');
7
- if (/access.*key|secret.*key|security.*token|xauth.*token|authorization|password|passwd|adminpass|credential|private.*key|userdata|metadata|inputvalue/.test(normalized)) {
7
+ if (/access.*key|secret.*key|secret.*string|secret.*binary|secret.*text|api.*key|security.*token|xauth.*token|authorization|password|passwd|adminpass|credential|private.*key|userdata|metadata|inputvalue/.test(normalized)) {
8
8
  return true;
9
9
  }
10
10
  return policy.secretKeyNamePatterns.some((pattern) => regexFrom(`^(${pattern})$`).test(String(key)));
11
11
  }
12
+ // The key vocabulary is shared by every evidence/command redaction face.
13
+ // Backslashes around the key/value are tolerated because shell-transcribed
14
+ // commands and nested JSON carry `\"password\":\"…\"` spellings; `secret://`
15
+ // refs are exempt (the ref is conversation-safe by doctrine). `secret_text`
16
+ // and `api_key` joined the family with the AX N-R4.1 fix — DEW's plaintext
17
+ // secret and the DevBridge key were crossing every evidence surface.
18
+ const SECRET_KEY_VALUE_RE = /((?:access[_-]?key(?:[_-]?(?:id|secret))?|secret[_-]?key|secret[_-]?string|secret[_-]?binary|secret[_-]?text|api[_-]?key|secret(?!:\/)|security[_-]?token|x[_-]?auth[_-]?token|token|authorization|password|passwd|admin[_-]?pass|credential|input[_-]?value)\\*["']?\s*[:=]\s*[\\"']*\s*)("[^"]*"|'[^']*'|[^\s,;]+)/gi;
12
19
  function redactString(text) {
13
20
  return (String(text)
14
21
  // Opaque blob keys (cloud-init user_data, metadata, private_key) carry
@@ -22,8 +29,19 @@ function redactString(text) {
22
29
  // credential itself, so this family consumes to end-of-line like the
23
30
  // blob-key branch above.
24
31
  .replace(/(["']?(?:user[_-]?data|metadata|private[_-]?key|authorization|x[_-]?auth[_-]?token)["']?\s*[:=]\s*).*/gi, '$1<redacted>')
25
- .replace(/(["']?(?:access[_-]?key(?:[_-]?(?:id|secret))?|secret[_-]?key|secret[_-]?string|secret[_-]?binary|security[_-]?token|token|password|passwd|admin[_-]?pass|credential|input[_-]?value)["']?\s*[:=]\s*)("[^"]*"|'[^']*'|[^\s,;]+)/gi, '$1<redacted>')
26
- .replace(/\b(["']?(?:AK|SK)["']?\s*[:=]\s*)("[^"]*"|'[^']*'|[^\s,;]+)/gi, '$1<redacted>'));
32
+ .replace(SECRET_KEY_VALUE_RE, '$1<redacted>')
33
+ // XML settings shapes (`<password>value</password>`, the settings.xml
34
+ // deploy idiom) carry no `:`/`=` separator, so the key-value family
35
+ // never saw them — the artifact evidence echoed the password verbatim
36
+ // (AX N-R4.1). The tag name is backreferenced so a mismatched close
37
+ // tag is not half-redacted.
38
+ .replace(/<(password|passwd|pwd)>[^<]*<\/\1>/gi, '<$1><redacted></$1>')
39
+ .replace(/\b(["']?(?:AK|SK)\\*["']?\s*[:=]\s*[\\"']*\s*)("[^"]*"|'[^']*'|[^\s,;]+)/gi, '$1<redacted>'));
40
+ }
41
+ // The string-level evidence redaction entry (risk-rule-engine's excerpt and
42
+ // any future evidence face): one vocabulary, no second drift-prone copy.
43
+ export function redactEvidenceText(text) {
44
+ return redactString(text);
27
45
  }
28
46
  export function redactSecrets(value, policy = DEFAULT_POLICY) {
29
47
  if (Array.isArray(value)) {
@@ -6,17 +6,37 @@ import { evaluateCommandRisk, mergeRiskDecision } from "../risk-rule-engine.js";
6
6
  function commandRiskText(normalizedArgs, options) {
7
7
  return options.rawCommand || ['hcloud', ...normalizedArgs].join(' ');
8
8
  }
9
+ // A deny-severity base (the generic write/execution gate) still carries the
10
+ // catalog's specialized findings: the approval decision the developer reads
11
+ // must show WHY the command is risky (broad administrator grant, anonymous
12
+ // write, high-cost shape), not only the generic "write must be approved".
13
+ // Only findings/warnings are attached — decision, risk, and reason stay the
14
+ // base's, so the PreToolUse hook's risk-shaped exemption logic does not
15
+ // drift.
16
+ function attachRiskFindings(base, risk) {
17
+ if (!risk.findings || risk.findings.length === 0)
18
+ return base;
19
+ const warnFindings = risk.findings.filter((finding) => finding.severity !== 'deny');
20
+ return {
21
+ ...base,
22
+ findings: [...(base.findings || []), ...risk.findings],
23
+ ...(warnFindings.length > 0 ? { warnings: [...(base.warnings || []), ...warnFindings] } : {}),
24
+ };
25
+ }
26
+ function mergeRisk(base, risk) {
27
+ return base.decision === 'deny' ? attachRiskFindings(base, risk) : mergeRiskDecision(base, risk);
28
+ }
9
29
  export function applyCommandRiskRules(base, normalizedArgs, options) {
10
- if (base.decision === 'deny' || options.skipRiskRules === true) {
30
+ if (options.skipRiskRules === true) {
11
31
  return base;
12
32
  }
13
33
  const risk = evaluateCommandRisk(commandRiskText(normalizedArgs, options));
14
- return mergeRiskDecision(base, risk);
34
+ return mergeRisk(base, risk);
15
35
  }
16
36
  export function applyRawCommandRiskRules(base, command, options) {
17
- if (base.decision === 'deny' || options.skipRiskRules === true) {
37
+ if (options.skipRiskRules === true) {
18
38
  return base;
19
39
  }
20
40
  const risk = evaluateCommandRisk(command);
21
- return mergeRiskDecision(base, risk);
41
+ return mergeRisk(base, risk);
22
42
  }