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
@@ -3,6 +3,7 @@ import { join } from 'node:path';
3
3
 
4
4
  import { copyDir, copyFileVerified, pruneStale } from './payload-files.ts';
5
5
  import { PLUGIN_ROOT } from './payload-utils.ts';
6
+ import { writeIntegrityReceipt } from './safety-integrity.ts';
6
7
 
7
8
  // The server-payload placement (the install-payload.ts internals split):
8
9
  // the one shared seam every per-agent install/update call site ships the
@@ -74,6 +75,13 @@ export function copyServerPayload(pluginDest: string, opts: { skipDist?: boolean
74
75
  }
75
76
  copyDir(join(PLUGIN_ROOT, 'safety'), join(pluginDest, 'safety'));
76
77
  console.log(` Safety Policy -> ${join(pluginDest, 'safety')}`);
78
+ // The integrity receipt (the integrity unit's layer 3): a hash manifest
79
+ // of the classifier files that just landed, written at the one shared
80
+ // placement seam so every install/update path records it and doctor can
81
+ // detect drift later. Covers whatever shipped — a skipDist payload
82
+ // records its safety/ files only.
83
+ writeIntegrityReceipt(pluginDest);
84
+ console.log(` Integrity receipt -> ${join(pluginDest, '.safety-integrity.json')}`);
77
85
  const skillsSrc = join(PLUGIN_ROOT, 'skills');
78
86
  // A missing source tree must abort, not silently skip: copyDir's
79
87
  // existsSync guard would no-op the copy while this function still prints
@@ -4,6 +4,7 @@ import { fileURLToPath } from 'node:url';
4
4
 
5
5
  import { asText } from './lib/as-text.ts';
6
6
  import { asRecord } from './lib/as-record.ts';
7
+ import { redactEvidenceText } from './safety/redact.ts';
7
8
 
8
9
  const __dirname = dirname(fileURLToPath(import.meta.url));
9
10
  const defaultRulesPath = join(__dirname, '..', 'safety', 'rules', 'cloud-risk-rules.json');
@@ -134,12 +135,7 @@ export function loadRiskRules(options: RiskRuleOptions = {}): RiskCatalog {
134
135
  }
135
136
 
136
137
  function redactEvidence(text: unknown): string {
137
- return String(text)
138
- .replace(
139
- /((?: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,
140
- '$1<redacted>',
141
- )
142
- .replace(/\b(AK|SK)\\*["']?\s*[:=]\s*("[^"]*"|'[^']*'|[^\s,;]+)/gi, '$1=<redacted>');
138
+ return redactEvidenceText(text);
143
139
  }
144
140
 
145
141
  function normalizeText(value: unknown): string {
@@ -174,10 +170,27 @@ function evaluationContext(stage: string, input: unknown): EvaluationContext {
174
170
  return { text: normalizeText(input) };
175
171
  }
176
172
 
173
+ // Shell-transcribed commands and nested JSON artifacts arrive with escaped
174
+ // quotes (`\"Action\":` / `{\"privileged\":true}`) — the spelling a shell or
175
+ // an embedded JSON string actually produces. The catalog's JSON-shaped rules
176
+ // were authored against the unescaped spelling, so a backslash between the
177
+ // key and the quote made deny-severity rules (IAM administrator grants, OBS
178
+ // anonymous writes, privileged containers) silently miss. Matching therefore
179
+ // tests the raw value AND a quote-unescaped shadow; evidence/display keep the
180
+ // raw text. Only quote-adjacent backslashes are folded, so Windows paths are
181
+ // untouched.
182
+ function normalizeRuleText(text: string): string {
183
+ return text.replace(/\\+(["'])/g, '$1');
184
+ }
185
+
177
186
  function conditionMatches(condition: RiskRuleCondition, context: EvaluationContext): boolean {
178
187
  const field = condition.field || 'text';
179
188
  const value = Object.hasOwn(context, field) ? context[field] : context.text;
180
- return new RegExp(condition.regex, 'ims').test(String(value || ''));
189
+ const raw = String(value || '');
190
+ const regex = new RegExp(condition.regex, 'ims');
191
+ if (regex.test(raw)) return true;
192
+ const normalized = normalizeRuleText(raw);
193
+ return normalized !== raw && regex.test(normalized);
181
194
  }
182
195
 
183
196
  function ruleMatches(rule: RiskRule, context: EvaluationContext): boolean {
@@ -129,20 +129,28 @@ export function classifyHcloudArgs(args: unknown, options: ClassifyOptions = {})
129
129
  const isWrite = !readOnly && hasWritePrefix(operation, policy);
130
130
 
131
131
  if (isExecution && !options.allowWrites) {
132
- return {
133
- decision: 'deny',
134
- risk: 'execution',
135
- reason: 'Huawei Cloud execution/trigger operation blocked until approved.',
136
- };
132
+ return applyCommandRiskRules(
133
+ {
134
+ decision: 'deny',
135
+ risk: 'execution',
136
+ reason: 'Huawei Cloud execution/trigger operation blocked until approved.',
137
+ },
138
+ normalizedArgs,
139
+ options,
140
+ );
137
141
  }
138
142
 
139
143
  if (isWrite && !options.allowWrites) {
140
- return {
141
- decision: 'deny',
142
- risk: 'write',
143
- reason:
144
- 'Huawei Cloud write operation blocked until the agent presents a plan and receives explicit user approval.',
145
- };
144
+ return applyCommandRiskRules(
145
+ {
146
+ decision: 'deny',
147
+ risk: 'write',
148
+ reason:
149
+ 'Huawei Cloud write operation blocked until the agent presents a plan and receives explicit user approval.',
150
+ },
151
+ normalizedArgs,
152
+ options,
153
+ );
146
154
  }
147
155
 
148
156
  const obsutilWrites = OBSUTIL_WRITES;
@@ -154,11 +162,15 @@ export function classifyHcloudArgs(args: unknown, options: ClassifyOptions = {})
154
162
  const isObsWrite = isObs && obsutilWrites.has(operation.toLowerCase());
155
163
  const isObsRead = isObs && obsutilReads.includes(operation.toLowerCase());
156
164
  if (isObsWrite && !options.allowWrites) {
157
- return {
158
- decision: 'deny',
159
- risk: 'write',
160
- reason: 'OBS write operation blocked until the agent presents a plan and receives explicit user approval.',
161
- };
165
+ return applyCommandRiskRules(
166
+ {
167
+ decision: 'deny',
168
+ risk: 'write',
169
+ reason: 'OBS write operation blocked until the agent presents a plan and receives explicit user approval.',
170
+ },
171
+ normalizedArgs,
172
+ options,
173
+ );
162
174
  }
163
175
  if (isObsRead) {
164
176
  return applyCommandRiskRules(
@@ -4,6 +4,7 @@ import { classifyHcloudArgs } from './classify-hcloud.ts';
4
4
  import { credentialFileCandidates } from './credential-path.ts';
5
5
  import { DEFAULT_POLICY } from './default-policy.ts';
6
6
  import { matchesAny, type ClassifyOptions } from './policy.ts';
7
+ import { protectedPayloadWriteDenied } from './protected-payload.ts';
7
8
  import { applyRawCommandRiskRules } from './risk-merge.ts';
8
9
  import { unwrapSecretExecWrapper } from './secret-exec.ts';
9
10
  import { unwrapSkillQualityCli } from './skill-quality-cli.ts';
@@ -828,6 +829,15 @@ export function classifyTextCommand(command: unknown, options: ClassifyOptions =
828
829
  };
829
830
  }
830
831
 
832
+ // The payload path-write gate (the integrity unit's layer 1): the same
833
+ // candidate doctrine as the credential gate, but WRITE-shaped — a
834
+ // redirection/tee/copy-family/dd/sed -i/patch command targeting a
835
+ // protectedPayloadPathMarkers path denies (the bash-face disarm vector
836
+ // the edit seam closed for edit tools; protected-payload.ts owns the
837
+ // shape spec, mirrored by the py twin after its CONFIG_FILE_RE gate).
838
+ const payloadWrite = protectedPayloadWriteDenied(text, policy);
839
+ if (payloadWrite !== null) return payloadWrite;
840
+
831
841
  // The vault CLI's own reveal surface: `secret get` prints a stored secret
832
842
  // to stdout, which is the agent context when run through the Bash tool.
833
843
  // `secret exec` (values reach only the child env) stays allowed. Matched
@@ -7,6 +7,7 @@ import { stripShellQuotes } from './shell-text.ts';
7
7
  export interface Policy {
8
8
  secretKeyNamePatterns: string[];
9
9
  credentialFilePatterns: string[];
10
+ protectedPayloadPathMarkers: string[];
10
11
  blockedConfigureSubcommands: string[];
11
12
  blockedSecretOperations: string[];
12
13
  blockedSecretCliPatterns: string[];
@@ -59,9 +60,21 @@ export function loadPolicy(path: string): Policy {
59
60
  if (raw.writeOperationPrefixes !== undefined && writeOperationPrefixes.length === 0) {
60
61
  throw new TypeError('safety policy field "writeOperationPrefixes" must not be empty');
61
62
  }
63
+ const protectedPayloadPathMarkers = toStringArray(raw.protectedPayloadPathMarkers, 'protectedPayloadPathMarkers');
64
+ // Same emptied-list doctrine as writeOperationPrefixes: a present-but-empty
65
+ // marker list silently disarms the payload path-write gate, so it fails
66
+ // LOUD at load. The py twin has no load-time throw (its load_policy catches
67
+ // everything) and normalizes the degraded shape to an unset gate — the
68
+ // recorded py fail-open posture for a hand-corrupted policy file, the same
69
+ // divergence class the write vocabulary carries (the .mjs face is the
70
+ // fail-closed one).
71
+ if (raw.protectedPayloadPathMarkers !== undefined && protectedPayloadPathMarkers.length === 0) {
72
+ throw new TypeError('safety policy field "protectedPayloadPathMarkers" must not be empty');
73
+ }
62
74
  return {
63
75
  secretKeyNamePatterns: toStringArray(raw.secretKeyNamePatterns, 'secretKeyNamePatterns'),
64
76
  credentialFilePatterns: toStringArray(raw.credentialFilePatterns, 'credentialFilePatterns'),
77
+ protectedPayloadPathMarkers,
65
78
  blockedConfigureSubcommands: toStringArray(raw.blockedConfigureSubcommands, 'blockedConfigureSubcommands'),
66
79
  blockedSecretOperations: toStringArray(raw.blockedSecretOperations, 'blockedSecretOperations'),
67
80
  blockedSecretCliPatterns: toStringArray(raw.blockedSecretCliPatterns, 'blockedSecretCliPatterns'),
@@ -0,0 +1,97 @@
1
+ import type { RiskDecision } from '../risk-rule-engine.ts';
2
+ import { credentialFileCandidates } from './credential-path.ts';
3
+ import type { Policy } from './default-policy.ts';
4
+
5
+ // The payload path-write gate (the integrity unit's layer 1): a
6
+ // write-shaped shell command that targets the DEPLOYED devkit payload —
7
+ // the classifier files the in-process gates import — denies. The residual
8
+ // it closes: PR #22's seam killed the edit-tool vector on the deployed
9
+ // classifier, but the bash face could still `echo '<permissive>' >
10
+ // …/dist/safety-policy.js` and the adapter's lazy, retryable import loaded
11
+ // the agent's file, disarming every in-process gate mid-session (the TLA
12
+ // counterexample path). READ-shaped references stay allowed: skills reads,
13
+ // skill-tracker, doctor, and plain `cat`/`ls`/`grep` over the payload tree
14
+ // are legitimate agent surface.
15
+ //
16
+ // Write-shape spec (mirrored by the py twin's evaluate gate — keep the two
17
+ // byte-identical in verdicts):
18
+ // candidates: raw text, quote-stripped shadow, path-normalized both (the
19
+ // credentialFileCandidates doctrine — a quote pair inside the path or a
20
+ // redundant `//`/`./` segment must not hide the marker);
21
+ // chunks: each candidate splits on [;&|\n\r] — a crude split, deliberately:
22
+ // it can only over-SPLIT (a separator inside quotes is part of a FILE
23
+ // NAME, and a real payload path never carries one), never join, so a
24
+ // detection can only be lost on non-payload targets;
25
+ // shapes, per chunk (MARKER = the policy alternation):
26
+ // 1. redirect />>?[^;&|]*MARKER/ — target-side marker
27
+ // 2. tee anchor + tee … MARKER — tee's operands are targets
28
+ // 3. cp|mv|rsync|install anchor + … final word carries MARKER (dest)
29
+ // 4. dd anchor + … of=… MARKER — of= is the output
30
+ // 5. sed anchor + … -i … MARKER — in-place edit target
31
+ // 6. patch anchor + … MARKER — operand is the target
32
+ // anchor: chunk start, optional env assignments, then optional
33
+ // sudo/env/nice/nohup/command/xargs heads — command position for the
34
+ // write verbs, so `grep tee <marker-file>` (a read) never trips.
35
+ // Whitespace classes are [ \t] (bash IFS without newline — chunks carry no
36
+ // newlines), keeping JS/py classes identical.
37
+ //
38
+ // Honest ceiling (documented, not closed): quote/variable indirection
39
+ // building the marker path, `cp -t`-style flag targets, timeout-wrapped
40
+ // write verbs, and verbs outside the shape table (truncate/ln/…) are
41
+ // residuals of a text gate; rm/rename of payload files break the gate
42
+ // fail-closed at import time rather than disarm it. Against arbitrary
43
+ // user-permission bash NO purely local mechanism fully closes this — the
44
+ // layer-2 load-time canary and the layer-3 doctor drift check raise the
45
+ // escape cost to forging multiple artifacts.
46
+
47
+ // The shape fragments are shared verbatim with the py twin. Every \s in
48
+ // them is [ \t]; MARKER substitutes the policy alternation.
49
+ function shapeRegexes(markers: string[]): RegExp[] {
50
+ if (markers.length === 0) return [];
51
+ const markerAlt = `(?:${markers.join('|')})`;
52
+ const anchor = String.raw`^[ \t]*(?:[A-Za-z_][A-Za-z0-9_]*=\S*[ \t]+)*(?:(?:sudo|env|nice|nohup|command|xargs)[ \t]+)*`;
53
+ return [
54
+ // 1. Redirection: the marker sits in the redirect's target region.
55
+ // Direction is inherent — `cat <marker> > /tmp/out` keeps its marker
56
+ // BEFORE the operator and never matches.
57
+ new RegExp(String.raw`>>?[^;&|]*` + markerAlt, 'i'),
58
+ // 2. tee: every operand is a write target.
59
+ new RegExp(anchor + String.raw`tee\b[^;&|]*` + markerAlt, 'i'),
60
+ // 3. The copy family: the destination is the LAST operand, so the
61
+ // marker must ride the final word — `cp <marker> /tmp/` (a copy-out)
62
+ // stays allowed.
63
+ new RegExp(anchor + String.raw`(?:cp|mv|rsync|install)\b[^;&|]*[ \t]\S*` + markerAlt + String.raw`\S*[ \t]*$`, 'i'),
64
+ // 4. dd: the of= operand is the output.
65
+ new RegExp(anchor + String.raw`dd\b[^;&|]*\bof[ \t]*=[ \t]*[^;&|]*` + markerAlt, 'i'),
66
+ // 5. sed: a whitespace-preceded -i flag (in-place) anywhere before the
67
+ // marker; a read-only sed over the payload stays allowed.
68
+ new RegExp(anchor + String.raw`sed\b[^;&|]*[ \t]-i\b[^;&|]*` + markerAlt, 'i'),
69
+ // 6. patch: the operand is the file being patched.
70
+ new RegExp(anchor + String.raw`patch\b[^;&|]*` + markerAlt, 'i'),
71
+ ];
72
+ }
73
+
74
+ export function protectedPayloadWriteDenied(text: string, policy: Policy): RiskDecision | null {
75
+ if (policy.protectedPayloadPathMarkers.length === 0) return null;
76
+ const shapes = shapeRegexes(policy.protectedPayloadPathMarkers);
77
+ // The candidates a path-bearing gate tests (the credential gate's set):
78
+ // quoting and path redundancy must not hide the marker.
79
+ for (const candidate of credentialFileCandidates(text)) {
80
+ for (const chunk of candidate.split(/[;&|\n\r]/)) {
81
+ for (const shape of shapes) {
82
+ if (shape.test(chunk)) {
83
+ return {
84
+ decision: 'deny',
85
+ // risk 'invalid': exempt from NO roster exemption class (the
86
+ // .mjs/py hooks skip write/execution/destructive for exempt
87
+ // shapes — a payload-write deny must never be skippable).
88
+ risk: 'invalid',
89
+ reason:
90
+ "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.",
91
+ };
92
+ }
93
+ }
94
+ }
95
+ }
96
+ return null;
97
+ }
@@ -6,7 +6,7 @@ function isSecretKeyName(key: unknown, policy: Policy = DEFAULT_POLICY): boolean
6
6
  .toLowerCase()
7
7
  .replace(/[^a-z0-9]/g, '');
8
8
  if (
9
- /access.*key|secret.*key|security.*token|xauth.*token|authorization|password|passwd|adminpass|credential|private.*key|userdata|metadata|inputvalue/.test(
9
+ /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(
10
10
  normalized,
11
11
  )
12
12
  ) {
@@ -15,6 +15,15 @@ function isSecretKeyName(key: unknown, policy: Policy = DEFAULT_POLICY): boolean
15
15
  return policy.secretKeyNamePatterns.some((pattern) => regexFrom(`^(${pattern})$`).test(String(key)));
16
16
  }
17
17
 
18
+ // The key vocabulary is shared by every evidence/command redaction face.
19
+ // Backslashes around the key/value are tolerated because shell-transcribed
20
+ // commands and nested JSON carry `\"password\":\"…\"` spellings; `secret://`
21
+ // refs are exempt (the ref is conversation-safe by doctrine). `secret_text`
22
+ // and `api_key` joined the family with the AX N-R4.1 fix — DEW's plaintext
23
+ // secret and the DevBridge key were crossing every evidence surface.
24
+ const SECRET_KEY_VALUE_RE =
25
+ /((?: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;
26
+
18
27
  function redactString(text: unknown): string {
19
28
  return (
20
29
  String(text)
@@ -32,14 +41,23 @@ function redactString(text: unknown): string {
32
41
  /(["']?(?:user[_-]?data|metadata|private[_-]?key|authorization|x[_-]?auth[_-]?token)["']?\s*[:=]\s*).*/gi,
33
42
  '$1<redacted>',
34
43
  )
35
- .replace(
36
- /(["']?(?:access[_-]?key(?:[_-]?(?:id|secret))?|secret[_-]?key|secret[_-]?string|secret[_-]?binary|security[_-]?token|token|password|passwd|admin[_-]?pass|credential|input[_-]?value)["']?\s*[:=]\s*)("[^"]*"|'[^']*'|[^\s,;]+)/gi,
37
- '$1<redacted>',
38
- )
39
- .replace(/\b(["']?(?:AK|SK)["']?\s*[:=]\s*)("[^"]*"|'[^']*'|[^\s,;]+)/gi, '$1<redacted>')
44
+ .replace(SECRET_KEY_VALUE_RE, '$1<redacted>')
45
+ // XML settings shapes (`<password>value</password>`, the settings.xml
46
+ // deploy idiom) carry no `:`/`=` separator, so the key-value family
47
+ // never saw them — the artifact evidence echoed the password verbatim
48
+ // (AX N-R4.1). The tag name is backreferenced so a mismatched close
49
+ // tag is not half-redacted.
50
+ .replace(/<(password|passwd|pwd)>[^<]*<\/\1>/gi, '<$1><redacted></$1>')
51
+ .replace(/\b(["']?(?:AK|SK)\\*["']?\s*[:=]\s*[\\"']*\s*)("[^"]*"|'[^']*'|[^\s,;]+)/gi, '$1<redacted>')
40
52
  );
41
53
  }
42
54
 
55
+ // The string-level evidence redaction entry (risk-rule-engine's excerpt and
56
+ // any future evidence face): one vocabulary, no second drift-prone copy.
57
+ export function redactEvidenceText(text: unknown): string {
58
+ return redactString(text);
59
+ }
60
+
43
61
  // Overload parameter names are documentation only; the implementation below
44
62
  // carries the real, used parameters.
45
63
  export function redactSecrets(value: string, policy?: Policy): string;
@@ -1,4 +1,4 @@
1
- import { evaluateCommandRisk, mergeRiskDecision, type RiskDecision } from '../risk-rule-engine.ts';
1
+ import { evaluateCommandRisk, mergeRiskDecision, type RiskDecision, type RiskEvaluation } from '../risk-rule-engine.ts';
2
2
  import type { ClassifyOptions } from './policy.ts';
3
3
 
4
4
  // The risk-rule merge seam for both classifiers: a non-deny base decision
@@ -10,22 +10,43 @@ function commandRiskText(normalizedArgs: string[], options: ClassifyOptions): st
10
10
  return options.rawCommand || ['hcloud', ...normalizedArgs].join(' ');
11
11
  }
12
12
 
13
+ // A deny-severity base (the generic write/execution gate) still carries the
14
+ // catalog's specialized findings: the approval decision the developer reads
15
+ // must show WHY the command is risky (broad administrator grant, anonymous
16
+ // write, high-cost shape), not only the generic "write must be approved".
17
+ // Only findings/warnings are attached — decision, risk, and reason stay the
18
+ // base's, so the PreToolUse hook's risk-shaped exemption logic does not
19
+ // drift.
20
+ function attachRiskFindings(base: RiskDecision, risk: RiskEvaluation): RiskDecision {
21
+ if (!risk.findings || risk.findings.length === 0) return base;
22
+ const warnFindings = risk.findings.filter((finding) => finding.severity !== 'deny');
23
+ return {
24
+ ...base,
25
+ findings: [...(base.findings || []), ...risk.findings],
26
+ ...(warnFindings.length > 0 ? { warnings: [...(base.warnings || []), ...warnFindings] } : {}),
27
+ };
28
+ }
29
+
30
+ function mergeRisk(base: RiskDecision, risk: RiskEvaluation): RiskDecision {
31
+ return base.decision === 'deny' ? attachRiskFindings(base, risk) : mergeRiskDecision(base, risk);
32
+ }
33
+
13
34
  export function applyCommandRiskRules(
14
35
  base: RiskDecision,
15
36
  normalizedArgs: string[],
16
37
  options: ClassifyOptions,
17
38
  ): RiskDecision {
18
- if (base.decision === 'deny' || options.skipRiskRules === true) {
39
+ if (options.skipRiskRules === true) {
19
40
  return base;
20
41
  }
21
42
  const risk = evaluateCommandRisk(commandRiskText(normalizedArgs, options));
22
- return mergeRiskDecision(base, risk);
43
+ return mergeRisk(base, risk);
23
44
  }
24
45
 
25
46
  export function applyRawCommandRiskRules(base: RiskDecision, command: string, options: ClassifyOptions): RiskDecision {
26
- if (base.decision === 'deny' || options.skipRiskRules === true) {
47
+ if (options.skipRiskRules === true) {
27
48
  return base;
28
49
  }
29
50
  const risk = evaluateCommandRisk(command);
30
- return mergeRiskDecision(base, risk);
51
+ return mergeRisk(base, risk);
31
52
  }
@@ -0,0 +1,132 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { existsSync, readdirSync, readFileSync, writeFileSync } from 'node:fs';
3
+ import { join } from 'node:path';
4
+
5
+ // The deployed-payload integrity receipt (the integrity unit's layer 3):
6
+ // install/update records a hash manifest of the CLASSIFIER files the
7
+ // in-process gates import — the same artifacts the layer-1 path gate
8
+ // protects and the layer-2 canaries behavior-check. Doctor compares the
9
+ // current hashes against the receipt: drift (an agent-side rewrite the
10
+ // path gate missed, a half-landed overwrite) FAILs with the reinstall
11
+ // remediation; a payload placed by an older devkit (no receipt yet) WARNs
12
+ // instead — backward compatibility, never a false red.
13
+ //
14
+ // Scope is the classifier chain, not the whole payload: dist/safety-policy.js
15
+ // plus its dist/safety/ import graph (the JS classifier the adapter and the
16
+ // .mjs hook load), safety/policy.json (the vocabulary both faces read), and
17
+ // safety/rules/ (the risk catalog). skills/ and node_modules/ are outside
18
+ // it — they have their own freshness/equality probes, and hashing them
19
+ // would make the receipt churn on every skill edit.
20
+ //
21
+ // A receipt-style marker beside the `.installed` precedent: written by the
22
+ // one shared placement seam (copyServerPayload), owned by the devkit,
23
+ // removed with the plugin dir on uninstall. Unlike `.installed` it
24
+ // persists across server boots (the server deletes the restart marker at
25
+ // boot; the receipt must survive for doctor to read).
26
+
27
+ export const INTEGRITY_RECEIPT_FILE = '.safety-integrity.json';
28
+
29
+ export interface IntegrityReceipt {
30
+ version: 1;
31
+ files: Record<string, string>;
32
+ }
33
+
34
+ export type IntegrityStatus =
35
+ | { status: 'no-payload' }
36
+ | { status: 'no-receipt' }
37
+ | { status: 'match' }
38
+ | { status: 'mismatch'; drifted: string[]; missing: string[]; unrecorded: string[] };
39
+
40
+ function sha256Of(file: string): string {
41
+ return createHash('sha256').update(readFileSync(file)).digest('hex');
42
+ }
43
+
44
+ function filesUnder(dir: string): string[] {
45
+ if (!existsSync(dir)) return [];
46
+ const out: string[] = [];
47
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
48
+ const full = join(dir, entry.name);
49
+ if (entry.isDirectory()) out.push(...filesUnder(full));
50
+ else if (entry.isFile()) out.push(full);
51
+ }
52
+ return out;
53
+ }
54
+
55
+ // The classifier artifacts present under a deployed payload dir, as sorted
56
+ // relative paths. Absent entries (a skipDist payload ships safety/ without
57
+ // dist/) simply stay out of the scope — the receipt records what shipped.
58
+ // The receipt's keys are wire vocabulary (pinned deep-equal in the tests and
59
+ // spelled forward-slash in policy docs), so the platform separator is
60
+ // normalized to posix: join()/readdirSync() produce '\' segments on win32
61
+ // and a raw slice would ship platform-dependent receipt keys.
62
+ export function integrityScopeFiles(dir: string): string[] {
63
+ const rel: string[] = [];
64
+ const push = (path: string) => {
65
+ if (existsSync(join(dir, path))) rel.push(path);
66
+ };
67
+ push('dist/safety-policy.js');
68
+ for (const file of filesUnder(join(dir, 'dist', 'safety'))) {
69
+ rel.push(file.slice(dir.length + 1).replaceAll('\\', '/'));
70
+ }
71
+ push('safety/policy.json');
72
+ for (const file of filesUnder(join(dir, 'safety', 'rules'))) {
73
+ rel.push(file.slice(dir.length + 1).replaceAll('\\', '/'));
74
+ }
75
+ return rel.sort((a, b) => a.localeCompare(b));
76
+ }
77
+
78
+ export function integrityReceiptPath(dir: string): string {
79
+ return join(dir, INTEGRITY_RECEIPT_FILE);
80
+ }
81
+
82
+ // Written at placement time over what actually landed (the verified-copy
83
+ // seam guarantees the bytes; hashing the DEST is the honest record).
84
+ export function writeIntegrityReceipt(dir: string): void {
85
+ const files: Record<string, string> = {};
86
+ for (const rel of integrityScopeFiles(dir)) files[rel] = sha256Of(join(dir, rel));
87
+ const receipt: IntegrityReceipt = { version: 1, files };
88
+ writeFileSync(integrityReceiptPath(dir), `${JSON.stringify(receipt, null, 2)}\n`);
89
+ }
90
+
91
+ // The doctor-side comparison. A receipt entry whose file changed or vanished
92
+ // drifts; a scope file present on disk but absent from the receipt drifts
93
+ // too — no legit path lands classifier files without rewriting the receipt
94
+ // (every install/update writes it), so an unrecorded classifier file is the
95
+ // dropped-in-later tamper shape.
96
+ export function verifyIntegrity(dir: string): IntegrityStatus {
97
+ const receiptFile = integrityReceiptPath(dir);
98
+ const scope = integrityScopeFiles(dir);
99
+ if (scope.length === 0) return { status: 'no-payload' };
100
+ if (!existsSync(receiptFile)) return { status: 'no-receipt' };
101
+ let receipt: IntegrityReceipt;
102
+ try {
103
+ receipt = JSON.parse(readFileSync(receiptFile, 'utf8')) as IntegrityReceipt;
104
+ } catch {
105
+ return { status: 'no-receipt' };
106
+ }
107
+ if (
108
+ receipt === null ||
109
+ typeof receipt !== 'object' ||
110
+ receipt.version !== 1 ||
111
+ receipt.files === null ||
112
+ typeof receipt.files !== 'object'
113
+ ) {
114
+ return { status: 'no-receipt' };
115
+ }
116
+ const recorded = new Set(Object.keys(receipt.files));
117
+ const drifted: string[] = [];
118
+ const missing: string[] = [];
119
+ for (const rel of scope) {
120
+ if (!recorded.has(rel)) continue; // counted as unrecorded below
121
+ const expected = receipt.files[rel];
122
+ if (typeof expected !== 'string' || sha256Of(join(dir, rel)) !== expected) drifted.push(rel);
123
+ }
124
+ for (const rel of Object.keys(receipt.files)) {
125
+ if (!existsSync(join(dir, rel))) missing.push(rel);
126
+ }
127
+ const unrecorded = scope.filter((rel) => !recorded.has(rel));
128
+ if (drifted.length > 0 || missing.length > 0 || unrecorded.length > 0) {
129
+ return { status: 'mismatch', drifted, missing, unrecorded };
130
+ }
131
+ return { status: 'match' };
132
+ }
@@ -236,9 +236,7 @@ export function planDevbridgeCleanup({
236
236
  }
237
237
  }
238
238
 
239
- const killPids = new Set(
240
- hosts.filter((h) => (h.id || h.port != null) && !mappedPids.has(h.pid)).map((h) => h.pid),
241
- );
239
+ const killPids = new Set(hosts.filter((h) => (h.id || h.port != null) && !mappedPids.has(h.pid)).map((h) => h.pid));
242
240
  const samePortIds = samePort == null ? [] : tunnels.filter((t) => hasPort(t.id, samePort)).map((t) => t.id);
243
241
  const orphanIds = tunnels.filter((t) => !protectedIds.has(t.id) && !liveIds.has(t.id)).map((t) => t.id);
244
242
  const deleteSet = new Set([...orphanIds, ...samePortIds]);
@@ -275,7 +273,10 @@ export function planDevbridgeCleanup({
275
273
  return { deleteIds: [...deleteSet], killPids: [...killPids] };
276
274
  }
277
275
 
278
- export function buildDevbridgeCleanupApplyScript({ deleteIds = [], killPids = [] }: Partial<DevbridgeCleanupPlan> = {}): string {
276
+ export function buildDevbridgeCleanupApplyScript({
277
+ deleteIds = [],
278
+ killPids = [],
279
+ }: Partial<DevbridgeCleanupPlan> = {}): string {
279
280
  for (const id of deleteIds) {
280
281
  if (!DEVBRIDGE_TUNNEL_ID_PATTERN.test(String(id))) {
281
282
  throw new Error(`devbridge cleanup: invalid tunnel id ${JSON.stringify(id)}`);
@@ -294,7 +295,8 @@ export function buildDevbridgeCleanupApplyScript({ deleteIds = [], killPids = []
294
295
  // Re-check the process identity before killing: state→apply can take
295
296
  // minutes, so a recycled PID must not hit an unrelated process.
296
297
  ...killPids.map(
297
- (pid) => `if ps -p ${pid} -o args= 2>/dev/null | grep -q "devbridge host"; then kill ${pid} >/dev/null 2>&1 || true; fi`,
298
+ (pid) =>
299
+ `if ps -p ${pid} -o args= 2>/dev/null | grep -q "devbridge host"; then kill ${pid} >/dev/null 2>&1 || true; fi`,
298
300
  ),
299
301
  `sleep 1`,
300
302
  ...deleteIds.map((id) => `devbridge delete ${id} >/dev/null 2>&1 || true`),
@@ -123,6 +123,7 @@ import {
123
123
  deployOpenCode,
124
124
  opencodeDoctorAskRule,
125
125
  opencodeDoctorMcpConfigured,
126
+ opencodeDoctorSafetyGate,
126
127
  opencodeDoctorSeam,
127
128
  opencodeStatus,
128
129
  uninstallOpenCode,
@@ -975,6 +976,12 @@ async function cmdDoctor(): Promise<void> {
975
976
  const safetyOk = sections.some((section) => section.triple.safety);
976
977
  check('Safety policy installed', safetyOk, 'Run: npx huaweicloud-devkit install');
977
978
 
979
+ // The integrity unit's layer 3: per-row comparison of the deployed
980
+ // classifier files against the receipt the placement seam wrote. A row
981
+ // with no payload stays silent; a payload without a receipt WARNs (a
982
+ // pre-integrity install); drift FAILs with the reinstall remediation.
983
+ for (const section of sections) section.integrity(ctx);
984
+
978
985
  // Secret vault — custody tier and inventory only; doctor never decrypts.
979
986
  try {
980
987
  const custody = custodyReport();
@@ -1057,6 +1064,7 @@ async function cmdDoctor(): Promise<void> {
1057
1064
  if (installedPayload?.id === 'opencode') {
1058
1065
  opencodeDoctorSeam(ctx);
1059
1066
  opencodeDoctorAskRule(ctx);
1067
+ opencodeDoctorSafetyGate(ctx);
1060
1068
  }
1061
1069
 
1062
1070
  // The codex client yield (PR-5): the per-tool approval_mode blocks the
@@ -186,6 +186,10 @@ export const TOOL_DEFINITIONS_LITERALS = [
186
186
  name: 'huaweicloud_sandbox_expose_tunnel',
187
187
  description: packDescription('huaweicloud_sandbox_expose_tunnel'),
188
188
  },
189
+ {
190
+ name: 'huaweicloud_sandbox_expose_poll',
191
+ description: packDescription('huaweicloud_sandbox_expose_poll'),
192
+ },
189
193
  {
190
194
  name: 'huaweicloud_sandbox_check_user',
191
195
  description: packDescription('huaweicloud_sandbox_check_user'),