connect-api-cli 1.1.8 → 1.1.10

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, "_");
@@ -325,8 +375,8 @@ async function resolveOAuthTeamId(cfg, accessToken) {
325
375
  if (cfg.teamId) {
326
376
  return cfg.teamId;
327
377
  }
328
- if (cachedTeamId !== void 0) {
329
- return cachedTeamId || void 0;
378
+ if (cachedTeamId) {
379
+ return cachedTeamId;
330
380
  }
331
381
  const persisted = readPersistedTeamId();
332
382
  if (persisted) {
@@ -344,26 +394,18 @@ async function resolveOAuthTeamId(cfg, accessToken) {
344
394
  maxRedirects: 0
345
395
  }
346
396
  );
347
- const teams = res.data.teams || [];
348
397
  if (res.data.ret && res.data.ret.code !== 0) {
349
398
  throw new Error(
350
399
  `Failed to list teams for OAuth teamId: ${res.data.ret.msg || JSON.stringify(res.data.ret)}`
351
400
  );
352
401
  }
353
- if (teams.length === 0) {
354
- cachedTeamId = null;
402
+ const firstTeam = res.data.teams?.[0];
403
+ if (!firstTeam?.id) {
355
404
  throw new Error("OAuth account has no teams. Cannot set teamId for API calls.");
356
405
  }
357
- if (teams.length === 1) {
358
- cachedTeamId = teams[0].id;
359
- writePersistedTeamId(cachedTeamId);
360
- return cachedTeamId;
361
- }
362
- cachedTeamId = null;
363
- const preview = teams.slice(0, 8).map((t) => `${t.id}${t.name ? `(${t.name})` : ""}`).join(", ");
364
- throw new Error(
365
- `Multiple teams found (${teams.length}). Set AGC_TEAM_ID to one of: ${preview}`
366
- );
406
+ cachedTeamId = firstTeam.id;
407
+ writePersistedTeamId(cachedTeamId);
408
+ return cachedTeamId;
367
409
  }
368
410
  function getCachedOAuthTeamId() {
369
411
  if (cachedTeamId) return cachedTeamId;
@@ -373,25 +415,197 @@ function clearOAuthTeamIdCache() {
373
415
  cachedTeamId = void 0;
374
416
  }
375
417
 
418
+ // src/core/deveco-token.ts
419
+ var import_crypto = require("crypto");
420
+ var import_fs4 = require("fs");
421
+ var import_os2 = require("os");
422
+ var import_path3 = require("path");
423
+ var ALGORITHM = "aes-256-gcm";
424
+ var KEY_LENGTH = 32;
425
+ var KEK_VERSIONS = ["kek-v1", "kek-v2", "kek-v3"];
426
+ var CLI_SOURCE_ALIASES = ["cli", "deveco", "deveco-cli"];
427
+ var SOURCE_APP_NAMES = {
428
+ "deveco-code": "deveco"
429
+ };
430
+ function decryptAesGcm(ciphertext, key, iv, authTag) {
431
+ const decipher = (0, import_crypto.createDecipheriv)(ALGORITHM, key, iv);
432
+ decipher.setAuthTag(authTag);
433
+ return Buffer.concat([decipher.update(ciphertext), decipher.final()]);
434
+ }
435
+ function readJson(filePath) {
436
+ return JSON.parse((0, import_fs4.readFileSync)(filePath, "utf8"));
437
+ }
438
+ function requireFile(filePath, label) {
439
+ try {
440
+ return (0, import_fs4.readFileSync)(filePath);
441
+ } catch (err) {
442
+ const code = err.code;
443
+ if (code === "ENOENT") {
444
+ throw new Error(`\u627E\u4E0D\u5230 ${label}: ${filePath}`);
445
+ }
446
+ if (code === "EACCES" || code === "EPERM") {
447
+ throw new Error(`\u65E0\u6743\u9650\u8BFB\u53D6 ${label}: ${filePath}`);
448
+ }
449
+ throw err;
450
+ }
451
+ }
452
+ function loadKek(kekId, keysDir) {
453
+ if (!KEK_VERSIONS.includes(kekId)) {
454
+ throw new Error(`\u975E\u6CD5 kekId: ${kekId}\uFF08\u671F\u671B ${KEK_VERSIONS.join("/")}\uFF09`);
455
+ }
456
+ const rootKeyPath = (0, import_path3.resolve)((0, import_path3.join)(keysDir, `${kekId}.bin`));
457
+ const keysDirBase = (0, import_path3.resolve)(keysDir);
458
+ if (!rootKeyPath.startsWith(keysDirBase)) {
459
+ throw new Error("kekId \u89E3\u6790\u7ED3\u679C\u8D85\u51FA keys \u76EE\u5F55\u8303\u56F4");
460
+ }
461
+ const kek = requireFile(rootKeyPath, "KEK \u6839\u5BC6\u94A5");
462
+ if (kek.length !== KEY_LENGTH) {
463
+ throw new Error(`KEK \u957F\u5EA6\u5F02\u5E38: ${kek.length} \u5B57\u8282\uFF08\u671F\u671B ${KEY_LENGTH}\uFF09`);
464
+ }
465
+ return kek;
466
+ }
467
+ function decryptToken(tokenDir, keysDir) {
468
+ const blob = readJson((0, import_path3.join)(tokenDir, "token.enc"));
469
+ if (blob.algorithm !== ALGORITHM) {
470
+ throw new Error(`\u672A\u77E5\u7B97\u6CD5: ${blob.algorithm}`);
471
+ }
472
+ if (!blob.ciphertext || !blob.iv || !blob.authTag) {
473
+ throw new Error(`token.enc \u683C\u5F0F\u5F02\u5E38\uFF08\u7F3A\u5C11 ciphertext/iv/authTag\uFF09: ${(0, import_path3.join)(tokenDir, "token.enc")}`);
474
+ }
475
+ const wrapped = readJson((0, import_path3.join)(tokenDir, "token.dek"));
476
+ if (!wrapped.encryptedDek || !wrapped.iv || !wrapped.authTag) {
477
+ throw new Error(`token.dek \u683C\u5F0F\u5F02\u5E38\uFF08\u7F3A\u5C11 encryptedDek/iv/authTag\uFF09: ${(0, import_path3.join)(tokenDir, "token.dek")}`);
478
+ }
479
+ const kek = loadKek(wrapped.kekId, keysDir);
480
+ const dek = decryptAesGcm(
481
+ Buffer.from(wrapped.encryptedDek, "base64"),
482
+ kek,
483
+ Buffer.from(wrapped.iv, "base64"),
484
+ Buffer.from(wrapped.authTag, "base64")
485
+ );
486
+ if (dek.length !== KEY_LENGTH) {
487
+ throw new Error(`DEK \u957F\u5EA6\u5F02\u5E38: ${dek.length} \u5B57\u8282\uFF08\u671F\u671B ${KEY_LENGTH}\uFF09`);
488
+ }
489
+ return decryptAesGcm(
490
+ Buffer.from(blob.ciphertext, "base64"),
491
+ dek,
492
+ Buffer.from(blob.iv, "base64"),
493
+ Buffer.from(blob.authTag, "base64")
494
+ ).toString("utf8");
495
+ }
496
+ function extractJwt(plaintext) {
497
+ let jwt = plaintext;
498
+ try {
499
+ const parsed = JSON.parse(plaintext);
500
+ if (parsed && typeof parsed.access_token === "string") {
501
+ jwt = parsed.access_token;
502
+ }
503
+ } catch {
504
+ }
505
+ const parts = jwt.split(".");
506
+ if (parts.length !== 3) {
507
+ 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");
508
+ }
509
+ try {
510
+ const payload = JSON.parse(Buffer.from(parts[1], "base64url").toString("utf8"));
511
+ if (typeof payload.exp === "number") {
512
+ return { jwt, expMs: payload.exp * 1e3 };
513
+ }
514
+ } catch {
515
+ }
516
+ return { jwt };
517
+ }
518
+ function configHome() {
519
+ return process.env.XDG_CONFIG_HOME || (0, import_path3.join)((0, import_os2.homedir)(), ".config");
520
+ }
521
+ function candidatesFor(source) {
522
+ const home = (0, import_os2.homedir)();
523
+ if (CLI_SOURCE_ALIASES.includes(source)) {
524
+ if (process.env.DEVECO_CLI_AUTH_SOURCE?.trim() === "deveco-code") {
525
+ return candidatesFor("deveco-code").map((c) => ({
526
+ ...c,
527
+ source,
528
+ via: "DEVECO_CLI_AUTH_SOURCE=deveco-code"
529
+ }));
530
+ }
531
+ return [
532
+ {
533
+ source,
534
+ tokenDir: process.env.DEVECO_CLI_DATA_DIR || (0, import_path3.join)(home, ".config", "deveco-cli"),
535
+ keysDir: (0, import_path3.join)(home, ".local", "share", "deveco-cli", "keys"),
536
+ via: process.env.DEVECO_CLI_DATA_DIR ? "DEVECO_CLI_DATA_DIR" : "\u5E73\u53F0\u9ED8\u8BA4\u8DEF\u5F84"
537
+ }
538
+ ];
539
+ }
540
+ const appName = SOURCE_APP_NAMES[source];
541
+ const viaEnv = process.env.DEVECO_CODE_AUTH_DIR?.trim();
542
+ if (source === "deveco-code" && viaEnv) {
543
+ const tokenDir = (0, import_path3.resolve)(viaEnv);
544
+ return [{ source, tokenDir, keysDir: (0, import_path3.join)(tokenDir, "keys"), via: "DEVECO_CODE_AUTH_DIR" }];
545
+ }
546
+ let dirs;
547
+ if (process.platform === "win32") {
548
+ const appData = process.env.APPDATA || (0, import_path3.join)(home, "AppData", "Roaming");
549
+ dirs = [(0, import_path3.join)(appData, appName), (0, import_path3.join)(home, ".config", appName)];
550
+ } else if (process.platform === "darwin") {
551
+ dirs = [
552
+ (0, import_path3.join)(configHome(), appName),
553
+ (0, import_path3.join)(home, "Library", "Application Support", appName)
554
+ ];
555
+ } else {
556
+ dirs = [(0, import_path3.join)(configHome(), appName)];
557
+ }
558
+ return dirs.map((tokenDir) => ({
559
+ source,
560
+ tokenDir,
561
+ keysDir: (0, import_path3.join)(tokenDir, "keys"),
562
+ via: "\u5E73\u53F0\u9ED8\u8BA4\u8DEF\u5F84"
563
+ }));
564
+ }
565
+ function resolveLocation(source) {
566
+ const candidates = candidatesFor(source);
567
+ const hit = candidates.find((c) => (0, import_fs4.existsSync)((0, import_path3.join)(c.tokenDir, "token.enc")));
568
+ if (hit) {
569
+ return hit;
570
+ }
571
+ const tried = candidates.map((c) => ` - ${c.tokenDir}`).join("\n");
572
+ throw new Error(
573
+ `[${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
574
+ ${tried}`
575
+ );
576
+ }
577
+ function loadDevecoLocalToken(source, authDir) {
578
+ const location = authDir ? { source: "dir", tokenDir: authDir, keysDir: (0, import_path3.join)(authDir, "keys"), via: "AGC_DEVECO_AUTH_DIR" } : resolveLocation(source);
579
+ const plaintext = decryptToken(location.tokenDir, location.keysDir);
580
+ const { jwt, expMs } = extractJwt(plaintext);
581
+ return { jwt, expMs, location };
582
+ }
583
+
376
584
  // src/core/auth-mgr.ts
377
585
  var crypto2 = __toESM(require("crypto"));
378
586
  var http = __toESM(require("http"));
379
587
  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"));
588
+ var import_fs5 = __toESM(require("fs"));
589
+ var import_path4 = __toESM(require("path"));
590
+ var import_os3 = __toESM(require("os"));
591
+ var DEVECO_CACHE_TTL_MS = 30 * 60 * 1e3;
383
592
  var AuthManager = class {
384
- static cacheFile = import_path3.default.join(import_os2.default.homedir(), ".connect-api-cli-token.json");
593
+ static cacheFile = import_path4.default.join(import_os3.default.homedir(), ".connect-api-cli-token.json");
594
+ static pendingOAuthLogin;
385
595
  /**
386
596
  * 获取当前生效的 access token,并具备自动刷新能力:
387
597
  * - OAuth 模式:token 过期时优先用 refreshToken 自动刷新,无需重新登录
388
598
  * - client_credentials / service_account:过期后重新换取 / 重新签 JWT
599
+ * - deveco:过期后重新解密本地登录态并 refresh 换取
600
+ *
601
+ * force 跳过缓存(供 DevEco 和自动模式的 401 重试使用)。
389
602
  */
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) {
603
+ static async getAccessToken(force = false) {
604
+ const { config: config2, cache } = this.getStatus();
605
+ return this.getToken(config2, cache, force);
606
+ }
607
+ static async getToken(cfg, cache, force = false) {
608
+ if (!force && cache && cache.expiresAt > Date.now() + 5 * 60 * 1e3) {
395
609
  return cache.accessToken;
396
610
  }
397
611
  if (cfg.authMode === "oauth" && cache?.refreshToken) {
@@ -413,18 +627,31 @@ var AuthManager = class {
413
627
  this.clearCache();
414
628
  }
415
629
  }
416
- return this.acquire();
630
+ return this.acquire(cfg);
417
631
  }
418
632
  /** 登录入口:按当前认证模式获取并缓存 token */
419
633
  static async login() {
420
634
  clearOAuthTeamIdCache();
421
- return this.acquire();
635
+ return this.acquire(getConfig());
422
636
  }
423
- /** 按当前认证模式获取 token(client_credentials / service_account / oauth) */
424
- static async acquire() {
425
- const cfg = getConfig();
637
+ /** 按当前认证模式获取 token(client_credentials / service_account / oauth / deveco) */
638
+ static async acquire(cfg) {
426
639
  if (cfg.authMode === "oauth") {
427
- return this.loginOAuth();
640
+ this.pendingOAuthLogin ??= this.loginOAuth(cfg).finally(() => {
641
+ this.pendingOAuthLogin = void 0;
642
+ });
643
+ return this.pendingOAuthLogin;
644
+ }
645
+ if (cfg.authMode === "deveco") {
646
+ try {
647
+ return await this.acquireDevecoToken(cfg);
648
+ } catch (err) {
649
+ if (process.env.AGC_AUTH_MODE !== void 0) throw err;
650
+ const oauthConfig = getConfig("oauth");
651
+ const cache = this.matchingCache(oauthConfig, this.readCache());
652
+ console.error("\u65E0\u6CD5\u4F7F\u7528\u672C\u5730 DevEco \u767B\u5F55\u6001\uFF0C\u6539\u7528\u534E\u4E3A\u8D26\u53F7 OAuth\u3002");
653
+ return this.getToken(oauthConfig, cache);
654
+ }
428
655
  }
429
656
  if (cfg.authMode === "service_account") {
430
657
  if (!cfg.serviceAccount) {
@@ -455,9 +682,8 @@ var AuthManager = class {
455
682
  throw new Error(`Failed to get token: ${JSON.stringify(res.ret)}`);
456
683
  }
457
684
  /** OAuth 授权码登录:启动本地回调服务器 + 打开浏览器 */
458
- static loginOAuth() {
459
- return new Promise((resolve, reject) => {
460
- const cfg = getConfig();
685
+ static loginOAuth(cfg) {
686
+ return new Promise((resolve2, reject) => {
461
687
  const redirectUri = cfg.oauth.redirectUri;
462
688
  const port = Number(new URL(redirectUri).port || 80);
463
689
  const state = crypto2.randomBytes(32).toString("hex");
@@ -473,6 +699,7 @@ var AuthManager = class {
473
699
  }
474
700
  const token = await AuthService.getOAuthToken(code, redirectUri);
475
701
  const expiresAt = Date.now() + token.expireTime * 1e3;
702
+ clearOAuthTeamIdCache();
476
703
  this.writeCache({
477
704
  accessToken: token.accessToken,
478
705
  expiresAt,
@@ -484,7 +711,7 @@ var AuthManager = class {
484
711
  res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
485
712
  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
713
  server.close();
487
- resolve(token.accessToken);
714
+ resolve2(token.accessToken);
488
715
  } catch (err) {
489
716
  server.close();
490
717
  reject(err instanceof Error ? err : new Error(String(err)));
@@ -496,19 +723,48 @@ var AuthManager = class {
496
723
  });
497
724
  server.listen(port, () => {
498
725
  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}`);
726
+ console.error("\u8BF7\u5728\u6D4F\u89C8\u5668\u4E2D\u5B8C\u6210\u534E\u4E3A\u8D26\u53F7\u6388\u6743...");
727
+ console.error(`\u82E5\u6D4F\u89C8\u5668\u672A\u81EA\u52A8\u6253\u5F00\uFF0C\u8BF7\u8BBF\u95EE: ${authUrl}`);
501
728
  openBrowser(authUrl);
502
729
  });
503
730
  });
504
731
  }
505
- /** 查询缓存状态(供 status 命令显示) */
732
+ /**
733
+ * deveco 模式:解密本地 DevEco 工具链登录态(只读),
734
+ * 用 JWT 调 jwToken/check(refresh=true)换取 access token 并缓存。
735
+ * 服务端不返回有效期:缓存取「本地 JWT 剩余寿命」与「30 分钟上限」的较小值。
736
+ */
737
+ static async acquireDevecoToken(cfg) {
738
+ const deveco = cfg.deveco;
739
+ const local = loadDevecoLocalToken(deveco.source, deveco.authDir);
740
+ const accessToken = await AuthService.checkDevecoJwtToken(local.jwt, true);
741
+ const jwtLimit = local.expMs !== void 0 ? local.expMs - 5 * 60 * 1e3 : Infinity;
742
+ this.writeCache({
743
+ accessToken,
744
+ expiresAt: Math.min(Date.now() + DEVECO_CACHE_TTL_MS, jwtLimit),
745
+ clientId: cfg.clientId,
746
+ domain: cfg.domain,
747
+ authMode: cfg.authMode
748
+ });
749
+ return accessToken;
750
+ }
751
+ /** 默认模式回退到 OAuth 后,后续命令继续使用该 OAuth 会话。 */
506
752
  static getStatus() {
507
- return this.readCache();
753
+ const config2 = getConfig();
754
+ const cache = this.readCache();
755
+ if (process.env.AGC_AUTH_MODE === void 0 && cache?.authMode === "oauth") {
756
+ const oauthConfig = getConfig("oauth");
757
+ const oauthCache = this.matchingCache(oauthConfig, cache);
758
+ if (oauthCache) return { config: oauthConfig, cache: oauthCache };
759
+ }
760
+ return { config: config2, cache: this.matchingCache(config2, cache) };
761
+ }
762
+ static matchingCache(cfg, cache) {
763
+ return cache?.authMode === cfg.authMode && cache.clientId === cfg.clientId && cache.domain === cfg.domain ? cache : null;
508
764
  }
509
765
  static readCache() {
510
766
  try {
511
- if (import_fs4.default.existsSync(this.cacheFile)) {
767
+ if (import_fs5.default.existsSync(this.cacheFile)) {
512
768
  const data = readPrivateFile(this.cacheFile);
513
769
  return JSON.parse(data);
514
770
  }
@@ -528,8 +784,8 @@ var AuthManager = class {
528
784
  static clearCache() {
529
785
  clearOAuthTeamIdCache();
530
786
  try {
531
- if (import_fs4.default.existsSync(this.cacheFile)) {
532
- import_fs4.default.unlinkSync(this.cacheFile);
787
+ if (import_fs5.default.existsSync(this.cacheFile)) {
788
+ import_fs5.default.unlinkSync(this.cacheFile);
533
789
  return true;
534
790
  }
535
791
  return false;
@@ -552,8 +808,8 @@ function openBrowser(url) {
552
808
  var import_axios3 = __toESM(require("axios"));
553
809
 
554
810
  // src/core/request-source.ts
555
- var import_fs5 = __toESM(require("fs"));
556
- var import_path4 = __toESM(require("path"));
811
+ var import_fs6 = __toESM(require("fs"));
812
+ var import_path5 = __toESM(require("path"));
557
813
  var REQUEST_SOURCE_HEADER = "Request-Source";
558
814
  var SOURCE_TOOL_NAME_HEADER = "Source-Tool-Name";
559
815
  var SKILL_CHANNEL = "skill";
@@ -693,15 +949,15 @@ function getRequestSource() {
693
949
  return agent ? `${agent}-skill` : SKILL_CHANNEL;
694
950
  }
695
951
  function readVersion() {
696
- const fromBuild = injected(true ? "1.1.8" : void 0);
952
+ const fromBuild = injected(true ? "1.1.10" : void 0);
697
953
  if (fromBuild) return fromBuild;
698
954
  const candidates = [
699
- import_path4.default.join(__dirname, "..", "..", "package.json"),
700
- import_path4.default.join(__dirname, "..", "package.json")
955
+ import_path5.default.join(__dirname, "..", "..", "package.json"),
956
+ import_path5.default.join(__dirname, "..", "package.json")
701
957
  ];
702
958
  for (const pkgPath of candidates) {
703
959
  try {
704
- const pkg = JSON.parse(import_fs5.default.readFileSync(pkgPath, "utf8"));
960
+ const pkg = JSON.parse(import_fs6.default.readFileSync(pkgPath, "utf8"));
705
961
  if (pkg.version) return pkg.version;
706
962
  } catch {
707
963
  }
@@ -725,7 +981,7 @@ function applySourceHeaders(headers) {
725
981
  }
726
982
 
727
983
  // src/core/http.ts
728
- var agcClient = import_axios3.default.create({ maxRedirects: 0 });
984
+ var connectApiClient = import_axios3.default.create({ maxRedirects: 0 });
729
985
  function setHeader(headers, name, value) {
730
986
  if (typeof headers?.set === "function") {
731
987
  headers.set(name, value);
@@ -747,7 +1003,7 @@ function getHeader(headers, name) {
747
1003
  return headers?.[name] ?? headers?.[name.toLowerCase()];
748
1004
  }
749
1005
  function applyAuthHeaders(headers, token, cfg, force = false) {
750
- if (cfg.authMode === "oauth") {
1006
+ if (cfg.authMode === "oauth" || cfg.authMode === "deveco") {
751
1007
  deleteHeader(headers, "Authorization");
752
1008
  deleteHeader(headers, "client_id");
753
1009
  setHeader(headers, "oauth2Token", token);
@@ -761,7 +1017,7 @@ function applyAuthHeaders(headers, token, cfg, force = false) {
761
1017
  setHeader(headers, "client_id", cfg.clientId);
762
1018
  }
763
1019
  }
764
- agcClient.interceptors.request.use(async (config2) => {
1020
+ connectApiClient.interceptors.request.use(async (config2) => {
765
1021
  const cfg = getConfig();
766
1022
  if (!config2.baseURL) {
767
1023
  config2.baseURL = `https://${cfg.domain}`;
@@ -772,10 +1028,11 @@ agcClient.interceptors.request.use(async (config2) => {
772
1028
  }
773
1029
  applySourceHeaders(config2.headers);
774
1030
  applyAuthHeaders(config2.headers, token, cfg);
775
- if (cfg.authMode === "oauth" && !getHeader(config2.headers, "teamId")) {
1031
+ if ((cfg.authMode === "oauth" || cfg.authMode === "deveco") && !getHeader(config2.headers, "teamId")) {
776
1032
  const teamId = await resolveOAuthTeamId(cfg, token);
777
1033
  if (teamId) {
778
1034
  setHeader(config2.headers, "teamId", teamId);
1035
+ config2._autoTeamId = true;
779
1036
  }
780
1037
  }
781
1038
  if (config2.data !== void 0 && !getHeader(config2.headers, "Content-Type")) {
@@ -785,7 +1042,7 @@ agcClient.interceptors.request.use(async (config2) => {
785
1042
  }, (error) => {
786
1043
  return Promise.reject(error);
787
1044
  });
788
- agcClient.interceptors.response.use(
1045
+ connectApiClient.interceptors.response.use(
789
1046
  (res) => res,
790
1047
  async (err) => {
791
1048
  const original = err.config;
@@ -794,12 +1051,13 @@ agcClient.interceptors.response.use(
794
1051
  original._retry = true;
795
1052
  try {
796
1053
  const cfg = getConfig();
797
- const newToken = await AuthManager.getAccessToken();
1054
+ const newToken = await AuthManager.getAccessToken(cfg.authMode === "deveco");
798
1055
  if (!original.headers) {
799
1056
  original.headers = {};
800
1057
  }
801
1058
  applyAuthHeaders(original.headers, newToken, cfg, true);
802
- return agcClient(original);
1059
+ if (original._autoTeamId) deleteHeader(original.headers, "teamId");
1060
+ return connectApiClient(original);
803
1061
  } catch (e) {
804
1062
  return Promise.reject(err);
805
1063
  }
@@ -828,7 +1086,7 @@ function withOptionalParams(base) {
828
1086
  var PublishService = class {
829
1087
  /** 查询应用包名对应的 appid */
830
1088
  static async getAppIdList(packageName, packageTypes) {
831
- const response = await agcClient.get("/api/publish/v2/appid-list", {
1089
+ const response = await connectApiClient.get("/api/publish/v2/appid-list", {
832
1090
  params: withOptionalParams({ packageName, packageTypes })
833
1091
  });
834
1092
  return response.data;
@@ -843,14 +1101,14 @@ var PublishService = class {
843
1101
  if (req.installationFree === 0 && packageName) {
844
1102
  body.packageName = packageName;
845
1103
  }
846
- const response = projectId ? await agcClient.post("/api/publish/v3/app", body, {
1104
+ const response = projectId ? await connectApiClient.post("/api/publish/v3/app", body, {
847
1105
  params: { projectId }
848
- }) : await agcClient.post("/api/publish/v3/app", body);
1106
+ }) : await connectApiClient.post("/api/publish/v3/app", body);
849
1107
  return response.data;
850
1108
  }
851
1109
  /** 查询团队账号下的成员角色列表 */
852
1110
  static async getMembersRoleList(req) {
853
- const response = await agcClient.get(
1111
+ const response = await connectApiClient.get(
854
1112
  "/api/publish/v3/members-role-list",
855
1113
  {
856
1114
  params: {
@@ -865,7 +1123,7 @@ var PublishService = class {
865
1123
  /** 查询应用信息 */
866
1124
  static async getAppInfo(appIdOrReq, lang) {
867
1125
  const req = typeof appIdOrReq === "string" ? { appId: appIdOrReq, lang } : appIdOrReq;
868
- const response = await agcClient.get("/api/publish/v3/app-info", {
1126
+ const response = await connectApiClient.get("/api/publish/v3/app-info", {
869
1127
  params: withOptionalParams({
870
1128
  appId: req.appId,
871
1129
  lang: req.lang,
@@ -878,7 +1136,7 @@ var PublishService = class {
878
1136
  /** 更新应用基本信息 */
879
1137
  static async updateAppInfo(req) {
880
1138
  const { appId, releaseType, releasePhase, ...body } = req;
881
- const response = await agcClient.put(
1139
+ const response = await connectApiClient.put(
882
1140
  "/api/publish/v3/app-info",
883
1141
  body,
884
1142
  {
@@ -890,7 +1148,7 @@ var PublishService = class {
890
1148
  /** 更新应用语言信息 */
891
1149
  static async updateLanguageInfo(req) {
892
1150
  const { appId, releaseType, releasePhase, ...body } = req;
893
- const response = await agcClient.put(
1151
+ const response = await connectApiClient.put(
894
1152
  "/api/publish/v3/app-language-info",
895
1153
  body,
896
1154
  {
@@ -901,7 +1159,7 @@ var PublishService = class {
901
1159
  }
902
1160
  /** 删除应用语言信息 */
903
1161
  static async deleteLanguageInfo(req) {
904
- const response = await agcClient.delete(
1162
+ const response = await connectApiClient.delete(
905
1163
  "/api/publish/v2/app-language-info",
906
1164
  {
907
1165
  params: withOptionalParams({
@@ -916,7 +1174,7 @@ var PublishService = class {
916
1174
  /** 更新应用文件信息(图标/截图/视频等) */
917
1175
  static async updateAppFileInfo(req) {
918
1176
  const { appId, releaseType, releasePhase, ...body } = req;
919
- const response = await agcClient.put(
1177
+ const response = await connectApiClient.put(
920
1178
  "/api/publish/v3/app-file-info",
921
1179
  body,
922
1180
  {
@@ -928,7 +1186,7 @@ var PublishService = class {
928
1186
  /** 更新应用软件包信息(OBS 上传后上报,HarmonyOS 开发者中心才会出现记录) */
929
1187
  static async updateAppPackageInfo(req) {
930
1188
  const { appId, releaseType, releasePhase, fileName, objectId } = req;
931
- const response = await agcClient.put(
1189
+ const response = await connectApiClient.put(
932
1190
  "/api/publish/v3/app-package-info",
933
1191
  { fileName, objectId },
934
1192
  {
@@ -940,7 +1198,7 @@ var PublishService = class {
940
1198
  /** 更新版本上架时间 */
941
1199
  static async updateReleaseTime(req) {
942
1200
  const { appId, ...body } = req;
943
- const response = await agcClient.put(
1201
+ const response = await connectApiClient.put(
944
1202
  "/api/publish/v2/on-shelf-time",
945
1203
  body,
946
1204
  { params: { appId } }
@@ -950,7 +1208,7 @@ var PublishService = class {
950
1208
  /** 更新分阶段发布 */
951
1209
  static async updatePhasedRelease(req) {
952
1210
  const { appId, ...body } = req;
953
- const response = await agcClient.put(
1211
+ const response = await connectApiClient.put(
954
1212
  "/api/publish/v2/version/phased-release",
955
1213
  body,
956
1214
  { headers: appIdHeaders(appId) }
@@ -959,7 +1217,7 @@ var PublishService = class {
959
1217
  }
960
1218
  /** 查询应用软件包信息 */
961
1219
  static async getPackageInfo(req) {
962
- const response = await agcClient.get(
1220
+ const response = await connectApiClient.get(
963
1221
  "/api/publish/v2/app-package-info",
964
1222
  {
965
1223
  params: { packageId: req.packageId },
@@ -970,7 +1228,7 @@ var PublishService = class {
970
1228
  }
971
1229
  /** 查询软件包编译状态 */
972
1230
  static async getCompileStatus(req) {
973
- const response = await agcClient.get(
1231
+ const response = await connectApiClient.get(
974
1232
  "/api/publish/v3/package/compile/status",
975
1233
  { params: { appId: req.appId, pkgIds: req.pkgIds } }
976
1234
  );
@@ -979,7 +1237,7 @@ var PublishService = class {
979
1237
  /** 查询应用所有版本类型的版本列表 */
980
1238
  static async queryBriefInfoList(req) {
981
1239
  const { appId, ...body } = req;
982
- const response = await agcClient.post(
1240
+ const response = await connectApiClient.post(
983
1241
  "/api/publish/v3/version/brief-info/list",
984
1242
  body,
985
1243
  { headers: appIdHeaders(appId) }
@@ -989,7 +1247,7 @@ var PublishService = class {
989
1247
  /** 查询应用未处理的问题工单 */
990
1248
  static async queryVersionVoc(req) {
991
1249
  const { appId, ...body } = req;
992
- const response = await agcClient.post(
1250
+ const response = await connectApiClient.post(
993
1251
  "/api/publish/v1/app-voc/version-voc",
994
1252
  body,
995
1253
  { headers: appIdHeaders(appId) }
@@ -998,7 +1256,7 @@ var PublishService = class {
998
1256
  }
999
1257
  /** 查询需要上传的资质文件信息 */
1000
1258
  static async queryTagQualDependent() {
1001
- const response = await agcClient.get(
1259
+ const response = await connectApiClient.get(
1002
1260
  "/api/publish/v2/tag-qual-dependent"
1003
1261
  );
1004
1262
  return response.data;
@@ -1006,7 +1264,7 @@ var PublishService = class {
1006
1264
  /** 提交资质审核任务 */
1007
1265
  static async submitQualificationReview(req) {
1008
1266
  const { appId, ...body } = req;
1009
- const response = await agcClient.post(
1267
+ const response = await connectApiClient.post(
1010
1268
  "/api/publish/v2/qualification-review-task",
1011
1269
  body,
1012
1270
  { headers: appIdHeaders(appId) }
@@ -1015,7 +1273,7 @@ var PublishService = class {
1015
1273
  }
1016
1274
  /** 查询资质审核任务详情 */
1017
1275
  static async getQualificationReview(req) {
1018
- const response = await agcClient.get(
1276
+ const response = await connectApiClient.get(
1019
1277
  "/api/publish/v2/qualification-review-task",
1020
1278
  {
1021
1279
  params: { tagIds: req.tagIds },
@@ -1027,7 +1285,7 @@ var PublishService = class {
1027
1285
  /** 修改资质审核任务 */
1028
1286
  static async updateQualificationReview(req) {
1029
1287
  const { appId, ...body } = req;
1030
- const response = await agcClient.put(
1288
+ const response = await connectApiClient.put(
1031
1289
  "/api/publish/v2/qualification-review-task",
1032
1290
  body,
1033
1291
  { headers: appIdHeaders(appId) }
@@ -1036,7 +1294,7 @@ var PublishService = class {
1036
1294
  }
1037
1295
  /** 撤销资质审核任务 */
1038
1296
  static async cancelQualificationReview(req) {
1039
- const response = await agcClient.put(
1297
+ const response = await connectApiClient.put(
1040
1298
  "/api/publish/v2/qualification-review-task/cancel",
1041
1299
  { taskId: req.taskId },
1042
1300
  { headers: appIdHeaders(req.appId) }
@@ -1045,7 +1303,7 @@ var PublishService = class {
1045
1303
  }
1046
1304
  /** 删除资质审核任务 */
1047
1305
  static async deleteQualificationReview(req) {
1048
- const response = await agcClient.delete(
1306
+ const response = await connectApiClient.delete(
1049
1307
  "/api/publish/v2/qualification-review-task",
1050
1308
  {
1051
1309
  data: { tagIds: req.tagIds },
@@ -1057,7 +1315,7 @@ var PublishService = class {
1057
1315
  /** 新建用户协议 / 隐私政策协议(body.type 区分) */
1058
1316
  static async createAgreement(req) {
1059
1317
  const { appId, ...body } = req;
1060
- const response = await agcClient.post(
1318
+ const response = await connectApiClient.post(
1061
1319
  "/api/publish/v2/agreement",
1062
1320
  body,
1063
1321
  { headers: appIdHeaders(appId) }
@@ -1067,7 +1325,7 @@ var PublishService = class {
1067
1325
  /** 查询用户协议 / 隐私政策协议列表(body.type 区分) */
1068
1326
  static async listAgreements(req) {
1069
1327
  const { appId, ...body } = req;
1070
- const response = await agcClient.post(
1328
+ const response = await connectApiClient.post(
1071
1329
  "/api/publish/v2/agreement/list",
1072
1330
  body,
1073
1331
  { headers: appIdHeaders(appId) }
@@ -1077,7 +1335,7 @@ var PublishService = class {
1077
1335
  /** 更新用户协议 / 隐私政策协议 */
1078
1336
  static async updateAgreement(req) {
1079
1337
  const { appId, ...body } = req;
1080
- const response = await agcClient.put(
1338
+ const response = await connectApiClient.put(
1081
1339
  "/api/publish/v2/agreement",
1082
1340
  body,
1083
1341
  { headers: appIdHeaders(appId) }
@@ -1087,7 +1345,7 @@ var PublishService = class {
1087
1345
  /** 提交隐私政策协议 */
1088
1346
  static async submitPrivacyAgreement(req) {
1089
1347
  const { appId, ...body } = req;
1090
- const response = await agcClient.put(
1348
+ const response = await connectApiClient.put(
1091
1349
  "/api/publish/v2/agreement/submit",
1092
1350
  body,
1093
1351
  { headers: appIdHeaders(appId) }
@@ -1097,7 +1355,7 @@ var PublishService = class {
1097
1355
  /** 申请年龄分级 */
1098
1356
  static async applyAgeRating(req) {
1099
1357
  const { appId, releaseType, releasePhase, ...body } = req;
1100
- const response = await agcClient.post(
1358
+ const response = await connectApiClient.post(
1101
1359
  "/api/publish/v2/app-age-rating",
1102
1360
  body,
1103
1361
  {
@@ -1110,16 +1368,16 @@ var PublishService = class {
1110
1368
  /** 提交发布 */
1111
1369
  static async submitApp(req) {
1112
1370
  const { appId, ...body } = req;
1113
- const response = await agcClient.post(
1371
+ const response = await connectApiClient.post(
1114
1372
  "/api/publish/v3/app-submit",
1115
1373
  body,
1116
- { headers: appIdHeaders(appId) }
1374
+ { params: { appId } }
1117
1375
  );
1118
1376
  return response.data;
1119
1377
  }
1120
1378
  /** 撤销审核 */
1121
1379
  static async cancelReview(req) {
1122
- const response = await agcClient.put(
1380
+ const response = await connectApiClient.put(
1123
1381
  "/api/publish/v3/version/on-shelf/cancel",
1124
1382
  { versionId: req.versionId },
1125
1383
  { headers: appIdHeaders(req.appId) }
@@ -1128,7 +1386,7 @@ var PublishService = class {
1128
1386
  }
1129
1387
  /** 下架应用 */
1130
1388
  static async shelfOff(req) {
1131
- const response = await agcClient.post(
1389
+ const response = await connectApiClient.post(
1132
1390
  "/api/publish/v2/app-shelf-off",
1133
1391
  null,
1134
1392
  {
@@ -1147,7 +1405,7 @@ var PublishService = class {
1147
1405
  var ProjectService = class {
1148
1406
  /** 查询团队下的项目列表(Project Management API) */
1149
1407
  static async listProjects() {
1150
- const response = await agcClient.get("/api/project-service/v1/projects");
1408
+ const response = await connectApiClient.get("/api/project-service/v1/projects");
1151
1409
  return response.data;
1152
1410
  }
1153
1411
  };
@@ -1156,20 +1414,20 @@ var ProjectService = class {
1156
1414
  var ProvisionService = class {
1157
1415
  // ================= Certificates =================
1158
1416
  static async createCert(req) {
1159
- const response = await agcClient.post("/api/publish/v3/cert", req);
1417
+ const response = await connectApiClient.post("/api/publish/v3/cert", req);
1160
1418
  return response.data;
1161
1419
  }
1162
1420
  static async getCertList(req) {
1163
- const response = await agcClient.post("/api/publish/v3/cert/list", req);
1421
+ const response = await connectApiClient.post("/api/publish/v3/cert/list", req);
1164
1422
  return response.data;
1165
1423
  }
1166
1424
  static async deleteCert(req) {
1167
- const response = await agcClient.post("/api/publish/v2/cert/delete", req);
1425
+ const response = await connectApiClient.post("/api/publish/v2/cert/delete", req);
1168
1426
  return response.data;
1169
1427
  }
1170
1428
  // ================= Devices =================
1171
1429
  static async addDevice(req) {
1172
- const response = await agcClient.post("/api/publish/v2/device", req);
1430
+ const response = await connectApiClient.post("/api/publish/v2/device", req);
1173
1431
  return response.data;
1174
1432
  }
1175
1433
  static async getDeviceList(req) {
@@ -1178,16 +1436,16 @@ var ProvisionService = class {
1178
1436
  if (req.fromRecCount !== void 0) params.fromRecCount = req.fromRecCount;
1179
1437
  if (req.maxReqCount !== void 0) params.maxReqCount = req.maxReqCount;
1180
1438
  if (req.order !== void 0) params.order = req.order;
1181
- const response = await agcClient.get("/api/publish/v2/device/list", { params });
1439
+ const response = await connectApiClient.get("/api/publish/v2/device/list", { params });
1182
1440
  return response.data;
1183
1441
  }
1184
1442
  static async deleteDevice(req) {
1185
- const response = await agcClient.post("/api/publish/v2/device/delete", req);
1443
+ const response = await connectApiClient.post("/api/publish/v2/device/delete", req);
1186
1444
  return response.data;
1187
1445
  }
1188
1446
  // ================= Profile / Provision =================
1189
1447
  static async createProvision(req) {
1190
- const response = await agcClient.post("/api/publish/v3/provision", req);
1448
+ const response = await connectApiClient.post("/api/publish/v3/provision", req);
1191
1449
  return response.data;
1192
1450
  }
1193
1451
  static async getProvisionList(req) {
@@ -1196,18 +1454,18 @@ var ProvisionService = class {
1196
1454
  if (req.maxReqCount !== void 0) params.maxReqCount = req.maxReqCount;
1197
1455
  const headers = { appId: req.appId };
1198
1456
  if (req.provisionId) headers.provisionId = req.provisionId;
1199
- const response = await agcClient.get("/api/publish/v3/provision/list", {
1457
+ const response = await connectApiClient.get("/api/publish/v3/provision/list", {
1200
1458
  params,
1201
1459
  headers
1202
1460
  });
1203
1461
  return response.data;
1204
1462
  }
1205
1463
  static async updateProvision(req) {
1206
- const response = await agcClient.put("/api/publish/v3/provision", req);
1464
+ const response = await connectApiClient.put("/api/publish/v3/provision", req);
1207
1465
  return response.data;
1208
1466
  }
1209
1467
  static async deleteProvision(req) {
1210
- const response = await agcClient.delete("/api/publish/v2/provision", {
1468
+ const response = await connectApiClient.delete("/api/publish/v2/provision", {
1211
1469
  params: { id: req.id }
1212
1470
  });
1213
1471
  return response.data;
@@ -1215,7 +1473,7 @@ var ProvisionService = class {
1215
1473
  // ================= Fingerprint =================
1216
1474
  static async addFingerprint(req) {
1217
1475
  const { appId, ...body } = req;
1218
- const response = await agcClient.post(
1476
+ const response = await connectApiClient.post(
1219
1477
  "/api/provision/v1/fingerprints",
1220
1478
  body,
1221
1479
  { headers: { appId } }
@@ -1223,14 +1481,14 @@ var ProvisionService = class {
1223
1481
  return response.data;
1224
1482
  }
1225
1483
  static async getFingerprintList(req) {
1226
- const response = await agcClient.get("/api/provision/v1/fingerprints", {
1484
+ const response = await connectApiClient.get("/api/provision/v1/fingerprints", {
1227
1485
  headers: { appId: req.appId }
1228
1486
  });
1229
1487
  return response.data;
1230
1488
  }
1231
1489
  static async deleteFingerprint(req) {
1232
1490
  const { appId, ...body } = req;
1233
- const response = await agcClient.delete(
1491
+ const response = await connectApiClient.delete(
1234
1492
  "/api/provision/v1/fingerprints",
1235
1493
  { headers: { appId }, data: body }
1236
1494
  );
@@ -1240,7 +1498,7 @@ var ProvisionService = class {
1240
1498
  /** 查询可申请的 ACL 权限列表 */
1241
1499
  static async getEligibleACL(req) {
1242
1500
  const { appId, ...body } = req;
1243
- const response = await agcClient.post(
1501
+ const response = await connectApiClient.post(
1244
1502
  "/api/provision/v1/user/permission/apply/list",
1245
1503
  body,
1246
1504
  { headers: { appId } }
@@ -1249,7 +1507,7 @@ var ProvisionService = class {
1249
1507
  }
1250
1508
  static async applyACL(req) {
1251
1509
  const { appId, ...body } = req;
1252
- const response = await agcClient.post(
1510
+ const response = await connectApiClient.post(
1253
1511
  "/api/provision/v1/user/permission/apply",
1254
1512
  body,
1255
1513
  { headers: { appId } }
@@ -1257,14 +1515,14 @@ var ProvisionService = class {
1257
1515
  return response.data;
1258
1516
  }
1259
1517
  static async getACLStatus(req) {
1260
- const response = await agcClient.get(
1518
+ const response = await connectApiClient.get(
1261
1519
  "/api/provision/v1/user/permission/apply/status",
1262
1520
  { headers: { appId: req.appId } }
1263
1521
  );
1264
1522
  return response.data;
1265
1523
  }
1266
1524
  static async getACLQuery(req) {
1267
- const response = await agcClient.get("/api/provision/v1/user/permission", {
1525
+ const response = await connectApiClient.get("/api/provision/v1/user/permission", {
1268
1526
  headers: { appId: req.appId }
1269
1527
  });
1270
1528
  return response.data;
@@ -1273,35 +1531,35 @@ var ProvisionService = class {
1273
1531
 
1274
1532
  // src/services/upload.ts
1275
1533
  var import_axios4 = __toESM(require("axios"));
1276
- var import_fs6 = __toESM(require("fs"));
1277
- var import_path5 = __toESM(require("path"));
1534
+ var import_fs7 = __toESM(require("fs"));
1535
+ var import_path6 = __toESM(require("path"));
1278
1536
  function pickObjectId(res) {
1279
1537
  return res.urlInfo?.objectId || res.objectId;
1280
1538
  }
1281
1539
  var UploadService = class {
1282
1540
  // ================= Raw APIs =================
1283
1541
  static async getUploadUrl(req) {
1284
- const response = await agcClient.get("/api/publish/v2/upload-url/for-obs", {
1542
+ const response = await connectApiClient.get("/api/publish/v2/upload-url/for-obs", {
1285
1543
  params: req
1286
1544
  });
1287
1545
  return response.data;
1288
1546
  }
1289
1547
  static async initMultipart(req) {
1290
- const response = await agcClient.post("/api/publish/v2/upload/multipart/init", null, {
1548
+ const response = await connectApiClient.post("/api/publish/v2/upload/multipart/init", null, {
1291
1549
  params: req
1292
1550
  });
1293
1551
  return response.data;
1294
1552
  }
1295
1553
  static async getMultipartParts(req) {
1296
1554
  const { objectId, nspUploadId, parts } = req;
1297
- const response = await agcClient.post("/api/publish/v2/upload/multipart/parts", parts, {
1555
+ const response = await connectApiClient.post("/api/publish/v2/upload/multipart/parts", parts, {
1298
1556
  params: { objectId, nspUploadId }
1299
1557
  });
1300
1558
  return response.data;
1301
1559
  }
1302
1560
  static async composeMultipart(req) {
1303
1561
  const { objectId, nspUploadId, parts } = req;
1304
- const response = await agcClient.post("/api/publish/v2/upload/multipart/compose", parts, {
1562
+ const response = await connectApiClient.post("/api/publish/v2/upload/multipart/compose", parts, {
1305
1563
  params: { objectId, nspUploadId }
1306
1564
  });
1307
1565
  return response.data;
@@ -1313,8 +1571,8 @@ var UploadService = class {
1313
1571
  * 仅完成 OBS 落盘;HarmonyOS `.app` 还须调用更新应用软件包信息,HarmonyOS 开发者中心才会有记录。
1314
1572
  */
1315
1573
  static async uploadFile(options) {
1316
- const stat = import_fs6.default.statSync(options.filePath);
1317
- const fileName = import_path5.default.basename(options.filePath) || "unknown";
1574
+ const stat = import_fs7.default.statSync(options.filePath);
1575
+ const fileName = import_path6.default.basename(options.filePath) || "unknown";
1318
1576
  if (stat.size < 5 * 1024 * 1024) {
1319
1577
  return this.uploadSingleFile(options, fileName, stat.size);
1320
1578
  }
@@ -1355,7 +1613,7 @@ var UploadService = class {
1355
1613
  );
1356
1614
  }
1357
1615
  const { url, headers } = urlRes.urlInfo;
1358
- const fileStream = import_fs6.default.createReadStream(options.filePath);
1616
+ const fileStream = import_fs7.default.createReadStream(options.filePath);
1359
1617
  await import_axios4.default.put(url, fileStream, {
1360
1618
  headers: this.buildObsPutHeaders(headers, contentLength),
1361
1619
  maxBodyLength: Infinity,
@@ -1396,7 +1654,7 @@ var UploadService = class {
1396
1654
  if (!uploadInfoMap) {
1397
1655
  throw new Error(`Failed to get parts upload URL: ${JSON.stringify(partsRes.ret)}`);
1398
1656
  }
1399
- const fd = import_fs6.default.openSync(options.filePath, "r");
1657
+ const fd = import_fs7.default.openSync(options.filePath, "r");
1400
1658
  const composeReqBody = {};
1401
1659
  for (let i = 1; i <= partsCount; i++) {
1402
1660
  const propKey = `additionalProp${i}`;
@@ -1405,7 +1663,7 @@ var UploadService = class {
1405
1663
  const end = Math.min(start + partSize, fileSize);
1406
1664
  const length = end - start;
1407
1665
  const buffer = Buffer.alloc(length);
1408
- import_fs6.default.readSync(fd, buffer, 0, length, start);
1666
+ import_fs7.default.readSync(fd, buffer, 0, length, start);
1409
1667
  const res = await import_axios4.default.put(uploadInfo.url, buffer, {
1410
1668
  headers: this.buildObsPutHeaders(uploadInfo.headers, length),
1411
1669
  maxBodyLength: Infinity,
@@ -1417,7 +1675,7 @@ var UploadService = class {
1417
1675
  etag
1418
1676
  };
1419
1677
  }
1420
- import_fs6.default.closeSync(fd);
1678
+ import_fs7.default.closeSync(fd);
1421
1679
  await this.composeMultipart({
1422
1680
  objectId,
1423
1681
  nspUploadId,
@@ -1428,13 +1686,13 @@ var UploadService = class {
1428
1686
  };
1429
1687
 
1430
1688
  // src/services/domain.ts
1431
- var import_fs7 = __toESM(require("fs"));
1689
+ var import_fs8 = __toESM(require("fs"));
1432
1690
  var DomainService = class {
1433
1691
  /**
1434
1692
  * 查询元服务的域名配置信息
1435
1693
  */
1436
1694
  static async queryDomain(req) {
1437
- const response = await agcClient.get(
1695
+ const response = await connectApiClient.get(
1438
1696
  "/api/dms/domain-manage/v1/app/domain",
1439
1697
  {
1440
1698
  params: { category: req.category },
@@ -1447,7 +1705,7 @@ var DomainService = class {
1447
1705
  * 新增/更新元服务的域名配置信息
1448
1706
  */
1449
1707
  static async updateDomain(req) {
1450
- const response = await agcClient.post(
1708
+ const response = await connectApiClient.post(
1451
1709
  "/api/dms/domain-manage/v1/app/domain",
1452
1710
  { domains: req.domains },
1453
1711
  {
@@ -1461,7 +1719,7 @@ var DomainService = class {
1461
1719
  * 查询域名修改次数/配置上限
1462
1720
  */
1463
1721
  static async queryDomainConfig(req) {
1464
- const response = await agcClient.get(
1722
+ const response = await connectApiClient.get(
1465
1723
  "/api/dms/domain-manage/v1/app/domain/config",
1466
1724
  {
1467
1725
  params: { appId: req.appId }
@@ -1473,15 +1731,15 @@ var DomainService = class {
1473
1731
  * 下载域名配置文件
1474
1732
  */
1475
1733
  static async verifyFile(req, outputPath) {
1476
- const response = await agcClient.get(
1734
+ const response = await connectApiClient.get(
1477
1735
  "/api/dms/domain-manage/v1/app/domain/verify-file",
1478
1736
  {
1479
1737
  headers: { appId: req.appId },
1480
1738
  responseType: "stream"
1481
1739
  }
1482
1740
  );
1483
- return new Promise((resolve, reject) => {
1484
- const writer = import_fs7.default.createWriteStream(outputPath);
1741
+ return new Promise((resolve2, reject) => {
1742
+ const writer = import_fs8.default.createWriteStream(outputPath);
1485
1743
  response.data.pipe(writer);
1486
1744
  let error = null;
1487
1745
  writer.on("error", (err) => {
@@ -1491,7 +1749,7 @@ var DomainService = class {
1491
1749
  });
1492
1750
  writer.on("close", () => {
1493
1751
  if (!error) {
1494
- resolve();
1752
+ resolve2();
1495
1753
  }
1496
1754
  });
1497
1755
  });
@@ -1500,7 +1758,7 @@ var DomainService = class {
1500
1758
  * 预检查业务域名配置
1501
1759
  */
1502
1760
  static async preCheckDomain(req) {
1503
- const response = await agcClient.post(
1761
+ const response = await connectApiClient.post(
1504
1762
  "/api/dms/domain-manage/v1/app/domain/pre-check",
1505
1763
  { domain: req.domain },
1506
1764
  {
@@ -1512,11 +1770,11 @@ var DomainService = class {
1512
1770
  };
1513
1771
 
1514
1772
  // src/services/sign.ts
1515
- var import_fs8 = __toESM(require("fs"));
1516
- var import_os3 = __toESM(require("os"));
1517
- var import_path6 = __toESM(require("path"));
1773
+ var import_fs9 = __toESM(require("fs"));
1774
+ var import_os4 = __toESM(require("os"));
1775
+ var import_path7 = __toESM(require("path"));
1518
1776
  var import_child_process2 = require("child_process");
1519
- var import_crypto = __toESM(require("crypto"));
1777
+ var import_crypto2 = __toESM(require("crypto"));
1520
1778
  var DEFAULT_SIGN_OUT_DIR = ".certs";
1521
1779
  var SIGN_FILE_PREFIX = {
1522
1780
  p12: "key_",
@@ -1526,11 +1784,11 @@ var SIGN_FILE_PREFIX = {
1526
1784
  };
1527
1785
  var SignService = class {
1528
1786
  static resolveSignOutputLayout(options) {
1529
- const rootDir = options.outDir ? import_path6.default.resolve(options.outDir) : import_path6.default.join(process.cwd(), DEFAULT_SIGN_OUT_DIR);
1787
+ const rootDir = options.outDir ? import_path7.default.resolve(options.outDir) : import_path7.default.join(process.cwd(), DEFAULT_SIGN_OUT_DIR);
1530
1788
  const signId = options.filename || this.createSignDefaultId();
1531
1789
  return {
1532
1790
  rootDir,
1533
- bundleDir: import_path6.default.join(rootDir, signId),
1791
+ bundleDir: import_path7.default.join(rootDir, signId),
1534
1792
  filename: signId
1535
1793
  };
1536
1794
  }
@@ -1553,17 +1811,17 @@ var SignService = class {
1553
1811
  /** 仅检查 `DEVECO_HOME` 本身及其 `Contents/`,找不到就返回 undefined */
1554
1812
  static sdkPathFromDevEcoHome(home) {
1555
1813
  if (!home) return void 0;
1556
- for (const sdk of [import_path6.default.join(home, "sdk"), import_path6.default.join(home, "Contents", "sdk")]) {
1814
+ for (const sdk of [import_path7.default.join(home, "sdk"), import_path7.default.join(home, "Contents", "sdk")]) {
1557
1815
  if (this.resolveSignTool(sdk)) return sdk;
1558
1816
  }
1559
1817
  return void 0;
1560
1818
  }
1561
1819
  /** jar 与无后缀可执行文件的绝对路径(不一定存在) */
1562
1820
  static signToolCandidates(sdkPath) {
1563
- const dir = import_path6.default.join(sdkPath, ...this.HAP_SIGN_TOOL_DIR);
1821
+ const dir = import_path7.default.join(sdkPath, ...this.HAP_SIGN_TOOL_DIR);
1564
1822
  return {
1565
- jar: import_path6.default.join(dir, this.HAP_SIGN_TOOL_JAR),
1566
- native: import_path6.default.join(dir, this.HAP_SIGN_TOOL_NATIVE)
1823
+ jar: import_path7.default.join(dir, this.HAP_SIGN_TOOL_JAR),
1824
+ native: import_path7.default.join(dir, this.HAP_SIGN_TOOL_NATIVE)
1567
1825
  };
1568
1826
  }
1569
1827
  /**
@@ -1571,8 +1829,8 @@ var SignService = class {
1571
1829
  */
1572
1830
  static resolveSignTool(sdkPath) {
1573
1831
  const { jar, native } = this.signToolCandidates(sdkPath);
1574
- if (import_fs8.default.existsSync(jar)) return { mode: "jar", path: jar };
1575
- if (import_fs8.default.existsSync(native)) return { mode: "native", path: native };
1832
+ if (import_fs9.default.existsSync(jar)) return { mode: "jar", path: jar };
1833
+ if (import_fs9.default.existsSync(native)) return { mode: "native", path: native };
1576
1834
  return void 0;
1577
1835
  }
1578
1836
  static async createSignP12AndCsr(options) {
@@ -1598,18 +1856,18 @@ var SignService = class {
1598
1856
  throw new Error(`hap-sign-tool not found at ${jar} or ${native}`);
1599
1857
  }
1600
1858
  const { rootDir, bundleDir, filename } = this.resolveSignOutputLayout(options);
1601
- const createdBundleDir = !import_fs8.default.existsSync(bundleDir);
1602
- if (!import_fs8.default.existsSync(rootDir)) {
1603
- import_fs8.default.mkdirSync(rootDir, { recursive: true });
1859
+ const createdBundleDir = !import_fs9.default.existsSync(bundleDir);
1860
+ if (!import_fs9.default.existsSync(rootDir)) {
1861
+ import_fs9.default.mkdirSync(rootDir, { recursive: true });
1604
1862
  }
1605
- import_fs8.default.mkdirSync(bundleDir, { recursive: true });
1606
- const p12FilePath = import_path6.default.join(bundleDir, this.signFileName(filename, "p12"));
1607
- const csrFilePath = import_path6.default.join(bundleDir, this.signFileName(filename, "csr"));
1863
+ import_fs9.default.mkdirSync(bundleDir, { recursive: true });
1864
+ const p12FilePath = import_path7.default.join(bundleDir, this.signFileName(filename, "p12"));
1865
+ const csrFilePath = import_path7.default.join(bundleDir, this.signFileName(filename, "csr"));
1608
1866
  const alias = options.alias;
1609
1867
  try {
1610
1868
  this.doCreateSignFileP12(javaPath, signTool, alias, pwd, p12FilePath);
1611
1869
  this.doCreateSignFileCsr(javaPath, signTool, alias, pwd, p12FilePath, csrFilePath);
1612
- const csrContent = import_fs8.default.readFileSync(csrFilePath, "utf8");
1870
+ const csrContent = import_fs9.default.readFileSync(csrFilePath, "utf8");
1613
1871
  const materialPath = this.placeMaterialBesideStore(bundleDir);
1614
1872
  return {
1615
1873
  alias,
@@ -1619,20 +1877,20 @@ var SignService = class {
1619
1877
  csrPath: csrFilePath,
1620
1878
  csrContent,
1621
1879
  storePath: bundleDir,
1622
- cerPath: import_path6.default.join(bundleDir, this.signFileName(filename, "cer")),
1623
- p7bPath: import_path6.default.join(bundleDir, this.signFileName(filename, "p7b")),
1880
+ cerPath: import_path7.default.join(bundleDir, this.signFileName(filename, "cer")),
1881
+ p7bPath: import_path7.default.join(bundleDir, this.signFileName(filename, "p7b")),
1624
1882
  ...materialPath ? { materialPath } : {}
1625
1883
  };
1626
1884
  } catch (err) {
1627
1885
  if (createdBundleDir) {
1628
- import_fs8.default.rmSync(bundleDir, { recursive: true, force: true });
1886
+ import_fs9.default.rmSync(bundleDir, { recursive: true, force: true });
1629
1887
  }
1630
1888
  throw err;
1631
1889
  }
1632
1890
  }
1633
1891
  /** 目录名与各文件共用的安全随机数(32 hex) */
1634
1892
  static createSignDefaultId() {
1635
- return import_crypto.default.randomBytes(16).toString("hex");
1893
+ return import_crypto2.default.randomBytes(16).toString("hex");
1636
1894
  }
1637
1895
  /** `key_<id>.p12` / `cert_<id>.cer` / `profile_<id>.p7b` 等 */
1638
1896
  static signFileName(id, ext) {
@@ -1640,22 +1898,22 @@ var SignService = class {
1640
1898
  }
1641
1899
  /** 密钥库密码:16 字节 CSPRNG → 32 hex(字母+数字,满足 hap-sign-tool 约束) */
1642
1900
  static createSignDefaultPassword() {
1643
- return import_crypto.default.randomBytes(16).toString("hex");
1901
+ return import_crypto2.default.randomBytes(16).toString("hex");
1644
1902
  }
1645
1903
  /**
1646
1904
  * hvigor 在 `.p12` 同级目录找 `material/`。把加密材料放到本套证书目录,
1647
1905
  * 避免签名文件被拷到工程根目录才能编过。配置目录里还没有 material 时先生成。
1648
1906
  */
1649
1907
  static placeMaterialBesideStore(bundleDir, configDir) {
1650
- const dest = import_path6.default.join(bundleDir, "material");
1651
- if (import_fs8.default.existsSync(dest)) {
1908
+ const dest = import_path7.default.join(bundleDir, "material");
1909
+ if (import_fs9.default.existsSync(dest)) {
1652
1910
  return dest;
1653
1911
  }
1654
1912
  const src = this.ensureMaterial(this.resolveOhosConfigDir(configDir));
1655
1913
  try {
1656
- import_fs8.default.symlinkSync(src, dest, process.platform === "win32" ? "junction" : "dir");
1914
+ import_fs9.default.symlinkSync(src, dest, process.platform === "win32" ? "junction" : "dir");
1657
1915
  } catch {
1658
- import_fs8.default.cpSync(src, dest, { recursive: true });
1916
+ import_fs9.default.cpSync(src, dest, { recursive: true });
1659
1917
  }
1660
1918
  return dest;
1661
1919
  }
@@ -1720,12 +1978,12 @@ var SignService = class {
1720
1978
  }
1721
1979
  static COMPONENT = new Int8Array([49, 243, 9, 115, 214, 175, 91, 184, 211, 190, 177, 88, 101, 131, 192, 119]);
1722
1980
  static readDirBytes(dirPath) {
1723
- const entries = import_fs8.default.readdirSync(dirPath).filter((f) => f !== ".DS_Store");
1724
- return new Int8Array(import_fs8.default.readFileSync(import_path6.default.resolve(dirPath, entries[0])));
1981
+ const entries = import_fs9.default.readdirSync(dirPath).filter((f) => f !== ".DS_Store");
1982
+ return new Int8Array(import_fs9.default.readFileSync(import_path7.default.resolve(dirPath, entries[0])));
1725
1983
  }
1726
1984
  static readFd(materialPath) {
1727
- const fdDir = import_path6.default.resolve(materialPath, "fd");
1728
- return import_fs8.default.readdirSync(fdDir).filter((f) => f !== ".DS_Store").map((e) => this.readDirBytes(import_path6.default.resolve(fdDir, e)));
1985
+ const fdDir = import_path7.default.resolve(materialPath, "fd");
1986
+ return import_fs9.default.readdirSync(fdDir).filter((f) => f !== ".DS_Store").map((e) => this.readDirBytes(import_path7.default.resolve(fdDir, e)));
1729
1987
  }
1730
1988
  static xorBuffers(a, b) {
1731
1989
  const result = new Int8Array(a.byteLength);
@@ -1742,13 +2000,13 @@ var SignService = class {
1742
2000
  const tagLen = (255 & d[0]) << 24 | (255 & d[1]) << 16 | (255 & d[2]) << 8 | 255 & d[3];
1743
2001
  const ivLen = d.length - 4 - tagLen;
1744
2002
  const iv = d.subarray(4, 4 + ivLen);
1745
- const decipher = import_crypto.default.createDecipheriv("aes-128-gcm", key, iv);
2003
+ const decipher = import_crypto2.default.createDecipheriv("aes-128-gcm", key, iv);
1746
2004
  decipher.setAuthTag(d.subarray(d.length - 16));
1747
2005
  return Buffer.concat([decipher.update(d.subarray(4 + ivLen, d.length - 16)), decipher.final()]);
1748
2006
  }
1749
2007
  static aesSeal(key, plaintext) {
1750
- const iv = import_crypto.default.randomBytes(12);
1751
- const cipher = import_crypto.default.createCipheriv("aes-128-gcm", key, iv);
2008
+ const iv = import_crypto2.default.randomBytes(12);
2009
+ const cipher = import_crypto2.default.createCipheriv("aes-128-gcm", key, iv);
1752
2010
  const enc = Buffer.concat([cipher.update(plaintext), cipher.final()]);
1753
2011
  const tag = cipher.getAuthTag();
1754
2012
  const header = Buffer.alloc(4);
@@ -1759,7 +2017,7 @@ var SignService = class {
1759
2017
  return this.aesSeal(key, Buffer.from(plaintext, "utf-8")).toString("hex").toUpperCase();
1760
2018
  }
1761
2019
  static deriveRootKey(components, salt) {
1762
- return import_crypto.default.pbkdf2Sync(
2020
+ return import_crypto2.default.pbkdf2Sync(
1763
2021
  this.xorAll(components.concat(this.COMPONENT)).toString(),
1764
2022
  Buffer.from(salt),
1765
2023
  1e4,
@@ -1768,57 +2026,64 @@ var SignService = class {
1768
2026
  );
1769
2027
  }
1770
2028
  static deriveEncryptionKey(configDir) {
1771
- const materialDir = import_path6.default.resolve(configDir, "material");
2029
+ const materialDir = import_path7.default.resolve(configDir, "material");
1772
2030
  const fd = this.readFd(materialDir);
1773
- const salt = this.readDirBytes(import_path6.default.resolve(materialDir, "ac"));
2031
+ const salt = this.readDirBytes(import_path7.default.resolve(materialDir, "ac"));
1774
2032
  const rawKey = new Int8Array(this.deriveRootKey(fd, salt));
1775
- return new Int8Array(this.aesDecrypt(rawKey, this.readDirBytes(import_path6.default.resolve(materialDir, "ce"))));
2033
+ return new Int8Array(this.aesDecrypt(rawKey, this.readDirBytes(import_path7.default.resolve(materialDir, "ce"))));
2034
+ }
2035
+ /** HOME 优先,与现有加密材料目录一致。Windows 上通常只有 USERPROFILE。 */
2036
+ static resolveUserHome() {
2037
+ return process.env.HOME || process.env.USERPROFILE || import_os4.default.homedir();
1776
2038
  }
1777
2039
  /** 显式目录优先;否则用户主目录。不用空的 HOME 落到当前工作目录。 */
1778
2040
  static resolveOhosConfigDir(configDir) {
1779
- if (configDir) return import_path6.default.resolve(configDir);
1780
- const home = process.env.HOME || process.env.USERPROFILE || import_os3.default.homedir();
1781
- return import_path6.default.join(home, ".ohos", "config");
2041
+ if (configDir) return import_path7.default.resolve(configDir);
2042
+ return import_path7.default.join(this.resolveUserHome(), ".ohos", "config");
2043
+ }
2044
+ /** 发布私钥登记根目录:`<用户主目录>/.ohos/release-signing`。只读这一处,不搜盘。 */
2045
+ static resolveReleaseSigningRoot() {
2046
+ return import_path7.default.join(this.resolveUserHome(), ".ohos", "release-signing");
1782
2047
  }
1783
2048
  /**
1784
2049
  * 与 devecocli KeyManager.generateMaterial 相同的 material/{fd,ac,ce}。
1785
2050
  * 目录已存在则直接复用,不删除、不覆盖,避免已加密密码失效。
1786
2051
  */
1787
2052
  static ensureMaterial(configDir) {
1788
- const materialDir = import_path6.default.resolve(configDir, "material");
1789
- if (!import_fs8.default.existsSync(materialDir)) this.generateMaterial(configDir);
2053
+ const materialDir = import_path7.default.resolve(configDir, "material");
2054
+ if (!import_fs9.default.existsSync(materialDir)) this.generateMaterial(configDir);
1790
2055
  return materialDir;
1791
2056
  }
1792
2057
  static generateMaterial(configDir) {
1793
- const materialDir = import_path6.default.resolve(configDir, "material");
1794
- if (import_fs8.default.existsSync(materialDir)) return;
1795
- import_fs8.default.mkdirSync(configDir, { recursive: true, mode: 448 });
1796
- const staging = import_path6.default.join(configDir, `.material-${import_crypto.default.randomBytes(8).toString("hex")}`);
1797
- const acDir = import_path6.default.join(staging, "ac");
1798
- const ceDir = import_path6.default.join(staging, "ce");
1799
- import_fs8.default.mkdirSync(acDir, { recursive: true, mode: 448 });
1800
- import_fs8.default.mkdirSync(ceDir, { recursive: true, mode: 448 });
1801
- const salt = import_crypto.default.randomBytes(16);
1802
- const components = [0, 1, 2].map(() => new Int8Array(import_crypto.default.randomBytes(16)));
2058
+ const materialDir = import_path7.default.resolve(configDir, "material");
2059
+ if (import_fs9.default.existsSync(materialDir)) return;
2060
+ import_fs9.default.mkdirSync(configDir, { recursive: true, mode: 448 });
2061
+ const staging = import_path7.default.join(configDir, `.material-${import_crypto2.default.randomBytes(8).toString("hex")}`);
2062
+ const acDir = import_path7.default.join(staging, "ac");
2063
+ const ceDir = import_path7.default.join(staging, "ce");
2064
+ import_fs9.default.mkdirSync(acDir, { recursive: true, mode: 448 });
2065
+ import_fs9.default.mkdirSync(ceDir, { recursive: true, mode: 448 });
2066
+ const salt = import_crypto2.default.randomBytes(16);
2067
+ const components = [0, 1, 2].map(() => new Int8Array(import_crypto2.default.randomBytes(16)));
1803
2068
  for (let i = 0; i < components.length; i++) {
1804
- import_fs8.default.mkdirSync(import_path6.default.join(staging, "fd", String(i)), { recursive: true, mode: 448 });
2069
+ import_fs9.default.mkdirSync(import_path7.default.join(staging, "fd", String(i)), { recursive: true, mode: 448 });
1805
2070
  }
1806
- const workKey = import_crypto.default.randomBytes(16);
2071
+ const workKey = import_crypto2.default.randomBytes(16);
1807
2072
  const derived = this.deriveRootKey(components, salt);
1808
2073
  this.writeMaterialFile(acDir, salt);
1809
2074
  this.writeMaterialFile(ceDir, this.aesSeal(derived, workKey));
1810
2075
  components.forEach((part, i) => {
1811
- this.writeMaterialFile(import_path6.default.join(staging, "fd", String(i)), Buffer.from(part));
2076
+ this.writeMaterialFile(import_path7.default.join(staging, "fd", String(i)), Buffer.from(part));
1812
2077
  });
1813
2078
  try {
1814
- import_fs8.default.renameSync(staging, materialDir);
2079
+ import_fs9.default.renameSync(staging, materialDir);
1815
2080
  } catch (err) {
1816
- import_fs8.default.rmSync(staging, { recursive: true, force: true });
1817
- if (!import_fs8.default.existsSync(materialDir)) throw err;
2081
+ import_fs9.default.rmSync(staging, { recursive: true, force: true });
2082
+ if (!import_fs9.default.existsSync(materialDir)) throw err;
1818
2083
  }
1819
2084
  }
1820
2085
  static writeMaterialFile(dir, data) {
1821
- import_fs8.default.writeFileSync(import_path6.default.join(dir, import_crypto.default.randomBytes(16).toString("hex")), data, { mode: 384 });
2086
+ import_fs9.default.writeFileSync(import_path7.default.join(dir, import_crypto2.default.randomBytes(16).toString("hex")), data, { mode: 384 });
1822
2087
  }
1823
2088
  /**
1824
2089
  * 使用与 devecocli / hvigor 相同的 AES-128-GCM 密钥加密密码,
@@ -1833,7 +2098,7 @@ var SignService = class {
1833
2098
  key = this.deriveEncryptionKey(dir);
1834
2099
  } catch (err) {
1835
2100
  throw new Error(
1836
- `\u65E0\u6CD5\u8BFB\u53D6\u52A0\u5BC6\u6750\u6599 ${import_path6.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`,
2101
+ `\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`,
1837
2102
  { cause: err }
1838
2103
  );
1839
2104
  }
@@ -1842,6 +2107,165 @@ var SignService = class {
1842
2107
  storePassword: this.aesEncrypt(key, password)
1843
2108
  };
1844
2109
  }
2110
+ /**
2111
+ * 复用已有 .p12:用它同级的 material/ 加密;同级还没有时,用 configDir 的材料再放到同级。
2112
+ * 已有 material/ 不覆盖,避免跟这份私钥以前加密过的密码对不上。
2113
+ */
2114
+ static encryptPasswordBeside(password, p12Path, configDir) {
2115
+ const storeFile = import_path7.default.resolve(p12Path);
2116
+ if (!import_fs9.default.existsSync(storeFile) || !import_fs9.default.statSync(storeFile).isFile()) {
2117
+ throw new Error(`p12 not found: ${storeFile}`);
2118
+ }
2119
+ const bundleDir = import_path7.default.dirname(storeFile);
2120
+ const dir = import_fs9.default.existsSync(import_path7.default.join(bundleDir, "material")) ? bundleDir : this.resolveOhosConfigDir(configDir);
2121
+ const encrypted = this.encryptPassword(password, dir);
2122
+ const materialPath = this.placeMaterialBesideStore(bundleDir, dir);
2123
+ if (!materialPath) {
2124
+ throw new Error(`\u65E0\u6CD5\u628A\u52A0\u5BC6\u6750\u6599\u653E\u5230 ${bundleDir}`);
2125
+ }
2126
+ return { ...encrypted, materialPath };
2127
+ }
2128
+ static CERT_ID_RE = /^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$/;
2129
+ static releaseSigningIndexPath() {
2130
+ return import_path7.default.join(this.resolveReleaseSigningRoot(), "index.json");
2131
+ }
2132
+ static isInside(child, parent) {
2133
+ const rel = import_path7.default.relative(import_path7.default.resolve(parent), import_path7.default.resolve(child));
2134
+ return rel === "" || !rel.startsWith("..") && !import_path7.default.isAbsolute(rel);
2135
+ }
2136
+ static readReleaseSigningCerts() {
2137
+ const file = this.releaseSigningIndexPath();
2138
+ if (!import_fs9.default.existsSync(file)) return [];
2139
+ let parsed;
2140
+ try {
2141
+ parsed = JSON.parse(import_fs9.default.readFileSync(file, "utf8"));
2142
+ } catch (err) {
2143
+ throw new Error(`\u65E0\u6CD5\u8BFB\u53D6\u53D1\u5E03\u8BC1\u4E66\u767B\u8BB0 ${file}`, { cause: err });
2144
+ }
2145
+ const certs = parsed?.certs;
2146
+ if (!Array.isArray(certs)) {
2147
+ throw new Error(`\u53D1\u5E03\u8BC1\u4E66\u767B\u8BB0\u683C\u5F0F\u65E0\u6548: ${file}`);
2148
+ }
2149
+ return certs;
2150
+ }
2151
+ static writeReleaseSigningCerts(certs) {
2152
+ const root = this.resolveReleaseSigningRoot();
2153
+ import_fs9.default.mkdirSync(root, { recursive: true, mode: 448 });
2154
+ const file = this.releaseSigningIndexPath();
2155
+ const tmp = import_path7.default.join(root, `.index-${import_crypto2.default.randomBytes(8).toString("hex")}.json`);
2156
+ import_fs9.default.writeFileSync(tmp, `${JSON.stringify({ certs }, null, 2)}
2157
+ `, { mode: 384 });
2158
+ try {
2159
+ if (import_fs9.default.existsSync(file)) import_fs9.default.rmSync(file);
2160
+ import_fs9.default.renameSync(tmp, file);
2161
+ } catch (err) {
2162
+ try {
2163
+ import_fs9.default.copyFileSync(tmp, file);
2164
+ import_fs9.default.rmSync(tmp, { force: true });
2165
+ } catch {
2166
+ import_fs9.default.rmSync(tmp, { force: true });
2167
+ throw err;
2168
+ }
2169
+ }
2170
+ }
2171
+ /**
2172
+ * 读取本机发布私钥登记。文件不存在时返回空列表。
2173
+ * 不扫描其他目录。
2174
+ */
2175
+ static listReleaseSigning() {
2176
+ const rootDir = this.resolveReleaseSigningRoot();
2177
+ const certs = this.readReleaseSigningCerts().map((entry) => ({
2178
+ ...entry,
2179
+ p12Exists: !!entry.p12Path && import_fs9.default.existsSync(entry.p12Path) && import_fs9.default.statSync(entry.p12Path).isFile()
2180
+ }));
2181
+ return { rootDir, certs };
2182
+ }
2183
+ /**
2184
+ * 把发布 .p12、别名、证书 id 和已加密密码写入用户目录。
2185
+ * `.p12` 不在该目录时复制进去;`csr-generate --out-dir` 落在此根目录下的临时子目录会改放到 `<certId>/`。
2186
+ * 明文密码只用于当场加密,不进入 index.json。
2187
+ */
2188
+ static saveReleaseSigning(options) {
2189
+ const certId = options.certId.trim();
2190
+ if (!this.CERT_ID_RE.test(certId)) {
2191
+ throw new Error(`invalid certId: ${options.certId}`);
2192
+ }
2193
+ const certName = options.certName.trim();
2194
+ const alias = options.alias.trim();
2195
+ if (!certName || !alias) {
2196
+ throw new Error("certName and alias are required");
2197
+ }
2198
+ const pwd = options.pwd ?? "";
2199
+ const hasPwd = pwd.length > 0;
2200
+ const hasHex = !!options.keyPassword && !!options.storePassword;
2201
+ if (hasPwd === hasHex) {
2202
+ throw new Error("pass either --pwd, or both --key-password and --store-password");
2203
+ }
2204
+ if (!hasPwd) {
2205
+ const hex = /^[0-9A-Fa-f]+$/;
2206
+ if (!hex.test(options.keyPassword) || !hex.test(options.storePassword)) {
2207
+ throw new Error("keyPassword and storePassword must be encrypt-pwd hex");
2208
+ }
2209
+ }
2210
+ const sourceP12 = import_path7.default.resolve(options.p12Path);
2211
+ if (!import_fs9.default.existsSync(sourceP12) || !import_fs9.default.statSync(sourceP12).isFile()) {
2212
+ throw new Error(`p12 not found: ${sourceP12}`);
2213
+ }
2214
+ const root = this.resolveReleaseSigningRoot();
2215
+ const destDir = import_path7.default.join(root, certId);
2216
+ const sourceDir = import_path7.default.dirname(sourceP12);
2217
+ const sourceMaterial = import_path7.default.join(sourceDir, "material");
2218
+ const sameDir = import_path7.default.resolve(sourceDir) === import_path7.default.resolve(destDir);
2219
+ const materialReady = import_fs9.default.existsSync(import_path7.default.join(sameDir ? destDir : sourceDir, "material")) || import_fs9.default.existsSync(import_path7.default.join(destDir, "material"));
2220
+ if (!hasPwd && !materialReady) {
2221
+ 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");
2222
+ }
2223
+ const existing = this.readReleaseSigningCerts();
2224
+ const sourceRegistered = existing.some((entry) => entry.p12Path && this.isInside(entry.p12Path, sourceDir));
2225
+ const sourceIsDirectChild = import_path7.default.resolve(import_path7.default.dirname(sourceDir)) === import_path7.default.resolve(root);
2226
+ import_fs9.default.mkdirSync(root, { recursive: true, mode: 448 });
2227
+ let storedP12;
2228
+ let removeSource;
2229
+ if (sameDir) {
2230
+ storedP12 = sourceP12;
2231
+ } else if (sourceIsDirectChild && !sourceRegistered && !import_fs9.default.existsSync(destDir)) {
2232
+ import_fs9.default.renameSync(sourceDir, destDir);
2233
+ storedP12 = import_path7.default.join(destDir, import_path7.default.basename(sourceP12));
2234
+ } else {
2235
+ import_fs9.default.mkdirSync(destDir, { recursive: true, mode: 448 });
2236
+ storedP12 = import_path7.default.join(destDir, import_path7.default.basename(sourceP12));
2237
+ if (import_path7.default.resolve(storedP12) !== sourceP12) {
2238
+ import_fs9.default.copyFileSync(sourceP12, storedP12);
2239
+ }
2240
+ if (sourceIsDirectChild && !sourceRegistered) removeSource = sourceDir;
2241
+ }
2242
+ const destMaterial = import_path7.default.join(destDir, "material");
2243
+ if (!import_fs9.default.existsSync(destMaterial)) {
2244
+ if (import_fs9.default.existsSync(sourceMaterial)) {
2245
+ import_fs9.default.cpSync(sourceMaterial, destMaterial, { recursive: true, dereference: true });
2246
+ } else {
2247
+ this.placeMaterialBesideStore(destDir, options.configDir);
2248
+ }
2249
+ }
2250
+ if (!import_fs9.default.existsSync(destMaterial)) {
2251
+ throw new Error(`\u65E0\u6CD5\u628A\u52A0\u5BC6\u6750\u6599\u653E\u5230 ${destDir}`);
2252
+ }
2253
+ const encrypted = hasPwd ? this.encryptPassword(pwd, destDir) : { keyPassword: options.keyPassword, storePassword: options.storePassword };
2254
+ const record = {
2255
+ certId,
2256
+ certName,
2257
+ alias,
2258
+ p12Path: storedP12,
2259
+ keyPassword: encrypted.keyPassword,
2260
+ storePassword: encrypted.storePassword,
2261
+ materialPath: destMaterial
2262
+ };
2263
+ this.writeReleaseSigningCerts([...existing.filter((entry) => entry.certId !== certId), record]);
2264
+ if (removeSource && import_fs9.default.existsSync(removeSource)) {
2265
+ import_fs9.default.rmSync(removeSource, { recursive: true, force: true });
2266
+ }
2267
+ return record;
2268
+ }
1845
2269
  };
1846
2270
 
1847
2271
  // src/services/testing.ts
@@ -1853,7 +2277,7 @@ var TestingService = class {
1853
2277
  /** 新建测试版本 */
1854
2278
  static async createVersion(req) {
1855
2279
  const { appId, ...body } = req;
1856
- const response = await agcClient.post(
2280
+ const response = await connectApiClient.post(
1857
2281
  "/api/publish/v2/test/app/version",
1858
2282
  {
1859
2283
  releaseType: body.releaseType ?? 6,
@@ -1867,7 +2291,7 @@ var TestingService = class {
1867
2291
  }
1868
2292
  /** 查询上架自检报告信息 */
1869
2293
  static async getDetectReport(req) {
1870
- const response = await agcClient.get(
2294
+ const response = await connectApiClient.get(
1871
2295
  "/api/publish/v2/test/app/version/detect-report",
1872
2296
  { params: { appId: req.appId, versionId: req.versionId } }
1873
2297
  );
@@ -1876,7 +2300,7 @@ var TestingService = class {
1876
2300
  /** 添加软件包到测试版本 */
1877
2301
  static async addPackage(req) {
1878
2302
  const { appId, ...body } = req;
1879
- const response = await agcClient.post(
2303
+ const response = await connectApiClient.post(
1880
2304
  "/api/publish/v2/test/version/pkg",
1881
2305
  body,
1882
2306
  { params: { appId } }
@@ -1886,7 +2310,7 @@ var TestingService = class {
1886
2310
  /** 更新测试版本(绑包、群组、多语言等) */
1887
2311
  static async updateVersion(req) {
1888
2312
  const { appId, ...body } = req;
1889
- const response = await agcClient.put(
2313
+ const response = await connectApiClient.put(
1890
2314
  "/api/publish/v2/test/app/version",
1891
2315
  body,
1892
2316
  { params: { appId } }
@@ -1896,7 +2320,7 @@ var TestingService = class {
1896
2320
  /** 更新测试生效版本 */
1897
2321
  static async releaseVersion(req) {
1898
2322
  const { appId, ...body } = req;
1899
- const response = await agcClient.put(
2323
+ const response = await connectApiClient.put(
1900
2324
  "/api/publish/v2/test/version/release",
1901
2325
  body,
1902
2326
  { params: { appId } }
@@ -1906,7 +2330,7 @@ var TestingService = class {
1906
2330
  /** 更新有效期内的测试版本时间和额度信息 */
1907
2331
  static async updateOpenTest(req) {
1908
2332
  const { appId, ...body } = req;
1909
- const response = await agcClient.put(
2333
+ const response = await connectApiClient.put(
1910
2334
  "/api/publish/v2/test/version/open-test",
1911
2335
  body,
1912
2336
  { params: { appId } }
@@ -1915,7 +2339,7 @@ var TestingService = class {
1915
2339
  }
1916
2340
  /** 提交测试版本 */
1917
2341
  static async submitVersion(req) {
1918
- const response = await agcClient.post(
2342
+ const response = await connectApiClient.post(
1919
2343
  "/api/publish/v2/test/app/version/submit",
1920
2344
  { versionId: req.versionId },
1921
2345
  { params: { appId: req.appId } }
@@ -1924,7 +2348,7 @@ var TestingService = class {
1924
2348
  }
1925
2349
  /** 停止测试版本 */
1926
2350
  static async stopVersion(req) {
1927
- const response = await agcClient.post(
2351
+ const response = await connectApiClient.post(
1928
2352
  "/api/publish/v2/test/version/stop",
1929
2353
  { versionId: req.versionId },
1930
2354
  { params: { appId: req.appId } }
@@ -1933,7 +2357,7 @@ var TestingService = class {
1933
2357
  }
1934
2358
  /** 删除测试版本 */
1935
2359
  static async deleteVersion(req) {
1936
- const response = await agcClient.delete(
2360
+ const response = await connectApiClient.delete(
1937
2361
  "/api/publish/v2/test/app/version",
1938
2362
  { params: { appId: req.appId, versionId: req.versionId } }
1939
2363
  );
@@ -1943,7 +2367,7 @@ var TestingService = class {
1943
2367
  /** 新增测试群组 */
1944
2368
  static async addGroup(req) {
1945
2369
  const { appId, ...body } = req;
1946
- const response = await agcClient.post(
2370
+ const response = await connectApiClient.post(
1947
2371
  "/api/app-test/v1/test-group",
1948
2372
  body,
1949
2373
  { headers: appIdHeaders2(appId) }
@@ -1956,7 +2380,7 @@ var TestingService = class {
1956
2380
  if (req.groupType !== void 0) params.groupType = req.groupType;
1957
2381
  if (req.current !== void 0) params.current = req.current;
1958
2382
  if (req.pageSize !== void 0) params.pageSize = req.pageSize;
1959
- const response = await agcClient.get(
2383
+ const response = await connectApiClient.get(
1960
2384
  "/api/app-test/v1/test-group/list",
1961
2385
  { params, headers: appIdHeaders2(req.appId) }
1962
2386
  );
@@ -1964,7 +2388,7 @@ var TestingService = class {
1964
2388
  }
1965
2389
  /** 删除测试群组 */
1966
2390
  static async deleteGroup(req) {
1967
- const response = await agcClient.delete(
2391
+ const response = await connectApiClient.delete(
1968
2392
  "/api/app-test/v1/publish-api/test-group",
1969
2393
  { params: { groupId: req.groupId }, headers: appIdHeaders2(req.appId) }
1970
2394
  );
@@ -1973,7 +2397,7 @@ var TestingService = class {
1973
2397
  /** 修改测试群组 */
1974
2398
  static async editGroup(req) {
1975
2399
  const { appId, ...body } = req;
1976
- const response = await agcClient.put(
2400
+ const response = await connectApiClient.put(
1977
2401
  "/api/app-test/v2/test-group",
1978
2402
  body,
1979
2403
  { headers: appIdHeaders2(appId) }
@@ -1985,7 +2409,7 @@ var TestingService = class {
1985
2409
  const params = {};
1986
2410
  if (req.current !== void 0) params.current = req.current;
1987
2411
  if (req.pageSize !== void 0) params.pageSize = req.pageSize;
1988
- const response = await agcClient.get(
2412
+ const response = await connectApiClient.get(
1989
2413
  "/api/app-test/v1/test-user",
1990
2414
  {
1991
2415
  params,
@@ -1998,7 +2422,7 @@ var TestingService = class {
1998
2422
  /** 新增测试群组成员 */
1999
2423
  static async addGroupUser(req) {
2000
2424
  const { appId, ...body } = req;
2001
- const response = await agcClient.post(
2425
+ const response = await connectApiClient.post(
2002
2426
  "/api/publish/v2/test/user",
2003
2427
  body,
2004
2428
  { headers: appIdHeaders2(appId) }
@@ -2008,7 +2432,7 @@ var TestingService = class {
2008
2432
  /** 删除测试群组成员 */
2009
2433
  static async deleteGroupUser(req) {
2010
2434
  const { appId, ...body } = req;
2011
- const response = await agcClient.delete(
2435
+ const response = await connectApiClient.delete(
2012
2436
  "/api/publish/v2/test/user",
2013
2437
  { data: body, headers: appIdHeaders2(appId) }
2014
2438
  );
@@ -2017,7 +2441,7 @@ var TestingService = class {
2017
2441
  /** 发送邀请测试通知 */
2018
2442
  static async notifyUsers(req) {
2019
2443
  const { appId, ...body } = req;
2020
- const response = await agcClient.post(
2444
+ const response = await connectApiClient.post(
2021
2445
  "/api/publish/v2/test/user/action/notify",
2022
2446
  body,
2023
2447
  { headers: appIdHeaders2(appId) }
@@ -2028,7 +2452,7 @@ var TestingService = class {
2028
2452
  /** 生成邀请码 */
2029
2453
  static async createInviteCode(req) {
2030
2454
  const { appId, ...body } = req;
2031
- const response = await agcClient.post(
2455
+ const response = await connectApiClient.post(
2032
2456
  "/api/app-test/v1/invitation-code",
2033
2457
  body,
2034
2458
  { headers: appIdHeaders2(appId) }
@@ -2037,7 +2461,7 @@ var TestingService = class {
2037
2461
  }
2038
2462
  /** 查询测试群组邀请码 */
2039
2463
  static async getInviteCode(req) {
2040
- const response = await agcClient.get(
2464
+ const response = await connectApiClient.get(
2041
2465
  "/api/app-test/v1/test-group/invitation-code",
2042
2466
  { params: { groupId: req.groupId }, headers: appIdHeaders2(req.appId) }
2043
2467
  );
@@ -2045,7 +2469,7 @@ var TestingService = class {
2045
2469
  }
2046
2470
  /** 停止邀请码 */
2047
2471
  static async stopInviteCode(req) {
2048
- const response = await agcClient.post(
2472
+ const response = await connectApiClient.post(
2049
2473
  "/api/app-test/v1/invitation-code/action/stop",
2050
2474
  { invitationCodeId: req.invitationCodeId },
2051
2475
  { headers: appIdHeaders2(req.appId) }
@@ -2054,7 +2478,7 @@ var TestingService = class {
2054
2478
  }
2055
2479
  /** 删除邀请码 */
2056
2480
  static async deleteInviteCode(req) {
2057
- const response = await agcClient.delete(
2481
+ const response = await connectApiClient.delete(
2058
2482
  "/api/app-test/v1/invitation-code",
2059
2483
  { params: { invitationCodeId: req.invitationCodeId }, headers: appIdHeaders2(req.appId) }
2060
2484
  );
@@ -2064,7 +2488,7 @@ var TestingService = class {
2064
2488
  /** 创建公开链接 */
2065
2489
  static async createPublicLink(req) {
2066
2490
  const { appId, ...body } = req;
2067
- const response = await agcClient.post(
2491
+ const response = await connectApiClient.post(
2068
2492
  "/api/app-test/v1/test-group/public-link",
2069
2493
  body,
2070
2494
  { headers: appIdHeaders2(appId) }
@@ -2074,7 +2498,7 @@ var TestingService = class {
2074
2498
  /** 修改公开链接 */
2075
2499
  static async editPublicLink(req) {
2076
2500
  const { appId, ...body } = req;
2077
- const response = await agcClient.put(
2501
+ const response = await connectApiClient.put(
2078
2502
  "/api/app-test/v1/test-group/public-link",
2079
2503
  body,
2080
2504
  { headers: appIdHeaders2(appId) }
@@ -2083,7 +2507,7 @@ var TestingService = class {
2083
2507
  }
2084
2508
  /** 查询公开链接 */
2085
2509
  static async queryPublicLink(req) {
2086
- const response = await agcClient.get(
2510
+ const response = await connectApiClient.get(
2087
2511
  "/api/app-test/v1/test-group/public-link",
2088
2512
  { params: { groupId: req.groupId }, headers: appIdHeaders2(req.appId) }
2089
2513
  );
@@ -2093,7 +2517,7 @@ var TestingService = class {
2093
2517
  /** 查询测试问题反馈维度 */
2094
2518
  static async queryFeedbackDimension(req) {
2095
2519
  const { appId, ...body } = req;
2096
- const response = await agcClient.post(
2520
+ const response = await connectApiClient.post(
2097
2521
  "/api/app-test/v1/mgmt/tester-feedback-dimension/action/query",
2098
2522
  body,
2099
2523
  { headers: appIdHeaders2(appId) }
@@ -2103,7 +2527,7 @@ var TestingService = class {
2103
2527
  /** 查询测试问题反馈 */
2104
2528
  static async queryFeedback(req) {
2105
2529
  const { appId, ...body } = req;
2106
- const response = await agcClient.post(
2530
+ const response = await connectApiClient.post(
2107
2531
  "/api/app-test/v1/mgmt/tester-feedback/action/query",
2108
2532
  body,
2109
2533
  { headers: appIdHeaders2(appId) }
@@ -2113,7 +2537,7 @@ var TestingService = class {
2113
2537
  /** 删除测试问题反馈 */
2114
2538
  static async deleteFeedback(req) {
2115
2539
  const { appId, ...body } = req;
2116
- const response = await agcClient.delete(
2540
+ const response = await connectApiClient.delete(
2117
2541
  "/api/app-test/v1/mgmt/tester-feedback",
2118
2542
  { data: body, headers: appIdHeaders2(appId) }
2119
2543
  );
@@ -2121,23 +2545,71 @@ var TestingService = class {
2121
2545
  }
2122
2546
  };
2123
2547
 
2548
+ // src/cli/upgrade.ts
2549
+ var import_node_child_process = require("child_process");
2550
+ var import_node_fs = require("fs");
2551
+ var import_node_path = __toESM(require("path"));
2552
+ var import_semver = require("semver");
2553
+ var CLI_PACKAGE_NAME = "connect-api-cli";
2554
+ var REGISTRY = "--registry=https://registry.npmjs.org/";
2555
+ function runNpm(args, stdio = "pipe") {
2556
+ const options = { encoding: "utf8", stdio };
2557
+ const result = process.platform === "win32" ? (0, import_node_child_process.spawnSync)(`npm ${args.join(" ")}`, { ...options, shell: true }) : (0, import_node_child_process.spawnSync)("npm", args, options);
2558
+ if (result.error) throw result.error;
2559
+ if (result.status !== 0) {
2560
+ const detail = result.stderr?.trim() || `npm exited with ${result.signal || `code ${result.status}`}`;
2561
+ throw new Error(detail);
2562
+ }
2563
+ return result.stdout?.trim() ?? "";
2564
+ }
2565
+ function upgradeCli(currentVersion, packageDirectory) {
2566
+ const npmRoot = runNpm(["root", "--global"]);
2567
+ const installedDirectory = (0, import_node_fs.existsSync)(npmRoot) ? import_node_path.default.join((0, import_node_fs.realpathSync)(npmRoot), CLI_PACKAGE_NAME) : void 0;
2568
+ if (!installedDirectory || (0, import_node_fs.realpathSync)(packageDirectory) !== installedDirectory) {
2569
+ throw new Error(
2570
+ `Run upgrade from the active npm global installation. Install it with npm install -g ${CLI_PACKAGE_NAME}@latest ${REGISTRY}`
2571
+ );
2572
+ }
2573
+ const publishedVersion = JSON.parse(runNpm(["view", `${CLI_PACKAGE_NAME}@latest`, "version", "--json", REGISTRY]));
2574
+ const latestVersion = typeof publishedVersion === "string" ? (0, import_semver.valid)(publishedVersion) : null;
2575
+ if (!latestVersion) throw new Error("npm did not report a valid latest version.");
2576
+ if (!(0, import_semver.gt)(latestVersion, currentVersion)) {
2577
+ console.log(`${CLI_PACKAGE_NAME} ${currentVersion} is up to date (npm latest: ${latestVersion}).`);
2578
+ return;
2579
+ }
2580
+ console.log(`Upgrading ${CLI_PACKAGE_NAME} from ${currentVersion} to ${latestVersion}\u2026`);
2581
+ runNpm(["install", "--global", `${CLI_PACKAGE_NAME}@${latestVersion}`, REGISTRY], "inherit");
2582
+ const installed = JSON.parse((0, import_node_fs.readFileSync)(import_node_path.default.join(installedDirectory, "package.json"), "utf8"));
2583
+ if (installed.version !== latestVersion) {
2584
+ throw new Error(`Expected version ${latestVersion} after npm install, found ${installed.version ?? "unknown"}.`);
2585
+ }
2586
+ console.log(`Upgraded ${CLI_PACKAGE_NAME} to ${latestVersion}.`);
2587
+ }
2588
+
2124
2589
  // src/cli/index.ts
2125
2590
  var program = new import_commander.Command();
2126
2591
  function readCliVersion() {
2127
- if ("1.1.8") {
2128
- return "1.1.8";
2592
+ if ("1.1.10") {
2593
+ return "1.1.10";
2129
2594
  }
2130
2595
  try {
2131
- const pkgPath = import_path7.default.join(__dirname, "..", "package.json");
2596
+ const pkgPath = import_path8.default.join(__dirname, "..", "package.json");
2132
2597
  const pkg = JSON.parse(fs9.readFileSync(pkgPath, "utf8"));
2133
2598
  if (pkg.version) return pkg.version;
2134
2599
  } catch {
2135
2600
  }
2136
2601
  return "0.0.0";
2137
2602
  }
2138
- program.name("connect-api-cli").description("HarmonyOS \u5F00\u53D1\u8005\u4E2D\u5FC3 API CLI Tool").version(readCliVersion());
2603
+ program.name(CLI_PACKAGE_NAME).description("HarmonyOS \u5F00\u53D1\u8005\u4E2D\u5FC3 API CLI Tool").version(readCliVersion());
2604
+ program.command("upgrade").description("Upgrade the npm global installation to the latest published version").action(() => {
2605
+ try {
2606
+ upgradeCli(readCliVersion(), import_path8.default.resolve(__dirname, ".."));
2607
+ } catch (error) {
2608
+ reportFailure("Upgrade failed:", error instanceof Error ? error.message : String(error));
2609
+ }
2610
+ });
2139
2611
  var authCmd = program.command("auth").description("Authentication management");
2140
- authCmd.command("login").description("Login and cache token (client_credentials / service_account JWT / OAuth browser)").action(async () => {
2612
+ authCmd.command("login").description("Login and cache token (default: local DevEco login, then browser OAuth)").action(async () => {
2141
2613
  try {
2142
2614
  const token = await AuthManager.login();
2143
2615
  console.log("Successfully logged in. Token generated and cached.");
@@ -2147,33 +2619,38 @@ authCmd.command("login").description("Login and cache token (client_credentials
2147
2619
  }
2148
2620
  });
2149
2621
  authCmd.command("status").description("Show current auth mode and cached token status").action(() => {
2150
- let cfg;
2622
+ let authStatus;
2151
2623
  try {
2152
- cfg = getConfig();
2624
+ authStatus = AuthManager.getStatus();
2153
2625
  } catch (e) {
2154
2626
  reportFailure(`Auth status unavailable: ${e.message}`);
2155
2627
  process.exitCode = 1;
2156
2628
  return;
2157
2629
  }
2158
- const status = AuthManager.getStatus();
2630
+ const { config: cfg, cache: status } = authStatus;
2159
2631
  console.log(`Auth mode: ${cfg.authMode}`);
2160
2632
  if (cfg.authMode === "service_account") {
2161
2633
  console.log(`Key ID: ${cfg.clientId}`);
2162
2634
  if (cfg.serviceAccount) {
2163
2635
  console.log(`Credentials: ${cfg.serviceAccount.credentialsPath}`);
2164
2636
  }
2637
+ } else if (cfg.authMode === "deveco") {
2638
+ console.log(`Token source: ${cfg.deveco?.source ?? "cli"}`);
2639
+ if (cfg.deveco?.authDir) {
2640
+ console.log(`Auth dir: ${cfg.deveco.authDir}`);
2641
+ }
2165
2642
  } else {
2166
2643
  console.log(`Client ID: ${cfg.clientId}`);
2167
2644
  }
2168
- if (cfg.authMode === "oauth") {
2645
+ if (cfg.authMode === "oauth" || cfg.authMode === "deveco") {
2169
2646
  const teamId = cfg.teamId || getCachedOAuthTeamId();
2170
- console.log(`Team ID: ${teamId || "(auto on first API call; or set AGC_TEAM_ID)"}`);
2647
+ console.log(`Team ID: ${teamId || "(first team returned by the API; override with AGC_TEAM_ID)"}`);
2171
2648
  }
2172
2649
  if (status) {
2173
2650
  const remaining = Math.max(0, Math.floor((status.expiresAt - Date.now()) / 1e3));
2174
2651
  console.log("Token cached: yes");
2175
2652
  console.log(`Expires in: ${Math.floor(remaining / 60)}m ${remaining % 60}s`);
2176
- const autoRefresh = cfg.authMode === "oauth" && !!status.refreshToken || cfg.authMode === "service_account" || cfg.authMode === "client_credentials";
2653
+ const autoRefresh = cfg.authMode === "oauth" && !!status.refreshToken || cfg.authMode === "service_account" || cfg.authMode === "client_credentials" || cfg.authMode === "deveco";
2177
2654
  console.log(`Auto-refresh: ${autoRefresh ? "enabled" : "n/a"}`);
2178
2655
  } else {
2179
2656
  console.log("Token cached: no");
@@ -2570,7 +3047,7 @@ uploadCmd.command("file").description("Upload a file (APP, APK, images, etc.); .
2570
3047
  releaseType,
2571
3048
  chineseMainlandFlag: options.chineseMainland ? Number(options.chineseMainland) : void 0
2572
3049
  });
2573
- const ext = import_path7.default.extname(uploaded.fileName).toLowerCase();
3050
+ const ext = import_path8.default.extname(uploaded.fileName).toLowerCase();
2574
3051
  const shouldBind = options.bind !== false && ext === ".app" && releaseType !== 6;
2575
3052
  if (!shouldBind) {
2576
3053
  console.log(JSON.stringify({
@@ -2621,14 +3098,39 @@ provisionCmd.command("csr-generate").description("Generate a new keypair and CSR
2621
3098
  reportFailure("CSR generation failed:", e.message);
2622
3099
  }
2623
3100
  });
2624
- 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)").action(async (options) => {
3101
+ 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) => {
2625
3102
  try {
2626
- const res = SignService.encryptPassword(options.pwd, options.configDir);
3103
+ const res = options.beside ? SignService.encryptPasswordBeside(options.pwd, options.beside, options.configDir) : SignService.encryptPassword(options.pwd, options.configDir);
2627
3104
  printResult(res);
2628
3105
  } catch (e) {
2629
3106
  reportFailure("\u52A0\u5BC6\u5931\u8D25:", e.message);
2630
3107
  }
2631
3108
  });
3109
+ 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(() => {
3110
+ try {
3111
+ printResult(SignService.listReleaseSigning());
3112
+ } catch (e) {
3113
+ reportFailure("\u8BFB\u53D6\u53D1\u5E03\u8BC1\u4E66\u767B\u8BB0\u5931\u8D25:", e.message);
3114
+ }
3115
+ });
3116
+ 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) => {
3117
+ try {
3118
+ const res = SignService.saveReleaseSigning({
3119
+ certId: options.certId,
3120
+ certName: options.certName,
3121
+ alias: options.alias,
3122
+ p12Path: options.p12,
3123
+ pwd: options.pwd,
3124
+ keyPassword: options.keyPassword,
3125
+ storePassword: options.storePassword,
3126
+ configDir: options.configDir
3127
+ });
3128
+ console.error("Release signing saved.");
3129
+ printResult(res);
3130
+ } catch (e) {
3131
+ reportFailure("\u4FDD\u5B58\u53D1\u5E03\u8BC1\u4E66\u767B\u8BB0\u5931\u8D25:", e.message);
3132
+ }
3133
+ });
2632
3134
  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) => {
2633
3135
  try {
2634
3136
  const csrContent = fs9.readFileSync(options.csr, "utf8");