huaweicloud-devkit 2.0.0-next.0 → 2.0.0-next.2

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 (62) hide show
  1. package/README.md +2 -0
  2. package/package.json +1 -1
  3. package/plugins/huaweicloud-core/.claude-plugin/plugin.json +1 -1
  4. package/plugins/huaweicloud-core/.codex-plugin/plugin.json +1 -1
  5. package/plugins/huaweicloud-core/.cursor-plugin/plugin.json +1 -1
  6. package/plugins/huaweicloud-core/.hermes-plugin/plugin.json +1 -1
  7. package/plugins/huaweicloud-core/.workbuddy-plugin/plugin.json +1 -1
  8. package/plugins/huaweicloud-core/dist/agents/codearts-work.js +4 -0
  9. package/plugins/huaweicloud-core/dist/agents/codearts.js +4 -0
  10. package/plugins/huaweicloud-core/dist/agents/officeace-sqlite.js +14 -4
  11. package/plugins/huaweicloud-core/dist/agents/opencode-config.js +5 -1
  12. package/plugins/huaweicloud-core/dist/approvals-cli.js +159 -0
  13. package/plugins/huaweicloud-core/dist/auth/s1-store.js +43 -22
  14. package/plugins/huaweicloud-core/dist/hcloud-plan.js +26 -4
  15. package/plugins/huaweicloud-core/dist/hcloud-run.js +4 -1
  16. package/plugins/huaweicloud-core/dist/lib/approval-tokens.js +135 -16
  17. package/plugins/huaweicloud-core/dist/lib/approvals-pin.js +128 -0
  18. package/plugins/huaweicloud-core/dist/lib/pack-state.js +23 -19
  19. package/plugins/huaweicloud-core/dist/lib/param-warnings.js +70 -0
  20. package/plugins/huaweicloud-core/dist/lib/state-dir.js +125 -0
  21. package/plugins/huaweicloud-core/dist/mcp-server.js +877 -595
  22. package/plugins/huaweicloud-core/dist/mcp-server.js.map +4 -4
  23. package/plugins/huaweicloud-core/dist/packs/huaweicloud-cli/tools.js +27 -9
  24. package/plugins/huaweicloud-core/dist/payload-runtime-deps.js +11 -3
  25. package/plugins/huaweicloud-core/dist/safety/classify-text.js +13 -0
  26. package/plugins/huaweicloud-core/dist/safety/policy.js +1 -0
  27. package/plugins/huaweicloud-core/dist/setup-cli.js +23 -0
  28. package/plugins/huaweicloud-core/dist/tool-schemas.js +15 -0
  29. package/plugins/huaweicloud-core/dist/tools.js +36 -4
  30. package/plugins/huaweicloud-core/dist/update-registry.js +8 -2
  31. package/plugins/huaweicloud-core/dist/update-skip.js +5 -6
  32. package/plugins/huaweicloud-core/dist/update-upgrade.js +8 -1
  33. package/plugins/huaweicloud-core/hooks/huaweicloud-safety.py +20 -1
  34. package/plugins/huaweicloud-core/openclaw.plugin.json +1 -1
  35. package/plugins/huaweicloud-core/safety/policy.json +8 -0
  36. package/plugins/huaweicloud-core/safety/rules/cloud-risk-rules.json +78 -2
  37. package/plugins/huaweicloud-core/skills/huaweicloud-cli-and-auth/SKILL.md +4 -1
  38. package/plugins/huaweicloud-core/skills/huaweicloud-safety/SKILL.md +13 -6
  39. package/plugins/huaweicloud-core/skills/huaweicloud-safety/references/approvals.md +47 -0
  40. package/plugins/huaweicloud-core/src/agents/codearts-work.ts +3 -0
  41. package/plugins/huaweicloud-core/src/agents/codearts.ts +4 -0
  42. package/plugins/huaweicloud-core/src/agents/officeace-sqlite.ts +14 -4
  43. package/plugins/huaweicloud-core/src/agents/opencode-config.ts +5 -1
  44. package/plugins/huaweicloud-core/src/approvals-cli.ts +187 -0
  45. package/plugins/huaweicloud-core/src/auth/s1-store.ts +41 -20
  46. package/plugins/huaweicloud-core/src/hcloud-plan.ts +44 -5
  47. package/plugins/huaweicloud-core/src/hcloud-run.ts +4 -1
  48. package/plugins/huaweicloud-core/src/lib/approval-tokens.ts +197 -16
  49. package/plugins/huaweicloud-core/src/lib/approvals-pin.ts +153 -0
  50. package/plugins/huaweicloud-core/src/lib/pack-state.ts +23 -20
  51. package/plugins/huaweicloud-core/src/lib/param-warnings.ts +69 -0
  52. package/plugins/huaweicloud-core/src/lib/state-dir.ts +128 -0
  53. package/plugins/huaweicloud-core/src/packs/huaweicloud-cli/tools.ts +29 -9
  54. package/plugins/huaweicloud-core/src/payload-runtime-deps.ts +11 -3
  55. package/plugins/huaweicloud-core/src/safety/classify-text.ts +15 -0
  56. package/plugins/huaweicloud-core/src/safety/policy.ts +2 -0
  57. package/plugins/huaweicloud-core/src/setup-cli.ts +28 -0
  58. package/plugins/huaweicloud-core/src/tool-schemas.ts +16 -0
  59. package/plugins/huaweicloud-core/src/tools.ts +39 -4
  60. package/plugins/huaweicloud-core/src/update-registry.ts +8 -2
  61. package/plugins/huaweicloud-core/src/update-skip.ts +5 -6
  62. package/plugins/huaweicloud-core/src/update-upgrade.ts +8 -1
