huaweicloud-devkit 2.0.0-next.3 → 2.0.0-next.5

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 (173) hide show
  1. package/README.md +3 -1
  2. package/package.json +3 -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/.mcp.json +55 -1
  8. package/plugins/huaweicloud-core/.workbuddy-plugin/plugin.json +1 -1
  9. package/plugins/huaweicloud-core/dist/agents/codex-config.js +374 -0
  10. package/plugins/huaweicloud-core/dist/agents/codex-desktop.js +8 -1
  11. package/plugins/huaweicloud-core/dist/agents/codex.js +9 -0
  12. package/plugins/huaweicloud-core/dist/agents/opencode-config.js +141 -86
  13. package/plugins/huaweicloud-core/dist/agents/opencode.js +106 -39
  14. package/plugins/huaweicloud-core/dist/approval-gate.js +1185 -0
  15. package/plugins/huaweicloud-core/dist/approval-ledger.js +2331 -0
  16. package/plugins/huaweicloud-core/dist/approval-roster.js +89 -0
  17. package/plugins/huaweicloud-core/dist/approval-types.js +1 -0
  18. package/plugins/huaweicloud-core/dist/approvals-cli.js +4 -4
  19. package/plugins/huaweicloud-core/dist/data/icons-manifest.v1.json +23 -5
  20. package/plugins/huaweicloud-core/dist/dep/receipts.js +65 -5
  21. package/plugins/huaweicloud-core/dist/explain-error.js +9 -1
  22. package/plugins/huaweicloud-core/dist/hcloud-cli.js +1 -1
  23. package/plugins/huaweicloud-core/dist/hcloud-plan.js +68 -62
  24. package/plugins/huaweicloud-core/dist/lib/approval-mode.js +7 -5
  25. package/plugins/huaweicloud-core/dist/lib/approval-tokens.js +18 -4
  26. package/plugins/huaweicloud-core/dist/lib/call-trace.js +7 -14
  27. package/plugins/huaweicloud-core/dist/lib/confirm-language.js +50 -0
  28. package/plugins/huaweicloud-core/dist/lib/credentials.js +9 -9
  29. package/plugins/huaweicloud-core/dist/lib/hdkit/hdkit-gate.js +1398 -0
  30. package/plugins/huaweicloud-core/dist/lib/hdkit/hdkitservice-api.js +371 -32
  31. package/plugins/huaweicloud-core/dist/lib/hdkit/sandbox-pool.js +6 -16
  32. package/plugins/huaweicloud-core/dist/lib/opencode-ask-rule.js +224 -78
  33. package/plugins/huaweicloud-core/dist/lib/opencode-saved-perms.js +282 -0
  34. package/plugins/huaweicloud-core/dist/lib/supplemental-redaction.js +116 -0
  35. package/plugins/huaweicloud-core/dist/lib/tool-schema-parts.js +31 -0
  36. package/plugins/huaweicloud-core/dist/lib/workspace-glob.js +442 -0
  37. package/plugins/huaweicloud-core/dist/mcp-config-io.js +28 -1
  38. package/plugins/huaweicloud-core/dist/mcp-protocol.js +68 -16
  39. package/plugins/huaweicloud-core/dist/mcp-server.js +6933 -1186
  40. package/plugins/huaweicloud-core/dist/mcp-server.js.map +4 -4
  41. package/plugins/huaweicloud-core/dist/mcp-stdio-transport.js +14 -4
  42. package/plugins/huaweicloud-core/dist/packs/auth/approval.js +249 -0
  43. package/plugins/huaweicloud-core/dist/packs/auth/tools.js +44 -44
  44. package/plugins/huaweicloud-core/dist/packs/huaweicloud-cli/tools.js +85 -130
  45. package/plugins/huaweicloud-core/dist/packs/obs/approval.js +110 -0
  46. package/plugins/huaweicloud-core/dist/packs/obs/tools.js +7 -2
  47. package/plugins/huaweicloud-core/dist/packs/registry.js +20 -1
  48. package/plugins/huaweicloud-core/dist/packs/sandbox/approval.js +245 -0
  49. package/plugins/huaweicloud-core/dist/packs/sandbox/expose-task.js +71 -0
  50. package/plugins/huaweicloud-core/dist/packs/sandbox/handlers-account.js +180 -23
  51. package/plugins/huaweicloud-core/dist/packs/sandbox/handlers-credentials.js +13 -1
  52. package/plugins/huaweicloud-core/dist/packs/sandbox/handlers-hwexec.js +136 -0
  53. package/plugins/huaweicloud-core/dist/packs/sandbox/handlers-session.js +11 -1
  54. package/plugins/huaweicloud-core/dist/packs/sandbox/handlers-tunnel.js +29 -3
  55. package/plugins/huaweicloud-core/dist/packs/sandbox/schemas.js +93 -9
  56. package/plugins/huaweicloud-core/dist/packs/sandbox/tools.js +37 -10
  57. package/plugins/huaweicloud-core/dist/packs/secrets/approval.js +46 -0
  58. package/plugins/huaweicloud-core/dist/packs/secrets/tools.js +4 -1
  59. package/plugins/huaweicloud-core/dist/packs/update/approval.js +79 -0
  60. package/plugins/huaweicloud-core/dist/packs/update/tools.js +8 -1
  61. package/plugins/huaweicloud-core/dist/packs/voucher/tools.js +1 -1
  62. package/plugins/huaweicloud-core/dist/packs-configure.js +74 -0
  63. package/plugins/huaweicloud-core/dist/risk-rule-engine.js +20 -4
  64. package/plugins/huaweicloud-core/dist/safety/classify-hcloud.js +6 -6
  65. package/plugins/huaweicloud-core/dist/safety/classify-text.js +36 -0
  66. package/plugins/huaweicloud-core/dist/safety/policy.js +2 -0
  67. package/plugins/huaweicloud-core/dist/safety/redact.js +21 -3
  68. package/plugins/huaweicloud-core/dist/safety/risk-merge.js +24 -4
  69. package/plugins/huaweicloud-core/dist/sandbox/deploy-check.js +1 -1
  70. package/plugins/huaweicloud-core/dist/sandbox/devbridge-auth.js +65 -14
  71. package/plugins/huaweicloud-core/dist/sandbox/devbridge-cleanup.js +422 -0
  72. package/plugins/huaweicloud-core/dist/sandbox/devbridge-expose-flow.js +66 -16
  73. package/plugins/huaweicloud-core/dist/sandbox/devbridge-expose.js +13 -10
  74. package/plugins/huaweicloud-core/dist/sandbox/devbridge-keepalive.js +42 -2
  75. package/plugins/huaweicloud-core/dist/sandbox/devbridge-key.js +11 -3
  76. package/plugins/huaweicloud-core/dist/sandbox/devbridge-tunnel.js +6 -0
  77. package/plugins/huaweicloud-core/dist/sandbox/devbridge-validation.js +10 -1
  78. package/plugins/huaweicloud-core/dist/sandbox/hwexec-task.js +244 -0
  79. package/plugins/huaweicloud-core/dist/setup-cli.js +36 -1
  80. package/plugins/huaweicloud-core/dist/tool-definitions.js +13 -1
  81. package/plugins/huaweicloud-core/dist/tool-schemas.js +32 -6
  82. package/plugins/huaweicloud-core/dist/tools.js +76 -9
  83. package/plugins/huaweicloud-core/dist/update-registry.js +358 -5
  84. package/plugins/huaweicloud-core/dist/update-upgrade.js +1083 -14
  85. package/plugins/huaweicloud-core/dist/vendor-gate.js +2 -2
  86. package/plugins/huaweicloud-core/hooks/huaweicloud-safety.mjs +150 -1
  87. package/plugins/huaweicloud-core/hooks/huaweicloud-safety.py +67 -4
  88. package/plugins/huaweicloud-core/openclaw.plugin.json +2 -2
  89. package/plugins/huaweicloud-core/safety/policy.json +18 -11
  90. package/plugins/huaweicloud-core/safety/rules/cloud-risk-rules.json +115 -11
  91. package/plugins/huaweicloud-core/skills/huawei-sandbox/SKILL.md +198 -143
  92. package/plugins/huaweicloud-core/skills/huawei-sandbox/references/resource-pool.md +36 -12
  93. package/plugins/huaweicloud-core/skills/huawei-voucher/SKILL.md +2 -0
  94. package/plugins/huaweicloud-core/skills/huaweicloud-cli-and-auth/SKILL.md +2 -2
  95. package/plugins/huaweicloud-core/skills/huaweicloud-safety/SKILL.md +11 -7
  96. package/plugins/huaweicloud-core/skills/huaweicloud-safety/references/approvals.md +74 -29
  97. package/plugins/huaweicloud-core/skills/huaweicloud-troubleshooting/SKILL.md +21 -19
  98. package/plugins/huaweicloud-core/src/agents/codex-config.ts +432 -0
  99. package/plugins/huaweicloud-core/src/agents/codex-desktop.ts +8 -1
  100. package/plugins/huaweicloud-core/src/agents/codex.ts +10 -0
  101. package/plugins/huaweicloud-core/src/agents/opencode-config.ts +176 -88
  102. package/plugins/huaweicloud-core/src/agents/opencode.ts +125 -54
  103. package/plugins/huaweicloud-core/src/approval-gate.ts +1306 -0
  104. package/plugins/huaweicloud-core/src/approval-ledger.ts +2446 -0
  105. package/plugins/huaweicloud-core/src/approval-roster.ts +127 -0
  106. package/plugins/huaweicloud-core/src/approval-types.ts +237 -0
  107. package/plugins/huaweicloud-core/src/approvals-cli.ts +4 -4
  108. package/plugins/huaweicloud-core/src/data/icons-manifest.v1.json +23 -5
  109. package/plugins/huaweicloud-core/src/dep/receipts.ts +84 -5
  110. package/plugins/huaweicloud-core/src/explain-error.ts +9 -1
  111. package/plugins/huaweicloud-core/src/hcloud-cli.ts +3 -0
  112. package/plugins/huaweicloud-core/src/hcloud-plan.ts +74 -71
  113. package/plugins/huaweicloud-core/src/lib/approval-mode.ts +7 -5
  114. package/plugins/huaweicloud-core/src/lib/approval-tokens.ts +19 -4
  115. package/plugins/huaweicloud-core/src/lib/call-trace.ts +7 -17
  116. package/plugins/huaweicloud-core/src/lib/confirm-language.ts +51 -0
  117. package/plugins/huaweicloud-core/src/lib/credentials.ts +9 -8
  118. package/plugins/huaweicloud-core/src/lib/hdkit/hdkit-gate.ts +1428 -0
  119. package/plugins/huaweicloud-core/src/lib/hdkit/hdkitservice-api.ts +408 -30
  120. package/plugins/huaweicloud-core/src/lib/hdkit/sandbox-pool.ts +8 -15
  121. package/plugins/huaweicloud-core/src/lib/opencode-ask-rule.ts +302 -83
  122. package/plugins/huaweicloud-core/src/lib/opencode-saved-perms.ts +354 -0
  123. package/plugins/huaweicloud-core/src/lib/supplemental-redaction.ts +129 -0
  124. package/plugins/huaweicloud-core/src/lib/tool-schema-parts.ts +40 -0
  125. package/plugins/huaweicloud-core/src/lib/workspace-glob.ts +414 -0
  126. package/plugins/huaweicloud-core/src/mcp-config-io.ts +27 -1
  127. package/plugins/huaweicloud-core/src/mcp-protocol.ts +81 -17
  128. package/plugins/huaweicloud-core/src/mcp-server.ts +7 -7
  129. package/plugins/huaweicloud-core/src/mcp-stdio-transport.ts +14 -4
  130. package/plugins/huaweicloud-core/src/packs/auth/approval.ts +302 -0
  131. package/plugins/huaweicloud-core/src/packs/auth/tools.ts +54 -45
  132. package/plugins/huaweicloud-core/src/packs/huaweicloud-cli/tools.ts +99 -137
  133. package/plugins/huaweicloud-core/src/packs/obs/approval.ts +122 -0
  134. package/plugins/huaweicloud-core/src/packs/obs/tools.ts +7 -2
  135. package/plugins/huaweicloud-core/src/packs/registry.ts +43 -1
  136. package/plugins/huaweicloud-core/src/packs/sandbox/approval.ts +296 -0
  137. package/plugins/huaweicloud-core/src/packs/sandbox/expose-task.ts +105 -0
  138. package/plugins/huaweicloud-core/src/packs/sandbox/handlers-account.ts +195 -23
  139. package/plugins/huaweicloud-core/src/packs/sandbox/handlers-credentials.ts +11 -1
  140. package/plugins/huaweicloud-core/src/packs/sandbox/handlers-hwexec.ts +228 -0
  141. package/plugins/huaweicloud-core/src/packs/sandbox/handlers-session.ts +11 -1
  142. package/plugins/huaweicloud-core/src/packs/sandbox/handlers-tunnel.ts +41 -14
  143. package/plugins/huaweicloud-core/src/packs/sandbox/schemas.ts +120 -8
  144. package/plugins/huaweicloud-core/src/packs/sandbox/tools.ts +42 -9
  145. package/plugins/huaweicloud-core/src/packs/secrets/approval.ts +50 -0
  146. package/plugins/huaweicloud-core/src/packs/secrets/tools.ts +4 -1
  147. package/plugins/huaweicloud-core/src/packs/update/approval.ts +87 -0
  148. package/plugins/huaweicloud-core/src/packs/update/tools.ts +8 -1
  149. package/plugins/huaweicloud-core/src/packs/voucher/tools.ts +1 -1
  150. package/plugins/huaweicloud-core/src/packs-configure.ts +75 -0
  151. package/plugins/huaweicloud-core/src/risk-rule-engine.ts +20 -7
  152. package/plugins/huaweicloud-core/src/safety/classify-hcloud.ts +28 -16
  153. package/plugins/huaweicloud-core/src/safety/classify-text.ts +40 -0
  154. package/plugins/huaweicloud-core/src/safety/policy.ts +7 -0
  155. package/plugins/huaweicloud-core/src/safety/redact.ts +24 -6
  156. package/plugins/huaweicloud-core/src/safety/risk-merge.ts +26 -5
  157. package/plugins/huaweicloud-core/src/sandbox/deploy-check.ts +1 -1
  158. package/plugins/huaweicloud-core/src/sandbox/devbridge-auth.ts +74 -14
  159. package/plugins/huaweicloud-core/src/sandbox/devbridge-cleanup.ts +511 -0
  160. package/plugins/huaweicloud-core/src/sandbox/devbridge-expose-flow.ts +70 -18
  161. package/plugins/huaweicloud-core/src/sandbox/devbridge-expose.ts +26 -10
  162. package/plugins/huaweicloud-core/src/sandbox/devbridge-keepalive.ts +41 -2
  163. package/plugins/huaweicloud-core/src/sandbox/devbridge-key.ts +9 -3
  164. package/plugins/huaweicloud-core/src/sandbox/devbridge-tunnel.ts +24 -0
  165. package/plugins/huaweicloud-core/src/sandbox/devbridge-validation.ts +11 -1
  166. package/plugins/huaweicloud-core/src/sandbox/hwexec-task.ts +304 -0
  167. package/plugins/huaweicloud-core/src/setup-cli.ts +39 -1
  168. package/plugins/huaweicloud-core/src/tool-definitions.ts +13 -1
  169. package/plugins/huaweicloud-core/src/tool-schemas.ts +39 -6
  170. package/plugins/huaweicloud-core/src/tools.ts +124 -10
  171. package/plugins/huaweicloud-core/src/update-registry.ts +340 -5
  172. package/plugins/huaweicloud-core/src/update-upgrade.ts +1130 -14
  173. package/plugins/huaweicloud-core/src/vendor-gate.ts +2 -2
