connect-api-cli 1.1.6 → 1.1.9

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.
package/dist/cli.js CHANGED
@@ -41,7 +41,7 @@ function printResult(result) {
41
41
  // src/cli/index.ts
42
42
  var import_commander = require("commander");
43
43
  var fs9 = __toESM(require("fs"));
44
- var import_path7 = __toESM(require("path"));
44
+ var import_path8 = __toESM(require("path"));
45
45
 
46
46
  // src/core/private-file.ts
47
47
  var import_fs = __toESM(require("fs"));
@@ -118,12 +118,11 @@ function loadServiceAccountCredentials(filePath) {
118
118
  client_cert_uri: creds.client_cert_uri
119
119
  };
120
120
  }
121
- function getConfig() {
121
+ function getConfig(authMode = process.env.AGC_AUTH_MODE ?? "deveco") {
122
122
  const clientId = process.env.AGC_CLIENT_ID;
123
123
  const clientSecret = process.env.AGC_CLIENT_SECRET;
124
- const authMode = process.env.AGC_AUTH_MODE ?? "client_credentials";
125
124
  if (authMode === "client_credentials" && (!clientId || !clientSecret)) {
126
- throw new Error("Missing AGC credentials. Please set AGC_CLIENT_ID and AGC_CLIENT_SECRET environment variables.");
125
+ throw new Error("Missing credentials. Please set AGC_CLIENT_ID and AGC_CLIENT_SECRET environment variables.");
127
126
  }
128
127
  if (authMode === "service_account" && !process.env.AGC_SA_CREDENTIALS) {
129
128
  throw new Error(
@@ -146,7 +145,22 @@ function getConfig() {
146
145
  credentials: loadServiceAccountCredentials(credentialsPath)
147
146
  };
148
147
  }
149
- const resolvedClientId = authMode === "oauth" ? oauth.clientId : authMode === "service_account" ? serviceAccount.credentials.key_id : clientId || "";
148
+ let deveco;
149
+ if (authMode === "deveco") {
150
+ const sourceEnv = process.env.AGC_DEVECO_SOURCE;
151
+ const devecoSources = ["cli", "deveco", "deveco-cli", "deveco-code"];
152
+ if (sourceEnv && !devecoSources.includes(sourceEnv)) {
153
+ throw new Error(
154
+ `Invalid AGC_DEVECO_SOURCE: ${sourceEnv} (expected ${devecoSources.join(" / ")})`
155
+ );
156
+ }
157
+ const authDirEnv = process.env.AGC_DEVECO_AUTH_DIR?.trim();
158
+ deveco = {
159
+ source: sourceEnv || "cli",
160
+ authDir: authDirEnv ? import_path.default.resolve(authDirEnv) : void 0
161
+ };
162
+ }
163
+ const resolvedClientId = authMode === "oauth" ? oauth.clientId : authMode === "service_account" ? serviceAccount.credentials.key_id : authMode === "deveco" ? deveco.authDir ? `deveco:${deveco.source}:${deveco.authDir}` : `deveco:${deveco.source}` : clientId || "";
150
164
  return {
151
165
  clientId: resolvedClientId,
152
166
  clientSecret: clientSecret || "",
@@ -154,19 +168,22 @@ function getConfig() {
154
168
  authMode,
155
169
  oauth,
156
170
  teamId: process.env.AGC_TEAM_ID || void 0,
157
- serviceAccount
171
+ serviceAccount,
172
+ deveco
158
173
  };
159
174
  }
160
175
 
161
176
  // src/services/auth.ts
162
177
  var SA_AUD = "https://oauth-login.cloud.huawei.com/oauth2/v3/token";
163
178
  var SA_JWT_TTL_SEC = 3600;
179
+ var DEVECO_CHECK_URL = process.env.AGC_DEVECO_CHECK_URL || "https://cn.devecostudio.huawei.com/authrouter/auth/api/jwToken/check";
180
+ var DEVECO_USER_AGENT = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36";
164
181
  var AuthService = class {
165
182
  /**
166
183
  * 获取访问API的Token(service to service,client_credentials 模式)
167
184
  */
168
185
  static async getToken() {
169
- const config2 = getConfig();
186
+ const config2 = getConfig("client_credentials");
170
187
  const url = `https://${config2.domain}/api/oauth2/v1/token`;
171
188
  const payload = {
172
189
  grant_type: "client_credentials",
@@ -221,7 +238,7 @@ var AuthService = class {
221
238
  * 拼装 OAuth 授权 URL(含随机 state 防 CSRF)
222
239
  */
223
240
  static buildAuthUrl(state) {
224
- const cfg = getConfig();
241
+ const cfg = getConfig("oauth");
225
242
  const url = new URL(cfg.oauth.authUrl);
226
243
  url.searchParams.set("client_id", cfg.oauth.clientId);
227
244
  url.searchParams.set("redirect_uri", cfg.oauth.redirectUri);
@@ -235,7 +252,7 @@ var AuthService = class {
235
252
  * 用授权码换取 OAuth token(与插件 /access-token/generate 对齐)
236
253
  */
237
254
  static async getOAuthToken(code, redirectUri) {
238
- const cfg = getConfig();
255
+ const cfg = getConfig("oauth");
239
256
  const controller = new AbortController();
240
257
  const timeoutId = setTimeout(() => controller.abort(), 3e4);
241
258
  try {
@@ -262,7 +279,7 @@ var AuthService = class {
262
279
  * 刷新接口只返回新的 accessToken,refreshToken 沿用旧值。
263
280
  */
264
281
  static async refreshOAuthToken(refreshToken) {
265
- const cfg = getConfig();
282
+ const cfg = getConfig("oauth");
266
283
  const controller = new AbortController();
267
284
  const timeoutId = setTimeout(() => controller.abort(), 3e4);
268
285
  try {
@@ -284,6 +301,39 @@ var AuthService = class {
284
301
  clearTimeout(timeoutId);
285
302
  }
286
303
  }
304
+ /**
305
+ * 用本地解密的 deveco JWT 调 jwToken/check 换取 access token
306
+ * (复刻 DevEco loginService.getUserInfo() / tokenChecker.checkJwtToken())。
307
+ * refresh=true 时服务端会刷新 accessToken;JWT 失效时抛错并提示重新登录 DevEco 工具。
308
+ */
309
+ static async checkDevecoJwtToken(jwtToken, refresh) {
310
+ const controller = new AbortController();
311
+ const timeoutId = setTimeout(() => controller.abort(), 3e4);
312
+ try {
313
+ const res = await import_axios.default.get(DEVECO_CHECK_URL, {
314
+ maxRedirects: 0,
315
+ headers: {
316
+ refresh: String(refresh),
317
+ jwtToken,
318
+ "User-Agent": DEVECO_USER_AGENT,
319
+ "accept-language": "zh-CN"
320
+ },
321
+ signal: controller.signal
322
+ });
323
+ const userInfo = res.data.userInfo;
324
+ if (!res.data.status || !userInfo?.accessToken) {
325
+ throw new Error("\u672C\u5730 DevEco \u767B\u5F55\u6001\u5DF2\u5931\u6548\uFF08jwToken/check \u5224\u5B9A\u65E0\u6548\uFF09\uFF0C\u8BF7\u5728 DevEco \u5DE5\u5177\u4E2D\u91CD\u65B0\u767B\u5F55");
326
+ }
327
+ return userInfo.accessToken;
328
+ } catch (err) {
329
+ if (err instanceof Error && err.name === "AbortError") {
330
+ throw new Error("\u8BF7\u6C42 jwToken/check \u8D85\u65F6\uFF0C\u8BF7\u68C0\u67E5\u7F51\u7EDC\u8FDE\u63A5");
331
+ }
332
+ throw err;
333
+ } finally {
334
+ clearTimeout(timeoutId);
335
+ }
336
+ }
287
337
  };
288
338
  function base64UrlEncode(buf) {
289
339
  return buf.toString("base64").replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_");
@@ -373,25 +423,197 @@ function clearOAuthTeamIdCache() {
373
423
  cachedTeamId = void 0;
374
424
  }
375
425
 
426
+ // src/core/deveco-token.ts
427
+ var import_crypto = require("crypto");
428
+ var import_fs4 = require("fs");
429
+ var import_os2 = require("os");
430
+ var import_path3 = require("path");
431
+ var ALGORITHM = "aes-256-gcm";
432
+ var KEY_LENGTH = 32;
433
+ var KEK_VERSIONS = ["kek-v1", "kek-v2", "kek-v3"];
434
+ var CLI_SOURCE_ALIASES = ["cli", "deveco", "deveco-cli"];
435
+ var SOURCE_APP_NAMES = {
436
+ "deveco-code": "deveco"
437
+ };
438
+ function decryptAesGcm(ciphertext, key, iv, authTag) {
439
+ const decipher = (0, import_crypto.createDecipheriv)(ALGORITHM, key, iv);
440
+ decipher.setAuthTag(authTag);
441
+ return Buffer.concat([decipher.update(ciphertext), decipher.final()]);
442
+ }
443
+ function readJson(filePath) {
444
+ return JSON.parse((0, import_fs4.readFileSync)(filePath, "utf8"));
445
+ }
446
+ function requireFile(filePath, label) {
447
+ try {
448
+ return (0, import_fs4.readFileSync)(filePath);
449
+ } catch (err) {
450
+ const code = err.code;
451
+ if (code === "ENOENT") {
452
+ throw new Error(`\u627E\u4E0D\u5230 ${label}: ${filePath}`);
453
+ }
454
+ if (code === "EACCES" || code === "EPERM") {
455
+ throw new Error(`\u65E0\u6743\u9650\u8BFB\u53D6 ${label}: ${filePath}`);
456
+ }
457
+ throw err;
458
+ }
459
+ }
460
+ function loadKek(kekId, keysDir) {
461
+ if (!KEK_VERSIONS.includes(kekId)) {
462
+ throw new Error(`\u975E\u6CD5 kekId: ${kekId}\uFF08\u671F\u671B ${KEK_VERSIONS.join("/")}\uFF09`);
463
+ }
464
+ const rootKeyPath = (0, import_path3.resolve)((0, import_path3.join)(keysDir, `${kekId}.bin`));
465
+ const keysDirBase = (0, import_path3.resolve)(keysDir);
466
+ if (!rootKeyPath.startsWith(keysDirBase)) {
467
+ throw new Error("kekId \u89E3\u6790\u7ED3\u679C\u8D85\u51FA keys \u76EE\u5F55\u8303\u56F4");
468
+ }
469
+ const kek = requireFile(rootKeyPath, "KEK \u6839\u5BC6\u94A5");
470
+ if (kek.length !== KEY_LENGTH) {
471
+ throw new Error(`KEK \u957F\u5EA6\u5F02\u5E38: ${kek.length} \u5B57\u8282\uFF08\u671F\u671B ${KEY_LENGTH}\uFF09`);
472
+ }
473
+ return kek;
474
+ }
475
+ function decryptToken(tokenDir, keysDir) {
476
+ const blob = readJson((0, import_path3.join)(tokenDir, "token.enc"));
477
+ if (blob.algorithm !== ALGORITHM) {
478
+ throw new Error(`\u672A\u77E5\u7B97\u6CD5: ${blob.algorithm}`);
479
+ }
480
+ if (!blob.ciphertext || !blob.iv || !blob.authTag) {
481
+ throw new Error(`token.enc \u683C\u5F0F\u5F02\u5E38\uFF08\u7F3A\u5C11 ciphertext/iv/authTag\uFF09: ${(0, import_path3.join)(tokenDir, "token.enc")}`);
482
+ }
483
+ const wrapped = readJson((0, import_path3.join)(tokenDir, "token.dek"));
484
+ if (!wrapped.encryptedDek || !wrapped.iv || !wrapped.authTag) {
485
+ throw new Error(`token.dek \u683C\u5F0F\u5F02\u5E38\uFF08\u7F3A\u5C11 encryptedDek/iv/authTag\uFF09: ${(0, import_path3.join)(tokenDir, "token.dek")}`);
486
+ }
487
+ const kek = loadKek(wrapped.kekId, keysDir);
488
+ const dek = decryptAesGcm(
489
+ Buffer.from(wrapped.encryptedDek, "base64"),
490
+ kek,
491
+ Buffer.from(wrapped.iv, "base64"),
492
+ Buffer.from(wrapped.authTag, "base64")
493
+ );
494
+ if (dek.length !== KEY_LENGTH) {
495
+ throw new Error(`DEK \u957F\u5EA6\u5F02\u5E38: ${dek.length} \u5B57\u8282\uFF08\u671F\u671B ${KEY_LENGTH}\uFF09`);
496
+ }
497
+ return decryptAesGcm(
498
+ Buffer.from(blob.ciphertext, "base64"),
499
+ dek,
500
+ Buffer.from(blob.iv, "base64"),
501
+ Buffer.from(blob.authTag, "base64")
502
+ ).toString("utf8");
503
+ }
504
+ function extractJwt(plaintext) {
505
+ let jwt = plaintext;
506
+ try {
507
+ const parsed = JSON.parse(plaintext);
508
+ if (parsed && typeof parsed.access_token === "string") {
509
+ jwt = parsed.access_token;
510
+ }
511
+ } catch {
512
+ }
513
+ const parts = jwt.split(".");
514
+ if (parts.length !== 3) {
515
+ throw new Error("\u89E3\u5BC6\u7ED3\u679C\u4E0D\u662F JWT \u683C\u5F0F\uFF0C\u672C\u5730\u767B\u5F55\u6001\u53EF\u80FD\u5DF2\u635F\u574F\uFF0C\u8BF7\u5728 DevEco \u5DE5\u5177\u4E2D\u91CD\u65B0\u767B\u5F55");
516
+ }
517
+ try {
518
+ const payload = JSON.parse(Buffer.from(parts[1], "base64url").toString("utf8"));
519
+ if (typeof payload.exp === "number") {
520
+ return { jwt, expMs: payload.exp * 1e3 };
521
+ }
522
+ } catch {
523
+ }
524
+ return { jwt };
525
+ }
526
+ function configHome() {
527
+ return process.env.XDG_CONFIG_HOME || (0, import_path3.join)((0, import_os2.homedir)(), ".config");
528
+ }
529
+ function candidatesFor(source) {
530
+ const home = (0, import_os2.homedir)();
531
+ if (CLI_SOURCE_ALIASES.includes(source)) {
532
+ if (process.env.DEVECO_CLI_AUTH_SOURCE?.trim() === "deveco-code") {
533
+ return candidatesFor("deveco-code").map((c) => ({
534
+ ...c,
535
+ source,
536
+ via: "DEVECO_CLI_AUTH_SOURCE=deveco-code"
537
+ }));
538
+ }
539
+ return [
540
+ {
541
+ source,
542
+ tokenDir: process.env.DEVECO_CLI_DATA_DIR || (0, import_path3.join)(home, ".config", "deveco-cli"),
543
+ keysDir: (0, import_path3.join)(home, ".local", "share", "deveco-cli", "keys"),
544
+ via: process.env.DEVECO_CLI_DATA_DIR ? "DEVECO_CLI_DATA_DIR" : "\u5E73\u53F0\u9ED8\u8BA4\u8DEF\u5F84"
545
+ }
546
+ ];
547
+ }
548
+ const appName = SOURCE_APP_NAMES[source];
549
+ const viaEnv = process.env.DEVECO_CODE_AUTH_DIR?.trim();
550
+ if (source === "deveco-code" && viaEnv) {
551
+ const tokenDir = (0, import_path3.resolve)(viaEnv);
552
+ return [{ source, tokenDir, keysDir: (0, import_path3.join)(tokenDir, "keys"), via: "DEVECO_CODE_AUTH_DIR" }];
553
+ }
554
+ let dirs;
555
+ if (process.platform === "win32") {
556
+ const appData = process.env.APPDATA || (0, import_path3.join)(home, "AppData", "Roaming");
557
+ dirs = [(0, import_path3.join)(appData, appName), (0, import_path3.join)(home, ".config", appName)];
558
+ } else if (process.platform === "darwin") {
559
+ dirs = [
560
+ (0, import_path3.join)(configHome(), appName),
561
+ (0, import_path3.join)(home, "Library", "Application Support", appName)
562
+ ];
563
+ } else {
564
+ dirs = [(0, import_path3.join)(configHome(), appName)];
565
+ }
566
+ return dirs.map((tokenDir) => ({
567
+ source,
568
+ tokenDir,
569
+ keysDir: (0, import_path3.join)(tokenDir, "keys"),
570
+ via: "\u5E73\u53F0\u9ED8\u8BA4\u8DEF\u5F84"
571
+ }));
572
+ }
573
+ function resolveLocation(source) {
574
+ const candidates = candidatesFor(source);
575
+ const hit = candidates.find((c) => (0, import_fs4.existsSync)((0, import_path3.join)(c.tokenDir, "token.enc")));
576
+ if (hit) {
577
+ return hit;
578
+ }
579
+ const tried = candidates.map((c) => ` - ${c.tokenDir}`).join("\n");
580
+ throw new Error(
581
+ `[${source}] \u672A\u627E\u5230\u672C\u5730\u767B\u5F55\u6001 token.enc\uFF0C\u8BF7\u5148\u7528\u5BF9\u5E94 DevEco \u5DE5\u5177\u767B\u5F55\u3002\u5DF2\u63A2\u6D4B\u4EE5\u4E0B\u4F4D\u7F6E\uFF1A
582
+ ${tried}`
583
+ );
584
+ }
585
+ function loadDevecoLocalToken(source, authDir) {
586
+ const location = authDir ? { source: "dir", tokenDir: authDir, keysDir: (0, import_path3.join)(authDir, "keys"), via: "AGC_DEVECO_AUTH_DIR" } : resolveLocation(source);
587
+ const plaintext = decryptToken(location.tokenDir, location.keysDir);
588
+ const { jwt, expMs } = extractJwt(plaintext);
589
+ return { jwt, expMs, location };
590
+ }
591
+
376
592
  // src/core/auth-mgr.ts
377
593
  var crypto2 = __toESM(require("crypto"));
378
594
  var http = __toESM(require("http"));
379
595
  var import_child_process = require("child_process");
380
- var import_fs4 = __toESM(require("fs"));
381
- var import_path3 = __toESM(require("path"));
382
- var import_os2 = __toESM(require("os"));
596
+ var import_fs5 = __toESM(require("fs"));
597
+ var import_path4 = __toESM(require("path"));
598
+ var import_os3 = __toESM(require("os"));
599
+ var DEVECO_CACHE_TTL_MS = 30 * 60 * 1e3;
383
600
  var AuthManager = class {
384
- static cacheFile = import_path3.default.join(import_os2.default.homedir(), ".connect-api-cli-token.json");
601
+ static cacheFile = import_path4.default.join(import_os3.default.homedir(), ".connect-api-cli-token.json");
602
+ static pendingOAuthLogin;
385
603
  /**
386
604
  * 获取当前生效的 access token,并具备自动刷新能力:
387
605
  * - OAuth 模式:token 过期时优先用 refreshToken 自动刷新,无需重新登录
388
606
  * - client_credentials / service_account:过期后重新换取 / 重新签 JWT
607
+ * - deveco:过期后重新解密本地登录态并 refresh 换取
608
+ *
609
+ * force 跳过缓存(供 DevEco 和自动模式的 401 重试使用)。
389
610
  */
390
- static async getAccessToken() {
391
- const cfg = getConfig();
392
- const cache = this.readCache();
393
- const sameCredential = cache && cache.clientId === cfg.clientId && cache.domain === cfg.domain && cache.authMode === cfg.authMode;
394
- if (sameCredential && cache.expiresAt > Date.now() + 5 * 60 * 1e3) {
611
+ static async getAccessToken(force = false) {
612
+ const { config: config2, cache } = this.getStatus();
613
+ return this.getToken(config2, cache, force);
614
+ }
615
+ static async getToken(cfg, cache, force = false) {
616
+ if (!force && cache && cache.expiresAt > Date.now() + 5 * 60 * 1e3) {
395
617
  return cache.accessToken;
396
618
  }
397
619
  if (cfg.authMode === "oauth" && cache?.refreshToken) {
@@ -413,18 +635,31 @@ var AuthManager = class {
413
635
  this.clearCache();
414
636
  }
415
637
  }
416
- return this.acquire();
638
+ return this.acquire(cfg);
417
639
  }
418
640
  /** 登录入口:按当前认证模式获取并缓存 token */
419
641
  static async login() {
420
642
  clearOAuthTeamIdCache();
421
- return this.acquire();
643
+ return this.acquire(getConfig());
422
644
  }
423
- /** 按当前认证模式获取 token(client_credentials / service_account / oauth) */
424
- static async acquire() {
425
- const cfg = getConfig();
645
+ /** 按当前认证模式获取 token(client_credentials / service_account / oauth / deveco) */
646
+ static async acquire(cfg) {
426
647
  if (cfg.authMode === "oauth") {
427
- return this.loginOAuth();
648
+ this.pendingOAuthLogin ??= this.loginOAuth(cfg).finally(() => {
649
+ this.pendingOAuthLogin = void 0;
650
+ });
651
+ return this.pendingOAuthLogin;
652
+ }
653
+ if (cfg.authMode === "deveco") {
654
+ try {
655
+ return await this.acquireDevecoToken(cfg);
656
+ } catch (err) {
657
+ if (process.env.AGC_AUTH_MODE !== void 0) throw err;
658
+ const oauthConfig = getConfig("oauth");
659
+ const cache = this.matchingCache(oauthConfig, this.readCache());
660
+ console.error("\u65E0\u6CD5\u4F7F\u7528\u672C\u5730 DevEco \u767B\u5F55\u6001\uFF0C\u6539\u7528\u534E\u4E3A\u8D26\u53F7 OAuth\u3002");
661
+ return this.getToken(oauthConfig, cache);
662
+ }
428
663
  }
429
664
  if (cfg.authMode === "service_account") {
430
665
  if (!cfg.serviceAccount) {
@@ -455,9 +690,8 @@ var AuthManager = class {
455
690
  throw new Error(`Failed to get token: ${JSON.stringify(res.ret)}`);
456
691
  }
457
692
  /** OAuth 授权码登录:启动本地回调服务器 + 打开浏览器 */
458
- static loginOAuth() {
459
- return new Promise((resolve, reject) => {
460
- const cfg = getConfig();
693
+ static loginOAuth(cfg) {
694
+ return new Promise((resolve2, reject) => {
461
695
  const redirectUri = cfg.oauth.redirectUri;
462
696
  const port = Number(new URL(redirectUri).port || 80);
463
697
  const state = crypto2.randomBytes(32).toString("hex");
@@ -473,6 +707,7 @@ var AuthManager = class {
473
707
  }
474
708
  const token = await AuthService.getOAuthToken(code, redirectUri);
475
709
  const expiresAt = Date.now() + token.expireTime * 1e3;
710
+ clearOAuthTeamIdCache();
476
711
  this.writeCache({
477
712
  accessToken: token.accessToken,
478
713
  expiresAt,
@@ -484,7 +719,7 @@ var AuthManager = class {
484
719
  res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
485
720
  res.end('<!DOCTYPE html><html><body style="font-family:sans-serif;padding:40px;text-align:center"><h2>\u767B\u5F55\u6210\u529F\uFF0C\u53EF\u5173\u95ED\u6B64\u7A97\u53E3</h2></body></html>');
486
721
  server.close();
487
- resolve(token.accessToken);
722
+ resolve2(token.accessToken);
488
723
  } catch (err) {
489
724
  server.close();
490
725
  reject(err instanceof Error ? err : new Error(String(err)));
@@ -496,19 +731,48 @@ var AuthManager = class {
496
731
  });
497
732
  server.listen(port, () => {
498
733
  const authUrl = AuthService.buildAuthUrl(state);
499
- console.log("\u8BF7\u5728\u6D4F\u89C8\u5668\u4E2D\u5B8C\u6210\u534E\u4E3A\u8D26\u53F7\u6388\u6743...");
500
- console.log(`\u82E5\u6D4F\u89C8\u5668\u672A\u81EA\u52A8\u6253\u5F00\uFF0C\u8BF7\u8BBF\u95EE: ${authUrl}`);
734
+ console.error("\u8BF7\u5728\u6D4F\u89C8\u5668\u4E2D\u5B8C\u6210\u534E\u4E3A\u8D26\u53F7\u6388\u6743...");
735
+ console.error(`\u82E5\u6D4F\u89C8\u5668\u672A\u81EA\u52A8\u6253\u5F00\uFF0C\u8BF7\u8BBF\u95EE: ${authUrl}`);
501
736
  openBrowser(authUrl);
502
737
  });
503
738
  });
504
739
  }
505
- /** 查询缓存状态(供 status 命令显示) */
740
+ /**
741
+ * deveco 模式:解密本地 DevEco 工具链登录态(只读),
742
+ * 用 JWT 调 jwToken/check(refresh=true)换取 access token 并缓存。
743
+ * 服务端不返回有效期:缓存取「本地 JWT 剩余寿命」与「30 分钟上限」的较小值。
744
+ */
745
+ static async acquireDevecoToken(cfg) {
746
+ const deveco = cfg.deveco;
747
+ const local = loadDevecoLocalToken(deveco.source, deveco.authDir);
748
+ const accessToken = await AuthService.checkDevecoJwtToken(local.jwt, true);
749
+ const jwtLimit = local.expMs !== void 0 ? local.expMs - 5 * 60 * 1e3 : Infinity;
750
+ this.writeCache({
751
+ accessToken,
752
+ expiresAt: Math.min(Date.now() + DEVECO_CACHE_TTL_MS, jwtLimit),
753
+ clientId: cfg.clientId,
754
+ domain: cfg.domain,
755
+ authMode: cfg.authMode
756
+ });
757
+ return accessToken;
758
+ }
759
+ /** 默认模式回退到 OAuth 后,后续命令继续使用该 OAuth 会话。 */
506
760
  static getStatus() {
507
- return this.readCache();
761
+ const config2 = getConfig();
762
+ const cache = this.readCache();
763
+ if (process.env.AGC_AUTH_MODE === void 0 && cache?.authMode === "oauth") {
764
+ const oauthConfig = getConfig("oauth");
765
+ const oauthCache = this.matchingCache(oauthConfig, cache);
766
+ if (oauthCache) return { config: oauthConfig, cache: oauthCache };
767
+ }
768
+ return { config: config2, cache: this.matchingCache(config2, cache) };
769
+ }
770
+ static matchingCache(cfg, cache) {
771
+ return cache?.authMode === cfg.authMode && cache.clientId === cfg.clientId && cache.domain === cfg.domain ? cache : null;
508
772
  }
509
773
  static readCache() {
510
774
  try {
511
- if (import_fs4.default.existsSync(this.cacheFile)) {
775
+ if (import_fs5.default.existsSync(this.cacheFile)) {
512
776
  const data = readPrivateFile(this.cacheFile);
513
777
  return JSON.parse(data);
514
778
  }
@@ -528,8 +792,8 @@ var AuthManager = class {
528
792
  static clearCache() {
529
793
  clearOAuthTeamIdCache();
530
794
  try {
531
- if (import_fs4.default.existsSync(this.cacheFile)) {
532
- import_fs4.default.unlinkSync(this.cacheFile);
795
+ if (import_fs5.default.existsSync(this.cacheFile)) {
796
+ import_fs5.default.unlinkSync(this.cacheFile);
533
797
  return true;
534
798
  }
535
799
  return false;
@@ -552,8 +816,8 @@ function openBrowser(url) {
552
816
  var import_axios3 = __toESM(require("axios"));
553
817
 
554
818
  // src/core/request-source.ts
555
- var import_fs5 = __toESM(require("fs"));
556
- var import_path4 = __toESM(require("path"));
819
+ var import_fs6 = __toESM(require("fs"));
820
+ var import_path5 = __toESM(require("path"));
557
821
  var REQUEST_SOURCE_HEADER = "Request-Source";
558
822
  var SOURCE_TOOL_NAME_HEADER = "Source-Tool-Name";
559
823
  var SKILL_CHANNEL = "skill";
@@ -693,15 +957,15 @@ function getRequestSource() {
693
957
  return agent ? `${agent}-skill` : SKILL_CHANNEL;
694
958
  }
695
959
  function readVersion() {
696
- const fromBuild = injected(true ? "1.1.6" : void 0);
960
+ const fromBuild = injected(true ? "1.1.9" : void 0);
697
961
  if (fromBuild) return fromBuild;
698
962
  const candidates = [
699
- import_path4.default.join(__dirname, "..", "..", "package.json"),
700
- import_path4.default.join(__dirname, "..", "package.json")
963
+ import_path5.default.join(__dirname, "..", "..", "package.json"),
964
+ import_path5.default.join(__dirname, "..", "package.json")
701
965
  ];
702
966
  for (const pkgPath of candidates) {
703
967
  try {
704
- const pkg = JSON.parse(import_fs5.default.readFileSync(pkgPath, "utf8"));
968
+ const pkg = JSON.parse(import_fs6.default.readFileSync(pkgPath, "utf8"));
705
969
  if (pkg.version) return pkg.version;
706
970
  } catch {
707
971
  }
@@ -725,7 +989,7 @@ function applySourceHeaders(headers) {
725
989
  }
726
990
 
727
991
  // src/core/http.ts
728
- var agcClient = import_axios3.default.create({ maxRedirects: 0 });
992
+ var connectApiClient = import_axios3.default.create({ maxRedirects: 0 });
729
993
  function setHeader(headers, name, value) {
730
994
  if (typeof headers?.set === "function") {
731
995
  headers.set(name, value);
@@ -747,7 +1011,7 @@ function getHeader(headers, name) {
747
1011
  return headers?.[name] ?? headers?.[name.toLowerCase()];
748
1012
  }
749
1013
  function applyAuthHeaders(headers, token, cfg, force = false) {
750
- if (cfg.authMode === "oauth") {
1014
+ if (cfg.authMode === "oauth" || cfg.authMode === "deveco") {
751
1015
  deleteHeader(headers, "Authorization");
752
1016
  deleteHeader(headers, "client_id");
753
1017
  setHeader(headers, "oauth2Token", token);
@@ -761,7 +1025,7 @@ function applyAuthHeaders(headers, token, cfg, force = false) {
761
1025
  setHeader(headers, "client_id", cfg.clientId);
762
1026
  }
763
1027
  }
764
- agcClient.interceptors.request.use(async (config2) => {
1028
+ connectApiClient.interceptors.request.use(async (config2) => {
765
1029
  const cfg = getConfig();
766
1030
  if (!config2.baseURL) {
767
1031
  config2.baseURL = `https://${cfg.domain}`;
@@ -772,10 +1036,11 @@ agcClient.interceptors.request.use(async (config2) => {
772
1036
  }
773
1037
  applySourceHeaders(config2.headers);
774
1038
  applyAuthHeaders(config2.headers, token, cfg);
775
- if (cfg.authMode === "oauth" && !getHeader(config2.headers, "teamId")) {
1039
+ if ((cfg.authMode === "oauth" || cfg.authMode === "deveco") && !getHeader(config2.headers, "teamId")) {
776
1040
  const teamId = await resolveOAuthTeamId(cfg, token);
777
1041
  if (teamId) {
778
1042
  setHeader(config2.headers, "teamId", teamId);
1043
+ config2._autoTeamId = true;
779
1044
  }
780
1045
  }
781
1046
  if (config2.data !== void 0 && !getHeader(config2.headers, "Content-Type")) {
@@ -785,7 +1050,7 @@ agcClient.interceptors.request.use(async (config2) => {
785
1050
  }, (error) => {
786
1051
  return Promise.reject(error);
787
1052
  });
788
- agcClient.interceptors.response.use(
1053
+ connectApiClient.interceptors.response.use(
789
1054
  (res) => res,
790
1055
  async (err) => {
791
1056
  const original = err.config;
@@ -794,12 +1059,13 @@ agcClient.interceptors.response.use(
794
1059
  original._retry = true;
795
1060
  try {
796
1061
  const cfg = getConfig();
797
- const newToken = await AuthManager.getAccessToken();
1062
+ const newToken = await AuthManager.getAccessToken(cfg.authMode === "deveco");
798
1063
  if (!original.headers) {
799
1064
  original.headers = {};
800
1065
  }
801
1066
  applyAuthHeaders(original.headers, newToken, cfg, true);
802
- return agcClient(original);
1067
+ if (original._autoTeamId) deleteHeader(original.headers, "teamId");
1068
+ return connectApiClient(original);
803
1069
  } catch (e) {
804
1070
  return Promise.reject(err);
805
1071
  }
@@ -828,7 +1094,7 @@ function withOptionalParams(base) {
828
1094
  var PublishService = class {
829
1095
  /** 查询应用包名对应的 appid */
830
1096
  static async getAppIdList(packageName, packageTypes) {
831
- const response = await agcClient.get("/api/publish/v2/appid-list", {
1097
+ const response = await connectApiClient.get("/api/publish/v2/appid-list", {
832
1098
  params: withOptionalParams({ packageName, packageTypes })
833
1099
  });
834
1100
  return response.data;
@@ -843,14 +1109,14 @@ var PublishService = class {
843
1109
  if (req.installationFree === 0 && packageName) {
844
1110
  body.packageName = packageName;
845
1111
  }
846
- const response = projectId ? await agcClient.post("/api/publish/v3/app", body, {
1112
+ const response = projectId ? await connectApiClient.post("/api/publish/v3/app", body, {
847
1113
  params: { projectId }
848
- }) : await agcClient.post("/api/publish/v3/app", body);
1114
+ }) : await connectApiClient.post("/api/publish/v3/app", body);
849
1115
  return response.data;
850
1116
  }
851
1117
  /** 查询团队账号下的成员角色列表 */
852
1118
  static async getMembersRoleList(req) {
853
- const response = await agcClient.get(
1119
+ const response = await connectApiClient.get(
854
1120
  "/api/publish/v3/members-role-list",
855
1121
  {
856
1122
  params: {
@@ -865,7 +1131,7 @@ var PublishService = class {
865
1131
  /** 查询应用信息 */
866
1132
  static async getAppInfo(appIdOrReq, lang) {
867
1133
  const req = typeof appIdOrReq === "string" ? { appId: appIdOrReq, lang } : appIdOrReq;
868
- const response = await agcClient.get("/api/publish/v3/app-info", {
1134
+ const response = await connectApiClient.get("/api/publish/v3/app-info", {
869
1135
  params: withOptionalParams({
870
1136
  appId: req.appId,
871
1137
  lang: req.lang,
@@ -878,7 +1144,7 @@ var PublishService = class {
878
1144
  /** 更新应用基本信息 */
879
1145
  static async updateAppInfo(req) {
880
1146
  const { appId, releaseType, releasePhase, ...body } = req;
881
- const response = await agcClient.put(
1147
+ const response = await connectApiClient.put(
882
1148
  "/api/publish/v3/app-info",
883
1149
  body,
884
1150
  {
@@ -890,7 +1156,7 @@ var PublishService = class {
890
1156
  /** 更新应用语言信息 */
891
1157
  static async updateLanguageInfo(req) {
892
1158
  const { appId, releaseType, releasePhase, ...body } = req;
893
- const response = await agcClient.put(
1159
+ const response = await connectApiClient.put(
894
1160
  "/api/publish/v3/app-language-info",
895
1161
  body,
896
1162
  {
@@ -901,7 +1167,7 @@ var PublishService = class {
901
1167
  }
902
1168
  /** 删除应用语言信息 */
903
1169
  static async deleteLanguageInfo(req) {
904
- const response = await agcClient.delete(
1170
+ const response = await connectApiClient.delete(
905
1171
  "/api/publish/v2/app-language-info",
906
1172
  {
907
1173
  params: withOptionalParams({
@@ -916,7 +1182,7 @@ var PublishService = class {
916
1182
  /** 更新应用文件信息(图标/截图/视频等) */
917
1183
  static async updateAppFileInfo(req) {
918
1184
  const { appId, releaseType, releasePhase, ...body } = req;
919
- const response = await agcClient.put(
1185
+ const response = await connectApiClient.put(
920
1186
  "/api/publish/v3/app-file-info",
921
1187
  body,
922
1188
  {
@@ -928,7 +1194,7 @@ var PublishService = class {
928
1194
  /** 更新应用软件包信息(OBS 上传后上报,HarmonyOS 开发者中心才会出现记录) */
929
1195
  static async updateAppPackageInfo(req) {
930
1196
  const { appId, releaseType, releasePhase, fileName, objectId } = req;
931
- const response = await agcClient.put(
1197
+ const response = await connectApiClient.put(
932
1198
  "/api/publish/v3/app-package-info",
933
1199
  { fileName, objectId },
934
1200
  {
@@ -940,7 +1206,7 @@ var PublishService = class {
940
1206
  /** 更新版本上架时间 */
941
1207
  static async updateReleaseTime(req) {
942
1208
  const { appId, ...body } = req;
943
- const response = await agcClient.put(
1209
+ const response = await connectApiClient.put(
944
1210
  "/api/publish/v2/on-shelf-time",
945
1211
  body,
946
1212
  { params: { appId } }
@@ -950,7 +1216,7 @@ var PublishService = class {
950
1216
  /** 更新分阶段发布 */
951
1217
  static async updatePhasedRelease(req) {
952
1218
  const { appId, ...body } = req;
953
- const response = await agcClient.put(
1219
+ const response = await connectApiClient.put(
954
1220
  "/api/publish/v2/version/phased-release",
955
1221
  body,
956
1222
  { headers: appIdHeaders(appId) }
@@ -959,7 +1225,7 @@ var PublishService = class {
959
1225
  }
960
1226
  /** 查询应用软件包信息 */
961
1227
  static async getPackageInfo(req) {
962
- const response = await agcClient.get(
1228
+ const response = await connectApiClient.get(
963
1229
  "/api/publish/v2/app-package-info",
964
1230
  {
965
1231
  params: { packageId: req.packageId },
@@ -970,7 +1236,7 @@ var PublishService = class {
970
1236
  }
971
1237
  /** 查询软件包编译状态 */
972
1238
  static async getCompileStatus(req) {
973
- const response = await agcClient.get(
1239
+ const response = await connectApiClient.get(
974
1240
  "/api/publish/v3/package/compile/status",
975
1241
  { params: { appId: req.appId, pkgIds: req.pkgIds } }
976
1242
  );
@@ -979,7 +1245,7 @@ var PublishService = class {
979
1245
  /** 查询应用所有版本类型的版本列表 */
980
1246
  static async queryBriefInfoList(req) {
981
1247
  const { appId, ...body } = req;
982
- const response = await agcClient.post(
1248
+ const response = await connectApiClient.post(
983
1249
  "/api/publish/v3/version/brief-info/list",
984
1250
  body,
985
1251
  { headers: appIdHeaders(appId) }
@@ -989,7 +1255,7 @@ var PublishService = class {
989
1255
  /** 查询应用未处理的问题工单 */
990
1256
  static async queryVersionVoc(req) {
991
1257
  const { appId, ...body } = req;
992
- const response = await agcClient.post(
1258
+ const response = await connectApiClient.post(
993
1259
  "/api/publish/v1/app-voc/version-voc",
994
1260
  body,
995
1261
  { headers: appIdHeaders(appId) }
@@ -998,7 +1264,7 @@ var PublishService = class {
998
1264
  }
999
1265
  /** 查询需要上传的资质文件信息 */
1000
1266
  static async queryTagQualDependent() {
1001
- const response = await agcClient.get(
1267
+ const response = await connectApiClient.get(
1002
1268
  "/api/publish/v2/tag-qual-dependent"
1003
1269
  );
1004
1270
  return response.data;
@@ -1006,7 +1272,7 @@ var PublishService = class {
1006
1272
  /** 提交资质审核任务 */
1007
1273
  static async submitQualificationReview(req) {
1008
1274
  const { appId, ...body } = req;
1009
- const response = await agcClient.post(
1275
+ const response = await connectApiClient.post(
1010
1276
  "/api/publish/v2/qualification-review-task",
1011
1277
  body,
1012
1278
  { headers: appIdHeaders(appId) }
@@ -1015,7 +1281,7 @@ var PublishService = class {
1015
1281
  }
1016
1282
  /** 查询资质审核任务详情 */
1017
1283
  static async getQualificationReview(req) {
1018
- const response = await agcClient.get(
1284
+ const response = await connectApiClient.get(
1019
1285
  "/api/publish/v2/qualification-review-task",
1020
1286
  {
1021
1287
  params: { tagIds: req.tagIds },
@@ -1027,7 +1293,7 @@ var PublishService = class {
1027
1293
  /** 修改资质审核任务 */
1028
1294
  static async updateQualificationReview(req) {
1029
1295
  const { appId, ...body } = req;
1030
- const response = await agcClient.put(
1296
+ const response = await connectApiClient.put(
1031
1297
  "/api/publish/v2/qualification-review-task",
1032
1298
  body,
1033
1299
  { headers: appIdHeaders(appId) }
@@ -1036,7 +1302,7 @@ var PublishService = class {
1036
1302
  }
1037
1303
  /** 撤销资质审核任务 */
1038
1304
  static async cancelQualificationReview(req) {
1039
- const response = await agcClient.put(
1305
+ const response = await connectApiClient.put(
1040
1306
  "/api/publish/v2/qualification-review-task/cancel",
1041
1307
  { taskId: req.taskId },
1042
1308
  { headers: appIdHeaders(req.appId) }
@@ -1045,7 +1311,7 @@ var PublishService = class {
1045
1311
  }
1046
1312
  /** 删除资质审核任务 */
1047
1313
  static async deleteQualificationReview(req) {
1048
- const response = await agcClient.delete(
1314
+ const response = await connectApiClient.delete(
1049
1315
  "/api/publish/v2/qualification-review-task",
1050
1316
  {
1051
1317
  data: { tagIds: req.tagIds },
@@ -1057,7 +1323,7 @@ var PublishService = class {
1057
1323
  /** 新建用户协议 / 隐私政策协议(body.type 区分) */
1058
1324
  static async createAgreement(req) {
1059
1325
  const { appId, ...body } = req;
1060
- const response = await agcClient.post(
1326
+ const response = await connectApiClient.post(
1061
1327
  "/api/publish/v2/agreement",
1062
1328
  body,
1063
1329
  { headers: appIdHeaders(appId) }
@@ -1067,7 +1333,7 @@ var PublishService = class {
1067
1333
  /** 查询用户协议 / 隐私政策协议列表(body.type 区分) */
1068
1334
  static async listAgreements(req) {
1069
1335
  const { appId, ...body } = req;
1070
- const response = await agcClient.post(
1336
+ const response = await connectApiClient.post(
1071
1337
  "/api/publish/v2/agreement/list",
1072
1338
  body,
1073
1339
  { headers: appIdHeaders(appId) }
@@ -1077,7 +1343,7 @@ var PublishService = class {
1077
1343
  /** 更新用户协议 / 隐私政策协议 */
1078
1344
  static async updateAgreement(req) {
1079
1345
  const { appId, ...body } = req;
1080
- const response = await agcClient.put(
1346
+ const response = await connectApiClient.put(
1081
1347
  "/api/publish/v2/agreement",
1082
1348
  body,
1083
1349
  { headers: appIdHeaders(appId) }
@@ -1087,7 +1353,7 @@ var PublishService = class {
1087
1353
  /** 提交隐私政策协议 */
1088
1354
  static async submitPrivacyAgreement(req) {
1089
1355
  const { appId, ...body } = req;
1090
- const response = await agcClient.put(
1356
+ const response = await connectApiClient.put(
1091
1357
  "/api/publish/v2/agreement/submit",
1092
1358
  body,
1093
1359
  { headers: appIdHeaders(appId) }
@@ -1097,7 +1363,7 @@ var PublishService = class {
1097
1363
  /** 申请年龄分级 */
1098
1364
  static async applyAgeRating(req) {
1099
1365
  const { appId, releaseType, releasePhase, ...body } = req;
1100
- const response = await agcClient.post(
1366
+ const response = await connectApiClient.post(
1101
1367
  "/api/publish/v2/app-age-rating",
1102
1368
  body,
1103
1369
  {
@@ -1110,16 +1376,16 @@ var PublishService = class {
1110
1376
  /** 提交发布 */
1111
1377
  static async submitApp(req) {
1112
1378
  const { appId, ...body } = req;
1113
- const response = await agcClient.post(
1379
+ const response = await connectApiClient.post(
1114
1380
  "/api/publish/v3/app-submit",
1115
1381
  body,
1116
- { headers: appIdHeaders(appId) }
1382
+ { params: { appId } }
1117
1383
  );
1118
1384
  return response.data;
1119
1385
  }
1120
1386
  /** 撤销审核 */
1121
1387
  static async cancelReview(req) {
1122
- const response = await agcClient.put(
1388
+ const response = await connectApiClient.put(
1123
1389
  "/api/publish/v3/version/on-shelf/cancel",
1124
1390
  { versionId: req.versionId },
1125
1391
  { headers: appIdHeaders(req.appId) }
@@ -1128,7 +1394,7 @@ var PublishService = class {
1128
1394
  }
1129
1395
  /** 下架应用 */
1130
1396
  static async shelfOff(req) {
1131
- const response = await agcClient.post(
1397
+ const response = await connectApiClient.post(
1132
1398
  "/api/publish/v2/app-shelf-off",
1133
1399
  null,
1134
1400
  {
@@ -1147,7 +1413,7 @@ var PublishService = class {
1147
1413
  var ProjectService = class {
1148
1414
  /** 查询团队下的项目列表(Project Management API) */
1149
1415
  static async listProjects() {
1150
- const response = await agcClient.get("/api/project-service/v1/projects");
1416
+ const response = await connectApiClient.get("/api/project-service/v1/projects");
1151
1417
  return response.data;
1152
1418
  }
1153
1419
  };
@@ -1156,20 +1422,20 @@ var ProjectService = class {
1156
1422
  var ProvisionService = class {
1157
1423
  // ================= Certificates =================
1158
1424
  static async createCert(req) {
1159
- const response = await agcClient.post("/api/publish/v3/cert", req);
1425
+ const response = await connectApiClient.post("/api/publish/v3/cert", req);
1160
1426
  return response.data;
1161
1427
  }
1162
1428
  static async getCertList(req) {
1163
- const response = await agcClient.post("/api/publish/v3/cert/list", req);
1429
+ const response = await connectApiClient.post("/api/publish/v3/cert/list", req);
1164
1430
  return response.data;
1165
1431
  }
1166
1432
  static async deleteCert(req) {
1167
- const response = await agcClient.post("/api/publish/v2/cert/delete", req);
1433
+ const response = await connectApiClient.post("/api/publish/v2/cert/delete", req);
1168
1434
  return response.data;
1169
1435
  }
1170
1436
  // ================= Devices =================
1171
1437
  static async addDevice(req) {
1172
- const response = await agcClient.post("/api/publish/v2/device", req);
1438
+ const response = await connectApiClient.post("/api/publish/v2/device", req);
1173
1439
  return response.data;
1174
1440
  }
1175
1441
  static async getDeviceList(req) {
@@ -1178,16 +1444,16 @@ var ProvisionService = class {
1178
1444
  if (req.fromRecCount !== void 0) params.fromRecCount = req.fromRecCount;
1179
1445
  if (req.maxReqCount !== void 0) params.maxReqCount = req.maxReqCount;
1180
1446
  if (req.order !== void 0) params.order = req.order;
1181
- const response = await agcClient.get("/api/publish/v2/device/list", { params });
1447
+ const response = await connectApiClient.get("/api/publish/v2/device/list", { params });
1182
1448
  return response.data;
1183
1449
  }
1184
1450
  static async deleteDevice(req) {
1185
- const response = await agcClient.post("/api/publish/v2/device/delete", req);
1451
+ const response = await connectApiClient.post("/api/publish/v2/device/delete", req);
1186
1452
  return response.data;
1187
1453
  }
1188
1454
  // ================= Profile / Provision =================
1189
1455
  static async createProvision(req) {
1190
- const response = await agcClient.post("/api/publish/v3/provision", req);
1456
+ const response = await connectApiClient.post("/api/publish/v3/provision", req);
1191
1457
  return response.data;
1192
1458
  }
1193
1459
  static async getProvisionList(req) {
@@ -1196,18 +1462,18 @@ var ProvisionService = class {
1196
1462
  if (req.maxReqCount !== void 0) params.maxReqCount = req.maxReqCount;
1197
1463
  const headers = { appId: req.appId };
1198
1464
  if (req.provisionId) headers.provisionId = req.provisionId;
1199
- const response = await agcClient.get("/api/publish/v3/provision/list", {
1465
+ const response = await connectApiClient.get("/api/publish/v3/provision/list", {
1200
1466
  params,
1201
1467
  headers
1202
1468
  });
1203
1469
  return response.data;
1204
1470
  }
1205
1471
  static async updateProvision(req) {
1206
- const response = await agcClient.put("/api/publish/v3/provision", req);
1472
+ const response = await connectApiClient.put("/api/publish/v3/provision", req);
1207
1473
  return response.data;
1208
1474
  }
1209
1475
  static async deleteProvision(req) {
1210
- const response = await agcClient.delete("/api/publish/v2/provision", {
1476
+ const response = await connectApiClient.delete("/api/publish/v2/provision", {
1211
1477
  params: { id: req.id }
1212
1478
  });
1213
1479
  return response.data;
@@ -1215,7 +1481,7 @@ var ProvisionService = class {
1215
1481
  // ================= Fingerprint =================
1216
1482
  static async addFingerprint(req) {
1217
1483
  const { appId, ...body } = req;
1218
- const response = await agcClient.post(
1484
+ const response = await connectApiClient.post(
1219
1485
  "/api/provision/v1/fingerprints",
1220
1486
  body,
1221
1487
  { headers: { appId } }
@@ -1223,14 +1489,14 @@ var ProvisionService = class {
1223
1489
  return response.data;
1224
1490
  }
1225
1491
  static async getFingerprintList(req) {
1226
- const response = await agcClient.get("/api/provision/v1/fingerprints", {
1492
+ const response = await connectApiClient.get("/api/provision/v1/fingerprints", {
1227
1493
  headers: { appId: req.appId }
1228
1494
  });
1229
1495
  return response.data;
1230
1496
  }
1231
1497
  static async deleteFingerprint(req) {
1232
1498
  const { appId, ...body } = req;
1233
- const response = await agcClient.delete(
1499
+ const response = await connectApiClient.delete(
1234
1500
  "/api/provision/v1/fingerprints",
1235
1501
  { headers: { appId }, data: body }
1236
1502
  );
@@ -1240,7 +1506,7 @@ var ProvisionService = class {
1240
1506
  /** 查询可申请的 ACL 权限列表 */
1241
1507
  static async getEligibleACL(req) {
1242
1508
  const { appId, ...body } = req;
1243
- const response = await agcClient.post(
1509
+ const response = await connectApiClient.post(
1244
1510
  "/api/provision/v1/user/permission/apply/list",
1245
1511
  body,
1246
1512
  { headers: { appId } }
@@ -1249,7 +1515,7 @@ var ProvisionService = class {
1249
1515
  }
1250
1516
  static async applyACL(req) {
1251
1517
  const { appId, ...body } = req;
1252
- const response = await agcClient.post(
1518
+ const response = await connectApiClient.post(
1253
1519
  "/api/provision/v1/user/permission/apply",
1254
1520
  body,
1255
1521
  { headers: { appId } }
@@ -1257,14 +1523,14 @@ var ProvisionService = class {
1257
1523
  return response.data;
1258
1524
  }
1259
1525
  static async getACLStatus(req) {
1260
- const response = await agcClient.get(
1526
+ const response = await connectApiClient.get(
1261
1527
  "/api/provision/v1/user/permission/apply/status",
1262
1528
  { headers: { appId: req.appId } }
1263
1529
  );
1264
1530
  return response.data;
1265
1531
  }
1266
1532
  static async getACLQuery(req) {
1267
- const response = await agcClient.get("/api/provision/v1/user/permission", {
1533
+ const response = await connectApiClient.get("/api/provision/v1/user/permission", {
1268
1534
  headers: { appId: req.appId }
1269
1535
  });
1270
1536
  return response.data;
@@ -1273,35 +1539,35 @@ var ProvisionService = class {
1273
1539
 
1274
1540
  // src/services/upload.ts
1275
1541
  var import_axios4 = __toESM(require("axios"));
1276
- var import_fs6 = __toESM(require("fs"));
1277
- var import_path5 = __toESM(require("path"));
1542
+ var import_fs7 = __toESM(require("fs"));
1543
+ var import_path6 = __toESM(require("path"));
1278
1544
  function pickObjectId(res) {
1279
1545
  return res.urlInfo?.objectId || res.objectId;
1280
1546
  }
1281
1547
  var UploadService = class {
1282
1548
  // ================= Raw APIs =================
1283
1549
  static async getUploadUrl(req) {
1284
- const response = await agcClient.get("/api/publish/v2/upload-url/for-obs", {
1550
+ const response = await connectApiClient.get("/api/publish/v2/upload-url/for-obs", {
1285
1551
  params: req
1286
1552
  });
1287
1553
  return response.data;
1288
1554
  }
1289
1555
  static async initMultipart(req) {
1290
- const response = await agcClient.post("/api/publish/v2/upload/multipart/init", null, {
1556
+ const response = await connectApiClient.post("/api/publish/v2/upload/multipart/init", null, {
1291
1557
  params: req
1292
1558
  });
1293
1559
  return response.data;
1294
1560
  }
1295
1561
  static async getMultipartParts(req) {
1296
1562
  const { objectId, nspUploadId, parts } = req;
1297
- const response = await agcClient.post("/api/publish/v2/upload/multipart/parts", parts, {
1563
+ const response = await connectApiClient.post("/api/publish/v2/upload/multipart/parts", parts, {
1298
1564
  params: { objectId, nspUploadId }
1299
1565
  });
1300
1566
  return response.data;
1301
1567
  }
1302
1568
  static async composeMultipart(req) {
1303
1569
  const { objectId, nspUploadId, parts } = req;
1304
- const response = await agcClient.post("/api/publish/v2/upload/multipart/compose", parts, {
1570
+ const response = await connectApiClient.post("/api/publish/v2/upload/multipart/compose", parts, {
1305
1571
  params: { objectId, nspUploadId }
1306
1572
  });
1307
1573
  return response.data;
@@ -1313,8 +1579,8 @@ var UploadService = class {
1313
1579
  * 仅完成 OBS 落盘;HarmonyOS `.app` 还须调用更新应用软件包信息,HarmonyOS 开发者中心才会有记录。
1314
1580
  */
1315
1581
  static async uploadFile(options) {
1316
- const stat = import_fs6.default.statSync(options.filePath);
1317
- const fileName = import_path5.default.basename(options.filePath) || "unknown";
1582
+ const stat = import_fs7.default.statSync(options.filePath);
1583
+ const fileName = import_path6.default.basename(options.filePath) || "unknown";
1318
1584
  if (stat.size < 5 * 1024 * 1024) {
1319
1585
  return this.uploadSingleFile(options, fileName, stat.size);
1320
1586
  }
@@ -1355,7 +1621,7 @@ var UploadService = class {
1355
1621
  );
1356
1622
  }
1357
1623
  const { url, headers } = urlRes.urlInfo;
1358
- const fileStream = import_fs6.default.createReadStream(options.filePath);
1624
+ const fileStream = import_fs7.default.createReadStream(options.filePath);
1359
1625
  await import_axios4.default.put(url, fileStream, {
1360
1626
  headers: this.buildObsPutHeaders(headers, contentLength),
1361
1627
  maxBodyLength: Infinity,
@@ -1396,7 +1662,7 @@ var UploadService = class {
1396
1662
  if (!uploadInfoMap) {
1397
1663
  throw new Error(`Failed to get parts upload URL: ${JSON.stringify(partsRes.ret)}`);
1398
1664
  }
1399
- const fd = import_fs6.default.openSync(options.filePath, "r");
1665
+ const fd = import_fs7.default.openSync(options.filePath, "r");
1400
1666
  const composeReqBody = {};
1401
1667
  for (let i = 1; i <= partsCount; i++) {
1402
1668
  const propKey = `additionalProp${i}`;
@@ -1405,7 +1671,7 @@ var UploadService = class {
1405
1671
  const end = Math.min(start + partSize, fileSize);
1406
1672
  const length = end - start;
1407
1673
  const buffer = Buffer.alloc(length);
1408
- import_fs6.default.readSync(fd, buffer, 0, length, start);
1674
+ import_fs7.default.readSync(fd, buffer, 0, length, start);
1409
1675
  const res = await import_axios4.default.put(uploadInfo.url, buffer, {
1410
1676
  headers: this.buildObsPutHeaders(uploadInfo.headers, length),
1411
1677
  maxBodyLength: Infinity,
@@ -1417,7 +1683,7 @@ var UploadService = class {
1417
1683
  etag
1418
1684
  };
1419
1685
  }
1420
- import_fs6.default.closeSync(fd);
1686
+ import_fs7.default.closeSync(fd);
1421
1687
  await this.composeMultipart({
1422
1688
  objectId,
1423
1689
  nspUploadId,
@@ -1428,13 +1694,13 @@ var UploadService = class {
1428
1694
  };
1429
1695
 
1430
1696
  // src/services/domain.ts
1431
- var import_fs7 = __toESM(require("fs"));
1697
+ var import_fs8 = __toESM(require("fs"));
1432
1698
  var DomainService = class {
1433
1699
  /**
1434
1700
  * 查询元服务的域名配置信息
1435
1701
  */
1436
1702
  static async queryDomain(req) {
1437
- const response = await agcClient.get(
1703
+ const response = await connectApiClient.get(
1438
1704
  "/api/dms/domain-manage/v1/app/domain",
1439
1705
  {
1440
1706
  params: { category: req.category },
@@ -1447,7 +1713,7 @@ var DomainService = class {
1447
1713
  * 新增/更新元服务的域名配置信息
1448
1714
  */
1449
1715
  static async updateDomain(req) {
1450
- const response = await agcClient.post(
1716
+ const response = await connectApiClient.post(
1451
1717
  "/api/dms/domain-manage/v1/app/domain",
1452
1718
  { domains: req.domains },
1453
1719
  {
@@ -1461,7 +1727,7 @@ var DomainService = class {
1461
1727
  * 查询域名修改次数/配置上限
1462
1728
  */
1463
1729
  static async queryDomainConfig(req) {
1464
- const response = await agcClient.get(
1730
+ const response = await connectApiClient.get(
1465
1731
  "/api/dms/domain-manage/v1/app/domain/config",
1466
1732
  {
1467
1733
  params: { appId: req.appId }
@@ -1473,15 +1739,15 @@ var DomainService = class {
1473
1739
  * 下载域名配置文件
1474
1740
  */
1475
1741
  static async verifyFile(req, outputPath) {
1476
- const response = await agcClient.get(
1742
+ const response = await connectApiClient.get(
1477
1743
  "/api/dms/domain-manage/v1/app/domain/verify-file",
1478
1744
  {
1479
1745
  headers: { appId: req.appId },
1480
1746
  responseType: "stream"
1481
1747
  }
1482
1748
  );
1483
- return new Promise((resolve, reject) => {
1484
- const writer = import_fs7.default.createWriteStream(outputPath);
1749
+ return new Promise((resolve2, reject) => {
1750
+ const writer = import_fs8.default.createWriteStream(outputPath);
1485
1751
  response.data.pipe(writer);
1486
1752
  let error = null;
1487
1753
  writer.on("error", (err) => {
@@ -1491,7 +1757,7 @@ var DomainService = class {
1491
1757
  });
1492
1758
  writer.on("close", () => {
1493
1759
  if (!error) {
1494
- resolve();
1760
+ resolve2();
1495
1761
  }
1496
1762
  });
1497
1763
  });
@@ -1500,7 +1766,7 @@ var DomainService = class {
1500
1766
  * 预检查业务域名配置
1501
1767
  */
1502
1768
  static async preCheckDomain(req) {
1503
- const response = await agcClient.post(
1769
+ const response = await connectApiClient.post(
1504
1770
  "/api/dms/domain-manage/v1/app/domain/pre-check",
1505
1771
  { domain: req.domain },
1506
1772
  {
@@ -1512,10 +1778,11 @@ var DomainService = class {
1512
1778
  };
1513
1779
 
1514
1780
  // src/services/sign.ts
1515
- var import_fs8 = __toESM(require("fs"));
1516
- var import_path6 = __toESM(require("path"));
1781
+ var import_fs9 = __toESM(require("fs"));
1782
+ var import_os4 = __toESM(require("os"));
1783
+ var import_path7 = __toESM(require("path"));
1517
1784
  var import_child_process2 = require("child_process");
1518
- var import_crypto = __toESM(require("crypto"));
1785
+ var import_crypto2 = __toESM(require("crypto"));
1519
1786
  var DEFAULT_SIGN_OUT_DIR = ".certs";
1520
1787
  var SIGN_FILE_PREFIX = {
1521
1788
  p12: "key_",
@@ -1525,16 +1792,22 @@ var SIGN_FILE_PREFIX = {
1525
1792
  };
1526
1793
  var SignService = class {
1527
1794
  static resolveSignOutputLayout(options) {
1528
- const rootDir = options.outDir ? import_path6.default.resolve(options.outDir) : import_path6.default.join(process.cwd(), DEFAULT_SIGN_OUT_DIR);
1795
+ const rootDir = options.outDir ? import_path7.default.resolve(options.outDir) : import_path7.default.join(process.cwd(), DEFAULT_SIGN_OUT_DIR);
1529
1796
  const signId = options.filename || this.createSignDefaultId();
1530
1797
  return {
1531
1798
  rootDir,
1532
- bundleDir: import_path6.default.join(rootDir, signId),
1799
+ bundleDir: import_path7.default.join(rootDir, signId),
1533
1800
  filename: signId
1534
1801
  };
1535
1802
  }
1536
- /** hap-sign-tool.jar 相对 SDK 根的位置 */
1537
- static HAP_SIGN_TOOL_REL = ["default", "openharmony", "toolchains", "lib", "hap-sign-tool.jar"];
1803
+ /**
1804
+ * 签名工具都在 SDK 的 `toolchains/lib/`。
1805
+ * Windows / macOS 是 `hap-sign-tool.jar`(`java -jar`);
1806
+ * 鸿蒙 PC 是同目录无后缀的 `hap-sign-tool`(直接执行)。
1807
+ */
1808
+ static HAP_SIGN_TOOL_DIR = ["default", "openharmony", "toolchains", "lib"];
1809
+ static HAP_SIGN_TOOL_JAR = "hap-sign-tool.jar";
1810
+ static HAP_SIGN_TOOL_NATIVE = "hap-sign-tool";
1538
1811
  /**
1539
1812
  * 只根据调用方给出的路径解析 SDK:`--sdk-path` → `DEVECO_HOME` 下的 `sdk/` 或 `Contents/sdk/`。
1540
1813
  * 不扫盘、不猜常见安装目录。
@@ -1546,11 +1819,28 @@ var SignService = class {
1546
1819
  /** 仅检查 `DEVECO_HOME` 本身及其 `Contents/`,找不到就返回 undefined */
1547
1820
  static sdkPathFromDevEcoHome(home) {
1548
1821
  if (!home) return void 0;
1549
- for (const sdk of [import_path6.default.join(home, "sdk"), import_path6.default.join(home, "Contents", "sdk")]) {
1550
- if (import_fs8.default.existsSync(import_path6.default.join(sdk, ...this.HAP_SIGN_TOOL_REL))) return sdk;
1822
+ for (const sdk of [import_path7.default.join(home, "sdk"), import_path7.default.join(home, "Contents", "sdk")]) {
1823
+ if (this.resolveSignTool(sdk)) return sdk;
1551
1824
  }
1552
1825
  return void 0;
1553
1826
  }
1827
+ /** jar 与无后缀可执行文件的绝对路径(不一定存在) */
1828
+ static signToolCandidates(sdkPath) {
1829
+ const dir = import_path7.default.join(sdkPath, ...this.HAP_SIGN_TOOL_DIR);
1830
+ return {
1831
+ jar: import_path7.default.join(dir, this.HAP_SIGN_TOOL_JAR),
1832
+ native: import_path7.default.join(dir, this.HAP_SIGN_TOOL_NATIVE)
1833
+ };
1834
+ }
1835
+ /**
1836
+ * 有 jar 就用 jar(Windows / macOS)。否则用同目录无后缀可执行文件(鸿蒙 PC)。
1837
+ */
1838
+ static resolveSignTool(sdkPath) {
1839
+ const { jar, native } = this.signToolCandidates(sdkPath);
1840
+ if (import_fs9.default.existsSync(jar)) return { mode: "jar", path: jar };
1841
+ if (import_fs9.default.existsSync(native)) return { mode: "native", path: native };
1842
+ return void 0;
1843
+ }
1554
1844
  static async createSignP12AndCsr(options) {
1555
1845
  const pwd = options.pwd;
1556
1846
  if (!pwd) {
@@ -1568,23 +1858,24 @@ var SignService = class {
1568
1858
  "sdkPath is required. Provide it via --sdk-path or DEVECO_HOME in .env."
1569
1859
  );
1570
1860
  }
1571
- const signToolPath = import_path6.default.join(sdkPath, "default", "openharmony", "toolchains", "lib", "hap-sign-tool.jar");
1572
- if (!import_fs8.default.existsSync(signToolPath)) {
1573
- throw new Error(`hap-sign-tool.jar not found at ${signToolPath}`);
1861
+ const signTool = this.resolveSignTool(sdkPath);
1862
+ if (!signTool) {
1863
+ const { jar, native } = this.signToolCandidates(sdkPath);
1864
+ throw new Error(`hap-sign-tool not found at ${jar} or ${native}`);
1574
1865
  }
1575
1866
  const { rootDir, bundleDir, filename } = this.resolveSignOutputLayout(options);
1576
- const createdBundleDir = !import_fs8.default.existsSync(bundleDir);
1577
- if (!import_fs8.default.existsSync(rootDir)) {
1578
- import_fs8.default.mkdirSync(rootDir, { recursive: true });
1867
+ const createdBundleDir = !import_fs9.default.existsSync(bundleDir);
1868
+ if (!import_fs9.default.existsSync(rootDir)) {
1869
+ import_fs9.default.mkdirSync(rootDir, { recursive: true });
1579
1870
  }
1580
- import_fs8.default.mkdirSync(bundleDir, { recursive: true });
1581
- const p12FilePath = import_path6.default.join(bundleDir, this.signFileName(filename, "p12"));
1582
- const csrFilePath = import_path6.default.join(bundleDir, this.signFileName(filename, "csr"));
1871
+ import_fs9.default.mkdirSync(bundleDir, { recursive: true });
1872
+ const p12FilePath = import_path7.default.join(bundleDir, this.signFileName(filename, "p12"));
1873
+ const csrFilePath = import_path7.default.join(bundleDir, this.signFileName(filename, "csr"));
1583
1874
  const alias = options.alias;
1584
1875
  try {
1585
- this.doCreateSignFileP12(javaPath, signToolPath, alias, pwd, p12FilePath);
1586
- this.doCreateSignFileCsr(javaPath, signToolPath, alias, pwd, p12FilePath, csrFilePath);
1587
- const csrContent = import_fs8.default.readFileSync(csrFilePath, "utf8");
1876
+ this.doCreateSignFileP12(javaPath, signTool, alias, pwd, p12FilePath);
1877
+ this.doCreateSignFileCsr(javaPath, signTool, alias, pwd, p12FilePath, csrFilePath);
1878
+ const csrContent = import_fs9.default.readFileSync(csrFilePath, "utf8");
1588
1879
  const materialPath = this.placeMaterialBesideStore(bundleDir);
1589
1880
  return {
1590
1881
  alias,
@@ -1594,20 +1885,20 @@ var SignService = class {
1594
1885
  csrPath: csrFilePath,
1595
1886
  csrContent,
1596
1887
  storePath: bundleDir,
1597
- cerPath: import_path6.default.join(bundleDir, this.signFileName(filename, "cer")),
1598
- p7bPath: import_path6.default.join(bundleDir, this.signFileName(filename, "p7b")),
1888
+ cerPath: import_path7.default.join(bundleDir, this.signFileName(filename, "cer")),
1889
+ p7bPath: import_path7.default.join(bundleDir, this.signFileName(filename, "p7b")),
1599
1890
  ...materialPath ? { materialPath } : {}
1600
1891
  };
1601
1892
  } catch (err) {
1602
1893
  if (createdBundleDir) {
1603
- import_fs8.default.rmSync(bundleDir, { recursive: true, force: true });
1894
+ import_fs9.default.rmSync(bundleDir, { recursive: true, force: true });
1604
1895
  }
1605
1896
  throw err;
1606
1897
  }
1607
1898
  }
1608
1899
  /** 目录名与各文件共用的安全随机数(32 hex) */
1609
1900
  static createSignDefaultId() {
1610
- return import_crypto.default.randomBytes(16).toString("hex");
1901
+ return import_crypto2.default.randomBytes(16).toString("hex");
1611
1902
  }
1612
1903
  /** `key_<id>.p12` / `cert_<id>.cer` / `profile_<id>.p7b` 等 */
1613
1904
  static signFileName(id, ext) {
@@ -1615,26 +1906,22 @@ var SignService = class {
1615
1906
  }
1616
1907
  /** 密钥库密码:16 字节 CSPRNG → 32 hex(字母+数字,满足 hap-sign-tool 约束) */
1617
1908
  static createSignDefaultPassword() {
1618
- return import_crypto.default.randomBytes(16).toString("hex");
1909
+ return import_crypto2.default.randomBytes(16).toString("hex");
1619
1910
  }
1620
1911
  /**
1621
- * hvigor 在 `.p12` 同级目录找 `material/`。把 DevEco 的加密材料放到本套证书目录,
1622
- * 避免签名文件被拷到工程根目录才能编过。
1912
+ * hvigor 在 `.p12` 同级目录找 `material/`。把加密材料放到本套证书目录,
1913
+ * 避免签名文件被拷到工程根目录才能编过。配置目录里还没有 material 时先生成。
1623
1914
  */
1624
1915
  static placeMaterialBesideStore(bundleDir, configDir) {
1625
- const dest = import_path6.default.join(bundleDir, "material");
1626
- if (import_fs8.default.existsSync(dest)) {
1916
+ const dest = import_path7.default.join(bundleDir, "material");
1917
+ if (import_fs9.default.existsSync(dest)) {
1627
1918
  return dest;
1628
1919
  }
1629
- const home = process.env.HOME || process.env.USERPROFILE || "";
1630
- const src = import_path6.default.resolve(configDir || import_path6.default.join(home, ".ohos", "config"), "material");
1631
- if (!import_fs8.default.existsSync(src)) {
1632
- return void 0;
1633
- }
1920
+ const src = this.ensureMaterial(this.resolveOhosConfigDir(configDir));
1634
1921
  try {
1635
- import_fs8.default.symlinkSync(src, dest, process.platform === "win32" ? "junction" : "dir");
1922
+ import_fs9.default.symlinkSync(src, dest, process.platform === "win32" ? "junction" : "dir");
1636
1923
  } catch {
1637
- import_fs8.default.cpSync(src, dest, { recursive: true });
1924
+ import_fs9.default.cpSync(src, dest, { recursive: true });
1638
1925
  }
1639
1926
  return dest;
1640
1927
  }
@@ -1648,14 +1935,19 @@ var SignService = class {
1648
1935
  * 执行签名工具:命令行与子进程输出统一走 stderr,
1649
1936
  * 保证 stdout 只有 CLI 的 JSON 结果,便于 jq 等下游解析。
1650
1937
  */
1651
- static runSignTool(javaPath, args) {
1938
+ /** jar 走 `java -jar`;无后缀可执行文件直接执行,子命令参数相同 */
1939
+ static runSignTool(javaPath, tool, toolArgs) {
1940
+ if (tool.mode === "native") {
1941
+ console.error(`Executing: ${tool.path} ${this.maskArgs(toolArgs)}`);
1942
+ (0, import_child_process2.execFileSync)(tool.path, toolArgs, { stdio: ["ignore", 2, "inherit"] });
1943
+ return;
1944
+ }
1945
+ const args = ["-jar", tool.path, ...toolArgs];
1652
1946
  console.error(`Executing: ${javaPath} ${this.maskArgs(args)}`);
1653
1947
  (0, import_child_process2.execFileSync)(javaPath, args, { stdio: ["ignore", 2, "inherit"] });
1654
1948
  }
1655
- static doCreateSignFileP12(javaPath, signToolPath, alias, pwd, outFilePath) {
1949
+ static doCreateSignFileP12(javaPath, tool, alias, pwd, outFilePath) {
1656
1950
  const args = [
1657
- "-jar",
1658
- signToolPath,
1659
1951
  "generate-keypair",
1660
1952
  "-keyAlias",
1661
1953
  alias,
@@ -1670,12 +1962,10 @@ var SignService = class {
1670
1962
  "-keystorePwd",
1671
1963
  pwd
1672
1964
  ];
1673
- this.runSignTool(javaPath, args);
1965
+ this.runSignTool(javaPath, tool, args);
1674
1966
  }
1675
- static doCreateSignFileCsr(javaPath, signToolPath, alias, pwd, p12Path, outFilePath) {
1967
+ static doCreateSignFileCsr(javaPath, tool, alias, pwd, p12Path, outFilePath) {
1676
1968
  const args = [
1677
- "-jar",
1678
- signToolPath,
1679
1969
  "generate-csr",
1680
1970
  "-keyAlias",
1681
1971
  alias,
@@ -1692,16 +1982,16 @@ var SignService = class {
1692
1982
  "-outFile",
1693
1983
  outFilePath
1694
1984
  ];
1695
- this.runSignTool(javaPath, args);
1985
+ this.runSignTool(javaPath, tool, args);
1696
1986
  }
1697
1987
  static COMPONENT = new Int8Array([49, 243, 9, 115, 214, 175, 91, 184, 211, 190, 177, 88, 101, 131, 192, 119]);
1698
1988
  static readDirBytes(dirPath) {
1699
- const entries = import_fs8.default.readdirSync(dirPath).filter((f) => f !== ".DS_Store");
1700
- return new Int8Array(import_fs8.default.readFileSync(import_path6.default.resolve(dirPath, entries[0])));
1989
+ const entries = import_fs9.default.readdirSync(dirPath).filter((f) => f !== ".DS_Store");
1990
+ return new Int8Array(import_fs9.default.readFileSync(import_path7.default.resolve(dirPath, entries[0])));
1701
1991
  }
1702
1992
  static readFd(materialPath) {
1703
- const fdDir = import_path6.default.resolve(materialPath, "fd");
1704
- return import_fs8.default.readdirSync(fdDir).filter((f) => f !== ".DS_Store").map((e) => this.readDirBytes(import_path6.default.resolve(fdDir, e)));
1993
+ const fdDir = import_path7.default.resolve(materialPath, "fd");
1994
+ return import_fs9.default.readdirSync(fdDir).filter((f) => f !== ".DS_Store").map((e) => this.readDirBytes(import_path7.default.resolve(fdDir, e)));
1705
1995
  }
1706
1996
  static xorBuffers(a, b) {
1707
1997
  const result = new Int8Array(a.byteLength);
@@ -1718,43 +2008,272 @@ var SignService = class {
1718
2008
  const tagLen = (255 & d[0]) << 24 | (255 & d[1]) << 16 | (255 & d[2]) << 8 | 255 & d[3];
1719
2009
  const ivLen = d.length - 4 - tagLen;
1720
2010
  const iv = d.subarray(4, 4 + ivLen);
1721
- const decipher = import_crypto.default.createDecipheriv("aes-128-gcm", key, iv);
2011
+ const decipher = import_crypto2.default.createDecipheriv("aes-128-gcm", key, iv);
1722
2012
  decipher.setAuthTag(d.subarray(d.length - 16));
1723
2013
  return Buffer.concat([decipher.update(d.subarray(4 + ivLen, d.length - 16)), decipher.final()]);
1724
2014
  }
1725
- static aesEncrypt(key, plaintext) {
1726
- const iv = import_crypto.default.randomBytes(12);
1727
- const cipher = import_crypto.default.createCipheriv("aes-128-gcm", key, iv);
1728
- const enc = Buffer.concat([cipher.update(plaintext, "utf-8"), cipher.final()]);
2015
+ static aesSeal(key, plaintext) {
2016
+ const iv = import_crypto2.default.randomBytes(12);
2017
+ const cipher = import_crypto2.default.createCipheriv("aes-128-gcm", key, iv);
2018
+ const enc = Buffer.concat([cipher.update(plaintext), cipher.final()]);
1729
2019
  const tag = cipher.getAuthTag();
1730
2020
  const header = Buffer.alloc(4);
1731
2021
  header.writeUInt32BE(enc.length + 16, 0);
1732
- return Buffer.concat([header, iv, enc, tag]).toString("hex").toUpperCase();
2022
+ return Buffer.concat([header, iv, enc, tag]);
2023
+ }
2024
+ static aesEncrypt(key, plaintext) {
2025
+ return this.aesSeal(key, Buffer.from(plaintext, "utf-8")).toString("hex").toUpperCase();
2026
+ }
2027
+ static deriveRootKey(components, salt) {
2028
+ return import_crypto2.default.pbkdf2Sync(
2029
+ this.xorAll(components.concat(this.COMPONENT)).toString(),
2030
+ Buffer.from(salt),
2031
+ 1e4,
2032
+ 16,
2033
+ "sha256"
2034
+ );
1733
2035
  }
1734
2036
  static deriveEncryptionKey(configDir) {
1735
- const materialDir = import_path6.default.resolve(configDir, "material");
2037
+ const materialDir = import_path7.default.resolve(configDir, "material");
1736
2038
  const fd = this.readFd(materialDir);
1737
- const salt = this.readDirBytes(import_path6.default.resolve(materialDir, "ac"));
1738
- const rawKey = new Int8Array(
1739
- import_crypto.default.pbkdf2Sync(this.xorAll(fd.concat(this.COMPONENT)).toString(), salt, 1e4, 16, "sha256")
1740
- );
1741
- return new Int8Array(this.aesDecrypt(rawKey, this.readDirBytes(import_path6.default.resolve(materialDir, "ce"))));
2039
+ const salt = this.readDirBytes(import_path7.default.resolve(materialDir, "ac"));
2040
+ const rawKey = new Int8Array(this.deriveRootKey(fd, salt));
2041
+ return new Int8Array(this.aesDecrypt(rawKey, this.readDirBytes(import_path7.default.resolve(materialDir, "ce"))));
2042
+ }
2043
+ /** HOME 优先,与现有加密材料目录一致。Windows 上通常只有 USERPROFILE。 */
2044
+ static resolveUserHome() {
2045
+ return process.env.HOME || process.env.USERPROFILE || import_os4.default.homedir();
2046
+ }
2047
+ /** 显式目录优先;否则用户主目录。不用空的 HOME 落到当前工作目录。 */
2048
+ static resolveOhosConfigDir(configDir) {
2049
+ if (configDir) return import_path7.default.resolve(configDir);
2050
+ return import_path7.default.join(this.resolveUserHome(), ".ohos", "config");
2051
+ }
2052
+ /** 发布私钥登记根目录:`<用户主目录>/.ohos/release-signing`。只读这一处,不搜盘。 */
2053
+ static resolveReleaseSigningRoot() {
2054
+ return import_path7.default.join(this.resolveUserHome(), ".ohos", "release-signing");
1742
2055
  }
1743
2056
  /**
1744
- * 使用 DevEco Studio 的加密密钥对密码进行 AES-128-GCM 加密,
2057
+ * 与 devecocli KeyManager.generateMaterial 相同的 material/{fd,ac,ce}。
2058
+ * 目录已存在则直接复用,不删除、不覆盖,避免已加密密码失效。
2059
+ */
2060
+ static ensureMaterial(configDir) {
2061
+ const materialDir = import_path7.default.resolve(configDir, "material");
2062
+ if (!import_fs9.default.existsSync(materialDir)) this.generateMaterial(configDir);
2063
+ return materialDir;
2064
+ }
2065
+ static generateMaterial(configDir) {
2066
+ const materialDir = import_path7.default.resolve(configDir, "material");
2067
+ if (import_fs9.default.existsSync(materialDir)) return;
2068
+ import_fs9.default.mkdirSync(configDir, { recursive: true, mode: 448 });
2069
+ const staging = import_path7.default.join(configDir, `.material-${import_crypto2.default.randomBytes(8).toString("hex")}`);
2070
+ const acDir = import_path7.default.join(staging, "ac");
2071
+ const ceDir = import_path7.default.join(staging, "ce");
2072
+ import_fs9.default.mkdirSync(acDir, { recursive: true, mode: 448 });
2073
+ import_fs9.default.mkdirSync(ceDir, { recursive: true, mode: 448 });
2074
+ const salt = import_crypto2.default.randomBytes(16);
2075
+ const components = [0, 1, 2].map(() => new Int8Array(import_crypto2.default.randomBytes(16)));
2076
+ for (let i = 0; i < components.length; i++) {
2077
+ import_fs9.default.mkdirSync(import_path7.default.join(staging, "fd", String(i)), { recursive: true, mode: 448 });
2078
+ }
2079
+ const workKey = import_crypto2.default.randomBytes(16);
2080
+ const derived = this.deriveRootKey(components, salt);
2081
+ this.writeMaterialFile(acDir, salt);
2082
+ this.writeMaterialFile(ceDir, this.aesSeal(derived, workKey));
2083
+ components.forEach((part, i) => {
2084
+ this.writeMaterialFile(import_path7.default.join(staging, "fd", String(i)), Buffer.from(part));
2085
+ });
2086
+ try {
2087
+ import_fs9.default.renameSync(staging, materialDir);
2088
+ } catch (err) {
2089
+ import_fs9.default.rmSync(staging, { recursive: true, force: true });
2090
+ if (!import_fs9.default.existsSync(materialDir)) throw err;
2091
+ }
2092
+ }
2093
+ static writeMaterialFile(dir, data) {
2094
+ import_fs9.default.writeFileSync(import_path7.default.join(dir, import_crypto2.default.randomBytes(16).toString("hex")), data, { mode: 384 });
2095
+ }
2096
+ /**
2097
+ * 使用与 devecocli / hvigor 相同的 AES-128-GCM 密钥加密密码,
1745
2098
  * 生成 build-profile.json5 中 signingConfigs 所需的加密密码。
2099
+ * 配置目录下没有 material/ 时自动生成,已有目录不覆盖。
1746
2100
  */
1747
2101
  static encryptPassword(password, configDir) {
1748
- const dir = configDir || import_path6.default.join(process.env.HOME || "", ".ohos", "config");
1749
- if (!import_fs8.default.existsSync(import_path6.default.resolve(dir, "material"))) {
1750
- throw new Error(`\u672A\u627E\u5230\u52A0\u5BC6\u5BC6\u94A5\u76EE\u5F55: ${import_path6.default.resolve(dir, "material")}\u3002\u8BF7\u786E\u8BA4 DevEco Studio \u5DF2\u5B89\u88C5\u5E76\u751F\u6210\u8FC7\u7B7E\u540D\u914D\u7F6E\u3002`);
2102
+ const dir = this.resolveOhosConfigDir(configDir);
2103
+ this.ensureMaterial(dir);
2104
+ let key;
2105
+ try {
2106
+ key = this.deriveEncryptionKey(dir);
2107
+ } catch (err) {
2108
+ throw new Error(
2109
+ `\u65E0\u6CD5\u8BFB\u53D6\u52A0\u5BC6\u6750\u6599 ${import_path7.default.resolve(dir, "material")}\u3002\u5DF2\u6709\u76EE\u5F55\u4E0D\u4F1A\u91CD\u65B0\u751F\u6210\uFF0C\u4EE5\u514D\u5DF2\u52A0\u5BC6\u5BC6\u7801\u5931\u6548\u3002`,
2110
+ { cause: err }
2111
+ );
1751
2112
  }
1752
- const key = this.deriveEncryptionKey(dir);
1753
2113
  return {
1754
2114
  keyPassword: this.aesEncrypt(key, password),
1755
2115
  storePassword: this.aesEncrypt(key, password)
1756
2116
  };
1757
2117
  }
2118
+ /**
2119
+ * 复用已有 .p12:用它同级的 material/ 加密;同级还没有时,用 configDir 的材料再放到同级。
2120
+ * 已有 material/ 不覆盖,避免跟这份私钥以前加密过的密码对不上。
2121
+ */
2122
+ static encryptPasswordBeside(password, p12Path, configDir) {
2123
+ const storeFile = import_path7.default.resolve(p12Path);
2124
+ if (!import_fs9.default.existsSync(storeFile) || !import_fs9.default.statSync(storeFile).isFile()) {
2125
+ throw new Error(`p12 not found: ${storeFile}`);
2126
+ }
2127
+ const bundleDir = import_path7.default.dirname(storeFile);
2128
+ const dir = import_fs9.default.existsSync(import_path7.default.join(bundleDir, "material")) ? bundleDir : this.resolveOhosConfigDir(configDir);
2129
+ const encrypted = this.encryptPassword(password, dir);
2130
+ const materialPath = this.placeMaterialBesideStore(bundleDir, dir);
2131
+ if (!materialPath) {
2132
+ throw new Error(`\u65E0\u6CD5\u628A\u52A0\u5BC6\u6750\u6599\u653E\u5230 ${bundleDir}`);
2133
+ }
2134
+ return { ...encrypted, materialPath };
2135
+ }
2136
+ static CERT_ID_RE = /^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$/;
2137
+ static releaseSigningIndexPath() {
2138
+ return import_path7.default.join(this.resolveReleaseSigningRoot(), "index.json");
2139
+ }
2140
+ static isInside(child, parent) {
2141
+ const rel = import_path7.default.relative(import_path7.default.resolve(parent), import_path7.default.resolve(child));
2142
+ return rel === "" || !rel.startsWith("..") && !import_path7.default.isAbsolute(rel);
2143
+ }
2144
+ static readReleaseSigningCerts() {
2145
+ const file = this.releaseSigningIndexPath();
2146
+ if (!import_fs9.default.existsSync(file)) return [];
2147
+ let parsed;
2148
+ try {
2149
+ parsed = JSON.parse(import_fs9.default.readFileSync(file, "utf8"));
2150
+ } catch (err) {
2151
+ throw new Error(`\u65E0\u6CD5\u8BFB\u53D6\u53D1\u5E03\u8BC1\u4E66\u767B\u8BB0 ${file}`, { cause: err });
2152
+ }
2153
+ const certs = parsed?.certs;
2154
+ if (!Array.isArray(certs)) {
2155
+ throw new Error(`\u53D1\u5E03\u8BC1\u4E66\u767B\u8BB0\u683C\u5F0F\u65E0\u6548: ${file}`);
2156
+ }
2157
+ return certs;
2158
+ }
2159
+ static writeReleaseSigningCerts(certs) {
2160
+ const root = this.resolveReleaseSigningRoot();
2161
+ import_fs9.default.mkdirSync(root, { recursive: true, mode: 448 });
2162
+ const file = this.releaseSigningIndexPath();
2163
+ const tmp = import_path7.default.join(root, `.index-${import_crypto2.default.randomBytes(8).toString("hex")}.json`);
2164
+ import_fs9.default.writeFileSync(tmp, `${JSON.stringify({ certs }, null, 2)}
2165
+ `, { mode: 384 });
2166
+ try {
2167
+ if (import_fs9.default.existsSync(file)) import_fs9.default.rmSync(file);
2168
+ import_fs9.default.renameSync(tmp, file);
2169
+ } catch (err) {
2170
+ try {
2171
+ import_fs9.default.copyFileSync(tmp, file);
2172
+ import_fs9.default.rmSync(tmp, { force: true });
2173
+ } catch {
2174
+ import_fs9.default.rmSync(tmp, { force: true });
2175
+ throw err;
2176
+ }
2177
+ }
2178
+ }
2179
+ /**
2180
+ * 读取本机发布私钥登记。文件不存在时返回空列表。
2181
+ * 不扫描其他目录。
2182
+ */
2183
+ static listReleaseSigning() {
2184
+ const rootDir = this.resolveReleaseSigningRoot();
2185
+ const certs = this.readReleaseSigningCerts().map((entry) => ({
2186
+ ...entry,
2187
+ p12Exists: !!entry.p12Path && import_fs9.default.existsSync(entry.p12Path) && import_fs9.default.statSync(entry.p12Path).isFile()
2188
+ }));
2189
+ return { rootDir, certs };
2190
+ }
2191
+ /**
2192
+ * 把发布 .p12、别名、证书 id 和已加密密码写入用户目录。
2193
+ * `.p12` 不在该目录时复制进去;`csr-generate --out-dir` 落在此根目录下的临时子目录会改放到 `<certId>/`。
2194
+ * 明文密码只用于当场加密,不进入 index.json。
2195
+ */
2196
+ static saveReleaseSigning(options) {
2197
+ const certId = options.certId.trim();
2198
+ if (!this.CERT_ID_RE.test(certId)) {
2199
+ throw new Error(`invalid certId: ${options.certId}`);
2200
+ }
2201
+ const certName = options.certName.trim();
2202
+ const alias = options.alias.trim();
2203
+ if (!certName || !alias) {
2204
+ throw new Error("certName and alias are required");
2205
+ }
2206
+ const pwd = options.pwd ?? "";
2207
+ const hasPwd = pwd.length > 0;
2208
+ const hasHex = !!options.keyPassword && !!options.storePassword;
2209
+ if (hasPwd === hasHex) {
2210
+ throw new Error("pass either --pwd, or both --key-password and --store-password");
2211
+ }
2212
+ if (!hasPwd) {
2213
+ const hex = /^[0-9A-Fa-f]+$/;
2214
+ if (!hex.test(options.keyPassword) || !hex.test(options.storePassword)) {
2215
+ throw new Error("keyPassword and storePassword must be encrypt-pwd hex");
2216
+ }
2217
+ }
2218
+ const sourceP12 = import_path7.default.resolve(options.p12Path);
2219
+ if (!import_fs9.default.existsSync(sourceP12) || !import_fs9.default.statSync(sourceP12).isFile()) {
2220
+ throw new Error(`p12 not found: ${sourceP12}`);
2221
+ }
2222
+ const root = this.resolveReleaseSigningRoot();
2223
+ const destDir = import_path7.default.join(root, certId);
2224
+ const sourceDir = import_path7.default.dirname(sourceP12);
2225
+ const sourceMaterial = import_path7.default.join(sourceDir, "material");
2226
+ const sameDir = import_path7.default.resolve(sourceDir) === import_path7.default.resolve(destDir);
2227
+ const materialReady = import_fs9.default.existsSync(import_path7.default.join(sameDir ? destDir : sourceDir, "material")) || import_fs9.default.existsSync(import_path7.default.join(destDir, "material"));
2228
+ if (!hasPwd && !materialReady) {
2229
+ throw new Error("\u4FDD\u5B58\u5DF2\u52A0\u5BC6\u5BC6\u7801\u65F6\uFF0C.p12 \u540C\u7EA7\u5FC5\u987B\u5DF2\u6709 material/\u3002\u8BF7\u6539\u7528 --pwd\uFF0C\u6216\u8FDE\u540C material/ \u4E00\u8D77\u63D0\u4F9B\u3002");
2230
+ }
2231
+ const existing = this.readReleaseSigningCerts();
2232
+ const sourceRegistered = existing.some((entry) => entry.p12Path && this.isInside(entry.p12Path, sourceDir));
2233
+ const sourceIsDirectChild = import_path7.default.resolve(import_path7.default.dirname(sourceDir)) === import_path7.default.resolve(root);
2234
+ import_fs9.default.mkdirSync(root, { recursive: true, mode: 448 });
2235
+ let storedP12;
2236
+ let removeSource;
2237
+ if (sameDir) {
2238
+ storedP12 = sourceP12;
2239
+ } else if (sourceIsDirectChild && !sourceRegistered && !import_fs9.default.existsSync(destDir)) {
2240
+ import_fs9.default.renameSync(sourceDir, destDir);
2241
+ storedP12 = import_path7.default.join(destDir, import_path7.default.basename(sourceP12));
2242
+ } else {
2243
+ import_fs9.default.mkdirSync(destDir, { recursive: true, mode: 448 });
2244
+ storedP12 = import_path7.default.join(destDir, import_path7.default.basename(sourceP12));
2245
+ if (import_path7.default.resolve(storedP12) !== sourceP12) {
2246
+ import_fs9.default.copyFileSync(sourceP12, storedP12);
2247
+ }
2248
+ if (sourceIsDirectChild && !sourceRegistered) removeSource = sourceDir;
2249
+ }
2250
+ const destMaterial = import_path7.default.join(destDir, "material");
2251
+ if (!import_fs9.default.existsSync(destMaterial)) {
2252
+ if (import_fs9.default.existsSync(sourceMaterial)) {
2253
+ import_fs9.default.cpSync(sourceMaterial, destMaterial, { recursive: true, dereference: true });
2254
+ } else {
2255
+ this.placeMaterialBesideStore(destDir, options.configDir);
2256
+ }
2257
+ }
2258
+ if (!import_fs9.default.existsSync(destMaterial)) {
2259
+ throw new Error(`\u65E0\u6CD5\u628A\u52A0\u5BC6\u6750\u6599\u653E\u5230 ${destDir}`);
2260
+ }
2261
+ const encrypted = hasPwd ? this.encryptPassword(pwd, destDir) : { keyPassword: options.keyPassword, storePassword: options.storePassword };
2262
+ const record = {
2263
+ certId,
2264
+ certName,
2265
+ alias,
2266
+ p12Path: storedP12,
2267
+ keyPassword: encrypted.keyPassword,
2268
+ storePassword: encrypted.storePassword,
2269
+ materialPath: destMaterial
2270
+ };
2271
+ this.writeReleaseSigningCerts([...existing.filter((entry) => entry.certId !== certId), record]);
2272
+ if (removeSource && import_fs9.default.existsSync(removeSource)) {
2273
+ import_fs9.default.rmSync(removeSource, { recursive: true, force: true });
2274
+ }
2275
+ return record;
2276
+ }
1758
2277
  };
1759
2278
 
1760
2279
  // src/services/testing.ts
@@ -1766,7 +2285,7 @@ var TestingService = class {
1766
2285
  /** 新建测试版本 */
1767
2286
  static async createVersion(req) {
1768
2287
  const { appId, ...body } = req;
1769
- const response = await agcClient.post(
2288
+ const response = await connectApiClient.post(
1770
2289
  "/api/publish/v2/test/app/version",
1771
2290
  {
1772
2291
  releaseType: body.releaseType ?? 6,
@@ -1780,7 +2299,7 @@ var TestingService = class {
1780
2299
  }
1781
2300
  /** 查询上架自检报告信息 */
1782
2301
  static async getDetectReport(req) {
1783
- const response = await agcClient.get(
2302
+ const response = await connectApiClient.get(
1784
2303
  "/api/publish/v2/test/app/version/detect-report",
1785
2304
  { params: { appId: req.appId, versionId: req.versionId } }
1786
2305
  );
@@ -1789,7 +2308,7 @@ var TestingService = class {
1789
2308
  /** 添加软件包到测试版本 */
1790
2309
  static async addPackage(req) {
1791
2310
  const { appId, ...body } = req;
1792
- const response = await agcClient.post(
2311
+ const response = await connectApiClient.post(
1793
2312
  "/api/publish/v2/test/version/pkg",
1794
2313
  body,
1795
2314
  { params: { appId } }
@@ -1799,7 +2318,7 @@ var TestingService = class {
1799
2318
  /** 更新测试版本(绑包、群组、多语言等) */
1800
2319
  static async updateVersion(req) {
1801
2320
  const { appId, ...body } = req;
1802
- const response = await agcClient.put(
2321
+ const response = await connectApiClient.put(
1803
2322
  "/api/publish/v2/test/app/version",
1804
2323
  body,
1805
2324
  { params: { appId } }
@@ -1809,7 +2328,7 @@ var TestingService = class {
1809
2328
  /** 更新测试生效版本 */
1810
2329
  static async releaseVersion(req) {
1811
2330
  const { appId, ...body } = req;
1812
- const response = await agcClient.put(
2331
+ const response = await connectApiClient.put(
1813
2332
  "/api/publish/v2/test/version/release",
1814
2333
  body,
1815
2334
  { params: { appId } }
@@ -1819,7 +2338,7 @@ var TestingService = class {
1819
2338
  /** 更新有效期内的测试版本时间和额度信息 */
1820
2339
  static async updateOpenTest(req) {
1821
2340
  const { appId, ...body } = req;
1822
- const response = await agcClient.put(
2341
+ const response = await connectApiClient.put(
1823
2342
  "/api/publish/v2/test/version/open-test",
1824
2343
  body,
1825
2344
  { params: { appId } }
@@ -1828,7 +2347,7 @@ var TestingService = class {
1828
2347
  }
1829
2348
  /** 提交测试版本 */
1830
2349
  static async submitVersion(req) {
1831
- const response = await agcClient.post(
2350
+ const response = await connectApiClient.post(
1832
2351
  "/api/publish/v2/test/app/version/submit",
1833
2352
  { versionId: req.versionId },
1834
2353
  { params: { appId: req.appId } }
@@ -1837,7 +2356,7 @@ var TestingService = class {
1837
2356
  }
1838
2357
  /** 停止测试版本 */
1839
2358
  static async stopVersion(req) {
1840
- const response = await agcClient.post(
2359
+ const response = await connectApiClient.post(
1841
2360
  "/api/publish/v2/test/version/stop",
1842
2361
  { versionId: req.versionId },
1843
2362
  { params: { appId: req.appId } }
@@ -1846,7 +2365,7 @@ var TestingService = class {
1846
2365
  }
1847
2366
  /** 删除测试版本 */
1848
2367
  static async deleteVersion(req) {
1849
- const response = await agcClient.delete(
2368
+ const response = await connectApiClient.delete(
1850
2369
  "/api/publish/v2/test/app/version",
1851
2370
  { params: { appId: req.appId, versionId: req.versionId } }
1852
2371
  );
@@ -1856,7 +2375,7 @@ var TestingService = class {
1856
2375
  /** 新增测试群组 */
1857
2376
  static async addGroup(req) {
1858
2377
  const { appId, ...body } = req;
1859
- const response = await agcClient.post(
2378
+ const response = await connectApiClient.post(
1860
2379
  "/api/app-test/v1/test-group",
1861
2380
  body,
1862
2381
  { headers: appIdHeaders2(appId) }
@@ -1869,7 +2388,7 @@ var TestingService = class {
1869
2388
  if (req.groupType !== void 0) params.groupType = req.groupType;
1870
2389
  if (req.current !== void 0) params.current = req.current;
1871
2390
  if (req.pageSize !== void 0) params.pageSize = req.pageSize;
1872
- const response = await agcClient.get(
2391
+ const response = await connectApiClient.get(
1873
2392
  "/api/app-test/v1/test-group/list",
1874
2393
  { params, headers: appIdHeaders2(req.appId) }
1875
2394
  );
@@ -1877,7 +2396,7 @@ var TestingService = class {
1877
2396
  }
1878
2397
  /** 删除测试群组 */
1879
2398
  static async deleteGroup(req) {
1880
- const response = await agcClient.delete(
2399
+ const response = await connectApiClient.delete(
1881
2400
  "/api/app-test/v1/publish-api/test-group",
1882
2401
  { params: { groupId: req.groupId }, headers: appIdHeaders2(req.appId) }
1883
2402
  );
@@ -1886,7 +2405,7 @@ var TestingService = class {
1886
2405
  /** 修改测试群组 */
1887
2406
  static async editGroup(req) {
1888
2407
  const { appId, ...body } = req;
1889
- const response = await agcClient.put(
2408
+ const response = await connectApiClient.put(
1890
2409
  "/api/app-test/v2/test-group",
1891
2410
  body,
1892
2411
  { headers: appIdHeaders2(appId) }
@@ -1898,7 +2417,7 @@ var TestingService = class {
1898
2417
  const params = {};
1899
2418
  if (req.current !== void 0) params.current = req.current;
1900
2419
  if (req.pageSize !== void 0) params.pageSize = req.pageSize;
1901
- const response = await agcClient.get(
2420
+ const response = await connectApiClient.get(
1902
2421
  "/api/app-test/v1/test-user",
1903
2422
  {
1904
2423
  params,
@@ -1911,7 +2430,7 @@ var TestingService = class {
1911
2430
  /** 新增测试群组成员 */
1912
2431
  static async addGroupUser(req) {
1913
2432
  const { appId, ...body } = req;
1914
- const response = await agcClient.post(
2433
+ const response = await connectApiClient.post(
1915
2434
  "/api/publish/v2/test/user",
1916
2435
  body,
1917
2436
  { headers: appIdHeaders2(appId) }
@@ -1921,7 +2440,7 @@ var TestingService = class {
1921
2440
  /** 删除测试群组成员 */
1922
2441
  static async deleteGroupUser(req) {
1923
2442
  const { appId, ...body } = req;
1924
- const response = await agcClient.delete(
2443
+ const response = await connectApiClient.delete(
1925
2444
  "/api/publish/v2/test/user",
1926
2445
  { data: body, headers: appIdHeaders2(appId) }
1927
2446
  );
@@ -1930,7 +2449,7 @@ var TestingService = class {
1930
2449
  /** 发送邀请测试通知 */
1931
2450
  static async notifyUsers(req) {
1932
2451
  const { appId, ...body } = req;
1933
- const response = await agcClient.post(
2452
+ const response = await connectApiClient.post(
1934
2453
  "/api/publish/v2/test/user/action/notify",
1935
2454
  body,
1936
2455
  { headers: appIdHeaders2(appId) }
@@ -1941,7 +2460,7 @@ var TestingService = class {
1941
2460
  /** 生成邀请码 */
1942
2461
  static async createInviteCode(req) {
1943
2462
  const { appId, ...body } = req;
1944
- const response = await agcClient.post(
2463
+ const response = await connectApiClient.post(
1945
2464
  "/api/app-test/v1/invitation-code",
1946
2465
  body,
1947
2466
  { headers: appIdHeaders2(appId) }
@@ -1950,7 +2469,7 @@ var TestingService = class {
1950
2469
  }
1951
2470
  /** 查询测试群组邀请码 */
1952
2471
  static async getInviteCode(req) {
1953
- const response = await agcClient.get(
2472
+ const response = await connectApiClient.get(
1954
2473
  "/api/app-test/v1/test-group/invitation-code",
1955
2474
  { params: { groupId: req.groupId }, headers: appIdHeaders2(req.appId) }
1956
2475
  );
@@ -1958,7 +2477,7 @@ var TestingService = class {
1958
2477
  }
1959
2478
  /** 停止邀请码 */
1960
2479
  static async stopInviteCode(req) {
1961
- const response = await agcClient.post(
2480
+ const response = await connectApiClient.post(
1962
2481
  "/api/app-test/v1/invitation-code/action/stop",
1963
2482
  { invitationCodeId: req.invitationCodeId },
1964
2483
  { headers: appIdHeaders2(req.appId) }
@@ -1967,7 +2486,7 @@ var TestingService = class {
1967
2486
  }
1968
2487
  /** 删除邀请码 */
1969
2488
  static async deleteInviteCode(req) {
1970
- const response = await agcClient.delete(
2489
+ const response = await connectApiClient.delete(
1971
2490
  "/api/app-test/v1/invitation-code",
1972
2491
  { params: { invitationCodeId: req.invitationCodeId }, headers: appIdHeaders2(req.appId) }
1973
2492
  );
@@ -1977,7 +2496,7 @@ var TestingService = class {
1977
2496
  /** 创建公开链接 */
1978
2497
  static async createPublicLink(req) {
1979
2498
  const { appId, ...body } = req;
1980
- const response = await agcClient.post(
2499
+ const response = await connectApiClient.post(
1981
2500
  "/api/app-test/v1/test-group/public-link",
1982
2501
  body,
1983
2502
  { headers: appIdHeaders2(appId) }
@@ -1987,7 +2506,7 @@ var TestingService = class {
1987
2506
  /** 修改公开链接 */
1988
2507
  static async editPublicLink(req) {
1989
2508
  const { appId, ...body } = req;
1990
- const response = await agcClient.put(
2509
+ const response = await connectApiClient.put(
1991
2510
  "/api/app-test/v1/test-group/public-link",
1992
2511
  body,
1993
2512
  { headers: appIdHeaders2(appId) }
@@ -1996,7 +2515,7 @@ var TestingService = class {
1996
2515
  }
1997
2516
  /** 查询公开链接 */
1998
2517
  static async queryPublicLink(req) {
1999
- const response = await agcClient.get(
2518
+ const response = await connectApiClient.get(
2000
2519
  "/api/app-test/v1/test-group/public-link",
2001
2520
  { params: { groupId: req.groupId }, headers: appIdHeaders2(req.appId) }
2002
2521
  );
@@ -2006,7 +2525,7 @@ var TestingService = class {
2006
2525
  /** 查询测试问题反馈维度 */
2007
2526
  static async queryFeedbackDimension(req) {
2008
2527
  const { appId, ...body } = req;
2009
- const response = await agcClient.post(
2528
+ const response = await connectApiClient.post(
2010
2529
  "/api/app-test/v1/mgmt/tester-feedback-dimension/action/query",
2011
2530
  body,
2012
2531
  { headers: appIdHeaders2(appId) }
@@ -2016,7 +2535,7 @@ var TestingService = class {
2016
2535
  /** 查询测试问题反馈 */
2017
2536
  static async queryFeedback(req) {
2018
2537
  const { appId, ...body } = req;
2019
- const response = await agcClient.post(
2538
+ const response = await connectApiClient.post(
2020
2539
  "/api/app-test/v1/mgmt/tester-feedback/action/query",
2021
2540
  body,
2022
2541
  { headers: appIdHeaders2(appId) }
@@ -2026,7 +2545,7 @@ var TestingService = class {
2026
2545
  /** 删除测试问题反馈 */
2027
2546
  static async deleteFeedback(req) {
2028
2547
  const { appId, ...body } = req;
2029
- const response = await agcClient.delete(
2548
+ const response = await connectApiClient.delete(
2030
2549
  "/api/app-test/v1/mgmt/tester-feedback",
2031
2550
  { data: body, headers: appIdHeaders2(appId) }
2032
2551
  );
@@ -2037,11 +2556,11 @@ var TestingService = class {
2037
2556
  // src/cli/index.ts
2038
2557
  var program = new import_commander.Command();
2039
2558
  function readCliVersion() {
2040
- if ("1.1.6") {
2041
- return "1.1.6";
2559
+ if ("1.1.9") {
2560
+ return "1.1.9";
2042
2561
  }
2043
2562
  try {
2044
- const pkgPath = import_path7.default.join(__dirname, "..", "package.json");
2563
+ const pkgPath = import_path8.default.join(__dirname, "..", "package.json");
2045
2564
  const pkg = JSON.parse(fs9.readFileSync(pkgPath, "utf8"));
2046
2565
  if (pkg.version) return pkg.version;
2047
2566
  } catch {
@@ -2050,7 +2569,7 @@ function readCliVersion() {
2050
2569
  }
2051
2570
  program.name("connect-api-cli").description("HarmonyOS \u5F00\u53D1\u8005\u4E2D\u5FC3 API CLI Tool").version(readCliVersion());
2052
2571
  var authCmd = program.command("auth").description("Authentication management");
2053
- authCmd.command("login").description("Login and cache token (client_credentials / service_account JWT / OAuth browser)").action(async () => {
2572
+ authCmd.command("login").description("Login and cache token (default: local DevEco login, then browser OAuth)").action(async () => {
2054
2573
  try {
2055
2574
  const token = await AuthManager.login();
2056
2575
  console.log("Successfully logged in. Token generated and cached.");
@@ -2060,25 +2579,30 @@ authCmd.command("login").description("Login and cache token (client_credentials
2060
2579
  }
2061
2580
  });
2062
2581
  authCmd.command("status").description("Show current auth mode and cached token status").action(() => {
2063
- let cfg;
2582
+ let authStatus;
2064
2583
  try {
2065
- cfg = getConfig();
2584
+ authStatus = AuthManager.getStatus();
2066
2585
  } catch (e) {
2067
2586
  reportFailure(`Auth status unavailable: ${e.message}`);
2068
2587
  process.exitCode = 1;
2069
2588
  return;
2070
2589
  }
2071
- const status = AuthManager.getStatus();
2590
+ const { config: cfg, cache: status } = authStatus;
2072
2591
  console.log(`Auth mode: ${cfg.authMode}`);
2073
2592
  if (cfg.authMode === "service_account") {
2074
2593
  console.log(`Key ID: ${cfg.clientId}`);
2075
2594
  if (cfg.serviceAccount) {
2076
2595
  console.log(`Credentials: ${cfg.serviceAccount.credentialsPath}`);
2077
2596
  }
2597
+ } else if (cfg.authMode === "deveco") {
2598
+ console.log(`Token source: ${cfg.deveco?.source ?? "cli"}`);
2599
+ if (cfg.deveco?.authDir) {
2600
+ console.log(`Auth dir: ${cfg.deveco.authDir}`);
2601
+ }
2078
2602
  } else {
2079
2603
  console.log(`Client ID: ${cfg.clientId}`);
2080
2604
  }
2081
- if (cfg.authMode === "oauth") {
2605
+ if (cfg.authMode === "oauth" || cfg.authMode === "deveco") {
2082
2606
  const teamId = cfg.teamId || getCachedOAuthTeamId();
2083
2607
  console.log(`Team ID: ${teamId || "(auto on first API call; or set AGC_TEAM_ID)"}`);
2084
2608
  }
@@ -2086,7 +2610,7 @@ authCmd.command("status").description("Show current auth mode and cached token s
2086
2610
  const remaining = Math.max(0, Math.floor((status.expiresAt - Date.now()) / 1e3));
2087
2611
  console.log("Token cached: yes");
2088
2612
  console.log(`Expires in: ${Math.floor(remaining / 60)}m ${remaining % 60}s`);
2089
- const autoRefresh = cfg.authMode === "oauth" && !!status.refreshToken || cfg.authMode === "service_account" || cfg.authMode === "client_credentials";
2613
+ const autoRefresh = cfg.authMode === "oauth" && !!status.refreshToken || cfg.authMode === "service_account" || cfg.authMode === "client_credentials" || cfg.authMode === "deveco";
2090
2614
  console.log(`Auto-refresh: ${autoRefresh ? "enabled" : "n/a"}`);
2091
2615
  } else {
2092
2616
  console.log("Token cached: no");
@@ -2483,7 +3007,7 @@ uploadCmd.command("file").description("Upload a file (APP, APK, images, etc.); .
2483
3007
  releaseType,
2484
3008
  chineseMainlandFlag: options.chineseMainland ? Number(options.chineseMainland) : void 0
2485
3009
  });
2486
- const ext = import_path7.default.extname(uploaded.fileName).toLowerCase();
3010
+ const ext = import_path8.default.extname(uploaded.fileName).toLowerCase();
2487
3011
  const shouldBind = options.bind !== false && ext === ".app" && releaseType !== 6;
2488
3012
  if (!shouldBind) {
2489
3013
  console.log(JSON.stringify({
@@ -2534,14 +3058,39 @@ provisionCmd.command("csr-generate").description("Generate a new keypair and CSR
2534
3058
  reportFailure("CSR generation failed:", e.message);
2535
3059
  }
2536
3060
  });
2537
- provisionCmd.command("encrypt-pwd").description("\u52A0\u5BC6 P12 \u5BC6\u7801\uFF0C\u751F\u6210 build-profile.json5 \u6240\u9700\u7684 keyPassword / storePassword").requiredOption("--pwd <password>", "P12 \u5BC6\u7801\u660E\u6587").option("--config-dir <configDir>", "DevEco Studio \u914D\u7F6E\u76EE\u5F55 (\u9ED8\u8BA4 ~/.ohos/config)").action(async (options) => {
3061
+ provisionCmd.command("encrypt-pwd").description("\u52A0\u5BC6 P12 \u5BC6\u7801\uFF0C\u751F\u6210 build-profile.json5 \u6240\u9700\u7684 keyPassword / storePassword").requiredOption("--pwd <password>", "P12 \u5BC6\u7801\u660E\u6587").option("--config-dir <configDir>", "\u52A0\u5BC6\u6750\u6599\u76EE\u5F55 (\u9ED8\u8BA4 ~/.ohos/config\uFF1B\u6CA1\u6709 material/ \u65F6\u81EA\u52A8\u751F\u6210\uFF0C\u5DF2\u6709\u76EE\u5F55\u4E0D\u8986\u76D6)").option("--beside <p12Path>", "\u590D\u7528\u5DF2\u6709 .p12\uFF1A\u7528\u5176\u540C\u7EA7 material/ \u52A0\u5BC6\uFF1B\u6CA1\u6709\u5219\u628A\u6750\u6599\u653E\u5230\u540C\u7EA7\u4E14\u4E0D\u8986\u76D6").action(async (options) => {
2538
3062
  try {
2539
- const res = SignService.encryptPassword(options.pwd, options.configDir);
3063
+ const res = options.beside ? SignService.encryptPasswordBeside(options.pwd, options.beside, options.configDir) : SignService.encryptPassword(options.pwd, options.configDir);
2540
3064
  printResult(res);
2541
3065
  } catch (e) {
2542
3066
  reportFailure("\u52A0\u5BC6\u5931\u8D25:", e.message);
2543
3067
  }
2544
3068
  });
3069
+ provisionCmd.command("release-list").description("\u5217\u51FA\u7528\u6237\u76EE\u5F55 ~/.ohos/release-signing \u4E2D\u5DF2\u767B\u8BB0\u7684\u53D1\u5E03\u79C1\u94A5\u3002\u4E0D\u641C\u5176\u4ED6\u76EE\u5F55").action(() => {
3070
+ try {
3071
+ printResult(SignService.listReleaseSigning());
3072
+ } catch (e) {
3073
+ reportFailure("\u8BFB\u53D6\u53D1\u5E03\u8BC1\u4E66\u767B\u8BB0\u5931\u8D25:", e.message);
3074
+ }
3075
+ });
3076
+ provisionCmd.command("release-save").description("\u628A\u53D1\u5E03 .p12\u3001\u5BC6\u94A5\u522B\u540D\u548C\u8BC1\u4E66 id \u767B\u8BB0\u5230\u7528\u6237\u76EE\u5F55\uFF0C\u4F9B\u4EE5\u540E\u7684\u5DE5\u7A0B\u590D\u7528").requiredOption("--cert-id <certId>", "\u53D1\u5E03\u8BC1\u4E66 id").requiredOption("--cert-name <certName>", "\u53D1\u5E03\u8BC1\u4E66\u540D\u79F0").requiredOption("--alias <alias>", "p12 \u5BC6\u94A5\u522B\u540D").requiredOption("--p12 <p12Path>", "\u5DF2\u6709 .p12 \u8DEF\u5F84").option("--pwd <pwd>", "P12 \u5BC6\u7801\u660E\u6587\u3002\u4E0E --key-password / --store-password \u4E8C\u9009\u4E00\uFF0C\u4E0D\u5199\u5165\u767B\u8BB0\u6587\u4EF6").option("--key-password <hex>", "\u5DF2\u52A0\u5BC6\u7684 keyPassword").option("--store-password <hex>", "\u5DF2\u52A0\u5BC6\u7684 storePassword").option("--config-dir <configDir>", "\u540C\u7EA7\u8FD8\u6CA1\u6709 material/ \u65F6\u4F7F\u7528\u7684\u52A0\u5BC6\u6750\u6599\u76EE\u5F55").action((options) => {
3077
+ try {
3078
+ const res = SignService.saveReleaseSigning({
3079
+ certId: options.certId,
3080
+ certName: options.certName,
3081
+ alias: options.alias,
3082
+ p12Path: options.p12,
3083
+ pwd: options.pwd,
3084
+ keyPassword: options.keyPassword,
3085
+ storePassword: options.storePassword,
3086
+ configDir: options.configDir
3087
+ });
3088
+ console.error("Release signing saved.");
3089
+ printResult(res);
3090
+ } catch (e) {
3091
+ reportFailure("\u4FDD\u5B58\u53D1\u5E03\u8BC1\u4E66\u767B\u8BB0\u5931\u8D25:", e.message);
3092
+ }
3093
+ });
2545
3094
  provisionCmd.command("cert-create").description("Create a certificate").requiredOption("--csr <csrFile>", "Path to CSR file").requiredOption("--cert-name <certName>", "Certificate name").requiredOption("--cert-type <certType>", "Certificate type (1: debug, 2: release, 3: in-house, 4: binary)").action(async (options) => {
2546
3095
  try {
2547
3096
  const csrContent = fs9.readFileSync(options.csr, "utf8");