huaweicloud-devkit 2.0.0-next.5 → 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 (40) 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 +1 -1
  6. package/plugins/huaweicloud-core/.codex-plugin/plugin.json +1 -1
  7. package/plugins/huaweicloud-core/.cursor-plugin/plugin.json +1 -1
  8. package/plugins/huaweicloud-core/.hermes-plugin/plugin.json +1 -1
  9. package/plugins/huaweicloud-core/.workbuddy-plugin/plugin.json +1 -1
  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/lib/opencode-permission-seam.js +51 -20
  15. package/plugins/huaweicloud-core/dist/mcp-server.js +85 -8
  16. package/plugins/huaweicloud-core/dist/mcp-server.js.map +4 -4
  17. package/plugins/huaweicloud-core/dist/packs/auth/tools.js +5 -1
  18. package/plugins/huaweicloud-core/dist/payload-placement.js +8 -0
  19. package/plugins/huaweicloud-core/dist/safety/classify-text.js +10 -0
  20. package/plugins/huaweicloud-core/dist/safety/policy.js +12 -0
  21. package/plugins/huaweicloud-core/dist/safety/protected-payload.js +93 -0
  22. package/plugins/huaweicloud-core/dist/safety-integrity.js +122 -0
  23. package/plugins/huaweicloud-core/dist/setup-cli.js +8 -1
  24. package/plugins/huaweicloud-core/hooks/huaweicloud-safety.mjs +44 -1
  25. package/plugins/huaweicloud-core/hooks/huaweicloud-safety.py +61 -1
  26. package/plugins/huaweicloud-core/openclaw.plugin.json +2 -2
  27. package/plugins/huaweicloud-core/safety/policy.json +5 -0
  28. package/plugins/huaweicloud-core/skills/huaweicloud-safety/references/approvals.md +1 -1
  29. package/plugins/huaweicloud-core/src/agents/opencode-config.ts +33 -3
  30. package/plugins/huaweicloud-core/src/agents/opencode.ts +66 -15
  31. package/plugins/huaweicloud-core/src/approval-gate.ts +29 -4
  32. package/plugins/huaweicloud-core/src/doctor-payload.ts +40 -2
  33. package/plugins/huaweicloud-core/src/lib/opencode-permission-seam.ts +60 -19
  34. package/plugins/huaweicloud-core/src/packs/auth/tools.ts +7 -1
  35. package/plugins/huaweicloud-core/src/payload-placement.ts +8 -0
  36. package/plugins/huaweicloud-core/src/safety/classify-text.ts +10 -0
  37. package/plugins/huaweicloud-core/src/safety/policy.ts +13 -0
  38. package/plugins/huaweicloud-core/src/safety/protected-payload.ts +97 -0
  39. package/plugins/huaweicloud-core/src/safety-integrity.ts +132 -0
  40. package/plugins/huaweicloud-core/src/setup-cli.ts +8 -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);