@@ -19,7 +19,7 @@ import { explainError } from "./explain-error.js";
19
19
  import { getRegionalAvailability } from "./services/availability.js";
20
20
  // PACK_TOOL_HANDLERS is the central pack dispatch table (its satisfies check
21
21
  // pins every PackToolName to a handler).
22
- import { PACK_TOOL_HANDLERS, isPackToolName } from "./packs/registry.js";
22
+ import { PACK_TOOL_HANDLERS, isPackToolName, APPROVAL_SPECS } from "./packs/registry.js";
23
23
  // The skill-dir listing lives in the shared zod-free module
24
24
  // (src/lib/skill-tree.ts) so the boot guard, the installer's doctor check,
25
25
  // the build-time --check stray scan, and validate-package's skill gate all
@@ -39,6 +39,12 @@ import { toolArgKeys } from "./tool-schemas.js";
39
39
  // importers (structure-load-path, e2e/cases/core) and dispatchTool calls
40
40
  // enforceVendorGate at dispatch's top.
41
41
  import { VENDOR_GATED_TOOLS, enforceVendorGate } from "./vendor-gate.js";
42
+ // The dispatch-layer approval gate (the roster, the per-pack specs it
43
+ // resolves from packs/registry.ts's APPROVAL_SPECS merge, the consent
44
+ // ledger, and the envelope faces) lives in the approval-* family;
45
+ // dispatchTool calls runApprovalGate after the vendor gate and before the
46
+ // pack dispatch.
47
+ import { recordApprovalDispatchOutcome, runApprovalGate, } from "./approval-gate.js";
42
48
  // The capability catalog (service_catalog / list_packs / pack_info