@@ -213,17 +213,36 @@ async function runApprovedCommand(args = {}) {
213
213
  if (placeholderArg) {
214
214
  throw new Error(`The argument "${placeholderArg}" still carries a placeholder secret value: replace <redacted> with the actual value the user approved, then re-run with the same approval token.`);
215
215
  }
216
- const stored = consumeApprovalToken(token);
217
- if (!stored) {
218
- // Defensive: inspectApprovalToken said 'valid' but consume returned null.
219
- // The only path is the O_EXCL claim losing a race — another consumer is
220
- // spending this exact token right now — so classify as already_consumed
221
- // (never a misleading success, never a false not_found).
216
+ // The strict plan is pure, so it is computed before the token is consumed:
217
+ // its userConfirmation.needed decides whether the consume requires a grant,
218
+ // and the result still embeds it.
219
+ const strictPlan = planHcloudCommand(effectiveArgs, { allowWrites: false, mintApprovalToken: false });
220
+ // One snapshot: the confirmation gate, the args-hash binding, the pinView
221
+ // fallback, and the single-use claim all read the SAME entry — the one
222
+ // consumeApprovalToken returns. The pre-consume inspect-gate this replaces
223
+ // verified the grant on one read while execution consumed another, which
224
+ // a same-user store swap between the two reads laundered (the review's
225
+ // TOCTOU repro).
226
+ const consumed = consumeApprovalToken(token, { requireGrant: strictPlan.userConfirmation.needed });
227
+ if (consumed.status === 'grant_required') {
228
+ return {
229
+ status: 'rejected',
230
+ code: 'USER_CONFIRMATION_REQUIRED',
231
+ nextStep: 'Ask the user to run "npx huaweicloud-devkit approve <this approvalToken>" in their own terminal, then retry this exact call.',
232
+ };
233
+ }
234
+ if (consumed.status === 'gone') {
235
+ // Defensive: inspectApprovalToken said 'valid' but consume returned gone.
236
+ // The paths are the O_EXCL claim losing a race (another consumer is
237
+ // spending this exact token right now) or a store swap removing the
238
+ // entry between the two reads — classify via re-inspect, never a
239
+ // misleading success and never a false not_found.
222
240
  const recheck = inspectApprovalToken(token);
223
241
  if (recheck.state === 'expired')
224
242
  return { status: 'rejected', code: 'CONFIRM_TOKEN_EXPIRED' };
225
243
  return { status: 'ok', outcome: 'already_processed' };
226
244
  }
245
+ const stored = consumed.entry;
227
246
  if (hashArgs(effectiveArgs) !== stored.argsHash) {
228
247
  // The pin view is the canonical fold for the substitution comparison
229
248
  // (loop round 4, seat-1 B2): it folds the two-token/glued secret forms
@@ -249,7 +268,6 @@ async function runApprovedCommand(args = {}) {
249
268
  throw new Error('Secret values are pinned to the approved plan: re-run huaweicloud_plan_cli_command with the final values and re-approve.');
250
269
  }
251
270
  }
252
- const strictPlan = planHcloudCommand(effectiveArgs, { allowWrites: false });
253
271
  const result = await runHcloud(effectiveArgs, {
254
272
  allowWrites: true,
255
273
  timeoutMs: args.timeoutMs,
@@ -373,7 +391,7 @@ export const HUAWEICLOUD_CLI_TOOLS = [
373
391
  },
374
392
  {
375
393
  name: 'huaweicloud_plan_cli_command',
376
- description: 'Classify and plan a Huawei Cloud hcloud command without executing it. Vendor-gated (vendorConfirmed): call only when the vendor is established — see the vendorConfirmed parameter description; when unknown, ask which cloud the user means first.',
394
+ description: "Classify and plan a Huawei Cloud hcloud command without executing it. When the result's userConfirmation.needed is true, the USER must confirm in their own terminal by running the userConfirmation.command line (npx huaweicloud-devkit approve <approvalToken>) before huaweicloud_run_approved_command will accept the command. Vendor-gated (vendorConfirmed): call only when the vendor is established — see the vendorConfirmed parameter description; when unknown, ask which cloud the user means first.",
377
395
  schema: planCliCommandSchema,
378
396
  handler: handlePlanCliCommand,
379
397
  },
@@ -391,7 +409,7 @@ export const HUAWEICLOUD_CLI_TOOLS = [
391
409
  },
392
410
  {
393
411
  name: 'huaweicloud_run_approved_command',
394
- description: 'Run a write-capable hcloud command only after the exact command has been shown and explicitly approved by the user. Vendor-gated (vendorConfirmed): call only when the vendor is established — see the vendorConfirmed parameter description; when unknown, ask which cloud the user means first.',
412
+ description: 'Run a write-capable hcloud command only after the exact command has been shown and explicitly approved by the user, and after the user confirmed the plan token in their own terminal (npx huaweicloud-devkit approve <token>). A non-read command without that terminal confirmation is rejected with USER_CONFIRMATION_REQUIRED and the token stays usable. Vendor-gated (vendorConfirmed): call only when the vendor is established — see the vendorConfirmed parameter description; when unknown, ask which cloud the user means first.',
395
413
  schema: runApprovedCommandSchema,
396
414
  handler: handleRunApprovedCommand,
397
415
  },
@@ -30,7 +30,15 @@ export function installRuntimeDeps(pluginsDir) {
30
30
  stdio: 'pipe',
31
31
  timeout: 120000,
32
32
  };
33
- let r = spawnSync('npm', ['install', '--omit=dev', '--no-audit', '--no-fund'], spawnOpts);
33
+ // A string command, never an args array: args + shell:true is DEP0190 on
34
+ // Node 24 (the shell concatenates args unescaped), and the warning lands
35
+ // on the CLI's own stderr mid-install — deferred by emitWarning, it even
36
+ // surfaced glued to the provisioning prompt (2026-11-10 report #2). The
37
+ // words are static, so the shell concatenation is injection-safe by
38
+ // construction, and shell:true stays load-bearing: it routes npm.cmd on
39
+ // Windows (the #643 EINVAL doctrine).
40
+ const installCommand = 'npm install --omit=dev --no-audit --no-fund';
41
+ let r = spawnSync(installCommand, spawnOpts);
34
42
  const isRetryable = (res) => {
35
43
  if (res.status === 0)
36
44
  return false;
@@ -40,12 +48,12 @@ export function installRuntimeDeps(pluginsDir) {
40
48
  if (r.status !== 0 && isRetryable(r)) {
41
49
  console.log(` \x1b[33m[WARN]\x1b[0m npm install hit file-lock error, retrying in 2s...`);
42
50
  sleepSync(2000);
43
- r = spawnSync('npm', ['install', '--omit=dev', '--no-audit', '--no-fund'], spawnOpts);
51
+ r = spawnSync(installCommand, spawnOpts);
44
52
  }
45
53
  if (r.status !== 0 && !isRetryable(r)) {
46
54
  console.log(` \x1b[33m[RETRY]\x1b[0m npm install failed (exit ${r.status}), retrying in 3s...`);
47
55
  sleepSync(3000);
48
- r = spawnSync('npm', ['install', '--omit=dev', '--no-audit', '--no-fund'], spawnOpts);
56
+ r = spawnSync(installCommand, spawnOpts);
49
57
  }
50
58
  const undiciDir = join(pluginsDir, 'node_modules', 'undici');
51
59
  if (r.status === 0 && existsSync(undiciDir)) {
@@ -818,6 +818,19 @@ export function classifyTextCommand(command, options = {}) {
818
818
  reason: 'Printing vault secrets into the agent context is blocked. Run the value consumer instead: npx huaweicloud-devkit secret exec --env NAME=secret://<scope>/<name> -- <command> — a child you trust not to print its own environment, since its stdout is this conversation. Or use secret get --file from your own terminal.',
819
819
  };
820
820
  }
821
+ // The approval CLI's terminal-only verbs: `approve` consumes the plan token
822
+ // the user is meant to confirm in their own TTY (PIN-checked), and `pin`
823
+ // enrolls the credential that confirm checks. An agent that runs either
824
+ // from Bash drives the human's channel itself — an enrolled-by-agent PIN
825
+ // owns every later confirmation — so both verbs deny. Matched against the
826
+ // same two shadows as the reveal gate.
827
+ if (shadowCandidates.some((candidate) => matchesAny(candidate, policy.blockedApprovalCliPatterns))) {
828
+ return {
829
+ decision: 'deny',
830
+ risk: 'approval',
831
+ reason: "Running the approval CLI from the agent Bash face is blocked: the confirmation must come from the user's own interactive terminal, where the PIN is checked. Ask the user to run the printed npx huaweicloud-devkit approve <token> line themselves (first use: npx huaweicloud-devkit pin, once), then retry the same call.",
832
+ };
833
+ }
821
834
  // Order-independent reveal pair: `echo secret get <ref> --stdout | xargs
822
835
  // npx huaweicloud-devkit` reorders the argv through xargs while every word
823
836
  // is literal in the text — the patterns above assume bin-before-
@@ -37,6 +37,7 @@ export function loadPolicy(path) {
37
37
  blockedConfigureSubcommands: toStringArray(raw.blockedConfigureSubcommands, 'blockedConfigureSubcommands'),
38
38
  blockedSecretOperations: toStringArray(raw.blockedSecretOperations, 'blockedSecretOperations'),
39
39
  blockedSecretCliPatterns: toStringArray(raw.blockedSecretCliPatterns, 'blockedSecretCliPatterns'),
40
+ blockedApprovalCliPatterns: toStringArray(raw.blockedApprovalCliPatterns, 'blockedApprovalCliPatterns'),
40
41
  writeOperationPrefixes,
41
42
  readOperationPrefixes: toStringArray(raw.readOperationPrefixes, 'readOperationPrefixes'),
42
43
  readOperationExceptions: toStringArray(raw.readOperationExceptions, 'readOperationExceptions'),
@@ -14,6 +14,7 @@ import { cmdProxy } from "./proxy/cli.js";
14
14
  import { removeKooCli, removeObsConfig } from "./sandbox/uninstall-cleanup.js";
15
15
  import { readReceipt, removeReceipt } from "./dep/receipts.js";
16
16
  import { runSecretCommand } from "./lib/secret-vault/cli.js";
17
+ import { createProcessApproveIo, runApproveCommand, runPinCommand } from "./approvals-cli.js";
17
18
  import { custodyReport } from "./lib/secret-vault/custody.js";
18
19
  import { vaultList } from "./lib/secret-vault/store.js";
19
20
  import { detectCodeartsSandbox } from "./codearts-sandbox.js";
@@ -24,6 +25,7 @@ import { queryDistTagsFetch, determineTarget, semverCompare } from "./update-che
24
25
  import { getKooCliVersion, compareVersion, kooCliDownloadBase } from "./koocli-version.js";
25
26
  import { hcloudProbeNextStep, hcloudProbeRaw, probeHcloud } from "./hcloud-probe.js";
26
27
  import { asRecord } from "./lib/as-record.js";
28
+ import { devkitStateBase, displayStatePath, huaweiConfigBase, probeWritableDir } from "./lib/state-dir.js";
27
29
  import { DEPENDENCIES, DEPENDENCY_IDS, requiredDependencies } from "./lib/dependency-model.js";
28
30
  import { resolveDependencyCommand } from "./lib/dep-resolve.js";
29
31
  // The installer's payload machinery: file ops, server payload placement,
@@ -764,6 +766,21 @@ async function cmdDoctor() {
764
766
  const nodeParts = process.versions.node.split('.').map(Number);
765
767
  const nodeOk = nodeParts[0] > 22 || (nodeParts[0] === 22 && nodeParts[1] >= 19);
766
768
  check('Node.js >= 22.19', nodeOk, 'Run: nvm install 22.19 && nvm use 22.19');
769
+ // State directory — gateway pack state, approval tokens, S1 writes and
770
+ // update state all write here. A read-only home falls back to an
771
+ // agent-owned dir (state-dir.ts); the fallback is a warning, not a failure.
772
+ const configBase = huaweiConfigBase();
773
+ const stateBase = devkitStateBase();
774
+ const stateDisplay = displayStatePath(stateBase);
775
+ if (stateBase === configBase) {
776
+ check(`State directory writable (${stateDisplay})`, probeWritableDir(stateBase), 'Fix permissions, or set HUAWEICLOUD_STATE_DIR to a writable path');
777
+ }
778
+ else if (probeWritableDir(stateBase)) {
779
+ ctx.warn(`State directory fallback: ${stateDisplay} (${displayStatePath(configBase)} is not writable; set HUAWEICLOUD_STATE_DIR to pin it)`);
780
+ }
781
+ else {
782
+ check(`State directory writable (${stateDisplay})`, false, 'Set HUAWEICLOUD_STATE_DIR to a writable path');
783
+ }
767
784
  // MCP server — derived from the per-row doctor bindings (one membership
768
785
  // table for every payload check in this doctor run). The bindings run the
769
786
  // pure triple probes here; their native-freshness halves run late, after
@@ -1273,6 +1290,12 @@ async function main() {
1273
1290
  case 'secret':
1274
1291
  process.exitCode = runSecretCommand(process.argv.slice(3));
1275
1292
  break;
1293
+ case 'approve':
1294
+ process.exitCode = await runApproveCommand(process.argv.slice(3), createProcessApproveIo());
1295
+ break;
1296
+ case 'pin':
1297
+ process.exitCode = await runPinCommand(process.argv.slice(3), createProcessApproveIo());
1298
+ break;
1276
1299
  case 'proxy':
1277
1300
  await cmdProxy();
1278
1301
  break;
@@ -142,6 +142,21 @@ export function getToolSchema(name) {
142
142
  export function toolSchemaEntries() {
143
143
  return Object.entries(TOOL_SCHEMAS);
144
144
  }
145
+ const argKeyCache = new Map();
146
+ // The keys a tool's input schema declares, plus the central vendorConfirmed
147
+ // part (rendered only on cloud-facing tools but accepted by the dispatch gate
148
+ // everywhere). callTool's unknown-parameter warning reads this; the #530
149
+ // pass-through leniency itself is unchanged.
150
+ export function toolArgKeys(name) {
151
+ const cached = argKeyCache.get(name);
152
+ if (cached)
153
+ return cached;
154
+ const def = TOOL_SCHEMAS[name]._zod?.def;
155
+ const keys = new Set(Object.keys(def?.shape ?? {}));
156
+ keys.add('vendorConfirmed');
157
+ argKeyCache.set(name, keys);
158
+ return keys;
159
+ }
145
160
  // Runtime guard: every entry must be a constructed zod loose-object. A bare
146
161
  // raw shape would be wrapped by the SDK into STRIP semantics, silently
147
162
  // dropping client keys instead of passing them through.
@@ -25,12 +25,14 @@ import { PACK_TOOL_HANDLERS, isPackToolName } from "./packs/registry.js";
25
25
  // the build-time --check stray scan, and validate-package's skill gate all
26
26
  // hold one membership predicate (dir-or-symlink with a SKILL.md).
27
27
  import { listSkillDirs } from "./lib/skill-tree.js";
28
+ import { attachParamWarnings, unknownParamWarnings } from "./lib/param-warnings.js";
28
29
  import { recordToolCall, traceEnabled } from "./lib/call-trace.js";
29
30
  // The tool name/description registry (TOOL_DEFINITIONS_LITERALS and its
30
31
  // derived types) lives in tool-definitions.ts; this module keeps the
31
32
  // re-export face every importer (mcp-protocol, tests, scripts) already
32
33
  // targets — same exported names, same import path, same behavior.
33
34
  import { TOOL_DEFINITIONS } from "./tool-definitions.js";
35
+ import { toolArgKeys } from "./tool-schemas.js";
34
36
  // The vendorConfirmed gate (VENDOR_GATED_TOOLS, the gate/challenge
35
37
  // messages, and the once-per-session challenge state) lives in
36
38
  // vendor-gate.ts; this module re-exports the roster for its existing
@@ -101,15 +103,19 @@ export async function callTool(name, rawArgs = {}, opts = {}) {
101
103
  const args = normalizeNumericArgs(rawArgs);
102
104
  const toolValue = toolInvokeValue(name, args);
103
105
  trackToolInvoke(name, toolValue);
106
+ // Unknown keys stay accepted (#530 leniency) but are no longer silent: a
107
+ // typo'd optional parameter would otherwise return a default-shaped result
108
+ // the model reads as a successful filter.
109
+ const paramWarnings = unknownParamWarnings(args, toolArgKeys(name));
104
110
  // Trace sits between normalization and dispatch: it records the shape
105
111
  // the handler will actually see, and only calls that reached dispatch —
106
112
  // SDK-level zod rejects never get here (see lib/call-trace.ts contract).
107
113
  if (!traceEnabled())
108
- return dispatchTool(name, args, opts);
114
+ return attachParamWarnings(await dispatchTool(name, args, opts), paramWarnings);
109
115
  try {
110
116
  const result = await dispatchTool(name, args, opts);
111
117
  recordToolCall(name, args, true);
112
- return result;
118
+ return attachParamWarnings(result, paramWarnings);
113
119
  }
114
120
  catch (error) {
115
121
  recordToolCall(name, args, false, error);
@@ -180,11 +186,14 @@ function hookResult(result) {
180
186
  ok: result.decision !== 'deny',
181
187
  decision: result.decision,
182
188
  findings: result.findings,
189
+ // allow means "no rule matched", never "approved": make that explicit so
190
+ // an agent cannot read a green advisory check as a safety verdict.
191
+ ...(result.decision === 'allow' ? { unmatched: true } : {}),
183
192
  nextStep: result.decision === 'deny'
184
193
  ? 'Revise the command, artifact, or deployment plan before execution.'
185
194
  : result.decision === 'warn'
186
195
  ? 'Review the warnings with the user before proceeding.'
187
- : 'No Huawei Cloud hook risk rule matched.',
196
+ : 'No Huawei Cloud hook risk rule matched. This is not a safety verdict or an approval.',
188
197
  };
189
198
  }
190
199
  // The advisory command face used to answer a bare allow for an hcloud command
@@ -199,7 +208,10 @@ function hookResult(result) {
199
208
  // cn hint, and a real service or a missing catalog keeps the original wording.
200
209
  // The run faces stay allow for everything but the triage's negative-evidence
201
210
  // deny (refined at planHcloudCommand, which the run engine asserts), and the
202
- // PreToolUse hook is untouched (it acts on deny alone).
211
+ // PreToolUse hook is untouched (it acts on deny alone). The same face upgrades
212
+ // classified write/execution operations to hwc-write-operation: the advisory
213
+ // signal that a write needs the plan + approval path, never an execution
214
+ // block (run_readonly_command and the approval chain own that decision).
203
215
  // `classify` is injectable so the OBS-14-shape closure is honestly pinnable:
204
216
  // a classifier crash used to fall through to the bare allow (silent fail-open,
205
217
  // the #564 shape one layer up); it now degrades to an hwc-unverified-command
@@ -227,6 +239,18 @@ const unverifiedFinding = (command) => ({
227
239
  source: 'command',
228
240
  evidence: command.slice(0, 240),
229
241
  });
242
+ const writeOperationFinding = (command) => ({
243
+ ruleId: 'hwc-write-operation',
244
+ title: 'Write or execution operation',
245
+ category: 'approval',
246
+ severity: 'warn',
247
+ message: 'This command is classified as a write or execution operation. Raw shell execution is blocked; ' +
248
+ 'writes require a plan and explicit user approval.',
249
+ remediation: 'Plan the exact command with huaweicloud_plan_cli_command, show it to the user, obtain explicit approval, ' +
250
+ 'then run it with huaweicloud_run_approved_command and the approval token.',
251
+ source: 'command',
252
+ evidence: command.slice(0, 240),
253
+ });
230
254
  export function withUnknownOperationWarn(command, result, classify = classifyTextCommand) {
231
255
  if (result.decision !== 'allow' || result.findings.length > 0 || !command.trim())
232
256
  return result;
@@ -237,6 +261,14 @@ export function withUnknownOperationWarn(command, result, classify = classifyTex
237
261
  catch {
238
262
  return { ...result, decision: 'warn', findings: [unverifiedFinding(command)] };
239
263
  }
264
+ // The advisory face never turns a write into "safe": classified writes and
265
+ // execution operations get a warn even when the pattern catalog has no
266
+ // specific finding. The enforcement faces (run_readonly_command, the
267
+ // PreToolUse hook, the plan/run approval chain) are unchanged — this is
268
+ // the pre-flight signal, not the gate.
269
+ if (classification?.risk === 'write' || classification?.risk === 'execution') {
270
+ return { ...result, decision: 'warn', findings: [writeOperationFinding(command)] };
271
+ }
240
272
  if (classification?.risk !== 'unknown_read')
241
273
  return result;
242
274
  const triage = triageUnknownService(classification.service);
@@ -65,7 +65,11 @@ export async function queryDistTagsFetch({ timeoutMs = 15000 } = {}) {
65
65
  }
66
66
  export function queryDistTagsSync({ timeoutMs = 15000, cwd, } = {}) {
67
67
  try {
68
- const result = spawnSync(NPM_BIN, ['view', 'huaweicloud-devkit', 'dist-tags', '--json'], {
68
+ // String command, never an args array: args + shell:true is DEP0190 on
69
+ // Node 24, and the words are static so the shell concatenation is
70
+ // injection-safe. shell:true stays load-bearing: it routes npm.cmd on
71
+ // Windows (the #643 EINVAL doctrine below).
72
+ const result = spawnSync(`${NPM_BIN} view huaweicloud-devkit dist-tags --json`, {
69
73
  encoding: 'utf8',
70
74
  timeout: timeoutMs,
71
75
  windowsHide: true,
@@ -97,7 +101,9 @@ export function queryDistTags({ timeoutMs = 15000, cwd, } = {}) {
97
101
  return new Promise((resolve) => {
98
102
  let child;
99
103
  try {
100
- child = spawn(NPM_BIN, ['view', 'huaweicloud-devkit', 'dist-tags', '--json'], {
104
+ // Same string-command doctrine as queryDistTagsSync: no args array
105
+ // under shell (DEP0190 on Node 24), static words only.
106
+ child = spawn(`${NPM_BIN} view huaweicloud-devkit dist-tags --json`, {
101
107
  windowsHide: true,
102
108
  cwd,
103
109
  shell: true,
@@ -1,19 +1,18 @@
1
1
  // Skip-state (dismiss) persistence for the update machinery: the plugin-local
2
- // skip file with per-session suffixing (#607), the HUAWEICLOUD_HOME fallback,
3
- // and the atomic read/write pair. Part of the src/update-* family behind the
4
- // src/update-check.ts re-export face.
2
+ // skip file with per-session suffixing (#607), the writable-state-tree
3
+ // fallback, and the atomic read/write pair. Part of the src/update-* family
4
+ // behind the src/update-check.ts re-export face.
5
5
  import { existsSync, readFileSync, writeFileSync, renameSync, mkdirSync, rmSync } from 'node:fs';
6
6
  import { join, dirname, resolve } from 'node:path';
7
- import { homedir } from 'node:os';
8
7
  import { asText } from "./lib/as-text.js";
8
+ import { devkitStateBase } from "./lib/pack-state.js";
9
9
  import { selfDir } from "./update-installed.js";
10
10
  const COOLDOWN_DAYS = 3;
11
11
  export function skipFilePath() {
12
12
  return join(resolve(selfDir(), '..'), '.update-skip.json');
13
13
  }
14
14
  export function fallbackSkipFilePath() {
15
- const base = process.env.HUAWEICLOUD_HOME || homedir();
16
- return join(base, '.config', 'huaweicloud', 'devkit-skip.json');
15
+ return join(devkitStateBase(), 'devkit-skip.json');
17
16
  }
18
17
  // 会话化 skip 文件:remote 多会话按 sessionId 拆分,stdio/默认保持原文件(向后兼容)。
19
18
  function sanitizeSessionId(sessionId) {
@@ -10,7 +10,14 @@ import { queryDistTags, errorMessage } from "./update-registry.js";
10
10
  import { invalidateUpdateCache } from "./update-cache.js";
11
11
  const NPX_BIN = process.platform === 'win32' ? 'npx.cmd' : 'npx';
12
12
  function defaultSpawn(command, args, options) {
13
- return spawnSync(command, args, options);
13
+ // The args join into the command string before the spawn: options carries
14
+ // shell:true (the #643 npm.cmd routing; the target interpolation stays
15
+ // guarded by the SUPPORTED_AGENT_TARGETS allowlist, review #717), and an
16
+ // args array under shell is DEP0190 on Node 24. shell:true already
17
+ // concatenates args unescaped, so the join is behavior-identical minus
18
+ // the warning; the seam's (command, args) contract is unchanged for the
19
+ // injected test doubles.
20
+ return spawnSync([command, ...args].join(' '), options);
14
21
  }
15
22
  function restartMessage(target) {
16
23
  if (target === 'officeace') {
@@ -34,6 +34,7 @@ HOOK_EVENTS_PATH = TELEMETRY_DIR / "hook-events.jsonl"
34
34
  CONFIG_FILE_RE = None
35
35
  SECRET_READ_RE = None
36
36
  SECRET_CLI_RE = None
37
+ APPROVAL_CLI_RE = None
37
38
  WRITE_OPERATION_RE = None
38
39
  WRITE_VOCAB_RE = None
39
40
  READ_OPERATION_RE = None
@@ -73,7 +74,7 @@ OBS_MARKER_RE = re.compile(r"\bOBS\b", re.I)
73
74
 
74
75
 
75
76
  def load_policy():
76
- global CONFIG_FILE_RE, SECRET_READ_RE, SECRET_CLI_RE, WRITE_OPERATION_RE, WRITE_VOCAB_RE, READ_OPERATION_RE, READ_OPERATION_EXCEPTIONS
77
+ global CONFIG_FILE_RE, SECRET_READ_RE, SECRET_CLI_RE, APPROVAL_CLI_RE, WRITE_OPERATION_RE, WRITE_VOCAB_RE, READ_OPERATION_RE, READ_OPERATION_EXCEPTIONS
77
78
  try:
78
79
  with POLICY_PATH.open("r", encoding="utf-8") as file_obj:
79
80
  policy = json.load(file_obj)
@@ -188,6 +189,22 @@ def load_policy():
188
189
  blocked_secret_cli = policy.get("blockedSecretCliPatterns", [])
189
190
  if blocked_secret_cli:
190
191
  SECRET_CLI_RE = re.compile("|".join(blocked_secret_cli), re.I)
192
+ # The approval CLI's terminal-confirm verb. No order-independent
193
+ # bin+verb pair guard here, unlike the reveal pair below: `approve`
194
+ # is a common word, so a Huawei Cloud operation named e.g.
195
+ # ApproveThing must never trip this gate. These anchored patterns
196
+ # fire only when a devkit binary spelling is present too.
197
+ blocked_approval_cli = policy.get("blockedApprovalCliPatterns", [])
198
+ if isinstance(blocked_approval_cli, list):
199
+ blocked_approval_cli = [p for p in blocked_approval_cli if isinstance(p, str)]
200
+ if blocked_approval_cli:
201
+ try:
202
+ APPROVAL_CLI_RE = re.compile("|".join(blocked_approval_cli), re.I)
203
+ except re.error:
204
+ # Isolate this gate's degradation: a malformed pattern
205
+ # leaves APPROVAL_CLI_RE None instead of aborting the
206
+ # whole policy load.
207
+ APPROVAL_CLI_RE = None
191
208
  except Exception:
192
209
  pass
193
210
 
@@ -2601,6 +2618,8 @@ def evaluate(tool_name, tool_input):
2601
2618
  return "reading Huawei Cloud credential/profile files can expose AK/SK or tokens. Use redacted toolkit tools."
2602
2619
  if SECRET_CLI_RE and any(SECRET_CLI_RE.search(candidate) for candidate in candidates):
2603
2620
  return "printing vault secrets into the agent context is blocked. Use secret exec so the value reaches only the child process environment."
2621
+ if APPROVAL_CLI_RE and any(APPROVAL_CLI_RE.search(candidate) for candidate in candidates):
2622
+ return "running the approval CLI from the agent Bash face is blocked: the confirmation must come from the user's own interactive terminal, where the PIN is checked. Ask the user to run the printed npx huaweicloud-devkit approve <token> line themselves (first use: npx huaweicloud-devkit pin, once), then retry the same call."
2604
2623
  # Order-independent reveal pair: xargs reorders the argv while every word
2605
2624
  # stays literal — a devkit bin plus a `secret get` pair anywhere is a
2606
2625
  # reveal regardless of order (both shadow candidates — the decoded one
@@ -2,7 +2,7 @@
2
2
  "name": "huaweicloud-devkit",
3
3
  "id": "huaweicloud-devkit",
4
4
  "displayName": "HuaweiCloud DevKit",
5
- "version": "2.0.0-next.0",
5
+ "version": "2.0.0-next.2",
6
6
  "family": "bundle-plugin",
7
7
  "bundleFormat": "codex",
8
8
  "description": "Guide coding agents to use Huawei Cloud safely — KooCLI, APIs, SDKs, 40 MCP tools, skills, and safety guardrails.",
@@ -45,6 +45,14 @@
45
45
  "setup-cli\\.(js|mjs|ts)(\\s+--)?\\s+secret\\s+get\\b",
46
46
  "setup\\.cjs(\\s+--)?\\s+secret\\s+get\\b"
47
47
  ],
48
+ "blockedApprovalCliPatterns": [
49
+ "huaweicloud-devkit(@[\\w.+-]+)?(\\.(js|cjs|mjs|exe|ts))?(\\s+--)?\\s+approve\\b",
50
+ "setup-cli\\.(js|mjs|ts)(\\s+--)?\\s+approve\\b",
51
+ "setup\\.cjs(\\s+--)?\\s+approve\\b",
52
+ "huaweicloud-devkit(@[\\w.+-]+)?(\\.(js|cjs|mjs|exe|ts))?(\\s+--)?\\s+pin\\b",
53
+ "setup-cli\\.(js|mjs|ts)(\\s+--)?\\s+pin\\b",
54
+ "setup\\.cjs(\\s+--)?\\s+pin\\b"
55
+ ],
48
56
  "writeOperationPrefixes": [
49
57
  "Create",
50
58
  "BatchCreate",
@@ -182,6 +182,61 @@
182
182
  "message": "The artifact contains a literal access key, secret key, or security token. Credentials committed to IaC, config, or code leak through git history, logs, and state files.",
183
183
  "remediation": "Remove the literal credential: reference it from environment variables, a DEW CSMS secret reference, or the platform credential vault (huaweicloud_secret_set), and rotate the exposed key immediately."
184
184
  },
185
+ {
186
+ "id": "hwc-artifact-plaintext-password",
187
+ "title": "Plaintext password in artifact",
188
+ "category": "secret",
189
+ "severity": "warn",
190
+ "stages": ["artifact", "deploy_plan"],
191
+ "match": {
192
+ "any": [
193
+ {
194
+ "field": "text",
195
+ "regex": "[A-Za-z0-9_.-]*(?:password|passwd|pwd|secret)(?!://)[\"']?\\s*[:=]\\s*[\"']?(?!(?:<|\\$|%|\\{\\{|#\\{|secret://|var\\.|local\\.|module\\.|data\\.|each\\.|path\\.|terraform\\.|env\\.|os\\.environ|process\\.env|\\*{3,}|changeme|change_me|placeholder|example|xxx|none|N/A))[^\\s\"'<>]{3,}"
196
+ },
197
+ {
198
+ "field": "text",
199
+ "regex": "<(?:password|passwd|pwd)[^>]*>\\s*(?!(?:<|\\$|%|\\{\\{|#\\{|secret://|\\*{3,}|changeme|change_me|placeholder|example|xxx|none|N/A))[^<\\s][^<]{2,}\\s*</(?:password|passwd|pwd)>"
200
+ }
201
+ ]
202
+ },
203
+ "message": "The artifact or plan carries what looks like a plaintext password or secret value.",
204
+ "remediation": "Replace the literal with a secret reference (DEW CSMS, huaweicloud_secret_set, ${VAR}, or var.<name>) and rotate any value that was committed."
205
+ },
206
+ {
207
+ "id": "hwc-container-privileged",
208
+ "title": "Privileged container",
209
+ "category": "container",
210
+ "severity": "deny",
211
+ "stages": ["artifact", "deploy_plan"],
212
+ "match": {
213
+ "any": [
214
+ {
215
+ "field": "text",
216
+ "regex": "\\bprivileged[\"']?\\s*[:=]\\s*[\"']?true\\b"
217
+ }
218
+ ]
219
+ },
220
+ "message": "The manifest or plan runs a container with privileged: true (host devices and capabilities).",
221
+ "remediation": "Drop privileged mode. Grant only the specific capabilities the workload needs (capabilities.add) and run as a non-root user."
222
+ },
223
+ {
224
+ "id": "hwc-container-privilege-escalation",
225
+ "title": "Container privilege escalation allowed",
226
+ "category": "container",
227
+ "severity": "warn",
228
+ "stages": ["artifact", "deploy_plan"],
229
+ "match": {
230
+ "any": [
231
+ {
232
+ "field": "text",
233
+ "regex": "\\ballowPrivilegeEscalation[\"']?\\s*[:=]\\s*[\"']?true\\b"
234
+ }
235
+ ]
236
+ },
237
+ "message": "The manifest allows a process to gain more privileges than its parent (allowPrivilegeEscalation: true).",
238
+ "remediation": "Set allowPrivilegeEscalation: false and runAsNonRoot: true unless the workload provably requires escalation."
239
+ },
185
240
  {
186
241
  "id": "hwc-obs-anonymous-write",
187
242
  "title": "OBS anonymous write",
@@ -244,17 +299,38 @@
244
299
  },
245
300
  {
246
301
  "field": "text",
247
- "regex": "(\\\"Action\\\"\\s*:\\s*(\\\"(\\*|\\*:\\*)\\\"|\\[\\s*\\\"(\\*|\\*:\\*)\\\")|Action\\s*[=:]\\s*(\\*|\\*:\\*)|AdministratorAccess|FullAccess)"
302
+ "regex": "(\\\"Action\\\"\\s*:\\s*(\\\"(\\*|\\*:\\*)\\\"|\\[\\s*\\\"(\\*|\\*:\\*)\\\")|Action\\s*[=:]\\s*(\\*|\\*:\\*)|[\"']?actions?[\"']?\\s*[=:]\\s*(?:\\[\\s*)?[\"']?(?:\\*|\\*:\\*)|AdministratorAccess|FullAccess)"
248
303
  },
249
304
  {
250
305
  "field": "text",
251
- "regex": "(\\\"Effect\\\"\\s*:\\s*\\\"Allow\\\"|Effect\\s*[=:]\\s*Allow)"
306
+ "regex": "(\\\"Effect\\\"\\s*:\\s*\\\"Allow\\\"|Effect\\s*[=:]\\s*[\"']?Allow[\"']?)"
252
307
  }
253
308
  ]
254
309
  },
255
310
  "message": "The change appears to grant broad administrator permissions.",
256
311
  "remediation": "Use least-privilege service actions, resource constraints, and short-lived credentials for generated application workflows."
257
312
  },
313
+ {
314
+ "id": "hwc-iam-wildcard-action",
315
+ "title": "Wildcard IAM action",
316
+ "category": "iam",
317
+ "severity": "warn",
318
+ "stages": ["command", "artifact", "deploy_plan"],
319
+ "match": {
320
+ "all": [
321
+ {
322
+ "field": "text",
323
+ "regex": "(IAM|policy|role|agency|Statement|Action|actions)"
324
+ },
325
+ {
326
+ "field": "text",
327
+ "regex": "[\"']?(?:Action|actions?)[\"']?\\s*[:=]\\s*(?:\\[\\s*)?[\"']?(?:\\*|\\*:\\*)[\"']?"
328
+ }
329
+ ]
330
+ },
331
+ "message": "The IAM grant uses a wildcard action (* or *:*), which grants every operation on the matched resources.",
332
+ "remediation": "Replace the wildcard with the least-privilege service actions the workflow actually calls, and constrain the resources."
333
+ },
258
334
  {
259
335
  "id": "hwc-iam-highrisk-write",
260
336
  "title": "High-risk IAM write operation",
@@ -99,7 +99,10 @@ curl -sSL https://cn-north-4-hdn-koocli.obs.cn-north-4.myhuaweicloud.com/cli/lat
99
99
  - Read-only: `List*`, `Show*`, `Get*`, `Describe*`.
100
100
  - Write: `Create*`, `Delete*`, `Update*`, `Resize*`, `Start*`, `Stop*`, `Authorize*`, and similar.
101
101
  - Secret: any operation returning secret string, binary secret, token, or password.
102
- 9. For write operations, show the exact command and ask for explicit approval.
102
+ 9. For write operations, follow the terminal confirmation contract:
103
+ - Call `huaweicloud_plan_cli_command` and read `userConfirmation`. When `needed` is true, show the user the command echo and the `userConfirmation.command` line.
104
+ - The user runs `npx huaweicloud-devkit approve <approvalToken>` in their own terminal. Never run it yourself. First use: the user runs `npx huaweicloud-devkit pin` once in their own terminal to enroll the approvals PIN.
105
+ - Then call `huaweicloud_run_approved_command` with that token. An unconfirmed non-read command is rejected with `USER_CONFIRMATION_REQUIRED`; the token stays usable, so retry the same call after the user confirms.
103
106
 
104
107
  ## KooCLI Syntax Notes
105
108
 
@@ -23,21 +23,27 @@ Use this skill before any Huawei Cloud action that may expose secrets, change re
23
23
  - IAM/security
24
24
  - cost/payment
25
25
  - public exposure
26
- 5. For any non-read-only operation, show the exact planned change and wait for explicit user approval.
26
+ 5. For any non-read-only operation, follow the plan, confirm, run contract: plan with `huaweicloud_plan_cli_command`, show the user the command and the terminal confirmation line, wait for the user to confirm in their own terminal, then run with `huaweicloud_run_approved_command`. See `references/approvals.md`.
27
27
  6. Redact secrets from command output, errors, JSON, logs, and generated reports.
28
28
  7. If a command contains `adminPass`, `password`, token, or any secret-like field, warn that plaintext can remain in shell history. Prefer local-only input, runtime injection, or user-side execution.
29
29
 
30
30
  ## Enforcement Layers
31
31
 
32
- - Hooks: `hooks/huaweicloud-safety.mjs` blocks risky Codex native hook calls without requiring Python; `hooks/huaweicloud-safety.py` remains for Hermes/Python hook compatibility.
33
- - MCP wrapper: the Node MCP server applies the same safety policy for Codex/OpenCode paths that do not enforce hooks.
32
+ - Hooks: `hooks/huaweicloud-safety.mjs` blocks risky Codex native hook calls without requiring Python; `hooks/huaweicloud-safety.py` remains for Hermes/Python hook compatibility. The hook also denies the `approve` and `pin` verbs on the agent Bash face.
33
+ - MCP wrapper: the Node MCP server applies the same safety policy for Codex/OpenCode paths that do not enforce hooks, and the run tool refuses a non-read command without the user's terminal confirmation.
34
34
  - Skills: this document teaches agents the rule before they act.
35
35
 
36
36
  ## Write Execution Boundary
37
37
 
38
- - Default path: use `huaweicloud_plan_cli_command` to produce a reviewed command block, then let the user or host agent execute it after approval.
39
- - Approved tool path: use `huaweicloud_run_approved_command` only when the exact planned command has been shown and the user explicitly approved that exact command.
40
- - After a write, verify with `huaweicloud_run_readonly_command` or another read-only check.
38
+ 1. Plan: call `huaweicloud_plan_cli_command`. The result echoes the exact command and carries `userConfirmation: { needed, command }`.
39
+ 2. Confirm: when `needed` is true, show the user the plan echo and the `userConfirmation.command` line (`npx huaweicloud-devkit approve <approvalToken>`), then wait. The USER runs that line in their own terminal, where a TTY check and a PIN gate the confirmation. First use: the user runs `npx huaweicloud-devkit pin` once in their own terminal to enroll the PIN.
40
+ 3. Run: call `huaweicloud_run_approved_command` with the same `approvalToken` and `approvedByUser: true`.
41
+
42
+ A non-read command without that terminal confirmation is rejected with `USER_CONFIRMATION_REQUIRED`. The refusal does not consume the token, so retry the same call after the user confirms. Re-running a write needs a fresh plan and a fresh confirmation.
43
+
44
+ Never run the approve or pin commands yourself; the hook denies both verbs on the agent's Bash face. The `approvedByUser: true` argument is not the terminal confirmation and never replaces it.
45
+
46
+ Without the devkit tools, show the reviewed command and let the user execute it in their own terminal. After a write, verify with `huaweicloud_run_readonly_command` or another read-only check.
41
47
 
42
48
  ## Proactive Hook Checks
43
49
 
@@ -58,5 +64,6 @@ Hook checks inspect the command or plan text that is available before execution.
58
64
  - Use redacted profile inspection instead of raw `hcloud configure show`.
59
65
  - Use runtime secret injection instead of fetching secret values into chat.
60
66
  - Use the encrypted secret vault for durable secrets: store values as `secret://<scope>/<name>` refs and pass refs, never values. See `references/secrets.md`.
67
+ - Use the terminal confirmation contract for writes: plan, user confirm, run. See `references/approvals.md`.
61
68
  - Use read-only verification after a write.
62
69
  - Prefer reviewed IaC for durable infrastructure changes.