@@ -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 { 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
+ }
@@ -0,0 +1,122 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { existsSync, readdirSync, readFileSync, writeFileSync } from 'node:fs';
3
+ import { join } from 'node:path';
4
+ // The deployed-payload integrity receipt (the integrity unit's layer 3):
5
+ // install/update records a hash manifest of the CLASSIFIER files the
6
+ // in-process gates import — the same artifacts the layer-1 path gate
7
+ // protects and the layer-2 canaries behavior-check. Doctor compares the
8
+ // current hashes against the receipt: drift (an agent-side rewrite the
9
+ // path gate missed, a half-landed overwrite) FAILs with the reinstall
10
+ // remediation; a payload placed by an older devkit (no receipt yet) WARNs
11
+ // instead — backward compatibility, never a false red.
12
+ //
13
+ // Scope is the classifier chain, not the whole payload: dist/safety-policy.js
14
+ // plus its dist/safety/ import graph (the JS classifier the adapter and the
15
+ // .mjs hook load), safety/policy.json (the vocabulary both faces read), and
16
+ // safety/rules/ (the risk catalog). skills/ and node_modules/ are outside
17
+ // it — they have their own freshness/equality probes, and hashing them
18
+ // would make the receipt churn on every skill edit.
19
+ //
20
+ // A receipt-style marker beside the `.installed` precedent: written by the
21
+ // one shared placement seam (copyServerPayload), owned by the devkit,
22
+ // removed with the plugin dir on uninstall. Unlike `.installed` it
23
+ // persists across server boots (the server deletes the restart marker at
24
+ // boot; the receipt must survive for doctor to read).
25
+ export const INTEGRITY_RECEIPT_FILE = '.safety-integrity.json';
26
+ function sha256Of(file) {
27
+ return createHash('sha256').update(readFileSync(file)).digest('hex');
28
+ }
29
+ function filesUnder(dir) {
30
+ if (!existsSync(dir))
31
+ return [];
32
+ const out = [];
33
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
34
+ const full = join(dir, entry.name);
35
+ if (entry.isDirectory())
36
+ out.push(...filesUnder(full));
37
+ else if (entry.isFile())
38
+ out.push(full);
39
+ }
40
+ return out;
41
+ }
42
+ // The classifier artifacts present under a deployed payload dir, as sorted
43
+ // relative paths. Absent entries (a skipDist payload ships safety/ without
44
+ // dist/) simply stay out of the scope — the receipt records what shipped.
45
+ // The receipt's keys are wire vocabulary (pinned deep-equal in the tests and
46
+ // spelled forward-slash in policy docs), so the platform separator is
47
+ // normalized to posix: join()/readdirSync() produce '\' segments on win32
48
+ // and a raw slice would ship platform-dependent receipt keys.
49
+ export function integrityScopeFiles(dir) {
50
+ const rel = [];
51
+ const push = (path) => {
52
+ if (existsSync(join(dir, path)))
53
+ rel.push(path);
54
+ };
55
+ push('dist/safety-policy.js');
56
+ for (const file of filesUnder(join(dir, 'dist', 'safety'))) {
57
+ rel.push(file.slice(dir.length + 1).replaceAll('\\', '/'));
58
+ }
59
+ push('safety/policy.json');
60
+ for (const file of filesUnder(join(dir, 'safety', 'rules'))) {
61
+ rel.push(file.slice(dir.length + 1).replaceAll('\\', '/'));
62
+ }
63
+ return rel.sort((a, b) => a.localeCompare(b));
64
+ }
65
+ export function integrityReceiptPath(dir) {
66
+ return join(dir, INTEGRITY_RECEIPT_FILE);
67
+ }
68
+ // Written at placement time over what actually landed (the verified-copy
69
+ // seam guarantees the bytes; hashing the DEST is the honest record).
70
+ export function writeIntegrityReceipt(dir) {
71
+ const files = {};
72
+ for (const rel of integrityScopeFiles(dir))
73
+ files[rel] = sha256Of(join(dir, rel));
74
+ const receipt = { version: 1, files };
75
+ writeFileSync(integrityReceiptPath(dir), `${JSON.stringify(receipt, null, 2)}\n`);
76
+ }
77
+ // The doctor-side comparison. A receipt entry whose file changed or vanished
78
+ // drifts; a scope file present on disk but absent from the receipt drifts
79
+ // too — no legit path lands classifier files without rewriting the receipt
80
+ // (every install/update writes it), so an unrecorded classifier file is the
81
+ // dropped-in-later tamper shape.
82
+ export function verifyIntegrity(dir) {
83
+ const receiptFile = integrityReceiptPath(dir);
84
+ const scope = integrityScopeFiles(dir);
85
+ if (scope.length === 0)
86
+ return { status: 'no-payload' };
87
+ if (!existsSync(receiptFile))
88
+ return { status: 'no-receipt' };
89
+ let receipt;
90
+ try {
91
+ receipt = JSON.parse(readFileSync(receiptFile, 'utf8'));
92
+ }
93
+ catch {
94
+ return { status: 'no-receipt' };
95
+ }
96
+ if (receipt === null ||
97
+ typeof receipt !== 'object' ||
98
+ receipt.version !== 1 ||
99
+ receipt.files === null ||
100
+ typeof receipt.files !== 'object') {
101
+ return { status: 'no-receipt' };
102
+ }
103
+ const recorded = new Set(Object.keys(receipt.files));
104
+ const drifted = [];
105
+ const missing = [];
106
+ for (const rel of scope) {
107
+ if (!recorded.has(rel))
108
+ continue; // counted as unrecorded below
109
+ const expected = receipt.files[rel];
110
+ if (typeof expected !== 'string' || sha256Of(join(dir, rel)) !== expected)
111
+ drifted.push(rel);
112
+ }
113
+ for (const rel of Object.keys(receipt.files)) {
114
+ if (!existsSync(join(dir, rel)))
115
+ missing.push(rel);
116
+ }
117
+ const unrecorded = scope.filter((rel) => !recorded.has(rel));
118
+ if (drifted.length > 0 || missing.length > 0 || unrecorded.length > 0) {
119
+ return { status: 'mismatch', drifted, missing, unrecorded };
120
+ }
121
+ return { status: 'match' };
122
+ }
@@ -67,7 +67,7 @@ import { codexDesktopDoctorMcpConfigured, deployCodexDesktop, uninstallCodexDesk
67
67
  import { codexDoctorApprovalRow } from "./agents/codex-config.js";
68
68
  import { deployDsh, dshStatus, uninstallDsh } from "./agents/dsh.js";
69
69
  import { dshDoctorMcpConfigured, dshPayloadDoctorSection } from "./agents/dsh-patch.js";
70
- import { deployOpenCode, opencodeDoctorAskRule, opencodeDoctorMcpConfigured, opencodeDoctorSeam, opencodeStatus, uninstallOpenCode, } from "./agents/opencode.js";
70
+ import { deployOpenCode, opencodeDoctorAskRule, opencodeDoctorMcpConfigured, opencodeDoctorSafetyGate, opencodeDoctorSeam, opencodeStatus, uninstallOpenCode, } from "./agents/opencode.js";
71
71
  import { deployOpenClaw, openclawDoctorMcpConfigured, openclawStatus, uninstallOpenClaw } from "./agents/openclaw.js";
72
72
  import { codeartsDoctorMcpConfigured, codeartsStatus, deployCodeArts, uninstallCodeArts } from "./agents/codearts.js";
73
73
  import { codeartsWorkDoctorMcpConfigured, codeartsWorkStatus, deployCodeArtsWork, uninstallCodeArtsWork, } from "./agents/codearts-work.js";
@@ -806,6 +806,12 @@ async function cmdDoctor() {
806
806
  check('Runtime deps (undici) installed', undiciOk, 'Run: npx huaweicloud-devkit install');
807
807
  const safetyOk = sections.some((section) => section.triple.safety);
808
808
  check('Safety policy installed', safetyOk, 'Run: npx huaweicloud-devkit install');
809
+ // The integrity unit's layer 3: per-row comparison of the deployed
810
+ // classifier files against the receipt the placement seam wrote. A row
811
+ // with no payload stays silent; a payload without a receipt WARNs (a
812
+ // pre-integrity install); drift FAILs with the reinstall remediation.
813
+ for (const section of sections)
814
+ section.integrity(ctx);
809
815
  // Secret vault — custody tier and inventory only; doctor never decrypts.
810
816
  try {
811
817
  const custody = custodyReport();
@@ -879,6 +885,7 @@ async function cmdDoctor() {
879
885
  if (installedPayload?.id === 'opencode') {
880
886
  opencodeDoctorSeam(ctx);
881
887
  opencodeDoctorAskRule(ctx);
888
+ opencodeDoctorSafetyGate(ctx);
882
889
  }
883
890
  // The codex client yield (PR-5): the per-tool approval_mode blocks the
884
891
  // devkit payload's .mcp.json carries (agents/codex-config.ts records why
@@ -84,8 +84,9 @@ let classifyTextCommand;
84
84
  // covers the transition.
85
85
  let rosterApprovalTools;
86
86
  let rosterInputShapes;
87
+ let policyModule;
87
88
  try {
88
- const policyModule = existsSync(join(__dirname, '..', 'dist', 'safety-policy.js'))
89
+ policyModule = existsSync(join(__dirname, '..', 'dist', 'safety-policy.js'))
89
90
  ? await import('../dist/safety-policy.js')
90
91
  : await import('../src/safety-policy.ts');
91
92
  ({ classifyTextCommand } = policyModule);
@@ -102,6 +103,48 @@ try {
102
103
  );
103
104
  process.exit(0);
104
105
  }
106
+
107
+ // The load-time behavior self-check (the integrity unit's layer 2, the
108
+ // opencode safety-gate adapter's twin): an import that succeeds is not yet
109
+ // a classifier — a stale replacement, a truncated overwrite, or a bad
110
+ // upgrade can hand over a module that is shaped right and decides wrong.
111
+ // Three canaries run before the module is trusted: the export shape, a
112
+ // canonical write vector (must deny), and a canonical benign read (must
113
+ // allow); any failure denies fail-closed with the self-check reason before
114
+ // main() runs. This runs per hook invocation (a fresh process per Bash
115
+ // call) and catches NON-adversarial corruption; the crafted module that
116
+ // passes the canaries is the documented residual the doctor drift check
117
+ // (layer 3) owns. The reason literal is pinned byte-identical to the
118
+ // adapter's by the safety-gate test.
119
+ const SELF_CHECK_FAILED_REASON =
120
+ 'the deployed safety policy failed its load-time self-check (shape or behavior canary); commands are denied fail-closed. Reinstall the huaweicloud-devkit plugin.';
121
+ const CANARY_WRITE_VECTOR = 'hcloud ECS DeleteServers --server.id=x';
122
+ const CANARY_BENIGN_READ = 'ls /tmp';
123
+
124
+ function policySelfCheckFailed(module) {
125
+ if (typeof module.classifyTextCommand !== 'function') return true;
126
+ try {
127
+ if (module.classifyTextCommand(CANARY_WRITE_VECTOR).decision !== 'deny') return true;
128
+ if (module.classifyTextCommand(CANARY_BENIGN_READ).decision !== 'allow') return true;
129
+ } catch {
130
+ return true;
131
+ }
132
+ return false;
133
+ }
134
+
135
+ if (policySelfCheckFailed(policyModule)) {
136
+ writeSync(
137
+ 1,
138
+ JSON.stringify({
139
+ hookSpecificOutput: {
140
+ hookEventName: 'PreToolUse',
141
+ permissionDecision: 'deny',
142
+ permissionDecisionReason: DENY_PREFIX + SELF_CHECK_FAILED_REASON,
143
+ },
144
+ }) + '\n',
145
+ );
146
+ process.exit(0);
147
+ }
105
148
  try {
106
149
  const rosterModule = existsSync(join(__dirname, '..', 'dist', 'approval-roster.js'))
107
150
  ? await import('../dist/approval-roster.js')
@@ -32,6 +32,19 @@ TELEMETRY_DIR = PLUGIN_DIR / "telemetry"
32
32
  HOOK_EVENTS_PATH = TELEMETRY_DIR / "hook-events.jsonl"
33
33
 
34
34
  CONFIG_FILE_RE = None
35
+ # The payload path-write gate (the integrity unit's layer 1): the compiled
36
+ # write-shape regexes over the policy's protectedPayloadPathMarkers, the py
37
+ # mirror of src/safety/protected-payload.ts. None (field absent, non-list,
38
+ # or empty — the degraded shapes load_policy normalizes) means the gate is
39
+ # unset: additive vocabulary, so an older policy.json without the key
40
+ # disables it on BOTH twins (the TS side's [] / py None agree in verdict).
41
+ PROTECTED_WRITE_RES = None
42
+ PROTECTED_WRITE_REASON = (
43
+ "writing to the deployed Huawei Cloud DevKit plugin payload is blocked: "
44
+ "this command targets the installed safety policy files, and modifying them "
45
+ "would disarm the gates that classify agent commands. Reinstall or update "
46
+ "via npx huaweicloud-devkit install from your own terminal."
47
+ )
35
48
  SECRET_READ_RE = None
36
49
  SECRET_CLI_RE = None
37
50
  APPROVAL_CLI_RE = None
@@ -76,7 +89,7 @@ OBS_MARKER_RE = re.compile(r"\bOBS\b", re.I)
76
89
 
77
90
 
78
91
  def load_policy():
79
- global CONFIG_FILE_RE, SECRET_READ_RE, SECRET_CLI_RE, APPROVAL_CLI_RE, ACCOUNT_SWITCH_CLI_RE, GATED_CLI_RE, WRITE_OPERATION_RE, WRITE_VOCAB_RE, READ_OPERATION_RE, READ_OPERATION_EXCEPTIONS
92
+ global CONFIG_FILE_RE, PROTECTED_WRITE_RES, SECRET_READ_RE, SECRET_CLI_RE, APPROVAL_CLI_RE, ACCOUNT_SWITCH_CLI_RE, GATED_CLI_RE, WRITE_OPERATION_RE, WRITE_VOCAB_RE, READ_OPERATION_RE, READ_OPERATION_EXCEPTIONS
80
93
  try:
81
94
  with POLICY_PATH.open("r", encoding="utf-8") as file_obj:
82
95
  policy = json.load(file_obj)
@@ -165,6 +178,41 @@ def load_policy():
165
178
  cred_patterns = policy.get("credentialFilePatterns", [])
166
179
  if cred_patterns:
167
180
  CONFIG_FILE_RE = re.compile("|".join(cred_patterns), re.I)
181
+ # The payload path-write gate (integrity layer 1): compiled from the
182
+ # policy's protectedPayloadPathMarkers — never a hand-copied marker
183
+ # list — with the SAME write-shape spec as the TS twin
184
+ # (src/safety/protected-payload.ts owns the doctrine comment):
185
+ # candidates split on [;&|\n\r], per-chunk shapes anchored at
186
+ # command position (env assignments + sudo/env/nice/nohup/command/
187
+ # xargs heads), whitespace [ \t] only. Absent/non-list/empty
188
+ # normalizes to an UNSET gate (additive vocabulary — the absent key
189
+ # on an older deployed policy must not fail this face), and a
190
+ # malformed marker pattern degrades ONLY this gate (the isolated
191
+ # per-field doctrine), never the later loads.
192
+ protected_markers = policy.get("protectedPayloadPathMarkers", [])
193
+ if not isinstance(protected_markers, list):
194
+ protected_markers = []
195
+ protected_markers = [m for m in protected_markers if isinstance(m, str) and m]
196
+ if protected_markers:
197
+ try:
198
+ marker_alt = "(?:" + "|".join(protected_markers) + ")"
199
+ anchor = (
200
+ r"^[ \t]*(?:[A-Za-z_][A-Za-z0-9_]*=\S*[ \t]+)*"
201
+ r"(?:(?:sudo|env|nice|nohup|command|xargs)[ \t]+)*"
202
+ )
203
+ PROTECTED_WRITE_RES = [
204
+ re.compile(r">>?[^;&|]*" + marker_alt, re.I),
205
+ re.compile(anchor + r"tee\b[^;&|]*" + marker_alt, re.I),
206
+ re.compile(
207
+ anchor + r"(?:cp|mv|rsync|install)\b[^;&|]*[ \t]\S*" + marker_alt + r"\S*[ \t]*$",
208
+ re.I,
209
+ ),
210
+ re.compile(anchor + r"dd\b[^;&|]*\bof[ \t]*=[ \t]*[^;&|]*" + marker_alt, re.I),
211
+ re.compile(anchor + r"sed\b[^;&|]*[ \t]-i\b[^;&|]*" + marker_alt, re.I),
212
+ re.compile(anchor + r"patch\b[^;&|]*" + marker_alt, re.I),
213
+ ]
214
+ except re.error:
215
+ PROTECTED_WRITE_RES = None
168
216
  blocked_secrets = [op for op in policy.get("blockedSecretOperations", []) if op != ""]
169
217
  if blocked_secrets:
170
218
  # Only entries that are a PREFIX of another entry (ShowSecret is
@@ -2666,6 +2714,18 @@ def evaluate(tool_name, tool_input):
2666
2714
  for candidate in (text, unquoted, normalized, normalized_unquoted)
2667
2715
  ):
2668
2716
  return "reading Huawei Cloud credential/profile files can expose AK/SK or tokens. Use redacted toolkit tools."
2717
+ # The payload path-write gate (integrity layer 1, the CONFIG_FILE_RE
2718
+ # gate's sibling): the same four candidates, WRITE-shaped only — the
2719
+ # py mirror of classify-text.ts's protectedPayloadWriteDenied, compiled
2720
+ # in load_policy from the same policy field. Reads of the payload tree
2721
+ # stay allowed (skills reads, direct inspection); only a write-shaped
2722
+ # command targeting a protected payload path denies.
2723
+ if PROTECTED_WRITE_RES:
2724
+ for candidate in (text, unquoted, normalized, normalized_unquoted):
2725
+ for chunk in re.split(r"[;&|\n\r]", candidate):
2726
+ for shape in PROTECTED_WRITE_RES:
2727
+ if shape.search(chunk):
2728
+ return PROTECTED_WRITE_REASON
2669
2729
  if SECRET_CLI_RE and any(SECRET_CLI_RE.search(candidate) for candidate in candidates):
2670
2730
  return "printing vault secrets into the agent context is blocked. Use secret exec so the value reaches only the child process environment."
2671
2731
  if APPROVAL_CLI_RE and any(APPROVAL_CLI_RE.search(candidate) for candidate in candidates):
@@ -2,10 +2,10 @@
2
2
  "name": "huaweicloud-devkit",
3
3
  "id": "huaweicloud-devkit",
4
4
  "displayName": "HuaweiCloud DevKit",
5
- "version": "2.0.0-next.5",
5
+ "version": "2.0.0-next.6",
6
6
  "family": "bundle-plugin",
7
7
  "bundleFormat": "codex",
8
- "description": "Guide coding agents to use Huawei Cloud safely �?KooCLI, APIs, SDKs, 40 MCP tools, skills, and safety guardrails.",
8
+ "description": "Guide coding agents to use Huawei Cloud safely �?KooCLI, APIs, SDKs, 40 MCP tools, skills, and safety guardrails.",
9
9
  "author": {
10
10
  "name": "HuaweiCloud Mate",
11
11
  "url": "https://github.com/huaweicloud"
@@ -27,6 +27,11 @@
27
27
  "/proc/(self|[0-9]+)/environ",
28
28
  "huaweicloud\\s*(?:&&|;|/|[\\n\\r])\\s*(?:\\S+\\s+){0,2}(?:credentials|creds-import|config)\\.json"
29
29
  ],
30
+ "protectedPayloadPathMarkers": [
31
+ "huaweicloud-plugins[/\\\\]",
32
+ "huaweicloud-core[/\\\\]dist[/\\\\]",
33
+ "huaweicloud-core[/\\\\]safety[/\\\\]"
34
+ ],
30
35
  "blockedConfigureSubcommands": ["show", "get", "list", "export", "init"],
31
36
  "blockedSecretOperations": [
32
37
  "ShowSecret",
@@ -88,7 +88,7 @@ The PIN record stores only a mac over the vault custody master key, never the pl
88
88
 
89
89
  The gate defends: execution needs a user-recorded confirmation — a PIN-checked terminal grant bound to the token and every stored field the run gate trusts (command hash, pin view, redacted form, mint time), or a server-raised form answer the client relayed, or an explicitly-labelled posture attestation whose line was shown first. The terminal grant is a custody-keyed mac, so a same-user edit of the state string or any trusted field does not verify; and a gated call without a valid confirmation never runs.
90
90
 
91
- It does NOT defend against: a socially engineered user who approves a command they did not read (the form and terminal print the request, but neither proves comprehension); a same-user process that holds BOTH the custody master key and write access to `~/.config/huaweicloud/`, which can forge a grant for any pending token on the keyfile tier; a harness without the safety hook, where the TTY check is the only barrier and an agent driving a pseudo-terminal looks like a terminal; the hook's text gate missing variable-indirect verbs (`V=approve; npx huaweicloud-devkit $V` — the same indirection residual the shell shadow documents for the secret gate), where the agent reaches the CLI spelling through a shell variable; or a posture-tier retry, which trusts the model's report of the user's answer by design and is labelled as such on every surface that shows it. This is a consent gate, not an isolation boundary.
91
+ It does NOT defend against: a socially engineered user who approves a command they did not read (the form and terminal print the request, but neither proves comprehension); a same-user process that holds BOTH the custody master key and write access to `~/.config/huaweicloud/`, which can forge a grant for any pending token on the keyfile tier; a harness without the safety hook, where the TTY check is the only barrier and an agent driving a pseudo-terminal looks like a terminal (on opencode 2.x the shell face is no longer in this class: the installer-deployed safety-gate adapter classifies each scanner segment in-process and denies classifier-refused compounds before execution, leaving only the gate's own text residuals there — the indirection classes below); the text gates' indirection residuals — variable-indirect verbs (`V=approve; npx huaweicloud-devkit $V`, the same indirection residual the shell shadow documents for the secret gate) and script-file carriers (`bash /tmp/x.sh` runs a script whose content no text gate ever sees), both reaching a gated verb through a shell variable or an indirect file; an agent that rewrites the deployed classifier file itself — the same attack that was once open on every in-process gate is now three layers deep rather than closed: the classifier denies write-shaped bash commands targeting the deployed payload paths (policy.json's `protectedPayloadPathMarkers`), the adapter and the `.mjs` hook refuse an imported module that fails the load-time shape/behavior canaries, and doctor compares the deployed classifier files against the install-time integrity receipt — so the naive vector (echo/tee/cp over `dist/safety-policy.js`) is denied at the command itself, non-adversarial corruption (a stale replacement, a truncated overwrite) denies fail-closed at load, and any drift that lands anyway surfaces in doctor with the reinstall remediation. Against arbitrary user-permission bash NO purely local mechanism fully closes this — with the file system writable by the same user the gate runs under, an escape requires a crafted module that passes the canaries and a bypass of the path gate's own text residuals (quote/variable-indirect path spellings, verbs outside the shape table), which raises the cost to forging multiple artifacts at once; full closure needs out-of-band verification (a read-only install location, a signed payload, or an integrity check from a process the agent cannot write). The integrity receipt is itself local, so a determined attacker can rewrite it too — doctor's drift check is detection, not proof. Also outside the gate: a posture-tier retry, which trusts the model's report of the user's answer by design and is labelled as such on every surface that shows it. This is a consent gate, not an isolation boundary.
92
92
 
93
93
  ## The registered non-CLI tools
94
94
 
@@ -19,6 +19,7 @@ import { readJsonRecord, writeMcpSettingsFile } from '../mcp-config-io.ts';
19
19
  import {
20
20
  applySkillTreePermissionSeam,
21
21
  opencodeSeamVersionSupported,
22
+ payloadEditDenyGlobs,
22
23
  removeSkillTreePermissionSeam,
23
24
  skillTreePermissionGlobs,
24
25
  } from '../lib/opencode-permission-seam.ts';
@@ -137,6 +138,30 @@ export function openCodeAskGate(): OpenCodeAskGate {
137
138
  return forced === 'on' ? 'v2-array' : 'off';
138
139
  }
139
140
 
141
+ // The safety gate's floor check: permission.hook("evaluate") is a V2
142
+ // surface (G1 measured the event shape, the "shell" action naming, and the
143
+ // deny semantics on 2.2.7; V1 named the action "bash" and had no evaluate
144
+ // hook), so the floor is the 2.0 major. Unparsable or absent stays
145
+ // unsupported — the caller's polarity is skip, never a guess.
146
+ export function opencodeSafetyGateVersionSupported(version: string | null): boolean {
147
+ if (version === null) return false;
148
+ const match = /^v?(\d+)\.(\d+)\.(\d+)/.exec(version.trim());
149
+ return match !== null && Number(match[1]) >= 2;
150
+ }
151
+
152
+ // The safety gate's version gate, same doctrine as the seam's:
153
+ // HUAWEICLOUD_OPENCODE_SAFETY_GATE=on|off is the deterministic override for
154
+ // the installer test suite (e2e strips it — the runner's install relies on
155
+ // the natural probe); unset runs the probe against the 2.0 floor. A
156
+ // below-floor, absent, or unparsable opencode gets no adapter file and a
157
+ // doctor SKIP, never a FAIL — 1.x has no evaluate hook to register on, and a
158
+ // later update heals the skip by deploying the file.
159
+ export function openCodeSafetyGate(): 'on' | 'off' {
160
+ const forced = process.env.HUAWEICLOUD_OPENCODE_SAFETY_GATE;
161
+ if (forced === 'on' || forced === 'off') return forced;
162
+ return opencodeSafetyGateVersionSupported(probeOpencodeVersion()) ? 'on' : 'off';
163
+ }
164
+
140
165
  // The server half of the ask posture: DEVKIT_APPROVAL_MODE=ask in the mcp
141
166
  // entry's environment (the field OpenCode reads — the applyPacksToEntry
142
167
  // 'environment' precedent). Ask mode now means the SERVER-RUN gate: the
@@ -198,7 +223,7 @@ export function updateOpenCodeConfig(pluginDir: string): void {
198
223
  // lib/opencode-permission-seam.ts), so the single write below carries it.
199
224
  let permChanged = false;
200
225
  if (openCodeSeamGate() === 'on') {
201
- const seam = applySkillTreePermissionSeam(config, openCodeSeamGlobs(pluginDir));
226
+ const seam = applySkillTreePermissionSeam(config, openCodeSeamGlobs(pluginDir), payloadEditDenyGlobs(pluginDir));
202
227
  permChanged = seam.changed;
203
228
  for (const section of seam.skipped) {
204
229
  console.log(
@@ -340,8 +365,13 @@ export function removeOpenCodeConfig(): void {
340
365
  // hand. Globs derive from the stable XDG paths (the plugin dir may
341
366
  // already be gone) and the running package's own manifest;
342
367
  // value-exact deletion keeps user-modified rules (the ownership contract
343
- // lives in lib/opencode-permission-seam.ts).
344
- const permCleaned = removeSkillTreePermissionSeam(config, openCodeSeamGlobs(opencodePluginsDir()));
368
+ // lives in lib/opencode-permission-seam.ts). The edit-only payload
369
+ // class is removed under the same value-exact rule.
370
+ const permCleaned = removeSkillTreePermissionSeam(
371
+ config,
372
+ openCodeSeamGlobs(opencodePluginsDir()),
373
+ payloadEditDenyGlobs(opencodePluginsDir()),
374
+ );
345
375
  // The client-rule cleanup also runs unconditionally of the version gate: an
346
376
  // uninstall must remove what any past install wrote — the opencode that
347
377
  // gated the write may since have been upgraded, downgraded, or removed from