43
49
  // handlers, the SKILL_OWNER inversion, and the shared pack-refusal
44
50
  // helpers) lives in capability-catalog.ts; dispatchTool switches into it.
@@ -133,15 +139,76 @@ async function dispatchTool(name, args, opts) {
133
139
  if (VENDOR_GATED_TOOLS.has(name)) {
134
140
  enforceVendorGate(args, opts);
135
141
  }
136
- // Pack tools (every non-core name) dispatch through the central handler
137
- // map in packs/registry.ts before the switch; the type guard narrows
138
- // `name` to the core remainder, which is what the switch below and its
139
- // never-guard are exhaustive over. opts rides through verbatim: every pack
140
- // handler takes (args, opts), and the update pack's doQuery/sessionId
141
- // seams keep reaching their handlers exactly as before the migration.
142
- if (isPackToolName(name)) {
143
- return await PACK_TOOL_HANDLERS[name](args, opts);
142
+ // The approval gate sits after the vendor gate and before the pack
143
+ // dispatch, spec-driven through the roster (APPROVAL_SPECS keys are
144
+ // exactly the roster names, compile-checked in packs/registry.ts). A
145
+ // non-roster tool pays one table miss here and dispatches unchanged.
146
+ // Envelopes are results, not throws, so a gated refusal reaches the
147
+ // caller as the same JSON the handler would have returned. On a pass
148
+ // the gate's binding rides the handler opts: the call's approved
149
+ // resolution, so credential-consuming handlers execute the snapshot the
150
+ // human confirmed — never a post-consent re-read (PR-3b's TOCTOU
151
+ // finding).
152
+ const approvalSpec = APPROVAL_SPECS[name];
153
+ let arrivalStamp;
154
+ let arrivalSeq;
155
+ let approvedVia;
156
+ let consentScope;
157
+ let handlerOpts = opts;
158
+ if (approvalSpec) {
159
+ const gated = await runApprovalGate(name, approvalSpec, args, opts);
160
+ if (!('pass' in gated))
161
+ return gated.envelope;
162
+ arrivalStamp = gated.pass.arrivalStamp;
163
+ arrivalSeq = gated.pass.arrivalSeq;
164
+ approvedVia = gated.pass.approvedVia;
165
+ consentScope = gated.pass.consentScope;
166
+ if (gated.binding !== undefined)
167
+ handlerOpts = { ...opts, approvedBinding: gated.binding };
144
168
  }
169
+ // The delivery-outcome recorder sits at the COMMON dispatch boundary
170
+ // (round 12, finding 3): the gate covers every roster member — pack
171
+ // tools and core tools alike (PR-3c's packs_configure registration is
172
+ // a CORE-tool dispatch through the switch below) — so the recorder must
173
+ // wrap BOTH dispatch legs, or a core-tool registration records its
174
+ // consent arrival but structurally never the delivery outcome the memo
175
+ // keys on. The wrapper hands the gate's spec and the arrival's stamp to
176
+ // the recorder; non-gated tools pay one no-op (the recorder returns
177
+ // without a spec) and dispatch through unchanged.
178
+ try {
179
+ const result = isPackToolName(name)
180
+ ? await PACK_TOOL_HANDLERS[name](args, handlerOpts)
181
+ : await dispatchCoreTool(name, args, handlerOpts);
182
+ recordApprovalDispatchOutcome(name, approvalSpec, args, opts, result, undefined, arrivalStamp, arrivalSeq, consentScope);
183
+ // The reuse attribution (PR-3a): a call that rode the retry memo or the
184
+ // session standing grant names it on the response, so the caller can
185
+ // tell a fresh confirmation's execution from a reused consent's. Object
186
+ // results carry the field; every registered tool's handler returns one,
187
+ // and a non-object shape keeps its wire contract untouched.
188
+ if (approvedVia !== undefined && result !== null && typeof result === 'object' && !Array.isArray(result)) {
189
+ result.approvedVia = approvedVia;
190
+ }
191
+ return result;
192
+ }
193
+ catch (error) {
194
+ recordApprovalDispatchOutcome(name, approvalSpec, args, opts, undefined, error, arrivalStamp, arrivalSeq, consentScope);
195
+ // The reuse attribution rides the error path too (interrogate round 2,
196
+ // F11): a memo-reused retry whose handler throws again still names what
197
+ // authorized it — programmatic callers see the marker on the error
198
+ // object; the wire shape of the error itself is unchanged.
199
+ if (approvedVia !== undefined && error instanceof Error) {
200
+ error.approvedVia = approvedVia;
201
+ }
202
+ throw error;
203
+ }
204
+ }
205
+ // The core-tool dispatch leg: the switch over the core remainder, after
206
+ // the pack guard — extracted so the delivery-outcome wrapper above can
207
+ // cover both dispatch paths from one boundary. The compile-time
208
+ // exhaustiveness never-guard moves with it: `name` is narrowed to
209
+ // Exclude<ToolName, PackToolName> by the call site's isPackToolName
210
+ // branch above.
211
+ async function dispatchCoreTool(name, args, opts) {
145
212
  switch (name) {
146
213
  case 'huaweicloud_hook_check_command':
147
214
  return hookResult(withUnknownOperationWarn(String(args.command || ''), evaluateCommandRisk(args.command || '')));
@@ -2,8 +2,12 @@
2
2
  // spawn) and the undici fetch path honoring HUAWEICLOUD_NPM_REGISTRY. Part of
3
3
  // the src/update-* family behind the src/update-check.ts re-export face.
4
4
  import { spawn, spawnSync } from 'node:child_process';
5
+ import { existsSync, readFileSync } from 'node:fs';
6
+ import { homedir } from 'node:os';
7
+ import { dirname, join, relative, sep } from 'node:path';
5
8
  import { fetchWithProxy } from "./proxy/proxy-agent.js";
6
9
  import { asText } from "./lib/as-text.js";
10
+ import { workspaceMemberMatch } from "./lib/workspace-glob.js";
7
11
  const NPM_BIN = process.platform === 'win32' ? 'npm.cmd' : 'npm';
8
12
  // One-property read with validation, for the JS boundary of thrown values:
9
13
  // only a non-empty `message` string is surfaced. Exported for the upgrade act
@@ -43,15 +47,364 @@ function debugLog(message) {
43
47
  console.error(`[debug] ${message}`);
44
48
  }
45
49
  }
50
+ // One spelling rule serves every env channel for the pre-flight and the child:
51
+ // trimmed non-empty exact-case first, else the first trimmed non-empty
52
+ // case/padding variant; whitespace counts as unset.
53
+ export function resolveEnvSpelling(env, canonical) {
54
+ const spellings = Object.entries(env)
55
+ .filter(([key, value]) => key.trim().toUpperCase() === canonical && Boolean(value?.trim()))
56
+ .map(([key, value]) => [key, value.trim()]);
57
+ const exact = spellings.find(([key]) => key === canonical);
58
+ return (exact ?? spellings[0])?.[1];
59
+ }
60
+ export function resolveRegistryOverride(env = process.env) {
61
+ return resolveEnvSpelling(env, 'HUAWEICLOUD_NPM_REGISTRY');
62
+ }
63
+ // The npm auth channels resolve through the same exact-case-first collapse as
64
+ // the child env, so duplicate/variant spellings cannot split the halves.
65
+ function resolveNpmAuthToken(env = process.env) {
66
+ return resolveEnvSpelling(env, 'NPM_TOKEN') ?? resolveEnvSpelling(env, 'NODE_AUTH_TOKEN');
67
+ }
68
+ // npm reads the userconfig by a case-insensitive `npm_config_userconfig` key,
69
+ // trims the value, and skips an empty value (falling back to ~/.npmrc). An
70
+ // empty spelling is skipped rather than terminal, so a set sibling still wins;
71
+ // a whitespace-only value trims to an empty path, which is not the fallback.
72
+ function resolveUserconfig(env = process.env) {
73
+ const raw = Object.entries(env)
74
+ .filter(([key, value]) => key.toUpperCase() === 'NPM_CONFIG_USERCONFIG' && value !== '')
75
+ .at(-1)?.[1];
76
+ if (raw === undefined)
77
+ return undefined;
78
+ // npm applies envReplace to every config value before path resolution, so a
79
+ // CI env block (`${CI_PROJECT_DIR}/.npmrc`) reaches the same file.
80
+ return expandTilde(envReplace(raw.trim(), env));
81
+ }
82
+ function expandTilde(value) {
83
+ if (value === '~')
84
+ return homedir();
85
+ return value.startsWith('~/') ? join(homedir(), value.slice(2)) : value;
86
+ }
87
+ function workspaceGlobs(value) {
88
+ const declared = Array.isArray(value)
89
+ ? value
90
+ : value && typeof value === 'object' && Array.isArray(value.packages)
91
+ ? value.packages
92
+ : [];
93
+ // npm rejects a non-string entry (EWORKSPACESCONFIG / a .match TypeError), so
94
+ // the declaration yields no members instead of promoting where npm crashes.
95
+ if (declared.some((entry) => typeof entry !== 'string'))
96
+ return [];
97
+ return declared;
98
+ }
99
+ function packageJsonWorkspaces(path) {
100
+ try {
101
+ const parsed = JSON.parse(readFileSync(path, 'utf8'));
102
+ if (!parsed || typeof parsed !== 'object')
103
+ return undefined;
104
+ const globs = workspaceGlobs(parsed.workspaces);
105
+ return globs.length ? globs : undefined;
106
+ }
107
+ catch {
108
+ return undefined;
109
+ }
110
+ }
111
+ function isWorkspaceMember(root, member, globs) {
112
+ return workspaceMemberMatch(relative(root, member).split(sep).join('/'), globs);
113
+ }
114
+ function localPrefix(start = process.cwd()) {
115
+ // npm's localPrefix starts at the nearest package dir and moves to an
116
+ // ancestor only when that ancestor's workspace map actually contains the
117
+ // package dir (mapWorkspaces membership, not the mere presence of the field).
118
+ let nearest;
119
+ let current = start;
120
+ for (;;) {
121
+ const manifest = join(current, 'package.json');
122
+ if (existsSync(manifest)) {
123
+ if (!nearest) {
124
+ nearest = current;
125
+ }
126
+ else {
127
+ const globs = packageJsonWorkspaces(manifest);
128
+ if (globs && isWorkspaceMember(current, nearest, globs))
129
+ return current;
130
+ }
131
+ }
132
+ const parent = dirname(current);
133
+ if (parent === current)
134
+ return nearest ?? start;
135
+ current = parent;
136
+ }
137
+ }
138
+ // Env spellings for npm's own config keys are case-insensitive; npm takes the
139
+ // last non-empty one when both are exported (an empty value is skipped, not
140
+ // terminal).
141
+ function envValue(env, name) {
142
+ const values = Object.entries(env)
143
+ .filter(([key]) => key.toUpperCase() === name)
144
+ .map(([, value]) => value?.trim())
145
+ .filter((value) => Boolean(value));
146
+ return values.at(-1);
147
+ }
148
+ function globalconfigPath(env) {
149
+ const globalconfig = envValue(env, 'NPM_CONFIG_GLOBALCONFIG');
150
+ if (globalconfig)
151
+ return expandTilde(globalconfig);
152
+ const prefix = envValue(env, 'NPM_CONFIG_PREFIX') || env.PREFIX || dirname(dirname(process.execPath));
153
+ return join(prefix, 'etc', 'npmrc');
154
+ }
155
+ function stripIniQuotes(value) {
156
+ const trimmed = value.trim();
157
+ const quoted = /^(['"])([\s\S]*)\1$/.exec(trimmed);
158
+ return quoted ? quoted[2] : trimmed;
159
+ }
160
+ // npm's ini value rule: a quoted value keeps its comment characters; an
161
+ // unquoted value ends at the first unescaped `;` or `#` (with or without
162
+ // whitespace) and backslash escapes those three characters.
163
+ function parseIniValue(raw) {
164
+ const trimmed = raw.trim();
165
+ if (/^(['"])[\s\S]*\1$/.test(trimmed))
166
+ return stripIniQuotes(trimmed);
167
+ let out = '';
168
+ let escaped = false;
169
+ for (const char of trimmed) {
170
+ if (escaped) {
171
+ out += ';#\\'.includes(char) ? char : `\\${char}`;
172
+ escaped = false;
173
+ }
174
+ else if (char === ';' || char === '#') {
175
+ break;
176
+ }
177
+ else if (char === '\\') {
178
+ escaped = true;
179
+ }
180
+ else {
181
+ out += char;
182
+ }
183
+ }
184
+ if (escaped)
185
+ out += '\\';
186
+ return out.trim();
187
+ }
188
+ // npm's env-replace: `\${...}` stays literal, `${VAR}` interpolates the exact
189
+ // env name (unset keeps the literal), and `${VAR?}` resolves empty when unset.
190
+ function envReplace(value, env) {
191
+ let out = '';
192
+ for (let index = 0; index < value.length; index += 1) {
193
+ const char = value[index];
194
+ if (char === '\\' && value[index + 1] === '$') {
195
+ out += '$';
196
+ index += 1;
197
+ continue;
198
+ }
199
+ if (char === '$' && value[index + 1] === '{') {
200
+ const end = value.indexOf('}', index + 2);
201
+ if (end < 0) {
202
+ out += char;
203
+ continue;
204
+ }
205
+ let name = value.slice(index + 2, end);
206
+ const optional = name.endsWith('?');
207
+ if (optional)
208
+ name = name.slice(0, -1);
209
+ const resolved = env[name];
210
+ out += resolved !== undefined ? resolved : optional ? '' : value.slice(index, end + 1);
211
+ index = end;
212
+ continue;
213
+ }
214
+ out += char;
215
+ }
216
+ return out;
217
+ }
218
+ function parseNpmrc(text, env) {
219
+ const entries = new Map();
220
+ for (const line of text.split(/\r?\n/)) {
221
+ const trimmed = line.trim();
222
+ if (!trimmed || trimmed.startsWith(';') || trimmed.startsWith('#'))
223
+ continue;
224
+ const match = /^([^=]+?)\s*=\s*(.*)$/.exec(trimmed);
225
+ if (!match)
226
+ continue;
227
+ const value = parseIniValue(match[2]);
228
+ entries.set(match[1].trim(), envReplace(value, env));
229
+ }
230
+ return entries;
231
+ }
232
+ // npm's auth cascade: env-spread nerf keys, the project/workspace root
233
+ // (nearest package.json), the userconfig, then the global config. Unreadable
234
+ // files contribute nothing.
235
+ function configLayers(env) {
236
+ const layers = [];
237
+ const spread = new Map();
238
+ for (const [key, value] of Object.entries(env)) {
239
+ const body = /^npm_config_(.*)$/i.exec(key)?.[1];
240
+ if (body?.startsWith('//') && value !== undefined)
241
+ spread.set(body, envReplace(value, env));
242
+ }
243
+ if (spread.size)
244
+ layers.push(spread);
245
+ const userconfig = resolveUserconfig(env);
246
+ const files = [join(localPrefix(), '.npmrc'), userconfig ?? join(homedir(), '.npmrc'), globalconfigPath(env)];
247
+ for (const file of files) {
248
+ try {
249
+ layers.push(parseNpmrc(readFileSync(file, 'utf8'), env));
250
+ }
251
+ catch {
252
+ // an unreadable config layer contributes no keys
253
+ }
254
+ }
255
+ return layers;
256
+ }
257
+ function basicHeader(username, password) {
258
+ if (!username || password === undefined)
259
+ return undefined;
260
+ const decoded = (() => {
261
+ try {
262
+ return Buffer.from(password, 'base64').toString('utf8');
263
+ }
264
+ catch {
265
+ return password;
266
+ }
267
+ })();
268
+ return `Basic ${Buffer.from(`${username}:${decoded}`).toString('base64')}`;
269
+ }
270
+ // The pre-flight auth header for a registry, resolved the way npm resolves it:
271
+ // walk every nerf-dart path level through to the host root (both the slash and
272
+ // slash-less keys), and take the first token/basic entry found across the
273
+ // config cascade. A falsy candidate is skipped, never terminal (npm's hasAuth
274
+ // tests truthiness and keeps walking), while an explicitly empty key's layer
275
+ // suppresses the lower layers; when the whole walk finds no auth and some level
276
+ // named an empty auth key, `null` tells the caller not to resurrect the env
277
+ // token.
278
+ function npmrcAuthHeader(registry, env = process.env) {
279
+ let url;
280
+ try {
281
+ url = new URL(registry);
282
+ }
283
+ catch {
284
+ return undefined;
285
+ }
286
+ const host = `//${url.host}`;
287
+ const path = url.pathname.replace(/\/+$/, '');
288
+ const levels = [];
289
+ let current = path;
290
+ for (;;) {
291
+ levels.push(current);
292
+ if (!current)
293
+ break;
294
+ const next = current.replace(/\/[^/]*$/, '');
295
+ if (next === current)
296
+ break;
297
+ current = next;
298
+ }
299
+ const layers = configLayers(env);
300
+ // `undefined` means no layer names the key; an empty string is that layer's
301
+ // explicit (falsy) value.
302
+ const lookup = (key) => {
303
+ for (const layer of layers) {
304
+ if (layer.has(key))
305
+ return layer.get(key);
306
+ }
307
+ return undefined;
308
+ };
309
+ let sawExplicitEmpty = false;
310
+ for (const level of levels) {
311
+ const prefix = `${host}${level}`;
312
+ const token = lookup(`${prefix}/:_authToken`) ?? lookup(`${prefix}:_authToken`);
313
+ if (token)
314
+ return token.startsWith('Bearer ') ? token : `Bearer ${token}`;
315
+ if (token === '')
316
+ sawExplicitEmpty = true;
317
+ const auth = lookup(`${prefix}/:_auth`) ?? lookup(`${prefix}:_auth`);
318
+ if (auth)
319
+ return `Basic ${auth}`;
320
+ if (auth === '')
321
+ sawExplicitEmpty = true;
322
+ const username = lookup(`${prefix}/:username`);
323
+ const password = lookup(`${prefix}/:_password`);
324
+ if (username && password) {
325
+ const basic = basicHeader(username, password);
326
+ if (basic)
327
+ return basic;
328
+ }
329
+ if (username !== undefined && password !== undefined && (!username || !password))
330
+ sawExplicitEmpty = true;
331
+ }
332
+ return sawExplicitEmpty ? null : undefined;
333
+ }
334
+ // The pre-flight follows redirects the way npm's registry client does: the same
335
+ // Authorization header travels to a same-host target leg (port or scheme
336
+ // changes re-authenticate), and a hostname change drops it.
337
+ async function fetchFollowingAuth(url, init) {
338
+ let current = url;
339
+ const originalHost = new URL(url).hostname;
340
+ for (let hop = 0; hop < 5; hop += 1) {
341
+ const hopInit = { ...init, redirect: 'manual' };
342
+ // npm re-authenticates a same-host redirect (port/scheme changes) but strips
343
+ // the Authorization when the hostname changes.
344
+ if (new URL(current).hostname !== originalHost)
345
+ delete hopInit.headers;
346
+ const response = await fetchWithProxy(current, hopInit);
347
+ const location = response.status >= 300 && response.status < 400 ? response.headers.get('location') : undefined;
348
+ if (!location)
349
+ return response;
350
+ try {
351
+ current = new URL(location, current).toString();
352
+ }
353
+ catch {
354
+ return response;
355
+ }
356
+ }
357
+ return null;
358
+ }
46
359
  export async function queryDistTagsFetch({ timeoutMs = 15000 } = {}) {
47
- let registry = 'https://registry.npmjs.org';
48
- if (process.env.HUAWEICLOUD_NPM_REGISTRY) {
49
- registry = process.env.HUAWEICLOUD_NPM_REGISTRY.replace(/\/+$/, '');
360
+ // One normalization with upgradeEnv: a padded or case-variant spelling is
361
+ // usable and a whitespace-only value is unset, so the pre-flight and the
362
+ // child pin cannot disagree.
363
+ let configured = resolveRegistryOverride();
364
+ // A registry override may carry URL credentials; npm only falls back to them
365
+ // when the config cascade yields no header, and it sends the raw
366
+ // (percent-encoded) userinfo as Basic.
367
+ let urlAuth;
368
+ if (configured) {
369
+ try {
370
+ const parsed = new URL(configured);
371
+ if (parsed.username || parsed.password) {
372
+ urlAuth = `Basic ${Buffer.from(`${parsed.username}:${parsed.password}`).toString('base64')}`;
373
+ parsed.username = '';
374
+ parsed.password = '';
375
+ configured = parsed.toString();
376
+ }
377
+ }
378
+ catch {
379
+ // a malformed URL degrades like npm's own registry parse
380
+ }
50
381
  }
382
+ let registry = 'https://registry.npmjs.org';
383
+ // The request URL is built by appending `/-/package/…`, so a trailing slash
384
+ // on the override would produce a doubled path.
385
+ if (configured)
386
+ registry = configured.replace(/\/+$/, '');
51
387
  const controller = new AbortController();
52
388
  const timer = setTimeout(() => controller.abort(), timeoutMs);
389
+ // The pre-flight query needs the same mirror auth the child npm gets: a
390
+ // token-guarded private mirror 401s the packument without it, aborting the
391
+ // act before the spawn. The token is read for this request only; the env
392
+ // shaping of the child is a separate concern.
393
+ // npm's own order: the config cascade's named channel first (an .npmrc value
394
+ // may interpolate NODE_AUTH_TOKEN even when a stale NPM_TOKEN is exported),
395
+ // then the URL userinfo, then the env tokens, then no auth.
396
+ const token = resolveNpmAuthToken();
397
+ const configAuth = npmrcAuthHeader(registry);
398
+ // `null` is an explicitly empty config token: no env fallback (npm's merged
399
+ // value is empty and it sends nothing); URL userinfo still applies, as it
400
+ // does for npm when no Authorization header was set.
401
+ const authorization = configAuth ?? urlAuth ?? (configAuth === null || !token ? undefined : `Bearer ${token}`);
402
+ const init = {
403
+ signal: controller.signal,
404
+ ...(authorization ? { headers: { authorization } } : {}),
405
+ };
53
406
  try {
54
- const resp = await fetchWithProxy(`${registry}/-/package/huaweicloud-devkit/dist-tags`);
407
+ const resp = await fetchFollowingAuth(`${registry}/-/package/huaweicloud-devkit/dist-tags`, init);
55
408
  clearTimeout(timer);
56
409
  if (!resp || !resp.ok)
57
410
  return null;
@@ -95,7 +448,7 @@ export function queryDistTags({ timeoutMs = 15000, cwd, } = {}) {
95
448
  // delegation closes that inconsistency, so every default consumer
96
449
  // (getCachedUpdateInfo, upgradePackage) honors the operator/E2E override
97
450
  // without spawning npm.
98
- if (process.env.HUAWEICLOUD_NPM_REGISTRY) {
451
+ if (resolveRegistryOverride()) {
99
452
  return queryDistTagsFetch({ timeoutMs });
100
453
  }
101
454
  return new Promise((resolve) => {