huaweicloud-devkit 1.1.13 → 1.1.14-next.1

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 (28) hide show
  1. package/integrations/opencode/package-lock.json +24 -0
  2. package/integrations/opencode/package.json +10 -0
  3. package/integrations/opencode/plugins/huaweicloud-devkit.js +194 -0
  4. package/package.json +1 -1
  5. package/plugins/huaweicloud-core/.claude-plugin/plugin.json +16 -3
  6. package/plugins/huaweicloud-core/.codex-plugin/plugin.json +16 -3
  7. package/plugins/huaweicloud-core/.cursor-plugin/plugin.json +16 -3
  8. package/plugins/huaweicloud-core/.hermes-plugin/plugin.json +16 -3
  9. package/plugins/huaweicloud-core/.workbuddy-plugin/plugin.json +16 -3
  10. package/plugins/huaweicloud-core/openclaw.plugin.json +1 -1
  11. package/plugins/huaweicloud-core/safety/rules/cloud-risk-rules.json +6 -0
  12. package/plugins/huaweicloud-core/src/account-type.mjs +10 -1
  13. package/plugins/huaweicloud-core/src/auth/agent-registration.mjs +1 -1
  14. package/plugins/huaweicloud-core/src/auth/credentials.mjs +118 -4
  15. package/plugins/huaweicloud-core/src/auth/service.mjs +25 -2
  16. package/plugins/huaweicloud-core/src/auth/token-exchange.mjs +100 -0
  17. package/plugins/huaweicloud-core/src/hcloud-cli.mjs +49 -4
  18. package/plugins/huaweicloud-core/src/hcloud-probe.mjs +12 -0
  19. package/plugins/huaweicloud-core/src/koocli-install.mjs +57 -0
  20. package/plugins/huaweicloud-core/src/mcp-config-merge.mjs +1 -1
  21. package/plugins/huaweicloud-core/src/risk-rule-engine.mjs +1 -1
  22. package/plugins/huaweicloud-core/src/safety-policy.mjs +1 -1
  23. package/plugins/huaweicloud-core/src/sandbox/devbridge-key.mjs +6 -0
  24. package/plugins/huaweicloud-core/src/sandbox/hdkitservice-api.mjs +29 -7
  25. package/plugins/huaweicloud-core/src/sandbox/hwlink-api.mjs +36 -1
  26. package/plugins/huaweicloud-core/src/sandbox/session-manager.mjs +4 -4
  27. package/plugins/huaweicloud-core/src/setup-cli.mjs +91 -9
  28. package/plugins/huaweicloud-core/src/tools.mjs +57 -3
@@ -11,6 +11,7 @@ import {
11
11
  readCodeArtsCredentials,
12
12
  readGlobalCredentials,
13
13
  resolveCredentialsWithRuntime,
14
+ resolveXAuthToken,
14
15
  writeLastSync,
15
16
  writeObsConfig,
16
17
  } from './credentials.mjs';
@@ -79,6 +80,15 @@ export function computeOnboarding({ credentials, reconciled } = {}) {
79
80
  message = '已从码道 MCP settings 读取到临时凭证,MCP 工具可直接使用。';
80
81
  return { needsSetup: false, scenario, reason, message, steps: [], accountHint };
81
82
  }
83
+ if (resolveXAuthToken() && !s1Has && !envHasCreds) {
84
+ // X-Auth-Token authentication: no AK/SK injected but a token is present —
85
+ // devkit exchanges it for temporary AK/SK on demand, so no manual setup.
86
+ scenario = 0;
87
+ reason = 'token-auth';
88
+ message =
89
+ '已使用 X-Auth-Token 认证。管理面与数据面(沙箱部署/exec)都会在需要时用 token 自动换取临时 AK/SK;请确保可访问 IAM 端点。';
90
+ return { needsSetup: false, scenario, reason, message, steps: [], accountHint };
91
+ }
82
92
  if (s1Has && !envHasCreds) {
83
93
  scenario = 1;
84
94
  reason = 's1-only';
@@ -167,6 +177,7 @@ export function getAuthStatus(target = 'all') {
167
177
  const s4Creds = readCodeArtsCredentials();
168
178
  const onboarding = computeOnboarding({ credentials, reconciled });
169
179
  const stsExpiry = computeStsExpiry();
180
+ const tokenAuth = resolveXAuthToken();
170
181
  const credentialPanel = {
171
182
  sts: stsExpiry, // 临时 STS(MCP==沙箱同源)
172
183
  s1: {
@@ -174,11 +185,23 @@ export function getAuthStatus(target = 'all') {
174
185
  fingerprint: credentials?.ak ? fingerprint(credentials.ak, credentials.sk) : null,
175
186
  persistent: true, // 永久,无过期
176
187
  },
177
- activeSource: stsExpiry ? 'temporary-sts' : credentials?.ak ? 's1-persistent' : 'none',
188
+ token: tokenAuth ? { active: true } : { active: false },
189
+ activeSource: stsExpiry ? 'temporary-sts' : credentials?.ak ? 's1-persistent' : tokenAuth ? 'x-auth-token' : 'none',
178
190
  };
179
191
  return {
180
192
  target,
181
- credentialsConfigured: Boolean(credentials?.ak && credentials?.sk),
193
+ // usableCredentials: any credential source that makes the MCP/backend path
194
+ // actually work right now (S1, CodeArts settings, platform STS triplet,
195
+ // X-Auth-Token, or runtime creds) — supersedes the misleading
196
+ // credentialsConfigured/onboarding split (#P4).
197
+ usableCredentials: Boolean(
198
+ (credentials?.ak && credentials?.sk) ||
199
+ (s4Creds?.ak && s4Creds?.sk) ||
200
+ envHasRealTriplet() ||
201
+ tokenAuth ||
202
+ hasRuntimeCredentials(),
203
+ ),
204
+ credentialsConfigured: Boolean(credentials?.ak && credentials?.sk) || Boolean(tokenAuth),
182
205
  credentialsPath: globalCredentialsPath(),
183
206
  mcpSettingsConfigured: Boolean(s4Creds?.ak && s4Creds?.sk),
184
207
  mcpSettingsSource: s4Creds ? 'codearts' : null,
@@ -0,0 +1,100 @@
1
+ import { fetchWithProxy } from '../proxy/proxy-agent.mjs';
2
+
3
+ const DEFAULT_DURATION_SECONDS = 900;
4
+ const DEFAULT_IAM_ENDPOINT = 'https://iam.myhuaweicloud.com';
5
+
6
+ export async function exchangeTokenForCredentials(token, options = {}) {
7
+ const durationSeconds = options.durationSeconds ?? DEFAULT_DURATION_SECONDS;
8
+ const iamEndpoint = options.iamEndpoint || process.env.HW_TOKEN_IAM_ENDPOINT || DEFAULT_IAM_ENDPOINT;
9
+ const fetchImpl = options.fetchImpl;
10
+
11
+ const body = {
12
+ auth: {
13
+ identity: {
14
+ methods: ['token'],
15
+ token: { id: token, duration_seconds: durationSeconds },
16
+ },
17
+ },
18
+ };
19
+
20
+ const fetchOpts = {
21
+ method: 'POST',
22
+ headers: { 'Content-Type': 'application/json;charset=utf8' },
23
+ body: JSON.stringify(body),
24
+ };
25
+
26
+ const url = `${iamEndpoint}/v3.0/OS-CREDENTIAL/securitytokens`;
27
+
28
+ let resp;
29
+ try {
30
+ resp = fetchImpl ? await fetchImpl(url, fetchOpts) : await fetchWithProxy(url, fetchOpts);
31
+ } catch (error) {
32
+ const err = new Error(`Token exchange request failed: ${error.message}`);
33
+ err.code = 'TOKEN_EXCHANGE_FAILED';
34
+ throw err;
35
+ }
36
+
37
+ if (resp.status === 401 || resp.status === 403) {
38
+ const err = new Error('X-Auth-Token is invalid or expired.');
39
+ err.code = 'TOKEN_INVALID';
40
+ throw err;
41
+ }
42
+ if (resp.status !== 201) {
43
+ const err = new Error(`Token exchange returned unexpected status ${resp.status}.`);
44
+ err.code = 'TOKEN_EXCHANGE_FAILED';
45
+ throw err;
46
+ }
47
+
48
+ let data;
49
+ try {
50
+ data = await resp.json();
51
+ } catch (error) {
52
+ const err = new Error(`Token exchange returned malformed JSON: ${error.message}`);
53
+ err.code = 'TOKEN_EXCHANGE_FAILED';
54
+ throw err;
55
+ }
56
+ const cred = data?.credential;
57
+ if (!cred?.access || !cred?.secret || !cred?.securitytoken) {
58
+ const err = new Error('Token exchange response missing credential fields.');
59
+ err.code = 'TOKEN_EXCHANGE_FAILED';
60
+ throw err;
61
+ }
62
+ // IAM always returns expires_at; if it is absent (or unparseable) we store
63
+ // expiresAt:null, which never satisfies the `cached.expiresAt && …` guard in
64
+ // getTokenCredentials — so the cache is always a miss and we deliberately
65
+ // re-exchange on every call rather than risk caching credentials forever.
66
+ const expiresAt = cred.expires_at ? Date.parse(cred.expires_at) : NaN;
67
+ return {
68
+ ak: cred.access,
69
+ sk: cred.secret,
70
+ securityToken: cred.securitytoken,
71
+ expiresAt: Number.isFinite(expiresAt) ? expiresAt : null,
72
+ };
73
+ }
74
+
75
+ const GRACE_MS = 60 * 1000;
76
+
77
+ let cached = null; // { ak, sk, securityToken, expiresAt }
78
+ let inflight = null; // Promise 单飞
79
+
80
+ export function __resetTokenCache() {
81
+ cached = null;
82
+ inflight = null;
83
+ }
84
+
85
+ export async function getTokenCredentials(token, options = {}) {
86
+ const now = Date.now();
87
+ if (cached && cached.expiresAt && cached.expiresAt - GRACE_MS > now) {
88
+ return cached;
89
+ }
90
+ if (inflight) return inflight;
91
+ inflight = (async () => {
92
+ try {
93
+ cached = await exchangeTokenForCredentials(token, options);
94
+ return cached;
95
+ } finally {
96
+ inflight = null;
97
+ }
98
+ })();
99
+ return inflight;
100
+ }
@@ -7,7 +7,14 @@ import { dirname, join } from 'node:path';
7
7
  import { classifyHcloudArgs, redactSecrets, assertAllowed } from './safety-policy.mjs';
8
8
  import { getProxySettings } from './proxy/proxy-config.mjs';
9
9
  import { resolveHcloudCommand } from './hcloud-probe.mjs';
10
- import { parseStsExpiry, resolveCredentialsWithRuntime } from './auth/credentials.mjs';
10
+ import {
11
+ parseStsExpiry,
12
+ resolveCredentialsWithRuntime,
13
+ warmTokenCredentials,
14
+ resolveXAuthToken,
15
+ resolveXAuthTokenExpiry,
16
+ } from './auth/credentials.mjs';
17
+ import { getTokenCredentials } from './auth/token-exchange.mjs';
11
18
 
12
19
  const DEFAULT_TIMEOUT_MS = 60_000;
13
20
  const DEFAULT_FORCE_KILL_AFTER_MS = 2_000;
@@ -297,7 +304,7 @@ export function redactArgsWithObs(rawArgs) {
297
304
  return redactSecrets(out);
298
305
  }
299
306
 
300
- export function resolveStsInjectArgs(rawArgs) {
307
+ export async function resolveStsInjectArgs(rawArgs) {
301
308
  const normalized = Array.isArray(rawArgs) ? rawArgs.map(String) : [];
302
309
  if (normalized.length === 0) return [];
303
310
  const flat = normalized.map(String);
@@ -350,7 +357,25 @@ export function resolveStsInjectArgs(rawArgs) {
350
357
  } catch {
351
358
  return [];
352
359
  }
353
- if (!creds || !creds.ak || !creds.sk || !creds.securityToken) return [];
360
+ if (!creds || !creds.ak || !creds.sk) {
361
+ const token = resolveXAuthToken();
362
+ if (token) {
363
+ const expiry = resolveXAuthTokenExpiry();
364
+ if (expiry !== null && expiry - 60000 <= Date.now()) {
365
+ const err = new Error('X-Auth-Token 已过期,请重启进程重新注入凭证。');
366
+ err.code = 'TOKEN_EXPIRED';
367
+ throw err;
368
+ }
369
+ const temp = await getTokenCredentials(token);
370
+ return [
371
+ '--cli-access-key=' + temp.ak,
372
+ '--cli-secret-key=' + temp.sk,
373
+ '--cli-security-token=' + temp.securityToken,
374
+ ];
375
+ }
376
+ return [];
377
+ }
378
+ if (!creds.securityToken) return [];
354
379
 
355
380
  // R3: if we can derive an expiry and the token is already at/within 60s of
356
381
  // expiring, skip injection — using a dead token would make a doomed IAM round
@@ -448,6 +473,11 @@ export async function runHcloud(args, options = {}) {
448
473
  };
449
474
  assertAllowed(plan.classification);
450
475
 
476
+ // Token-only users: warm X-Auth-Token → runtime STS BEFORE any sync
477
+ // credential reads (isTemporaryStsExpired / resolveStsInjectArgs) so the
478
+ // hcloud path works without permanent AK/SK. No-op when AK/SK present.
479
+ await warmTokenCredentials();
480
+
451
481
  // A: fail fast when the platform-injected temporary STS is already expired —
452
482
  // otherwise hcloud would make a doomed IAM round trip and surface a misleading
453
483
  // error (e.g. "缺少 cli-domain-id"). Permanent AK/SK are unaffected.
@@ -468,7 +498,22 @@ export async function runHcloud(args, options = {}) {
468
498
  // and R3 forbids writing them to disk). Inject per-command so hcloud actually
469
499
  // authenticates with the platform-provided STS. Injection args are appended to
470
500
  // the EXECUTED args only; classification/approval used the original args.
471
- const stsInject = resolveStsInjectArgs(normalizedArgs);
501
+ let stsInject;
502
+ try {
503
+ stsInject = await resolveStsInjectArgs(normalizedArgs);
504
+ } catch (error) {
505
+ if (error?.code === 'TOKEN_INVALID' || error?.code === 'TOKEN_EXCHANGE_FAILED' || error?.code === 'TOKEN_EXPIRED') {
506
+ return {
507
+ ok: false,
508
+ code: error.code,
509
+ error: error.message,
510
+ stderr: '',
511
+ stdout: '',
512
+ plan,
513
+ };
514
+ }
515
+ throw error;
516
+ }
472
517
  if (stsInject.length > 0) {
473
518
  plan.rawArgs = [...plan.rawArgs, ...stsInject];
474
519
  }
@@ -111,6 +111,18 @@ export function classifyHcloudProbe(result, requiredVersion = getKooCliVersion()
111
111
  };
112
112
  }
113
113
 
114
+ // Probe timed out / was signal-killed: we can't tell whether hcloud is truly
115
+ // broken or just slow on this box — report unknown instead of unavailable so
116
+ // the caller doesn't falsely conclude "CLI not installed" (#P0-2).
117
+ if (result.signal || result.status === null || result.error?.code === 'ETIMEDOUT') {
118
+ return {
119
+ status: 'unknown',
120
+ installed: false,
121
+ ok: false,
122
+ errorCode: 'HCLOUD_UNKNOWN',
123
+ };
124
+ }
125
+
114
126
  return {
115
127
  status: 'unavailable',
116
128
  installed: false,
@@ -0,0 +1,57 @@
1
+ import { spawnSync } from 'node:child_process';
2
+ import { chmodSync, existsSync, mkdirSync, rmSync, writeFileSync } from 'node:fs';
3
+ import { homedir } from 'node:os';
4
+ import { join } from 'node:path';
5
+
6
+ import { getKooCliVersion, kooCliDownloadBase } from './koocli-version.mjs';
7
+
8
+ // Programmatic KooCLI (hcloud) install — downloadable from inside the MCP server
9
+ // process via Node (fetch + tar via child_process), so it does NOT depend on the
10
+ // agent's bash tool (which is unavailable in CodeArts with OPENCODE_CONFIG
11
+ // unset — experience-report #3.5). Returns a structured result for the
12
+ // `huaweicloud_install_hcloud` MCP tool.
13
+ export async function installKooCli(options = {}) {
14
+ const os = process.platform;
15
+ const arch = process.arch;
16
+
17
+ // Windows auto-install needs PowerShell specifics — keep it on the CLI path.
18
+ if (os === 'win32') {
19
+ return { ok: false, error: 'Windows 环境请使用 CLI: npx huaweicloud-devkit install-hcloud' };
20
+ }
21
+ if (os !== 'linux' && os !== 'darwin') {
22
+ return { ok: false, error: `不支持的操作系统: ${os}` };
23
+ }
24
+
25
+ const installDir = options.binDir || (os === 'linux' ? join(homedir(), '.local', 'bin') : '/usr/local/bin');
26
+ const pkg =
27
+ os === 'linux' ? (arch === 'arm64' ? 'linux-arm64' : 'linux-amd64') : arch === 'arm64' ? 'mac-arm64' : 'mac-amd64';
28
+ const url = `${kooCliDownloadBase()}/huaweicloud-cli-${pkg}.tar.gz`;
29
+ const binPath = join(installDir, 'hcloud');
30
+
31
+ try {
32
+ mkdirSync(installDir, { recursive: true });
33
+
34
+ const tmpTar = join(installDir, `huaweicloud-cli-${pkg}.tar.gz`);
35
+ const resp = await fetch(url);
36
+ if (!resp.ok) {
37
+ return { ok: false, error: `下载失败 (HTTP ${resp.status}): ${url}` };
38
+ }
39
+ const buf = Buffer.from(await resp.arrayBuffer());
40
+ writeFileSync(tmpTar, buf);
41
+
42
+ const ex = spawnSync('tar', ['-xzf', tmpTar, '-C', installDir], { stdio: 'pipe', timeout: 60000 });
43
+ rmSync(tmpTar, { force: true });
44
+ if (ex.status !== 0) {
45
+ return { ok: false, error: `解压失败 (tar exit ${ex.status}): ${(ex.stderr || '').toString().slice(0, 200)}` };
46
+ }
47
+
48
+ if (!existsSync(binPath)) {
49
+ return { ok: false, error: `hcloud 二进制未生成于 ${binPath}` };
50
+ }
51
+ chmodSync(binPath, 0o755);
52
+
53
+ return { ok: true, binPath, version: getKooCliVersion() };
54
+ } catch (error) {
55
+ return { ok: false, error: error?.message || String(error) };
56
+ }
57
+ }
@@ -3,7 +3,7 @@
3
3
  // Program-owned fields (the node executable + mcp-server.mjs path, required env
4
4
  // keys) are corrected by the installer; everything else belongs to the user.
5
5
 
6
- function isPlainObject(value) {
6
+ export function isPlainObject(value) {
7
7
  return Boolean(value) && typeof value === 'object' && !Array.isArray(value);
8
8
  }
9
9
 
@@ -19,7 +19,7 @@ export function loadRiskRules(options = {}) {
19
19
  function redactEvidence(text) {
20
20
  return String(text)
21
21
  .replace(
22
- /((?:access[_-]?key|secret[_-]?key|secret|security[_-]?token|x[_-]?auth[_-]?token|token|authorization|password|passwd|admin[_-]?pass|credential)\s*[:=]\s*)("[^"]*"|'[^']*'|[^\s,;]+)/gi,
22
+ /((?:access[_-]?key|secret[_-]?key|secret|security[_-]?token|x[_-]?auth[_-]?token|x[_-]?subject[_-]?token|token|authorization|password|passwd|admin[_-]?pass|credential)\s*[:=]\s*)("[^"]*"|'[^']*'|[^\s,;]+)/gi,
23
23
  '$1<redacted>',
24
24
  )
25
25
  .replace(/(AK|SK)\s*[:=]\s*("[^"]*"|'[^']*'|[^\s,;]+)/g, '$1=<redacted>');
@@ -39,7 +39,7 @@ function redactString(text) {
39
39
  // Redact the ENTIRE value of this arg — not just the first whitespace token.
40
40
  .replace(/((?:user[_-]?data|metadata|private[_-]?key)\s*[:=]\s*).*/gi, '$1<redacted>')
41
41
  .replace(
42
- /((?:access[_-]?key|secret[_-]?key|security[_-]?token|x[_-]?auth[_-]?token|token|authorization|password|passwd|admin[_-]?pass|credential)\s*[:=]\s*)("[^"]*"|'[^']*'|[^\s,;]+)/gi,
42
+ /((?:access[_-]?key|secret[_-]?key|security[_-]?token|x[_-]?auth[_-]?token|x[_-]?subject[_-]?token|token|authorization|password|passwd|admin[_-]?pass|credential)\s*[:=]\s*)("[^"]*"|'[^']*'|[^\s,;]+)/gi,
43
43
  '$1<redacted>',
44
44
  )
45
45
  .replace(/(AK|SK)\s*[:=]\s*("[^"]*"|'[^']*'|[^\s,;]+)/g, '$1=<redacted>')
@@ -20,6 +20,7 @@ import { createHash } from 'node:crypto';
20
20
 
21
21
  import { hdkitCreateApiKey, hdkitListApiKeys, hdkitDeleteApiKey } from './hdkitservice-api.mjs';
22
22
  import { getCredentials } from './hwlink-api.mjs';
23
+ import { warmTokenCredentials } from '../auth/credentials.mjs';
23
24
 
24
25
  const POOL_KEY_NAMES = {
25
26
  ephemeral: 'devkit-ephemeral',
@@ -97,6 +98,10 @@ export function clearCachedKey(ak, poolType) {
97
98
  * @throws Error 配额满(code=HDKIT_DEVBRIDGE_KEY_QUOTA_EXCEEDED)或上游错误
98
99
  */
99
100
  export async function ensureDevbridgeKey(poolType) {
101
+ // Token-only users: exchange X-Auth-Token → runtime STS first, so the sync
102
+ // getCredentials() below succeeds (it throws HDKIT_CRED_MISSING otherwise,
103
+ // which blocked the whole auto-create fallback for token-auth users).
104
+ await warmTokenCredentials();
100
105
  const { ak } = getCredentials();
101
106
  const pool = POOL_KEY_NAMES[poolType] ? poolType : DEFAULT_POOL;
102
107
  const name = keyNameForPool(pool);
@@ -132,6 +137,7 @@ export async function ensureDevbridgeKey(poolType) {
132
137
  * 由沙箱内 devbridge auth login 失败触发。
133
138
  */
134
139
  export async function recreateDevbridgeKey(poolType) {
140
+ await warmTokenCredentials();
135
141
  const { ak } = getCredentials();
136
142
  clearCachedKey(ak, poolType);
137
143
  return ensureDevbridgeKey(poolType);
@@ -1,22 +1,44 @@
1
- import { getCredentials } from './hwlink-api.mjs';
1
+ import { pinnedTemplateFor } from './sandbox-pool.mjs';
2
2
  import { getProxyDispatcher } from '../proxy/proxy-agent.mjs';
3
3
  import { cacheUserHash } from '../telemetry/telemetry.mjs';
4
4
  import { detectAgent } from '../telemetry/agent-detect.mjs';
5
5
  import { readInstalledVersion } from '../update-check.mjs';
6
- import { pinnedTemplateFor } from './sandbox-pool.mjs';
6
+ import { resolveCredentialsWithRuntime, resolveXAuthToken } from '../auth/credentials.mjs';
7
+ import { getTokenCredentials } from '../auth/token-exchange.mjs';
8
+ import { makeError } from '../auth/guidance.mjs';
7
9
 
8
10
  function getHdkitBaseUrl() {
9
11
  return process.env.HDKITSERVICE_ENDPOINT || 'https://devkit.huaweicloud.com/rest/developer/server/hdkitservice/';
10
12
  }
11
13
 
14
+ // Backend (hdkitservice/voucher) credentials: prefer AK/SK, else fall back to
15
+ // X-Auth-Token → temporary AK/SK exchange, so token-auth users are not blocked.
16
+ async function resolveBackendCredentials() {
17
+ try {
18
+ const creds = resolveCredentialsWithRuntime({ allowMissing: true });
19
+ if (creds && creds.ak && creds.sk) return creds;
20
+ } catch {
21
+ // no AK/SK — fall through to token
22
+ }
23
+ const token = resolveXAuthToken();
24
+ if (!token) return null;
25
+ try {
26
+ return await getTokenCredentials(token);
27
+ } catch {
28
+ return null;
29
+ }
30
+ }
31
+
12
32
  async function hdkitRequest(method, path, body, timeoutMs = 300000) {
13
- const { ak, sk, securitytoken } = getCredentials();
33
+ const creds = await resolveBackendCredentials();
34
+ const ak = creds?.ak;
35
+ const sk = creds?.sk;
36
+ const securitytoken = creds?.securityToken || '';
14
37
 
15
38
  if (!ak || !sk) {
16
- throw new Error(
17
- 'Huawei Cloud credentials are not configured. ' +
18
- 'Run "npx huaweicloud-devkit auth init" or set HW_ACCESS_KEY/HW_SECRET_KEY.',
19
- );
39
+ const err = makeError('HDKIT_CRED_MISSING');
40
+ err.detail = 'Run "npx huaweicloud-devkit auth init" or set HW_ACCESS_KEY/HW_SECRET_KEY/HW_X_AUTH_TOKEN.';
41
+ throw err;
20
42
  }
21
43
  const headers = {
22
44
  'Content-Type': 'application/json',
@@ -1,6 +1,8 @@
1
1
  import crypto from 'node:crypto';
2
2
 
3
- import { resolveCredentialsWithRuntime } from '../auth/credentials.mjs';
3
+ import { resolveCredentialsWithRuntime, resolveXAuthToken } from '../auth/credentials.mjs';
4
+ import { getTokenCredentials } from '../auth/token-exchange.mjs';
5
+ import { makeError } from '../auth/guidance.mjs';
4
6
  import { getProxyDispatcher } from '../proxy/proxy-agent.mjs';
5
7
 
6
8
  const BASE_URL = process.env.HWLINK_ENDPOINT || 'https://devstation.myhuaweicloud.com';
@@ -82,6 +84,39 @@ export function getCredentials() {
82
84
  return { ak: credentials.ak, sk: credentials.sk, securitytoken: credentials.securityToken };
83
85
  }
84
86
 
87
+ // Data-plane (sandbox exec/upload/tunnel) credentials: prefer AK/SK, else fall
88
+ // back to X-Auth-Token → temporary AK/SK, so token-auth users can drive the data
89
+ // plane without a permanent AK/SK (experience-report #3.3/#3.7 dead-loop fix).
90
+ // NOTE: returns `securitytoken` (lowercase t) — the call sites (session-manager,
91
+ // tools.mjs) destructure that exact spelling; returning `securityToken` here
92
+ // silently drops the STS token from the hwlink signature (APIGW.0301).
93
+ export async function resolveBackendCredentials() {
94
+ try {
95
+ const creds = resolveCredentialsWithRuntime({ allowMissing: true });
96
+ if (creds && creds.ak && creds.sk) {
97
+ return { ak: creds.ak, sk: creds.sk, securitytoken: creds.securityToken || '' };
98
+ }
99
+ } catch {
100
+ // no AK/SK — fall through to token
101
+ }
102
+ const token = resolveXAuthToken();
103
+ if (token) {
104
+ try {
105
+ const temp = await getTokenCredentials(token);
106
+ return { ak: temp.ak, sk: temp.sk, securitytoken: temp.securityToken || '' };
107
+ } catch (error) {
108
+ // Distinguish "token exchange failed" from "no credential at all" (#3.4).
109
+ const err = makeError('HDKIT_CRED_MISSING');
110
+ err.code = error?.code || 'TOKEN_EXCHANGE_FAILED';
111
+ err.messageZh =
112
+ `X-Auth-Token 换取临时 AK/SK 失败(${err.code}):` +
113
+ `${error?.message || '网络异常或 token 无效'},请检查网络连通性与 token 有效性。`;
114
+ throw err;
115
+ }
116
+ }
117
+ throw makeError('HDKIT_CRED_MISSING');
118
+ }
119
+
85
120
  async function apiGet(path, query, ak, sk, securitytoken) {
86
121
  query = query || {};
87
122
  const qs = sortedQs(query);
@@ -16,7 +16,7 @@ import { join, dirname, basename } from 'node:path';
16
16
  import { tmpdir } from 'node:os';
17
17
  import { fileURLToPath, pathToFileURL } from 'node:url';
18
18
 
19
- import { createConnection, getCredentials } from './hwlink-api.mjs';
19
+ import { createConnection, resolveBackendCredentials } from './hwlink-api.mjs';
20
20
  import { getWebSocketImpl } from '../proxy/proxy-agent.mjs';
21
21
  import { trackSandboxConnect, trackSandboxDisconnect } from '../telemetry/telemetry.mjs';
22
22
  import { buildExposeLifetimeNotice } from './sandbox-pool.mjs';
@@ -108,7 +108,7 @@ async function getSession(workspaceId, username, timeoutMs) {
108
108
  const key = `${workspaceId}:${username}`;
109
109
  if (sessions.has(key)) return sessions.get(key);
110
110
 
111
- const { ak, sk, securitytoken } = getCredentials();
111
+ const { ak, sk, securitytoken } = await resolveBackendCredentials();
112
112
  const { wsUrl, source } = await createConnection(workspaceId, ak, sk, securitytoken);
113
113
 
114
114
  const WebSocketImpl = await getWebSocketImpl(wsUrl);
@@ -127,7 +127,7 @@ async function getSession(workspaceId, username, timeoutMs) {
127
127
  }
128
128
 
129
129
  async function createTunnelSession(workspaceId, username, timeoutMs = 30000) {
130
- const { ak, sk, securitytoken } = getCredentials();
130
+ const { ak, sk, securitytoken } = await resolveBackendCredentials();
131
131
  const { wsUrl, source } = await createConnection(workspaceId, ak, sk, securitytoken);
132
132
  const WebSocketImpl = await getWebSocketImpl(wsUrl);
133
133
 
@@ -166,7 +166,7 @@ async function createTunnelSession(workspaceId, username, timeoutMs = 30000) {
166
166
  }
167
167
 
168
168
  export async function execOneShot(workspaceId, command, username, timeoutMs) {
169
- const { ak, sk, securitytoken } = getCredentials();
169
+ const { ak, sk, securitytoken } = await resolveBackendCredentials();
170
170
  const { wsUrl, source } = await createConnection(workspaceId, ak, sk, securitytoken);
171
171
 
172
172
  const WebSocketImpl = await getWebSocketImpl(wsUrl);